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