Importing qgnus-0.19
[elisp/gnus.git-] / lisp / nntp.el
1 ;;; nntp.el --- nntp access for Gnus
2 ;;; Copyright (C) 1987-90,92-97 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'nnheader)
28 (require 'nnoo)
29 (require 'gnus-util)
30
31 (nnoo-declare nntp)
32
33 (eval-and-compile
34   (unless (fboundp 'open-network-stream)
35     (require 'tcp)))
36
37 (eval-when-compile (require 'cl))
38
39 (defvoo nntp-address nil
40   "Address of the physical nntp server.")
41
42 (defvoo nntp-port-number "nntp"
43   "Port number on the physical nntp server.")
44
45 (defvoo nntp-server-opened-hook '(nntp-send-mode-reader)
46   "*Hook used for sending commands to the server at startup.
47 The default value is `nntp-send-mode-reader', which makes an innd
48 server spawn an nnrpd server.  Another useful function to put in this
49 hook might be `nntp-send-authinfo', which will prompt for a password
50 to allow posting from the server.  Note that this is only necessary to
51 do on servers that use strict access control.")
52
53 (defvoo nntp-authinfo-function 'nntp-send-authinfo
54   "Function used to send AUTHINFO to the server.")
55
56 (defvoo nntp-server-action-alist
57   '(("nntpd 1\\.5\\.11t"
58      (remove-hook 'nntp-server-opened-hook 'nntp-send-mode-reader))
59     ("NNRP server Netscape"
60      (setq nntp-server-list-active-group nil)))
61   "Alist of regexps to match on server types and actions to be taken.
62 For instance, if you want Gnus to beep every time you connect
63 to innd, you could say something like:
64
65 \(setq nntp-server-action-alist
66        '((\"innd\" (ding))))
67
68 You probably don't want to do that, though.")
69
70 (defvoo nntp-open-connection-function 'nntp-open-network-stream
71   "*Function used for connecting to a remote system.
72 It will be called with the buffer to output in.
73
74 Two pre-made functions are `nntp-open-network-stream', which is the
75 default, and simply connects to some port or other on the remote
76 system (see nntp-port-number).  The other are `nntp-open-rlogin',
77 which does an rlogin on the remote system, and then does a telnet to
78 the NNTP server available there (see nntp-rlogin-parameters) and
79 `nntp-open-telnet' which telnets to a remote system, logs in and does
80 the same.")
81
82 (defvoo nntp-rlogin-program "rsh"
83   "*Program used to log in on remote machines.
84 The default is \"rsh\", but \"ssh\" is a popular alternative.")
85
86 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
87   "*Parameters to `nntp-open-login'.
88 That function may be used as `nntp-open-connection-function'.  In that
89 case, this list will be used as the parameter list given to rsh.")
90
91 (defvoo nntp-rlogin-user-name nil
92   "*User name on remote system when using the rlogin connect method.")
93
94 (defvoo nntp-telnet-parameters '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
95   "*Parameters to `nntp-open-telnet'.
96 That function may be used as `nntp-open-connection-function'.  In that
97 case, this list will be executed as a command after logging in
98 via telnet.")
99
100 (defvoo nntp-telnet-user-name nil
101   "User name to log in via telnet with.")
102
103 (defvoo nntp-telnet-passwd nil
104   "Password to use to log in via telnet with.")
105
106 (defvoo nntp-telnet-command "telnet"
107   "Command used to start telnet.")
108
109 (defvoo nntp-telnet-switches '("-8")
110   "Switches given to the telnet command.")
111
112 (defvoo nntp-end-of-line "\r\n"
113   "String to use on the end of lines when talking to the NNTP server.
114 This is \"\\r\\n\" by default, but should be \"\\n\" when
115 using rlogin or telnet to communicate with the server.")
116
117 (defvoo nntp-large-newsgroup 50
118   "*The number of the articles which indicates a large newsgroup.
119 If the number of the articles is greater than the value, verbose
120 messages will be shown to indicate the current status.")
121
122 (defvoo nntp-maximum-request 400
123   "*The maximum number of the requests sent to the NNTP server at one time.
124 If Emacs hangs up while retrieving headers, set the variable to a
125 lower value.")
126
127 (defvoo nntp-nov-is-evil nil
128   "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
129
130 (defvoo nntp-xover-commands '("XOVER" "XOVERVIEW")
131   "*List of strings that are used as commands to fetch NOV lines from a server.
132 The strings are tried in turn until a positive response is gotten.  If
133 none of the commands are successful, nntp will just grab headers one
134 by one.")
135
136 (defvoo nntp-nov-gap 5
137   "*Maximum allowed gap between two articles.
138 If the gap between two consecutive articles is bigger than this
139 variable, split the XOVER request into two requests.")
140
141 (defvoo nntp-connection-timeout nil
142   "*Number of seconds to wait before an nntp connection times out.
143 If this variable is nil, which is the default, no timers are set.")
144
145 (defvoo nntp-prepare-server-hook nil
146   "*Hook run before a server is opened.
147 If can be used to set up a server remotely, for instance.  Say you
148 have an account at the machine \"other.machine\".  This machine has
149 access to an NNTP server that you can't access locally.  You could
150 then use this hook to rsh to the remote machine and start a proxy NNTP
151 server there that you can connect to.  See also `nntp-open-connection-function'")
152
153 (defvoo nntp-warn-about-losing-connection t
154   "*If non-nil, beep when a server closes connection.")
155
156 (defvoo nntp-coding-system-for-read 'binary
157   "*Coding system to read from NNTP.")
158
159 (defvoo nntp-coding-system-for-write 'binary
160     "*Coding system to write to NNTP.")
161
162 \f
163
164 ;;; Internal variables.
165
166 (defvar nntp-have-messaged nil)
167
168 (defvar nntp-process-wait-for nil)
169 (defvar nntp-process-to-buffer nil)
170 (defvar nntp-process-callback nil)
171 (defvar nntp-process-decode nil)
172 (defvar nntp-process-start-point nil)
173 (defvar nntp-inside-change-function nil)
174 (defvoo nntp-last-command-time nil)
175
176 (defvar nntp-connection-list nil)
177
178 (defvoo nntp-server-type nil)
179 (defvoo nntp-connection-alist nil)
180 (defvoo nntp-status-string "")
181 (defconst nntp-version "nntp 5.0")
182 (defvoo nntp-inhibit-erase nil)
183 (defvoo nntp-inhibit-output nil)
184
185 (defvoo nntp-server-xover 'try)
186 (defvoo nntp-server-list-active-group 'try)
187
188 (eval-and-compile
189   (autoload 'nnmail-read-passwd "nnmail"))
190
191 \f
192
193 ;;; Internal functions.
194
195 (defsubst nntp-send-string (process string)
196   "Send STRING to PROCESS."
197   (process-send-string process (concat string nntp-end-of-line)))
198
199 (defsubst nntp-wait-for (process wait-for buffer &optional decode discard)
200   "Wait for WAIT-FOR to arrive from PROCESS."
201   (save-excursion
202     (set-buffer (process-buffer process))
203     (goto-char (point-min))
204     (while (or (not (memq (char-after (point)) '(?2 ?3 ?4 ?5)))
205                (looking-at "480"))
206       (when (looking-at "480")
207         (erase-buffer)
208         (funcall nntp-authinfo-function))
209       (nntp-accept-process-output process)
210       (goto-char (point-min)))
211     (prog1
212         (if (looking-at "[45]")
213             (progn
214               (nntp-snarf-error-message)
215               nil)
216           (goto-char (point-max))
217           (let ((limit (point-min)))
218             (while (not (re-search-backward wait-for limit t))
219               ;; We assume that whatever we wait for is less than 1000
220               ;; characters long.
221               (setq limit (max (- (point-max) 1000) (point-min)))
222               (nntp-accept-process-output process)
223               (goto-char (point-max))))
224           (nntp-decode-text (not decode))
225           (unless discard
226             (save-excursion
227               (set-buffer buffer)
228               (goto-char (point-max))
229               (insert-buffer-substring (process-buffer process))
230               ;; Nix out "nntp reading...." message.
231               (when nntp-have-messaged
232                 (setq nntp-have-messaged nil)
233                 (message ""))
234               t)))
235       (unless discard
236         (erase-buffer)))))
237
238 (defsubst nntp-find-connection (buffer)
239   "Find the connection delivering to BUFFER."
240   (let ((alist nntp-connection-alist)
241         (buffer (if (stringp buffer) (get-buffer buffer) buffer))
242         process entry)
243     (while (setq entry (pop alist))
244       (when (eq buffer (cadr entry))
245         (setq process (car entry)
246               alist nil)))
247     (when process
248       (if (memq (process-status process) '(open run))
249           process
250         (when (buffer-name (process-buffer process))
251           (message "Killed buffer %s" (process-buffer process))
252           (kill-buffer (process-buffer process)))
253         (setq nntp-connection-alist (delq entry nntp-connection-alist))
254         nil))))
255
256 (defsubst nntp-find-connection-entry (buffer)
257   "Return the entry for the connection to BUFFER."
258   (assq (nntp-find-connection buffer) nntp-connection-alist))
259
260 (defun nntp-find-connection-buffer (buffer)
261   "Return the process connection buffer tied to BUFFER."
262   (let ((process (nntp-find-connection buffer)))
263     (when process
264       (process-buffer process))))
265
266 (defsubst nntp-retrieve-data (command address port buffer
267                                    &optional wait-for callback decode)
268   "Use COMMAND to retrieve data into BUFFER from PORT on ADDRESS."
269   (setq nntp-last-command-time (current-time))
270   (let ((process (or (nntp-find-connection buffer)
271                      (nntp-open-connection buffer))))
272     (if (not process)
273         (nnheader-report 'nntp "Couldn't open connection to %s" address)
274       (unless (or nntp-inhibit-erase nnheader-callback-function)
275         (save-excursion
276           (set-buffer (process-buffer process))
277           (erase-buffer)))
278       (when command
279         (nntp-send-string process command))
280       (cond
281        ((eq callback 'ignore)
282         t)
283        ((and callback wait-for)
284         (save-excursion
285           (set-buffer (process-buffer process))
286           (unless nntp-inside-change-function
287             (erase-buffer))
288           (setq nntp-process-decode decode
289                 nntp-process-to-buffer buffer
290                 nntp-process-wait-for wait-for
291                 nntp-process-callback callback
292                 nntp-process-start-point (point-max)
293                 after-change-functions
294                 (list 'nntp-after-change-function-callback)))
295         t)
296        (wait-for
297         (nntp-wait-for process wait-for buffer decode))
298        (t t)))))
299
300 (defsubst nntp-send-command (wait-for &rest strings)
301   "Send STRINGS to server and wait until WAIT-FOR returns."
302   (when (and (not nnheader-callback-function)
303              (not nntp-inhibit-output))
304     (save-excursion
305       (set-buffer nntp-server-buffer)
306       (erase-buffer)))
307   (nntp-retrieve-data
308    (mapconcat 'identity strings " ")
309    nntp-address nntp-port-number nntp-server-buffer
310    wait-for nnheader-callback-function))
311
312 (defun nntp-send-command-nodelete (wait-for &rest strings)
313   "Send STRINGS to server and wait until WAIT-FOR returns."
314   (nntp-retrieve-data
315    (mapconcat 'identity strings " ")
316    nntp-address nntp-port-number nntp-server-buffer
317    wait-for nnheader-callback-function))
318
319 (defun nntp-send-command-and-decode (wait-for &rest strings)
320   "Send STRINGS to server and wait until WAIT-FOR returns."
321   (when (and (not nnheader-callback-function)
322              (not nntp-inhibit-output))
323     (save-excursion
324       (set-buffer nntp-server-buffer)
325       (erase-buffer)))
326   (nntp-retrieve-data
327    (mapconcat 'identity strings " ")
328    nntp-address nntp-port-number nntp-server-buffer
329    wait-for nnheader-callback-function t))
330
331 (defun nntp-send-buffer (wait-for)
332   "Send the current buffer to server and wait until WAIT-FOR returns."
333   (when (and (not nnheader-callback-function)
334              (not nntp-inhibit-output))
335     (save-excursion
336       (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
337       (erase-buffer)))
338   (nntp-encode-text)
339   (process-send-region (nntp-find-connection nntp-server-buffer)
340                        (point-min) (point-max))
341   (nntp-retrieve-data
342    nil nntp-address nntp-port-number nntp-server-buffer
343    wait-for nnheader-callback-function))
344
345 \f
346
347 ;;; Interface functions.
348
349 (nnoo-define-basics nntp)
350
351 (defsubst nntp-next-result-arrived-p ()
352   (let ((point (point)))
353     (cond
354      ((eq (following-char) ?2)
355       (if (re-search-forward "\n\\.\r?\n" nil t)
356           t
357         (goto-char point)
358         nil))
359      ((looking-at "[34]")
360       (forward-line 1)
361       t)
362      (t
363       nil))))
364
365 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
366   "Retrieve the headers of ARTICLES."
367   (nntp-possibly-change-group group server)
368   (save-excursion
369     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
370     (erase-buffer)
371     (if (and (not gnus-nov-is-evil)
372              (not nntp-nov-is-evil)
373              (nntp-retrieve-headers-with-xover articles fetch-old))
374         ;; We successfully retrieved the headers via XOVER.
375         'nov
376       ;; XOVER didn't work, so we do it the hard, slow and inefficient
377       ;; way.
378       (let ((number (length articles))
379             (count 0)
380             (received 0)
381             (last-point (point-min))
382             (buf (nntp-find-connection-buffer nntp-server-buffer))
383             (nntp-inhibit-erase t)
384             article)
385         ;; Send HEAD commands.
386       (while (setq article (pop articles))
387         (nntp-send-command
388          nil
389          "HEAD" (if (numberp article)
390                     (int-to-string article)
391                   ;; `articles' is either a list of article numbers
392                   ;; or a list of article IDs.
393                   article))
394         (incf count)
395         ;; Every 400 requests we have to read the stream in
396         ;; order to avoid deadlocks.
397         (when (or (null articles)       ;All requests have been sent.
398                   (zerop (% count nntp-maximum-request)))
399           (nntp-accept-response)
400           (while (progn
401                    (set-buffer buf)
402                    (goto-char last-point)
403                    ;; Count replies.
404                    (while (nntp-next-result-arrived-p)
405                      (setq last-point (point))
406                      (incf received))
407                    (< received count))
408             ;; If number of headers is greater than 100, give
409             ;;  informative messages.
410             (and (numberp nntp-large-newsgroup)
411                  (> number nntp-large-newsgroup)
412                  (zerop (% received 20))
413                  (nnheader-message 6 "NNTP: Receiving headers... %d%%"
414                                    (/ (* received 100) number)))
415             (nntp-accept-response))))
416         (and (numberp nntp-large-newsgroup)
417              (> number nntp-large-newsgroup)
418              (nnheader-message 6 "NNTP: Receiving headers...done"))
419
420         ;; Now all of replies are received.  Fold continuation lines.
421         (nnheader-fold-continuation-lines)
422         ;; Remove all "\r"'s.
423         (nnheader-strip-cr)
424         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
425         'headers))))
426
427 (deffoo nntp-retrieve-groups (groups &optional server)
428   "Retrieve group info on GROUPS."
429   (nntp-possibly-change-group nil server)
430   (save-excursion
431     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
432     ;; The first time this is run, this variable is `try'.  So we
433     ;; try.
434     (when (eq nntp-server-list-active-group 'try)
435       (nntp-try-list-active (car groups)))
436     (erase-buffer)
437     (let ((count 0)
438           (received 0)
439           (last-point (point-min))
440           (nntp-inhibit-erase t)
441           (command (if nntp-server-list-active-group "LIST ACTIVE" "GROUP")))
442       (while groups
443         ;; Send the command to the server.
444         (nntp-send-command nil command (pop groups))
445         (incf count)
446         ;; Every 400 requests we have to read the stream in
447         ;; order to avoid deadlocks.
448         (when (or (null groups)         ;All requests have been sent.
449                   (zerop (% count nntp-maximum-request)))
450           (nntp-accept-response)
451           (while (progn
452                    (goto-char last-point)
453                    ;; Count replies.
454                    (while (re-search-forward "^[0-9]" nil t)
455                      (incf received))
456                    (setq last-point (point))
457                    (< received count))
458             (nntp-accept-response))))
459
460       ;; Wait for the reply from the final command.
461       (goto-char (point-max))
462       (re-search-backward "^[0-9]" nil t)
463       (when (looking-at "^[23]")
464         (while (progn
465                  (goto-char (point-max))
466                  (if (not nntp-server-list-active-group)
467                      (not (re-search-backward "\r?\n" (- (point) 3) t))
468                    (not (re-search-backward "^\\.\r?\n" (- (point) 4) t))))
469           (nntp-accept-response)))
470
471       ;; Now all replies are received.  We remove CRs.
472       (goto-char (point-min))
473       (while (search-forward "\r" nil t)
474         (replace-match "" t t))
475
476       (if (not nntp-server-list-active-group)
477           (progn
478             (copy-to-buffer nntp-server-buffer (point-min) (point-max))
479             'group)
480         ;; We have read active entries, so we just delete the
481         ;; superfluous gunk.
482         (goto-char (point-min))
483         (while (re-search-forward "^[.2-5]" nil t)
484           (delete-region (match-beginning 0)
485                          (progn (forward-line 1) (point))))
486         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
487         'active))))
488
489 (deffoo nntp-retrieve-articles (articles &optional group server)
490   (nntp-possibly-change-group group server)
491   (save-excursion
492     (let ((number (length articles))
493           (count 0)
494           (received 0)
495           (last-point (point-min))
496           (buf (nntp-find-connection-buffer nntp-server-buffer))
497           (nntp-inhibit-erase t)
498           (map (apply 'vector articles))
499           (point 1)
500           article alist)
501       (set-buffer buf)
502       (erase-buffer)
503       ;; Send ARTICLE command.
504       (while (setq article (pop articles))
505         (nntp-send-command
506          nil
507          "ARTICLE" (if (numberp article)
508                        (int-to-string article)
509                      ;; `articles' is either a list of article numbers
510                      ;; or a list of article IDs.
511                      article))
512         (incf count)
513         ;; Every 400 requests we have to read the stream in
514         ;; order to avoid deadlocks.
515         (when (or (null articles)       ;All requests have been sent.
516                   (zerop (% count nntp-maximum-request)))
517           (nntp-accept-response)
518           (while (progn
519                    (set-buffer buf)
520                    (goto-char last-point)
521                    ;; Count replies.
522                    (while (nntp-next-result-arrived-p)
523                      (aset map received (cons (aref map received) (point)))
524                      (setq last-point (point))
525                      (incf received))
526                    (< received count))
527             ;; If number of headers is greater than 100, give
528             ;;  informative messages.
529             (and (numberp nntp-large-newsgroup)
530                  (> number nntp-large-newsgroup)
531                  (zerop (% received 20))
532                  (nnheader-message 6 "NNTP: Receiving articles... %d%%"
533                                    (/ (* received 100) number)))
534             (nntp-accept-response))))
535       (and (numberp nntp-large-newsgroup)
536            (> number nntp-large-newsgroup)
537            (nnheader-message 6 "NNTP: Receiving articles...done"))
538       
539       ;; Now we have all the responses.  We go through the results,
540       ;; washes it and copies it over to the server buffer.
541       (set-buffer nntp-server-buffer)
542       (erase-buffer)
543       (setq last-point (point-min))
544       (mapcar
545        (lambda (entry)
546          (narrow-to-region
547           (setq point (goto-char (point-max)))
548           (progn
549             (insert-buffer-substring buf last-point (cdr entry))
550             (point-max)))
551          (setq last-point (cdr entry))
552          (nntp-decode-text)
553          (widen)
554          (cons (car entry) point))
555        map))))
556
557 (defun nntp-try-list-active (group)
558   (nntp-list-active-group group)
559   (save-excursion
560     (set-buffer nntp-server-buffer)
561     (goto-char (point-min))
562     (cond ((or (eobp)
563                (looking-at "5[0-9]+"))
564            (setq nntp-server-list-active-group nil))
565           (t
566            (setq nntp-server-list-active-group t)))))
567
568 (deffoo nntp-list-active-group (group &optional server)
569   "Return the active info on GROUP (which can be a regexp."
570   (nntp-possibly-change-group nil server)
571   (nntp-send-command "^.*\r?\n" "LIST ACTIVE" group))
572
573 (deffoo nntp-request-article (article &optional group server buffer command)
574   (nntp-possibly-change-group group server)
575   (when (nntp-send-command-and-decode
576          "\r?\n\\.\r?\n" "ARTICLE"
577          (if (numberp article) (int-to-string article) article))
578     (if (and buffer
579              (not (equal buffer nntp-server-buffer)))
580         (save-excursion
581           (set-buffer nntp-server-buffer)
582           (copy-to-buffer buffer (point-min) (point-max))
583           (nntp-find-group-and-number))
584       (nntp-find-group-and-number))))
585
586 (deffoo nntp-request-head (article &optional group server)
587   (nntp-possibly-change-group group server)
588   (when (nntp-send-command
589          "\r?\n\\.\r?\n" "HEAD"
590          (if (numberp article) (int-to-string article) article))
591     (prog1
592         (nntp-find-group-and-number)
593       (nntp-decode-text))))
594
595 (deffoo nntp-request-body (article &optional group server)
596   (nntp-possibly-change-group group server)
597   (nntp-send-command-and-decode
598    "\r?\n\\.\r?\n" "BODY"
599    (if (numberp article) (int-to-string article) article)))
600
601 (deffoo nntp-request-group (group &optional server dont-check)
602   (nntp-possibly-change-group nil server)
603   (when (nntp-send-command "^2.*\n" "GROUP" group)
604     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
605       (setcar (cddr entry) group))))
606
607 (deffoo nntp-close-group (group &optional server)
608   t)
609
610 (deffoo nntp-server-opened (&optional server)
611   "Say whether a connection to SERVER has been opened."
612   (and (nnoo-current-server-p 'nntp server)
613        nntp-server-buffer
614        (gnus-buffer-live-p nntp-server-buffer)
615        (nntp-find-connection nntp-server-buffer)))
616
617 (deffoo nntp-open-server (server &optional defs connectionless)
618   (nnheader-init-server-buffer)
619   (if (nntp-server-opened server)
620       t
621     (when (or (stringp (car defs))
622               (numberp (car defs)))
623       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
624     (unless (assq 'nntp-address defs)
625       (setq defs (append defs (list (list 'nntp-address server)))))
626     (nnoo-change-server 'nntp server defs)
627     (unless connectionless
628       (or (nntp-find-connection nntp-server-buffer)
629           (nntp-open-connection nntp-server-buffer)))))
630
631 (deffoo nntp-close-server (&optional server)
632   (nntp-possibly-change-group nil server t)
633   (let (process)
634     (while (setq process (car (pop nntp-connection-alist)))
635       (when (memq (process-status process) '(open run))
636         (set-process-sentinel process nil)
637         (ignore-errors
638           (nntp-send-string process "QUIT")
639           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
640             (sleep-for 1))))
641       (when (buffer-name (process-buffer process))
642         (kill-buffer (process-buffer process))))
643     (nnoo-close-server 'nntp)))
644
645 (deffoo nntp-request-close ()
646   (let (process)
647     (while (setq process (pop nntp-connection-list))
648       (when (memq (process-status process) '(open run))
649         (set-process-sentinel process nil)
650         (ignore-errors
651           (nntp-send-string process "QUIT")
652           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
653             (sleep-for 1))))
654       (when (buffer-name (process-buffer process))
655         (kill-buffer (process-buffer process))))))
656
657 (deffoo nntp-request-list (&optional server)
658   (nntp-possibly-change-group nil server)
659   (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST"))
660
661 (deffoo nntp-request-list-newsgroups (&optional server)
662   (nntp-possibly-change-group nil server)
663   (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS"))
664
665 (deffoo nntp-request-newgroups (date &optional server)
666   (nntp-possibly-change-group nil server)
667   (save-excursion
668     (set-buffer nntp-server-buffer)
669     (let* ((date (timezone-parse-date date))
670            (time-string
671             (format "%s%02d%02d %s%s%s"
672                     (substring (aref date 0) 2) (string-to-int (aref date 1))
673                     (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
674                     (substring
675                      (aref date 3) 3 5) (substring (aref date 3) 6 8))))
676       (prog1
677           (nntp-send-command "^\\.\r?\n" "NEWGROUPS" time-string)
678         (nntp-decode-text)))))
679
680 (deffoo nntp-request-post (&optional server)
681   (nntp-possibly-change-group nil server)
682   (when (nntp-send-command "^[23].*\r?\n" "POST")
683     (nntp-send-buffer "^[23].*\n")))
684
685 (deffoo nntp-request-type (group article)
686   'news)
687
688 (deffoo nntp-asynchronous-p ()
689   t)
690
691 ;;; Hooky functions.
692
693 (defun nntp-send-mode-reader ()
694   "Send the MODE READER command to the nntp server.
695 This function is supposed to be called from `nntp-server-opened-hook'.
696 It will make innd servers spawn an nnrpd process to allow actual article
697 reading."
698   (nntp-send-command "^.*\r?\n" "MODE READER"))
699
700 (defun nntp-send-nosy-authinfo ()
701   "Send the AUTHINFO to the nntp server.
702 This function is supposed to be called from `nntp-server-opened-hook'.
703 It will prompt for a password."
704   (nntp-send-command
705    "^.*\r?\n" "AUTHINFO USER"
706    (read-string (format "NNTP (%s) user name: " nntp-address)))
707   (nntp-send-command
708    "^.*\r?\n" "AUTHINFO PASS"
709    (nnmail-read-passwd "NNTP (%s) password: " nntp-address)))
710
711 (defun nntp-send-authinfo ()
712   "Send the AUTHINFO to the nntp server.
713 This function is supposed to be called from `nntp-server-opened-hook'.
714 It will prompt for a password."
715   (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
716   (nntp-send-command
717    "^.*\r?\n" "AUTHINFO PASS"
718    (nnmail-read-passwd (format "NNTP (%s) password: " nntp-address))))
719
720 (defun nntp-send-authinfo-from-file ()
721   "Send the AUTHINFO to the nntp server.
722 This function is supposed to be called from `nntp-server-opened-hook'."
723   (when (file-exists-p "~/.nntp-authinfo")
724     (nnheader-temp-write nil
725       (insert-file-contents "~/.nntp-authinfo")
726       (goto-char (point-min))
727       (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
728       (nntp-send-command
729        "^.*\r?\n" "AUTHINFO PASS"
730        (buffer-substring (point) (progn (end-of-line) (point)))))))
731
732 ;;; Internal functions.
733
734 (defun nntp-make-process-buffer (buffer)
735   "Create a new, fresh buffer usable for nntp process connections."
736   (save-excursion
737     (set-buffer
738      (generate-new-buffer
739       (format " *server %s %s %s*"
740               nntp-address nntp-port-number
741               (buffer-name (get-buffer buffer)))))
742     (buffer-disable-undo (current-buffer))
743     (set (make-local-variable 'after-change-functions) nil)
744     (set (make-local-variable 'nntp-process-wait-for) nil)
745     (set (make-local-variable 'nntp-process-callback) nil)
746     (set (make-local-variable 'nntp-process-to-buffer) nil)
747     (set (make-local-variable 'nntp-process-start-point) nil)
748     (set (make-local-variable 'nntp-process-decode) nil)
749     (current-buffer)))
750
751 (defun nntp-open-connection (buffer)
752   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
753   (run-hooks 'nntp-prepare-server-hook)
754   (let* ((pbuffer (nntp-make-process-buffer buffer))
755          (process
756           (condition-case ()
757               (let ((coding-system-for-read nntp-coding-system-for-read))
758                 (funcall nntp-open-connection-function pbuffer))
759             (error nil)
760             (quit nil))))
761     (when process
762       (process-kill-without-query process)
763       (nntp-wait-for process "^.*\n" buffer nil t)
764       (if (memq (process-status process) '(open run))
765           (prog1
766               (caar (push (list process buffer nil) nntp-connection-alist))
767             (push process nntp-connection-list)
768             (save-excursion
769               (set-buffer pbuffer)
770               (nntp-read-server-type)
771               (erase-buffer)
772               (set-buffer nntp-server-buffer)
773               (let ((nnheader-callback-function nil))
774                 (run-hooks 'nntp-server-opened-hook))))
775         (when (buffer-name (process-buffer process))
776           (kill-buffer (process-buffer process)))
777         nil))))
778
779 (defun nntp-open-network-stream (buffer)
780   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
781
782 (defun nntp-read-server-type ()
783   "Find out what the name of the server we have connected to is."
784   ;; Wait for the status string to arrive.
785   (setq nntp-server-type (buffer-string))
786   (let ((alist nntp-server-action-alist)
787         (case-fold-search t)
788         entry)
789     ;; Run server-specific commands.
790     (while alist
791       (setq entry (pop alist))
792       (when (string-match (car entry) nntp-server-type)
793         (if (and (listp (cadr entry))
794                  (not (eq 'lambda (caadr entry))))
795             (eval (cadr entry))
796           (funcall (cadr entry)))))))
797
798 (defun nntp-after-change-function-callback (beg end len)
799   (when nntp-process-callback
800     (save-match-data
801       (if (and (= beg (point-min))
802                (memq (char-after beg) '(?4 ?5)))
803           ;; Report back error messages.
804           (save-excursion
805             (goto-char beg)
806             (if (looking-at "480")
807                 (funcall nntp-authinfo-function)
808               (nntp-snarf-error-message)
809               (funcall nntp-process-callback nil)))
810         (goto-char end)
811         (when (and (> (point) nntp-process-start-point)
812                    (re-search-backward nntp-process-wait-for
813                                        nntp-process-start-point t))
814           (when (buffer-name (get-buffer nntp-process-to-buffer))
815             (let ((cur (current-buffer))
816                   (start nntp-process-start-point))
817               (save-excursion
818                 (set-buffer (get-buffer nntp-process-to-buffer))
819                 (goto-char (point-max))
820                 (let ((b (point)))
821                   (insert-buffer-substring cur start)
822                   (narrow-to-region b (point-max))
823                   (nntp-decode-text)
824                   (widen)))))
825           (goto-char end)
826           (let ((callback nntp-process-callback)
827                 (nntp-inside-change-function t))
828             (setq nntp-process-callback nil)
829             (save-excursion
830               (funcall callback (buffer-name
831                                  (get-buffer nntp-process-to-buffer))))))))))
832
833 (defun nntp-snarf-error-message ()
834   "Save the error message in the current buffer."
835   (let ((message (buffer-string)))
836     (while (string-match "[\r\n]+" message)
837       (setq message (replace-match " " t t message)))
838     (nnheader-report 'nntp message)
839     message))
840
841 (defun nntp-accept-process-output (process)
842   "Wait for output from PROCESS and message some dots."
843   (save-excursion
844     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
845                     nntp-server-buffer))
846     (let ((len (/ (point-max) 1024))
847           message-log-max)
848       (unless (< len 10)
849         (setq nntp-have-messaged t)
850         (nnheader-message 7 "nntp read: %dk" len)))
851     (accept-process-output process 1)))
852
853 (defun nntp-accept-response ()
854   "Wait for output from the process that outputs to BUFFER."
855   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
856
857 (defun nntp-possibly-change-group (group server &optional connectionless)
858   (let ((nnheader-callback-function nil))
859     (when server
860       (or (nntp-server-opened server)
861           (nntp-open-server server nil connectionless)))
862
863     (unless connectionless
864       (or (nntp-find-connection nntp-server-buffer)
865           (nntp-open-connection nntp-server-buffer))))
866
867   (when group
868     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
869       (when (not (equal group (caddr entry)))
870         (save-excursion
871           (set-buffer (process-buffer (car entry)))
872           (erase-buffer)
873           (nntp-send-string (car entry) (concat "GROUP " group))
874           (nntp-wait-for-string "^2.*\n")
875           (setcar (cddr entry) group)
876           (erase-buffer))))))
877
878 (defun nntp-decode-text (&optional cr-only)
879   "Decode the text in the current buffer."
880   (goto-char (point-min))
881   (while (search-forward "\r" nil t)
882     (delete-char -1))
883   (unless cr-only
884     ;; Remove trailing ".\n" end-of-transfer marker.
885     (goto-char (point-max))
886     (forward-line -1)
887     (when (looking-at ".\n")
888       (delete-char 2))
889     ;; Delete status line.
890     (goto-char (point-min))
891     (delete-region (point) (progn (forward-line 1) (point)))
892     ;; Remove "." -> ".." encoding.
893     (while (search-forward "\n.." nil t)
894       (delete-char -1))))
895
896 (defun nntp-encode-text ()
897   "Encode the text in the current buffer."
898   (save-excursion
899     ;; Replace "." at beginning of line with "..".
900     (goto-char (point-min))
901     (while (re-search-forward "^\\." nil t)
902       (insert "."))
903     (goto-char (point-max))
904     ;; Insert newline at the end of the buffer.
905     (unless (bolp)
906       (insert "\n"))
907     ;; Insert `.' at end of buffer (end of text mark).
908     (goto-char (point-max))
909     (insert ".\n")
910     (goto-char (point-min))
911     (while (not (eobp))
912       (end-of-line)
913       (insert "\r")
914       (forward-line 1))))
915
916 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
917   (set-buffer nntp-server-buffer)
918   (erase-buffer)
919   (cond
920
921    ;; This server does not talk NOV.
922    ((not nntp-server-xover)
923     nil)
924
925    ;; We don't care about gaps.
926    ((or (not nntp-nov-gap)
927         fetch-old)
928     (nntp-send-xover-command
929      (if fetch-old
930          (if (numberp fetch-old)
931              (max 1 (- (car articles) fetch-old))
932            1)
933        (car articles))
934      (car (last articles)) 'wait)
935
936     (goto-char (point-min))
937     (when (looking-at "[1-5][0-9][0-9] ")
938       (delete-region (point) (progn (forward-line 1) (point))))
939     (while (search-forward "\r" nil t)
940       (replace-match "" t t))
941     (goto-char (point-max))
942     (forward-line -1)
943     (when (looking-at "\\.")
944       (delete-region (point) (progn (forward-line 1) (point)))))
945
946    ;; We do it the hard way.  For each gap, an XOVER command is sent
947    ;; to the server.  We do not wait for a reply from the server, we
948    ;; just send them off as fast as we can.  That means that we have
949    ;; to count the number of responses we get back to find out when we
950    ;; have gotten all we asked for.
951    ((numberp nntp-nov-gap)
952     (let ((count 0)
953           (received 0)
954           (last-point (point-min))
955           (buf nntp-server-buffer)
956           ;;(process-buffer (nntp-find-connection (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         ;;(copy-to-buffer nntp-server-buffer (point-min) (point-max))
1011         t))))
1012
1013   nntp-server-xover)
1014
1015 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1016   "Send the XOVER command to the server."
1017   (let ((range (format "%d-%d" beg end))
1018         (nntp-inhibit-erase t))
1019     (if (stringp nntp-server-xover)
1020         ;; If `nntp-server-xover' is a string, then we just send this
1021         ;; command.
1022         (if wait-for-reply
1023             (nntp-send-command-nodelete
1024              "\r?\n\\.\r?\n" nntp-server-xover range)
1025           ;; We do not wait for the reply.
1026           (nntp-send-command-nodelete "\r?\n\\.\r?\n" nntp-server-xover range))
1027       (let ((commands nntp-xover-commands))
1028         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1029         ;; We try them all until we get at positive response.
1030         (while (and commands (eq nntp-server-xover 'try))
1031           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1032           (save-excursion
1033             (set-buffer nntp-server-buffer)
1034             (goto-char (point-min))
1035             (and (looking-at "[23]")    ; No error message.
1036                  ;; We also have to look at the lines.  Some buggy
1037                  ;; servers give back simple lines with just the
1038                  ;; article number.  How... helpful.
1039                  (progn
1040                    (forward-line 1)
1041                    (looking-at "[0-9]+\t...")) ; More text after number.
1042                  (setq nntp-server-xover (car commands))))
1043           (setq commands (cdr commands)))
1044         ;; If none of the commands worked, we disable XOVER.
1045         (when (eq nntp-server-xover 'try)
1046           (save-excursion
1047             (set-buffer nntp-server-buffer)
1048             (erase-buffer)
1049             (setq nntp-server-xover nil)))
1050         nntp-server-xover))))
1051
1052 ;;; Alternative connection methods.
1053
1054 (defun nntp-wait-for-string (regexp)
1055   "Wait until string arrives in the buffer."
1056   (let ((buf (current-buffer)))
1057     (goto-char (point-min))
1058     (while (not (re-search-forward regexp nil t))
1059       (accept-process-output (nntp-find-connection nntp-server-buffer))
1060       (set-buffer buf)
1061       (goto-char (point-min)))))
1062
1063 (defun nntp-open-telnet (buffer)
1064   (save-excursion
1065     (set-buffer buffer)
1066     (erase-buffer)
1067     (let ((proc (apply
1068                  'start-process
1069                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1070           (case-fold-search t))
1071       (when (memq (process-status proc) '(open run))
1072         (process-send-string proc "set escape \^X\n")
1073         (process-send-string proc (concat "open " nntp-address "\n"))
1074         (nntp-wait-for-string "^\r*.?login:")
1075         (process-send-string
1076          proc (concat
1077                (or nntp-telnet-user-name
1078                    (setq nntp-telnet-user-name (read-string "login: ")))
1079                "\n"))
1080         (nntp-wait-for-string "^\r*.?password:")
1081         (process-send-string
1082          proc (concat
1083                (or nntp-telnet-passwd
1084                    (setq nntp-telnet-passwd
1085                          (nnmail-read-passwd "Password: ")))
1086                "\n"))
1087         (erase-buffer)
1088         (nntp-wait-for-string "bash\\|\$ *\r?$\\|> *\r?")
1089         (process-send-string
1090          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1091         (nntp-wait-for-string "^\r*20[01]")
1092         (beginning-of-line)
1093         (delete-region (point-min) (point))
1094         (process-send-string proc "\^]")
1095         (nntp-wait-for-string "^telnet")
1096         (process-send-string proc "mode character\n")
1097         (accept-process-output proc 1)
1098         (sit-for 1)
1099         (goto-char (point-min))
1100         (forward-line 1)
1101         (delete-region (point) (point-max)))
1102       proc)))
1103
1104 (defun nntp-open-rlogin (buffer)
1105   "Open a connection to SERVER using rsh."
1106   (let ((proc (if nntp-rlogin-user-name
1107                   (apply 'start-process
1108                          "nntpd" buffer nntp-rlogin-program
1109                          nntp-address "-l" nntp-rlogin-user-name
1110                          nntp-rlogin-parameters)
1111                 (apply 'start-process
1112                        "nntpd" buffer nntp-rlogin-program nntp-address
1113                        nntp-rlogin-parameters))))
1114     (set-buffer buffer)
1115     (nntp-wait-for-string "^\r*20[01]")
1116     (beginning-of-line)
1117     (delete-region (point-min) (point))
1118     proc))
1119
1120 (defun nntp-find-group-and-number ()
1121   (save-excursion
1122     (save-restriction
1123       (set-buffer nntp-server-buffer)
1124       (narrow-to-region (goto-char (point-min))
1125                         (or (search-forward "\n\n" nil t) (point-max)))
1126       (goto-char (point-min))
1127       ;; We first find the number by looking at the status line.
1128       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1129                          (string-to-int
1130                           (buffer-substring (match-beginning 1)
1131                                             (match-end 1)))))
1132             group newsgroups xref)
1133         (and number (zerop number) (setq number nil))
1134         ;; Then we find the group name.
1135         (setq group
1136               (cond
1137                ;; If there is only one group in the Newsgroups header,
1138                ;; then it seems quite likely that this article comes
1139                ;; from that group, I'd say.
1140                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
1141                      (not (string-match "," newsgroups)))
1142                 newsgroups)
1143                ;; If there is more than one group in the Newsgroups
1144                ;; header, then the Xref header should be filled out.
1145                ;; We hazard a guess that the group that has this
1146                ;; article number in the Xref header is the one we are
1147                ;; looking for.  This might very well be wrong if this
1148                ;; article happens to have the same number in several
1149                ;; groups, but that's life.
1150                ((and (setq xref (mail-fetch-field "xref"))
1151                      number
1152                      (string-match (format "\\([^ :]+\\):%d" number) xref))
1153                 (substring xref (match-beginning 1) (match-end 1)))
1154                (t "")))
1155         (when (string-match "\r" group)
1156           (setq group (substring group 0 (match-beginning 0))))
1157         (cons group number)))))
1158
1159 (provide 'nntp)
1160
1161 ;;; nntp.el ends here