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