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