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