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