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