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