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