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