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