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