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