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