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