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