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