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