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