*** 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                 (art (if (numberp id) (int-to-string id) id))
421                 beg end)
422             (if (and (or (re-search-forward (concat "^2.. +" art) nil t)
423                          (progn
424                            (goto-char (point-min))
425                            (re-search-forward (concat "^2.. +" art) opoint t)))
426                      (progn
427                        (beginning-of-line)
428                        (setq beg (point)
429                              end (re-search-forward "^\\.\r?\n" nil t))))
430                 (progn
431                   (setq found t)
432                   (save-excursion
433                     (set-buffer (or buffer nntp-server-buffer))
434                     (erase-buffer)
435                     (insert-buffer-substring nntp-async-buffer beg end)
436                     (let ((nntp-server-buffer (current-buffer)))
437                       (nntp-decode-text)))
438                   (delete-region beg end)
439                   (and nntp-async-articles
440                        (nntp-async-fetch-articles id)))))))
441
442     (if found 
443         t
444       ;; The article was not in the async buffer, so we fetch it now.
445       (unwind-protect
446           (progn
447             (if buffer (set-process-buffer nntp-server-process buffer))
448             (let ((nntp-server-buffer (or buffer nntp-server-buffer))
449                   (art (or (and (numberp id) (int-to-string id)) id)))
450               ;; If NEmacs, end of message may look like: "\256\215" (".^M")
451               (prog1
452                   (nntp-send-command "^\\.\r$" "ARTICLE" art)
453                 (nntp-decode-text)
454                 (and nntp-async-articles (nntp-async-fetch-articles id)))))
455         (if buffer (set-process-buffer 
456                     nntp-server-process nntp-server-buffer))))))
457
458 (defun nntp-request-body (id &optional newsgroup server)
459   "Request body of article ID (message-id or number)."
460   (nntp-possibly-change-server newsgroup server)
461   (prog1
462       ;; If NEmacs, end of message may look like: "\256\215" (".^M")
463       (nntp-send-command
464        "^\\.\r$" "BODY" (or (and (numberp id) (int-to-string id)) id))
465     (nntp-decode-text)))
466
467 (defun nntp-request-head (id &optional newsgroup server)
468   "Request head of article ID (message-id or number)."
469   (nntp-possibly-change-server newsgroup server)
470   (prog1
471       (nntp-send-command 
472        "^\\.\r$" "HEAD" (or (and (numberp id) (int-to-string id)) id))
473     (nntp-decode-text)))
474
475 (defun nntp-request-stat (id &optional newsgroup server)
476   "Request STAT of article ID (message-id or number)."
477   (nntp-possibly-change-server newsgroup server)
478   (nntp-send-command 
479    "^[23].*\r$" "STAT" (or (and (numberp id) (int-to-string id)) id)))
480
481 (defun nntp-request-group (group &optional server dont-check)
482   "Select GROUP."
483   (nntp-send-command "^.*\r$" "GROUP" group)
484   (save-excursion
485     (set-buffer nntp-server-buffer)
486     (goto-char (point-min))
487     (looking-at "[23]")))
488
489 (defun nntp-request-asynchronous (group &optional server articles)
490   (or (nntp-async-server-opened)
491       (nntp-async-open-server)
492       (error "Can't open second connection to %s" nntp-address))
493   (setq nntp-async-articles articles)
494   (setq nntp-async-fetched nil)
495   (save-excursion
496     (set-buffer nntp-async-buffer)
497     (erase-buffer))
498   (nntp-async-send-strings "GROUP" group)
499   t)
500
501 (defun nntp-list-active-group (group &optional server)
502   (nntp-send-command "^.*\r$" "LIST ACTIVE" group))
503
504 (defun nntp-request-group-description (group &optional server)
505   "Get description of GROUP."
506   (if (nntp-possibly-change-server nil server)
507       (prog1
508           (nntp-send-command "^.*\r$" "XGTITLE" group)
509         (nntp-decode-text))))
510
511 (defun nntp-close-group (group &optional server)
512   t)
513
514 (defun nntp-request-list (&optional server)
515   "List active groups."
516   (nntp-possibly-change-server nil server)
517   (prog1
518       (nntp-send-command "^\\.\r$" "LIST")
519     (nntp-decode-text)))
520
521 (defun nntp-request-list-newsgroups (&optional server)
522   "List groups."
523   (nntp-possibly-change-server nil server)
524   (prog1
525       (nntp-send-command "^\\.\r$" "LIST NEWSGROUPS")
526     (nntp-decode-text)))
527
528 (defun nntp-request-newgroups (date &optional server)
529   "List new groups."
530   (nntp-possibly-change-server nil server)
531   (let* ((date (timezone-parse-date date))
532          (time-string
533           (format "%s%02d%02d %s%s%s"
534                   (substring (aref date 0) 2) (string-to-int (aref date 1)) 
535                   (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
536                   (substring 
537                    (aref date 3) 3 5) (substring (aref date 3) 6 8))))
538     (prog1
539         (nntp-send-command "^\\.\r$" "NEWGROUPS" time-string)
540       (nntp-decode-text))))
541
542 (defun nntp-request-list-distributions (&optional server)
543   "List distributions."
544   (nntp-possibly-change-server nil server)
545   (prog1
546       (nntp-send-command "^\\.\r$" "LIST DISTRIBUTIONS")
547     (nntp-decode-text)))
548
549 (defun nntp-request-last (&optional newsgroup server)
550   "Decrease the current article pointer."
551   (nntp-possibly-change-server newsgroup server)
552   (nntp-send-command "^[23].*\r$" "LAST"))
553
554 (defun nntp-request-next (&optional newsgroup server)
555   "Advance the current article pointer."
556   (nntp-possibly-change-server newsgroup server)
557   (nntp-send-command "^[23].*\r$" "NEXT"))
558
559 (defun nntp-request-post (&optional server)
560   "Post the current buffer."
561   (nntp-possibly-change-server nil server)
562   (if (nntp-send-command "^[23].*\r$" "POST")
563       (progn
564         (nntp-encode-text)
565         (nntp-send-region-to-server (point-min) (point-max))
566         ;; 1.2a NNTP's post command is buggy. "^M" (\r) is not
567         ;;  appended to end of the status message.
568         (nntp-wait-for-response "^[23].*$"))))
569
570 (defun nntp-request-post-buffer 
571   (post group subject header article-buffer info follow-to respect-poster)
572   "Request a buffer suitable for composing an article.
573 If POST, this is an original article; otherwise it's a followup.
574 GROUP is the group to be posted to, the article should have subject
575 SUBJECT.  HEADER is a Gnus header vector.  ARTICLE-BUFFER contains the
576 article being followed up.  INFO is a Gnus info list.  If FOLLOW-TO,
577 post to this group instead.  If RESPECT-POSTER, heed the special
578 \"poster\" value of the Followup-to header."
579   (if (assq 'to-address (nth 5 info))
580       (nnmail-request-post-buffer 
581        post group subject header article-buffer info follow-to respect-poster)
582     (let ((mail-default-headers 
583            (or nntp-news-default-headers mail-default-headers))
584           from date to followup-to newsgroups message-of
585           references distribution message-id)
586       (save-excursion
587         (set-buffer (get-buffer-create "*post-news*"))
588         (news-reply-mode)
589         (if (and (buffer-modified-p)
590                  (> (buffer-size) 0)
591                  (not (y-or-n-p "Unsent article being composed; erase it? ")))
592             ()
593           (erase-buffer)
594           (if post
595               (news-setup nil subject nil group nil)
596             (save-excursion
597               (set-buffer article-buffer)
598               (goto-char (point-min))
599               (narrow-to-region (point-min)
600                                 (progn (search-forward "\n\n") (point)))
601               (setq from (header-from header))
602               (setq date (header-date header))
603               (and from
604                    (let ((stop-pos 
605                           (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
606                      (setq 
607                       message-of
608                       (concat (if stop-pos (substring from 0 stop-pos) from) 
609                               "'s message of " date))))
610               (setq subject (or subject (header-subject header)))
611               (or (string-match "^[Rr][Ee]:" subject)
612                   (setq subject (concat "Re: " subject)))
613               (setq followup-to (mail-fetch-field "followup-to"))
614               (if (or (null respect-poster) ;Ignore followup-to: field.
615                       (string-equal "" followup-to) ;Bogus header.
616                       (string-equal "poster" followup-to)) ;Poster
617                   (setq followup-to nil))
618               (setq newsgroups
619                     (or follow-to followup-to (mail-fetch-field "newsgroups")))
620               (setq references (header-references header))
621               (setq distribution (mail-fetch-field "distribution"))
622               ;; Remove bogus distribution.
623               (and (stringp distribution)
624                    (string-match "world" distribution)
625                    (setq distribution nil))
626               (setq message-id (header-id header))
627               (widen))
628             (setq news-reply-yank-from from)
629             (setq news-reply-yank-message-id message-id)
630             (news-setup to subject message-of 
631                         (if (stringp newsgroups) newsgroups "") 
632                         article-buffer)
633             (if (and newsgroups (listp newsgroups))
634                 (progn
635                   (goto-char (point-min))
636                   (while newsgroups
637                     (insert (car (car newsgroups)) ": " 
638                             (cdr (car newsgroups)) "\n")
639                     (setq newsgroups (cdr newsgroups)))))
640             ;; Fold long references line to follow RFC1036.
641             (mail-position-on-field "References")
642             (let ((begin (- (point) (length "References: ")))
643                   (fill-column 79)
644                   (fill-prefix "\t"))
645               (if references (insert references))
646               (if (and references message-id) (insert " "))
647               (if message-id (insert message-id))
648               ;; The region must end with a newline to fill the region
649               ;; without inserting extra newline.
650               (fill-region-as-paragraph begin (1+ (point))))
651             (if distribution
652                 (progn
653                   (mail-position-on-field "Distribution")
654                   (insert distribution)))))
655         (current-buffer)))))
656
657 ;;; Internal functions.
658
659 (defun nntp-send-mode-reader ()
660   "Send the MODE READER command to the nntp server.
661 This function is supposed to be called from `nntp-server-opened-hook'.
662 It will make innd servers spawn an nnrpd process to allow actual article
663 reading."
664   (nntp-send-command "^.*\r$" "MODE READER"))
665
666 (defun nntp-send-authinfo ()
667   "Send the AUTHINFO to the nntp server.
668 This function is supposed to be called from `nntp-server-opened-hook'.
669 It will prompt for a password."
670   (nntp-send-command "^.*\r$" "AUTHINFO USER" (user-login-name))
671   (nntp-send-command "^.*\r$" "AUTHINFO PASS" (read-string "NNTP password: ")))
672
673 (defun nntp-default-sentinel (proc status)
674   "Default sentinel function for NNTP server process."
675   (let ((servers nntp-server-alist)
676         server)
677     ;; Go through the alist of server names and find the name of the
678     ;; server that the process that sent the signal is connected to.
679     ;; If you get my drift.
680     (if (equal proc nntp-server-process)
681         (setq server nntp-address)
682       (while (and servers 
683                   (not (equal proc (nth 1 (assq 'nntp-server-process
684                                                 (car servers))))))
685         (setq servers (cdr servers)))
686       (setq server (car (car servers))))
687     (message "nntp: Connection closed to server %s" (or server "(none)"))
688     (ding)))
689
690 (defun nntp-kill-connection (server)
691   (let ((proc (nth 1 (assq 'nntp-server-process 
692                            (assoc server nntp-server-alist)))))
693     (and proc (delete-process (process-name proc)))
694     (nntp-close-server server)
695     (setq nntp-timeout-servers (cons server nntp-timeout-servers))
696     (setq nntp-status-string 
697           (message "Connection timed out to server %s." server))
698     (ding)
699     (sit-for 1)))
700
701 ;; Encoding and decoding of NNTP text.
702
703 (defun nntp-decode-text ()
704   "Decode text transmitted by NNTP.
705 0. Delete status line.
706 1. Delete `^M' at end of line.
707 2. Delete `.' at end of buffer (end of text mark).
708 3. Delete `.' at beginning of line."
709   (save-excursion
710     (set-buffer nntp-server-buffer)
711     ;; Insert newline at end of buffer.
712     (goto-char (point-max))
713     (or (bolp) (insert "\n"))
714     ;; Delete status line.
715     (goto-char (point-min))
716     (delete-region (point) (progn (forward-line 1) (point)))
717     ;; Delete `^M' at the end of lines.
718     (while (not (eobp))
719       (end-of-line)
720       (and (= (preceding-char) ?\r)
721            (delete-char -1))
722       (forward-line 1))
723     ;; Delete `.' at end of the buffer (end of text mark).
724     (goto-char (point-max))
725     (forward-line -1)
726     (if (looking-at "^\\.$")
727         (delete-region (point) (progn (forward-line 1) (point))))
728     ;; Replace `..' at beginning of line with `.'.
729     (goto-char (point-min))
730     ;; (replace-regexp "^\\.\\." ".")
731     (while (search-forward "\n.." nil t)
732       (delete-char -1))))
733
734 (defun nntp-encode-text ()
735   "Encode text in current buffer for NNTP transmission.
736 1. Insert `.' at beginning of line.
737 2. Insert `.' at end of buffer (end of text mark)."
738   (save-excursion
739     ;; Insert newline at end of buffer.
740     (goto-char (point-max))
741     (or (bolp) (insert "\n"))
742     ;; Replace `.' at beginning of line with `..'.
743     (goto-char (point-min))
744     ;; (replace-regexp "^\\." "..")
745     (while (search-forward "\n." nil t)
746       (insert "."))
747     ;; Insert `.' at end of buffer (end of text mark).
748     (goto-char (point-max))
749     (insert ".\r\n")))
750
751 \f
752 ;;;
753 ;;; Synchronous Communication with NNTP Server.
754 ;;;
755
756 (defun nntp-send-command (response cmd &rest args)
757   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
758   (save-excursion
759     ;; Clear communication buffer.
760     (set-buffer nntp-server-buffer)
761     (erase-buffer)
762     (apply 'nntp-send-strings-to-server cmd args)
763     (if response
764         (nntp-wait-for-response response)
765       t)))
766
767 (defun nntp-wait-for-response (regexp)
768   "Wait for server response which matches REGEXP."
769   (save-excursion
770     (let ((status t)
771           (wait t)
772           (dotnum 0)                    ;Number of "." being displayed.
773           (dotsize                      ;How often "." displayed.
774            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
775       (set-buffer nntp-server-buffer)
776       ;; Wait for status response (RFC977).
777       ;; 1xx - Informative message.
778       ;; 2xx - Command ok.
779       ;; 3xx - Command ok so far, send the rest of it.
780       ;; 4xx - Command was correct, but couldn't be performed for some
781       ;;       reason.
782       ;; 5xx - Command unimplemented, or incorrect, or a serious
783       ;;       program error occurred.
784       (nntp-accept-response)
785       (while wait
786         (goto-char (point-min))
787         (cond ((looking-at "[23]")
788                (setq wait nil))
789               ((looking-at "[45]")
790                (setq status nil)
791                (setq wait nil))
792               (t (nntp-accept-response))))
793       ;; Save status message.
794       (end-of-line)
795       (setq nntp-status-string
796             (buffer-substring (point-min) (point)))
797       (if status
798           (progn
799             (setq wait t)
800             (while wait
801               (goto-char (point-max))
802               (forward-line -1)         ;(beginning-of-line)
803               ;;(message (buffer-substring
804               ;;         (point)
805               ;;         (save-excursion (end-of-line) (point))))
806               (if (looking-at regexp)
807                   (setq wait nil)
808                 (if nntp-debug-read
809                     (let ((newnum (/ (buffer-size) dotsize)))
810                       (if (not (= dotnum newnum))
811                           (progn
812                             (setq dotnum newnum)
813                             (message "NNTP: Reading %s"
814                                      (make-string dotnum ?.))))))
815                 (nntp-accept-response)))
816             ;; Remove "...".
817             (if (and nntp-debug-read (> dotnum 0))
818                 (message ""))
819             ;; Successfully received server response.
820             t)))))
821
822 \f
823 ;;;
824 ;;; Low-Level Interface to NNTP Server.
825 ;;; 
826
827 (defun nntp-retrieve-headers-with-xover (sequence)
828   (if (not nntp-server-xover)
829       ()
830     (let ((range (format "%d-%d" (car sequence)
831                          (nntp-last-element sequence))))
832       (prog1
833           (if (stringp nntp-server-xover)
834               (nntp-send-command "^\\.\r$" nntp-server-xover range)
835             (let ((commands nntp-xover-commands))
836               (while (and commands (eq nntp-server-xover 'try))
837                 (nntp-send-command "^\\.\r$" (car commands) range)
838                 (save-excursion
839                   (set-buffer nntp-server-buffer)
840                   (goto-char 1)
841                   (if (looking-at "[23]") 
842                       (setq nntp-server-xover (car commands))))
843                 (setq commands (cdr commands)))
844               (if (eq nntp-server-xover 'try)
845                   (setq nntp-server-xover nil))
846               nntp-server-xover))
847         (if nntp-server-xover
848             (nntp-decode-text)
849           (erase-buffer))))))
850
851 (defun nntp-send-strings-to-server (&rest strings)
852   "Send list of STRINGS to news server as command and its arguments."
853   (let ((cmd (concat (mapconcat (lambda (s) s) strings " ") "\r\n")))
854     ;; We open the nntp server if it is down.
855     (or (nntp-server-opened nntp-current-server)
856         (progn
857           (nntp-close-server nntp-address)
858           (nntp-open-server nntp-address))
859         (error (nntp-status-message)))
860     ;; Send the strings.
861     (process-send-string nntp-server-process cmd)))
862
863 (defun nntp-send-region-to-server (begin end)
864   "Send current buffer region (from BEGIN to END) to news server."
865   (save-excursion
866     ;; We have to work in the buffer associated with NNTP server
867     ;;  process because of NEmacs hack.
868     (copy-to-buffer nntp-server-buffer begin end)
869     (set-buffer nntp-server-buffer)
870     (setq begin (point-min))
871     (setq end (point-max))
872     ;; `process-send-region' does not work if text to be sent is very
873     ;;  large. I don't know maximum size of text sent correctly.
874     (let ((last nil)
875           (size 100))                   ;Size of text sent at once.
876       (save-restriction
877         (narrow-to-region begin end)
878         (goto-char begin)
879         (while (not (eobp))
880           ;;(setq last (min end (+ (point) size)))
881           ;; NEmacs gets confused if character at `last' is Kanji.
882           (setq last (save-excursion
883                        (goto-char (min end (+ (point) size)))
884                        (or (eobp) (forward-char 1)) ;Adjust point
885                        (point)))
886           (process-send-region nntp-server-process (point) last)
887           ;; I don't know whether the next codes solve the known
888           ;;  problem of communication error of GNU Emacs.
889           (accept-process-output)
890           ;;(sit-for 0)
891           (goto-char last))))
892     ;; We cannot erase buffer, because reply may be received.
893     (delete-region begin end)))
894
895 (defun nntp-open-server-semi-internal (server &optional service)
896   "Open SERVER.
897 If SERVER is nil, use value of environment variable `NNTPSERVER'.
898 If SERVICE, this this as the port number."
899   (let ((server (or server (getenv "NNTPSERVER")))
900         (status nil)
901         (timer 
902          (and nntp-connection-timeout 
903               (run-at-time nntp-connection-timeout
904                            nil 'nntp-kill-connection server))))
905     (setq nntp-status-string "")
906     (message "nntp: Connecting to server on %s..." server)
907     (cond ((and server (nntp-open-server-internal server service))
908            (setq nntp-address server)
909            (setq status
910                  (condition-case nil
911                      (nntp-wait-for-response "^[23].*\r$")
912                    (error nil)
913                    (quit nil)))
914            (or status (nntp-close-server-internal server))
915            (and nntp-server-process
916                 (progn
917                   (set-process-sentinel 
918                    nntp-server-process 'nntp-default-sentinel)
919                   ;; You can send commands at startup like AUTHINFO here.
920                   ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
921                   (run-hooks 'nntp-server-opened-hook))))
922           ((null server)
923            (setq nntp-status-string "NNTP server is not specified.")))
924     (and timer (cancel-timer timer))
925     (message "")
926     (or status
927         (setq nntp-current-server nil))
928     status))
929
930 (defun nntp-open-server-internal (server &optional service)
931   "Open connection to news server on SERVER by SERVICE (default is nntp)."
932   (let (proc)
933     (save-excursion
934       ;; Use TCP/IP stream emulation package if needed.
935       (or (fboundp 'open-network-stream)
936           (require 'tcp))
937       ;; Initialize communication buffer.
938       (nnheader-init-server-buffer)
939       (set-buffer nntp-server-buffer)
940       (if (setq proc
941                 (condition-case nil
942                     (funcall nntp-open-server-function server)
943                   (error nil)))
944           (progn
945             (setq nntp-server-process proc)
946             ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
947             (process-kill-without-query proc)
948             (setq nntp-address server)
949             ;; It is possible to change kanji-fileio-code in this hook.
950             (run-hooks 'nntp-server-hook)
951             nntp-server-process)))))
952
953 (defun nntp-open-network-stream (server)
954   (open-network-stream "nntpd" nntp-server-buffer server nntp-port-number))
955
956 (defun nntp-open-rlogin (server)
957   (let ((proc (start-process "nntpd" nntp-server-buffer "rsh" server)))
958     (process-send-string proc (mapconcat (lambda (s) s) nntp-rlogin-parameters
959                                          " "))
960     (process-send-string proc "\n")))
961
962 (defun nntp-close-server-internal (&optional server)
963   "Close connection to news server."
964   (nntp-possibly-change-server nil server)
965   (if nntp-server-process
966       (delete-process nntp-server-process))
967   (setq nntp-server-process nil)
968   (setq nntp-address ""))
969
970 (defun nntp-accept-response ()
971   "Read response of server.
972 It is well-known that the communication speed will be much improved by
973 defining this function as macro."
974   ;; To deal with server process exiting before
975   ;;  accept-process-output is called.
976   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
977   ;; This is a copy of `nntp-default-sentinel'.
978   (if (or (not nntp-server-process)
979           (not (memq (process-status nntp-server-process) '(open run))))
980       (error "nntp: Process connection closed; %s" (nntp-status-message))
981     (if nntp-buggy-select
982         (progn
983           ;; We cannot use `accept-process-output'.
984           ;; Fujitsu UTS requires messages during sleep-for. I don't know why.
985           (message "NNTP: Reading...")
986           (sleep-for 1)
987           (message ""))
988       (condition-case errorcode
989           (accept-process-output nntp-server-process)
990         (error
991          (cond ((string-equal "select error: Invalid argument" 
992                               (nth 1 errorcode))
993                 ;; Ignore select error.
994                 nil)
995                (t
996                 (signal (car errorcode) (cdr errorcode)))))))))
997
998 (defun nntp-last-element (list)
999   "Return last element of LIST."
1000   (while (cdr list)
1001     (setq list (cdr list)))
1002   (car list))
1003
1004 (defun nntp-possibly-change-server (newsgroup server)
1005   (let ((result t))
1006     ;; We see whether it is necessary to change newsgroup.
1007     (and newsgroup 
1008          (or (not (string= newsgroup nntp-current-group)))
1009          (progn
1010            (setq result (nntp-request-group newsgroup server))
1011            (setq nntp-current-group newsgroup)))
1012     result))
1013
1014 (defun nntp-try-list-active (group)
1015   (nntp-list-active-group group)
1016   (save-excursion
1017     (set-buffer nntp-server-buffer)
1018     (goto-char (point-min))
1019     (cond ((looking-at "5[0-9]+")
1020            (setq nntp-server-list-active-group nil))
1021           (t
1022            (setq nntp-server-list-active-group t)))))
1023
1024 (defun nntp-async-server-opened ()
1025   (and nntp-async-process
1026        (memq (process-status nntp-async-process) '(open run))))
1027
1028 (defun nntp-async-open-server ()
1029   (save-excursion
1030     (set-buffer (generate-new-buffer " *async-nntp*"))
1031     (setq nntp-async-buffer (current-buffer))
1032     (buffer-disable-undo (current-buffer)))
1033   (let ((nntp-server-process nil)
1034         (nntp-server-buffer nntp-async-buffer))
1035     (nntp-open-server-semi-internal nntp-address nntp-port-number)
1036     (setq nntp-async-process nntp-server-process)
1037     (set-process-buffer nntp-async-process nntp-async-buffer)))
1038
1039 (defun nntp-async-fetch-articles (article)
1040   (if (stringp article)
1041       ()
1042     (let ((articles (cdr (memq (assq article nntp-async-articles)
1043                                nntp-async-articles)))
1044           (max (cond ((numberp nntp-async-number)
1045                       nntp-async-number) 
1046                      ((eq nntp-async-number t)
1047                       (length nntp-async-articles))
1048                      (t 0)))
1049           nart)
1050       (while (and (>= (setq max (1- max)) 0)
1051                   articles)
1052         (or (memq (setq nart (car (car articles))) nntp-async-fetched)
1053             (progn
1054               (nntp-async-send-strings "ARTICLE " (int-to-string nart))
1055               (setq nntp-async-fetched (cons nart nntp-async-fetched))))
1056         (setq articles (cdr articles))))))
1057
1058 (defun nntp-async-send-strings (&rest strings)
1059   (let ((cmd (concat (mapconcat (lambda (s) s) strings " ") "\r\n")))
1060     (or (nntp-async-server-opened)
1061         (nntp-async-open-server)
1062         (error (nntp-status-message)))
1063     (process-send-string nntp-async-process cmd)))
1064
1065 (provide 'nntp)
1066
1067 ;;; nntp.el ends here