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