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