(message-get-reply-headers): Bind `extra'.
[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, 2003, 2004 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 (require 'gnus)
33
34 (nnoo-declare nntp)
35
36 (eval-when-compile (require 'cl))
37
38 (defgroup nntp nil
39   "NNTP access for Gnus."
40   :group 'gnus)
41
42 (defvoo nntp-address nil
43   "Address of the physical nntp server.")
44
45 (defvoo nntp-port-number "nntp"
46   "Port number on the physical nntp server.")
47
48 (defvoo nntp-server-opened-hook '(nntp-send-mode-reader)
49   "*Hook used for sending commands to the server at startup.
50 The default value is `nntp-send-mode-reader', which makes an innd
51 server spawn an nnrpd server.")
52
53 (defvoo nntp-authinfo-function 'nntp-send-authinfo
54   "Function used to send AUTHINFO to the server.
55 It is called with no parameters.")
56
57 (defvoo nntp-server-action-alist
58     '(("nntpd 1\\.5\\.11t"
59        (remove-hook 'nntp-server-opened-hook 'nntp-send-mode-reader))
60       ("NNRP server Netscape"
61        (setq nntp-server-list-active-group nil)))
62   "Alist of regexps to match on server types and actions to be taken.
63 For instance, if you want Gnus to beep every time you connect
64 to innd, you could say something like:
65
66 \(setq nntp-server-action-alist
67        '((\"innd\" (ding))))
68
69 You probably don't want to do that, though.")
70
71 (defvoo nntp-open-connection-function 'nntp-open-network-stream
72   "*Function used for connecting to a remote system.
73 It will be called with the buffer to output in as argument.
74
75 Currently, five such functions are provided (please refer to their
76 respective doc string for more information), three of them establishing
77 direct connections to the nntp server, and two of them using an indirect
78 host.
79
80 Direct connections:
81 - `nntp-open-network-stream' (the default),
82 - `nntp-open-ssl-stream',
83 - `nntp-open-tls-stream',
84 - `nntp-open-telnet-stream'.
85
86 Indirect connections:
87 - `nntp-open-via-rlogin-and-telnet',
88 - `nntp-open-via-rlogin-and-netcat',
89 - `nntp-open-via-telnet-and-telnet'.")
90
91 (defvoo nntp-pre-command nil
92   "*Pre-command to use with the various nntp-open-via-* methods.
93 This is where you would put \"runsocks\" or stuff like that.")
94
95 (defvoo nntp-telnet-command "telnet"
96   "*Telnet command used to connect to the nntp server.
97 This command is used by the methods `nntp-open-telnet-stream',
98 `nntp-open-via-rlogin-and-telnet' and `nntp-open-via-telnet-and-telnet'.")
99
100 (defvoo nntp-telnet-switches '("-8")
101   "*Switches given to the telnet command `nntp-telnet-command'.")
102
103 (defvoo nntp-end-of-line "\r\n"
104   "*String to use on the end of lines when talking to the NNTP server.
105 This is \"\\r\\n\" by default, but should be \"\\n\" when using and
106 indirect telnet connection method (nntp-open-via-*-and-telnet).")
107
108 (defvoo nntp-via-rlogin-command "rsh"
109   "*Rlogin command used to connect to an intermediate host.
110 This command is used by the methods `nntp-open-via-rlogin-and-telnet'
111 and `nntp-open-via-rlogin-and-netcat'.  The default is \"rsh\", but \"ssh\"
112 is a popular alternative.")
113
114 (defvoo nntp-via-rlogin-command-switches nil
115   "*Switches given to the rlogin command `nntp-via-rlogin-command'.
116 If you use \"ssh\" for `nntp-via-rlogin-command', you may set this to
117 \(\"-C\") in order to compress all data connections, otherwise set this
118 to \(\"-t\" \"-e\" \"none\") or (\"-C\" \"-t\" \"-e\" \"none\") if the telnet
119 command requires a pseudo-tty allocation on an intermediate host.")
120
121 (defvoo nntp-via-telnet-command "telnet"
122   "*Telnet command used to connect to an intermediate host.
123 This command is used by the `nntp-open-via-telnet-and-telnet' method.")
124
125 (defvoo nntp-via-telnet-switches '("-8")
126   "*Switches given to the telnet command `nntp-via-telnet-command'.")
127
128 (defvoo nntp-via-netcat-command "nc"
129   "*Netcat command used to connect to the nntp server.
130 This command is used by the `nntp-open-via-rlogin-and-netcat' method.")
131
132 (defvoo nntp-via-netcat-switches nil
133   "*Switches given to the netcat command `nntp-via-netcat-command'.")
134
135 (defvoo nntp-via-user-name nil
136   "*User name to log in on an intermediate host with.
137 This variable is used by the various nntp-open-via-* methods.")
138
139 (defvoo nntp-via-user-password nil
140   "*Password to use to log in on an intermediate host with.
141 This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
142
143 (defvoo nntp-via-address nil
144   "*Address of an intermediate host to connect to.
145 This variable is used by the various nntp-open-via-* methods.")
146
147 (defvoo nntp-via-envuser nil
148   "*Whether both telnet client and server support the ENVIRON option.
149 If non-nil, there will be no prompt for a login name.")
150
151 (defvoo nntp-via-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
152   "*Regular expression to match the shell prompt on an intermediate host.
153 This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
154
155 (defvoo nntp-large-newsgroup 50
156   "*The number of articles which indicates a large newsgroup.
157 If the number of articles is greater than the value, verbose
158 messages will be shown to indicate the current status.")
159
160 (defvoo nntp-maximum-request 400
161   "*The maximum number of the requests sent to the NNTP server at one time.
162 If Emacs hangs up while retrieving headers, set the variable to a
163 lower value.")
164
165 (defvoo nntp-nov-is-evil nil
166   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
167
168 (defvoo nntp-xover-commands '("XOVER" "XOVERVIEW")
169   "*List of strings that are used as commands to fetch NOV lines from a server.
170 The strings are tried in turn until a positive response is gotten.  If
171 none of the commands are successful, nntp will just grab headers one
172 by one.")
173
174 (defvoo nntp-nov-gap 5
175   "*Maximum allowed gap between two articles.
176 If the gap between two consecutive articles is bigger than this
177 variable, split the XOVER request into two requests.")
178
179 (defvoo nntp-prepare-server-hook nil
180   "*Hook run before a server is opened.
181 If can be used to set up a server remotely, for instance.  Say you
182 have an account at the machine \"other.machine\".  This machine has
183 access to an NNTP server that you can't access locally.  You could
184 then use this hook to rsh to the remote machine and start a proxy NNTP
185 server there that you can connect to.  See also
186 `nntp-open-connection-function'")
187
188 (defvoo nntp-warn-about-losing-connection t
189   "*If non-nil, beep when a server closes connection.")
190
191 (defvoo nntp-coding-system-for-read 'binary
192   "*Coding system to read from NNTP.")
193
194 (defvoo nntp-coding-system-for-write 'binary
195   "*Coding system to write to NNTP.")
196
197 ;; Marks
198 (defvoo nntp-marks-is-evil nil
199   "*If non-nil, Gnus will never generate and use marks file for nntp groups.
200 See `nnml-marks-is-evil' for more information.")
201
202 (defvoo nntp-marks-file-name ".marks")
203 (defvoo nntp-marks nil)
204 (defvar nntp-marks-modtime (gnus-make-hashtable))
205
206 (defcustom nntp-marks-directory
207   (nnheader-concat gnus-directory "marks/")
208   "*The directory where marks for nntp groups will be stored."
209   :group 'gnus
210   :type 'directory)
211
212 (defcustom nntp-authinfo-file "~/.authinfo"
213   ".netrc-like file that holds nntp authinfo passwords."
214   :group 'nntp
215   :type
216   '(choice file
217            (repeat :tag "Entries"
218                    :menu-tag "Inline"
219                    (list :format "%v"
220                          :value ("" ("login" . "") ("password" . ""))
221                          (string :tag "Host")
222                          (checklist :inline t
223                                     (cons :format "%v"
224                                           (const :format "" "login")
225                                           (string :format "Login: %v"))
226                                     (cons :format "%v"
227                                           (const :format "" "password")
228                                           (string :format "Password: %v")))))))
229
230 \f
231
232 (defvoo nntp-connection-timeout nil
233   "*Number of seconds to wait before an nntp connection times out.
234 If this variable is nil, which is the default, no timers are set.
235 NOTE: This variable is never seen to work in Emacs 20 and XEmacs 21.")
236
237 (defvoo nntp-prepare-post-hook nil
238   "*Hook run just before posting an article.  It is supposed to be used
239 to insert Cancel-Lock headers.")
240
241 ;;; Internal variables.
242
243 (defvar nntp-record-commands nil
244   "*If non-nil, nntp will record all commands in the \"*nntp-log*\" buffer.")
245
246 (defvar nntp-have-messaged nil)
247
248 (defvar nntp-process-wait-for nil)
249 (defvar nntp-process-to-buffer nil)
250 (defvar nntp-process-callback nil)
251 (defvar nntp-process-decode nil)
252 (defvar nntp-process-start-point nil)
253 (defvar nntp-inside-change-function nil)
254 (defvoo nntp-last-command-time nil)
255 (defvoo nntp-last-command nil)
256 (defvoo nntp-authinfo-password nil)
257 (defvoo nntp-authinfo-user nil)
258
259 (defvar nntp-connection-list nil)
260
261 (defvoo nntp-server-type nil)
262 (defvoo nntp-connection-alist nil)
263 (defvoo nntp-status-string "")
264 (defconst nntp-version "nntp 5.0")
265 (defvoo nntp-inhibit-erase nil)
266 (defvoo nntp-inhibit-output nil)
267
268 (defvoo nntp-server-xover 'try)
269 (defvoo nntp-server-list-active-group 'try)
270
271 (defvar nntp-async-needs-kluge
272   (string-match "^GNU Emacs 20\\.3\\." (emacs-version))
273   "*When non-nil, nntp will poll asynchronous connections
274 once a second.  By default, this is turned on only for Emacs
275 20.3, which has a bug that breaks nntp's normal method of
276 noticing asynchronous data.")
277
278 (defvar nntp-async-timer nil)
279 (defvar nntp-async-process-list nil)
280
281 (defvar nntp-ssl-program 
282   "openssl s_client -quiet -ssl3 -connect %s:%p"
283 "A string containing commands for SSL connections.
284 Within a string, %s is replaced with the server address and %p with
285 port number on server.  The program should accept IMAP commands on
286 stdin and return responses to stdout.")
287
288 \f
289
290 ;;; Internal functions.
291
292 (defsubst nntp-send-string (process string)
293   "Send STRING to PROCESS."
294   ;; We need to store the time to provide timeouts, and
295   ;; to store the command so the we can replay the command
296   ;; if the server gives us an AUTHINFO challenge.
297   (setq nntp-last-command-time (current-time)
298         nntp-last-command string)
299   (when nntp-record-commands
300     (nntp-record-command string))
301   (process-send-string process (concat string nntp-end-of-line))
302   (or (memq (process-status process) '(open run))
303       (nntp-report "Server closed connection")))
304
305 (defun nntp-record-command (string)
306   "Record the command STRING."
307   (save-excursion
308     (set-buffer (get-buffer-create "*nntp-log*"))
309     (goto-char (point-max))
310     (let ((time (current-time)))
311       (insert (format-time-string "%Y%m%dT%H%M%S" time)
312               "." (format "%03d" (/ (nth 2 time) 1000))
313               " " nntp-address " " string "\n"))))
314
315 (defun nntp-report (&rest args)
316   "Report an error from the nntp backend.  The first string in ARGS
317 can be a format string.  For some commands, the failed command may be
318 retried once before actually displaying the error report."
319
320   (when nntp-record-commands
321     (nntp-record-command "*** CALLED nntp-report ***"))
322
323   (nnheader-report 'nntp args)
324
325   (apply 'error args))
326
327 (defun nntp-report-1 (&rest args)
328   "Throws out to nntp-with-open-group-error so that the connection may
329 be restored and the command retried."
330
331   (when nntp-record-commands
332     (nntp-record-command "*** CONNECTION LOST ***"))
333
334   (throw 'nntp-with-open-group-error t))
335
336 (defsubst nntp-wait-for (process wait-for buffer &optional decode discard)
337   "Wait for WAIT-FOR to arrive from PROCESS."
338   (save-excursion
339     (set-buffer (process-buffer process))
340     (goto-char (point-min))
341     (while (and (or (not (memq (char-after (point)) '(?2 ?3 ?4 ?5)))
342                     (looking-at "480"))
343                 (memq (process-status process) '(open run)))
344       (when (looking-at "480")
345         (nntp-handle-authinfo process))
346       (when (looking-at "^.*\n")
347         (delete-region (point) (progn (forward-line 1) (point))))
348       (nntp-accept-process-output process)
349       (goto-char (point-min)))
350     (prog1
351         (cond
352          ((looking-at "[45]")
353           (progn
354             (nntp-snarf-error-message)
355             nil))
356          ((not (memq (process-status process) '(open run)))
357           (nntp-report "Server closed connection"))
358          (t
359           (goto-char (point-max))
360           (let ((limit (point-min))
361                 response)
362             (while (not (re-search-backward wait-for limit t))
363               (nntp-accept-process-output process)
364               ;; We assume that whatever we wait for is less than 1000
365               ;; characters long.
366               (setq limit (max (- (point-max) 1000) (point-min)))
367               (goto-char (point-max)))
368             (setq response (match-string 0))
369             (with-current-buffer nntp-server-buffer
370               (setq nntp-process-response response)))
371           (nntp-decode-text (not decode))
372           (unless discard
373             (save-excursion
374               (set-buffer buffer)
375               (goto-char (point-max))
376               (insert-buffer-substring (process-buffer process))
377               ;; Nix out "nntp reading...." message.
378               (when nntp-have-messaged
379                 (setq nntp-have-messaged nil)
380                 (nnheader-message 5 ""))))
381           t))
382       (unless discard
383         (erase-buffer)))))
384
385 (defun nntp-kill-buffer (buffer)
386   (when (buffer-name buffer)
387     (kill-buffer buffer)
388     (nnheader-init-server-buffer)))
389
390 (defun nntp-erase-buffer (buffer)
391   "Erase contents of BUFFER."
392   (with-current-buffer buffer
393     (erase-buffer)))
394
395 (defsubst nntp-find-connection (buffer)
396   "Find the connection delivering to BUFFER."
397   (let ((alist nntp-connection-alist)
398         (buffer (if (stringp buffer) (get-buffer buffer) buffer))
399         process entry)
400     (while (and alist (setq entry (pop alist)))
401       (when (eq buffer (cadr entry))
402         (setq process (car entry)
403               alist nil)))
404     (when process
405       (if (memq (process-status process) '(open run))
406           process
407         (nntp-kill-buffer (process-buffer process))
408         (setq nntp-connection-alist (delq entry nntp-connection-alist))
409         nil))))
410
411 (defsubst nntp-find-connection-entry (buffer)
412   "Return the entry for the connection to BUFFER."
413   (assq (nntp-find-connection buffer) nntp-connection-alist))
414
415 (defun nntp-find-connection-buffer (buffer)
416   "Return the process connection buffer tied to BUFFER."
417   (let ((process (nntp-find-connection buffer)))
418     (when process
419       (process-buffer process))))
420
421 (defsubst nntp-retrieve-data (command address port buffer
422                                       &optional wait-for callback decode)
423   "Use COMMAND to retrieve data into BUFFER from PORT on ADDRESS."
424   (let ((process (or (nntp-find-connection buffer)
425                      (nntp-open-connection buffer))))
426     (if process
427         (progn
428           (unless (or nntp-inhibit-erase nnheader-callback-function)
429             (nntp-erase-buffer (process-buffer process)))
430           (condition-case err
431               (progn
432                 (when command
433                   (nntp-send-string process command))
434                 (cond
435                  ((eq callback 'ignore)
436                   t)
437                  ((and callback wait-for)
438                   (nntp-async-wait process wait-for buffer decode callback)
439                   t)
440                  (wait-for
441                   (nntp-wait-for process wait-for buffer decode))
442                  (t t)))
443             (error
444              (nnheader-report 'nntp "Couldn't open connection to %s: %s"
445                               address err))
446             (quit
447              (message "Quit retrieving data from nntp")
448              (signal 'quit nil)
449              nil)))
450       (nnheader-report 'nntp "Couldn't open connection to %s" address))))
451
452 (defsubst nntp-send-command (wait-for &rest strings)
453   "Send STRINGS to server and wait until WAIT-FOR returns."
454   (when (and (not nnheader-callback-function)
455              (not nntp-inhibit-output))
456     (nntp-erase-buffer nntp-server-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)
467           ;; If nothing to wait for, still remove possibly echo'ed commands.
468           ;; We don't have echos if nntp-open-connection-function
469           ;; is `nntp-open-network-stream', so we skip this in that case.
470           (unless (or wait-for
471                       (equal nntp-open-connection-function
472                              'nntp-open-network-stream))
473             (nntp-accept-response)
474             (save-excursion
475               (set-buffer buffer)
476               (goto-char pos)
477               (if (looking-at (regexp-quote command))
478                   (delete-region pos (progn (forward-line 1)
479                                             (point-at-bol))))
480               )))
481       (nnheader-report 'nntp "Couldn't open connection to %s."
482                        nntp-address))))
483
484 (defun nntp-send-command-nodelete (wait-for &rest strings)
485   "Send STRINGS to server and wait until WAIT-FOR returns."
486   (let* ((command (mapconcat 'identity strings " "))
487          (process (nntp-find-connection nntp-server-buffer))
488          (buffer (and process (process-buffer process)))
489          (pos (and buffer (with-current-buffer buffer (point)))))
490     (if process
491         (prog1
492             (nntp-retrieve-data command
493                                 nntp-address nntp-port-number
494                                 nntp-server-buffer
495                                 wait-for nnheader-callback-function)
496           ;; If nothing to wait for, still remove possibly echo'ed commands
497           (unless wait-for
498             (nntp-accept-response)
499             (save-excursion
500               (set-buffer buffer)
501               (goto-char pos)
502               (if (looking-at (regexp-quote command))
503                   (delete-region pos (progn (forward-line 1)
504                                             (point-at-bol)))))))
505       (nnheader-report 'nntp "Couldn't open connection to %s."
506                        nntp-address))))
507
508 (defun nntp-send-command-and-decode (wait-for &rest strings)
509   "Send STRINGS to server and wait until WAIT-FOR returns."
510   (when (and (not nnheader-callback-function)
511              (not nntp-inhibit-output))
512     (nntp-erase-buffer nntp-server-buffer))
513   (let* ((command (mapconcat 'identity strings " "))
514          (process (nntp-find-connection nntp-server-buffer))
515          (buffer (and process (process-buffer process)))
516          (pos (and buffer (with-current-buffer buffer (point)))))
517     (if process
518         (prog1
519             (nntp-retrieve-data command
520                                 nntp-address nntp-port-number
521                                 nntp-server-buffer
522                                 wait-for nnheader-callback-function t)
523           ;; If nothing to wait for, still remove possibly echo'ed commands
524           (unless wait-for
525             (nntp-accept-response)
526             (save-excursion
527               (set-buffer buffer)
528               (goto-char pos)
529               (if (looking-at (regexp-quote command))
530                   (delete-region pos (progn (forward-line 1) (point-at-bol))))
531               )))
532       (nnheader-report 'nntp "Couldn't open connection to %s."
533                        nntp-address))))
534
535
536 (defun nntp-send-buffer (wait-for)
537   "Send the current buffer to server and wait until WAIT-FOR returns."
538   (when (and (not nnheader-callback-function)
539              (not nntp-inhibit-output))
540     (nntp-erase-buffer
541      (nntp-find-connection-buffer nntp-server-buffer)))
542   (nntp-encode-text)
543   (mm-with-unibyte-current-buffer
544     ;; Some encoded unicode text contains character 0x80-0x9f e.g. Euro.
545     (process-send-region (nntp-find-connection nntp-server-buffer)
546                          (point-min) (point-max)))
547   (nntp-retrieve-data
548    nil nntp-address nntp-port-number nntp-server-buffer
549    wait-for nnheader-callback-function))
550
551 \f
552
553 ;;; Interface functions.
554
555 (nnoo-define-basics nntp)
556
557 (defsubst nntp-next-result-arrived-p ()
558   (cond
559    ;; A result that starts with a 2xx code is terminated by
560    ;; a line with only a "." on it.
561    ((eq (char-after) ?2)
562     (if (re-search-forward "\n\\.\r?\n" nil t)
563         t
564       nil))
565    ;; A result that starts with a 3xx or 4xx code is terminated
566    ;; by a newline.
567    ((looking-at "[34]")
568     (if (search-forward "\n" nil t)
569         t
570       nil))
571    ;; No result here.
572    (t
573     nil)))
574
575 (eval-when-compile
576   (defvar nntp-with-open-group-internal nil)
577   (defvar nntp-report-n nil))
578
579 (defmacro nntp-with-open-group (group server &optional connectionless &rest forms)
580   "Protect against servers that don't like clients that keep idle connections opens.
581 The problem being that these servers may either close a connection or
582 simply ignore any further requests on a connection.  Closed
583 connections are not detected until accept-process-output has updated
584 the process-status.  Dropped connections are not detected until the
585 connection timeouts (which may be several minutes) or
586 nntp-connection-timeout has expired.  When these occur
587 nntp-with-open-group, opens a new connection then re-issues the NNTP
588 command whose response triggered the error."
589   (when (and (listp connectionless)
590              (not (eq connectionless nil)))
591     (setq forms (cons connectionless forms)
592           connectionless nil))
593   `(letf ((nntp-report-n (symbol-function 'nntp-report))
594           ((symbol-function 'nntp-report) (symbol-function 'nntp-report-1))
595           (nntp-with-open-group-internal nil))
596      (while (catch 'nntp-with-open-group-error
597               ;; Open the connection to the server
598               ;; NOTE: Existing connections are NOT tested.
599               (nntp-possibly-change-group ,group ,server ,connectionless)
600
601               (let ((timer
602                      (and nntp-connection-timeout
603                           (run-at-time
604                            nntp-connection-timeout nil
605                            '(lambda ()
606                               (let ((process (nntp-find-connection
607                                               nntp-server-buffer))
608                                     (buffer  (and process
609                                                   (process-buffer process))))
610                                 ;; When I an able to identify the
611                                 ;; connection to the server AND I've
612                                 ;; received NO reponse for
613                                 ;; nntp-connection-timeout seconds.
614                                 (when (and buffer (eq 0 (buffer-size buffer)))
615                                   ;; Close the connection.  Take no
616                                   ;; other action as the accept input
617                                   ;; code will handle the closed
618                                   ;; connection.
619                                   (nntp-kill-buffer buffer))))))))
620                 (unwind-protect
621                     (setq nntp-with-open-group-internal
622                           (condition-case nil
623                               (progn ,@forms)
624                             (quit
625                              (nntp-close-server)
626                              (signal 'quit nil))))
627                   (when timer
628                     (nnheader-cancel-timer timer)))
629                 nil))
630        (setf (symbol-function 'nntp-report) nntp-report-n))
631      nntp-with-open-group-internal))
632
633 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
634   "Retrieve the headers of ARTICLES."
635   (nntp-with-open-group
636    group server
637    (save-excursion
638      (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
639      (erase-buffer)
640      (if (and (not gnus-nov-is-evil)
641               (not nntp-nov-is-evil)
642               (nntp-retrieve-headers-with-xover articles fetch-old))
643          ;; We successfully retrieved the headers via XOVER.
644          'nov
645        ;; XOVER didn't work, so we do it the hard, slow and inefficient
646        ;; way.
647        (let ((number (length articles))
648              (articles articles)
649              (count 0)
650              (received 0)
651              (last-point (point-min))
652              (buf (nntp-find-connection-buffer nntp-server-buffer))
653              (nntp-inhibit-erase t)
654              article)
655          ;; Send HEAD commands.
656          (while (setq article (pop articles))
657            (nntp-send-command
658             nil
659             "HEAD" (if (numberp article)
660                        (int-to-string article)
661                      ;; `articles' is either a list of article numbers
662                      ;; or a list of article IDs.
663                      article))
664            (incf count)
665            ;; Every 400 requests we have to read the stream in
666            ;; order to avoid deadlocks.
667            (when (or (null articles)    ;All requests have been sent.
668                      (zerop (% count nntp-maximum-request)))
669              (nntp-accept-response)
670              (while (progn
671                       (set-buffer buf)
672                       (goto-char last-point)
673                       ;; Count replies.
674                       (while (nntp-next-result-arrived-p)
675                         (setq last-point (point))
676                         (incf received))
677                       (< received count))
678                ;; If number of headers is greater than 100, give
679                ;;  informative messages.
680                (and (numberp nntp-large-newsgroup)
681                     (> number nntp-large-newsgroup)
682                     (zerop (% received 20))
683                     (nnheader-message 6 "NNTP: Receiving headers... %d%%"
684                                       (/ (* received 100) number)))
685                (nntp-accept-response))))
686          (and (numberp nntp-large-newsgroup)
687               (> number nntp-large-newsgroup)
688               (nnheader-message 6 "NNTP: Receiving headers...done"))
689
690          ;; Now all of replies are received.  Fold continuation lines.
691          (nnheader-fold-continuation-lines)
692          ;; Remove all "\r"'s.
693          (nnheader-strip-cr)
694          (copy-to-buffer nntp-server-buffer (point-min) (point-max))
695          'headers)))))
696
697 (deffoo nntp-retrieve-groups (groups &optional server)
698   "Retrieve group info on GROUPS."
699   (nntp-with-open-group
700    nil server
701    (when (nntp-find-connection-buffer nntp-server-buffer)
702      (catch 'done
703        (save-excursion
704          ;; Erase nntp-server-buffer before nntp-inhibit-erase.
705          (nntp-erase-buffer nntp-server-buffer)
706          (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
707          ;; The first time this is run, this variable is `try'.  So we
708          ;; try.
709          (when (eq nntp-server-list-active-group 'try)
710            (nntp-try-list-active (car groups)))
711          (erase-buffer)
712          (let ((count 0)
713                (groups groups)
714                (received 0)
715                (last-point (point-min))
716                (nntp-inhibit-erase t)
717                (buf (nntp-find-connection-buffer nntp-server-buffer))
718                (command (if nntp-server-list-active-group
719                             "LIST ACTIVE" "GROUP")))
720            (while groups
721              ;; Timeout may have killed the buffer.
722              (unless (gnus-buffer-live-p buf)
723                (nnheader-report 'nntp "Connection to %s is closed." server)
724                (throw 'done nil))
725              ;; Send the command to the server.
726              (nntp-send-command nil command (pop groups))
727              (incf count)
728              ;; Every 400 requests we have to read the stream in
729              ;; order to avoid deadlocks.
730              (when (or (null groups)    ;All requests have been sent.
731                        (zerop (% count nntp-maximum-request)))
732                (nntp-accept-response)
733                (while (and (gnus-buffer-live-p buf)
734                            (progn
735                              ;; Search `blue moon' in this file for the
736                              ;; reason why set-buffer here.
737                              (set-buffer buf)
738                              (goto-char last-point)
739                              ;; Count replies.
740                              (while (re-search-forward "^[0-9]" nil t)
741                                (incf received))
742                              (setq last-point (point))
743                              (< received count)))
744                  (nntp-accept-response))))
745
746            ;; Wait for the reply from the final command.
747            (unless (gnus-buffer-live-p buf)
748              (nnheader-report 'nntp "Connection to %s is closed." server)
749              (throw 'done nil))
750            (set-buffer buf)
751            (goto-char (point-max))
752            (re-search-backward "^[0-9]" nil t)
753            (when (looking-at "^[23]")
754              (while (and (gnus-buffer-live-p buf)
755                          (progn
756                            (set-buffer buf)
757                            (goto-char (point-max))
758                            (if (not nntp-server-list-active-group)
759                                (not (re-search-backward "\r?\n"
760                                                         (- (point) 3) t))
761                              (not (re-search-backward "^\\.\r?\n"
762                                                       (- (point) 4) t)))))
763                (nntp-accept-response)))
764
765            ;; Now all replies are received.  We remove CRs.
766            (unless (gnus-buffer-live-p buf)
767              (nnheader-report 'nntp "Connection to %s is closed." server)
768              (throw 'done nil))
769            (set-buffer buf)
770            (goto-char (point-min))
771            (while (search-forward "\r" nil t)
772              (replace-match "" t t))
773
774            (if (not nntp-server-list-active-group)
775                (progn
776                  (copy-to-buffer nntp-server-buffer (point-min) (point-max))
777                  'group)
778              ;; We have read active entries, so we just delete the
779              ;; superfluous gunk.
780              (goto-char (point-min))
781              (while (re-search-forward "^[.2-5]" nil t)
782                (delete-region (match-beginning 0)
783                               (progn (forward-line 1) (point))))
784              (copy-to-buffer nntp-server-buffer (point-min) (point-max))
785              'active)))))))
786
787 (deffoo nntp-retrieve-articles (articles &optional group server)
788   (nntp-with-open-group
789     group server
790    (save-excursion
791      (let ((number (length articles))
792            (articles articles)
793            (count 0)
794            (received 0)
795            (last-point (point-min))
796            (buf (nntp-find-connection-buffer nntp-server-buffer))
797            (nntp-inhibit-erase t)
798            (map (apply 'vector articles))
799            (point 1)
800            article)
801        (set-buffer buf)
802        (erase-buffer)
803        ;; Send ARTICLE command.
804        (while (setq article (pop articles))
805          (nntp-send-command
806           nil
807           "ARTICLE" (if (numberp article)
808                         (int-to-string article)
809                       ;; `articles' is either a list of article numbers
810                       ;; or a list of article IDs.
811                       article))
812          (incf count)
813          ;; Every 400 requests we have to read the stream in
814          ;; order to avoid deadlocks.
815          (when (or (null articles)      ;All requests have been sent.
816                    (zerop (% count nntp-maximum-request)))
817            (nntp-accept-response)
818            (while (progn
819                     (set-buffer buf)
820                     (goto-char last-point)
821                     ;; Count replies.
822                     (while (nntp-next-result-arrived-p)
823                       (aset map received (cons (aref map received) (point)))
824                       (setq last-point (point))
825                       (incf received))
826                     (< received count))
827              ;; If number of headers is greater than 100, give
828              ;;  informative messages.
829              (and (numberp nntp-large-newsgroup)
830                   (> number nntp-large-newsgroup)
831                   (zerop (% received 20))
832                   (nnheader-message 6 "NNTP: Receiving articles... %d%%"
833                                     (/ (* received 100) number)))
834              (nntp-accept-response))))
835        (and (numberp nntp-large-newsgroup)
836             (> number nntp-large-newsgroup)
837             (nnheader-message 6 "NNTP: Receiving articles...done"))
838
839        ;; Now we have all the responses.  We go through the results,
840        ;; wash it and copy it over to the server buffer.
841        (set-buffer nntp-server-buffer)
842        (erase-buffer)
843        (setq last-point (point-min))
844        (mapcar
845         (lambda (entry)
846           (narrow-to-region
847            (setq point (goto-char (point-max)))
848            (progn
849              (insert-buffer-substring buf last-point (cdr entry))
850              (point-max)))
851           (setq last-point (cdr entry))
852           (nntp-decode-text)
853           (widen)
854           (cons (car entry) point))
855         map)))))
856
857 (defun nntp-try-list-active (group)
858   (nntp-list-active-group group)
859   (save-excursion
860     (set-buffer nntp-server-buffer)
861     (goto-char (point-min))
862     (cond ((or (eobp)
863                (looking-at "5[0-9]+"))
864            (setq nntp-server-list-active-group nil))
865           (t
866            (setq nntp-server-list-active-group t)))))
867
868 (deffoo nntp-list-active-group (group &optional server)
869   "Return the active info on GROUP (which can be a regexp)."
870   (nntp-with-open-group
871    nil server
872    (nntp-send-command "^\\.*\r?\n" "LIST ACTIVE" group)))
873
874 (deffoo nntp-request-group-articles (group &optional server)
875   "Return the list of existing articles in GROUP."
876   (nntp-with-open-group
877    nil server
878    (nntp-send-command "^\\.*\r?\n" "LISTGROUP" group)))
879
880 (deffoo nntp-request-article (article &optional group server buffer command)
881   (nntp-with-open-group
882     group server
883     (when (nntp-send-command-and-decode
884            "\r?\n\\.\r?\n" "ARTICLE"
885            (if (numberp article) (int-to-string article) article))
886       (if (and buffer
887                (not (equal buffer nntp-server-buffer)))
888           (save-excursion
889             (set-buffer nntp-server-buffer)
890             (copy-to-buffer buffer (point-min) (point-max))
891             (nntp-find-group-and-number group))
892         (nntp-find-group-and-number group)))))
893
894 (deffoo nntp-request-head (article &optional group server)
895   (nntp-with-open-group
896    group server
897    (when (nntp-send-command
898           "\r?\n\\.\r?\n" "HEAD"
899           (if (numberp article) (int-to-string article) article))
900      (prog1
901          (nntp-find-group-and-number group)
902        (nntp-decode-text)))))
903
904 (deffoo nntp-request-body (article &optional group server)
905   (nntp-with-open-group
906    group server
907    (nntp-send-command-and-decode
908     "\r?\n\\.\r?\n" "BODY"
909     (if (numberp article) (int-to-string article) article))))
910
911 (deffoo nntp-request-group (group &optional server dont-check)
912   (nntp-with-open-group 
913     nil server
914     (when (nntp-send-command "^[245].*\n" "GROUP" group)
915       (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
916         (setcar (cddr entry) group)))))
917
918 (deffoo nntp-close-group (group &optional server)
919   t)
920
921 (deffoo nntp-server-opened (&optional server)
922   "Say whether a connection to SERVER has been opened."
923   (and (nnoo-current-server-p 'nntp server)
924        nntp-server-buffer
925        (gnus-buffer-live-p nntp-server-buffer)
926        (nntp-find-connection nntp-server-buffer)))
927
928 (deffoo nntp-open-server (server &optional defs connectionless)
929   (nnheader-init-server-buffer)
930   (if (nntp-server-opened server)
931       t
932     (when (or (stringp (car defs))
933               (numberp (car defs)))
934       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
935     (unless (assq 'nntp-address defs)
936       (setq defs (append defs (list (list 'nntp-address server)))))
937     (nnoo-change-server 'nntp server defs)
938     (unless connectionless
939       (or (nntp-find-connection nntp-server-buffer)
940           (nntp-open-connection nntp-server-buffer)))))
941
942 (deffoo nntp-close-server (&optional server)
943   (nntp-possibly-change-group nil server t)
944   (let ((process (nntp-find-connection nntp-server-buffer)))
945     (while process
946       (when (memq (process-status process) '(open run))
947         (ignore-errors
948           (nntp-send-string process "QUIT")
949           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
950             ;; Ok, this is evil, but when using telnet and stuff
951             ;; as the connection method, it's important that the
952             ;; QUIT command actually is sent out before we kill
953             ;; the process.
954             (sleep-for 1))))
955       (nntp-kill-buffer (process-buffer process))
956       (setq process (car (pop nntp-connection-alist))))
957     (nnoo-close-server 'nntp)))
958
959 (deffoo nntp-request-close ()
960   (let (process)
961     (while (setq process (pop nntp-connection-list))
962       (when (memq (process-status process) '(open run))
963         (ignore-errors
964           (nntp-send-string process "QUIT")
965           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
966             ;; Ok, this is evil, but when using telnet and stuff
967             ;; as the connection method, it's important that the
968             ;; QUIT command actually is sent out before we kill
969             ;; the process.
970             (sleep-for 1))))
971       (nntp-kill-buffer (process-buffer process)))))
972
973 (deffoo nntp-request-list (&optional server)
974   (nntp-with-open-group
975    nil server
976    (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST")))
977
978 (deffoo nntp-request-list-newsgroups (&optional server)
979   (nntp-with-open-group
980    nil server
981    (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS")))
982
983 (deffoo nntp-request-newgroups (date &optional server)
984   (nntp-with-open-group
985    nil server
986    (save-excursion
987      (set-buffer nntp-server-buffer)
988      (let* ((time (date-to-time date))
989             (ls (- (cadr time) (nth 8 (decode-time time)))))
990        (cond ((< ls 0)
991               (setcar time (1- (car time)))
992               (setcar (cdr time) (+ ls 65536)))
993              ((>= ls 65536)
994               (setcar time (1+ (car time)))
995               (setcar (cdr time) (- ls 65536)))
996              (t
997               (setcar (cdr time) ls)))
998        (prog1
999            (nntp-send-command
1000             "^\\.\r?\n" "NEWGROUPS"
1001             (format-time-string "%y%m%d %H%M%S" time)
1002             "GMT")
1003          (nntp-decode-text))))))