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