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