*** empty log message ***
[gnus] / lisp / nntp.el
1 ;;; nntp.el --- nntp access for Gnus
2 ;; Copyright (C) 1987,88,89,90,92,93,94,95 Free Software Foundation, Inc.
3
4 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
5 ;;      Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to
22 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (require 'rnews)
29 (require 'sendmail)
30 (require 'nnheader)
31
32 (eval-when-compile (require 'cl))
33
34 (eval-and-compile
35   (autoload 'news-setup "rnewspost")
36   (autoload 'news-reply-mode "rnewspost")
37   (autoload 'cancel-timer "timer")
38   (autoload 'telnet "telnet" nil t)
39   (autoload 'telnet-send-input "telnet" nil t)
40   (autoload 'timezone-parse-date "timezone"))
41
42 (defvar nntp-server-hook nil
43   "*Hooks for the NNTP server.
44 If the kanji code of the NNTP server is different from the local kanji
45 code, the correct kanji code of the buffer associated with the NNTP
46 server must be specified as follows:
47
48 \(setq nntp-server-hook
49       (function
50        (lambda ()
51          ;; Server's Kanji code is EUC (NEmacs hack).
52          (make-local-variable 'kanji-fileio-code)
53          (setq kanji-fileio-code 0))))
54
55 If you'd like to change something depending on the server in this
56 hook, use the variable `nntp-address'.")
57
58 (defvar nntp-server-opened-hook nil
59   "*Hook used for sending commands to the server at startup.  
60 The default value is `nntp-send-mode-reader', which makes an innd
61 server spawn an nnrpd server.  Another useful function to put in this
62 hook might be `nntp-send-authinfo', which will prompt for a password
63 to allow posting from the server.  Note that this is only necessary to
64 do on servers that use strict access control.")  
65 (add-hook 'nntp-server-opened-hook 'nntp-send-mode-reader)
66
67 (defvar nntp-open-server-function 'nntp-open-network-stream
68   "*Function used for connecting to a remote system.
69 It will be called with the address of the remote system.
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 is `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).")
76
77 (defvar nntp-rlogin-parameters '("telnet" "${NNTPSERVER:=localhost}" "nntp")
78   "*Parameters to `nntp-open-login'.
79 That function may be used as `nntp-open-server-function'.  In that
80 case, this list will be used as the parameter list given to rsh.")
81
82 (defvar nntp-rlogin-user-name nil
83   "*User name on remote system when using the rlogin connect method.")
84
85 (defvar nntp-address nil
86   "*The name of the NNTP server.")
87
88 (defvar nntp-port-number "nntp"
89   "*Port number to connect to.")
90
91 (defvar nntp-large-newsgroup 50
92   "*The number of the articles which indicates a large newsgroup.
93 If the number of the articles is greater than the value, verbose
94 messages will be shown to indicate the current status.")
95
96 (defvar nntp-buggy-select (memq system-type '(fujitsu-uts))
97   "*t if your select routine is buggy.
98 If the select routine signals error or fall into infinite loop while
99 waiting for the server response, the variable must be set to t.  In
100 case of Fujitsu UTS, it is set to T since `accept-process-output'
101 doesn't work properly.")
102
103 (defvar nntp-maximum-request 400
104   "*The maximum number of the requests sent to the NNTP server at one time.
105 If Emacs hangs up while retrieving headers, set the variable to a
106 lower value.")
107
108 (defvar nntp-debug-read 10000
109   "*Display '...' every 10Kbytes of a message being received if it is non-nil.
110 If it is a number, dots are displayed per the number.")
111
112 (defvar nntp-nov-is-evil nil
113   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
114
115 (defvar nntp-xover-commands '("XOVER" "XOVERVIEW")
116   "*List of strings that are used as commands to fetch NOV lines from a server.
117 The strings are tried in turn until a positive response is gotten. If
118 none of the commands are successful, nntp will just grab headers one
119 by one.")
120
121 (defvar nntp-nov-gap 20
122   "*Maximum allowed gap between two articles.
123 If the gap between two consecutive articles is bigger than this
124 variable, split the XOVER request into two requests.")
125
126 (defvar nntp-connection-timeout nil
127   "*Number of seconds to wait before an nntp connection times out.
128 If this variable is nil, which is the default, no timers are set.")
129
130 (defvar nntp-news-default-headers nil
131   "*If non-nil, override `mail-default-headers' when posting news.")
132
133 (defvar nntp-prepare-server-hook nil
134   "*Hook run before a server is opened.
135 If can be used to set up a server remotely, for instance.  Say you
136 have an account at the machine \"other.machine\".  This machine has
137 access to an NNTP server that you can't access locally.  You could
138 then use this hook to rsh to the remote machine and start a proxy NNTP
139 server there that you can connect to.")
140
141 (defvar nntp-async-number 5
142   "*How many articles should be prefetched when in asynchronous mode.")
143
144 (defvar nntp-warn-about-losing-connection t
145   "*If non-nil, beep when a server closes connection.")
146
147 \f
148
149 (defconst nntp-version "nntp 4.0"
150   "Version numbers of this version of NNTP.")
151
152 (defvar nntp-server-buffer nil
153   "Buffer associated with the NNTP server process.")
154
155 (defvar nntp-server-process nil
156   "The NNTP server process.
157 You'd better not use this variable in NNTP front-end program, but
158 instead use `nntp-server-buffer'.")
159
160 (defvar nntp-status-string nil
161   "Save the server response message.
162 You'd better not use this variable in NNTP front-end program but
163 instead call function `nntp-status-message' to get status message.")
164
165 (defvar nntp-opened-connections nil
166   "All (possibly) opened connections.")
167
168 (defvar nntp-server-xover 'try)
169 (defvar nntp-server-list-active-group 'try)
170 (defvar nntp-current-group "")
171
172 (defvar nntp-async-process nil)
173 (defvar nntp-async-buffer nil)
174 (defvar nntp-async-articles nil)
175 (defvar nntp-async-fetched nil)
176 (defvar nntp-async-group-alist nil)
177
178
179 \f
180 (defvar nntp-current-server nil)
181 (defvar nntp-server-alist nil)
182 (defvar nntp-server-variables 
183   `((nntp-server-hook ,nntp-server-hook)
184     (nntp-server-opened-hook ,nntp-server-opened-hook)
185     (nntp-port-number ,nntp-port-number)
186     (nntp-address ,nntp-address)
187     (nntp-large-newsgroup ,nntp-large-newsgroup)
188     (nntp-buggy-select ,nntp-buggy-select)
189     (nntp-maximum-request ,nntp-maximum-request)
190     (nntp-debug-read ,nntp-debug-read)
191     (nntp-nov-is-evil ,nntp-nov-is-evil)
192     (nntp-xover-commands ,nntp-xover-commands)
193     (nntp-connection-timeout ,nntp-connection-timeout)
194     (nntp-news-default-headers ,nntp-news-default-headers)
195     (nntp-prepare-server-hook ,nntp-prepare-server-hook) 
196     (nntp-async-number ,nntp-async-number)
197     (nntp-async-process nil)
198     (nntp-async-buffer nil)
199     (nntp-async-articles nil)
200     (nntp-async-fetched nil)
201     (nntp-async-group-alist nil)
202     (nntp-server-process nil)
203     (nntp-status-string nil)
204     (nntp-server-xover try)
205     (nntp-server-list-active-group try)
206     (nntp-current-group "")))
207
208 \f
209 ;;; Interface functions.
210
211 (defun nntp-retrieve-headers (articles &optional group server fetch-old)
212   "Retrieve the headers of ARTICLES."
213   (nntp-possibly-change-server group server)
214   (save-excursion
215     (set-buffer nntp-server-buffer)
216     (erase-buffer)
217     (if (and (not gnus-nov-is-evil) 
218              (not nntp-nov-is-evil)
219              (nntp-retrieve-headers-with-xover articles fetch-old))
220         ;; We successfully retrieved the headers via XOVER.
221         'nov
222       ;; XOVER didn't work, so we do it the hard, slow and inefficient
223       ;; way.  
224       (let ((number (length articles))
225             (count 0)
226             (received 0)
227             (last-point (point-min)))
228         ;; Send HEAD command.
229         (while articles
230           (nntp-send-strings-to-server 
231            "HEAD" (if (numberp (car articles)) 
232                       (int-to-string (car articles))
233                     ;; `articles' is either a list of article numbers
234                     ;; or a list of article IDs.
235                     (car articles)))
236           (setq articles (cdr articles)
237                 count (1+ count))
238           ;; Every 400 header requests we have to read the stream in
239           ;; order to avoid deadlocks.
240           (when (or (null articles)     ;All requests have been sent.
241                     (zerop (% count nntp-maximum-request)))
242             (nntp-accept-response)
243             (while (progn
244                      (goto-char last-point)
245                      ;; Count replies.
246                      (while (re-search-forward "^[0-9]" nil t)
247                        (setq received (1+ received)))
248                      (setq last-point (point))
249                      (< received count))
250               ;; If number of headers is greater than 100, give
251               ;;  informative messages.
252               (and (numberp nntp-large-newsgroup)
253                    (> number nntp-large-newsgroup)
254                    (zerop (% received 20))
255                    (message "NNTP: Receiving headers... %d%%"
256                             (/ (* received 100) number)))
257               (nntp-accept-response))))
258         ;; Wait for text of last command.
259         (goto-char (point-max))
260         (re-search-backward "^[0-9]" nil t)
261         (when (looking-at "^[23]")
262           (while (progn
263                    (goto-char (- (point-max) 3))
264                    (not (looking-at "^\\.\r?\n")))
265             (nntp-accept-response)))
266         (and (numberp nntp-large-newsgroup)
267              (> number nntp-large-newsgroup)
268              (message "NNTP: Receiving headers...done"))
269
270         ;; Now all of replies are received.  Fold continuation lines.
271         (goto-char (point-min))
272         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
273           (replace-match " " t t))
274         ;; Remove all "\r"'s.
275         (goto-char (point-min))
276         (while (search-forward "\r" nil t)
277           (replace-match "" t t))
278         'headers))))
279
280
281 (defun nntp-retrieve-groups (groups &optional server)
282   "Retrieve group info on GROUPS."
283   (nntp-possibly-change-server nil server)
284   (save-excursion
285     (set-buffer nntp-server-buffer)
286     ;; The first time this is run, this variable is `try'.  So we
287     ;; try.   
288     (when (eq nntp-server-list-active-group 'try)
289       (nntp-try-list-active (car groups)))
290     (erase-buffer)
291     (let ((count 0)
292           (received 0)
293           (last-point (point-min))
294           (command (if nntp-server-list-active-group "LIST ACTIVE" "GROUP")))
295       (while groups
296         ;; Send the command to the server.
297         (nntp-send-strings-to-server command (car groups))
298         (setq groups (cdr groups))
299         (setq count (1+ count))
300         ;; Every 400 requests we have to read the stream in
301         ;; order to avoid deadlocks.
302         (when (or (null groups)         ;All requests have been sent.
303                   (zerop (% count nntp-maximum-request)))
304           (nntp-accept-response)
305           (while (progn
306                    (goto-char last-point)
307                    ;; Count replies.
308                    (while (re-search-forward "^[0-9]" nil t)
309                      (setq received (1+ received)))
310                    (setq last-point (point))
311                    (< received count))
312             (nntp-accept-response))))
313
314       ;; Wait for the reply from the final command.
315       (when nntp-server-list-active-group
316         (goto-char (point-max))
317         (re-search-backward "^[0-9]" nil t)
318         (when (looking-at "^[23]")
319           (while (progn
320                    (goto-char (- (point-max) 3))
321                    (not (looking-at "^\\.\r?\n")))
322             (nntp-accept-response))))
323
324       ;; Now all replies are received. We remove CRs.
325       (goto-char (point-min))
326       (while (search-forward "\r" nil t)
327         (replace-match "" t t))
328
329       (if (not nntp-server-list-active-group)
330           'group
331         ;; We have read active entries, so we just delete the
332         ;; superfluos gunk.
333         (goto-char (point-min))
334         (while (re-search-forward "^[.2-5]" nil t)
335           (delete-region (match-beginning 0) 
336                          (progn (forward-line 1) (point))))
337         'active))))
338
339 (defun nntp-open-server (server &optional defs connectionless)
340   "Open the virtual server SERVER.
341 If CONNECTIONLESS is non-nil, don't attempt to connect to any physical
342 servers."
343   (nnheader-init-server-buffer)
344   (if (nntp-server-opened server)
345       t
346     (if (or (stringp (car defs))
347             (numberp (car defs)))
348         (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
349     (or (assq 'nntp-address defs)
350         (setq defs (append defs (list (list 'nntp-address server)))))
351     (if (and nntp-current-server
352              (not (equal server nntp-current-server)))
353         (setq nntp-server-alist 
354               (cons (list nntp-current-server
355                           (nnheader-save-variables nntp-server-variables))
356                     nntp-server-alist)))
357     (let ((state (assoc server nntp-server-alist)))
358       (if state 
359           (progn
360             (nnheader-restore-variables (nth 1 state))
361             (setq nntp-server-alist (delq state nntp-server-alist)))
362         (nnheader-set-init-variables nntp-server-variables defs)))
363     (setq nntp-current-server server)
364     (or (nntp-server-opened server)
365         connectionless
366         (progn
367           (run-hooks 'nntp-prepare-server-hook)
368           (nntp-open-server-semi-internal nntp-address nntp-port-number)))))
369
370 (defun nntp-close-server (&optional server)
371   "Close connection to SERVER."
372   (nntp-possibly-change-server nil server t)
373   (unwind-protect
374       (progn
375         ;; Un-set default sentinel function before closing connection.
376         (and nntp-server-process
377              (eq 'nntp-default-sentinel
378                  (process-sentinel nntp-server-process))
379              (set-process-sentinel nntp-server-process nil))
380         ;; We cannot send QUIT command unless the process is running.
381         (if (nntp-server-opened)
382             (nntp-send-command nil "QUIT")))
383     (nntp-close-server-internal server)))
384
385 (defalias 'nntp-request-quit (symbol-function 'nntp-close-server))
386
387 (defun nntp-request-close ()
388   "Close all server connections."
389   (let (proc)
390      (while nntp-opened-connections
391        (when (setq proc (pop nntp-opened-connections))
392          (condition-case ()
393              (process-send-string proc "QUIT\n")
394            (error nil))
395          (delete-process proc)))
396      (and nntp-async-buffer
397           (get-buffer nntp-async-buffer)
398           (kill-buffer nntp-async-buffer))
399     (while nntp-server-alist
400       (and (setq proc (nth 1 (assq 'nntp-async-buffer
401                                    (car nntp-server-alist))))
402            (buffer-name proc)
403            (kill-buffer proc))
404       (setq nntp-server-alist (cdr nntp-server-alist)))
405     (setq nntp-current-server nil
406           nntp-async-group-alist nil)))
407
408 (defun nntp-server-opened (&optional server)
409   "Say whether a connection to SERVER has been opened."
410   (and (equal server nntp-current-server)
411        nntp-server-buffer
412        (buffer-name nntp-server-buffer)
413        nntp-server-process
414        (memq (process-status nntp-server-process) '(open run))))
415
416 (defun nntp-status-message (&optional server)
417   "Return server status as a string."
418   (if (and nntp-status-string
419            ;; NNN MESSAGE
420            (string-match "[0-9][0-9][0-9][ \t]+\\([^\r]*\\).*$"
421                          nntp-status-string))
422       (substring nntp-status-string (match-beginning 1) (match-end 1))
423     ;; Empty message if nothing.
424     (or nntp-status-string "")))
425
426 (defun nntp-request-article (id &optional group server buffer)
427   "Request article ID (Message-ID or number)."
428   (nntp-possibly-change-server group server)
429
430   (let (found)
431
432     ;; First we see whether we can get the article from the async buffer. 
433     (when (and (numberp id)
434                nntp-async-articles
435                (memq id nntp-async-fetched))
436       (save-excursion
437         (set-buffer nntp-async-buffer)
438         (let ((opoint (point))
439               (art (if (numberp id) (int-to-string id) id))
440               beg end)
441           (when (and (or (re-search-forward (concat "^2.. +" art) nil t)
442                          (progn
443                            (goto-char (point-min))
444                            (re-search-forward (concat "^2.. +" art) opoint t)))
445                      (progn
446                        (beginning-of-line)
447                        (setq beg (point)
448                              end (re-search-forward "^\\.\r?\n" nil t))))
449             (setq found t)
450             (save-excursion
451               (set-buffer (or buffer nntp-server-buffer))
452               (erase-buffer)
453               (insert-buffer-substring nntp-async-buffer beg end)
454               (let ((nntp-server-buffer (current-buffer)))
455                 (nntp-decode-text)))
456             (delete-region beg end)
457             (when nntp-async-articles
458               (nntp-async-fetch-articles id))))))
459
460     (if found 
461         id
462       ;; The article was not in the async buffer, so we fetch it now.
463       (unwind-protect
464           (progn
465             (if buffer (set-process-buffer nntp-server-process buffer))
466             (let ((nntp-server-buffer (or buffer nntp-server-buffer))
467                   (art (or (and (numberp id) (int-to-string id)) id)))
468               (prog1
469                   (and (nntp-send-command "^\\.\r?\n" "ARTICLE" art)
470                        (if (numberp id) 
471                            (cons nntp-current-group id)
472                          ;; We find out what the article number was.
473                          (nntp-find-group-and-number)))
474                 (nntp-decode-text)
475                 (and nntp-async-articles (nntp-async-fetch-articles id)))))
476         (when buffer 
477           (set-process-buffer nntp-server-process nntp-server-buffer))))))
478
479 (defun nntp-request-body (id &optional group server)
480   "Request body of article ID (Message-ID or number)."
481   (nntp-possibly-change-server group server)
482   (prog1
483       ;; If NEmacs, end of message may look like: "\256\215" (".^M")
484       (nntp-send-command
485        "^\\.\r?\n" "BODY" (or (and (numberp id) (int-to-string id)) id))
486     (nntp-decode-text)))
487
488 (defun nntp-request-head (id &optional group server)
489   "Request head of article ID (Message-ID or number)."
490   (nntp-possibly-change-server group server)
491   (prog1
492       (and (nntp-send-command 
493             "^\\.\r?\n" "HEAD" (if (numberp id) (int-to-string id) id))
494            (if (numberp id) id
495              ;; We find out what the article number was.
496              (nntp-find-group-and-number)))
497     (nntp-decode-text)))
498
499 (defun nntp-request-stat (id &optional group server)
500   "Request STAT of article ID (Message-ID or number)."
501   (nntp-possibly-change-server group server)
502   (nntp-send-command 
503    "^[23].*\r?\n" "STAT" (or (and (numberp id) (int-to-string id)) id)))
504
505 (defun nntp-request-group (group &optional server dont-check)
506   "Select GROUP."
507   (setq nntp-current-group
508         (when (nntp-send-command "^2.*\r?\n" "GROUP" group)
509           group)))
510
511 (defun nntp-request-asynchronous (group &optional server articles)
512   "Enable pre-fetch in GROUP."
513   (when nntp-async-articles
514     (nntp-async-request-group group))
515   (when nntp-async-number
516     (if (not (or (nntp-async-server-opened)
517                  (nntp-async-open-server)))
518         ;; Couldn't open the second connection
519         (progn
520           (message "Can't open second connection to %s" nntp-address)
521           (ding)
522           (setq nntp-async-articles nil)
523           (sit-for 2))
524       ;; We opened the second connection (or it was opened already).  
525       (setq nntp-async-articles articles)
526       (setq nntp-async-fetched nil)
527       ;; Clear any old data.
528       (save-excursion
529         (set-buffer nntp-async-buffer)
530         (erase-buffer))
531       ;; Select the correct current group on this server.
532       (nntp-async-send-strings "GROUP" group)
533       t)))
534
535 (defun nntp-list-active-group (group &optional server)
536   "Return the active info on GROUP (which can be a regexp."
537   (nntp-possibly-change-server group server)
538   (nntp-send-command "^.*\r?\n" "LIST ACTIVE" group))
539
540 (defun nntp-request-group-description (group &optional server)
541   "Get the description of GROUP."
542   (nntp-possibly-change-server nil server)
543   (prog1
544       (nntp-send-command "^.*\r?\n" "XGTITLE" group)
545     (nntp-decode-text)))
546
547 (defun nntp-close-group (group &optional server)
548   "Close GROUP."
549   (setq nntp-current-group nil)
550   t)
551
552 (defun nntp-request-list (&optional server)
553   "List all active groups."
554   (nntp-possibly-change-server nil server)
555   (prog1
556       (nntp-send-command "^\\.\r?\n" "LIST")
557     (nntp-decode-text)))
558
559 (defun nntp-request-list-newsgroups (&optional server)
560   "Get descriptions on all groups on SERVER."
561   (nntp-possibly-change-server nil server)
562   (prog1
563       (nntp-send-command "^\\.\r?\n" "LIST NEWSGROUPS")
564     (nntp-decode-text)))
565
566 (defun nntp-request-newgroups (date &optional server)
567   "List groups that have arrived since DATE."
568   (nntp-possibly-change-server nil server)
569   (let* ((date (timezone-parse-date date))
570          (time-string
571           (format "%s%02d%02d %s%s%s"
572                   (substring (aref date 0) 2) (string-to-int (aref date 1)) 
573                   (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
574                   (substring 
575                    (aref date 3) 3 5) (substring (aref date 3) 6 8))))
576     (prog1
577         (nntp-send-command "^\\.\r?\n" "NEWGROUPS" time-string)
578       (nntp-decode-text))))
579
580 (defun nntp-request-list-distributions (&optional server)
581   "List distributions."
582   (nntp-possibly-change-server nil server)
583   (prog1
584       (nntp-send-command "^\\.\r?\n" "LIST DISTRIBUTIONS")
585     (nntp-decode-text)))
586
587 (defun nntp-request-last (&optional group server)
588   "Decrease the current article pointer."
589   (nntp-possibly-change-server group server)
590   (nntp-send-command "^[23].*\r?\n" "LAST"))
591
592 (defun nntp-request-next (&optional group server)
593   "Advance the current article pointer."
594   (nntp-possibly-change-server group server)
595   (nntp-send-command "^[23].*\r?\n" "NEXT"))
596
597 (defun nntp-request-post (&optional server)
598   "Post the current buffer."
599   (nntp-possibly-change-server nil server)
600   (when (nntp-send-command "^[23].*\r?\n" "POST")
601     (nntp-encode-text)
602     (nntp-send-region-to-server (point-min) (point-max))
603     ;; 1.2a NNTP's post command is buggy. "^M" (\r) is not
604     ;;  appended to end of the status message.
605     (nntp-wait-for-response "^[23].*\n")))
606
607 ;;; Internal functions.
608
609 (defun nntp-send-mode-reader ()
610   "Send the MODE READER command to the nntp server.
611 This function is supposed to be called from `nntp-server-opened-hook'.
612 It will make innd servers spawn an nnrpd process to allow actual article
613 reading."
614   (nntp-send-command "^.*\r?\n" "MODE READER"))
615
616 (defun nntp-send-authinfo ()
617   "Send the AUTHINFO to the nntp server.
618 This function is supposed to be called from `nntp-server-opened-hook'.
619 It will prompt for a password."
620   (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
621   (nntp-send-command "^.*\r?\n" "AUTHINFO PASS" 
622                      (read-string "NNTP password: ")))
623
624 (defun nntp-send-authinfo-from-file ()
625   "Send the AUTHINFO to the nntp server.
626 This function is supposed to be called from `nntp-server-opened-hook'.
627 It will prompt for a password."
628   (when (file-exists-p "~/.nntp-authinfo")
629     (save-excursion
630       (set-buffer (get-buffer-create " *authinfo*"))
631       (buffer-disable-undo (current-buffer))
632       (erase-buffer)
633       (insert-file-contents "~/.nntp-authinfo")
634       (goto-char (point-min))
635       (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
636       (nntp-send-command 
637        "^.*\r?\n" "AUTHINFO PASS" 
638        (buffer-substring (point) (progn (end-of-line) (point))))
639       (kill-buffer (current-buffer)))))
640
641 (defun nntp-default-sentinel (proc status)
642   "Default sentinel function for NNTP server process."
643   (let ((servers nntp-server-alist)
644         server)
645     ;; Go through the alist of server names and find the name of the
646     ;; server that the process that sent the signal is connected to.
647     ;; If you get my drift.
648     (if (equal proc nntp-server-process)
649         (setq server nntp-address)
650       (while (and servers 
651                   (not (equal proc (nth 1 (assq 'nntp-server-process
652                                                 (car servers))))))
653         (setq servers (cdr servers)))
654       (setq server (car (car servers))))
655     (when (and server
656                nntp-warn-about-losing-connection)
657       (message "nntp: Connection closed to server %s" server)
658       (ding))))
659
660 (defun nntp-kill-connection (server)
661   "Choke the connection to SERVER."
662   (let ((proc (nth 1 (assq 'nntp-server-process 
663                            (assoc server nntp-server-alist)))))
664     (when proc 
665       (delete-process (process-name proc)))
666     (nntp-close-server server)
667     (setq nntp-status-string 
668           (message "Connection timed out to server %s." server))
669     (ding)
670     (sit-for 1)))
671
672 ;; Encoding and decoding of NNTP text.
673
674 (defun nntp-decode-text ()
675   "Decode text transmitted by NNTP.
676 0. Delete status line.
677 1. Delete `^M' at end of line.
678 2. Delete `.' at end of buffer (end of text mark).
679 3. Delete `.' at beginning of line."
680   (save-excursion
681     (set-buffer nntp-server-buffer)
682     ;; Insert newline at end of buffer.
683     (goto-char (point-max))
684     (or (bolp) (insert "\n"))
685     ;; Delete status line.
686     (delete-region (goto-char (point-min)) (progn (forward-line 1) (point)))
687     ;; Delete `^M's.
688     (while (search-forward "\r" nil t)
689       (replace-match "" t t))
690     ;; Delete `.' at end of the buffer (end of text mark).
691     (goto-char (point-max))
692     (forward-line -1)
693     (when (looking-at "^\\.\n")
694       (delete-region (point) (progn (forward-line 1) (point))))
695     ;; Replace `..' at beginning of line with `.'.
696     (goto-char (point-min))
697     ;; (replace-regexp "^\\.\\." ".")
698     (while (search-forward "\n.." nil t)
699       (delete-char -1))))
700
701 (defun nntp-encode-text ()
702   "Encode text in current buffer for NNTP transmission.
703 1. Insert `.' at beginning of line.
704 2. Insert `.' at end of buffer (end of text mark)."
705   (save-excursion
706     ;; Replace `.' at beginning of line with `..'.
707     (goto-char (point-min))
708     (while (search-forward "\n." nil t)
709       (insert "."))
710     (goto-char (point-max))
711     ;; Insert newline at end of buffer.
712     (or (bolp) (insert "\n"))
713     ;; Insert `.' at end of buffer (end of text mark).
714     (insert ".\r\n")))
715
716 \f
717 ;;;
718 ;;; Synchronous Communication with NNTP servers.
719 ;;;
720
721 (defun nntp-send-command (response cmd &rest args)
722   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
723   (save-excursion
724     ;; Clear communication buffer.
725     (set-buffer nntp-server-buffer)
726     (erase-buffer)
727     (apply 'nntp-send-strings-to-server cmd args)
728     (if response
729         (nntp-wait-for-response response)
730       t)))
731
732 (defun nntp-wait-for-response (regexp &optional slow)
733   "Wait for server response which matches REGEXP."
734   (save-excursion
735     (let ((status t)
736           (wait t)
737           (dotnum 0)                    ;Number of "." being displayed.
738           (dotsize                      ;How often "." displayed.
739            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
740       (set-buffer nntp-server-buffer)
741       ;; Wait for status response (RFC977).
742       ;; 1xx - Informative message.
743       ;; 2xx - Command ok.
744       ;; 3xx - Command ok so far, send the rest of it.
745       ;; 4xx - Command was correct, but couldn't be performed for some
746       ;;       reason.
747       ;; 5xx - Command unimplemented, or incorrect, or a serious
748       ;;       program error occurred.
749       (nntp-accept-response)
750       (while wait
751         (goto-char (point-min))
752         (if slow
753             (progn
754               (cond ((re-search-forward "^[23][0-9][0-9]" nil t)
755                      (setq wait nil))
756                     ((re-search-forward "^[45][0-9][0-9]" nil t)
757                      (setq status nil)
758                      (setq wait nil))
759                     (t (nntp-accept-response)))
760               (if (not wait) (delete-region (point-min) 
761                                             (progn (beginning-of-line)
762                                                    (point)))))
763           (cond ((looking-at "[23]")
764                  (setq wait nil))
765                 ((looking-at "[45]")
766                  (setq status nil)
767                  (setq wait nil))
768                 (t (nntp-accept-response)))))
769       ;; Save status message.
770       (end-of-line)
771       (setq nntp-status-string
772             (buffer-substring (point-min) (point)))
773       (when status
774         (setq wait t)
775         (while wait
776           (goto-char (point-max))
777           (forward-line -1)
778           (if (looking-at regexp)
779               (setq wait nil)
780             (when nntp-debug-read
781               (let ((newnum (/ (buffer-size) dotsize)))
782                 (if (not (= dotnum newnum))
783                     (progn
784                       (setq dotnum newnum)
785                       (message "NNTP: Reading %s"
786                                (make-string dotnum ?.))))))
787             (nntp-accept-response)))
788         ;; Remove "...".
789         (when (and nntp-debug-read (> dotnum 0))
790           (message ""))
791         ;; Successfully received server response.
792         t))))
793
794 \f
795
796 ;;;
797 ;;; Low-Level Interface to NNTP Server.
798 ;;; 
799
800 (defun nntp-find-group-and-number ()
801   (save-excursion
802     (save-restriction
803       (set-buffer nntp-server-buffer)
804       (narrow-to-region (goto-char (point-min))
805                         (or (search-forward "\n\n" nil t) (point-max)))
806       (goto-char (point-min))
807       ;; We first find the number by looking at the status line.
808       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
809                          (string-to-int
810                           (buffer-substring (match-beginning 1)
811                                             (match-end 1)))))
812             group newsgroups xref)
813         (and number (zerop number) (setq number nil))
814         ;; Then we find the group name.
815         (setq group
816               (cond 
817                ;; If there is only one group in the Newsgroups header,
818                ;; then it seems quite likely that this article comes
819                ;; from that group, I'd say.
820                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
821                      (not (string-match "," newsgroups)))
822                 newsgroups)
823                ;; If there is more than one group in the Newsgroups
824                ;; header, then the Xref header should be filled out.
825                ;; We hazard a guess that the group that has this
826                ;; article number in the Xref header is the one we are
827                ;; looking for.  This might very well be wrong if this
828                ;; article happens to have the same number in several
829                ;; groups, but that's life. 
830                ((and (setq xref (mail-fetch-field "xref"))
831                      number
832                      (string-match (format "\\([^ :]+\\):%d" number) xref))
833                 (substring xref (match-beginning 1) (match-end 1)))
834                (t "")))
835         (when (string-match "\r" group) 
836           (setq group (substring group 0 (match-beginning 0))))
837         (cons group number)))))
838
839 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
840   (erase-buffer)
841   (cond 
842
843    ;; This server does not talk NOV.
844    ((not nntp-server-xover)
845     nil)
846
847    ;; We don't care about gaps.
848    ((or (not nntp-nov-gap)
849         fetch-old)
850     (nntp-send-xover-command 
851      (if fetch-old
852          (if (numberp fetch-old) 
853              (max 1 (- (car articles) fetch-old)) 
854            1)
855        (car articles))
856      (nntp-last-element articles) 'wait)
857
858     (goto-char (point-min))
859     (when (looking-at "[1-5][0-9][0-9] ")
860       (delete-region (point) (progn (forward-line 1) (point))))
861     (while (search-forward "\r" nil t)
862       (replace-match "" t t))
863     (goto-char (point-max))
864     (forward-line -1)
865     (when (looking-at "\\.")
866       (delete-region (point) (progn (forward-line 1) (point)))))
867
868    ;; We do it the hard way.  For each gap, an XOVER command is sent
869    ;; to the server.  We do not wait for a reply from the server, we
870    ;; just send them off as fast as we can.  That means that we have
871    ;; to count the number of responses we get back to find out when we
872    ;; have gotten all we asked for.
873    ((numberp nntp-nov-gap)
874     (let ((count 0)
875           (received 0)
876           (last-point (point-min))
877           (buf (current-buffer))
878           first)
879       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
880       ;; that means that the server does not understand XOVER, but we
881       ;; won't know that until we try.
882       (while (and nntp-server-xover articles)
883         (setq first (car articles))
884         ;; Search forward until we find a gap, or until we run out of
885         ;; articles. 
886         (while (and (cdr articles) 
887                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
888           (setq articles (cdr articles)))
889
890         (when (nntp-send-xover-command first (car articles))
891           (setq articles (cdr articles)
892                 count (1+ count))
893
894           ;; Every 400 requests we have to read the stream in
895           ;; order to avoid deadlocks.
896           (when (or (null articles)     ;All requests have been sent.
897                     (zerop (% count nntp-maximum-request)))
898             (accept-process-output)
899             ;; On some Emacs versions the preceding function has
900             ;; a tendency to change the buffer. Perhaps. It's
901             ;; quite difficult to reporduce, because it only
902             ;; seems to happen once in a blue moon. 
903             (set-buffer buf) 
904             (while (progn
905                      (goto-char last-point)
906                      ;; Count replies.
907                      (while (re-search-forward "^[0-9][0-9][0-9] " nil t)
908                        (setq received (1+ received)))
909                      (setq last-point (point))
910                      (< received count))
911               (accept-process-output)
912               (set-buffer buf)))))
913
914       (when nntp-server-xover
915         ;; Wait for the reply from the final command.
916         (goto-char (point-max))
917         (re-search-backward "^[0-9][0-9][0-9] " nil t)
918         (when (looking-at "^[23]")
919           (while (progn
920                    (goto-char (point-max))
921                    (forward-line -1)
922                    (not (looking-at "^\\.\r?\n")))
923             (nntp-accept-response)))
924         
925         ;; We remove any "." lines and status lines.
926         (goto-char (point-min))
927         (while (search-forward "\r" nil t)
928           (delete-char -1))
929         (goto-char (point-min))
930         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")))))
931
932   nntp-server-xover)
933
934 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
935   "Send the XOVER command to the server."
936   (let ((range (format "%d-%d" beg end)))
937     (if (stringp nntp-server-xover)
938         ;; If `nntp-server-xover' is a string, then we just send this
939         ;; command.
940         (if wait-for-reply
941             (nntp-send-command "^\\.\r?\n" nntp-server-xover range)
942           ;; We do not wait for the reply.
943           (nntp-send-strings-to-server nntp-server-xover range))
944       (let ((commands nntp-xover-commands))
945         ;; `nntp-xover-commands' is a list of possible XOVER commands.
946         ;; We try them all until we get at positive response. 
947         (while (and commands (eq nntp-server-xover 'try))
948           (nntp-send-command "^\\.\r?\n" (car commands) range)
949           (save-excursion
950             (set-buffer nntp-server-buffer)
951             (goto-char (point-min))
952             (and (looking-at "[23]") ; No error message.
953                  ;; We also have to look at the lines.  Some buggy
954                  ;; servers give back simple lines with just the
955                  ;; article number.  How... helpful.
956                  (progn
957                    (forward-line 1)
958                    (looking-at "[0-9]+\t...")) ; More text after number.
959                  (setq nntp-server-xover (car commands))))
960           (setq commands (cdr commands)))
961         ;; If none of the commands worked, we disable XOVER.
962         (when (eq nntp-server-xover 'try)
963           (save-excursion
964             (set-buffer nntp-server-buffer)
965             (erase-buffer)
966             (setq nntp-server-xover nil)))
967         nntp-server-xover))))
968
969 (defun nntp-send-strings-to-server (&rest strings)
970   "Send STRINGS to the server."
971   (let ((cmd (concat (mapconcat 'identity strings " ") "\r\n")))
972     ;; We open the nntp server if it is down.
973     (or (nntp-server-opened nntp-current-server)
974         (nntp-open-server nntp-current-server)
975         (error (nntp-status-message)))
976     ;; Send the strings.
977     (process-send-string nntp-server-process cmd)
978     t))
979
980 (defun nntp-send-region-to-server (begin end)
981   "Send the current buffer region (from BEGIN to END) to the server."
982   (save-excursion
983     ;; If we're not the the nntp server buffer, we copy the region
984     ;; over to that buffer.  
985     (if (eq (get-buffer nntp-server-buffer) (current-buffer))
986         (let ((orig (current-buffer)))
987           (set-buffer nntp-server-buffer)
988           (erase-buffer)
989           (insert-buffer-substring orig begin end))
990       ;; We are in the nntp buffer, so we just narrow it.
991       (narrow-to-region begin end))
992     ;; `process-send-region' does not work if the text to be sent is very
993     ;; large, so we send it piecemeal.
994     (let ((last (point-min))
995           (size 100))                   ;Size of text sent at once.
996       (while (/= last (point-max))
997         (process-send-region 
998          nntp-server-process last (setq last (min (+ last size) (point-max))))
999         ;; Read any output from the server.  May be unnecessary.
1000         (accept-process-output)))
1001     ;; Delete the area we sent.
1002     (delete-region (point-min) (point-max))
1003     (widen)))
1004
1005 (defun nntp-open-server-semi-internal (server &optional service)
1006   "Open SERVER.
1007 If SERVER is nil, use value of environment variable `NNTPSERVER'.
1008 If SERVICE, this this as the port number."
1009   (let ((server (or server (getenv "NNTPSERVER")))
1010         (status nil)
1011         (timer 
1012          (and nntp-connection-timeout 
1013               (cond
1014                ((fboundp 'run-at-time)
1015                 (run-at-time nntp-connection-timeout
1016                              nil 'nntp-kill-connection server))
1017                ((fboundp 'start-itimer)
1018                 ;; Not sure if this will work or not, only one way to
1019                 ;; find out
1020                 (eval '(start-itimer "nntp-timeout"
1021                                      (lambda ()
1022                                        (nntp-kill-connection server))
1023                                      nntp-connection-timeout nil)))))))
1024     (save-excursion
1025       (set-buffer nntp-server-buffer)
1026       (setq nntp-status-string "")
1027       (message "nntp: Connecting to server on %s..." server)
1028       (cond ((and server (nntp-open-server-internal server service))
1029              (setq nntp-address server)
1030              (setq status
1031                    (condition-case nil
1032                        (nntp-wait-for-response "^[23].*\r?\n" 'slow)
1033                      (error nil)
1034                      (quit nil)))
1035              (or status (nntp-close-server-internal server))
1036              (and nntp-server-process
1037                   (progn
1038                     (set-process-sentinel 
1039                      nntp-server-process 'nntp-default-sentinel)
1040                     ;; You can send commands at startup like AUTHINFO here.
1041                     ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
1042                     (run-hooks 'nntp-server-opened-hook))))
1043             ((null server)
1044              (setq nntp-status-string "NNTP server is not specified."))
1045             (t                          ; We couldn't open the server.
1046              (setq nntp-status-string 
1047                    (buffer-substring (point-min) (point-max)))))
1048       (and timer (cancel-timer timer))
1049       (message "")
1050       (or status
1051           (setq nntp-current-server nil
1052                 nntp-async-number nil))
1053       status)))
1054
1055 (defun nntp-open-server-internal (server &optional service)
1056   "Open connection to news server on SERVER by SERVICE (default is nntp)."
1057   (let (proc)
1058     (save-excursion
1059       ;; Use TCP/IP stream emulation package if needed.
1060       (or (fboundp 'open-network-stream)
1061           (require 'tcp))
1062       ;; Initialize communication buffer.
1063       (nnheader-init-server-buffer)
1064       (set-buffer nntp-server-buffer)
1065       (if (setq proc
1066                 (condition-case nil
1067                     (funcall nntp-open-server-function server)
1068                   (error nil)))
1069           (progn
1070             (setq nntp-server-process proc)
1071             ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
1072             (process-kill-without-query proc)
1073             (setq nntp-address server)
1074             ;; It is possible to change kanji-fileio-code in this hook.
1075             (run-hooks 'nntp-server-hook)
1076             (push proc nntp-opened-connections)
1077             nntp-server-process)
1078         (setq nntp-status-string (format "Couldn't open server %s" server))
1079         nil))))
1080
1081 (defun nntp-open-network-stream (server)
1082   (open-network-stream 
1083    "nntpd" nntp-server-buffer server nntp-port-number))
1084
1085 (defun nntp-open-rlogin (server)
1086   (let ((proc (start-process "nntpd" nntp-server-buffer "rsh" server)))
1087     (process-send-string proc (mapconcat 'identity nntp-rlogin-parameters
1088                                          " "))
1089     (process-send-string proc "\n")))
1090
1091 (defun nntp-telnet-to-machine ()
1092   (let (b)
1093     (telnet "localhost")
1094     (goto-char (point-min))
1095     (while (not (re-search-forward "^login: *" nil t))
1096       (sit-for 1)
1097       (goto-char (point-min)))
1098     (goto-char (point-max))
1099     (insert "larsi")
1100     (telnet-send-input)
1101     (setq b (point))
1102     (while (not (re-search-forward ">" nil t))
1103       (sit-for 1)
1104       (goto-char b))
1105     (goto-char (point-max))
1106     (insert "ls")
1107     (telnet-send-input)))
1108
1109 (defun nntp-close-server-internal (&optional server)
1110   "Close connection to news server."
1111   (nntp-possibly-change-server nil server)
1112   (if nntp-server-process
1113       (delete-process nntp-server-process))
1114   (setq nntp-server-process nil)
1115   (setq nntp-address ""))
1116
1117 (defun nntp-accept-response ()
1118   "Read response of server.
1119 It is well-known that the communication speed will be much improved by
1120 defining this function as macro."
1121   ;; To deal with server process exiting before
1122   ;;  accept-process-output is called.
1123   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
1124   ;; This is a copy of `nntp-default-sentinel'.
1125   (let ((buf (current-buffer)))
1126     (prog1
1127         (if (or (not nntp-server-process)
1128                 (not (memq (process-status nntp-server-process) '(open run))))
1129             (error "nntp: Process connection closed; %s" (nntp-status-message))
1130           (if nntp-buggy-select
1131               (progn
1132                 ;; We cannot use `accept-process-output'.
1133                 ;; Fujitsu UTS requires messages during sleep-for.
1134                 ;; I don't know why.
1135                 (message "NNTP: Reading...")
1136                 (sleep-for 1)
1137                 (message ""))
1138             (condition-case errorcode
1139                 (accept-process-output nntp-server-process)
1140               (error
1141                (cond ((string-equal "select error: Invalid argument" 
1142                                     (nth 1 errorcode))
1143                       ;; Ignore select error.
1144                       nil)
1145                      (t
1146                       (signal (car errorcode) (cdr errorcode))))))))
1147       (set-buffer buf))))
1148
1149 (defun nntp-last-element (list)
1150   "Return last element of LIST."
1151   (while (cdr list)
1152     (setq list (cdr list)))
1153   (car list))
1154
1155 (defun nntp-possibly-change-server (newsgroup server &optional connectionless)
1156   "Check whether the virtual server needs changing."
1157   (if (and server
1158            (not (nntp-server-opened server)))
1159       ;; This virtual server isn't open, so we (re)open it here.
1160       (nntp-open-server server nil t))
1161   (if (and newsgroup 
1162            (not (equal newsgroup nntp-current-group)))
1163       ;; Set the proper current group.
1164       (nntp-request-group newsgroup server)))
1165  
1166 (defun nntp-try-list-active (group)
1167   (nntp-list-active-group group)
1168   (save-excursion
1169     (set-buffer nntp-server-buffer)
1170     (goto-char (point-min))
1171     (cond ((looking-at "5[0-9]+")
1172            (setq nntp-server-list-active-group nil))
1173           (t
1174            (setq nntp-server-list-active-group t)))))
1175
1176 (defun nntp-async-server-opened ()
1177   (and nntp-async-process
1178        (memq (process-status nntp-async-process) '(open run))))
1179
1180 (defun nntp-async-open-server ()
1181   (save-excursion
1182     (set-buffer (generate-new-buffer " *async-nntp*"))
1183     (setq nntp-async-buffer (current-buffer))
1184     (buffer-disable-undo (current-buffer)))
1185   (let ((nntp-server-process nil)
1186         (nntp-server-buffer nntp-async-buffer))
1187     (nntp-open-server-semi-internal nntp-address nntp-port-number)
1188     (if (not (setq nntp-async-process nntp-server-process))
1189         (progn
1190           (setq nntp-async-number nil))
1191       (set-process-buffer nntp-async-process nntp-async-buffer))))
1192
1193 (defun nntp-async-fetch-articles (article)
1194   (if (stringp article)
1195       ()
1196     (let ((articles (cdr (memq (assq article nntp-async-articles)
1197                                nntp-async-articles)))
1198           (max (cond ((numberp nntp-async-number)
1199                       nntp-async-number) 
1200                      ((eq nntp-async-number t)
1201                       (length nntp-async-articles))
1202                      (t 0)))
1203           nart)
1204       (while (and (>= (setq max (1- max)) 0)
1205                   articles)
1206         (or (memq (setq nart (car (car articles))) nntp-async-fetched)
1207             (progn
1208               (nntp-async-send-strings "ARTICLE " (int-to-string nart))
1209               (setq nntp-async-fetched (cons nart nntp-async-fetched))))
1210         (setq articles (cdr articles))))))
1211
1212 (defun nntp-async-send-strings (&rest strings)
1213   (let ((cmd (concat (mapconcat 'identity strings " ") "\r\n")))
1214     (or (nntp-async-server-opened)
1215         (nntp-async-open-server)
1216         (error (nntp-status-message)))
1217     (process-send-string nntp-async-process cmd)))
1218
1219 (defun nntp-async-request-group (group)
1220   (if (equal group nntp-current-group)
1221       ()
1222     (let ((asyncs (assoc group nntp-async-group-alist)))
1223       ;; A new group has been selected, so we push the current state
1224       ;; of async articles on an alist, and pull the old state off.
1225       (setq nntp-async-group-alist 
1226             (cons (list nntp-current-group
1227                         nntp-async-articles nntp-async-fetched
1228                         nntp-async-process)
1229                   (delq asyncs nntp-async-group-alist)))
1230       (and asyncs
1231            (progn
1232              (setq nntp-async-articles (nth 1 asyncs))
1233              (setq nntp-async-fetched (nth 2 asyncs))
1234              (setq nntp-async-process (nth 3 asyncs)))))))
1235
1236 (provide 'nntp)
1237
1238 ;;; nntp.el ends here