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