*** empty log message ***
[gnus] / lisp / nntp.el
1 ;;; nntp.el --- NNTP (RFC977) Interface for GNU Emacs
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-and-compile
33   (autoload 'news-setup "rnewspost")
34   (autoload 'news-reply-mode "rnewspost")
35   (autoload 'nnmail-request-post-buffer "nnmail")
36   (autoload 'cancel-timer "timer"))
37
38 (defvar nntp-server-hook nil
39   "*Hooks for the NNTP server.
40 If the kanji code of the NNTP server is different from the local kanji
41 code, the correct kanji code of the buffer associated with the NNTP
42 server must be specified as follows:
43
44 \(setq nntp-server-hook
45       (function
46        (lambda ()
47          ;; Server's Kanji code is EUC (NEmacs hack).
48          (make-local-variable 'kanji-fileio-code)
49          (setq kanji-fileio-code 0))))
50
51 If you'd like to change something depending on the server in this
52 hook, use the variable `nntp-address'.")
53
54 (defvar nntp-server-opened-hook nil
55   "*Hook used for sending commands to the server at startup.  
56 The default value is `nntp-send-mode-reader', whick makes an innd
57 server spawn an nnrpd server.  Another useful function to put in this
58 hook might be `nntp-send-authinfo', which will prompt for a password
59 to allow posting from the server.  Note that this is only necessary to
60 do on servers that use strict access control.")  (add-hook
61 'nntp-server-opened-hook 'nntp-send-mode-reader)
62
63 (defvar nntp-open-server-function 'nntp-open-network-stream
64   "*Function used for connecting to a remote system.
65 It will be called with the address of the remote system.
66
67 Two pre-made functions are `nntp-open-network-stream', which is the
68 default, and simply connects to some port or other on the remote
69 system (see nntp-port-number).  The other is `nntp-open-rlogin', which
70 does an rlogin on the remote system, and then does a telnet to the
71 NNTP server available there (see nntp-rlogin-parameters).")
72
73 (defvar nntp-rlogin-parameters '("telnet" "${NNTPSERVER:=localhost}" "nntp")
74   "*Parameters to `nntp-open-login'.
75 That function may be used as `nntp-open-server-function'.  In that
76 case, this list will be used as the parameter list given to rsh.")
77
78 (defvar nntp-rlogin-user-name nil
79   "*User name on remote system when using the rlogin connect method.")
80
81 (defvar nntp-address nil
82   "*The name of the NNTP server.")
83
84 (defvar nntp-port-number "nntp"
85   "*Port number to connect to.")
86
87 (defvar nntp-large-newsgroup 50
88   "*The number of the articles which indicates a large newsgroup.
89 If the number of the articles is greater than the value, verbose
90 messages will be shown to indicate the current status.")
91
92 (defvar nntp-buggy-select (memq system-type '(fujitsu-uts))
93   "*t if your select routine is buggy.
94 If the select routine signals error or fall into infinite loop while
95 waiting for the server response, the variable must be set to t.  In
96 case of Fujitsu UTS, it is set to T since `accept-process-output'
97 doesn't work properly.")
98
99 (defvar nntp-maximum-request 400
100   "*The maximum number of the requests sent to the NNTP server at one time.
101 If Emacs hangs up while retrieving headers, set the variable to a
102 lower value.")
103
104 (defvar nntp-debug-read 10000
105   "*Display '...' every 10Kbytes of a message being received if it is non-nil.
106 If it is a number, dots are displayed per the number.")
107
108 (defvar nntp-nov-is-evil nil
109   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
110
111 (defvar nntp-xover-commands '("XOVER" "XOVERVIEW")
112   "*List of strings that are used as commands to fetch NOV lines from a server.
113 The strings are tried in turn until a positive response is gotten. If
114 none of the commands are successful, nntp will just grab headers one
115 by one.")
116
117 (defvar nntp-connection-timeout nil
118   "*Number of seconds to wait before an nntp connection times out.
119 If this variable is nil, which is the default, no timers are set.")
120
121 (defvar nntp-news-default-headers nil
122   "*If non-nil, override `mail-default-headers' when posting news.")
123
124 (defvar nntp-prepare-server-hook nil
125   "*Hook run before a server is opened.
126 If can be used to set up a server remotely, for instance.  Say you
127 have an account at the machine \"other.machine\".  This machine has
128 access to an NNTP server that you can't access locally.  You could
129 then use this hook to rsh to the remote machine and start a proxy NNTP
130 server there that you can connect to.")
131
132 (defvar nntp-async-number 5
133   "*How many articles should be prefetched when in asynchronous mode.")
134
135
136 \f
137
138 (defconst nntp-version "nntp 4.0"
139   "Version numbers of this version of NNTP.")
140
141 (defvar nntp-server-buffer nil
142   "Buffer associated with the NNTP server process.")
143
144 (defvar nntp-server-process nil
145   "The NNTP server process.
146 You'd better not use this variable in NNTP front-end program, but
147 instead use `nntp-server-buffer'.")
148
149 (defvar nntp-status-string nil
150   "Save the server response message.
151 You'd better not use this variable in NNTP front-end program but
152 instead call function `nntp-status-message' to get status message.")
153
154 (defvar nntp-server-xover 'try)
155 (defvar nntp-server-list-active-group 'try)
156 (defvar nntp-current-group "")
157 (defvar nntp-timeout-servers nil)
158
159 (defvar nntp-async-process nil)
160 (defvar nntp-async-buffer nil)
161 (defvar nntp-async-articles nil)
162 (defvar nntp-async-fetched nil)
163
164 \f
165 (defvar nntp-current-server nil)
166 (defvar nntp-server-alist nil)
167 (defvar nntp-server-variables 
168   (list
169    (list 'nntp-server-hook nntp-server-hook)
170    (list 'nntp-server-opened-hook nntp-server-opened-hook)
171    (list 'nntp-port-number nntp-port-number)
172    (list 'nntp-address nntp-address)
173    (list 'nntp-large-newsgroup nntp-large-newsgroup)
174    (list 'nntp-buggy-select nntp-buggy-select)
175    (list 'nntp-maximum-request nntp-maximum-request)
176    (list 'nntp-debug-read nntp-debug-read)
177    (list 'nntp-nov-is-evil nntp-nov-is-evil)
178    (list 'nntp-xover-commands nntp-xover-commands)
179    (list 'nntp-connection-timeout nntp-connection-timeout)
180    (list 'nntp-news-default-headers nntp-news-default-headers)
181    (list 'nntp-prepare-server-hook nntp-prepare-server-hook) 
182    '(nntp-async-process nil)
183    '(nntp-async-buffer nil)
184    '(nntp-async-articles nil)
185    '(nntp-async-fetched nil)
186    '(nntp-server-process nil)
187    '(nntp-status-string nil)
188    '(nntp-server-xover try)
189    '(nntp-server-list-active-group try)
190    '(nntp-timeout-servers nil)
191    '(nntp-current-group "")))
192
193 \f
194 ;;; Interface funtions.
195
196 (defun nntp-retrieve-headers (sequence &optional newsgroup server)
197   "Retrieve the headers to the articles in SEQUENCE."
198   (nntp-possibly-change-server newsgroup server)
199   (save-excursion
200     (set-buffer nntp-server-buffer)
201     (erase-buffer)
202     (if (and (not gnus-nov-is-evil) 
203              (not nntp-nov-is-evil)
204              (nntp-retrieve-headers-with-xover sequence))
205         'nov
206       (let ((number (length sequence))
207             (count 0)
208             (received 0)
209             (last-point (point-min)))
210         ;; Send HEAD command.
211         (while sequence
212           (nntp-send-strings-to-server 
213            "HEAD" (if (numberp (car sequence)) (int-to-string (car sequence))
214                     (car sequence)))
215           (setq sequence (cdr sequence)
216                 count (1+ count))
217           ;; Every 400 header requests we have to read stream in order
218           ;;  to avoid deadlock.
219           (if (or (null sequence)       ;All requests have been sent.
220                   (zerop (% count nntp-maximum-request)))
221               (progn
222                 (accept-process-output)
223                 (while (progn
224                          (goto-char last-point)
225                          ;; Count replies.
226                          (while (re-search-forward "^[0-9]" nil t)
227                            (setq received (1+ received)))
228                          (setq last-point (point))
229                          (< received count))
230                   ;; If number of headers is greater than 100, give
231                   ;;  informative messages.
232                   (and (numberp nntp-large-newsgroup)
233                        (> number nntp-large-newsgroup)
234                        (zerop (% received 20))
235                        (message "NNTP: Receiving headers... %d%%"
236                                 (/ (* received 100) number)))
237                   (nntp-accept-response)))))
238         ;; Wait for text of last command.
239         (goto-char (point-max))
240         (re-search-backward "^[0-9]" nil t)
241         (if (looking-at "^[23]")
242             (while (progn
243                      (goto-char (- (point-max) 3))
244                      (not (looking-at "^\\.\r$")))
245               (nntp-accept-response)))
246         (and (numberp nntp-large-newsgroup)
247              (> number nntp-large-newsgroup)
248              (message "NNTP: Receiving headers... done"))
249
250         ;; Now all of replies are received.
251         (setq received number)
252         ;; First, fold continuation lines.
253         (goto-char (point-min))
254         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
255           (replace-match " "))
256         ;; Remove all "\r"'s
257         (goto-char (point-min))
258         (while (search-forward "\r" nil t)
259           (replace-match ""))
260         'headers))))
261
262
263 (defun nntp-retrieve-groups (groups &optional server)
264   (nntp-possibly-change-server nil server)
265   (save-excursion
266     (set-buffer nntp-server-buffer)
267     (and (eq nntp-server-list-active-group 'try)
268          (nntp-try-list-active (car groups)))
269     (erase-buffer)
270     (let ((count 0)
271           (received 0)
272           (last-point (point-min))
273           (command (if nntp-server-list-active-group
274                        "LIST ACTIVE" "GROUP")))
275         (while groups
276           (nntp-send-strings-to-server command (car groups))
277           (setq groups (cdr groups))
278           (setq count (1+ count))
279           ;; Every 400 requests we have to read the stream in
280           ;; order to avoid deadlocks.
281           (if (or (null groups)       ;All requests have been sent.
282                   (zerop (% count nntp-maximum-request)))
283               (progn
284                 (accept-process-output)
285                 (while (progn
286                          (goto-char last-point)
287                          ;; Count replies.
288                          (while (re-search-forward "^[0-9]" nil t)
289                            (setq received (1+ received)))
290                          (setq last-point (point))
291                          (< received count))
292                   (nntp-accept-response)))))
293
294         ;; Wait for the reply from the final command.
295         (if nntp-server-list-active-group
296             (progn
297               (goto-char (point-max))
298               (re-search-backward "^[0-9]" nil t)
299               (if (looking-at "^[23]")
300                   (while (progn
301                            (goto-char (- (point-max) 3))
302                            (not (looking-at "^\\.\r$")))
303                     (nntp-accept-response)))))
304
305         ;; Now all replies are received. We remove CRs.
306         (goto-char (point-min))
307         (while (search-forward "\r" nil t)
308           (replace-match ""))
309
310         (if nntp-server-list-active-group
311             (progn
312               ;; We have read active entries, so we just delete the
313               ;; superfluos gunk.
314               (goto-char (point-min))
315               (while (re-search-forward "^[\\.234]" nil t)
316                 (delete-region (match-beginning 0) 
317                                (progn (forward-line 1) (point))))
318               'active)
319           'group))))
320
321 (defun nntp-open-server (server &optional defs)
322   (nnheader-init-server-buffer)
323   (if (nntp-server-opened server)
324       t
325     (if (or (stringp (car defs))
326             (numberp (car defs)))
327         (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
328     (or (assq 'nntp-address defs)
329         (setq defs (append defs (list (list 'nntp-address server)))))
330     (if (and nntp-current-server
331              (not (equal server nntp-current-server)))
332         (setq nntp-server-alist 
333               (cons (list nntp-current-server
334                           (nnheader-save-variables nntp-server-variables))
335                     nntp-server-alist)))
336     (let ((state (assoc server nntp-server-alist)))
337       (if state 
338           (progn
339             (nnheader-restore-variables (nth 1 state))
340             (setq nntp-server-alist (delq state nntp-server-alist)))
341         (nnheader-set-init-variables nntp-server-variables defs)))
342     (setq nntp-current-server server)
343     (or (nntp-server-opened server)
344         (progn
345           (if (member server nntp-timeout-servers)
346               nil
347             (run-hooks 'nntp-prepare-server-hook)
348             (nntp-open-server-semi-internal nntp-address))))))
349
350 (defun nntp-close-server (&optional server)
351   "Close connection to SERVER."
352   (nntp-possibly-change-server nil server)
353   (unwind-protect
354       (progn
355         ;; Un-set default sentinel function before closing connection.
356         (and nntp-server-process
357              (eq 'nntp-default-sentinel
358                  (process-sentinel nntp-server-process))
359              (set-process-sentinel nntp-server-process nil))
360         ;; We cannot send QUIT command unless the process is running.
361         (if (nntp-server-opened)
362             (nntp-send-command nil "QUIT")))
363     (nntp-close-server-internal server)))
364
365 (fset 'nntp-request-quit (symbol-function 'nntp-close-server))
366
367 (defun nntp-request-close ()
368   "Close all server connections."
369   (let (proc)
370     (and nntp-async-process
371          (progn
372            (delete-process nntp-async-process)
373            (and (get-buffer nntp-async-buffer)
374                 (kill-buffer nntp-async-buffer))))
375     (while nntp-server-alist
376       (and 
377        (setq proc (nth 1 (assq 'nntp-server-process (car nntp-server-alist))))
378        (delete-process proc))
379       (and 
380        (setq proc (nth 1 (assq 'nntp-async-process (car nntp-server-alist))))
381        (delete-process proc))
382       (and (setq proc (nth 1 (assq 'nntp-async-buffer
383                                    (car nntp-server-alist))))
384            (buffer-name proc)
385            (kill-buffer proc))
386       (setq nntp-server-alist (cdr nntp-server-alist)))
387     (setq nntp-current-server nil)))
388
389 (defun nntp-server-opened (&optional server)
390   "Say whether a connection to SERVER has been opened."
391   (and (equal server nntp-current-server)
392        nntp-server-buffer
393        (buffer-name nntp-server-buffer)
394        nntp-server-process
395        (memq (process-status nntp-server-process) '(open run))))
396
397 (defun nntp-status-message (&optional server)
398   "Return server status as a string."
399   (if (and nntp-status-string
400            ;; NNN MESSAGE
401            (string-match "[0-9][0-9][0-9][ \t]+\\([^\r]*\\).*$"
402                          nntp-status-string))
403       (substring nntp-status-string (match-beginning 1) (match-end 1))
404     ;; Empty message if nothing.
405     nntp-status-string))
406
407 (defun nntp-request-article (id &optional newsgroup server buffer)
408   "Request article ID (message-id or number)."
409   (nntp-possibly-change-server newsgroup server)
410
411   (let (found)
412
413     ;; First we see whether we can get the article from the async buffer. 
414     (if (and (numberp id)
415              nntp-async-articles
416              (memq id nntp-async-fetched))
417         (save-excursion
418           (set-buffer nntp-async-buffer)
419           (let ((opoint (point))
420                 beg end)
421             (if (and (or (re-search-forward (concat "^2?? +" id) nil t)
422                          (progn
423                            (goto-char (point-min))
424                            (re-search-forward (concat "^2?? +" id) opoint t)))
425                      (progn
426                        (beginning-of-line)
427                        (setq beg (point)
428                              end (re-search-forward "^\\.\r?\n" nil t))))
429                 (progn
430                   (setq found t)
431                   (save-excursion
432                     (set-buffer (or buffer nntp-server-buffer))
433                     (erase-buffer)
434                     (insert-buffer-substring nntp-async-buffer beg end)
435                     (let ((nntp-server-buffer (current-buffer)))
436                       (nntp-decode-text)))
437                   (delete-region beg end)
438                   (and nntp-async-articles
439                        (nntp-async-fetch-articles id)))))))
440
441     (if found 
442         t
443       ;; The article was not in the async buffer, so we fetch it now.
444       (unwind-protect
445           (progn
446             (if buffer (set-process-buffer nntp-server-process buffer))
447             (let ((nntp-server-buffer (or buffer nntp-server-buffer))
448                   (art (or (and (numberp id) (int-to-string id)) id)))
449               ;; If NEmacs, end of message may look like: "\256\215" (".^M")
450               (prog1
451                   (nntp-send-command "^\\.\r$" "ARTICLE" art)
452                 (nntp-decode-text)
453                 (and nntp-async-articles (nntp-async-fetch-articles id)))))
454         (if buffer (set-process-buffer 
455                     nntp-server-process nntp-server-buffer))))))
456
457 (defun nntp-request-body (id &optional newsgroup server)
458   "Request body of article ID (message-id or number)."
459   (nntp-possibly-change-server newsgroup server)
460   (prog1
461       ;; If NEmacs, end of message may look like: "\256\215" (".^M")
462       (nntp-send-command
463        "^\\.\r$" "BODY" (or (and (numberp id) (int-to-string id)) id))
464     (nntp-decode-text)))
465
466 (defun nntp-request-head (id &optional newsgroup server)
467   "Request head of article ID (message-id or number)."
468   (nntp-possibly-change-server newsgroup server)
469   (prog1
470       (nntp-send-command 
471        "^\\.\r$" "HEAD" (or (and (numberp id) (int-to-string id)) id))
472     (nntp-decode-text)))
473
474 (defun nntp-request-stat (id &optional newsgroup server)
475   "Request STAT of article ID (message-id or number)."
476   (nntp-possibly-change-server newsgroup server)
477   (nntp-send-command 
478    "^[23].*\r$" "STAT" (or (and (numberp id) (int-to-string id)) id)))
479
480 (defun nntp-request-group (group &optional server dont-check)
481   "Select GROUP."
482   (nntp-send-command "^.*\r$" "GROUP" group)
483   (save-excursion
484     (set-buffer nntp-server-buffer)
485     (goto-char (point-min))
486     (looking-at "[23]")))
487
488 (defun nntp-request-asynchronous (group &optional server articles)
489   (or (nntp-async-server-opened)
490       (nntp-async-open-server)
491       (error "Can't open second connection to %s" nntp-address))
492   (setq nntp-async-articles articles)
493   (setq nntp-async-fetched nil)
494   (save-excursion
495     (set-buffer nntp-async-buffer)
496     (erase-buffer))
497   (nntp-async-send-strings "GROUP" group)
498   t)
499
500 (defun nntp-list-active-group (group &optional server)
501   (nntp-send-command "^.*\r$" "LIST ACTIVE" group))
502
503 (defun nntp-request-group-description (group &optional server)
504   "Get description of GROUP."
505   (if (nntp-possibly-change-server nil server)
506       (prog1
507           (nntp-send-command "^.*\r$" "XGTITLE" group)
508         (nntp-decode-text))))
509
510 (defun nntp-close-group (group &optional server)
511   t)
512
513 (defun nntp-request-list (&optional server)
514   "List active groups."
515   (nntp-possibly-change-server nil server)
516   (prog1
517       (nntp-send-command "^\\.\r$" "LIST")
518     (nntp-decode-text)))
519
520 (defun nntp-request-list-newsgroups (&optional server)
521   "List groups."
522   (nntp-possibly-change-server nil server)
523   (prog1
524       (nntp-send-command "^\\.\r$" "LIST NEWSGROUPS")
525     (nntp-decode-text)))
526
527 (defun nntp-request-newgroups (date &optional server)
528   "List new groups."
529   (nntp-possibly-change-server nil server)
530   (let* ((date (timezone-parse-date date))
531          (time-string
532           (format "%s%02d%02d %s%s%s"
533                   (substring (aref date 0) 2) (string-to-int (aref date 1)) 
534                   (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
535                   (substring 
536                    (aref date 3) 3 5) (substring (aref date 3) 6 8))))
537     (prog1
538         (nntp-send-command "^\\.\r$" "NEWGROUPS" time-string)
539       (nntp-decode-text))))
540
541 (defun nntp-request-list-distributions (&optional server)
542   "List distributions."
543   (nntp-possibly-change-server nil server)
544   (prog1
545       (nntp-send-command "^\\.\r$" "LIST DISTRIBUTIONS")
546     (nntp-decode-text)))
547
548 (defun nntp-request-last (&optional newsgroup server)
549   "Decrease the current article pointer."
550   (nntp-possibly-change-server newsgroup server)
551   (nntp-send-command "^[23].*\r$" "LAST"))
552
553 (defun nntp-request-next (&optional newsgroup server)
554   "Advance the current article pointer."
555   (nntp-possibly-change-server newsgroup server)
556   (nntp-send-command "^[23].*\r$" "NEXT"))
557
558 (defun nntp-request-post (&optional server)
559   "Post the current buffer."
560   (nntp-possibly-change-server nil server)
561   (if (nntp-send-command "^[23].*\r$" "POST")
562       (progn
563         (nntp-encode-text)
564         (nntp-send-region-to-server (point-min) (point-max))
565         ;; 1.2a NNTP's post command is buggy. "^M" (\r) is not
566         ;;  appended to end of the status message.
567         (nntp-wait-for-response "^[23].*$"))))
568
569 (defun nntp-request-post-buffer 
570   (post group subject header article-buffer info follow-to respect-poster)
571   "Request a buffer suitable for composing an article.
572 If POST, this is an original article; otherwise it's a followup.
573 GROUP is the group to be posted to, the article should have subject
574 SUBJECT.  HEADER is a Gnus header vector.  ARTICLE-BUFFER contains the
575 article being followed up.  INFO is a Gnus info list.  If FOLLOW-TO,
576 post to this group instead.  If RESPECT-POSTER, heed the special
577 \"poster\" value of the Followup-to header."
578   (if (assq 'to-address (nth 5 info))
579       (nnmail-request-post-buffer 
580        post group subject header article-buffer info follow-to respect-poster)
581     (let ((mail-default-headers 
582            (or nntp-news-default-headers mail-default-headers))
583           from date to followup-to newsgroups message-of
584           references distribution message-id)
585       (save-excursion
586         (set-buffer (get-buffer-create "*post-news*"))
587         (news-reply-mode)
588         (if (and (buffer-modified-p)
589                  (> (buffer-size) 0)
590                  (not (y-or-n-p "Unsent article being composed; erase it? ")))
591             ()
592           (erase-buffer)
593           (if post
594               (news-setup nil subject nil group nil)
595             (save-excursion
596               (set-buffer article-buffer)
597               (goto-char (point-min))
598               (narrow-to-region (point-min)
599                                 (progn (search-forward "\n\n") (point)))
600               (setq from (header-from header))
601               (setq date (header-date header))
602               (and from
603                    (let ((stop-pos 
604                           (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
605                      (setq 
606                       message-of
607                       (concat (if stop-pos (substring from 0 stop-pos) from) 
608                               "'s message of " date))))
609               (setq subject (or subject (header-subject header)))
610               (or (string-match "^[Rr][Ee]:" subject)
611                   (setq subject (concat "Re: " subject)))
612               (setq followup-to (mail-fetch-field "followup-to"))
613               (if (or (null respect-poster) ;Ignore followup-to: field.
614                       (string-equal "" followup-to) ;Bogus header.
615                       (string-equal "poster" followup-to)) ;Poster
616                   (setq followup-to nil))
617               (setq newsgroups
618                     (or follow-to followup-to (mail-fetch-field "newsgroups")))
619               (setq references (header-references header))
620               (setq distribution (mail-fetch-field "distribution"))
621               ;; Remove bogus distribution.
622               (and (stringp distribution)
623                    (string-match "world" distribution)
624                    (setq distribution nil))
625               (setq message-id (header-id header))
626               (widen))
627             (setq news-reply-yank-from from)
628             (setq news-reply-yank-message-id message-id)
629             (news-setup to subject message-of 
630                         (if (stringp newsgroups) newsgroups "") 
631                         article-buffer)
632             (if (and newsgroups (listp newsgroups))
633                 (progn
634                   (goto-char (point-min))
635                   (while newsgroups
636                     (insert (car (car newsgroups)) ": " 
637                             (cdr (car newsgroups)) "\n")
638                     (setq newsgroups (cdr newsgroups)))))
639             ;; Fold long references line to follow RFC1036.
640             (mail-position-on-field "References")
641             (let ((begin (- (point) (length "References: ")))
642                   (fill-column 79)
643                   (fill-prefix "\t"))
644               (if references (insert references))
645               (if (and references message-id) (insert " "))
646               (if message-id (insert message-id))
647               ;; The region must end with a newline to fill the region
648               ;; without inserting extra newline.
649               (fill-region-as-paragraph begin (1+ (point))))
650             (if distribution
651                 (progn
652                   (mail-position-on-field "Distribution")
653                   (insert distribution)))))
654         (current-buffer)))))
655
656 ;;; Internal functions.
657
658 (defun nntp-send-mode-reader ()
659   "Send the MODE READER command to the nntp server.
660 This function is supposed to be called from `nntp-server-opened-hook'.
661 It will make innd servers spawn an nnrpd process to allow actual article
662 reading."
663   (nntp-send-command "^.*\r$" "MODE READER"))
664
665 (defun nntp-send-authinfo ()
666   "Send the AUTHINFO to the nntp server.
667 This function is supposed to be called from `nntp-server-opened-hook'.
668 It will prompt for a password."
669   (nntp-send-command "^.*\r$" "AUTHINFO USER" (user-login-name))
670   (nntp-send-command "^.*\r$" "AUTHINFO PASS" (read-string "NNTP password: ")))
671
672 (defun nntp-default-sentinel (proc status)
673   "Default sentinel function for NNTP server process."
674   (let ((servers nntp-server-alist)
675         server)
676     ;; Go through the alist of server names and find the name of the
677     ;; server that the process that sent the signal is connected to.
678     ;; If you get my drift.
679     (if (equal proc nntp-server-process)
680         (setq server nntp-address)
681       (while (and servers 
682                   (not (equal proc (nth 1 (assq 'nntp-server-process
683                                                 (car servers))))))
684         (setq servers (cdr servers)))
685       (setq server (car (car servers))))
686     (message "nntp: Connection closed to server %s." (or server "(none)"))
687     (ding)))
688
689 (defun nntp-kill-connection (server)
690   (let ((proc (nth 1 (assq 'nntp-server-process 
691                            (assoc server nntp-server-alist)))))
692     (and proc (delete-process (process-name proc)))
693     (nntp-close-server server)
694     (setq nntp-timeout-servers (cons server nntp-timeout-servers))
695     (setq nntp-status-string 
696           (message "Connection timed out to server %s." server))
697     (ding)
698     (sit-for 1)))
699
700 ;; Encoding and decoding of NNTP text.
701
702 (defun nntp-decode-text ()
703   "Decode text transmitted by NNTP.
704 0. Delete status line.
705 1. Delete `^M' at end of line.
706 2. Delete `.' at end of buffer (end of text mark).
707 3. Delete `.' at beginning of line."
708   (save-excursion
709     (set-buffer nntp-server-buffer)
710     ;; Insert newline at end of buffer.
711     (goto-char (point-max))
712     (or (bolp) (insert "\n"))
713     ;; Delete status line.
714     (goto-char (point-min))
715     (delete-region (point) (progn (forward-line 1) (point)))
716     ;; Delete `^M' at the end of lines.
717     (while (not (eobp))
718       (end-of-line)
719       (and (= (preceding-char) ?\r)
720            (delete-char -1))
721       (forward-line 1))
722     ;; Delete `.' at end of the buffer (end of text mark).
723     (goto-char (point-max))
724     (forward-line -1)
725     (if (looking-at "^\\.$")
726         (delete-region (point) (progn (forward-line 1) (point))))
727     ;; Replace `..' at beginning of line with `.'.
728     (goto-char (point-min))
729     ;; (replace-regexp "^\\.\\." ".")
730     (while (search-forward "\n.." nil t)
731       (delete-char -1))))
732
733 (defun nntp-encode-text ()
734   "Encode text in current buffer for NNTP transmission.
735 1. Insert `.' at beginning of line.
736 2. Insert `.' at end of buffer (end of text mark)."
737   (save-excursion
738     ;; Insert newline at end of buffer.
739     (goto-char (point-max))
740     (or (bolp) (insert "\n"))
741     ;; Replace `.' at beginning of line with `..'.
742     (goto-char (point-min))
743     ;; (replace-regexp "^\\." "..")
744     (while (search-forward "\n." nil t)
745       (insert "."))
746     ;; Insert `.' at end of buffer (end of text mark).
747     (goto-char (point-max))
748     (insert ".\r\n")))
749
750 \f
751 ;;;
752 ;;; Synchronous Communication with NNTP Server.
753 ;;;
754
755 (defun nntp-send-command (response cmd &rest args)
756   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
757   (save-excursion
758     ;; Clear communication buffer.
759     (set-buffer nntp-server-buffer)
760     (erase-buffer)
761     (apply 'nntp-send-strings-to-server cmd args)
762     (if response
763         (nntp-wait-for-response response)
764       t)))
765
766 (defun nntp-wait-for-response (regexp)
767   "Wait for server response which matches REGEXP."
768   (save-excursion
769     (let ((status t)
770           (wait t)
771           (dotnum 0)                    ;Number of "." being displayed.
772           (dotsize                      ;How often "." displayed.
773            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
774       (set-buffer nntp-server-buffer)
775       ;; Wait for status response (RFC977).
776       ;; 1xx - Informative message.
777       ;; 2xx - Command ok.
778       ;; 3xx - Command ok so far, send the rest of it.
779       ;; 4xx - Command was correct, but couldn't be performed for some
780       ;;       reason.
781       ;; 5xx - Command unimplemented, or incorrect, or a serious
782       ;;       program error occurred.
783       (nntp-accept-response)
784       (while wait
785         (goto-char (point-min))
786         (cond ((looking-at "[23]")
787                (setq wait nil))
788               ((looking-at "[45]")
789                (setq status nil)
790                (setq wait nil))
791               (t (nntp-accept-response))))
792       ;; Save status message.
793       (end-of-line)
794       (setq nntp-status-string
795             (buffer-substring (point-min) (point)))
796       (if status
797           (progn
798             (setq wait t)
799             (while wait
800               (goto-char (point-max))
801               (forward-line -1)         ;(beginning-of-line)
802               ;;(message (buffer-substring
803               ;;         (point)
804               ;;         (save-excursion (end-of-line) (point))))
805               (if (looking-at regexp)
806                   (setq wait nil)
807                 (if nntp-debug-read
808                     (let ((newnum (/ (buffer-size) dotsize)))
809                       (if (not (= dotnum newnum))
810                           (progn
811                             (setq dotnum newnum)
812                             (message "NNTP: Reading %s"
813                                      (make-string dotnum ?.))))))
814                 (nntp-accept-response)))
815             ;; Remove "...".
816             (if (and nntp-debug-read (> dotnum 0))
817                 (message ""))
818             ;; Successfully received server response.
819             t)))))
820
821 \f
822 ;;;
823 ;;; Low-Level Interface to NNTP Server.
824 ;;; 
825
826 (defun nntp-retrieve-headers-with-xover (sequence)
827   (if (not nntp-server-xover)
828       ()
829     (let ((range (format "%d-%d" (car sequence)
830                          (nntp-last-element sequence))))
831       (prog1
832           (if (stringp nntp-server-xover)
833               (nntp-send-command "^\\.\r$" nntp-server-xover range)
834             (let ((commands nntp-xover-commands))
835               (while (and commands (eq nntp-server-xover 'try))
836                 (nntp-send-command "^\\.\r$" (car commands) range)
837                 (save-excursion
838                   (set-buffer nntp-server-buffer)
839                   (goto-char 1)
840                   (if (looking-at "[23]") 
841                       (setq nntp-server-xover (car commands))))
842                 (setq commands (cdr commands)))
843               (if (eq nntp-server-xover 'try)
844                   (setq nntp-server-xover nil))
845               nntp-server-xover))
846         (if nntp-server-xover
847             (nntp-decode-text)
848           (erase-buffer))))))
849
850 (defun nntp-send-strings-to-server (&rest strings)
851   "Send list of STRINGS to news server as command and its arguments."
852   (let ((cmd (concat (mapconcat (lambda (s) s) strings " ") "\r\n")))
853     ;; We open the nntp server if it is down.
854     (or (nntp-server-opened nntp-current-server)
855         (progn
856           (nntp-close-server nntp-address)
857           (nntp-open-server nntp-address))
858         (error (nntp-status-message)))
859     ;; Send the strings.
860     (process-send-string nntp-server-process cmd)))
861
862 (defun nntp-send-region-to-server (begin end)
863   "Send current buffer region (from BEGIN to END) to news server."
864   (save-excursion
865     ;; We have to work in the buffer associated with NNTP server
866     ;;  process because of NEmacs hack.
867     (copy-to-buffer nntp-server-buffer begin end)
868     (set-buffer nntp-server-buffer)
869     (setq begin (point-min))
870     (setq end (point-max))
871     ;; `process-send-region' does not work if text to be sent is very
872     ;;  large. I don't know maximum size of text sent correctly.
873     (let ((last nil)
874           (size 100))                   ;Size of text sent at once.
875       (save-restriction
876         (narrow-to-region begin end)
877         (goto-char begin)
878         (while (not (eobp))
879           ;;(setq last (min end (+ (point) size)))
880           ;; NEmacs gets confused if character at `last' is Kanji.
881           (setq last (save-excursion
882                        (goto-char (min end (+ (point) size)))
883                        (or (eobp) (forward-char 1)) ;Adjust point
884                        (point)))
885           (process-send-region nntp-server-process (point) last)
886           ;; I don't know whether the next codes solve the known
887           ;;  problem of communication error of GNU Emacs.
888           (accept-process-output)
889           ;;(sit-for 0)
890           (goto-char last))))
891     ;; We cannot erase buffer, because reply may be received.
892     (delete-region begin end)))
893
894 (defun nntp-open-server-semi-internal (server &optional service)
895   "Open SERVER.
896 If SERVER is nil, use value of environment variable `NNTPSERVER'.
897 If SERVICE, this this as the port number."
898   (let ((server (or server (getenv "NNTPSERVER")))
899         (status nil)
900         (timer 
901          (and nntp-connection-timeout 
902               (run-at-time nntp-connection-timeout
903                            nil 'nntp-kill-connection server))))
904     (setq nntp-status-string "")
905     (message "nntp: Connecting to server on %s..." server)
906     (cond ((and server (nntp-open-server-internal server service))
907            (setq nntp-address server)
908            (setq status
909                  (condition-case nil
910                      (nntp-wait-for-response "^[23].*\r$")
911                    (error nil)
912                    (quit nil)))
913            (or status (nntp-close-server-internal server))
914            (and nntp-server-process
915                 (progn
916                   (set-process-sentinel 
917                    nntp-server-process 'nntp-default-sentinel)
918                   ;; You can send commands at startup like AUTHINFO here.
919                   ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
920                   (run-hooks 'nntp-server-opened-hook))))
921           ((null server)
922            (setq nntp-status-string "NNTP server is not specified.")))
923     (and timer (cancel-timer timer))
924     (message "")
925     (or status
926         (setq nntp-current-server nil))
927     status))
928
929 (defun nntp-open-server-internal (server &optional service)
930   "Open connection to news server on SERVER by SERVICE (default is nntp)."
931   (let (proc)
932     (save-excursion
933       ;; Use TCP/IP stream emulation package if needed.
934       (or (fboundp 'open-network-stream)
935           (require 'tcp))
936       ;; Initialize communication buffer.
937       (nnheader-init-server-buffer)
938       (set-buffer nntp-server-buffer)
939       (if (setq proc
940                 (condition-case nil
941                     (funcall nntp-open-server-function server)
942                   (error nil)))
943           (progn
944             (setq nntp-server-process proc)
945             ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
946             (process-kill-without-query proc)
947             (setq nntp-address server)
948             ;; It is possible to change kanji-fileio-code in this hook.
949             (run-hooks 'nntp-server-hook)
950             nntp-server-process)))))
951
952 (defun nntp-open-network-stream (server)
953   (open-network-stream "nntpd" nntp-server-buffer server nntp-port-number))
954
955 (defun nntp-open-rlogin (server)
956   (let ((proc (start-process "nntpd" nntp-server-buffer "rsh" server)))
957     (process-send-string proc (mapconcat (lambda (s) s) nntp-rlogin-parameters
958                                          " "))
959     (process-send-string proc "\n")))
960
961 (defun nntp-close-server-internal (&optional server)
962   "Close connection to news server."
963   (nntp-possibly-change-server nil server)
964   (if nntp-server-process
965       (delete-process nntp-server-process))
966   (setq nntp-server-process nil)
967   (setq nntp-address ""))
968
969 (defun nntp-accept-response ()
970   "Read response of server.
971 It is well-known that the communication speed will be much improved by
972 defining this function as macro."
973   ;; To deal with server process exiting before
974   ;;  accept-process-output is called.
975   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
976   ;; This is a copy of `nntp-default-sentinel'.
977   (if (or (not nntp-server-process)
978           (not (memq (process-status nntp-server-process) '(open run))))
979       (error "nntp: Process connection closed; %s" (nntp-status-message))
980     (if nntp-buggy-select
981         (progn
982           ;; We cannot use `accept-process-output'.
983           ;; Fujitsu UTS requires messages during sleep-for. I don't know why.
984           (message "NNTP: Reading...")
985           (sleep-for 1)
986           (message ""))
987       (condition-case errorcode
988           (accept-process-output nntp-server-process)
989         (error
990          (cond ((string-equal "select error: Invalid argument" 
991                               (nth 1 errorcode))
992                 ;; Ignore select error.
993                 nil)
994                (t
995                 (signal (car errorcode) (cdr errorcode)))))))))
996
997 (defun nntp-last-element (list)
998   "Return last element of LIST."
999   (while (cdr list)
1000     (setq list (cdr list)))
1001   (car list))
1002
1003 (defun nntp-possibly-change-server (newsgroup server)
1004   (let ((result t))
1005     ;; We see whether it is necessary to change newsgroup.
1006     (and newsgroup 
1007          (or (not (string= newsgroup nntp-current-group)))
1008          (progn
1009            (setq result (nntp-request-group newsgroup server))
1010            (setq nntp-current-group newsgroup)))
1011     result))
1012
1013 (defun nntp-try-list-active (group)
1014   (nntp-list-active-group group)
1015   (save-excursion
1016     (set-buffer nntp-server-buffer)
1017     (goto-char (point-min))
1018     (cond ((looking-at "5[0-9]+")
1019            (setq nntp-server-list-active-group nil))
1020           (t
1021            (setq nntp-server-list-active-group t)))))
1022
1023 (defun nntp-async-server-opened ()
1024   (and nntp-async-process
1025        (memq (process-status nntp-async-process) '(open run))))
1026
1027 (defun nntp-async-open-server ()
1028   (save-excursion
1029     (set-buffer (generate-new-buffer " *async-nntp*"))
1030     (setq nntp-async-buffer (current-buffer))
1031     (buffer-disable-undo (current-buffer)))
1032   (let ((nntp-server-process nil)
1033         (nntp-server-buffer nntp-async-buffer))
1034     (nntp-open-server-semi-internal nntp-address nntp-port-number)
1035     (setq nntp-async-process nntp-server-process)
1036     (set-process-buffer nntp-async-process nntp-async-buffer)))
1037
1038 (defun nntp-async-fetch-articles (article)
1039   (if (stringp article)
1040       ()
1041     (let ((articles (memq (assq article nntp-async-articles) 
1042                           nntp-async-articles))
1043           (max (cond ((numberp nntp-async-number)
1044                       nntp-async-number) 
1045                      ((eq nntp-async-number t)
1046                       (length nntp-async-articles))
1047                      (t 0)))
1048           nart)
1049       (while (and (>= (setq max (1- max)) 0)
1050                   articles)
1051         (or (memq (setq nart (car (car articles))) nntp-async-fetched)
1052             (progn
1053               (nntp-async-send-strings "ARTICLE " (int-to-string nart))
1054               (setq nntp-async-fetched (cons nart nntp-async-fetched))))
1055         (setq articles (cdr articles))))))
1056
1057 (defun nntp-async-send-strings (&rest strings)
1058   (let ((cmd (concat (mapconcat (lambda (s) s) strings " ") "\r\n")))
1059     (or (nntp-async-server-opened)
1060         (nntp-async-open-server)
1061         (error (nntp-status-message)))
1062     (process-send-string nntp-async-process cmd)))
1063
1064 (provide 'nntp)
1065
1066 ;;; nntp.el ends here