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