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