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