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