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