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