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