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