nntp.el (nntp-send-authinfo): Work for secure nntp entry in authinfo.
[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                 (gnus-groups-to-gnus-format method gnus-active-hashtb t))
813             ;; We have read active entries, so we just delete the
814             ;; superfluous gunk.
815             (goto-char (point-min))
816             (while (re-search-forward "^[.2-5]" nil t)
817               (delete-region (match-beginning 0)
818                              (progn (forward-line 1) (point))))
819             (nntp-copy-to-buffer nntp-server-buffer (point-min) (point-max))
820             (with-current-buffer nntp-server-buffer
821               (gnus-active-to-gnus-format
822                ;; Kludge to use the extended method name if you have
823                ;; an extended one.
824                (if (consp (gnus-info-method (car infos)))
825                    (gnus-info-method (car infos))
826                  method)
827                gnus-active-hashtb nil t))))))))
828
829 (deffoo nntp-retrieve-groups (groups &optional server)
830   "Retrieve group info on GROUPS."
831   (nntp-with-open-group
832    nil server
833    (when (and (nntp-find-connection-buffer nntp-server-buffer)
834               (with-current-buffer
835                   (nntp-find-connection-buffer nntp-server-buffer)
836                 (if (not nntp-retrieval-in-progress)
837                     t
838                   (message "Warning: Refusing to do retrieval from %s because a retrieval is already happening"
839                            server)
840                   nil)))
841      (catch 'done
842        (save-excursion
843          ;; Erase nntp-server-buffer before nntp-inhibit-erase.
844          (nntp-erase-buffer nntp-server-buffer)
845          (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
846          ;; The first time this is run, this variable is `try'.  So we
847          ;; try.
848          (when (eq nntp-server-list-active-group 'try)
849            (nntp-try-list-active (car groups)))
850          (erase-buffer)
851          (let ((count 0)
852                (groups groups)
853                (received 0)
854                (last-point (point-min))
855                (nntp-inhibit-erase t)
856                (buf (nntp-find-connection-buffer nntp-server-buffer))
857                (command (if nntp-server-list-active-group
858                             "LIST ACTIVE" "GROUP")))
859            (while groups
860              ;; Timeout may have killed the buffer.
861              (unless (gnus-buffer-live-p buf)
862                (nnheader-report 'nntp "Connection to %s is closed." server)
863                (throw 'done nil))
864              ;; Send the command to the server.
865              (nntp-send-command nil command (pop groups))
866              (incf count)
867              ;; Every 400 requests we have to read the stream in
868              ;; order to avoid deadlocks.
869              (when (or (null groups)    ;All requests have been sent.
870                        (zerop (% count nntp-maximum-request)))
871                (nntp-accept-response)
872                (while (and (gnus-buffer-live-p buf)
873                            (progn
874                              ;; Search `blue moon' in this file for the
875                              ;; reason why set-buffer here.
876                              (set-buffer buf)
877                              (goto-char last-point)
878                              ;; Count replies.
879                              (while (re-search-forward "^[0-9]" nil t)
880                                (incf received))
881                              (setq last-point (point))
882                              (< received count)))
883                  (nntp-accept-response))))
884
885            ;; Wait for the reply from the final command.
886            (unless (gnus-buffer-live-p buf)
887              (nnheader-report 'nntp "Connection to %s is closed." server)
888              (throw 'done nil))
889            (set-buffer buf)
890            (goto-char (point-max))
891            (re-search-backward "^[0-9]" nil t)
892            (when (looking-at "^[23]")
893              (while (and (gnus-buffer-live-p buf)
894                          (progn
895                            (set-buffer buf)
896                            (goto-char (point-max))
897                            (if (not nntp-server-list-active-group)
898                                (not (re-search-backward "\r?\n"
899                                                         (- (point) 3) t))
900                              (not (re-search-backward "^\\.\r?\n"
901                                                       (- (point) 4) t)))))
902                (nntp-accept-response)))
903
904            ;; Now all replies are received.  We remove CRs.
905            (unless (gnus-buffer-live-p buf)
906              (nnheader-report 'nntp "Connection to %s is closed." server)
907              (throw 'done nil))
908            (set-buffer buf)
909            (goto-char (point-min))
910            (while (search-forward "\r" nil t)
911              (replace-match "" t t))
912
913            (if (not nntp-server-list-active-group)
914                (progn
915                  (nntp-copy-to-buffer nntp-server-buffer
916                                       (point-min) (point-max))
917                  'group)
918              ;; We have read active entries, so we just delete the
919              ;; superfluous gunk.
920              (goto-char (point-min))
921              (while (re-search-forward "^[.2-5]" nil t)
922                (delete-region (match-beginning 0)
923                               (progn (forward-line 1) (point))))
924              (nntp-copy-to-buffer nntp-server-buffer (point-min) (point-max))
925              'active)))))))
926
927 (deffoo nntp-retrieve-articles (articles &optional group server)
928   (nntp-with-open-group
929     group server
930    (save-excursion
931      (let ((number (length articles))
932            (articles articles)
933            (count 0)
934            (received 0)
935            (last-point (point-min))
936            (buf (nntp-find-connection-buffer nntp-server-buffer))
937            (nntp-inhibit-erase t)
938            (map (apply 'vector articles))
939            (point 1)
940            article)
941        (set-buffer buf)
942        (erase-buffer)
943        ;; Send ARTICLE command.
944        (while (setq article (pop articles))
945          (nntp-send-command
946           nil
947           "ARTICLE" (if (numberp article)
948                         (int-to-string article)
949                       ;; `articles' is either a list of article numbers
950                       ;; or a list of article IDs.
951                       article))
952          (incf count)
953          ;; Every 400 requests we have to read the stream in
954          ;; order to avoid deadlocks.
955          (when (or (null articles)      ;All requests have been sent.
956                    (zerop (% count nntp-maximum-request)))
957            (nntp-accept-response)
958            (while (progn
959                     (set-buffer buf)
960                     (goto-char last-point)
961                     ;; Count replies.
962                     (while (nntp-next-result-arrived-p)
963                       (aset map received (cons (aref map received) (point)))
964                       (setq last-point (point))
965                       (incf received))
966                     (< received count))
967              ;; If number of headers is greater than 100, give
968              ;;  informative messages.
969              (and (numberp nntp-large-newsgroup)
970                   (> number nntp-large-newsgroup)
971                   (zerop (% received 20))
972                   (nnheader-message 6 "NNTP: Receiving articles... %d%%"
973                                     (/ (* received 100) number)))
974              (nntp-accept-response))))
975        (and (numberp nntp-large-newsgroup)
976             (> number nntp-large-newsgroup)
977             (nnheader-message 6 "NNTP: Receiving articles...done"))
978
979        ;; Now we have all the responses.  We go through the results,
980        ;; wash it and copy it over to the server buffer.
981        (set-buffer nntp-server-buffer)
982        (erase-buffer)
983        (setq last-point (point-min))
984        (mapcar
985         (lambda (entry)
986           (narrow-to-region
987            (setq point (goto-char (point-max)))
988            (progn
989              (nnheader-insert-buffer-substring buf last-point (cdr entry))
990              (point-max)))
991           (setq last-point (cdr entry))
992           (nntp-decode-text)
993           (widen)
994           (cons (car entry) point))
995         map)))))
996
997 (defun nntp-try-list-active (group)
998   (nntp-list-active-group group)
999   (with-current-buffer nntp-server-buffer
1000     (goto-char (point-min))
1001     (cond ((or (eobp)
1002                (looking-at "5[0-9]+"))
1003            (setq nntp-server-list-active-group nil))
1004           (t
1005            (setq nntp-server-list-active-group t)))))
1006
1007 (deffoo nntp-list-active-group (group &optional server)
1008   "Return the active info on GROUP (which can be a regexp)."
1009   (nntp-with-open-group
1010    nil server
1011    (nntp-send-command "^\\.*\r?\n" "LIST ACTIVE" group)))
1012
1013 (deffoo nntp-request-group-articles (group &optional server)
1014   "Return the list of existing articles in GROUP."
1015   (nntp-with-open-group
1016    nil server
1017    (nntp-send-command "^\\.*\r?\n" "LISTGROUP" group)))
1018
1019 (deffoo nntp-request-article (article &optional group server buffer command)
1020   (nntp-with-open-group
1021       group server
1022     (when (nntp-send-command-and-decode
1023            "\r?\n\\.\r?\n" "ARTICLE"
1024            (if (numberp article) (int-to-string article) article))
1025       (when (and buffer
1026                  (not (equal buffer nntp-server-buffer)))
1027         (with-current-buffer nntp-server-buffer
1028           (copy-to-buffer buffer (point-min) (point-max))))
1029       (nntp-find-group-and-number group))))
1030
1031 (deffoo nntp-request-head (article &optional group server)
1032   (nntp-with-open-group
1033    group server
1034    (when (nntp-send-command
1035           "\r?\n\\.\r?\n" "HEAD"
1036           (if (numberp article) (int-to-string article) article))
1037      (prog1
1038          (nntp-find-group-and-number group)
1039        (nntp-decode-text)))))
1040
1041 (deffoo nntp-request-body (article &optional group server)
1042   (nntp-with-open-group
1043    group server
1044    (nntp-send-command-and-decode
1045     "\r?\n\\.\r?\n" "BODY"
1046     (if (numberp article) (int-to-string article) article))))
1047
1048 (deffoo nntp-request-group (group &optional server dont-check info)
1049   (nntp-with-open-group
1050     nil server
1051     (when (nntp-send-command "^[245].*\n" "GROUP" group)
1052       (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1053         (setcar (cddr entry) group)))))
1054
1055 (deffoo nntp-close-group (group &optional server)
1056   t)
1057
1058 (deffoo nntp-server-opened (&optional server)
1059   "Say whether a connection to SERVER has been opened."
1060   (and (nnoo-current-server-p 'nntp server)
1061        nntp-server-buffer
1062        (gnus-buffer-live-p nntp-server-buffer)
1063        (nntp-find-connection nntp-server-buffer)))
1064
1065 (deffoo nntp-open-server (server &optional defs connectionless)
1066   (nnheader-init-server-buffer)
1067   (if (nntp-server-opened server)
1068       t
1069     (when (or (stringp (car defs))
1070               (numberp (car defs)))
1071       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
1072     (unless (assq 'nntp-address defs)
1073       (setq defs (append defs (list (list 'nntp-address server)))))
1074     (nnoo-change-server 'nntp server defs)
1075     (if connectionless
1076         t
1077       (or (nntp-find-connection nntp-server-buffer)
1078           (nntp-open-connection nntp-server-buffer)))))
1079
1080 (deffoo nntp-close-server (&optional server)
1081   (nntp-possibly-change-group nil server t)
1082   (let ((process (nntp-find-connection nntp-server-buffer)))
1083     (while process
1084       (when (memq (process-status process) '(open run))
1085         (ignore-errors
1086           (nntp-send-string process "QUIT")
1087           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
1088             ;; Ok, this is evil, but when using telnet and stuff
1089             ;; as the connection method, it's important that the
1090             ;; QUIT command actually is sent out before we kill
1091             ;; the process.
1092             (sleep-for 1))))
1093       (nntp-kill-buffer (process-buffer process))
1094       (setq process (car (pop nntp-connection-alist))))
1095     (nnoo-close-server 'nntp)))
1096
1097 (deffoo nntp-request-close ()
1098   (let (process)
1099     (while (setq process (pop nntp-connection-list))
1100       (when (memq (process-status process) '(open run))
1101         (ignore-errors
1102           (nntp-send-string process "QUIT")
1103           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
1104             ;; Ok, this is evil, but when using telnet and stuff
1105             ;; as the connection method, it's important that the
1106             ;; QUIT command actually is sent out before we kill
1107             ;; the process.
1108             (sleep-for 1))))
1109       (nntp-kill-buffer (process-buffer process)))))
1110
1111 (deffoo nntp-request-list (&optional server)
1112   (nntp-with-open-group
1113    nil server
1114    (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST")))
1115
1116 (deffoo nntp-request-list-newsgroups (&optional server)
1117   (nntp-with-open-group
1118    nil server
1119    (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS")))
1120
1121 (deffoo nntp-request-newgroups (date &optional server)
1122   (nntp-with-open-group
1123    nil server
1124    (with-current-buffer nntp-server-buffer
1125      (let* ((time (date-to-time date))
1126             (ls (- (cadr time) (nth 8 (decode-time time)))))
1127        (cond ((< ls 0)
1128               (setcar time (1- (car time)))
1129               (setcar (cdr time) (+ ls 65536)))
1130              ((>= ls 65536)
1131               (setcar time (1+ (car time)))
1132               (setcar (cdr time) (- ls 65536)))
1133              (t
1134               (setcar (cdr time) ls)))
1135        (prog1
1136            (nntp-send-command
1137             "^\\.\r?\n" "NEWGROUPS"
1138             (format-time-string "%y%m%d %H%M%S" time)
1139             "GMT")
1140          (nntp-decode-text))))))
1141
1142 (deffoo nntp-request-post (&optional server)
1143   (nntp-with-open-group
1144    nil server
1145    (when (nntp-send-command "^[23].*\r?\n" "POST")
1146      (let ((response (with-current-buffer nntp-server-buffer
1147                        nntp-process-response))
1148            server-id)
1149        (when (and response
1150                   (string-match "^[23].*\\(<[^\t\n @<>]+@[^\t\n @<>]+>\\)"
1151                                 response))
1152          (setq server-id (match-string 1 response))
1153          (narrow-to-region (goto-char (point-min))
1154                            (if (search-forward "\n\n" nil t)
1155                                (1- (point))
1156                              (point-max)))
1157          (unless (mail-fetch-field "Message-ID")
1158            (goto-char (point-min))
1159            (insert "Message-ID: " server-id "\n"))
1160          (widen))
1161        (run-hooks 'nntp-prepare-post-hook)
1162        (nntp-send-buffer "^[23].*\n")))))
1163
1164 (deffoo nntp-request-type (group article)
1165   'news)
1166
1167 (deffoo nntp-asynchronous-p ()
1168   t)
1169
1170
1171 ;;; Hooky functions.
1172
1173 (defun nntp-send-mode-reader ()
1174   "Send the MODE READER command to the nntp server.
1175 This function is supposed to be called from `nntp-server-opened-hook'.
1176 It will make innd servers spawn an nnrpd process to allow actual article
1177 reading."
1178   (nntp-send-command "^.*\n" "MODE READER"))
1179
1180 (declare-function netrc-parse "netrc" (&optional file))
1181 (declare-function netrc-machine "netrc"
1182                   (list machine &optional port defaultport))
1183 (declare-function netrc-get "netrc" (alist type))
1184
1185 (defun nntp-send-authinfo (&optional send-if-force)
1186   "Send the AUTHINFO to the nntp server.
1187 It will look in the \"~/.authinfo\" file for matching entries.  If
1188 nothing suitable is found there, it will prompt for a user name
1189 and a password.
1190
1191 If SEND-IF-FORCE, only send authinfo to the server if the
1192 .authinfo file has the FORCE token."
1193   (require 'netrc)
1194   (let* ((list (netrc-parse nntp-authinfo-file))
1195          (alist (netrc-machine list nntp-address "nntp"))
1196          (auth-info
1197           (nth 0 (auth-source-search
1198                   :max 1
1199                   :host (list nntp-address
1200                               (nnoo-current-server 'nntp))
1201                   :port (or (cdr (assoc (format "%s" nntp-port-number)
1202                                         '(("563" . ("563" "nntps" "snews")))))
1203                             '("119" "nntp")))))
1204          (auth-user (plist-get auth-info :user))
1205          (auth-force (plist-get auth-info :force))
1206          (auth-passwd (plist-get auth-info :secret))
1207          (auth-passwd (if (functionp auth-passwd)
1208                           (funcall auth-passwd)
1209                         auth-passwd))
1210          (force (or (netrc-get alist "force")
1211                     nntp-authinfo-force
1212                     auth-force))
1213          (user (or
1214                 ;; this is preferred to netrc-*
1215                 auth-user
1216                 (netrc-get alist "login")
1217                 nntp-authinfo-user))
1218          (passwd (or
1219                   ;; this is preferred to netrc-*
1220                   auth-passwd
1221                   (netrc-get alist "password"))))
1222     (when (or (not send-if-force)
1223               force)
1224       (unless user
1225         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
1226               nntp-authinfo-user user))
1227       (unless (member user '(nil ""))
1228         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1229         (when t                         ;???Should check if AUTHINFO succeeded
1230           (nntp-send-command
1231            "^2.*\r?\n" "AUTHINFO PASS"
1232            (or passwd
1233                nntp-authinfo-password
1234                (setq nntp-authinfo-password
1235                      (read-passwd (format "NNTP (%s@%s) password: "
1236                                           user nntp-address))))))))))
1237
1238 (defun nntp-send-nosy-authinfo ()
1239   "Send the AUTHINFO to the nntp server."
1240   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
1241     (unless (member user '(nil ""))
1242       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1243       (when t                           ;???Should check if AUTHINFO succeeded
1244         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
1245                            (read-passwd (format "NNTP (%s@%s) password: "
1246                                                 user nntp-address)))))))
1247
1248 (defun nntp-send-authinfo-from-file ()
1249   "Send the AUTHINFO to the nntp server.
1250
1251 The authinfo login name is taken from the user's login name and the
1252 password contained in '~/.nntp-authinfo'."
1253   (when (file-exists-p "~/.nntp-authinfo")
1254     (with-temp-buffer
1255       (insert-file-contents "~/.nntp-authinfo")
1256       (goto-char (point-min))
1257       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
1258       (nntp-send-command
1259        "^2.*\r?\n" "AUTHINFO PASS"
1260        (buffer-substring (point) (point-at-eol))))))
1261
1262 ;;; Internal functions.
1263
1264 (defun nntp-handle-authinfo (process)
1265   "Take care of an authinfo response from the server."
1266   (let ((last nntp-last-command))
1267     (funcall nntp-authinfo-function)
1268     ;; We have to re-send the function that was interrupted by
1269     ;; the authinfo request.
1270     (nntp-erase-buffer nntp-server-buffer)
1271     (nntp-send-string process last)))
1272
1273 (defun nntp-make-process-buffer (buffer)
1274   "Create a new, fresh buffer usable for nntp process connections."
1275   (with-current-buffer
1276       (generate-new-buffer
1277        (format " *server %s %s %s*"
1278                nntp-address nntp-port-number
1279                (gnus-buffer-exists-p buffer)))
1280     (mm-disable-multibyte)
1281     (set (make-local-variable 'after-change-functions) nil)
1282     (set (make-local-variable 'nntp-process-wait-for) nil)
1283     (set (make-local-variable 'nntp-process-callback) nil)
1284     (set (make-local-variable 'nntp-process-to-buffer) nil)
1285     (set (make-local-variable 'nntp-process-start-point) nil)
1286     (set (make-local-variable 'nntp-process-decode) nil)
1287     (set (make-local-variable 'nntp-retrieval-in-progress) nil)
1288     (current-buffer)))
1289
1290 (defun nntp-open-connection (buffer)
1291   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
1292   (run-hooks 'nntp-prepare-server-hook)
1293   (let* ((pbuffer (nntp-make-process-buffer buffer))
1294          (timer
1295           (and nntp-connection-timeout
1296                (run-at-time
1297                 nntp-connection-timeout nil
1298                 `(lambda ()
1299                    (nntp-kill-buffer ,pbuffer)))))
1300          (process
1301           (condition-case err
1302               (let ((coding-system-for-read 'binary)
1303                     (coding-system-for-write 'binary)
1304                     (map '((nntp-open-network-stream network)
1305                            (network-only plain) ; compat
1306                            (nntp-open-plain-stream plain)
1307                            (nntp-open-ssl-stream tls)
1308                            (nntp-open-tls-stream tls))))
1309                 (if (assoc nntp-open-connection-function map)
1310                     (open-protocol-stream
1311                      "nntpd" pbuffer nntp-address nntp-port-number
1312                      :type (cadr (assoc nntp-open-connection-function map))
1313                      :end-of-command "^\\([2345]\\|[.]\\).*\n"
1314                      :capability-command "CAPABILITIES\r\n"
1315                      :success "^3"
1316                      :starttls-function
1317                      (lambda (capabilities)
1318                        (if (not (string-match "STARTTLS" capabilities))
1319                            nil
1320                          "STARTTLS\r\n")))
1321                   (funcall nntp-open-connection-function pbuffer)))
1322             (error
1323              (nnheader-report 'nntp ">>> %s" err))
1324             (quit
1325              (message "Quit opening connection to %s" nntp-address)
1326              (nntp-kill-buffer pbuffer)
1327              (signal 'quit nil)
1328              nil))))
1329     (when timer
1330       (nnheader-cancel-timer timer))
1331     (when (and process
1332                (not (memq (process-status process) '(open run))))
1333       (with-current-buffer pbuffer
1334         (goto-char (point-min))
1335         (nnheader-report 'nntp "Error when connecting: %s"
1336                          (buffer-substring (point) (line-end-position))))
1337       (setq process nil))
1338     (unless process
1339       (nntp-kill-buffer pbuffer))
1340     (when (and (buffer-name pbuffer)
1341                process)
1342       (when (and (fboundp 'set-network-process-option) ;; Unavailable in XEmacs.
1343                  (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
1344                  (eq (process-type process) 'network))
1345         ;; Use TCP-keepalive so that connections that pass through a NAT router
1346         ;; don't hang when left idle.
1347         (set-network-process-option process :keepalive t))
1348       (gnus-set-process-query-on-exit-flag process nil)
1349       (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
1350                (memq (process-status process) '(open run)))
1351           (prog1
1352               (caar (push (list process buffer nil) nntp-connection-alist))
1353             (push process nntp-connection-list)
1354             (with-current-buffer pbuffer
1355               (nntp-read-server-type)
1356               (erase-buffer)
1357               (set-buffer nntp-server-buffer)
1358               (let ((nnheader-callback-function nil))
1359                 (run-hooks 'nntp-server-opened-hook)
1360                 (nntp-send-authinfo t))))
1361         (nntp-kill-buffer (process-buffer process))
1362         nil))))
1363
1364 (defun nntp-read-server-type ()
1365   "Find out what the name of the server we have connected to is."
1366   ;; Wait for the status string to arrive.
1367   (setq nntp-server-type (buffer-string))
1368   (let ((case-fold-search t))
1369     ;; Run server-specific commands.
1370     (dolist (entry nntp-server-action-alist)
1371       (when (string-match (car entry) nntp-server-type)
1372         (if (and (listp (cadr entry))
1373                  (not (eq 'lambda (caadr entry))))
1374             (eval (cadr entry))
1375           (funcall (cadr entry)))))))
1376
1377 (defun nntp-async-wait (process wait-for buffer decode callback)
1378   (with-current-buffer (process-buffer process)
1379     (unless nntp-inside-change-function
1380       (erase-buffer))
1381     (setq nntp-process-wait-for wait-for
1382           nntp-process-to-buffer buffer
1383           nntp-process-decode decode
1384           nntp-process-callback callback
1385           nntp-process-start-point (point-max))
1386     (setq after-change-functions '(nntp-after-change-function))))
1387
1388 (defun nntp-async-timer-handler ()
1389   (mapcar
1390    (lambda (proc)
1391      (if (memq (process-status proc) '(open run))
1392          (nntp-async-trigger proc)
1393        (nntp-async-stop proc)))
1394    nntp-async-process-list))
1395
1396 (defun nntp-async-stop (proc)
1397   (setq nntp-async-process-list (delq proc nntp-async-process-list))
1398   (when (and nntp-async-timer (not nntp-async-process-list))
1399     (nnheader-cancel-timer nntp-async-timer)
1400     (setq nntp-async-timer nil)))
1401
1402 (defun nntp-after-change-function (beg end len)
1403   (unwind-protect
1404       ;; we only care about insertions at eob
1405       (when (and (eq 0 len) (eq (point-max) end))
1406         (save-match-data
1407           (let ((proc (get-buffer-process (current-buffer))))
1408             (when proc
1409               (nntp-async-trigger proc)))))
1410     ;; any throw from after-change-functions will leave it
1411     ;; set to nil.  so we reset it here, if necessary.
1412     (when quit-flag
1413       (setq after-change-functions '(nntp-after-change-function)))))
1414
1415 (defun nntp-async-trigger (process)
1416   (with-current-buffer (process-buffer process)
1417     (when nntp-process-callback
1418       ;; do we have an error message?
1419       (goto-char nntp-process-start-point)
1420       (if (memq (following-char) '(?4 ?5))
1421           ;; wants credentials?
1422           (if (looking-at "480")
1423               (nntp-handle-authinfo process)
1424             ;; report error message.
1425             (nntp-snarf-error-message)
1426             (nntp-do-callback nil))
1427
1428         ;; got what we expect?
1429         (goto-char (point-max))
1430         (when (re-search-backward
1431                nntp-process-wait-for nntp-process-start-point t)
1432           (let ((response (match-string 0)))
1433             (with-current-buffer nntp-server-buffer
1434               (setq nntp-process-response response)))
1435           (nntp-async-stop process)
1436           ;; convert it.
1437           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1438             (let ((buf (current-buffer))
1439                   (start nntp-process-start-point)
1440                   (decode nntp-process-decode))
1441               (with-current-buffer nntp-process-to-buffer
1442                 (goto-char (point-max))
1443                 (save-restriction
1444                   (narrow-to-region (point) (point))
1445                   (nnheader-insert-buffer-substring buf start)
1446                   (when decode
1447                     (nntp-decode-text))))))
1448           ;; report it.
1449           (goto-char (point-max))
1450           (nntp-do-callback
1451            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1452
1453 (defun nntp-do-callback (arg)
1454   (let ((callback nntp-process-callback)
1455         (nntp-inside-change-function t))
1456     (setq nntp-process-callback nil)
1457     (funcall callback arg)))
1458
1459 (defun nntp-snarf-error-message ()
1460   "Save the error message in the current buffer."
1461   (let ((message (buffer-string)))
1462     (while (string-match "[\r\n]+" message)
1463       (setq message (replace-match " " t t message)))
1464     (nnheader-report 'nntp "%s" message)
1465     message))
1466
1467 (defun nntp-accept-process-output (process)
1468   "Wait for output from PROCESS and message some dots."
1469   (with-current-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1470                            nntp-server-buffer)
1471     (let ((len (/ (buffer-size) 1024))
1472           message-log-max)
1473       (unless (< len 10)
1474         (setq nntp-have-messaged t)
1475         (nnheader-message 7 "nntp read: %dk" len)))
1476     (prog1
1477         (nnheader-accept-process-output process)
1478       ;; accept-process-output may update status of process to indicate
1479       ;; that the server has closed the connection.  This MUST be
1480       ;; handled here as the buffer restored by the save-excursion may
1481       ;; be the process's former output buffer (i.e. now killed)
1482       (or (and process
1483                (memq (process-status process) '(open run)))
1484           (nntp-report "Server closed connection")))))
1485
1486 (defun nntp-accept-response ()
1487   "Wait for output from the process that outputs to BUFFER."
1488   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1489
1490 (defun nntp-possibly-change-group (group server &optional connectionless)
1491   (let ((nnheader-callback-function nil))
1492     (when server
1493       (or (nntp-server-opened server)
1494           (nntp-open-server server nil connectionless)))
1495
1496     (unless connectionless
1497       (or (nntp-find-connection nntp-server-buffer)
1498           (nntp-open-connection nntp-server-buffer))))
1499
1500   (when group
1501     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1502       (cond ((not entry)
1503              (nntp-report "Server closed connection"))
1504             ((not (equal group (caddr entry)))
1505              (with-current-buffer (process-buffer (car entry))
1506                (erase-buffer)
1507                (nntp-send-command "^[245].*\n" "GROUP" group)
1508                (setcar (cddr entry) group)
1509                (erase-buffer)
1510                (nntp-erase-buffer nntp-server-buffer)))))))
1511
1512 (defun nntp-decode-text (&optional cr-only)
1513   "Decode the text in the current buffer."
1514   (goto-char (point-min))
1515   (while (search-forward "\r" nil t)
1516     (delete-char -1))
1517   (unless cr-only
1518     ;; Remove trailing ".\n" end-of-transfer marker.
1519     (goto-char (point-max))
1520     (forward-line -1)
1521     (when (looking-at ".\n")
1522       (delete-char 2))
1523     ;; Delete status line.
1524     (goto-char (point-min))
1525     (while (looking-at "[1-5][0-9][0-9] .*\n")
1526       ;; For some unknown reason, there is more than one status line.
1527       (delete-region (point) (progn (forward-line 1) (point))))
1528     ;; Remove "." -> ".." encoding.
1529     (while (search-forward "\n.." nil t)
1530       (delete-char -1))))
1531
1532 (defun nntp-encode-text ()
1533   "Encode the text in the current buffer."
1534   (save-excursion
1535     ;; Replace "." at beginning of line with "..".
1536     (goto-char (point-min))
1537     (while (re-search-forward "^\\." nil t)
1538       (insert "."))
1539     (goto-char (point-max))
1540     ;; Insert newline at the end of the buffer.
1541     (unless (bolp)
1542       (insert "\n"))
1543     ;; Insert `.' at end of buffer (end of text mark).
1544     (goto-char (point-max))
1545     (insert ".\n")
1546     (goto-char (point-min))
1547     (while (not (eobp))
1548       (end-of-line)
1549       (delete-char 1)
1550       (insert nntp-end-of-line))))
1551
1552 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1553   (set-buffer nntp-server-buffer)
1554   (erase-buffer)
1555   (cond
1556
1557    ;; This server does not talk NOV.
1558    ((not nntp-server-xover)
1559     nil)
1560
1561    ;; We don't care about gaps.
1562    ((or (not nntp-nov-gap)
1563         fetch-old)
1564     (nntp-send-xover-command
1565      (if fetch-old
1566          (if (numberp fetch-old)
1567              (max 1 (- (car articles) fetch-old))
1568            1)
1569        (car articles))
1570      (car (last articles)) 'wait)
1571
1572     (goto-char (point-min))
1573     (when (looking-at "[1-5][0-9][0-9] .*\n")
1574       (delete-region (point) (progn (forward-line 1) (point))))
1575     (while (search-forward "\r" nil t)
1576       (replace-match "" t t))
1577     (goto-char (point-max))
1578     (forward-line -1)
1579     (when (looking-at "\\.")
1580       (delete-region (point) (progn (forward-line 1) (point)))))
1581
1582    ;; We do it the hard way.  For each gap, an XOVER command is sent
1583    ;; to the server.  We do not wait for a reply from the server, we
1584    ;; just send them off as fast as we can.  That means that we have
1585    ;; to count the number of responses we get back to find out when we
1586    ;; have gotten all we asked for.
1587    ((numberp nntp-nov-gap)
1588     (let ((count 0)
1589           (received 0)
1590           last-point
1591           in-process-buffer-p
1592           (buf nntp-server-buffer)
1593           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1594           first last status)
1595       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1596       ;; that means that the server does not understand XOVER, but we
1597       ;; won't know that until we try.
1598       (while (and nntp-server-xover articles)
1599         (setq first (car articles))
1600         ;; Search forward until we find a gap, or until we run out of
1601         ;; articles.
1602         (while (and (cdr articles)
1603                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1604           (setq articles (cdr articles)))
1605
1606         (setq in-process-buffer-p (stringp nntp-server-xover))
1607         (nntp-send-xover-command first (setq last (car articles)))
1608         (setq articles (cdr articles))
1609
1610         (when (and nntp-server-xover in-process-buffer-p)
1611           ;; Don't count tried request.
1612           (setq count (1+ count))
1613
1614           ;; Every 400 requests we have to read the stream in
1615           ;; order to avoid deadlocks.
1616           (when (or (null articles)     ;All requests have been sent.
1617                     (= 1 (% count nntp-maximum-request)))
1618
1619             (nntp-accept-response)
1620             ;; On some Emacs versions the preceding function has a
1621             ;; tendency to change the buffer.  Perhaps.  It's quite
1622             ;; difficult to reproduce, because it only seems to happen
1623             ;; once in a blue moon.
1624             (set-buffer process-buffer)
1625             (while (progn
1626                      (goto-char (or last-point (point-min)))
1627                      ;; Count replies.
1628                      (while (re-search-forward "^\\([0-9][0-9][0-9]\\) .*\n"
1629                                                nil t)
1630                        (incf received)
1631                        (setq status (match-string 1))
1632                        (if (string-match "^[45]" status)
1633                            (setq status 'error)
1634                          (setq status 'ok)))
1635                      (setq last-point (point))
1636                      (or (< received count)
1637                          (if (eq status 'error)
1638                              nil
1639                            ;; I haven't started reading the final response
1640                            (progn
1641                              (goto-char (point-max))
1642                              (forward-line -1)
1643                              (not (looking-at "^\\.\r?\n"))))))
1644               ;; I haven't read the end of the final response
1645               (nntp-accept-response)
1646               (set-buffer process-buffer))))
1647
1648         ;; Some nntp servers seem to have an extension to the XOVER
1649         ;; extension.  On these servers, requesting an article range
1650         ;; preceding the active range does not return an error as
1651         ;; specified in the RFC.  What we instead get is the NOV entry
1652         ;; for the first available article.  Obviously, a client can
1653         ;; use that entry to avoid making unnecessary requests.  The
1654         ;; only problem is for a client that assumes that the response
1655         ;; will always be within the requested range.  For such a
1656         ;; client, we can get N copies of the same entry (one for each
1657         ;; XOVER command sent to the server).
1658
1659         (when (<= count 1)
1660           (goto-char (point-min))
1661           (when (re-search-forward "^[0-9][0-9][0-9] .*\n\\([0-9]+\\)" nil t)
1662             (let ((low-limit (string-to-number
1663                               (buffer-substring (match-beginning 1)
1664                                                 (match-end 1)))))
1665               (while (and articles (<= (car articles) low-limit))
1666                 (setq articles (cdr articles))))))
1667         (set-buffer buf))
1668
1669       (when nntp-server-xover
1670         (when in-process-buffer-p
1671           (set-buffer buf)
1672           (goto-char (point-max))
1673           (nnheader-insert-buffer-substring process-buffer)
1674           (set-buffer process-buffer)
1675           (erase-buffer)
1676           (set-buffer buf))
1677
1678         ;; We remove any "." lines and status lines.
1679         (goto-char (point-min))
1680         (while (search-forward "\r" nil t)
1681           (delete-char -1))
1682         (goto-char (point-min))
1683         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1684         t))))
1685
1686   nntp-server-xover)
1687
1688 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1689   "Send the XOVER command to the server."
1690   (let ((range (format "%d-%d" beg end))
1691         (nntp-inhibit-erase t))
1692     (if (stringp nntp-server-xover)
1693         ;; If `nntp-server-xover' is a string, then we just send this
1694         ;; command.
1695         (if wait-for-reply
1696             (nntp-send-command-nodelete
1697              "\r?\n\\.\r?\n" nntp-server-xover range)
1698           ;; We do not wait for the reply.
1699           (nntp-send-command-nodelete nil nntp-server-xover range))
1700       (let ((commands nntp-xover-commands))
1701         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1702         ;; We try them all until we get at positive response.
1703         (while (and commands (eq nntp-server-xover 'try))
1704           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1705           (with-current-buffer nntp-server-buffer
1706             (goto-char (point-min))
1707             (and (looking-at "[23]")    ; No error message.
1708                  ;; We also have to look at the lines.  Some buggy
1709                  ;; servers give back simple lines with just the
1710                  ;; article number.  How... helpful.
1711                  (progn
1712                    (forward-line 1)
1713                    ;; More text after number, or a dot.
1714                    (looking-at "[0-9]+\t...\\|\\.\r?\n"))
1715                  (setq nntp-server-xover (car commands))))
1716           (setq commands (cdr commands)))
1717         ;; If none of the commands worked, we disable XOVER.
1718         (when (eq nntp-server-xover 'try)
1719           (nntp-erase-buffer nntp-server-buffer)
1720           (setq nntp-server-xover nil))
1721         nntp-server-xover))))
1722
1723 (defun nntp-find-group-and-number (&optional group)
1724   (save-excursion
1725     (save-restriction
1726       ;; FIXME: This is REALLY FISHY: set-buffer after save-restriction?!?
1727       (set-buffer nntp-server-buffer)
1728       (narrow-to-region (goto-char (point-min))
1729                         (or (search-forward "\n\n" nil t) (point-max)))
1730       (goto-char (point-min))
1731       ;; We first find the number by looking at the status line.
1732       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1733                          (string-to-number
1734                           (buffer-substring (match-beginning 1)
1735                                             (match-end 1)))))
1736             newsgroups xref)
1737         (and number (zerop number) (setq number nil))
1738         (if number
1739             ;; Then we find the group name.
1740             (setq group
1741                   (cond
1742                    ;; If there is only one group in the Newsgroups
1743                    ;; header, then it seems quite likely that this
1744                    ;; article comes from that group, I'd say.
1745                    ((and (setq newsgroups
1746                                (mail-fetch-field "newsgroups"))
1747                          (not (string-match "," newsgroups)))
1748                     newsgroups)
1749                    ;; If there is more than one group in the
1750                    ;; Newsgroups header, then the Xref header should
1751                    ;; be filled out.  We hazard a guess that the group
1752                    ;; that has this article number in the Xref header
1753                    ;; is the one we are looking for.  This might very
1754                    ;; well be wrong if this article happens to have
1755                    ;; the same number in several groups, but that's
1756                    ;; life.
1757                    ((and (setq xref (mail-fetch-field "xref"))
1758                          number
1759                          (string-match
1760                           (format "\\([^ :]+\\):%d" number) xref))
1761                     (match-string 1 xref))
1762                    (t "")))
1763           (cond
1764            ((and (not nntp-xref-number-is-evil)
1765                  (setq xref (mail-fetch-field "xref"))
1766                  (string-match
1767                   (if group
1768                       (concat "\\(" (regexp-quote group) "\\):\\([0-9]+\\)")
1769                     "\\([^ :]+\\):\\([0-9]+\\)")
1770                   xref))
1771             (setq group (match-string 1 xref)
1772                   number (string-to-number (match-string 2 xref))))
1773            ((and (setq newsgroups
1774                        (mail-fetch-field "newsgroups"))
1775                  (not (string-match "," newsgroups)))
1776             (setq group newsgroups))
1777            (group)
1778            (t (setq group ""))))
1779         (when (string-match "\r" group)
1780           (setq group (substring group 0 (match-beginning 0))))
1781         (cons group number)))))
1782
1783 (defun nntp-wait-for-string (regexp)
1784   "Wait until string arrives in the buffer."
1785   (let ((buf (current-buffer))
1786         proc)
1787     (goto-char (point-min))
1788     (while (and (setq proc (get-buffer-process buf))
1789                 (memq (process-status proc) '(open run))
1790                 (not (re-search-forward regexp nil t)))
1791       (accept-process-output proc 0.1)
1792       (set-buffer buf)
1793       (goto-char (point-min)))))
1794
1795
1796 ;; ==========================================================================
1797 ;; Obsolete nntp-open-* connection methods -- drv
1798 ;; ==========================================================================
1799
1800 (defvoo nntp-open-telnet-envuser nil
1801   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1802
1803 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1804   "*Regular expression to match the shell prompt on the remote machine.")
1805
1806 (defvoo nntp-rlogin-program "rsh"
1807   "*Program used to log in on remote machines.
1808 The default is \"rsh\", but \"ssh\" is a popular alternative.")
1809
1810 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1811   "*Parameters to `nntp-open-rlogin'.
1812 That function may be used as `nntp-open-connection-function'.  In that
1813 case, this list will be used as the parameter list given to rsh.")
1814
1815 (defvoo nntp-rlogin-user-name nil
1816   "*User name on remote system when using the rlogin connect method.")
1817
1818 (defvoo nntp-telnet-parameters
1819     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1820   "*Parameters to `nntp-open-telnet'.
1821 That function may be used as `nntp-open-connection-function'.  In that
1822 case, this list will be executed as a command after logging in
1823 via telnet.")
1824
1825 (defvoo nntp-telnet-user-name nil
1826   "User name to log in via telnet with.")
1827
1828 (defvoo nntp-telnet-passwd nil
1829   "Password to use to log in via telnet with.")
1830
1831 (defun nntp-service-to-port (svc)
1832   (cond
1833    ((integerp svc) (number-to-string svc))
1834    ((string-match "\\`[0-9]+\\'" svc) svc)
1835    (t
1836     (with-temp-buffer
1837       (ignore-errors (insert-file-contents "/etc/services"))
1838       (goto-char (point-min))
1839       (if (re-search-forward (concat "^" (regexp-quote svc)
1840                                      "[ \t]+\\([0-9]+\\)/tcp"))
1841           (match-string 1)
1842         svc)))))
1843
1844 (defun nntp-open-telnet (buffer)
1845   (with-current-buffer buffer
1846     (erase-buffer)
1847     (let ((proc (apply
1848                  'start-process
1849                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1850           (case-fold-search t))
1851       (when (memq (process-status proc) '(open run))
1852         (nntp-wait-for-string "^r?telnet")
1853         (process-send-string proc "set escape \^X\n")
1854         (cond
1855          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1856           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1857                                             nntp-address "\n")))
1858          (t
1859           (process-send-string proc (concat "open " nntp-address "\n"))))
1860         (cond
1861          ((not nntp-open-telnet-envuser)
1862           (nntp-wait-for-string "^\r*.?login:")
1863           (process-send-string
1864            proc (concat
1865                  (or nntp-telnet-user-name
1866                      (setq nntp-telnet-user-name (read-string "login: ")))
1867                  "\n"))))
1868         (nntp-wait-for-string "^\r*.?password:")
1869         (process-send-string
1870          proc (concat
1871                (or nntp-telnet-passwd
1872                    (setq nntp-telnet-passwd
1873                          (read-passwd "Password: ")))
1874                "\n"))
1875         (nntp-wait-for-string nntp-telnet-shell-prompt)
1876         (process-send-string
1877          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1878         (nntp-wait-for-string "^\r*20[01]")
1879         (beginning-of-line)
1880         (delete-region (point-min) (point))
1881         (process-send-string proc "\^]")
1882         (nntp-wait-for-string "^r?telnet")
1883         (process-send-string proc "mode character\n")
1884         (accept-process-output proc 1)
1885         (sit-for 1)
1886         (goto-char (point-min))
1887         (forward-line 1)
1888         (delete-region (point) (point-max)))
1889       proc)))
1890
1891 (defun nntp-open-rlogin (buffer)
1892   "Open a connection to SERVER using rsh."
1893   (let ((proc (if nntp-rlogin-user-name
1894                   (apply 'start-process
1895                          "nntpd" buffer nntp-rlogin-program
1896                          nntp-address "-l" nntp-rlogin-user-name
1897                          nntp-rlogin-parameters)
1898                 (apply 'start-process
1899                        "nntpd" buffer nntp-rlogin-program nntp-address
1900                        nntp-rlogin-parameters))))
1901     (with-current-buffer buffer
1902       (nntp-wait-for-string "^\r*20[01]")
1903       (beginning-of-line)
1904       (delete-region (point-min) (point))
1905       proc)))
1906
1907
1908 ;; ==========================================================================
1909 ;; Replacements for the nntp-open-* functions -- drv
1910 ;; ==========================================================================
1911
1912 (defun nntp-open-telnet-stream (buffer)
1913   "Open a nntp connection by telnet'ing the news server.
1914 `nntp-open-netcat-stream' is recommended in place of this function
1915 because it is more reliable.
1916
1917 Please refer to the following variables to customize the connection:
1918 - `nntp-pre-command',
1919 - `nntp-telnet-command',
1920 - `nntp-telnet-switches',
1921 - `nntp-address',
1922 - `nntp-port-number',
1923 - `nntp-end-of-line'."
1924   (let ((command `(,nntp-telnet-command
1925                    ,@nntp-telnet-switches
1926                    ,nntp-address
1927                    ,(nntp-service-to-port nntp-port-number)))
1928         proc)
1929     (and nntp-pre-command
1930          (push nntp-pre-command command))
1931     (setq proc (apply 'start-process "nntpd" buffer command))
1932     (with-current-buffer buffer
1933       (nntp-wait-for-string "^\r*20[01]")
1934       (beginning-of-line)
1935       (delete-region (point-min) (point))
1936       proc)))
1937
1938 (defun nntp-open-via-rlogin-and-telnet (buffer)
1939   "Open a connection to an nntp server through an intermediate host.
1940 First rlogin to the remote host, and then telnet the real news server
1941 from there.
1942 `nntp-open-via-rlogin-and-netcat' is recommended in place of this function
1943 because it is more reliable.
1944
1945 Please refer to the following variables to customize the connection:
1946 - `nntp-pre-command',
1947 - `nntp-via-rlogin-command',
1948 - `nntp-via-rlogin-command-switches',
1949 - `nntp-via-user-name',
1950 - `nntp-via-address',
1951 - `nntp-telnet-command',
1952 - `nntp-telnet-switches',
1953 - `nntp-address',
1954 - `nntp-port-number',
1955 - `nntp-end-of-line'."
1956   (let ((command `(,nntp-via-address
1957                    ,nntp-telnet-command
1958                    ,@nntp-telnet-switches))
1959         proc)
1960     (when nntp-via-user-name
1961       (setq command `("-l" ,nntp-via-user-name ,@command)))
1962     (when nntp-via-rlogin-command-switches
1963       (setq command (append nntp-via-rlogin-command-switches command)))
1964     (push nntp-via-rlogin-command command)
1965     (and nntp-pre-command
1966          (push nntp-pre-command command))
1967     (setq proc (apply 'start-process "nntpd" buffer command))
1968     (with-current-buffer buffer
1969       (nntp-wait-for-string "^r?telnet")
1970       (process-send-string proc (concat "open " nntp-address " "
1971                                         (nntp-service-to-port nntp-port-number)
1972                                         "\n"))
1973       (nntp-wait-for-string "^\r*20[01]")
1974       (beginning-of-line)
1975       (delete-region (point-min) (point))
1976       (process-send-string proc "\^]")
1977       (nntp-wait-for-string "^r?telnet")
1978       (process-send-string proc "mode character\n")
1979       (accept-process-output proc 1)
1980       (sit-for 1)
1981       (goto-char (point-min))
1982       (forward-line 1)
1983       (delete-region (point) (point-max)))
1984     proc))
1985
1986 (defun nntp-open-via-rlogin-and-netcat (buffer)
1987   "Open a connection to an nntp server through an intermediate host.
1988 First rlogin to the remote host, and then connect to the real news
1989 server from there using the netcat command.
1990
1991 Please refer to the following variables to customize the connection:
1992 - `nntp-pre-command',
1993 - `nntp-via-rlogin-command',
1994 - `nntp-via-rlogin-command-switches',
1995 - `nntp-via-user-name',
1996 - `nntp-via-address',
1997 - `nntp-netcat-command',
1998 - `nntp-netcat-switches',
1999 - `nntp-address',
2000 - `nntp-port-number'."
2001   (let ((command `(,@(when nntp-pre-command
2002                        (list nntp-pre-command))
2003                    ,nntp-via-rlogin-command
2004                    ,@nntp-via-rlogin-command-switches
2005                    ,@(when nntp-via-user-name
2006                        (list "-l" nntp-via-user-name))
2007                    ,nntp-via-address
2008                    ,nntp-netcat-command
2009                    ,@nntp-netcat-switches
2010                    ,nntp-address
2011                    ,(nntp-service-to-port nntp-port-number))))
2012     ;; A non-nil connection type results in mightily odd behavior where
2013     ;; (process-send-string proc "\^M") ends up sending a "\n" to the
2014     ;; ssh process.  --Stef
2015     ;; Also a nil connection allow ssh-askpass to work under X11.
2016     (let ((process-connection-type nil))
2017       (apply 'start-process "nntpd" buffer command))))
2018
2019 (defun nntp-open-netcat-stream (buffer)
2020   "Open a connection to an nntp server through netcat.
2021 I.e. use the `nc' command rather than Emacs's builtin networking code.
2022
2023 Please refer to the following variables to customize the connection:
2024 - `nntp-pre-command',
2025 - `nntp-netcat-command',
2026 - `nntp-netcat-switches',
2027 - `nntp-address',
2028 - `nntp-port-number'."
2029   (let ((command `(,nntp-netcat-command
2030                    ,@nntp-netcat-switches
2031                    ,nntp-address
2032                    ,(nntp-service-to-port nntp-port-number))))
2033     (and nntp-pre-command (push nntp-pre-command command))
2034     (let ((process-connection-type nil)) ;See `nntp-open-via-rlogin-and-netcat'.
2035       (apply 'start-process "nntpd" buffer command))))
2036
2037
2038 (defun nntp-open-via-telnet-and-telnet (buffer)
2039   "Open a connection to an nntp server through an intermediate host.
2040 First telnet the remote host, and then telnet the real news server
2041 from there.
2042
2043 Please refer to the following variables to customize the connection:
2044 - `nntp-pre-command',
2045 - `nntp-via-telnet-command',
2046 - `nntp-via-telnet-switches',
2047 - `nntp-via-address',
2048 - `nntp-via-envuser',
2049 - `nntp-via-user-name',
2050 - `nntp-via-user-password',
2051 - `nntp-via-shell-prompt',
2052 - `nntp-telnet-command',
2053 - `nntp-telnet-switches',
2054 - `nntp-address',
2055 - `nntp-port-number',
2056 - `nntp-end-of-line'."
2057   (with-current-buffer buffer
2058     (erase-buffer)
2059     (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
2060           (case-fold-search t)
2061           proc)
2062       (and nntp-pre-command (push nntp-pre-command command))
2063       (setq proc (apply 'start-process "nntpd" buffer command))
2064       (when (memq (process-status proc) '(open run))
2065         (nntp-wait-for-string "^r?telnet")
2066         (process-send-string proc "set escape \^X\n")
2067         (cond
2068          ((and nntp-via-envuser nntp-via-user-name)
2069           (process-send-string proc (concat "open " "-l" nntp-via-user-name
2070                                             nntp-via-address "\n")))
2071          (t
2072           (process-send-string proc (concat "open " nntp-via-address
2073                                             "\n"))))
2074         (when (not nntp-via-envuser)
2075           (nntp-wait-for-string "^\r*.?login:")
2076           (process-send-string proc
2077                                (concat
2078                                 (or nntp-via-user-name
2079                                     (setq nntp-via-user-name
2080                                           (read-string "login: ")))
2081                                 "\n")))
2082         (nntp-wait-for-string "^\r*.?password:")
2083         (process-send-string proc
2084                              (concat
2085                               (or nntp-via-user-password
2086                                   (setq nntp-via-user-password
2087                                         (read-passwd "Password: ")))
2088                               "\n"))
2089         (nntp-wait-for-string nntp-via-shell-prompt)
2090         (let ((real-telnet-command `("exec"
2091                                      ,nntp-telnet-command
2092                                      ,@nntp-telnet-switches
2093                                      ,nntp-address
2094                                      ,(nntp-service-to-port nntp-port-number))))
2095           (process-send-string proc
2096                                (concat (mapconcat 'identity
2097                                                   real-telnet-command " ")
2098                                        "\n")))
2099         (nntp-wait-for-string "^\r*20[01]")
2100         (beginning-of-line)
2101         (delete-region (point-min) (point))
2102         (process-send-string proc "\^]")
2103         (nntp-wait-for-string "^r?telnet")
2104         (process-send-string proc "mode character\n")
2105         (accept-process-output proc 1)
2106         (sit-for 1)
2107         (goto-char (point-min))
2108         (forward-line 1)
2109         (delete-region (point) (point-max)))
2110       proc)))
2111
2112 (provide 'nntp)
2113
2114 ;;; nntp.el ends here