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