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