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