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