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