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