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