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