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