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