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