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