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