*** 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 t)
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 t)
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 "HEAD" (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         ;; Wait for the reply from the final command.
276         (goto-char (point-max))
277         (re-search-backward "^[0-9]" nil t)
278         (if (looking-at "^[23]")
279             (while (progn
280                      (goto-char (- (point-max) 3))
281                      (not (looking-at "^\\.\r$")))
282               (nntp-accept-response)))
283
284         ;; Now all replies are received. We remove CRs.
285         (goto-char (point-min))
286         (while (search-forward "\r" nil t)
287           (replace-match ""))
288
289         (if nntp-server-list-active-group
290             (progn
291               ;; We have read active entries, so we just delete the
292               ;; superfluos gunk.
293               (goto-char (point-min))
294               (while (re-search-forward "^[\\.234]" nil t)
295                 (delete-region (match-beginning 0) 
296                                (progn (forward-line 1) (point))))
297               'active)
298           'group))))
299
300 (defun nntp-open-server (server &optional defs)
301   (nnheader-init-server-buffer)
302   (if (nntp-server-opened server)
303       t
304     (if (or (stringp (car defs))
305             (numberp (car defs)))
306         (setq defs (cons (list 'nntp-server-port (car defs)) (cdr defs))))
307     (or (assq 'nntp-address defs)
308         (setq defs (append defs (list (list 'nntp-address server)))))
309     (if (and nntp-current-server
310              (not (equal server nntp-current-server)))
311         (setq nntp-server-alist 
312               (cons (list nntp-current-server
313                           (nnheader-save-variables nntp-server-variables))
314                     nntp-server-alist)))
315     (let ((state (assoc server nntp-server-alist)))
316       (if state 
317           (progn
318             (nnheader-restore-variables (nth 1 state))
319             (setq nntp-server-alist (delq state nntp-server-alist)))
320         (nnheader-set-init-variables nntp-server-variables defs)))
321     (setq nntp-current-server server)
322     (run-hooks 'nntp-prepare-server-hook)
323     (nntp-open-server-semi-internal nntp-address)))
324
325 (defun nntp-close-server (&optional server)
326   "Close connection to SERVER."
327   (nntp-possibly-change-server nil server)
328   (unwind-protect
329       (progn
330         ;; Un-set default sentinel function before closing connection.
331         (and nntp-server-process
332              (eq 'nntp-default-sentinel
333                  (process-sentinel nntp-server-process))
334              (set-process-sentinel nntp-server-process nil))
335         ;; We cannot send QUIT command unless the process is running.
336         (if (nntp-server-opened)
337             (nntp-send-command nil "QUIT")))
338     (nntp-close-server-internal server)))
339
340 (fset 'nntp-request-quit (symbol-function 'nntp-close-server))
341
342 (defun nntp-request-close ()
343   "Close all server connections."
344   (let (proc)
345     (while nntp-server-alist
346       (setq proc (nth 1 (assq 'nntp-server-process (car nntp-server-alist))))
347       (and proc (delete-process proc))
348       (setq nntp-server-alist (cdr nntp-server-alist)))
349     (setq nntp-current-server nil)))
350
351 (defun nntp-server-opened (&optional server)
352   "Say whether a connection to SERVER has been opened."
353   (and (equal server nntp-current-server)
354        nntp-server-buffer
355        (buffer-name nntp-server-buffer)
356        nntp-server-process
357        (memq (process-status nntp-server-process) '(open run))))
358
359 (defun nntp-status-message (&optional server)
360   "Return server status as a string."
361   (if (and nntp-status-string
362            ;; NNN MESSAGE
363            (string-match "[0-9][0-9][0-9][ \t]+\\([^\r]*\\).*$"
364                          nntp-status-string))
365       (substring nntp-status-string (match-beginning 1) (match-end 1))
366     ;; Empty message if nothing.
367     nntp-status-string))
368
369 (defun nntp-request-article (id &optional newsgroup server buffer)
370   "Request article ID (message-id or number)."
371   (nntp-possibly-change-server newsgroup server)
372   (unwind-protect
373       (progn
374         (if buffer (set-process-buffer nntp-server-process buffer))
375         (let ((nntp-server-buffer (or buffer nntp-server-buffer))
376               (id (or (and (numberp id) (int-to-string id)) id)))
377           ;; If NEmacs, end of message may look like: "\256\215" (".^M")
378           (prog1
379               (nntp-send-command "^\\.\r$" "ARTICLE" id)
380             (nntp-decode-text))))
381     (if buffer (set-process-buffer nntp-server-process nntp-server-buffer))))
382
383 (defun nntp-request-body (id &optional newsgroup server)
384   "Request body of article ID (message-id or number)."
385   (nntp-possibly-change-server newsgroup server)
386   (prog1
387       ;; If NEmacs, end of message may look like: "\256\215" (".^M")
388       (nntp-send-command
389        "^\\.\r$" "BODY" (or (and (numberp id) (int-to-string id)) id))
390     (nntp-decode-text)))
391
392 (defun nntp-request-head (id &optional newsgroup server)
393   "Request head of article ID (message-id or number)."
394   (nntp-possibly-change-server newsgroup server)
395   (prog1
396       (nntp-send-command 
397        "^\\.\r$" "HEAD" (or (and (numberp id) (int-to-string id)) id))
398     (nntp-decode-text)))
399
400 (defun nntp-request-stat (id &optional newsgroup server)
401   "Request STAT of article ID (message-id or number)."
402   (nntp-possibly-change-server newsgroup server)
403   (nntp-send-command 
404    "^[23].*\r$" "STAT" (or (and (numberp id) (int-to-string id)) id)))
405
406 (defun nntp-request-group (group &optional server dont-check)
407   "Select GROUP."
408   (if dont-check
409       (nntp-send-command "^.*\r$" "GROUP" group)
410     (cond ((eq nntp-server-list-active-group 'try)
411            (or (nntp-try-list-active group)
412                (nntp-send-command "^.*\r$" "GROUP" group)))
413           (nntp-server-list-active-group
414            (nntp-list-active-group group))
415           (t
416            (nntp-send-command "^.*\r$" "GROUP" group)))
417     (if nntp-server-list-active-group
418         (save-excursion
419           (set-buffer nntp-server-buffer)
420           (goto-char (point-min))
421           (forward-line 1)
422           (if (looking-at "[^ ]+[ \t]+\\([0-9]\\)[ \t]+\\([0-9]\\)")
423               (let ((end (progn (goto-char (match-beginning 1))
424                                 (read (current-buffer))))
425                     (beg (read (current-buffer))))
426                 (and (> beg end)
427                      (setq end 0
428                            beg 0))
429                 (erase-buffer)
430                 (insert (format "211 %s %d %d %d\n"
431                                 group (max (- (1+ end) beg) 0)
432                                 beg end))))))
433     (save-excursion
434       (set-buffer nntp-server-buffer)
435       (goto-char (point-min))
436       (looking-at "[23]"))))
437
438 (defun nntp-list-active-group (group &optional server)
439   (nntp-send-command "^.*\r$" "LIST ACTIVE" group))
440
441 (defun nntp-request-group-description (group &optional server)
442   "Get description of GROUP."
443   (if (nntp-possibly-change-server nil server)
444       (prog1
445           (nntp-send-command "^.*\r$" "XGTITLE" group)
446         (nntp-decode-text))))
447
448 (defun nntp-close-group (group &optional server)
449   t)
450
451 (defun nntp-request-list (&optional server)
452   "List active groups."
453   (nntp-possibly-change-server nil server)
454   (prog1
455       (nntp-send-command "^\\.\r$" "LIST")
456     (nntp-decode-text)))
457
458 (defun nntp-request-list-newsgroups (&optional server)
459   "List groups."
460   (nntp-possibly-change-server nil server)
461   (prog1
462       (nntp-send-command "^\\.\r$" "LIST NEWSGROUPS")
463     (nntp-decode-text)))
464
465 (defun nntp-request-newgroups (date &optional server)
466   "List new groups."
467   (nntp-possibly-change-server nil server)
468   (let* ((date (timezone-parse-date date))
469          (time-string
470           (format "%s%02d%02d %s%s%s"
471                   (substring (aref date 0) 2) (string-to-int (aref date 1)) 
472                   (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
473                   (substring 
474                    (aref date 3) 3 5) (substring (aref date 3) 6 8))))
475     (prog1
476         (nntp-send-command "^\\.\r$" "NEWGROUPS" time-string)
477       (nntp-decode-text))))
478
479 (defun nntp-request-list-distributions (&optional server)
480   "List distributions."
481   (nntp-possibly-change-server nil server)
482   (prog1
483       (nntp-send-command "^\\.\r$" "LIST DISTRIBUTIONS")
484     (nntp-decode-text)))
485
486 (defun nntp-request-last (&optional newsgroup server)
487   "Decrease the current article pointer."
488   (nntp-possibly-change-server newsgroup server)
489   (nntp-send-command "^[23].*\r$" "LAST"))
490
491 (defun nntp-request-next (&optional newsgroup server)
492   "Advance the current article pointer."
493   (nntp-possibly-change-server newsgroup server)
494   (nntp-send-command "^[23].*\r$" "NEXT"))
495
496 (defun nntp-request-post (&optional server)
497   "Post the current buffer."
498   (nntp-possibly-change-server nil server)
499   (if (nntp-send-command "^[23].*\r$" "POST")
500       (progn
501         (nntp-encode-text)
502         (nntp-send-region-to-server (point-min) (point-max))
503         ;; 1.2a NNTP's post command is buggy. "^M" (\r) is not
504         ;;  appended to end of the status message.
505         (nntp-wait-for-response "^[23].*$"))))
506
507 (defun nntp-request-post-buffer 
508   (post group subject header article-buffer info follow-to respect-poster)
509   "Request a buffer suitable for composing an article.
510 If POST, this is an original article; otherwise it's a followup.
511 GROUP is the group to be posted to, the article should have subject
512 SUBJECT.  HEADER is a Gnus header vector.  ARTICLE-BUFFER contains the
513 article being followed up.  INFO is a Gnus info list.  If FOLLOW-TO,
514 post to this group instead.  If RESPECT-POSTER, heed the special
515 \"poster\" value of the Followup-to header."
516   (if (assq 'to-address (nth 4 info))
517       (nnmail-request-post-buffer 
518        post group subject header article-buffer info follow-to respect-poster)
519     (let ((mail-default-headers 
520            (or nntp-news-default-headers mail-default-headers))
521           from date to followup-to newsgroups message-of
522           references distribution message-id)
523       (save-excursion
524         (set-buffer (get-buffer-create "*post-news*"))
525         (news-reply-mode)
526         (if (and (buffer-modified-p)
527                  (> (buffer-size) 0)
528                  (not (y-or-n-p "Unsent article being composed; erase it? ")))
529             ()
530           (erase-buffer)
531           (if post
532               (news-setup nil subject nil group nil)
533             (save-excursion
534               (set-buffer article-buffer)
535               (goto-char (point-min))
536               (narrow-to-region (point-min)
537                                 (progn (search-forward "\n\n") (point)))
538               (setq from (header-from header))
539               (setq date (header-date header))
540               (and from
541                    (let ((stop-pos 
542                           (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
543                      (setq 
544                       message-of
545                       (concat (if stop-pos (substring from 0 stop-pos) from) 
546                               "'s message of " date))))
547               (setq subject (or subject (header-subject header)))
548               (or (string-match "^[Rr][Ee]:" subject)
549                   (setq subject (concat "Re: " subject)))
550               (setq followup-to (mail-fetch-field "followup-to"))
551               (if (or (null respect-poster) ;Ignore followup-to: field.
552                       (string-equal "" followup-to) ;Bogus header.
553                       (string-equal "poster" followup-to)) ;Poster
554                   (setq followup-to nil))
555               (setq newsgroups
556                     (or follow-to followup-to (mail-fetch-field "newsgroups")))
557               (setq references (header-references header))
558               (setq distribution (mail-fetch-field "distribution"))
559               ;; Remove bogus distribution.
560               (and (stringp distribution)
561                    (string-match "world" distribution)
562                    (setq distribution nil))
563               (setq message-id (header-id header))
564               (widen))
565             (setq news-reply-yank-from from)
566             (setq news-reply-yank-message-id message-id)
567             (news-setup to subject message-of 
568                         (if (stringp newsgroups) newsgroups "") 
569                         article-buffer)
570             (if (and newsgroups (listp newsgroups))
571                 (progn
572                   (goto-char (point-min))
573                   (while newsgroups
574                     (insert (car (car newsgroups)) ": " 
575                             (cdr (car newsgroups)) "\n")
576                     (setq newsgroups (cdr newsgroups)))))
577             ;; Fold long references line to follow RFC1036.
578             (mail-position-on-field "References")
579             (let ((begin (- (point) (length "References: ")))
580                   (fill-column 79)
581                   (fill-prefix "\t"))
582               (if references (insert references))
583               (if (and references message-id) (insert " "))
584               (if message-id (insert message-id))
585               ;; The region must end with a newline to fill the region
586               ;; without inserting extra newline.
587               (fill-region-as-paragraph begin (1+ (point))))
588             (if distribution
589                 (progn
590                   (mail-position-on-field "Distribution")
591                   (insert distribution)))))
592         (current-buffer)))))
593
594 ;;; Internal functions.
595
596 (defun nntp-send-mode-reader ()
597   "Send the MODE READER command to the nntp server.
598 This function is supposed to be called from `nntp-server-opened-hook'.
599 It will make innd servers spawn an nnrpd process to allow actual article
600 reading."
601   (nntp-send-command "^.*\r$" "MODE READER"))
602
603 (defun nntp-send-authinfo ()
604   "Send the AUTHINFO to the nntp server.
605 This function is supposed to be called from `nntp-server-opened-hook'.
606 It will prompt for a password."
607   (nntp-send-command "^.*\r$" "AUTHINFO USER" (user-login-name))
608   (nntp-send-command "^.*\r$" "AUTHINFO PASS" (read-string "NNTP password: ")))
609
610 (defun nntp-default-sentinel (proc status)
611   "Default sentinel function for NNTP server process."
612   (let ((servers nntp-server-alist))
613     ;; Go through the alist of server names and find the name of the
614     ;; server that the process that sent the signal is connected to.
615     ;; If you get my drift.
616     (while (and servers 
617                 (not (equal proc (nth 1 (assq 'nntp-server-process
618                                               (car servers))))))
619       (setq servers (cdr servers)))
620     (message "nntp: Connection closed to server %s." 
621              (or (car (car servers)) "(none)"))
622     (ding)))
623
624 (defun nntp-kill-connection (server)
625   (let ((proc (nth 1 (assq 'nntp-server-process 
626                            (assoc server nntp-server-alist)))))
627     (and proc (delete-process (process-name proc)))
628     (nntp-close-server server)
629     (setq nntp-status-string 
630           (message "Connection timed out to server %s." server))
631     (ding)))
632
633 ;; Encoding and decoding of NNTP text.
634
635 (defun nntp-decode-text ()
636   "Decode text transmitted by NNTP.
637 0. Delete status line.
638 1. Delete `^M' at end of line.
639 2. Delete `.' at end of buffer (end of text mark).
640 3. Delete `.' at beginning of line."
641   (save-excursion
642     (set-buffer nntp-server-buffer)
643     ;; Insert newline at end of buffer.
644     (goto-char (point-max))
645     (or (bolp) (insert "\n"))
646     ;; Delete status line.
647     (goto-char (point-min))
648     (delete-region (point) (progn (forward-line 1) (point)))
649     ;; Delete `^M' at the end of lines.
650     (while (not (eobp))
651       (end-of-line)
652       (and (= (preceding-char) ?\r)
653            (delete-char -1))
654       (forward-line 1))
655     ;; Delete `.' at end of the buffer (end of text mark).
656     (goto-char (point-max))
657     (forward-line -1)
658     (if (looking-at "^\\.$")
659         (delete-region (point) (progn (forward-line 1) (point))))
660     ;; Replace `..' at beginning of line with `.'.
661     (goto-char (point-min))
662     ;; (replace-regexp "^\\.\\." ".")
663     (while (search-forward "\n.." nil t)
664       (delete-char -1))))
665
666 (defun nntp-encode-text ()
667   "Encode text in current buffer for NNTP transmission.
668 1. Insert `.' at beginning of line.
669 2. Insert `.' at end of buffer (end of text mark)."
670   (save-excursion
671     ;; Insert newline at end of buffer.
672     (goto-char (point-max))
673     (or (bolp) (insert "\n"))
674     ;; Replace `.' at beginning of line with `..'.
675     (goto-char (point-min))
676     ;; (replace-regexp "^\\." "..")
677     (while (search-forward "\n." nil t)
678       (insert "."))
679     ;; Insert `.' at end of buffer (end of text mark).
680     (goto-char (point-max))
681     (insert ".\r\n")))
682
683 \f
684 ;;;
685 ;;; Synchronous Communication with NNTP Server.
686 ;;;
687
688 (defun nntp-send-command (response cmd &rest args)
689   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
690   (save-excursion
691     ;; Clear communication buffer.
692     (set-buffer nntp-server-buffer)
693     (erase-buffer)
694     (apply 'nntp-send-strings-to-server cmd args)
695     (if response
696         (nntp-wait-for-response response)
697       t)))
698
699 (defun nntp-wait-for-response (regexp)
700   "Wait for server response which matches REGEXP."
701   (save-excursion
702     (let ((status t)
703           (wait t)
704           (dotnum 0)                    ;Number of "." being displayed.
705           (dotsize                      ;How often "." displayed.
706            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
707       (set-buffer nntp-server-buffer)
708       ;; Wait for status response (RFC977).
709       ;; 1xx - Informative message.
710       ;; 2xx - Command ok.
711       ;; 3xx - Command ok so far, send the rest of it.
712       ;; 4xx - Command was correct, but couldn't be performed for some
713       ;;       reason.
714       ;; 5xx - Command unimplemented, or incorrect, or a serious
715       ;;       program error occurred.
716       (nntp-accept-response)
717       (while wait
718         (goto-char (point-min))
719         (cond ((looking-at "[23]")
720                (setq wait nil))
721               ((looking-at "[45]")
722                (setq status nil)
723                (setq wait nil))
724               (t (nntp-accept-response))))
725       ;; Save status message.
726       (end-of-line)
727       (setq nntp-status-string
728             (buffer-substring (point-min) (point)))
729       (if status
730           (progn
731             (setq wait t)
732             (while wait
733               (goto-char (point-max))
734               (forward-line -1)         ;(beginning-of-line)
735               ;;(message (buffer-substring
736               ;;         (point)
737               ;;         (save-excursion (end-of-line) (point))))
738               (if (looking-at regexp)
739                   (setq wait nil)
740                 (if nntp-debug-read
741                     (let ((newnum (/ (buffer-size) dotsize)))
742                       (if (not (= dotnum newnum))
743                           (progn
744                             (setq dotnum newnum)
745                             (message "NNTP: Reading %s"
746                                      (make-string dotnum ?.))))))
747                 (nntp-accept-response)))
748             ;; Remove "...".
749             (if (and nntp-debug-read (> dotnum 0))
750                 (message ""))
751             ;; Successfully received server response.
752             t)))))
753
754 \f
755 ;;;
756 ;;; Low-Level Interface to NNTP Server.
757 ;;; 
758
759 (defun nntp-retrieve-headers-with-xover (sequence)
760   (if (not nntp-server-xover)
761       ()
762     (let ((range (format "%d-%d" (car sequence)
763                          (nntp-last-element sequence))))
764       (prog1
765           (if (stringp nntp-server-xover)
766               (nntp-send-command "^\\.\r$" nntp-server-xover range)
767             (let ((commands nntp-xover-commands))
768               (while (and commands
769                           (eq t nntp-server-xover))
770                 (nntp-send-command "^\\.\r$" (car commands) range)
771                 (save-excursion
772                   (set-buffer nntp-server-buffer)
773                   (goto-char 1)
774                   (if (looking-at "[23]") 
775                       (setq nntp-server-xover (car commands))))
776                 (setq commands (cdr commands)))
777               (if (eq t nntp-server-xover)
778                   (setq nntp-server-xover nil))
779               nntp-server-xover))
780         (if nntp-server-xover (nntp-decode-text) (erase-buffer))))))
781
782 (defun nntp-send-strings-to-server (&rest strings)
783   "Send list of STRINGS to news server as command and its arguments."
784   (let ((cmd (car strings))
785         (strings (cdr strings)))
786     ;; Command and each argument must be separated by one or more spaces.
787     (while strings
788       (setq cmd (concat cmd " " (car strings)))
789       (setq strings (cdr strings)))
790     ;; Command line must be terminated by a CR-LF.
791     (if (not (nntp-server-opened nntp-current-server))
792         (progn
793           (nntp-close-server nntp-address)
794           (if (not (nntp-open-server nntp-address))
795               (error (nntp-status-message)))
796           (save-excursion
797             (set-buffer nntp-server-buffer)
798             (erase-buffer))))
799     (process-send-string nntp-server-process (concat cmd "\r\n"))))
800
801 (defun nntp-send-region-to-server (begin end)
802   "Send current buffer region (from BEGIN to END) to news server."
803   (save-excursion
804     ;; We have to work in the buffer associated with NNTP server
805     ;;  process because of NEmacs hack.
806     (copy-to-buffer nntp-server-buffer begin end)
807     (set-buffer nntp-server-buffer)
808     (setq begin (point-min))
809     (setq end (point-max))
810     ;; `process-send-region' does not work if text to be sent is very
811     ;;  large. I don't know maximum size of text sent correctly.
812     (let ((last nil)
813           (size 100))                   ;Size of text sent at once.
814       (save-restriction
815         (narrow-to-region begin end)
816         (goto-char begin)
817         (while (not (eobp))
818           ;;(setq last (min end (+ (point) size)))
819           ;; NEmacs gets confused if character at `last' is Kanji.
820           (setq last (save-excursion
821                        (goto-char (min end (+ (point) size)))
822                        (or (eobp) (forward-char 1)) ;Adjust point
823                        (point)))
824           (process-send-region nntp-server-process (point) last)
825           ;; I don't know whether the next codes solve the known
826           ;;  problem of communication error of GNU Emacs.
827           (accept-process-output)
828           ;;(sit-for 0)
829           (goto-char last))))
830     ;; We cannot erase buffer, because reply may be received.
831     (delete-region begin end)))
832
833 (defun nntp-open-server-semi-internal (server &optional service)
834   "Open SERVER.
835 If SERVER is nil, use value of environment variable `NNTPSERVER'.
836 If SERVICE, this this as the port number."
837   (let ((server (or server (getenv "NNTPSERVER")))
838         (status nil)
839         (timer 
840          (and nntp-connection-timeout 
841               (run-at-time nntp-connection-timeout
842                            nil 'nntp-kill-connection server))))
843     (setq nntp-status-string "")
844     (message "nntp: Connecting to server on %s..." server)
845     (cond ((and server (nntp-open-server-internal server service))
846            (setq nntp-address server)
847            (setq status
848                  (condition-case nil
849                      (nntp-wait-for-response "^[23].*\r$")
850                    (error nil)
851                    (quit nil)))
852            (or status (nntp-close-server-internal server))
853            (and nntp-server-process
854                 (progn
855                   (set-process-sentinel 
856                    nntp-server-process 'nntp-default-sentinel)
857                   ;; You can send commands at startup like AUTHINFO here.
858                   ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
859                   (run-hooks 'nntp-server-opened-hook))))
860           ((null server)
861            (setq nntp-status-string "NNTP server is not specified.")))
862     (and timer (cancel-timer timer))
863     (message "")
864     (or status
865         (setq nntp-current-server nil))
866     status))
867
868 (defun nntp-open-server-internal (server &optional service)
869   "Open connection to news server on SERVER by SERVICE (default is nntp)."
870   (let (proc)
871     (save-excursion
872       ;; Use TCP/IP stream emulation package if needed.
873       (or (fboundp 'open-network-stream)
874           (require 'tcp))
875       ;; Initialize communication buffer.
876       (nnheader-init-server-buffer)
877       (set-buffer nntp-server-buffer)
878       (if (setq proc
879                 (condition-case nil
880                     (funcall nntp-open-server-function server)
881                   (error nil)))
882           (progn
883             (setq nntp-server-process proc)
884             ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
885             (process-kill-without-query proc)
886             (setq nntp-server-xover t)
887             (setq nntp-server-list-active-group t)
888             (setq nntp-address server)
889             ;; It is possible to change kanji-fileio-code in this hook.
890             (run-hooks 'nntp-server-hook)
891             nntp-server-process)))))
892
893 (defun nntp-open-network-stream (server)
894   (open-network-stream "nntpd" nntp-server-buffer server nntp-port-number))
895
896 (defun nntp-open-rlogin-stream (server)
897   (apply 'start-process "nntpd" nntp-server-buffer "rsh" 
898          "-l" (or nntp-rlogin-user-name (user-login-name))
899          server nntp-rlogin-parameters))
900
901 (defun nntp-close-server-internal (&optional server)
902   "Close connection to news server."
903   (nntp-possibly-change-server nil server)
904   (if nntp-server-process
905       (delete-process nntp-server-process))
906   (setq nntp-server-process nil)
907   (setq nntp-address ""))
908
909 (defun nntp-accept-response ()
910   "Read response of server.
911 It is well-known that the communication speed will be much improved by
912 defining this function as macro."
913   ;; To deal with server process exiting before
914   ;;  accept-process-output is called.
915   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
916   ;; This is a copy of `nntp-default-sentinel'.
917   (if (or (not nntp-server-process)
918           (not (memq (process-status nntp-server-process) '(open run))))
919       (error "nntp: Process connection closed; %s" (nntp-status-message))
920     (if nntp-buggy-select
921         (progn
922           ;; We cannot use `accept-process-output'.
923           ;; Fujitsu UTS requires messages during sleep-for. I don't know why.
924           (message "NNTP: Reading...")
925           (sleep-for 1)
926           (message ""))
927       (condition-case errorcode
928           (accept-process-output nntp-server-process)
929         (error
930          (cond ((string-equal "select error: Invalid argument" 
931                               (nth 1 errorcode))
932                 ;; Ignore select error.
933                 nil)
934                (t
935                 (signal (car errorcode) (cdr errorcode)))))))))
936
937 (defun nntp-last-element (list)
938   "Return last element of LIST."
939   (while (cdr list)
940     (setq list (cdr list)))
941   (car list))
942
943 (defun nntp-possibly-change-server (newsgroup server)
944   (let ((result t))
945     ;; We see whether it is necessary to change newsgroup.
946     (and newsgroup 
947          (or (not (string= newsgroup nntp-current-group)))
948          (progn
949            (setq result (nntp-request-group newsgroup server))
950            (setq nntp-current-group newsgroup)))
951     result))
952
953 (defun nntp-try-list-active (group)
954   (nntp-list-active-group group)
955   (save-excursion
956     (set-buffer nntp-server-buffer)
957     (goto-char (point-min))
958     (cond ((looking-at "5[0-9]+")
959            (setq nntp-server-list-active-group nil))
960           (t
961            (setq nntp-server-list-active-group t)))))
962
963 (provide 'nntp)
964
965 ;;; nntp.el ends here