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