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