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