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