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