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