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