* imap.el: Add compiler directives.
[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   (nntp-possibly-create-directory group server)
1029   (unless nntp-marks-is-evil
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   (nntp-possibly-create-directory group server)
1049   (when (and (not nntp-marks-is-evil) (nntp-marks-changed-p group server))
1050     (nnheader-message 8 "Updating marks for %s..." group)
1051     (nntp-open-marks group server)
1052     ;; Update info using `nntp-marks'.
1053     (mapc (lambda (pred)
1054             (unless (memq (cdr pred) gnus-article-unpropagated-mark-lists)
1055               (gnus-info-set-marks
1056                info
1057                (gnus-update-alist-soft
1058                 (cdr pred)
1059                 (cdr (assq (cdr pred) nntp-marks))
1060                 (gnus-info-marks info))
1061                t)))
1062           gnus-article-mark-lists)
1063     (let ((seen (cdr (assq 'read nntp-marks))))
1064       (gnus-info-set-read info
1065                           (if (and (integerp (car seen))
1066                                    (null (cdr seen)))
1067                               (list (cons (car seen) (car seen)))
1068                             seen)))
1069     (nnheader-message 8 "Updating marks for %s...done" group))
1070   info)
1071
1072
1073
1074 ;;; Hooky functions.
1075
1076 (defun nntp-send-mode-reader ()
1077   "Send the MODE READER command to the nntp server.
1078 This function is supposed to be called from `nntp-server-opened-hook'.
1079 It will make innd servers spawn an nnrpd process to allow actual article
1080 reading."
1081   (nntp-send-command "^.*\n" "MODE READER"))
1082
1083 (defun nntp-send-authinfo (&optional send-if-force)
1084   "Send the AUTHINFO to the nntp server.
1085 It will look in the \"~/.authinfo\" file for matching entries.  If
1086 nothing suitable is found there, it will prompt for a user name
1087 and a password.
1088
1089 If SEND-IF-FORCE, only send authinfo to the server if the
1090 .authinfo file has the FORCE token."
1091   (let* ((list (gnus-parse-netrc nntp-authinfo-file))
1092          (alist (gnus-netrc-machine list nntp-address "nntp"))
1093          (force (gnus-netrc-get alist "force"))
1094          (user (or (gnus-netrc-get alist "login") nntp-authinfo-user))
1095          (passwd (gnus-netrc-get alist "password")))
1096     (when (or (not send-if-force)
1097               force)
1098       (unless user
1099         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
1100               nntp-authinfo-user user))
1101       (unless (member user '(nil ""))
1102         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1103         (when t                         ;???Should check if AUTHINFO succeeded
1104           (nntp-send-command
1105            "^2.*\r?\n" "AUTHINFO PASS"
1106            (or passwd
1107                nntp-authinfo-password
1108                (setq nntp-authinfo-password
1109                      (read-passwd (format "NNTP (%s@%s) password: "
1110                                           user nntp-address))))))))))
1111
1112 (defun nntp-send-nosy-authinfo ()
1113   "Send the AUTHINFO to the nntp server."
1114   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
1115     (unless (member user '(nil ""))
1116       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1117       (when t                           ;???Should check if AUTHINFO succeeded
1118         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
1119                            (read-passwd (format "NNTP (%s@%s) password: "
1120                                                 user nntp-address)))))))
1121
1122 (defun nntp-send-authinfo-from-file ()
1123   "Send the AUTHINFO to the nntp server.
1124
1125 The authinfo login name is taken from the user's login name and the
1126 password contained in '~/.nntp-authinfo'."
1127   (when (file-exists-p "~/.nntp-authinfo")
1128     (with-temp-buffer
1129       (insert-file-contents "~/.nntp-authinfo")
1130       (goto-char (point-min))
1131       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
1132       (nntp-send-command
1133        "^2.*\r?\n" "AUTHINFO PASS"
1134        (buffer-substring (point) (point-at-eol))))))
1135
1136 ;;; Internal functions.
1137
1138 (defun nntp-handle-authinfo (process)
1139   "Take care of an authinfo response from the server."
1140   (let ((last nntp-last-command))
1141     (funcall nntp-authinfo-function)
1142     ;; We have to re-send the function that was interrupted by
1143     ;; the authinfo request.
1144     (nntp-erase-buffer nntp-server-buffer)
1145     (nntp-send-string process last)))
1146
1147 (defun nntp-make-process-buffer (buffer)
1148   "Create a new, fresh buffer usable for nntp process connections."
1149   (save-excursion
1150     (set-buffer
1151      (generate-new-buffer
1152       (format " *server %s %s %s*"
1153               nntp-address nntp-port-number
1154               (gnus-buffer-exists-p buffer))))
1155     (mm-enable-multibyte)
1156     (set (make-local-variable 'after-change-functions) nil)
1157     (set (make-local-variable 'nntp-process-wait-for) nil)
1158     (set (make-local-variable 'nntp-process-callback) nil)
1159     (set (make-local-variable 'nntp-process-to-buffer) nil)
1160     (set (make-local-variable 'nntp-process-start-point) nil)
1161     (set (make-local-variable 'nntp-process-decode) nil)
1162     (current-buffer)))
1163
1164 (defun nntp-open-connection (buffer)
1165   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
1166   (run-hooks 'nntp-prepare-server-hook)
1167   (let* ((pbuffer (nntp-make-process-buffer buffer))
1168          (timer
1169           (and nntp-connection-timeout
1170                (run-at-time
1171                 nntp-connection-timeout nil
1172                 `(lambda ()
1173                    (nntp-kill-buffer ,pbuffer)))))
1174          (process
1175           (condition-case ()
1176               (let ((coding-system-for-read nntp-coding-system-for-read)
1177                     (coding-system-for-write nntp-coding-system-for-write))
1178                 (funcall nntp-open-connection-function pbuffer))
1179             (error nil)
1180             (quit
1181              (message "Quit opening connection")
1182              (nntp-kill-buffer pbuffer)
1183              (signal 'quit nil)
1184              nil))))
1185     (when timer
1186       (nnheader-cancel-timer timer))
1187     (unless process
1188       (nntp-kill-buffer pbuffer))
1189     (when (and (buffer-name pbuffer)
1190                process)
1191       (process-kill-without-query process)
1192       (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
1193                (memq (process-status process) '(open run)))
1194           (prog1
1195               (caar (push (list process buffer nil) nntp-connection-alist))
1196             (push process nntp-connection-list)
1197             (save-excursion
1198               (set-buffer pbuffer)
1199               (nntp-read-server-type)
1200               (erase-buffer)
1201               (set-buffer nntp-server-buffer)
1202               (let ((nnheader-callback-function nil))
1203                 (run-hooks 'nntp-server-opened-hook)
1204                 (nntp-send-authinfo t))))
1205         (nntp-kill-buffer (process-buffer process))
1206         nil))))
1207
1208 (defun nntp-open-network-stream (buffer)
1209   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
1210
1211 (autoload 'format-spec "format")
1212 (autoload 'format-spec-make "format")
1213 (autoload 'open-tls-stream "tls")
1214
1215 (defun nntp-open-ssl-stream (buffer)
1216   (let* ((process-connection-type nil)
1217          (proc (start-process "nntpd" buffer 
1218                               shell-file-name
1219                               shell-command-switch
1220                               (format-spec nntp-ssl-program 
1221                                            (format-spec-make
1222                                             ?s nntp-address
1223                                             ?p nntp-port-number)))))
1224     (process-kill-without-query proc)
1225     (save-excursion
1226       (set-buffer buffer)
1227       (let ((nntp-connection-alist (list proc buffer nil)))
1228         (nntp-wait-for-string "^\r*20[01]"))
1229       (beginning-of-line)
1230       (delete-region (point-min) (point))
1231       proc)))
1232
1233 (defun nntp-open-tls-stream (buffer)
1234   (let ((proc (open-tls-stream "nntpd" buffer nntp-address nntp-port-number)))
1235     (process-kill-without-query proc)
1236     (save-excursion
1237       (set-buffer buffer)
1238       (let ((nntp-connection-alist (list proc buffer nil)))
1239         (nntp-wait-for-string "^\r*20[01]"))
1240       (beginning-of-line)
1241       (delete-region (point-min) (point))
1242       proc)))
1243
1244 (defun nntp-read-server-type ()
1245   "Find out what the name of the server we have connected to is."
1246   ;; Wait for the status string to arrive.
1247   (setq nntp-server-type (buffer-string))
1248   (let ((alist nntp-server-action-alist)
1249         (case-fold-search t)
1250         entry)
1251     ;; Run server-specific commands.
1252     (while alist
1253       (setq entry (pop alist))
1254       (when (string-match (car entry) nntp-server-type)
1255         (if (and (listp (cadr entry))
1256                  (not (eq 'lambda (caadr entry))))
1257             (eval (cadr entry))
1258           (funcall (cadr entry)))))))
1259
1260 (defun nntp-async-wait (process wait-for buffer decode callback)
1261   (save-excursion
1262     (set-buffer (process-buffer process))
1263     (unless nntp-inside-change-function
1264       (erase-buffer))
1265     (setq nntp-process-wait-for wait-for
1266           nntp-process-to-buffer buffer
1267           nntp-process-decode decode
1268           nntp-process-callback callback
1269           nntp-process-start-point (point-max))
1270     (setq after-change-functions '(nntp-after-change-function))
1271     (if nntp-async-needs-kluge
1272         (nntp-async-kluge process))))
1273
1274 (defun nntp-async-kluge (process)
1275   ;; emacs 20.3 bug: process output with encoding 'binary
1276   ;; doesn't trigger after-change-functions.
1277   (unless nntp-async-timer
1278     (setq nntp-async-timer
1279           (run-at-time 1 1 'nntp-async-timer-handler)))
1280   (add-to-list 'nntp-async-process-list process))
1281
1282 (defun nntp-async-timer-handler ()
1283   (mapcar
1284    (lambda (proc)
1285      (if (memq (process-status proc) '(open run))
1286          (nntp-async-trigger proc)
1287        (nntp-async-stop proc)))
1288    nntp-async-process-list))
1289
1290 (defun nntp-async-stop (proc)
1291   (setq nntp-async-process-list (delq proc nntp-async-process-list))
1292   (when (and nntp-async-timer (not nntp-async-process-list))
1293     (nnheader-cancel-timer nntp-async-timer)
1294     (setq nntp-async-timer nil)))
1295
1296 (defun nntp-after-change-function (beg end len)
1297   (unwind-protect
1298       ;; we only care about insertions at eob
1299       (when (and (eq 0 len) (eq (point-max) end))
1300         (save-match-data
1301           (let ((proc (get-buffer-process (current-buffer))))
1302             (when proc
1303               (nntp-async-trigger proc)))))
1304     ;; any throw from after-change-functions will leave it
1305     ;; set to nil.  so we reset it here, if necessary.
1306     (when quit-flag
1307       (setq after-change-functions '(nntp-after-change-function)))))
1308
1309 (defun nntp-async-trigger (process)
1310   (save-excursion
1311     (set-buffer (process-buffer process))
1312     (when nntp-process-callback
1313       ;; do we have an error message?
1314       (goto-char nntp-process-start-point)
1315       (if (memq (following-char) '(?4 ?5))
1316           ;; wants credentials?
1317           (if (looking-at "480")
1318               (nntp-handle-authinfo process)
1319             ;; report error message.
1320             (nntp-snarf-error-message)
1321             (nntp-do-callback nil))
1322
1323         ;; got what we expect?
1324         (goto-char (point-max))
1325         (when (re-search-backward
1326                nntp-process-wait-for nntp-process-start-point t)
1327           (let ((response (match-string 0)))
1328             (with-current-buffer nntp-server-buffer
1329               (setq nntp-process-response response)))
1330           (nntp-async-stop process)
1331           ;; convert it.
1332           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1333             (let ((buf (current-buffer))
1334                   (start nntp-process-start-point)
1335                   (decode nntp-process-decode))
1336               (save-excursion
1337                 (set-buffer nntp-process-to-buffer)
1338                 (goto-char (point-max))
1339                 (save-restriction
1340                   (narrow-to-region (point) (point))
1341                   (insert-buffer-substring buf start)
1342                   (when decode
1343                     (nntp-decode-text))))))
1344           ;; report it.
1345           (goto-char (point-max))
1346           (nntp-do-callback
1347            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1348
1349 (defun nntp-do-callback (arg)
1350   (let ((callback nntp-process-callback)
1351         (nntp-inside-change-function t))
1352     (setq nntp-process-callback nil)
1353     (funcall callback arg)))
1354
1355 (defun nntp-snarf-error-message ()
1356   "Save the error message in the current buffer."
1357   (let ((message (buffer-string)))
1358     (while (string-match "[\r\n]+" message)
1359       (setq message (replace-match " " t t message)))
1360     (nnheader-report 'nntp message)
1361     message))
1362
1363 (defun nntp-accept-process-output (process)
1364   "Wait for output from PROCESS and message some dots."
1365   (save-excursion
1366     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1367                     nntp-server-buffer))
1368     (let ((len (/ (buffer-size) 1024))
1369           message-log-max)
1370       (unless (< len 10)
1371         (setq nntp-have-messaged t)
1372         (nnheader-message 7 "nntp read: %dk" len)))
1373     (nnheader-accept-process-output process)
1374     ;; accept-process-output may update status of process to indicate
1375     ;; that the server has closed the connection.  This MUST be
1376     ;; handled here as the buffer restored by the save-excursion may
1377     ;; be the process's former output buffer (i.e. now killed)
1378     (or (and process 
1379              (memq (process-status process) '(open run)))
1380         (nntp-report "Server closed connection"))))
1381
1382 (defun nntp-accept-response ()
1383   "Wait for output from the process that outputs to BUFFER."
1384   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1385
1386 (defun nntp-possibly-change-group (group server &optional connectionless)
1387   (let ((nnheader-callback-function nil))
1388     (when server
1389       (or (nntp-server-opened server)
1390           (nntp-open-server server nil connectionless)))
1391
1392     (unless connectionless
1393       (or (nntp-find-connection nntp-server-buffer)
1394           (nntp-open-connection nntp-server-buffer))))
1395
1396   (when group
1397     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1398       (cond ((not entry)
1399              (nntp-report "Server closed connection"))
1400             ((not (equal group (caddr entry)))
1401              (save-excursion
1402                (set-buffer (process-buffer (car entry)))
1403                (erase-buffer)
1404                (nntp-send-command "^[245].*\n" "GROUP" group)
1405                (setcar (cddr entry) group)
1406                (erase-buffer)
1407                (nntp-erase-buffer nntp-server-buffer)))))))
1408
1409 (defun nntp-decode-text (&optional cr-only)
1410   "Decode the text in the current buffer."
1411   (goto-char (point-min))
1412   (while (search-forward "\r" nil t)
1413     (delete-char -1))
1414   (unless cr-only
1415     ;; Remove trailing ".\n" end-of-transfer marker.
1416     (goto-char (point-max))
1417     (forward-line -1)
1418     (when (looking-at ".\n")
1419       (delete-char 2))
1420     ;; Delete status line.
1421     (goto-char (point-min))
1422     (while (looking-at "[1-5][0-9][0-9] .*\n")
1423       ;; For some unknown reason, there is more than one status line.
1424       (delete-region (point) (progn (forward-line 1) (point))))
1425     ;; Remove "." -> ".." encoding.
1426     (while (search-forward "\n.." nil t)
1427       (delete-char -1))))
1428
1429 (defun nntp-encode-text ()
1430   "Encode the text in the current buffer."
1431   (save-excursion
1432     ;; Replace "." at beginning of line with "..".
1433     (goto-char (point-min))
1434     (while (re-search-forward "^\\." nil t)
1435       (insert "."))
1436     (goto-char (point-max))
1437     ;; Insert newline at the end of the buffer.
1438     (unless (bolp)
1439       (insert "\n"))
1440     ;; Insert `.' at end of buffer (end of text mark).
1441     (goto-char (point-max))
1442     (insert ".\n")
1443     (goto-char (point-min))
1444     (while (not (eobp))
1445       (end-of-line)
1446       (delete-char 1)
1447       (insert nntp-end-of-line))))
1448
1449 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1450   (set-buffer nntp-server-buffer)
1451   (erase-buffer)
1452   (cond
1453
1454    ;; This server does not talk NOV.
1455    ((not nntp-server-xover)
1456     nil)
1457
1458    ;; We don't care about gaps.
1459    ((or (not nntp-nov-gap)
1460         fetch-old)
1461     (nntp-send-xover-command
1462      (if fetch-old
1463          (if (numberp fetch-old)
1464              (max 1 (- (car articles) fetch-old))
1465            1)
1466        (car articles))
1467      (car (last articles)) 'wait)
1468
1469     (goto-char (point-min))
1470     (when (looking-at "[1-5][0-9][0-9] .*\n")
1471       (delete-region (point) (progn (forward-line 1) (point))))
1472     (while (search-forward "\r" nil t)
1473       (replace-match "" t t))
1474     (goto-char (point-max))
1475     (forward-line -1)
1476     (when (looking-at "\\.")
1477       (delete-region (point) (progn (forward-line 1) (point)))))
1478
1479    ;; We do it the hard way.  For each gap, an XOVER command is sent
1480    ;; to the server.  We do not wait for a reply from the server, we
1481    ;; just send them off as fast as we can.  That means that we have
1482    ;; to count the number of responses we get back to find out when we
1483    ;; have gotten all we asked for.
1484    ((numberp nntp-nov-gap)
1485     (let ((count 0)
1486           (received 0)
1487           last-point
1488           in-process-buffer-p
1489           (buf nntp-server-buffer)
1490           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1491           first last status)
1492       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1493       ;; that means that the server does not understand XOVER, but we
1494       ;; won't know that until we try.
1495       (while (and nntp-server-xover articles)
1496         (setq first (car articles))
1497         ;; Search forward until we find a gap, or until we run out of
1498         ;; articles.
1499         (while (and (cdr articles)
1500                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1501           (setq articles (cdr articles)))
1502
1503         (setq in-process-buffer-p (stringp nntp-server-xover))
1504         (nntp-send-xover-command first (setq last (car articles)))
1505         (setq articles (cdr articles))
1506
1507         (when (and nntp-server-xover in-process-buffer-p)
1508           ;; Don't count tried request.
1509           (setq count (1+ count))
1510
1511           ;; Every 400 requests we have to read the stream in
1512           ;; order to avoid deadlocks.
1513           (when (or (null articles)     ;All requests have been sent.
1514                     (= 1 (% count nntp-maximum-request)))
1515
1516             (nntp-accept-response)
1517             ;; On some Emacs versions the preceding function has a
1518             ;; tendency to change the buffer.  Perhaps.  It's quite
1519             ;; difficult to reproduce, because it only seems to happen
1520             ;; once in a blue moon.
1521             (set-buffer process-buffer)
1522             (while (progn
1523                      (goto-char (or last-point (point-min)))
1524                      ;; Count replies.
1525                      (while (re-search-forward "^\\([0-9][0-9][0-9]\\) .*\n"
1526                                                nil t)
1527                        (incf received)
1528                        (setq status (match-string 1))
1529                        (if (string-match "^[45]" status)
1530                            (setq status 'error)
1531                          (setq status 'ok)))
1532                      (setq last-point (point))
1533                      (or (< received count)
1534                          (if (eq status 'error)
1535                              nil
1536                            ;; I haven't started reading the final response
1537                            (progn
1538                              (goto-char (point-max))
1539                              (forward-line -1)
1540                              (not (looking-at "^\\.\r?\n"))))))
1541               ;; I haven't read the end of the final response
1542               (nntp-accept-response)
1543               (set-buffer process-buffer))))
1544
1545         ;; Some nntp servers seem to have an extension to the XOVER
1546         ;; extension.  On these servers, requesting an article range
1547         ;; preceeding the active range does not return an error as
1548         ;; specified in the RFC.  What we instead get is the NOV entry
1549         ;; for the first available article.  Obviously, a client can
1550         ;; use that entry to avoid making unnecessary requests.  The
1551         ;; only problem is for a client that assumes that the response
1552         ;; will always be within the requested ranage.  For such a
1553         ;; client, we can get N copies of the same entry (one for each
1554         ;; XOVER command sent to the server).
1555
1556         (when (<= count 1)
1557           (goto-char (point-min))
1558           (when (re-search-forward "^[0-9][0-9][0-9] .*\n\\([0-9]+\\)" nil t)
1559             (let ((low-limit (string-to-int
1560                               (buffer-substring (match-beginning 1) 
1561                                                 (match-end 1)))))
1562               (while (and articles (<= (car articles) low-limit))
1563                 (setq articles (cdr articles))))))
1564         (set-buffer buf))
1565
1566       (when nntp-server-xover
1567         (when in-process-buffer-p
1568           (set-buffer buf)
1569           (goto-char (point-max))
1570           (insert-buffer-substring process-buffer)
1571           (set-buffer process-buffer)
1572           (erase-buffer)
1573           (set-buffer buf))
1574
1575         ;; We remove any "." lines and status lines.
1576         (goto-char (point-min))
1577         (while (search-forward "\r" nil t)
1578           (delete-char -1))
1579         (goto-char (point-min))
1580         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1581         t))))
1582
1583   nntp-server-xover)
1584
1585 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1586   "Send the XOVER command to the server."
1587   (let ((range (format "%d-%d" beg end))
1588         (nntp-inhibit-erase t))
1589     (if (stringp nntp-server-xover)
1590         ;; If `nntp-server-xover' is a string, then we just send this
1591         ;; command.
1592         (if wait-for-reply
1593             (nntp-send-command-nodelete
1594              "\r?\n\\.\r?\n" nntp-server-xover range)
1595           ;; We do not wait for the reply.
1596           (nntp-send-command-nodelete nil nntp-server-xover range))
1597       (let ((commands nntp-xover-commands))
1598         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1599         ;; We try them all until we get at positive response.
1600         (while (and commands (eq nntp-server-xover 'try))
1601           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1602           (save-excursion
1603             (set-buffer nntp-server-buffer)
1604             (goto-char (point-min))
1605             (and (looking-at "[23]")    ; No error message.
1606                  ;; We also have to look at the lines.  Some buggy
1607                  ;; servers give back simple lines with just the
1608                  ;; article number.  How... helpful.
1609                  (progn
1610                    (forward-line 1)
1611                    (looking-at "[0-9]+\t...")) ; More text after number.
1612                  (setq nntp-server-xover (car commands))))
1613           (setq commands (cdr commands)))
1614         ;; If none of the commands worked, we disable XOVER.
1615         (when (eq nntp-server-xover 'try)
1616           (nntp-erase-buffer nntp-server-buffer)
1617           (setq nntp-server-xover nil))
1618         nntp-server-xover))))
1619
1620 (defun nntp-find-group-and-number (&optional group)
1621   (save-excursion
1622     (save-restriction
1623       (set-buffer nntp-server-buffer)
1624       (narrow-to-region (goto-char (point-min))
1625                         (or (search-forward "\n\n" nil t) (point-max)))
1626       (goto-char (point-min))
1627       ;; We first find the number by looking at the status line.
1628       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1629                          (string-to-int
1630                           (buffer-substring (match-beginning 1)
1631                                             (match-end 1)))))
1632             newsgroups xref)
1633         (and number (zerop number) (setq number nil))
1634         (if number
1635             ;; Then we find the group name.
1636             (setq group
1637                   (cond
1638                    ;; If there is only one group in the Newsgroups
1639                    ;; header, then it seems quite likely that this
1640                    ;; article comes from that group, I'd say.
1641                    ((and (setq newsgroups
1642                                (mail-fetch-field "newsgroups"))
1643                          (not (string-match "," newsgroups)))
1644                     newsgroups)
1645                    ;; If there is more than one group in the
1646                    ;; Newsgroups header, then the Xref header should
1647                    ;; be filled out.  We hazard a guess that the group
1648                    ;; that has this article number in the Xref header
1649                    ;; is the one we are looking for.  This might very
1650                    ;; well be wrong if this article happens to have
1651                    ;; the same number in several groups, but that's
1652                    ;; life.
1653                    ((and (setq xref (mail-fetch-field "xref"))
1654                          number
1655                          (string-match
1656                           (format "\\([^ :]+\\):%d" number) xref))
1657                     (match-string 1 xref))
1658                    (t "")))
1659           (cond
1660            ((and (setq xref (mail-fetch-field "xref"))
1661                  (string-match
1662                   (if group
1663                       (concat "\\(" (regexp-quote group) "\\):\\([0-9]+\\)")
1664                     "\\([^ :]+\\):\\([0-9]+\\)")
1665                   xref))
1666             (setq group (match-string 1 xref)
1667                   number (string-to-int (match-string 2 xref))))
1668            ((and (setq newsgroups
1669                        (mail-fetch-field "newsgroups"))
1670                  (not (string-match "," newsgroups)))
1671             (setq group newsgroups))
1672            (group)
1673            (t (setq group ""))))
1674         (when (string-match "\r" group)
1675           (setq group (substring group 0 (match-beginning 0))))
1676         (cons group number)))))
1677
1678 (defun nntp-wait-for-string (regexp)
1679   "Wait until string arrives in the buffer."
1680   (let ((buf (current-buffer))
1681         proc)
1682     (goto-char (point-min))
1683     (while (and (setq proc (get-buffer-process buf))
1684                 (memq (process-status proc) '(open run))
1685                 (not (re-search-forward regexp nil t)))
1686       (accept-process-output proc)
1687       (set-buffer buf)
1688       (goto-char (point-min)))))
1689
1690
1691 ;; ==========================================================================
1692 ;; Obsolete nntp-open-* connection methods -- drv
1693 ;; ==========================================================================
1694
1695 (defvoo nntp-open-telnet-envuser nil
1696   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1697
1698 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1699   "*Regular expression to match the shell prompt on the remote machine.")
1700
1701 (defvoo nntp-rlogin-program "rsh"
1702   "*Program used to log in on remote machines.
1703 The default is \"rsh\", but \"ssh\" is a popular alternative.")
1704
1705 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1706   "*Parameters to `nntp-open-rlogin'.
1707 That function may be used as `nntp-open-connection-function'.  In that
1708 case, this list will be used as the parameter list given to rsh.")
1709
1710 (defvoo nntp-rlogin-user-name nil
1711   "*User name on remote system when using the rlogin connect method.")
1712
1713 (defvoo nntp-telnet-parameters
1714     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1715   "*Parameters to `nntp-open-telnet'.
1716 That function may be used as `nntp-open-connection-function'.  In that
1717 case, this list will be executed as a command after logging in
1718 via telnet.")
1719
1720 (defvoo nntp-telnet-user-name nil
1721   "User name to log in via telnet with.")
1722
1723 (defvoo nntp-telnet-passwd nil
1724   "Password to use to log in via telnet with.")
1725
1726 (defun nntp-open-telnet (buffer)
1727   (save-excursion
1728     (set-buffer buffer)
1729     (erase-buffer)
1730     (let ((proc (apply
1731                  'start-process
1732                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1733           (case-fold-search t))
1734       (when (memq (process-status proc) '(open run))
1735         (nntp-wait-for-string "^r?telnet")
1736         (process-send-string proc "set escape \^X\n")
1737         (cond
1738          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1739           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1740                                             nntp-address "\n")))
1741          (t
1742           (process-send-string proc (concat "open " nntp-address "\n"))))
1743         (cond
1744          ((not nntp-open-telnet-envuser)
1745           (nntp-wait-for-string "^\r*.?login:")
1746           (process-send-string
1747            proc (concat
1748                  (or nntp-telnet-user-name
1749                      (setq nntp-telnet-user-name (read-string "login: ")))
1750                  "\n"))))
1751         (nntp-wait-for-string "^\r*.?password:")
1752         (process-send-string
1753          proc (concat
1754                (or nntp-telnet-passwd
1755                    (setq nntp-telnet-passwd
1756                          (read-passwd "Password: ")))
1757                "\n"))
1758         (nntp-wait-for-string nntp-telnet-shell-prompt)
1759         (process-send-string
1760          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1761         (nntp-wait-for-string "^\r*20[01]")
1762         (beginning-of-line)
1763         (delete-region (point-min) (point))
1764         (process-send-string proc "\^]")
1765         (nntp-wait-for-string "^r?telnet")
1766         (process-send-string proc "mode character\n")
1767         (accept-process-output proc 1)
1768         (sit-for 1)
1769         (goto-char (point-min))
1770         (forward-line 1)
1771         (delete-region (point) (point-max)))
1772       proc)))
1773
1774 (defun nntp-open-rlogin (buffer)
1775   "Open a connection to SERVER using rsh."
1776   (let ((proc (if nntp-rlogin-user-name
1777                   (apply 'start-process
1778                          "nntpd" buffer nntp-rlogin-program
1779                          nntp-address "-l" nntp-rlogin-user-name
1780                          nntp-rlogin-parameters)
1781                 (apply 'start-process
1782                        "nntpd" buffer nntp-rlogin-program nntp-address
1783                        nntp-rlogin-parameters))))
1784     (save-excursion
1785       (set-buffer buffer)
1786       (nntp-wait-for-string "^\r*20[01]")
1787       (beginning-of-line)
1788       (delete-region (point-min) (point))
1789       proc)))
1790
1791
1792 ;; ==========================================================================
1793 ;; Replacements for the nntp-open-* functions -- drv
1794 ;; ==========================================================================
1795
1796 (defun nntp-open-telnet-stream (buffer)
1797   "Open a nntp connection by telnet'ing the news server.
1798
1799 Please refer to the following variables to customize the connection:
1800 - `nntp-pre-command',
1801 - `nntp-telnet-command',
1802 - `nntp-telnet-switches',
1803 - `nntp-address',
1804 - `nntp-port-number',
1805 - `nntp-end-of-line'."
1806   (let ((command `(,nntp-telnet-command
1807                    ,@nntp-telnet-switches
1808                    ,nntp-address ,nntp-port-number))
1809         proc)
1810     (and nntp-pre-command
1811          (push nntp-pre-command command))
1812     (setq proc (apply 'start-process "nntpd" buffer command))
1813     (save-excursion
1814       (set-buffer buffer)
1815       (nntp-wait-for-string "^\r*20[01]")
1816       (beginning-of-line)
1817       (delete-region (point-min) (point))
1818       proc)))
1819
1820 (defun nntp-open-via-rlogin-and-telnet (buffer)
1821   "Open a connection to an nntp server through an intermediate host.
1822 First rlogin to the remote host, and then telnet the real news server
1823 from there.
1824
1825 Please refer to the following variables to customize the connection:
1826 - `nntp-pre-command',
1827 - `nntp-via-rlogin-command',
1828 - `nntp-via-rlogin-command-switches',
1829 - `nntp-via-user-name',
1830 - `nntp-via-address',
1831 - `nntp-telnet-command',
1832 - `nntp-telnet-switches',
1833 - `nntp-address',
1834 - `nntp-port-number',
1835 - `nntp-end-of-line'."
1836   (let ((command `(,nntp-via-address
1837                    ,nntp-telnet-command
1838                    ,@nntp-telnet-switches))
1839         proc)
1840     (when nntp-via-user-name
1841       (setq command `("-l" ,nntp-via-user-name ,@command)))
1842     (when nntp-via-rlogin-command-switches
1843       (setq command (append nntp-via-rlogin-command-switches command)))
1844     (push nntp-via-rlogin-command command)
1845     (and nntp-pre-command
1846          (push nntp-pre-command command))
1847     (setq proc (apply 'start-process "nntpd" buffer command))
1848     (save-excursion
1849       (set-buffer buffer)
1850       (nntp-wait-for-string "^r?telnet")
1851       (process-send-string proc (concat "open " nntp-address
1852                                         " " nntp-port-number "\n"))
1853       (nntp-wait-for-string "^\r*20[01]")
1854       (beginning-of-line)
1855       (delete-region (point-min) (point))
1856       (process-send-string proc "\^]")
1857       (nntp-wait-for-string "^r?telnet")
1858       (process-send-string proc "mode character\n")
1859       (accept-process-output proc 1)
1860       (sit-for 1)
1861       (goto-char (point-min))
1862       (forward-line 1)
1863       (delete-region (point) (point-max)))
1864     proc))
1865
1866 (defun nntp-open-via-rlogin-and-netcat (buffer)
1867   "Open a connection to an nntp server through an intermediate host.
1868 First rlogin to the remote host, and then connect to the real news
1869 server from there using the netcat command.
1870
1871 Please refer to the following variables to customize the connection:
1872 - `nntp-pre-command',
1873 - `nntp-via-rlogin-command',
1874 - `nntp-via-rlogin-command-switches',
1875 - `nntp-via-user-name',
1876 - `nntp-via-address',
1877 - `nntp-via-netcat-command',
1878 - `nntp-via-netcat-switches',
1879 - `nntp-address',
1880 - `nntp-port-number',
1881 - `nntp-end-of-line'."
1882   (let ((command `(,@(when nntp-pre-command
1883                        (list nntp-pre-command))
1884                    ,nntp-via-rlogin-command
1885                    ,@(when nntp-via-rlogin-command-switches
1886                        nntp-via-rlogin-command-switches)
1887                    ,@(when nntp-via-user-name
1888                        (list "-l" nntp-via-user-name))
1889                    ,nntp-via-address
1890                    ,nntp-via-netcat-command
1891                    ,@nntp-via-netcat-switches
1892                    ,nntp-address
1893                    ,nntp-port-number)))
1894     (apply 'start-process "nntpd" buffer command)))
1895
1896 (defun nntp-open-via-telnet-and-telnet (buffer)
1897   "Open a connection to an nntp server through an intermediate host.
1898 First telnet the remote host, and then telnet the real news server
1899 from there.
1900
1901 Please refer to the following variables to customize the connection:
1902 - `nntp-pre-command',
1903 - `nntp-via-telnet-command',
1904 - `nntp-via-telnet-switches',
1905 - `nntp-via-address',
1906 - `nntp-via-envuser',
1907 - `nntp-via-user-name',
1908 - `nntp-via-user-password',
1909 - `nntp-via-shell-prompt',
1910 - `nntp-telnet-command',
1911 - `nntp-telnet-switches',
1912 - `nntp-address',
1913 - `nntp-port-number',
1914 - `nntp-end-of-line'."
1915   (save-excursion
1916     (set-buffer buffer)
1917     (erase-buffer)
1918     (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
1919           (case-fold-search t)
1920           proc)
1921       (and nntp-pre-command (push nntp-pre-command command))
1922       (setq proc (apply 'start-process "nntpd" buffer command))
1923       (when (memq (process-status proc) '(open run))
1924         (nntp-wait-for-string "^r?telnet")
1925         (process-send-string proc "set escape \^X\n")
1926         (cond
1927          ((and nntp-via-envuser nntp-via-user-name)
1928           (process-send-string proc (concat "open " "-l" nntp-via-user-name
1929                                             nntp-via-address "\n")))
1930          (t
1931           (process-send-string proc (concat "open " nntp-via-address
1932                                             "\n"))))
1933         (when (not nntp-via-envuser)
1934           (nntp-wait-for-string "^\r*.?login:")
1935           (process-send-string proc
1936                                (concat
1937                                 (or nntp-via-user-name
1938                                     (setq nntp-via-user-name
1939                                           (read-string "login: ")))
1940                                 "\n")))
1941         (nntp-wait-for-string "^\r*.?password:")
1942         (process-send-string proc
1943                              (concat
1944                               (or nntp-via-user-password
1945                                   (setq nntp-via-user-password
1946                                         (read-passwd "Password: ")))
1947                               "\n"))
1948         (nntp-wait-for-string nntp-via-shell-prompt)
1949         (let ((real-telnet-command `("exec"
1950                                      ,nntp-telnet-command
1951                                      ,@nntp-telnet-switches
1952                                      ,nntp-address
1953                                      ,nntp-port-number)))
1954           (process-send-string proc
1955                                (concat (mapconcat 'identity
1956                                                   real-telnet-command " ")
1957                                        "\n")))
1958         (nntp-wait-for-string "^\r*20[01]")
1959         (beginning-of-line)
1960         (delete-region (point-min) (point))
1961         (process-send-string proc "\^]")
1962         (nntp-wait-for-string "^r?telnet")
1963         (process-send-string proc "mode character\n")
1964         (accept-process-output proc 1)
1965         (sit-for 1)
1966         (goto-char (point-min))
1967         (forward-line 1)
1968         (delete-region (point) (point-max)))
1969       proc)))
1970
1971 ;; Marks handling
1972
1973 (defun nntp-marks-directory (server)
1974   (expand-file-name server nntp-marks-directory))
1975
1976 (defun nntp-possibly-create-directory (group server)
1977   (let ((dir (nnmail-group-pathname
1978               group (nntp-marks-directory server))))
1979     (unless (file-exists-p dir)
1980       (make-directory (directory-file-name dir) t)
1981       (nnheader-message 5 "Creating nntp marks directory %s" dir))))
1982
1983 (defun nntp-marks-changed-p (group server)
1984   (let ((file (expand-file-name
1985                nntp-marks-file-name 
1986                (nnmail-group-pathname
1987                 group (nntp-marks-directory server)))))
1988     (if (null (gnus-gethash file nntp-marks-modtime))
1989         t ;; never looked at marks file, assume it has changed
1990       (not (equal (gnus-gethash file nntp-marks-modtime)
1991                   (nth 5 (file-attributes file)))))))
1992
1993 (defun nntp-save-marks (group server)
1994   (let ((file-name-coding-system nnmail-pathname-coding-system)
1995         (file (expand-file-name
1996                nntp-marks-file-name 
1997                (nnmail-group-pathname
1998                 group (nntp-marks-directory server)))))
1999     (condition-case err
2000         (progn
2001           (nntp-possibly-create-directory group server)
2002           (with-temp-file file
2003             (erase-buffer)
2004             (gnus-prin1 nntp-marks)
2005             (insert "\n"))
2006           (gnus-sethash file
2007                         (nth 5 (file-attributes file))
2008                         nntp-marks-modtime))
2009       (error (or (gnus-yes-or-no-p
2010                   (format "Could not write to %s (%s).  Continue? " file err))
2011                  (error "Cannot write to %s (%s)" file err))))))
2012
2013 (defun nntp-open-marks (group server)
2014   (let ((file (expand-file-name
2015                nntp-marks-file-name
2016                (nnmail-group-pathname
2017                 group (nntp-marks-directory server)))))
2018     (if (file-exists-p file)
2019         (condition-case err
2020             (with-temp-buffer
2021               (gnus-sethash file (nth 5 (file-attributes file))
2022                             nntp-marks-modtime)
2023               (nnheader-insert-file-contents file)
2024               (setq nntp-marks (read (current-buffer)))
2025               (dolist (el gnus-article-unpropagated-mark-lists)
2026                 (setq nntp-marks (gnus-remassoc el nntp-marks))))
2027           (error (or (gnus-yes-or-no-p
2028                       (format "Error reading nntp marks file %s (%s).  Continuing will use marks from .newsrc.eld.  Continue? " file err))
2029                      (error "Cannot read nntp marks file %s (%s)" file err))))
2030       ;; User didn't have a .marks file.  Probably first time
2031       ;; user of the .marks stuff.  Bootstrap it from .newsrc.eld.
2032       (let ((info (gnus-get-info
2033                    (gnus-group-prefixed-name
2034                     group
2035                     (gnus-server-to-method (format "nntp:%s" server))))))
2036         (nnheader-message 7 "Bootstrapping marks for %s..." group)
2037         (setq nntp-marks (gnus-info-marks info))
2038         (push (cons 'read (gnus-info-read info)) nntp-marks)
2039         (dolist (el gnus-article-unpropagated-mark-lists)
2040           (setq nntp-marks (gnus-remassoc el nntp-marks)))
2041         (nntp-save-marks group server)
2042         (nnheader-message 7 "Bootstrapping marks for %s...done" group)))))
2043
2044 (provide 'nntp)
2045
2046 ;;; nntp.el ends here