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