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