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