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