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