Gnus v5.6.7.
[elisp/gnus.git-] / lisp / nntp.el
1 ;;; nntp.el --- nntp access for Gnus
2 ;;; Copyright (C) 1987-90,92-97 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'nnheader)
28 (require 'nnoo)
29 (require 'gnus-util)
30
31 (nnoo-declare nntp)
32
33 (eval-and-compile
34   (unless (fboundp 'open-network-stream)
35     (require 'tcp)))
36
37 (eval-when-compile (require 'cl))
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-server-opened-hook '(nntp-send-mode-reader)
46   "*Hook used for sending commands to the server at startup.
47 The default value is `nntp-send-mode-reader', which makes an innd
48 server spawn an nnrpd server.  Another useful function to put in this
49 hook might be `nntp-send-authinfo', which will prompt for a password
50 to allow posting from the server.  Note that this is only necessary to
51 do on servers that use strict access control.")
52
53 (defvoo nntp-authinfo-function 'nntp-send-authinfo
54   "Function used to send AUTHINFO to the server.")
55
56 (defvoo nntp-server-action-alist
57   '(("nntpd 1\\.5\\.11t"
58      (remove-hook 'nntp-server-opened-hook 'nntp-send-mode-reader))
59     ("NNRP server Netscape"
60      (setq nntp-server-list-active-group nil)))
61   "Alist of regexps to match on server types and actions to be taken.
62 For instance, if you want Gnus to beep every time you connect
63 to innd, you could say something like:
64
65 \(setq nntp-server-action-alist
66        '((\"innd\" (ding))))
67
68 You probably don't want to do that, though.")
69
70 (defvoo nntp-open-connection-function 'nntp-open-network-stream
71   "*Function used for connecting to a remote system.
72 It will be called with the buffer to output in.
73
74 Two pre-made functions are `nntp-open-network-stream', which is the
75 default, and simply connects to some port or other on the remote
76 system (see nntp-port-number).  The other are `nntp-open-rlogin',
77 which does an rlogin on the remote system, and then does a telnet to
78 the NNTP server available there (see nntp-rlogin-parameters) and
79 `nntp-open-telnet' which telnets to a remote system, logs in and does
80 the same.")
81
82 (defvoo nntp-rlogin-program "rsh"
83   "*Program used to log in on remote machines.
84 The default is \"rsh\", but \"ssh\" is a popular alternative.")
85
86 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
87   "*Parameters to `nntp-open-rlogin'.
88 That function may be used as `nntp-open-connection-function'.  In that
89 case, this list will be used as the parameter list given to rsh.")
90
91 (defvoo nntp-rlogin-user-name nil
92   "*User name on remote system when using the rlogin connect method.")
93
94 (defvoo nntp-telnet-parameters '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
95   "*Parameters to `nntp-open-telnet'.
96 That function may be used as `nntp-open-connection-function'.  In that
97 case, this list will be executed as a command after logging in
98 via telnet.")
99
100 (defvoo nntp-telnet-user-name nil
101   "User name to log in via telnet with.")
102
103 (defvoo nntp-telnet-passwd nil
104   "Password to use to log in via telnet with.")
105
106 (defvoo nntp-open-telnet-envuser nil
107   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
108
109 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
110   "*Regular expression to match the shell prompt on the remote machine.")
111
112 (defvoo nntp-telnet-command "telnet"
113   "Command used to start telnet.")
114
115 (defvoo nntp-telnet-switches '("-8")
116   "Switches given to the telnet command.")
117
118 (defvoo nntp-end-of-line "\r\n"
119   "String to use on the end of lines when talking to the NNTP server.
120 This is \"\\r\\n\" by default, but should be \"\\n\" when
121 using rlogin or telnet to communicate with the server.")
122
123 (defvoo nntp-large-newsgroup 50
124   "*The number of the articles which indicates a large newsgroup.
125 If the number of the articles is greater than the value, verbose
126 messages will be shown to indicate the current status.")
127
128 (defvoo nntp-maximum-request 400
129   "*The maximum number of the requests sent to the NNTP server at one time.
130 If Emacs hangs up while retrieving headers, set the variable to a
131 lower value.")
132
133 (defvoo nntp-nov-is-evil nil
134   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
135
136 (defvoo nntp-xover-commands '("XOVER" "XOVERVIEW")
137   "*List of strings that are used as commands to fetch NOV lines from a server.
138 The strings are tried in turn until a positive response is gotten.  If
139 none of the commands are successful, nntp will just grab headers one
140 by one.")
141
142 (defvoo nntp-nov-gap 5
143   "*Maximum allowed gap between two articles.
144 If the gap between two consecutive articles is bigger than this
145 variable, split the XOVER request into two requests.")
146
147 (defvoo nntp-prepare-server-hook nil
148   "*Hook run before a server is opened.
149 If can be used to set up a server remotely, for instance.  Say you
150 have an account at the machine \"other.machine\".  This machine has
151 access to an NNTP server that you can't access locally.  You could
152 then use this hook to rsh to the remote machine and start a proxy NNTP
153 server there that you can connect to.  See also
154 `nntp-open-connection-function'")
155
156 (defvoo nntp-warn-about-losing-connection t
157   "*If non-nil, beep when a server closes connection.")
158
159 (defvoo nntp-coding-system-for-read 'binary
160   "*Coding system to read from NNTP.")
161
162 (defvoo nntp-coding-system-for-write 'binary
163   "*Coding system to write to NNTP.")
164
165 (defcustom nntp-authinfo-file "~/.authinfo"
166   ".netrc-like file that holds nntp authinfo passwords."
167   :type
168   '(choice file
169            (repeat :tag "Entries"
170                    :menu-tag "Inline"
171                    (list :format "%v"
172                          :value ("" ("login" . "") ("password" . ""))
173                          (string :tag "Host")
174                          (checklist :inline t
175                                     (cons :format "%v"
176                                           (const :format "" "login")
177                                           (string :format "Login: %v"))
178                                     (cons :format "%v"
179                                           (const :format "" "password")
180                                           (string :format "Password: %v")))))))
181
182 \f
183
184 ;;; Internal variables.
185
186 (defvar nntp-record-commands nil
187   "*If non-nil, nntp will record all commands in the \"*nntp-log*\" buffer.")
188
189 (defvar nntp-have-messaged nil)
190
191 (defvar nntp-process-wait-for nil)
192 (defvar nntp-process-to-buffer nil)
193 (defvar nntp-process-callback nil)
194 (defvar nntp-process-decode nil)
195 (defvar nntp-process-start-point nil)
196 (defvar nntp-inside-change-function nil)
197 (defvoo nntp-last-command-time nil)
198 (defvoo nntp-last-command nil)
199 (defvoo nntp-authinfo-password nil)
200
201 (defvar nntp-connection-list nil)
202
203 (defvoo nntp-server-type nil)
204 (defvoo nntp-connection-alist nil)
205 (defvoo nntp-status-string "")
206 (defconst nntp-version "nntp 5.0")
207 (defvoo nntp-inhibit-erase nil)
208 (defvoo nntp-inhibit-output nil)
209
210 (defvoo nntp-server-xover 'try)
211 (defvoo nntp-server-list-active-group 'try)
212
213 (eval-and-compile
214   (autoload 'nnmail-read-passwd "nnmail"))
215
216 \f
217
218 ;;; Internal functions.
219
220 (defsubst nntp-send-string (process string)
221   "Send STRING to PROCESS."
222   ;; We need to store the time to provide timeouts, and
223   ;; to store the command so the we can replay the command
224   ;; if the server gives us an AUTHINFO challenge.
225   (setq nntp-last-command-time (current-time)
226         nntp-last-command string)
227   (when nntp-record-commands
228     (nntp-record-command string))
229   (process-send-string process (concat string nntp-end-of-line)))
230
231 (defun nntp-record-command (string)
232   "Record the command STRING."
233   (save-excursion
234     (set-buffer (get-buffer-create "*nntp-log*"))
235     (goto-char (point-max))
236     (insert (format-time-string "%Y%m%dT%H%M%S" (current-time))
237             " " nntp-address " " string "\n")))
238
239 (defsubst nntp-wait-for (process wait-for buffer &optional decode discard)
240   "Wait for WAIT-FOR to arrive from PROCESS."
241   (save-excursion
242     (set-buffer (process-buffer process))
243     (goto-char (point-min))
244     (while (and (or (not (memq (char-after (point)) '(?2 ?3 ?4 ?5)))
245                     (looking-at "480"))
246                 (memq (process-status process) '(open run)))
247       (when (looking-at "480")
248         (nntp-handle-authinfo process))
249       (nntp-accept-process-output process)
250       (goto-char (point-min)))
251     (prog1
252         (cond
253          ((looking-at "[45]")
254           (progn
255             (nntp-snarf-error-message)
256             nil))
257          ((not (memq (process-status process) '(open run)))
258           (nnheader-report 'nntp "Server closed connection"))
259          (t
260           (goto-char (point-max))
261           (let ((limit (point-min)))
262             (while (not (re-search-backward wait-for limit t))
263               (nntp-accept-process-output process)
264               ;; We assume that whatever we wait for is less than 1000
265               ;; characters long.
266               (setq limit (max (- (point-max) 1000) (point-min)))
267               (goto-char (point-max))))
268           (nntp-decode-text (not decode))
269           (unless discard
270             (save-excursion
271               (set-buffer buffer)
272               (goto-char (point-max))
273               (insert-buffer-substring (process-buffer process))
274               ;; Nix out "nntp reading...." message.
275               (when nntp-have-messaged
276                 (setq nntp-have-messaged nil)
277                 (message ""))
278               t))))
279       (unless discard
280         (erase-buffer)))))
281
282 (defsubst nntp-find-connection (buffer)
283   "Find the connection delivering to BUFFER."
284   (let ((alist nntp-connection-alist)
285         (buffer (if (stringp buffer) (get-buffer buffer) buffer))
286         process entry)
287     (while (setq entry (pop alist))
288       (when (eq buffer (cadr entry))
289         (setq process (car entry)
290               alist nil)))
291     (when process
292       (if (memq (process-status process) '(open run))
293           process
294         (when (buffer-name (process-buffer process))
295           (kill-buffer (process-buffer process)))
296         (setq nntp-connection-alist (delq entry nntp-connection-alist))
297         nil))))
298
299 (defsubst nntp-find-connection-entry (buffer)
300   "Return the entry for the connection to BUFFER."
301   (assq (nntp-find-connection buffer) nntp-connection-alist))
302
303 (defun nntp-find-connection-buffer (buffer)
304   "Return the process connection buffer tied to BUFFER."
305   (let ((process (nntp-find-connection buffer)))
306     (when process
307       (process-buffer process))))
308
309 (defsubst nntp-retrieve-data (command address port buffer
310                                       &optional wait-for callback decode)
311   "Use COMMAND to retrieve data into BUFFER from PORT on ADDRESS."
312   (let ((process (or (nntp-find-connection buffer)
313                      (nntp-open-connection buffer))))
314     (if (not process)
315         (nnheader-report 'nntp "Couldn't open connection to %s" address)
316       (unless (or nntp-inhibit-erase nnheader-callback-function)
317         (save-excursion
318           (set-buffer (process-buffer process))
319           (erase-buffer)))
320       (when command
321         (nntp-send-string process command))
322       (cond
323        ((eq callback 'ignore)
324         t)
325        ((and callback wait-for)
326         (save-excursion
327           (set-buffer (process-buffer process))
328           (unless nntp-inside-change-function
329             (erase-buffer))
330           (setq nntp-process-decode decode
331                 nntp-process-to-buffer buffer
332                 nntp-process-wait-for wait-for
333                 nntp-process-callback callback
334                 nntp-process-start-point (point-max)
335                 after-change-functions
336                 (list 'nntp-after-change-function-callback)))
337         t)
338        (wait-for
339         (nntp-wait-for process wait-for buffer decode))
340        (t t)))))
341
342 (defsubst nntp-send-command (wait-for &rest strings)
343   "Send STRINGS to server and wait until WAIT-FOR returns."
344   (when (and (not nnheader-callback-function)
345              (not nntp-inhibit-output))
346     (save-excursion
347       (set-buffer nntp-server-buffer)
348       (erase-buffer)))
349   (nntp-retrieve-data
350    (mapconcat 'identity strings " ")
351    nntp-address nntp-port-number nntp-server-buffer
352    wait-for nnheader-callback-function))
353
354 (defun nntp-send-command-nodelete (wait-for &rest strings)
355   "Send STRINGS to server and wait until WAIT-FOR returns."
356   (nntp-retrieve-data
357    (mapconcat 'identity strings " ")
358    nntp-address nntp-port-number nntp-server-buffer
359    wait-for nnheader-callback-function))
360
361 (defun nntp-send-command-and-decode (wait-for &rest strings)
362   "Send STRINGS to server and wait until WAIT-FOR returns."
363   (when (and (not nnheader-callback-function)
364              (not nntp-inhibit-output))
365     (save-excursion
366       (set-buffer nntp-server-buffer)
367       (erase-buffer)))
368   (nntp-retrieve-data
369    (mapconcat 'identity strings " ")
370    nntp-address nntp-port-number nntp-server-buffer
371    wait-for nnheader-callback-function t))
372
373 (defun nntp-send-buffer (wait-for)
374   "Send the current buffer to server and wait until WAIT-FOR returns."
375   (when (and (not nnheader-callback-function)
376              (not nntp-inhibit-output))
377     (save-excursion
378       (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
379       (erase-buffer)))
380   (nntp-encode-text)
381   (process-send-region (nntp-find-connection nntp-server-buffer)
382                        (point-min) (point-max))
383   (nntp-retrieve-data
384    nil nntp-address nntp-port-number nntp-server-buffer
385    wait-for nnheader-callback-function))
386
387 \f
388
389 ;;; Interface functions.
390
391 (nnoo-define-basics nntp)
392
393 (defsubst nntp-next-result-arrived-p ()
394   (let ((point (point)))
395     (cond
396      ((eq (following-char) ?2)
397       (if (re-search-forward "\n\\.\r?\n" nil t)
398           t
399         (goto-char point)
400         nil))
401      ((looking-at "[34]")
402       (forward-line 1)
403       t)
404      (t
405       nil))))
406
407 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
408   "Retrieve the headers of ARTICLES."
409   (nntp-possibly-change-group group server)
410   (save-excursion
411     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
412     (erase-buffer)
413     (if (and (not gnus-nov-is-evil)
414              (not nntp-nov-is-evil)
415              (nntp-retrieve-headers-with-xover articles fetch-old))
416         ;; We successfully retrieved the headers via XOVER.
417         'nov
418       ;; XOVER didn't work, so we do it the hard, slow and inefficient
419       ;; way.
420       (let ((number (length articles))
421             (count 0)
422             (received 0)
423             (last-point (point-min))
424             (buf (nntp-find-connection-buffer nntp-server-buffer))
425             (nntp-inhibit-erase t)
426             article)
427         ;; Send HEAD commands.
428       (while (setq article (pop articles))
429         (nntp-send-command
430          nil
431          "HEAD" (if (numberp article)
432                     (int-to-string article)
433                   ;; `articles' is either a list of article numbers
434                   ;; or a list of article IDs.
435                   article))
436         (incf count)
437         ;; Every 400 requests we have to read the stream in
438         ;; order to avoid deadlocks.
439         (when (or (null articles)       ;All requests have been sent.
440                   (zerop (% count nntp-maximum-request)))
441           (nntp-accept-response)
442           (while (progn
443                    (set-buffer buf)
444                    (goto-char last-point)
445                    ;; Count replies.
446                    (while (nntp-next-result-arrived-p)
447                      (setq last-point (point))
448                      (incf received))
449                    (< received count))
450             ;; If number of headers is greater than 100, give
451             ;;  informative messages.
452             (and (numberp nntp-large-newsgroup)
453                  (> number nntp-large-newsgroup)
454                  (zerop (% received 20))
455                  (nnheader-message 6 "NNTP: Receiving headers... %d%%"
456                                    (/ (* received 100) number)))
457             (nntp-accept-response))))
458         (and (numberp nntp-large-newsgroup)
459              (> number nntp-large-newsgroup)
460              (nnheader-message 6 "NNTP: Receiving headers...done"))
461
462         ;; Now all of replies are received.  Fold continuation lines.
463         (nnheader-fold-continuation-lines)
464         ;; Remove all "\r"'s.
465         (nnheader-strip-cr)
466         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
467         'headers))))
468
469 (deffoo nntp-retrieve-groups (groups &optional server)
470   "Retrieve group info on GROUPS."
471   (nntp-possibly-change-group nil server)
472   (save-excursion
473     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
474     ;; The first time this is run, this variable is `try'.  So we
475     ;; try.
476     (when (eq nntp-server-list-active-group 'try)
477       (nntp-try-list-active (car groups)))
478     (erase-buffer)
479     (let ((count 0)
480           (received 0)
481           (last-point (point-min))
482           (nntp-inhibit-erase t)
483           (command (if nntp-server-list-active-group "LIST ACTIVE" "GROUP")))
484       (while groups
485         ;; Send the command to the server.
486         (nntp-send-command nil command (pop groups))
487         (incf count)
488         ;; Every 400 requests we have to read the stream in
489         ;; order to avoid deadlocks.
490         (when (or (null groups)         ;All requests have been sent.
491                   (zerop (% count nntp-maximum-request)))
492           (nntp-accept-response)
493           (while (progn
494                    (goto-char last-point)
495                    ;; Count replies.
496                    (while (re-search-forward "^[0-9]" nil t)
497                      (incf received))
498                    (setq last-point (point))
499                    (< received count))
500             (nntp-accept-response))))
501
502       ;; Wait for the reply from the final command.
503       (goto-char (point-max))
504       (re-search-backward "^[0-9]" nil t)
505       (when (looking-at "^[23]")
506         (while (progn
507                  (goto-char (point-max))
508                  (if (not nntp-server-list-active-group)
509                      (not (re-search-backward "\r?\n" (- (point) 3) t))
510                    (not (re-search-backward "^\\.\r?\n" (- (point) 4) t))))
511           (nntp-accept-response)))
512
513       ;; Now all replies are received.  We remove CRs.
514       (goto-char (point-min))
515       (while (search-forward "\r" nil t)
516         (replace-match "" t t))
517
518       (if (not nntp-server-list-active-group)
519           (progn
520             (copy-to-buffer nntp-server-buffer (point-min) (point-max))
521             'group)
522         ;; We have read active entries, so we just delete the
523         ;; superfluous gunk.
524         (goto-char (point-min))
525         (while (re-search-forward "^[.2-5]" nil t)
526           (delete-region (match-beginning 0)
527                          (progn (forward-line 1) (point))))
528         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
529         'active))))
530
531 (deffoo nntp-retrieve-articles (articles &optional group server)
532   (nntp-possibly-change-group group server)
533   (save-excursion
534     (let ((number (length articles))
535           (count 0)
536           (received 0)
537           (last-point (point-min))
538           (buf (nntp-find-connection-buffer nntp-server-buffer))
539           (nntp-inhibit-erase t)
540           (map (apply 'vector articles))
541           (point 1)
542           article alist)
543       (set-buffer buf)
544       (erase-buffer)
545       ;; Send ARTICLE command.
546       (while (setq article (pop articles))
547         (nntp-send-command
548          nil
549          "ARTICLE" (if (numberp article)
550                        (int-to-string article)
551                      ;; `articles' is either a list of article numbers
552                      ;; or a list of article IDs.
553                      article))
554         (incf count)
555         ;; Every 400 requests we have to read the stream in
556         ;; order to avoid deadlocks.
557         (when (or (null articles)       ;All requests have been sent.
558                   (zerop (% count nntp-maximum-request)))
559           (nntp-accept-response)
560           (while (progn
561                    (set-buffer buf)
562                    (goto-char last-point)
563                    ;; Count replies.
564                    (while (nntp-next-result-arrived-p)
565                      (aset map received (cons (aref map received) (point)))
566                      (setq last-point (point))
567                      (incf received))
568                    (< received count))
569             ;; If number of headers is greater than 100, give
570             ;;  informative messages.
571             (and (numberp nntp-large-newsgroup)
572                  (> number nntp-large-newsgroup)
573                  (zerop (% received 20))
574                  (nnheader-message 6 "NNTP: Receiving articles... %d%%"
575                                    (/ (* received 100) number)))
576             (nntp-accept-response))))
577       (and (numberp nntp-large-newsgroup)
578            (> number nntp-large-newsgroup)
579            (nnheader-message 6 "NNTP: Receiving articles...done"))
580       
581       ;; Now we have all the responses.  We go through the results,
582       ;; washes it and copies it over to the server buffer.
583       (set-buffer nntp-server-buffer)
584       (erase-buffer)
585       (setq last-point (point-min))
586       (mapcar
587        (lambda (entry)
588          (narrow-to-region
589           (setq point (goto-char (point-max)))
590           (progn
591             (insert-buffer-substring buf last-point (cdr entry))
592             (point-max)))
593          (setq last-point (cdr entry))
594          (nntp-decode-text)
595          (widen)
596          (cons (car entry) point))
597        map))))
598
599 (defun nntp-try-list-active (group)
600   (nntp-list-active-group group)
601   (save-excursion
602     (set-buffer nntp-server-buffer)
603     (goto-char (point-min))
604     (cond ((or (eobp)
605                (looking-at "5[0-9]+"))
606            (setq nntp-server-list-active-group nil))
607           (t
608            (setq nntp-server-list-active-group t)))))
609
610 (deffoo nntp-list-active-group (group &optional server)
611   "Return the active info on GROUP (which can be a regexp."
612   (nntp-possibly-change-group nil server)
613   (nntp-send-command "^.*\r?\n" "LIST ACTIVE" group))
614
615 (deffoo nntp-request-article (article &optional group server buffer command)
616   (nntp-possibly-change-group group server)
617   (when (nntp-send-command-and-decode
618          "\r?\n\\.\r?\n" "ARTICLE"
619          (if (numberp article) (int-to-string article) article))
620     (if (and buffer
621              (not (equal buffer nntp-server-buffer)))
622         (save-excursion
623           (set-buffer nntp-server-buffer)
624           (copy-to-buffer buffer (point-min) (point-max))
625           (nntp-find-group-and-number))
626       (nntp-find-group-and-number))))
627
628 (deffoo nntp-request-head (article &optional group server)
629   (nntp-possibly-change-group group server)
630   (when (nntp-send-command
631          "\r?\n\\.\r?\n" "HEAD"
632          (if (numberp article) (int-to-string article) article))
633     (prog1
634         (nntp-find-group-and-number)
635       (nntp-decode-text))))
636
637 (deffoo nntp-request-body (article &optional group server)
638   (nntp-possibly-change-group group server)
639   (nntp-send-command-and-decode
640    "\r?\n\\.\r?\n" "BODY"
641    (if (numberp article) (int-to-string article) article)))
642
643 (deffoo nntp-request-group (group &optional server dont-check)
644   (nntp-possibly-change-group nil server)
645   (when (nntp-send-command "^21.*\n" "GROUP" group)
646     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
647       (setcar (cddr entry) group))))
648
649 (deffoo nntp-close-group (group &optional server)
650   t)
651
652 (deffoo nntp-server-opened (&optional server)
653   "Say whether a connection to SERVER has been opened."
654   (and (nnoo-current-server-p 'nntp server)
655        nntp-server-buffer
656        (gnus-buffer-live-p nntp-server-buffer)
657        (nntp-find-connection nntp-server-buffer)))
658
659 (deffoo nntp-open-server (server &optional defs connectionless)
660   (nnheader-init-server-buffer)
661   (if (nntp-server-opened server)
662       t
663     (when (or (stringp (car defs))
664               (numberp (car defs)))
665       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
666     (unless (assq 'nntp-address defs)
667       (setq defs (append defs (list (list 'nntp-address server)))))
668     (nnoo-change-server 'nntp server defs)
669     (unless connectionless
670       (or (nntp-find-connection nntp-server-buffer)
671           (nntp-open-connection nntp-server-buffer)))))
672
673 (deffoo nntp-close-server (&optional server)
674   (nntp-possibly-change-group nil server t)
675   (let ((process (nntp-find-connection nntp-server-buffer)))
676     (while process
677       (when (memq (process-status process) '(open run))
678         (ignore-errors
679           (nntp-send-string process "QUIT")
680           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
681             (sleep-for 1))))
682       (when (buffer-name (process-buffer process))
683         (kill-buffer (process-buffer process)))
684       (setq process (car (pop nntp-connection-alist))))
685     (nnoo-close-server 'nntp)))
686
687 (deffoo nntp-request-close ()
688   (let (process)
689     (while (setq process (pop nntp-connection-list))
690       (when (memq (process-status process) '(open run))
691         (ignore-errors
692           (nntp-send-string process "QUIT")
693           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
694             ;; Ok, this is evil, but when using telnet and stuff
695             ;; as the connection method, it's important that the
696             ;; QUIT command actually is sent out before we kill
697             ;; the process.  
698             (sleep-for 1))))
699       (when (buffer-name (process-buffer process))
700         (kill-buffer (process-buffer process))))))
701
702 (deffoo nntp-request-list (&optional server)
703   (nntp-possibly-change-group nil server)
704   (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST"))
705
706 (deffoo nntp-request-list-newsgroups (&optional server)
707   (nntp-possibly-change-group nil server)
708   (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS"))
709
710 (deffoo nntp-request-newgroups (date &optional server)
711   (nntp-possibly-change-group nil server)
712   (save-excursion
713     (set-buffer nntp-server-buffer)
714     (let* ((date (timezone-parse-date date))
715            (time-string
716             (format "%s%02d%02d %s%s%s"
717                     (substring (aref date 0) 2) (string-to-int (aref date 1))
718                     (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
719                     (substring
720                      (aref date 3) 3 5) (substring (aref date 3) 6 8))))
721       (prog1
722           (nntp-send-command "^\\.\r?\n" "NEWGROUPS" time-string)
723         (nntp-decode-text)))))
724
725 (deffoo nntp-request-post (&optional server)
726   (nntp-possibly-change-group nil server)
727   (when (nntp-send-command "^[23].*\r?\n" "POST")
728     (nntp-send-buffer "^[23].*\n")))
729
730 (deffoo nntp-request-type (group article)
731   'news)
732
733 (deffoo nntp-asynchronous-p ()
734   t)
735
736 ;;; Hooky functions.
737
738 (defun nntp-send-mode-reader ()
739   "Send the MODE READER command to the nntp server.
740 This function is supposed to be called from `nntp-server-opened-hook'.
741 It will make innd servers spawn an nnrpd process to allow actual article
742 reading."
743   (nntp-send-command "^.*\r?\n" "MODE READER"))
744
745 (defun nntp-send-authinfo (&optional send-if-force)
746   "Send the AUTHINFO to the nntp server.
747 It will look in the \"~/.authinfo\" file for matching entries.  If
748 nothing suitable is found there, it will prompt for a user name
749 and a password."
750   (let* ((list (gnus-parse-netrc nntp-authinfo-file))
751          (alist (gnus-netrc-machine list nntp-address))
752          (force (gnus-netrc-get alist "force"))
753          (user (gnus-netrc-get alist "login"))
754          (passwd (gnus-netrc-get alist "password")))
755     (when (or (not send-if-force)
756               force)
757       (nntp-send-command
758        "^3.*\r?\n" "AUTHINFO USER"
759        (or user (read-string (format "NNTP (%s) user name: " nntp-address))))
760       (nntp-send-command
761        "^2.*\r?\n" "AUTHINFO PASS"
762        (or passwd
763            nntp-authinfo-password
764            (setq nntp-authinfo-password
765                  (nnmail-read-passwd (format "NNTP (%s) password: "
766                                              nntp-address))))))))
767
768 (defun nntp-send-nosy-authinfo ()
769   "Send the AUTHINFO to the nntp server."
770   (nntp-send-command
771    "^3.*\r?\n" "AUTHINFO USER"
772    (read-string (format "NNTP (%s) user name: " nntp-address)))
773   (nntp-send-command
774    "^2.*\r?\n" "AUTHINFO PASS"
775    (nnmail-read-passwd "NNTP (%s) password: " nntp-address)))
776
777 (defun nntp-send-authinfo-from-file ()
778   "Send the AUTHINFO to the nntp server.
779
780 The authinfo login name is taken from the user's login name and the
781 password contained in '~/.nntp-authinfo'."
782   (when (file-exists-p "~/.nntp-authinfo")
783     (nnheader-temp-write nil
784       (insert-file-contents "~/.nntp-authinfo")
785       (goto-char (point-min))
786       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
787       (nntp-send-command
788        "^2.*\r?\n" "AUTHINFO PASS"
789        (buffer-substring (point) (progn (end-of-line) (point)))))))
790
791 ;;; Internal functions.
792
793 (defun nntp-handle-authinfo (process)
794   "Take care of an authinfo response from the server."
795   (let ((last nntp-last-command))
796     (funcall nntp-authinfo-function)
797     ;; We have to re-send the function that was interrupted by
798     ;; the authinfo request.
799     (save-excursion
800       (set-buffer nntp-server-buffer)
801       (erase-buffer))
802     (nntp-send-string process last)))
803
804 (defun nntp-make-process-buffer (buffer)
805   "Create a new, fresh buffer usable for nntp process connections."
806   (save-excursion
807     (set-buffer
808      (generate-new-buffer
809       (format " *server %s %s %s*"
810               nntp-address nntp-port-number
811               (gnus-buffer-exists-p buffer))))
812     (buffer-disable-undo (current-buffer))
813     (set (make-local-variable 'after-change-functions) nil)
814     (set (make-local-variable 'nntp-process-wait-for) nil)
815     (set (make-local-variable 'nntp-process-callback) nil)
816     (set (make-local-variable 'nntp-process-to-buffer) nil)
817     (set (make-local-variable 'nntp-process-start-point) nil)
818     (set (make-local-variable 'nntp-process-decode) nil)
819     (current-buffer)))
820
821 (defun nntp-open-connection (buffer)
822   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
823   (run-hooks 'nntp-prepare-server-hook)
824   (let* ((pbuffer (nntp-make-process-buffer buffer))
825          (process
826           (condition-case ()
827               (let ((coding-system-for-read nntp-coding-system-for-read))
828                 (funcall nntp-open-connection-function pbuffer))
829             (error nil)
830             (quit nil))))
831     (when process
832       (process-kill-without-query process)
833       (nntp-wait-for process "^.*\n" buffer nil t)
834       (if (memq (process-status process) '(open run))
835           (prog1
836               (caar (push (list process buffer nil) nntp-connection-alist))
837             (push process nntp-connection-list)
838             (save-excursion
839               (set-buffer pbuffer)
840               (nntp-read-server-type)
841               (erase-buffer)
842               (set-buffer nntp-server-buffer)
843               (let ((nnheader-callback-function nil))
844                 (run-hooks 'nntp-server-opened-hook)
845                 (nntp-send-authinfo t))))
846         (when (buffer-name (process-buffer process))
847           (kill-buffer (process-buffer process)))
848         nil))))
849
850 (defun nntp-open-network-stream (buffer)
851   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
852
853 (defun nntp-read-server-type ()
854   "Find out what the name of the server we have connected to is."
855   ;; Wait for the status string to arrive.
856   (setq nntp-server-type (buffer-string))
857   (let ((alist nntp-server-action-alist)
858         (case-fold-search t)
859         entry)
860     ;; Run server-specific commands.
861     (while alist
862       (setq entry (pop alist))
863       (when (string-match (car entry) nntp-server-type)
864         (if (and (listp (cadr entry))
865                  (not (eq 'lambda (caadr entry))))
866             (eval (cadr entry))
867           (funcall (cadr entry)))))))
868
869 (defun nntp-after-change-function-callback (beg end len)
870   (when nntp-process-callback
871     (save-match-data
872       (if (and (= beg (point-min))
873                (memq (char-after beg) '(?4 ?5)))
874           ;; Report back error messages.
875           (save-excursion
876             (goto-char beg)
877             (if (looking-at "480")
878                 (nntp-handle-authinfo nntp-process-to-buffer)
879               (nntp-snarf-error-message)
880               (funcall nntp-process-callback nil)))
881         (goto-char end)
882         (when (and (> (point) nntp-process-start-point)
883                    (re-search-backward nntp-process-wait-for
884                                        nntp-process-start-point t))
885           (when (gnus-buffer-exists-p nntp-process-to-buffer)
886             (let ((cur (current-buffer))
887                   (start nntp-process-start-point))
888               (save-excursion
889                 (set-buffer nntp-process-to-buffer)
890                 (goto-char (point-max))
891                 (let ((b (point)))
892                   (insert-buffer-substring cur start)
893                   (narrow-to-region b (point-max))
894                   (nntp-decode-text)
895                   (widen)))))
896           (goto-char end)
897           (let ((callback nntp-process-callback)
898                 (nntp-inside-change-function t))
899             (setq nntp-process-callback nil)
900             (save-excursion
901               (funcall callback (buffer-name
902                                  (get-buffer nntp-process-to-buffer))))))))))
903
904 (defun nntp-snarf-error-message ()
905   "Save the error message in the current buffer."
906   (let ((message (buffer-string)))
907     (while (string-match "[\r\n]+" message)
908       (setq message (replace-match " " t t message)))
909     (nnheader-report 'nntp message)
910     message))
911
912 (defun nntp-accept-process-output (process)
913   "Wait for output from PROCESS and message some dots."
914   (save-excursion
915     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
916                     nntp-server-buffer))
917     (let ((len (/ (point-max) 1024))
918           message-log-max)
919       (unless (< len 10)
920         (setq nntp-have-messaged t)
921         (nnheader-message 7 "nntp read: %dk" len)))
922     (accept-process-output process 1)))
923
924 (defun nntp-accept-response ()
925   "Wait for output from the process that outputs to BUFFER."
926   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
927
928 (defun nntp-possibly-change-group (group server &optional connectionless)
929   (let ((nnheader-callback-function nil))
930     (when server
931       (or (nntp-server-opened server)
932           (nntp-open-server server nil connectionless)))
933
934     (unless connectionless
935       (or (nntp-find-connection nntp-server-buffer)
936           (nntp-open-connection nntp-server-buffer))))
937
938   (when group
939     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
940       (when (not (equal group (caddr entry)))
941         (save-excursion
942           (set-buffer (process-buffer (car entry)))
943           (erase-buffer)
944           (nntp-send-string (car entry) (concat "GROUP " group))
945           (nntp-wait-for-string "^2.*\n")
946           (setcar (cddr entry) group)
947           (erase-buffer))))))
948
949 (defun nntp-decode-text (&optional cr-only)
950   "Decode the text in the current buffer."
951   (goto-char (point-min))
952   (while (search-forward "\r" nil t)
953     (delete-char -1))
954   (unless cr-only
955     ;; Remove trailing ".\n" end-of-transfer marker.
956     (goto-char (point-max))
957     (forward-line -1)
958     (when (looking-at ".\n")
959       (delete-char 2))
960     ;; Delete status line.
961     (goto-char (point-min))
962     (delete-region (point) (progn (forward-line 1) (point)))
963     ;; Remove "." -> ".." encoding.
964     (while (search-forward "\n.." nil t)
965       (delete-char -1))))
966
967 (defun nntp-encode-text ()
968   "Encode the text in the current buffer."
969   (save-excursion
970     ;; Replace "." at beginning of line with "..".
971     (goto-char (point-min))
972     (while (re-search-forward "^\\." nil t)
973       (insert "."))
974     (goto-char (point-max))
975     ;; Insert newline at the end of the buffer.
976     (unless (bolp)
977       (insert "\n"))
978     ;; Insert `.' at end of buffer (end of text mark).
979     (goto-char (point-max))
980     (insert ".\n")
981     (goto-char (point-min))
982     (while (not (eobp))
983       (end-of-line)
984       (delete-char 1)
985       (insert nntp-end-of-line)
986       (forward-line 1))
987     (forward-char -1)
988     (unless (eq (char-after (1- (point))) ?\r)
989       (insert "\r"))))
990
991 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
992   (set-buffer nntp-server-buffer)
993   (erase-buffer)
994   (cond
995
996    ;; This server does not talk NOV.
997    ((not nntp-server-xover)
998     nil)
999
1000    ;; We don't care about gaps.
1001    ((or (not nntp-nov-gap)
1002         fetch-old)
1003     (nntp-send-xover-command
1004      (if fetch-old
1005          (if (numberp fetch-old)
1006              (max 1 (- (car articles) fetch-old))
1007            1)
1008        (car articles))
1009      (car (last articles)) 'wait)
1010
1011     (goto-char (point-min))
1012     (when (looking-at "[1-5][0-9][0-9] ")
1013       (delete-region (point) (progn (forward-line 1) (point))))
1014     (while (search-forward "\r" nil t)
1015       (replace-match "" t t))
1016     (goto-char (point-max))
1017     (forward-line -1)
1018     (when (looking-at "\\.")
1019       (delete-region (point) (progn (forward-line 1) (point)))))
1020
1021    ;; We do it the hard way.  For each gap, an XOVER command is sent
1022    ;; to the server.  We do not wait for a reply from the server, we
1023    ;; just send them off as fast as we can.  That means that we have
1024    ;; to count the number of responses we get back to find out when we
1025    ;; have gotten all we asked for.
1026    ((numberp nntp-nov-gap)
1027     (let ((count 0)
1028           (received 0)
1029           (last-point (point-min))
1030           (buf nntp-server-buffer)
1031           ;;(process-buffer (nntp-find-connection (current-buffer))))
1032           first)
1033       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1034       ;; that means that the server does not understand XOVER, but we
1035       ;; won't know that until we try.
1036       (while (and nntp-server-xover articles)
1037         (setq first (car articles))
1038         ;; Search forward until we find a gap, or until we run out of
1039         ;; articles.
1040         (while (and (cdr articles)
1041                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1042           (setq articles (cdr articles)))
1043
1044         (when (nntp-send-xover-command first (car articles))
1045           (setq articles (cdr articles)
1046                 count (1+ count))
1047
1048           ;; Every 400 requests we have to read the stream in
1049           ;; order to avoid deadlocks.
1050           (when (or (null articles)     ;All requests have been sent.
1051                     (zerop (% count nntp-maximum-request)))
1052             (accept-process-output)
1053             ;; On some Emacs versions the preceding function has
1054             ;; a tendency to change the buffer.  Perhaps.  It's
1055             ;; quite difficult to reproduce, because it only
1056             ;; seems to happen once in a blue moon.
1057             (set-buffer buf)
1058             (while (progn
1059                      (goto-char last-point)
1060                      ;; Count replies.
1061                      (while (re-search-forward "^[0-9][0-9][0-9] " nil t)
1062                        (setq received (1+ received)))
1063                      (setq last-point (point))
1064                      (< received count))
1065               (accept-process-output)
1066               (set-buffer buf)))))
1067
1068       (when nntp-server-xover
1069         ;; Wait for the reply from the final command.
1070         (goto-char (point-max))
1071         (re-search-backward "^[0-9][0-9][0-9] " nil t)
1072         (when (looking-at "^[23]")
1073           (while (progn
1074                    (goto-char (point-max))
1075                    (forward-line -1)
1076                    (not (looking-at "^\\.\r?\n")))
1077             (nntp-accept-response)))
1078
1079         ;; We remove any "." lines and status lines.
1080         (goto-char (point-min))
1081         (while (search-forward "\r" nil t)
1082           (delete-char -1))
1083         (goto-char (point-min))
1084         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1085         ;;(copy-to-buffer nntp-server-buffer (point-min) (point-max))
1086         t))))
1087
1088   nntp-server-xover)
1089
1090 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1091   "Send the XOVER command to the server."
1092   (let ((range (format "%d-%d" beg end))
1093         (nntp-inhibit-erase t))
1094     (if (stringp nntp-server-xover)
1095         ;; If `nntp-server-xover' is a string, then we just send this
1096         ;; command.
1097         (if wait-for-reply
1098             (nntp-send-command-nodelete
1099              "\r?\n\\.\r?\n" nntp-server-xover range)
1100           ;; We do not wait for the reply.
1101           (nntp-send-command-nodelete "\r?\n\\.\r?\n" nntp-server-xover range))
1102       (let ((commands nntp-xover-commands))
1103         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1104         ;; We try them all until we get at positive response.
1105         (while (and commands (eq nntp-server-xover 'try))
1106           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1107           (save-excursion
1108             (set-buffer nntp-server-buffer)
1109             (goto-char (point-min))
1110             (and (looking-at "[23]")    ; No error message.
1111                  ;; We also have to look at the lines.  Some buggy
1112                  ;; servers give back simple lines with just the
1113                  ;; article number.  How... helpful.
1114                  (progn
1115                    (forward-line 1)
1116                    (looking-at "[0-9]+\t...")) ; More text after number.
1117                  (setq nntp-server-xover (car commands))))
1118           (setq commands (cdr commands)))
1119         ;; If none of the commands worked, we disable XOVER.
1120         (when (eq nntp-server-xover 'try)
1121           (save-excursion
1122             (set-buffer nntp-server-buffer)
1123             (erase-buffer)
1124             (setq nntp-server-xover nil)))
1125         nntp-server-xover))))
1126
1127 ;;; Alternative connection methods.
1128
1129 (defun nntp-wait-for-string (regexp)
1130   "Wait until string arrives in the buffer."
1131   (let ((buf (current-buffer)))
1132     (goto-char (point-min))
1133     (while (not (re-search-forward regexp nil t))
1134       (accept-process-output (nntp-find-connection nntp-server-buffer))
1135       (set-buffer buf)
1136       (goto-char (point-min)))))
1137
1138 (defun nntp-open-telnet (buffer)
1139   (save-excursion
1140     (set-buffer buffer)
1141     (erase-buffer)
1142     (let ((proc (apply
1143                  'start-process
1144                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1145           (case-fold-search t))
1146       (when (memq (process-status proc) '(open run))
1147         (process-send-string proc "set escape \^X\n")
1148         (cond
1149          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1150           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1151                                             nntp-address "\n")))
1152          (t
1153           (process-send-string proc (concat "open " nntp-address "\n"))))
1154         (cond
1155          ((not nntp-open-telnet-envuser)
1156           (nntp-wait-for-string "^\r*.?login:")
1157           (process-send-string
1158            proc (concat
1159                  (or nntp-telnet-user-name
1160                      (setq nntp-telnet-user-name (read-string "login: ")))
1161                  "\n"))))
1162         (nntp-wait-for-string "^\r*.?password:")
1163         (process-send-string
1164          proc (concat
1165                (or nntp-telnet-passwd
1166                    (setq nntp-telnet-passwd
1167                          (nnmail-read-passwd "Password: ")))
1168                "\n"))
1169         (erase-buffer)
1170         (nntp-wait-for-string nntp-telnet-shell-prompt)
1171         (process-send-string
1172          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1173         (nntp-wait-for-string "^\r*20[01]")
1174         (beginning-of-line)
1175         (delete-region (point-min) (point))
1176         (process-send-string proc "\^]")
1177         (nntp-wait-for-string "^telnet")
1178         (process-send-string proc "mode character\n")
1179         (accept-process-output proc 1)
1180         (sit-for 1)
1181         (goto-char (point-min))
1182         (forward-line 1)
1183         (delete-region (point) (point-max)))
1184       proc)))
1185
1186 (defun nntp-open-rlogin (buffer)
1187   "Open a connection to SERVER using rsh."
1188   (let ((proc (if nntp-rlogin-user-name
1189                   (apply 'start-process
1190                          "nntpd" buffer nntp-rlogin-program
1191                          nntp-address "-l" nntp-rlogin-user-name
1192                          nntp-rlogin-parameters)
1193                 (apply 'start-process
1194                        "nntpd" buffer nntp-rlogin-program nntp-address
1195                        nntp-rlogin-parameters))))
1196     (save-excursion
1197       (set-buffer buffer)
1198       (nntp-wait-for-string "^\r*20[01]")
1199       (beginning-of-line)
1200       (delete-region (point-min) (point))
1201       proc)))
1202
1203 (defun nntp-find-group-and-number ()
1204   (save-excursion
1205     (save-restriction
1206       (set-buffer nntp-server-buffer)
1207       (narrow-to-region (goto-char (point-min))
1208                         (or (search-forward "\n\n" nil t) (point-max)))
1209       (goto-char (point-min))
1210       ;; We first find the number by looking at the status line.
1211       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1212                          (string-to-int
1213                           (buffer-substring (match-beginning 1)
1214                                             (match-end 1)))))
1215             group newsgroups xref)
1216         (and number (zerop number) (setq number nil))
1217         ;; Then we find the group name.
1218         (setq group
1219               (cond
1220                ;; If there is only one group in the Newsgroups header,
1221                ;; then it seems quite likely that this article comes
1222                ;; from that group, I'd say.
1223                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
1224                      (not (string-match "," newsgroups)))
1225                 newsgroups)
1226                ;; If there is more than one group in the Newsgroups
1227                ;; header, then the Xref header should be filled out.
1228                ;; We hazard a guess that the group that has this
1229                ;; article number in the Xref header is the one we are
1230                ;; looking for.  This might very well be wrong if this
1231                ;; article happens to have the same number in several
1232                ;; groups, but that's life.
1233                ((and (setq xref (mail-fetch-field "xref"))
1234                      number
1235                      (string-match (format "\\([^ :]+\\):%d" number) xref))
1236                 (substring xref (match-beginning 1) (match-end 1)))
1237                (t "")))
1238         (when (string-match "\r" group)
1239           (setq group (substring group 0 (match-beginning 0))))
1240         (cons group number)))))
1241
1242 (provide 'nntp)
1243
1244 ;;; nntp.el ends here