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