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