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