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