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