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