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