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