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