07f49fe60924088f417e0d795e76de8a33a8f171
[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" "-8" "${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 or telnet 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 (re-search-forward "^\\." nil t)
737       (insert "."))
738     (goto-char (point-max))
739     ;; Insert newline at end of buffer.
740     (or (bolp) (insert "\n"))
741     ;(goto-char (point-min))
742     ;(while (not (eobp))
743     ;  (end-of-line)
744     ;  (insert "\r")
745     ;  (forward-line 1))
746     ;; Insert `.' at end of buffer (end of text mark).
747     (goto-char (point-max))
748     (insert "." nntp-end-of-line)))
749
750
751 \f
752 ;;;
753 ;;; Synchronous Communication with NNTP servers.
754 ;;;
755
756 (defvar nntp-retry-command)
757
758 (defun nntp-send-command (response cmd &rest args)
759   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
760   (let ((timer 
761          (and nntp-command-timeout 
762               (nnheader-run-at-time
763                nntp-command-timeout nil 'nntp-kill-command 
764                (nnoo-current-server 'nntp))))
765         (nntp-retry-command t)
766         result)
767     (unwind-protect
768         (save-excursion
769           (while nntp-retry-command
770             (setq nntp-retry-command nil)
771             ;; Clear communication buffer.
772             (set-buffer nntp-server-buffer)
773             (widen)
774             (erase-buffer)
775             (if nntp-retry-on-break
776                 (condition-case ()
777                     (progn
778                       (apply 'nntp-send-strings-to-server cmd args)
779                       (setq result
780                             (if response
781                                 (nntp-wait-for-response response)
782                               t)))
783                   (quit (setq nntp-retry-command t)))
784               (apply 'nntp-send-strings-to-server cmd args)
785               (setq result
786                     (if response
787                         (nntp-wait-for-response response)
788                       t))))
789           result)
790       (when timer 
791         (nnheader-cancel-timer timer)))))
792
793 (defun nntp-kill-command (server)
794   "Kill and restart the connection to SERVER."
795   (let ((proc (cdr (assq 
796                     'nntp-server-process 
797                     (assoc server (cddr (assq 'nntp nnoo-state-alist)))))))
798     (when proc 
799       (delete-process (process-name proc)))
800     (nntp-close-server server)
801     (nntp-open-server server)
802     (when nntp-current-group
803       (nntp-request-group nntp-current-group))
804     (setq nntp-retry-command t)))
805
806 (defun nntp-send-command-old (response cmd &rest args)
807   "Wait for server RESPONSE after sending CMD and optional ARGS to server."
808   (save-excursion
809     ;; Clear communication buffer.
810     (set-buffer nntp-server-buffer)
811     (erase-buffer)
812     (apply 'nntp-send-strings-to-server cmd args)
813     (if response
814         (nntp-wait-for-response response)
815       t)))
816
817 (defun nntp-wait-for-response (regexp &optional slow)
818   "Wait for server response which matches REGEXP."
819   (save-excursion
820     (let ((status t)
821           (wait t)
822           (dotnum 0)                    ;Number of "." being displayed.
823           (dotsize                      ;How often "." displayed.
824            (if (numberp nntp-debug-read) nntp-debug-read 10000)))
825       (set-buffer nntp-server-buffer)
826       ;; Wait for status response (RFC977).
827       ;; 1xx - Informative message.
828       ;; 2xx - Command ok.
829       ;; 3xx - Command ok so far, send the rest of it.
830       ;; 4xx - Command was correct, but couldn't be performed for some
831       ;;       reason.
832       ;; 5xx - Command unimplemented, or incorrect, or a serious
833       ;;       program error occurred.
834       (nntp-accept-response)
835       (while wait
836         (goto-char (point-min))
837         (if slow
838             (progn
839               (cond ((re-search-forward "^[23][0-9][0-9]" nil t)
840                      (setq wait nil))
841                     ((re-search-forward "^[45][0-9][0-9]" nil t)
842                      (setq status nil)
843                      (setq wait nil))
844                     (t (nntp-accept-response)))
845               (if (not wait) (delete-region (point-min) 
846                                             (progn (beginning-of-line)
847                                                    (point)))))
848           (cond ((looking-at "[23]")
849                  (setq wait nil))
850                 ((looking-at "[45]")
851                  (setq status nil)
852                  (setq wait nil))
853                 (t (nntp-accept-response)))))
854       ;; Save status message.
855       (end-of-line)
856       (setq nntp-status-string
857             (nnheader-replace-chars-in-string 
858              (buffer-substring (point-min) (point)) ?\r ? ))
859       (when status
860         (setq wait t)
861         (while wait
862           (goto-char (point-max))
863           (if (bolp) (forward-line -1) (beginning-of-line))
864           (if (looking-at regexp)
865               (setq wait nil)
866             (when nntp-debug-read
867               (let ((newnum (/ (buffer-size) dotsize))
868                     (message-log-max nil))
869                 (unless (= dotnum newnum)
870                   (setq dotnum newnum)
871                   (nnheader-message 7 "NNTP: Reading %s"
872                                     (make-string dotnum ?.)))))
873             (nntp-accept-response)))
874         ;; Remove "...".
875         (when (and nntp-debug-read (> dotnum 0))
876           (message ""))
877         ;; Successfully received server response.
878         t))))
879
880 \f
881
882 ;;;
883 ;;; Low-Level Interface to NNTP Server.
884 ;;; 
885
886 (defun nntp-find-group-and-number ()
887   (save-excursion
888     (save-restriction
889       (set-buffer nntp-server-buffer)
890       (narrow-to-region (goto-char (point-min))
891                         (or (search-forward "\n\n" nil t) (point-max)))
892       (goto-char (point-min))
893       ;; We first find the number by looking at the status line.
894       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
895                          (string-to-int
896                           (buffer-substring (match-beginning 1)
897                                             (match-end 1)))))
898             group newsgroups xref)
899         (and number (zerop number) (setq number nil))
900         ;; Then we find the group name.
901         (setq group
902               (cond 
903                ;; If there is only one group in the Newsgroups header,
904                ;; then it seems quite likely that this article comes
905                ;; from that group, I'd say.
906                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
907                      (not (string-match "," newsgroups)))
908                 newsgroups)
909                ;; If there is more than one group in the Newsgroups
910                ;; header, then the Xref header should be filled out.
911                ;; We hazard a guess that the group that has this
912                ;; article number in the Xref header is the one we are
913                ;; looking for.  This might very well be wrong if this
914                ;; article happens to have the same number in several
915                ;; groups, but that's life. 
916                ((and (setq xref (mail-fetch-field "xref"))
917                      number
918                      (string-match (format "\\([^ :]+\\):%d" number) xref))
919                 (substring xref (match-beginning 1) (match-end 1)))
920                (t "")))
921         (when (string-match "\r" group) 
922           (setq group (substring group 0 (match-beginning 0))))
923         (cons group number)))))
924
925 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
926   (erase-buffer)
927   (cond 
928
929    ;; This server does not talk NOV.
930    ((not nntp-server-xover)
931     nil)
932
933    ;; We don't care about gaps.
934    ((or (not nntp-nov-gap)
935         fetch-old)
936     (nntp-send-xover-command 
937      (if fetch-old
938          (if (numberp fetch-old) 
939              (max 1 (- (car articles) fetch-old)) 
940            1)
941        (car articles))
942      (nntp-last-element articles) 'wait)
943
944     (goto-char (point-min))
945     (when (looking-at "[1-5][0-9][0-9] ")
946       (delete-region (point) (progn (forward-line 1) (point))))
947     (while (search-forward "\r" nil t)
948       (replace-match "" t t))
949     (goto-char (point-max))
950     (forward-line -1)
951     (when (looking-at "\\.")
952       (delete-region (point) (progn (forward-line 1) (point)))))
953
954    ;; We do it the hard way.  For each gap, an XOVER command is sent
955    ;; to the server.  We do not wait for a reply from the server, we
956    ;; just send them off as fast as we can.  That means that we have
957    ;; to count the number of responses we get back to find out when we
958    ;; have gotten all we asked for.
959    ((numberp nntp-nov-gap)
960     (let ((count 0)
961           (received 0)
962           (last-point (point-min))
963           (buf (current-buffer))
964           first)
965       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
966       ;; that means that the server does not understand XOVER, but we
967       ;; won't know that until we try.
968       (while (and nntp-server-xover articles)
969         (setq first (car articles))
970         ;; Search forward until we find a gap, or until we run out of
971         ;; articles. 
972         (while (and (cdr articles) 
973                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
974           (setq articles (cdr articles)))
975
976         (when (nntp-send-xover-command first (car articles))
977           (setq articles (cdr articles)
978                 count (1+ count))
979
980           ;; Every 400 requests we have to read the stream in
981           ;; order to avoid deadlocks.
982           (when (or (null articles)     ;All requests have been sent.
983                     (zerop (% count nntp-maximum-request)))
984             (accept-process-output nntp-server-process)
985             ;; On some Emacs versions the preceding function has
986             ;; a tendency to change the buffer. Perhaps. It's
987             ;; quite difficult to reproduce, because it only
988             ;; seems to happen once in a blue moon. 
989             (set-buffer buf) 
990             (while (progn
991                      (goto-char last-point)
992                      ;; Count replies.
993                      (while (re-search-forward "^[0-9][0-9][0-9] " nil t)
994                        (setq received (1+ received)))
995                      (setq last-point (point))
996                      (< received count))
997               (accept-process-output nntp-server-process)
998               (set-buffer buf)))))
999
1000       (when nntp-server-xover
1001         ;; Wait for the reply from the final command.
1002         (goto-char (point-max))
1003         (re-search-backward "^[0-9][0-9][0-9] " nil t)
1004         (when (looking-at "^[23]")
1005           (while (progn
1006                    (goto-char (point-max))
1007                    (forward-line -1)
1008                    (not (looking-at "^\\.\r?\n")))
1009             (nntp-accept-response)))
1010         
1011         ;; We remove any "." lines and status lines.
1012         (goto-char (point-min))
1013         (while (search-forward "\r" nil t)
1014           (delete-char -1))
1015         (goto-char (point-min))
1016         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")))))
1017
1018   nntp-server-xover)
1019
1020 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1021   "Send the XOVER command to the server."
1022   (let ((range (format "%d-%d" (or beg 1) (or end beg 1))))
1023     (if (stringp nntp-server-xover)
1024         ;; If `nntp-server-xover' is a string, then we just send this
1025         ;; command.
1026         (if wait-for-reply
1027             (nntp-send-command "^\\.\r?\n" nntp-server-xover range)
1028           ;; We do not wait for the reply.
1029           (nntp-send-strings-to-server nntp-server-xover range))
1030       (let ((commands nntp-xover-commands))
1031         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1032         ;; We try them all until we get at positive response. 
1033         (while (and commands (eq nntp-server-xover 'try))
1034           (nntp-send-command "^\\.\r?\n" (car commands) range)
1035           (save-excursion
1036             (set-buffer nntp-server-buffer)
1037             (goto-char (point-min))
1038             (and (looking-at "[23]") ; No error message.
1039                  ;; We also have to look at the lines.  Some buggy
1040                  ;; servers give back simple lines with just the
1041                  ;; article number.  How... helpful.
1042                  (progn
1043                    (forward-line 1)
1044                    (looking-at "[0-9]+\t...")) ; More text after number.
1045                  (setq nntp-server-xover (car commands))))
1046           (setq commands (cdr commands)))
1047         ;; If none of the commands worked, we disable XOVER.
1048         (when (eq nntp-server-xover 'try)
1049           (save-excursion
1050             (set-buffer nntp-server-buffer)
1051             (erase-buffer)
1052             (setq nntp-server-xover nil)))
1053         nntp-server-xover))))
1054
1055 (defun nntp-send-strings-to-server (&rest strings)
1056   "Send STRINGS to the server."
1057   (let ((cmd (concat (mapconcat 'identity strings " ") nntp-end-of-line)))
1058     ;; We open the nntp server if it is down.
1059     (or (nntp-server-opened (nnoo-current-server 'nntp))
1060         (nntp-open-server (nnoo-current-server 'nntp))
1061         (error (nntp-status-message)))
1062     ;; Send the strings.
1063     (process-send-string nntp-server-process cmd)
1064     t))
1065
1066 (defun nntp-send-region-to-server (begin end)
1067   "Send the current buffer region (from BEGIN to END) to the server."
1068   (save-excursion
1069     (let ((cur (current-buffer)))
1070       ;; Copy the buffer over to the send buffer.
1071       (nnheader-set-temp-buffer " *nntp send*")
1072       (insert-buffer-substring cur begin end)
1073       (save-excursion
1074         (set-buffer cur)
1075         (erase-buffer))
1076       ;; `process-send-region' does not work if the text to be sent is very
1077       ;; large, so we send it piecemeal.
1078       (let ((last (point-min))
1079             (size 100))                 ;Size of text sent at once.
1080         (while (and (/= last (point-max))
1081                     (memq (process-status nntp-server-process) '(open run)))
1082           (process-send-region 
1083            nntp-server-process
1084            last (setq last (min (+ last size) (point-max))))
1085           ;; Read any output from the server.  May be unnecessary.
1086           (accept-process-output)))
1087       (kill-buffer (current-buffer)))))
1088
1089 (defun nntp-open-server-semi-internal (server &optional service)
1090   "Open SERVER.
1091 If SERVER is nil, use value of environment variable `NNTPSERVER'.
1092 If SERVICE, use this as the port number."
1093   (nnheader-insert "")
1094   (let ((server (or server (getenv "NNTPSERVER")))
1095         (status nil)
1096         (timer 
1097          (and nntp-connection-timeout 
1098               (nnheader-run-at-time nntp-connection-timeout
1099                                     nil 'nntp-kill-connection server))))
1100     (save-excursion
1101       (set-buffer nntp-server-buffer)
1102       (setq nntp-status-string "")
1103       (nnheader-message 5 "nntp: Connecting to server on %s..." nntp-address)
1104       (cond ((and server (nntp-open-server-internal server service))
1105              (setq nntp-address server)
1106              (setq status
1107                    (condition-case nil
1108                        (nntp-wait-for-response "^[23].*\r?\n" 'slow)
1109                      (error nil)
1110                      ;(quit nil)
1111                      ))
1112              (unless status
1113                (nntp-close-server-internal server)
1114                (nnheader-report 
1115                 'nntp "Couldn't open connection to %s" 
1116                 (if (and nntp-address
1117                          (not (equal nntp-address "")))
1118                     nntp-address server)))
1119              (when nntp-server-process
1120                (set-process-sentinel 
1121                 nntp-server-process 'nntp-default-sentinel)
1122                ;; You can send commands at startup like AUTHINFO here.
1123                ;; Added by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>
1124                (run-hooks 'nntp-server-opened-hook)))
1125             ((null server)
1126              (nnheader-report 'nntp "NNTP server is not specified."))
1127             (t                          ; We couldn't open the server.
1128              (nnheader-report 'nntp (buffer-string))))
1129       (when timer 
1130         (nnheader-cancel-timer timer))
1131       (message "")
1132       (unless status
1133         (nnoo-close-server 'nntp server)
1134         (setq nntp-async-number nil))
1135       status)))
1136
1137 (defvar nntp-default-directories '("~" "/tmp" "/")
1138   "Directories to as current directory in the nntp server buffer.")
1139
1140 (defun nntp-open-server-internal (server &optional service)
1141   "Open connection to news server on SERVER by SERVICE (default is nntp)."
1142   (let (proc)
1143     (save-excursion
1144       (set-buffer nntp-server-buffer)
1145       ;; Make sure we have a valid current directory for the
1146       ;; nntp server buffer.
1147       (unless (file-exists-p default-directory)
1148         (let ((dirs nntp-default-directories))
1149           (while dirs
1150             (when (file-exists-p (car dirs))
1151               (setq default-directory (car dirs)
1152                     dirs nil))
1153             (setq dirs (cdr dirs)))))
1154       (cond
1155        ((and (setq proc
1156                    (condition-case nil
1157                        (funcall nntp-open-server-function server)
1158                      (error nil)))
1159              (memq (process-status proc) '(open run)))
1160         (setq nntp-server-process proc)
1161         (setq nntp-address server)
1162         ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
1163         (process-kill-without-query proc)
1164         (run-hooks 'nntp-server-hook)
1165         (push proc nntp-opened-connections)
1166         (condition-case ()
1167             (nntp-read-server-type)
1168           (error 
1169            (nnheader-report 'nntp "Couldn't open server %s" server)
1170            (nntp-close-server)))
1171         nntp-server-process)
1172        (t
1173         (nnheader-report 'nntp "Couldn't open server %s" server))))))
1174
1175 (defun nntp-read-server-type ()
1176   "Find out what the name of the server we have connected to is."
1177   ;; Wait for the status string to arrive.
1178   (nntp-wait-for-response "^.*\n" t)
1179   (setq nntp-server-type (buffer-string))
1180   (let ((alist nntp-server-action-alist)
1181         entry)
1182     ;; Run server-specific commmands.
1183     (while alist
1184       (setq entry (pop alist))
1185       (when (string-match (car entry) nntp-server-type)
1186         (if (and (listp (cadr entry))
1187                  (not (eq 'lambda (caadr entry))))
1188             (eval (cadr entry))
1189           (funcall (cadr entry)))))))
1190
1191 (defun nntp-open-network-stream (server)
1192   (open-network-stream 
1193    "nntpd" nntp-server-buffer server nntp-port-number))
1194
1195 (defun nntp-open-rlogin (server)
1196   (let ((proc (if nntp-rlogin-user-name
1197                   (start-process
1198                    "nntpd" nntp-server-buffer "rsh"
1199                    "-l" nntp-rlogin-user-name server
1200                    (mapconcat 'identity
1201                               nntp-rlogin-parameters " "))
1202                 (start-process
1203                  "nntpd" nntp-server-buffer "rsh" server
1204                  (mapconcat 'identity
1205                             nntp-rlogin-parameters " ")))))
1206     proc))
1207
1208 (defun nntp-wait-for-string (regexp)
1209   "Wait until string arrives in the buffer."
1210   (let ((buf (current-buffer)))
1211     (goto-char (point-min))
1212     (while (not (re-search-forward regexp nil t))
1213       (accept-process-output nntp-server-process)
1214       (set-buffer buf)
1215       (goto-char (point-min)))))
1216
1217 (defun nntp-open-telnet (server)
1218   (save-excursion
1219     (set-buffer nntp-server-buffer)
1220     (erase-buffer)
1221     (let ((proc (start-process
1222                  "nntpd" nntp-server-buffer "telnet" "-8"))
1223           (case-fold-search t))
1224       (when (memq (process-status proc) '(open run))
1225         (process-send-string proc "set escape \^X\n")
1226         (process-send-string proc (concat "open " server "\n"))
1227         (nntp-wait-for-string "^\r*login:")
1228         (process-send-string
1229          proc (concat
1230                (or nntp-telnet-user-name
1231                    (setq nntp-telnet-user-name (read-string "login: ")))
1232                "\n"))
1233         (nntp-wait-for-string "^\r*password:")
1234         (process-send-string
1235          proc (concat
1236                (or nntp-telnet-passwd
1237                    (setq nntp-telnet-passwd
1238                          (nnmail-read-passwd "Password: ")))
1239                "\n"))
1240         (erase-buffer)
1241         (nntp-wait-for-string "bash\\|\$ *\r?$\\|> *\r?")
1242         (process-send-string
1243          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1244         (nntp-wait-for-string "^\r*200")
1245         (beginning-of-line)
1246         (delete-region (point-min) (point))
1247         (process-send-string proc "\^]")
1248         (nntp-wait-for-string "^telnet")
1249         (process-send-string proc "mode character\n")
1250         (accept-process-output proc 1)
1251         (sit-for 1)
1252         (goto-char (point-min))
1253         (forward-line 1)
1254         (delete-region (point) (point-max)))
1255       proc)))
1256
1257 (defun nntp-close-server-internal (&optional server)
1258   "Close connection to news server."
1259   (nntp-possibly-change-server nil server)
1260   (if nntp-server-process
1261       (delete-process nntp-server-process))
1262   (setq nntp-server-process nil)
1263   ;(setq nntp-address "")
1264   )
1265
1266 (defun nntp-accept-response ()
1267   "Read response of server.
1268 It is well-known that the communication speed will be much improved by
1269 defining this function as macro."
1270   ;; To deal with server process exiting before
1271   ;;  accept-process-output is called.
1272   ;; Suggested by Jason Venner <jason@violet.berkeley.edu>.
1273   ;; This is a copy of `nntp-default-sentinel'.
1274   (let ((buf (current-buffer)))
1275     (prog1
1276         (if (or (not nntp-server-process)
1277                 (not (memq (process-status nntp-server-process) '(open run))))
1278             (error "nntp: Process connection closed; %s" (nntp-status-message))
1279           (if nntp-buggy-select
1280               (progn
1281                 ;; We cannot use `accept-process-output'.
1282                 ;; Fujitsu UTS requires messages during sleep-for.
1283                 ;; I don't know why.
1284                 (nnheader-message 5 "NNTP: Reading...")
1285                 (sleep-for 1)
1286                 (nnheader-message 5 ""))
1287             (condition-case errorcode
1288                 (accept-process-output nntp-server-process 1)
1289               (error
1290                (cond ((string-equal "select error: Invalid argument" 
1291                                     (nth 1 errorcode))
1292                       ;; Ignore select error.
1293                       nil)
1294                      (t
1295                       (signal (car errorcode) (cdr errorcode))))))))
1296       (set-buffer buf))))
1297
1298 (defun nntp-last-element (list)
1299   "Return last element of LIST."
1300   (while (cdr list)
1301     (setq list (cdr list)))
1302   (car list))
1303
1304 (defun nntp-possibly-change-server (newsgroup server &optional connectionless)
1305   "Check whether the virtual server needs changing."
1306   (when (and server
1307              (not (nntp-server-opened server)))
1308     ;; This virtual server isn't open, so we (re)open it here.
1309     (nntp-open-server server nil t))
1310   (when (and newsgroup 
1311              (not (equal newsgroup nntp-current-group)))
1312     ;; Set the proper current group.
1313     (nntp-request-group newsgroup server)))
1314  
1315 (defun nntp-try-list-active (group)
1316   (nntp-list-active-group group)
1317   (save-excursion
1318     (set-buffer nntp-server-buffer)
1319     (goto-char (point-min))
1320     (cond ((looking-at "5[0-9]+")
1321            (setq nntp-server-list-active-group nil))
1322           (t
1323            (setq nntp-server-list-active-group t)))))
1324
1325 (defun nntp-async-server-opened ()
1326   (and nntp-async-process
1327        (memq (process-status nntp-async-process) '(open run))))
1328
1329 (defun nntp-async-open-server ()
1330   (save-excursion
1331     (set-buffer (generate-new-buffer " *async-nntp*"))
1332     (setq nntp-async-buffer (current-buffer))
1333     (buffer-disable-undo (current-buffer)))
1334   (let ((nntp-server-process nil)
1335         (nntp-server-buffer nntp-async-buffer))
1336     (nntp-open-server-semi-internal nntp-address nntp-port-number)
1337     (if (not (setq nntp-async-process nntp-server-process))
1338         (progn
1339           (setq nntp-async-number nil))
1340       (set-process-buffer nntp-async-process nntp-async-buffer))))
1341
1342 (defun nntp-async-fetch-articles (article)
1343   (if (stringp article)
1344       ()
1345     (let ((articles (cdr (memq (assq article nntp-async-articles)
1346                                nntp-async-articles)))
1347           (max (cond ((numberp nntp-async-number)
1348                       nntp-async-number) 
1349                      ((eq nntp-async-number t)
1350                       (length nntp-async-articles))
1351                      (t 0)))
1352           nart)
1353       (while (and (>= (setq max (1- max)) 0)
1354                   articles)
1355         (or (memq (setq nart (caar articles)) nntp-async-fetched)
1356             (progn
1357               (nntp-async-send-strings "ARTICLE " (int-to-string nart))
1358               (setq nntp-async-fetched (cons nart nntp-async-fetched))))
1359         (setq articles (cdr articles))))))
1360
1361 (defun nntp-async-send-strings (&rest strings)
1362   (let ((cmd (concat (mapconcat 'identity strings " ") nntp-end-of-line)))
1363     (or (nntp-async-server-opened)
1364         (nntp-async-open-server)
1365         (error (nntp-status-message)))
1366     (process-send-string nntp-async-process cmd)))
1367
1368 (defun nntp-async-request-group (group)
1369   (if (equal group nntp-current-group)
1370       ()
1371     (let ((asyncs (assoc group nntp-async-group-alist)))
1372       ;; A new group has been selected, so we push the current state
1373       ;; of async articles on an alist, and pull the old state off.
1374       (setq nntp-async-group-alist 
1375             (cons (list nntp-current-group
1376                         nntp-async-articles nntp-async-fetched
1377                         nntp-async-process)
1378                   (delq asyncs nntp-async-group-alist)))
1379       (and asyncs
1380            (progn
1381              (setq nntp-async-articles (nth 1 asyncs))
1382              (setq nntp-async-fetched (nth 2 asyncs))
1383              (setq nntp-async-process (nth 3 asyncs)))))))
1384
1385 (provide 'nntp)
1386
1387 ;;; nntp.el ends here