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