Merge remote 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
1198                   :max 1
1199                   :host (list nntp-address (nnoo-current-server 'nntp))
1200                   :port `("119" "nntp" ,(format "%s" nntp-port-number)
1201                           "563" "nntps" "snews"))))
1202          (auth-user (plist-get auth-info :user))
1203          (auth-force (plist-get auth-info :force))
1204          (auth-passwd (plist-get auth-info :secret))
1205          (auth-passwd (if (functionp auth-passwd)
1206                           (funcall auth-passwd)
1207                         auth-passwd))
1208          (force (or (netrc-get alist "force")
1209                     nntp-authinfo-force
1210                     auth-force))
1211          (user (or
1212                 ;; this is preferred to netrc-*
1213                 auth-user
1214                 (netrc-get alist "login")
1215                 nntp-authinfo-user))
1216          (passwd (or
1217                   ;; this is preferred to netrc-*
1218                   auth-passwd
1219                   (netrc-get alist "password"))))
1220     (when (or (not send-if-force)
1221               force)
1222       (unless user
1223         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
1224               nntp-authinfo-user user))
1225       (unless (member user '(nil ""))
1226         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1227         (when t                         ;???Should check if AUTHINFO succeeded
1228           (nntp-send-command
1229            "^2.*\r?\n" "AUTHINFO PASS"
1230            (or passwd
1231                nntp-authinfo-password
1232                (setq nntp-authinfo-password
1233                      (read-passwd (format "NNTP (%s@%s) password: "
1234                                           user nntp-address))))))))))
1235
1236 (defun nntp-send-nosy-authinfo ()
1237   "Send the AUTHINFO to the nntp server."
1238   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
1239     (unless (member user '(nil ""))
1240       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1241       (when t                           ;???Should check if AUTHINFO succeeded
1242         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
1243                            (read-passwd (format "NNTP (%s@%s) password: "
1244                                                 user nntp-address)))))))
1245
1246 (defun nntp-send-authinfo-from-file ()
1247   "Send the AUTHINFO to the nntp server.
1248
1249 The authinfo login name is taken from the user's login name and the
1250 password contained in '~/.nntp-authinfo'."
1251   (when (file-exists-p "~/.nntp-authinfo")
1252     (with-temp-buffer
1253       (insert-file-contents "~/.nntp-authinfo")
1254       (goto-char (point-min))
1255       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
1256       (nntp-send-command
1257        "^2.*\r?\n" "AUTHINFO PASS"
1258        (buffer-substring (point) (point-at-eol))))))
1259
1260 ;;; Internal functions.
1261
1262 (defun nntp-handle-authinfo (process)
1263   "Take care of an authinfo response from the server."
1264   (let ((last nntp-last-command))
1265     (funcall nntp-authinfo-function)
1266     ;; We have to re-send the function that was interrupted by
1267     ;; the authinfo request.
1268     (nntp-erase-buffer nntp-server-buffer)
1269     (nntp-send-string process last)))
1270
1271 (defun nntp-make-process-buffer (buffer)
1272   "Create a new, fresh buffer usable for nntp process connections."
1273   (with-current-buffer
1274       (generate-new-buffer
1275        (format " *server %s %s %s*"
1276                nntp-address nntp-port-number
1277                (gnus-buffer-exists-p buffer)))
1278     (mm-disable-multibyte)
1279     (set (make-local-variable 'after-change-functions) nil)
1280     (set (make-local-variable 'nntp-process-wait-for) nil)
1281     (set (make-local-variable 'nntp-process-callback) nil)
1282     (set (make-local-variable 'nntp-process-to-buffer) nil)
1283     (set (make-local-variable 'nntp-process-start-point) nil)
1284     (set (make-local-variable 'nntp-process-decode) nil)
1285     (set (make-local-variable 'nntp-retrieval-in-progress) nil)
1286     (current-buffer)))
1287
1288 (defun nntp-open-connection (buffer)
1289   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
1290   (run-hooks 'nntp-prepare-server-hook)
1291   (let* ((pbuffer (nntp-make-process-buffer buffer))
1292          (timer
1293           (and nntp-connection-timeout
1294                (run-at-time
1295                 nntp-connection-timeout nil
1296                 `(lambda ()
1297                    (nntp-kill-buffer ,pbuffer)))))
1298          (process
1299           (condition-case err
1300               (let ((coding-system-for-read 'binary)
1301                     (coding-system-for-write 'binary)
1302                     (map '((nntp-open-network-stream network)
1303                            (network-only plain) ; compat
1304                            (nntp-open-plain-stream plain)
1305                            (nntp-open-ssl-stream tls)
1306                            (nntp-open-tls-stream tls))))
1307                 (if (assoc nntp-open-connection-function map)
1308                     (open-protocol-stream
1309                      "nntpd" pbuffer nntp-address nntp-port-number
1310                      :type (cadr (assoc nntp-open-connection-function map))
1311                      :end-of-command "^\\([2345]\\|[.]\\).*\n"
1312                      :capability-command "CAPABILITIES\r\n"
1313                      :success "^3"
1314                      :starttls-function
1315                      (lambda (capabilities)
1316                        (if (not (string-match "STARTTLS" capabilities))
1317                            nil
1318                          "STARTTLS\r\n")))
1319                   (funcall nntp-open-connection-function pbuffer)))
1320             (error
1321              (nnheader-report 'nntp ">>> %s" err))
1322             (quit
1323              (message "Quit opening connection to %s" nntp-address)
1324              (nntp-kill-buffer pbuffer)
1325              (signal 'quit nil)
1326              nil))))
1327     (when timer
1328       (nnheader-cancel-timer timer))
1329     (when (and process
1330                (not (memq (process-status process) '(open run))))
1331       (with-current-buffer pbuffer
1332         (goto-char (point-min))
1333         (nnheader-report 'nntp "Error when connecting: %s"
1334                          (buffer-substring (point) (line-end-position))))
1335       (setq process nil))
1336     (unless process
1337       (nntp-kill-buffer pbuffer))
1338     (when (and (buffer-name pbuffer)
1339                process)
1340       (when (and (fboundp 'set-network-process-option) ;; Unavailable in XEmacs.
1341                  (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
1342                  (eq (process-type process) 'network))
1343         ;; Use TCP-keepalive so that connections that pass through a NAT router
1344         ;; don't hang when left idle.
1345         (set-network-process-option process :keepalive t))
1346       (gnus-set-process-query-on-exit-flag process nil)
1347       (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
1348                (memq (process-status process) '(open run)))
1349           (prog1
1350               (caar (push (list process buffer nil) nntp-connection-alist))
1351             (push process nntp-connection-list)
1352             (with-current-buffer pbuffer
1353               (nntp-read-server-type)
1354               (erase-buffer)
1355               (set-buffer nntp-server-buffer)
1356               (let ((nnheader-callback-function nil))
1357                 (run-hooks 'nntp-server-opened-hook)
1358                 (nntp-send-authinfo t))))
1359         (nntp-kill-buffer (process-buffer process))
1360         nil))))
1361
1362 (defun nntp-read-server-type ()
1363   "Find out what the name of the server we have connected to is."
1364   ;; Wait for the status string to arrive.
1365   (setq nntp-server-type (buffer-string))
1366   (let ((case-fold-search t))
1367     ;; Run server-specific commands.
1368     (dolist (entry nntp-server-action-alist)
1369       (when (string-match (car entry) nntp-server-type)
1370         (if (and (listp (cadr entry))
1371                  (not (eq 'lambda (caadr entry))))
1372             (eval (cadr entry))
1373           (funcall (cadr entry)))))))
1374
1375 (defun nntp-async-wait (process wait-for buffer decode callback)
1376   (with-current-buffer (process-buffer process)
1377     (unless nntp-inside-change-function
1378       (erase-buffer))
1379     (setq nntp-process-wait-for wait-for
1380           nntp-process-to-buffer buffer
1381           nntp-process-decode decode
1382           nntp-process-callback callback
1383           nntp-process-start-point (point-max))
1384     (setq after-change-functions '(nntp-after-change-function))))
1385
1386 (defun nntp-async-timer-handler ()
1387   (mapcar
1388    (lambda (proc)
1389      (if (memq (process-status proc) '(open run))
1390          (nntp-async-trigger proc)
1391        (nntp-async-stop proc)))
1392    nntp-async-process-list))
1393
1394 (defun nntp-async-stop (proc)
1395   (setq nntp-async-process-list (delq proc nntp-async-process-list))
1396   (when (and nntp-async-timer (not nntp-async-process-list))
1397     (nnheader-cancel-timer nntp-async-timer)
1398     (setq nntp-async-timer nil)))
1399
1400 (defun nntp-after-change-function (beg end len)
1401   (unwind-protect
1402       ;; we only care about insertions at eob
1403       (when (and (eq 0 len) (eq (point-max) end))
1404         (save-match-data
1405           (let ((proc (get-buffer-process (current-buffer))))
1406             (when proc
1407               (nntp-async-trigger proc)))))
1408     ;; any throw from after-change-functions will leave it
1409     ;; set to nil.  so we reset it here, if necessary.
1410     (when quit-flag
1411       (setq after-change-functions '(nntp-after-change-function)))))
1412
1413 (defun nntp-async-trigger (process)
1414   (with-current-buffer (process-buffer process)
1415     (when nntp-process-callback
1416       ;; do we have an error message?
1417       (goto-char nntp-process-start-point)
1418       (if (memq (following-char) '(?4 ?5))
1419           ;; wants credentials?
1420           (if (looking-at "480")
1421               (nntp-handle-authinfo process)
1422             ;; report error message.
1423             (nntp-snarf-error-message)
1424             (nntp-do-callback nil))
1425
1426         ;; got what we expect?
1427         (goto-char (point-max))
1428         (when (re-search-backward
1429                nntp-process-wait-for nntp-process-start-point t)
1430           (let ((response (match-string 0)))
1431             (with-current-buffer nntp-server-buffer
1432               (setq nntp-process-response response)))
1433           (nntp-async-stop process)
1434           ;; convert it.
1435           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1436             (let ((buf (current-buffer))
1437                   (start nntp-process-start-point)
1438                   (decode nntp-process-decode))
1439               (with-current-buffer nntp-process-to-buffer
1440                 (goto-char (point-max))
1441                 (save-restriction
1442                   (narrow-to-region (point) (point))
1443                   (nnheader-insert-buffer-substring buf start)
1444                   (when decode
1445                     (nntp-decode-text))))))
1446           ;; report it.
1447           (goto-char (point-max))
1448           (nntp-do-callback
1449            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1450
1451 (defun nntp-do-callback (arg)
1452   (let ((callback nntp-process-callback)
1453         (nntp-inside-change-function t))
1454     (setq nntp-process-callback nil)
1455     (funcall callback arg)))
1456
1457 (defun nntp-snarf-error-message ()
1458   "Save the error message in the current buffer."
1459   (let ((message (buffer-string)))
1460     (while (string-match "[\r\n]+" message)
1461       (setq message (replace-match " " t t message)))
1462     (nnheader-report 'nntp "%s" message)
1463     message))
1464
1465 (defun nntp-accept-process-output (process)
1466   "Wait for output from PROCESS and message some dots."
1467   (with-current-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1468                            nntp-server-buffer)
1469     (let ((len (/ (buffer-size) 1024))
1470           message-log-max)
1471       (unless (< len 10)
1472         (setq nntp-have-messaged t)
1473         (nnheader-message 7 "nntp read: %dk" len)))
1474     (prog1
1475         (nnheader-accept-process-output process)
1476       ;; accept-process-output may update status of process to indicate
1477       ;; that the server has closed the connection.  This MUST be
1478       ;; handled here as the buffer restored by the save-excursion may
1479       ;; be the process's former output buffer (i.e. now killed)
1480       (or (and process
1481                (memq (process-status process) '(open run)))
1482           (nntp-report "Server closed connection")))))
1483
1484 (defun nntp-accept-response ()
1485   "Wait for output from the process that outputs to BUFFER."
1486   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1487
1488 (defun nntp-possibly-change-group (group server &optional connectionless)
1489   (let ((nnheader-callback-function nil))
1490     (when server
1491       (or (nntp-server-opened server)
1492           (nntp-open-server server nil connectionless)))
1493
1494     (unless connectionless
1495       (or (nntp-find-connection nntp-server-buffer)
1496           (nntp-open-connection nntp-server-buffer))))
1497
1498   (when group
1499     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1500       (cond ((not entry)
1501              (nntp-report "Server closed connection"))
1502             ((not (equal group (caddr entry)))
1503              (with-current-buffer (process-buffer (car entry))
1504                (erase-buffer)
1505                (nntp-send-command "^[245].*\n" "GROUP" group)
1506                (setcar (cddr entry) group)
1507                (erase-buffer)
1508                (nntp-erase-buffer nntp-server-buffer)))))))
1509
1510 (defun nntp-decode-text (&optional cr-only)
1511   "Decode the text in the current buffer."
1512   (goto-char (point-min))
1513   (while (search-forward "\r" nil t)
1514     (delete-char -1))
1515   (unless cr-only
1516     ;; Remove trailing ".\n" end-of-transfer marker.
1517     (goto-char (point-max))
1518     (forward-line -1)
1519     (when (looking-at ".\n")
1520       (delete-char 2))
1521     ;; Delete status line.
1522     (goto-char (point-min))
1523     (while (looking-at "[1-5][0-9][0-9] .*\n")
1524       ;; For some unknown reason, there is more than one status line.
1525       (delete-region (point) (progn (forward-line 1) (point))))
1526     ;; Remove "." -> ".." encoding.
1527     (while (search-forward "\n.." nil t)
1528       (delete-char -1))))
1529
1530 (defun nntp-encode-text ()
1531   "Encode the text in the current buffer."
1532   (save-excursion
1533     ;; Replace "." at beginning of line with "..".
1534     (goto-char (point-min))
1535     (while (re-search-forward "^\\." nil t)
1536       (insert "."))
1537     (goto-char (point-max))
1538     ;; Insert newline at the end of the buffer.
1539     (unless (bolp)
1540       (insert "\n"))
1541     ;; Insert `.' at end of buffer (end of text mark).
1542     (goto-char (point-max))
1543     (insert ".\n")
1544     (goto-char (point-min))
1545     (while (not (eobp))
1546       (end-of-line)
1547       (delete-char 1)
1548       (insert nntp-end-of-line))))
1549
1550 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1551   (set-buffer nntp-server-buffer)
1552   (erase-buffer)
1553   (cond
1554
1555    ;; This server does not talk NOV.
1556    ((not nntp-server-xover)
1557     nil)
1558
1559    ;; We don't care about gaps.
1560    ((or (not nntp-nov-gap)
1561         fetch-old)
1562     (nntp-send-xover-command
1563      (if fetch-old
1564          (if (numberp fetch-old)
1565              (max 1 (- (car articles) fetch-old))
1566            1)
1567        (car articles))
1568      (car (last articles)) 'wait)
1569
1570     (goto-char (point-min))
1571     (when (looking-at "[1-5][0-9][0-9] .*\n")
1572       (delete-region (point) (progn (forward-line 1) (point))))
1573     (while (search-forward "\r" nil t)
1574       (replace-match "" t t))
1575     (goto-char (point-max))
1576     (forward-line -1)
1577     (when (looking-at "\\.")
1578       (delete-region (point) (progn (forward-line 1) (point)))))
1579
1580    ;; We do it the hard way.  For each gap, an XOVER command is sent
1581    ;; to the server.  We do not wait for a reply from the server, we
1582    ;; just send them off as fast as we can.  That means that we have
1583    ;; to count the number of responses we get back to find out when we
1584    ;; have gotten all we asked for.
1585    ((numberp nntp-nov-gap)
1586     (let ((count 0)
1587           (received 0)
1588           last-point
1589           in-process-buffer-p
1590           (buf nntp-server-buffer)
1591           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1592           first last status)
1593       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1594       ;; that means that the server does not understand XOVER, but we
1595       ;; won't know that until we try.
1596       (while (and nntp-server-xover articles)
1597         (setq first (car articles))
1598         ;; Search forward until we find a gap, or until we run out of
1599         ;; articles.
1600         (while (and (cdr articles)
1601                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1602           (setq articles (cdr articles)))
1603
1604         (setq in-process-buffer-p (stringp nntp-server-xover))
1605         (nntp-send-xover-command first (setq last (car articles)))
1606         (setq articles (cdr articles))
1607
1608         (when (and nntp-server-xover in-process-buffer-p)
1609           ;; Don't count tried request.
1610           (setq count (1+ count))
1611
1612           ;; Every 400 requests we have to read the stream in
1613           ;; order to avoid deadlocks.
1614           (when (or (null articles)     ;All requests have been sent.
1615                     (= 1 (% count nntp-maximum-request)))
1616
1617             (nntp-accept-response)
1618             ;; On some Emacs versions the preceding function has a
1619             ;; tendency to change the buffer.  Perhaps.  It's quite
1620             ;; difficult to reproduce, because it only seems to happen
1621             ;; once in a blue moon.
1622             (set-buffer process-buffer)
1623             (while (progn
1624                      (goto-char (or last-point (point-min)))
1625                      ;; Count replies.
1626                      (while (re-search-forward "^\\([0-9][0-9][0-9]\\) .*\n"
1627                                                nil t)
1628                        (incf received)
1629                        (setq status (match-string 1))
1630                        (if (string-match "^[45]" status)
1631                            (setq status 'error)
1632                          (setq status 'ok)))
1633                      (setq last-point (point))
1634                      (or (< received count)
1635                          (if (eq status 'error)
1636                              nil
1637                            ;; I haven't started reading the final response
1638                            (progn
1639                              (goto-char (point-max))
1640                              (forward-line -1)
1641                              (not (looking-at "^\\.\r?\n"))))))
1642               ;; I haven't read the end of the final response
1643               (nntp-accept-response)
1644               (set-buffer process-buffer))))
1645
1646         ;; Some nntp servers seem to have an extension to the XOVER
1647         ;; extension.  On these servers, requesting an article range
1648         ;; preceding the active range does not return an error as
1649         ;; specified in the RFC.  What we instead get is the NOV entry
1650         ;; for the first available article.  Obviously, a client can
1651         ;; use that entry to avoid making unnecessary requests.  The
1652         ;; only problem is for a client that assumes that the response
1653         ;; will always be within the requested range.  For such a
1654         ;; client, we can get N copies of the same entry (one for each
1655         ;; XOVER command sent to the server).
1656
1657         (when (<= count 1)
1658           (goto-char (point-min))
1659           (when (re-search-forward "^[0-9][0-9][0-9] .*\n\\([0-9]+\\)" nil t)
1660             (let ((low-limit (string-to-number
1661                               (buffer-substring (match-beginning 1)
1662                                                 (match-end 1)))))
1663               (while (and articles (<= (car articles) low-limit))
1664                 (setq articles (cdr articles))))))
1665         (set-buffer buf))
1666
1667       (when nntp-server-xover
1668         (when in-process-buffer-p
1669           (set-buffer buf)
1670           (goto-char (point-max))
1671           (nnheader-insert-buffer-substring process-buffer)
1672           (set-buffer process-buffer)
1673           (erase-buffer)
1674           (set-buffer buf))
1675
1676         ;; We remove any "." lines and status lines.
1677         (goto-char (point-min))
1678         (while (search-forward "\r" nil t)
1679           (delete-char -1))
1680         (goto-char (point-min))
1681         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1682         t))))
1683
1684   nntp-server-xover)
1685
1686 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1687   "Send the XOVER command to the server."
1688   (let ((range (format "%d-%d" beg end))
1689         (nntp-inhibit-erase t))
1690     (if (stringp nntp-server-xover)
1691         ;; If `nntp-server-xover' is a string, then we just send this
1692         ;; command.
1693         (if wait-for-reply
1694             (nntp-send-command-nodelete
1695              "\r?\n\\.\r?\n" nntp-server-xover range)
1696           ;; We do not wait for the reply.
1697           (nntp-send-command-nodelete nil nntp-server-xover range))
1698       (let ((commands nntp-xover-commands))
1699         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1700         ;; We try them all until we get at positive response.
1701         (while (and commands (eq nntp-server-xover 'try))
1702           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1703           (with-current-buffer nntp-server-buffer
1704             (goto-char (point-min))
1705             (and (looking-at "[23]")    ; No error message.
1706                  ;; We also have to look at the lines.  Some buggy
1707                  ;; servers give back simple lines with just the
1708                  ;; article number.  How... helpful.
1709                  (progn
1710                    (forward-line 1)
1711                    ;; More text after number, or a dot.
1712                    (looking-at "[0-9]+\t...\\|\\.\r?\n"))
1713                  (setq nntp-server-xover (car commands))))
1714           (setq commands (cdr commands)))
1715         ;; If none of the commands worked, we disable XOVER.
1716         (when (eq nntp-server-xover 'try)
1717           (nntp-erase-buffer nntp-server-buffer)
1718           (setq nntp-server-xover nil))
1719         nntp-server-xover))))
1720
1721 (defun nntp-find-group-and-number (&optional group)
1722   (save-excursion
1723     (save-restriction
1724       ;; FIXME: This is REALLY FISHY: set-buffer after save-restriction?!?
1725       (set-buffer nntp-server-buffer)
1726       (narrow-to-region (goto-char (point-min))
1727                         (or (search-forward "\n\n" nil t) (point-max)))
1728       (goto-char (point-min))
1729       ;; We first find the number by looking at the status line.
1730       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1731                          (string-to-number
1732                           (buffer-substring (match-beginning 1)
1733                                             (match-end 1)))))
1734             newsgroups xref)
1735         (and number (zerop number) (setq number nil))
1736         (if number
1737             ;; Then we find the group name.
1738             (setq group
1739                   (cond
1740                    ;; If there is only one group in the Newsgroups
1741                    ;; header, then it seems quite likely that this
1742                    ;; article comes from that group, I'd say.
1743                    ((and (setq newsgroups
1744                                (mail-fetch-field "newsgroups"))
1745                          (not (string-match "," newsgroups)))
1746                     newsgroups)
1747                    ;; If there is more than one group in the
1748                    ;; Newsgroups header, then the Xref header should
1749                    ;; be filled out.  We hazard a guess that the group
1750                    ;; that has this article number in the Xref header
1751                    ;; is the one we are looking for.  This might very
1752                    ;; well be wrong if this article happens to have
1753                    ;; the same number in several groups, but that's
1754                    ;; life.
1755                    ((and (setq xref (mail-fetch-field "xref"))
1756                          number
1757                          (string-match
1758                           (format "\\([^ :]+\\):%d" number) xref))
1759                     (match-string 1 xref))
1760                    (t "")))
1761           (cond
1762            ((and (not nntp-xref-number-is-evil)
1763                  (setq xref (mail-fetch-field "xref"))
1764                  (string-match
1765                   (if group
1766                       (concat "\\(" (regexp-quote group) "\\):\\([0-9]+\\)")
1767                     "\\([^ :]+\\):\\([0-9]+\\)")
1768                   xref))
1769             (setq group (match-string 1 xref)
1770                   number (string-to-number (match-string 2 xref))))
1771            ((and (setq newsgroups
1772                        (mail-fetch-field "newsgroups"))
1773                  (not (string-match "," newsgroups)))
1774             (setq group newsgroups))
1775            (group)
1776            (t (setq group ""))))
1777         (when (string-match "\r" group)
1778           (setq group (substring group 0 (match-beginning 0))))
1779         (cons group number)))))
1780
1781 (defun nntp-wait-for-string (regexp)
1782   "Wait until string arrives in the buffer."
1783   (let ((buf (current-buffer))
1784         proc)
1785     (goto-char (point-min))
1786     (while (and (setq proc (get-buffer-process buf))
1787                 (memq (process-status proc) '(open run))
1788                 (not (re-search-forward regexp nil t)))
1789       (accept-process-output proc 0.1)
1790       (set-buffer buf)
1791       (goto-char (point-min)))))
1792
1793
1794 ;; ==========================================================================
1795 ;; Obsolete nntp-open-* connection methods -- drv
1796 ;; ==========================================================================
1797
1798 (defvoo nntp-open-telnet-envuser nil
1799   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1800
1801 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1802   "*Regular expression to match the shell prompt on the remote machine.")
1803
1804 (defvoo nntp-rlogin-program "rsh"
1805   "*Program used to log in on remote machines.
1806 The default is \"rsh\", but \"ssh\" is a popular alternative.")
1807
1808 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1809   "*Parameters to `nntp-open-rlogin'.
1810 That function may be used as `nntp-open-connection-function'.  In that
1811 case, this list will be used as the parameter list given to rsh.")
1812
1813 (defvoo nntp-rlogin-user-name nil
1814   "*User name on remote system when using the rlogin connect method.")
1815
1816 (defvoo nntp-telnet-parameters
1817     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1818   "*Parameters to `nntp-open-telnet'.
1819 That function may be used as `nntp-open-connection-function'.  In that
1820 case, this list will be executed as a command after logging in
1821 via telnet.")
1822
1823 (defvoo nntp-telnet-user-name nil
1824   "User name to log in via telnet with.")
1825
1826 (defvoo nntp-telnet-passwd nil
1827   "Password to use to log in via telnet with.")
1828
1829 (defun nntp-service-to-port (svc)
1830   (cond
1831    ((integerp svc) (number-to-string svc))
1832    ((string-match "\\`[0-9]+\\'" svc) svc)
1833    (t
1834     (with-temp-buffer
1835       (ignore-errors (insert-file-contents "/etc/services"))
1836       (goto-char (point-min))
1837       (if (re-search-forward (concat "^" (regexp-quote svc)
1838                                      "[ \t]+\\([0-9]+\\)/tcp"))
1839           (match-string 1)
1840         svc)))))
1841
1842 (defun nntp-open-telnet (buffer)
1843   (with-current-buffer buffer
1844     (erase-buffer)
1845     (let ((proc (apply
1846                  'start-process
1847                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1848           (case-fold-search t))
1849       (when (memq (process-status proc) '(open run))
1850         (nntp-wait-for-string "^r?telnet")
1851         (process-send-string proc "set escape \^X\n")
1852         (cond
1853          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1854           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1855                                             nntp-address "\n")))
1856          (t
1857           (process-send-string proc (concat "open " nntp-address "\n"))))
1858         (cond
1859          ((not nntp-open-telnet-envuser)
1860           (nntp-wait-for-string "^\r*.?login:")
1861           (process-send-string
1862            proc (concat
1863                  (or nntp-telnet-user-name
1864                      (setq nntp-telnet-user-name (read-string "login: ")))
1865                  "\n"))))
1866         (nntp-wait-for-string "^\r*.?password:")
1867         (process-send-string
1868          proc (concat
1869                (or nntp-telnet-passwd
1870                    (setq nntp-telnet-passwd
1871                          (read-passwd "Password: ")))
1872                "\n"))
1873         (nntp-wait-for-string nntp-telnet-shell-prompt)
1874         (process-send-string
1875          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1876         (nntp-wait-for-string "^\r*20[01]")
1877         (beginning-of-line)
1878         (delete-region (point-min) (point))
1879         (process-send-string proc "\^]")
1880         (nntp-wait-for-string "^r?telnet")
1881         (process-send-string proc "mode character\n")
1882         (accept-process-output proc 1)
1883         (sit-for 1)
1884         (goto-char (point-min))
1885         (forward-line 1)
1886         (delete-region (point) (point-max)))
1887       proc)))
1888
1889 (defun nntp-open-rlogin (buffer)
1890   "Open a connection to SERVER using rsh."
1891   (let ((proc (if nntp-rlogin-user-name
1892                   (apply 'start-process
1893                          "nntpd" buffer nntp-rlogin-program
1894                          nntp-address "-l" nntp-rlogin-user-name
1895                          nntp-rlogin-parameters)
1896                 (apply 'start-process
1897                        "nntpd" buffer nntp-rlogin-program nntp-address
1898                        nntp-rlogin-parameters))))
1899     (with-current-buffer buffer
1900       (nntp-wait-for-string "^\r*20[01]")
1901       (beginning-of-line)
1902       (delete-region (point-min) (point))
1903       proc)))
1904
1905
1906 ;; ==========================================================================
1907 ;; Replacements for the nntp-open-* functions -- drv
1908 ;; ==========================================================================
1909
1910 (defun nntp-open-telnet-stream (buffer)
1911   "Open a nntp connection by telnet'ing the news server.
1912 `nntp-open-netcat-stream' is recommended in place of this function
1913 because it is more reliable.
1914
1915 Please refer to the following variables to customize the connection:
1916 - `nntp-pre-command',
1917 - `nntp-telnet-command',
1918 - `nntp-telnet-switches',
1919 - `nntp-address',
1920 - `nntp-port-number',
1921 - `nntp-end-of-line'."
1922   (let ((command `(,nntp-telnet-command
1923                    ,@nntp-telnet-switches
1924                    ,nntp-address
1925                    ,(nntp-service-to-port nntp-port-number)))
1926         proc)
1927     (and nntp-pre-command
1928          (push nntp-pre-command command))
1929     (setq proc (apply 'start-process "nntpd" buffer command))
1930     (with-current-buffer buffer
1931       (nntp-wait-for-string "^\r*20[01]")
1932       (beginning-of-line)
1933       (delete-region (point-min) (point))
1934       proc)))
1935
1936 (defun nntp-open-via-rlogin-and-telnet (buffer)
1937   "Open a connection to an nntp server through an intermediate host.
1938 First rlogin to the remote host, and then telnet the real news server
1939 from there.
1940 `nntp-open-via-rlogin-and-netcat' is recommended in place of this function
1941 because it is more reliable.
1942
1943 Please refer to the following variables to customize the connection:
1944 - `nntp-pre-command',
1945 - `nntp-via-rlogin-command',
1946 - `nntp-via-rlogin-command-switches',
1947 - `nntp-via-user-name',
1948 - `nntp-via-address',
1949 - `nntp-telnet-command',
1950 - `nntp-telnet-switches',
1951 - `nntp-address',
1952 - `nntp-port-number',
1953 - `nntp-end-of-line'."
1954   (let ((command `(,nntp-via-address
1955                    ,nntp-telnet-command
1956                    ,@nntp-telnet-switches))
1957         proc)
1958     (when nntp-via-user-name
1959       (setq command `("-l" ,nntp-via-user-name ,@command)))
1960     (when nntp-via-rlogin-command-switches
1961       (setq command (append nntp-via-rlogin-command-switches command)))
1962     (push nntp-via-rlogin-command command)
1963     (and nntp-pre-command
1964          (push nntp-pre-command command))
1965     (setq proc (apply 'start-process "nntpd" buffer command))
1966     (with-current-buffer buffer
1967       (nntp-wait-for-string "^r?telnet")
1968       (process-send-string proc (concat "open " nntp-address " "
1969                                         (nntp-service-to-port nntp-port-number)
1970                                         "\n"))
1971       (nntp-wait-for-string "^\r*20[01]")
1972       (beginning-of-line)
1973       (delete-region (point-min) (point))
1974       (process-send-string proc "\^]")
1975       (nntp-wait-for-string "^r?telnet")
1976       (process-send-string proc "mode character\n")
1977       (accept-process-output proc 1)
1978       (sit-for 1)
1979       (goto-char (point-min))
1980       (forward-line 1)
1981       (delete-region (point) (point-max)))
1982     proc))
1983
1984 (defun nntp-open-via-rlogin-and-netcat (buffer)
1985   "Open a connection to an nntp server through an intermediate host.
1986 First rlogin to the remote host, and then connect to the real news
1987 server from there using the netcat command.
1988
1989 Please refer to the following variables to customize the connection:
1990 - `nntp-pre-command',
1991 - `nntp-via-rlogin-command',
1992 - `nntp-via-rlogin-command-switches',
1993 - `nntp-via-user-name',
1994 - `nntp-via-address',
1995 - `nntp-netcat-command',
1996 - `nntp-netcat-switches',
1997 - `nntp-address',
1998 - `nntp-port-number'."
1999   (let ((command `(,@(when nntp-pre-command
2000                        (list nntp-pre-command))
2001                    ,nntp-via-rlogin-command
2002                    ,@nntp-via-rlogin-command-switches
2003                    ,@(when nntp-via-user-name
2004                        (list "-l" nntp-via-user-name))
2005                    ,nntp-via-address
2006                    ,nntp-netcat-command
2007                    ,@nntp-netcat-switches
2008                    ,nntp-address
2009                    ,(nntp-service-to-port nntp-port-number))))
2010     ;; A non-nil connection type results in mightily odd behavior where
2011     ;; (process-send-string proc "\^M") ends up sending a "\n" to the
2012     ;; ssh process.  --Stef
2013     ;; Also a nil connection allow ssh-askpass to work under X11.
2014     (let ((process-connection-type nil))
2015       (apply 'start-process "nntpd" buffer command))))
2016
2017 (defun nntp-open-netcat-stream (buffer)
2018   "Open a connection to an nntp server through netcat.
2019 I.e. use the `nc' command rather than Emacs's builtin networking code.
2020
2021 Please refer to the following variables to customize the connection:
2022 - `nntp-pre-command',
2023 - `nntp-netcat-command',
2024 - `nntp-netcat-switches',
2025 - `nntp-address',
2026 - `nntp-port-number'."
2027   (let ((command `(,nntp-netcat-command
2028                    ,@nntp-netcat-switches
2029                    ,nntp-address
2030                    ,(nntp-service-to-port nntp-port-number))))
2031     (and nntp-pre-command (push nntp-pre-command command))
2032     (let ((process-connection-type nil)) ;See `nntp-open-via-rlogin-and-netcat'.
2033       (apply 'start-process "nntpd" buffer command))))
2034
2035
2036 (defun nntp-open-via-telnet-and-telnet (buffer)
2037   "Open a connection to an nntp server through an intermediate host.
2038 First telnet the remote host, and then telnet the real news server
2039 from there.
2040
2041 Please refer to the following variables to customize the connection:
2042 - `nntp-pre-command',
2043 - `nntp-via-telnet-command',
2044 - `nntp-via-telnet-switches',
2045 - `nntp-via-address',
2046 - `nntp-via-envuser',
2047 - `nntp-via-user-name',
2048 - `nntp-via-user-password',
2049 - `nntp-via-shell-prompt',
2050 - `nntp-telnet-command',
2051 - `nntp-telnet-switches',
2052 - `nntp-address',
2053 - `nntp-port-number',
2054 - `nntp-end-of-line'."
2055   (with-current-buffer buffer
2056     (erase-buffer)
2057     (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
2058           (case-fold-search t)
2059           proc)
2060       (and nntp-pre-command (push nntp-pre-command command))
2061       (setq proc (apply 'start-process "nntpd" buffer command))
2062       (when (memq (process-status proc) '(open run))
2063         (nntp-wait-for-string "^r?telnet")
2064         (process-send-string proc "set escape \^X\n")
2065         (cond
2066          ((and nntp-via-envuser nntp-via-user-name)
2067           (process-send-string proc (concat "open " "-l" nntp-via-user-name
2068                                             nntp-via-address "\n")))
2069          (t
2070           (process-send-string proc (concat "open " nntp-via-address
2071                                             "\n"))))
2072         (when (not nntp-via-envuser)
2073           (nntp-wait-for-string "^\r*.?login:")
2074           (process-send-string proc
2075                                (concat
2076                                 (or nntp-via-user-name
2077                                     (setq nntp-via-user-name
2078                                           (read-string "login: ")))
2079                                 "\n")))
2080         (nntp-wait-for-string "^\r*.?password:")
2081         (process-send-string proc
2082                              (concat
2083                               (or nntp-via-user-password
2084                                   (setq nntp-via-user-password
2085                                         (read-passwd "Password: ")))
2086                               "\n"))
2087         (nntp-wait-for-string nntp-via-shell-prompt)
2088         (let ((real-telnet-command `("exec"
2089                                      ,nntp-telnet-command
2090                                      ,@nntp-telnet-switches
2091                                      ,nntp-address
2092                                      ,(nntp-service-to-port nntp-port-number))))
2093           (process-send-string proc
2094                                (concat (mapconcat 'identity
2095                                                   real-telnet-command " ")
2096                                        "\n")))
2097         (nntp-wait-for-string "^\r*20[01]")
2098         (beginning-of-line)
2099         (delete-region (point-min) (point))
2100         (process-send-string proc "\^]")
2101         (nntp-wait-for-string "^r?telnet")
2102         (process-send-string proc "mode character\n")
2103         (accept-process-output proc 1)
2104         (sit-for 1)
2105         (goto-char (point-min))
2106         (forward-line 1)
2107         (delete-region (point) (point-max)))
2108       proc)))
2109
2110 (provide 'nntp)
2111
2112 ;;; nntp.el ends here