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