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