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