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