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