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