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