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