*** empty log message ***
[gnus] / lisp / nntp.el
1 ;; Copyright (C) 1987,88,89,90,92,93,94,95,96 Free Software Foundation, Inc.
2
3 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
4 ;; Keywords: news
5
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to
20 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 ;;; Commentary:
23
24 ;;; Code:
25
26 (require 'nnheader)
27 (require 'nnoo)
28 (require 'gnus-util)
29
30 (nnoo-declare nntp)
31
32 (eval-and-compile
33   (unless (fboundp 'open-network-stream)
34     (require 'tcp)))
35
36 (eval-when-compile (require 'cl))
37
38 (defvoo nntp-address nil
39   "Address of the physical nntp server.")
40
41 (defvoo nntp-port-number "nntp"
42   "Port number on the physical nntp server.")
43
44 (defvoo nntp-server-opened-hook '(nntp-send-mode-reader)
45   "*Hook used for sending commands to the server at startup.  
46 The default value is `nntp-send-mode-reader', which makes an innd
47 server spawn an nnrpd server.  Another useful function to put in this
48 hook might be `nntp-send-authinfo', which will prompt for a password
49 to allow posting from the server.  Note that this is only necessary to
50 do on servers that use strict access control.")  
51
52 (defvoo nntp-authinfo-function 'nntp-send-authinfo
53   "Function used to send AUTHINFO to the server.")
54
55 (defvoo nntp-server-action-alist 
56   '(("nntpd 1\\.5\\.11t" 
57      (remove-hook 'nntp-server-opened-hook 'nntp-send-mode-reader)))
58   "Alist of regexps to match on server types and actions to be taken.
59 For instance, if you want Gnus to beep every time you connect
60 to innd, you could say something like:
61
62 \(setq nntp-server-action-alist
63        '((\"innd\" (ding))))
64
65 You probably don't want to do that, though.")
66
67 (defvoo nntp-open-connection-function 'nntp-open-network-stream
68   "*Function used for connecting to a remote system.
69 It will be called with the buffer to output in.
70
71 Two pre-made functions are `nntp-open-network-stream', which is the
72 default, and simply connects to some port or other on the remote
73 system (see nntp-port-number).  The other are `nntp-open-rlogin', which
74 does an rlogin on the remote system, and then does a telnet to the
75 NNTP server available there (see nntp-rlogin-parameters) and `nntp-open-telnet' which
76 telnets to a remote system, logs in and does the same")
77
78 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
79   "*Parameters to `nntp-open-login'.
80 That function may be used as `nntp-open-server-function'.  In that
81 case, this list will be used as the parameter list given to rsh.")
82
83 (defvoo nntp-rlogin-user-name nil
84   "*User name on remote system when using the rlogin connect method.")
85
86 (defvoo nntp-telnet-parameters '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
87   "*Parameters to `nntp-open-telnet'.
88 That function may be used as `nntp-open-server-function'.  In that
89 case, this list will be executed as a command after logging in
90 via telnet.")
91
92 (defvoo nntp-telnet-user-name nil
93   "User name to log in via telnet with.")
94
95 (defvoo nntp-telnet-passwd nil
96   "Password to use to log in via telnet with.")
97
98 (defvoo nntp-end-of-line "\r\n"
99   "String to use on the end of lines when talking to the NNTP server.
100 This is \"\\r\\n\" by default, but should be \"\\n\" when
101 using rlogin or telnet to communicate with the server.")
102
103 (defvoo nntp-large-newsgroup 50
104   "*The number of the articles which indicates a large newsgroup.
105 If the number of the articles is greater than the value, verbose
106 messages will be shown to indicate the current status.")
107
108 (defvoo nntp-maximum-request 400
109   "*The maximum number of the requests sent to the NNTP server at one time.
110 If Emacs hangs up while retrieving headers, set the variable to a
111 lower value.")
112
113 (defvoo nntp-nov-is-evil nil
114   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
115
116 (defvoo nntp-xover-commands '("XOVER" "XOVERVIEW")
117   "*List of strings that are used as commands to fetch NOV lines from a server.
118 The strings are tried in turn until a positive response is gotten. If
119 none of the commands are successful, nntp will just grab headers one
120 by one.")
121
122 (defvoo nntp-nov-gap 20
123   "*Maximum allowed gap between two articles.
124 If the gap between two consecutive articles is bigger than this
125 variable, split the XOVER request into two requests.")
126
127 (defvoo nntp-connection-timeout nil
128   "*Number of seconds to wait before an nntp connection times out.
129 If this variable is nil, which is the default, no timers are set.")
130
131 (defvoo nntp-prepare-server-hook nil
132   "*Hook run before a server is opened.
133 If can be used to set up a server remotely, for instance.  Say you
134 have an account at the machine \"other.machine\".  This machine has
135 access to an NNTP server that you can't access locally.  You could
136 then use this hook to rsh to the remote machine and start a proxy NNTP
137 server there that you can connect to. See also `nntp-open-connection-function'")
138
139 (defvoo nntp-warn-about-losing-connection t
140   "*If non-nil, beep when a server closes connection.")
141
142 \f
143
144 ;;; Internal variables.
145
146 (defvar nntp-process-wait-for nil)
147 (defvar nntp-process-to-buffer nil)
148 (defvar nntp-process-callback nil)
149 (defvar nntp-process-decode nil)
150 (defvar nntp-process-start-point nil)
151 (defvar nntp-inside-change-function nil)
152
153 (defvar nntp-connection-list nil)
154
155 (defvoo nntp-server-type nil)
156 (defvoo nntp-connection-alist nil)
157 (defvoo nntp-status-string "")
158 (defconst nntp-version "nntp 5.0")
159 (defvoo nntp-inhibit-erase nil)
160
161 (defvoo nntp-server-xover 'try)
162 (defvoo nntp-server-list-active-group 'try)
163
164 (eval-and-compile
165   (autoload 'nnmail-read-passwd "nnmail"))
166
167 \f
168
169 ;;; Interface functions.
170
171 (nnoo-define-basics nntp)
172
173 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
174   "Retrieve the headers of ARTICLES."
175   (nntp-possibly-change-group group server)
176   (save-excursion
177     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
178     (erase-buffer)
179     (if (and (not gnus-nov-is-evil) 
180              (not nntp-nov-is-evil)
181              (nntp-retrieve-headers-with-xover articles fetch-old))
182         ;; We successfully retrieved the headers via XOVER.
183         'nov
184       ;; XOVER didn't work, so we do it the hard, slow and inefficient
185       ;; way.  
186       (let ((number (length articles))
187             (count 0)
188             (received 0)
189             (last-point (point-min))
190             (buf (nntp-find-connection-buffer nntp-server-buffer))
191             (nntp-inhibit-erase t))
192         ;; Send HEAD command.
193         (while articles
194           (nntp-send-command 
195            nil
196            "HEAD" (if (numberp (car articles)) 
197                       (int-to-string (car articles))
198                     ;; `articles' is either a list of article numbers
199                     ;; or a list of article IDs.
200                     (car articles)))
201           (setq articles (cdr articles)
202                 count (1+ count))
203           ;; Every 400 header requests we have to read the stream in
204           ;; order to avoid deadlocks.
205           (when (or (null articles)     ;All requests have been sent.
206                     (zerop (% count nntp-maximum-request)))
207             (nntp-accept-response)
208             (while (progn
209                      (progn
210                        (set-buffer buf)
211                        (goto-char last-point))
212                      ;; Count replies.
213                      (while (re-search-forward "^[0-9]" nil t)
214                        (incf received))
215                      (setq last-point (point))
216                      (< received count))
217               ;; If number of headers is greater than 100, give
218               ;;  informative messages.
219               (and (numberp nntp-large-newsgroup)
220                    (> number nntp-large-newsgroup)
221                    (zerop (% received 20))
222                    (message "NNTP: Receiving headers... %d%%"
223                             (/ (* received 100) number)))
224               (nntp-accept-response))))
225         ;; Wait for text of last command.
226         (goto-char (point-max))
227         (re-search-backward "^[0-9]" nil t)
228         (when (looking-at "^[23]")
229           (while (progn
230                    (goto-char (- (point-max) 3))
231                    (not (looking-at "^\\.\r?\n")))
232             (nntp-accept-response)))
233         (and (numberp nntp-large-newsgroup)
234              (> number nntp-large-newsgroup)
235              (message "NNTP: Receiving headers...done"))
236
237         ;; Now all of replies are received.  Fold continuation lines.
238         (nnheader-fold-continuation-lines)
239         ;; Remove all "\r"'s.
240         (goto-char (point-min))
241         (while (search-forward "\r" nil t)
242           (replace-match "" t t))
243         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
244         'headers))))
245
246 (deffoo nntp-retrieve-groups (groups &optional server)
247   "Retrieve group info on GROUPS."
248   (nntp-possibly-change-group nil server)
249   (save-excursion
250     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
251     ;; The first time this is run, this variable is `try'.  So we
252     ;; try.   
253     (when (eq nntp-server-list-active-group 'try)
254       (nntp-try-list-active (car groups)))
255     (erase-buffer)
256     (let ((count 0)
257           (received 0)
258           (last-point (point-min))
259           (nntp-inhibit-erase t)
260           (command (if nntp-server-list-active-group "LIST ACTIVE" "GROUP")))
261       (while groups
262         ;; Send the command to the server.
263         (nntp-send-command nil command (pop groups))
264         (incf count)
265         ;; Every 400 requests we have to read the stream in
266         ;; order to avoid deadlocks.
267         (when (or (null groups)         ;All requests have been sent.
268                   (zerop (% count nntp-maximum-request)))
269           (nntp-accept-response)
270           (while (progn
271                    (goto-char last-point)
272                    ;; Count replies.
273                    (while (re-search-forward "^[0-9]" nil t)
274                      (incf received))
275                    (setq last-point (point))
276                    (< received count))
277             (nntp-accept-response))))
278
279       ;; Wait for the reply from the final command.
280       (goto-char (point-max))
281       (re-search-backward "^[0-9]" nil t)
282       (when (looking-at "^[23]")
283         (while (progn
284                  (goto-char (point-max))
285                  (if (not nntp-server-list-active-group)
286                      (not (re-search-backward "\r?\n" (- (point) 3) t))
287                    (not (re-search-backward "^\\.\r?\n" (- (point) 4) t))))
288           (nntp-accept-response)))
289
290       ;; Now all replies are received. We remove CRs.
291       (goto-char (point-min))
292       (while (search-forward "\r" nil t)
293         (replace-match "" t t))
294
295       (if (not nntp-server-list-active-group)
296           (progn
297             (copy-to-buffer nntp-server-buffer (point-min) (point-max))
298             'group)
299         ;; We have read active entries, so we just delete the
300         ;; superfluos gunk.
301         (goto-char (point-min))
302         (while (re-search-forward "^[.2-5]" nil t)
303           (delete-region (match-beginning 0) 
304                          (progn (forward-line 1) (point))))
305         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
306         'active))))
307
308 (defun nntp-try-list-active (group)
309   (nntp-list-active-group group)
310   (save-excursion
311     (goto-char (point-min))
312     (cond ((looking-at "5[0-9]+")
313            (setq nntp-server-list-active-group nil))
314           (t
315            (setq nntp-server-list-active-group t)))))
316
317 (deffoo nntp-list-active-group (group &optional server)
318   "Return the active info on GROUP (which can be a regexp."
319   (nntp-possibly-change-group nil server)
320   (nntp-send-command "^.*\r?\n" "LIST ACTIVE" group))
321
322 (deffoo nntp-request-article (article &optional group server buffer command)
323   (nntp-possibly-change-group group server)
324   (when (nntp-send-command-and-decode
325          "\r?\n\\.\r?\n" "ARTICLE"
326          (if (numberp article) (int-to-string article) article))
327     (when (and buffer
328                (not (equal buffer nntp-server-buffer)))
329       (save-excursion
330         (set-buffer nntp-server-buffer)
331         (copy-to-buffer buffer (point-min) (point-max))
332         (nntp-find-group-and-number)))
333     (nntp-find-group-and-number)))
334
335 (deffoo nntp-request-head (article &optional group server)
336   (nntp-possibly-change-group group server)
337   (when (nntp-send-command-and-decode
338          "\r\n\\.\r\n" "HEAD"
339          (if (numberp article) (int-to-string article) article))
340     (nntp-find-group-and-number)))
341
342 (deffoo nntp-request-body (article &optional group server)
343   (nntp-possibly-change-group group server)
344   (nntp-send-command-and-decode
345    "\r?\n\\.\r?\n" "BODY"
346    (if (numberp article) (int-to-string article) article)))
347
348 (deffoo nntp-request-group (group &optional server dont-check)
349   (nntp-possibly-change-group nil server)
350   (when (nntp-send-command "^2.*\n" "GROUP" group)
351     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
352       (setcar (cddr entry) group))))
353
354 (deffoo nntp-close-group (group &optional server)
355   t)
356
357 (deffoo nntp-server-opened (&optional server)
358   "Say whether a connection to SERVER has been opened."
359   (and (nnoo-current-server-p 'nntp server)
360        nntp-server-buffer
361        (gnus-buffer-live-p nntp-server-buffer)
362        (nntp-find-connection nntp-server-buffer)))
363
364 (deffoo nntp-open-server (server &optional defs connectionless)
365   (nnheader-init-server-buffer)
366   (if (nntp-server-opened server)
367       t
368     (when (or (stringp (car defs))
369               (numberp (car defs)))
370       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
371     (unless (assq 'nntp-address defs)
372       (setq defs (append defs (list (list 'nntp-address server)))))
373     (nnoo-change-server 'nntp server defs)
374     (unless connectionless
375       (or (nntp-find-connection nntp-server-buffer)
376           (nntp-open-connection nntp-server-buffer)))))
377
378 (deffoo nntp-close-server (&optional server)
379   (nntp-possibly-change-group nil server t)
380   (let (process)
381     (while (setq process (car (pop nntp-connection-alist)))
382       (when (memq (process-status process) '(open run))
383         (set-process-sentinel process nil)
384         (nntp-send-string process "QUIT"))
385       (when (buffer-name (process-buffer process))
386         (kill-buffer (process-buffer process))))
387     (nnoo-close-server 'nntp)))
388
389 (deffoo nntp-request-close ()
390   (let (process)
391     (while (setq process (pop nntp-connection-list))
392       (when (memq (process-status process) '(open run))
393         (set-process-sentinel process nil)
394         (nntp-send-string process "QUIT"))
395       (when (buffer-name (process-buffer process))
396         (kill-buffer (process-buffer process))))))
397
398 (deffoo nntp-request-list (&optional server)
399   (nntp-possibly-change-group nil server)
400   (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST"))
401
402 (deffoo nntp-request-list-newsgroups (&optional server)
403   (nntp-possibly-change-group nil server)
404   (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS"))
405
406 (deffoo nntp-request-newgroups (date &optional server)
407   (nntp-possibly-change-group nil server)
408   (save-excursion
409     (set-buffer nntp-server-buffer)
410     (let* ((date (timezone-parse-date date))
411            (time-string
412             (format "%s%02d%02d %s%s%s"
413                     (substring (aref date 0) 2) (string-to-int (aref date 1)) 
414                     (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
415                     (substring 
416                      (aref date 3) 3 5) (substring (aref date 3) 6 8))))
417       (prog1
418           (nntp-send-command "^\\.\r?\n" "NEWGROUPS" time-string)
419         (nntp-decode-text)))))
420
421 (deffoo nntp-request-post (&optional server)
422   (nntp-possibly-change-group nil server)
423   (when (nntp-send-command "^[23].*\r?\n" "POST")
424     (nntp-send-buffer "^[23].*\n")))
425
426 (deffoo nntp-request-type (group article)
427   'news)
428   
429 (deffoo nntp-asynchronous-p ()
430   t)
431
432 ;;; Hooky functions.
433
434 (defun nntp-send-mode-reader ()
435   "Send the MODE READER command to the nntp server.
436 This function is supposed to be called from `nntp-server-opened-hook'.
437 It will make innd servers spawn an nnrpd process to allow actual article
438 reading."
439   (nntp-send-command "^.*\r?\n" "MODE READER"))
440
441 (defun nntp-send-nosy-authinfo ()
442   "Send the AUTHINFO to the nntp server.
443 This function is supposed to be called from `nntp-server-opened-hook'.
444 It will prompt for a password."
445   (nntp-send-command "^.*\r?\n" "AUTHINFO USER"
446                      (read-string "NNTP user name: "))
447   (nntp-send-command "^.*\r?\n" "AUTHINFO PASS" 
448                      (nnmail-read-passwd "NNTP password: ")))
449
450 (defun nntp-send-authinfo ()
451   "Send the AUTHINFO to the nntp server.
452 This function is supposed to be called from `nntp-server-opened-hook'.
453 It will prompt for a password."
454   (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
455   (nntp-send-command "^.*\r?\n" "AUTHINFO PASS" 
456                      (read-string "NNTP password: ")))
457
458 (defun nntp-send-authinfo-from-file ()
459   "Send the AUTHINFO to the nntp server.
460 This function is supposed to be called from `nntp-server-opened-hook'.
461 It will prompt for a password."
462   (when (file-exists-p "~/.nntp-authinfo")
463     (save-excursion
464       (set-buffer (get-buffer-create " *authinfo*"))
465       (buffer-disable-undo (current-buffer))
466       (erase-buffer)
467       (insert-file-contents "~/.nntp-authinfo")
468       (goto-char (point-min))
469       (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
470       (nntp-send-command 
471        "^.*\r?\n" "AUTHINFO PASS" 
472        (buffer-substring (point) (progn (end-of-line) (point))))
473       (kill-buffer (current-buffer)))))
474
475 ;;; Internal functions.
476
477 (defun nntp-send-command (wait-for &rest strings)
478   "Send STRINGS to server and wait until WAIT-FOR returns."
479   (unless nnheader-callback-function
480     (save-excursion
481       (set-buffer nntp-server-buffer)
482       (erase-buffer)))
483   (nntp-retrieve-data
484    (mapconcat 'identity strings " ") 
485    nntp-address nntp-port-number nntp-server-buffer
486    wait-for nnheader-callback-function))
487
488 (defun nntp-send-command-nodelete (wait-for &rest strings)
489   "Send STRINGS to server and wait until WAIT-FOR returns."
490   (nntp-retrieve-data
491    (mapconcat 'identity strings " ") 
492    nntp-address nntp-port-number nntp-server-buffer
493    wait-for nnheader-callback-function))
494
495 (defun nntp-send-command-and-decode (wait-for &rest strings)
496   "Send STRINGS to server and wait until WAIT-FOR returns."
497   (unless nnheader-callback-function
498     (save-excursion
499       (set-buffer nntp-server-buffer)
500       (erase-buffer)))
501   (nntp-retrieve-data
502    (mapconcat 'identity strings " ") 
503    nntp-address nntp-port-number nntp-server-buffer
504    wait-for nnheader-callback-function t))
505
506 (defun nntp-send-buffer (wait-for)
507   "Send the current buffer to server and wait until WAIT-FOR returns."
508   (unless nnheader-callback-function
509     (save-excursion
510       (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
511       (erase-buffer)))
512   (nntp-encode-text)
513   (process-send-region (nntp-find-connection nntp-server-buffer)
514                        (point-min) (point-max))
515   (nntp-retrieve-data
516    nil nntp-address nntp-port-number nntp-server-buffer
517    wait-for nnheader-callback-function))
518
519 (defun nntp-find-connection (buffer)
520   "Find the connection delivering to BUFFER."
521   (let ((alist nntp-connection-alist)
522         (buffer (if (stringp buffer) (get-buffer buffer) buffer))
523         process entry)
524     (while (setq entry (pop alist))
525       (when (eq buffer (cadr entry))
526         (setq process (car entry)
527               alist nil)))
528     (when process
529       (if (memq (process-status process) '(open run))
530           process
531         (when (buffer-name (process-buffer process))
532           (kill-buffer (process-buffer process)))
533         (setq nntp-connection-alist (delq entry nntp-connection-alist))
534         nil))))
535
536 (defun nntp-find-connection-entry (buffer)
537   "Return the entry for the connection to BUFFER."
538   (assq (nntp-find-connection buffer) nntp-connection-alist))
539
540 (defun nntp-find-connection-buffer (buffer)
541   "Return the process connection buffer tied to BUFFER."
542   (let ((process (nntp-find-connection buffer)))
543     (when process
544       (process-buffer process))))
545
546 (defun nntp-make-process-buffer (buffer)
547   "Create a new, fresh buffer usable for nntp process connections."
548   (save-excursion
549     (set-buffer 
550      (generate-new-buffer
551       (format " *server %s %s %s*"
552               nntp-address nntp-port-number
553               (buffer-name (get-buffer buffer)))))
554     (buffer-disable-undo (current-buffer))
555     (set (make-local-variable 'after-change-functions) nil)
556     (set (make-local-variable 'nntp-process-wait-for) nil)
557     (set (make-local-variable 'nntp-process-callback) nil)
558     (set (make-local-variable 'nntp-process-to-buffer) nil)
559     (set (make-local-variable 'nntp-process-start-point) nil)
560     (set (make-local-variable 'nntp-process-decode) nil)
561     (current-buffer)))
562
563 (defun nntp-open-connection (buffer)
564   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
565   (run-hooks 'nntp-prepare-server-hook)
566   (let* ((pbuffer (nntp-make-process-buffer buffer))
567          (process
568           (condition-case ()
569               (funcall
570                nntp-open-connection-function pbuffer)
571             (error nil))))
572     (when process
573       (process-kill-without-query process)
574       (nntp-wait-for process "^.*\n" buffer)
575       (if (memq (process-status process) '(open run))
576           (prog1
577               (caar (push (list process buffer nil) 
578                           nntp-connection-alist))
579             (push process nntp-connection-list)
580             (nntp-read-server-type)
581             (run-hooks 'nntp-server-opened-hook))
582         (when (buffer-name (process-buffer process))
583           (kill-buffer (process-buffer process)))
584         nil))))
585
586 (defun nntp-open-network-stream (buffer)
587   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
588
589 (defun nntp-read-server-type ()
590   "Find out what the name of the server we have connected to is."
591   ;; Wait for the status string to arrive.
592   (setq nntp-server-type (buffer-string))
593   (let ((alist nntp-server-action-alist)
594         entry)
595     ;; Run server-specific commmands.
596     (while alist
597       (setq entry (pop alist))
598       (when (string-match (car entry) nntp-server-type)
599         (if (and (listp (cadr entry))
600                  (not (eq 'lambda (caadr entry))))
601             (eval (cadr entry))
602           (funcall (cadr entry)))))))
603
604 (defun nntp-after-change-function (beg end len)
605   (when nntp-process-callback
606     (save-match-data
607       (if (and (= beg (point-min))
608                (memq (char-after beg) '(?4 ?5)))
609           ;; Report back error messages.
610           (save-excursion
611             (goto-char beg)
612             (if (looking-at "480")
613                 (funcall nntp-authinfo-function)
614               (nntp-snarf-error-message)
615               (funcall nntp-process-callback nil)))
616         (goto-char end)
617         (when (and (> (point) nntp-process-start-point)
618                    (re-search-backward nntp-process-wait-for
619                                        nntp-process-start-point t))
620           (when (buffer-name (get-buffer nntp-process-to-buffer))
621             (let ((cur (current-buffer))
622                   (start nntp-process-start-point))
623               (save-excursion
624                 (set-buffer (get-buffer nntp-process-to-buffer))
625                 (goto-char (point-max))
626                 (let ((b (point)))
627                   (insert-buffer-substring cur start)
628                   (narrow-to-region b (point-max))
629                   (nntp-decode-text)
630                   (goto-char (point-min))
631                   (gnus-delete-line)
632                   (widen)))))
633           (goto-char end)
634           (let ((callback nntp-process-callback)
635                 (nntp-inside-change-function t))
636             (setq nntp-process-callback nil)
637             (save-excursion
638               (funcall callback t))))))))
639
640 (defun nntp-retrieve-data (command address port buffer
641                                    &optional wait-for callback decode)
642   "Use COMMAND to retrieve data into BUFFER from PORT on ADDRESS."
643   (let ((process (or (nntp-find-connection buffer)
644                      (nntp-open-connection buffer))))
645     (if (not process)
646         (nnheader-report 'nntp "Couldn't open connection to %s" address)
647       (unless (or nntp-inhibit-erase nnheader-callback-function)
648         (save-excursion
649           (set-buffer (process-buffer process))
650           (erase-buffer)))
651       (when command
652         (nntp-send-string process command))
653       (cond 
654        ((eq callback 'ignore)
655         t)
656        ((and callback wait-for)
657         (save-excursion
658           (set-buffer (process-buffer process))
659           (unless nntp-inside-change-function 
660             (erase-buffer))
661           (setq nntp-process-decode decode
662                 nntp-process-to-buffer buffer
663                 nntp-process-wait-for wait-for
664                 nntp-process-callback callback
665                 nntp-process-start-point (point-max)
666                 after-change-functions (list 'nntp-after-change-function)))
667         t)
668        (wait-for 
669         (nntp-wait-for process wait-for buffer decode))
670        (t t)))))
671
672 (defun nntp-send-string (process string)
673   "Send STRING to PROCESS."
674   (process-send-string process (concat string nntp-end-of-line)))
675
676 (defun nntp-wait-for (process wait-for buffer &optional decode)
677   "Wait for WAIT-FOR to arrive from PROCESS."
678   (save-excursion
679     (set-buffer (process-buffer process))
680     (goto-char (point-min))
681     (while (or (not (memq (following-char) '(?2 ?3 ?4 ?5)))
682                (looking-at "480"))
683       (when (looking-at "480")
684         (erase-buffer)
685         (funcall nntp-authinfo-function))
686       (nntp-accept-process-output process)
687       (goto-char (point-min)))
688     (prog1
689         (if (looking-at "[45]")
690             (progn
691               (nntp-snarf-error-message)
692               nil)
693           (goto-char (point-max))
694           (while (not (re-search-backward wait-for nil t))
695             (nntp-accept-process-output process)
696             (goto-char (point-max)))
697           (nntp-decode-text (not decode))
698           (save-excursion
699             (set-buffer buffer)
700             (goto-char (point-max))
701             (insert-buffer-substring (process-buffer process))
702             t))
703       (erase-buffer))))
704
705 (defun nntp-snarf-error-message ()
706   "Save the error message in the current buffer."
707   (setq nntp-status-string (buffer-string)))
708
709 (defun nntp-accept-process-output (process)
710   "Wait for output from PROCESS and message some dots."
711   (save-excursion
712     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
713                     nntp-server-buffer))
714     (message "nntp reading%s" (make-string (/ (point-max) 10000) ?.))
715     (accept-process-output process 1)))
716
717 (defun nntp-accept-response ()
718   "Wait for output from the process that outputs to BUFFER."
719   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
720
721 (defun nntp-possibly-change-group (group server &optional connectionless)
722   (when server
723     (or (nntp-server-opened server)
724         (nntp-open-server server nil connectionless)))
725
726   (unless connectionless
727     (or (nntp-find-connection nntp-server-buffer)
728         (nntp-open-connection nntp-server-buffer)))
729
730   (when group
731     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
732       (when (not (equal group (caddr entry)))
733         (nntp-request-group group)))))
734
735 (defun nntp-decode-text (&optional cr-only)
736   "Decode the text in the current buffer."
737   (goto-char (point-min))
738   (while (search-forward "\r" nil t)
739     (delete-char -1))
740   (unless cr-only
741     (goto-char (point-max))
742     (forward-line -1)
743     (when (looking-at ".\n")
744       (delete-char 2))
745     (goto-char (point-min))
746     (delete-region (point) (progn (forward-line 1) (point)))
747     (while (search-forward "\n.." nil t)
748       (delete-char -1))))
749
750 (defun nntp-encode-text ()
751   "Encode the text in the current buffer."
752   (save-excursion
753     ;; Replace "." at beginning of line with "..".
754     (goto-char (point-min))
755     (while (re-search-forward "^\\." nil t)
756       (insert "."))
757     (goto-char (point-max))
758     ;; Insert newline at the end of the buffer.
759     (unless (bolp)
760       (insert "\n"))
761     ;; Insert `.' at end of buffer (end of text mark).
762     (goto-char (point-max))
763     (insert "." nntp-end-of-line)))
764
765 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
766   (set-buffer nntp-server-buffer)
767   (erase-buffer)
768   (cond 
769
770    ;; This server does not talk NOV.
771    ((not nntp-server-xover)
772     nil)
773
774    ;; We don't care about gaps.
775    ((or (not nntp-nov-gap)
776         fetch-old)
777     (nntp-send-xover-command 
778      (if fetch-old
779          (if (numberp fetch-old) 
780              (max 1 (- (car articles) fetch-old)) 
781            1)
782        (car articles))
783      (car (last articles)) 'wait)
784
785     (goto-char (point-min))
786     (when (looking-at "[1-5][0-9][0-9] ")
787       (delete-region (point) (progn (forward-line 1) (point))))
788     (while (search-forward "\r" nil t)
789       (replace-match "" t t))
790     (goto-char (point-max))
791     (forward-line -1)
792     (when (looking-at "\\.")
793       (delete-region (point) (progn (forward-line 1) (point)))))
794
795    ;; We do it the hard way.  For each gap, an XOVER command is sent
796    ;; to the server.  We do not wait for a reply from the server, we
797    ;; just send them off as fast as we can.  That means that we have
798    ;; to count the number of responses we get back to find out when we
799    ;; have gotten all we asked for.
800    ((numberp nntp-nov-gap)
801     (let ((count 0)
802           (received 0)
803           (last-point (point-min))
804           (buf nntp-server-buffer)
805           ;;(process-buffer (nntp-find-connection (current-buffer))))
806           first)
807       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
808       ;; that means that the server does not understand XOVER, but we
809       ;; won't know that until we try.
810       (while (and nntp-server-xover articles)
811         (setq first (car articles))
812         ;; Search forward until we find a gap, or until we run out of
813         ;; articles. 
814         (while (and (cdr articles) 
815                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
816           (setq articles (cdr articles)))
817
818         (when (nntp-send-xover-command first (car articles))
819           (setq articles (cdr articles)
820                 count (1+ count))
821
822           ;; Every 400 requests we have to read the stream in
823           ;; order to avoid deadlocks.
824           (when (or (null articles)     ;All requests have been sent.
825                     (zerop (% count nntp-maximum-request)))
826             (accept-process-output)
827             ;; On some Emacs versions the preceding function has
828             ;; a tendency to change the buffer. Perhaps. It's
829             ;; quite difficult to reproduce, because it only
830             ;; seems to happen once in a blue moon. 
831             (set-buffer buf) 
832             (while (progn
833                      (goto-char last-point)
834                      ;; Count replies.
835                      (while (re-search-forward "^[0-9][0-9][0-9] " nil t)
836                        (setq received (1+ received)))
837                      (setq last-point (point))
838                      (< received count))
839               (accept-process-output)
840               (set-buffer buf)))))
841
842       (when nntp-server-xover
843         ;; Wait for the reply from the final command.
844         (goto-char (point-max))
845         (re-search-backward "^[0-9][0-9][0-9] " nil t)
846         (when (looking-at "^[23]")
847           (while (progn
848                    (goto-char (point-max))
849                    (forward-line -1)
850                    (not (looking-at "^\\.\r?\n")))
851             (nntp-accept-response)))
852         
853         ;; We remove any "." lines and status lines.
854         (goto-char (point-min))
855         (while (search-forward "\r" nil t)
856           (delete-char -1))
857         (goto-char (point-min))
858         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
859         ;;(copy-to-buffer nntp-server-buffer (point-min) (point-max))
860         t))))
861
862   nntp-server-xover)
863
864 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
865   "Send the XOVER command to the server."
866   (let ((range (format "%d-%d" beg end))
867         (nntp-inhibit-erase t))
868     (if (stringp nntp-server-xover)
869         ;; If `nntp-server-xover' is a string, then we just send this
870         ;; command.
871         (if wait-for-reply
872             (nntp-send-command-nodelete "\r?\n\\.\r?\n" nntp-server-xover range)
873           ;; We do not wait for the reply.
874           (nntp-send-command-nodelete "\r?\n\\.\r?\n" nntp-server-xover range))
875       (let ((commands nntp-xover-commands))
876         ;; `nntp-xover-commands' is a list of possible XOVER commands.
877         ;; We try them all until we get at positive response. 
878         (while (and commands (eq nntp-server-xover 'try))
879           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
880           (save-excursion
881             (set-buffer nntp-server-buffer)
882             (goto-char (point-min))
883             (and (looking-at "[23]") ; No error message.
884                  ;; We also have to look at the lines.  Some buggy
885                  ;; servers give back simple lines with just the
886                  ;; article number.  How... helpful.
887                  (progn
888                    (forward-line 1)
889                    (looking-at "[0-9]+\t...")) ; More text after number.
890                  (setq nntp-server-xover (car commands))))
891           (setq commands (cdr commands)))
892         ;; If none of the commands worked, we disable XOVER.
893         (when (eq nntp-server-xover 'try)
894           (save-excursion
895             (set-buffer nntp-server-buffer)
896             (erase-buffer)
897             (setq nntp-server-xover nil)))
898         nntp-server-xover))))
899
900 ;;; Alternative connection methods.
901
902 (defun nntp-wait-for-string (regexp)
903   "Wait until string arrives in the buffer."
904   (let ((buf (current-buffer)))
905     (goto-char (point-min))
906     (while (not (re-search-forward regexp nil t))
907       (accept-process-output (nntp-find-connection nntp-server-buffer))
908       (set-buffer buf)
909       (goto-char (point-min)))))
910
911 (defun nntp-open-telnet (buffer)
912   (save-excursion
913     (set-buffer buffer)
914     (erase-buffer)
915     (let ((proc (start-process
916                  "nntpd" buffer "telnet" "-8"))
917           (case-fold-search t))
918       (when (memq (process-status proc) '(open run))
919         (process-send-string proc "set escape \^X\n")
920         (process-send-string proc (concat "open " nntp-address "\n"))
921         (nntp-wait-for-string "^\r*.?login:")
922         (process-send-string
923          proc (concat
924                (or nntp-telnet-user-name
925                    (setq nntp-telnet-user-name (read-string "login: ")))
926                "\n"))
927         (nntp-wait-for-string "^\r*.?password:")
928         (process-send-string
929          proc (concat
930                (or nntp-telnet-passwd
931                    (setq nntp-telnet-passwd
932                          (nnmail-read-passwd "Password: ")))
933                "\n"))
934         (erase-buffer)
935         (nntp-wait-for-string "bash\\|\$ *\r?$\\|> *\r?")
936         (process-send-string
937          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
938         (nntp-wait-for-string "^\r*200")
939         (beginning-of-line)
940         (delete-region (point-min) (point))
941         (process-send-string proc "\^]")
942         (nntp-wait-for-string "^telnet")
943         (process-send-string proc "mode character\n")
944         (accept-process-output proc 1)
945         (sit-for 1)
946         (goto-char (point-min))
947         (forward-line 1)
948         (delete-region (point) (point-max)))
949       proc)))
950
951 (defun nntp-open-rlogin (buffer)
952   "Open a connection to SERVER using rsh."
953   (let ((proc (if nntp-rlogin-user-name
954                   (start-process
955                    "nntpd" buffer "rsh"
956                    nntp-address "-l" nntp-rlogin-user-name
957                    (mapconcat 'identity
958                               nntp-rlogin-parameters " "))
959                 (start-process
960                  "nntpd" buffer "rsh" nntp-address
961                  (mapconcat 'identity
962                             nntp-rlogin-parameters " ")))))
963     (set-buffer buffer)
964     (nntp-wait-for-string "^\r*200")
965     (beginning-of-line)
966     (delete-region (point-min) (point))
967     proc)
968   )
969
970 (defun nntp-find-group-and-number ()
971   (save-excursion
972     (save-restriction
973       (set-buffer nntp-server-buffer)
974       (narrow-to-region (goto-char (point-min))
975                         (or (search-forward "\n\n" nil t) (point-max)))
976       (goto-char (point-min))
977       ;; We first find the number by looking at the status line.
978       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
979                          (string-to-int
980                           (buffer-substring (match-beginning 1)
981                                             (match-end 1)))))
982             group newsgroups xref)
983         (and number (zerop number) (setq number nil))
984         ;; Then we find the group name.
985         (setq group
986               (cond 
987                ;; If there is only one group in the Newsgroups header,
988                ;; then it seems quite likely that this article comes
989                ;; from that group, I'd say.
990                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
991                      (not (string-match "," newsgroups)))
992                 newsgroups)
993                ;; If there is more than one group in the Newsgroups
994                ;; header, then the Xref header should be filled out.
995                ;; We hazard a guess that the group that has this
996                ;; article number in the Xref header is the one we are
997                ;; looking for.  This might very well be wrong if this
998                ;; article happens to have the same number in several
999                ;; groups, but that's life. 
1000                ((and (setq xref (mail-fetch-field "xref"))
1001                      number
1002                      (string-match (format "\\([^ :]+\\):%d" number) xref))
1003                 (substring xref (match-beginning 1) (match-end 1)))
1004                (t "")))
1005         (when (string-match "\r" group) 
1006           (setq group (substring group 0 (match-beginning 0))))
1007         (cons group number)))))
1008
1009 (provide 'nntp)
1010
1011 ;;; nntp.el ends here