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