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