*** empty log message ***
[gnus] / lisp / nntp.el
1 ;;; nntp.el --- NNTP (RFC977) Interface for GNU Emacs
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 'nnheader)
30
31 (eval-and-compile
32   (autoload 'news-setup "rnewspost")
33   (autoload 'news-reply-mode "rnewspost")
34   (autoload 'nnmail-request-post-buffer "nnmail")
35   (autoload 'cancel-timer "timer"))
36
37 (defvar nntp-server-hook nil
38   "*Hooks for the NNTP server.
39 If the kanji code of the NNTP server is different from the local kanji
40 code, the correct kanji code of the buffer associated with the NNTP
41 server must be specified as follows:
42
43 \(setq nntp-server-hook
44       (function
45        (lambda ()
46          ;; Server's Kanji code is EUC (NEmacs hack).
47          (make-local-variable 'kanji-fileio-code)
48          (setq kanji-fileio-code 0))))
49
50 If you'd like to change something depending on the server in this
51 hook, use the variable `nntp-address'.")
52
53 (defvar nntp-server-opened-hook nil
54   "*Hook used for sending commands to the server at startup.  
55 The default value is `nntp-send-mode-reader', whick makes an innd
56 server spawn an nnrpd server.  Another useful function to put in this
57 hook might be `nntp-send-authinfo', which will prompt for a password
58 to allow posting from the server.  Note that this is only necessary to
59 do on servers that use strict access control.")  (add-hook
60 'nntp-server-opened-hook 'nntp-send-mode-reader)
61
62 (defvar nntp-open-server-function 'nntp-open-network-stream
63   "*Function used for connecting to a remote system.
64 It will be called with the address of the remote system.
65
66 Two pre-made functions are `nntp-open-network-stream', which is the
67 default, and simply connects to some port or other on the remote
68 system (see nntp-port-number).  The other is `nntp-open-rlogin', which
69 does an rlogin on the remote system, and then does a telnet to the
70 NNTP server available there (see nntp-rlogin-parameters).")
71
72 (defvar nntp-rlogin-parameters '("telnet" "${NNTPSERVER:=localhost}" "nntp")
73   "*Parameters to `nntp-open-login'.
74 That function may be used as `nntp-open-server-function'.  In that
75 case, this list will be used as the parameter list given to rsh.")
76
77 (defvar nntp-rlogin-user-name nil
78   "*User name on remote system when using the rlogin connect method.")
79
80 (defvar nntp-address nil
81   "*The name of the NNTP server.")
82
83 (defvar nntp-port-number "nntp"
84   "*Port number to connect to.")
85
86 (defvar nntp-large-newsgroup 50
87   "*The number of the articles which indicates a large newsgroup.
88 If the number of the articles is greater than the value, verbose
89 messages will be shown to indicate the current status.")
90
91 (defvar nntp-buggy-select (memq system-type '(fujitsu-uts))
92   "*t if your select routine is buggy.
93 If the select routine signals error or fall into infinite loop while
94 waiting for the server response, the variable must be set to t.  In
95 case of Fujitsu UTS, it is set to T since `accept-process-output'
96 doesn't work properly.")
97
98 (defvar nntp-maximum-request 400
99   "*The maximum number of the requests sent to the NNTP server at one time.
100 If Emacs hangs up while retrieving headers, set the variable to a
101 lower value.")
102
103 (defvar nntp-debug-read 10000
104   "*Display '...' every 10Kbytes of a message being received if it is non-nil.
105 If it is a number, dots are displayed per the number.")
106
107 (defvar nntp-nov-is-evil nil
108   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
109
110 (defvar nntp-xover-commands '("XOVER" "XOVERVIEW")
111   "*List of strings that are used as commands to fetch NOV lines from a server.
112 The strings are tried in turn until a positive response is gotten. If
113 none of the commands are successful, nntp will just grab headers one
114 by one.")
115
116 (defvar nntp-connection-timeout nil
117   "*Number of seconds to wait before an nntp connection times out.
118 If this variable is nil, which is the default, no timers are set.")
119
120 (defvar nntp-news-default-headers nil
121   "*If non-nil, override `mail-default-headers' when posting news.")
122
123 (defvar nntp-prepare-server-hook nil
124   "*Hook run before a server is opened.
125 If can be used to set up a server remotely, for instance.  Say you
126 have an account at the machine \"other.machine\".  This machine has
127 access to an NNTP server that you can't access locally.  You could
128 then use this hook to rsh to the remote machine and start a proxy NNTP
129 server there that you can connect to.")
130
131 \f
132
133 (defconst nntp-version "nntp 4.0"
134   "Version numbers of this version of NNTP.")
135
136 (defvar nntp-server-buffer nil
137   "Buffer associated with the NNTP server process.")
138
139 (defvar nntp-server-process nil
140   "The NNTP server process.
141 You'd better not use this variable in NNTP front-end program, but
142 instead use `nntp-server-buffer'.")
143
144 (defvar nntp-status-string nil
145   "Save the server response message.
146 You'd better not use this variable in NNTP front-end program but
147 instead call function `nntp-status-message' to get status message.")
148
149 (defvar nntp-server-xover 'try)
150 (defvar nntp-server-list-active-group 'try)
151 (defvar nntp-current-group "")
152
153 \f
154 (defvar nntp-current-server nil)
155 (defvar nntp-server-alist nil)
156 (defvar nntp-server-variables 
157   (list
158    (list 'nntp-server-hook nntp-server-hook)
159    (list 'nntp-server-opened-hook nntp-server-opened-hook)
160    (list 'nntp-port-number nntp-port-number)
161    (list 'nntp-address nntp-address)
162    (list 'nntp-large-newsgroup nntp-large-newsgroup)
163    (list 'nntp-buggy-select nntp-buggy-select)
164    (list 'nntp-maximum-request nntp-maximum-request)
165    (list 'nntp-debug-read nntp-debug-read)
166    (list 'nntp-nov-is-evil nntp-nov-is-evil)
167    (list 'nntp-xover-commands nntp-xover-commands)
168    (list 'nntp-connection-timeout nntp-connection-timeout)
169    (list 'nntp-news-default-headers nntp-news-default-headers)
170    (list 'nntp-prepare-server-hook nntp-prepare-server-hook) 
171    '(nntp-server-process nil)
172    '(nntp-status-string nil)
173    '(nntp-server-xover try)
174    '(nntp-server-list-active-group try)
175    '(nntp-current-group "")))
176
177 \f
178 ;;; Interface funtions.
179
180 (defun nntp-retrieve-headers (sequence &optional newsgroup server)
181   "Retrieve the headers to the articles in SEQUENCE."
182   (nntp-possibly-change-server newsgroup server)
183   (save-excursion
184     (set-buffer nntp-server-buffer)
185     (erase-buffer)
186     (if (and (not gnus-nov-is-evil) 
187              (not nntp-nov-is-evil)
188              (nntp-retrieve-headers-with-xover sequence))
189         'nov
190       (let ((number (length sequence))
191             (count 0)
192             (received 0)
193             (last-point (point-min)))
194         ;; Send HEAD command.
195         (while sequence
196           (nntp-send-strings-to-server "HEAD" (car sequence))
197           (setq sequence (cdr sequence))
198           (setq count (1+ count))
199           ;; Every 400 header requests we have to read stream in order
200           ;;  to avoid deadlock.
201           (if (or (null sequence)       ;All requests have been sent.
202                   (zerop (% count nntp-maximum-request)))
203               (progn
204                 (accept-process-output)
205                 (while (progn
206                          (goto-char last-point)
207                          ;; Count replies.
208                          (while (re-search-forward "^[0-9]" nil t)
209                            (setq received (1+ received)))
210                          (setq last-point (point))
211                          (< received count))
212                   ;; If number of headers is greater than 100, give
213                   ;;  informative messages.
214                   (and (numberp nntp-large-newsgroup)
215                        (> number nntp-large-newsgroup)
216                        (zerop (% received 20))
217                        (message "NNTP: Receiving headers... %d%%"
218                                 (/ (* received 100) number)))
219                   (nntp-accept-response)))))
220         ;; Wait for text of last command.
221         (goto-char (point-max))
222         (re-search-backward "^[0-9]" nil t)
223         (if (looking-at "^[23]")
224             (while (progn
225                      (goto-char (- (point-max) 3))
226                      (not (looking-at "^\\.\r$")))
227               (nntp-accept-response)))
228         (and (numberp nntp-large-newsgroup)
229              (> number nntp-large-newsgroup)
230              (message "NNTP: Receiving headers... done"))
231
232         ;; Now all of replies are received.
233         (setq received number)
234         ;; First, fold continuation lines.
235         (goto-char (point-min))
236         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
237           (replace-match " "))
238         ;; Remove all "\r"'s
239         (goto-char (point-min))
240         (while (search-forward "\r" nil t)
241           (replace-match ""))
242         'headers))))
243
244
245 (defun nntp-retrieve-groups (groups &optional server)
246   (nntp-possibly-change-server nil server)
247   (save-excursion
248     (set-buffer nntp-server-buffer)
249     (and (eq nntp-server-list-active-group 'try)
250          (nntp-try-list-active (car groups)))
251     (erase-buffer)
252     (let ((count 0)
253           (received 0)
254           (last-point (point-min))
255           (command (if nntp-server-list-active-group
256                        "LIST ACTIVE" "GROUP")))
257         (while groups
258           (nntp-send-strings-to-server command (car groups))
259           (setq groups (cdr groups))
260           (setq count (1+ count))
261           ;; Every 400 requests we have to read the stream in
262           ;; order to avoid deadlocks.
263           (if (or (null groups)       ;All requests have been sent.
264                   (zerop (% count nntp-maximum-request)))
265               (progn
266                 (accept-process-output)
267                 (while (progn
268                          (goto-char last-point)
269                          ;; Count replies.
270                          (while (re-search-forward "^[0-9]" nil t)
271                            (setq received (1+ received)))
272                          (setq last-point (point))
273                          (< received count))
274                   (nntp-accept-response)))))
275
276         ;; Wait for the reply from the final command.
277         (if nntp-server-list-active-group
278             (progn
279               (goto-char (point-max))
280               (re-search-backward "^[0-9]" nil t)
281               (if (looking-at "^[23]")
282                   (while (progn
283                            (goto-char (- (point-max) 3))
284                            (not (looking-at "^\\.\r$")))
285                     (nntp-accept-response)))))
286
287         ;; Now all replies are received. We remove CRs.
288         (goto-char (point-min))
289         (while (search-forward "\r" nil t)
290           (replace-match ""))
291
292         (if nntp-server-list-active-group
293             (progn
294               ;; We have read active entries, so we just delete the
295               ;; superfluos gunk.
296               (goto-char (point-min))
297               (while (re-search-forward "^[\\.234]" nil t)
298                 (delete-region (match-beginning 0) 
299                                (progn (forward-line 1) (point))))
300               'active)
301           'group))))
302
303 (defun nntp-open-server (server &optional defs)
304   (nnheader-init-server-buffer)
305   (if (nntp-server-opened server)
306       t
307     (if (or (stringp (car defs))
308             (numberp (car defs)))
309         (setq defs (cons (list 'nntp-server-port (car defs)) (cdr defs))))
310     (or (assq 'nntp-address defs)
311         (setq defs (append defs (list (list 'nntp-address server)))))
312     (if (and nntp-current-server
313              (not (equal server nntp-current-server)))
314         (setq nntp-server-alist 
315               (cons (list nntp-current-server
316                           (nnheader-save-variables nntp-server-variables))
317                     nntp-server-alist)))
318     (let ((state (assoc server nntp-server-alist)))
319       (if state 
320           (progn
321             (nnheader-restore-variables (nth 1 state))
322             (setq nntp-server-alist (delq state nntp-server-alist)))
323         (nnheader-set-init-variables nntp-server-variables defs)))
324     (setq nntp-current-server server)
325     (run-hooks 'nntp-prepare-server-hook)
326     (nntp-open-server-semi-internal nntp-address)))
327
328 (defun nntp-close-server (&optional server)
329   "Close connection to SERVER."
330   (nntp-possibly-change-server nil server)
331   (unwind-protect
332       (progn
333         ;; Un-set default sentinel function before closing connection.
334         (and nntp-server-process
335              (eq 'nntp-default-sentinel
336                  (process-sentinel nntp-server-process))
337              (set-process-sentinel nntp-server-process nil))
338         ;; We cannot send QUIT command unless the process is running.
339         (if (nntp-server-opened)
340             (nntp-send-command nil "QUIT")))
341     (nntp-close-server-internal server)))
342
343 (fset 'nntp-request-quit (symbol-function 'nntp-close-server))
344
345 (defun nntp-request-close ()
346   "Close all server connections."
347   (let (proc)
348     (while nntp-server-alist
349       (setq proc (nth 1 (assq 'nntp-server-process (car nntp-server-alist))))
350       (and proc (delete-process proc))
351       (setq nntp-server-alist (cdr nntp-server-alist)))
352     (setq nntp-current-server nil)))
353
354 (defun nntp-server-opened (&optional server)
355   "Say whether a connection to SERVER has been opened."
356   (and (equal server nntp-current-server)
357        nntp-server-buffer
358        (buffer-name nntp-server-buffer)
359        nntp-server-process
360        (memq (process-status nntp-server-process) '(open run))))
361
362 (defun nntp-status-message (&optional server)
363   "Return server status as a string."
364   (if (and nntp-status-string
365            ;; NNN MESSAGE
366            (string-match "[0-9][0-9][0-9][ \t]+\\([^\r]*\\).*$"
367                          nntp-status-string))
368       (substring nntp-status-string (match-beginning 1) (match-end 1))
369     ;; Empty message if nothing.
370     nntp-status-string))
371
372 (defun nntp-request-article (id &optional newsgroup server buffer)
373   "Request article ID (message-id or number)."
374   (nntp-possibly-change-server newsgroup server)
375   (unwind-protect
376       (progn
377         (if buffer (set-process-buffer nntp-server-process buffer))
378         (let ((nntp-server-buffer (or buffer nntp-server-buffer))
379               (id (or (and (numberp id) (int-to-string id)) id)))
380           ;; If NEmacs, end of message may look like: "\256\215" (".^M")
381           (prog1
382               (nntp-send-command "^\\.\r$" "ARTICLE" id)
383             (nntp-decode-text))))
384     (if buffer (set-process-buffer nntp-server-process nntp-server-buffer))))
385
386 (defun nntp-request-body (id &optional newsgroup server)
387   "Request body of article ID (message-id or number)."
388   (nntp-possibly-change-server newsgroup server)
389   (prog1
390       ;; If NEmacs, end of message may look like: "\256\215" (".^M")
391       (nntp-send-command
392        "^\\.\r$" "BODY" (or (and (numberp id) (int-to-string id)) id))
393     (nntp-decode-text)))
394
395 (defun nntp-request-head (id &optional newsgroup server)
396   "Request head of article ID (message-id or number)."
397   (nntp-possibly-change-server newsgroup server)
398   (prog1
399       (nntp-send-command 
400        "^\\.\r$" "HEAD" (or (and (numberp id) (int-to-string id)) id))
401     (nntp-decode-text)))
402
403 (defun nntp-request-stat (id &optional newsgroup server)
404   "Request STAT of article ID (message-id or number)."
405   (nntp-possibly-change-server newsgroup server)
406   (nntp-send-command 
407    "^[23].*\r$" "STAT" (or (and (numberp id) (int-to-string id)) id)))
408
409 (defun nntp-request-group (group &optional server dont-check)
410   "Select GROUP."
411   (if dont-check
412       (nntp-send-command "^.*\r$" "GROUP" group)
413     (cond ((eq nntp-server-list-active-group 'try)
414            (or (nntp-try-list-active group)
415                (nntp-send-command "^.*\r$" "GROUP" group)))
416           (nntp-server-list-active-group
417            (nntp-list-active-group group))
418           (t
419            (nntp-send-command "^.*\r$" "GROUP" group)))
420     (if nntp-server-list-active-group
421         (save-excursion
422           (set-buffer nntp-server-buffer)
423           (goto-char (point-min))
424           (forward-line 1)
425           (if (looking-at "[^ ]+[ \t]+\\([0-9]\\)[ \t]+\\([0-9]\\)")
426               (let ((end (progn (goto-char (match-beginning 1))
427                                 (read (current-buffer))))
428                     (beg (read (current-buffer))))
429                 (and (> beg end)
430                      (setq end 0
431                            beg 0))
432                 (erase-buffer)
433                 (insert (format "211 %s %d %d %d\n"
434                                 group (max (- (1+ end) beg) 0)
435                                 beg end))))))
436     (save-excursion
437       (set-buffer nntp-server-buffer)
438       (goto-char (point-min))
439       (looking-at "[23]"))))
440
441 (defun nntp-list-active-group (group &optional server)
442   (nntp-send-command "^.*\r$" "LIST ACTIVE" group))
443
444 (defun nntp-request-group-description (group &optional server)
445   "Get description of GROUP."
446   (if (nntp-possibly-change-server nil server)
447       (prog1
448           (nntp-send-command "^.*\r$" "XGTITLE" group)
449         (nntp-decode-text))))
450
451 (defun nntp-close-group (group &optional server)
452   t)
453
454 (defun nntp-request-list (&optional server)
455   "List active groups."
456   (nntp-possibly-change-server nil server)
457   (prog1
458       (nntp-send-command "^\\.\r$" "LIST")
459     (nntp-decode-text)))
460
461 (defun nntp-request-list-newsgroups (&optional server)
462   "List groups."
463   (nntp-possibly-change-server nil server)
464   (prog1
465       (nntp-send-command "^\\.\r$" "LIST NEWSGROUPS")
466     (nntp-decode-text)))
467
468 (defun nntp-request-newgroups (date &optional server)
469   "List new groups."
470   (nntp-possibly-change-server nil server)
471   (let* ((date (timezone-parse-date date))
472          (time-string
473           (format "%s%02d%02d %s%s%s"
474                   (substring (aref date 0) 2) (string-to-int (aref date 1)) 
475                   (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
476                   (substring 
477                    (aref date 3) 3 5) (substring (aref date 3) 6 8))))
478     (prog1
479         (nntp-send-command "^\\.\r$" "NEWGROUPS" time-string)
480       (nntp-decode-text))))
481
482 (defun nntp-request-list-distributions (&optional server)
483   "List distributions."
484   (nntp-possibly-change-server nil server)
485   (prog1
486       (nntp-send-command "^\\.\r$" "LIST DISTRIBUTIONS")
487     (nntp-decode-text)))
488
489 (defun nntp-request-last (&optional newsgroup server)
490   "Decrease the current article pointer."
491   (nntp-possibly-change-server newsgroup server)
492   (nntp-send-command "^[23].*\r$" "LAST"))
493
494 (defun nntp-request-next (&optional newsgroup server)
495   "Advance the current article pointer."
496   (nntp-possibly-change-server newsgroup server)
497   (nntp-send-command "^[23].*\r$" "NEXT"))
498
499 (defun nntp-request-post (&optional server)
500   "Post the current buffer."
501   (nntp-possibly-change-server nil server)
502   (if (nntp-send-command "^[23].*\r$" "POST")
503       (progn
504         (nntp-encode-text)
505         (nntp-send-region-to-server (point-min) (point-max))
506         ;; 1.2a NNTP's post command is buggy. "^M" (\r) is not
507         ;;  appended to end of the status message.
508         (nntp-wait-for-response "^[23].*$"))))
509
510 (defun nntp-request-post-buffer 
511   (post group subject header article-buffer info follow-to respect-poster)
512   "Request a buffer suitable for composing an article.
513 If POST, this is an original article; otherwise it's a followup.
514 GROUP is the group to be posted to, the article should have subject
515 SUBJECT.  HEADER is a Gnus header vector.  ARTICLE-BUFFER contains the
516 article being followed up.  INFO is a Gnus info list.  If FOLLOW-TO,
517 post to this group instead.  If RESPECT-POSTER, heed the special
518 \"poster\" value of the Followup-to header."
519   (if (assq 'to-address (nth 5 info))
520       (nnmail-request-post-buffer 
521        post group subject header article-buffer info follow-to respect-poster)
522     (let ((mail-default-headers 
523            (or nntp-news-default-headers mail-default-headers))
524           from date to followup-to newsgroups message-of
525           references distribution message-id)
526       (save-excursion
527         (set-buffer (get-buffer-create "*post-news*"))
528         (news-reply-mode)
529         (if (and (buffer-modified-p)
530                  (> (buffer-size) 0)
531                  (not (y-or-n-p "Unsent article being composed; erase it? ")))
532             ()
533           (erase-buffer)
534           (if post
535               (news-setup nil subject nil group nil)
536             (save-excursion
537               (set-buffer article-buffer)
538               (goto-char (point-min))
539               (narrow-to-region (point-min)
540                                 (progn (search-forward "\n\n") (point)))
541               (setq from (header-from header))
542               (setq date (header-date header))
543               (and from
544                    (let ((stop-pos 
545                           (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
546                      (setq 
547                       message-of
548                       (concat (if stop-pos (substring from 0 stop-pos) from) 
549                               "'s message of " date))))
550               (setq subject (or subject (header-subject header)))
551               (or (string-match "^[Rr][Ee]:" subject)
552                   (setq subject (concat "Re: " subject)))
553               (setq followup-to (mail-fetch-field "followup-to"))
554               (if (or (null respect-poster) ;Ignore followup-to: field.
555                       (string-equal "" followup-to) ;Bogus header.
556                       (string-equal "poster" followup-to)) ;Poster
557                   (setq followup-to nil))
558               (setq newsgroups
559                     (or follow-to followup-to (mail-fetch-field "newsgroups")))
560               (setq references (header-references header))
561               (setq distribution (mail-fetch-field "distribution"))
562               ;; Remove bogus distribution.
563               (and (stringp distribution)
564                    (string-match "world" distribution)
565                    (setq distribution nil))
566               (setq message-id (header-id header))
567               (widen))
568             (setq news-reply-yank-from from)
569             (setq news-reply-yank-message-id message-id)
570             (news-setup to subject message-of 
571                         (if (stringp newsgroups) newsgroups "") 
572                         article-buffer)
573             (if (and newsgroups (listp newsgroups))
574                 (progn
575                   (goto-char (point-min))
576                   (while newsgroups
577                     (insert (car (car newsgroups)) ": " 
578                             (cdr (car newsgroups)) "\n")
579                     (setq newsgroups (cdr newsgroups)))))
580             ;; Fold long references line to follow RFC1036.
581             (mail-position-on-field "References")
582             (let ((begin (- (point) (length "References: ")))
583                   (fill-column 79)
584                   (fill-prefix "\t"))
585               (if references (insert references))
586               (if (and references message-id) (insert " "))
587               (if message-id (insert message-id))
588               ;; The region must end with a newline to fill the region
589               ;; without inserting extra newline.
590               (fill-region-as-paragraph begin (1+ (point))))
591             (if distribution
592                 (progn
593                   (mail-position-on-field "Distribution")
594                   (insert distribution)))))
595         (current-buffer)))))
596
597 ;;; Internal functions.
598
599 (defun nntp-send-mode-reader ()
600   "Send the MODE READER command to the nntp server.
601 This function is supposed to be called from `nntp-server-opened-hook'.
602 It will make innd servers spawn an nnrpd process to allow actual article
603 reading."
604   (nntp-send-command "^.*\r$" "MODE READER"))
605
606 (defun nntp-send-authinfo ()
607   "Send the AUTHINFO to the nntp server.
608 This function is supposed to be called from `nntp-server-opened-hook'.
609 It will prompt for a password."
610   (nntp-send-command "^.*\r$" "AUTHINFO USER" (user-login-name))
611   (nntp-send-command "^.*\r$" "AUTHINFO PASS" (read-string "NNTP password: ")))
612
613 (defun nntp-default-sentinel (proc status)
614   "Default sentinel function for NNTP server process."
615   (let ((servers nntp-server-alist))
616     ;; Go through the alist of server names and find the name of the
617     ;; server that the process that sent the signal is connected to.
618     ;; If you get my drift.
619     (while (and servers 
620                 (not (equal proc (nth 1 (assq 'nntp-server-process
621                                               (car servers))))))
622       (setq servers (cdr servers)))
623     (message "nntp: Connection closed to server %s." 
624              (or (car (car servers)) "(none)"))
625     (ding)))
626
627 (defun nntp-kill-connection (server)
628   (let ((proc (nth 1 (assq 'nntp-server-process 
629                            (assoc server nntp-server-alist)))))
630     (and proc (delete-process (process-name proc)))
631     (nntp-close-server server)
632     (setq nntp-status-string 
633           (message "Connection timed out to server %s." server))
634     (ding)))
635
636 ;; Encoding and decoding of NNTP text.
637
638 (defun nntp-decode-text ()
639   "Decode text transmitted by NNTP.
640 0. Delete status line.
641 1. Delete `^M' at end of line.
642 2. Delete `.' at end of buffer (end of text mark).
643 3. Delete `.' at beginning of line."
644   (save-excursion
645     (set-buffer nntp-server-buffer)
646     ;; Insert newline at end of buffer.
647     (goto-char (point-max))
648     (or (bolp) (insert "\n"))
649     ;; Delete status line.
650     (goto-char (point-min))
651     (delete-region (point) (progn (forward-line 1) (point)))
652     ;; Delete `^M' at the end of lines.
653     (while (not (eobp))
654       (end-of-line)
655       (and (= (preceding-char) ?\r)
656            (delete-char -1))
657       (forward-line 1))
658     ;; Delete `.' at end of the buffer (end of text mark).
659     (goto-char (point-max))
660     (forward-line -1)
661     (if (looking-at "^\\.$")
662         (delete-region (point) (progn (forward-line 1) (point))))
663     ;; Replace `..' at beginning of line with `.'.
664     (goto-char (point-min))
665     ;; (replace-regexp "^\\.\\." ".")
666     (while (search-forward "\n.." nil t)
667       (delete-char -1))))
668
669 (defun nntp-encode-text ()
670   "Encode text in current buffer for NNTP transmission.
671 1. Insert `.' at beginning of line.
672 2. Insert `.' at end of buffer (end of text mark)."
673   (save-excursion
674     ;; Insert newline at end of buffer.
675     (goto-char (point-max))
676     (or (bolp) (insert "\n"))
677     ;; Replace `.' at beginning of line with `..'.
678     (goto-char (point-min))
679     ;; (replace-regexp "^\\." "..")
680     (while (search-forward "\n." nil t)
681       (insert "."))
682     ;; Insert `.' at end of buffer (end of text mark).
683     (goto-char (point-max))
684     (insert ".\r\n")))
685
686 \f
687 ;;;
688 ;;; Synchronous Communication with NNTP Server.
689 ;;;
690
691 (defun nntp-send-command (response cmd &rest args)
692   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
693   (save-excursion
694     ;; Clear communication buffer.
695     (set-buffer nntp-server-buffer)
696     (erase-buffer)
697     (apply 'nntp-send-strings-to-server cmd args)
698     (if response
699         (nntp-wait-for-response response)
700       t)))
701
702 (defun nntp-wait-for-response (regexp)
703   "Wait for server response which matches REGEXP."
704   (save-excursion
705     (let ((status t)
706           (wait t)
707           (dotnum 0)                    ;Number of "." being displayed.
708           (dotsize                      ;How often "." displayed.
709            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
710       (set-buffer nntp-server-buffer)
711       ;; Wait for status response (RFC977).
712       ;; 1xx - Informative message.
713       ;; 2xx - Command ok.
714       ;; 3xx - Command ok so far, send the rest of it.
715       ;; 4xx - Command was correct, but couldn't be performed for some
716       ;;       reason.
717       ;; 5xx - Command unimplemented, or incorrect, or a serious
718       ;;       program error occurred.
719       (nntp-accept-response)
720       (while wait
721         (goto-char (point-min))
722         (cond ((looking-at "[23]")
723                (setq wait nil))
724               ((looking-at "[45]")
725                (setq status nil)
726                (setq wait nil))
727               (t (nntp-accept-response))))
728       ;; Save status message.
729       (end-of-line)
730       (setq nntp-status-string
731             (buffer-substring (point-min) (point)))
732       (if status
733           (progn
734             (setq wait t)
735             (while wait
736               (goto-char (point-max))
737               (forward-line -1)         ;(beginning-of-line)
738               ;;(message (buffer-substring
739               ;;         (point)
740               ;;         (save-excursion (end-of-line) (point))))
741               (if (looking-at regexp)
742                   (setq wait nil)
743                 (if nntp-debug-read
744                     (let ((newnum (/ (buffer-size) dotsize)))
745                       (if (not (= dotnum newnum))
746                           (progn
747                             (setq dotnum newnum)
748                             (message "NNTP: Reading %s"
749                                      (make-string dotnum ?.))))))
750                 (nntp-accept-response)))
751             ;; Remove "...".
752             (if (and nntp-debug-read (> dotnum 0))
753                 (message ""))
754             ;; Successfully received server response.
755             t)))))
756
757 \f
758 ;;;
759 ;;; Low-Level Interface to NNTP Server.
760 ;;; 
761
762 (defun nntp-retrieve-headers-with-xover (sequence)
763   (if (not nntp-server-xover)
764       ()
765     (let ((range (format "%d-%d" (car sequence)
766                          (nntp-last-element sequence))))
767       (prog1
768           (if (stringp nntp-server-xover)
769               (nntp-send-command "^\\.\r$" nntp-server-xover range)
770             (let ((commands nntp-xover-commands))
771               (while (and commands (eq nntp-server-xover 'try))
772                 (nntp-send-command "^\\.\r$" (car commands) range)
773                 (save-excursion
774                   (set-buffer nntp-server-buffer)
775                   (goto-char 1)
776                   (if (looking-at "[23]") 
777                       (setq nntp-server-xover (car commands))))
778                 (setq commands (cdr commands)))
779               (if (eq nntp-server-xover 'try)
780                   (setq nntp-server-xover nil))
781               nntp-server-xover))
782         (if nntp-server-xover
783             (nntp-decode-text)
784           (erase-buffer))))))
785
786 (defun nntp-send-strings-to-server (&rest strings)
787   "Send list of STRINGS to news server as command and its arguments."
788   (let ((cmd (car strings))
789         (strings (cdr strings)))
790     ;; Command and each argument must be separated by one or more spaces.
791     (while strings
792       (setq cmd (concat cmd " " (car strings)))
793       (setq strings (cdr strings)))
794     ;; Command line must be terminated by a CR-LF.
795     (if (not (nntp-server-opened nntp-current-server))
796         (progn
797           (nntp-close-server nntp-address)
798           (if (not (nntp-open-server nntp-address))
799               (error (nntp-status-message)))
800           (save-excursion
801             (set-buffer nntp-server-buffer)
802             (erase-buffer))))
803     (process-send-string nntp-server-process (concat cmd "\r\n"))))
804
805 (defun nntp-send-region-to-server (begin end)
806   "Send current buffer region (from BEGIN to END) to news server."
807   (save-excursion
808     ;; We have to work in the buffer associated with NNTP server
809     ;;  process because of NEmacs hack.
810     (copy-to-buffer nntp-server-buffer begin end)
811     (set-buffer nntp-server-buffer)
812     (setq begin (point-min))
813     (setq end (point-max))
814     ;; `process-send-region' does not work if text to be sent is very
815     ;;  large. I don't know maximum size of text sent correctly.
816     (let ((last nil)
817           (size 100))                   ;Size of text sent at once.
818       (save-restriction
819         (narrow-to-region begin end)
820         (goto-char begin)
821         (while (not (eobp))
822           ;;(setq last (min end (+ (point) size)))
823           ;; NEmacs gets confused if character at `last' is Kanji.
824           (setq last (save-excursion
825                        (goto-char (min end (+ (point) size)))
826                        (or (eobp) (forward-char 1)) ;Adjust point
827                        (point)))
828           (process-send-region nntp-server-process (point) last)
829           ;; I don't know whether the next codes solve the known
830           ;;  problem of communication error of GNU Emacs.
831           (accept-process-output)
832           ;;(sit-for 0)
833           (goto-char last))))
834     ;; We cannot erase buffer, because reply may be received.
835     (delete-region begin end)))
836
837 (defun nntp-open-server-semi-internal (server &optional service)
838   "Open SERVER.
839 If SERVER is nil, use value of environment variable `NNTPSERVER'.
840 If SERVICE, this this as the port number."
841   (let ((server (or server (getenv "NNTPSERVER")))
842         (status nil)
843         (timer 
844          (and nntp-connection-timeout 
845               (run-at-time nntp-connection-timeout
846                            nil 'nntp-kill-connection server))))
847     (setq nntp-status-string "")
848     (message "nntp: Connecting to server on %s..." server)
849     (cond ((and server (nntp-open-server-internal server service))
850            (setq nntp-address server)
851            (setq status
852                  (condition-case nil
853                      (nntp-wait-for-response "^[23].*\r$")
854                    (error nil)
855                    (quit nil)))
856            (or status (nntp-close-server-internal server))
857            (and nntp-server-process
858                 (progn
859                   (set-process-sentinel 
860                    nntp-server-process 'nntp-default-sentinel)
861                   ;; You can send commands at startup like AUTHINFO here.
862                   ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
863                   (run-hooks 'nntp-server-opened-hook))))
864           ((null server)
865            (setq nntp-status-string "NNTP server is not specified.")))
866     (and timer (cancel-timer timer))
867     (message "")
868     (or status
869         (setq nntp-current-server nil))
870     status))
871
872 (defun nntp-open-server-internal (server &optional service)
873   "Open connection to news server on SERVER by SERVICE (default is nntp)."
874   (let (proc)
875     (save-excursion
876       ;; Use TCP/IP stream emulation package if needed.
877       (or (fboundp 'open-network-stream)
878           (require 'tcp))
879       ;; Initialize communication buffer.
880       (nnheader-init-server-buffer)
881       (set-buffer nntp-server-buffer)
882       (if (setq proc
883                 (condition-case nil
884                     (funcall nntp-open-server-function server)
885                   (error nil)))
886           (progn
887             (setq nntp-server-process proc)
888             ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
889             (process-kill-without-query proc)
890             (setq nntp-address server)
891             ;; It is possible to change kanji-fileio-code in this hook.
892             (run-hooks 'nntp-server-hook)
893             nntp-server-process)))))
894
895 (defun nntp-open-network-stream (server)
896   (open-network-stream "nntpd" nntp-server-buffer server nntp-port-number))
897
898 (defun nntp-open-rlogin-stream (server)
899   (apply 'start-process "nntpd" nntp-server-buffer "rsh" 
900          "-l" (or nntp-rlogin-user-name (user-login-name))
901          server nntp-rlogin-parameters))
902
903 (defun nntp-close-server-internal (&optional server)
904   "Close connection to news server."
905   (nntp-possibly-change-server nil server)
906   (if nntp-server-process
907       (delete-process nntp-server-process))
908   (setq nntp-server-process nil)
909   (setq nntp-address ""))
910
911 (defun nntp-accept-response ()
912   "Read response of server.
913 It is well-known that the communication speed will be much improved by
914 defining this function as macro."
915   ;; To deal with server process exiting before
916   ;;  accept-process-output is called.
917   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
918   ;; This is a copy of `nntp-default-sentinel'.
919   (if (or (not nntp-server-process)
920           (not (memq (process-status nntp-server-process) '(open run))))
921       (error "nntp: Process connection closed; %s" (nntp-status-message))
922     (if nntp-buggy-select
923         (progn
924           ;; We cannot use `accept-process-output'.
925           ;; Fujitsu UTS requires messages during sleep-for. I don't know why.
926           (message "NNTP: Reading...")
927           (sleep-for 1)
928           (message ""))
929       (condition-case errorcode
930           (accept-process-output nntp-server-process)
931         (error
932          (cond ((string-equal "select error: Invalid argument" 
933                               (nth 1 errorcode))
934                 ;; Ignore select error.
935                 nil)
936                (t
937                 (signal (car errorcode) (cdr errorcode)))))))))
938
939 (defun nntp-last-element (list)
940   "Return last element of LIST."
941   (while (cdr list)
942     (setq list (cdr list)))
943   (car list))
944
945 (defun nntp-possibly-change-server (newsgroup server)
946   (let ((result t))
947     ;; We see whether it is necessary to change newsgroup.
948     (and newsgroup 
949          (or (not (string= newsgroup nntp-current-group)))
950          (progn
951            (setq result (nntp-request-group newsgroup server))
952            (setq nntp-current-group newsgroup)))
953     result))
954
955 (defun nntp-try-list-active (group)
956   (nntp-list-active-group group)
957   (save-excursion
958     (set-buffer nntp-server-buffer)
959     (goto-char (point-min))
960     (cond ((looking-at "5[0-9]+")
961            (setq nntp-server-list-active-group nil))
962           (t
963            (setq nntp-server-list-active-group t)))))
964
965 (provide 'nntp)
966
967 ;;; nntp.el ends here