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