Importing Oort Gnus v0.05.
[elisp/gnus.git-] / 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          (buffer (process-buffer (nntp-find-connection nntp-server-buffer)))
438          (pos (with-current-buffer buffer (point))))
439     (prog1
440         (nntp-retrieve-data command
441                             nntp-address nntp-port-number nntp-server-buffer
442                             wait-for nnheader-callback-function t)
443       ;; If nothing to wait for, still remove possibly echo'ed commands
444       (unless wait-for
445         (nntp-accept-response)
446         (save-excursion
447           (set-buffer buffer)
448           (goto-char pos)
449           (if (looking-at (regexp-quote command))
450               (delete-region pos (progn (forward-line 1) (gnus-point-at-bol))))
451           )))
452     ))
453
454
455 (defun nntp-send-buffer (wait-for)
456   "Send the current buffer to server and wait until WAIT-FOR returns."
457   (when (and (not nnheader-callback-function)
458              (not nntp-inhibit-output))
459     (save-excursion
460       (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
461       (erase-buffer)))
462   (nntp-encode-text)
463   (mm-with-unibyte-current-buffer
464     ;; Some encoded unicode text contains character 0x80-0x9f e.g. Euro.
465     (process-send-region (nntp-find-connection nntp-server-buffer)
466                          (point-min) (point-max)))
467   (nntp-retrieve-data
468    nil nntp-address nntp-port-number nntp-server-buffer
469    wait-for nnheader-callback-function))
470
471 \f
472
473 ;;; Interface functions.
474
475 (nnoo-define-basics nntp)
476
477 (defsubst nntp-next-result-arrived-p ()
478   (cond
479    ;; A result that starts with a 2xx code is terminated by
480    ;; a line with only a "." on it.
481    ((eq (char-after) ?2)
482     (if (re-search-forward "\n\\.\r?\n" nil t)
483         t
484       nil))
485    ;; A result that starts with a 3xx or 4xx code is terminated
486    ;; by a newline.
487    ((looking-at "[34]")
488     (if (search-forward "\n" nil t)
489         t
490       nil))
491    ;; No result here.
492    (t
493     nil)))
494
495 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
496   "Retrieve the headers of ARTICLES."
497   (nntp-possibly-change-group group server)
498   (save-excursion
499     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
500     (erase-buffer)
501     (if (and (not gnus-nov-is-evil)
502              (not nntp-nov-is-evil)
503              (nntp-retrieve-headers-with-xover articles fetch-old))
504         ;; We successfully retrieved the headers via XOVER.
505         'nov
506       ;; XOVER didn't work, so we do it the hard, slow and inefficient
507       ;; way.
508       (let ((number (length articles))
509             (count 0)
510             (received 0)
511             (last-point (point-min))
512             (buf (nntp-find-connection-buffer nntp-server-buffer))
513             (nntp-inhibit-erase t)
514             article)
515         ;; Send HEAD commands.
516         (while (setq article (pop articles))
517           (nntp-send-command
518            nil
519            "HEAD" (if (numberp article)
520                       (int-to-string article)
521                     ;; `articles' is either a list of article numbers
522                     ;; or a list of article IDs.
523                     article))
524           (incf count)
525           ;; Every 400 requests we have to read the stream in
526           ;; order to avoid deadlocks.
527           (when (or (null articles)     ;All requests have been sent.
528                     (zerop (% count nntp-maximum-request)))
529             (nntp-accept-response)
530             (while (progn
531                      (set-buffer buf)
532                      (goto-char last-point)
533                      ;; Count replies.
534                      (while (nntp-next-result-arrived-p)
535                        (setq last-point (point))
536                        (incf received))
537                      (< received count))
538               ;; If number of headers is greater than 100, give
539               ;;  informative messages.
540               (and (numberp nntp-large-newsgroup)
541                    (> number nntp-large-newsgroup)
542                    (zerop (% received 20))
543                    (nnheader-message 6 "NNTP: Receiving headers... %d%%"
544                                      (/ (* received 100) number)))
545               (nntp-accept-response))))
546         (and (numberp nntp-large-newsgroup)
547              (> number nntp-large-newsgroup)
548              (nnheader-message 6 "NNTP: Receiving headers...done"))
549
550         ;; Now all of replies are received.  Fold continuation lines.
551         (nnheader-fold-continuation-lines)
552         ;; Remove all "\r"'s.
553         (nnheader-strip-cr)
554         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
555         'headers))))
556
557 (deffoo nntp-retrieve-groups (groups &optional server)
558   "Retrieve group info on GROUPS."
559   (nntp-possibly-change-group nil server)
560   (when (nntp-find-connection-buffer nntp-server-buffer)
561     (catch 'done
562       (save-excursion
563         ;; Erase nntp-server-buffer before nntp-inhibit-erase.
564         (set-buffer nntp-server-buffer)
565         (erase-buffer)
566         (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
567         ;; The first time this is run, this variable is `try'.  So we
568         ;; try.
569         (when (eq nntp-server-list-active-group 'try)
570           (nntp-try-list-active (car groups)))
571         (erase-buffer)
572         (let ((count 0)
573               (received 0)
574               (last-point (point-min))
575               (nntp-inhibit-erase t)
576               (buf (nntp-find-connection-buffer nntp-server-buffer))
577               (command (if nntp-server-list-active-group
578                            "LIST ACTIVE" "GROUP")))
579           (while groups
580             ;; Send the command to the server.
581             (nntp-send-command nil command (pop groups))
582             (incf count)
583             ;; Every 400 requests we have to read the stream in
584             ;; order to avoid deadlocks.
585             (when (or (null groups)     ;All requests have been sent.
586                       (zerop (% count nntp-maximum-request)))
587               (nntp-accept-response)
588               (while (and (gnus-buffer-live-p buf)
589                           (progn
590                             ;; Search `blue moon' in this file for the
591                             ;; reason why set-buffer here.
592                             (set-buffer buf)
593                             (goto-char last-point)
594                             ;; Count replies.
595                             (while (re-search-forward "^[0-9]" nil t)
596                               (incf received))
597                             (setq last-point (point))
598                             (< received count)))
599                 (nntp-accept-response))))
600
601           ;; Wait for the reply from the final command.
602           (unless (gnus-buffer-live-p buf)
603             (nnheader-report 'nntp "Connection to %s is closed." server)
604             (throw 'done nil))
605           (set-buffer buf)
606           (goto-char (point-max))
607           (re-search-backward "^[0-9]" nil t)
608           (when (looking-at "^[23]")
609             (while (and (gnus-buffer-live-p buf)
610                         (progn
611                           (set-buffer buf)
612                           (goto-char (point-max))
613                           (if (not nntp-server-list-active-group)
614                               (not (re-search-backward "\r?\n" (- (point) 3) t))
615                             (not (re-search-backward "^\\.\r?\n"
616                                                      (- (point) 4) t)))))
617               (nntp-accept-response)))
618
619           ;; Now all replies are received.  We remove CRs.
620           (unless (gnus-buffer-live-p buf)
621             (nnheader-report 'nntp "Connection to %s is closed." server)
622             (throw 'done nil))
623           (set-buffer buf)
624           (goto-char (point-min))
625           (while (search-forward "\r" nil t)
626             (replace-match "" t t))
627
628           (if (not nntp-server-list-active-group)
629               (progn
630                 (copy-to-buffer nntp-server-buffer (point-min) (point-max))
631                 'group)
632             ;; We have read active entries, so we just delete the
633             ;; superfluous gunk.
634             (goto-char (point-min))
635             (while (re-search-forward "^[.2-5]" nil t)
636               (delete-region (match-beginning 0)
637                              (progn (forward-line 1) (point))))
638             (copy-to-buffer nntp-server-buffer (point-min) (point-max))
639             'active))))))
640
641 (deffoo nntp-retrieve-articles (articles &optional group server)
642   (nntp-possibly-change-group group server)
643   (save-excursion
644     (let ((number (length articles))
645           (count 0)
646           (received 0)
647           (last-point (point-min))
648           (buf (nntp-find-connection-buffer nntp-server-buffer))
649           (nntp-inhibit-erase t)
650           (map (apply 'vector articles))
651           (point 1)
652           article)
653       (set-buffer buf)
654       (erase-buffer)
655       ;; Send ARTICLE command.
656       (while (setq article (pop articles))
657         (nntp-send-command
658          nil
659          "ARTICLE" (if (numberp article)
660                        (int-to-string article)
661                      ;; `articles' is either a list of article numbers
662                      ;; or a list of article IDs.
663                      article))
664         (incf count)
665         ;; Every 400 requests we have to read the stream in
666         ;; order to avoid deadlocks.
667         (when (or (null articles)       ;All requests have been sent.
668                   (zerop (% count nntp-maximum-request)))
669           (nntp-accept-response)
670           (while (progn
671                    (set-buffer buf)
672                    (goto-char last-point)
673                    ;; Count replies.
674                    (while (nntp-next-result-arrived-p)
675                      (aset map received (cons (aref map received) (point)))
676                      (setq last-point (point))
677                      (incf received))
678                    (< received count))
679             ;; If number of headers is greater than 100, give
680             ;;  informative messages.
681             (and (numberp nntp-large-newsgroup)
682                  (> number nntp-large-newsgroup)
683                  (zerop (% received 20))
684                  (nnheader-message 6 "NNTP: Receiving articles... %d%%"
685                                    (/ (* received 100) number)))
686             (nntp-accept-response))))
687       (and (numberp nntp-large-newsgroup)
688            (> number nntp-large-newsgroup)
689            (nnheader-message 6 "NNTP: Receiving articles...done"))
690
691       ;; Now we have all the responses.  We go through the results,
692       ;; wash it and copy it over to the server buffer.
693       (set-buffer nntp-server-buffer)
694       (erase-buffer)
695       (setq last-point (point-min))
696       (mapcar
697        (lambda (entry)
698          (narrow-to-region
699           (setq point (goto-char (point-max)))
700           (progn
701             (insert-buffer-substring buf last-point (cdr entry))
702             (point-max)))
703          (setq last-point (cdr entry))
704          (nntp-decode-text)
705          (widen)
706          (cons (car entry) point))
707        map))))
708
709 (defun nntp-try-list-active (group)
710   (nntp-list-active-group group)
711   (save-excursion
712     (set-buffer nntp-server-buffer)
713     (goto-char (point-min))
714     (cond ((or (eobp)
715                (looking-at "5[0-9]+"))
716            (setq nntp-server-list-active-group nil))
717           (t
718            (setq nntp-server-list-active-group t)))))
719
720 (deffoo nntp-list-active-group (group &optional server)
721   "Return the active info on GROUP (which can be a regexp)."
722   (nntp-possibly-change-group nil server)
723   (nntp-send-command "^\\.*\r?\n" "LIST ACTIVE" group))
724
725 (deffoo nntp-request-group-articles (group &optional server)
726   "Return the list of existing articles in GROUP."
727   (nntp-possibly-change-group nil server)
728   (nntp-send-command "^\\.*\r?\n" "LISTGROUP" group))
729
730 (deffoo nntp-request-article (article &optional group server buffer command)
731   (nntp-possibly-change-group group server)
732   (when (nntp-send-command-and-decode
733          "\r?\n\\.\r?\n" "ARTICLE"
734          (if (numberp article) (int-to-string article) article))
735     (if (and buffer
736              (not (equal buffer nntp-server-buffer)))
737         (save-excursion
738           (set-buffer nntp-server-buffer)
739           (copy-to-buffer buffer (point-min) (point-max))
740           (nntp-find-group-and-number group))
741       (nntp-find-group-and-number group))))
742
743 (deffoo nntp-request-head (article &optional group server)
744   (nntp-possibly-change-group group server)
745   (when (nntp-send-command
746          "\r?\n\\.\r?\n" "HEAD"
747          (if (numberp article) (int-to-string article) article))
748     (prog1
749         (nntp-find-group-and-number group)
750       (nntp-decode-text))))
751
752 (deffoo nntp-request-body (article &optional group server)
753   (nntp-possibly-change-group group server)
754   (nntp-send-command-and-decode
755    "\r?\n\\.\r?\n" "BODY"
756    (if (numberp article) (int-to-string article) article)))
757
758 (deffoo nntp-request-group (group &optional server dont-check)
759   (nntp-possibly-change-group nil server)
760   (when (nntp-send-command "^[245].*\n" "GROUP" group)
761     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
762       (setcar (cddr entry) group))))
763
764 (deffoo nntp-close-group (group &optional server)
765   t)
766
767 (deffoo nntp-server-opened (&optional server)
768   "Say whether a connection to SERVER has been opened."
769   (and (nnoo-current-server-p 'nntp server)
770        nntp-server-buffer
771        (gnus-buffer-live-p nntp-server-buffer)
772        (nntp-find-connection nntp-server-buffer)))
773
774 (deffoo nntp-open-server (server &optional defs connectionless)
775   (nnheader-init-server-buffer)
776   (if (nntp-server-opened server)
777       t
778     (when (or (stringp (car defs))
779               (numberp (car defs)))
780       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
781     (unless (assq 'nntp-address defs)
782       (setq defs (append defs (list (list 'nntp-address server)))))
783     (nnoo-change-server 'nntp server defs)
784     (unless connectionless
785       (or (nntp-find-connection nntp-server-buffer)
786           (nntp-open-connection nntp-server-buffer)))))
787
788 (deffoo nntp-close-server (&optional server)
789   (nntp-possibly-change-group nil server t)
790   (let ((process (nntp-find-connection nntp-server-buffer)))
791     (while process
792       (when (memq (process-status process) '(open run))
793         (ignore-errors
794           (nntp-send-string process "QUIT")
795           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
796             ;; Ok, this is evil, but when using telnet and stuff
797             ;; as the connection method, it's important that the
798             ;; QUIT command actually is sent out before we kill
799             ;; the process.
800             (sleep-for 1))))
801       (nntp-kill-buffer (process-buffer process))
802       (setq process (car (pop nntp-connection-alist))))
803     (nnoo-close-server 'nntp)))
804
805 (deffoo nntp-request-close ()
806   (let (process)
807     (while (setq process (pop nntp-connection-list))
808       (when (memq (process-status process) '(open run))
809         (ignore-errors
810           (nntp-send-string process "QUIT")
811           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
812             ;; Ok, this is evil, but when using telnet and stuff
813             ;; as the connection method, it's important that the
814             ;; QUIT command actually is sent out before we kill
815             ;; the process.
816             (sleep-for 1))))
817       (nntp-kill-buffer (process-buffer process)))))
818
819 (deffoo nntp-request-list (&optional server)
820   (nntp-possibly-change-group nil server)
821   (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST"))
822
823 (deffoo nntp-request-list-newsgroups (&optional server)
824   (nntp-possibly-change-group nil server)
825   (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS"))
826
827 (deffoo nntp-request-newgroups (date &optional server)
828   (nntp-possibly-change-group nil server)
829   (save-excursion
830     (set-buffer nntp-server-buffer)
831     (let* ((time (date-to-time date))
832            (ls (- (cadr time) (nth 8 (decode-time time)))))
833       (cond ((< ls 0)
834              (setcar time (1- (car time)))
835              (setcar (cdr time) (+ ls 65536)))
836             ((>= ls 65536)
837              (setcar time (1+ (car time)))
838              (setcar (cdr time) (- ls 65536)))
839             (t
840              (setcar (cdr time) ls)))
841       (prog1
842           (nntp-send-command
843            "^\\.\r?\n" "NEWGROUPS"
844            (format-time-string "%y%m%d %H%M%S" time)
845            "GMT")
846         (nntp-decode-text)))))
847
848 (deffoo nntp-request-post (&optional server)
849   (nntp-possibly-change-group nil server)
850   (when (nntp-send-command "^[23].*\r?\n" "POST")
851     (let ((response (with-current-buffer nntp-server-buffer
852                       nntp-process-response))
853           server-id)
854       (when (and response
855                  (string-match "^[23].*\\(<[^\t\n @<>]+@[^\t\n @<>]+>\\)"
856                                response))
857         (setq server-id (match-string 1 response))
858         (narrow-to-region (goto-char (point-min))
859                           (if (search-forward "\n\n" nil t)
860                               (1- (point))
861                             (point-max)))
862         (unless (mail-fetch-field "Message-ID")
863           (goto-char (point-min))
864           (insert "Message-ID: " server-id "\n"))
865         (widen))
866       (run-hooks 'nntp-prepare-post-hook)
867       (nntp-send-buffer "^[23].*\n"))))
868
869 (deffoo nntp-request-type (group article)
870   'news)
871
872 (deffoo nntp-asynchronous-p ()
873   t)
874
875 ;;; Hooky functions.
876
877 (defun nntp-send-mode-reader ()
878   "Send the MODE READER command to the nntp server.
879 This function is supposed to be called from `nntp-server-opened-hook'.
880 It will make innd servers spawn an nnrpd process to allow actual article
881 reading."
882   (nntp-send-command "^.*\n" "MODE READER"))
883
884 (defun nntp-send-authinfo (&optional send-if-force)
885   "Send the AUTHINFO to the nntp server.
886 It will look in the \"~/.authinfo\" file for matching entries.  If
887 nothing suitable is found there, it will prompt for a user name
888 and a password.
889
890 If SEND-IF-FORCE, only send authinfo to the server if the
891 .authinfo file has the FORCE token."
892   (let* ((list (gnus-parse-netrc nntp-authinfo-file))
893          (alist (gnus-netrc-machine list nntp-address "nntp"))
894          (force (gnus-netrc-get alist "force"))
895          (user (or (gnus-netrc-get alist "login") nntp-authinfo-user))
896          (passwd (gnus-netrc-get alist "password")))
897     (when (or (not send-if-force)
898               force)
899       (unless user
900         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
901               nntp-authinfo-user user))
902       (unless (member user '(nil ""))
903         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
904         (when t                         ;???Should check if AUTHINFO succeeded
905           (nntp-send-command
906            "^2.*\r?\n" "AUTHINFO PASS"
907            (or passwd
908                nntp-authinfo-password
909                (setq nntp-authinfo-password
910                      (mail-source-read-passwd
911                       (format "NNTP (%s@%s) password: "
912                               user nntp-address))))))))))
913
914 (defun nntp-send-nosy-authinfo ()
915   "Send the AUTHINFO to the nntp server."
916   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
917     (unless (member user '(nil ""))
918       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
919       (when t                           ;???Should check if AUTHINFO succeeded
920         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
921                            (mail-source-read-passwd "NNTP (%s@%s) password: "
922                                                     user nntp-address))))))
923
924 (defun nntp-send-authinfo-from-file ()
925   "Send the AUTHINFO to the nntp server.
926
927 The authinfo login name is taken from the user's login name and the
928 password contained in '~/.nntp-authinfo'."
929   (when (file-exists-p "~/.nntp-authinfo")
930     (with-temp-buffer
931       (insert-file-contents "~/.nntp-authinfo")
932       (goto-char (point-min))
933       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
934       (nntp-send-command
935        "^2.*\r?\n" "AUTHINFO PASS"
936        (buffer-substring (point) (progn (end-of-line) (point)))))))
937
938 ;;; Internal functions.
939
940 (defun nntp-handle-authinfo (process)
941   "Take care of an authinfo response from the server."
942   (let ((last nntp-last-command))
943     (funcall nntp-authinfo-function)
944     ;; We have to re-send the function that was interrupted by
945     ;; the authinfo request.
946     (save-excursion
947       (set-buffer nntp-server-buffer)
948       (erase-buffer))
949     (nntp-send-string process last)))
950
951 (defun nntp-make-process-buffer (buffer)
952   "Create a new, fresh buffer usable for nntp process connections."
953   (save-excursion
954     (set-buffer
955      (generate-new-buffer
956       (format " *server %s %s %s*"
957               nntp-address nntp-port-number
958               (gnus-buffer-exists-p buffer))))
959     (mm-enable-multibyte)
960     (set (make-local-variable 'after-change-functions) nil)
961     (set (make-local-variable 'nntp-process-wait-for) nil)
962     (set (make-local-variable 'nntp-process-callback) nil)
963     (set (make-local-variable 'nntp-process-to-buffer) nil)
964     (set (make-local-variable 'nntp-process-start-point) nil)
965     (set (make-local-variable 'nntp-process-decode) nil)
966     (current-buffer)))
967
968 (defun nntp-open-connection (buffer)
969   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
970   (run-hooks 'nntp-prepare-server-hook)
971   (let* ((pbuffer (nntp-make-process-buffer buffer))
972          (timer
973           (and nntp-connection-timeout
974                (nnheader-run-at-time
975                 nntp-connection-timeout nil
976                 `(lambda ()
977                    (nntp-kill-buffer ,pbuffer)))))
978          (process
979           (condition-case ()
980               (let ((coding-system-for-read nntp-coding-system-for-read)
981                     (coding-system-for-write nntp-coding-system-for-write))
982                 (funcall nntp-open-connection-function pbuffer))
983             (error nil)
984             (quit
985              (message "Quit opening connection")
986              (nntp-kill-buffer pbuffer)
987              (signal 'quit nil)
988              nil))))
989     (when timer
990       (nnheader-cancel-timer timer))
991     (unless process
992       (nntp-kill-buffer pbuffer))
993     (when (and (buffer-name pbuffer)
994                process)
995       (process-kill-without-query process)
996       (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
997                (memq (process-status process) '(open run)))
998           (prog1
999               (caar (push (list process buffer nil) nntp-connection-alist))
1000             (push process nntp-connection-list)
1001             (save-excursion
1002               (set-buffer pbuffer)
1003               (nntp-read-server-type)
1004               (erase-buffer)
1005               (set-buffer nntp-server-buffer)
1006               (let ((nnheader-callback-function nil))
1007                 (run-hooks 'nntp-server-opened-hook)
1008                 (nntp-send-authinfo t))))
1009         (nntp-kill-buffer (process-buffer process))
1010         nil))))
1011
1012 (defun nntp-open-network-stream (buffer)
1013   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
1014
1015 (defun nntp-open-ssl-stream (buffer)
1016   (let ((proc (open-ssl-stream "nntpd" buffer nntp-address nntp-port-number)))
1017     (save-excursion
1018       (set-buffer buffer)
1019       (nntp-wait-for-string "^\r*20[01]")
1020       (beginning-of-line)
1021       (delete-region (point-min) (point))
1022       proc)))
1023
1024 (defun nntp-read-server-type ()
1025   "Find out what the name of the server we have connected to is."
1026   ;; Wait for the status string to arrive.
1027   (setq nntp-server-type (buffer-string))
1028   (let ((alist nntp-server-action-alist)
1029         (case-fold-search t)
1030         entry)
1031     ;; Run server-specific commands.
1032     (while alist
1033       (setq entry (pop alist))
1034       (when (string-match (car entry) nntp-server-type)
1035         (if (and (listp (cadr entry))
1036                  (not (eq 'lambda (caadr entry))))
1037             (eval (cadr entry))
1038           (funcall (cadr entry)))))))
1039
1040 (defun nntp-async-wait (process wait-for buffer decode callback)
1041   (save-excursion
1042     (set-buffer (process-buffer process))
1043     (unless nntp-inside-change-function
1044       (erase-buffer))
1045     (setq nntp-process-wait-for wait-for
1046           nntp-process-to-buffer buffer
1047           nntp-process-decode decode
1048           nntp-process-callback callback
1049           nntp-process-start-point (point-max))
1050     (setq after-change-functions '(nntp-after-change-function))
1051     (if nntp-async-needs-kluge
1052         (nntp-async-kluge process))))
1053
1054 (defun nntp-async-kluge (process)
1055   ;; emacs 20.3 bug: process output with encoding 'binary
1056   ;; doesn't trigger after-change-functions.
1057   (unless nntp-async-timer
1058     (setq nntp-async-timer
1059           (nnheader-run-at-time 1 1 'nntp-async-timer-handler)))
1060   (add-to-list 'nntp-async-process-list process))
1061
1062 (defun nntp-async-timer-handler ()
1063   (mapcar
1064    (lambda (proc)
1065      (if (memq (process-status proc) '(open run))
1066          (nntp-async-trigger proc)
1067        (nntp-async-stop proc)))
1068    nntp-async-process-list))
1069
1070 (defun nntp-async-stop (proc)
1071   (setq nntp-async-process-list (delq proc nntp-async-process-list))
1072   (when (and nntp-async-timer (not nntp-async-process-list))
1073     (nnheader-cancel-timer nntp-async-timer)
1074     (setq nntp-async-timer nil)))
1075
1076 (defun nntp-after-change-function (beg end len)
1077   (unwind-protect
1078       ;; we only care about insertions at eob
1079       (when (and (eq 0 len) (eq (point-max) end))
1080         (save-match-data
1081           (let ((proc (get-buffer-process (current-buffer))))
1082             (when proc
1083               (nntp-async-trigger proc)))))
1084     ;; any throw from after-change-functions will leave it
1085     ;; set to nil.  so we reset it here, if necessary.
1086     (when quit-flag
1087       (setq after-change-functions '(nntp-after-change-function)))))
1088
1089 (defun nntp-async-trigger (process)
1090   (save-excursion
1091     (set-buffer (process-buffer process))
1092     (when nntp-process-callback
1093       ;; do we have an error message?
1094       (goto-char nntp-process-start-point)
1095       (if (memq (following-char) '(?4 ?5))
1096           ;; wants credentials?
1097           (if (looking-at "480")
1098               (nntp-handle-authinfo process)
1099             ;; report error message.
1100             (nntp-snarf-error-message)
1101             (nntp-do-callback nil))
1102
1103         ;; got what we expect?
1104         (goto-char (point-max))
1105         (when (re-search-backward
1106                nntp-process-wait-for nntp-process-start-point t)
1107           (let ((response (match-string 0)))
1108             (with-current-buffer nntp-server-buffer
1109               (setq nntp-process-response response)))
1110           (nntp-async-stop process)
1111           ;; convert it.
1112           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1113             (let ((buf (current-buffer))
1114                   (start nntp-process-start-point)
1115                   (decode nntp-process-decode))
1116               (save-excursion
1117                 (set-buffer nntp-process-to-buffer)
1118                 (goto-char (point-max))
1119                 (save-restriction
1120                   (narrow-to-region (point) (point))
1121                   (insert-buffer-substring buf start)
1122                   (when decode
1123                     (nntp-decode-text))))))
1124           ;; report it.
1125           (goto-char (point-max))
1126           (nntp-do-callback
1127            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1128
1129 (defun nntp-do-callback (arg)
1130   (let ((callback nntp-process-callback)
1131         (nntp-inside-change-function t))
1132     (setq nntp-process-callback nil)
1133     (funcall callback arg)))
1134
1135 (defun nntp-snarf-error-message ()
1136   "Save the error message in the current buffer."
1137   (let ((message (buffer-string)))
1138     (while (string-match "[\r\n]+" message)
1139       (setq message (replace-match " " t t message)))
1140     (nnheader-report 'nntp message)
1141     message))
1142
1143 (defun nntp-accept-process-output (process &optional timeout)
1144   "Wait for output from PROCESS and message some dots."
1145   (save-excursion
1146     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1147                     nntp-server-buffer))
1148     (let ((len (/ (point-max) 1024))
1149           message-log-max)
1150       (unless (< len 10)
1151         (setq nntp-have-messaged t)
1152         (nnheader-message 7 "nntp read: %dk" len)))
1153     (accept-process-output process (or timeout 1))))
1154
1155 (defun nntp-accept-response ()
1156   "Wait for output from the process that outputs to BUFFER."
1157   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1158
1159 (defun nntp-possibly-change-group (group server &optional connectionless)
1160   (let ((nnheader-callback-function nil))
1161     (when server
1162       (or (nntp-server-opened server)
1163           (nntp-open-server server nil connectionless)))
1164
1165     (unless connectionless
1166       (or (nntp-find-connection nntp-server-buffer)
1167           (nntp-open-connection nntp-server-buffer))))
1168
1169   (when group
1170     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1171       (when (not (equal group (caddr entry)))
1172         (save-excursion
1173           (set-buffer (process-buffer (car entry)))
1174           (erase-buffer)
1175           (nntp-send-command "^[245].*\n" "GROUP" group)
1176           (setcar (cddr entry) group)
1177           (erase-buffer)
1178           (save-excursion
1179             (set-buffer nntp-server-buffer)
1180             (erase-buffer)))))))
1181
1182 (defun nntp-decode-text (&optional cr-only)
1183   "Decode the text in the current buffer."
1184   (goto-char (point-min))
1185   (while (search-forward "\r" nil t)
1186     (delete-char -1))
1187   (unless cr-only
1188     ;; Remove trailing ".\n" end-of-transfer marker.
1189     (goto-char (point-max))
1190     (forward-line -1)
1191     (when (looking-at ".\n")
1192       (delete-char 2))
1193     ;; Delete status line.
1194     (goto-char (point-min))
1195     (while (looking-at "[1-5][0-9][0-9] .*\n")
1196       ;; For some unknown reason, there is more than one status line.
1197       (delete-region (point) (progn (forward-line 1) (point))))
1198     ;; Remove "." -> ".." encoding.
1199     (while (search-forward "\n.." nil t)
1200       (delete-char -1))))
1201
1202 (defun nntp-encode-text ()
1203   "Encode the text in the current buffer."
1204   (save-excursion
1205     ;; Replace "." at beginning of line with "..".
1206     (goto-char (point-min))
1207     (while (re-search-forward "^\\." nil t)
1208       (insert "."))
1209     (goto-char (point-max))
1210     ;; Insert newline at the end of the buffer.
1211     (unless (bolp)
1212       (insert "\n"))
1213     ;; Insert `.' at end of buffer (end of text mark).
1214     (goto-char (point-max))
1215     (insert ".\n")
1216     (goto-char (point-min))
1217     (while (not (eobp))
1218       (end-of-line)
1219       (delete-char 1)
1220       (insert nntp-end-of-line))))
1221
1222 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1223   (set-buffer nntp-server-buffer)
1224   (erase-buffer)
1225   (cond
1226
1227    ;; This server does not talk NOV.
1228    ((not nntp-server-xover)
1229     nil)
1230
1231    ;; We don't care about gaps.
1232    ((or (not nntp-nov-gap)
1233         fetch-old)
1234     (nntp-send-xover-command
1235      (if fetch-old
1236          (if (numberp fetch-old)
1237              (max 1 (- (car articles) fetch-old))
1238            1)
1239        (car articles))
1240      (car (last articles)) 'wait)
1241
1242     (goto-char (point-min))
1243     (when (looking-at "[1-5][0-9][0-9] .*\n")
1244       (delete-region (point) (progn (forward-line 1) (point))))
1245     (while (search-forward "\r" nil t)
1246       (replace-match "" t t))
1247     (goto-char (point-max))
1248     (forward-line -1)
1249     (when (looking-at "\\.")
1250       (delete-region (point) (progn (forward-line 1) (point)))))
1251
1252    ;; We do it the hard way.  For each gap, an XOVER command is sent
1253    ;; to the server.  We do not wait for a reply from the server, we
1254    ;; just send them off as fast as we can.  That means that we have
1255    ;; to count the number of responses we get back to find out when we
1256    ;; have gotten all we asked for.
1257    ((numberp nntp-nov-gap)
1258     (let ((count 0)
1259           (received 0)
1260           last-point
1261           in-process-buffer-p
1262           (buf nntp-server-buffer)
1263           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1264           first)
1265       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1266       ;; that means that the server does not understand XOVER, but we
1267       ;; won't know that until we try.
1268       (while (and nntp-server-xover articles)
1269         (setq first (car articles))
1270         ;; Search forward until we find a gap, or until we run out of
1271         ;; articles.
1272         (while (and (cdr articles)
1273                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1274           (setq articles (cdr articles)))
1275
1276         (setq in-process-buffer-p (stringp nntp-server-xover))
1277         (nntp-send-xover-command first (car articles))
1278         (setq articles (cdr articles))
1279
1280         (when (and nntp-server-xover in-process-buffer-p)
1281           ;; Don't count tried request.
1282           (setq count (1+ count))
1283
1284           ;; Every 400 requests we have to read the stream in
1285           ;; order to avoid deadlocks.
1286           (when (or (null articles)     ;All requests have been sent.
1287                     (zerop (% count nntp-maximum-request)))
1288
1289             (nntp-accept-response)
1290             ;; On some Emacs versions the preceding function has a
1291             ;; tendency to change the buffer.  Perhaps.  It's quite
1292             ;; difficult to reproduce, because it only seems to happen
1293             ;; once in a blue moon.
1294             (set-buffer process-buffer)
1295             (while (progn
1296                      (goto-char (or last-point (point-min)))
1297                      ;; Count replies.
1298                      (while (re-search-forward "^[0-9][0-9][0-9] .*\n" nil t)
1299                        (incf received))
1300                      (setq last-point (point))
1301                      (< received count))
1302               (nntp-accept-response)
1303               (set-buffer process-buffer))
1304             (set-buffer buf))))
1305
1306       (when nntp-server-xover
1307         (when in-process-buffer-p
1308           (set-buffer process-buffer)
1309           ;; Wait for the reply from the final command.
1310           (goto-char (point-max))
1311           (while (not (re-search-backward "^[0-9][0-9][0-9] " nil t))
1312             (nntp-accept-response)
1313             (set-buffer process-buffer)
1314             (goto-char (point-max)))
1315           (when (looking-at "^[23]")
1316             (while (progn
1317                      (goto-char (point-max))
1318                      (forward-line -1)
1319                      (not (looking-at "^\\.\r?\n")))
1320               (nntp-accept-response)
1321               (set-buffer process-buffer)))
1322           (set-buffer buf)
1323           (goto-char (point-max))
1324           (insert-buffer-substring process-buffer)
1325           (set-buffer process-buffer)
1326           (erase-buffer)
1327           (set-buffer buf))
1328
1329         ;; We remove any "." lines and status lines.
1330         (goto-char (point-min))
1331         (while (search-forward "\r" nil t)
1332           (delete-char -1))
1333         (goto-char (point-min))
1334         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1335         t))))
1336
1337   nntp-server-xover)
1338
1339 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1340   "Send the XOVER command to the server."
1341   (let ((range (format "%d-%d" beg end))
1342         (nntp-inhibit-erase t))
1343     (if (stringp nntp-server-xover)
1344         ;; If `nntp-server-xover' is a string, then we just send this
1345         ;; command.
1346         (if wait-for-reply
1347             (nntp-send-command-nodelete
1348              "\r?\n\\.\r?\n" nntp-server-xover range)
1349           ;; We do not wait for the reply.
1350           (nntp-send-command-nodelete nil nntp-server-xover range))
1351       (let ((commands nntp-xover-commands))
1352         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1353         ;; We try them all until we get at positive response.
1354         (while (and commands (eq nntp-server-xover 'try))
1355           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1356           (save-excursion
1357             (set-buffer nntp-server-buffer)
1358             (goto-char (point-min))
1359             (and (looking-at "[23]")    ; No error message.
1360                  ;; We also have to look at the lines.  Some buggy
1361                  ;; servers give back simple lines with just the
1362                  ;; article number.  How... helpful.
1363                  (progn
1364                    (forward-line 1)
1365                    (looking-at "[0-9]+\t...")) ; More text after number.
1366                  (setq nntp-server-xover (car commands))))
1367           (setq commands (cdr commands)))
1368         ;; If none of the commands worked, we disable XOVER.
1369         (when (eq nntp-server-xover 'try)
1370           (save-excursion
1371             (set-buffer nntp-server-buffer)
1372             (erase-buffer)
1373             (setq nntp-server-xover nil)))
1374         nntp-server-xover))))
1375
1376 (defun nntp-find-group-and-number (&optional group)
1377   (save-excursion
1378     (save-restriction
1379       (set-buffer nntp-server-buffer)
1380       (narrow-to-region (goto-char (point-min))
1381                         (or (search-forward "\n\n" nil t) (point-max)))
1382       (goto-char (point-min))
1383       ;; We first find the number by looking at the status line.
1384       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1385                          (string-to-int
1386                           (buffer-substring (match-beginning 1)
1387                                             (match-end 1)))))
1388             newsgroups xref)
1389         (and number (zerop number) (setq number nil))
1390         (if number
1391             ;; Then we find the group name.
1392             (setq group
1393                   (cond
1394                    ;; If there is only one group in the Newsgroups
1395                    ;; header, then it seems quite likely that this
1396                    ;; article comes from that group, I'd say.
1397                    ((and (setq newsgroups 
1398                                (mail-fetch-field "newsgroups"))
1399                          (not (string-match "," newsgroups)))
1400                     newsgroups)
1401                    ;; If there is more than one group in the
1402                    ;; Newsgroups header, then the Xref header should
1403                    ;; be filled out.  We hazard a guess that the group
1404                    ;; that has this article number in the Xref header
1405                    ;; is the one we are looking for.  This might very
1406                    ;; well be wrong if this article happens to have
1407                    ;; the same number in several groups, but that's
1408                    ;; life.
1409                    ((and (setq xref (mail-fetch-field "xref"))
1410                          number
1411                          (string-match 
1412                           (format "\\([^ :]+\\):%d" number) xref))
1413                     (match-string 1 xref))
1414                    (t "")))
1415           (cond
1416            ((and (setq xref (mail-fetch-field "xref"))
1417                  (string-match 
1418                   (if group
1419                       (concat "\\(" (regexp-quote group) "\\):\\([0-9]+\\)")
1420                     "\\([^ :]+\\):\\([0-9]+\\)")
1421                   xref))
1422             (setq group (match-string 1 xref)
1423                   number (string-to-int (match-string 2 xref))))
1424            ((and (setq newsgroups 
1425                        (mail-fetch-field "newsgroups"))
1426                  (not (string-match "," newsgroups)))
1427             (setq group newsgroups))
1428            (group)
1429            (t (setq group ""))))
1430         (when (string-match "\r" group)
1431           (setq group (substring group 0 (match-beginning 0))))
1432         (cons group number)))))
1433
1434 (defun nntp-wait-for-string (regexp)
1435   "Wait until string arrives in the buffer."
1436   (let ((buf (current-buffer)))
1437     (goto-char (point-min))
1438     (while (not (re-search-forward regexp nil t))
1439       (accept-process-output (nntp-find-connection nntp-server-buffer))
1440       (set-buffer buf)
1441       (goto-char (point-min)))))
1442
1443
1444 ;; ==========================================================================
1445 ;; Obsolete nntp-open-* connection methods -- drv
1446 ;; ==========================================================================
1447
1448 (defvoo nntp-open-telnet-envuser nil
1449   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1450
1451 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1452   "*Regular expression to match the shell prompt on the remote machine.")
1453
1454 (defvoo nntp-rlogin-program "rsh"
1455   "*Program used to log in on remote machines.
1456 The default is \"rsh\", but \"ssh\" is a popular alternative.")
1457
1458 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1459   "*Parameters to `nntp-open-rlogin'.
1460 That function may be used as `nntp-open-connection-function'.  In that
1461 case, this list will be used as the parameter list given to rsh.")
1462
1463 (defvoo nntp-rlogin-user-name nil
1464   "*User name on remote system when using the rlogin connect method.")
1465
1466 (defvoo nntp-telnet-parameters
1467     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1468   "*Parameters to `nntp-open-telnet'.
1469 That function may be used as `nntp-open-connection-function'.  In that
1470 case, this list will be executed as a command after logging in
1471 via telnet.")
1472
1473 (defvoo nntp-telnet-user-name nil
1474   "User name to log in via telnet with.")
1475
1476 (defvoo nntp-telnet-passwd nil
1477   "Password to use to log in via telnet with.")
1478
1479 (defun nntp-open-telnet (buffer)
1480   (save-excursion
1481     (set-buffer buffer)
1482     (erase-buffer)
1483     (let ((proc (apply
1484                  'start-process
1485                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1486           (case-fold-search t))
1487       (when (memq (process-status proc) '(open run))
1488         (nntp-wait-for-string "^r?telnet")
1489         (process-send-string proc "set escape \^X\n")
1490         (cond
1491          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1492           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1493                                             nntp-address "\n")))
1494          (t
1495           (process-send-string proc (concat "open " nntp-address "\n"))))
1496         (cond
1497          ((not nntp-open-telnet-envuser)
1498           (nntp-wait-for-string "^\r*.?login:")
1499           (process-send-string
1500            proc (concat
1501                  (or nntp-telnet-user-name
1502                      (setq nntp-telnet-user-name (read-string "login: ")))
1503                  "\n"))))
1504         (nntp-wait-for-string "^\r*.?password:")
1505         (process-send-string
1506          proc (concat
1507                (or nntp-telnet-passwd
1508                    (setq nntp-telnet-passwd
1509                          (mail-source-read-passwd "Password: ")))
1510                "\n"))
1511         (nntp-wait-for-string nntp-telnet-shell-prompt)
1512         (process-send-string
1513          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1514         (nntp-wait-for-string "^\r*20[01]")
1515         (beginning-of-line)
1516         (delete-region (point-min) (point))
1517         (process-send-string proc "\^]")
1518         (nntp-wait-for-string "^r?telnet")
1519         (process-send-string proc "mode character\n")
1520         (accept-process-output proc 1)
1521         (sit-for 1)
1522         (goto-char (point-min))
1523         (forward-line 1)
1524         (delete-region (point) (point-max)))
1525       proc)))
1526
1527 (defun nntp-open-rlogin (buffer)
1528   "Open a connection to SERVER using rsh."
1529   (let ((proc (if nntp-rlogin-user-name
1530                   (apply 'start-process
1531                          "nntpd" buffer nntp-rlogin-program
1532                          nntp-address "-l" nntp-rlogin-user-name
1533                          nntp-rlogin-parameters)
1534                 (apply 'start-process
1535                        "nntpd" buffer nntp-rlogin-program nntp-address
1536                        nntp-rlogin-parameters))))
1537     (save-excursion
1538       (set-buffer buffer)
1539       (nntp-wait-for-string "^\r*20[01]")
1540       (beginning-of-line)
1541       (delete-region (point-min) (point))
1542       proc)))
1543
1544
1545 ;; ==========================================================================
1546 ;; Replacements for the nntp-open-* functions -- drv
1547 ;; ==========================================================================
1548
1549 (defun nntp-open-telnet-stream (buffer)
1550   "Open a nntp connection by telnet'ing the news server.
1551
1552 Please refer to the following variables to customize the connection:
1553 - `nntp-pre-command',
1554 - `nntp-telnet-command',
1555 - `nntp-telnet-switches',
1556 - `nntp-address',
1557 - `nntp-port-number',
1558 - `nntp-end-of-line'."
1559   (let ((command `(,nntp-telnet-command
1560                    ,@nntp-telnet-switches
1561                    ,nntp-address ,nntp-port-number))
1562         proc)
1563     (and nntp-pre-command
1564          (push nntp-pre-command command))
1565     (setq proc (apply 'start-process "nntpd" buffer command))
1566     (save-excursion
1567       (set-buffer buffer)
1568       (nntp-wait-for-string "^\r*20[01]")
1569       (beginning-of-line)
1570       (delete-region (point-min) (point))
1571       proc)))
1572
1573 (defun nntp-open-via-rlogin-and-telnet (buffer)
1574   "Open a connection to an nntp server through an intermediate host.
1575 First rlogin to the remote host, and then telnet the real news server
1576 from there.
1577
1578 Please refer to the following variables to customize the connection:
1579 - `nntp-pre-command',
1580 - `nntp-via-rlogin-command',
1581 - `nntp-via-user-name',
1582 - `nntp-via-address',
1583 - `nntp-telnet-command',
1584 - `nntp-telnet-switches',
1585 - `nntp-address',
1586 - `nntp-port-number',
1587 - `nntp-end-of-line'."
1588   (let ((command `(,nntp-via-address
1589                    ,nntp-telnet-command
1590                    ,@nntp-telnet-switches
1591                    ,nntp-address ,nntp-port-number))
1592         proc)
1593     (and nntp-via-user-name
1594          (setq command `("-l" ,nntp-via-user-name ,@command)))
1595     (push nntp-via-rlogin-command command)
1596     (and nntp-pre-command
1597          (push nntp-pre-command command))
1598     (setq proc (apply 'start-process "nntpd" buffer command))
1599     (save-excursion
1600       (set-buffer buffer)
1601       (nntp-wait-for-string "^\r*20[01]")
1602       (beginning-of-line)
1603       (delete-region (point-min) (point))
1604       proc)))
1605
1606 (defun nntp-open-via-telnet-and-telnet (buffer)
1607   "Open a connection to an nntp server through an intermediate host.
1608 First telnet the remote host, and then telnet the real news server
1609 from there.
1610
1611 Please refer to the following variables to customize the connection:
1612 - `nntp-pre-command',
1613 - `nntp-via-telnet-command',
1614 - `nntp-via-telnet-switches',
1615 - `nntp-via-address',
1616 - `nntp-via-envuser',
1617 - `nntp-via-user-name',
1618 - `nntp-via-user-password',
1619 - `nntp-via-shell-prompt',
1620 - `nntp-telnet-command',
1621 - `nntp-telnet-switches',
1622 - `nntp-address',
1623 - `nntp-port-number',
1624 - `nntp-end-of-line'."
1625   (save-excursion
1626     (set-buffer buffer)
1627     (erase-buffer)
1628     (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
1629           (case-fold-search t)
1630           proc)
1631       (and nntp-pre-command (push nntp-pre-command command))
1632       (setq proc (apply 'start-process "nntpd" buffer command))
1633       (when (memq (process-status proc) '(open run))
1634         (nntp-wait-for-string "^r?telnet")
1635         (process-send-string proc "set escape \^X\n")
1636         (cond
1637          ((and nntp-via-envuser nntp-via-user-name)
1638           (process-send-string proc (concat "open " "-l" nntp-via-user-name
1639                                             nntp-via-address "\n")))
1640          (t
1641           (process-send-string proc (concat "open " nntp-via-address
1642                                             "\n"))))
1643         (when (not nntp-via-envuser)
1644           (nntp-wait-for-string "^\r*.?login:")
1645           (process-send-string proc
1646                                (concat
1647                                 (or nntp-via-user-name
1648                                     (setq nntp-via-user-name
1649                                           (read-string "login: ")))
1650                                 "\n")))
1651         (nntp-wait-for-string "^\r*.?password:")
1652         (process-send-string proc
1653                              (concat
1654                               (or nntp-via-user-password
1655                                   (setq nntp-via-user-password
1656                                         (mail-source-read-passwd
1657                                          "Password: ")))
1658                               "\n"))
1659         (nntp-wait-for-string nntp-via-shell-prompt)
1660         (let ((real-telnet-command `("exec"
1661                                      ,nntp-telnet-command
1662                                      ,@nntp-telnet-switches
1663                                      ,nntp-address
1664                                      ,nntp-port-number)))
1665           (process-send-string proc
1666                                (concat (mapconcat 'identity
1667                                                   real-telnet-command " ")
1668                                        "\n")))
1669         (nntp-wait-for-string "^\r*20[01]")
1670         (beginning-of-line)
1671         (delete-region (point-min) (point))
1672         (process-send-string proc "\^]")
1673         (nntp-wait-for-string "^r?telnet")
1674         (process-send-string proc "mode character\n")
1675         (accept-process-output proc 1)
1676         (sit-for 1)
1677         (goto-char (point-min))
1678         (forward-line 1)
1679         (delete-region (point) (point-max)))
1680       proc)))
1681
1682 (provide 'nntp)
1683
1684 ;;; nntp.el ends here