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