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