6c4b226b28778e70611e49fb30c21cb2d5b39165
[gnus] / lisp / nntp.el
1 ;;; nntp.el --- nntp access for Gnus
2
3 ;; Copyright (C) 1987, 1988, 1989, 1990, 1992, 1993, 1994, 1995, 1996,
4 ;; 1997, 1998, 2000, 2001, 2002 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: news
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published
13 ;; by the Free Software Foundation; either version 2, or (at your
14 ;; option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (require 'nnheader)
30 (require 'nnoo)
31 (require 'gnus-util)
32
33 (nnoo-declare nntp)
34
35 (eval-when-compile (require 'cl))
36
37 (defvoo nntp-address nil
38   "Address of the physical nntp server.")
39
40 (defvoo nntp-port-number "nntp"
41   "Port number on the physical nntp server.")
42
43 (defvoo nntp-server-opened-hook '(nntp-send-mode-reader)
44   "*Hook used for sending commands to the server at startup.
45 The default value is `nntp-send-mode-reader', which makes an innd
46 server spawn an nnrpd server.")
47
48 (defvoo nntp-authinfo-function 'nntp-send-authinfo
49   "Function used to send AUTHINFO to the server.
50 It is called with no parameters.")
51
52 (defvoo nntp-server-action-alist
53     '(("nntpd 1\\.5\\.11t"
54        (remove-hook 'nntp-server-opened-hook 'nntp-send-mode-reader))
55       ("NNRP server Netscape"
56        (setq nntp-server-list-active-group nil)))
57   "Alist of regexps to match on server types and actions to be taken.
58 For instance, if you want Gnus to beep every time you connect
59 to innd, you could say something like:
60
61 \(setq nntp-server-action-alist
62        '((\"innd\" (ding))))
63
64 You probably don't want to do that, though.")
65
66 (defvoo nntp-open-connection-function 'nntp-open-network-stream
67   "*Function used for connecting to a remote system.
68 It will be called with the buffer to output in as argument.
69
70 Currently, five such functions are provided (please refer to their
71 respective doc string for more information), three of them establishing
72 direct connections to the nntp server, and two of them using an indirect
73 host.
74
75 Direct connections:
76 - `nntp-open-network-stream' (the default),
77 - `nntp-open-ssl-stream',
78 - `nntp-open-telnet-stream'.
79
80 Indirect connections:
81 - `nntp-open-via-rlogin-and-telnet',
82 - `nntp-open-via-telnet-and-telnet'.")
83
84 (defvoo nntp-pre-command nil
85   "*Pre-command to use with the various nntp-open-via-* methods.
86 This is where you would put \"runsocks\" or stuff like that.")
87
88 (defvoo nntp-telnet-command "telnet"
89   "*Telnet command used to connect to the nntp server.
90 This command is used by the various nntp-open-via-* methods.")
91
92 (defvoo nntp-telnet-switches '("-8")
93   "*Switches given to the telnet command `nntp-telnet-command'.")
94
95 (defvoo nntp-end-of-line "\r\n"
96   "*String to use on the end of lines when talking to the NNTP server.
97 This is \"\\r\\n\" by default, but should be \"\\n\" when
98 using and indirect connection method (nntp-open-via-*).")
99
100 (defvoo nntp-via-rlogin-command "rsh"
101   "*Rlogin command used to connect to an intermediate host.
102 This command is used by the `nntp-open-via-rlogin-and-telnet' method.
103 The default is \"rsh\", but \"ssh\" is a popular alternative.")
104
105 (defvoo nntp-via-telnet-command "telnet"
106   "*Telnet command used to connect to an intermediate host.
107 This command is used by the `nntp-open-via-telnet-and-telnet' method.")
108
109 (defvoo nntp-via-telnet-switches '("-8")
110   "*Switches given to the telnet command `nntp-via-telnet-command'.")
111
112 (defvoo nntp-via-user-name nil
113   "*User name to log in on an intermediate host with.
114 This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
115
116 (defvoo nntp-via-user-password nil
117   "*Password to use to log in on an intermediate host with.
118 This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
119
120 (defvoo nntp-via-address nil
121   "*Address of an intermediate host to connect to.
122 This variable is used by the `nntp-open-via-rlogin-and-telnet' and
123 `nntp-open-via-telnet-and-telnet' methods.")
124
125 (defvoo nntp-via-envuser nil
126   "*Whether both telnet client and server support the ENVIRON option.
127 If non-nil, there will be no prompt for a login name.")
128
129 (defvoo nntp-via-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
130   "*Regular expression to match the shell prompt on an intermediate host.
131 This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
132
133 (defvoo nntp-large-newsgroup 50
134   "*The number of the articles which indicates a large newsgroup.
135 If the number of the articles is greater than the value, verbose
136 messages will be shown to indicate the current status.")
137
138 (defvoo nntp-maximum-request 400
139   "*The maximum number of the requests sent to the NNTP server at one time.
140 If Emacs hangs up while retrieving headers, set the variable to a
141 lower value.")
142
143 (defvoo nntp-nov-is-evil nil
144   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
145
146 (defvoo nntp-xover-commands '("XOVER" "XOVERVIEW")
147   "*List of strings that are used as commands to fetch NOV lines from a server.
148 The strings are tried in turn until a positive response is gotten.  If
149 none of the commands are successful, nntp will just grab headers one
150 by one.")
151
152 (defvoo nntp-nov-gap 5
153   "*Maximum allowed gap between two articles.
154 If the gap between two consecutive articles is bigger than this
155 variable, split the XOVER request into two requests.")
156
157 (defvoo nntp-prepare-server-hook nil
158   "*Hook run before a server is opened.
159 If can be used to set up a server remotely, for instance.  Say you
160 have an account at the machine \"other.machine\".  This machine has
161 access to an NNTP server that you can't access locally.  You could
162 then use this hook to rsh to the remote machine and start a proxy NNTP
163 server there that you can connect to.  See also
164 `nntp-open-connection-function'")
165
166 (defvoo nntp-warn-about-losing-connection t
167   "*If non-nil, beep when a server closes connection.")
168
169 (defvoo nntp-coding-system-for-read 'binary
170   "*Coding system to read from NNTP.")
171
172 (defvoo nntp-coding-system-for-write 'binary
173   "*Coding system to write to NNTP.")
174
175 (defcustom nntp-authinfo-file "~/.authinfo"
176   ".netrc-like file that holds nntp authinfo passwords."
177   :type
178   '(choice file
179            (repeat :tag "Entries"
180                    :menu-tag "Inline"
181                    (list :format "%v"
182                          :value ("" ("login" . "") ("password" . ""))
183                          (string :tag "Host")
184                          (checklist :inline t
185                                     (cons :format "%v"
186                                           (const :format "" "login")
187                                           (string :format "Login: %v"))
188                                     (cons :format "%v"
189                                           (const :format "" "password")
190                                           (string :format "Password: %v")))))))
191
192 \f
193
194 (defvoo nntp-connection-timeout nil
195   "*Number of seconds to wait before an nntp connection times out.
196 If this variable is nil, which is the default, no timers are set.
197 NOTE: This variable is never seen to work in Emacs 20 and XEmacs 21.")
198
199 (defvoo nntp-prepare-post-hook nil
200   "*Hook run just before posting an article.  It is supposed to be used
201 to insert Cancel-Lock headers.")
202
203 ;;; Internal variables.
204
205 (defvar nntp-record-commands nil
206   "*If non-nil, nntp will record all commands in the \"*nntp-log*\" buffer.")
207
208 (defvar nntp-have-messaged nil)
209
210 (defvar nntp-process-wait-for nil)
211 (defvar nntp-process-to-buffer nil)
212 (defvar nntp-process-callback nil)
213 (defvar nntp-process-decode nil)
214 (defvar nntp-process-start-point nil)
215 (defvar nntp-inside-change-function nil)
216 (defvoo nntp-last-command-time nil)
217 (defvoo nntp-last-command nil)
218 (defvoo nntp-authinfo-password nil)
219 (defvoo nntp-authinfo-user nil)
220
221 (defvar nntp-connection-list nil)
222
223 (defvoo nntp-server-type nil)
224 (defvoo nntp-connection-alist nil)
225 (defvoo nntp-status-string "")
226 (defconst nntp-version "nntp 5.0")
227 (defvoo nntp-inhibit-erase nil)
228 (defvoo nntp-inhibit-output nil)
229
230 (defvoo nntp-server-xover 'try)
231 (defvoo nntp-server-list-active-group 'try)
232
233 (defvar nntp-async-needs-kluge
234   (string-match "^GNU Emacs 20\\.3\\." (emacs-version))
235   "*When non-nil, nntp will poll asynchronous connections
236 once a second.  By default, this is turned on only for Emacs
237 20.3, which has a bug that breaks nntp's normal method of
238 noticing asynchronous data.")
239
240 (defvar nntp-async-timer nil)
241 (defvar nntp-async-process-list nil)
242
243 (eval-and-compile
244   (autoload 'mail-source-read-passwd "mail-source")
245   (autoload 'open-ssl-stream "ssl"))
246
247 \f
248
249 ;;; Internal functions.
250
251 (defsubst nntp-send-string (process string)
252   "Send STRING to PROCESS."
253   ;; We need to store the time to provide timeouts, and
254   ;; to store the command so the we can replay the command
255   ;; if the server gives us an AUTHINFO challenge.
256   (setq nntp-last-command-time (current-time)
257         nntp-last-command string)
258   (when nntp-record-commands
259     (nntp-record-command string))
260   (process-send-string process (concat string nntp-end-of-line)))
261
262 (defun nntp-record-command (string)
263   "Record the command STRING."
264   (save-excursion
265     (set-buffer (get-buffer-create "*nntp-log*"))
266     (goto-char (point-max))
267     (let ((time (current-time)))
268       (insert (format-time-string "%Y%m%dT%H%M%S" time)
269               "." (format "%03d" (/ (nth 2 time) 1000))
270               " " nntp-address " " string "\n"))))
271
272 (defsubst nntp-wait-for (process wait-for buffer &optional decode discard)
273   "Wait for WAIT-FOR to arrive from PROCESS."
274   (save-excursion
275     (set-buffer (process-buffer process))
276     (goto-char (point-min))
277     (while (and (or (not (memq (char-after (point)) '(?2 ?3 ?4 ?5)))
278                     (looking-at "480"))
279                 (memq (process-status process) '(open run)))
280       (when (looking-at "480")
281         (nntp-handle-authinfo process))
282       (when (looking-at "^.*\n")
283         (delete-region (point) (progn (forward-line 1) (point))))
284       (nntp-accept-process-output process)
285       (goto-char (point-min)))
286     (prog1
287         (cond
288          ((looking-at "[45]")
289           (progn
290             (nntp-snarf-error-message)
291             nil))
292          ((not (memq (process-status process) '(open run)))
293           (nnheader-report 'nntp "Server closed connection"))
294          (t
295           (goto-char (point-max))
296           (let ((limit (point-min))
297                 response)
298             (while (not (re-search-backward wait-for limit t))
299               (nntp-accept-process-output process)
300               ;; We assume that whatever we wait for is less than 1000
301               ;; characters long.
302               (setq limit (max (- (point-max) 1000) (point-min)))
303               (goto-char (point-max)))
304             (setq response (match-string 0))
305             (with-current-buffer nntp-server-buffer
306               (setq nntp-process-response response)))
307           (nntp-decode-text (not decode))
308           (unless discard
309             (save-excursion
310               (set-buffer buffer)
311               (goto-char (point-max))
312               (insert-buffer-substring (process-buffer process))
313               ;; Nix out "nntp reading...." message.
314               (when nntp-have-messaged
315                 (setq nntp-have-messaged nil)
316                 (nnheader-message 5 ""))))
317           t))
318       (unless discard
319         (erase-buffer)))))
320
321 (defun nntp-kill-buffer (buffer)
322   (when (buffer-name buffer)
323     (kill-buffer buffer)
324     (nnheader-init-server-buffer)))
325
326 (defsubst nntp-find-connection (buffer)
327   "Find the connection delivering to BUFFER."
328   (let ((alist nntp-connection-alist)
329         (buffer (if (stringp buffer) (get-buffer buffer) buffer))
330         process entry)
331     (while (and alist (setq entry (pop alist)))
332       (when (eq buffer (cadr entry))
333         (setq process (car entry)
334               alist nil)))
335     (when process
336       (if (memq (process-status process) '(open run))
337           process
338         (nntp-kill-buffer (process-buffer process))
339         (setq nntp-connection-alist (delq entry nntp-connection-alist))
340         nil))))
341
342 (defsubst nntp-find-connection-entry (buffer)
343   "Return the entry for the connection to BUFFER."
344   (assq (nntp-find-connection buffer) nntp-connection-alist))
345
346 (defun nntp-find-connection-buffer (buffer)
347   "Return the process connection buffer tied to BUFFER."
348   (let ((process (nntp-find-connection buffer)))
349     (when process
350       (process-buffer process))))
351
352 (defsubst nntp-retrieve-data (command address port buffer
353                                       &optional wait-for callback decode)
354   "Use COMMAND to retrieve data into BUFFER from PORT on ADDRESS."
355   (let ((process (or (nntp-find-connection buffer)
356                      (nntp-open-connection buffer))))
357     (if (not process)
358         (nnheader-report 'nntp "Couldn't open connection to %s" address)
359       (unless (or nntp-inhibit-erase nnheader-callback-function)
360         (save-excursion
361           (set-buffer (process-buffer process))
362           (erase-buffer)))
363       (condition-case err
364           (progn
365             (when command
366               (nntp-send-string process command))
367             (cond
368              ((eq callback 'ignore)
369               t)
370              ((and callback wait-for)
371               (nntp-async-wait process wait-for buffer decode callback)
372               t)
373              (wait-for
374               (nntp-wait-for process wait-for buffer decode))
375              (t t)))
376         (error
377          (nnheader-report 'nntp "Couldn't open connection to %s: %s"
378                           address err))
379         (quit
380          (message "Quit retrieving data from nntp")
381          (signal 'quit nil)
382          nil)))))
383
384 (defsubst nntp-send-command (wait-for &rest strings)
385   "Send STRINGS to server and wait until WAIT-FOR returns."
386   (when (and (not nnheader-callback-function)
387              (not nntp-inhibit-output))
388     (save-excursion
389       (set-buffer nntp-server-buffer)
390       (erase-buffer)))
391   (let* ((command (mapconcat 'identity strings " "))
392          (buffer (process-buffer (nntp-find-connection nntp-server-buffer)))
393          (pos (with-current-buffer buffer (point))))
394     (prog1
395         (nntp-retrieve-data command
396                             nntp-address nntp-port-number nntp-server-buffer
397                             wait-for nnheader-callback-function)
398       ;; If nothing to wait for, still remove possibly echo'ed commands
399       (unless wait-for
400         (nntp-accept-response)
401         (save-excursion
402           (set-buffer buffer)
403           (goto-char pos)
404           (if (looking-at (regexp-quote command))
405               (delete-region pos (progn (forward-line 1) (gnus-point-at-bol))))
406           )))
407     ))
408
409 (defun nntp-send-command-nodelete (wait-for &rest strings)
410   "Send STRINGS to server and wait until WAIT-FOR returns."
411   (let* ((command (mapconcat 'identity strings " "))
412          (buffer (process-buffer (nntp-find-connection nntp-server-buffer)))
413          (pos (with-current-buffer buffer (point))))
414     (prog1
415         (nntp-retrieve-data command
416                             nntp-address nntp-port-number nntp-server-buffer
417                             wait-for nnheader-callback-function)
418       ;; If nothing to wait for, still remove possibly echo'ed commands
419       (unless wait-for
420         (nntp-accept-response)
421         (save-excursion
422           (set-buffer buffer)
423           (goto-char pos)
424           (if (looking-at (regexp-quote command))
425               (delete-region pos (progn (forward-line 1) (gnus-point-at-bol))))
426           )))
427     ))
428
429 (defun nntp-send-command-and-decode (wait-for &rest strings)
430   "Send STRINGS to server and wait until WAIT-FOR returns."
431   (when (and (not nnheader-callback-function)
432              (not nntp-inhibit-output))
433     (save-excursion
434       (set-buffer nntp-server-buffer)
435       (erase-buffer)))
436   (let* ((command (mapconcat 'identity strings " "))
437          (process (nntp-find-connection nntp-server-buffer))
438          (buffer (and process (process-buffer process)))
439          (pos (and buffer (with-current-buffer buffer (point)))))
440     (if process
441         (prog1
442             (nntp-retrieve-data command
443                                 nntp-address nntp-port-number 
444                                 nntp-server-buffer
445                                 wait-for nnheader-callback-function t)
446           ;; If nothing to wait for, still remove possibly echo'ed commands
447           (unless wait-for
448             (nntp-accept-response)
449             (save-excursion
450           (set-buffer buffer)
451           (goto-char pos)
452           (if (looking-at (regexp-quote command))
453               (delete-region pos (progn (forward-line 1) (gnus-point-at-bol))))
454           )))
455       (nnheader-report 'nntp "Couldn't open connection to %s."
456                        nntp-address))))
457
458
459 (defun nntp-send-buffer (wait-for)
460   "Send the current buffer to server and wait until WAIT-FOR returns."
461   (when (and (not nnheader-callback-function)
462              (not nntp-inhibit-output))
463     (save-excursion
464       (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
465       (erase-buffer)))
466   (nntp-encode-text)
467   (mm-with-unibyte-current-buffer
468     ;; Some encoded unicode text contains character 0x80-0x9f e.g. Euro.
469     (process-send-region (nntp-find-connection nntp-server-buffer)
470                          (point-min) (point-max)))
471   (nntp-retrieve-data
472    nil nntp-address nntp-port-number nntp-server-buffer
473    wait-for nnheader-callback-function))
474
475 \f
476
477 ;;; Interface functions.
478
479 (nnoo-define-basics nntp)
480
481 (defsubst nntp-next-result-arrived-p ()
482   (cond
483    ;; A result that starts with a 2xx code is terminated by
484    ;; a line with only a "." on it.
485    ((eq (char-after) ?2)
486     (if (re-search-forward "\n\\.\r?\n" nil t)
487         t
488       nil))
489    ;; A result that starts with a 3xx or 4xx code is terminated
490    ;; by a newline.
491    ((looking-at "[34]")
492     (if (search-forward "\n" nil t)
493         t
494       nil))
495    ;; No result here.
496    (t
497     nil)))
498
499 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
500   "Retrieve the headers of ARTICLES."
501   (nntp-possibly-change-group group server)
502   (save-excursion
503     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
504     (erase-buffer)
505     (if (and (not gnus-nov-is-evil)
506              (not nntp-nov-is-evil)
507              (nntp-retrieve-headers-with-xover articles fetch-old))
508         ;; We successfully retrieved the headers via XOVER.
509         'nov
510       ;; XOVER didn't work, so we do it the hard, slow and inefficient
511       ;; way.
512       (let ((number (length articles))
513             (count 0)
514             (received 0)
515             (last-point (point-min))
516             (buf (nntp-find-connection-buffer nntp-server-buffer))
517             (nntp-inhibit-erase t)
518             article)
519         ;; Send HEAD commands.
520         (while (setq article (pop articles))
521           (nntp-send-command
522            nil
523            "HEAD" (if (numberp article)
524                       (int-to-string article)
525                     ;; `articles' is either a list of article numbers
526                     ;; or a list of article IDs.
527                     article))
528           (incf count)
529           ;; Every 400 requests we have to read the stream in
530           ;; order to avoid deadlocks.
531           (when (or (null articles)     ;All requests have been sent.
532                     (zerop (% count nntp-maximum-request)))
533             (nntp-accept-response)
534             (while (progn
535                      (set-buffer buf)
536                      (goto-char last-point)
537                      ;; Count replies.
538                      (while (nntp-next-result-arrived-p)
539                        (setq last-point (point))
540                        (incf received))
541                      (< received count))
542               ;; If number of headers is greater than 100, give
543               ;;  informative messages.
544               (and (numberp nntp-large-newsgroup)
545                    (> number nntp-large-newsgroup)
546                    (zerop (% received 20))
547                    (nnheader-message 6 "NNTP: Receiving headers... %d%%"
548                                      (/ (* received 100) number)))
549               (nntp-accept-response))))
550         (and (numberp nntp-large-newsgroup)
551              (> number nntp-large-newsgroup)
552              (nnheader-message 6 "NNTP: Receiving headers...done"))
553
554         ;; Now all of replies are received.  Fold continuation lines.
555         (nnheader-fold-continuation-lines)
556         ;; Remove all "\r"'s.
557         (nnheader-strip-cr)
558         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
559         'headers))))
560
561 (deffoo nntp-retrieve-groups (groups &optional server)
562   "Retrieve group info on GROUPS."
563   (nntp-possibly-change-group nil server)
564   (when (nntp-find-connection-buffer nntp-server-buffer)
565     (catch 'done
566       (save-excursion
567         ;; Erase nntp-server-buffer before nntp-inhibit-erase.
568         (set-buffer nntp-server-buffer)
569         (erase-buffer)
570         (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
571         ;; The first time this is run, this variable is `try'.  So we
572         ;; try.
573         (when (eq nntp-server-list-active-group 'try)
574           (nntp-try-list-active (car groups)))
575         (erase-buffer)
576         (let ((count 0)
577               (received 0)
578               (last-point (point-min))
579               (nntp-inhibit-erase t)
580               (buf (nntp-find-connection-buffer nntp-server-buffer))
581               (command (if nntp-server-list-active-group
582                            "LIST ACTIVE" "GROUP")))
583           (while groups
584             ;; Timeout may have killed the buffer.
585             (unless (gnus-buffer-live-p buf)
586               (nnheader-report 'nntp "Connection to %s is closed." server)
587               (throw 'done nil))
588             ;; Send the command to the server.
589             (nntp-send-command nil command (pop groups))
590             (incf count)
591             ;; Every 400 requests we have to read the stream in
592             ;; order to avoid deadlocks.
593             (when (or (null groups)     ;All requests have been sent.
594                       (zerop (% count nntp-maximum-request)))
595               (nntp-accept-response)
596               (while (and (gnus-buffer-live-p buf)
597                           (progn
598                             ;; Search `blue moon' in this file for the
599                             ;; reason why set-buffer here.
600                             (set-buffer buf)
601                             (goto-char last-point)
602                             ;; Count replies.
603                             (while (re-search-forward "^[0-9]" nil t)
604                               (incf received))
605                             (setq last-point (point))
606                             (< received count)))
607                 (nntp-accept-response))))
608
609           ;; Wait for the reply from the final command.
610           (unless (gnus-buffer-live-p buf)
611             (nnheader-report 'nntp "Connection to %s is closed." server)
612             (throw 'done nil))
613           (set-buffer buf)
614           (goto-char (point-max))
615           (re-search-backward "^[0-9]" nil t)
616           (when (looking-at "^[23]")
617             (while (and (gnus-buffer-live-p buf)
618                         (progn
619                           (set-buffer buf)
620                           (goto-char (point-max))
621                           (if (not nntp-server-list-active-group)
622                               (not (re-search-backward "\r?\n" (- (point) 3) t))
623                             (not (re-search-backward "^\\.\r?\n"
624                                                      (- (point) 4) t)))))
625               (nntp-accept-response)))
626
627           ;; Now all replies are received.  We remove CRs.
628           (unless (gnus-buffer-live-p buf)
629             (nnheader-report 'nntp "Connection to %s is closed." server)
630             (throw 'done nil))
631           (set-buffer buf)
632           (goto-char (point-min))
633           (while (search-forward "\r" nil t)
634             (replace-match "" t t))
635
636           (if (not nntp-server-list-active-group)
637               (progn
638                 (copy-to-buffer nntp-server-buffer (point-min) (point-max))
639                 'group)
640             ;; We have read active entries, so we just delete the
641             ;; superfluous gunk.
642             (goto-char (point-min))
643             (while (re-search-forward "^[.2-5]" nil t)
644               (delete-region (match-beginning 0)
645                              (progn (forward-line 1) (point))))
646             (copy-to-buffer nntp-server-buffer (point-min) (point-max))
647             'active))))))
648
649 (deffoo nntp-retrieve-articles (articles &optional group server)
650   (nntp-possibly-change-group group server)
651   (save-excursion
652     (let ((number (length articles))
653           (count 0)
654           (received 0)
655           (last-point (point-min))
656           (buf (nntp-find-connection-buffer nntp-server-buffer))
657           (nntp-inhibit-erase t)
658           (map (apply 'vector articles))
659           (point 1)
660           article)
661       (set-buffer buf)
662       (erase-buffer)
663       ;; Send ARTICLE command.
664       (while (setq article (pop articles))
665         (nntp-send-command
666          nil
667          "ARTICLE" (if (numberp article)
668                        (int-to-string article)
669                      ;; `articles' is either a list of article numbers
670                      ;; or a list of article IDs.
671                      article))
672         (incf count)
673         ;; Every 400 requests we have to read the stream in
674         ;; order to avoid deadlocks.
675         (when (or (null articles)       ;All requests have been sent.
676                   (zerop (% count nntp-maximum-request)))
677           (nntp-accept-response)
678           (while (progn
679                    (set-buffer buf)
680                    (goto-char last-point)
681                    ;; Count replies.
682                    (while (nntp-next-result-arrived-p)
683                      (aset map received (cons (aref map received) (point)))
684                      (setq last-point (point))
685                      (incf received))
686                    (< received count))
687             ;; If number of headers is greater than 100, give
688             ;;  informative messages.
689             (and (numberp nntp-large-newsgroup)
690                  (> number nntp-large-newsgroup)
691                  (zerop (% received 20))
692                  (nnheader-message 6 "NNTP: Receiving articles... %d%%"
693                                    (/ (* received 100) number)))
694             (nntp-accept-response))))
695       (and (numberp nntp-large-newsgroup)
696            (> number nntp-large-newsgroup)
697            (nnheader-message 6 "NNTP: Receiving articles...done"))
698
699       ;; Now we have all the responses.  We go through the results,
700       ;; wash it and copy it over to the server buffer.
701       (set-buffer nntp-server-buffer)
702       (erase-buffer)
703       (setq last-point (point-min))
704       (mapcar
705        (lambda (entry)
706          (narrow-to-region
707           (setq point (goto-char (point-max)))
708           (progn
709             (insert-buffer-substring buf last-point (cdr entry))
710             (point-max)))
711          (setq last-point (cdr entry))
712          (nntp-decode-text)
713          (widen)
714          (cons (car entry) point))
715        map))))
716
717 (defun nntp-try-list-active (group)
718   (nntp-list-active-group group)
719   (save-excursion
720     (set-buffer nntp-server-buffer)
721     (goto-char (point-min))
722     (cond ((or (eobp)
723                (looking-at "5[0-9]+"))
724            (setq nntp-server-list-active-group nil))
725           (t
726            (setq nntp-server-list-active-group t)))))
727
728 (deffoo nntp-list-active-group (group &optional server)
729   "Return the active info on GROUP (which can be a regexp)."
730   (nntp-possibly-change-group nil server)
731   (nntp-send-command "^\\.*\r?\n" "LIST ACTIVE" group))
732
733 (deffoo nntp-request-group-articles (group &optional server)
734   "Return the list of existing articles in GROUP."
735   (nntp-possibly-change-group nil server)
736   (nntp-send-command "^\\.*\r?\n" "LISTGROUP" group))
737
738 (deffoo nntp-request-article (article &optional group server buffer command)
739   (nntp-possibly-change-group group server)
740   (when (nntp-send-command-and-decode
741          "\r?\n\\.\r?\n" "ARTICLE"
742          (if (numberp article) (int-to-string article) article))
743     (if (and buffer
744              (not (equal buffer nntp-server-buffer)))
745         (save-excursion
746           (set-buffer nntp-server-buffer)
747           (copy-to-buffer buffer (point-min) (point-max))
748           (nntp-find-group-and-number group))
749       (nntp-find-group-and-number group))))
750
751 (deffoo nntp-request-head (article &optional group server)
752   (nntp-possibly-change-group group server)
753   (when (nntp-send-command
754          "\r?\n\\.\r?\n" "HEAD"
755          (if (numberp article) (int-to-string article) article))
756     (prog1
757         (nntp-find-group-and-number group)
758       (nntp-decode-text))))
759
760 (deffoo nntp-request-body (article &optional group server)
761   (nntp-possibly-change-group group server)
762   (nntp-send-command-and-decode
763    "\r?\n\\.\r?\n" "BODY"
764    (if (numberp article) (int-to-string article) article)))
765
766 (deffoo nntp-request-group (group &optional server dont-check)
767   (nntp-possibly-change-group nil server)
768   (when (nntp-send-command "^[245].*\n" "GROUP" group)
769     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
770       (setcar (cddr entry) group))))
771
772 (deffoo nntp-close-group (group &optional server)
773   t)
774
775 (deffoo nntp-server-opened (&optional server)
776   "Say whether a connection to SERVER has been opened."
777   (and (nnoo-current-server-p 'nntp server)
778        nntp-server-buffer
779        (gnus-buffer-live-p nntp-server-buffer)
780        (nntp-find-connection nntp-server-buffer)))
781
782 (deffoo nntp-open-server (server &optional defs connectionless)
783   (nnheader-init-server-buffer)
784   (if (nntp-server-opened server)
785       t
786     (when (or (stringp (car defs))
787               (numberp (car defs)))
788       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
789     (unless (assq 'nntp-address defs)
790       (setq defs (append defs (list (list 'nntp-address server)))))
791     (nnoo-change-server 'nntp server defs)
792     (unless connectionless
793       (or (nntp-find-connection nntp-server-buffer)
794           (nntp-open-connection nntp-server-buffer)))))
795
796 (deffoo nntp-close-server (&optional server)
797   (nntp-possibly-change-group nil server t)
798   (let ((process (nntp-find-connection nntp-server-buffer)))
799     (while process
800       (when (memq (process-status process) '(open run))
801         (ignore-errors
802           (nntp-send-string process "QUIT")
803           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
804             ;; Ok, this is evil, but when using telnet and stuff
805             ;; as the connection method, it's important that the
806             ;; QUIT command actually is sent out before we kill
807             ;; the process.
808             (sleep-for 1))))
809       (nntp-kill-buffer (process-buffer process))
810       (setq process (car (pop nntp-connection-alist))))
811     (nnoo-close-server 'nntp)))
812
813 (deffoo nntp-request-close ()
814   (let (process)
815     (while (setq process (pop nntp-connection-list))
816       (when (memq (process-status process) '(open run))
817         (ignore-errors
818           (nntp-send-string process "QUIT")
819           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
820             ;; Ok, this is evil, but when using telnet and stuff
821             ;; as the connection method, it's important that the
822             ;; QUIT command actually is sent out before we kill
823             ;; the process.
824             (sleep-for 1))))
825       (nntp-kill-buffer (process-buffer process)))))
826
827 (deffoo nntp-request-list (&optional server)
828   (nntp-possibly-change-group nil server)
829   (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST"))
830
831 (deffoo nntp-request-list-newsgroups (&optional server)
832   (nntp-possibly-change-group nil server)
833   (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS"))
834
835 (deffoo nntp-request-newgroups (date &optional server)
836   (nntp-possibly-change-group nil server)
837   (save-excursion
838     (set-buffer nntp-server-buffer)
839     (let* ((time (date-to-time date))
840            (ls (- (cadr time) (nth 8 (decode-time time)))))
841       (cond ((< ls 0)
842              (setcar time (1- (car time)))
843              (setcar (cdr time) (+ ls 65536)))
844             ((>= ls 65536)
845              (setcar time (1+ (car time)))
846              (setcar (cdr time) (- ls 65536)))
847             (t
848              (setcar (cdr time) ls)))
849       (prog1
850           (nntp-send-command
851            "^\\.\r?\n" "NEWGROUPS"
852            (format-time-string "%y%m%d %H%M%S" time)
853            "GMT")
854         (nntp-decode-text)))))
855
856 (deffoo nntp-request-post (&optional server)
857   (nntp-possibly-change-group nil server)
858   (when (nntp-send-command "^[23].*\r?\n" "POST")
859     (let ((response (with-current-buffer nntp-server-buffer
860                       nntp-process-response))
861           server-id)
862       (when (and response
863                  (string-match "^[23].*\\(<[^\t\n @<>]+@[^\t\n @<>]+>\\)"
864                                response))
865         (setq server-id (match-string 1 response))
866         (narrow-to-region (goto-char (point-min))
867                           (if (search-forward "\n\n" nil t)
868                               (1- (point))
869                             (point-max)))
870         (unless (mail-fetch-field "Message-ID")
871           (goto-char (point-min))
872           (insert "Message-ID: " server-id "\n"))
873         (widen))
874       (run-hooks 'nntp-prepare-post-hook)
875       (nntp-send-buffer "^[23].*\n"))))
876
877 (deffoo nntp-request-type (group article)
878   'news)
879
880 (deffoo nntp-asynchronous-p ()
881   t)
882
883 ;;; Hooky functions.
884
885 (defun nntp-send-mode-reader ()
886   "Send the MODE READER command to the nntp server.
887 This function is supposed to be called from `nntp-server-opened-hook'.
888 It will make innd servers spawn an nnrpd process to allow actual article
889 reading."
890   (nntp-send-command "^.*\n" "MODE READER"))
891
892 (defun nntp-send-authinfo (&optional send-if-force)
893   "Send the AUTHINFO to the nntp server.
894 It will look in the \"~/.authinfo\" file for matching entries.  If
895 nothing suitable is found there, it will prompt for a user name
896 and a password.
897
898 If SEND-IF-FORCE, only send authinfo to the server if the
899 .authinfo file has the FORCE token."
900   (let* ((list (gnus-parse-netrc nntp-authinfo-file))
901          (alist (gnus-netrc-machine list nntp-address "nntp"))
902          (force (gnus-netrc-get alist "force"))
903          (user (or (gnus-netrc-get alist "login") nntp-authinfo-user))
904          (passwd (gnus-netrc-get alist "password")))
905     (when (or (not send-if-force)
906               force)
907       (unless user
908         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
909               nntp-authinfo-user user))
910       (unless (member user '(nil ""))
911         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
912         (when t                         ;???Should check if AUTHINFO succeeded
913           (nntp-send-command
914            "^2.*\r?\n" "AUTHINFO PASS"
915            (or passwd
916                nntp-authinfo-password
917                (setq nntp-authinfo-password
918                      (mail-source-read-passwd
919                       (format "NNTP (%s@%s) password: "
920                               user nntp-address))))))))))
921
922 (defun nntp-send-nosy-authinfo ()
923   "Send the AUTHINFO to the nntp server."
924   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
925     (unless (member user '(nil ""))
926       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
927       (when t                           ;???Should check if AUTHINFO succeeded
928         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
929                            (mail-source-read-passwd "NNTP (%s@%s) password: "
930                                                     user nntp-address))))))
931
932 (defun nntp-send-authinfo-from-file ()
933   "Send the AUTHINFO to the nntp server.
934
935 The authinfo login name is taken from the user's login name and the
936 password contained in '~/.nntp-authinfo'."
937   (when (file-exists-p "~/.nntp-authinfo")
938     (with-temp-buffer
939       (insert-file-contents "~/.nntp-authinfo")
940       (goto-char (point-min))
941       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
942       (nntp-send-command
943        "^2.*\r?\n" "AUTHINFO PASS"
944        (buffer-substring (point) (progn (end-of-line) (point)))))))
945
946 ;;; Internal functions.
947
948 (defun nntp-handle-authinfo (process)
949   "Take care of an authinfo response from the server."
950   (let ((last nntp-last-command))
951     (funcall nntp-authinfo-function)
952     ;; We have to re-send the function that was interrupted by
953     ;; the authinfo request.
954     (save-excursion
955       (set-buffer nntp-server-buffer)
956       (erase-buffer))
957     (nntp-send-string process last)))
958
959 (defun nntp-make-process-buffer (buffer)
960   "Create a new, fresh buffer usable for nntp process connections."
961   (save-excursion
962     (set-buffer
963      (generate-new-buffer
964       (format " *server %s %s %s*"
965               nntp-address nntp-port-number
966               (gnus-buffer-exists-p buffer))))
967     (mm-enable-multibyte)
968     (set (make-local-variable 'after-change-functions) nil)
969     (set (make-local-variable 'nntp-process-wait-for) nil)
970     (set (make-local-variable 'nntp-process-callback) nil)
971     (set (make-local-variable 'nntp-process-to-buffer) nil)
972     (set (make-local-variable 'nntp-process-start-point) nil)
973     (set (make-local-variable 'nntp-process-decode) nil)
974     (current-buffer)))
975
976 (defun nntp-open-connection (buffer)
977   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
978   (run-hooks 'nntp-prepare-server-hook)
979   (let* ((pbuffer (nntp-make-process-buffer buffer))
980          (timer
981           (and nntp-connection-timeout
982                (nnheader-run-at-time
983                 nntp-connection-timeout nil
984                 `(lambda ()
985                    (nntp-kill-buffer ,pbuffer)))))
986          (process
987           (condition-case ()
988               (let ((coding-system-for-read nntp-coding-system-for-read)
989                     (coding-system-for-write nntp-coding-system-for-write))
990                 (funcall nntp-open-connection-function pbuffer))
991             (error nil)
992             (quit
993              (message "Quit opening connection")
994              (nntp-kill-buffer pbuffer)
995              (signal 'quit nil)
996              nil))))
997     (when timer
998       (nnheader-cancel-timer timer))
999     (unless process
1000       (nntp-kill-buffer pbuffer))
1001     (when (and (buffer-name pbuffer)
1002                process)
1003       (process-kill-without-query process)
1004       (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
1005                (memq (process-status process) '(open run)))
1006           (prog1
1007               (caar (push (list process buffer nil) nntp-connection-alist))
1008             (push process nntp-connection-list)
1009             (save-excursion
1010               (set-buffer pbuffer)
1011               (nntp-read-server-type)
1012               (erase-buffer)
1013               (set-buffer nntp-server-buffer)
1014               (let ((nnheader-callback-function nil))
1015                 (run-hooks 'nntp-server-opened-hook)
1016                 (nntp-send-authinfo t))))
1017         (nntp-kill-buffer (process-buffer process))
1018         nil))))
1019
1020 (defun nntp-open-network-stream (buffer)
1021   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
1022
1023 (defun nntp-open-ssl-stream (buffer)
1024   (let ((proc (open-ssl-stream "nntpd" buffer nntp-address nntp-port-number)))
1025     (save-excursion
1026       (set-buffer buffer)
1027       (nntp-wait-for-string "^\r*20[01]")
1028       (beginning-of-line)
1029       (delete-region (point-min) (point))
1030       proc)))
1031
1032 (defun nntp-read-server-type ()
1033   "Find out what the name of the server we have connected to is."
1034   ;; Wait for the status string to arrive.
1035   (setq nntp-server-type (buffer-string))
1036   (let ((alist nntp-server-action-alist)
1037         (case-fold-search t)
1038         entry)
1039     ;; Run server-specific commands.
1040     (while alist
1041       (setq entry (pop alist))
1042       (when (string-match (car entry) nntp-server-type)
1043         (if (and (listp (cadr entry))
1044                  (not (eq 'lambda (caadr entry))))
1045             (eval (cadr entry))
1046           (funcall (cadr entry)))))))
1047
1048 (defun nntp-async-wait (process wait-for buffer decode callback)
1049   (save-excursion
1050     (set-buffer (process-buffer process))
1051     (unless nntp-inside-change-function
1052       (erase-buffer))
1053     (setq nntp-process-wait-for wait-for
1054           nntp-process-to-buffer buffer
1055           nntp-process-decode decode
1056           nntp-process-callback callback
1057           nntp-process-start-point (point-max))
1058     (setq after-change-functions '(nntp-after-change-function))
1059     (if nntp-async-needs-kluge
1060         (nntp-async-kluge process))))
1061
1062 (defun nntp-async-kluge (process)
1063   ;; emacs 20.3 bug: process output with encoding 'binary
1064   ;; doesn't trigger after-change-functions.
1065   (unless nntp-async-timer
1066     (setq nntp-async-timer
1067           (nnheader-run-at-time 1 1 'nntp-async-timer-handler)))
1068   (add-to-list 'nntp-async-process-list process))
1069
1070 (defun nntp-async-timer-handler ()
1071   (mapcar
1072    (lambda (proc)
1073      (if (memq (process-status proc) '(open run))
1074          (nntp-async-trigger proc)
1075        (nntp-async-stop proc)))
1076    nntp-async-process-list))
1077
1078 (defun nntp-async-stop (proc)
1079   (setq nntp-async-process-list (delq proc nntp-async-process-list))
1080   (when (and nntp-async-timer (not nntp-async-process-list))
1081     (nnheader-cancel-timer nntp-async-timer)
1082     (setq nntp-async-timer nil)))
1083
1084 (defun nntp-after-change-function (beg end len)
1085   (unwind-protect
1086       ;; we only care about insertions at eob
1087       (when (and (eq 0 len) (eq (point-max) end))
1088         (save-match-data
1089           (let ((proc (get-buffer-process (current-buffer))))
1090             (when proc
1091               (nntp-async-trigger proc)))))
1092     ;; any throw from after-change-functions will leave it
1093     ;; set to nil.  so we reset it here, if necessary.
1094     (when quit-flag
1095       (setq after-change-functions '(nntp-after-change-function)))))
1096
1097 (defun nntp-async-trigger (process)
1098   (save-excursion
1099     (set-buffer (process-buffer process))
1100     (when nntp-process-callback
1101       ;; do we have an error message?
1102       (goto-char nntp-process-start-point)
1103       (if (memq (following-char) '(?4 ?5))
1104           ;; wants credentials?
1105           (if (looking-at "480")
1106               (nntp-handle-authinfo process)
1107             ;; report error message.
1108             (nntp-snarf-error-message)
1109             (nntp-do-callback nil))
1110
1111         ;; got what we expect?
1112         (goto-char (point-max))
1113         (when (re-search-backward
1114                nntp-process-wait-for nntp-process-start-point t)
1115           (let ((response (match-string 0)))
1116             (with-current-buffer nntp-server-buffer
1117               (setq nntp-process-response response)))
1118           (nntp-async-stop process)
1119           ;; convert it.
1120           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1121             (let ((buf (current-buffer))
1122                   (start nntp-process-start-point)
1123                   (decode nntp-process-decode))
1124               (save-excursion
1125                 (set-buffer nntp-process-to-buffer)
1126                 (goto-char (point-max))
1127                 (save-restriction
1128                   (narrow-to-region (point) (point))
1129                   (insert-buffer-substring buf start)
1130                   (when decode
1131                     (nntp-decode-text))))))
1132           ;; report it.
1133           (goto-char (point-max))
1134           (nntp-do-callback
1135            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1136
1137 (defun nntp-do-callback (arg)
1138   (let ((callback nntp-process-callback)
1139         (nntp-inside-change-function t))
1140     (setq nntp-process-callback nil)
1141     (funcall callback arg)))
1142
1143 (defun nntp-snarf-error-message ()
1144   "Save the error message in the current buffer."
1145   (let ((message (buffer-string)))
1146     (while (string-match "[\r\n]+" message)
1147       (setq message (replace-match " " t t message)))
1148     (nnheader-report 'nntp message)
1149     message))
1150
1151 (defun nntp-accept-process-output (process &optional timeout)
1152   "Wait for output from PROCESS and message some dots."
1153   (save-excursion
1154     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1155                     nntp-server-buffer))
1156     (let ((len (/ (point-max) 1024))
1157           message-log-max)
1158       (unless (< len 10)
1159         (setq nntp-have-messaged t)
1160         (nnheader-message 7 "nntp read: %dk" len)))
1161     (accept-process-output process (or timeout 1))))
1162
1163 (defun nntp-accept-response ()
1164   "Wait for output from the process that outputs to BUFFER."
1165   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1166
1167 (defun nntp-possibly-change-group (group server &optional connectionless)
1168   (let ((nnheader-callback-function nil))
1169     (when server
1170       (or (nntp-server-opened server)
1171           (nntp-open-server server nil connectionless)))
1172
1173     (unless connectionless
1174       (or (nntp-find-connection nntp-server-buffer)
1175           (nntp-open-connection nntp-server-buffer))))
1176
1177   (when group
1178     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1179       (when (not (equal group (caddr entry)))
1180         (save-excursion
1181           (set-buffer (process-buffer (car entry)))
1182           (erase-buffer)
1183           (nntp-send-command "^[245].*\n" "GROUP" group)
1184           (setcar (cddr entry) group)
1185           (erase-buffer)
1186           (save-excursion
1187             (set-buffer nntp-server-buffer)
1188             (erase-buffer)))))))
1189
1190 (defun nntp-decode-text (&optional cr-only)
1191   "Decode the text in the current buffer."
1192   (goto-char (point-min))
1193   (while (search-forward "\r" nil t)
1194     (delete-char -1))
1195   (unless cr-only
1196     ;; Remove trailing ".\n" end-of-transfer marker.
1197     (goto-char (point-max))
1198     (forward-line -1)
1199     (when (looking-at ".\n")
1200       (delete-char 2))
1201     ;; Delete status line.
1202     (goto-char (point-min))
1203     (while (looking-at "[1-5][0-9][0-9] .*\n")
1204       ;; For some unknown reason, there is more than one status line.
1205       (delete-region (point) (progn (forward-line 1) (point))))
1206     ;; Remove "." -> ".." encoding.
1207     (while (search-forward "\n.." nil t)
1208       (delete-char -1))))
1209
1210 (defun nntp-encode-text ()
1211   "Encode the text in the current buffer."
1212   (save-excursion
1213     ;; Replace "." at beginning of line with "..".
1214     (goto-char (point-min))
1215     (while (re-search-forward "^\\." nil t)
1216       (insert "."))
1217     (goto-char (point-max))
1218     ;; Insert newline at the end of the buffer.
1219     (unless (bolp)
1220       (insert "\n"))
1221     ;; Insert `.' at end of buffer (end of text mark).
1222     (goto-char (point-max))
1223     (insert ".\n")
1224     (goto-char (point-min))
1225     (while (not (eobp))
1226       (end-of-line)
1227       (delete-char 1)
1228       (insert nntp-end-of-line))))
1229
1230 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1231   (set-buffer nntp-server-buffer)
1232   (erase-buffer)
1233   (cond
1234
1235    ;; This server does not talk NOV.
1236    ((not nntp-server-xover)
1237     nil)
1238
1239    ;; We don't care about gaps.
1240    ((or (not nntp-nov-gap)
1241         fetch-old)
1242     (nntp-send-xover-command
1243      (if fetch-old
1244          (if (numberp fetch-old)
1245              (max 1 (- (car articles) fetch-old))
1246            1)
1247        (car articles))
1248      (car (last articles)) 'wait)
1249
1250     (goto-char (point-min))
1251     (when (looking-at "[1-5][0-9][0-9] .*\n")
1252       (delete-region (point) (progn (forward-line 1) (point))))
1253     (while (search-forward "\r" nil t)
1254       (replace-match "" t t))
1255     (goto-char (point-max))
1256     (forward-line -1)
1257     (when (looking-at "\\.")
1258       (delete-region (point) (progn (forward-line 1) (point)))))
1259
1260    ;; We do it the hard way.  For each gap, an XOVER command is sent
1261    ;; to the server.  We do not wait for a reply from the server, we
1262    ;; just send them off as fast as we can.  That means that we have
1263    ;; to count the number of responses we get back to find out when we
1264    ;; have gotten all we asked for.
1265    ((numberp nntp-nov-gap)
1266     (let ((count 0)
1267           (received 0)
1268           last-point
1269           in-process-buffer-p
1270           (buf nntp-server-buffer)
1271           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1272           first)
1273       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1274       ;; that means that the server does not understand XOVER, but we
1275       ;; won't know that until we try.
1276       (while (and nntp-server-xover articles)
1277         (setq first (car articles))
1278         ;; Search forward until we find a gap, or until we run out of
1279         ;; articles.
1280         (while (and (cdr articles)
1281                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1282           (setq articles (cdr articles)))
1283
1284         (setq in-process-buffer-p (stringp nntp-server-xover))
1285         (nntp-send-xover-command first (car articles))
1286         (setq articles (cdr articles))
1287
1288         (when (and nntp-server-xover in-process-buffer-p)
1289           ;; Don't count tried request.
1290           (setq count (1+ count))
1291
1292           ;; Every 400 requests we have to read the stream in
1293           ;; order to avoid deadlocks.
1294           (when (or (null articles)     ;All requests have been sent.
1295                     (zerop (% count nntp-maximum-request)))
1296
1297             (nntp-accept-response)
1298             ;; On some Emacs versions the preceding function has a
1299             ;; tendency to change the buffer.  Perhaps.  It's quite
1300             ;; difficult to reproduce, because it only seems to happen
1301             ;; once in a blue moon.
1302             (set-buffer process-buffer)
1303             (while (progn
1304                      (goto-char (or last-point (point-min)))
1305                      ;; Count replies.
1306                      (while (re-search-forward "^[0-9][0-9][0-9] .*\n" nil t)
1307                        (incf received))
1308                      (setq last-point (point))
1309                      (< received count))
1310               (nntp-accept-response)
1311               (set-buffer process-buffer))
1312             (set-buffer buf))))
1313
1314       (when nntp-server-xover
1315         (when in-process-buffer-p
1316           (set-buffer process-buffer)
1317           ;; Wait for the reply from the final command.
1318           (goto-char (point-max))
1319           (while (not (re-search-backward "^[0-9][0-9][0-9] " nil t))
1320             (nntp-accept-response)
1321             (set-buffer process-buffer)
1322             (goto-char (point-max)))
1323           (when (looking-at "^[23]")
1324             (while (progn
1325                      (goto-char (point-max))
1326                      (forward-line -1)
1327                      (not (looking-at "^\\.\r?\n")))
1328               (nntp-accept-response)
1329               (set-buffer process-buffer)))
1330           (set-buffer buf)
1331           (goto-char (point-max))
1332           (insert-buffer-substring process-buffer)
1333           (set-buffer process-buffer)
1334           (erase-buffer)
1335           (set-buffer buf))
1336
1337         ;; We remove any "." lines and status lines.
1338         (goto-char (point-min))
1339         (while (search-forward "\r" nil t)
1340           (delete-char -1))
1341         (goto-char (point-min))
1342         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1343         t))))
1344
1345   nntp-server-xover)
1346
1347 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1348   "Send the XOVER command to the server."
1349   (let ((range (format "%d-%d" beg end))
1350         (nntp-inhibit-erase t))
1351     (if (stringp nntp-server-xover)
1352         ;; If `nntp-server-xover' is a string, then we just send this
1353         ;; command.
1354         (if wait-for-reply
1355             (nntp-send-command-nodelete
1356              "\r?\n\\.\r?\n" nntp-server-xover range)
1357           ;; We do not wait for the reply.
1358           (nntp-send-command-nodelete nil nntp-server-xover range))
1359       (let ((commands nntp-xover-commands))
1360         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1361         ;; We try them all until we get at positive response.
1362         (while (and commands (eq nntp-server-xover 'try))
1363           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1364           (save-excursion
1365             (set-buffer nntp-server-buffer)
1366             (goto-char (point-min))
1367             (and (looking-at "[23]")    ; No error message.
1368                  ;; We also have to look at the lines.  Some buggy
1369                  ;; servers give back simple lines with just the
1370                  ;; article number.  How... helpful.
1371                  (progn
1372                    (forward-line 1)
1373                    (looking-at "[0-9]+\t...")) ; More text after number.
1374                  (setq nntp-server-xover (car commands))))
1375           (setq commands (cdr commands)))
1376         ;; If none of the commands worked, we disable XOVER.
1377         (when (eq nntp-server-xover 'try)
1378           (save-excursion
1379             (set-buffer nntp-server-buffer)
1380             (erase-buffer)
1381             (setq nntp-server-xover nil)))
1382         nntp-server-xover))))
1383
1384 (defun nntp-find-group-and-number (&optional group)
1385   (save-excursion
1386     (save-restriction
1387       (set-buffer nntp-server-buffer)
1388       (narrow-to-region (goto-char (point-min))
1389                         (or (search-forward "\n\n" nil t) (point-max)))
1390       (goto-char (point-min))
1391       ;; We first find the number by looking at the status line.
1392       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1393                          (string-to-int
1394                           (buffer-substring (match-beginning 1)
1395                                             (match-end 1)))))
1396             newsgroups xref)
1397         (and number (zerop number) (setq number nil))
1398         (if number
1399             ;; Then we find the group name.
1400             (setq group
1401                   (cond
1402                    ;; If there is only one group in the Newsgroups
1403                    ;; header, then it seems quite likely that this
1404                    ;; article comes from that group, I'd say.
1405                    ((and (setq newsgroups 
1406                                (mail-fetch-field "newsgroups"))
1407                          (not (string-match "," newsgroups)))
1408                     newsgroups)
1409                    ;; If there is more than one group in the
1410                    ;; Newsgroups header, then the Xref header should
1411                    ;; be filled out.  We hazard a guess that the group
1412                    ;; that has this article number in the Xref header
1413                    ;; is the one we are looking for.  This might very
1414                    ;; well be wrong if this article happens to have
1415                    ;; the same number in several groups, but that's
1416                    ;; life.
1417                    ((and (setq xref (mail-fetch-field "xref"))
1418                          number
1419                          (string-match 
1420                           (format "\\([^ :]+\\):%d" number) xref))
1421                     (match-string 1 xref))
1422                    (t "")))
1423           (cond
1424            ((and (setq xref (mail-fetch-field "xref"))
1425                  (string-match 
1426                   (if group
1427                       (concat "\\(" (regexp-quote group) "\\):\\([0-9]+\\)")
1428                     "\\([^ :]+\\):\\([0-9]+\\)")
1429                   xref))
1430             (setq group (match-string 1 xref)
1431                   number (string-to-int (match-string 2 xref))))
1432            ((and (setq newsgroups 
1433                        (mail-fetch-field "newsgroups"))
1434                  (not (string-match "," newsgroups)))
1435             (setq group newsgroups))
1436            (group)
1437            (t (setq group ""))))
1438         (when (string-match "\r" group)
1439           (setq group (substring group 0 (match-beginning 0))))
1440         (cons group number)))))
1441
1442 (defun nntp-wait-for-string (regexp)
1443   "Wait until string arrives in the buffer."
1444   (let ((buf (current-buffer)))
1445     (goto-char (point-min))
1446     (while (not (re-search-forward regexp nil t))
1447       (accept-process-output (nntp-find-connection nntp-server-buffer))
1448       (set-buffer buf)
1449       (goto-char (point-min)))))
1450
1451
1452 ;; ==========================================================================
1453 ;; Obsolete nntp-open-* connection methods -- drv
1454 ;; ==========================================================================
1455
1456 (defvoo nntp-open-telnet-envuser nil
1457   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1458
1459 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1460   "*Regular expression to match the shell prompt on the remote machine.")
1461
1462 (defvoo nntp-rlogin-program "rsh"
1463   "*Program used to log in on remote machines.
1464 The default is \"rsh\", but \"ssh\" is a popular alternative.")
1465
1466 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1467   "*Parameters to `nntp-open-rlogin'.
1468 That function may be used as `nntp-open-connection-function'.  In that
1469 case, this list will be used as the parameter list given to rsh.")
1470
1471 (defvoo nntp-rlogin-user-name nil
1472   "*User name on remote system when using the rlogin connect method.")
1473
1474 (defvoo nntp-telnet-parameters
1475     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1476   "*Parameters to `nntp-open-telnet'.
1477 That function may be used as `nntp-open-connection-function'.  In that
1478 case, this list will be executed as a command after logging in
1479 via telnet.")
1480
1481 (defvoo nntp-telnet-user-name nil
1482   "User name to log in via telnet with.")
1483
1484 (defvoo nntp-telnet-passwd nil
1485   "Password to use to log in via telnet with.")
1486
1487 (defun nntp-open-telnet (buffer)
1488   (save-excursion
1489     (set-buffer buffer)
1490     (erase-buffer)
1491     (let ((proc (apply
1492                  'start-process
1493                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1494           (case-fold-search t))
1495       (when (memq (process-status proc) '(open run))
1496         (nntp-wait-for-string "^r?telnet")
1497         (process-send-string proc "set escape \^X\n")
1498         (cond
1499          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1500           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1501                                             nntp-address "\n")))
1502          (t
1503           (process-send-string proc (concat "open " nntp-address "\n"))))
1504         (cond
1505          ((not nntp-open-telnet-envuser)
1506           (nntp-wait-for-string "^\r*.?login:")
1507           (process-send-string
1508            proc (concat
1509                  (or nntp-telnet-user-name
1510                      (setq nntp-telnet-user-name (read-string "login: ")))
1511                  "\n"))))
1512         (nntp-wait-for-string "^\r*.?password:")
1513         (process-send-string
1514          proc (concat
1515                (or nntp-telnet-passwd
1516                    (setq nntp-telnet-passwd
1517                          (mail-source-read-passwd "Password: ")))
1518                "\n"))
1519         (nntp-wait-for-string nntp-telnet-shell-prompt)
1520         (process-send-string
1521          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1522         (nntp-wait-for-string "^\r*20[01]")
1523         (beginning-of-line)
1524         (delete-region (point-min) (point))
1525         (process-send-string proc "\^]")
1526         (nntp-wait-for-string "^r?telnet")
1527         (process-send-string proc "mode character\n")
1528         (accept-process-output proc 1)
1529         (sit-for 1)
1530         (goto-char (point-min))
1531         (forward-line 1)
1532         (delete-region (point) (point-max)))
1533       proc)))
1534
1535 (defun nntp-open-rlogin (buffer)
1536   "Open a connection to SERVER using rsh."
1537   (let ((proc (if nntp-rlogin-user-name
1538                   (apply 'start-process
1539                          "nntpd" buffer nntp-rlogin-program
1540                          nntp-address "-l" nntp-rlogin-user-name
1541                          nntp-rlogin-parameters)
1542                 (apply 'start-process
1543                        "nntpd" buffer nntp-rlogin-program nntp-address
1544                        nntp-rlogin-parameters))))
1545     (save-excursion
1546       (set-buffer buffer)
1547       (nntp-wait-for-string "^\r*20[01]")
1548       (beginning-of-line)
1549       (delete-region (point-min) (point))
1550       proc)))
1551
1552
1553 ;; ==========================================================================
1554 ;; Replacements for the nntp-open-* functions -- drv
1555 ;; ==========================================================================
1556
1557 (defun nntp-open-telnet-stream (buffer)
1558   "Open a nntp connection by telnet'ing the news server.
1559
1560 Please refer to the following variables to customize the connection:
1561 - `nntp-pre-command',
1562 - `nntp-telnet-command',
1563 - `nntp-telnet-switches',
1564 - `nntp-address',
1565 - `nntp-port-number',
1566 - `nntp-end-of-line'."
1567   (let ((command `(,nntp-telnet-command
1568                    ,@nntp-telnet-switches
1569                    ,nntp-address ,nntp-port-number))
1570         proc)
1571     (and nntp-pre-command
1572          (push nntp-pre-command command))
1573     (setq proc (apply 'start-process "nntpd" buffer command))
1574     (save-excursion
1575       (set-buffer buffer)
1576       (nntp-wait-for-string "^\r*20[01]")
1577       (beginning-of-line)
1578       (delete-region (point-min) (point))
1579       proc)))
1580
1581 (defun nntp-open-via-rlogin-and-telnet (buffer)
1582   "Open a connection to an nntp server through an intermediate host.
1583 First rlogin to the remote host, and then telnet the real news server
1584 from there.
1585
1586 Please refer to the following variables to customize the connection:
1587 - `nntp-pre-command',
1588 - `nntp-via-rlogin-command',
1589 - `nntp-via-user-name',
1590 - `nntp-via-address',
1591 - `nntp-telnet-command',
1592 - `nntp-telnet-switches',
1593 - `nntp-address',
1594 - `nntp-port-number',
1595 - `nntp-end-of-line'."
1596   (let ((command `(,nntp-via-address
1597                    ,nntp-telnet-command
1598                    ,@nntp-telnet-switches
1599                    ,nntp-address ,nntp-port-number))
1600         proc)
1601     (and nntp-via-user-name
1602          (setq command `("-l" ,nntp-via-user-name ,@command)))
1603     (push nntp-via-rlogin-command command)
1604     (and nntp-pre-command
1605          (push nntp-pre-command command))
1606     (setq proc (apply 'start-process "nntpd" buffer command))
1607     (save-excursion
1608       (set-buffer buffer)
1609       (nntp-wait-for-string "^\r*20[01]")
1610       (beginning-of-line)
1611       (delete-region (point-min) (point))
1612       proc)))
1613
1614 (defun nntp-open-via-telnet-and-telnet (buffer)
1615   "Open a connection to an nntp server through an intermediate host.
1616 First telnet the remote host, and then telnet the real news server
1617 from there.
1618
1619 Please refer to the following variables to customize the connection:
1620 - `nntp-pre-command',
1621 - `nntp-via-telnet-command',
1622 - `nntp-via-telnet-switches',
1623 - `nntp-via-address',
1624 - `nntp-via-envuser',
1625 - `nntp-via-user-name',
1626 - `nntp-via-user-password',
1627 - `nntp-via-shell-prompt',
1628 - `nntp-telnet-command',
1629 - `nntp-telnet-switches',
1630 - `nntp-address',
1631 - `nntp-port-number',
1632 - `nntp-end-of-line'."
1633   (save-excursion
1634     (set-buffer buffer)
1635     (erase-buffer)
1636     (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
1637           (case-fold-search t)
1638           proc)
1639       (and nntp-pre-command (push nntp-pre-command command))
1640       (setq proc (apply 'start-process "nntpd" buffer command))
1641       (when (memq (process-status proc) '(open run))
1642         (nntp-wait-for-string "^r?telnet")
1643         (process-send-string proc "set escape \^X\n")
1644         (cond
1645          ((and nntp-via-envuser nntp-via-user-name)
1646           (process-send-string proc (concat "open " "-l" nntp-via-user-name
1647                                             nntp-via-address "\n")))
1648          (t
1649           (process-send-string proc (concat "open " nntp-via-address
1650                                             "\n"))))
1651         (when (not nntp-via-envuser)
1652           (nntp-wait-for-string "^\r*.?login:")
1653           (process-send-string proc
1654                                (concat
1655                                 (or nntp-via-user-name
1656                                     (setq nntp-via-user-name
1657                                           (read-string "login: ")))
1658                                 "\n")))
1659         (nntp-wait-for-string "^\r*.?password:")
1660         (process-send-string proc
1661                              (concat
1662                               (or nntp-via-user-password
1663                                   (setq nntp-via-user-password
1664                                         (mail-source-read-passwd
1665                                          "Password: ")))
1666                               "\n"))
1667         (nntp-wait-for-string nntp-via-shell-prompt)
1668         (let ((real-telnet-command `("exec"
1669                                      ,nntp-telnet-command
1670                                      ,@nntp-telnet-switches
1671                                      ,nntp-address
1672                                      ,nntp-port-number)))
1673           (process-send-string proc
1674                                (concat (mapconcat 'identity
1675                                                   real-telnet-command " ")
1676                                        "\n")))
1677         (nntp-wait-for-string "^\r*20[01]")
1678         (beginning-of-line)
1679         (delete-region (point-min) (point))
1680         (process-send-string proc "\^]")
1681         (nntp-wait-for-string "^r?telnet")
1682         (process-send-string proc "mode character\n")
1683         (accept-process-output proc 1)
1684         (sit-for 1)
1685         (goto-char (point-min))
1686         (forward-line 1)
1687         (delete-region (point) (point-max)))
1688       proc)))
1689
1690 (provide 'nntp)
1691
1692 ;;; nntp.el ends here