Replace "explicite" with "explicit" globally
[bpt/emacs.git] / lisp / net / tramp.el
CommitLineData
b1a2b924 1;;; tramp.el --- Transparent Remote Access, Multiple Protocol
fb7933a3 2
73b0cd50 3;; Copyright (C) 1998-2011 Free Software Foundation, Inc.
fb7933a3 4
cdd44874 5;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
d2a2c17f 6;; Michael Albinus <michael.albinus@gmx.de>
fb7933a3 7;; Keywords: comm, processes
0f34aa77 8;; Package: tramp
fb7933a3
KG
9
10;; This file is part of GNU Emacs.
11
874a927a 12;; GNU Emacs is free software: you can redistribute it and/or modify
fb7933a3 13;; it under the terms of the GNU General Public License as published by
874a927a
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
fb7933a3
KG
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
874a927a 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
fb7933a3
KG
24
25;;; Commentary:
26
27;; This package provides remote file editing, similar to ange-ftp.
28;; The difference is that ange-ftp uses FTP to transfer files between
29;; the local and the remote host, whereas tramp.el uses a combination
30;; of rsh and rcp or other work-alike programs, such as ssh/scp.
31;;
b1a2b924 32;; For more detailed instructions, please see the info file.
fb7933a3
KG
33;;
34;; Notes:
35;; -----
bf247b6e 36;;
b533bc97 37;; This package only works for Emacs 22.1 and higher, and for XEmacs 21.4
00d6fd04 38;; and higher. For XEmacs 21, you need the package `fsf-compat' for
7f4d4a97 39;; the `with-timeout' macro.
fb7933a3 40;;
fb7933a3
KG
41;; Also see the todo list at the bottom of this file.
42;;
b1a2b924 43;; The current version of Tramp can be retrieved from the following URL:
340b8d4f 44;; http://ftp.gnu.org/gnu/tramp/
fb7933a3
KG
45;;
46;; There's a mailing list for this, as well. Its name is:
340b8d4f
MA
47;; tramp-devel@gnu.org
48;; You can use the Web to subscribe, under the following URL:
49;; http://lists.gnu.org/mailman/listinfo/tramp-devel
fb7933a3
KG
50;;
51;; For the adventurous, the current development sources are available
52;; via CVS. You can find instructions about this at the following URL:
c62c9d08 53;; http://savannah.gnu.org/projects/tramp/
fb7933a3
KG
54;; Click on "CVS" in the navigation bar near the top.
55;;
56;; Don't forget to put on your asbestos longjohns, first!
57
58;;; Code:
59
9e6ab520 60(require 'tramp-compat)
fb7933a3 61
fb7933a3
KG
62;;; User Customizable Internal Variables:
63
64(defgroup tramp nil
65 "Edit remote files with a combination of rsh and rcp or similar programs."
589d30dd 66 :group 'files
26f4b8ab 67 :group 'comm
bf247b6e 68 :version "22.1")
fb7933a3 69
2e271195
MA
70;; Maybe we need once a real Tramp mode, with key bindings etc.
71;;;###autoload
72(defcustom tramp-mode t
73 "*Whether Tramp is enabled.
74If it is set to nil, all remote file names are used literally."
75 :group 'tramp
76 :type 'boolean)
77
00d6fd04 78(defcustom tramp-verbose 3
263c02ef 79 "*Verbosity level for Tramp messages.
00d6fd04
MA
80Any level x includes messages for all levels 1 .. x-1. The levels are
81
82 0 silent (no tramp messages at all)
83 1 errors
84 2 warnings
85 3 connection to remote hosts (default level)
86 4 activities
87 5 internal
88 6 sent and received strings
89 7 file caching
90 8 connection properties
8fbcce2d 91 9 test commands
00d6fd04 9210 traces (huge)."
fb7933a3
KG
93 :group 'tramp
94 :type 'integer)
95
263c02ef 96;; Emacs case.
38c65fca
KG
97(eval-and-compile
98 (when (boundp 'backup-directory-alist)
99 (defcustom tramp-backup-directory-alist nil
100 "Alist of filename patterns and backup directory names.
101Each element looks like (REGEXP . DIRECTORY), with the same meaning like
102in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
103is a local file name, the backup directory is prepended with Tramp file
00d6fd04 104name prefix \(method, user, host\) of file.
38c65fca
KG
105
106\(setq tramp-backup-directory-alist backup-directory-alist\)
107
108gives the same backup policy for Tramp files on their hosts like the
109policy for local files."
110 :group 'tramp
111 :type '(repeat (cons (regexp :tag "Regexp matching filename")
112 (directory :tag "Backup directory name"))))))
113
114;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
115;; the package "backup-dir" might not be loaded yet.
116(eval-and-compile
117 (when (featurep 'xemacs)
118 (defcustom tramp-bkup-backup-directory-info nil
119 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
120It has the same meaning like `bkup-backup-directory-info' from package
121`backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
122file name, the backup directory is prepended with Tramp file name prefix
00d6fd04 123\(method, user, host\) of file.
38c65fca
KG
124
125\(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
126
127gives the same backup policy for Tramp files on their hosts like the
128policy for local files."
bf247b6e 129 :type '(repeat
38c65fca
KG
130 (list (regexp :tag "File regexp")
131 (string :tag "Backup Dir")
132 (set :inline t
133 (const ok-create)
134 (const full-path)
135 (const prepend-name)
136 (const search-upward))))
137 :group 'tramp)))
138
fb7933a3
KG
139(defcustom tramp-auto-save-directory nil
140 "*Put auto-save files in this directory, if set.
141The idea is to use a local directory so that auto-saving is faster."
142 :group 'tramp
00d6fd04 143 :type '(choice (const nil) string))
fb7933a3 144
16674e4f
KG
145(defcustom tramp-encoding-shell
146 (if (memq system-type '(windows-nt))
147 (getenv "COMSPEC")
148 "/bin/sh")
149 "*Use this program for encoding and decoding commands on the local host.
150This shell is used to execute the encoding and decoding command on the
151local host, so if you want to use `~' in those commands, you should
152choose a shell here which groks tilde expansion. `/bin/sh' normally
153does not understand tilde expansion.
154
155For encoding and deocding, commands like the following are executed:
156
157 /bin/sh -c COMMAND < INPUT > OUTPUT
158
159This variable can be used to change the \"/bin/sh\" part. See the
00d6fd04 160variable `tramp-encoding-command-switch' for the \"-c\" part.
fb7933a3
KG
161
162Note that this variable is not used for remote commands. There are
163mechanisms in tramp.el which automatically determine the right shell to
164use for the remote host."
165 :group 'tramp
166 :type '(file :must-match t))
167
16674e4f
KG
168(defcustom tramp-encoding-command-switch
169 (if (string-match "cmd\\.exe" tramp-encoding-shell)
170 "/c"
171 "-c")
172 "*Use this switch together with `tramp-encoding-shell' for local commands.
173See the variable `tramp-encoding-shell' for more information."
174 :group 'tramp
175 :type 'string)
176
0f34aa77 177;;;###tramp-autoload
03c1ad43 178(defvar tramp-methods nil
fb7933a3
KG
179 "*Alist of methods for remote files.
180This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
181Each NAME stands for a remote access method. Each PARAM is a
182pair of the form (KEY VALUE). The following KEYs are defined:
fb7933a3
KG
183 * `tramp-remote-sh'
184 This specifies the Bourne shell to use on the remote host. This
185 MUST be a Bourne-like shell. It is normally not necessary to set
a4aeb9a4 186 this to any value other than \"/bin/sh\": Tramp wants to use a shell
fb7933a3
KG
187 which groks tilde expansion, but it can search for it. Also note
188 that \"/bin/sh\" exists on all Unixen, this might not be true for
189 the value that you decide to use. You Have Been Warned.
b25a52cc
KG
190 * `tramp-login-program'
191 This specifies the name of the program to use for logging in to the
00d6fd04
MA
192 remote host. This may be the name of rsh or a workalike program,
193 or the name of telnet or a workalike, or the name of su or a workalike.
b25a52cc 194 * `tramp-login-args'
fb7933a3 195 This specifies the list of arguments to pass to the above
00d6fd04 196 mentioned program. Please note that this is a list of list of arguments,
fb7933a3 197 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
00d6fd04
MA
198 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
199 There are some patterns: \"%h\" in this list is replaced by the host
200 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
201 port number, and \"%%\" can be used to obtain a literal percent character.
202 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
203 expansion (i.e. no host or no user specified), this list is not used as
204 argument. By this, arguments like (\"-l\" \"%u\") are optional.
205 \"%t\" is replaced by the temporary file name produced with
206 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
207 parameter of a program, if exists.
a7723e05
MA
208 * `tramp-async-args'
209 When an asynchronous process is started, we know already that
210 the connection works. Therefore, we can pass additional
211 parameters to suppress diagnostic messages, in order not to
212 tamper the process output.
b25a52cc
KG
213 * `tramp-copy-program'
214 This specifies the name of the program to use for remotely copying
215 the file; this might be the absolute filename of rcp or the name of
216 a workalike program.
217 * `tramp-copy-args'
fb7933a3 218 This specifies the list of parameters to pass to the above mentioned
b25a52cc 219 program, the hints for `tramp-login-args' also apply here.
00d6fd04
MA
220 * `tramp-copy-keep-date'
221 This specifies whether the copying program when the preserves the
222 timestamp of the original file.
b88f2d0a
MA
223 * `tramp-copy-keep-tmpfile'
224 This specifies whether a temporary local file shall be kept
225 for optimization reasons (useful for \"rsync\" methods).
226 * `tramp-copy-recursive'
227 Whether the operation copies directories recursively.
00d6fd04
MA
228 * `tramp-default-port'
229 The default port of a method is needed in case of gateway connections.
230 Additionally, it is used as indication which method is prepared for
231 passing gateways.
232 * `tramp-gw-args'
233 As the attribute name says, additional arguments are specified here
234 when a method is applied via a gateway.
90f8dc03
KG
235 * `tramp-password-end-of-line'
236 This specifies the string to use for terminating the line after
237 submitting the password. If this method parameter is nil, then the
238 value of the normal variable `tramp-default-password-end-of-line'
239 is used. This parameter is necessary because the \"plink\" program
240 requires any two characters after sending the password. These do
241 not have to be newline or carriage return characters. Other login
242 programs are happy with just one character, the newline character.
243 We use \"xy\" as the value for methods using \"plink\".
b25a52cc
KG
244
245What does all this mean? Well, you should specify `tramp-login-program'
246for all methods; this program is used to log in to the remote site. Then,
247there are two ways to actually transfer the files between the local and the
248remote side. One way is using an additional rcp-like program. If you want
249to do this, set `tramp-copy-program' in the method.
fb7933a3
KG
250
251Another possibility for file transfer is inline transfer, i.e. the
b25a52cc 252file is passed through the same buffer used by `tramp-login-program'. In
fb7933a3 253this case, the file contents need to be protected since the
b25a52cc 254`tramp-login-program' might use escape codes or the connection might not
fb7933a3 255be eight-bit clean. Therefore, file contents are encoded for transit.
00d6fd04
MA
256See the variables `tramp-local-coding-commands' and
257`tramp-remote-coding-commands' for details.
fb7933a3 258
16674e4f 259So, to summarize: if the method is an out-of-band method, then you
b25a52cc 260must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
00d6fd04
MA
261inline method, then these two parameters should be nil. Methods which
262are fit for gateways must have `tramp-default-port' at least.
fb7933a3
KG
263
264Notes:
265
00d6fd04
MA
266When using `su' or `sudo' the phrase `open connection to a remote
267host' sounds strange, but it is used nevertheless, for consistency.
268No connection is opened to a remote host, but `su' or `sudo' is
269started on the local host. You should specify a remote host
270`localhost' or the name of the local host. Another host name is
271useful only in combination with `tramp-default-proxies-alist'.")
fb7933a3 272
a92375d9
MA
273(defun tramp-detect-ssh-controlmaster ()
274 "Call ssh to detect whether it supports the ControlMaster argument.
275This function may return nil when the argument is supported, but
276shouldn't return t when it isn't."
277 (ignore-errors
278 (with-temp-buffer
279 (call-process "ssh" nil t nil "-o" "ControlMaster")
280 (goto-char (point-min))
281 (search-forward-regexp "Missing ControlMaster argument" nil t))))
282
b25a52cc 283(defcustom tramp-default-method
83e20b5c
MA
284 ;; An external copy method seems to be preferred, because it is much
285 ;; more performant for large files, and it hasn't too serious delays
286 ;; for small files. But it must be ensured that there aren't
287 ;; permanent password queries. Either a password agent like
263c02ef
MA
288 ;; "ssh-agent" or "Pageant" shall run, or the optional
289 ;; password-cache.el or auth-sources.el packages shall be active for
a92375d9
MA
290 ;; password caching. "scpc" is chosen if we detect that the user is
291 ;; running OpenSSH 4.0 or newer.
00d6fd04 292 (cond
362b9d48
GM
293 ;; PuTTY is installed. We don't take it, if it is installed on a
294 ;; non-windows system, or pscp from the pssh (parallel ssh) package
295 ;; is found.
296 ((and (eq system-type 'windows-nt)
297 (executable-find "pscp"))
00d6fd04 298 (if (or (fboundp 'password-read)
263c02ef 299 (fboundp 'auth-source-user-or-password)
00d6fd04 300 ;; Pageant is running.
70c11b0b 301 (tramp-compat-process-running-p "Pageant"))
00d6fd04
MA
302 "pscp"
303 "plink"))
304 ;; There is an ssh installation.
305 ((executable-find "scp")
a92375d9
MA
306 (cond
307 ((tramp-detect-ssh-controlmaster) "scpc")
308 ((or (fboundp 'password-read)
309 (fboundp 'auth-source-user-or-password)
310 ;; ssh-agent is running.
311 (getenv "SSH_AUTH_SOCK")
312 (getenv "SSH_AGENT_PID"))
313 "scp")
314 (t "ssh")))
00d6fd04
MA
315 ;; Fallback.
316 (t "ftp"))
fb7933a3 317 "*Default method to use for transferring files.
c62c9d08 318See `tramp-methods' for possibilities.
4007ba5b 319Also see `tramp-default-method-alist'."
c62c9d08
KG
320 :group 'tramp
321 :type 'string)
322
b191c9d9 323;;;###tramp-autoload
03c1ad43 324(defcustom tramp-default-method-alist nil
00d6fd04 325 "*Default method to use for specific host/user pairs.
c62c9d08
KG
326This is an alist of items (HOST USER METHOD). The first matching item
327specifies the method to use for a file name which does not specify a
328method. HOST and USER are regular expressions or nil, which is
329interpreted as a regular expression which always matches. If no entry
330matches, the variable `tramp-default-method' takes effect.
331
332If the file name does not specify the user, lookup is done using the
333empty string for the user name.
334
335See `tramp-methods' for a list of possibilities for METHOD."
336 :group 'tramp
e40fc745
MA
337 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
338 (choice :tag "User regexp" regexp sexp)
339 (choice :tag "Method name" string (const nil)))))
c62c9d08 340
03c1ad43 341(defcustom tramp-default-user nil
00d6fd04
MA
342 "*Default user to use for transferring files.
343It is nil by default; otherwise settings in configuration files like
344\"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
345
346This variable is regarded as obsolete, and will be removed soon."
347 :group 'tramp
348 :type '(choice (const nil) string))
349
b191c9d9 350;;;###tramp-autoload
03c1ad43 351(defcustom tramp-default-user-alist nil
00d6fd04
MA
352 "*Default user to use for specific method/host pairs.
353This is an alist of items (METHOD HOST USER). The first matching item
354specifies the user to use for a file name which does not specify a
355user. METHOD and USER are regular expressions or nil, which is
356interpreted as a regular expression which always matches. If no entry
357matches, the variable `tramp-default-user' takes effect.
358
359If the file name does not specify the method, lookup is done using the
360empty string for the method name."
361 :group 'tramp
e40fc745
MA
362 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
363 (choice :tag " Host regexp" regexp sexp)
364 (choice :tag " User name" string (const nil)))))
00d6fd04 365
03c1ad43 366(defcustom tramp-default-host (system-name)
00d6fd04
MA
367 "*Default host to use for transferring files.
368Useful for su and sudo methods mostly."
369 :group 'tramp
370 :type 'string)
371
372(defcustom tramp-default-proxies-alist nil
373 "*Route to be followed for specific host/user pairs.
374This is an alist of items (HOST USER PROXY). The first matching
375item specifies the proxy to be passed for a file name located on
376a remote target matching USER@HOST. HOST and USER are regular
70c11b0b
MA
377expressions. PROXY must be a Tramp filename without a localname
378part. Method and user name on PROXY are optional, which is
379interpreted with the default values. PROXY can contain the
380patterns %h and %u, which are replaced by the strings matching
381HOST or USER, respectively.
382
383HOST, USER or PROXY could also be Lisp forms, which will be
384evaluated. The result must be a string or nil, which is
385interpreted as a regular expression which always matches."
00d6fd04 386 :group 'tramp
70c11b0b
MA
387 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
388 (choice :tag "User regexp" regexp sexp)
e40fc745 389 (choice :tag " Proxy name" string (const nil)))))
00d6fd04 390
b191c9d9 391;;;###tramp-autoload
b96e6899
MA
392(defconst tramp-local-host-regexp
393 (concat
66feec8b
MA
394 "\\`"
395 (regexp-opt
396 (list "localhost" "localhost6" (system-name) "127\.0\.0\.1" "::1") t)
397 "\\'")
b96e6899
MA
398 "*Host names which are regarded as local host.")
399
5ec2cc41 400(defvar tramp-completion-function-alist nil
16674e4f 401 "*Alist of methods for remote files.
b533bc97 402This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
16674e4f 403Each NAME stands for a remote access method. Each PAIR is of the form
b533bc97 404\(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
16674e4f
KG
405names from FILE for completion. The following predefined FUNCTIONs exists:
406
5ec2cc41
KG
407 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
408 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
409 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
410 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
411 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
412 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
413 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
414 * `tramp-parse-netrc' for \"~/.netrc\" like files.
00d6fd04 415 * `tramp-parse-putty' for PuTTY registry keys.
5ec2cc41
KG
416
417FUNCTION can also be a customer defined function. For more details see
418the info pages.")
419
674da028
MA
420(defconst tramp-echo-mark-marker "_echo"
421 "String marker to surround echoed commands.")
422
68712eb6
MA
423(defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
424 "String length of `tramp-echo-mark-marker'.")
425
426(defconst tramp-echo-mark
427 (concat tramp-echo-mark-marker
428 (make-string tramp-echo-mark-marker-length ?\b))
00d6fd04
MA
429 "String mark to be transmitted around shell commands.
430Used to separate their echo from the output they produce. This
431will only be used if we cannot disable remote echo via stty.
432This string must have no effect on the remote shell except for
433producing some echo which can later be detected by
674da028
MA
434`tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
435followed by an equal number of backspaces to erase them will
436usually suffice.")
00d6fd04 437
68712eb6
MA
438(defconst tramp-echoed-echo-mark-regexp
439 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
440 tramp-echo-mark-marker tramp-echo-mark-marker-length)
00d6fd04
MA
441 "Regexp which matches `tramp-echo-mark' as it gets echoed by
442the remote shell.")
443
fb7933a3
KG
444(defcustom tramp-rsh-end-of-line "\n"
445 "*String used for end of line in rsh connections.
446I don't think this ever needs to be changed, so please tell me about it
16674e4f 447if you need to change this.
90f8dc03
KG
448Also see the method parameter `tramp-password-end-of-line' and the normal
449variable `tramp-default-password-end-of-line'."
16674e4f
KG
450 :group 'tramp
451 :type 'string)
452
90f8dc03
KG
453(defcustom tramp-default-password-end-of-line
454 tramp-rsh-end-of-line
16674e4f 455 "*String used for end of line after sending a password.
90f8dc03
KG
456This variable provides the default value for the method parameter
457`tramp-password-end-of-line', see `tramp-methods' for more details.
458
16674e4f
KG
459It seems that people using plink under Windows need to send
460\"\\r\\n\" (carriage-return, then newline) after a password, but just
461\"\\n\" after all other lines. This variable can be used for the
462password, see `tramp-rsh-end-of-line' for the other cases.
463
464The default value is to use the same value as `tramp-rsh-end-of-line'."
fb7933a3
KG
465 :group 'tramp
466 :type 'string)
467
fb7933a3 468(defcustom tramp-login-prompt-regexp
bc103d00 469 ".*ogin\\( .*\\)?: *"
fb7933a3 470 "*Regexp matching login-like prompts.
bc103d00
MA
471The regexp should match at end of buffer.
472
473Sometimes the prompt is reported to look like \"login as:\"."
fb7933a3
KG
474 :group 'tramp
475 :type 'regexp)
476
821e6e36 477(defcustom tramp-shell-prompt-pattern
aa485f7c 478 ;; Allow a prompt to start right after a ^M since it indeed would be
b81a0b56
MA
479 ;; displayed at the beginning of the line (and Zsh uses it). This
480 ;; regexp works only for GNU Emacs.
481 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
482 "[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
821e6e36
KG
483 "Regexp to match prompts from remote shell.
484Normally, Tramp expects you to configure `shell-prompt-pattern'
485correctly, but sometimes it happens that you are connecting to a
486remote host which sends a different kind of shell prompt. Therefore,
487Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
488and also things matched by this variable. The default value of this
b25a52cc 489variable is similar to the default value of `shell-prompt-pattern',
dab816a9
MA
490which should work well in many cases.
491
492This regexp must match both `tramp-initial-end-of-output' and
493`tramp-end-of-output'."
821e6e36
KG
494 :group 'tramp
495 :type 'regexp)
496
fb7933a3 497(defcustom tramp-password-prompt-regexp
00d6fd04 498 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
fb7933a3 499 "*Regexp matching password-like prompts.
ac474af1 500The regexp should match at end of buffer.
fb7933a3
KG
501
502The `sudo' program appears to insert a `^@' character into the prompt."
503 :group 'tramp
504 :type 'regexp)
505
506(defcustom tramp-wrong-passwd-regexp
b1d06e75
KG
507 (concat "^.*"
508 ;; These strings should be on the last line
a4aeb9a4 509 (regexp-opt '("Permission denied"
b1d06e75
KG
510 "Login incorrect"
511 "Login Incorrect"
512 "Connection refused"
27e813fe 513 "Connection closed"
7e5686f0 514 "Timeout, server not responding."
b1d06e75
KG
515 "Sorry, try again."
516 "Name or service not known"
00d6fd04 517 "Host key verification failed."
70c11b0b 518 "No supported authentication methods left to try!") t)
b1d06e75
KG
519 ".*"
520 "\\|"
521 "^.*\\("
522 ;; Here comes a list of regexes, separated by \\|
523 "Received signal [0-9]+"
524 "\\).*")
fb7933a3 525 "*Regexp matching a `login failed' message.
ac474af1
KG
526The regexp should match at end of buffer."
527 :group 'tramp
528 :type 'regexp)
529
530(defcustom tramp-yesno-prompt-regexp
3cdaec13
KG
531 (concat
532 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
533 "\\s-*")
534 "Regular expression matching all yes/no queries which need to be confirmed.
ac474af1 535The confirmation should be done with yes or no.
3cdaec13
KG
536The regexp should match at end of buffer.
537See also `tramp-yn-prompt-regexp'."
fb7933a3
KG
538 :group 'tramp
539 :type 'regexp)
540
3cdaec13 541(defcustom tramp-yn-prompt-regexp
658052a2
MA
542 (concat
543 (regexp-opt '("Store key in cache? (y/n)"
544 "Update cached key? (y/n, Return cancels connection)") t)
545 "\\s-*")
3cdaec13
KG
546 "Regular expression matching all y/n queries which need to be confirmed.
547The confirmation should be done with y or n.
548The regexp should match at end of buffer.
549See also `tramp-yesno-prompt-regexp'."
550 :group 'tramp
551 :type 'regexp)
487f4fb7
KG
552
553(defcustom tramp-terminal-prompt-regexp
554 (concat "\\("
555 "TERM = (.*)"
556 "\\|"
557 "Terminal type\\? \\[.*\\]"
558 "\\)\\s-*")
559 "Regular expression matching all terminal setting prompts.
560The regexp should match at end of buffer.
561The answer will be provided by `tramp-action-terminal', which see."
562 :group 'tramp
563 :type 'regexp)
3cdaec13 564
01917a18
MA
565(defcustom tramp-operation-not-permitted-regexp
566 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
567 (regexp-opt '("Operation not permitted") t))
568 "Regular expression matching keep-date problems in (s)cp operations.
569Copying has been performed successfully already, so this message can
570be ignored safely."
571 :group 'tramp
572 :type 'regexp)
573
6b2633cc
LH
574(defcustom tramp-copy-failed-regexp
575 (concat "\\(.+: "
576 (regexp-opt '("Permission denied"
577 "not a regular file"
578 "is a directory"
579 "No such file or directory") t)
580 "\\)\\s-*")
581 "Regular expression matching copy problems in (s)cp operations."
582 :group 'tramp
583 :type 'regexp)
584
19a87064 585(defcustom tramp-process-alive-regexp
38c65fca 586 ""
19a87064 587 "Regular expression indicating a process has finished.
38c65fca
KG
588In fact this expression is empty by intention, it will be used only to
589check regularly the status of the associated process.
07dfe738 590The answer will be provided by `tramp-action-process-alive',
00d6fd04 591`tramp-action-out-of-band', which see."
38c65fca
KG
592 :group 'tramp
593 :type 'regexp)
594
03c1ad43 595(defconst tramp-temp-name-prefix "tramp."
fb7933a3
KG
596 "*Prefix to use for temporary files.
597If this is a relative file name (such as \"tramp.\"), it is considered
598relative to the directory name returned by the function
9e6ab520 599`tramp-compat-temporary-file-directory' (which see). It may also be an
fb7933a3 600absolute file name; don't forget to include a prefix for the filename
03c1ad43 601part, though.")
fb7933a3 602
2296b54d
MA
603(defconst tramp-temp-buffer-name " *tramp temp*"
604 "Buffer name for a temporary buffer.
605It shall be used in combination with `generate-new-buffer-name'.")
606
b88f2d0a
MA
607(defvar tramp-temp-buffer-file-name nil
608 "File name of a persistent local temporary file.
609Useful for \"rsync\" like methods.")
610(make-variable-buffer-local 'tramp-temp-buffer-file-name)
d68b0220 611(put 'tramp-temp-buffer-file-name 'permanent-local t)
b88f2d0a 612
00d6fd04
MA
613;; XEmacs is distributed with few Lisp packages. Further packages are
614;; installed using EFS. If we use a unified filename format, then
615;; Tramp is required in addition to EFS. (But why can't Tramp just
616;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
617;; just like before.) Another reason for using a separate filename
618;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
619;; Tramp only knows how to deal with `file-name-handler-alist', not
620;; the other places.
621
622;; Currently, we have the choice between 'ftp, 'sep, and 'url.
623;;;###autoload
624(defcustom tramp-syntax
625 (if (featurep 'xemacs) 'sep 'ftp)
626 "Tramp filename syntax to be used.
627
628It can have the following values:
629
630 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
631 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
632 'url -- URL-like syntax."
16674e4f 633 :group 'tramp
00d6fd04
MA
634 :type (if (featurep 'xemacs)
635 '(choice (const :tag "EFS" ftp)
636 (const :tag "XEmacs" sep)
637 (const :tag "URL" url))
638 '(choice (const :tag "Ange-FTP" ftp)
639 (const :tag "URL" url))))
640
641(defconst tramp-prefix-format
642 (cond ((equal tramp-syntax 'ftp) "/")
643 ((equal tramp-syntax 'sep) "/[")
644 ((equal tramp-syntax 'url) "/")
645 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4 646 "*String matching the very beginning of Tramp file names.
00d6fd04 647Used in `tramp-make-tramp-file-name'.")
16674e4f 648
00d6fd04 649(defconst tramp-prefix-regexp
16674e4f 650 (concat "^" (regexp-quote tramp-prefix-format))
a4aeb9a4 651 "*Regexp matching the very beginning of Tramp file names.
00d6fd04 652Should always start with \"^\". Derived from `tramp-prefix-format'.")
16674e4f 653
00d6fd04 654(defconst tramp-method-regexp
16674e4f 655 "[a-zA-Z_0-9-]+"
00d6fd04 656 "*Regexp matching methods identifiers.")
16674e4f 657
00d6fd04
MA
658(defconst tramp-postfix-method-format
659 (cond ((equal tramp-syntax 'ftp) ":")
660 ((equal tramp-syntax 'sep) "/")
661 ((equal tramp-syntax 'url) "://")
662 (t (error "Wrong `tramp-syntax' defined")))
16674e4f 663 "*String matching delimeter between method and user or host names.
00d6fd04 664Used in `tramp-make-tramp-file-name'.")
16674e4f 665
00d6fd04
MA
666(defconst tramp-postfix-method-regexp
667 (regexp-quote tramp-postfix-method-format)
16674e4f 668 "*Regexp matching delimeter between method and user or host names.
00d6fd04 669Derived from `tramp-postfix-method-format'.")
16674e4f 670
03c1ad43 671(defconst tramp-user-regexp "[^:/ \t]+"
00d6fd04 672 "*Regexp matching user names.")
16674e4f 673
b191c9d9 674;;;###tramp-autoload
b96e6899
MA
675(defconst tramp-prefix-domain-format "%"
676 "*String matching delimeter between user and domain names.")
677
b191c9d9 678;;;###tramp-autoload
b96e6899
MA
679(defconst tramp-prefix-domain-regexp
680 (regexp-quote tramp-prefix-domain-format)
681 "*Regexp matching delimeter between user and domain names.
682Derived from `tramp-prefix-domain-format'.")
683
03c1ad43 684(defconst tramp-domain-regexp "[-a-zA-Z0-9_.]+"
b96e6899
MA
685 "*Regexp matching domain names.")
686
687(defconst tramp-user-with-domain-regexp
688 (concat "\\(" tramp-user-regexp "\\)"
689 tramp-prefix-domain-regexp
690 "\\(" tramp-domain-regexp "\\)")
691 "*Regexp matching user names with domain names.")
692
03c1ad43 693(defconst tramp-postfix-user-format "@"
16674e4f 694 "*String matching delimeter between user and host names.
00d6fd04 695Used in `tramp-make-tramp-file-name'.")
16674e4f 696
00d6fd04 697(defconst tramp-postfix-user-regexp
16674e4f
KG
698 (regexp-quote tramp-postfix-user-format)
699 "*Regexp matching delimeter between user and host names.
00d6fd04
MA
700Derived from `tramp-postfix-user-format'.")
701
03c1ad43 702(defconst tramp-host-regexp "[a-zA-Z0-9_.-]+"
00d6fd04
MA
703 "*Regexp matching host names.")
704
b96e6899
MA
705(defconst tramp-prefix-ipv6-format
706 (cond ((equal tramp-syntax 'ftp) "[")
707 ((equal tramp-syntax 'sep) "")
708 ((equal tramp-syntax 'url) "[")
709 (t (error "Wrong `tramp-syntax' defined")))
710 "*String matching left hand side of IPv6 addresses.
711Used in `tramp-make-tramp-file-name'.")
712
713(defconst tramp-prefix-ipv6-regexp
714 (regexp-quote tramp-prefix-ipv6-format)
715 "*Regexp matching left hand side of IPv6 addresses.
716Derived from `tramp-prefix-ipv6-format'.")
717
e0b6e3b9
MA
718;; The following regexp is a bit sloppy. But it shall serve our
719;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
720;; "::ffff:192.168.0.1".
b96e6899 721(defconst tramp-ipv6-regexp
e0b6e3b9 722 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
b96e6899
MA
723 "*Regexp matching IPv6 addresses.")
724
725(defconst tramp-postfix-ipv6-format
726 (cond ((equal tramp-syntax 'ftp) "]")
727 ((equal tramp-syntax 'sep) "")
728 ((equal tramp-syntax 'url) "]")
729 (t (error "Wrong `tramp-syntax' defined")))
730 "*String matching right hand side of IPv6 addresses.
731Used in `tramp-make-tramp-file-name'.")
732
733(defconst tramp-postfix-ipv6-regexp
734 (regexp-quote tramp-postfix-ipv6-format)
735 "*Regexp matching right hand side of IPv6 addresses.
736Derived from `tramp-postfix-ipv6-format'.")
737
00d6fd04
MA
738(defconst tramp-prefix-port-format
739 (cond ((equal tramp-syntax 'ftp) "#")
740 ((equal tramp-syntax 'sep) "#")
741 ((equal tramp-syntax 'url) ":")
742 (t (error "Wrong `tramp-syntax' defined")))
743 "*String matching delimeter between host names and port numbers.")
744
745(defconst tramp-prefix-port-regexp
746 (regexp-quote tramp-prefix-port-format)
747 "*Regexp matching delimeter between host names and port numbers.
748Derived from `tramp-prefix-port-format'.")
749
03c1ad43 750(defconst tramp-port-regexp "[0-9]+"
00d6fd04
MA
751 "*Regexp matching port numbers.")
752
753(defconst tramp-host-with-port-regexp
754 (concat "\\(" tramp-host-regexp "\\)"
755 tramp-prefix-port-regexp
756 "\\(" tramp-port-regexp "\\)")
757 "*Regexp matching host names with port numbers.")
758
759(defconst tramp-postfix-host-format
760 (cond ((equal tramp-syntax 'ftp) ":")
761 ((equal tramp-syntax 'sep) "]")
762 ((equal tramp-syntax 'url) "")
763 (t (error "Wrong `tramp-syntax' defined")))
7432277c 764 "*String matching delimeter between host names and localnames.
00d6fd04 765Used in `tramp-make-tramp-file-name'.")
16674e4f 766
00d6fd04 767(defconst tramp-postfix-host-regexp
16674e4f 768 (regexp-quote tramp-postfix-host-format)
7432277c 769 "*Regexp matching delimeter between host names and localnames.
00d6fd04 770Derived from `tramp-postfix-host-format'.")
16674e4f 771
03c1ad43 772(defconst tramp-localname-regexp ".*$"
00d6fd04 773 "*Regexp matching localnames.")
16674e4f 774
4a93e698 775;;; File name format:
505edaeb 776
00d6fd04 777(defconst tramp-file-name-structure
16674e4f
KG
778 (list
779 (concat
780 tramp-prefix-regexp
00d6fd04
MA
781 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
782 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
b96e6899
MA
783 "\\(" "\\(" tramp-host-regexp
784 "\\|"
785 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
786 tramp-postfix-ipv6-regexp "\\)"
787 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
00d6fd04
MA
788 tramp-postfix-host-regexp
789 "\\(" tramp-localname-regexp "\\)")
b96e6899 790 2 4 5 8)
16674e4f 791
fb7933a3 792 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
a4aeb9a4 793the Tramp file name structure.
fb7933a3 794
a4aeb9a4 795The first element REGEXP is a regular expression matching a Tramp file
fb7933a3
KG
796name. The regex should contain parentheses around the method name,
797the user name, the host name, and the file name parts.
798
799The second element METHOD is a number, saying which pair of
800parentheses matches the method name. The third element USER is
801similar, but for the user name. The fourth element HOST is similar,
802but for the host name. The fifth element FILE is for the file name.
803These numbers are passed directly to `match-string', which see. That
804means the opening parentheses are counted to identify the pair.
805
00d6fd04 806See also `tramp-file-name-regexp'.")
fb7933a3
KG
807
808;;;###autoload
505edaeb 809(defconst tramp-file-name-regexp-unified
1eb5ca1c
MA
810 (if (memq system-type '(cygwin windows-nt))
811 "\\`/\\([^[/:]\\{2,\\}\\|[^/]\\{2,\\}]\\):"
812 "\\`/\\([^[/:]+\\|[^/]+]\\):")
505edaeb
KG
813 "Value for `tramp-file-name-regexp' for unified remoting.
814Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1eb5ca1c
MA
815Tramp. See `tramp-file-name-structure' for more explanations.
816
817On W32 systems, the volume letter must be ignored.")
505edaeb
KG
818
819;;;###autoload
03c1ad43 820(defconst tramp-file-name-regexp-separate "\\`/\\[.*\\]"
505edaeb
KG
821 "Value for `tramp-file-name-regexp' for separate remoting.
822XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 823See `tramp-file-name-structure' for more explanations.")
505edaeb
KG
824
825;;;###autoload
03c1ad43 826(defconst tramp-file-name-regexp-url "\\`/[^/:]+://"
00d6fd04
MA
827 "Value for `tramp-file-name-regexp' for URL-like remoting.
828See `tramp-file-name-structure' for more explanations.")
829
830;;;###autoload
831(defconst tramp-file-name-regexp
832 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
833 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
834 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
835 (t (error "Wrong `tramp-syntax' defined")))
94be87e8 836 "*Regular expression matching file names handled by Tramp.
a4aeb9a4 837This regexp should match Tramp file names but no other file names.
b533bc97 838When tramp.el is loaded, this regular expression is prepended to
fb7933a3 839`file-name-handler-alist', and that is searched sequentially. Thus,
a4aeb9a4
MA
840if the Tramp entry appears rather early in the `file-name-handler-alist'
841and is a bit too general, then some files might be considered Tramp
00d6fd04 842files which are not really Tramp files.
fb7933a3
KG
843
844Please note that the entry in `file-name-handler-alist' is made when
b533bc97 845this file \(tramp.el\) is loaded. This means that this variable must be set
fb7933a3
KG
846before loading tramp.el. Alternatively, `file-name-handler-alist' can be
847updated after changing this variable.
848
00d6fd04 849Also see `tramp-file-name-structure'.")
fb7933a3 850
16674e4f 851;;;###autoload
8a798e41 852(defconst tramp-root-regexp
00d6fd04 853 (if (memq system-type '(cygwin windows-nt))
aa485f7c
MA
854 "\\`\\([a-zA-Z]:\\)?/"
855 "\\`/")
8a798e41 856 "Beginning of an incomplete Tramp file name.
aa485f7c 857Usually, it is just \"\\\\`/\". On W32 systems, there might be a
57671b72 858volume letter, which will be removed by `tramp-drop-volume-letter'.")
8a798e41
MA
859
860;;;###autoload
861(defconst tramp-completion-file-name-regexp-unified
1eb5ca1c
MA
862 (if (memq system-type '(cygwin windows-nt))
863 (concat tramp-root-regexp "[^/]\\{2,\\}\\'")
864 (concat tramp-root-regexp "[^/]*\\'"))
16674e4f 865 "Value for `tramp-completion-file-name-regexp' for unified remoting.
8a798e41 866GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1eb5ca1c
MA
867See `tramp-file-name-structure' for more explanations.
868
869On W32 systems, the volume letter must be ignored.")
fb7933a3 870
16674e4f
KG
871;;;###autoload
872(defconst tramp-completion-file-name-regexp-separate
aa485f7c 873 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
16674e4f
KG
874 "Value for `tramp-completion-file-name-regexp' for separate remoting.
875XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 876See `tramp-file-name-structure' for more explanations.")
fb7933a3 877
16674e4f 878;;;###autoload
00d6fd04 879(defconst tramp-completion-file-name-regexp-url
aa485f7c 880 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
00d6fd04
MA
881 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
882See `tramp-file-name-structure' for more explanations.")
883
884;;;###autoload
885(defconst tramp-completion-file-name-regexp
886 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
887 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
888 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
889 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4
MA
890 "*Regular expression matching file names handled by Tramp completion.
891This regexp should match partial Tramp file names only.
16674e4f
KG
892
893Please note that the entry in `file-name-handler-alist' is made when
894this file (tramp.el) is loaded. This means that this variable must be set
895before loading tramp.el. Alternatively, `file-name-handler-alist' can be
896updated after changing this variable.
897
00d6fd04 898Also see `tramp-file-name-structure'.")
fb7933a3 899
00d6fd04 900;; Chunked sending kludge. We set this to 500 for black-listed constellations
7432277c 901;; known to have a bug in `process-send-string'; some ssh connections appear
7177e2a3
MA
902;; to drop bytes when data is sent too quickly. There is also a connection
903;; buffer local variable, which is computed depending on remote host properties
904;; when `tramp-chunksize' is zero or nil.
7432277c
KG
905(defcustom tramp-chunksize
906 (when (and (not (featurep 'xemacs))
907 (memq system-type '(hpux)))
908 500)
55880756
MA
909;; Parentheses in docstring starting at beginning of line are escaped.
910;; Fontification is messed up when
911;; `open-paren-in-column-0-is-defun-start' set to t.
7432277c
KG
912 "*If non-nil, chunksize for sending input to local process.
913It is necessary only on systems which have a buggy `process-send-string'
914implementation. The necessity, whether this variable must be set, can be
915checked via the following code:
916
917 (with-temp-buffer
11948172
MA
918 (let* ((user \"xxx\") (host \"yyy\")
919 (init 0) (step 50)
920 (sent init) (received init))
921 (while (= sent received)
922 (setq sent (+ sent step))
923 (erase-buffer)
924 (let ((proc (start-process (buffer-name) (current-buffer)
925 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
926 (when (memq (process-status proc) '(run open))
927 (process-send-string proc (make-string sent ?\\ ))
928 (process-send-eof proc)
929 (process-send-eof proc))
930 (while (not (progn (goto-char (point-min))
931 (re-search-forward \"\\\\w+\" (point-max) t)))
932 (accept-process-output proc 1))
933 (when (memq (process-status proc) '(run open))
934 (setq received (string-to-number (match-string 0)))
935 (delete-process proc)
936 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
937 (sit-for 0))))
938 (if (> sent (+ init step))
939 (message \"You should set `tramp-chunksize' to a maximum of %s\"
940 (- sent step))
941 (message \"Test does not work\")
942 (display-buffer (current-buffer))
943 (sit-for 30))))
944
945In the Emacs normally running Tramp, evaluate the above code
55880756 946\(replace \"xxx\" and \"yyy\" by the remote user and host name,
b533bc97 947respectively\). You can do this, for example, by pasting it into
11948172
MA
948the `*scratch*' buffer and then hitting C-j with the cursor after the
949last closing parenthesis. Note that it works only if you have configured
b533bc97 950\"ssh\" to run without password query, see ssh-agent\(1\).
11948172
MA
951
952You will see the number of bytes sent successfully to the remote host.
953If that number exceeds 1000, you can stop the execution by hitting
954C-g, because your Emacs is likely clean.
955
11948172 956When it is necessary to set `tramp-chunksize', you might consider to
b533bc97
MA
957use an out-of-the-band method \(like \"scp\"\) instead of an internal one
958\(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
11948172 959performance.
c951aecb 960
00d6fd04
MA
961If your Emacs is buggy, the code stops and gives you an indication
962about the value `tramp-chunksize' should be set. Maybe you could just
963experiment a bit, e.g. changing the values of `init' and `step'
964in the third line of the code.
965
7432277c
KG
966Please raise a bug report via \"M-x tramp-bug\" if your system needs
967this variable to be set as well."
968 :group 'tramp
b1a2b924 969 :type '(choice (const nil) integer))
7432277c 970
5ec2cc41
KG
971;; Logging in to a remote host normally requires obtaining a pty. But
972;; Emacs on MacOS X has process-connection-type set to nil by default,
973;; so on those systems Tramp doesn't obtain a pty. Here, we allow
974;; for an override of the system default.
975(defcustom tramp-process-connection-type t
976 "Overrides `process-connection-type' for connections from Tramp.
977Tramp binds process-connection-type to the value given here before
978opening a connection to a remote host."
979 :group 'tramp
980 :type '(choice (const nil) (const t) (const pty)))
981
b50dd0d2
MA
982(defcustom tramp-completion-reread-directory-timeout 10
983 "Defines seconds since last remote command before rereading a directory.
984A remote directory might have changed its contents. In order to
985make it visible during file name completion in the minibuffer,
986Tramp flushes its cache and rereads the directory contents when
987more than `tramp-completion-reread-directory-timeout' seconds
4bc3c53d
MA
988have been gone since last remote command execution. A value of `t'
989would require an immediate reread during filename completion, `nil'
b50dd0d2
MA
990means to use always cached values for the directory contents."
991 :group 'tramp
992 :type '(choice (const nil) integer))
993
fb7933a3
KG
994;;; Internal Variables:
995
fb7933a3 996(defvar tramp-current-method nil
00d6fd04 997 "Connection method for this *tramp* buffer.")
fb7933a3
KG
998
999(defvar tramp-current-user nil
00d6fd04 1000 "Remote login name for this *tramp* buffer.")
fb7933a3
KG
1001
1002(defvar tramp-current-host nil
00d6fd04
MA
1003 "Remote host for this *tramp* buffer.")
1004
a01b1e22 1005;;;###autoload
16674e4f 1006(defconst tramp-completion-file-name-handler-alist
a01b1e22 1007 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
41c8e348 1008 (file-name-completion . tramp-completion-handle-file-name-completion))
16674e4f 1009 "Alist of completion handler functions.
03c1ad43
MA
1010Used for file names matching `tramp-file-name-regexp'. Operations
1011not mentioned here will be handled by Tramp's file name handler
1012functions, or the normal Emacs functions.")
16674e4f 1013
4007ba5b 1014;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
0f34aa77 1015;;;###tramp-autoload
03c1ad43 1016(defvar tramp-foreign-file-name-handler-alist nil
4007ba5b
KG
1017 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1018If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1019calling HANDLER.")
1020
0664ff72 1021;;; Internal functions which must come first:
fb7933a3 1022
0f34aa77
MA
1023;; Conversion functions between external representation and
1024;; internal data structure. Convenience functions for internal
1025;; data structure.
1026
1027(defun tramp-file-name-p (vec)
1028 "Check, whether VEC is a Tramp object."
1029 (and (vectorp vec) (= 4 (length vec))))
1030
1031(defun tramp-file-name-method (vec)
1032 "Return method component of VEC."
1033 (and (tramp-file-name-p vec) (aref vec 0)))
1034
1035(defun tramp-file-name-user (vec)
1036 "Return user component of VEC."
1037 (and (tramp-file-name-p vec) (aref vec 1)))
1038
1039(defun tramp-file-name-host (vec)
1040 "Return host component of VEC."
1041 (and (tramp-file-name-p vec) (aref vec 2)))
1042
1043(defun tramp-file-name-localname (vec)
1044 "Return localname component of VEC."
1045 (and (tramp-file-name-p vec) (aref vec 3)))
1046
1047;; The user part of a Tramp file name vector can be of kind
1048;; "user%domain". Sometimes, we must extract these parts.
1049(defun tramp-file-name-real-user (vec)
1050 "Return the user name of VEC without domain."
1051 (save-match-data
1052 (let ((user (tramp-file-name-user vec)))
1053 (if (and (stringp user)
1054 (string-match tramp-user-with-domain-regexp user))
1055 (match-string 1 user)
1056 user))))
1057
1058(defun tramp-file-name-domain (vec)
1059 "Return the domain name of VEC."
1060 (save-match-data
1061 (let ((user (tramp-file-name-user vec)))
1062 (and (stringp user)
1063 (string-match tramp-user-with-domain-regexp user)
1064 (match-string 2 user)))))
1065
1066;; The host part of a Tramp file name vector can be of kind
1067;; "host#port". Sometimes, we must extract these parts.
1068(defun tramp-file-name-real-host (vec)
1069 "Return the host name of VEC without port."
1070 (save-match-data
1071 (let ((host (tramp-file-name-host vec)))
1072 (if (and (stringp host)
1073 (string-match tramp-host-with-port-regexp host))
1074 (match-string 1 host)
1075 host))))
1076
1077(defun tramp-file-name-port (vec)
1078 "Return the port number of VEC."
1079 (save-match-data
66feec8b
MA
1080 (let ((method (tramp-file-name-method vec))
1081 (host (tramp-file-name-host vec)))
1082 (or (and (stringp host)
1083 (string-match tramp-host-with-port-regexp host)
1084 (string-to-number (match-string 2 host)))
1085 (tramp-get-method-parameter method 'tramp-default-port)))))
0f34aa77
MA
1086
1087;;;###tramp-autoload
1088(defun tramp-tramp-file-p (name)
1089 "Return t if NAME is a string with Tramp file name syntax."
1090 (save-match-data
1091 (and (stringp name) (string-match tramp-file-name-regexp name))))
1092
1093(defun tramp-find-method (method user host)
1094 "Return the right method string to use.
1095This is METHOD, if non-nil. Otherwise, do a lookup in
1096`tramp-default-method-alist'."
1097 (or method
1098 (let ((choices tramp-default-method-alist)
1099 lmethod item)
1100 (while choices
1101 (setq item (pop choices))
1102 (when (and (string-match (or (nth 0 item) "") (or host ""))
1103 (string-match (or (nth 1 item) "") (or user "")))
1104 (setq lmethod (nth 2 item))
1105 (setq choices nil)))
1106 lmethod)
1107 tramp-default-method))
1108
1109(defun tramp-find-user (method user host)
1110 "Return the right user string to use.
1111This is USER, if non-nil. Otherwise, do a lookup in
1112`tramp-default-user-alist'."
1113 (or user
1114 (let ((choices tramp-default-user-alist)
1115 luser item)
1116 (while choices
1117 (setq item (pop choices))
1118 (when (and (string-match (or (nth 0 item) "") (or method ""))
1119 (string-match (or (nth 1 item) "") (or host "")))
1120 (setq luser (nth 2 item))
1121 (setq choices nil)))
1122 luser)
1123 tramp-default-user))
1124
1125(defun tramp-find-host (method user host)
1126 "Return the right host string to use.
1127This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
1128 (or (and (> (length host) 0) host)
1129 tramp-default-host))
1130
1131(defun tramp-dissect-file-name (name &optional nodefault)
1132 "Return a `tramp-file-name' structure.
1133The structure consists of remote method, remote user, remote host
1134and localname (file name on remote host). If NODEFAULT is
1135non-nil, the file name parts are not expanded to their default
1136values."
1137 (save-match-data
1138 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
1139 (unless match (error "Not a Tramp file name: %s" name))
1140 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
1141 (user (match-string (nth 2 tramp-file-name-structure) name))
1142 (host (match-string (nth 3 tramp-file-name-structure) name))
1143 (localname (match-string (nth 4 tramp-file-name-structure) name)))
0f34aa77
MA
1144 (when host
1145 (when (string-match tramp-prefix-ipv6-regexp host)
1146 (setq host (replace-match "" nil t host)))
1147 (when (string-match tramp-postfix-ipv6-regexp host)
1148 (setq host (replace-match "" nil t host))))
1149 (if nodefault
1150 (vector method user host localname)
1151 (vector
1152 (tramp-find-method method user host)
1153 (tramp-find-user method user host)
1154 (tramp-find-host method user host)
1155 localname))))))
1156
1157(defun tramp-buffer-name (vec)
1158 "A name for the connection buffer VEC."
1159 ;; We must use `tramp-file-name-real-host', because for gateway
1160 ;; methods the default port will be expanded later on, which would
1161 ;; tamper the name.
1162 (let ((method (tramp-file-name-method vec))
1163 (user (tramp-file-name-user vec))
1164 (host (tramp-file-name-real-host vec)))
1165 (if (not (zerop (length user)))
1166 (format "*tramp/%s %s@%s*" method user host)
1167 (format "*tramp/%s %s*" method host))))
1168
1169(defun tramp-make-tramp-file-name (method user host localname)
1170 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
1171 (concat tramp-prefix-format
1172 (when (not (zerop (length method)))
1173 (concat method tramp-postfix-method-format))
1174 (when (not (zerop (length user)))
1175 (concat user tramp-postfix-user-format))
1176 (when host
1177 (if (string-match tramp-ipv6-regexp host)
1178 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1179 host))
1180 tramp-postfix-host-format
1181 (when localname localname)))
1182
1183(defun tramp-completion-make-tramp-file-name (method user host localname)
1184 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1185It must not be a complete Tramp file name, but as long as there are
1186necessary only. This function will be used in file name completion."
1187 (concat tramp-prefix-format
1188 (when (not (zerop (length method)))
1189 (concat method tramp-postfix-method-format))
1190 (when (not (zerop (length user)))
1191 (concat user tramp-postfix-user-format))
1192 (when (not (zerop (length host)))
1193 (concat
1194 (if (string-match tramp-ipv6-regexp host)
03c1ad43
MA
1195 (concat
1196 tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
0f34aa77
MA
1197 host)
1198 tramp-postfix-host-format))
1199 (when localname localname)))
1200
1201(defun tramp-get-buffer (vec)
1202 "Get the connection buffer to be used for VEC."
1203 (or (get-buffer (tramp-buffer-name vec))
1204 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
1205 (setq buffer-undo-list t)
1206 (setq default-directory
1207 (tramp-make-tramp-file-name
1208 (tramp-file-name-method vec)
1209 (tramp-file-name-user vec)
1210 (tramp-file-name-host vec)
1211 "/"))
1212 (current-buffer))))
1213
1214(defun tramp-get-connection-buffer (vec)
1215 "Get the connection buffer to be used for VEC.
1216In case a second asynchronous communication has been started, it is different
1217from `tramp-get-buffer'."
1218 (or (tramp-get-connection-property vec "process-buffer" nil)
1219 (tramp-get-buffer vec)))
1220
66feec8b
MA
1221(defun tramp-get-connection-name (vec)
1222 "Get the connection name to be used for VEC.
1223In case a second asynchronous communication has been started, it is different
1224from the default one."
1225 (or (tramp-get-connection-property vec "process-name" nil)
1226 (tramp-buffer-name vec)))
1227
0f34aa77
MA
1228(defun tramp-get-connection-process (vec)
1229 "Get the connection process to be used for VEC.
1230In case a second asynchronous communication has been started, it is different
1231from the default one."
66feec8b 1232 (get-process (tramp-get-connection-name vec)))
0f34aa77
MA
1233
1234(defun tramp-debug-buffer-name (vec)
1235 "A name for the debug buffer for VEC."
1236 ;; We must use `tramp-file-name-real-host', because for gateway
1237 ;; methods the default port will be expanded later on, which would
1238 ;; tamper the name.
1239 (let ((method (tramp-file-name-method vec))
1240 (user (tramp-file-name-user vec))
1241 (host (tramp-file-name-real-host vec)))
1242 (if (not (zerop (length user)))
1243 (format "*debug tramp/%s %s@%s*" method user host)
1244 (format "*debug tramp/%s %s*" method host))))
1245
1246(defconst tramp-debug-outline-regexp
03c1ad43
MA
1247 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #"
1248 "Used for highlighting Tramp debug buffers in `outline-mode'.")
1249
1250(defun tramp-debug-outline-level ()
1251 "Return the depth to which a statement is nested in the outline.
1252Point must be at the beginning of a header line.
1253
1254The outline level is equal to the verbosity of the Tramp message."
1255 (1+ (string-to-number (match-string 1))))
0f34aa77
MA
1256
1257(defun tramp-get-debug-buffer (vec)
1258 "Get the debug buffer for VEC."
1259 (with-current-buffer
1260 (get-buffer-create (tramp-debug-buffer-name vec))
1261 (when (bobp)
1262 (setq buffer-undo-list t)
1263 ;; Activate `outline-mode'. This runs `text-mode-hook' and
1264 ;; `outline-mode-hook'. We must prevent that local processes
1265 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
1266 ;; Furthermore, `outline-regexp' must have the correct value
1267 ;; already, because it is used by `font-lock-compile-keywords'.
1268 (let ((default-directory (tramp-compat-temporary-file-directory))
1269 (outline-regexp tramp-debug-outline-regexp))
1270 (outline-mode))
1271 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
03c1ad43 1272 (set (make-local-variable 'outline-level) 'tramp-debug-outline-level))
0f34aa77
MA
1273 (current-buffer)))
1274
00d6fd04
MA
1275(defsubst tramp-debug-message (vec fmt-string &rest args)
1276 "Append message to debug buffer.
1277Message is formatted with FMT-STRING as control string and the remaining
1278ARGS to actually emit the message (if applicable)."
1279 (when (get-buffer (tramp-buffer-name vec))
1280 (with-current-buffer (tramp-get-debug-buffer vec)
1281 (goto-char (point-max))
70c11b0b
MA
1282 ;; Headline.
1283 (when (bobp)
1284 (insert
1285 (format
1286 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1287 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1288 emacs-version tramp-version)))
00d6fd04
MA
1289 (unless (bolp)
1290 (insert "\n"))
70c11b0b 1291 ;; Timestamp.
736ac90f
MA
1292 (let ((now (current-time)))
1293 (insert (format-time-string "%T." now))
1294 (insert (format "%06d " (nth 2 now))))
56761182
MA
1295 ;; Calling Tramp function. We suppress compat and trace
1296 ;; functions from being displayed.
00d6fd04
MA
1297 (let ((btn 1) btf fn)
1298 (while (not fn)
1299 (setq btf (nth 1 (backtrace-frame btn)))
1300 (if (not btf)
1301 (setq fn "")
1302 (when (symbolp btf)
1303 (setq fn (symbol-name btf))
56761182
MA
1304 (unless
1305 (and
1306 (string-match "^tramp" fn)
1307 (not
1308 (string-match
1309 (concat
1310 "^"
1311 (regexp-opt
1312 '("tramp-compat-funcall"
1313 "tramp-compat-with-temp-message"
1314 "tramp-debug-message"
1315 "tramp-error"
1316 "tramp-error-with-buffer"
1317 "tramp-message")
1318 t)
1319 "$")
1320 fn)))
00d6fd04
MA
1321 (setq fn nil)))
1322 (setq btn (1+ btn))))
1323 ;; The following code inserts filename and line number.
1324 ;; Should be deactivated by default, because it is time
1325 ;; consuming.
1326; (let ((ffn (find-function-noselect (intern fn))))
1327; (insert
1328; (format
1329; "%s:%d: "
1330; (file-name-nondirectory (buffer-file-name (car ffn)))
1331; (with-current-buffer (car ffn)
1332; (1+ (count-lines (point-min) (cdr ffn)))))))
1333 (insert (format "%s " fn)))
70c11b0b 1334 ;; The message.
00d6fd04
MA
1335 (insert (apply 'format fmt-string args)))))
1336
946a5aeb
MA
1337(defvar tramp-message-show-message t
1338 "Show Tramp message in the minibuffer.
1339This variable is used to disable messages from `tramp-error'.
1340The messages are visible anyway, because an error is raised.")
1341
00d6fd04 1342(defsubst tramp-message (vec-or-proc level fmt-string &rest args)
fb7933a3 1343 "Emit a message depending on verbosity level.
a4aeb9a4 1344VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
00d6fd04
MA
1345vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1346less than LEVEL. The message is emitted only if `tramp-verbose' is
1347greater than or equal to LEVEL.
1348
1349The message is also logged into the debug buffer when `tramp-verbose'
1350is greater than or equal 4.
1351
1352Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1353control string and the remaining ARGS to actually emit the message (if
1354applicable)."
03c1ad43
MA
1355 (ignore-errors
1356 (when (<= level tramp-verbose)
1357 ;; Match data must be preserved!
1358 (save-match-data
1359 ;; Display only when there is a minimum level.
1360 (when (and tramp-message-show-message (<= level 3))
1361 (apply 'message
1362 (concat
1363 (cond
1364 ((= level 0) "")
1365 ((= level 1) "")
1366 ((= level 2) "Warning: ")
1367 (t "Tramp: "))
1368 fmt-string)
1369 args))
1370 ;; Log only when there is a minimum level.
1371 (when (>= tramp-verbose 4)
1372 (when (and vec-or-proc
1373 (processp vec-or-proc)
1374 (buffer-name (process-buffer vec-or-proc)))
1375 (with-current-buffer (process-buffer vec-or-proc)
1376 ;; Translate proc to vec.
1377 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
1378 (when (and vec-or-proc (vectorp vec-or-proc))
1379 (apply 'tramp-debug-message
1380 vec-or-proc
1381 (concat (format "(%d) # " level) fmt-string)
1382 args)))))))
00d6fd04
MA
1383
1384(defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
1385 "Emit an error.
1386VEC-OR-PROC identifies the connection to use, SIGNAL is the
1387signal identifier to be raised, remaining args passed to
1388`tramp-message'. Finally, signal SIGNAL is raised."
946a5aeb
MA
1389 (let (tramp-message-show-message)
1390 (tramp-message
1391 vec-or-proc 1 "%s"
1392 (error-message-string
1393 (list signal
1394 (get signal 'error-message)
1395 (apply 'format fmt-string args))))
1396 (signal signal (list (apply 'format fmt-string args)))))
00d6fd04
MA
1397
1398(defsubst tramp-error-with-buffer
1399 (buffer vec-or-proc signal fmt-string &rest args)
1400 "Emit an error, and show BUFFER.
1401If BUFFER is nil, show the connection buffer. Wait for 30\", or until
1402an input event arrives. The other arguments are passed to `tramp-error'."
1403 (save-window-excursion
1404 (unwind-protect
1405 (apply 'tramp-error vec-or-proc signal fmt-string args)
4874f5e6
MA
1406 (when (and vec-or-proc
1407 (not (zerop tramp-verbose))
1408 (not (tramp-completion-mode-p)))
00d6fd04
MA
1409 (let ((enable-recursive-minibuffers t))
1410 (pop-to-buffer
1411 (or (and (bufferp buffer) buffer)
1412 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1413 (tramp-get-buffer vec-or-proc)))
1414 (sit-for 30))))))
fb7933a3 1415
c62c9d08
KG
1416(defmacro with-parsed-tramp-file-name (filename var &rest body)
1417 "Parse a Tramp filename and make components available in the body.
1418
1419First arg FILENAME is evaluated and dissected into its components.
1420Second arg VAR is a symbol. It is used as a variable name to hold
1421the filename structure. It is also used as a prefix for the variables
1422holding the components. For example, if VAR is the symbol `foo', then
00d6fd04
MA
1423`foo' will be bound to the whole structure, `foo-method' will be bound to
1424the method component, and so on for `foo-user', `foo-host', `foo-localname'.
c62c9d08
KG
1425
1426Remaining args are Lisp expressions to be evaluated (inside an implicit
1427`progn').
1428
00d6fd04
MA
1429If VAR is nil, then we bind `v' to the structure and `method', `user',
1430`host', `localname' to the components."
c62c9d08 1431 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
c62c9d08
KG
1432 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
1433 (tramp-file-name-method ,(or var 'v)))
1434 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
1435 (tramp-file-name-user ,(or var 'v)))
1436 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
1437 (tramp-file-name-host ,(or var 'v)))
7432277c
KG
1438 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
1439 (tramp-file-name-localname ,(or var 'v))))
c62c9d08
KG
1440 ,@body))
1441
1442(put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
00d6fd04 1443(put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
6139f995
MA
1444(tramp-compat-font-lock-add-keywords
1445 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
00d6fd04 1446
9e021389
MA
1447(defun tramp-progress-reporter-update (reporter &optional value)
1448 (let* ((parameters (cdr reporter))
1449 (message (aref parameters 3)))
1450 (when (string-match message (or (current-message) ""))
6139f995 1451 (tramp-compat-funcall 'progress-reporter-update reporter value))))
9e021389 1452
a94d821f 1453(defmacro with-progress-reporter (vec level message &rest body)
b6827fff
MA
1454 "Executes BODY, spinning a progress reporter with MESSAGE.
1455If LEVEL does not fit for visible messages, or if this is a
1456nested call of the macro, there are only traces without a visible
1457progress reporter."
a94d821f
MA
1458 `(let (pr tm)
1459 (tramp-message ,vec ,level "%s..." ,message)
1460 ;; We start a pulsing progress reporter after 3 seconds. Feature
1461 ;; introduced in Emacs 24.1.
3b30ccda
MA
1462 (when (and tramp-message-show-message
1463 ;; Display only when there is a minimum level.
1464 (<= ,level (min tramp-verbose 3)))
03c1ad43
MA
1465 (ignore-errors
1466 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
1467 tm (when pr
1468 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))))
a94d821f 1469 (unwind-protect
b6827fff
MA
1470 ;; Execute the body. Unset `tramp-message-show-message' when
1471 ;; the timer object is created, in order to suppress
1472 ;; concurrent timers.
3b30ccda
MA
1473 (let ((tramp-message-show-message
1474 (and tramp-message-show-message (not tm))))
1475 ,@body)
a94d821f 1476 ;; Stop progress reporter.
0d5852cf 1477 (if tm (tramp-compat-funcall 'cancel-timer tm))
a94d821f
MA
1478 (tramp-message ,vec ,level "%s...done" ,message))))
1479
1480(put 'with-progress-reporter 'lisp-indent-function 3)
1481(put 'with-progress-reporter 'edebug-form-spec t)
6139f995
MA
1482(tramp-compat-font-lock-add-keywords
1483 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
a94d821f
MA
1484
1485(eval-and-compile ;; Silence compiler.
628c97b2
GM
1486 (if (memq system-type '(cygwin windows-nt))
1487 (defun tramp-drop-volume-letter (name)
1488 "Cut off unnecessary drive letter from file NAME.
66feec8b 1489The functions `tramp-*-handle-expand-file-name' call `expand-file-name'
628c97b2
GM
1490locally on a remote file name. When the local system is a W32 system
1491but the remote system is Unix, this introduces a superfluous drive
1492letter into the file name. This function removes it."
1493 (save-match-data
1494 (if (string-match tramp-root-regexp name)
1495 (replace-match "/" nil t name)
1496 name)))
1497
1498 (defalias 'tramp-drop-volume-letter 'identity)))
1499
16674e4f
KG
1500;;; Config Manipulation Functions:
1501
1502(defun tramp-set-completion-function (method function-list)
1503 "Sets the list of completion functions for METHOD.
1504FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
1505The FUNCTION is intended to parse FILE according its syntax.
1506It might be a predefined FUNCTION, or a user defined FUNCTION.
1507Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
8fc29035 1508`tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
8daea7fc
KG
1509and `tramp-parse-netrc'.
1510
16674e4f
KG
1511Example:
1512
1513 (tramp-set-completion-function
1514 \"ssh\"
8daea7fc
KG
1515 '((tramp-parse-sconfig \"/etc/ssh_config\")
1516 (tramp-parse-sconfig \"~/.ssh/config\")))"
16674e4f 1517
5ec2cc41
KG
1518 (let ((r function-list)
1519 (v function-list))
1520 (setq tramp-completion-function-alist
1521 (delete (assoc method tramp-completion-function-alist)
1522 tramp-completion-function-alist))
1523
1524 (while v
00d6fd04 1525 ;; Remove double entries.
5ec2cc41
KG
1526 (when (member (car v) (cdr v))
1527 (setcdr v (delete (car v) (cdr v))))
00d6fd04 1528 ;; Check for function and file or registry key.
5ec2cc41 1529 (unless (and (functionp (nth 0 (car v)))
00d6fd04
MA
1530 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
1531 ;; Windows registry.
1532 (and (memq system-type '(cygwin windows-nt))
a4aeb9a4 1533 (zerop
0f34aa77 1534 (tramp-compat-call-process
a4aeb9a4 1535 "reg" nil nil nil "query" (nth 1 (car v)))))
00d6fd04
MA
1536 ;; Configuration file.
1537 (file-exists-p (nth 1 (car v)))))
5ec2cc41
KG
1538 (setq r (delete (car v) r)))
1539 (setq v (cdr v)))
1540
1541 (when r
4007ba5b 1542 (add-to-list 'tramp-completion-function-alist
5ec2cc41 1543 (cons method r)))))
16674e4f
KG
1544
1545(defun tramp-get-completion-function (method)
00d6fd04 1546 "Returns a list of completion functions for METHOD.
16674e4f 1547For definition of that list see `tramp-set-completion-function'."
00d6fd04
MA
1548 (cons
1549 ;; Hosts visited once shall be remembered.
1550 `(tramp-parse-connection-properties ,method)
1551 ;; The method related defaults.
1552 (cdr (assoc method tramp-completion-function-alist))))
16674e4f 1553
d037d501 1554
0664ff72 1555;;; Fontification of `read-file-name':
d037d501 1556
0664ff72 1557;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
d037d501
MA
1558(defvar tramp-rfn-eshadow-overlay)
1559(make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
1560
1561(defun tramp-rfn-eshadow-setup-minibuffer ()
1562 "Set up a minibuffer for `file-name-shadow-mode'.
1563Adds another overlay hiding filename parts according to Tramp's
1564special handling of `substitute-in-file-name'."
9ce8462a 1565 (when (symbol-value 'minibuffer-completing-file-name)
d037d501 1566 (setq tramp-rfn-eshadow-overlay
0d5852cf
MA
1567 (tramp-compat-funcall
1568 'make-overlay
1569 (tramp-compat-funcall 'minibuffer-prompt-end)
1570 (tramp-compat-funcall 'minibuffer-prompt-end)))
d037d501 1571 ;; Copy rfn-eshadow-overlay properties.
0d5852cf
MA
1572 (let ((props (tramp-compat-funcall
1573 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
d037d501 1574 (while props
0d5852cf
MA
1575 (tramp-compat-funcall
1576 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
d037d501
MA
1577
1578(when (boundp 'rfn-eshadow-setup-minibuffer-hook)
1579 (add-hook 'rfn-eshadow-setup-minibuffer-hook
48846dc5
MA
1580 'tramp-rfn-eshadow-setup-minibuffer)
1581 (add-hook 'tramp-unload-hook
aa485f7c
MA
1582 (lambda ()
1583 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
1584 'tramp-rfn-eshadow-setup-minibuffer))))
d037d501 1585
adcbca53
MA
1586(defconst tramp-rfn-eshadow-update-overlay-regexp
1587 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
1588
d037d501
MA
1589(defun tramp-rfn-eshadow-update-overlay ()
1590 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
1591This is intended to be used as a minibuffer `post-command-hook' for
1592`file-name-shadow-mode'; the minibuffer should have already
1593been set up by `rfn-eshadow-setup-minibuffer'."
1594 ;; In remote files name, there is a shadowing just for the local part.
0d5852cf
MA
1595 (let ((end (or (tramp-compat-funcall
1596 'overlay-end (symbol-value 'rfn-eshadow-overlay))
1597 (tramp-compat-funcall 'minibuffer-prompt-end))))
1598 (when
1599 (file-remote-p
1600 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
bd316474
KY
1601 (save-excursion
1602 (save-restriction
1603 (narrow-to-region
adcbca53
MA
1604 (1+ (or (string-match
1605 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
1606 end))
1607 (point-max))
bd316474
KY
1608 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
1609 (rfn-eshadow-update-overlay-hook nil))
0d5852cf
MA
1610 (tramp-compat-funcall
1611 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
1612 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
d037d501
MA
1613
1614(when (boundp 'rfn-eshadow-update-overlay-hook)
1615 (add-hook 'rfn-eshadow-update-overlay-hook
b88f2d0a
MA
1616 'tramp-rfn-eshadow-update-overlay)
1617 (add-hook 'tramp-unload-hook
1618 (lambda ()
1619 (remove-hook 'rfn-eshadow-update-overlay-hook
1620 'tramp-rfn-eshadow-update-overlay))))
d037d501 1621
00d6fd04
MA
1622;; Inodes don't exist for some file systems. Therefore we must
1623;; generate virtual ones. Used in `find-buffer-visiting'. The method
1624;; applied might be not so efficient (Ange-FTP uses hashes). But
1625;; performance isn't the major issue given that file transfer will
1626;; take time.
1627(defvar tramp-inodes nil
1628 "Keeps virtual inodes numbers.")
1629
8daea7fc
KG
1630;; Devices must distinguish physical file systems. The device numbers
1631;; provided by "lstat" aren't unique, because we operate on different hosts.
1632;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
1633;; EFS use device number "-1". In order to be different, we use device number
b946a456 1634;; (-1 . x), whereby "x" is unique for a given (method user host).
8daea7fc
KG
1635(defvar tramp-devices nil
1636 "Keeps virtual device numbers.")
1637
b86c1cd8
MA
1638(defun tramp-default-file-modes (filename)
1639 "Return file modes of FILENAME as integer.
1640If the file modes of FILENAME cannot be determined, return the
974647ac
MA
1641value of `default-file-modes', without execute permissions."
1642 (or (file-modes filename)
0f34aa77 1643 (logand (default-file-modes) (tramp-compat-octal-to-decimal "0666"))))
b86c1cd8 1644
c23c3394
MA
1645(defun tramp-replace-environment-variables (filename)
1646 "Replace environment variables in FILENAME.
1647Return the string with the replaced variables."
2e271195 1648 (save-match-data
ec5145d6 1649 (let ((idx (string-match "$\\(\\w+\\)" filename)))
2e271195 1650 ;; `$' is coded as `$$'.
ec5145d6
MA
1651 (when (and idx
1652 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
1653 (getenv (match-string 1 filename)))
2e271195
MA
1654 (setq filename
1655 (replace-match
1656 (substitute-in-file-name (match-string 0 filename))
1657 t nil filename)))
1658 filename)))
c23c3394 1659
00d6fd04
MA
1660;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
1661;; which calls corresponding functions (see minibuf.el).
1662(when (fboundp 'minibuffer-electric-separator)
9e6ab520 1663 (mapc
aa485f7c
MA
1664 (lambda (x)
1665 (eval
1666 `(defadvice ,x
1667 (around ,(intern (format "tramp-advice-%s" x)) activate)
1668 "Invoke `substitute-in-file-name' for Tramp files."
1669 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
1670 (tramp-tramp-file-p (buffer-substring)))
1671 ;; We don't need to handle `last-input-event', because
1672 ;; due to the key map we know it must be ?/ or ?~.
1673 (let ((s (concat (buffer-substring (point-min) (point))
1674 (string last-command-char))))
1675 (delete-region (point-min) (point))
1676 (insert (substitute-in-file-name s))
1677 (setq ad-return-value last-command-char))
d7ec1df7
MA
1678 ad-do-it)))
1679 (eval
1680 `(add-hook
1681 'tramp-unload-hook
1682 (lambda ()
1683 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
1684 (ad-activate ',x)))))
00d6fd04
MA
1685
1686 '(minibuffer-electric-separator
1687 minibuffer-electric-tilde)))
1688
eb562962
MA
1689(defun tramp-find-file-name-coding-system-alist (filename tmpname)
1690 "Like `find-operation-coding-system' for Tramp filenames.
1691Tramp's `insert-file-contents' and `write-region' work over
1692temporary file names. If `file-coding-system-alist' contains an
1693expression, which matches more than the file name suffix, the
1694coding system might not be determined. This function repairs it."
1695 (let (result)
1696 (dolist (elt file-coding-system-alist result)
1697 (when (and (consp elt) (string-match (car elt) filename))
1698 ;; We found a matching entry in `file-coding-system-alist'.
1699 ;; So we add a similar entry, but with the temporary file name
1700 ;; as regexp.
1701 (add-to-list
1702 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
1703
a01b1e22
MA
1704;;;###autoload
1705(progn (defun tramp-run-real-handler (operation args)
fb7933a3 1706 "Invoke normal file name handler for OPERATION.
c62c9d08
KG
1707First arg specifies the OPERATION, second arg is a list of arguments to
1708pass to the OPERATION."
4007ba5b
KG
1709 (let* ((inhibit-file-name-handlers
1710 `(tramp-file-name-handler
946a5aeb 1711 tramp-vc-file-name-handler
4007ba5b
KG
1712 tramp-completion-file-name-handler
1713 cygwin-mount-name-hook-function
1714 cygwin-mount-map-drive-hook-function
1715 .
1716 ,(and (eq inhibit-file-name-operation operation)
1717 inhibit-file-name-handlers)))
1718 (inhibit-file-name-operation operation))
a01b1e22 1719 (apply operation args))))
16674e4f 1720
a01b1e22
MA
1721;;;###autoload
1722(progn (defun tramp-completion-run-real-handler (operation args)
16674e4f
KG
1723 "Invoke `tramp-file-name-handler' for OPERATION.
1724First arg specifies the OPERATION, second arg is a list of arguments to
1725pass to the OPERATION."
4007ba5b
KG
1726 (let* ((inhibit-file-name-handlers
1727 `(tramp-completion-file-name-handler
1728 cygwin-mount-name-hook-function
1729 cygwin-mount-map-drive-hook-function
1730 .
1731 ,(and (eq inhibit-file-name-operation operation)
1732 inhibit-file-name-handlers)))
1733 (inhibit-file-name-operation operation))
a01b1e22 1734 (apply operation args))))
fb7933a3 1735
4007ba5b
KG
1736;; We handle here all file primitives. Most of them have the file
1737;; name as first parameter; nevertheless we check for them explicitly
04bf5b65 1738;; in order to be signaled if a new primitive appears. This
4007ba5b
KG
1739;; scenario is needed because there isn't a way to decide by
1740;; syntactical means whether a foreign method must be called. It would
19a87064 1741;; ease the life if `file-name-handler-alist' would support a decision
4007ba5b
KG
1742;; function as well but regexp only.
1743(defun tramp-file-name-for-operation (operation &rest args)
1744 "Return file name related to OPERATION file primitive.
1745ARGS are the arguments OPERATION has been called with."
1746 (cond
b533bc97 1747 ;; FILE resp DIRECTORY.
4007ba5b
KG
1748 ((member operation
1749 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
1750 'delete-file 'diff-latest-backup-file 'directory-file-name
1751 'directory-files 'directory-files-and-attributes
1752 'dired-compress-file 'dired-uncache
1753 'file-accessible-directory-p 'file-attributes
1754 'file-directory-p 'file-executable-p 'file-exists-p
25f14cdb 1755 'file-local-copy 'file-remote-p 'file-modes
19a87064
MA
1756 'file-name-as-directory 'file-name-directory
1757 'file-name-nondirectory 'file-name-sans-versions
1758 'file-ownership-preserved-p 'file-readable-p
1759 'file-regular-p 'file-symlink-p 'file-truename
1760 'file-writable-p 'find-backup-file-name 'find-file-noselect
1761 'get-file-buffer 'insert-directory 'insert-file-contents
1762 'load 'make-directory 'make-directory-internal
1763 'set-file-modes 'substitute-in-file-name
1764 'unhandled-file-name-directory 'vc-registered
b533bc97 1765 ;; Emacs 22+ only.
ce3f516f 1766 'set-file-times
25f14cdb
MA
1767 ;; Emacs 24+ only.
1768 'file-selinux-context 'set-file-selinux-context
b533bc97 1769 ;; XEmacs only.
4007ba5b
KG
1770 'abbreviate-file-name 'create-file-buffer
1771 'dired-file-modtime 'dired-make-compressed-filename
1772 'dired-recursive-delete-directory 'dired-set-file-modtime
1773 'dired-shell-unhandle-file-name 'dired-uucode-file
5615d63f 1774 'insert-file-contents-literally 'make-temp-name 'recover-file
4007ba5b 1775 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
8daea7fc
KG
1776 (if (file-name-absolute-p (nth 0 args))
1777 (nth 0 args)
1778 (expand-file-name (nth 0 args))))
b533bc97 1779 ;; FILE DIRECTORY resp FILE1 FILE2.
4007ba5b
KG
1780 ((member operation
1781 (list 'add-name-to-file 'copy-file 'expand-file-name
1782 'file-name-all-completions 'file-name-completion
1783 'file-newer-than-file-p 'make-symbolic-link 'rename-file
b533bc97 1784 ;; Emacs 23+ only.
263c02ef 1785 'copy-directory
b533bc97 1786 ;; XEmacs only.
4007ba5b
KG
1787 'dired-make-relative-symlink
1788 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
1789 (save-match-data
1790 (cond
1791 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
1792 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
1793 (t (buffer-file-name (current-buffer))))))
b533bc97 1794 ;; START END FILE.
4007ba5b
KG
1795 ((eq operation 'write-region)
1796 (nth 2 args))
b533bc97 1797 ;; BUFFER.
4007ba5b 1798 ((member operation
00d6fd04 1799 (list 'set-visited-file-modtime 'verify-visited-file-modtime
b533bc97 1800 ;; Emacs 22+ only.
00d6fd04 1801 'make-auto-save-file-name
b533bc97 1802 ;; XEmacs only.
4007ba5b
KG
1803 'backup-buffer))
1804 (buffer-file-name
1805 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
b533bc97 1806 ;; COMMAND.
4007ba5b 1807 ((member operation
b533bc97 1808 (list ;; not in Emacs 23+.
00d6fd04 1809 'dired-call-process
b533bc97 1810 ;; Emacs only.
b71c9e75 1811 'shell-command
b533bc97 1812 ;; Emacs 22+ only.
0457dd55 1813 'process-file
b533bc97 1814 ;; Emacs 23+ only.
00d6fd04 1815 'start-file-process
b533bc97 1816 ;; XEmacs only.
00d6fd04 1817 'dired-print-file 'dired-shell-call-process
b533bc97 1818 ;; nowhere yet.
b81a0b56
MA
1819 'executable-find 'start-process
1820 'call-process 'call-process-region))
4007ba5b 1821 default-directory)
b533bc97 1822 ;; Unknown file primitive.
4007ba5b
KG
1823 (t (error "unknown file I/O primitive: %s" operation))))
1824
1825(defun tramp-find-foreign-file-name-handler (filename)
1826 "Return foreign file name handler if exists."
b533bc97 1827 (when (tramp-tramp-file-p filename)
9ce8462a
MA
1828 (let ((v (tramp-dissect-file-name filename t))
1829 (handler tramp-foreign-file-name-handler-alist)
1830 elt res)
1831 ;; When we are not fully sure that filename completion is safe,
1832 ;; we should not return a handler.
1833 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1834b39f
MA
1834 (and (tramp-file-name-host v)
1835 (not (member (tramp-file-name-host v)
1836 (mapcar 'car tramp-methods))))
9ce8462a
MA
1837 (not (tramp-completion-mode-p)))
1838 (while handler
1839 (setq elt (car handler)
1840 handler (cdr handler))
1841 (when (funcall (car elt) filename)
1842 (setq handler nil
1843 res (cdr elt))))
1844 res))))
4007ba5b 1845
fb7933a3
KG
1846;; Main function.
1847;;;###autoload
1848(defun tramp-file-name-handler (operation &rest args)
ea9d1443 1849 "Invoke Tramp file name handler.
a4aeb9a4 1850Falls back to normal file name handler if no Tramp file name handler exists."
2e271195
MA
1851 (if tramp-mode
1852 (save-match-data
1853 (let* ((filename
1854 (tramp-replace-environment-variables
1855 (apply 'tramp-file-name-for-operation operation args)))
1856 (completion (tramp-completion-mode-p))
1857 (foreign (tramp-find-foreign-file-name-handler filename)))
1858 (with-parsed-tramp-file-name filename nil
4874f5e6
MA
1859 ;; Call the backend function.
1860 (if foreign
1861 (condition-case err
1862 (apply foreign operation args)
af4b9ae5 1863
03c1ad43 1864 ;; Trace, that somebody has interrupted the operation.
af4b9ae5
MA
1865 (quit
1866 (let (tramp-message-show-message)
1867 (tramp-message
1868 v 1 "Interrupt received in operation %s"
1869 (append (list operation) args)))
1870 ;; Propagate the quit signal.
1871 (signal (car err) (cdr err)))
1872
1873 ;; When we are in completion mode, some failed
1874 ;; operations shall return at least a default value
1875 ;; in order to give the user a chance to correct the
1876 ;; file name in the minibuffer.
4874f5e6
MA
1877 (error
1878 (cond
4874f5e6
MA
1879 ((and completion (zerop (length localname))
1880 (memq operation '(file-exists-p file-directory-p)))
1881 t)
1882 ((and completion (zerop (length localname))
1883 (memq operation
1884 '(expand-file-name file-name-as-directory)))
1885 filename)
1886 ;; Propagate the error.
1887 (t (signal (car err) (cdr err))))))
af4b9ae5 1888
4874f5e6
MA
1889 ;; Nothing to do for us.
1890 (tramp-run-real-handler operation args)))))
1891
2e271195
MA
1892 ;; When `tramp-mode' is not enabled, we don't do anything.
1893 (tramp-run-real-handler operation args)))
fb7933a3 1894
07dfe738
KG
1895;; In Emacs, there is some concurrency due to timers. If a timer
1896;; interrupts Tramp and wishes to use the same connection buffer as
1897;; the "main" Emacs, then garbage might occur in the connection
1898;; buffer. Therefore, we need to make sure that a timer does not use
1899;; the same connection buffer as the "main" Emacs. We implement a
1900;; cheap global lock, instead of locking each connection buffer
1901;; separately. The global lock is based on two variables,
1902;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
1903;; (with setq) to indicate a lock. But Tramp also calls itself during
1904;; processing of a single file operation, so we need to allow
1905;; recursive calls. That's where the `tramp-locker' variable comes in
1906;; -- it is let-bound to t during the execution of the current
1907;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
1908;; then we should just proceed because we have been called
1909;; recursively. But if `tramp-locker' is nil, then we are a timer
1910;; interrupting the "main" Emacs, and then we signal an error.
1911
1912(defvar tramp-locked nil
1913 "If non-nil, then Tramp is currently busy.
1914Together with `tramp-locker', this implements a locking mechanism
1915preventing reentrant calls of Tramp.")
1916
1917(defvar tramp-locker nil
1918 "If non-nil, then a caller has locked Tramp.
1919Together with `tramp-locked', this implements a locking mechanism
1920preventing reentrant calls of Tramp.")
1921
16674e4f 1922;;;###autoload
1ecc6145 1923(progn (defun tramp-completion-file-name-handler (operation &rest args)
a4aeb9a4
MA
1924 "Invoke Tramp file name completion handler.
1925Falls back to normal file name handler if no Tramp file name handler exists."
57671b72
MA
1926 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
1927 ;; would otherwise use backslash.
aff67808
MA
1928 (let ((directory-sep-char ?/)
1929 (fn (assoc operation tramp-completion-file-name-handler-alist)))
aa485f7c
MA
1930 (if (and
1931 ;; When `tramp-mode' is not enabled, we don't do anything.
1932 fn tramp-mode
1933 ;; For other syntaxes than `sep', the regexp matches many common
1934 ;; situations where the user doesn't actually want to use Tramp.
1935 ;; So to avoid autoloading Tramp after typing just "/s", we
1936 ;; disable this part of the completion, unless the user implicitly
1937 ;; indicated his interest in using a fancier completion system.
1938 (or (eq tramp-syntax 'sep)
a94d821f
MA
1939 (featurep 'tramp) ;; If it's loaded, we may as well use it.
1940 ;; `partial-completion-mode' does not exist in XEmacs.
1941 ;; It is obsoleted with Emacs 24.1.
0d5852cf
MA
1942 (and (boundp 'partial-completion-mode)
1943 (symbol-value 'partial-completion-mode))
aa485f7c
MA
1944 ;; FIXME: These may have been loaded even if the user never
1945 ;; intended to use them.
1946 (featurep 'ido)
1947 (featurep 'icicles)))
aff67808
MA
1948 (save-match-data (apply (cdr fn) args))
1949 (tramp-completion-run-real-handler operation args)))))
a01b1e22 1950
b25a52cc 1951;;;###autoload
aa485f7c
MA
1952(progn (defun tramp-register-file-name-handlers ()
1953 "Add Tramp file name handlers to `file-name-handler-alist'."
1954 ;; Remove autoloaded handlers from file name handler alist. Useful,
00d6fd04
MA
1955 ;; if `tramp-syntax' has been changed.
1956 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
aa485f7c
MA
1957 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
1958 (let ((a1 (rassq
1959 'tramp-completion-file-name-handler file-name-handler-alist)))
1960 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
1961 ;; Add the handlers.
a01b1e22
MA
1962 (add-to-list 'file-name-handler-alist
1963 (cons tramp-file-name-regexp 'tramp-file-name-handler))
0c0b61f1 1964 (put 'tramp-file-name-handler 'safe-magic t)
aa485f7c
MA
1965 (add-to-list 'file-name-handler-alist
1966 (cons tramp-completion-file-name-regexp
1967 'tramp-completion-file-name-handler))
1968 (put 'tramp-completion-file-name-handler 'safe-magic t)
1969 ;; If jka-compr or epa-file are already loaded, move them to the
1970 ;; front of `file-name-handler-alist'.
1971 (dolist (fnh '(epa-file-handler jka-compr-handler))
1972 (let ((entry (rassoc fnh file-name-handler-alist)))
1973 (when entry
1974 (setq file-name-handler-alist
1975 (cons entry (delete entry file-name-handler-alist))))))))
69cee873 1976
00d6fd04
MA
1977;; `tramp-file-name-handler' must be registered before evaluation of
1978;; site-start and init files, because there might exist remote files
1979;; already, f.e. files kept via recentf-mode.
4a93e698 1980;;;###autoload
aa485f7c 1981(tramp-register-file-name-handlers)
b25a52cc 1982
4a93e698
MA
1983(defun tramp-exists-file-name-handler (operation &rest args)
1984 "Check, whether OPERATION runs a file name handler."
1985 ;; The file name handler is determined on base of either an
1986 ;; argument, `buffer-file-name', or `default-directory'.
1987 (ignore-errors
1988 (let* ((buffer-file-name "/")
1989 (default-directory "/")
1990 (fnha file-name-handler-alist)
1991 (check-file-name-operation operation)
1992 (file-name-handler-alist
1993 (list
1994 (cons "/"
1995 (lambda (operation &rest args)
1996 "Returns OPERATION if it is the one to be checked."
1997 (if (equal check-file-name-operation operation)
1998 operation
1999 (let ((file-name-handler-alist fnha))
2000 (apply operation args))))))))
2001 (equal (apply operation args) operation))))
2002
fb7933a3 2003;;;###autoload
8c04e197 2004(defun tramp-unload-file-name-handlers ()
a69c01a0
MA
2005 (setq file-name-handler-alist
2006 (delete (rassoc 'tramp-file-name-handler
2007 file-name-handler-alist)
2008 (delete (rassoc 'tramp-completion-file-name-handler
2009 file-name-handler-alist)
2010 file-name-handler-alist))))
2011
8c04e197 2012(add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
a69c01a0 2013
0664ff72 2014;;; File name handler functions for completion mode:
a6e96327
MA
2015
2016(defvar tramp-completion-mode nil
2017 "If non-nil, external packages signal that they are in file name completion.
2018
2019This is necessary, because Tramp uses a heuristic depending on last
2020input event. This fails when external packages use other characters
2021but <TAB>, <SPACE> or ?\\? for file name completion. This variable
2022should never be set globally, the intention is to let-bind it.")
16674e4f
KG
2023
2024;; Necessary because `tramp-file-name-regexp-unified' and
00d6fd04
MA
2025;; `tramp-completion-file-name-regexp-unified' aren't different. If
2026;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
2027;; to `tramp-file-name-handler'). Otherwise, it takes
2028;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
2029;; risky, because completing a file might require loading other files,
2030;; like "~/.netrc", and for them it shouldn't be decided based on that
2031;; variable. On the other hand, those files shouldn't have partial
a4aeb9a4
MA
2032;; Tramp file name syntax. Maybe another variable should be introduced
2033;; overwriting this check in such cases. Or we change Tramp file name
00d6fd04 2034;; syntax in order to avoid ambiguities, like in XEmacs ...
0f34aa77 2035;;;###tramp-autoload
6c4e47fa 2036(defun tramp-completion-mode-p ()
a94d821f 2037 "Check, whether method / user name / host name completion is active."
6c4e47fa 2038 (or
5f2b693f
MA
2039 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
2040 (and (boundp 'non-essential) (symbol-value 'non-essential))
a6e96327
MA
2041 tramp-completion-mode
2042 ;; Emacs.
94be87e8 2043 (equal last-input-event 'tab)
6c4e47fa 2044 (and (natnump last-input-event)
94be87e8 2045 (or
a6e96327 2046 ;; ?\t has event-modifier 'control.
800a97b8 2047 (equal last-input-event ?\t)
94be87e8 2048 (and (not (event-modifiers last-input-event))
800a97b8
SM
2049 (or (equal last-input-event ?\?)
2050 (equal last-input-event ?\ )))))
a6e96327 2051 ;; XEmacs.
6c4e47fa
MA
2052 (and (featurep 'xemacs)
2053 ;; `last-input-event' might be nil.
2054 (not (null last-input-event))
2055 ;; `last-input-event' may have no character approximation.
0d5852cf 2056 (tramp-compat-funcall 'event-to-character last-input-event)
94be87e8 2057 (or
a6e96327 2058 ;; ?\t has event-modifier 'control.
800a97b8 2059 (equal
0d5852cf 2060 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
94be87e8 2061 (and (not (event-modifiers last-input-event))
800a97b8 2062 (or (equal
0d5852cf
MA
2063 (tramp-compat-funcall 'event-to-character last-input-event)
2064 ?\?)
800a97b8 2065 (equal
0d5852cf
MA
2066 (tramp-compat-funcall 'event-to-character last-input-event)
2067 ?\ )))))))
16674e4f 2068
acd1f317
MA
2069(defun tramp-connectable-p (filename)
2070 "Check, whether it is possible to connect the remote host w/o side-effects.
2071This is true, if either the remote host is already connected, or if we are
2072not in completion mode."
2073 (and (tramp-tramp-file-p filename)
2074 (with-parsed-tramp-file-name filename nil
2075 (or (get-buffer (tramp-buffer-name v))
2076 (not (tramp-completion-mode-p))))))
2077
16674e4f
KG
2078;; Method, host name and user name completion.
2079;; `tramp-completion-dissect-file-name' returns a list of
2080;; tramp-file-name structures. For all of them we return possible completions.
a01b1e22 2081;;;###autoload
16674e4f 2082(defun tramp-completion-handle-file-name-all-completions (filename directory)
00d6fd04 2083 "Like `file-name-all-completions' for partial Tramp files."
16674e4f 2084
00d6fd04
MA
2085 (let* ((fullname (tramp-drop-volume-letter
2086 (expand-file-name filename directory)))
2087 ;; Possible completion structures.
2088 (v (tramp-completion-dissect-file-name fullname))
2089 result result1)
2090
2091 (while v
2092 (let* ((car (car v))
2093 (method (tramp-file-name-method car))
2094 (user (tramp-file-name-user car))
2095 (host (tramp-file-name-host car))
2096 (localname (tramp-file-name-localname car))
2097 (m (tramp-find-method method user host))
2098 (tramp-current-user user) ; see `tramp-parse-passwd'
2099 all-user-hosts)
2100
2101 (unless localname ;; Nothing to complete.
2102
2103 (if (or user host)
2104
2105 ;; Method dependent user / host combinations.
2106 (progn
9e6ab520 2107 (mapc
00d6fd04
MA
2108 (lambda (x)
2109 (setq all-user-hosts
2110 (append all-user-hosts
2111 (funcall (nth 0 x) (nth 1 x)))))
2112 (tramp-get-completion-function m))
2113
9e6ab520
MA
2114 (setq result
2115 (append result
2116 (mapcar
2117 (lambda (x)
2118 (tramp-get-completion-user-host
2119 method user host (nth 0 x) (nth 1 x)))
2120 (delq nil all-user-hosts)))))
00d6fd04
MA
2121
2122 ;; Possible methods.
2123 (setq result
2124 (append result (tramp-get-completion-methods m)))))
2125
2126 (setq v (cdr v))))
2127
2128 ;; Unify list, remove nil elements.
2129 (while result
2130 (let ((car (car result)))
2131 (when car
2132 (add-to-list
2133 'result1
2134 (substring car (length (tramp-drop-volume-letter directory)))))
2135 (setq result (cdr result))))
2136
2137 ;; Complete local parts.
2138 (append
2139 result1
03c1ad43
MA
2140 (ignore-errors
2141 (apply (if (tramp-connectable-p fullname)
2142 'tramp-completion-run-real-handler
2143 'tramp-run-real-handler)
2144 'file-name-all-completions (list (list filename directory)))))))
16674e4f
KG
2145
2146;; Method, host name and user name completion for a file.
a01b1e22 2147;;;###autoload
e1e17cae
MA
2148(defun tramp-completion-handle-file-name-completion
2149 (filename directory &optional predicate)
00d6fd04 2150 "Like `file-name-completion' for Tramp files."
e1e17cae
MA
2151 (try-completion
2152 filename
2153 (mapcar 'list (file-name-all-completions filename directory))
acd1f317
MA
2154 (when (and predicate
2155 (tramp-connectable-p (expand-file-name filename directory)))
83e20b5c 2156 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
16674e4f
KG
2157
2158;; I misuse a little bit the tramp-file-name structure in order to handle
2159;; completion possibilities for partial methods / user names / host names.
2160;; Return value is a list of tramp-file-name structures according to possible
00d6fd04 2161;; completions. If "localname" is non-nil it means there
16674e4f
KG
2162;; shouldn't be a completion anymore.
2163
2164;; Expected results:
2165
00d6fd04
MA
2166;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
2167;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
2168;; [nil "x" nil nil]
2169;; ["x" nil nil nil]
2170
2171;; "/x:" "/x:y" "/x:y:"
2172;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
2173;; "/[x/" "/[x/y"
2174;; ["x" nil "" nil] ["x" nil "y" nil]
2175;; ["x" "" nil nil] ["x" "y" nil nil]
2176
2177;; "/x:y@" "/x:y@z" "/x:y@z:"
2178;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
2179;; "/[x/y@" "/[x/y@z"
2180;; ["x" nil "y" nil] ["x" "y" "z" nil]
16674e4f
KG
2181(defun tramp-completion-dissect-file-name (name)
2182 "Returns a list of `tramp-file-name' structures.
2183They are collected by `tramp-completion-dissect-file-name1'."
2184
2185 (let* ((result)
4007ba5b 2186 (x-nil "\\|\\(\\)")
b96e6899
MA
2187 (tramp-completion-ipv6-regexp
2188 (format
2189 "[^%s]*"
2190 (if (zerop (length tramp-postfix-ipv6-format))
2191 tramp-postfix-host-format
2192 tramp-postfix-ipv6-format)))
4007ba5b
KG
2193 ;; "/method" "/[method"
2194 (tramp-completion-file-name-structure1
2195 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
2196 1 nil nil nil))
2197 ;; "/user" "/[user"
2198 (tramp-completion-file-name-structure2
2199 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
2200 nil 1 nil nil))
2201 ;; "/host" "/[host"
2202 (tramp-completion-file-name-structure3
2203 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
2204 nil nil 1 nil))
b96e6899 2205 ;; "/[ipv6" "/[ipv6"
4007ba5b 2206 (tramp-completion-file-name-structure4
b96e6899
MA
2207 (list (concat tramp-prefix-regexp
2208 tramp-prefix-ipv6-regexp
2209 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2210 nil nil 1 nil))
2211 ;; "/user@host" "/[user@host"
2212 (tramp-completion-file-name-structure5
4007ba5b
KG
2213 (list (concat tramp-prefix-regexp
2214 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2215 "\\(" tramp-host-regexp x-nil "\\)$")
2216 nil 1 2 nil))
b96e6899
MA
2217 ;; "/user@[ipv6" "/[user@ipv6"
2218 (tramp-completion-file-name-structure6
2219 (list (concat tramp-prefix-regexp
2220 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2221 tramp-prefix-ipv6-regexp
2222 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2223 nil 1 2 nil))
00d6fd04 2224 ;; "/method:user" "/[method/user" "/method://user"
b96e6899 2225 (tramp-completion-file-name-structure7
4007ba5b 2226 (list (concat tramp-prefix-regexp
00d6fd04 2227 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
2228 "\\(" tramp-user-regexp x-nil "\\)$")
2229 1 2 nil nil))
00d6fd04 2230 ;; "/method:host" "/[method/host" "/method://host"
b96e6899 2231 (tramp-completion-file-name-structure8
4007ba5b 2232 (list (concat tramp-prefix-regexp
00d6fd04 2233 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
2234 "\\(" tramp-host-regexp x-nil "\\)$")
2235 1 nil 2 nil))
b96e6899
MA
2236 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
2237 (tramp-completion-file-name-structure9
2238 (list (concat tramp-prefix-regexp
2239 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2240 tramp-prefix-ipv6-regexp
2241 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2242 1 nil 2 nil))
00d6fd04 2243 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
b96e6899 2244 (tramp-completion-file-name-structure10
4007ba5b 2245 (list (concat tramp-prefix-regexp
00d6fd04 2246 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
2247 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2248 "\\(" tramp-host-regexp x-nil "\\)$")
00d6fd04 2249 1 2 3 nil))
b96e6899
MA
2250 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
2251 (tramp-completion-file-name-structure11
2252 (list (concat tramp-prefix-regexp
2253 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2254 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2255 tramp-prefix-ipv6-regexp
2256 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2257 1 2 3 nil))
00d6fd04 2258 ;; "/method: "/method:/"
b96e6899 2259 (tramp-completion-file-name-structure12
00d6fd04
MA
2260 (list
2261 (if (equal tramp-syntax 'url)
2262 (concat tramp-prefix-regexp
2263 "\\(" tramp-method-regexp "\\)"
2264 "\\(" (substring tramp-postfix-method-regexp 0 1)
2265 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2266 "\\(" "\\)$")
2267 ;; Should not match if not URL syntax.
2268 (concat tramp-prefix-regexp "/$"))
2269 1 3 nil nil))
2270 ;; "/method: "/method:/"
b96e6899 2271 (tramp-completion-file-name-structure13
00d6fd04
MA
2272 (list
2273 (if (equal tramp-syntax 'url)
2274 (concat tramp-prefix-regexp
2275 "\\(" tramp-method-regexp "\\)"
2276 "\\(" (substring tramp-postfix-method-regexp 0 1)
2277 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2278 "\\(" "\\)$")
2279 ;; Should not match if not URL syntax.
2280 (concat tramp-prefix-regexp "/$"))
2281 1 nil 3 nil)))
4007ba5b 2282
9e6ab520 2283 (mapc (lambda (regexp)
16674e4f
KG
2284 (add-to-list 'result
2285 (tramp-completion-dissect-file-name1 regexp name)))
2286 (list
2287 tramp-completion-file-name-structure1
2288 tramp-completion-file-name-structure2
2289 tramp-completion-file-name-structure3
2290 tramp-completion-file-name-structure4
2291 tramp-completion-file-name-structure5
2292 tramp-completion-file-name-structure6
2293 tramp-completion-file-name-structure7
00d6fd04
MA
2294 tramp-completion-file-name-structure8
2295 tramp-completion-file-name-structure9
b96e6899
MA
2296 tramp-completion-file-name-structure10
2297 tramp-completion-file-name-structure11
2298 tramp-completion-file-name-structure12
2299 tramp-completion-file-name-structure13
16674e4f
KG
2300 tramp-file-name-structure))
2301
2302 (delq nil result)))
2303
2304(defun tramp-completion-dissect-file-name1 (structure name)
2305 "Returns a `tramp-file-name' structure matching STRUCTURE.
00d6fd04 2306The structure consists of remote method, remote user,
7432277c 2307remote host and localname (filename on remote host)."
fb7933a3 2308
00d6fd04
MA
2309 (save-match-data
2310 (when (string-match (nth 0 structure) name)
2311 (let ((method (and (nth 1 structure)
2312 (match-string (nth 1 structure) name)))
2313 (user (and (nth 2 structure)
2314 (match-string (nth 2 structure) name)))
2315 (host (and (nth 3 structure)
2316 (match-string (nth 3 structure) name)))
2317 (localname (and (nth 4 structure)
2318 (match-string (nth 4 structure) name))))
2319 (vector method user host localname)))))
16674e4f
KG
2320
2321;; This function returns all possible method completions, adding the
2322;; trailing method delimeter.
16674e4f
KG
2323(defun tramp-get-completion-methods (partial-method)
2324 "Returns all method completions for PARTIAL-METHOD."
4007ba5b
KG
2325 (mapcar
2326 (lambda (method)
2327 (and method
2328 (string-match (concat "^" (regexp-quote partial-method)) method)
00d6fd04
MA
2329 (tramp-completion-make-tramp-file-name method nil nil nil)))
2330 (mapcar 'car tramp-methods)))
16674e4f
KG
2331
2332;; Compares partial user and host names with possible completions.
2333(defun tramp-get-completion-user-host (method partial-user partial-host user host)
2334 "Returns the most expanded string for user and host name completion.
2335PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2336 (cond
2337
2338 ((and partial-user partial-host)
2339 (if (and host
2340 (string-match (concat "^" (regexp-quote partial-host)) host)
2341 (string-equal partial-user (or user partial-user)))
2342 (setq user partial-user)
2343 (setq user nil
2344 host nil)))
2345
2346 (partial-user
2347 (setq host nil)
2348 (unless
2349 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2350 (setq user nil)))
2351
2352 (partial-host
2353 (setq user nil)
2354 (unless
2355 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2356 (setq host nil)))
2357
2358 (t (setq user nil
2359 host nil)))
2360
292ffc15 2361 (unless (zerop (+ (length user) (length host)))
00d6fd04 2362 (tramp-completion-make-tramp-file-name method user host nil)))
16674e4f
KG
2363
2364(defun tramp-parse-rhosts (filename)
2365 "Return a list of (user host) tuples allowed to access.
292ffc15 2366Either user or host may be nil."
00d6fd04
MA
2367 ;; On Windows, there are problems in completion when
2368 ;; `default-directory' is remote.
9e6ab520 2369 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 2370 res)
8daea7fc 2371 (when (file-readable-p filename)
16674e4f
KG
2372 (with-temp-buffer
2373 (insert-file-contents filename)
2374 (goto-char (point-min))
2375 (while (not (eobp))
292ffc15 2376 (push (tramp-parse-rhosts-group) res))))
16674e4f
KG
2377 res))
2378
16674e4f
KG
2379(defun tramp-parse-rhosts-group ()
2380 "Return a (user host) tuple allowed to access.
292ffc15 2381Either user or host may be nil."
16674e4f
KG
2382 (let ((result)
2383 (regexp
2384 (concat
2385 "^\\(" tramp-host-regexp "\\)"
2386 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6e060cee 2387 (narrow-to-region (point) (point-at-eol))
16674e4f
KG
2388 (when (re-search-forward regexp nil t)
2389 (setq result (append (list (match-string 3) (match-string 1)))))
2390 (widen)
2391 (forward-line 1)
2392 result))
2393
2394(defun tramp-parse-shosts (filename)
2395 "Return a list of (user host) tuples allowed to access.
2396User is always nil."
00d6fd04
MA
2397 ;; On Windows, there are problems in completion when
2398 ;; `default-directory' is remote.
9e6ab520 2399 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 2400 res)
8daea7fc 2401 (when (file-readable-p filename)
16674e4f
KG
2402 (with-temp-buffer
2403 (insert-file-contents filename)
2404 (goto-char (point-min))
2405 (while (not (eobp))
292ffc15 2406 (push (tramp-parse-shosts-group) res))))
16674e4f
KG
2407 res))
2408
2409(defun tramp-parse-shosts-group ()
2410 "Return a (user host) tuple allowed to access.
2411User is always nil."
16674e4f
KG
2412 (let ((result)
2413 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
6e060cee 2414 (narrow-to-region (point) (point-at-eol))
16674e4f
KG
2415 (when (re-search-forward regexp nil t)
2416 (setq result (list nil (match-string 1))))
2417 (widen)
2418 (or
2419 (> (skip-chars-forward ",") 0)
2420 (forward-line 1))
2421 result))
2422
8daea7fc
KG
2423(defun tramp-parse-sconfig (filename)
2424 "Return a list of (user host) tuples allowed to access.
2425User is always nil."
00d6fd04
MA
2426 ;; On Windows, there are problems in completion when
2427 ;; `default-directory' is remote.
9e6ab520 2428 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 2429 res)
8daea7fc
KG
2430 (when (file-readable-p filename)
2431 (with-temp-buffer
2432 (insert-file-contents filename)
2433 (goto-char (point-min))
2434 (while (not (eobp))
2435 (push (tramp-parse-sconfig-group) res))))
2436 res))
2437
2438(defun tramp-parse-sconfig-group ()
2439 "Return a (user host) tuple allowed to access.
2440User is always nil."
8daea7fc
KG
2441 (let ((result)
2442 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
6e060cee 2443 (narrow-to-region (point) (point-at-eol))
8daea7fc
KG
2444 (when (re-search-forward regexp nil t)
2445 (setq result (list nil (match-string 1))))
2446 (widen)
2447 (or
2448 (> (skip-chars-forward ",") 0)
2449 (forward-line 1))
2450 result))
2451
5ec2cc41
KG
2452(defun tramp-parse-shostkeys (dirname)
2453 "Return a list of (user host) tuples allowed to access.
2454User is always nil."
00d6fd04
MA
2455 ;; On Windows, there are problems in completion when
2456 ;; `default-directory' is remote.
9e6ab520 2457 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
2458 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
2459 (files (when (file-directory-p dirname) (directory-files dirname)))
2460 result)
5ec2cc41
KG
2461 (while files
2462 (when (string-match regexp (car files))
2463 (push (list nil (match-string 1 (car files))) result))
2464 (setq files (cdr files)))
2465 result))
2466
2467(defun tramp-parse-sknownhosts (dirname)
2468 "Return a list of (user host) tuples allowed to access.
2469User is always nil."
00d6fd04
MA
2470 ;; On Windows, there are problems in completion when
2471 ;; `default-directory' is remote.
9e6ab520 2472 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
2473 (regexp (concat "^\\(" tramp-host-regexp
2474 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
2475 (files (when (file-directory-p dirname) (directory-files dirname)))
2476 result)
5ec2cc41
KG
2477 (while files
2478 (when (string-match regexp (car files))
2479 (push (list nil (match-string 1 (car files))) result))
2480 (setq files (cdr files)))
2481 result))
2482
16674e4f
KG
2483(defun tramp-parse-hosts (filename)
2484 "Return a list of (user host) tuples allowed to access.
2485User is always nil."
00d6fd04
MA
2486 ;; On Windows, there are problems in completion when
2487 ;; `default-directory' is remote.
9e6ab520 2488 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 2489 res)
8daea7fc 2490 (when (file-readable-p filename)
16674e4f
KG
2491 (with-temp-buffer
2492 (insert-file-contents filename)
2493 (goto-char (point-min))
2494 (while (not (eobp))
292ffc15 2495 (push (tramp-parse-hosts-group) res))))
16674e4f
KG
2496 res))
2497
2498(defun tramp-parse-hosts-group ()
2499 "Return a (user host) tuple allowed to access.
2500User is always nil."
16674e4f 2501 (let ((result)
b96e6899
MA
2502 (regexp
2503 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6e060cee 2504 (narrow-to-region (point) (point-at-eol))
16674e4f 2505 (when (re-search-forward regexp nil t)
b96e6899 2506 (setq result (list nil (match-string 1))))
16674e4f
KG
2507 (widen)
2508 (or
2509 (> (skip-chars-forward " \t") 0)
2510 (forward-line 1))
2511 result))
2512
8daea7fc
KG
2513;; For su-alike methods it would be desirable to return "root@localhost"
2514;; as default. Unfortunately, we have no information whether any user name
00d6fd04 2515;; has been typed already. So we use `tramp-current-user' as indication,
8daea7fc 2516;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
16674e4f
KG
2517(defun tramp-parse-passwd (filename)
2518 "Return a list of (user host) tuples allowed to access.
2519Host is always \"localhost\"."
00d6fd04
MA
2520 ;; On Windows, there are problems in completion when
2521 ;; `default-directory' is remote.
9e6ab520 2522 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 2523 res)
8daea7fc 2524 (if (zerop (length tramp-current-user))
16674e4f 2525 '(("root" nil))
8daea7fc 2526 (when (file-readable-p filename)
16674e4f
KG
2527 (with-temp-buffer
2528 (insert-file-contents filename)
2529 (goto-char (point-min))
2530 (while (not (eobp))
292ffc15 2531 (push (tramp-parse-passwd-group) res))))
16674e4f
KG
2532 res)))
2533
2534(defun tramp-parse-passwd-group ()
2535 "Return a (user host) tuple allowed to access.
292ffc15 2536Host is always \"localhost\"."
16674e4f
KG
2537 (let ((result)
2538 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6e060cee 2539 (narrow-to-region (point) (point-at-eol))
16674e4f
KG
2540 (when (re-search-forward regexp nil t)
2541 (setq result (list (match-string 1) "localhost")))
2542 (widen)
2543 (forward-line 1)
2544 result))
2545
292ffc15
KG
2546(defun tramp-parse-netrc (filename)
2547 "Return a list of (user host) tuples allowed to access.
2548User may be nil."
00d6fd04
MA
2549 ;; On Windows, there are problems in completion when
2550 ;; `default-directory' is remote.
9e6ab520 2551 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 2552 res)
8daea7fc 2553 (when (file-readable-p filename)
292ffc15
KG
2554 (with-temp-buffer
2555 (insert-file-contents filename)
2556 (goto-char (point-min))
2557 (while (not (eobp))
2558 (push (tramp-parse-netrc-group) res))))
2559 res))
2560
2561(defun tramp-parse-netrc-group ()
2562 "Return a (user host) tuple allowed to access.
2563User may be nil."
292ffc15
KG
2564 (let ((result)
2565 (regexp
2566 (concat
2567 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2568 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6e060cee 2569 (narrow-to-region (point) (point-at-eol))
292ffc15
KG
2570 (when (re-search-forward regexp nil t)
2571 (setq result (list (match-string 3) (match-string 1))))
2572 (widen)
2573 (forward-line 1)
2574 result))
2575
00d6fd04
MA
2576(defun tramp-parse-putty (registry)
2577 "Return a list of (user host) tuples allowed to access.
2578User is always nil."
2579 ;; On Windows, there are problems in completion when
2580 ;; `default-directory' is remote.
9e6ab520 2581 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
2582 res)
2583 (with-temp-buffer
0f34aa77 2584 (when (zerop (tramp-compat-call-process "reg" nil t nil "query" registry))
00d6fd04
MA
2585 (goto-char (point-min))
2586 (while (not (eobp))
2587 (push (tramp-parse-putty-group registry) res))))
2588 res))
2589
2590(defun tramp-parse-putty-group (registry)
2591 "Return a (user host) tuple allowed to access.
2592User is always nil."
2593 (let ((result)
2594 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6e060cee 2595 (narrow-to-region (point) (point-at-eol))
00d6fd04
MA
2596 (when (re-search-forward regexp nil t)
2597 (setq result (list nil (match-string 1))))
2598 (widen)
2599 (forward-line 1)
2600 result))
2601
4a93e698 2602;;; Common file name handler functions for different backends:
b88f2d0a 2603
4a93e698
MA
2604(defvar tramp-handle-file-local-copy-hook nil
2605 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2606
2607(defvar tramp-handle-write-region-hook nil
2608 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2609
2610(defun tramp-handle-directory-file-name (directory)
2611 "Like `directory-file-name' for Tramp files."
2612 ;; If localname component of filename is "/", leave it unchanged.
2613 ;; Otherwise, remove any trailing slash from localname component.
2614 ;; Method, host, etc, are unchanged. Does it make sense to try
2615 ;; to avoid parsing the filename?
2616 (with-parsed-tramp-file-name directory nil
2617 (if (and (not (zerop (length localname)))
2618 (eq (aref localname (1- (length localname))) ?/)
2619 (not (string= localname "/")))
2620 (substring directory 0 -1)
2621 directory)))
2622
2623(defun tramp-handle-directory-files
2624 (directory &optional full match nosort files-only)
2625 "Like `directory-files' for Tramp files."
2626 ;; FILES-ONLY is valid for XEmacs only.
2627 (when (file-directory-p directory)
2628 (setq directory (file-name-as-directory (expand-file-name directory)))
2629 (let ((temp (nreverse (file-name-all-completions "" directory)))
2630 result item)
2631
2632 (while temp
2633 (setq item (directory-file-name (pop temp)))
2634 (when (and (or (null match) (string-match match item))
2635 (or (null files-only)
2636 ;; Files only.
2637 (and (equal files-only t) (file-regular-p item))
2638 ;; Directories only.
2639 (file-directory-p item)))
2640 (push (if full (concat directory item) item)
2641 result)))
2642 (if nosort result (sort result 'string<)))))
2643
bd8fadca
MA
2644(defun tramp-handle-directory-files-and-attributes
2645 (directory &optional full match nosort id-format)
2646 "Like `directory-files-and-attributes' for Tramp files."
2647 (mapcar
2648 (lambda (x)
2649 (cons x (tramp-compat-file-attributes
2650 (if full x (expand-file-name x directory)) id-format)))
2651 (directory-files directory full match nosort)))
2652
4a93e698
MA
2653(defun tramp-handle-dired-uncache (dir &optional dir-p)
2654 "Like `dired-uncache' for Tramp files."
2655 ;; DIR-P is valid for XEmacs only.
2656 (with-parsed-tramp-file-name
2657 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
2658 (tramp-flush-directory-property v localname)))
2659
bd8fadca
MA
2660(defun tramp-handle-file-exists-p (filename)
2661 "Like `file-exists-p' for Tramp files."
2662 (not (null (file-attributes filename))))
2663
4a93e698
MA
2664(defun tramp-handle-file-modes (filename)
2665 "Like `file-modes' for Tramp files."
2666 (let ((truename (or (file-truename filename) filename)))
2667 (when (file-exists-p truename)
2668 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
2669
2670;; Localname manipulation functions that grok Tramp localnames...
2671(defun tramp-handle-file-name-as-directory (file)
2672 "Like `file-name-as-directory' but aware of Tramp files."
2673 ;; `file-name-as-directory' would be sufficient except localname is
2674 ;; the empty string.
2675 (let ((v (tramp-dissect-file-name file t)))
2676 ;; Run the command on the localname portion only.
2677 (tramp-make-tramp-file-name
2678 (tramp-file-name-method v)
2679 (tramp-file-name-user v)
2680 (tramp-file-name-host v)
2681 (tramp-run-real-handler
2682 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2683
2684(defun tramp-handle-file-name-completion
2685 (filename directory &optional predicate)
2686 "Like `file-name-completion' for Tramp files."
2687 (unless (tramp-tramp-file-p directory)
2688 (error
2689 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2690 directory))
2691 (try-completion
2692 filename
2693 (mapcar 'list (file-name-all-completions filename directory))
2694 (when predicate
2695 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2696
2697(defun tramp-handle-file-name-directory (file)
2698 "Like `file-name-directory' but aware of Tramp files."
2699 ;; Everything except the last filename thing is the directory. We
2700 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2701 ;; the remote file name parts. This is a problem when we are in
2702 ;; file name completion.
2703 (let ((v (tramp-dissect-file-name file t)))
2704 ;; Run the command on the localname portion only.
2705 (tramp-make-tramp-file-name
2706 (tramp-file-name-method v)
2707 (tramp-file-name-user v)
2708 (tramp-file-name-host v)
2709 (tramp-run-real-handler
2710 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2711
2712(defun tramp-handle-file-name-nondirectory (file)
2713 "Like `file-name-nondirectory' but aware of Tramp files."
2714 (with-parsed-tramp-file-name file nil
2715 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2716
bd8fadca
MA
2717(defun tramp-handle-file-newer-than-file-p (file1 file2)
2718 "Like `file-newer-than-file-p' for Tramp files."
2719 (cond
2720 ((not (file-exists-p file1)) nil)
2721 ((not (file-exists-p file2)) t)
2722 (t (tramp-time-less-p (nth 5 (file-attributes file2))
2723 (nth 5 (file-attributes file1))))))
2724
4a93e698
MA
2725(defun tramp-handle-file-regular-p (filename)
2726 "Like `file-regular-p' for Tramp files."
2727 (and (file-exists-p filename)
2728 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
2729
2730(defun tramp-handle-file-remote-p (filename &optional identification connected)
2731 "Like `file-remote-p' for Tramp files."
2732 (let ((tramp-verbose 3))
2733 (when (tramp-tramp-file-p filename)
2734 (let* ((v (tramp-dissect-file-name filename))
2735 (p (tramp-get-connection-process v))
2736 (c (and p (processp p) (memq (process-status p) '(run open)))))
2737 ;; We expand the file name only, if there is already a connection.
2738 (with-parsed-tramp-file-name
2739 (if c (expand-file-name filename) filename) nil
2740 (and (or (not connected) c)
2741 (cond
2742 ((eq identification 'method) method)
2743 ((eq identification 'user) user)
2744 ((eq identification 'host) host)
2745 ((eq identification 'localname) localname)
2746 (t (tramp-make-tramp-file-name method user host "")))))))))
2747
2748(defun tramp-handle-file-symlink-p (filename)
2749 "Like `file-symlink-p' for Tramp files."
2750 (with-parsed-tramp-file-name filename nil
2751 (let ((x (car (file-attributes filename))))
2752 (when (stringp x)
2753 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2754 ;; might do weird things.
2755 (if (file-name-absolute-p x)
2756 (tramp-make-tramp-file-name method user host x)
2757 x)))))
2758
2759(defun tramp-handle-find-backup-file-name (filename)
2760 "Like `find-backup-file-name' for Tramp files."
2761 (with-parsed-tramp-file-name filename nil
2762 ;; We set both variables. It doesn't matter whether it is
2763 ;; Emacs or XEmacs.
2764 (let ((backup-directory-alist
2765 ;; Emacs case.
2766 (when (boundp 'backup-directory-alist)
2767 (if (symbol-value 'tramp-backup-directory-alist)
2768 (mapcar
2769 (lambda (x)
2770 (cons
2771 (car x)
2772 (if (and (stringp (cdr x))
2773 (file-name-absolute-p (cdr x))
2774 (not (tramp-file-name-p (cdr x))))
2775 (tramp-make-tramp-file-name method user host (cdr x))
2776 (cdr x))))
2777 (symbol-value 'tramp-backup-directory-alist))
2778 (symbol-value 'backup-directory-alist))))
2779
2780 (bkup-backup-directory-info
2781 ;; XEmacs case.
2782 (when (boundp 'bkup-backup-directory-info)
2783 (if (symbol-value 'tramp-bkup-backup-directory-info)
2784 (mapcar
2785 (lambda (x)
2786 (nconc
2787 (list (car x))
2788 (list
2789 (if (and (stringp (car (cdr x)))
2790 (file-name-absolute-p (car (cdr x)))
2791 (not (tramp-file-name-p (car (cdr x)))))
2792 (tramp-make-tramp-file-name
2793 method user host (car (cdr x)))
2794 (car (cdr x))))
2795 (cdr (cdr x))))
2796 (symbol-value 'tramp-bkup-backup-directory-info))
2797 (symbol-value 'bkup-backup-directory-info)))))
2798
2799 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
2800
2801(defun tramp-handle-insert-file-contents
2802 (filename &optional visit beg end replace)
2803 "Like `insert-file-contents' for Tramp files."
2804 (barf-if-buffer-read-only)
2805 (setq filename (expand-file-name filename))
2806 (let (result local-copy remote-copy)
2807 (with-parsed-tramp-file-name filename nil
2808 (unwind-protect
2809 (if (not (file-exists-p filename))
2810 ;; We don't raise a Tramp error, because it might be
2811 ;; suppressed, like in `find-file-noselect-1'.
2812 (signal 'file-error
2813 (list "File not found on remote host" filename))
2814
2815 (if (and (tramp-local-host-p v)
2816 (let (file-name-handler-alist)
2817 (file-readable-p localname)))
2818 ;; Short track: if we are on the local host, we can
2819 ;; run directly.
2820 (setq result
2821 (tramp-run-real-handler
2822 'insert-file-contents
2823 (list localname visit beg end replace)))
2824
2825 ;; When we shall insert only a part of the file, we copy
2826 ;; this part.
2827 (when (or beg end)
2828 (setq remote-copy (tramp-make-tramp-temp-file v))
2829 ;; This is defined in tramp-sh.el. Let's assume this
2830 ;; is loaded already.
2831 (tramp-compat-funcall 'tramp-send-command
2832 v
2833 (cond
2834 ((and beg end)
2835 (format "tail -c +%d %s | head -c +%d >%s"
2836 (1+ beg) (tramp-shell-quote-argument localname)
2837 (- end beg) remote-copy))
2838 (beg
2839 (format "tail -c +%d %s >%s"
2840 (1+ beg) (tramp-shell-quote-argument localname)
2841 remote-copy))
2842 (end
2843 (format "head -c +%d %s >%s"
2844 (1+ end) (tramp-shell-quote-argument localname)
2845 remote-copy)))))
2846
2847 ;; `insert-file-contents-literally' takes care to avoid
2848 ;; calling jka-compr. By let-binding
2849 ;; `inhibit-file-name-operation', we propagate that care
2850 ;; to the `file-local-copy' operation.
2851 (setq local-copy
2852 (let ((inhibit-file-name-operation
2853 (when (eq inhibit-file-name-operation
2854 'insert-file-contents)
2855 'file-local-copy)))
2856 (cond
2857 ((stringp remote-copy)
2858 (file-local-copy
2859 (tramp-make-tramp-file-name
2860 method user host remote-copy)))
2861 ((stringp tramp-temp-buffer-file-name)
2862 (copy-file filename tramp-temp-buffer-file-name 'ok)
2863 tramp-temp-buffer-file-name)
2864 (t (file-local-copy filename)))))
2865
2866 ;; When the file is not readable for the owner, it
d68b0220
MA
2867 ;; cannot be inserted, even if it is readable for the
2868 ;; group or for everybody.
4a93e698
MA
2869 (set-file-modes local-copy (tramp-compat-octal-to-decimal "0600"))
2870
2871 (when (and (null remote-copy)
2872 (tramp-get-method-parameter
2873 method 'tramp-copy-keep-tmpfile))
2874 ;; We keep the local file for performance reasons,
2875 ;; useful for "rsync".
d68b0220 2876 (setq tramp-temp-buffer-file-name local-copy))
4a93e698
MA
2877
2878 (with-progress-reporter
2879 v 3 (format "Inserting local temp file `%s'" local-copy)
2880 ;; We must ensure that `file-coding-system-alist'
2881 ;; matches `local-copy'.
2882 (let ((file-coding-system-alist
2883 (tramp-find-file-name-coding-system-alist
2884 filename local-copy)))
2885 (setq result
2886 (insert-file-contents
2887 local-copy nil nil nil replace))))))
2888
2889 ;; Save exit.
2890 (progn
2891 (when visit
2892 (setq buffer-file-name filename)
2893 (setq buffer-read-only (not (file-writable-p filename)))
2894 (set-visited-file-modtime)
e274eb13 2895 (set-buffer-modified-p nil))
4a93e698
MA
2896 (when (and (stringp local-copy)
2897 (or remote-copy (null tramp-temp-buffer-file-name)))
2898 (delete-file local-copy))
2899 (when (stringp remote-copy)
2900 (delete-file
2901 (tramp-make-tramp-file-name method user host remote-copy))))))
2902
2903 ;; Result.
2904 (list (expand-file-name filename)
2905 (cadr result))))
2906
2907(defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2908 "Like `load' for Tramp files."
2909 (with-parsed-tramp-file-name (expand-file-name file) nil
2910 (unless nosuffix
2911 (cond ((file-exists-p (concat file ".elc"))
2912 (setq file (concat file ".elc")))
2913 ((file-exists-p (concat file ".el"))
2914 (setq file (concat file ".el")))))
2915 (when must-suffix
2916 ;; The first condition is always true for absolute file names.
2917 ;; Included for safety's sake.
2918 (unless (or (file-name-directory file)
2919 (string-match "\\.elc?\\'" file))
2920 (tramp-error
2921 v 'file-error
2922 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2923 (unless noerror
2924 (when (not (file-exists-p file))
2925 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2926 (if (not (file-exists-p file))
2927 nil
2928 (let ((tramp-message-show-message (not nomessage)))
2929 (with-progress-reporter v 0 (format "Loading %s" file)
2930 (let ((local-copy (file-local-copy file)))
2931 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2932 (unwind-protect
2933 (load local-copy noerror t t)
2934 (delete-file local-copy)))))
2935 t)))
2936
2937(defun tramp-handle-substitute-in-file-name (filename)
2938 "Like `substitute-in-file-name' for Tramp files.
2939\"//\" and \"/~\" substitute only in the local filename part.
2940If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
2941beginning of local filename are not substituted."
2942 ;; First, we must replace environment variables.
2943 (setq filename (tramp-replace-environment-variables filename))
2944 (with-parsed-tramp-file-name filename nil
2945 (if (equal tramp-syntax 'url)
2946 ;; We need to check localname only. The other parts cannot contain
2947 ;; "//" or "/~".
2948 (if (and (> (length localname) 1)
2949 (or (string-match "//" localname)
2950 (string-match "/~" localname 1)))
2951 (tramp-run-real-handler 'substitute-in-file-name (list filename))
2952 (tramp-make-tramp-file-name
2953 (when method (substitute-in-file-name method))
2954 (when user (substitute-in-file-name user))
2955 (when host (substitute-in-file-name host))
2956 (when localname
2957 (tramp-run-real-handler
2958 'substitute-in-file-name (list localname)))))
2959 ;; Ignore in LOCALNAME everything before "//" or "/~".
2960 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
2961 (setq filename
2962 (concat (file-remote-p filename)
2963 (replace-match "\\1" nil nil localname)))
2964 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
2965 (when (string-match "~$" filename)
2966 (setq filename (concat filename "/"))))
2967 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
2968
2969(defun tramp-handle-unhandled-file-name-directory (filename)
2970 "Like `unhandled-file-name-directory' for Tramp files."
2971 ;; With Emacs 23, we could simply return `nil'. But we must keep it
2972 ;; for backward compatibility.
2973 (expand-file-name "~/"))
b88f2d0a 2974
4a93e698 2975;;; Functions for establishing connection:
fb7933a3 2976
ac474af1
KG
2977;; The following functions are actions to be taken when seeing certain
2978;; prompts from the remote host. See the variable
2979;; `tramp-actions-before-shell' for usage of these functions.
2980
00d6fd04 2981(defun tramp-action-login (proc vec)
ac474af1 2982 "Send the login name."
00d6fd04
MA
2983 (when (not (stringp tramp-current-user))
2984 (save-window-excursion
2985 (let ((enable-recursive-minibuffers t))
2986 (pop-to-buffer (tramp-get-connection-buffer vec))
2987 (setq tramp-current-user (read-string (match-string 0))))))
2988 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
2989 (with-current-buffer (tramp-get-connection-buffer vec)
2990 (tramp-message vec 6 "\n%s" (buffer-string)))
2991 (tramp-send-string vec tramp-current-user))
2992
2993(defun tramp-action-password (proc vec)
ac474af1 2994 "Query the user for a password."
70c11b0b
MA
2995 (with-current-buffer (process-buffer proc)
2996 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
bb6aba9c
MA
2997 (tramp-message vec 3 "Sending %s" (match-string 1))
2998 (tramp-enter-password proc)
2999 ;; Hide password prompt.
3000 (narrow-to-region (point-max) (point-max))))
00d6fd04
MA
3001
3002(defun tramp-action-succeed (proc vec)
ac474af1 3003 "Signal success in finding shell prompt."
ac474af1
KG
3004 (throw 'tramp-action 'ok))
3005
00d6fd04 3006(defun tramp-action-permission-denied (proc vec)
ac474af1 3007 "Signal permission denied."
00d6fd04 3008 (kill-process proc)
ac474af1
KG
3009 (throw 'tramp-action 'permission-denied))
3010
00d6fd04 3011(defun tramp-action-yesno (proc vec)
3cdaec13
KG
3012 "Ask the user for confirmation using `yes-or-no-p'.
3013Send \"yes\" to remote process on confirmation, abort otherwise.
3014See also `tramp-action-yn'."
ac474af1 3015 (save-window-excursion
00d6fd04
MA
3016 (let ((enable-recursive-minibuffers t))
3017 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3018 (unless (yes-or-no-p (match-string 0))
3019 (kill-process proc)
3020 (throw 'tramp-action 'permission-denied))
3021 (with-current-buffer (tramp-get-connection-buffer vec)
3022 (tramp-message vec 6 "\n%s" (buffer-string)))
3023 (tramp-send-string vec "yes"))))
3024
3025(defun tramp-action-yn (proc vec)
3cdaec13
KG
3026 "Ask the user for confirmation using `y-or-n-p'.
3027Send \"y\" to remote process on confirmation, abort otherwise.
3028See also `tramp-action-yesno'."
3029 (save-window-excursion
00d6fd04
MA
3030 (let ((enable-recursive-minibuffers t))
3031 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3032 (unless (y-or-n-p (match-string 0))
3033 (kill-process proc)
3034 (throw 'tramp-action 'permission-denied))
3035 (with-current-buffer (tramp-get-connection-buffer vec)
3036 (tramp-message vec 6 "\n%s" (buffer-string)))
3037 (tramp-send-string vec "y"))))
3038
3039(defun tramp-action-terminal (proc vec)
487f4fb7
KG
3040 "Tell the remote host which terminal type to use.
3041The terminal type can be configured with `tramp-terminal-type'."
00d6fd04 3042 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
7e780ff1
MA
3043 (with-current-buffer (tramp-get-connection-buffer vec)
3044 (tramp-message vec 6 "\n%s" (buffer-string)))
00d6fd04 3045 (tramp-send-string vec tramp-terminal-type))
487f4fb7 3046
00d6fd04 3047(defun tramp-action-process-alive (proc vec)
a94d821f 3048 "Check, whether a process has finished."
00d6fd04 3049 (unless (memq (process-status proc) '(run open))
19a87064
MA
3050 (throw 'tramp-action 'process-died)))
3051
00d6fd04 3052(defun tramp-action-out-of-band (proc vec)
a94d821f 3053 "Check, whether an out-of-band copy has finished."
00d6fd04
MA
3054 (cond ((and (memq (process-status proc) '(stop exit))
3055 (zerop (process-exit-status proc)))
3056 (tramp-message vec 3 "Process has finished.")
38c65fca 3057 (throw 'tramp-action 'ok))
00d6fd04
MA
3058 ((or (and (memq (process-status proc) '(stop exit))
3059 (not (zerop (process-exit-status proc))))
3060 (memq (process-status proc) '(signal)))
01917a18
MA
3061 ;; `scp' could have copied correctly, but set modes could have failed.
3062 ;; This can be ignored.
00d6fd04
MA
3063 (with-current-buffer (process-buffer proc)
3064 (goto-char (point-min))
3065 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3066 (progn
3067 (tramp-message vec 5 "'set mode' error ignored.")
3068 (tramp-message vec 3 "Process has finished.")
3069 (throw 'tramp-action 'ok))
3070 (tramp-message vec 3 "Process has died.")
3071 (throw 'tramp-action 'process-died))))
38c65fca
KG
3072 (t nil)))
3073
4a93e698 3074;;; Functions for processing the actions:
ac474af1 3075
00d6fd04 3076(defun tramp-process-one-action (proc vec actions)
ac474af1 3077 "Wait for output from the shell and perform one action."
00d6fd04 3078 (let (found todo item pattern action)
e6466697 3079 (while (not found)
00d6fd04
MA
3080 ;; Reread output once all actions have been performed.
3081 ;; Obviously, the output was not complete.
3082 (tramp-accept-process-output proc 1)
e6466697
MA
3083 (setq todo actions)
3084 (while todo
e6466697 3085 (setq item (pop todo))
95d610cb 3086 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
e6466697 3087 (setq action (nth 1 item))
00d6fd04
MA
3088 (tramp-message
3089 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3090 (when (tramp-check-for-regexp proc pattern)
3091 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3092 (setq found (funcall action proc vec)))))
e6466697
MA
3093 found))
3094
00d6fd04 3095(defun tramp-process-actions (proc vec actions &optional timeout)
e6466697 3096 "Perform actions until success or TIMEOUT."
9e021389 3097 ;; Preserve message for `progress-reporter'.
6139f995 3098 (tramp-compat-with-temp-message ""
9e021389
MA
3099 ;; Enable auth-source and password-cache.
3100 (tramp-set-connection-property vec "first-password-request" t)
158d5945
MA
3101 (save-restriction
3102 (let (exit)
3103 (while (not exit)
3104 (tramp-message proc 3 "Waiting for prompts from remote shell")
3105 (setq exit
3106 (catch 'tramp-action
3107 (if timeout
3108 (with-timeout (timeout)
3109 (tramp-process-one-action proc vec actions))
3110 (tramp-process-one-action proc vec actions)))))
3111 (with-current-buffer (tramp-get-connection-buffer vec)
3112 (widen)
3113 (tramp-message vec 6 "\n%s" (buffer-string)))
3114 (unless (eq exit 'ok)
3115 (tramp-clear-passwd vec)
3116 (tramp-error-with-buffer
3117 nil vec 'file-error
3118 (cond
3119 ((eq exit 'permission-denied) "Permission denied")
3120 ((eq exit 'process-died) "Process died")
3121 (t "Login failed"))))))))
fb7933a3 3122
4a93e698 3123:;; Utility functions:
fb7933a3 3124
00d6fd04 3125(defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
d2a2c17f
MA
3126 "Like `accept-process-output' for Tramp processes.
3127This is needed in order to hide `last-coding-system-used', which is set
3128for process communication also."
00d6fd04
MA
3129 (with-current-buffer (process-buffer proc)
3130 (tramp-message proc 10 "%s %s" proc (process-status proc))
3131 (let (buffer-read-only last-coding-system-used)
3132 ;; Under Windows XP, accept-process-output doesn't return
3133 ;; sometimes. So we add an additional timeout.
3134 (with-timeout ((or timeout 1))
3135 (accept-process-output proc timeout timeout-msecs)))
3136 (tramp-message proc 10 "\n%s" (buffer-string))))
3137
3138(defun tramp-check-for-regexp (proc regexp)
a94d821f 3139 "Check, whether REGEXP is contained in process buffer of PROC.
00d6fd04
MA
3140Erase echoed commands if exists."
3141 (with-current-buffer (process-buffer proc)
3142 (goto-char (point-min))
674da028 3143
00d6fd04
MA
3144 ;; Check whether we need to remove echo output.
3145 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3146 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3147 (let ((begin (match-beginning 0)))
3148 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3149 ;; Discard echo from remote output.
3150 (tramp-set-connection-property proc "check-remote-echo" nil)
3151 (tramp-message proc 5 "echo-mark found")
b533bc97 3152 (forward-line 1)
00d6fd04
MA
3153 (delete-region begin (point))
3154 (goto-char (point-min)))))
674da028 3155
68712eb6
MA
3156 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3157 ;; Sometimes, the echo string is suppressed on the remote side.
3158 (not (string-equal
0d5852cf
MA
3159 (tramp-compat-funcall
3160 'substring-no-properties tramp-echo-mark-marker
68712eb6 3161 0 (min tramp-echo-mark-marker-length (1- (point-max))))
0d5852cf
MA
3162 (tramp-compat-funcall
3163 'buffer-substring-no-properties
68712eb6 3164 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
70c11b0b 3165 ;; No echo to be handled, now we can look for the regexp.
674da028 3166 (goto-char (point-min))
00d6fd04 3167 (re-search-forward regexp nil t))))
d2a2c17f 3168
fb7933a3
KG
3169(defun tramp-wait-for-regexp (proc timeout regexp)
3170 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3171Expects the output of PROC to be sent to the current buffer. Returns
3172the string that matched, or nil. Waits indefinitely if TIMEOUT is
3173nil."
00d6fd04
MA
3174 (with-current-buffer (process-buffer proc)
3175 (let ((found (tramp-check-for-regexp proc regexp))
3176 (start-time (current-time)))
3177 (cond (timeout
3178 ;; Work around a bug in XEmacs 21, where the timeout
3179 ;; expires faster than it should. This degenerates
3180 ;; to polling for buggy XEmacsen, but oh, well.
3181 (while (and (not found)
3182 (< (tramp-time-diff (current-time) start-time)
3183 timeout))
3184 (with-timeout (timeout)
3185 (while (not found)
3186 (tramp-accept-process-output proc 1)
3187 (unless (memq (process-status proc) '(run open))
3188 (tramp-error-with-buffer
3189 nil proc 'file-error "Process has died"))
3190 (setq found (tramp-check-for-regexp proc regexp))))))
3191 (t
3192 (while (not found)
3193 (tramp-accept-process-output proc 1)
3194 (unless (memq (process-status proc) '(run open))
3195 (tramp-error-with-buffer
3196 nil proc 'file-error "Process has died"))
3197 (setq found (tramp-check-for-regexp proc regexp)))))
3198 (tramp-message proc 6 "\n%s" (buffer-string))
fb7933a3 3199 (when (not found)
00d6fd04
MA
3200 (if timeout
3201 (tramp-error
3202 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3203 regexp timeout)
3204 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3205 found)))
fb7933a3 3206
7e780ff1
MA
3207;; We don't call `tramp-send-string' in order to hide the password
3208;; from the debug buffer, and because end-of-line handling of the
3209;; string.
3210(defun tramp-enter-password (proc)
00d6fd04
MA
3211 "Prompt for a password and send it to the remote end."
3212 (process-send-string
7e780ff1
MA
3213 proc (concat (tramp-read-passwd proc)
3214 (or (tramp-get-method-parameter
3215 tramp-current-method
3216 'tramp-password-end-of-line)
3217 tramp-default-password-end-of-line))))
00d6fd04 3218
7432277c
KG
3219;; It seems that Tru64 Unix does not like it if long strings are sent
3220;; to it in one go. (This happens when sending the Perl
3221;; `file-attributes' implementation, for instance.) Therefore, we
27e813fe 3222;; have this function which sends the string in chunks.
00d6fd04
MA
3223(defun tramp-send-string (vec string)
3224 "Send the STRING via connection VEC.
7432277c
KG
3225
3226The STRING is expected to use Unix line-endings, but the lines sent to
3227the remote host use line-endings as defined in the variable
00d6fd04
MA
3228`tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3229 (let* ((p (tramp-get-connection-process vec))
3230 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3231 (unless p
3232 (tramp-error
3233 vec 'file-error "Can't send string to remote host -- not logged in"))
3234 (tramp-set-connection-property p "last-cmd-time" (current-time))
3235 (tramp-message vec 10 "%s" string)
3236 (with-current-buffer (tramp-get-connection-buffer vec)
3237 ;; Clean up the buffer. We cannot call `erase-buffer' because
3238 ;; narrowing might be in effect.
3239 (let (buffer-read-only) (delete-region (point-min) (point-max)))
27e813fe 3240 ;; Replace "\n" by `tramp-rsh-end-of-line'.
00d6fd04
MA
3241 (setq string
3242 (mapconcat 'identity
70c11b0b 3243 (tramp-compat-split-string string "\n")
00d6fd04
MA
3244 tramp-rsh-end-of-line))
3245 (unless (or (string= string "")
3246 (string-equal (substring string -1) tramp-rsh-end-of-line))
3247 (setq string (concat string tramp-rsh-end-of-line)))
27e813fe 3248 ;; Send the string.
00d6fd04
MA
3249 (if (and chunksize (not (zerop chunksize)))
3250 (let ((pos 0)
3251 (end (length string)))
3252 (while (< pos end)
3253 (tramp-message
3254 vec 10 "Sending chunk from %s to %s"
3255 pos (min (+ pos chunksize) end))
3256 (process-send-string
3257 p (substring string pos (min (+ pos chunksize) end)))
3258 (setq pos (+ pos chunksize))))
3259 (process-send-string p string)))))
fb7933a3 3260
ce3f516f 3261(defun tramp-get-inode (vec)
00d6fd04
MA
3262 "Returns the virtual inode number.
3263If it doesn't exist, generate a new one."
ce3f516f
MA
3264 (let ((string (tramp-make-tramp-file-name
3265 (tramp-file-name-method vec)
3266 (tramp-file-name-user vec)
3267 (tramp-file-name-host vec)
3268 "")))
00d6fd04
MA
3269 (unless (assoc string tramp-inodes)
3270 (add-to-list 'tramp-inodes
3271 (list string (length tramp-inodes))))
3272 (nth 1 (assoc string tramp-inodes))))
3273
3274(defun tramp-get-device (vec)
c82c5727
LH
3275 "Returns the virtual device number.
3276If it doesn't exist, generate a new one."
00d6fd04
MA
3277 (let ((string (tramp-make-tramp-file-name
3278 (tramp-file-name-method vec)
3279 (tramp-file-name-user vec)
3280 (tramp-file-name-host vec)
3281 "")))
c82c5727
LH
3282 (unless (assoc string tramp-devices)
3283 (add-to-list 'tramp-devices
3284 (list string (length tramp-devices))))
b946a456 3285 (cons -1 (nth 1 (assoc string tramp-devices)))))
fb7933a3 3286
00d6fd04 3287(defun tramp-equal-remote (file1 file2)
a94d821f 3288 "Check, whether the remote parts of FILE1 and FILE2 are identical.
00d6fd04
MA
3289The check depends on method, user and host name of the files. If
3290one of the components is missing, the default values are used.
3291The local file name parts of FILE1 and FILE2 are not taken into
3292account.
fb7933a3 3293
00d6fd04
MA
3294Example:
3295
3296 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3297
3298would yield `t'. On the other hand, the following check results in nil:
3299
3300 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
9e6ab520
MA
3301 (and (stringp (file-remote-p file1))
3302 (stringp (file-remote-p file2))
94be87e8 3303 (string-equal (file-remote-p file1) (file-remote-p file2))))
00d6fd04 3304
00d6fd04 3305(defun tramp-get-method-parameter (method param)
c951aecb 3306 "Return the method parameter PARAM.
6a29a838 3307If the `tramp-methods' entry does not exist, return nil."
00d6fd04
MA
3308 (let ((entry (assoc param (assoc method tramp-methods))))
3309 (when entry (cadr entry))))
90f8dc03 3310
4a93e698
MA
3311(defun tramp-mode-string-to-int (mode-string)
3312 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3313 (let* (case-fold-search
3314 (mode-chars (string-to-vector mode-string))
3315 (owner-read (aref mode-chars 1))
3316 (owner-write (aref mode-chars 2))
3317 (owner-execute-or-setid (aref mode-chars 3))
3318 (group-read (aref mode-chars 4))
3319 (group-write (aref mode-chars 5))
3320 (group-execute-or-setid (aref mode-chars 6))
3321 (other-read (aref mode-chars 7))
3322 (other-write (aref mode-chars 8))
3323 (other-execute-or-sticky (aref mode-chars 9)))
3324 (save-match-data
3325 (logior
3326 (cond
3327 ((char-equal owner-read ?r) (tramp-compat-octal-to-decimal "00400"))
3328 ((char-equal owner-read ?-) 0)
3329 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3330 (cond
3331 ((char-equal owner-write ?w) (tramp-compat-octal-to-decimal "00200"))
3332 ((char-equal owner-write ?-) 0)
3333 (t (error "Third char `%c' must be one of `w-'" owner-write)))
3334 (cond
3335 ((char-equal owner-execute-or-setid ?x)
3336 (tramp-compat-octal-to-decimal "00100"))
3337 ((char-equal owner-execute-or-setid ?S)
3338 (tramp-compat-octal-to-decimal "04000"))
3339 ((char-equal owner-execute-or-setid ?s)
3340 (tramp-compat-octal-to-decimal "04100"))
3341 ((char-equal owner-execute-or-setid ?-) 0)
3342 (t (error "Fourth char `%c' must be one of `xsS-'"
3343 owner-execute-or-setid)))
3344 (cond
3345 ((char-equal group-read ?r) (tramp-compat-octal-to-decimal "00040"))
3346 ((char-equal group-read ?-) 0)
3347 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
3348 (cond
3349 ((char-equal group-write ?w) (tramp-compat-octal-to-decimal "00020"))
3350 ((char-equal group-write ?-) 0)
3351 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
3352 (cond
3353 ((char-equal group-execute-or-setid ?x)
3354 (tramp-compat-octal-to-decimal "00010"))
3355 ((char-equal group-execute-or-setid ?S)
3356 (tramp-compat-octal-to-decimal "02000"))
3357 ((char-equal group-execute-or-setid ?s)
3358 (tramp-compat-octal-to-decimal "02010"))
3359 ((char-equal group-execute-or-setid ?-) 0)
3360 (t (error "Seventh char `%c' must be one of `xsS-'"
3361 group-execute-or-setid)))
3362 (cond
3363 ((char-equal other-read ?r)
3364 (tramp-compat-octal-to-decimal "00004"))
3365 ((char-equal other-read ?-) 0)
3366 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
3367 (cond
3368 ((char-equal other-write ?w) (tramp-compat-octal-to-decimal "00002"))
3369 ((char-equal other-write ?-) 0)
3370 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
3371 (cond
3372 ((char-equal other-execute-or-sticky ?x)
3373 (tramp-compat-octal-to-decimal "00001"))
3374 ((char-equal other-execute-or-sticky ?T)
3375 (tramp-compat-octal-to-decimal "01000"))
3376 ((char-equal other-execute-or-sticky ?t)
3377 (tramp-compat-octal-to-decimal "01001"))
3378 ((char-equal other-execute-or-sticky ?-) 0)
3379 (t (error "Tenth char `%c' must be one of `xtT-'"
3380 other-execute-or-sticky)))))))
3381
3382(defun tramp-local-host-p (vec)
3383 "Return t if this points to the local host, nil otherwise."
3384 ;; We cannot use `tramp-file-name-real-host'. A port is an
3385 ;; indication for an ssh tunnel or alike.
3386 (let ((host (tramp-file-name-host vec)))
3387 (and
3388 (stringp host)
3389 (string-match tramp-local-host-regexp host)
3390 ;; The method shall be applied to one of the shell file name
3391 ;; handler. `tramp-local-host-p' is also called for "smb" and
3392 ;; alike, where it must fail.
3393 (tramp-get-method-parameter
3394 (tramp-file-name-method vec) 'tramp-login-program)
3395 ;; The local temp directory must be writable for the other user.
3396 (file-writable-p
3397 (tramp-make-tramp-file-name
3398 (tramp-file-name-method vec)
3399 (tramp-file-name-user vec)
3400 host
3401 (tramp-compat-temporary-file-directory)))
3402 ;; On some systems, chown runs only for root.
3403 (or (zerop (user-uid))
3404 ;; This is defined in tramp-sh.el. Let's assume this is
3405 ;; loaded already.
3406 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
3407
3408(defun tramp-make-tramp-temp-file (vec)
3409 "Create a temporary file on the remote host identified by VEC.
3410Return the local name of the temporary file."
3411 (let ((prefix
3412 (tramp-make-tramp-file-name
3413 (tramp-file-name-method vec)
3414 (tramp-file-name-user vec)
3415 (tramp-file-name-host vec)
3416 (tramp-drop-volume-letter
3417 (expand-file-name
3418 tramp-temp-name-prefix
3419 ;; This is defined in tramp-sh.el. Let's assume this is
3420 ;; loaded already.
3421 (tramp-compat-funcall 'tramp-get-remote-tmpdir vec)))))
3422 result)
3423 (while (not result)
3424 ;; `make-temp-file' would be the natural choice for
3425 ;; implementation. But it calls `write-region' internally,
3426 ;; which also needs a temporary file - we would end in an
3427 ;; infinite loop.
3428 (setq result (make-temp-name prefix))
3429 (if (file-exists-p result)
3430 (setq result nil)
3431 ;; This creates the file by side effect.
3432 (set-file-times result)
3433 (set-file-modes result (tramp-compat-octal-to-decimal "0700"))))
3434
3435 ;; Return the local part.
3436 (with-parsed-tramp-file-name result nil localname)))
fb7933a3 3437
4a93e698
MA
3438(defun tramp-delete-temp-file-function ()
3439 "Remove temporary files related to current buffer."
3440 (when (stringp tramp-temp-buffer-file-name)
3441 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
3442
3443(add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
3444(add-hook 'tramp-cache-unload-hook
3445 (lambda ()
3446 (remove-hook 'kill-buffer-hook
3447 'tramp-delete-temp-file-function)))
3448
3449;;; Auto saving to a special directory:
c1105d05
MA
3450
3451(unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
3452 (defadvice make-auto-save-file-name
3453 (around tramp-advice-make-auto-save-file-name () activate)
03c1ad43 3454 "Invoke `tramp-*-handle-make-auto-save-file-name' for Tramp files."
b533bc97 3455 (if (tramp-tramp-file-p (buffer-file-name))
7f49fe46
MA
3456 ;; We cannot call `tramp-handle-make-auto-save-file-name'
3457 ;; directly, because this would bypass the locking mechanism.
3458 (setq ad-return-value
3459 (tramp-file-name-handler 'make-auto-save-file-name))
a69c01a0 3460 ad-do-it))
191bb792
MA
3461 (add-hook
3462 'tramp-unload-hook
3463 (lambda ()
3464 (ad-remove-advice
3465 'make-auto-save-file-name
d7ec1df7
MA
3466 'around 'tramp-advice-make-auto-save-file-name)
3467 (ad-activate 'make-auto-save-file-name))))
fb7933a3 3468
b533bc97
MA
3469;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
3470;; umask. This is a security threat.
414da5ab
MA
3471
3472(defun tramp-set-auto-save-file-modes ()
3473 "Set permissions of autosaved remote files to the original permissions."
3474 (let ((bfn (buffer-file-name)))
b533bc97 3475 (when (and (tramp-tramp-file-p bfn)
b50dd0d2 3476 (buffer-modified-p)
414da5ab 3477 (stringp buffer-auto-save-file-name)
340b8d4f
MA
3478 (not (equal bfn buffer-auto-save-file-name)))
3479 (unless (file-exists-p buffer-auto-save-file-name)
3480 (write-region "" nil buffer-auto-save-file-name))
3481 ;; Permissions should be set always, because there might be an old
3482 ;; auto-saved file belonging to another original file. This could
3483 ;; be a security threat.
0f34aa77
MA
3484 (set-file-modes
3485 buffer-auto-save-file-name
3486 (or (file-modes bfn) (tramp-compat-octal-to-decimal "0600"))))))
414da5ab 3487
b533bc97
MA
3488(unless (and (featurep 'xemacs)
3489 (= emacs-major-version 21)
3490 (> emacs-minor-version 4))
a69c01a0
MA
3491 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
3492 (add-hook 'tramp-unload-hook
aa485f7c
MA
3493 (lambda ()
3494 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
414da5ab 3495
fb7933a3
KG
3496(defun tramp-subst-strs-in-string (alist string)
3497 "Replace all occurrences of the string FROM with TO in STRING.
3498ALIST is of the form ((FROM . TO) ...)."
3499 (save-match-data
3500 (while alist
3501 (let* ((pr (car alist))
3502 (from (car pr))
3503 (to (cdr pr)))
3504 (while (string-match (regexp-quote from) string)
3505 (setq string (replace-match to t t string)))
3506 (setq alist (cdr alist))))
3507 string))
3508
4a93e698 3509;;; Compatibility functions section:
fb7933a3 3510
00d6fd04 3511(defun tramp-read-passwd (proc &optional prompt)
fb7933a3 3512 "Read a password from user (compat function).
5615d63f 3513Consults the auth-source package.
5ec2cc41 3514Invokes `password-read' if available, `read-passwd' else."
00d6fd04
MA
3515 (let* ((key (tramp-make-tramp-file-name
3516 tramp-current-method tramp-current-user
3517 tramp-current-host ""))
3518 (pw-prompt
3519 (or prompt
3520 (with-current-buffer (process-buffer proc)
3521 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3522 (format "%s for %s " (capitalize (match-string 1)) key)))))
7540f029
MA
3523 (with-parsed-tramp-file-name key nil
3524 (prog1
3525 (or
3526 ;; See if auth-sources contains something useful, if it's bound.
3527 (and (boundp 'auth-sources)
3528 (tramp-get-connection-property v "first-password-request" nil)
3529 ;; Try with Tramp's current method.
0d5852cf
MA
3530 (tramp-compat-funcall
3531 'auth-source-user-or-password
3532 "password" tramp-current-host tramp-current-method))
7540f029
MA
3533 ;; Try the password cache.
3534 (when (functionp 'password-read)
3535 (unless (tramp-get-connection-property
3536 v "first-password-request" nil)
0d5852cf 3537 (tramp-compat-funcall 'password-cache-remove key))
7540f029 3538 (let ((password
0d5852cf
MA
3539 (tramp-compat-funcall 'password-read pw-prompt key)))
3540 (tramp-compat-funcall 'password-cache-add key password)
7540f029
MA
3541 password))
3542 ;; Else, get the password interactively.
3543 (read-passwd pw-prompt))
3544 (tramp-set-connection-property v "first-password-request" nil)))))
00d6fd04 3545
9c13938d
MA
3546(defun tramp-clear-passwd (vec)
3547 "Clear password cache for connection related to VEC."
0d5852cf
MA
3548 (tramp-compat-funcall
3549 'password-cache-remove
3550 (tramp-make-tramp-file-name
3551 (tramp-file-name-method vec)
3552 (tramp-file-name-user vec)
3553 (tramp-file-name-host vec)
3554 "")))
00d6fd04
MA
3555
3556;; Snarfed code from time-date.el and parse-time.el
3557
3558(defconst tramp-half-a-year '(241 17024)
3559"Evaluated by \"(days-to-time 183)\".")
3560
3561(defconst tramp-parse-time-months
3562 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
3563 ("apr" . 4) ("may" . 5) ("jun" . 6)
3564 ("jul" . 7) ("aug" . 8) ("sep" . 9)
3565 ("oct" . 10) ("nov" . 11) ("dec" . 12))
3566 "Alist mapping month names to integers.")
3567
3568(defun tramp-time-less-p (t1 t2)
3569 "Say whether time value T1 is less than time value T2."
3570 (unless t1 (setq t1 '(0 0)))
3571 (unless t2 (setq t2 '(0 0)))
3572 (or (< (car t1) (car t2))
3573 (and (= (car t1) (car t2))
3574 (< (nth 1 t1) (nth 1 t2)))))
3575
3576(defun tramp-time-subtract (t1 t2)
3577 "Subtract two time values.
3578Return the difference in the format of a time value."
3579 (unless t1 (setq t1 '(0 0)))
3580 (unless t2 (setq t2 '(0 0)))
3581 (let ((borrow (< (cadr t1) (cadr t2))))
3582 (list (- (car t1) (car t2) (if borrow 1 0))
3583 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
fb7933a3
KG
3584
3585(defun tramp-time-diff (t1 t2)
3586 "Return the difference between the two times, in seconds.
1a762140 3587T1 and T2 are time values (as returned by `current-time' for example)."
ea9d1443
KG
3588 (cond ((and (fboundp 'subtract-time)
3589 (fboundp 'float-time))
0d5852cf
MA
3590 (tramp-compat-funcall
3591 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
ea9d1443
KG
3592 ((and (fboundp 'subtract-time)
3593 (fboundp 'time-to-seconds))
0d5852cf
MA
3594 (tramp-compat-funcall
3595 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
fb7933a3 3596 ((fboundp 'itimer-time-difference)
0d5852cf
MA
3597 (tramp-compat-funcall
3598 'itimer-time-difference
3599 (if (< (length t1) 3) (append t1 '(0)) t1)
3600 (if (< (length t2) 3) (append t2 '(0)) t2)))
fb7933a3 3601 (t
00d6fd04 3602 (let ((time (tramp-time-subtract t1 t2)))
ea9d1443
KG
3603 (+ (* (car time) 65536.0)
3604 (cadr time)
3605 (/ (or (nth 2 time) 0) 1000000.0))))))
fb7933a3 3606
fb7933a3
KG
3607;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
3608;; does not deal well with newline characters. Newline is replaced by
3609;; backslash newline. But if, say, the string `a backslash newline b'
3610;; is passed to a shell, the shell will expand this into "ab",
3611;; completely omitting the newline. This is not what was intended.
3612;; It does not appear to be possible to make the function
3613;; `shell-quote-argument' work with newlines without making it
3614;; dependent on the shell used. But within this package, we know that
3615;; we will always use a Bourne-like shell, so we use an approach which
3616;; groks newlines.
3617;;
3618;; The approach is simple: we call `shell-quote-argument', then
3619;; massage the newline part of the result.
3620;;
3621;; This function should produce a string which is grokked by a Unix
3622;; shell, even if the Emacs is running on Windows. Since this is the
3623;; kludges section, we bind `system-type' in such a way that
3624;; `shell-quote-arguments' behaves as if on Unix.
3625;;
3626;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
3627;; function to work with Bourne-like shells.
3628;;
3629;; CCC: This function should be rewritten so that
3630;; `shell-quote-argument' is not used. This way, we are safe from
3631;; changes in `shell-quote-argument'.
0f34aa77 3632;;;###tramp-autoload
fb7933a3
KG
3633(defun tramp-shell-quote-argument (s)
3634 "Similar to `shell-quote-argument', but groks newlines.
3635Only works for Bourne-like shells."
3636 (let ((system-type 'not-windows))
3637 (save-match-data
3638 (let ((result (shell-quote-argument s))
3639 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
3640 (when (and (>= (length result) 2)
3641 (string= (substring result 0 2) "\\~"))
3642 (setq result (substring result 1)))
3643 (while (string-match nl result)
3644 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
3645 t t result)))
3646 result))))
3647
a69c01a0
MA
3648;; Checklist for `tramp-unload-hook'
3649;; - Unload all `tramp-*' packages
3650;; - Reset `file-name-handler-alist'
3651;; - Cleanup hooks where Tramp functions are in
3652;; - Cleanup advised functions
3653;; - Cleanup autoloads
3654;;;###autoload
3655(defun tramp-unload-tramp ()
08b1eb21 3656 "Discard Tramp from loading remote files."
a69c01a0 3657 (interactive)
a69c01a0 3658 ;; ange-ftp settings must be enabled.
0d5852cf 3659 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
0f34aa77 3660 ;; Maybe it's not loaded yet.
03c1ad43 3661 (ignore-errors (unload-feature 'tramp 'force)))
ccb4a481 3662
fb7933a3
KG
3663(provide 'tramp)
3664
fb7933a3
KG
3665;;; TODO:
3666
fb7933a3 3667;; * Rewrite `tramp-shell-quote-argument' to abstain from using
b1d06e75 3668;; `shell-quote-argument'.
fb7933a3
KG
3669;; * In Emacs 21, `insert-directory' shows total number of bytes used
3670;; by the files in that directory. Add this here.
3671;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
3672;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
fb7933a3 3673;; * abbreviate-file-name
8e754ea2 3674;; * Better error checking. At least whenever we see something
fb7933a3
KG
3675;; strange when doing zerop, we should kill the process and start
3676;; again. (Greg Stark)
3cdaec13 3677;; * Username and hostname completion.
6c4e47fa 3678;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8daea7fc 3679;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
16674e4f 3680;; Code is nearly identical.
00d6fd04 3681;; * Make `tramp-default-user' obsolete.
3e2fa353
MA
3682;; * Implement a general server-local-variable mechanism, as there are
3683;; probably other variables that need different values for different
3684;; servers too. The user could then configure a variable (such as
3685;; tramp-server-local-variable-alist) to define any such variables
3686;; that they need to, which would then be let bound as appropriate
6e4f5731 3687;; in tramp functions. (Jason Rumney)
7e5686f0
MA
3688;; * IMHO, it's a drawback that currently Tramp doesn't support
3689;; Unicode in Dired file names by default. Is it possible to
3690;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
3691;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
6e4f5731 3692;; expects only English messages? (Juri Linkov)
7e5686f0 3693;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
44ffae96
MA
3694;; * I was wondering it it would be possible to use tramp even if I'm
3695;; actually using sshfs. But when I launch a command I would like
3696;; to get it executed on the remote machine where the files really
3697;; are. (Andrea Crotti)
3698;; * Run emerge on two remote files. Bug is described here:
3699;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
3700;; (Bug#6850)
fb7933a3
KG
3701
3702;; Functions for file-name-handler-alist:
3703;; diff-latest-backup-file -- in diff.el
fb7933a3
KG
3704
3705;;; tramp.el ends here
57671b72
MA
3706
3707;; Local Variables:
3708;; mode: Emacs-Lisp
3709;; coding: utf-8
3710;; End: