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