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