2001-07-19 Katsumi Yamaoka <yamaoka@jpl.org>
[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 (with-current-buffer buffer (point))))
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) (gnus-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 (with-current-buffer buffer (point))))
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) (gnus-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 (with-current-buffer buffer (point))))
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) (gnus-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     (let* ((time (date-to-time date))
821            (ls (- (cadr time) (nth 8 (decode-time time)))))
822       (cond ((< ls 0)
823              (setcar time (1- (car time)))
824              (setcar (cdr time) (+ ls 65536)))
825             ((>= ls 65536)
826              (setcar time (1+ (car time)))
827              (setcar (cdr time) (- ls 65536)))
828             (t
829              (setcar (cdr time) ls)))
830       (prog1
831           (nntp-send-command
832            "^\\.\r?\n" "NEWGROUPS"
833            (format-time-string "%y%m%d %H%M%S" time)
834            "GMT")
835         (nntp-decode-text)))))
836
837 (deffoo nntp-request-post (&optional server)
838   (nntp-possibly-change-group nil server)
839   (when (nntp-send-command "^[23].*\r?\n" "POST")
840     (nntp-send-buffer "^[23].*\n")))
841
842 (deffoo nntp-request-type (group article)
843   'news)
844
845 (deffoo nntp-asynchronous-p ()
846   t)
847
848 ;;; Hooky functions.
849
850 (defun nntp-send-mode-reader ()
851   "Send the MODE READER command to the nntp server.
852 This function is supposed to be called from `nntp-server-opened-hook'.
853 It will make innd servers spawn an nnrpd process to allow actual article
854 reading."
855   (nntp-send-command "^.*\n" "MODE READER"))
856
857 (defun nntp-send-authinfo (&optional send-if-force)
858   "Send the AUTHINFO to the nntp server.
859 It will look in the \"~/.authinfo\" file for matching entries.  If
860 nothing suitable is found there, it will prompt for a user name
861 and a password.
862
863 If SEND-IF-FORCE, only send authinfo to the server if the
864 .authinfo file has the FORCE token."
865   (let* ((list (gnus-parse-netrc nntp-authinfo-file))
866          (alist (gnus-netrc-machine list nntp-address "nntp"))
867          (force (gnus-netrc-get alist "force"))
868          (user (or (gnus-netrc-get alist "login") nntp-authinfo-user))
869          (passwd (gnus-netrc-get alist "password")))
870     (when (or (not send-if-force)
871               force)
872       (unless user
873         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
874               nntp-authinfo-user user))
875       (unless (member user '(nil ""))
876         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
877         (when t                         ;???Should check if AUTHINFO succeeded
878           (nntp-send-command
879            "^2.*\r?\n" "AUTHINFO PASS"
880            (or passwd
881                nntp-authinfo-password
882                (setq nntp-authinfo-password
883                      (mail-source-read-passwd
884                       (format "NNTP (%s@%s) password: "
885                               user nntp-address))))))))))
886
887 (defun nntp-send-nosy-authinfo ()
888   "Send the AUTHINFO to the nntp server."
889   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
890     (unless (member user '(nil ""))
891       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
892       (when t                           ;???Should check if AUTHINFO succeeded
893         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
894                            (mail-source-read-passwd "NNTP (%s@%s) password: "
895                                                     user nntp-address))))))
896
897 (defun nntp-send-authinfo-from-file ()
898   "Send the AUTHINFO to the nntp server.
899
900 The authinfo login name is taken from the user's login name and the
901 password contained in '~/.nntp-authinfo'."
902   (when (file-exists-p "~/.nntp-authinfo")
903     (with-temp-buffer
904       (insert-file-contents "~/.nntp-authinfo")
905       (goto-char (point-min))
906       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
907       (nntp-send-command
908        "^2.*\r?\n" "AUTHINFO PASS"
909        (buffer-substring (point) (progn (end-of-line) (point)))))))
910
911 ;;; Internal functions.
912
913 (defun nntp-handle-authinfo (process)
914   "Take care of an authinfo response from the server."
915   (let ((last nntp-last-command))
916     (funcall nntp-authinfo-function)
917     ;; We have to re-send the function that was interrupted by
918     ;; the authinfo request.
919     (save-excursion
920       (set-buffer nntp-server-buffer)
921       (erase-buffer))
922     (nntp-send-string process last)))
923
924 (defun nntp-make-process-buffer (buffer)
925   "Create a new, fresh buffer usable for nntp process connections."
926   (save-excursion
927     (set-buffer
928      (generate-new-buffer
929       (format " *server %s %s %s*"
930               nntp-address nntp-port-number
931               (gnus-buffer-exists-p buffer))))
932     (mm-enable-multibyte)
933     (set (make-local-variable 'after-change-functions) nil)
934     (set (make-local-variable 'nntp-process-wait-for) nil)
935     (set (make-local-variable 'nntp-process-callback) nil)
936     (set (make-local-variable 'nntp-process-to-buffer) nil)
937     (set (make-local-variable 'nntp-process-start-point) nil)
938     (set (make-local-variable 'nntp-process-decode) nil)
939     (current-buffer)))
940
941 (defun nntp-open-connection (buffer)
942   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
943   (run-hooks 'nntp-prepare-server-hook)
944   (let* ((pbuffer (nntp-make-process-buffer buffer))
945          (timer
946           (and nntp-connection-timeout
947                (nnheader-run-at-time
948                 nntp-connection-timeout nil
949                 `(lambda ()
950                    (nntp-kill-buffer ,pbuffer)))))
951          (process
952           (condition-case ()
953               (let ((coding-system-for-read nntp-coding-system-for-read)
954                     (coding-system-for-write nntp-coding-system-for-write))
955                 (funcall nntp-open-connection-function pbuffer))
956             (error nil)
957             (quit
958              (message "Quit opening connection")
959              (nntp-kill-buffer pbuffer)
960              (signal 'quit nil)
961              nil))))
962     (when timer
963       (nnheader-cancel-timer timer))
964     (unless process
965       (nntp-kill-buffer pbuffer))
966     (when (and (buffer-name pbuffer)
967                process)
968       (process-kill-without-query process)
969       (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
970                (memq (process-status process) '(open run)))
971           (prog1
972               (caar (push (list process buffer nil) nntp-connection-alist))
973             (push process nntp-connection-list)
974             (save-excursion
975               (set-buffer pbuffer)
976               (nntp-read-server-type)
977               (erase-buffer)
978               (set-buffer nntp-server-buffer)
979               (let ((nnheader-callback-function nil))
980                 (run-hooks 'nntp-server-opened-hook)
981                 (nntp-send-authinfo t))))
982         (nntp-kill-buffer (process-buffer process))
983         nil))))
984
985 (defun nntp-open-network-stream (buffer)
986   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
987
988 (defun nntp-open-ssl-stream (buffer)
989   (let* ((ssl-program-arguments '("-connect" (concat host ":" service)))
990          (proc (open-ssl-stream "nntpd" buffer nntp-address nntp-port-number)))
991     (save-excursion
992       (set-buffer buffer)
993       (nntp-wait-for-string "^\r*20[01]")
994       (beginning-of-line)
995       (delete-region (point-min) (point))
996       proc)))
997
998 (defun nntp-read-server-type ()
999   "Find out what the name of the server we have connected to is."
1000   ;; Wait for the status string to arrive.
1001   (setq nntp-server-type (buffer-string))
1002   (let ((alist nntp-server-action-alist)
1003         (case-fold-search t)
1004         entry)
1005     ;; Run server-specific commands.
1006     (while alist
1007       (setq entry (pop alist))
1008       (when (string-match (car entry) nntp-server-type)
1009         (if (and (listp (cadr entry))
1010                  (not (eq 'lambda (caadr entry))))
1011             (eval (cadr entry))
1012           (funcall (cadr entry)))))))
1013
1014 (defun nntp-async-wait (process wait-for buffer decode callback)
1015   (save-excursion
1016     (set-buffer (process-buffer process))
1017     (unless nntp-inside-change-function
1018       (erase-buffer))
1019     (setq nntp-process-wait-for wait-for
1020           nntp-process-to-buffer buffer
1021           nntp-process-decode decode
1022           nntp-process-callback callback
1023           nntp-process-start-point (point-max))
1024     (setq after-change-functions '(nntp-after-change-function))
1025     (if nntp-async-needs-kluge
1026         (nntp-async-kluge process))))
1027
1028 (defun nntp-async-kluge (process)
1029   ;; emacs 20.3 bug: process output with encoding 'binary
1030   ;; doesn't trigger after-change-functions.
1031   (unless nntp-async-timer
1032     (setq nntp-async-timer
1033           (nnheader-run-at-time 1 1 'nntp-async-timer-handler)))
1034   (add-to-list 'nntp-async-process-list process))
1035
1036 (defun nntp-async-timer-handler ()
1037   (mapcar
1038    (lambda (proc)
1039      (if (memq (process-status proc) '(open run))
1040          (nntp-async-trigger proc)
1041        (nntp-async-stop proc)))
1042    nntp-async-process-list))
1043
1044 (defun nntp-async-stop (proc)
1045   (setq nntp-async-process-list (delq proc nntp-async-process-list))
1046   (when (and nntp-async-timer (not nntp-async-process-list))
1047     (nnheader-cancel-timer nntp-async-timer)
1048     (setq nntp-async-timer nil)))
1049
1050 (defun nntp-after-change-function (beg end len)
1051   (unwind-protect
1052       ;; we only care about insertions at eob
1053       (when (and (eq 0 len) (eq (point-max) end))
1054         (save-match-data
1055           (let ((proc (get-buffer-process (current-buffer))))
1056             (when proc
1057               (nntp-async-trigger proc)))))
1058     ;; any throw from after-change-functions will leave it
1059     ;; set to nil.  so we reset it here, if necessary.
1060     (when quit-flag
1061       (setq after-change-functions '(nntp-after-change-function)))))
1062
1063 (defun nntp-async-trigger (process)
1064   (save-excursion
1065     (set-buffer (process-buffer process))
1066     (when nntp-process-callback
1067       ;; do we have an error message?
1068       (goto-char nntp-process-start-point)
1069       (if (memq (following-char) '(?4 ?5))
1070           ;; wants credentials?
1071           (if (looking-at "480")
1072               (nntp-handle-authinfo process)
1073             ;; report error message.
1074             (nntp-snarf-error-message)
1075             (nntp-do-callback nil))
1076
1077         ;; got what we expect?
1078         (goto-char (point-max))
1079         (when (re-search-backward
1080                nntp-process-wait-for nntp-process-start-point t)
1081           (nntp-async-stop process)
1082           ;; convert it.
1083           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1084             (let ((buf (current-buffer))
1085                   (start nntp-process-start-point)
1086                   (decode nntp-process-decode))
1087               (save-excursion
1088                 (set-buffer nntp-process-to-buffer)
1089                 (goto-char (point-max))
1090                 (save-restriction
1091                   (narrow-to-region (point) (point))
1092                   (insert-buffer-substring buf start)
1093                   (when decode
1094                     (nntp-decode-text))))))
1095           ;; report it.
1096           (goto-char (point-max))
1097           (nntp-do-callback
1098            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1099
1100 (defun nntp-do-callback (arg)
1101   (let ((callback nntp-process-callback)
1102         (nntp-inside-change-function t))
1103     (setq nntp-process-callback nil)
1104     (funcall callback arg)))
1105
1106 (defun nntp-snarf-error-message ()
1107   "Save the error message in the current buffer."
1108   (let ((message (buffer-string)))
1109     (while (string-match "[\r\n]+" message)
1110       (setq message (replace-match " " t t message)))
1111     (nnheader-report 'nntp message)
1112     message))
1113
1114 (defun nntp-accept-process-output (process &optional timeout)
1115   "Wait for output from PROCESS and message some dots."
1116   (save-excursion
1117     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1118                     nntp-server-buffer))
1119     (let ((len (/ (point-max) 1024))
1120           message-log-max)
1121       (unless (< len 10)
1122         (setq nntp-have-messaged t)
1123         (nnheader-message 7 "nntp read: %dk" len)))
1124     (accept-process-output process (or timeout 1))))
1125
1126 (defun nntp-accept-response ()
1127   "Wait for output from the process that outputs to BUFFER."
1128   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1129
1130 (defun nntp-possibly-change-group (group server &optional connectionless)
1131   (let ((nnheader-callback-function nil))
1132     (when server
1133       (or (nntp-server-opened server)
1134           (nntp-open-server server nil connectionless)))
1135
1136     (unless connectionless
1137       (or (nntp-find-connection nntp-server-buffer)
1138           (nntp-open-connection nntp-server-buffer))))
1139
1140   (when group
1141     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1142       (when (not (equal group (caddr entry)))
1143         (save-excursion
1144           (set-buffer (process-buffer (car entry)))
1145           (erase-buffer)
1146           (nntp-send-command "^[245].*\n" "GROUP" group)
1147           (setcar (cddr entry) group)
1148           (erase-buffer))))))
1149
1150 (defun nntp-decode-text (&optional cr-only)
1151   "Decode the text in the current buffer."
1152   (goto-char (point-min))
1153   (while (search-forward "\r" nil t)
1154     (delete-char -1))
1155   (unless cr-only
1156     ;; Remove trailing ".\n" end-of-transfer marker.
1157     (goto-char (point-max))
1158     (forward-line -1)
1159     (when (looking-at ".\n")
1160       (delete-char 2))
1161     ;; Delete status line.
1162     (goto-char (point-min))
1163     (while (looking-at "[1-5][0-9][0-9] .*\n")
1164       ;; For some unknown reason, there is more than one status line.
1165       (delete-region (point) (progn (forward-line 1) (point))))
1166     ;; Remove "." -> ".." encoding.
1167     (while (search-forward "\n.." nil t)
1168       (delete-char -1))))
1169
1170 (defun nntp-encode-text ()
1171   "Encode the text in the current buffer."
1172   (save-excursion
1173     ;; Replace "." at beginning of line with "..".
1174     (goto-char (point-min))
1175     (while (re-search-forward "^\\." nil t)
1176       (insert "."))
1177     (goto-char (point-max))
1178     ;; Insert newline at the end of the buffer.
1179     (unless (bolp)
1180       (insert "\n"))
1181     ;; Insert `.' at end of buffer (end of text mark).
1182     (goto-char (point-max))
1183     (insert ".\n")
1184     (goto-char (point-min))
1185     (while (not (eobp))
1186       (end-of-line)
1187       (delete-char 1)
1188       (insert nntp-end-of-line))))
1189
1190 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1191   (set-buffer nntp-server-buffer)
1192   (erase-buffer)
1193   (cond
1194
1195    ;; This server does not talk NOV.
1196    ((not nntp-server-xover)
1197     nil)
1198
1199    ;; We don't care about gaps.
1200    ((or (not nntp-nov-gap)
1201         fetch-old)
1202     (nntp-send-xover-command
1203      (if fetch-old
1204          (if (numberp fetch-old)
1205              (max 1 (- (car articles) fetch-old))
1206            1)
1207        (car articles))
1208      (car (last articles)) 'wait)
1209
1210     (goto-char (point-min))
1211     (when (looking-at "[1-5][0-9][0-9] .*\n")
1212       (delete-region (point) (progn (forward-line 1) (point))))
1213     (while (search-forward "\r" nil t)
1214       (replace-match "" t t))
1215     (goto-char (point-max))
1216     (forward-line -1)
1217     (when (looking-at "\\.")
1218       (delete-region (point) (progn (forward-line 1) (point)))))
1219
1220    ;; We do it the hard way.  For each gap, an XOVER command is sent
1221    ;; to the server.  We do not wait for a reply from the server, we
1222    ;; just send them off as fast as we can.  That means that we have
1223    ;; to count the number of responses we get back to find out when we
1224    ;; have gotten all we asked for.
1225    ((numberp nntp-nov-gap)
1226     (let ((count 0)
1227           (received 0)
1228           last-point
1229           in-process-buffer-p
1230           (buf nntp-server-buffer)
1231           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1232           first)
1233       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1234       ;; that means that the server does not understand XOVER, but we
1235       ;; won't know that until we try.
1236       (while (and nntp-server-xover articles)
1237         (setq first (car articles))
1238         ;; Search forward until we find a gap, or until we run out of
1239         ;; articles.
1240         (while (and (cdr articles)
1241                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1242           (setq articles (cdr articles)))
1243
1244         (setq in-process-buffer-p (stringp nntp-server-xover))
1245         (nntp-send-xover-command first (car articles))
1246         (setq articles (cdr articles))
1247
1248         (when (and nntp-server-xover in-process-buffer-p)
1249           ;; Don't count tried request.
1250           (setq count (1+ count))
1251
1252           ;; Every 400 requests we have to read the stream in
1253           ;; order to avoid deadlocks.
1254           (when (or (null articles)     ;All requests have been sent.
1255                     (zerop (% count nntp-maximum-request)))
1256
1257             (nntp-accept-response)
1258             ;; On some Emacs versions the preceding function has a
1259             ;; tendency to change the buffer.  Perhaps.  It's quite
1260             ;; difficult to reproduce, because it only seems to happen
1261             ;; once in a blue moon.
1262             (set-buffer process-buffer)
1263             (while (progn
1264                      (goto-char (or last-point (point-min)))
1265                      ;; Count replies.
1266                      (while (re-search-forward "^[0-9][0-9][0-9] .*\n" nil t)
1267                        (incf received))
1268                      (setq last-point (point))
1269                      (< received count))
1270               (nntp-accept-response)
1271               (set-buffer process-buffer))
1272             (set-buffer buf))))
1273
1274       (when nntp-server-xover
1275         (when in-process-buffer-p
1276           (set-buffer process-buffer)
1277           ;; Wait for the reply from the final command.
1278           (goto-char (point-max))
1279           (while (not (re-search-backward "^[0-9][0-9][0-9] " nil t))
1280             (nntp-accept-response)
1281             (set-buffer process-buffer)
1282             (goto-char (point-max)))
1283           (when (looking-at "^[23]")
1284             (while (progn
1285                      (goto-char (point-max))
1286                      (forward-line -1)
1287                      (not (looking-at "^\\.\r?\n")))
1288               (nntp-accept-response)
1289               (set-buffer process-buffer)))
1290           (set-buffer buf)
1291           (goto-char (point-max))
1292           (insert-buffer-substring process-buffer)
1293           (set-buffer process-buffer)
1294           (erase-buffer)
1295           (set-buffer buf))
1296
1297         ;; We remove any "." lines and status lines.
1298         (goto-char (point-min))
1299         (while (search-forward "\r" nil t)
1300           (delete-char -1))
1301         (goto-char (point-min))
1302         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1303         t))))
1304
1305   nntp-server-xover)
1306
1307 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1308   "Send the XOVER command to the server."
1309   (let ((range (format "%d-%d" beg end))
1310         (nntp-inhibit-erase t))
1311     (if (stringp nntp-server-xover)
1312         ;; If `nntp-server-xover' is a string, then we just send this
1313         ;; command.
1314         (if wait-for-reply
1315             (nntp-send-command-nodelete
1316              "\r?\n\\.\r?\n" nntp-server-xover range)
1317           ;; We do not wait for the reply.
1318           (nntp-send-command-nodelete nil nntp-server-xover range))
1319       (let ((commands nntp-xover-commands))
1320         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1321         ;; We try them all until we get at positive response.
1322         (while (and commands (eq nntp-server-xover 'try))
1323           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1324           (save-excursion
1325             (set-buffer nntp-server-buffer)
1326             (goto-char (point-min))
1327             (and (looking-at "[23]")    ; No error message.
1328                  ;; We also have to look at the lines.  Some buggy
1329                  ;; servers give back simple lines with just the
1330                  ;; article number.  How... helpful.
1331                  (progn
1332                    (forward-line 1)
1333                    (looking-at "[0-9]+\t...")) ; More text after number.
1334                  (setq nntp-server-xover (car commands))))
1335           (setq commands (cdr commands)))
1336         ;; If none of the commands worked, we disable XOVER.
1337         (when (eq nntp-server-xover 'try)
1338           (save-excursion
1339             (set-buffer nntp-server-buffer)
1340             (erase-buffer)
1341             (setq nntp-server-xover nil)))
1342         nntp-server-xover))))
1343
1344 (defun nntp-find-group-and-number ()
1345   (save-excursion
1346     (save-restriction
1347       (set-buffer nntp-server-buffer)
1348       (narrow-to-region (goto-char (point-min))
1349                         (or (search-forward "\n\n" nil t) (point-max)))
1350       (goto-char (point-min))
1351       ;; We first find the number by looking at the status line.
1352       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1353                          (string-to-int
1354                           (buffer-substring (match-beginning 1)
1355                                             (match-end 1)))))
1356             group newsgroups xref)
1357         (and number (zerop number) (setq number nil))
1358         ;; Then we find the group name.
1359         (setq group
1360               (cond
1361                ;; If there is only one group in the Newsgroups header,
1362                ;; then it seems quite likely that this article comes
1363                ;; from that group, I'd say.
1364                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
1365                      (not (string-match "," newsgroups)))
1366                 newsgroups)
1367                ;; If there is more than one group in the Newsgroups
1368                ;; header, then the Xref header should be filled out.
1369                ;; We hazard a guess that the group that has this
1370                ;; article number in the Xref header is the one we are
1371                ;; looking for.  This might very well be wrong if this
1372                ;; article happens to have the same number in several
1373                ;; groups, but that's life.
1374                ((and (setq xref (mail-fetch-field "xref"))
1375                      number
1376                      (string-match (format "\\([^ :]+\\):%d" number) xref))
1377                 (substring xref (match-beginning 1) (match-end 1)))
1378                (t "")))
1379         (when (string-match "\r" group)
1380           (setq group (substring group 0 (match-beginning 0))))
1381         (cons group number)))))
1382
1383 (defun nntp-wait-for-string (regexp)
1384   "Wait until string arrives in the buffer."
1385   (let ((buf (current-buffer)))
1386     (goto-char (point-min))
1387     (while (not (re-search-forward regexp nil t))
1388       (accept-process-output (nntp-find-connection nntp-server-buffer))
1389       (set-buffer buf)
1390       (goto-char (point-min)))))
1391
1392
1393 ;; ==========================================================================
1394 ;; Obsolete nntp-open-* connection methods -- drv
1395 ;; ==========================================================================
1396
1397 (defvoo nntp-open-telnet-envuser nil
1398   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1399
1400 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1401   "*Regular expression to match the shell prompt on the remote machine.")
1402
1403 (defvoo nntp-rlogin-program "rsh"
1404   "*Program used to log in on remote machines.
1405 The default is \"rsh\", but \"ssh\" is a popular alternative.")
1406
1407 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1408   "*Parameters to `nntp-open-rlogin'.
1409 That function may be used as `nntp-open-connection-function'.  In that
1410 case, this list will be used as the parameter list given to rsh.")
1411
1412 (defvoo nntp-rlogin-user-name nil
1413   "*User name on remote system when using the rlogin connect method.")
1414
1415 (defvoo nntp-telnet-parameters
1416     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1417   "*Parameters to `nntp-open-telnet'.
1418 That function may be used as `nntp-open-connection-function'.  In that
1419 case, this list will be executed as a command after logging in
1420 via telnet.")
1421
1422 (defvoo nntp-telnet-user-name nil
1423   "User name to log in via telnet with.")
1424
1425 (defvoo nntp-telnet-passwd nil
1426   "Password to use to log in via telnet with.")
1427
1428 (defun nntp-open-telnet (buffer)
1429   (save-excursion
1430     (set-buffer buffer)
1431     (erase-buffer)
1432     (let ((proc (apply
1433                  'start-process
1434                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1435           (case-fold-search t))
1436       (when (memq (process-status proc) '(open run))
1437         (nntp-wait-for-string "^r?telnet")
1438         (process-send-string proc "set escape \^X\n")
1439         (cond
1440          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1441           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1442                                             nntp-address "\n")))
1443          (t
1444           (process-send-string proc (concat "open " nntp-address "\n"))))
1445         (cond
1446          ((not nntp-open-telnet-envuser)
1447           (nntp-wait-for-string "^\r*.?login:")
1448           (process-send-string
1449            proc (concat
1450                  (or nntp-telnet-user-name
1451                      (setq nntp-telnet-user-name (read-string "login: ")))
1452                  "\n"))))
1453         (nntp-wait-for-string "^\r*.?password:")
1454         (process-send-string
1455          proc (concat
1456                (or nntp-telnet-passwd
1457                    (setq nntp-telnet-passwd
1458                          (mail-source-read-passwd "Password: ")))
1459                "\n"))
1460         (nntp-wait-for-string nntp-telnet-shell-prompt)
1461         (process-send-string
1462          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1463         (nntp-wait-for-string "^\r*20[01]")
1464         (beginning-of-line)
1465         (delete-region (point-min) (point))
1466         (process-send-string proc "\^]")
1467         (nntp-wait-for-string "^r?telnet")
1468         (process-send-string proc "mode character\n")
1469         (accept-process-output proc 1)
1470         (sit-for 1)
1471         (goto-char (point-min))
1472         (forward-line 1)
1473         (delete-region (point) (point-max)))
1474       proc)))
1475
1476 (defun nntp-open-rlogin (buffer)
1477   "Open a connection to SERVER using rsh."
1478   (let ((proc (if nntp-rlogin-user-name
1479                   (apply 'start-process
1480                          "nntpd" buffer nntp-rlogin-program
1481                          nntp-address "-l" nntp-rlogin-user-name
1482                          nntp-rlogin-parameters)
1483                 (apply 'start-process
1484                        "nntpd" buffer nntp-rlogin-program nntp-address
1485                        nntp-rlogin-parameters))))
1486     (save-excursion
1487       (set-buffer buffer)
1488       (nntp-wait-for-string "^\r*20[01]")
1489       (beginning-of-line)
1490       (delete-region (point-min) (point))
1491       proc)))
1492
1493
1494 ;; ==========================================================================
1495 ;; Replacements for the nntp-open-* functions -- drv
1496 ;; ==========================================================================
1497
1498 (defun nntp-open-telnet-stream (buffer)
1499   "Open a nntp connection by telnet'ing the news server.
1500
1501 Please refer to the following variables to customize the connection:
1502 - `nntp-pre-command',
1503 - `nntp-telnet-command',
1504 - `nntp-telnet-switches',
1505 - `nntp-address',
1506 - `nntp-port-number',
1507 - `nntp-end-of-line'."
1508   (let ((command `(,nntp-telnet-command
1509                    ,@nntp-telnet-switches
1510                    ,nntp-address ,nntp-port-number))
1511         proc)
1512     (and nntp-pre-command
1513          (push nntp-pre-command command))
1514     (setq proc (apply 'start-process "nntpd" buffer command))
1515     (save-excursion
1516       (set-buffer buffer)
1517       (nntp-wait-for-string "^\r*20[01]")
1518       (beginning-of-line)
1519       (delete-region (point-min) (point))
1520       proc)))
1521
1522 (defun nntp-open-via-rlogin-and-telnet (buffer)
1523   "Open a connection to an nntp server through an intermediate host.
1524 First rlogin to the remote host, and then telnet the real news server
1525 from there.
1526
1527 Please refer to the following variables to customize the connection:
1528 - `nntp-pre-command',
1529 - `nntp-via-rlogin-command',
1530 - `nntp-via-user-name',
1531 - `nntp-via-address',
1532 - `nntp-telnet-command',
1533 - `nntp-telnet-switches',
1534 - `nntp-address',
1535 - `nntp-port-number',
1536 - `nntp-end-of-line'."
1537   (let ((command `(,nntp-via-address
1538                    ,nntp-telnet-command
1539                    ,@nntp-telnet-switches
1540                    ,nntp-address ,nntp-port-number))
1541         proc)
1542     (and nntp-via-user-name
1543          (setq command `("-l" ,nntp-via-user-name ,@command)))
1544     (push nntp-via-rlogin-command command)
1545     (and nntp-pre-command
1546          (push nntp-pre-command command))
1547     (setq proc (apply 'start-process "nntpd" buffer command))
1548     (save-excursion
1549       (set-buffer buffer)
1550       (nntp-wait-for-string "^\r*20[01]")
1551       (beginning-of-line)
1552       (delete-region (point-min) (point))
1553       proc)))
1554
1555 (defun nntp-open-via-telnet-and-telnet (buffer)
1556   "Open a connection to an nntp server through an intermediate host.
1557 First telnet the remote host, and then telnet the real news server
1558 from there.
1559
1560 Please refer to the following variables to customize the connection:
1561 - `nntp-pre-command',
1562 - `nntp-via-telnet-command',
1563 - `nntp-via-telnet-switches',
1564 - `nntp-via-address',
1565 - `nntp-via-envuser',
1566 - `nntp-via-user-name',
1567 - `nntp-via-user-password',
1568 - `nntp-via-shell-prompt',
1569 - `nntp-telnet-command',
1570 - `nntp-telnet-switches',
1571 - `nntp-address',
1572 - `nntp-port-number',
1573 - `nntp-end-of-line'."
1574   (save-excursion
1575     (set-buffer buffer)
1576     (erase-buffer)
1577     (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
1578           (case-fold-search t)
1579           proc)
1580       (and nntp-pre-command (push nntp-pre-command command))
1581       (setq proc (apply 'start-process "nntpd" buffer command))
1582       (when (memq (process-status proc) '(open run))
1583         (nntp-wait-for-string "^r?telnet")
1584         (process-send-string proc "set escape \^X\n")
1585         (cond
1586          ((and nntp-via-envuser nntp-via-user-name)
1587           (process-send-string proc (concat "open " "-l" nntp-via-user-name
1588                                             nntp-via-address "\n")))
1589          (t
1590           (process-send-string proc (concat "open " nntp-via-address
1591                                             "\n"))))
1592         (when (not nntp-via-envuser)
1593           (nntp-wait-for-string "^\r*.?login:")
1594           (process-send-string proc
1595                                (concat
1596                                 (or nntp-via-user-name
1597                                     (setq nntp-via-user-name
1598                                           (read-string "login: ")))
1599                                 "\n")))
1600         (nntp-wait-for-string "^\r*.?password:")
1601         (process-send-string proc
1602                              (concat
1603                               (or nntp-via-user-password
1604                                   (setq nntp-via-user-password
1605                                         (mail-source-read-passwd
1606                                          "Password: ")))
1607                               "\n"))
1608         (nntp-wait-for-string nntp-via-shell-prompt)
1609         (let ((real-telnet-command `("exec"
1610                                      ,nntp-telnet-command
1611                                      ,@nntp-telnet-switches
1612                                      ,nntp-address
1613                                      ,nntp-port-number)))
1614           (process-send-string proc
1615                                (concat (mapconcat 'identity
1616                                                   real-telnet-command " ")
1617                                        "\n")))
1618         (nntp-wait-for-string "^\r*20[01]")
1619         (beginning-of-line)
1620         (delete-region (point-min) (point))
1621         (process-send-string proc "\^]")
1622         (nntp-wait-for-string "^r?telnet")
1623         (process-send-string proc "mode character\n")
1624         (accept-process-output proc 1)
1625         (sit-for 1)
1626         (goto-char (point-min))
1627         (forward-line 1)
1628         (delete-region (point) (point-max)))
1629       proc)))
1630
1631 (provide 'nntp)
1632
1633 ;;; nntp.el ends here