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