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