*** 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 "^\\.\r?\n" "ARTICLE" art)
507                        (if (numberp id) 
508                            (cons nntp-current-group id)
509                          ;; We find out what the article number was.
510                          (nntp-find-group-and-number)))
511                 (nntp-decode-text)
512                 (and nntp-async-articles (nntp-async-fetch-articles id)))))
513         (when buffer 
514           (set-process-buffer nntp-server-process nntp-server-buffer))))))
515
516 (defun nntp-request-body (id &optional group server)
517   "Request body of article ID (Message-ID or number)."
518   (nntp-possibly-change-server group server)
519   (prog1
520       ;; If NEmacs, end of message may look like: "\256\215" (".^M")
521       (nntp-send-command
522        "^\\.\r?\n" "BODY" (or (and (numberp id) (int-to-string id)) id))
523     (nntp-decode-text)))
524
525 (defun nntp-request-head (id &optional group server)
526   "Request head of article ID (Message-ID or number)."
527   (nntp-possibly-change-server group server)
528   (prog1
529       (when (nntp-send-command 
530              "^\\.\r?\n" "HEAD" (if (numberp id) (int-to-string id) id))
531         (if (numberp id) id
532           ;; We find out what the article number was.
533           (nntp-find-group-and-number)))
534     (nntp-decode-text)))
535
536 (defun nntp-request-stat (id &optional group server)
537   "Request STAT of article ID (Message-ID or number)."
538   (nntp-possibly-change-server group server)
539   (nntp-send-command 
540    "^[23].*\r?\n" "STAT" (or (and (numberp id) (int-to-string id)) id)))
541
542 (defun nntp-request-type (group &optional article)
543   'news)
544
545 (defun nntp-request-group (group &optional server dont-check)
546   "Select GROUP."
547   (nntp-possibly-change-server nil server)
548   (setq nntp-current-group
549         (when (nntp-send-command "^2.*\r?\n" "GROUP" group)
550           group)))
551
552 (defun nntp-request-asynchronous (group &optional server articles)
553   "Enable pre-fetch in GROUP."
554   (when nntp-async-articles
555     (nntp-async-request-group group))
556   (when nntp-async-number
557     (if (not (or (nntp-async-server-opened)
558                  (nntp-async-open-server)))
559         ;; Couldn't open the second connection
560         (progn
561           (message "Can't open second connection to %s" nntp-address)
562           (ding)
563           (setq nntp-async-articles nil)
564           (sit-for 2))
565       ;; We opened the second connection (or it was opened already).  
566       (setq nntp-async-articles articles)
567       (setq nntp-async-fetched nil)
568       ;; Clear any old data.
569       (save-excursion
570         (set-buffer nntp-async-buffer)
571         (erase-buffer))
572       ;; Select the correct current group on this server.
573       (nntp-async-send-strings "GROUP" group)
574       t)))
575
576 (defun nntp-list-active-group (group &optional server)
577   "Return the active info on GROUP (which can be a regexp."
578   (nntp-possibly-change-server group server)
579   (nntp-send-command "^.*\r?\n" "LIST ACTIVE" group))
580
581 (defun nntp-request-group-description (group &optional server)
582   "Get the description of GROUP."
583   (nntp-possibly-change-server nil server)
584   (prog1
585       (nntp-send-command "^.*\r?\n" "XGTITLE" group)
586     (nntp-decode-text)))
587
588 (defun nntp-close-group (group &optional server)
589   "Close GROUP."
590   (setq nntp-current-group nil)
591   t)
592
593 (defun nntp-request-list (&optional server)
594   "List all active groups."
595   (nntp-possibly-change-server nil server)
596   (prog1
597       (nntp-send-command "^\\.\r?\n" "LIST")
598     (nntp-decode-text)))
599
600 (defun nntp-request-list-newsgroups (&optional server)
601   "Get descriptions on all groups on SERVER."
602   (nntp-possibly-change-server nil server)
603   (prog1
604       (nntp-send-command "^\\.\r?\n" "LIST NEWSGROUPS")
605     (nntp-decode-text)))
606
607 (defun nntp-request-newgroups (date &optional server)
608   "List groups that have arrived since DATE."
609   (nntp-possibly-change-server nil server)
610   (let* ((date (timezone-parse-date date))
611          (time-string
612           (format "%s%02d%02d %s%s%s"
613                   (substring (aref date 0) 2) (string-to-int (aref date 1)) 
614                   (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
615                   (substring 
616                    (aref date 3) 3 5) (substring (aref date 3) 6 8))))
617     (prog1
618         (nntp-send-command "^\\.\r?\n" "NEWGROUPS" time-string)
619       (nntp-decode-text))))
620
621 (defun nntp-request-list-distributions (&optional server)
622   "List distributions."
623   (nntp-possibly-change-server nil server)
624   (prog1
625       (nntp-send-command "^\\.\r?\n" "LIST DISTRIBUTIONS")
626     (nntp-decode-text)))
627
628 (defun nntp-request-last (&optional group server)
629   "Decrease the current article pointer."
630   (nntp-possibly-change-server group server)
631   (nntp-send-command "^[23].*\r?\n" "LAST"))
632
633 (defun nntp-request-next (&optional group server)
634   "Advance the current article pointer."
635   (nntp-possibly-change-server group server)
636   (nntp-send-command "^[23].*\r?\n" "NEXT"))
637
638 (defun nntp-request-post (&optional server)
639   "Post the current buffer."
640   (nntp-possibly-change-server nil server)
641   (when (nntp-send-command "^[23].*\r?\n" "POST")
642     (nnheader-insert "")
643     (nntp-encode-text)
644     (nntp-send-region-to-server (point-min) (point-max))
645     ;; 1.2a NNTP's post command is buggy. "^M" (\r) is not
646     ;;  appended to end of the status message.
647     (nntp-wait-for-response "^[23].*\n")))
648
649 ;;; Internal functions.
650
651 (defun nntp-send-mode-reader ()
652   "Send the MODE READER command to the nntp server.
653 This function is supposed to be called from `nntp-server-opened-hook'.
654 It will make innd servers spawn an nnrpd process to allow actual article
655 reading."
656   (nntp-send-command "^.*\r?\n" "MODE READER"))
657
658 (defun nntp-send-nosy-authinfo ()
659   "Send the AUTHINFO to the nntp server.
660 This function is supposed to be called from `nntp-server-opened-hook'.
661 It will prompt for a password."
662   (nntp-send-command "^.*\r?\n" "AUTHINFO USER"
663                      (read-string "NNTP user name: "))
664   (nntp-send-command "^.*\r?\n" "AUTHINFO PASS" 
665                      (read-string "NNTP password: ")))
666
667 (defun nntp-send-authinfo ()
668   "Send the AUTHINFO to the nntp server.
669 This function is supposed to be called from `nntp-server-opened-hook'.
670 It will prompt for a password."
671   (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
672   (nntp-send-command "^.*\r?\n" "AUTHINFO PASS" 
673                      (read-string "NNTP password: ")))
674
675 (defun nntp-send-authinfo-from-file ()
676   "Send the AUTHINFO to the nntp server.
677 This function is supposed to be called from `nntp-server-opened-hook'.
678 It will prompt for a password."
679   (when (file-exists-p "~/.nntp-authinfo")
680     (save-excursion
681       (set-buffer (get-buffer-create " *authinfo*"))
682       (buffer-disable-undo (current-buffer))
683       (erase-buffer)
684       (insert-file-contents "~/.nntp-authinfo")
685       (goto-char (point-min))
686       (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
687       (nntp-send-command 
688        "^.*\r?\n" "AUTHINFO PASS" 
689        (buffer-substring (point) (progn (end-of-line) (point))))
690       (kill-buffer (current-buffer)))))
691
692 (defun nntp-default-sentinel (proc status)
693   "Default sentinel function for NNTP server process."
694   (let ((servers nntp-server-alist)
695         server)
696     ;; Go through the alist of server names and find the name of the
697     ;; server that the process that sent the signal is connected to.
698     ;; If you get my drift.
699     (if (equal proc nntp-server-process)
700         (setq server nntp-address)
701       (while (and servers 
702                   (not (equal proc (nth 1 (assq 'nntp-server-process
703                                                 (car servers))))))
704         (setq servers (cdr servers)))
705       (setq server (caar servers)))
706     (when (and server
707                nntp-warn-about-losing-connection)
708       (message "nntp: Connection closed to server %s" server)
709       (ding))))
710
711 (defun nntp-kill-connection (server)
712   "Choke the connection to SERVER."
713   (let ((proc (nth 1 (assq 'nntp-server-process 
714                            (assoc server nntp-server-alist)))))
715     (when proc 
716       (delete-process (process-name proc)))
717     (nntp-close-server server)
718     (nnheader-report
719      'nntp (message "Connection timed out to server %s" server))
720     (ding)
721     (sit-for 1)))
722
723 ;; Encoding and decoding of NNTP text.
724
725 (defun nntp-decode-text ()
726   "Decode text transmitted by NNTP.
727 0. Delete status line.
728 1. Delete `^M' at end of line.
729 2. Delete `.' at end of buffer (end of text mark).
730 3. Delete `.' at beginning of line."
731   (save-excursion
732     (set-buffer nntp-server-buffer)
733     ;; Insert newline at end of buffer.
734     (goto-char (point-max))
735     (or (bolp) (insert "\n"))
736     ;; Delete status line.
737     (delete-region (goto-char (point-min)) (progn (forward-line 1) (point)))
738     ;; Delete `^M's.
739     (while (search-forward "\r" nil t)
740       (replace-match "" t t))
741     ;; Delete `.' at end of the buffer (end of text mark).
742     (goto-char (point-max))
743     (forward-line -1)
744     (when (looking-at "^\\.\n")
745       (delete-region (point) (progn (forward-line 1) (point))))
746     ;; Replace `..' at beginning of line with `.'.
747     (goto-char (point-min))
748     ;; (replace-regexp "^\\.\\." ".")
749     (while (search-forward "\n.." nil t)
750       (delete-char -1))))
751
752 (defun nntp-encode-text ()
753   "Encode text in current buffer for NNTP transmission.
754 1. Insert `.' at beginning of line.
755 2. Insert `.' at end of buffer (end of text mark)."
756   (save-excursion
757     ;; Replace `.' at beginning of line with `..'.
758     (goto-char (point-min))
759     (while (search-forward "\n." nil t)
760       (insert "."))
761     (goto-char (point-max))
762     ;; Insert newline at end of buffer.
763     (or (bolp) (insert "\n"))
764     ;; Insert `.' at end of buffer (end of text mark).
765     (insert "." nntp-end-of-line)))
766
767 \f
768 ;;;
769 ;;; Synchronous Communication with NNTP servers.
770 ;;;
771
772 (defvar nntp-retry-command)
773
774 (defun nntp-send-command (response cmd &rest args)
775   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
776   (let ((timer 
777          (and nntp-command-timeout 
778               (cond
779                ((fboundp 'run-at-time)
780                 (run-at-time nntp-command-timeout
781                              nil 'nntp-kill-command nntp-current-server))
782                ((fboundp 'start-itimer)
783                 ;; Not sure if this will work or not, only one way to
784                 ;; find out
785                 (eval '(start-itimer "nntp-timeout"
786                                      (lambda ()
787                                        (nntp-kill-command nntp-current-server))
788                                      nntp-command-timeout nil))))))
789         (nntp-retry-command t)
790         result)
791     (unwind-protect
792         (save-excursion
793           (while nntp-retry-command
794             (setq nntp-retry-command nil)
795             ;; Clear communication buffer.
796             (set-buffer nntp-server-buffer)
797             (widen)
798             (erase-buffer)
799             (if nntp-retry-on-break
800                 (condition-case ()
801                     (progn
802                       (apply 'nntp-send-strings-to-server cmd args)
803                       (setq result
804                             (if response
805                                 (nntp-wait-for-response response)
806                               t)))
807                   (quit (setq nntp-retry-command t)))
808               (apply 'nntp-send-strings-to-server cmd args)
809               (setq result
810                     (if response
811                         (nntp-wait-for-response response)
812                       t))))
813           result)
814       (when timer 
815         (cancel-timer timer)))))
816
817 (defun nntp-kill-command (server)
818   "Kill and restart the connection to SERVER."
819   (let ((proc (nth 1 (assq 'nntp-server-process 
820                            (assoc server nntp-server-alist)))))
821     (when proc 
822       (delete-process (process-name proc)))
823     (nntp-close-server server)
824     (nntp-open-server server)
825     (when nntp-current-group
826       (nntp-request-group nntp-current-group))
827     (setq nntp-retry-command t)))
828
829 (defun nntp-send-command-old (response cmd &rest args)
830   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
831   (save-excursion
832     ;; Clear communication buffer.
833     (set-buffer nntp-server-buffer)
834     (erase-buffer)
835     (apply 'nntp-send-strings-to-server cmd args)
836     (if response
837         (nntp-wait-for-response response)
838       t)))
839
840 (defun nntp-wait-for-response (regexp &optional slow)
841   "Wait for server response which matches REGEXP."
842   (save-excursion
843     (let ((status t)
844           (wait t)
845           (dotnum 0)                    ;Number of "." being displayed.
846           (dotsize                      ;How often "." displayed.
847            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
848       (set-buffer nntp-server-buffer)
849       ;; Wait for status response (RFC977).
850       ;; 1xx - Informative message.
851       ;; 2xx - Command ok.
852       ;; 3xx - Command ok so far, send the rest of it.
853       ;; 4xx - Command was correct, but couldn't be performed for some
854       ;;       reason.
855       ;; 5xx - Command unimplemented, or incorrect, or a serious
856       ;;       program error occurred.
857       (nntp-accept-response)
858       (while wait
859         (goto-char (point-min))
860         (if slow
861             (progn
862               (cond ((re-search-forward "^[23][0-9][0-9]" nil t)
863                      (setq wait nil))
864                     ((re-search-forward "^[45][0-9][0-9]" nil t)
865                      (setq status nil)
866                      (setq wait nil))
867                     (t (nntp-accept-response)))
868               (if (not wait) (delete-region (point-min) 
869                                             (progn (beginning-of-line)
870                                                    (point)))))
871           (cond ((looking-at "[23]")
872                  (setq wait nil))
873                 ((looking-at "[45]")
874                  (setq status nil)
875                  (setq wait nil))
876                 (t (nntp-accept-response)))))
877       ;; Save status message.
878       (end-of-line)
879       (setq nntp-status-string
880             (buffer-substring (point-min) (point)))
881       (when status
882         (setq wait t)
883         (while wait
884           (goto-char (point-max))
885           (forward-line -1)
886           (if (looking-at regexp)
887               (setq wait nil)
888             (when nntp-debug-read
889               (let ((newnum (/ (buffer-size) dotsize))
890                     (message-log-max nil))
891                 (unless (= dotnum newnum)
892                   (setq dotnum newnum)
893                   (message "NNTP: Reading %s"
894                            (make-string dotnum ?.)))))
895             (nntp-accept-response)))
896         ;; Remove "...".
897         (when (and nntp-debug-read (> dotnum 0))
898           (message ""))
899         ;; Successfully received server response.
900         t))))
901
902 \f
903
904 ;;;
905 ;;; Low-Level Interface to NNTP Server.
906 ;;; 
907
908 (defun nntp-find-group-and-number ()
909   (save-excursion
910     (save-restriction
911       (set-buffer nntp-server-buffer)
912       (narrow-to-region (goto-char (point-min))
913                         (or (search-forward "\n\n" nil t) (point-max)))
914       (goto-char (point-min))
915       ;; We first find the number by looking at the status line.
916       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
917                          (string-to-int
918                           (buffer-substring (match-beginning 1)
919                                             (match-end 1)))))
920             group newsgroups xref)
921         (and number (zerop number) (setq number nil))
922         ;; Then we find the group name.
923         (setq group
924               (cond 
925                ;; If there is only one group in the Newsgroups header,
926                ;; then it seems quite likely that this article comes
927                ;; from that group, I'd say.
928                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
929                      (not (string-match "," newsgroups)))
930                 newsgroups)
931                ;; If there is more than one group in the Newsgroups
932                ;; header, then the Xref header should be filled out.
933                ;; We hazard a guess that the group that has this
934                ;; article number in the Xref header is the one we are
935                ;; looking for.  This might very well be wrong if this
936                ;; article happens to have the same number in several
937                ;; groups, but that's life. 
938                ((and (setq xref (mail-fetch-field "xref"))
939                      number
940                      (string-match (format "\\([^ :]+\\):%d" number) xref))
941                 (substring xref (match-beginning 1) (match-end 1)))
942                (t "")))
943         (when (string-match "\r" group) 
944           (setq group (substring group 0 (match-beginning 0))))
945         (cons group number)))))
946
947 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
948   (erase-buffer)
949   (cond 
950
951    ;; This server does not talk NOV.
952    ((not nntp-server-xover)
953     nil)
954
955    ;; We don't care about gaps.
956    ((or (not nntp-nov-gap)
957         fetch-old)
958     (nntp-send-xover-command 
959      (if fetch-old
960          (if (numberp fetch-old) 
961              (max 1 (- (car articles) fetch-old)) 
962            1)
963        (car articles))
964      (nntp-last-element articles) 'wait)
965
966     (goto-char (point-min))
967     (when (looking-at "[1-5][0-9][0-9] ")
968       (delete-region (point) (progn (forward-line 1) (point))))
969     (while (search-forward "\r" nil t)
970       (replace-match "" t t))
971     (goto-char (point-max))
972     (forward-line -1)
973     (when (looking-at "\\.")
974       (delete-region (point) (progn (forward-line 1) (point)))))
975
976    ;; We do it the hard way.  For each gap, an XOVER command is sent
977    ;; to the server.  We do not wait for a reply from the server, we
978    ;; just send them off as fast as we can.  That means that we have
979    ;; to count the number of responses we get back to find out when we
980    ;; have gotten all we asked for.
981    ((numberp nntp-nov-gap)
982     (let ((count 0)
983           (received 0)
984           (last-point (point-min))
985           (buf (current-buffer))
986           first)
987       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
988       ;; that means that the server does not understand XOVER, but we
989       ;; won't know that until we try.
990       (while (and nntp-server-xover articles)
991         (setq first (car articles))
992         ;; Search forward until we find a gap, or until we run out of
993         ;; articles. 
994         (while (and (cdr articles) 
995                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
996           (setq articles (cdr articles)))
997
998         (when (nntp-send-xover-command first (car articles))
999           (setq articles (cdr articles)
1000                 count (1+ count))
1001
1002           ;; Every 400 requests we have to read the stream in
1003           ;; order to avoid deadlocks.
1004           (when (or (null articles)     ;All requests have been sent.
1005                     (zerop (% count nntp-maximum-request)))
1006             (accept-process-output)
1007             ;; On some Emacs versions the preceding function has
1008             ;; a tendency to change the buffer. Perhaps. It's
1009             ;; quite difficult to reproduce, because it only
1010             ;; seems to happen once in a blue moon. 
1011             (set-buffer buf) 
1012             (while (progn
1013                      (goto-char last-point)
1014                      ;; Count replies.
1015                      (while (re-search-forward "^[0-9][0-9][0-9] " nil t)
1016                        (setq received (1+ received)))
1017                      (setq last-point (point))
1018                      (< received count))
1019               (accept-process-output)
1020               (set-buffer buf)))))
1021
1022       (when nntp-server-xover
1023         ;; Wait for the reply from the final command.
1024         (goto-char (point-max))
1025         (re-search-backward "^[0-9][0-9][0-9] " nil t)
1026         (when (looking-at "^[23]")
1027           (while (progn
1028                    (goto-char (point-max))
1029                    (forward-line -1)
1030                    (not (looking-at "^\\.\r?\n")))
1031             (nntp-accept-response)))
1032         
1033         ;; We remove any "." lines and status lines.
1034         (goto-char (point-min))
1035         (while (search-forward "\r" nil t)
1036           (delete-char -1))
1037         (goto-char (point-min))
1038         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")))))
1039
1040   nntp-server-xover)
1041
1042 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1043   "Send the XOVER command to the server."
1044   (let ((range (format "%d-%d" beg end)))
1045     (if (stringp nntp-server-xover)
1046         ;; If `nntp-server-xover' is a string, then we just send this
1047         ;; command.
1048         (if wait-for-reply
1049             (nntp-send-command "^\\.\r?\n" nntp-server-xover range)
1050           ;; We do not wait for the reply.
1051           (nntp-send-strings-to-server nntp-server-xover range))
1052       (let ((commands nntp-xover-commands))
1053         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1054         ;; We try them all until we get at positive response. 
1055         (while (and commands (eq nntp-server-xover 'try))
1056           (nntp-send-command "^\\.\r?\n" (car commands) range)
1057           (save-excursion
1058             (set-buffer nntp-server-buffer)
1059             (goto-char (point-min))
1060             (and (looking-at "[23]") ; No error message.
1061                  ;; We also have to look at the lines.  Some buggy
1062                  ;; servers give back simple lines with just the
1063                  ;; article number.  How... helpful.
1064                  (progn
1065                    (forward-line 1)
1066                    (looking-at "[0-9]+\t...")) ; More text after number.
1067                  (setq nntp-server-xover (car commands))))
1068           (setq commands (cdr commands)))
1069         ;; If none of the commands worked, we disable XOVER.
1070         (when (eq nntp-server-xover 'try)
1071           (save-excursion
1072             (set-buffer nntp-server-buffer)
1073             (erase-buffer)
1074             (setq nntp-server-xover nil)))
1075         nntp-server-xover))))
1076
1077 (defun nntp-send-strings-to-server (&rest strings)
1078   "Send STRINGS to the server."
1079   (let ((cmd (concat (mapconcat 'identity strings " ") nntp-end-of-line)))
1080     ;; We open the nntp server if it is down.
1081     (or (nntp-server-opened nntp-current-server)
1082         (nntp-open-server nntp-current-server)
1083         (error (nntp-status-message)))
1084     ;; Send the strings.
1085     (process-send-string nntp-server-process cmd)
1086     t))
1087
1088 (defun nntp-send-region-to-server (begin end)
1089   "Send the current buffer region (from BEGIN to END) to the server."
1090   (save-excursion
1091     (let ((cur (current-buffer)))
1092       ;; Copy the buffer over to the send buffer.
1093       (nnheader-set-temp-buffer " *nntp send*")
1094       (insert-buffer-substring cur begin end)
1095       (save-excursion
1096         (set-buffer cur)
1097         (erase-buffer))
1098       ;; `process-send-region' does not work if the text to be sent is very
1099       ;; large, so we send it piecemeal.
1100       (let ((last (point-min))
1101             (size 100))                 ;Size of text sent at once.
1102         (while (/= last (point-max))
1103           (process-send-region 
1104            nntp-server-process
1105            last (setq last (min (+ last size) (point-max))))
1106           ;; Read any output from the server.  May be unnecessary.
1107           (accept-process-output)))
1108       (kill-buffer (current-buffer)))))
1109
1110 (defun nntp-open-server-semi-internal (server &optional service)
1111   "Open SERVER.
1112 If SERVER is nil, use value of environment variable `NNTPSERVER'.
1113 If SERVICE, this this as the port number."
1114   (let ((server (or server (getenv "NNTPSERVER")))
1115         (status nil)
1116         (timer 
1117          (and nntp-connection-timeout 
1118               (cond
1119                ((fboundp 'run-at-time)
1120                 (run-at-time nntp-connection-timeout
1121                              nil 'nntp-kill-connection server))
1122                ((fboundp 'start-itimer)
1123                 ;; Not sure if this will work or not, only one way to
1124                 ;; find out
1125                 (eval '(start-itimer "nntp-timeout"
1126                                      (lambda ()
1127                                        (nntp-kill-connection server))
1128                                      nntp-connection-timeout nil)))))))
1129     (save-excursion
1130       (set-buffer nntp-server-buffer)
1131       (setq nntp-status-string "")
1132       (message "nntp: Connecting to server on %s..." nntp-address)
1133       (cond ((and server (nntp-open-server-internal server service))
1134              (setq nntp-address server)
1135              (setq status
1136                    (condition-case nil
1137                        (nntp-wait-for-response "^[23].*\r?\n" 'slow)
1138                      (error nil)
1139                      (quit nil)))
1140              (unless status
1141                (nntp-close-server-internal server)
1142                (nnheader-report 
1143                 'nntp "Couldn't open connection to %s" nntp-address))
1144              (when nntp-server-process
1145                (set-process-sentinel 
1146                 nntp-server-process 'nntp-default-sentinel)
1147                ;; You can send commands at startup like AUTHINFO here.
1148                ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
1149                (run-hooks 'nntp-server-opened-hook)))
1150             ((null server)
1151              (nnheader-report 'nntp "NNTP server is not specified."))
1152             (t                          ; We couldn't open the server.
1153              (nnheader-report 
1154               'nntp (buffer-substring (point-min) (point-max)))))
1155       (and timer (cancel-timer timer))
1156       (message "")
1157       (or status
1158           (setq nntp-current-server nil
1159                 nntp-async-number nil))
1160       status)))
1161
1162 (defvar nntp-default-directories '("~" "/tmp" "/")
1163   "Directories to as current directory in the nntp server buffer.")
1164
1165 (defun nntp-open-server-internal (server &optional service)
1166   "Open connection to news server on SERVER by SERVICE (default is nntp)."
1167   (let (proc)
1168     (save-excursion
1169       (set-buffer nntp-server-buffer)
1170       ;; Make sure we have a valid current directory for the
1171       ;; nntp server buffer.
1172       (unless (file-exists-p default-directory)
1173         (let ((dirs nntp-default-directories))
1174           (while dirs
1175             (when (file-exists-p (car dirs))
1176               (setq default-directory (car dirs)
1177                     dirs nil))
1178             (setq dirs (cdr dirs)))))
1179       (cond
1180        ((and (setq proc
1181                    (condition-case nil
1182                        (funcall nntp-open-server-function server)
1183                      (error nil)))
1184              (memq (process-status proc) '(open run)))
1185         (setq nntp-server-process proc)
1186         (setq nntp-address server)
1187         ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
1188         (process-kill-without-query proc)
1189         (run-hooks 'nntp-server-hook)
1190         (push proc nntp-opened-connections)
1191         (condition-case ()
1192             (nntp-read-server-type)
1193           (error 
1194            (nnheader-report 'nntp "Couldn't open server %s" server)
1195            (nntp-close-server)))
1196         nntp-server-process)
1197        (t
1198         (nnheader-report 'nntp "Couldn't open server %s" server))))))
1199
1200 (defun nntp-read-server-type ()
1201   "Find out what the name of the server we have connected to is."
1202   ;; Wait for the status string to arrive.
1203   (nntp-wait-for-response "^.*\n" t)
1204   (setq nntp-server-type (buffer-string))
1205   (let ((alist nntp-server-action-alist)
1206         entry)
1207     ;; Run server-specific commmands.
1208     (while alist
1209       (setq entry (pop alist))
1210       (when (string-match (car entry) nntp-server-type)
1211         (if (and (listp (cadr entry))
1212                  (not (eq 'lambda (caadr entry))))
1213             (eval (cadr entry))
1214           (funcall (cadr entry)))))))
1215
1216 (defun nntp-open-network-stream (server)
1217   (open-network-stream 
1218    "nntpd" nntp-server-buffer server nntp-port-number))
1219
1220 (defun nntp-open-rlogin (server)
1221   (let ((proc (if nntp-rlogin-user-name
1222                   (start-process "nntpd" nntp-server-buffer "rsh"
1223                                  "-l"
1224                                  nntp-rlogin-user-name
1225                                  server
1226                                  (mapconcat 'identity
1227                                             nntp-rlogin-parameters " "))
1228                 (start-process "nntpd" nntp-server-buffer "rsh"
1229                                server
1230                                (mapconcat 'identity
1231                                           nntp-rlogin-parameters " ")))))
1232     proc))
1233
1234 (defun nntp-telnet-to-machine ()
1235   (let (b)
1236     (telnet "localhost")
1237     (goto-char (point-min))
1238     (while (not (re-search-forward "^login: *" nil t))
1239       (sit-for 1)
1240       (goto-char (point-min)))
1241     (goto-char (point-max))
1242     (insert "larsi")
1243     (telnet-send-input)
1244     (setq b (point))
1245     (while (not (re-search-forward ">" nil t))
1246       (sit-for 1)
1247       (goto-char b))
1248     (goto-char (point-max))
1249     (insert "ls")
1250     (telnet-send-input)))
1251
1252 (defun nntp-close-server-internal (&optional server)
1253   "Close connection to news server."
1254   (nntp-possibly-change-server nil server)
1255   (if nntp-server-process
1256       (delete-process nntp-server-process))
1257   (setq nntp-server-process nil)
1258   (setq nntp-address ""))
1259
1260 (defun nntp-accept-response ()
1261   "Read response of server.
1262 It is well-known that the communication speed will be much improved by
1263 defining this function as macro."
1264   ;; To deal with server process exiting before
1265   ;;  accept-process-output is called.
1266   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
1267   ;; This is a copy of `nntp-default-sentinel'.
1268   (let ((buf (current-buffer)))
1269     (prog1
1270         (if (or (not nntp-server-process)
1271                 (not (memq (process-status nntp-server-process) '(open run))))
1272             (error "nntp: Process connection closed; %s" (nntp-status-message))
1273           (if nntp-buggy-select
1274               (progn
1275                 ;; We cannot use `accept-process-output'.
1276                 ;; Fujitsu UTS requires messages during sleep-for.
1277                 ;; I don't know why.
1278                 (message "NNTP: Reading...")
1279                 (sleep-for 1)
1280                 (message ""))
1281             (condition-case errorcode
1282                 (accept-process-output nntp-server-process 1)
1283               (error
1284                (cond ((string-equal "select error: Invalid argument" 
1285                                     (nth 1 errorcode))
1286                       ;; Ignore select error.
1287                       nil)
1288                      (t
1289                       (signal (car errorcode) (cdr errorcode))))))))
1290       (set-buffer buf))))
1291
1292 (defun nntp-last-element (list)
1293   "Return last element of LIST."
1294   (while (cdr list)
1295     (setq list (cdr list)))
1296   (car list))
1297
1298 (defun nntp-possibly-change-server (newsgroup server &optional connectionless)
1299   "Check whether the virtual server needs changing."
1300   (if (and server
1301            (not (nntp-server-opened server)))
1302       ;; This virtual server isn't open, so we (re)open it here.
1303       (nntp-open-server server nil t))
1304   (if (and newsgroup 
1305            (not (equal newsgroup nntp-current-group)))
1306       ;; Set the proper current group.
1307       (nntp-request-group newsgroup server)))
1308  
1309 (defun nntp-try-list-active (group)
1310   (nntp-list-active-group group)
1311   (save-excursion
1312     (set-buffer nntp-server-buffer)
1313     (goto-char (point-min))
1314     (cond ((looking-at "5[0-9]+")
1315            (setq nntp-server-list-active-group nil))
1316           (t
1317            (setq nntp-server-list-active-group t)))))
1318
1319 (defun nntp-async-server-opened ()
1320   (and nntp-async-process
1321        (memq (process-status nntp-async-process) '(open run))))
1322
1323 (defun nntp-async-open-server ()
1324   (save-excursion
1325     (set-buffer (generate-new-buffer " *async-nntp*"))
1326     (setq nntp-async-buffer (current-buffer))
1327     (buffer-disable-undo (current-buffer)))
1328   (let ((nntp-server-process nil)
1329         (nntp-server-buffer nntp-async-buffer))
1330     (nntp-open-server-semi-internal nntp-address nntp-port-number)
1331     (if (not (setq nntp-async-process nntp-server-process))
1332         (progn
1333           (setq nntp-async-number nil))
1334       (set-process-buffer nntp-async-process nntp-async-buffer))))
1335
1336 (defun nntp-async-fetch-articles (article)
1337   (if (stringp article)
1338       ()
1339     (let ((articles (cdr (memq (assq article nntp-async-articles)
1340                                nntp-async-articles)))
1341           (max (cond ((numberp nntp-async-number)
1342                       nntp-async-number) 
1343                      ((eq nntp-async-number t)
1344                       (length nntp-async-articles))
1345                      (t 0)))
1346           nart)
1347       (while (and (>= (setq max (1- max)) 0)
1348                   articles)
1349         (or (memq (setq nart (caar articles)) nntp-async-fetched)
1350             (progn
1351               (nntp-async-send-strings "ARTICLE " (int-to-string nart))
1352               (setq nntp-async-fetched (cons nart nntp-async-fetched))))
1353         (setq articles (cdr articles))))))
1354
1355 (defun nntp-async-send-strings (&rest strings)
1356   (let ((cmd (concat (mapconcat 'identity strings " ") nntp-end-of-line)))
1357     (or (nntp-async-server-opened)
1358         (nntp-async-open-server)
1359         (error (nntp-status-message)))
1360     (process-send-string nntp-async-process cmd)))
1361
1362 (defun nntp-async-request-group (group)
1363   (if (equal group nntp-current-group)
1364       ()
1365     (let ((asyncs (assoc group nntp-async-group-alist)))
1366       ;; A new group has been selected, so we push the current state
1367       ;; of async articles on an alist, and pull the old state off.
1368       (setq nntp-async-group-alist 
1369             (cons (list nntp-current-group
1370                         nntp-async-articles nntp-async-fetched
1371                         nntp-async-process)
1372                   (delq asyncs nntp-async-group-alist)))
1373       (and asyncs
1374            (progn
1375              (setq nntp-async-articles (nth 1 asyncs))
1376              (setq nntp-async-fetched (nth 2 asyncs))
1377              (setq nntp-async-process (nth 3 asyncs)))))))
1378
1379 (provide 'nntp)
1380
1381 ;;; nntp.el ends here