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