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