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