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