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