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