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