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