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