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