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