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