*** 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-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           (sleep-for 1)))
639       (when (buffer-name (process-buffer process))
640         (kill-buffer (process-buffer process))))
641     (nnoo-close-server 'nntp)))
642
643 (deffoo nntp-request-close ()
644   (let (process)
645     (while (setq process (pop nntp-connection-list))
646       (when (memq (process-status process) '(open run))
647         (set-process-sentinel process nil)
648         (ignore-errors
649           (nntp-send-string process "QUIT")
650           (sleep-for 1)))
651       (when (buffer-name (process-buffer process))
652         (kill-buffer (process-buffer process))))))
653
654 (deffoo nntp-request-list (&optional server)
655   (nntp-possibly-change-group nil server)
656   (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST"))
657
658 (deffoo nntp-request-list-newsgroups (&optional server)
659   (nntp-possibly-change-group nil server)
660   (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS"))
661
662 (deffoo nntp-request-newgroups (date &optional server)
663   (nntp-possibly-change-group nil server)
664   (save-excursion
665     (set-buffer nntp-server-buffer)
666     (let* ((date (timezone-parse-date date))
667            (time-string
668             (format "%s%02d%02d %s%s%s"
669                     (substring (aref date 0) 2) (string-to-int (aref date 1))
670                     (string-to-int (aref date 2)) (substring (aref date 3) 0 2)
671                     (substring
672                      (aref date 3) 3 5) (substring (aref date 3) 6 8))))
673       (prog1
674           (nntp-send-command "^\\.\r?\n" "NEWGROUPS" time-string)
675         (nntp-decode-text)))))
676
677 (deffoo nntp-request-post (&optional server)
678   (nntp-possibly-change-group nil server)
679   (when (nntp-send-command "^[23].*\r?\n" "POST")
680     (nntp-send-buffer "^[23].*\n")))
681
682 (deffoo nntp-request-type (group article)
683   'news)
684
685 (deffoo nntp-asynchronous-p ()
686   t)
687
688 ;;; Hooky functions.
689
690 (defun nntp-send-mode-reader ()
691   "Send the MODE READER command to the nntp server.
692 This function is supposed to be called from `nntp-server-opened-hook'.
693 It will make innd servers spawn an nnrpd process to allow actual article
694 reading."
695   (nntp-send-command "^.*\r?\n" "MODE READER"))
696
697 (defun nntp-send-nosy-authinfo ()
698   "Send the AUTHINFO to the nntp server.
699 This function is supposed to be called from `nntp-server-opened-hook'.
700 It will prompt for a password."
701   (nntp-send-command
702    "^.*\r?\n" "AUTHINFO USER"
703    (read-string (format "NNTP (%s) user name: " nntp-address)))
704   (nntp-send-command
705    "^.*\r?\n" "AUTHINFO PASS"
706    (nnmail-read-passwd "NNTP (%s) password: " nntp-address)))
707
708 (defun nntp-send-authinfo ()
709   "Send the AUTHINFO to the nntp server.
710 This function is supposed to be called from `nntp-server-opened-hook'.
711 It will prompt for a password."
712   (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
713   (nntp-send-command
714    "^.*\r?\n" "AUTHINFO PASS"
715    (nnmail-read-passwd (format "NNTP (%s) password: " nntp-address))))
716
717 (defun nntp-send-authinfo-from-file ()
718   "Send the AUTHINFO to the nntp server.
719 This function is supposed to be called from `nntp-server-opened-hook'."
720   (when (file-exists-p "~/.nntp-authinfo")
721     (nnheader-temp-write nil
722       (insert-file-contents "~/.nntp-authinfo")
723       (goto-char (point-min))
724       (nntp-send-command "^.*\r?\n" "AUTHINFO USER" (user-login-name))
725       (nntp-send-command
726        "^.*\r?\n" "AUTHINFO PASS"
727        (buffer-substring (point) (progn (end-of-line) (point)))))))
728
729 ;;; Internal functions.
730
731 (defun nntp-make-process-buffer (buffer)
732   "Create a new, fresh buffer usable for nntp process connections."
733   (save-excursion
734     (set-buffer
735      (generate-new-buffer
736       (format " *server %s %s %s*"
737               nntp-address nntp-port-number
738               (buffer-name (get-buffer buffer)))))
739     (buffer-disable-undo (current-buffer))
740     (set (make-local-variable 'after-change-functions) nil)
741     (set (make-local-variable 'nntp-process-wait-for) nil)
742     (set (make-local-variable 'nntp-process-callback) nil)
743     (set (make-local-variable 'nntp-process-to-buffer) nil)
744     (set (make-local-variable 'nntp-process-start-point) nil)
745     (set (make-local-variable 'nntp-process-decode) nil)
746     (current-buffer)))
747
748 (defun nntp-open-connection (buffer)
749   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
750   (run-hooks 'nntp-prepare-server-hook)
751   (let* ((pbuffer (nntp-make-process-buffer buffer))
752          (process
753           (condition-case ()
754               (let ((coding-system-for-read nntp-coding-system-for-read))
755                 (funcall nntp-open-connection-function pbuffer))
756             (error nil)
757             (quit nil))))
758     (when process
759       (process-kill-without-query process)
760       (nntp-wait-for process "^.*\n" buffer nil t)
761       (if (memq (process-status process) '(open run))
762           (prog1
763               (caar (push (list process buffer nil) nntp-connection-alist))
764             (push process nntp-connection-list)
765             (save-excursion
766               (set-buffer pbuffer)
767               (nntp-read-server-type)
768               (erase-buffer)
769               (set-buffer nntp-server-buffer)
770               (let ((nnheader-callback-function nil))
771                 (run-hooks 'nntp-server-opened-hook))))
772         (when (buffer-name (process-buffer process))
773           (kill-buffer (process-buffer process)))
774         nil))))
775
776 (defun nntp-open-network-stream (buffer)
777   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
778
779 (defun nntp-read-server-type ()
780   "Find out what the name of the server we have connected to is."
781   ;; Wait for the status string to arrive.
782   (setq nntp-server-type (buffer-string))
783   (let ((alist nntp-server-action-alist)
784         (case-fold-search t)
785         entry)
786     ;; Run server-specific commands.
787     (while alist
788       (setq entry (pop alist))
789       (when (string-match (car entry) nntp-server-type)
790         (if (and (listp (cadr entry))
791                  (not (eq 'lambda (caadr entry))))
792             (eval (cadr entry))
793           (funcall (cadr entry)))))))
794
795 (defun nntp-after-change-function-callback (beg end len)
796   (when nntp-process-callback
797     (save-match-data
798       (if (and (= beg (point-min))
799                (memq (char-after beg) '(?4 ?5)))
800           ;; Report back error messages.
801           (save-excursion
802             (goto-char beg)
803             (if (looking-at "480")
804                 (funcall nntp-authinfo-function)
805               (nntp-snarf-error-message)
806               (funcall nntp-process-callback nil)))
807         (goto-char end)
808         (when (and (> (point) nntp-process-start-point)
809                    (re-search-backward nntp-process-wait-for
810                                        nntp-process-start-point t))
811           (when (buffer-name (get-buffer nntp-process-to-buffer))
812             (let ((cur (current-buffer))
813                   (start nntp-process-start-point))
814               (save-excursion
815                 (set-buffer (get-buffer nntp-process-to-buffer))
816                 (goto-char (point-max))
817                 (let ((b (point)))
818                   (insert-buffer-substring cur start)
819                   (narrow-to-region b (point-max))
820                   (nntp-decode-text)
821                   (widen)))))
822           (goto-char end)
823           (let ((callback nntp-process-callback)
824                 (nntp-inside-change-function t))
825             (setq nntp-process-callback nil)
826             (save-excursion
827               (funcall callback (buffer-name
828                                  (get-buffer nntp-process-to-buffer))))))))))
829
830 (defun nntp-snarf-error-message ()
831   "Save the error message in the current buffer."
832   (let ((message (buffer-string)))
833     (while (string-match "[\r\n]+" message)
834       (setq message (replace-match " " t t message)))
835     (nnheader-report 'nntp message)
836     message))
837
838 (defun nntp-accept-process-output (process)
839   "Wait for output from PROCESS and message some dots."
840   (save-excursion
841     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
842                     nntp-server-buffer))
843     (let ((len (/ (point-max) 1024))
844           message-log-max)
845       (unless (< len 10)
846         (setq nntp-have-messaged t)
847         (nnheader-message 7 "nntp read: %dk" len)))
848     (accept-process-output process 1)))
849
850 (defun nntp-accept-response ()
851   "Wait for output from the process that outputs to BUFFER."
852   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
853
854 (defun nntp-possibly-change-group (group server &optional connectionless)
855   (let ((nnheader-callback-function nil))
856     (when server
857       (or (nntp-server-opened server)
858           (nntp-open-server server nil connectionless)))
859
860     (unless connectionless
861       (or (nntp-find-connection nntp-server-buffer)
862           (nntp-open-connection nntp-server-buffer))))
863
864   (when group
865     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
866       (when (not (equal group (caddr entry)))
867         (save-excursion
868           (set-buffer (process-buffer (car entry)))
869           (erase-buffer)
870           (nntp-send-string (car entry) (concat "GROUP " group))
871           (nntp-wait-for-string "^2.*\n")
872           (setcar (cddr entry) group)
873           (erase-buffer))))))
874
875 (defun nntp-decode-text (&optional cr-only)
876   "Decode the text in the current buffer."
877   (goto-char (point-min))
878   (while (search-forward "\r" nil t)
879     (delete-char -1))
880   (unless cr-only
881     ;; Remove trailing ".\n" end-of-transfer marker.
882     (goto-char (point-max))
883     (forward-line -1)
884     (when (looking-at ".\n")
885       (delete-char 2))
886     ;; Delete status line.
887     (goto-char (point-min))
888     (delete-region (point) (progn (forward-line 1) (point)))
889     ;; Remove "." -> ".." encoding.
890     (while (search-forward "\n.." nil t)
891       (delete-char -1))))
892
893 (defun nntp-encode-text ()
894   "Encode the text in the current buffer."
895   (save-excursion
896     ;; Replace "." at beginning of line with "..".
897     (goto-char (point-min))
898     (while (re-search-forward "^\\." nil t)
899       (insert "."))
900     (goto-char (point-max))
901     ;; Insert newline at the end of the buffer.
902     (unless (bolp)
903       (insert "\n"))
904     ;; Insert `.' at end of buffer (end of text mark).
905     (goto-char (point-max))
906     (insert ".\n")
907     (goto-char (point-min))
908     (while (not (eobp))
909       (end-of-line)
910       (insert "\r")
911       (forward-line 1))))
912
913 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
914   (set-buffer nntp-server-buffer)
915   (erase-buffer)
916   (cond
917
918    ;; This server does not talk NOV.
919    ((not nntp-server-xover)
920     nil)
921
922    ;; We don't care about gaps.
923    ((or (not nntp-nov-gap)
924         fetch-old)
925     (nntp-send-xover-command
926      (if fetch-old
927          (if (numberp fetch-old)
928              (max 1 (- (car articles) fetch-old))
929            1)
930        (car articles))
931      (car (last articles)) 'wait)
932
933     (goto-char (point-min))
934     (when (looking-at "[1-5][0-9][0-9] ")
935       (delete-region (point) (progn (forward-line 1) (point))))
936     (while (search-forward "\r" nil t)
937       (replace-match "" t t))
938     (goto-char (point-max))
939     (forward-line -1)
940     (when (looking-at "\\.")
941       (delete-region (point) (progn (forward-line 1) (point)))))
942
943    ;; We do it the hard way.  For each gap, an XOVER command is sent
944    ;; to the server.  We do not wait for a reply from the server, we
945    ;; just send them off as fast as we can.  That means that we have
946    ;; to count the number of responses we get back to find out when we
947    ;; have gotten all we asked for.
948    ((numberp nntp-nov-gap)
949     (let ((count 0)
950           (received 0)
951           (last-point (point-min))
952           (buf nntp-server-buffer)
953           ;;(process-buffer (nntp-find-connection (current-buffer))))
954           first)
955       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
956       ;; that means that the server does not understand XOVER, but we
957       ;; won't know that until we try.
958       (while (and nntp-server-xover articles)
959         (setq first (car articles))
960         ;; Search forward until we find a gap, or until we run out of
961         ;; articles.
962         (while (and (cdr articles)
963                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
964           (setq articles (cdr articles)))
965
966         (when (nntp-send-xover-command first (car articles))
967           (setq articles (cdr articles)
968                 count (1+ count))
969
970           ;; Every 400 requests we have to read the stream in
971           ;; order to avoid deadlocks.
972           (when (or (null articles)     ;All requests have been sent.
973                     (zerop (% count nntp-maximum-request)))
974             (accept-process-output)
975             ;; On some Emacs versions the preceding function has
976             ;; a tendency to change the buffer.  Perhaps.  It's
977             ;; quite difficult to reproduce, because it only
978             ;; seems to happen once in a blue moon.
979             (set-buffer buf)
980             (while (progn
981                      (goto-char last-point)
982                      ;; Count replies.
983                      (while (re-search-forward "^[0-9][0-9][0-9] " nil t)
984                        (setq received (1+ received)))
985                      (setq last-point (point))
986                      (< received count))
987               (accept-process-output)
988               (set-buffer buf)))))
989
990       (when nntp-server-xover
991         ;; Wait for the reply from the final command.
992         (goto-char (point-max))
993         (re-search-backward "^[0-9][0-9][0-9] " nil t)
994         (when (looking-at "^[23]")
995           (while (progn
996                    (goto-char (point-max))
997                    (forward-line -1)
998                    (not (looking-at "^\\.\r?\n")))
999             (nntp-accept-response)))
1000
1001         ;; We remove any "." lines and status lines.
1002         (goto-char (point-min))
1003         (while (search-forward "\r" nil t)
1004           (delete-char -1))
1005         (goto-char (point-min))
1006         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1007         ;;(copy-to-buffer nntp-server-buffer (point-min) (point-max))
1008         t))))
1009
1010   nntp-server-xover)
1011
1012 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1013   "Send the XOVER command to the server."
1014   (let ((range (format "%d-%d" beg end))
1015         (nntp-inhibit-erase t))
1016     (if (stringp nntp-server-xover)
1017         ;; If `nntp-server-xover' is a string, then we just send this
1018         ;; command.
1019         (if wait-for-reply
1020             (nntp-send-command-nodelete
1021              "\r?\n\\.\r?\n" nntp-server-xover range)
1022           ;; We do not wait for the reply.
1023           (nntp-send-command-nodelete "\r?\n\\.\r?\n" nntp-server-xover range))
1024       (let ((commands nntp-xover-commands))
1025         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1026         ;; We try them all until we get at positive response.
1027         (while (and commands (eq nntp-server-xover 'try))
1028           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1029           (save-excursion
1030             (set-buffer nntp-server-buffer)
1031             (goto-char (point-min))
1032             (and (looking-at "[23]")    ; No error message.
1033                  ;; We also have to look at the lines.  Some buggy
1034                  ;; servers give back simple lines with just the
1035                  ;; article number.  How... helpful.
1036                  (progn
1037                    (forward-line 1)
1038                    (looking-at "[0-9]+\t...")) ; More text after number.
1039                  (setq nntp-server-xover (car commands))))
1040           (setq commands (cdr commands)))
1041         ;; If none of the commands worked, we disable XOVER.
1042         (when (eq nntp-server-xover 'try)
1043           (save-excursion
1044             (set-buffer nntp-server-buffer)
1045             (erase-buffer)
1046             (setq nntp-server-xover nil)))
1047         nntp-server-xover))))
1048
1049 ;;; Alternative connection methods.
1050
1051 (defun nntp-wait-for-string (regexp)
1052   "Wait until string arrives in the buffer."
1053   (let ((buf (current-buffer)))
1054     (goto-char (point-min))
1055     (while (not (re-search-forward regexp nil t))
1056       (accept-process-output (nntp-find-connection nntp-server-buffer))
1057       (set-buffer buf)
1058       (goto-char (point-min)))))
1059
1060 (defun nntp-open-telnet (buffer)
1061   (save-excursion
1062     (set-buffer buffer)
1063     (erase-buffer)
1064     (let ((proc (apply
1065                  'start-process
1066                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1067           (case-fold-search t))
1068       (when (memq (process-status proc) '(open run))
1069         (process-send-string proc "set escape \^X\n")
1070         (process-send-string proc (concat "open " nntp-address "\n"))
1071         (nntp-wait-for-string "^\r*.?login:")
1072         (process-send-string
1073          proc (concat
1074                (or nntp-telnet-user-name
1075                    (setq nntp-telnet-user-name (read-string "login: ")))
1076                "\n"))
1077         (nntp-wait-for-string "^\r*.?password:")
1078         (process-send-string
1079          proc (concat
1080                (or nntp-telnet-passwd
1081                    (setq nntp-telnet-passwd
1082                          (nnmail-read-passwd "Password: ")))
1083                "\n"))
1084         (erase-buffer)
1085         (nntp-wait-for-string "bash\\|\$ *\r?$\\|> *\r?")
1086         (process-send-string
1087          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1088         (nntp-wait-for-string "^\r*20[01]")
1089         (beginning-of-line)
1090         (delete-region (point-min) (point))
1091         (process-send-string proc "\^]")
1092         (nntp-wait-for-string "^telnet")
1093         (process-send-string proc "mode character\n")
1094         (accept-process-output proc 1)
1095         (sit-for 1)
1096         (goto-char (point-min))
1097         (forward-line 1)
1098         (delete-region (point) (point-max)))
1099       proc)))
1100
1101 (defun nntp-open-rlogin (buffer)
1102   "Open a connection to SERVER using rsh."
1103   (let ((proc (if nntp-rlogin-user-name
1104                   (start-process
1105                    "nntpd" buffer nntp-rlogin-program
1106                    nntp-address "-l" nntp-rlogin-user-name
1107                    (mapconcat 'identity
1108                               nntp-rlogin-parameters " "))
1109                 (start-process
1110                  "nntpd" buffer nntp-rlogin-program nntp-address
1111                  (mapconcat 'identity
1112                             nntp-rlogin-parameters " ")))))
1113     (set-buffer buffer)
1114     (nntp-wait-for-string "^\r*20[01]")
1115     (beginning-of-line)
1116     (delete-region (point-min) (point))
1117     proc))
1118
1119 (defun nntp-find-group-and-number ()
1120   (save-excursion
1121     (save-restriction
1122       (set-buffer nntp-server-buffer)
1123       (narrow-to-region (goto-char (point-min))
1124                         (or (search-forward "\n\n" nil t) (point-max)))
1125       (goto-char (point-min))
1126       ;; We first find the number by looking at the status line.
1127       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1128                          (string-to-int
1129                           (buffer-substring (match-beginning 1)
1130                                             (match-end 1)))))
1131             group newsgroups xref)
1132         (and number (zerop number) (setq number nil))
1133         ;; Then we find the group name.
1134         (setq group
1135               (cond
1136                ;; If there is only one group in the Newsgroups header,
1137                ;; then it seems quite likely that this article comes
1138                ;; from that group, I'd say.
1139                ((and (setq newsgroups (mail-fetch-field "newsgroups"))
1140                      (not (string-match "," newsgroups)))
1141                 newsgroups)
1142                ;; If there is more than one group in the Newsgroups
1143                ;; header, then the Xref header should be filled out.
1144                ;; We hazard a guess that the group that has this
1145                ;; article number in the Xref header is the one we are
1146                ;; looking for.  This might very well be wrong if this
1147                ;; article happens to have the same number in several
1148                ;; groups, but that's life.
1149                ((and (setq xref (mail-fetch-field "xref"))
1150                      number
1151                      (string-match (format "\\([^ :]+\\):%d" number) xref))
1152                 (substring xref (match-beginning 1) (match-end 1)))
1153                (t "")))
1154         (when (string-match "\r" group)
1155           (setq group (substring group 0 (match-beginning 0))))
1156         (cons group number)))))
1157
1158 (provide 'nntp)
1159
1160 ;;; nntp.el ends here