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