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