* dgnushack.el: Autoload mail-extract-address-components for XEmacs.
[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         t
565       nil))
566    ;; A result that starts with a 3xx or 4xx code is terminated
567    ;; by a newline.
568    ((looking-at "[34]")
569     (if (search-forward "\n" nil t)
570         t
571       nil))
572    ;; No result here.
573    (t
574     nil)))
575
576 (eval-when-compile
577   (defvar nntp-with-open-group-internal nil)
578   (defvar nntp-report-n nil))
579
580 (defmacro nntp-with-open-group (group server &optional connectionless &rest forms)
581   "Protect against servers that don't like clients that keep idle connections opens.
582 The problem being that these servers may either close a connection or
583 simply ignore any further requests on a connection.  Closed
584 connections are not detected until accept-process-output has updated
585 the process-status.  Dropped connections are not detected until the
586 connection timeouts (which may be several minutes) or
587 nntp-connection-timeout has expired.  When these occur
588 nntp-with-open-group, opens a new connection then re-issues the NNTP
589 command whose response triggered the error."
590   (when (and (listp connectionless)
591              (not (eq connectionless nil)))
592     (setq forms (cons connectionless forms)
593           connectionless nil))
594   `(letf ((nntp-report-n (symbol-function 'nntp-report))
595           ((symbol-function 'nntp-report) (symbol-function 'nntp-report-1))
596           (nntp-with-open-group-internal nil))
597      (while (catch 'nntp-with-open-group-error
598               ;; Open the connection to the server
599               ;; NOTE: Existing connections are NOT tested.
600               (nntp-possibly-change-group ,group ,server ,connectionless)
601
602               (let ((timer
603                      (and nntp-connection-timeout
604                           (run-at-time
605                            nntp-connection-timeout nil
606                            '(lambda ()
607                               (let ((process (nntp-find-connection
608                                               nntp-server-buffer))
609                                     (buffer  (and process
610                                                   (process-buffer process))))
611                                 ;; When I an able to identify the
612                                 ;; connection to the server AND I've
613                                 ;; received NO reponse for
614                                 ;; nntp-connection-timeout seconds.
615                                 (when (and buffer (eq 0 (buffer-size buffer)))
616                                   ;; Close the connection.  Take no
617                                   ;; other action as the accept input
618                                   ;; code will handle the closed
619                                   ;; connection.
620                                   (nntp-kill-buffer buffer))))))))
621                 (unwind-protect
622                     (setq nntp-with-open-group-internal
623                           (condition-case nil
624                               (progn ,@forms)
625                             (quit
626                              (nntp-close-server)
627                              (signal 'quit nil))))
628                   (when timer
629                     (nnheader-cancel-timer timer)))
630                 nil))
631        (setf (symbol-function 'nntp-report) nntp-report-n))
632      nntp-with-open-group-internal))
633
634 (deffoo nntp-retrieve-headers (articles &optional group server fetch-old)
635   "Retrieve the headers of ARTICLES."
636   (nntp-with-open-group
637    group server
638    (save-excursion
639      (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
640      (erase-buffer)
641      (if (and (not gnus-nov-is-evil)
642               (not nntp-nov-is-evil)
643               (nntp-retrieve-headers-with-xover articles fetch-old))
644          ;; We successfully retrieved the headers via XOVER.
645          'nov
646        ;; XOVER didn't work, so we do it the hard, slow and inefficient
647        ;; way.
648        (let ((number (length articles))
649              (articles articles)
650              (count 0)
651              (received 0)
652              (last-point (point-min))
653              (buf (nntp-find-connection-buffer nntp-server-buffer))
654              (nntp-inhibit-erase t)
655              article)
656          ;; Send HEAD commands.
657          (while (setq article (pop articles))
658            (nntp-send-command
659             nil
660             "HEAD" (if (numberp article)
661                        (int-to-string article)
662                      ;; `articles' is either a list of article numbers
663                      ;; or a list of article IDs.
664                      article))
665            (incf count)
666            ;; Every 400 requests we have to read the stream in
667            ;; order to avoid deadlocks.
668            (when (or (null articles)    ;All requests have been sent.
669                      (zerop (% count nntp-maximum-request)))
670              (nntp-accept-response)
671              (while (progn
672                       (set-buffer buf)
673                       (goto-char last-point)
674                       ;; Count replies.
675                       (while (nntp-next-result-arrived-p)
676                         (setq last-point (point))
677                         (incf received))
678                       (< received count))
679                ;; If number of headers is greater than 100, give
680                ;;  informative messages.
681                (and (numberp nntp-large-newsgroup)
682                     (> number nntp-large-newsgroup)
683                     (zerop (% received 20))
684                     (nnheader-message 6 "NNTP: Receiving headers... %d%%"
685                                       (/ (* received 100) number)))
686                (nntp-accept-response))))
687          (and (numberp nntp-large-newsgroup)
688               (> number nntp-large-newsgroup)
689               (nnheader-message 6 "NNTP: Receiving headers...done"))
690
691          ;; Now all of replies are received.  Fold continuation lines.
692          (nnheader-fold-continuation-lines)
693          ;; Remove all "\r"'s.
694          (nnheader-strip-cr)
695          (copy-to-buffer nntp-server-buffer (point-min) (point-max))
696          'headers)))))
697
698 (deffoo nntp-retrieve-groups (groups &optional server)
699   "Retrieve group info on GROUPS."
700   (nntp-with-open-group
701    nil server
702    (when (nntp-find-connection-buffer nntp-server-buffer)
703      (catch 'done
704        (save-excursion
705          ;; Erase nntp-server-buffer before nntp-inhibit-erase.
706          (nntp-erase-buffer nntp-server-buffer)
707          (set-buffer (nntp-find-connection-buffer nntp-server-buffer))
708          ;; The first time this is run, this variable is `try'.  So we
709          ;; try.
710          (when (eq nntp-server-list-active-group 'try)
711            (nntp-try-list-active (car groups)))
712          (erase-buffer)
713          (let ((count 0)
714                (groups groups)
715                (received 0)
716                (last-point (point-min))
717                (nntp-inhibit-erase t)
718                (buf (nntp-find-connection-buffer nntp-server-buffer))
719                (command (if nntp-server-list-active-group
720                             "LIST ACTIVE" "GROUP")))
721            (while groups
722              ;; Timeout may have killed the buffer.
723              (unless (gnus-buffer-live-p buf)
724                (nnheader-report 'nntp "Connection to %s is closed." server)
725                (throw 'done nil))
726              ;; Send the command to the server.
727              (nntp-send-command nil command (pop groups))
728              (incf count)
729              ;; Every 400 requests we have to read the stream in
730              ;; order to avoid deadlocks.
731              (when (or (null groups)    ;All requests have been sent.
732                        (zerop (% count nntp-maximum-request)))
733                (nntp-accept-response)
734                (while (and (gnus-buffer-live-p buf)
735                            (progn
736                              ;; Search `blue moon' in this file for the
737                              ;; reason why set-buffer here.
738                              (set-buffer buf)
739                              (goto-char last-point)
740                              ;; Count replies.
741                              (while (re-search-forward "^[0-9]" nil t)
742                                (incf received))
743                              (setq last-point (point))
744                              (< received count)))
745                  (nntp-accept-response))))
746
747            ;; Wait for the reply from the final command.
748            (unless (gnus-buffer-live-p buf)
749              (nnheader-report 'nntp "Connection to %s is closed." server)
750              (throw 'done nil))
751            (set-buffer buf)
752            (goto-char (point-max))
753            (re-search-backward "^[0-9]" nil t)
754            (when (looking-at "^[23]")
755              (while (and (gnus-buffer-live-p buf)
756                          (progn
757                            (set-buffer buf)
758                            (goto-char (point-max))
759                            (if (not nntp-server-list-active-group)
760                                (not (re-search-backward "\r?\n"
761                                                         (- (point) 3) t))
762                              (not (re-search-backward "^\\.\r?\n"
763                                                       (- (point) 4) t)))))
764                (nntp-accept-response)))
765
766            ;; Now all replies are received.  We remove CRs.
767            (unless (gnus-buffer-live-p buf)
768              (nnheader-report 'nntp "Connection to %s is closed." server)
769              (throw 'done nil))
770            (set-buffer buf)
771            (goto-char (point-min))
772            (while (search-forward "\r" nil t)
773              (replace-match "" t t))
774
775            (if (not nntp-server-list-active-group)
776                (progn
777                  (copy-to-buffer nntp-server-buffer (point-min) (point-max))
778                  'group)
779              ;; We have read active entries, so we just delete the
780              ;; superfluous gunk.
781              (goto-char (point-min))
782              (while (re-search-forward "^[.2-5]" nil t)
783                (delete-region (match-beginning 0)
784                               (progn (forward-line 1) (point))))
785              (copy-to-buffer nntp-server-buffer (point-min) (point-max))
786              'active)))))))
787
788 (deffoo nntp-retrieve-articles (articles &optional group server)
789   (nntp-with-open-group
790     group server
791    (save-excursion
792      (let ((number (length articles))
793            (articles articles)
794            (count 0)
795            (received 0)
796            (last-point (point-min))
797            (buf (nntp-find-connection-buffer nntp-server-buffer))
798            (nntp-inhibit-erase t)
799            (map (apply 'vector articles))
800            (point 1)
801            article)
802        (set-buffer buf)
803        (erase-buffer)
804        ;; Send ARTICLE command.
805        (while (setq article (pop articles))
806          (nntp-send-command
807           nil
808           "ARTICLE" (if (numberp article)
809                         (int-to-string article)
810                       ;; `articles' is either a list of article numbers
811                       ;; or a list of article IDs.
812                       article))
813          (incf count)
814          ;; Every 400 requests we have to read the stream in
815          ;; order to avoid deadlocks.
816          (when (or (null articles)      ;All requests have been sent.
817                    (zerop (% count nntp-maximum-request)))
818            (nntp-accept-response)
819            (while (progn
820                     (set-buffer buf)
821                     (goto-char last-point)
822                     ;; Count replies.
823                     (while (nntp-next-result-arrived-p)
824                       (aset map received (cons (aref map received) (point)))
825                       (setq last-point (point))
826                       (incf received))
827                     (< received count))
828              ;; If number of headers is greater than 100, give
829              ;;  informative messages.
830              (and (numberp nntp-large-newsgroup)
831                   (> number nntp-large-newsgroup)
832                   (zerop (% received 20))
833                   (nnheader-message 6 "NNTP: Receiving articles... %d%%"
834                                     (/ (* received 100) number)))
835              (nntp-accept-response))))
836        (and (numberp nntp-large-newsgroup)
837             (> number nntp-large-newsgroup)
838             (nnheader-message 6 "NNTP: Receiving articles...done"))
839
840        ;; Now we have all the responses.  We go through the results,
841        ;; wash it and copy it over to the server buffer.
842        (set-buffer nntp-server-buffer)
843        (erase-buffer)
844        (setq last-point (point-min))
845        (mapcar
846         (lambda (entry)
847           (narrow-to-region
848            (setq point (goto-char (point-max)))
849            (progn
850              (insert-buffer-substring buf last-point (cdr entry))
851              (point-max)))
852           (setq last-point (cdr entry))
853           (nntp-decode-text)
854           (widen)
855           (cons (car entry) point))
856         map)))))
857
858 (defun nntp-try-list-active (group)
859   (nntp-list-active-group group)
860   (save-excursion
861     (set-buffer nntp-server-buffer)
862     (goto-char (point-min))
863     (cond ((or (eobp)
864                (looking-at "5[0-9]+"))
865            (setq nntp-server-list-active-group nil))
866           (t
867            (setq nntp-server-list-active-group t)))))
868
869 (deffoo nntp-list-active-group (group &optional server)
870   "Return the active info on GROUP (which can be a regexp)."
871   (nntp-with-open-group
872    nil server
873    (nntp-send-command "^\\.*\r?\n" "LIST ACTIVE" group)))
874
875 (deffoo nntp-request-group-articles (group &optional server)
876   "Return the list of existing articles in GROUP."
877   (nntp-with-open-group
878    nil server
879    (nntp-send-command "^\\.*\r?\n" "LISTGROUP" group)))
880
881 (deffoo nntp-request-article (article &optional group server buffer command)
882   (nntp-with-open-group
883     group server
884     (when (nntp-send-command-and-decode
885            "\r?\n\\.\r?\n" "ARTICLE"
886            (if (numberp article) (int-to-string article) article))
887       (if (and buffer
888                (not (equal buffer nntp-server-buffer)))
889           (save-excursion
890             (set-buffer nntp-server-buffer)
891             (copy-to-buffer buffer (point-min) (point-max))
892             (nntp-find-group-and-number group))
893         (nntp-find-group-and-number group)))))
894
895 (deffoo nntp-request-head (article &optional group server)
896   (nntp-with-open-group
897    group server
898    (when (nntp-send-command
899           "\r?\n\\.\r?\n" "HEAD"
900           (if (numberp article) (int-to-string article) article))
901      (prog1
902          (nntp-find-group-and-number group)
903        (nntp-decode-text)))))
904
905 (deffoo nntp-request-body (article &optional group server)
906   (nntp-with-open-group
907    group server
908    (nntp-send-command-and-decode
909     "\r?\n\\.\r?\n" "BODY"
910     (if (numberp article) (int-to-string article) article))))
911
912 (deffoo nntp-request-group (group &optional server dont-check)
913   (nntp-with-open-group 
914     nil server
915     (when (nntp-send-command "^[245].*\n" "GROUP" group)
916       (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
917         (setcar (cddr entry) group)))))
918
919 (deffoo nntp-close-group (group &optional server)
920   t)
921
922 (deffoo nntp-server-opened (&optional server)
923   "Say whether a connection to SERVER has been opened."
924   (and (nnoo-current-server-p 'nntp server)
925        nntp-server-buffer
926        (gnus-buffer-live-p nntp-server-buffer)
927        (nntp-find-connection nntp-server-buffer)))
928
929 (deffoo nntp-open-server (server &optional defs connectionless)
930   (nnheader-init-server-buffer)
931   (if (nntp-server-opened server)
932       t
933     (when (or (stringp (car defs))
934               (numberp (car defs)))
935       (setq defs (cons (list 'nntp-port-number (car defs)) (cdr defs))))
936     (unless (assq 'nntp-address defs)
937       (setq defs (append defs (list (list 'nntp-address server)))))
938     (nnoo-change-server 'nntp server defs)
939     (unless connectionless
940       (or (nntp-find-connection nntp-server-buffer)
941           (nntp-open-connection nntp-server-buffer)))))
942
943 (deffoo nntp-close-server (&optional server)
944   (nntp-possibly-change-group nil server t)
945   (let ((process (nntp-find-connection nntp-server-buffer)))
946     (while process
947       (when (memq (process-status process) '(open run))
948         (ignore-errors
949           (nntp-send-string process "QUIT")
950           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
951             ;; Ok, this is evil, but when using telnet and stuff
952             ;; as the connection method, it's important that the
953             ;; QUIT command actually is sent out before we kill
954             ;; the process.
955             (sleep-for 1))))
956       (nntp-kill-buffer (process-buffer process))
957       (setq process (car (pop nntp-connection-alist))))
958     (nnoo-close-server 'nntp)))
959
960 (deffoo nntp-request-close ()
961   (let (process)
962     (while (setq process (pop nntp-connection-list))
963       (when (memq (process-status process) '(open run))
964         (ignore-errors
965           (nntp-send-string process "QUIT")
966           (unless (eq nntp-open-connection-function 'nntp-open-network-stream)
967             ;; Ok, this is evil, but when using telnet and stuff
968             ;; as the connection method, it's important that the
969             ;; QUIT command actually is sent out before we kill
970             ;; the process.
971             (sleep-for 1))))
972       (nntp-kill-buffer (process-buffer process)))))
973
974 (deffoo nntp-request-list (&optional server)
975   (nntp-with-open-group
976    nil server
977    (nntp-send-command-and-decode "\r?\n\\.\r?\n" "LIST")))
978
979 (deffoo nntp-request-list-newsgroups (&optional server)
980   (nntp-with-open-group
981    nil server
982    (nntp-send-command "\r?\n\\.\r?\n" "LIST NEWSGROUPS")))
983
984 (deffoo nntp-request-newgroups (date &optional server)
985   (nntp-with-open-group
986    nil server
987    (save-excursion
988      (set-buffer nntp-server-buffer)
989      (let* ((time (date-to-time date))
990             (ls (- (cadr time) (nth 8 (decode-time time)))))
991        (cond ((< ls 0)
992               (setcar time (1- (car time)))
993               (setcar (cdr time) (+ ls 65536)))
994              ((>= ls 65536)
995               (setcar time (1+ (car time)))
996               (setcar (cdr time) (- ls 65536)))
997              (t
998               (setcar (cdr time) ls)))
999        (prog1
1000            (nntp-send-command
1001             "^\\.\r?\n" "NEWGROUPS"
1002             (format-time-string "%y%m%d %H%M%S" time)
1003             "GMT")
1004          (nntp-decode-text))))))
1005
1006 (deffoo nntp-request-post (&optional server)
1007   (nntp-with-open-group
1008    nil server
1009    (when (nntp-send-command "^[23].*\r?\n" "POST")
1010      (let ((response (with-current-buffer nntp-server-buffer
1011                        nntp-process-response))
1012            server-id)
1013        (when (and response
1014                   (string-match "^[23].*\\(<[^\t\n @<>]+@[^\t\n @<>]+>\\)"
1015                                 response))
1016          (setq server-id (match-string 1 response))
1017          (narrow-to-region (goto-char (point-min))
1018                            (if (search-forward "\n\n" nil t)
1019                                (1- (point))
1020                              (point-max)))
1021          (unless (mail-fetch-field "Message-ID")
1022            (goto-char (point-min))
1023            (insert "Message-ID: " server-id "\n"))
1024          (widen))
1025        (run-hooks 'nntp-prepare-post-hook)
1026        (nntp-send-buffer "^[23].*\n")))))
1027
1028 (deffoo nntp-request-type (group article)
1029   'news)
1030
1031 (deffoo nntp-asynchronous-p ()
1032   t)
1033
1034 (deffoo nntp-request-set-mark (group actions &optional server)
1035   (unless nntp-marks-is-evil
1036     (nntp-possibly-create-directory group server)
1037     (nntp-open-marks group server)
1038     (dolist (action actions)
1039       (let ((range (nth 0 action))
1040             (what  (nth 1 action))
1041             (marks (nth 2 action)))
1042         (assert (or (eq what 'add) (eq what 'del)) nil
1043                 "Unknown request-set-mark action: %s" what)
1044         (dolist (mark marks)
1045           (setq nntp-marks (gnus-update-alist-soft
1046                             mark
1047                             (funcall (if (eq what 'add) 'gnus-range-add
1048                                        'gnus-remove-from-range)
1049                                      (cdr (assoc mark nntp-marks)) range)
1050                             nntp-marks)))))
1051     (nntp-save-marks group server))
1052   nil)
1053
1054 (deffoo nntp-request-update-info (group info &optional server)
1055   (unless nntp-marks-is-evil
1056     (nntp-possibly-create-directory group server)
1057     (when (nntp-marks-changed-p group server)
1058       (nnheader-message 8 "Updating marks for %s..." group)
1059       (nntp-open-marks group server)
1060       ;; Update info using `nntp-marks'.
1061       (mapc (lambda (pred)
1062               (unless (memq (cdr pred) gnus-article-unpropagated-mark-lists)
1063                 (gnus-info-set-marks
1064                  info
1065                  (gnus-update-alist-soft
1066                   (cdr pred)
1067                   (cdr (assq (cdr pred) nntp-marks))
1068                   (gnus-info-marks info))
1069                  t)))
1070             gnus-article-mark-lists)
1071       (let ((seen (cdr (assq 'read nntp-marks))))
1072         (gnus-info-set-read info
1073                             (if (and (integerp (car seen))
1074                                      (null (cdr seen)))
1075                                 (list (cons (car seen) (car seen)))
1076                               seen)))
1077       (nnheader-message 8 "Updating marks for %s...done" group)))
1078   nil)
1079
1080
1081
1082 ;;; Hooky functions.
1083
1084 (defun nntp-send-mode-reader ()
1085   "Send the MODE READER command to the nntp server.
1086 This function is supposed to be called from `nntp-server-opened-hook'.
1087 It will make innd servers spawn an nnrpd process to allow actual article
1088 reading."
1089   (nntp-send-command "^.*\n" "MODE READER"))
1090
1091 (defun nntp-send-authinfo (&optional send-if-force)
1092   "Send the AUTHINFO to the nntp server.
1093 It will look in the \"~/.authinfo\" file for matching entries.  If
1094 nothing suitable is found there, it will prompt for a user name
1095 and a password.
1096
1097 If SEND-IF-FORCE, only send authinfo to the server if the
1098 .authinfo file has the FORCE token."
1099   (let* ((list (netrc-parse nntp-authinfo-file))
1100          (alist (netrc-machine list nntp-address "nntp"))
1101          (force (netrc-get alist "force"))
1102          (user (or (netrc-get alist "login") nntp-authinfo-user))
1103          (passwd (netrc-get alist "password")))
1104     (when (or (not send-if-force)
1105               force)
1106       (unless user
1107         (setq user (read-string (format "NNTP (%s) user name: " nntp-address))
1108               nntp-authinfo-user user))
1109       (unless (member user '(nil ""))
1110         (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1111         (when t                         ;???Should check if AUTHINFO succeeded
1112           (nntp-send-command
1113            "^2.*\r?\n" "AUTHINFO PASS"
1114            (or passwd
1115                nntp-authinfo-password
1116                (setq nntp-authinfo-password
1117                      (read-passwd (format "NNTP (%s@%s) password: "
1118                                           user nntp-address))))))))))
1119
1120 (defun nntp-send-nosy-authinfo ()
1121   "Send the AUTHINFO to the nntp server."
1122   (let ((user (read-string (format "NNTP (%s) user name: " nntp-address))))
1123     (unless (member user '(nil ""))
1124       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" user)
1125       (when t                           ;???Should check if AUTHINFO succeeded
1126         (nntp-send-command "^2.*\r?\n" "AUTHINFO PASS"
1127                            (read-passwd (format "NNTP (%s@%s) password: "
1128                                                 user nntp-address)))))))
1129
1130 (defun nntp-send-authinfo-from-file ()
1131   "Send the AUTHINFO to the nntp server.
1132
1133 The authinfo login name is taken from the user's login name and the
1134 password contained in '~/.nntp-authinfo'."
1135   (when (file-exists-p "~/.nntp-authinfo")
1136     (with-temp-buffer
1137       (insert-file-contents "~/.nntp-authinfo")
1138       (goto-char (point-min))
1139       (nntp-send-command "^3.*\r?\n" "AUTHINFO USER" (user-login-name))
1140       (nntp-send-command
1141        "^2.*\r?\n" "AUTHINFO PASS"
1142        (buffer-substring (point) (point-at-eol))))))
1143
1144 ;;; Internal functions.
1145
1146 (defun nntp-handle-authinfo (process)
1147   "Take care of an authinfo response from the server."
1148   (let ((last nntp-last-command))
1149     (funcall nntp-authinfo-function)
1150     ;; We have to re-send the function that was interrupted by
1151     ;; the authinfo request.
1152     (nntp-erase-buffer nntp-server-buffer)
1153     (nntp-send-string process last)))
1154
1155 (defun nntp-make-process-buffer (buffer)
1156   "Create a new, fresh buffer usable for nntp process connections."
1157   (save-excursion
1158     (set-buffer
1159      (generate-new-buffer
1160       (format " *server %s %s %s*"
1161               nntp-address nntp-port-number
1162               (gnus-buffer-exists-p buffer))))
1163     (mm-enable-multibyte)
1164     (set (make-local-variable 'after-change-functions) nil)
1165     (set (make-local-variable 'nntp-process-wait-for) nil)
1166     (set (make-local-variable 'nntp-process-callback) nil)
1167     (set (make-local-variable 'nntp-process-to-buffer) nil)
1168     (set (make-local-variable 'nntp-process-start-point) nil)
1169     (set (make-local-variable 'nntp-process-decode) nil)
1170     (current-buffer)))
1171
1172 (defun nntp-open-connection (buffer)
1173   "Open a connection to PORT on ADDRESS delivering output to BUFFER."
1174   (run-hooks 'nntp-prepare-server-hook)
1175   (let* ((pbuffer (nntp-make-process-buffer buffer))
1176          (timer
1177           (and nntp-connection-timeout
1178                (run-at-time
1179                 nntp-connection-timeout nil
1180                 `(lambda ()
1181                    (nntp-kill-buffer ,pbuffer)))))
1182          (process
1183           (condition-case ()
1184               (let ((coding-system-for-read nntp-coding-system-for-read)
1185                     (coding-system-for-write nntp-coding-system-for-write))
1186                 (funcall nntp-open-connection-function pbuffer))
1187             (error nil)
1188             (quit
1189              (message "Quit opening connection")
1190              (nntp-kill-buffer pbuffer)
1191              (signal 'quit nil)
1192              nil))))
1193     (when timer
1194       (nnheader-cancel-timer timer))
1195     (unless process
1196       (nntp-kill-buffer pbuffer))
1197     (when (and (buffer-name pbuffer)
1198                process)
1199       (process-kill-without-query process)
1200       (if (and (nntp-wait-for process "^2.*\n" buffer nil t)
1201                (memq (process-status process) '(open run)))
1202           (prog1
1203               (caar (push (list process buffer nil) nntp-connection-alist))
1204             (push process nntp-connection-list)
1205             (save-excursion
1206               (set-buffer pbuffer)
1207               (nntp-read-server-type)
1208               (erase-buffer)
1209               (set-buffer nntp-server-buffer)
1210               (let ((nnheader-callback-function nil))
1211                 (run-hooks 'nntp-server-opened-hook)
1212                 (nntp-send-authinfo t))))
1213         (nntp-kill-buffer (process-buffer process))
1214         nil))))
1215
1216 (defun nntp-open-network-stream (buffer)
1217   (open-network-stream "nntpd" buffer nntp-address nntp-port-number))
1218
1219 (eval-and-compile
1220   (autoload 'format-spec "format-spec")
1221   (autoload 'format-spec-make "format-spec")
1222   (autoload 'open-tls-stream "tls"))
1223
1224 (defun nntp-open-ssl-stream (buffer)
1225   (let* ((process-connection-type nil)
1226          (proc (start-process "nntpd" buffer 
1227                               shell-file-name
1228                               shell-command-switch
1229                               (format-spec nntp-ssl-program 
1230                                            (format-spec-make
1231                                             ?s nntp-address
1232                                             ?p nntp-port-number)))))
1233     (process-kill-without-query proc)
1234     (save-excursion
1235       (set-buffer buffer)
1236       (let ((nntp-connection-alist (list proc buffer nil)))
1237         (nntp-wait-for-string "^\r*20[01]"))
1238       (beginning-of-line)
1239       (delete-region (point-min) (point))
1240       proc)))
1241
1242 (defun nntp-open-tls-stream (buffer)
1243   (let ((proc (open-tls-stream "nntpd" buffer nntp-address nntp-port-number)))
1244     (process-kill-without-query proc)
1245     (save-excursion
1246       (set-buffer buffer)
1247       (let ((nntp-connection-alist (list proc buffer nil)))
1248         (nntp-wait-for-string "^\r*20[01]"))
1249       (beginning-of-line)
1250       (delete-region (point-min) (point))
1251       proc)))
1252
1253 (defun nntp-read-server-type ()
1254   "Find out what the name of the server we have connected to is."
1255   ;; Wait for the status string to arrive.
1256   (setq nntp-server-type (buffer-string))
1257   (let ((case-fold-search t))
1258     ;; Run server-specific commands.
1259     (dolist (entry nntp-server-action-alist)
1260       (when (string-match (car entry) nntp-server-type)
1261         (if (and (listp (cadr entry))
1262                  (not (eq 'lambda (caadr entry))))
1263             (eval (cadr entry))
1264           (funcall (cadr entry)))))))
1265
1266 (defun nntp-async-wait (process wait-for buffer decode callback)
1267   (save-excursion
1268     (set-buffer (process-buffer process))
1269     (unless nntp-inside-change-function
1270       (erase-buffer))
1271     (setq nntp-process-wait-for wait-for
1272           nntp-process-to-buffer buffer
1273           nntp-process-decode decode
1274           nntp-process-callback callback
1275           nntp-process-start-point (point-max))
1276     (setq after-change-functions '(nntp-after-change-function))
1277     (if nntp-async-needs-kluge
1278         (nntp-async-kluge process))))
1279
1280 (defun nntp-async-kluge (process)
1281   ;; emacs 20.3 bug: process output with encoding 'binary
1282   ;; doesn't trigger after-change-functions.
1283   (unless nntp-async-timer
1284     (setq nntp-async-timer
1285           (run-at-time 1 1 'nntp-async-timer-handler)))
1286   (add-to-list 'nntp-async-process-list process))
1287
1288 (defun nntp-async-timer-handler ()
1289   (mapcar
1290    (lambda (proc)
1291      (if (memq (process-status proc) '(open run))
1292          (nntp-async-trigger proc)
1293        (nntp-async-stop proc)))
1294    nntp-async-process-list))
1295
1296 (defun nntp-async-stop (proc)
1297   (setq nntp-async-process-list (delq proc nntp-async-process-list))
1298   (when (and nntp-async-timer (not nntp-async-process-list))
1299     (nnheader-cancel-timer nntp-async-timer)
1300     (setq nntp-async-timer nil)))
1301
1302 (defun nntp-after-change-function (beg end len)
1303   (unwind-protect
1304       ;; we only care about insertions at eob
1305       (when (and (eq 0 len) (eq (point-max) end))
1306         (save-match-data
1307           (let ((proc (get-buffer-process (current-buffer))))
1308             (when proc
1309               (nntp-async-trigger proc)))))
1310     ;; any throw from after-change-functions will leave it
1311     ;; set to nil.  so we reset it here, if necessary.
1312     (when quit-flag
1313       (setq after-change-functions '(nntp-after-change-function)))))
1314
1315 (defun nntp-async-trigger (process)
1316   (save-excursion
1317     (set-buffer (process-buffer process))
1318     (when nntp-process-callback
1319       ;; do we have an error message?
1320       (goto-char nntp-process-start-point)
1321       (if (memq (following-char) '(?4 ?5))
1322           ;; wants credentials?
1323           (if (looking-at "480")
1324               (nntp-handle-authinfo process)
1325             ;; report error message.
1326             (nntp-snarf-error-message)
1327             (nntp-do-callback nil))
1328
1329         ;; got what we expect?
1330         (goto-char (point-max))
1331         (when (re-search-backward
1332                nntp-process-wait-for nntp-process-start-point t)
1333           (let ((response (match-string 0)))
1334             (with-current-buffer nntp-server-buffer
1335               (setq nntp-process-response response)))
1336           (nntp-async-stop process)
1337           ;; convert it.
1338           (when (gnus-buffer-exists-p nntp-process-to-buffer)
1339             (let ((buf (current-buffer))
1340                   (start nntp-process-start-point)
1341                   (decode nntp-process-decode))
1342               (save-excursion
1343                 (set-buffer nntp-process-to-buffer)
1344                 (goto-char (point-max))
1345                 (save-restriction
1346                   (narrow-to-region (point) (point))
1347                   (insert-buffer-substring buf start)
1348                   (when decode
1349                     (nntp-decode-text))))))
1350           ;; report it.
1351           (goto-char (point-max))
1352           (nntp-do-callback
1353            (buffer-name (get-buffer nntp-process-to-buffer))))))))
1354
1355 (defun nntp-do-callback (arg)
1356   (let ((callback nntp-process-callback)
1357         (nntp-inside-change-function t))
1358     (setq nntp-process-callback nil)
1359     (funcall callback arg)))
1360
1361 (defun nntp-snarf-error-message ()
1362   "Save the error message in the current buffer."
1363   (let ((message (buffer-string)))
1364     (while (string-match "[\r\n]+" message)
1365       (setq message (replace-match " " t t message)))
1366     (nnheader-report 'nntp message)
1367     message))
1368
1369 (defun nntp-accept-process-output (process)
1370   "Wait for output from PROCESS and message some dots."
1371   (save-excursion
1372     (set-buffer (or (nntp-find-connection-buffer nntp-server-buffer)
1373                     nntp-server-buffer))
1374     (let ((len (/ (buffer-size) 1024))
1375           message-log-max)
1376       (unless (< len 10)
1377         (setq nntp-have-messaged t)
1378         (nnheader-message 7 "nntp read: %dk" len)))
1379     (nnheader-accept-process-output process)
1380     ;; accept-process-output may update status of process to indicate
1381     ;; that the server has closed the connection.  This MUST be
1382     ;; handled here as the buffer restored by the save-excursion may
1383     ;; be the process's former output buffer (i.e. now killed)
1384     (or (and process 
1385              (memq (process-status process) '(open run)))
1386         (nntp-report "Server closed connection"))))
1387
1388 (defun nntp-accept-response ()
1389   "Wait for output from the process that outputs to BUFFER."
1390   (nntp-accept-process-output (nntp-find-connection nntp-server-buffer)))
1391
1392 (defun nntp-possibly-change-group (group server &optional connectionless)
1393   (let ((nnheader-callback-function nil))
1394     (when server
1395       (or (nntp-server-opened server)
1396           (nntp-open-server server nil connectionless)))
1397
1398     (unless connectionless
1399       (or (nntp-find-connection nntp-server-buffer)
1400           (nntp-open-connection nntp-server-buffer))))
1401
1402   (when group
1403     (let ((entry (nntp-find-connection-entry nntp-server-buffer)))
1404       (cond ((not entry)
1405              (nntp-report "Server closed connection"))
1406             ((not (equal group (caddr entry)))
1407              (save-excursion
1408                (set-buffer (process-buffer (car entry)))
1409                (erase-buffer)
1410                (nntp-send-command "^[245].*\n" "GROUP" group)
1411                (setcar (cddr entry) group)
1412                (erase-buffer)
1413                (nntp-erase-buffer nntp-server-buffer)))))))
1414
1415 (defun nntp-decode-text (&optional cr-only)
1416   "Decode the text in the current buffer."
1417   (goto-char (point-min))
1418   (while (search-forward "\r" nil t)
1419     (delete-char -1))
1420   (unless cr-only
1421     ;; Remove trailing ".\n" end-of-transfer marker.
1422     (goto-char (point-max))
1423     (forward-line -1)
1424     (when (looking-at ".\n")
1425       (delete-char 2))
1426     ;; Delete status line.
1427     (goto-char (point-min))
1428     (while (looking-at "[1-5][0-9][0-9] .*\n")
1429       ;; For some unknown reason, there is more than one status line.
1430       (delete-region (point) (progn (forward-line 1) (point))))
1431     ;; Remove "." -> ".." encoding.
1432     (while (search-forward "\n.." nil t)
1433       (delete-char -1))))
1434
1435 (defun nntp-encode-text ()
1436   "Encode the text in the current buffer."
1437   (save-excursion
1438     ;; Replace "." at beginning of line with "..".
1439     (goto-char (point-min))
1440     (while (re-search-forward "^\\." nil t)
1441       (insert "."))
1442     (goto-char (point-max))
1443     ;; Insert newline at the end of the buffer.
1444     (unless (bolp)
1445       (insert "\n"))
1446     ;; Insert `.' at end of buffer (end of text mark).
1447     (goto-char (point-max))
1448     (insert ".\n")
1449     (goto-char (point-min))
1450     (while (not (eobp))
1451       (end-of-line)
1452       (delete-char 1)
1453       (insert nntp-end-of-line))))
1454
1455 (defun nntp-retrieve-headers-with-xover (articles &optional fetch-old)
1456   (set-buffer nntp-server-buffer)
1457   (erase-buffer)
1458   (cond
1459
1460    ;; This server does not talk NOV.
1461    ((not nntp-server-xover)
1462     nil)
1463
1464    ;; We don't care about gaps.
1465    ((or (not nntp-nov-gap)
1466         fetch-old)
1467     (nntp-send-xover-command
1468      (if fetch-old
1469          (if (numberp fetch-old)
1470              (max 1 (- (car articles) fetch-old))
1471            1)
1472        (car articles))
1473      (car (last articles)) 'wait)
1474
1475     (goto-char (point-min))
1476     (when (looking-at "[1-5][0-9][0-9] .*\n")
1477       (delete-region (point) (progn (forward-line 1) (point))))
1478     (while (search-forward "\r" nil t)
1479       (replace-match "" t t))
1480     (goto-char (point-max))
1481     (forward-line -1)
1482     (when (looking-at "\\.")
1483       (delete-region (point) (progn (forward-line 1) (point)))))
1484
1485    ;; We do it the hard way.  For each gap, an XOVER command is sent
1486    ;; to the server.  We do not wait for a reply from the server, we
1487    ;; just send them off as fast as we can.  That means that we have
1488    ;; to count the number of responses we get back to find out when we
1489    ;; have gotten all we asked for.
1490    ((numberp nntp-nov-gap)
1491     (let ((count 0)
1492           (received 0)
1493           last-point
1494           in-process-buffer-p
1495           (buf nntp-server-buffer)
1496           (process-buffer (nntp-find-connection-buffer nntp-server-buffer))
1497           first last status)
1498       ;; We have to check `nntp-server-xover'.  If it gets set to nil,
1499       ;; that means that the server does not understand XOVER, but we
1500       ;; won't know that until we try.
1501       (while (and nntp-server-xover articles)
1502         (setq first (car articles))
1503         ;; Search forward until we find a gap, or until we run out of
1504         ;; articles.
1505         (while (and (cdr articles)
1506                     (< (- (nth 1 articles) (car articles)) nntp-nov-gap))
1507           (setq articles (cdr articles)))
1508
1509         (setq in-process-buffer-p (stringp nntp-server-xover))
1510         (nntp-send-xover-command first (setq last (car articles)))
1511         (setq articles (cdr articles))
1512
1513         (when (and nntp-server-xover in-process-buffer-p)
1514           ;; Don't count tried request.
1515           (setq count (1+ count))
1516
1517           ;; Every 400 requests we have to read the stream in
1518           ;; order to avoid deadlocks.
1519           (when (or (null articles)     ;All requests have been sent.
1520                     (= 1 (% count nntp-maximum-request)))
1521
1522             (nntp-accept-response)
1523             ;; On some Emacs versions the preceding function has a
1524             ;; tendency to change the buffer.  Perhaps.  It's quite
1525             ;; difficult to reproduce, because it only seems to happen
1526             ;; once in a blue moon.
1527             (set-buffer process-buffer)
1528             (while (progn
1529                      (goto-char (or last-point (point-min)))
1530                      ;; Count replies.
1531                      (while (re-search-forward "^\\([0-9][0-9][0-9]\\) .*\n"
1532                                                nil t)
1533                        (incf received)
1534                        (setq status (match-string 1))
1535                        (if (string-match "^[45]" status)
1536                            (setq status 'error)
1537                          (setq status 'ok)))
1538                      (setq last-point (point))
1539                      (or (< received count)
1540                          (if (eq status 'error)
1541                              nil
1542                            ;; I haven't started reading the final response
1543                            (progn
1544                              (goto-char (point-max))
1545                              (forward-line -1)
1546                              (not (looking-at "^\\.\r?\n"))))))
1547               ;; I haven't read the end of the final response
1548               (nntp-accept-response)
1549               (set-buffer process-buffer))))
1550
1551         ;; Some nntp servers seem to have an extension to the XOVER
1552         ;; extension.  On these servers, requesting an article range
1553         ;; preceeding the active range does not return an error as
1554         ;; specified in the RFC.  What we instead get is the NOV entry
1555         ;; for the first available article.  Obviously, a client can
1556         ;; use that entry to avoid making unnecessary requests.  The
1557         ;; only problem is for a client that assumes that the response
1558         ;; will always be within the requested ranage.  For such a
1559         ;; client, we can get N copies of the same entry (one for each
1560         ;; XOVER command sent to the server).
1561
1562         (when (<= count 1)
1563           (goto-char (point-min))
1564           (when (re-search-forward "^[0-9][0-9][0-9] .*\n\\([0-9]+\\)" nil t)
1565             (let ((low-limit (string-to-int
1566                               (buffer-substring (match-beginning 1) 
1567                                                 (match-end 1)))))
1568               (while (and articles (<= (car articles) low-limit))
1569                 (setq articles (cdr articles))))))
1570         (set-buffer buf))
1571
1572       (when nntp-server-xover
1573         (when in-process-buffer-p
1574           (set-buffer buf)
1575           (goto-char (point-max))
1576           (insert-buffer-substring process-buffer)
1577           (set-buffer process-buffer)
1578           (erase-buffer)
1579           (set-buffer buf))
1580
1581         ;; We remove any "." lines and status lines.
1582         (goto-char (point-min))
1583         (while (search-forward "\r" nil t)
1584           (delete-char -1))
1585         (goto-char (point-min))
1586         (delete-matching-lines "^\\.$\\|^[1-5][0-9][0-9] ")
1587         t))))
1588
1589   nntp-server-xover)
1590
1591 (defun nntp-send-xover-command (beg end &optional wait-for-reply)
1592   "Send the XOVER command to the server."
1593   (let ((range (format "%d-%d" beg end))
1594         (nntp-inhibit-erase t))
1595     (if (stringp nntp-server-xover)
1596         ;; If `nntp-server-xover' is a string, then we just send this
1597         ;; command.
1598         (if wait-for-reply
1599             (nntp-send-command-nodelete
1600              "\r?\n\\.\r?\n" nntp-server-xover range)
1601           ;; We do not wait for the reply.
1602           (nntp-send-command-nodelete nil nntp-server-xover range))
1603       (let ((commands nntp-xover-commands))
1604         ;; `nntp-xover-commands' is a list of possible XOVER commands.
1605         ;; We try them all until we get at positive response.
1606         (while (and commands (eq nntp-server-xover 'try))
1607           (nntp-send-command-nodelete "\r?\n\\.\r?\n" (car commands) range)
1608           (save-excursion
1609             (set-buffer nntp-server-buffer)
1610             (goto-char (point-min))
1611             (and (looking-at "[23]")    ; No error message.
1612                  ;; We also have to look at the lines.  Some buggy
1613                  ;; servers give back simple lines with just the
1614                  ;; article number.  How... helpful.
1615                  (progn
1616                    (forward-line 1)
1617                    (looking-at "[0-9]+\t...")) ; More text after number.
1618                  (setq nntp-server-xover (car commands))))
1619           (setq commands (cdr commands)))
1620         ;; If none of the commands worked, we disable XOVER.
1621         (when (eq nntp-server-xover 'try)
1622           (nntp-erase-buffer nntp-server-buffer)
1623           (setq nntp-server-xover nil))
1624         nntp-server-xover))))
1625
1626 (defun nntp-find-group-and-number (&optional group)
1627   (save-excursion
1628     (save-restriction
1629       (set-buffer nntp-server-buffer)
1630       (narrow-to-region (goto-char (point-min))
1631                         (or (search-forward "\n\n" nil t) (point-max)))
1632       (goto-char (point-min))
1633       ;; We first find the number by looking at the status line.
1634       (let ((number (and (looking-at "2[0-9][0-9] +\\([0-9]+\\) ")
1635                          (string-to-int
1636                           (buffer-substring (match-beginning 1)
1637                                             (match-end 1)))))
1638             newsgroups xref)
1639         (and number (zerop number) (setq number nil))
1640         (if number
1641             ;; Then we find the group name.
1642             (setq group
1643                   (cond
1644                    ;; If there is only one group in the Newsgroups
1645                    ;; header, then it seems quite likely that this
1646                    ;; article comes from that group, I'd say.
1647                    ((and (setq newsgroups
1648                                (mail-fetch-field "newsgroups"))
1649                          (not (string-match "," newsgroups)))
1650                     newsgroups)
1651                    ;; If there is more than one group in the
1652                    ;; Newsgroups header, then the Xref header should
1653                    ;; be filled out.  We hazard a guess that the group
1654                    ;; that has this article number in the Xref header
1655                    ;; is the one we are looking for.  This might very
1656                    ;; well be wrong if this article happens to have
1657                    ;; the same number in several groups, but that's
1658                    ;; life.
1659                    ((and (setq xref (mail-fetch-field "xref"))
1660                          number
1661                          (string-match
1662                           (format "\\([^ :]+\\):%d" number) xref))
1663                     (match-string 1 xref))
1664                    (t "")))
1665           (cond
1666            ((and (setq xref (mail-fetch-field "xref"))
1667                  (string-match
1668                   (if group
1669                       (concat "\\(" (regexp-quote group) "\\):\\([0-9]+\\)")
1670                     "\\([^ :]+\\):\\([0-9]+\\)")
1671                   xref))
1672             (setq group (match-string 1 xref)
1673                   number (string-to-int (match-string 2 xref))))
1674            ((and (setq newsgroups
1675                        (mail-fetch-field "newsgroups"))
1676                  (not (string-match "," newsgroups)))
1677             (setq group newsgroups))
1678            (group)
1679            (t (setq group ""))))
1680         (when (string-match "\r" group)
1681           (setq group (substring group 0 (match-beginning 0))))
1682         (cons group number)))))
1683
1684 (defun nntp-wait-for-string (regexp)
1685   "Wait until string arrives in the buffer."
1686   (let ((buf (current-buffer))
1687         proc)
1688     (goto-char (point-min))
1689     (while (and (setq proc (get-buffer-process buf))
1690                 (memq (process-status proc) '(open run))
1691                 (not (re-search-forward regexp nil t)))
1692       (accept-process-output proc)
1693       (set-buffer buf)
1694       (goto-char (point-min)))))
1695
1696
1697 ;; ==========================================================================
1698 ;; Obsolete nntp-open-* connection methods -- drv
1699 ;; ==========================================================================
1700
1701 (defvoo nntp-open-telnet-envuser nil
1702   "*If non-nil, telnet session (client and server both) will support the ENVIRON option and not prompt for login name.")
1703
1704 (defvoo nntp-telnet-shell-prompt "bash\\|\$ *\r?$\\|> *\r?"
1705   "*Regular expression to match the shell prompt on the remote machine.")
1706
1707 (defvoo nntp-rlogin-program "rsh"
1708   "*Program used to log in on remote machines.
1709 The default is \"rsh\", but \"ssh\" is a popular alternative.")
1710
1711 (defvoo nntp-rlogin-parameters '("telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1712   "*Parameters to `nntp-open-rlogin'.
1713 That function may be used as `nntp-open-connection-function'.  In that
1714 case, this list will be used as the parameter list given to rsh.")
1715
1716 (defvoo nntp-rlogin-user-name nil
1717   "*User name on remote system when using the rlogin connect method.")
1718
1719 (defvoo nntp-telnet-parameters
1720     '("exec" "telnet" "-8" "${NNTPSERVER:=news}" "nntp")
1721   "*Parameters to `nntp-open-telnet'.
1722 That function may be used as `nntp-open-connection-function'.  In that
1723 case, this list will be executed as a command after logging in
1724 via telnet.")
1725
1726 (defvoo nntp-telnet-user-name nil
1727   "User name to log in via telnet with.")
1728
1729 (defvoo nntp-telnet-passwd nil
1730   "Password to use to log in via telnet with.")
1731
1732 (defun nntp-open-telnet (buffer)
1733   (save-excursion
1734     (set-buffer buffer)
1735     (erase-buffer)
1736     (let ((proc (apply
1737                  'start-process
1738                  "nntpd" buffer nntp-telnet-command nntp-telnet-switches))
1739           (case-fold-search t))
1740       (when (memq (process-status proc) '(open run))
1741         (nntp-wait-for-string "^r?telnet")
1742         (process-send-string proc "set escape \^X\n")
1743         (cond
1744          ((and nntp-open-telnet-envuser nntp-telnet-user-name)
1745           (process-send-string proc (concat "open " "-l" nntp-telnet-user-name
1746                                             nntp-address "\n")))
1747          (t
1748           (process-send-string proc (concat "open " nntp-address "\n"))))
1749         (cond
1750          ((not nntp-open-telnet-envuser)
1751           (nntp-wait-for-string "^\r*.?login:")
1752           (process-send-string
1753            proc (concat
1754                  (or nntp-telnet-user-name
1755                      (setq nntp-telnet-user-name (read-string "login: ")))
1756                  "\n"))))
1757         (nntp-wait-for-string "^\r*.?password:")
1758         (process-send-string
1759          proc (concat
1760                (or nntp-telnet-passwd
1761                    (setq nntp-telnet-passwd
1762                          (read-passwd "Password: ")))
1763                "\n"))
1764         (nntp-wait-for-string nntp-telnet-shell-prompt)
1765         (process-send-string
1766          proc (concat (mapconcat 'identity nntp-telnet-parameters " ") "\n"))
1767         (nntp-wait-for-string "^\r*20[01]")
1768         (beginning-of-line)
1769         (delete-region (point-min) (point))
1770         (process-send-string proc "\^]")
1771         (nntp-wait-for-string "^r?telnet")
1772         (process-send-string proc "mode character\n")
1773         (accept-process-output proc 1)
1774         (sit-for 1)
1775         (goto-char (point-min))
1776         (forward-line 1)
1777         (delete-region (point) (point-max)))
1778       proc)))
1779
1780 (defun nntp-open-rlogin (buffer)
1781   "Open a connection to SERVER using rsh."
1782   (let ((proc (if nntp-rlogin-user-name
1783                   (apply 'start-process
1784                          "nntpd" buffer nntp-rlogin-program
1785                          nntp-address "-l" nntp-rlogin-user-name
1786                          nntp-rlogin-parameters)
1787                 (apply 'start-process
1788                        "nntpd" buffer nntp-rlogin-program nntp-address
1789                        nntp-rlogin-parameters))))
1790     (save-excursion
1791       (set-buffer buffer)
1792       (nntp-wait-for-string "^\r*20[01]")
1793       (beginning-of-line)
1794       (delete-region (point-min) (point))
1795       proc)))
1796
1797
1798 ;; ==========================================================================
1799 ;; Replacements for the nntp-open-* functions -- drv
1800 ;; ==========================================================================
1801
1802 (defun nntp-open-telnet-stream (buffer)
1803   "Open a nntp connection by telnet'ing the news server.
1804
1805 Please refer to the following variables to customize the connection:
1806 - `nntp-pre-command',
1807 - `nntp-telnet-command',
1808 - `nntp-telnet-switches',
1809 - `nntp-address',
1810 - `nntp-port-number',
1811 - `nntp-end-of-line'."
1812   (let ((command `(,nntp-telnet-command
1813                    ,@nntp-telnet-switches
1814                    ,nntp-address ,nntp-port-number))
1815         proc)
1816     (and nntp-pre-command
1817          (push nntp-pre-command command))
1818     (setq proc (apply 'start-process "nntpd" buffer command))
1819     (save-excursion
1820       (set-buffer buffer)
1821       (nntp-wait-for-string "^\r*20[01]")
1822       (beginning-of-line)
1823       (delete-region (point-min) (point))
1824       proc)))
1825
1826 (defun nntp-open-via-rlogin-and-telnet (buffer)
1827   "Open a connection to an nntp server through an intermediate host.
1828 First rlogin to the remote host, and then telnet the real news server
1829 from there.
1830
1831 Please refer to the following variables to customize the connection:
1832 - `nntp-pre-command',
1833 - `nntp-via-rlogin-command',
1834 - `nntp-via-rlogin-command-switches',
1835 - `nntp-via-user-name',
1836 - `nntp-via-address',
1837 - `nntp-telnet-command',
1838 - `nntp-telnet-switches',
1839 - `nntp-address',
1840 - `nntp-port-number',
1841 - `nntp-end-of-line'."
1842   (let ((command `(,nntp-via-address
1843                    ,nntp-telnet-command
1844                    ,@nntp-telnet-switches))
1845         proc)
1846     (when nntp-via-user-name
1847       (setq command `("-l" ,nntp-via-user-name ,@command)))
1848     (when nntp-via-rlogin-command-switches
1849       (setq command (append nntp-via-rlogin-command-switches command)))
1850     (push nntp-via-rlogin-command command)
1851     (and nntp-pre-command
1852          (push nntp-pre-command command))
1853     (setq proc (apply 'start-process "nntpd" buffer command))
1854     (save-excursion
1855       (set-buffer buffer)
1856       (nntp-wait-for-string "^r?telnet")
1857       (process-send-string proc (concat "open " nntp-address
1858                                         " " nntp-port-number "\n"))
1859       (nntp-wait-for-string "^\r*20[01]")
1860       (beginning-of-line)
1861       (delete-region (point-min) (point))
1862       (process-send-string proc "\^]")
1863       (nntp-wait-for-string "^r?telnet")
1864       (process-send-string proc "mode character\n")
1865       (accept-process-output proc 1)
1866       (sit-for 1)
1867       (goto-char (point-min))
1868       (forward-line 1)
1869       (delete-region (point) (point-max)))
1870     proc))
1871
1872 (defun nntp-open-via-rlogin-and-netcat (buffer)
1873   "Open a connection to an nntp server through an intermediate host.
1874 First rlogin to the remote host, and then connect to the real news
1875 server from there using the netcat command.
1876
1877 Please refer to the following variables to customize the connection:
1878 - `nntp-pre-command',
1879 - `nntp-via-rlogin-command',
1880 - `nntp-via-rlogin-command-switches',
1881 - `nntp-via-user-name',
1882 - `nntp-via-address',
1883 - `nntp-via-netcat-command',
1884 - `nntp-via-netcat-switches',
1885 - `nntp-address',
1886 - `nntp-port-number',
1887 - `nntp-end-of-line'."
1888   (let ((command `(,@(when nntp-pre-command
1889                        (list nntp-pre-command))
1890                    ,nntp-via-rlogin-command
1891                    ,@(when nntp-via-rlogin-command-switches
1892                        nntp-via-rlogin-command-switches)
1893                    ,@(when nntp-via-user-name
1894                        (list "-l" nntp-via-user-name))
1895                    ,nntp-via-address
1896                    ,nntp-via-netcat-command
1897                    ,@nntp-via-netcat-switches
1898                    ,nntp-address
1899                    ,nntp-port-number)))
1900     (apply 'start-process "nntpd" buffer command)))
1901
1902 (defun nntp-open-via-telnet-and-telnet (buffer)
1903   "Open a connection to an nntp server through an intermediate host.
1904 First telnet the remote host, and then telnet the real news server
1905 from there.
1906
1907 Please refer to the following variables to customize the connection:
1908 - `nntp-pre-command',
1909 - `nntp-via-telnet-command',
1910 - `nntp-via-telnet-switches',
1911 - `nntp-via-address',
1912 - `nntp-via-envuser',
1913 - `nntp-via-user-name',
1914 - `nntp-via-user-password',
1915 - `nntp-via-shell-prompt',
1916 - `nntp-telnet-command',
1917 - `nntp-telnet-switches',
1918 - `nntp-address',
1919 - `nntp-port-number',
1920 - `nntp-end-of-line'."
1921   (save-excursion
1922     (set-buffer buffer)
1923     (erase-buffer)
1924     (let ((command `(,nntp-via-telnet-command ,@nntp-via-telnet-switches))
1925           (case-fold-search t)
1926           proc)
1927       (and nntp-pre-command (push nntp-pre-command command))
1928       (setq proc (apply 'start-process "nntpd" buffer command))
1929       (when (memq (process-status proc) '(open run))
1930         (nntp-wait-for-string "^r?telnet")
1931         (process-send-string proc "set escape \^X\n")
1932         (cond
1933          ((and nntp-via-envuser nntp-via-user-name)
1934           (process-send-string proc (concat "open " "-l" nntp-via-user-name
1935                                             nntp-via-address "\n")))
1936          (t
1937           (process-send-string proc (concat "open " nntp-via-address
1938                                             "\n"))))
1939         (when (not nntp-via-envuser)
1940           (nntp-wait-for-string "^\r*.?login:")
1941           (process-send-string proc
1942                                (concat
1943                                 (or nntp-via-user-name
1944                                     (setq nntp-via-user-name
1945                                           (read-string "login: ")))
1946                                 "\n")))
1947         (nntp-wait-for-string "^\r*.?password:")
1948         (process-send-string proc
1949                              (concat
1950                               (or nntp-via-user-password
1951                                   (setq nntp-via-user-password
1952                                         (read-passwd "Password: ")))
1953                               "\n"))
1954         (nntp-wait-for-string nntp-via-shell-prompt)
1955         (let ((real-telnet-command `("exec"
1956                                      ,nntp-telnet-command
1957                                      ,@nntp-telnet-switches
1958                                      ,nntp-address
1959                                      ,nntp-port-number)))
1960           (process-send-string proc
1961                                (concat (mapconcat 'identity
1962                                                   real-telnet-command " ")
1963                                        "\n")))
1964         (nntp-wait-for-string "^\r*20[01]")
1965         (beginning-of-line)
1966         (delete-region (point-min) (point))
1967         (process-send-string proc "\^]")
1968         (nntp-wait-for-string "^r?telnet")
1969         (process-send-string proc "mode character\n")
1970         (accept-process-output proc 1)
1971         (sit-for 1)
1972         (goto-char (point-min))
1973         (forward-line 1)
1974         (delete-region (point) (point-max)))
1975       proc)))
1976
1977 ;; Marks handling
1978
1979 (defun nntp-marks-directory (server)
1980   (expand-file-name server nntp-marks-directory))
1981
1982 (defun nntp-possibly-create-directory (group server)
1983   (let ((dir (nnmail-group-pathname
1984               group (nntp-marks-directory server))))
1985     (unless (file-exists-p dir)
1986       (make-directory (directory-file-name dir) t)
1987       (nnheader-message 5 "Creating nntp marks directory %s" dir))))
1988
1989 (eval-and-compile
1990   (autoload 'time-less-p "time-date"))
1991
1992 (defun nntp-marks-changed-p (group server)
1993   (let ((file (expand-file-name
1994                nntp-marks-file-name
1995                (nnmail-group-pathname
1996                 group (nntp-marks-directory server)))))
1997     (if (null (gnus-gethash file nntp-marks-modtime))
1998         t ;; never looked at marks file, assume it has changed
1999       (time-less-p (gnus-gethash file nntp-marks-modtime)
2000                    (nth 5 (file-attributes file))))))
2001
2002 (defun nntp-save-marks (group server)
2003   (let ((file-name-coding-system nnmail-pathname-coding-system)
2004         (file (expand-file-name
2005                nntp-marks-file-name 
2006                (nnmail-group-pathname
2007                 group (nntp-marks-directory server)))))
2008     (condition-case err
2009         (progn
2010           (nntp-possibly-create-directory group server)
2011           (with-temp-file file
2012             (erase-buffer)
2013             (gnus-prin1 nntp-marks)
2014             (insert "\n"))
2015           (gnus-sethash file
2016                         (nth 5 (file-attributes file))
2017                         nntp-marks-modtime))
2018       (error (or (gnus-yes-or-no-p
2019                   (format "Could not write to %s (%s).  Continue? " file err))
2020                  (error "Cannot write to %s (%s)" file err))))))
2021
2022 (defun nntp-open-marks (group server)
2023   (let ((file (expand-file-name
2024                nntp-marks-file-name
2025                (nnmail-group-pathname
2026                 group (nntp-marks-directory server)))))
2027     (if (file-exists-p file)
2028         (condition-case err
2029             (with-temp-buffer
2030               (gnus-sethash file (nth 5 (file-attributes file))
2031                             nntp-marks-modtime)
2032               (nnheader-insert-file-contents file)
2033               (setq nntp-marks (read (current-buffer)))
2034               (dolist (el gnus-article-unpropagated-mark-lists)
2035                 (setq nntp-marks (gnus-remassoc el nntp-marks))))
2036           (error (or (gnus-yes-or-no-p
2037                       (format "Error reading nntp marks file %s (%s).  Continuing will use marks from .newsrc.eld.  Continue? " file err))
2038                      (error "Cannot read nntp marks file %s (%s)" file err))))
2039       ;; User didn't have a .marks file.  Probably first time
2040       ;; user of the .marks stuff.  Bootstrap it from .newsrc.eld.
2041       (let ((info (gnus-get-info
2042                    (gnus-group-prefixed-name
2043                     group
2044                     (gnus-server-to-method (format "nntp:%s" server))))))
2045         (nnheader-message 7 "Bootstrapping marks for %s..." group)
2046         (setq nntp-marks (gnus-info-marks info))
2047         (push (cons 'read (gnus-info-read info)) nntp-marks)
2048         (dolist (el gnus-article-unpropagated-mark-lists)
2049           (setq nntp-marks (gnus-remassoc el nntp-marks)))
2050         (nntp-save-marks group server)
2051         (nnheader-message 7 "Bootstrapping marks for %s...done" group)))))
2052
2053 (provide 'nntp)
2054
2055 ;;; arch-tag: 8655466a-b1b5-4929-9c45-7b1b2e767271
2056 ;;; nntp.el ends here