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