1;;; nntp.el --- nntp access for Gnus
2
3;; Copyright (C) 1987, 1988, 1989, 1990, 1992, 1993,
4;;   1994, 1995, 1996, 1997, 1998, 2000, 2001, 2002,
5;;   2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
6
7;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
8;; Keywords: news
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published
14;; by the Free Software Foundation; either version 2, or (at your
15;; option) any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful, but
18;; WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20;; General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs; see the file COPYING.  If not, write to the
24;; Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
25;; MA 02110-1301, USA.
26
27;;; Commentary:
28
29;;; Code:
30
31(require 'nnheader)
32(require 'nnoo)
33(require 'gnus-util)
34
35(nnoo-declare nntp)
36
37(eval-when-compile (require 'cl))
38
39(defgroup nntp nil
40  "NNTP access for Gnus."
41  :group 'gnus)
42
43(defvoo nntp-address nil
44  "Address of the physical nntp server.")
45
46(defvoo nntp-port-number "nntp"
47  "Port number on the physical nntp server.")
48
49(defvoo nntp-server-opened-hook '(nntp-send-mode-reader)
50  "*Hook used for sending commands to the server at startup.
51The default value is `nntp-send-mode-reader', which makes an innd
52server spawn an nnrpd server.")
53
54(defvoo nntp-authinfo-function 'nntp-send-authinfo
55  "Function used to send AUTHINFO to the server.
56It is called with no parameters.")
57
58(defvoo nntp-server-action-alist
59    '(("nntpd 1\\.5\\.11t"
60       (remove-hook 'nntp-server-opened-hook 'nntp-send-mode-reader))
61      ("NNRP server Netscape"
62       (setq nntp-server-list-active-group nil)))
63  "Alist of regexps to match on server types and actions to be taken.
64For instance, if you want Gnus to beep every time you connect
65to innd, you could say something like:
66
67\(setq nntp-server-action-alist
68       '((\"innd\" (ding))))
69
70You probably don't want to do that, though.")
71
72(defvoo nntp-open-connection-function 'nntp-open-network-stream
73  "*Function used for connecting to a remote system.
74It will be called with the buffer to output in as argument.
75
76Currently, five such functions are provided (please refer to their
77respective doc string for more information), three of them establishing
78direct connections to the nntp server, and two of them using an indirect
79host.
80
81Direct connections:
82- `nntp-open-network-stream' (the default),
83- `nntp-open-ssl-stream',
84- `nntp-open-tls-stream',
85- `nntp-open-telnet-stream'.
86
87Indirect connections:
88- `nntp-open-via-rlogin-and-telnet',
89- `nntp-open-via-telnet-and-telnet'.")
90
91(defvoo nntp-never-echoes-commands nil
92  "*Non-nil means the nntp server never echoes commands.
93It is reported that some nntps server doesn't echo commands.  So, you
94may want to set this to non-nil in the method for such a server setting
95`nntp-open-connection-function' to `nntp-open-ssl-stream' for example.
96Note that the `nntp-open-connection-functions-never-echo-commands'
97variable overrides the nil value of this variable.")
98
99(defvoo nntp-open-connection-functions-never-echo-commands
100    '(nntp-open-network-stream)
101  "*List of functions that never echo commands.
102Add or set a function which you set to `nntp-open-connection-function'
103to this list if it does not echo commands.  Note that a non-nil value
104of the `nntp-never-echoes-commands' variable overrides this variable.")
105
106(defvoo nntp-pre-command nil
107  "*Pre-command to use with the various nntp-open-via-* methods.
108This is where you would put \"runsocks\" or stuff like that.")
109
110(defvoo nntp-telnet-command "telnet"
111  "*Telnet command used to connect to the nntp server.
112This command is used by the various nntp-open-via-* methods.")
113
114(defvoo nntp-telnet-switches '("-8")
115  "*Switches given to the telnet command `nntp-telnet-command'.")
116
117(defvoo nntp-end-of-line "\r\n"
118  "*String to use on the end of lines when talking to the NNTP server.
119This is \"\\r\\n\" by default, but should be \"\\n\" when
120using an indirect connection method (nntp-open-via-*).")
121
122(defvoo nntp-via-rlogin-command "rsh"
123  "*Rlogin command used to connect to an intermediate host.
124This command is used by the `nntp-open-via-rlogin-and-telnet' method.
125The default is \"rsh\", but \"ssh\" is a popular alternative.")
126
127(defvoo nntp-via-rlogin-command-switches nil
128  "*Switches given to the rlogin command `nntp-via-rlogin-command'.
129If you use \"ssh\" for `nntp-via-rlogin-command', you may set this to
130\(\"-C\") in order to compress all data connections, otherwise set this
131to \(\"-t\" \"-e\" \"none\") or (\"-C\" \"-t\" \"-e\" \"none\") if the telnet
132command requires a pseudo-tty allocation on an intermediate host.")
133
134(defvoo nntp-via-telnet-command "telnet"
135  "*Telnet command used to connect to an intermediate host.
136This command is used by the `nntp-open-via-telnet-and-telnet' method.")
137
138(defvoo nntp-via-telnet-switches '("-8")
139  "*Switches given to the telnet command `nntp-via-telnet-command'.")
140
141(defvoo nntp-via-user-name nil
142  "*User name to log in on an intermediate host with.
143This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
144
145(defvoo nntp-via-user-password nil
146  "*Password to use to log in on an intermediate host with.
147This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
148
149(defvoo nntp-via-address nil
150  "*Address of an intermediate host to connect to.
151This variable is used by the `nntp-open-via-rlogin-and-telnet' and
152`nntp-open-via-telnet-and-telnet' methods.")
153
154(defvoo nntp-via-envuser nil
155  "*Whether both telnet client and server support the ENVIRON option.
156If non-nil, there will be no prompt for a login name.")
157
158(defvoo nntp-via-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
159  "*Regular expression to match the shell prompt on an intermediate host.
160This variable is used by the `nntp-open-via-telnet-and-telnet' method.")
161
162(defvoo nntp-large-newsgroup 50
163  "*The number of articles which indicates a large newsgroup.
164If the number of articles is greater than the value, verbose
165messages will be shown to indicate the current status.")
166
167(defvoo nntp-maximum-request 400
168  "*The maximum number of the requests sent to the NNTP server at one time.
169If Emacs hangs up while retrieving headers, set the variable to a
170lower value.")
171
172(defvoo nntp-nov-is-evil nil
173  "*If non-nil, nntp will never attempt to use XOVER when talking to the server.")
174
175(defvoo nntp-xover-commands '("XOVER" "XOVERVIEW")
176  "*List of strings that are used as commands to fetch NOV lines from a server.
177The strings are tried in turn until a positive response is gotten.  If
178none of the commands are successful, nntp will just grab headers one
179by one.")
180
181(defvoo nntp-nov-gap 5
182  "*Maximum allowed gap between two articles.
183If the gap between two consecutive articles is bigger than this
184variable, split the XOVER request into two requests.")
185
186(defvoo nntp-prepare-server-hook nil
187  "*Hook run before a server is opened.
188If can be used to set up a server remotely, for instance.  Say you
189have an account at the machine \"other.machine\".  This machine has
190access to an NNTP server that you can't access locally.  You could
191then use this hook to rsh to the remote machine and start a proxy NNTP
192server there that you can connect to.  See also
193`nntp-open-connection-function'")
194
195(defvoo nntp-coding-system-for-read 'binary
196  "*Coding system to read from NNTP.")
197
198(defvoo nntp-coding-system-for-write 'binary
199  "*Coding system to write to NNTP.")
200
201(defcustom nntp-authinfo-file "~/.authinfo"
202  ".netrc-like file that holds nntp authinfo passwords."
203  :group 'nntp
204  :type
205  '(choice file
206	   (repeat :tag "Entries"
207		   :menu-tag "Inline"
208		   (list :format "%v"
209			 :value ("" ("login" . "") ("password" . ""))
210			 (string :tag "Host")
211			 (checklist :inline t
212				    (cons :format "%v"
213					  (const :format "" "login")
214					  (string :format "Login: %v"))
215				    (cons :format "%v"
216					  (const :format "" "password")
217					  (string :format "Password: %v")))))))
218
219
220
221(defvoo nntp-connection-timeout nil
222  "*Number of seconds to wait before an nntp connection times out.
223If this variable is nil, which is the default, no timers are set.
224NOTE: This variable is never seen to work in Emacs 20 and XEmacs 21.")
225
226(defvoo nntp-prepare-post-hook nil
227  "*Hook run just before posting an article.  It is supposed to be used
228to insert Cancel-Lock headers.")
229
230;;; Internal variables.
231
232(defvar nntp-record-commands nil
233  "*If non-nil, nntp will record all commands in the \"*nntp-log*\" buffer.")
234
235(defvar nntp-have-messaged nil)
236
237(defvar nntp-process-wait-for nil)
238(defvar nntp-process-to-buffer nil)
239(defvar nntp-process-callback nil)
240(defvar nntp-process-decode nil)
241(defvar nntp-process-start-point nil)
242(defvar nntp-inside-change-function nil)
243(defvoo nntp-last-command-time nil)
244(defvoo nntp-last-command nil)
245(defvoo nntp-authinfo-password nil)
246(defvoo nntp-authinfo-user nil)
247
248(defvar nntp-connection-list nil)
249
250(defvoo nntp-server-type nil)
251(defvoo nntp-connection-alist nil)
252(defvoo nntp-status-string "")
253(defconst nntp-version "nntp 5.0")
254(defvoo nntp-inhibit-erase nil)
255(defvoo nntp-inhibit-output nil)
256
257(defvoo nntp-server-xover 'try)
258(defvoo nntp-server-list-active-group 'try)
259
260(defvar nntp-async-needs-kluge
261  (string-match "^GNU Emacs 20\\.3\\." (emacs-version))
262  "*When non-nil, nntp will poll asynchronous connections
263once a second.  By default, this is turned on only for Emacs
26420.3, which has a bug that breaks nntp's normal method of
265noticing asynchronous data.")
266
267(defvar nntp-async-timer nil)
268(defvar nntp-async-process-list nil)
269
270(defvar nntp-ssl-program
271  "openssl s_client -quiet -ssl3 -connect %s:%p"
272"A string containing commands for SSL connections.
273Within a string, %s is replaced with the server address and %p with
274port number on server.  The program should accept IMAP commands on
275stdin and return responses to stdout.")
276
277(defvar nntp-authinfo-rejected nil
278"A custom error condition used to report 'Authentication Rejected' errors.
279Condition handlers that match just this condition ensure that the nntp
280backend doesn't catch this error.")
281(put 'nntp-authinfo-rejected 'error-conditions '(error nntp-authinfo-rejected))
282(put 'nntp-authinfo-rejected 'error-message "Authorization Rejected")
283
284
285
286;;; Internal functions.
287
288(defsubst nntp-send-string (process string)
289  "Send STRING to PROCESS."
290  ;; We need to store the time to provide timeouts, and
291  ;; to store the command so the we can replay the command
292  ;; if the server gives us an AUTHINFO challenge.
293  (setq nntp-last-command-time (current-time)
294	nntp-last-command string)
295  (when nntp-record-commands
296    (nntp-record-command string))
297  (process-send-string process (concat string nntp-end-of-line))
298  (or (memq (process-status process) '(open run))
299      (nntp-report "Server closed connection")))
300
301(defun nntp-record-command (string)
302  "Record the command STRING."
303  (save-excursion
304    (set-buffer (get-buffer-create "*nntp-log*"))
305    (goto-char (point-max))
306    (let ((time (current-time)))
307      (insert (format-time-string "%Y%m%dT%H%M%S" time)
308	      "." (format "%03d" (/ (nth 2 time) 1000))
309	      " " nntp-address " " string "\n"))))
310
311(defun nntp-report (&rest args)
312  "Report an error from the nntp backend.  The first string in ARGS
313can be a format string.  For some commands, the failed command may be
314retried once before actually displaying the error report."
315
316  (when nntp-record-commands
317    (nntp-record-command "*** CALLED nntp-report ***"))
318
319  (nnheader-report 'nntp args)
320
321  (apply 'error args))
322
323(defun nntp-report-1 (&rest args)
324  "Throws out to nntp-with-open-group-error so that the connection may
325be restored and the command retried."
326
327  (when nntp-record-commands
328    (nntp-record-command "*** CONNECTION LOST ***"))
329
330  (throw 'nntp-with-open-group-error t))
331
332(defsubst nntp-wait-for (process wait-for buffer &optional decode discard)
333  "Wait for WAIT-FOR to arrive from PROCESS."
334  (save-excursion
335    (set-buffer (process-buffer process))
336    (goto-char (point-min))
337    (while (and (or (not (memq (char-after (point)) '(?2 ?3 ?4 ?5)))
338		    (looking-at "48[02]"))
339		(memq (process-status process) '(open run)))
340      (cond ((looking-at "480")
341	(nntp-handle-authinfo process))
342	    ((looking-at "482")
343	     (nnheader-report 'nntp (get 'nntp-authinfo-rejected 'error-message))
344	     (signal 'nntp-authinfo-rejected nil))
345	    ((looking-at "^.*\n")
346	     (delete-region (point) (progn (forward-line 1) (point)))))
347      (nntp-accept-process-output process)
348      (goto-char (point-min)))
349    (prog1
350	(cond
351	 ((looking-at "[45]")
352	  (progn
353	    (nntp-snarf-error-message)
354	    nil))
355	 ((not (memq (process-status process) '(open run)))
356	  (nntp-report "Server closed connection"))
357	 (t
358	  (goto-char (point-max))
359	  (let ((limit (point-min))
360		response)
361	    (while (not (re-search-backward wait-for limit t))
362	      (nntp-accept-process-output process)
363	      ;; We assume that whatever we wait for is less than 1000
364	      ;; characters long.
365	      (setq limit (max (- (point-max) 1000) (point-min)))
366	      (goto-char (point-max)))
367	    (setq response (match-string 0))
368	    (with-current-buffer nntp-server-buffer
369	      (setq nntp-process-response response)))
370	  (nntp-decode-text (not decode))
371	  (unless discard
372	    (save-excursion
373	      (set-buffer buffer)
374	      (goto-char (point-max))
375	      (insert-buffer-substring (process-buffer process))
376	      ;; Nix out "nntp reading...." message.
377	      (when nntp-have-messaged
378		(setq nntp-have-messaged nil)
379		(nnheader-message 5 ""))))
380	  t))
381      (unless discard
382	(erase-buffer)))))
383
384(defun nntp-kill-buffer (buffer)
385  (when (buffer-name buffer)
386    (kill-buffer buffer)
387    (nnheader-init-server-buffer)))
388
389(defsubst nntp-find-connection (buffer)
390  "Find the connection delivering to BUFFER."
391  (let ((alist nntp-connection-alist)
392	(buffer (if (stringp buffer) (get-buffer buffer) buffer))
393	process entry)
394    (while (and alist (setq entry (pop alist)))
395      (when (eq buffer (cadr entry))
396	(setq process (car entry)
397	      alist nil)))
398    (when process
399      (if (memq (process-status process) '(open run))
400	  process
401	(nntp-kill-buffer (process-buffer process))
402	(setq nntp-connection-alist (delq entry nntp-connection-alist))
403	nil))))
404
405(defsubst nntp-find-connection-entry (buffer)
406  "Return the entry for the connection to BUFFER."
407  (assq (nntp-find-connection buffer) nntp-connection-alist))
408
409(defun nntp-find-connection-buffer (buffer)
410  "Return the process connection buffer tied to BUFFER."
411  (let ((process (nntp-find-connection buffer)))
412    (when process
413      (process-buffer process))))
414
415(defsubst nntp-retrieve-data (command address port buffer
416				      &optional wait-for callback decode)
417  "Use COMMAND to retrieve data into BUFFER from PORT on ADDRESS."
418  (let ((process (or (nntp-find-connection buffer)
419		     (nntp-open-connection buffer))))
420    (if process
421        (progn
422          (unless (or nntp-inhibit-erase nnheader-callback-function)
423            (save-excursion
424              (set-buffer (process-buffer process))
425              (erase-buffer)))
426          (condition-case err
427              (progn
428                (when command
429                  (nntp-send-string process command))
430                (cond
431                 ((eq callback 'ignore)
432                  t)
433                 ((and callback wait-for)
434                  (nntp-async-wait process wait-for buffer decode callback)
435                  t)
436                 (wait-for
437                  (nntp-wait-for process wait-for buffer decode))
438                 (t t)))
439	    (nntp-authinfo-rejected
440	     (signal 'nntp-authinfo-rejected (cdr err)))
441            (error
442             (nnheader-report 'nntp "Couldn't open connection to %s: %s"
443                              address err))
444            (quit
445             (message "Quit retrieving data from nntp")
446             (signal 'quit nil)
447             nil)))
448      (nnheader-report 'nntp "Couldn't open connection to %s" address))))
449
450(defsubst nntp-send-command (wait-for &rest strings)
451  "Send STRINGS to server and wait until WAIT-FOR returns."
452  (when (and (not nnheader-callback-function)
453	     (not nntp-inhibit-output))
454    (save-excursion
455      (set-buffer nntp-server-buffer)
456      (erase-buffer)))
457  (let* ((command (mapconcat 'identity strings " "))
458	 (process (nntp-find-connection nntp-server-buffer))
459	 (buffer (and process (process-buffer process)))
460	 (pos (and buffer (with-current-buffer buffer (point)))))
461    (if process
462	(prog1
463	    (nntp-retrieve-data command
464				nntp-address nntp-port-number
465				nntp-server-buffer
466				wait-for nnheader-callback-function)
467	  ;; If nothing to wait for, still remove possibly echo'ed commands.
468	  ;; We don't have echoes if `nntp-never-echoes-commands' is non-nil
469	  ;; or the value of `nntp-open-connection-function' is in
470	  ;; `nntp-open-connection-functions-never-echo-commands', so we
471	  ;; skip this in that cases.
472	  (unless (or wait-for
473		      nntp-never-echoes-commands
474		      (memq
475		       nntp-open-connection-function
476		       nntp-open-connection-functions-never-echo-commands))
477	    (nntp-accept-response)
478	    (save-excursion
479	      (set-buffer buffer)
480	      (goto-char pos)
481	      (if (looking-at (regexp-quote command))
482		  (delete-region pos (progn (forward-line 1)
483					    (gnus-point-at-bol))))
484	      )))
485      (nnheader-report 'nntp "Couldn't open connection to %s."
486		       nntp-address))))
487
488(defun nntp-send-command-nodelete (wait-for &rest strings)
489  "Send STRINGS to server and wait until WAIT-FOR returns."
490  (let* ((command (mapconcat 'identity strings " "))
491	 (process (nntp-find-connection nntp-server-buffer))
492	 (buffer (and process (process-buffer process)))
493	 (pos (and buffer (with-current-buffer buffer (point)))))
494    (if process
495	(prog1
496	    (nntp-retrieve-data command
497				nntp-address nntp-port-number
498				nntp-server-buffer
499				wait-for nnheader-callback-function)
500	  ;; If nothing to wait for, still remove possibly echo'ed commands
501	  (unless wait-for
502	    (nntp-accept-response)
503	    (save-excursion
504	      (set-buffer buffer)
505	      (goto-char pos)
506	      (if (looking-at (regexp-quote command))
507		  (delete-region pos (progn (forward-line 1)
508					    (gnus-point-at-bol)))))))
509      (nnheader-report 'nntp "Couldn't open connection to %s."
510		       nntp-address))))
511
512(defun nntp-send-command-and-decode (wait-for &rest strings)
513  "Send STRINGS to server and wait until WAIT-FOR returns."
514  (when (and (not nnheader-callback-function)
515	     (not nntp-inhibit-output))
516    (save-excursion
517      (set-buffer nntp-server-buffer)
518      (erase-buffer)))
519  (let* ((command (mapconcat 'identity strings " "))
520	 (process (nntp-find-connection nntp-server-buffer))
521	 (buffer (and process (process-buffer process)))
522	 (pos (and buffer (with-current-buffer buffer (point)))))
523    (if process
524	(prog1
525	    (nntp-retrieve-data command
526				nntp-address nntp-port-number
527				nntp-server-buffer
528				wait-for nnheader-callback-function t)
529	  ;; If nothing to wait for, still remove possibly echo'ed commands
530	  (unless wait-for
531	    (nntp-accept-response)
532	    (save-excursion
533	  (set-buffer buffer)
534	  (goto-char pos)
535	  (if (looking-at (regexp-quote command))
536	      (delete-region pos (progn (forward-line 1) (gnus-point-at-bol))))
537	  )))
538      (nnheader-report 'nntp "Couldn't open connection to %s."
539		       nntp-address))))
540
541
542(defun nntp-send-buffer (wait-for)
543  "Send the current buffer to server and wait until WAIT-FOR returns."
544  (when (and (not nnheader-callback-function)
545	     (not nntp-inhibit-output))
546    (save-excursion
547      (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
548      (erase-buffer)))
549  (nntp-encode-text)
550  (mm-with-unibyte-current-buffer
551    ;; Some encoded unicode text contains character 0x80-0x9f e.g. Euro.
552    (process-send-region (nntp-find-connection nntp-server-buffer)
553			 (point-min) (point-max)))
554  (nntp-retrieve-data
555   nil nntp-address nntp-port-number nntp-server-buffer
556   wait-for nnheader-callback-function))
557
558
559
560;;; Interface functions.
561
562(nnoo-define-basics nntp)
563
564(defsubst nntp-next-result-arrived-p ()
565  (cond
566   ;; A result that starts with a 2xx code is terminated by
567   ;; a line with only a "." on it.
568   ((eq (char-after) ?2)
569    (if (re-search-forward "\n\\.\r?\n" nil t)
570	t
571      nil))
572   ;; A result that starts with a 3xx or 4xx code is terminated
573   ;; by a newline.
574   ((looking-at "[34]")
575    (if (search-forward "\n" nil t)
576	t
577      nil))
578   ;; No result here.
579   (t
580    nil)))
581
582(eval-when-compile
583  (defvar nntp-with-open-group-internal nil)
584  (defvar nntp-report-n nil))
585
586(defmacro nntp-with-open-group (group server &optional connectionless &rest forms)
587  "Protect against servers that don't like clients that keep idle connections opens.
588The problem being that these servers may either close a connection or
589simply ignore any further requests on a connection.  Closed
590connections are not detected until accept-process-output has updated
591the process-status.  Dropped connections are not detected until the
592connection timeouts (which may be several minutes) or
593nntp-connection-timeout has expired.  When these occur
594nntp-with-open-group, opens a new connection then re-issues the NNTP
595command whose response triggered the error."
596  (when (and (listp connectionless)
597	     (not (eq connectionless nil)))
598    (setq forms (cons connectionless forms)
599	  connectionless nil))
600  `(letf ((nntp-report-n (symbol-function 'nntp-report))
601	  ((symbol-function 'nntp-report) (symbol-function 'nntp-report-1))
602	  (nntp-with-open-group-internal nil))
603     (while (catch 'nntp-with-open-group-error
604	      ;; Open the connection to the server
605	      ;; NOTE: Existing connections are NOT tested.
606	      (nntp-possibly-change-group ,group ,server ,connectionless)
607
608	      (let ((timer
609		     (and nntp-connection-timeout
610			  (nnheader-run-at-time
611			   nntp-connection-timeout nil
612			   '(lambda ()
613			      (let ((process (nntp-find-connection
614					      nntp-server-buffer))
615				    (buffer  (and process
616						  (process-buffer process))))
617				;; When I an able to identify the
618				;; connection to the server AND I've
619				;; received NO reponse for
620				;; nntp-connection-timeout seconds.
621				(when (and buffer (eq 0 (buffer-size buffer)))
622				  ;; Close the connection.  Take no
623				  ;; other action as the accept input
624				  ;; code will handle the closed
625				  ;; connection.
626				  (nntp-kill-buffer buffer))))))))
627		(unwind-protect
628		    (setq nntp-with-open-group-internal
629                          (condition-case nil
630			      (progn ,@forms)
631			    (quit
632			     (nntp-close-server)
633                             (signal 'quit nil))))
634		  (when timer
635		    (nnheader-cancel-timer timer)))
636		nil))
637       (setf (symbol-function 'nntp-report) nntp-report-n))
638     nntp-with-open-group-internal))
639
640(deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
641  "Retrieve the headers of ARTICLES."
642  (nntp-with-open-group
643   group server
644   (save-excursion
645     (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
646     (erase-buffer)
647     (if (and (not gnus-nov-is-evil)
648              (not nntp-nov-is-evil)
649              (nntp-retrieve-headers-with-xover articles fetch-old))
650         ;; We successfully retrieved the headers via XOVER.
651         'nov
652       ;; XOVER didn't work, so we do it the hard, slow and inefficient
653       ;; way.
654       (let ((number (length articles))
655             (articles articles)
656             (count 0)
657             (received 0)
658             (last-point (point-min))
659             (buf (nntp-find-connection-buffer nntp-server-buffer))
660             (nntp-inhibit-erase t)
661             article)
662         ;; Send HEAD commands.
663         (while (setq article (pop articles))
664           (nntp-send-command
665            nil
666            "HEAD" (if (numberp article)
667                       (int-to-string article)
668                     ;; `articles' is either a list of article numbers
669                     ;; or a list of article IDs.
670                     article))
671           (incf count)
672           ;; Every 400 requests we have to read the stream in
673           ;; order to avoid deadlocks.
674           (when (or (null articles)    ;All requests have been sent.
675                     (zerop (% count nntp-maximum-request)))
676             (nntp-accept-response)
677             (while (progn
678                      (set-buffer buf)
679                      (goto-char last-point)
680                      ;; Count replies.
681                      (while (nntp-next-result-arrived-p)
682                        (setq last-point (point))
683                        (incf received))
684                      (< received count))
685               ;; If number of headers is greater than 100, give
686               ;;  informative messages.
687               (and (numberp nntp-large-newsgroup)
688                    (> number nntp-large-newsgroup)
689                    (zerop (% received 20))
690                    (nnheader-message 6 "NNTP: Receiving headers... %d%%"
691                                      (/ (* received 100) number)))
692               (nntp-accept-response))))
693         (and (numberp nntp-large-newsgroup)
694              (> number nntp-large-newsgroup)
695              (nnheader-message 6 "NNTP: Receiving headers...done"))
696
697         ;; Now all of replies are received.  Fold continuation lines.
698         (nnheader-fold-continuation-lines)
699         ;; Remove all "\r"'s.
700         (nnheader-strip-cr)
701         (copy-to-buffer nntp-server-buffer (point-min) (point-max))
702         'headers)))))
703
704(deffoo nntp-retrieve-groups (groups &optional server)
705  "Retrieve group info on GROUPS."
706  (nntp-with-open-group
707   nil server
708   (when (nntp-find-connection-buffer nntp-server-buffer)
709     (catch 'done
710       (save-excursion
711         ;; Erase nntp-server-buffer before nntp-inhibit-erase.
712         (set-buffer nntp-server-buffer)
713         (erase-buffer)
714         (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
715         ;; The first time this is run, this variable is `try'.  So we
716         ;; try.
717         (when (eq nntp-server-list-active-group 'try)
718           (nntp-try-list-active (car groups)))
719         (erase-buffer)
720         (let ((count 0)
721               (groups groups)
722               (received 0)
723               (last-point (point-min))
724               (nntp-inhibit-erase t)
725               (buf (nntp-find-connection-buffer nntp-server-buffer))
726               (command (if nntp-server-list-active-group
727                            "LIST ACTIVE" "GROUP")))
728           (while groups
729             ;; Timeout may have killed the buffer.
730             (unless (gnus-buffer-live-p buf)
731               (nnheader-report 'nntp "Connection to %s is closed." server)
732               (throw 'done nil))
733             ;; Send the command to the server.
734             (nntp-send-command nil command (pop groups))
735             (incf count)
736             ;; Every 400 requests we have to read the stream in
737             ;; order to avoid deadlocks.
738             (when (or (null groups)    ;All requests have been sent.
739                       (zerop (% count nntp-maximum-request)))
740               (nntp-accept-response)
741               (while (and (gnus-buffer-live-p buf)
742                           (progn
743                             ;; Search `blue moon' in this file for the
744                             ;; reason why set-buffer here.
745                             (set-buffer buf)
746                             (goto-char last-point)
747                             ;; Count replies.
748                             (while (re-search-forward "^[0-9]" nil t)
749                               (incf received))
750                             (setq last-point (point))
751                             (< received count)))
752                 (nntp-accept-response))))
753
754           ;; Wait for the reply from the final command.
755           (unless (gnus-buffer-live-p buf)
756             (nnheader-report 'nntp "Connection to %s is closed." server)
757             (throw 'done nil))
758           (set-buffer buf)
759           (goto-char (point-max))
760           (re-search-backward "^[0-9]" nil t)
761           (when (looking-at "^[23]")
762             (while (and (gnus-buffer-live-p buf)
763                         (progn
764                           (set-buffer buf)
765                           (goto-char (point-max))
766                           (if (not nntp-server-list-active-group)
767                               (not (re-search-backward "\r?\n"
768							(- (point) 3) t))
769                             (not (re-search-backward "^\\.\r?\n"
770                                                      (- (point) 4) t)))))
771               (nntp-accept-response)))
772
773           ;; Now all replies are received.  We remove CRs.
774           (unless (gnus-buffer-live-p buf)
775             (nnheader-report 'nntp "Connection to %s is closed." server)
776             (throw 'done nil))
777           (set-buffer buf)
778           (goto-char (point-min))
779           (while (search-forward "\r" nil t)
780             (replace-match "" t t))
781
782           (if (not nntp-server-list-active-group)
783               (progn
784                 (copy-to-buffer nntp-server-buffer (point-min) (point-max))
785                 'group)
786             ;; We have read active entries, so we just delete the
787             ;; superfluous gunk.
788             (goto-char (point-min))
789             (while (re-search-forward "^[.2-5]" nil t)
790               (delete-region (match-beginning 0)
791                              (progn (forward-line 1) (point))))
792             (copy-to-buffer nntp-server-buffer (point-min) (point-max))
793             'active)))))))
794
795(deffoo nntp-retrieve-articles (articles &optional group server)
796  (nntp-with-open-group
797    group server
798   (save-excursion
799     (let ((number (length articles))
800           (articles articles)
801           (count 0)
802           (received 0)
803           (last-point (point-min))
804           (buf (nntp-find-connection-buffer nntp-server-buffer))
805           (nntp-inhibit-erase t)
806           (map (apply 'vector articles))
807           (point 1)
808           article)
809       (set-buffer buf)
810       (erase-buffer)
811       ;; Send ARTICLE command.
812       (while (setq article (pop articles))
813         (nntp-send-command
814          nil
815          "ARTICLE" (if (numberp article)
816                        (int-to-string article)
817                      ;; `articles' is either a list of article numbers
818                      ;; or a list of article IDs.
819                      article))
820         (incf count)
821         ;; Every 400 requests we have to read the stream in
822         ;; order to avoid deadlocks.
823         (when (or (null articles)	;All requests have been sent.
824                   (zerop (% count nntp-maximum-request)))
825           (nntp-accept-response)
826           (while (progn
827                    (set-buffer buf)
828                    (goto-char last-point)
829                    ;; Count replies.
830                    (while (nntp-next-result-arrived-p)
831                      (aset map received (cons (aref map received) (point)))
832                      (setq last-point (point))
833                      (incf received))
834                    (< received count))
835             ;; If number of headers is greater than 100, give
836             ;;  informative messages.
837             (and (numberp nntp-large-newsgroup)
838                  (> number nntp-large-newsgroup)
839                  (zerop (% received 20))
840                  (nnheader-message 6 "NNTP: Receiving articles... %d%%"
841                                    (/ (* received 100) number)))
842             (nntp-accept-response))))
843       (and (numberp nntp-large-newsgroup)
844            (> number nntp-large-newsgroup)
845            (nnheader-message 6 "NNTP: Receiving articles...done"))
846
847       ;; Now we have all the responses.  We go through the results,
848       ;; wash it and copy it over to the server buffer.
849       (set-buffer nntp-server-buffer)
850       (erase-buffer)
851       (setq last-point (point-min))
852       (mapcar
853        (lambda (entry)
854          (narrow-to-region
855           (setq point (goto-char (point-max)))
856           (progn
857             (insert-buffer-substring buf last-point (cdr entry))
858             (point-max)))
859          (setq last-point (cdr entry))
860          (nntp-decode-text)
861          (widen)
862          (cons (car entry) point))
863        map)))))
864
865(defun nntp-try-list-active (group)
866  (nntp-list-active-group group)
867  (save-excursion
868    (set-buffer nntp-server-buffer)
869    (goto-char (point-min))
870    (cond ((or (eobp)
871	       (looking-at "5[0-9]+"))
872	   (setq nntp-server-list-active-group nil))
873	  (t
874	   (setq nntp-server-list-active-group t)))))
875
876(deffoo nntp-list-active-group (group &optional server)
877  "Return the active info on GROUP (which can be a regexp)."
878  (nntp-with-open-group
879   nil server
880   (nntp-send-command "^\\.*\r?\n" "LIST ACTIVE" group)))
881
882(deffoo nntp-request-group-articles (group &optional server)
883  "Return the list of existing articles in GROUP."
884  (nntp-with-open-group
885   nil server
886   (nntp-send-command "^\\.*\r?\n" "LISTGROUP" group)))
887
888(deffoo nntp-request-article (article &optional group server buffer command)
889  (nntp-with-open-group
890    group server
891    (when (nntp-send-command-and-decode
892           "\r?\n\\.\r?\n" "ARTICLE"
893           (if (numberp article) (int-to-string article) article))
894      (if (and buffer
895               (not (equal buffer nntp-server-buffer)))
896          (save-excursion
897            (set-buffer nntp-server-buffer)
898            (copy-to-buffer buffer (point-min) (point-max))
899            (nntp-find-group-and-number group))
900        (nntp-find-group-and-number group)))))
901
902(deffoo nntp-request-head (article &optional group server)
903  (nntp-with-open-group
904   group server
905   (when (nntp-send-command
906          "\r?\n\\.\r?\n" "HEAD"
907          (if (numberp article) (int-to-string article) article))
908     (prog1
909         (nntp-find-group-and-number group)
910       (nntp-decode-text)))))
911
912(deffoo nntp-request-body (article &optional group server)
913  (nntp-with-open-group
914   group server
915   (nntp-send-command-and-decode
916    "\r?\n\\.\r?\n" "BODY"
917    (if (numberp article) (int-to-string article) article))))
918
919(deffoo nntp-request-group (group &optional server dont-check)
920  (nntp-with-open-group
921    nil server
922    (when (nntp-send-command "^[245].*\n" "GROUP" group)
923      (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
924        (setcar (cddr entry) group)))))
925
926(deffoo nntp-close-group (group &optional server)
927  t)
928
929(deffoo nntp-server-opened (&optional server)
930  "Say whether a connection to SERVER has been opened."
931  (and (nnoo-current-server-p 'nntp server)
932       nntp-server-buffer
933       (gnus-buffer-live-p nntp-server-buffer)
934       (nntp-find-connection nntp-server-buffer)))
935
936(deffoo nntp-open-server (server &optional defs connectionless)
937  (nnheader-init-server-buffer)
938  (if (nntp-server-opened server)
939      t
940    (when (or (stringp (car defs))
941	      (numberp (car defs)))
942      (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
943    (unless (assq 'nntp-address defs)
944      (setq defs (append defs (list (list 'nntp-address server)))))
945    (nnoo-change-server 'nntp server defs)
946    (unless connectionless
947      (or (nntp-find-connection nntp-server-buffer)
948	  (nntp-open-connection nntp-server-buffer)))))
949
950(deffoo nntp-close-server (&optional server)
951  (nntp-possibly-change-group nil server t)
952  (let ((process (nntp-find-connection nntp-server-buffer)))
953    (while process
954      (when (memq (process-status process) '(open run))
955	(ignore-errors
956	  (nntp-send-string process "QUIT")
957	  (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
958	    ;; Ok, this is evil, but when using telnet and stuff
959	    ;; as the connection method, it's important that the
960	    ;; QUIT command actually is sent out before we kill
961	    ;; the process.
962	    (sleep-for 1))))
963      (nntp-kill-buffer (process-buffer process))
964      (setq process (car (pop nntp-connection-alist))))
965    (nnoo-close-server 'nntp)))
966
967(deffoo nntp-request-close ()
968  (let (process)
969    (while (setq process (pop nntp-connection-list))
970      (when (memq (process-status process) '(open run))
971	(ignore-errors
972	  (nntp-send-string process "QUIT")
973	  (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
974	    ;; Ok, this is evil, but when using telnet and stuff
975	    ;; as the connection method, it's important that the
976	    ;; QUIT command actually is sent out before we kill
977	    ;; the process.
978	    (sleep-for 1))))
979      (nntp-kill-buffer (process-buffer process)))))
980
981(deffoo nntp-request-list (&optional server)
982  (nntp-with-open-group
983   nil server
984   (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST")))
985
986(deffoo nntp-request-list-newsgroups (&optional server)
987  (nntp-with-open-group
988   nil server
989   (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS")))
990
991(deffoo nntp-request-newgroups (date &optional server)
992  (nntp-with-open-group
993   nil server
994   (save-excursion
995     (set-buffer nntp-server-buffer)
996     (let* ((time (date-to-time date))
997            (ls (- (cadr time) (nth 8 (decode-time time)))))
998       (cond ((< ls 0)
999              (setcar time (1- (car time)))
1000              (setcar (cdr time) (+ ls 65536)))
1001             ((>= ls 65536)
1002              (setcar time (1+ (car time)))
1003              (setcar (cdr time) (- ls 65536)))
1004             (t
1005              (setcar (cdr time) ls)))
1006       (prog1
1007           (nntp-send-command
1008            "^\\.\r?\n" "NEWGROUPS"
1009            (format-time-string "%y%m%d %H%M%S" time)
1010            "GMT")
1011         (nntp-decode-text))))))
1012
1013(deffoo nntp-request-post (&optional server)
1014  (nntp-with-open-group
1015   nil server
1016   (when (nntp-send-command "^[23].*\r?\n" "POST")
1017     (let ((response (with-current-buffer nntp-server-buffer
1018                       nntp-process-response))
1019           server-id)
1020       (when (and response
1021                  (string-match "^[23].*\\(<[^\t\n @<>]+@[^\t\n @<>]+>\\)"
1022                                response))
1023         (setq server-id (match-string 1 response))
1024         (narrow-to-region (goto-char (point-min))
1025                           (if (search-forward "\n\n" nil t)
1026                               (1- (point))
1027                             (point-max)))
1028         (unless (mail-fetch-field "Message-ID")
1029           (goto-char (point-min))
1030           (insert "Message-ID: " server-id "\n"))
1031         (widen))
1032       (run-hooks 'nntp-prepare-post-hook)
1033       (nntp-send-buffer "^[23].*\n")))))
1034
1035(deffoo nntp-request-type (group article)
1036  'news)
1037
1038(deffoo nntp-asynchronous-p ()
1039  t)
1040
1041;;; Hooky functions.
1042
1043(defun nntp-send-mode-reader ()
1044  "Send the MODE READER command to the nntp server.
1045This function is supposed to be called from `nntp-server-opened-hook'.
1046It will make innd servers spawn an nnrpd process to allow actual article
1047reading."
1048  (nntp-send-command "^.*\n" "MODE READER"))
1049
1050(defun nntp-send-authinfo (&optional send-if-force)
1051  "Send the AUTHINFO to the nntp server.
1052It will look in the \"~/.authinfo\" file for matching entries.  If
1053nothing suitable is found there, it will prompt for a user name
1054and a password.
1055
1056If SEND-IF-FORCE, only send authinfo to the server if the
1057.authinfo file has the FORCE token."
1058  (let* ((list (gnus-parse-netrc nntp-authinfo-file))
1059	 (alist (gnus-netrc-machine list nntp-address "nntp"))
1060	 (force (gnus-netrc-get alist "force"))
1061	 (user (or (gnus-netrc-get alist "login") nntp-authinfo-user))
1062	 (passwd (gnus-netrc-get alist "password")))
1063    (when (or (not send-if-force)
1064	      force)
1065      (unless user
1066	(setq user (read-string (format "NNTP (%s) user name: " nntp-address))
1067	      nntp-authinfo-user user))
1068      (unless (member user '(nil ""))
1069	(nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1070	(when t				;???Should check if AUTHINFO succeeded
1071	  (nntp-send-command
1072	   "^2.*\r?\n" "AUTHINFO PASS"
1073	   (or passwd
1074	       nntp-authinfo-password
1075	       (setq nntp-authinfo-password
1076		     (read-passwd (format "NNTP (%s@%s) password: "
1077					  user nntp-address))))))))))
1078
1079(defun nntp-send-nosy-authinfo ()
1080  "Send the AUTHINFO to the nntp server."
1081  (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
1082    (unless (member user '(nil ""))
1083      (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1084      (when t				;???Should check if AUTHINFO succeeded
1085	(nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
1086			   (read-passwd (format "NNTP (%s@%s) password: "
1087						user nntp-address)))))))
1088
1089(defun nntp-send-authinfo-from-file ()
1090  "Send the AUTHINFO to the nntp server.
1091
1092The authinfo login name is taken from the user's login name and the
1093password contained in '~/.nntp-authinfo'."
1094  (when (file-exists-p "~/.nntp-authinfo")
1095    (with-temp-buffer
1096      (insert-file-contents "~/.nntp-authinfo")
1097      (goto-char (point-min))
1098      (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
1099      (nntp-send-command
1100       "^2.*\r?\n" "AUTHINFO PASS"
1101       (buffer-substring (point) (gnus-point-at-eol))))))
1102
1103;;; Internal functions.
1104
1105(defun nntp-handle-authinfo (process)
1106  "Take care of an authinfo response from the server."
1107  (let ((last nntp-last-command))
1108    (funcall nntp-authinfo-function)
1109    ;; We have to re-send the function that was interrupted by
1110    ;; the authinfo request.
1111    (save-excursion
1112      (set-buffer nntp-server-buffer)
1113      (erase-buffer))
1114    (nntp-send-string process last)))
1115
1116(defun nntp-make-process-buffer (buffer)
1117  "Create a new, fresh buffer usable for nntp process connections."
1118  (save-excursion
1119    (set-buffer
1120     (generate-new-buffer
1121      (format " *server %s %s %s*"
1122	      nntp-address nntp-port-number
1123	      (gnus-buffer-exists-p buffer))))
1124    (mm-enable-multibyte)
1125    (set (make-local-variable 'after-change-functions) nil)
1126    (set (make-local-variable 'nntp-process-wait-for) nil)
1127    (set (make-local-variable 'nntp-process-callback) nil)
1128    (set (make-local-variable 'nntp-process-to-buffer) nil)
1129    (set (make-local-variable 'nntp-process-start-point) nil)
1130    (set (make-local-variable 'nntp-process-decode) nil)
1131    (current-buffer)))
1132
1133(defun nntp-open-connection (buffer)
1134  "Open a connection to PORT on ADDRESS delivering output to BUFFER."
1135  (run-hooks 'nntp-prepare-server-hook)
1136  (let* ((pbuffer (nntp-make-process-buffer buffer))
1137	 (timer
1138	  (and nntp-connection-timeout
1139	       (nnheader-run-at-time
1140		nntp-connection-timeout nil
1141		`(lambda ()
1142		   (nntp-kill-buffer ,pbuffer)))))
1143	 (process
1144	  (condition-case ()
1145	      (let ((coding-system-for-read nntp-coding-system-for-read)
1146		    (coding-system-for-write nntp-coding-system-for-write))
1147		(funcall nntp-open-connection-function pbuffer))
1148	    (error nil)
1149	    (quit
1150	     (message "Quit opening connection")
1151	     (nntp-kill-buffer pbuffer)
1152	     (signal 'quit nil)
1153	     nil))))
1154    (when timer
1155      (nnheader-cancel-timer timer))
1156    (unless process
1157      (nntp-kill-buffer pbuffer))
1158    (when (and (buffer-name pbuffer)
1159	       process)
1160      (gnus-set-process-query-on-exit-flag process nil)
1161      (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
1162	       (memq (process-status process) '(open run)))
1163	  (prog1
1164	      (caar (push (list process buffer nil) nntp-connection-alist))
1165	    (push process nntp-connection-list)
1166	    (save-excursion
1167	      (set-buffer pbuffer)
1168	      (nntp-read-server-type)
1169	      (erase-buffer)
1170	      (set-buffer nntp-server-buffer)
1171	      (let ((nnheader-callback-function nil))
1172		(run-hooks 'nntp-server-opened-hook)
1173		(nntp-send-authinfo t))))
1174	(nntp-kill-buffer (process-buffer process))
1175	nil))))
1176
1177(defun nntp-open-network-stream (buffer)
1178  (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
1179
1180(eval-and-compile
1181  (autoload 'format-spec "format-spec")
1182  (autoload 'format-spec-make "format-spec")
1183  (autoload 'open-tls-stream "tls"))
1184
1185(defun nntp-open-ssl-stream (buffer)
1186  (let* ((process-connection-type nil)
1187	 (proc (start-process "nntpd" buffer
1188			      shell-file-name
1189			      shell-command-switch
1190			      (format-spec nntp-ssl-program
1191					   (format-spec-make
1192					    ?s nntp-address
1193					    ?p nntp-port-number)))))
1194    (gnus-set-process-query-on-exit-flag proc nil)
1195    (save-excursion
1196      (set-buffer buffer)
1197      (let ((nntp-connection-alist (list proc buffer nil)))
1198	(nntp-wait-for-string "^\r*20[01]"))
1199      (beginning-of-line)
1200      (delete-region (point-min) (point))
1201      proc)))
1202
1203(defun nntp-open-tls-stream (buffer)
1204  (let ((proc (open-tls-stream "nntpd" buffer nntp-address nntp-port-number)))
1205    (gnus-set-process-query-on-exit-flag proc nil)
1206    (save-excursion
1207      (set-buffer buffer)
1208      (let ((nntp-connection-alist (list proc buffer nil)))
1209	(nntp-wait-for-string "^\r*20[01]"))
1210      (beginning-of-line)
1211      (delete-region (point-min) (point))
1212      proc)))
1213
1214(defun nntp-read-server-type ()
1215  "Find out what the name of the server we have connected to is."
1216  ;; Wait for the status string to arrive.
1217  (setq nntp-server-type (buffer-string))
1218  (let ((alist nntp-server-action-alist)
1219	(case-fold-search t)
1220	entry)
1221    ;; Run server-specific commands.
1222    (while alist
1223      (setq entry (pop alist))
1224      (when (string-match (car entry) nntp-server-type)
1225	(if (and (listp (cadr entry))
1226		 (not (eq 'lambda (caadr entry))))
1227	    (eval (cadr entry))
1228	  (funcall (cadr entry)))))))
1229
1230(defun nntp-async-wait (process wait-for buffer decode callback)
1231  (save-excursion
1232    (set-buffer (process-buffer process))
1233    (unless nntp-inside-change-function
1234      (erase-buffer))
1235    (setq nntp-process-wait-for wait-for
1236	  nntp-process-to-buffer buffer
1237	  nntp-process-decode decode
1238	  nntp-process-callback callback
1239	  nntp-process-start-point (point-max))
1240    (setq after-change-functions '(nntp-after-change-function))
1241    (if nntp-async-needs-kluge
1242	(nntp-async-kluge process))))
1243
1244(defun nntp-async-kluge (process)
1245  ;; emacs 20.3 bug: process output with encoding 'binary
1246  ;; doesn't trigger after-change-functions.
1247  (unless nntp-async-timer
1248    (setq nntp-async-timer
1249	  (nnheader-run-at-time 1 1 'nntp-async-timer-handler)))
1250  (add-to-list 'nntp-async-process-list process))
1251
1252(defun nntp-async-timer-handler ()
1253  (mapcar
1254   (lambda (proc)
1255     (if (memq (process-status proc) '(open run))
1256	 (nntp-async-trigger proc)
1257       (nntp-async-stop proc)))
1258   nntp-async-process-list))
1259
1260(defun nntp-async-stop (proc)
1261  (setq nntp-async-process-list (delq proc nntp-async-process-list))
1262  (when (and nntp-async-timer (not nntp-async-process-list))
1263    (nnheader-cancel-timer nntp-async-timer)
1264    (setq nntp-async-timer nil)))
1265
1266(defun nntp-after-change-function (beg end len)
1267  (unwind-protect
1268      ;; we only care about insertions at eob
1269      (when (and (eq 0 len) (eq (point-max) end))
1270	(save-match-data
1271	  (let ((proc (get-buffer-process (current-buffer))))
1272	    (when proc
1273	      (nntp-async-trigger proc)))))
1274    ;; any throw from after-change-functions will leave it
1275    ;; set to nil.  so we reset it here, if necessary.
1276    (when quit-flag
1277      (setq after-change-functions '(nntp-after-change-function)))))
1278
1279(defun nntp-async-trigger (process)
1280  (save-excursion
1281    (set-buffer (process-buffer process))
1282    (when nntp-process-callback
1283      ;; do we have an error message?
1284      (goto-char nntp-process-start-point)
1285      (if (memq (following-char) '(?4 ?5))
1286	  ;; wants credentials?
1287	  (if (looking-at "480")
1288	      (nntp-handle-authinfo process)
1289	    ;; report error message.
1290	    (nntp-snarf-error-message)
1291	    (nntp-do-callback nil))
1292
1293	;; got what we expect?
1294	(goto-char (point-max))
1295	(when (re-search-backward
1296	       nntp-process-wait-for nntp-process-start-point t)
1297	  (let ((response (match-string 0)))
1298	    (with-current-buffer nntp-server-buffer
1299	      (setq nntp-process-response response)))
1300	  (nntp-async-stop process)
1301	  ;; convert it.
1302	  (when (gnus-buffer-exists-p nntp-process-to-buffer)
1303	    (let ((buf (current-buffer))
1304		  (start nntp-process-start-point)
1305		  (decode nntp-process-decode))
1306	      (save-excursion
1307		(set-buffer nntp-process-to-buffer)
1308		(goto-char (point-max))
1309		(save-restriction
1310		  (narrow-to-region (point) (point))
1311		  (insert-buffer-substring buf start)
1312		  (when decode
1313		    (nntp-decode-text))))))
1314	  ;; report it.
1315	  (goto-char (point-max))
1316	  (nntp-do-callback
1317	   (buffer-name (get-buffer nntp-process-to-buffer))))))))
1318
1319(defun nntp-do-callback (arg)
1320  (let ((callback nntp-process-callback)
1321	(nntp-inside-change-function t))
1322    (setq nntp-process-callback nil)
1323    (funcall callback arg)))
1324
1325(defun nntp-snarf-error-message ()
1326  "Save the error message in the current buffer."
1327  (let ((message (buffer-string)))
1328    (while (string-match "[\r\n]+" message)
1329      (setq message (replace-match " " t t message)))
1330    (nnheader-report 'nntp message)
1331    message))
1332
1333(defun nntp-accept-process-output (process)
1334  "Wait for output from PROCESS and message some dots."
1335  (save-excursion
1336    (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1337		    nntp-server-buffer))
1338    (let ((len (/ (buffer-size) 1024))
1339	  message-log-max)
1340      (unless (< len 10)
1341	(setq nntp-have-messaged t)
1342	(nnheader-message 7 "nntp read: %dk" len)))
1343    (nnheader-accept-process-output process)
1344    ;; accept-process-output may update status of process to indicate
1345    ;; that the server has closed the connection.  This MUST be
1346    ;; handled here as the buffer restored by the save-excursion may
1347    ;; be the process's former output buffer (i.e. now killed)
1348    (or (and process
1349	     (memq (process-status process) '(open run)))
1350        (nntp-report "Server closed connection"))))
1351
1352(defun nntp-accept-response ()
1353  "Wait for output from the process that outputs to BUFFER."
1354  (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1355
1356(defun nntp-possibly-change-group (group server &optional connectionless)
1357  (let ((nnheader-callback-function nil))
1358    (when server
1359      (or (nntp-server-opened server)
1360	  (nntp-open-server server nil connectionless)))
1361
1362    (unless connectionless
1363      (or (nntp-find-connection nntp-server-buffer)
1364	  (nntp-open-connection nntp-server-buffer))))
1365
1366  (when group
1367    (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1368      (cond ((not entry)
1369             (nntp-report "Server closed connection"))
1370            ((not (equal group (caddr entry)))
1371             (save-excursion
1372               (set-buffer (process-buffer (car entry)))
1373               (erase-buffer)
1374               (nntp-send-command "^[245].*\n" "GROUP" group)
1375               (setcar (cddr entry) group)
1376               (erase-buffer)
1377               (save-excursion
1378                 (set-buffer nntp-server-buffer)
1379                 (erase-buffer))))))))
1380
1381(defun nntp-decode-text (&optional cr-only)
1382  "Decode the text in the current buffer."
1383  (goto-char (point-min))
1384  (while (search-forward "\r" nil t)
1385    (delete-char -1))
1386  (unless cr-only
1387    ;; Remove trailing ".\n" end-of-transfer marker.
1388    (goto-char (point-max))
1389    (forward-line -1)
1390    (when (looking-at ".\n")
1391      (delete-char 2))
1392    ;; Delete status line.
1393    (goto-char (point-min))
1394    (while (looking-at "[1-5][0-9][0-9] .*\n")
1395      ;; For some unknown reason, there is more than one status line.
1396      (delete-region (point) (progn (forward-line 1) (point))))
1397    ;; Remove "." -> ".." encoding.
1398    (while (search-forward "\n.." nil t)
1399      (delete-char -1))))
1400
1401(defun nntp-encode-text ()
1402  "Encode the text in the current buffer."
1403  (save-excursion
1404    ;; Replace "." at beginning of line with "..".
1405    (goto-char (point-min))
1406    (while (re-search-forward "^\\." nil t)
1407      (insert "."))
1408    (goto-char (point-max))
1409    ;; Insert newline at the end of the buffer.
1410    (unless (bolp)
1411      (insert "\n"))
1412    ;; Insert `.' at end of buffer (end of text mark).
1413    (goto-char (point-max))
1414    (insert ".\n")
1415    (goto-char (point-min))
1416    (while (not (eobp))
1417      (end-of-line)
1418      (delete-char 1)
1419      (insert nntp-end-of-line))))
1420
1421(defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1422  (set-buffer nntp-server-buffer)
1423  (erase-buffer)
1424  (cond
1425
1426   ;; This server does not talk NOV.
1427   ((not nntp-server-xover)
1428    nil)
1429
1430   ;; We don't care about gaps.
1431   ((or (not nntp-nov-gap)
1432	fetch-old)
1433    (nntp-send-xover-command
1434     (if fetch-old
1435	 (if (numberp fetch-old)
1436	     (max 1 (- (car articles) fetch-old))
1437	   1)
1438       (car articles))
1439     (car (last articles)) 'wait)
1440
1441    (goto-char (point-min))
1442    (when (looking-at "[1-5][0-9][0-9] .*\n")
1443      (delete-region (point) (progn (forward-line 1) (point))))
1444    (while (search-forward "\r" nil t)
1445      (replace-match "" t t))
1446    (goto-char (point-max))
1447    (forward-line -1)
1448    (when (looking-at "\\.")
1449      (delete-region (point) (progn (forward-line 1) (point)))))
1450
1451   ;; We do it the hard way.  For each gap, an XOVER command is sent
1452   ;; to the server.  We do not wait for a reply from the server, we
1453   ;; just send them off as fast as we can.  That means that we have
1454   ;; to count the number of responses we get back to find out when we
1455   ;; have gotten all we asked for.
1456   ((numberp nntp-nov-gap)
1457    (let ((count 0)
1458	  (received 0)
1459	  last-point
1460	  in-process-buffer-p
1461	  (buf nntp-server-buffer)
1462	  (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1463	  first last status)
1464      ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1465      ;; that means that the server does not understand XOVER, but we
1466      ;; won't know that until we try.
1467      (while (and nntp-server-xover articles)
1468	(setq first (car articles))
1469	;; Search forward until we find a gap, or until we run out of
1470	;; articles.
1471	(while (and (cdr articles)
1472		    (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1473	  (setq articles (cdr articles)))
1474
1475	(setq in-process-buffer-p (stringp nntp-server-xover))
1476        (nntp-send-xover-command first (setq last (car articles)))
1477        (setq articles (cdr articles))
1478
1479	(when (and nntp-server-xover in-process-buffer-p)
1480	  ;; Don't count tried request.
1481	  (setq count (1+ count))
1482
1483	  ;; Every 400 requests we have to read the stream in
1484	  ;; order to avoid deadlocks.
1485	  (when (or (null articles)	;All requests have been sent.
1486		    (= 1 (% count nntp-maximum-request)))
1487
1488	    (nntp-accept-response)
1489	    ;; On some Emacs versions the preceding function has a
1490	    ;; tendency to change the buffer.  Perhaps.  It's quite
1491	    ;; difficult to reproduce, because it only seems to happen
1492	    ;; once in a blue moon.
1493	    (set-buffer process-buffer)
1494	    (while (progn
1495		     (goto-char (or last-point (point-min)))
1496		     ;; Count replies.
1497		     (while (re-search-forward "^\\([0-9][0-9][0-9]\\) .*\n"
1498					       nil t)
1499		       (incf received)
1500		       (setq status (match-string 1))
1501		       (if (string-match "^[45]" status)
1502			   (setq status 'error)
1503			 (setq status 'ok)))
1504		     (setq last-point (point))
1505		     (or (< received count)
1506			 (if (eq status 'error)
1507			     nil
1508			   ;; I haven't started reading the final response
1509			   (progn
1510			     (goto-char (point-max))
1511			     (forward-line -1)
1512			     (not (looking-at "^\\.\r?\n"))))))
1513	      ;; I haven't read the end of the final response
1514	      (nntp-accept-response)
1515	      (set-buffer process-buffer))))
1516
1517        ;; Some nntp servers seem to have an extension to the XOVER
1518        ;; extension.  On these servers, requesting an article range
1519        ;; preceeding the active range does not return an error as
1520        ;; specified in the RFC.  What we instead get is the NOV entry
1521        ;; for the first available article.  Obviously, a client can
1522        ;; use that entry to avoid making unnecessary requests.  The
1523        ;; only problem is for a client that assumes that the response
1524        ;; will always be within the requested ranage.  For such a
1525        ;; client, we can get N copies of the same entry (one for each
1526        ;; XOVER command sent to the server).
1527
1528        (when (<= count 1)
1529          (goto-char (point-min))
1530          (when (re-search-forward "^[0-9][0-9][0-9] .*\n\\([0-9]+\\)" nil t)
1531            (let ((low-limit (string-to-number
1532			      (buffer-substring (match-beginning 1)
1533						(match-end 1)))))
1534              (while (and articles (<= (car articles) low-limit))
1535                (setq articles (cdr articles))))))
1536        (set-buffer buf))
1537
1538      (when nntp-server-xover
1539	(when in-process-buffer-p
1540	  (set-buffer buf)
1541	  (goto-char (point-max))
1542	  (insert-buffer-substring process-buffer)
1543	  (set-buffer process-buffer)
1544	  (erase-buffer)
1545	  (set-buffer buf))
1546
1547	;; We remove any "." lines and status lines.
1548	(goto-char (point-min))
1549	(while (search-forward "\r" nil t)
1550	  (delete-char -1))
1551	(goto-char (point-min))
1552	(delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1553	t))))
1554
1555  nntp-server-xover)
1556
1557(defun nntp-send-xover-command (beg end &optional wait-for-reply)
1558  "Send the XOVER command to the server."
1559  (let ((range (format "%d-%d" beg end))
1560	(nntp-inhibit-erase t))
1561    (if (stringp nntp-server-xover)
1562	;; If `nntp-server-xover' is a string, then we just send this
1563	;; command.
1564	(if wait-for-reply
1565	    (nntp-send-command-nodelete
1566	     "\r?\n\\.\r?\n" nntp-server-xover range)
1567	  ;; We do not wait for the reply.
1568	  (nntp-send-command-nodelete nil nntp-server-xover range))
1569      (let ((commands nntp-xover-commands))
1570	;; `nntp-xover-commands' is a list of possible XOVER commands.
1571	;; We try them all until we get at positive response.
1572	(while (and commands (eq nntp-server-xover 'try))
1573	  (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1574	  (save-excursion
1575	    (set-buffer nntp-server-buffer)
1576	    (goto-char (point-min))
1577	    (and (looking-at "[23]")	; No error message.
1578		 ;; We also have to look at the lines.  Some buggy
1579		 ;; servers give back simple lines with just the
1580		 ;; article number.  How... helpful.
1581		 (progn
1582		   (forward-line 1)
1583		   (looking-at "[0-9]+\t...")) ; More text after number.
1584		 (setq nntp-server-xover (car commands))))
1585	  (setq commands (cdr commands)))
1586	;; If none of the commands worked, we disable XOVER.
1587	(when (eq nntp-server-xover 'try)
1588	  (save-excursion
1589	    (set-buffer nntp-server-buffer)
1590	    (erase-buffer)
1591	    (setq nntp-server-xover nil)))
1592        nntp-server-xover))))
1593
1594(defun nntp-find-group-and-number (&optional group)
1595  (save-excursion
1596    (save-restriction
1597      (set-buffer nntp-server-buffer)
1598      (narrow-to-region (goto-char (point-min))
1599			(or (search-forward "\n\n" nil t) (point-max)))
1600      (goto-char (point-min))
1601      ;; We first find the number by looking at the status line.
1602      (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1603			 (string-to-number
1604			  (buffer-substring (match-beginning 1)
1605					    (match-end 1)))))
1606	    newsgroups xref)
1607	(and number (zerop number) (setq number nil))
1608	(if number
1609	    ;; Then we find the group name.
1610	    (setq group
1611		  (cond
1612		   ;; If there is only one group in the Newsgroups
1613		   ;; header, then it seems quite likely that this
1614		   ;; article comes from that group, I'd say.
1615		   ((and (setq newsgroups
1616			       (mail-fetch-field "newsgroups"))
1617			 (not (string-match "," newsgroups)))
1618		    newsgroups)
1619		   ;; If there is more than one group in the
1620		   ;; Newsgroups header, then the Xref header should
1621		   ;; be filled out.  We hazard a guess that the group
1622		   ;; that has this article number in the Xref header
1623		   ;; is the one we are looking for.  This might very
1624		   ;; well be wrong if this article happens to have
1625		   ;; the same number in several groups, but that's
1626		   ;; life.
1627		   ((and (setq xref (mail-fetch-field "xref"))
1628			 number
1629			 (string-match
1630			  (format "\\([^ :]+\\):%d" number) xref))
1631		    (match-string 1 xref))
1632		   (t "")))
1633	  (cond
1634	   ((and (setq xref (mail-fetch-field "xref"))
1635		 (string-match
1636		  (if group
1637		      (concat "\\(" (regexp-quote group) "\\):\\([0-9]+\\)")
1638		    "\\([^ :]+\\):\\([0-9]+\\)")
1639		  xref))
1640	    (setq group (match-string 1 xref)
1641		  number (string-to-number (match-string 2 xref))))
1642	   ((and (setq newsgroups
1643		       (mail-fetch-field "newsgroups"))
1644		 (not (string-match "," newsgroups)))
1645	    (setq group newsgroups))
1646	   (group)
1647	   (t (setq group ""))))
1648	(when (string-match "\r" group)
1649	  (setq group (substring group 0 (match-beginning 0))))
1650	(cons group number)))))
1651
1652(defun nntp-wait-for-string (regexp)
1653  "Wait until string arrives in the buffer."
1654  (let ((buf (current-buffer))
1655	proc)
1656    (goto-char (point-min))
1657    (while (and (setq proc (get-buffer-process buf))
1658		(memq (process-status proc) '(open run))
1659		(not (re-search-forward regexp nil t)))
1660      (accept-process-output proc)
1661      (set-buffer buf)
1662      (goto-char (point-min)))))
1663
1664
1665;; ==========================================================================
1666;; Obsolete nntp-open-* connection methods -- drv
1667;; ==========================================================================
1668
1669(defvoo nntp-open-telnet-envuser nil
1670  "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1671
1672(defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1673  "*Regular expression to match the shell prompt on the remote machine.")
1674
1675(defvoo nntp-rlogin-program "rsh"
1676  "*Program used to log in on remote machines.
1677The default is \"rsh\", but \"ssh\" is a popular alternative.")
1678
1679(defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1680  "*Parameters to `nntp-open-rlogin'.
1681That function may be used as `nntp-open-connection-function'.  In that
1682case, this list will be used as the parameter list given to rsh.")
1683
1684(defvoo nntp-rlogin-user-name nil
1685  "*User name on remote system when using the rlogin connect method.")
1686
1687(defvoo nntp-telnet-parameters
1688    '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1689  "*Parameters to `nntp-open-telnet'.
1690That function may be used as `nntp-open-connection-function'.  In that
1691case, this list will be executed as a command after logging in
1692via telnet.")
1693
1694(defvoo nntp-telnet-user-name nil
1695  "User name to log in via telnet with.")
1696
1697(defvoo nntp-telnet-passwd nil
1698  "Password to use to log in via telnet with.")
1699
1700(defun nntp-open-telnet (buffer)
1701  (save-excursion
1702    (set-buffer buffer)
1703    (erase-buffer)
1704    (let ((proc (apply
1705		 'start-process
1706		 "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1707	  (case-fold-search t))
1708      (when (memq (process-status proc) '(open run))
1709	(nntp-wait-for-string "^r?telnet")
1710	(process-send-string proc "set escape \^X\n")
1711	(cond
1712	 ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1713	  (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1714					    nntp-address "\n")))
1715	 (t
1716	  (process-send-string proc (concat "open " nntp-address "\n"))))
1717	(cond
1718	 ((not nntp-open-telnet-envuser)
1719	  (nntp-wait-for-string "^\r*.?login:")
1720	  (process-send-string
1721	   proc (concat
1722		 (or nntp-telnet-user-name
1723		     (setq nntp-telnet-user-name (read-string "login: ")))
1724		 "\n"))))
1725	(nntp-wait-for-string "^\r*.?password:")
1726	(process-send-string
1727	 proc (concat
1728	       (or nntp-telnet-passwd
1729		   (setq nntp-telnet-passwd
1730			 (read-passwd "Password: ")))
1731	       "\n"))
1732	(nntp-wait-for-string nntp-telnet-shell-prompt)
1733	(process-send-string
1734	 proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1735	(nntp-wait-for-string "^\r*20[01]")
1736	(beginning-of-line)
1737	(delete-region (point-min) (point))
1738	(process-send-string proc "\^]")
1739	(nntp-wait-for-string "^r?telnet")
1740	(process-send-string proc "mode character\n")
1741	(accept-process-output proc 1)
1742	(sit-for 1)
1743	(goto-char (point-min))
1744	(forward-line 1)
1745	(delete-region (point) (point-max)))
1746      proc)))
1747
1748(defun nntp-open-rlogin (buffer)
1749  "Open a connection to SERVER using rsh."
1750  (let ((proc (if nntp-rlogin-user-name
1751		  (apply 'start-process
1752			 "nntpd" buffer nntp-rlogin-program
1753			 nntp-address "-l" nntp-rlogin-user-name
1754			 nntp-rlogin-parameters)
1755		(apply 'start-process
1756		       "nntpd" buffer nntp-rlogin-program nntp-address
1757		       nntp-rlogin-parameters))))
1758    (save-excursion
1759      (set-buffer buffer)
1760      (nntp-wait-for-string "^\r*20[01]")
1761      (beginning-of-line)
1762      (delete-region (point-min) (point))
1763      proc)))
1764
1765
1766;; ==========================================================================
1767;; Replacements for the nntp-open-* functions -- drv
1768;; ==========================================================================
1769
1770(defun nntp-open-telnet-stream (buffer)
1771  "Open a nntp connection by telnet'ing the news server.
1772
1773Please refer to the following variables to customize the connection:
1774- `nntp-pre-command',
1775- `nntp-telnet-command',
1776- `nntp-telnet-switches',
1777- `nntp-address',
1778- `nntp-port-number',
1779- `nntp-end-of-line'."
1780  (let ((command `(,nntp-telnet-command
1781		   ,@nntp-telnet-switches
1782		   ,nntp-address ,nntp-port-number))
1783	proc)
1784    (and nntp-pre-command
1785	 (push nntp-pre-command command))
1786    (setq proc (apply 'start-process "nntpd" buffer command))
1787    (save-excursion
1788      (set-buffer buffer)
1789      (nntp-wait-for-string "^\r*20[01]")
1790      (beginning-of-line)
1791      (delete-region (point-min) (point))
1792      proc)))
1793
1794(defun nntp-open-via-rlogin-and-telnet (buffer)
1795  "Open a connection to an nntp server through an intermediate host.
1796First rlogin to the remote host, and then telnet the real news server
1797from there.
1798
1799Please refer to the following variables to customize the connection:
1800- `nntp-pre-command',
1801- `nntp-via-rlogin-command',
1802- `nntp-via-rlogin-command-switches',
1803- `nntp-via-user-name',
1804- `nntp-via-address',
1805- `nntp-telnet-command',
1806- `nntp-telnet-switches',
1807- `nntp-address',
1808- `nntp-port-number',
1809- `nntp-end-of-line'."
1810  (let ((command `(,nntp-via-address
1811		   ,nntp-telnet-command
1812		   ,@nntp-telnet-switches))
1813	proc)
1814    (when nntp-via-user-name
1815      (setq command `("-l" ,nntp-via-user-name ,@command)))
1816    (when nntp-via-rlogin-command-switches
1817      (setq command (append nntp-via-rlogin-command-switches command)))
1818    (push nntp-via-rlogin-command command)
1819    (and nntp-pre-command
1820	 (push nntp-pre-command command))
1821    (setq proc (apply 'start-process "nntpd" buffer command))
1822    (save-excursion
1823      (set-buffer buffer)
1824      (nntp-wait-for-string "^r?telnet")
1825      (process-send-string proc (concat "open " nntp-address
1826					" " nntp-port-number "\n"))
1827      (nntp-wait-for-string "^\r*20[01]")
1828      (beginning-of-line)
1829      (delete-region (point-min) (point))
1830      (process-send-string proc "\^]")
1831      (nntp-wait-for-string "^r?telnet")
1832      (process-send-string proc "mode character\n")
1833      (accept-process-output proc 1)
1834      (sit-for 1)
1835      (goto-char (point-min))
1836      (forward-line 1)
1837      (delete-region (point) (point-max)))
1838    proc))
1839
1840(defun nntp-open-via-telnet-and-telnet (buffer)
1841  "Open a connection to an nntp server through an intermediate host.
1842First telnet the remote host, and then telnet the real news server
1843from there.
1844
1845Please refer to the following variables to customize the connection:
1846- `nntp-pre-command',
1847- `nntp-via-telnet-command',
1848- `nntp-via-telnet-switches',
1849- `nntp-via-address',
1850- `nntp-via-envuser',
1851- `nntp-via-user-name',
1852- `nntp-via-user-password',
1853- `nntp-via-shell-prompt',
1854- `nntp-telnet-command',
1855- `nntp-telnet-switches',
1856- `nntp-address',
1857- `nntp-port-number',
1858- `nntp-end-of-line'."
1859  (save-excursion
1860    (set-buffer buffer)
1861    (erase-buffer)
1862    (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
1863	  (case-fold-search t)
1864	  proc)
1865      (and nntp-pre-command (push nntp-pre-command command))
1866      (setq proc (apply 'start-process "nntpd" buffer command))
1867      (when (memq (process-status proc) '(open run))
1868	(nntp-wait-for-string "^r?telnet")
1869	(process-send-string proc "set escape \^X\n")
1870	(cond
1871	 ((and nntp-via-envuser nntp-via-user-name)
1872	  (process-send-string proc (concat "open " "-l" nntp-via-user-name
1873					    nntp-via-address "\n")))
1874	 (t
1875	  (process-send-string proc (concat "open " nntp-via-address
1876					    "\n"))))
1877	(when (not nntp-via-envuser)
1878	  (nntp-wait-for-string "^\r*.?login:")
1879	  (process-send-string proc
1880			       (concat
1881				(or nntp-via-user-name
1882				    (setq nntp-via-user-name
1883					  (read-string "login: ")))
1884				"\n")))
1885	(nntp-wait-for-string "^\r*.?password:")
1886	(process-send-string proc
1887			     (concat
1888			      (or nntp-via-user-password
1889				  (setq nntp-via-user-password
1890					(read-passwd "Password: ")))
1891			      "\n"))
1892	(nntp-wait-for-string nntp-via-shell-prompt)
1893	(let ((real-telnet-command `("exec"
1894				     ,nntp-telnet-command
1895				     ,@nntp-telnet-switches
1896				     ,nntp-address
1897				     ,nntp-port-number)))
1898	  (process-send-string proc
1899			       (concat (mapconcat 'identity
1900						  real-telnet-command " ")
1901				       "\n")))
1902	(nntp-wait-for-string "^\r*20[01]")
1903	(beginning-of-line)
1904	(delete-region (point-min) (point))
1905	(process-send-string proc "\^]")
1906	(nntp-wait-for-string "^r?telnet")
1907	(process-send-string proc "mode character\n")
1908	(accept-process-output proc 1)
1909	(sit-for 1)
1910	(goto-char (point-min))
1911	(forward-line 1)
1912	(delete-region (point) (point-max)))
1913      proc)))
1914
1915(provide 'nntp)
1916
1917;;; arch-tag: 8655466a-b1b5-4929-9c45-7b1b2e767271
1918;;; nntp.el ends here
1919