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