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