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