*** 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-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       (unless (< len 10)
825         (setq nntp-have-messaged t)
826         (nnheader-message 7 "nntp read: %dk" len)))
827     (accept-process-output process 1)))
828
829 (defun nntp-accept-response ()
830   "Wait for output from the process that outputs to BUFFER."
831   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
832
833 (defun nntp-possibly-change-group (group server &optional connectionless)
834   (let ((nnheader-callback-function nil))
835     (when server
836       (or (nntp-server-opened server)
837           (nntp-open-server server nil connectionless)))
838
839     (unless connectionless
840       (or (nntp-find-connection nntp-server-buffer)
841           (nntp-open-connection nntp-server-buffer))))
842
843   (when group
844     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
845       (when (not (equal group (caddr entry)))
846         (save-excursion
847           (set-buffer (process-buffer (car entry)))
848           (erase-buffer)
849           (nntp-send-string (car entry) (concat "GROUP " group))
850           (nntp-wait-for-string "^2.*\n")
851           (setcar (cddr entry) group)
852           (erase-buffer))))))
853
854 (defun nntp-decode-text (&optional cr-only)
855   "Decode the text in the current buffer."
856   (goto-char (point-min))
857   (while (search-forward "\r" nil t)
858     (delete-char -1))
859   (unless cr-only
860     ;; Remove trailing ".\n" end-of-transfer marker.
861     (goto-char (point-max))
862     (forward-line -1)
863     (when (looking-at ".\n")
864       (delete-char 2))
865     ;; Delete status line.
866     (goto-char (point-min))
867     (delete-region (point) (progn (forward-line 1) (point)))
868     ;; Remove "." -> ".." encoding.
869     (while (search-forward "\n.." nil t)
870       (delete-char -1))))
871
872 (defun nntp-encode-text ()
873   "Encode the text in the current buffer."
874   (save-excursion
875     ;; Replace "." at beginning of line with "..".
876     (goto-char (point-min))
877     (while (re-search-forward "^\\." nil t)
878       (insert "."))
879     (goto-char (point-max))
880     ;; Insert newline at the end of the buffer.
881     (unless (bolp)
882       (insert "\n"))
883     ;; Insert `.' at end of buffer (end of text mark).
884     (goto-char (point-max))
885     (insert "." nntp-end-of-line)))
886
887 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
888   (set-buffer nntp-server-buffer)
889   (erase-buffer)
890   (cond 
891
892    ;; This server does not talk NOV.
893    ((not nntp-server-xover)
894     nil)
895
896    ;; We don't care about gaps.
897    ((or (not nntp-nov-gap)
898         fetch-old)
899     (nntp-send-xover-command 
900      (if fetch-old
901          (if (numberp fetch-old)
902              (max 1 (- (car articles) fetch-old))
903            1)
904        (car articles))
905      (car (last articles)) 'wait)
906
907     (goto-char (point-min))
908     (when (looking-at "[1-5][0-9][0-9] ")
909       (delete-region (point) (progn (forward-line 1) (point))))
910     (while (search-forward "\r" nil t)
911       (replace-match "" t t))
912     (goto-char (point-max))
913     (forward-line -1)
914     (when (looking-at "\\.")
915       (delete-region (point) (progn (forward-line 1) (point)))))
916
917    ;; We do it the hard way.  For each gap, an XOVER command is sent
918    ;; to the server.  We do not wait for a reply from the server, we
919    ;; just send them off as fast as we can.  That means that we have
920    ;; to count the number of responses we get back to find out when we
921    ;; have gotten all we asked for.
922    ((numberp nntp-nov-gap)
923     (let ((count 0)
924           (received 0)
925           (last-point (point-min))
926           (buf nntp-server-buffer)
927           ;;(process-buffer (nntp-find-connection (current-buffer))))
928           first)
929       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
930       ;; that means that the server does not understand XOVER, but we
931       ;; won't know that until we try.
932       (while (and nntp-server-xover articles)
933         (setq first (car articles))
934         ;; Search forward until we find a gap, or until we run out of
935         ;; articles. 
936         (while (and (cdr articles)
937                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
938           (setq articles (cdr articles)))
939
940         (when (nntp-send-xover-command first (car articles))
941           (setq articles (cdr articles)
942                 count (1+ count))
943
944           ;; Every 400 requests we have to read the stream in
945           ;; order to avoid deadlocks.
946           (when (or (null articles)     ;All requests have been sent.
947                     (zerop (% count nntp-maximum-request)))
948             (accept-process-output)
949             ;; On some Emacs versions the preceding function has
950             ;; a tendency to change the buffer.  Perhaps.  It's
951             ;; quite difficult to reproduce, because it only
952             ;; seems to happen once in a blue moon. 
953             (set-buffer buf)
954             (while (progn
955                      (goto-char last-point)
956                      ;; Count replies.
957                      (while (re-search-forward "^[0-9][0-9][0-9] " nil t)
958                        (setq received (1+ received)))
959                      (setq last-point (point))
960                      (< received count))
961               (accept-process-output)
962               (set-buffer buf)))))
963
964       (when nntp-server-xover
965         ;; Wait for the reply from the final command.
966         (goto-char (point-max))
967         (re-search-backward "^[0-9][0-9][0-9] " nil t)
968         (when (looking-at "^[23]")
969           (while (progn
970                    (goto-char (point-max))
971                    (forward-line -1)
972                    (not (looking-at "^\\.\r?\n")))
973             (nntp-accept-response)))
974         
975         ;; We remove any "." lines and status lines.
976         (goto-char (point-min))
977         (while (search-forward "\r" nil t)
978           (delete-char -1))
979         (goto-char (point-min))
980         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
981         ;;(copy-to-buffer nntp-server-buffer (point-min) (point-max))
982         t))))
983
984   nntp-server-xover)
985
986 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
987   "Send the XOVER command to the server."
988   (let ((range (format "%d-%d" beg end))
989         (nntp-inhibit-erase t))
990     (if (stringp nntp-server-xover)
991         ;; If `nntp-server-xover' is a string, then we just send this
992         ;; command.
993         (if wait-for-reply
994             (nntp-send-command-nodelete 
995              "\r?\n\\.\r?\n" nntp-server-xover range)
996           ;; We do not wait for the reply.
997           (nntp-send-command-nodelete "\r?\n\\.\r?\n" nntp-server-xover range))
998       (let ((commands nntp-xover-commands))
999         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1000         ;; We try them all until we get at positive response. 
1001         (while (and commands (eq nntp-server-xover 'try))
1002           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1003           (save-excursion
1004             (set-buffer nntp-server-buffer)
1005             (goto-char (point-min))
1006             (and (looking-at "[23]")    ; No error message.
1007                  ;; We also have to look at the lines.  Some buggy
1008                  ;; servers give back simple lines with just the
1009                  ;; article number.  How... helpful.
1010                  (progn
1011                    (forward-line 1)
1012                    (looking-at "[0-9]+\t...")) ; More text after number.
1013                  (setq nntp-server-xover (car commands))))
1014           (setq commands (cdr commands)))
1015         ;; If none of the commands worked, we disable XOVER.
1016         (when (eq nntp-server-xover 'try)
1017           (save-excursion
1018             (set-buffer nntp-server-buffer)
1019             (erase-buffer)
1020             (setq nntp-server-xover nil)))
1021         nntp-server-xover))))
1022
1023 ;;; Alternative connection methods.
1024
1025 (defun nntp-wait-for-string (regexp)
1026   "Wait until string arrives in the buffer."
1027   (let ((buf (current-buffer)))
1028     (goto-char (point-min))
1029     (while (not (re-search-forward regexp nil t))
1030       (accept-process-output (nntp-find-connection nntp-server-buffer))
1031       (set-buffer buf)
1032       (goto-char (point-min)))))
1033
1034 (defun nntp-open-telnet (buffer)
1035   (save-excursion
1036     (set-buffer buffer)
1037     (erase-buffer)
1038     (let ((proc (start-process
1039                  "nntpd" buffer "telnet" "-8"))
1040           (case-fold-search t))
1041       (when (memq (process-status proc) '(open run))
1042         (process-send-string proc "set escape \^X\n")
1043         (process-send-string proc (concat "open " nntp-address "\n"))
1044         (nntp-wait-for-string "^\r*.?login:")
1045         (process-send-string
1046          proc (concat
1047                (or nntp-telnet-user-name
1048                    (setq nntp-telnet-user-name (read-string "login: ")))
1049                "\n"))
1050         (nntp-wait-for-string "^\r*.?password:")
1051         (process-send-string
1052          proc (concat
1053                (or nntp-telnet-passwd
1054                    (setq nntp-telnet-passwd
1055                          (nnmail-read-passwd "Password: ")))
1056                "\n"))
1057         (erase-buffer)
1058         (nntp-wait-for-string "bash\\|\$ *\r?$\\|> *\r?")
1059         (process-send-string
1060          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1061         (nntp-wait-for-string "^\r*200")
1062         (beginning-of-line)
1063         (delete-region (point-min) (point))
1064         (process-send-string proc "\^]")
1065         (nntp-wait-for-string "^telnet")
1066         (process-send-string proc "mode character\n")
1067         (accept-process-output proc 1)
1068         (sit-for 1)
1069         (goto-char (point-min))
1070         (forward-line 1)
1071         (delete-region (point) (point-max)))
1072       proc)))
1073
1074 (defun nntp-open-rlogin (buffer)
1075   "Open a connection to SERVER using rsh."
1076   (let ((proc (if nntp-rlogin-user-name
1077                   (start-process
1078                    "nntpd" buffer "rsh"
1079                    nntp-address "-l" nntp-rlogin-user-name
1080                    (mapconcat 'identity
1081                               nntp-rlogin-parameters " "))
1082                 (start-process
1083                  "nntpd" buffer "rsh" nntp-address
1084                  (mapconcat 'identity
1085                             nntp-rlogin-parameters " ")))))
1086     (set-buffer buffer)
1087     (nntp-wait-for-string "^\r*200")
1088     (beginning-of-line)
1089     (delete-region (point-min) (point))
1090     proc))
1091
1092 (defun nntp-find-group-and-number ()
1093   (save-excursion
1094     (save-restriction
1095       (set-buffer nntp-server-buffer)
1096       (narrow-to-region (goto-char (point-min))
1097                         (or (search-forward "\n\n" nil t) (point-max)))
1098       (goto-char (point-min))
1099       ;; We first find the number by looking at the status line.
1100       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1101                          (string-to-int
1102                           (buffer-substring (match-beginning 1)
1103                                             (match-end 1)))))
1104             group newsgroups xref)
1105         (and number (zerop number) (setq number nil))
1106         ;; Then we find the group name.
1107         (setq group
1108               (cond 
1109                ;; If there is only one group in the Newsgroups header,
1110                ;; then it seems quite likely that this article comes
1111                ;; from that group, I'd say.
1112                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
1113                      (not (string-match "," newsgroups)))
1114                 newsgroups)
1115                ;; If there is more than one group in the Newsgroups
1116                ;; header, then the Xref header should be filled out.
1117                ;; We hazard a guess that the group that has this
1118                ;; article number in the Xref header is the one we are
1119                ;; looking for.  This might very well be wrong if this
1120                ;; article happens to have the same number in several
1121                ;; groups, but that's life. 
1122                ((and (setq xref (mail-fetch-field "xref"))
1123                      number
1124                      (string-match (format "\\([^ :]+\\):%d" number) xref))
1125                 (substring xref (match-beginning 1) (match-end 1)))
1126                (t "")))
1127         (when (string-match "\r" group)
1128           (setq group (substring group 0 (match-beginning 0))))
1129         (cons group number)))))
1130
1131 (provide 'nntp)
1132
1133 ;;; nntp.el ends here