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