1 ;;; tramp-sh.el --- Tramp access functions for (s)sh-like connections
3 ;; Copyright (C) 1998-2015 Free Software Foundation, Inc.
5 ;; (copyright statements below in code to be updated with the above notice)
7 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
8 ;; Michael Albinus <michael.albinus@gmx.de>
9 ;; Keywords: comm, processes
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 ;; Pacify byte-compiler.
35 (defvar directory-sep-char)
36 (defvar tramp-gw-tunnel-method)
37 (defvar tramp-gw-socks-method)
38 (defvar vc-handled-backends)
39 (defvar vc-bzr-program)
40 (defvar vc-git-program)
41 (defvar vc-hg-program)
43 (defcustom tramp-inline-compress-start-size 4096
44 "The minimum size of compressing where inline transfer.
45 When inline transfer, compress transferred data of file
46 whose size is this value or above (up to `tramp-copy-size-limit').
47 If it is nil, no compression at all will be applied."
49 :type '(choice (const nil) integer))
51 (defcustom tramp-copy-size-limit 10240
52 "The maximum file size where inline copying is preferred over an \
54 If it is nil, out-of-the-band copy will be used without a check."
56 :type '(choice (const nil) integer))
59 (defcustom tramp-terminal-type "dumb"
60 "Value of TERM environment variable for logging in to remote host.
61 Because Tramp wants to parse the output of the remote shell, it is easily
62 confused by ANSI color escape sequences and suchlike. Often, shell init
63 files conditionalize this setup based on the TERM environment variable."
68 (defcustom tramp-histfile-override t
69 "When invoking a shell, override the HISTFILE with this value.
70 When setting to a string, it redirects the shell history to that
71 file. Be careful when setting to \"/dev/null\"; this might
72 result in undesired results when using \"bash\" as shell.
74 The value t, the default value, unsets any setting of HISTFILE.
75 If you set this variable to nil, however, the *override* is
76 disabled, so the history will go to the default storage
77 location, e.g. \"$HOME/.sh_history\"."
80 :type '(choice (const :tag "Do not override HISTFILE" nil)
81 (const :tag "Unset HISTFILE" t)
82 (string :tag "Redirect to a file")))
85 (defconst tramp-color-escape-sequence-regexp "\e[[;0-9]+m"
86 "Escape sequences produced by the \"ls\" command.")
88 ;; ksh on OpenBSD 4.5 requires that $PS1 contains a `#' character for
89 ;; root users. It uses the `$' character for other users. In order
90 ;; to guarantee a proper prompt, we use "#$ " for the prompt.
92 (defvar tramp-end-of-output
95 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
96 "String used to recognize end of output.
97 The '$' character at the end is quoted; the string cannot be
98 detected as prompt when being sent on echoing hosts, therefore.")
101 (defconst tramp-initial-end-of-output "#$ "
102 "Prompt when establishing a connection.")
104 (defconst tramp-end-of-heredoc (md5 tramp-end-of-output)
105 "String used to recognize end of heredoc strings.")
107 ;; Initialize `tramp-methods' with the supported methods.
109 (add-to-list 'tramp-methods
111 (tramp-login-program "rsh")
112 (tramp-login-args (("%h") ("-l" "%u")))
113 (tramp-remote-shell "/bin/sh")
114 (tramp-remote-shell-args ("-c"))
115 (tramp-copy-program "rcp")
116 (tramp-copy-args (("-p" "%k") ("-r")))
117 (tramp-copy-keep-date t)
118 (tramp-copy-recursive t)))
120 (add-to-list 'tramp-methods
122 (tramp-login-program "remsh")
123 (tramp-login-args (("%h") ("-l" "%u")))
124 (tramp-remote-shell "/bin/sh")
125 (tramp-remote-shell-args ("-c"))
126 (tramp-copy-program "rcp")
127 (tramp-copy-args (("-p" "%k")))
128 (tramp-copy-keep-date t)))
130 (add-to-list 'tramp-methods
132 (tramp-login-program "ssh")
133 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
134 ("-e" "none") ("%h")))
135 (tramp-async-args (("-q")))
136 (tramp-remote-shell "/bin/sh")
137 (tramp-remote-shell-args ("-c"))
138 (tramp-copy-program "scp")
139 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q") ("-r") ("%c")))
140 (tramp-copy-keep-date t)
141 (tramp-copy-recursive t)
142 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
143 ("-o" "UserKnownHostsFile=/dev/null")
144 ("-o" "StrictHostKeyChecking=no")))
145 (tramp-default-port 22)))
147 (add-to-list 'tramp-methods
149 (tramp-login-program "ssh")
150 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
151 ("-e" "none") ("-t" "-t") ("%h") ("/bin/sh")))
152 (tramp-async-args (("-q")))
153 (tramp-remote-shell "/bin/sh")
154 (tramp-remote-shell-args ("-c"))
155 (tramp-copy-program "scp")
156 (tramp-copy-args (("-P" "%p") ("-p" "%k")
157 ("-q") ("-r") ("%c")))
158 (tramp-copy-keep-date t)
159 (tramp-copy-recursive t)
160 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
161 ("-o" "UserKnownHostsFile=/dev/null")
162 ("-o" "StrictHostKeyChecking=no")))
163 (tramp-default-port 22)))
165 (add-to-list 'tramp-methods
167 (tramp-login-program "ssh")
168 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
169 ("-e" "none") ("%h")))
170 (tramp-async-args (("-q")))
171 (tramp-remote-shell "/bin/sh")
172 (tramp-remote-shell-args ("-c"))
173 (tramp-copy-program "rsync")
174 (tramp-copy-args (("-t" "%k") ("-r")))
175 (tramp-copy-env (("RSYNC_RSH") ("ssh" "%c")))
176 (tramp-copy-keep-date t)
177 (tramp-copy-keep-tmpfile t)
178 (tramp-copy-recursive t)))
180 (add-to-list 'tramp-methods
182 (tramp-login-program "rsh")
183 (tramp-login-args (("%h") ("-l" "%u")))
184 (tramp-remote-shell "/bin/sh")
185 (tramp-remote-shell-args ("-c"))))
187 (add-to-list 'tramp-methods
189 (tramp-login-program "remsh")
190 (tramp-login-args (("%h") ("-l" "%u")))
191 (tramp-remote-shell "/bin/sh")
192 (tramp-remote-shell-args ("-c"))))
194 (add-to-list 'tramp-methods
196 (tramp-login-program "ssh")
197 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
198 ("-e" "none") ("%h")))
199 (tramp-async-args (("-q")))
200 (tramp-remote-shell "/bin/sh")
201 (tramp-remote-shell-args ("-c"))
202 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
203 ("-o" "UserKnownHostsFile=/dev/null")
204 ("-o" "StrictHostKeyChecking=no")))
205 (tramp-default-port 22)))
207 (add-to-list 'tramp-methods
209 (tramp-login-program "ssh")
210 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
211 ("-e" "none") ("-t" "-t") ("%h") ("/bin/sh")))
212 (tramp-async-args (("-q")))
213 (tramp-remote-shell "/bin/sh")
214 (tramp-remote-shell-args ("-c"))
215 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
216 ("-o" "UserKnownHostsFile=/dev/null")
217 ("-o" "StrictHostKeyChecking=no")))
218 (tramp-default-port 22)))
220 (add-to-list 'tramp-methods
222 (tramp-login-program "telnet")
223 (tramp-login-args (("%h") ("%p") ("2>/dev/null")))
224 (tramp-remote-shell "/bin/sh")
225 (tramp-remote-shell-args ("-c"))
226 (tramp-default-port 23)))
228 (add-to-list 'tramp-methods
230 (tramp-login-program "telnet")
231 (tramp-login-args (("%h") ("%p") ("2>/dev/null")))
232 (tramp-remote-shell "/bin/sh")
233 (tramp-remote-shell-args ("-c"))
234 (tramp-copy-program "nc")
235 ;; We use "-v" for better error tracking.
236 (tramp-copy-args (("-w" "1") ("-v") ("%h") ("%r")))
237 (tramp-remote-copy-program "nc")
238 ;; We use "-p" as required for newer busyboxes. For older
239 ;; busybox/nc versions, the value must be (("-l") ("%r")). This
240 ;; can be achieved by tweaking `tramp-connection-properties'.
241 (tramp-remote-copy-args (("-l") ("-p" "%r")))
242 (tramp-default-port 23)))
244 (add-to-list 'tramp-methods
246 (tramp-login-program "su")
247 (tramp-login-args (("-") ("%u")))
248 (tramp-remote-shell "/bin/sh")
249 (tramp-remote-shell-args ("-c"))
250 (tramp-connection-timeout 10)))
252 (add-to-list 'tramp-methods
254 (tramp-login-program "sudo")
255 (tramp-login-args (("-u" "%u") ("-s") ("-H") ("-p" "Password:")))
256 ;; Local $SHELL could be a nasty one, like zsh or fish. Let's override it.
257 (tramp-login-env (("SHELL") ("/bin/sh")))
258 (tramp-remote-shell "/bin/sh")
259 (tramp-remote-shell-args ("-c"))
260 (tramp-connection-timeout 10)))
262 (add-to-list 'tramp-methods
264 (tramp-login-program "ksu")
265 (tramp-login-args (("%u") ("-q")))
266 (tramp-remote-shell "/bin/sh")
267 (tramp-remote-shell-args ("-c"))
268 (tramp-connection-timeout 10)))
270 (add-to-list 'tramp-methods
272 (tramp-login-program "krlogin")
273 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
274 (tramp-remote-shell "/bin/sh")
275 (tramp-remote-shell-args ("-c"))))
277 (add-to-list 'tramp-methods
279 (tramp-login-program "plink")
280 ;; ("%h") must be a single element, see `tramp-compute-multi-hops'.
281 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("-t")
284 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
286 tramp-initial-end-of-output))
288 (tramp-remote-shell "/bin/sh")
289 (tramp-remote-shell-args ("-c"))
290 (tramp-default-port 22)))
292 (add-to-list 'tramp-methods
294 (tramp-login-program "plink")
295 (tramp-login-args (("-load") ("%h") ("-t") ("\"")
297 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
299 tramp-initial-end-of-output))
301 (tramp-remote-shell "/bin/sh")
302 (tramp-remote-shell-args ("-c"))))
304 (add-to-list 'tramp-methods
306 (tramp-login-program "plink")
307 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("-t")
310 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
312 tramp-initial-end-of-output))
314 (tramp-remote-shell "/bin/sh")
315 (tramp-remote-shell-args ("-c"))
316 (tramp-copy-program "pscp")
317 (tramp-copy-args (("-l" "%u") ("-P" "%p") ("-scp") ("-p" "%k")
319 (tramp-copy-keep-date t)
320 (tramp-copy-recursive t)
321 (tramp-default-port 22)))
323 (add-to-list 'tramp-methods
325 (tramp-login-program "plink")
326 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("-t")
329 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
331 tramp-initial-end-of-output))
333 (tramp-remote-shell "/bin/sh")
334 (tramp-remote-shell-args ("-c"))
335 (tramp-copy-program "pscp")
336 (tramp-copy-args (("-l" "%u") ("-P" "%p") ("-sftp") ("-p" "%k")
338 (tramp-copy-keep-date t)
339 (tramp-copy-recursive t)))
341 (add-to-list 'tramp-methods
343 (tramp-login-program "fsh")
344 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
345 (tramp-remote-shell "/bin/sh")
346 (tramp-remote-shell-args ("-i") ("-c"))
347 (tramp-copy-program "fcp")
348 (tramp-copy-args (("-p" "%k")))
349 (tramp-copy-keep-date t)))
352 (add-to-list 'tramp-default-method-alist
353 `(,tramp-local-host-regexp "\\`root\\'" "su"))
356 (add-to-list 'tramp-default-user-alist
357 `(,(concat "\\`" (regexp-opt '("su" "sudo" "ksu")) "\\'")
359 ;; Do not add "ssh" based methods, otherwise ~/.ssh/config would be ignored.
360 ;; Do not add "plink" based methods, they ask interactively for the user.
362 (add-to-list 'tramp-default-user-alist
366 '("rcp" "remcp" "rsh" "telnet" "nc" "krlogin" "fcp"))
368 nil ,(user-login-name)))
371 (defconst tramp-completion-function-alist-rsh
372 '((tramp-parse-rhosts "/etc/hosts.equiv")
373 (tramp-parse-rhosts "~/.rhosts"))
374 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
377 (defconst tramp-completion-function-alist-ssh
378 '((tramp-parse-rhosts "/etc/hosts.equiv")
379 (tramp-parse-rhosts "/etc/shosts.equiv")
380 (tramp-parse-shosts "/etc/ssh_known_hosts")
381 (tramp-parse-sconfig "/etc/ssh_config")
382 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
383 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
384 (tramp-parse-rhosts "~/.rhosts")
385 (tramp-parse-rhosts "~/.shosts")
386 (tramp-parse-shosts "~/.ssh/known_hosts")
387 (tramp-parse-sconfig "~/.ssh/config")
388 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
389 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
390 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
393 (defconst tramp-completion-function-alist-telnet
394 '((tramp-parse-hosts "/etc/hosts"))
395 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
398 (defconst tramp-completion-function-alist-su
399 '((tramp-parse-passwd "/etc/passwd"))
400 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
403 (defconst tramp-completion-function-alist-putty
405 ,(if (memq system-type '(windows-nt))
406 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"
407 "~/.putty/sessions")))
408 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty sessions.")
411 (eval-after-load 'tramp
413 (tramp-set-completion-function "rcp" tramp-completion-function-alist-rsh)
414 (tramp-set-completion-function "remcp" tramp-completion-function-alist-rsh)
415 (tramp-set-completion-function "scp" tramp-completion-function-alist-ssh)
416 (tramp-set-completion-function "scpx" tramp-completion-function-alist-ssh)
417 (tramp-set-completion-function "rsync" tramp-completion-function-alist-ssh)
418 (tramp-set-completion-function "rsh" tramp-completion-function-alist-rsh)
419 (tramp-set-completion-function "remsh" tramp-completion-function-alist-rsh)
420 (tramp-set-completion-function "ssh" tramp-completion-function-alist-ssh)
421 (tramp-set-completion-function "sshx" tramp-completion-function-alist-ssh)
422 (tramp-set-completion-function
423 "telnet" tramp-completion-function-alist-telnet)
424 (tramp-set-completion-function "nc" tramp-completion-function-alist-telnet)
425 (tramp-set-completion-function "su" tramp-completion-function-alist-su)
426 (tramp-set-completion-function "sudo" tramp-completion-function-alist-su)
427 (tramp-set-completion-function "ksu" tramp-completion-function-alist-su)
428 (tramp-set-completion-function
429 "krlogin" tramp-completion-function-alist-rsh)
430 (tramp-set-completion-function "plink" tramp-completion-function-alist-ssh)
431 (tramp-set-completion-function
432 "plinkx" tramp-completion-function-alist-putty)
433 (tramp-set-completion-function "pscp" tramp-completion-function-alist-ssh)
434 (tramp-set-completion-function "psftp" tramp-completion-function-alist-ssh)
435 (tramp-set-completion-function "fcp" tramp-completion-function-alist-ssh)))
437 ;; "getconf PATH" yields:
438 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
439 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
440 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
441 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
444 (defcustom tramp-remote-path
445 '(tramp-default-remote-path "/bin" "/usr/bin" "/sbin" "/usr/sbin"
446 "/usr/local/bin" "/usr/local/sbin" "/local/bin" "/local/freeware/bin"
447 "/local/gnu/bin" "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin"
448 "/opt/bin" "/opt/sbin" "/opt/local/bin")
449 "List of directories to search for executables on remote host.
450 For every remote host, this variable will be set buffer local,
451 keeping the list of existing directories on that host.
453 You can use `~' in this list, but when searching for a shell which groks
454 tilde expansion, all directory names starting with `~' will be ignored.
456 `Default Directories' represent the list of directories given by
457 the command \"getconf PATH\". It is recommended to use this
458 entry on top of this list, because these are the default
459 directories for POSIX compatible commands. On remote hosts which
460 do not offer the getconf command (like cygwin), the value
461 \"/bin:/usr/bin\" is used instead of.
463 `Private Directories' are the settings of the $PATH environment,
464 as given in your `~/.profile'."
466 :type '(repeat (choice
467 (const :tag "Default Directories" tramp-default-remote-path)
468 (const :tag "Private Directories" tramp-own-remote-path)
469 (string :tag "Directory"))))
472 (defcustom tramp-remote-process-environment
473 `("TMOUT=0" "LC_CTYPE=''"
474 ,(format "TERM=%s" tramp-terminal-type)
475 "EMACS=t" ;; Deprecated.
476 ,(format "INSIDE_EMACS='%s,tramp:%s'" emacs-version tramp-version)
477 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH=" "PAGER=\"\""
478 "autocorrect=" "correct=")
479 "List of environment variables to be set on the remote host.
481 Each element should be a string of the form ENVVARNAME=VALUE. An
482 entry ENVVARNAME= disables the corresponding environment variable,
483 which might have been set in the init files like ~/.profile.
485 Special handling is applied to the PATH environment, which should
486 not be set here. Instead, it should be set via `tramp-remote-path'."
489 :type '(repeat string))
491 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
492 "Alist specifying extra arguments to pass to the remote shell.
493 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
494 matching the shell file name and ARGS is a string specifying the
497 This variable is only used when Tramp needs to start up another shell
498 for tilde expansion. The extra arguments should typically prevent the
499 shell from reading its init file."
501 ;; This might be the wrong way to test whether the widget type
502 ;; `alist' is available. Who knows the right way to test it?
503 :type (if (get 'alist 'widget-type)
504 '(alist :key-type string :value-type string)
505 '(repeat (cons string string))))
507 (defconst tramp-actions-before-shell
508 '((tramp-login-prompt-regexp tramp-action-login)
509 (tramp-password-prompt-regexp tramp-action-password)
510 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
511 (shell-prompt-pattern tramp-action-succeed)
512 (tramp-shell-prompt-pattern tramp-action-succeed)
513 (tramp-yesno-prompt-regexp tramp-action-yesno)
514 (tramp-yn-prompt-regexp tramp-action-yn)
515 (tramp-terminal-prompt-regexp tramp-action-terminal)
516 (tramp-process-alive-regexp tramp-action-process-alive))
517 "List of pattern/action pairs.
518 Whenever a pattern matches, the corresponding action is performed.
519 Each item looks like (PATTERN ACTION).
521 The PATTERN should be a symbol, a variable. The value of this
522 variable gives the regular expression to search for. Note that the
523 regexp must match at the end of the buffer, \"\\'\" is implicitly
526 The ACTION should also be a symbol, but a function. When the
527 corresponding PATTERN matches, the ACTION function is called.")
529 (defconst tramp-actions-copy-out-of-band
530 '((tramp-password-prompt-regexp tramp-action-password)
531 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
532 (tramp-copy-failed-regexp tramp-action-permission-denied)
533 (tramp-process-alive-regexp tramp-action-out-of-band))
534 "List of pattern/action pairs.
535 This list is used for copying/renaming with out-of-band methods.
537 See `tramp-actions-before-shell' for more info.")
539 (defconst tramp-uudecode
540 "(echo begin 600 %t; tail -n +2) | uudecode
543 "Shell function to implement `uudecode' to standard output.
544 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
545 for this or `uudecode -p', but some systems don't, and for them
546 we have this shell function.")
548 (defconst tramp-perl-file-truename
551 use Cwd \"realpath\";
554 my ($volume, @dirs) = @_;
555 my $real = realpath(File::Spec->catpath(
556 $volume, File::Spec->catdir(@dirs), \"\"));
558 my ($vol, $dir) = File::Spec->splitpath($real, 1);
559 return ($vol, File::Spec->splitdir($dir));
562 my $last = pop(@dirs);
563 ($volume, @dirs) = recursive($volume, @dirs);
565 return ($volume, @dirs);
569 $result = realpath($ARGV[0]);
571 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
572 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
574 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
577 if ($ARGV[0] =~ /\\/$/) {
578 $result = $result . \"/\";
581 print \"\\\"$result\\\"\\n\";
582 ' \"$1\" 2>/dev/null"
583 "Perl script to produce output suitable for use with `file-truename'
584 on the remote file system.
585 Escape sequence %s is replaced with name of Perl binary.
586 This string is passed to `format', so percent characters need to be doubled.")
588 (defconst tramp-perl-file-name-all-completions
598 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
599 @files = readdir(d); closedir(d);
600 foreach $f (@files) {
601 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
602 if (-d \"$ARGV[0]/$f\") {
611 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
612 "Perl script to produce output suitable for use with
613 `file-name-all-completions' on the remote file system. Escape
614 sequence %s is replaced with name of Perl binary. This string is
615 passed to `format', so percent characters need to be doubled.")
617 ;; Perl script to implement `file-attributes' in a Lisp `read'able
618 ;; output. If you are hacking on this, note that you get *no* output
619 ;; unless this spits out a complete line, including the '\n' at the
621 ;; The device number is returned as "-1", because there will be a virtual
622 ;; device number set in `tramp-sh-handle-file-attributes'.
623 (defconst tramp-perl-file-attributes
625 @stat = lstat($ARGV[0]);
630 if (($stat[2] & 0170000) == 0120000)
632 $type = readlink($ARGV[0]);
633 $type = \"\\\"$type\\\"\";
635 elsif (($stat[2] & 0170000) == 040000)
643 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
644 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
646 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
651 $stat[8] >> 16 & 0xffff,
653 $stat[9] >> 16 & 0xffff,
655 $stat[10] >> 16 & 0xffff,
659 $stat[1] >> 16 & 0xffff,
661 );' \"$1\" \"$2\" 2>/dev/null"
662 "Perl script to produce output suitable for use with `file-attributes'
663 on the remote file system.
664 Escape sequence %s is replaced with name of Perl binary.
665 This string is passed to `format', so percent characters need to be doubled.")
667 (defconst tramp-perl-directory-files-and-attributes
669 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
670 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
671 @list = readdir(DIR);
675 for($i = 0; $i < $n; $i++)
677 $filename = $list[$i];
678 @stat = lstat($filename);
679 if (($stat[2] & 0170000) == 0120000)
681 $type = readlink($filename);
682 $type = \"\\\"$type\\\"\";
684 elsif (($stat[2] & 0170000) == 040000)
692 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
693 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
695 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
701 $stat[8] >> 16 & 0xffff,
703 $stat[9] >> 16 & 0xffff,
705 $stat[10] >> 16 & 0xffff,
709 $stat[1] >> 16 & 0xffff,
711 $stat[0] >> 16 & 0xffff,
714 printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
715 "Perl script implementing `directory-files-attributes' as Lisp `read'able
717 Escape sequence %s is replaced with name of Perl binary.
718 This string is passed to `format', so percent characters need to be doubled.")
720 ;; These two use base64 encoding.
721 (defconst tramp-perl-encode-with-module
722 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
723 "Perl program to use for encoding a file.
724 Escape sequence %s is replaced with name of Perl binary.
725 This string is passed to `format', so percent characters need to be doubled.
726 This implementation requires the MIME::Base64 Perl module to be installed
727 on the remote host.")
729 (defconst tramp-perl-decode-with-module
730 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
731 "Perl program to use for decoding a file.
732 Escape sequence %s is replaced with name of Perl binary.
733 This string is passed to `format', so percent characters need to be doubled.
734 This implementation requires the MIME::Base64 Perl module to be installed
735 on the remote host.")
737 (defconst tramp-perl-encode
739 # This script contributed by Juanma Barranquero <lektu@terra.es>.
740 # Copyright (C) 2002-2015 Free Software Foundation, Inc.
745 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
746 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
750 # We read in chunks of 54 bytes, to generate output lines
751 # of 72 chars (plus end of line)
752 while (read STDIN, $data, 54) {
755 # Only for the last chunk, and only if did not fill the last three-byte packet
757 my $mod = length($data) %% 3;
758 $pad = q(=) x (3 - $mod) if $mod;
761 # Not the fastest method, but it is simple: unpack to binary string, split
762 # by groups of 6 bits and convert back from binary to byte; then map into
763 # the translation table
767 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
771 "Perl program to use for encoding a file.
772 Escape sequence %s is replaced with name of Perl binary.
773 This string is passed to `format', so percent characters need to be doubled.")
775 (defconst tramp-perl-decode
777 # This script contributed by Juanma Barranquero <lektu@terra.es>.
778 # Copyright (C) 2002-2015 Free Software Foundation, Inc.
783 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
784 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
787 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
791 # We are going to accumulate into $pending to accept any line length
792 # (we do not check they are <= 76 chars as the RFC says)
795 while (my $data = <STDIN>) {
798 # If we find one or two =, we have reached the end and
799 # any following data is to be discarded
800 my $finished = $data =~ s/(==?).*/$1/;
803 my $len = length($pending);
804 my $chunk = substr($pending, 0, $len & ~3);
805 $pending = substr($pending, $len & ~3 + 1);
807 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
808 # split in 8-bit chunks and convert back to char.
811 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
815 "Perl program to use for decoding a file.
816 Escape sequence %s is replaced with name of Perl binary.
817 This string is passed to `format', so percent characters need to be doubled.")
819 (defconst tramp-perl-pack
820 "%s -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
821 "Perl program to use for encoding a file.
822 Escape sequence %s is replaced with name of Perl binary.")
824 (defconst tramp-perl-unpack
825 "%s -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"
826 "Perl program to use for decoding a file.
827 Escape sequence %s is replaced with name of Perl binary.")
829 (defconst tramp-vc-registered-read-file-names
832 if %s \"$file\"; then
833 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
835 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
837 if %s \"$file\"; then
838 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
840 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
844 "Script to check existence of VC related files.
845 It must be send formatted with two strings; the tests for file
846 existence, and file readability. Input shall be read via
847 here-document, otherwise the command could exceed maximum length
850 ;; New handlers should be added here.
851 (defconst tramp-sh-file-name-handler-alist
852 '(;; `access-file' performed by default handler.
853 (add-name-to-file . tramp-sh-handle-add-name-to-file)
854 ;; `byte-compiler-base-file-name' performed by default handler.
855 (copy-directory . tramp-sh-handle-copy-directory)
856 (copy-file . tramp-sh-handle-copy-file)
857 (delete-directory . tramp-sh-handle-delete-directory)
858 (delete-file . tramp-sh-handle-delete-file)
859 ;; `diff-latest-backup-file' performed by default handler.
860 (directory-file-name . tramp-handle-directory-file-name)
861 (directory-files . tramp-handle-directory-files)
862 (directory-files-and-attributes
863 . tramp-sh-handle-directory-files-and-attributes)
864 ;; `dired-call-process' performed by default handler.
865 (dired-compress-file . tramp-sh-handle-dired-compress-file)
866 (dired-recursive-delete-directory
867 . tramp-sh-handle-dired-recursive-delete-directory)
868 (dired-uncache . tramp-handle-dired-uncache)
869 (expand-file-name . tramp-sh-handle-expand-file-name)
870 (file-accessible-directory-p . tramp-handle-file-accessible-directory-p)
871 (file-acl . tramp-sh-handle-file-acl)
872 (file-attributes . tramp-sh-handle-file-attributes)
873 (file-directory-p . tramp-sh-handle-file-directory-p)
874 ;; `file-equal-p' performed by default handler.
875 (file-executable-p . tramp-sh-handle-file-executable-p)
876 (file-exists-p . tramp-sh-handle-file-exists-p)
877 ;; `file-in-directory-p' performed by default handler.
878 (file-local-copy . tramp-sh-handle-file-local-copy)
879 (file-modes . tramp-handle-file-modes)
880 (file-name-all-completions . tramp-sh-handle-file-name-all-completions)
881 (file-name-as-directory . tramp-handle-file-name-as-directory)
882 (file-name-completion . tramp-handle-file-name-completion)
883 (file-name-directory . tramp-handle-file-name-directory)
884 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
885 ;; `file-name-sans-versions' performed by default handler.
886 (file-newer-than-file-p . tramp-sh-handle-file-newer-than-file-p)
887 (file-notify-add-watch . tramp-sh-handle-file-notify-add-watch)
888 (file-notify-rm-watch . tramp-handle-file-notify-rm-watch)
889 (file-ownership-preserved-p . tramp-sh-handle-file-ownership-preserved-p)
890 (file-readable-p . tramp-sh-handle-file-readable-p)
891 (file-regular-p . tramp-handle-file-regular-p)
892 (file-remote-p . tramp-handle-file-remote-p)
893 (file-selinux-context . tramp-sh-handle-file-selinux-context)
894 (file-symlink-p . tramp-handle-file-symlink-p)
895 (file-truename . tramp-sh-handle-file-truename)
896 (file-writable-p . tramp-sh-handle-file-writable-p)
897 (find-backup-file-name . tramp-handle-find-backup-file-name)
898 ;; `find-file-noselect' performed by default handler.
899 ;; `get-file-buffer' performed by default handler.
900 (insert-directory . tramp-sh-handle-insert-directory)
901 (insert-file-contents . tramp-handle-insert-file-contents)
902 (insert-file-contents-literally
903 . tramp-sh-handle-insert-file-contents-literally)
904 (load . tramp-handle-load)
905 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
906 (make-directory . tramp-sh-handle-make-directory)
907 (make-symbolic-link . tramp-sh-handle-make-symbolic-link)
908 (process-file . tramp-sh-handle-process-file)
909 (rename-file . tramp-sh-handle-rename-file)
910 (set-file-acl . tramp-sh-handle-set-file-acl)
911 (set-file-modes . tramp-sh-handle-set-file-modes)
912 (set-file-selinux-context . tramp-sh-handle-set-file-selinux-context)
913 (set-file-times . tramp-sh-handle-set-file-times)
914 (set-visited-file-modtime . tramp-sh-handle-set-visited-file-modtime)
915 (shell-command . tramp-handle-shell-command)
916 (start-file-process . tramp-sh-handle-start-file-process)
917 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
918 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
919 (vc-registered . tramp-sh-handle-vc-registered)
920 (verify-visited-file-modtime . tramp-sh-handle-verify-visited-file-modtime)
921 (write-region . tramp-sh-handle-write-region))
922 "Alist of handler functions.
923 Operations not mentioned here will be handled by the normal Emacs functions.")
925 ;; This must be the last entry, because `identity' always matches.
927 (add-to-list 'tramp-foreign-file-name-handler-alist
928 '(identity . tramp-sh-file-name-handler) 'append)
930 ;;; File Name Handler Functions:
932 (defun tramp-sh-handle-make-symbolic-link
933 (filename linkname &optional ok-if-already-exists)
934 "Like `make-symbolic-link' for Tramp files.
935 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
936 the symlink. If LINKNAME is a Tramp file, only the localname component is
937 used as the target of the symlink.
939 If LINKNAME is a Tramp file and the localname component is relative, then
940 it is expanded first, before the localname component is taken. Note that
941 this can give surprising results if the user/host for the source and
942 target of the symlink differ."
943 (with-parsed-tramp-file-name linkname l
944 (let ((ln (tramp-get-remote-ln l))
945 (cwd (tramp-run-real-handler
946 'file-name-directory (list l-localname))))
950 "Making a symbolic link. ln(1) does not exist on the remote host."))
952 ;; Do the 'confirm if exists' thing.
953 (when (file-exists-p linkname)
955 (if (or (null ok-if-already-exists) ; not allowed to exist
956 (and (numberp ok-if-already-exists)
959 "File %s already exists; make it a link anyway? "
962 l 'file-already-exists "File %s already exists" l-localname)
963 (delete-file linkname)))
965 ;; If FILENAME is a Tramp name, use just the localname component.
966 (when (tramp-tramp-file-p filename)
968 (tramp-file-name-localname
969 (tramp-dissect-file-name (expand-file-name filename)))))
971 (tramp-flush-file-property l (file-name-directory l-localname))
972 (tramp-flush-file-property l l-localname)
974 ;; Right, they are on the same host, regardless of user, method,
975 ;; etc. We now make the link on the remote machine. This will
976 ;; occur as the user that FILENAME belongs to.
977 (tramp-send-command-and-check
980 "cd %s && %s -sf %s %s"
981 (tramp-shell-quote-argument cwd)
983 (tramp-shell-quote-argument filename)
984 (tramp-shell-quote-argument l-localname))
987 (defun tramp-sh-handle-file-truename (filename)
988 "Like `file-truename' for Tramp files."
991 (with-parsed-tramp-file-name (expand-file-name filename) nil
992 (tramp-make-tramp-file-name
994 (with-tramp-file-property v localname "file-truename"
995 (let ((result nil)) ; result steps in reverse order
996 (tramp-message v 4 "Finding true name for `%s'" filename)
998 ;; Use GNU readlink --canonicalize-missing where available.
999 ((tramp-get-remote-readlink v)
1000 (tramp-send-command-and-check
1002 (format "%s --canonicalize-missing %s"
1003 (tramp-get-remote-readlink v)
1004 (tramp-shell-quote-argument localname)))
1005 (with-current-buffer (tramp-get-connection-buffer v)
1006 (goto-char (point-min))
1007 (setq result (buffer-substring (point-min) (point-at-eol)))))
1009 ;; Use Perl implementation.
1010 ((and (tramp-get-remote-perl v)
1011 (tramp-get-connection-property v "perl-file-spec" nil)
1012 (tramp-get-connection-property v "perl-cwd-realpath" nil))
1013 (tramp-maybe-send-script
1014 v tramp-perl-file-truename "tramp_perl_file_truename")
1016 (tramp-send-command-and-read
1018 (format "tramp_perl_file_truename %s"
1019 (tramp-shell-quote-argument localname)))))
1021 ;; Do it yourself. We bind `directory-sep-char' here for
1022 ;; XEmacs on Windows, which would otherwise use backslash.
1023 (t (let* ((directory-sep-char ?/)
1024 (steps (tramp-compat-split-string localname "/"))
1025 (localnamedir (tramp-run-real-handler
1026 'file-name-as-directory (list localname)))
1027 (is-dir (string= localname localnamedir))
1030 ;; Don't make the following value larger than
1031 ;; necessary. People expect an error message in
1032 ;; a timely fashion when something is wrong;
1033 ;; otherwise they might think that Emacs is hung.
1034 ;; Of course, correctness has to come first.
1037 (while (and steps (< numchase numchase-limit))
1038 (setq thisstep (pop steps))
1041 (mapconcat 'identity
1042 (append '("") (reverse result) (list thisstep))
1044 (setq symlink-target
1045 (nth 0 (file-attributes
1046 (tramp-make-tramp-file-name
1048 (mapconcat 'identity
1053 (cond ((string= "." thisstep)
1054 (tramp-message v 5 "Ignoring step `.'"))
1055 ((string= ".." thisstep)
1056 (tramp-message v 5 "Processing step `..'")
1058 ((stringp symlink-target)
1059 ;; It's a symlink, follow it.
1061 v 5 "Follow symlink to %s" symlink-target)
1062 (setq numchase (1+ numchase))
1063 (when (file-name-absolute-p symlink-target)
1065 ;; If the symlink was absolute, we'll get a
1066 ;; string like "/user@host:/some/target";
1067 ;; extract the "/some/target" part from it.
1068 (when (tramp-tramp-file-p symlink-target)
1069 (unless (tramp-equal-remote filename symlink-target)
1072 "Symlink target `%s' on wrong host"
1074 (setq symlink-target localname))
1076 (append (tramp-compat-split-string
1081 (setq result (cons thisstep result)))))
1082 (when (>= numchase numchase-limit)
1085 "Maximum number (%d) of symlinks exceeded" numchase-limit))
1086 (setq result (reverse result))
1087 ;; Combine list to form string.
1090 (mapconcat 'identity (cons "" result) "/")
1093 (or (string= "" result)
1094 (not (string= (substring result -1) "/"))))
1095 (setq result (concat result "/"))))))
1097 (tramp-message v 4 "True name of `%s' is `%s'" localname result)
1100 ;; Preserve trailing "/".
1101 (if (string-equal (file-name-nondirectory filename) "") "/" "")))
1105 (defun tramp-sh-handle-file-exists-p (filename)
1106 "Like `file-exists-p' for Tramp files."
1107 (with-parsed-tramp-file-name filename nil
1108 (with-tramp-file-property v localname "file-exists-p"
1109 (or (not (null (tramp-get-file-property
1110 v localname "file-attributes-integer" nil)))
1111 (not (null (tramp-get-file-property
1112 v localname "file-attributes-string" nil)))
1113 (tramp-send-command-and-check
1117 (tramp-get-file-exists-command v)
1118 (tramp-shell-quote-argument localname)))))))
1120 (defun tramp-sh-handle-file-attributes (filename &optional id-format)
1121 "Like `file-attributes' for Tramp files."
1122 (unless id-format (setq id-format 'integer))
1124 ;; Don't modify `last-coding-system-used' by accident.
1125 (let ((last-coding-system-used last-coding-system-used))
1126 (with-parsed-tramp-file-name (expand-file-name filename) nil
1127 (with-tramp-file-property
1128 v localname (format "file-attributes-%s" id-format)
1130 (tramp-convert-file-attributes
1134 ((tramp-get-remote-stat v)
1135 (tramp-do-file-attributes-with-stat v localname id-format))
1136 ((tramp-get-remote-perl v)
1137 (tramp-do-file-attributes-with-perl v localname id-format))
1139 ;; The scripts could fail, for example with huge file size.
1140 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
1142 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
1143 "Implement `file-attributes' for Tramp files using the ls(1) command."
1145 res-inode res-filemodes res-numlinks
1146 res-uid res-gid res-size res-symlink-target)
1147 (tramp-message vec 5 "file attributes with ls: %s" localname)
1150 (format "(%s %s || %s -h %s) && %s %s %s"
1151 (tramp-get-file-exists-command vec)
1152 (tramp-shell-quote-argument localname)
1153 (tramp-get-test-command vec)
1154 (tramp-shell-quote-argument localname)
1155 (tramp-get-ls-command vec)
1156 (if (eq id-format 'integer) "-ildn" "-ild")
1157 (tramp-shell-quote-argument localname)))
1158 ;; parse `ls -l' output ...
1159 (with-current-buffer (tramp-get-buffer vec)
1160 (when (> (buffer-size) 0)
1161 (goto-char (point-min))
1165 (read (current-buffer))
1166 (invalid-read-syntax
1167 (when (and (equal (cadr err)
1168 "Integer constant overflow in reader")
1170 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
1172 (let* ((big (read (substring (car (cddr err)) 0
1173 (match-beginning 1))))
1174 (small (read (match-string 1 (car (cddr err)))))
1175 (twiddle (/ small 65536)))
1176 (cons (+ big twiddle)
1177 (- small (* twiddle 65536))))))))
1178 ;; ... file mode flags
1179 (setq res-filemodes (symbol-name (read (current-buffer))))
1181 (setq res-numlinks (read (current-buffer)))
1183 (setq res-uid (read (current-buffer)))
1184 (setq res-gid (read (current-buffer)))
1185 (if (eq id-format 'integer)
1187 (unless (numberp res-uid) (setq res-uid -1))
1188 (unless (numberp res-gid) (setq res-gid -1)))
1190 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
1191 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
1193 (setq res-size (read (current-buffer)))
1194 ;; From the file modes, figure out other stuff.
1195 (setq symlinkp (eq ?l (aref res-filemodes 0)))
1196 (setq dirp (eq ?d (aref res-filemodes 0)))
1197 ;; if symlink, find out file name pointed to
1199 (search-forward "-> ")
1200 (setq res-symlink-target (buffer-substring (point) (point-at-eol))))
1201 ;; return data gathered
1203 ;; 0. t for directory, string (name linked to) for symbolic
1205 (or dirp res-symlink-target)
1206 ;; 1. Number of links to file.
1212 ;; 4. Last access time, as a list of integers. Normally this
1213 ;; would be in the same format as `current-time', but the
1214 ;; subseconds part is not currently implemented, and (0 0)
1215 ;; denotes an unknown time.
1216 ;; 5. Last modification time, likewise.
1217 ;; 6. Last status change time, likewise.
1218 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
1219 ;; 7. Size in bytes (-1, if number is out of range).
1221 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
1223 ;; 9. t if file's gid would change if file were deleted and
1224 ;; recreated. Will be set in `tramp-convert-file-attributes'
1226 ;; 10. inode number.
1228 ;; 11. Device number. Will be replaced by a virtual device number.
1232 (defun tramp-do-file-attributes-with-perl
1233 (vec localname &optional id-format)
1234 "Implement `file-attributes' for Tramp files using a Perl script."
1235 (tramp-message vec 5 "file attributes with perl: %s" localname)
1236 (tramp-maybe-send-script
1237 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
1238 (tramp-send-command-and-read
1240 (format "tramp_perl_file_attributes %s %s"
1241 (tramp-shell-quote-argument localname) id-format)))
1243 (defun tramp-do-file-attributes-with-stat
1244 (vec localname &optional id-format)
1245 "Implement `file-attributes' for Tramp files using stat(1) command."
1246 (tramp-message vec 5 "file attributes with stat: %s" localname)
1247 (tramp-send-command-and-read
1250 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
1251 ;; parse correctly the sequence "((". Therefore, we add a space.
1252 "( (%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)' %s || echo nil)"
1253 (tramp-get-file-exists-command vec)
1254 (tramp-shell-quote-argument localname)
1255 (tramp-get-test-command vec)
1256 (tramp-shell-quote-argument localname)
1257 (tramp-get-remote-stat vec)
1258 (if (eq id-format 'integer) "%ue0" "\"%U\"")
1259 (if (eq id-format 'integer) "%ge0" "\"%G\"")
1260 (tramp-shell-quote-argument localname))))
1262 (defun tramp-sh-handle-set-visited-file-modtime (&optional time-list)
1263 "Like `set-visited-file-modtime' for Tramp files."
1264 (unless (buffer-file-name)
1265 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
1268 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
1269 (let ((f (buffer-file-name))
1271 (with-parsed-tramp-file-name f nil
1272 (let* ((remote-file-name-inhibit-cache t)
1273 (attr (file-attributes f))
1274 ;; '(-1 65535) means file doesn't exists yet.
1275 (modtime (or (nth 5 attr) '(-1 65535))))
1276 (when (boundp 'last-coding-system-used)
1277 (setq coding-system-used (symbol-value 'last-coding-system-used)))
1278 ;; We use '(0 0) as a don't-know value. See also
1279 ;; `tramp-do-file-attributes-with-ls'.
1280 (if (not (equal modtime '(0 0)))
1281 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
1285 (format "%s -ild %s"
1286 (tramp-get-ls-command v)
1287 (tramp-shell-quote-argument localname)))
1288 (setq attr (buffer-substring (point) (point-at-eol))))
1289 (tramp-set-file-property
1290 v localname "visited-file-modtime-ild" attr))
1291 (when (boundp 'last-coding-system-used)
1292 (set 'last-coding-system-used coding-system-used))
1295 ;; This function makes the same assumption as
1296 ;; `tramp-sh-handle-set-visited-file-modtime'.
1297 (defun tramp-sh-handle-verify-visited-file-modtime (&optional buf)
1298 "Like `verify-visited-file-modtime' for Tramp files.
1299 At the time `verify-visited-file-modtime' calls this function, we
1300 already know that the buffer is visiting a file and that
1301 `visited-file-modtime' does not return 0. Do not call this
1302 function directly, unless those two cases are already taken care
1304 (with-current-buffer (or buf (current-buffer))
1305 (let ((f (buffer-file-name)))
1306 ;; There is no file visiting the buffer, or the buffer has no
1307 ;; recorded last modification time, or there is no established
1310 (eq (visited-file-modtime) 0)
1311 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
1313 (with-parsed-tramp-file-name f nil
1314 (let* ((remote-file-name-inhibit-cache t)
1315 (attr (file-attributes f))
1316 (modtime (nth 5 attr))
1317 (mt (visited-file-modtime)))
1320 ;; File exists, and has a known modtime.
1321 ((and attr (not (equal modtime '(0 0))))
1322 (< (abs (tramp-time-diff
1324 ;; For compatibility, deal with both the old
1325 ;; (HIGH . LOW) and the new (HIGH LOW) return
1326 ;; values of `visited-file-modtime'.
1328 (list (car mt) (cdr mt))
1331 ;; Modtime has the don't know value.
1335 (format "%s -ild %s"
1336 (tramp-get-ls-command v)
1337 (tramp-shell-quote-argument localname)))
1338 (with-current-buffer (tramp-get-buffer v)
1339 (setq attr (buffer-substring (point) (point-at-eol))))
1342 (tramp-get-file-property
1343 v localname "visited-file-modtime-ild" "")))
1344 ;; If file does not exist, say it is not modified if and
1345 ;; only if that agrees with the buffer's record.
1346 (t (equal mt '(-1 65535))))))))))
1348 (defun tramp-sh-handle-set-file-modes (filename mode)
1349 "Like `set-file-modes' for Tramp files."
1350 (with-parsed-tramp-file-name filename nil
1351 (tramp-flush-file-property v localname)
1352 ;; FIXME: extract the proper text from chmod's stderr.
1353 (tramp-barf-unless-okay
1355 (format "chmod %s %s"
1356 (tramp-compat-decimal-to-octal mode)
1357 (tramp-shell-quote-argument localname))
1358 "Error while changing file's mode %s" filename)))
1360 (defun tramp-sh-handle-set-file-times (filename &optional time)
1361 "Like `set-file-times' for Tramp files."
1362 (if (tramp-tramp-file-p filename)
1363 (with-parsed-tramp-file-name filename nil
1364 (when (tramp-get-remote-touch v)
1365 (tramp-flush-file-property v localname)
1366 (let ((time (if (or (null time) (equal time '(0 0)))
1369 ;; With GNU Emacs, `format-time-string' has an
1370 ;; optional parameter UNIVERSAL. This is preferred,
1371 ;; because we could handle the case when the remote
1372 ;; host is located in a different time zone as the
1374 (utc (not (featurep 'xemacs))))
1375 (tramp-send-command-and-check
1378 (if utc "env TZ=UTC" "")
1379 (tramp-get-remote-touch v)
1380 (if (tramp-get-connection-property v "touch-t" nil)
1383 (format-time-string "%Y%m%d%H%M.%S" time t)
1384 (format-time-string "%Y%m%d%H%M.%S" time)))
1386 (tramp-shell-quote-argument localname))))))
1388 ;; We handle also the local part, because in older Emacsen,
1389 ;; without `set-file-times', this function is an alias for this.
1390 ;; We are local, so we don't need the UTC settings.
1393 nil "touch" nil nil nil "-t"
1394 (format-time-string "%Y%m%d%H%M.%S" time)
1395 (tramp-shell-quote-argument filename)))))
1397 (defun tramp-set-file-uid-gid (filename &optional uid gid)
1398 "Set the ownership for FILENAME.
1399 If UID and GID are provided, these values are used; otherwise uid
1400 and gid of the corresponding user is taken. Both parameters must
1401 be non-negative integers."
1402 ;; Modern Unices allow chown only for root. So we might need
1403 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
1404 ;; working with su(do)? when it is needed, so it shall succeed in
1405 ;; the majority of cases.
1406 ;; Don't modify `last-coding-system-used' by accident.
1407 (let ((last-coding-system-used last-coding-system-used))
1408 (if (tramp-tramp-file-p filename)
1409 (with-parsed-tramp-file-name filename nil
1410 (if (and (zerop (user-uid)) (tramp-local-host-p v))
1411 ;; If we are root on the local host, we can do it directly.
1412 (tramp-set-file-uid-gid localname uid gid)
1413 (let ((uid (or (and (natnump uid) uid)
1414 (tramp-get-remote-uid v 'integer)))
1415 (gid (or (and (natnump gid) gid)
1416 (tramp-get-remote-gid v 'integer))))
1419 "chown %d:%d %s" uid gid
1420 (tramp-shell-quote-argument localname))))))
1422 ;; We handle also the local part, because there doesn't exist
1423 ;; `set-file-uid-gid'. On W32 "chown" might not work.
1424 (let ((uid (or (and (natnump uid) uid) (tramp-get-local-uid 'integer)))
1425 (gid (or (and (natnump gid) gid) (tramp-get-local-gid 'integer))))
1427 nil "chown" nil nil nil
1428 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
1430 (defun tramp-remote-selinux-p (vec)
1431 "Check, whether SELINUX is enabled on the remote host."
1432 (with-tramp-connection-property
1433 (tramp-get-connection-process vec) "selinux-p"
1434 (let ((result (tramp-find-executable
1435 vec "getenforce" (tramp-get-remote-path vec) t t)))
1438 (tramp-send-command-and-read
1439 vec (format "echo \\\"`%S`\\\"" result))
1442 (defun tramp-sh-handle-file-selinux-context (filename)
1443 "Like `file-selinux-context' for Tramp files."
1444 (with-parsed-tramp-file-name filename nil
1445 (with-tramp-file-property v localname "file-selinux-context"
1446 (let ((context '(nil nil nil nil))
1447 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
1448 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
1449 (when (and (tramp-remote-selinux-p v)
1450 (tramp-send-command-and-check
1453 (tramp-get-ls-command v)
1454 (tramp-shell-quote-argument localname))))
1455 (with-current-buffer (tramp-get-connection-buffer v)
1456 (goto-char (point-min))
1457 (when (re-search-forward regexp (point-at-eol) t)
1458 (setq context (list (match-string 1) (match-string 2)
1459 (match-string 3) (match-string 4))))))
1460 ;; Return the context.
1463 (defun tramp-sh-handle-set-file-selinux-context (filename context)
1464 "Like `set-file-selinux-context' for Tramp files."
1465 (with-parsed-tramp-file-name filename nil
1466 (if (and (consp context)
1467 (tramp-remote-selinux-p v)
1468 (tramp-send-command-and-check
1469 v (format "chcon %s %s %s %s %s"
1470 (if (stringp (nth 0 context))
1471 (format "--user=%s" (nth 0 context)) "")
1472 (if (stringp (nth 1 context))
1473 (format "--role=%s" (nth 1 context)) "")
1474 (if (stringp (nth 2 context))
1475 (format "--type=%s" (nth 2 context)) "")
1476 (if (stringp (nth 3 context))
1477 (format "--range=%s" (nth 3 context)) "")
1478 (tramp-shell-quote-argument localname))))
1480 (tramp-set-file-property v localname "file-selinux-context" context)
1482 (tramp-set-file-property v localname "file-selinux-context" 'undef)
1485 (defun tramp-remote-acl-p (vec)
1486 "Check, whether ACL is enabled on the remote host."
1487 (with-tramp-connection-property (tramp-get-connection-process vec) "acl-p"
1488 (tramp-send-command-and-check vec "getfacl /")))
1490 (defun tramp-sh-handle-file-acl (filename)
1491 "Like `file-acl' for Tramp files."
1492 (with-parsed-tramp-file-name filename nil
1493 (with-tramp-file-property v localname "file-acl"
1494 (when (and (tramp-remote-acl-p v)
1495 (tramp-send-command-and-check
1497 "getfacl -ac %s 2>/dev/null"
1498 (tramp-shell-quote-argument localname))))
1499 (with-current-buffer (tramp-get-connection-buffer v)
1500 (goto-char (point-max))
1501 (delete-blank-lines)
1502 (when (> (point-max) (point-min))
1503 (tramp-compat-funcall
1504 'substring-no-properties (buffer-string))))))))
1506 (defun tramp-sh-handle-set-file-acl (filename acl-string)
1507 "Like `set-file-acl' for Tramp files."
1508 (with-parsed-tramp-file-name (expand-file-name filename) nil
1509 (if (and (stringp acl-string) (tramp-remote-acl-p v)
1512 v (format "setfacl --set-file=- %s <<'%s'\n%s\n%s\n"
1513 (tramp-shell-quote-argument localname)
1514 tramp-end-of-heredoc
1516 tramp-end-of-heredoc))
1517 (tramp-send-command-and-check v nil)))
1520 (tramp-set-file-property v localname "file-acl" acl-string)
1522 ;; In case of errors, we return `nil'.
1523 (tramp-set-file-property v localname "file-acl-string" 'undef)
1526 ;; Simple functions using the `test' command.
1528 (defun tramp-sh-handle-file-executable-p (filename)
1529 "Like `file-executable-p' for Tramp files."
1530 (with-parsed-tramp-file-name filename nil
1531 (with-tramp-file-property v localname "file-executable-p"
1532 ;; Examine `file-attributes' cache to see if request can be
1533 ;; satisfied without remote operation.
1534 (or (tramp-check-cached-permissions v ?x)
1535 (tramp-run-test "-x" filename)))))
1537 (defun tramp-sh-handle-file-readable-p (filename)
1538 "Like `file-readable-p' for Tramp files."
1539 (with-parsed-tramp-file-name filename nil
1540 (with-tramp-file-property v localname "file-readable-p"
1541 ;; Examine `file-attributes' cache to see if request can be
1542 ;; satisfied without remote operation.
1543 (or (tramp-check-cached-permissions v ?r)
1544 (tramp-run-test "-r" filename)))))
1546 ;; When the remote shell is started, it looks for a shell which groks
1547 ;; tilde expansion. Here, we assume that all shells which grok tilde
1548 ;; expansion will also provide a `test' command which groks `-nt' (for
1549 ;; newer than). If this breaks, tell me about it and I'll try to do
1550 ;; something smarter about it.
1551 (defun tramp-sh-handle-file-newer-than-file-p (file1 file2)
1552 "Like `file-newer-than-file-p' for Tramp files."
1553 (cond ((not (file-exists-p file1))
1555 ((not (file-exists-p file2))
1557 ;; We are sure both files exist at this point.
1560 ;; We try to get the mtime of both files. If they are not
1561 ;; equal to the "dont-know" value, then we subtract the times
1562 ;; and obtain the result.
1563 (let ((fa1 (file-attributes file1))
1564 (fa2 (file-attributes file2)))
1565 (if (and (not (equal (nth 5 fa1) '(0 0)))
1566 (not (equal (nth 5 fa2) '(0 0))))
1567 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
1568 ;; If one of them is the dont-know value, then we can
1569 ;; still try to run a shell command on the remote host.
1570 ;; However, this only works if both files are Tramp
1571 ;; files and both have the same method, same user, same
1573 (unless (tramp-equal-remote file1 file2)
1574 (with-parsed-tramp-file-name
1575 (if (tramp-tramp-file-p file1) file1 file2) nil
1578 "Files %s and %s must have same method, user, host"
1580 (with-parsed-tramp-file-name file1 nil
1582 (tramp-get-test-nt-command v) file1 file2))))))))
1584 ;; Functions implemented using the basic functions above.
1586 (defun tramp-sh-handle-file-directory-p (filename)
1587 "Like `file-directory-p' for Tramp files."
1588 (with-parsed-tramp-file-name filename nil
1589 ;; `file-directory-p' is used as predicate for file name completion.
1590 ;; Sometimes, when a connection is not established yet, it is
1591 ;; desirable to return t immediately for "/method:foo:". It can
1592 ;; be expected that this is always a directory.
1593 (or (zerop (length localname))
1594 (with-tramp-file-property v localname "file-directory-p"
1595 (tramp-run-test "-d" filename)))))
1597 (defun tramp-sh-handle-file-writable-p (filename)
1598 "Like `file-writable-p' for Tramp files."
1599 (with-parsed-tramp-file-name filename nil
1600 (with-tramp-file-property v localname "file-writable-p"
1601 (if (file-exists-p filename)
1602 ;; Examine `file-attributes' cache to see if request can be
1603 ;; satisfied without remote operation.
1604 (or (tramp-check-cached-permissions v ?w)
1605 (tramp-run-test "-w" filename))
1606 ;; If file doesn't exist, check if directory is writable.
1607 (and (tramp-run-test "-d" (file-name-directory filename))
1608 (tramp-run-test "-w" (file-name-directory filename)))))))
1610 (defun tramp-sh-handle-file-ownership-preserved-p (filename &optional group)
1611 "Like `file-ownership-preserved-p' for Tramp files."
1612 (with-parsed-tramp-file-name filename nil
1613 (with-tramp-file-property v localname "file-ownership-preserved-p"
1614 (let ((attributes (file-attributes filename)))
1615 ;; Return t if the file doesn't exist, since it's true that no
1616 ;; information would be lost by an (attempted) delete and create.
1617 (or (null attributes)
1619 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer))
1621 (= (nth 3 attributes) (tramp-get-remote-gid v 'integer)))))))))
1623 ;; Directory listings.
1625 (defun tramp-sh-handle-directory-files-and-attributes
1626 (directory &optional full match nosort id-format)
1627 "Like `directory-files-and-attributes' for Tramp files."
1628 (if (with-parsed-tramp-file-name directory nil
1629 (not (or (tramp-get-remote-stat v) (tramp-get-remote-perl v))))
1630 (tramp-handle-directory-files-and-attributes
1631 directory full match nosort id-format)
1634 (unless id-format (setq id-format 'integer))
1635 (when (file-directory-p directory)
1636 (setq directory (expand-file-name directory))
1639 (with-parsed-tramp-file-name directory nil
1640 (with-tramp-file-property
1642 (format "directory-files-and-attributes-%s" id-format)
1647 (tramp-convert-file-attributes v (cdr x))))
1649 ((tramp-get-remote-stat v)
1650 (tramp-do-directory-files-and-attributes-with-stat
1651 v localname id-format))
1652 ((tramp-get-remote-perl v)
1653 (tramp-do-directory-files-and-attributes-with-perl
1654 v localname id-format)))))))))
1658 (setq item (pop temp))
1659 (when (or (null match) (string-match match (car item)))
1661 (setcar item (expand-file-name (car item) directory)))
1662 (push item result)))
1666 (sort result (lambda (x y) (string< (car x) (car y)))))))))
1668 (defun tramp-do-directory-files-and-attributes-with-perl
1669 (vec localname &optional id-format)
1670 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
1671 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
1672 (tramp-maybe-send-script
1673 vec tramp-perl-directory-files-and-attributes
1674 "tramp_perl_directory_files_and_attributes")
1676 (tramp-send-command-and-read
1678 (format "tramp_perl_directory_files_and_attributes %s %s"
1679 (tramp-shell-quote-argument localname) id-format))))
1680 (when (stringp object) (tramp-error vec 'file-error object))
1683 (defun tramp-do-directory-files-and-attributes-with-stat
1684 (vec localname &optional id-format)
1685 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
1686 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
1687 (tramp-send-command-and-read
1691 ;; We must care about file names with spaces, or starting with
1692 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
1693 ;; but it does not work on all remote systems. Therefore, we
1694 ;; quote the file names via sed.
1695 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | "
1697 "'(\"%%n\" (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)'"
1698 " 2>/dev/null); echo \")\"")
1699 (tramp-shell-quote-argument localname)
1700 (tramp-get-ls-command vec)
1701 (tramp-get-remote-stat vec)
1702 (if (eq id-format 'integer) "%ue0" "\"%U\"")
1703 (if (eq id-format 'integer) "%ge0" "\"%G\""))))
1705 ;; This function should return "foo/" for directories and "bar" for
1707 (defun tramp-sh-handle-file-name-all-completions (filename directory)
1708 "Like `file-name-all-completions' for Tramp files."
1709 (unless (save-match-data (string-match "/" filename))
1710 (with-parsed-tramp-file-name (expand-file-name directory) nil
1717 ;; Try cache entries for `filename', `filename' with last
1718 ;; character removed, `filename' with last two characters
1719 ;; removed, ..., and finally the empty string - all
1720 ;; concatenated to the local directory name.
1721 (let ((remote-file-name-inhibit-cache
1722 (or remote-file-name-inhibit-cache
1723 tramp-completion-reread-directory-timeout)))
1725 ;; This is inefficient for very long file names, pity
1726 ;; `reduce' is not available...
1733 (tramp-get-file-property
1735 (concat localname (substring filename 0 x))
1736 "file-name-all-completions"
1738 (when cache-hit (list cache-hit))))
1739 ;; We cannot use a length of 0, because file properties
1740 ;; for "foo" and "foo/" are identical.
1741 (tramp-compat-number-sequence (length filename) 1 -1)))))
1743 ;; Cache expired or no matching cache entry found so we need
1744 ;; to perform a remote operation.
1746 ;; Get a list of directories and files, including reliably
1747 ;; tagging the directories with a trailing '/'. Because I
1748 ;; rock. --daniel@danann.net
1750 ;; Changed to perform `cd' in the same remote op and only
1751 ;; get entries starting with `filename'. Capture any `cd'
1752 ;; error messages. Ensure any `cd' and `echo' aliases are
1756 (if (tramp-get-remote-perl v)
1758 (tramp-maybe-send-script
1759 v tramp-perl-file-name-all-completions
1760 "tramp_perl_file_name_all_completions")
1761 (format "tramp_perl_file_name_all_completions %s %s %d"
1762 (tramp-shell-quote-argument localname)
1763 (tramp-shell-quote-argument filename)
1765 ;; `read-file-name-completion-ignore-case'
1766 ;; is introduced with Emacs 22.1.
1768 'read-file-name-completion-ignore-case)
1769 'read-file-name-completion-ignore-case
1770 'completion-ignore-case))
1774 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
1775 ;; `ls' with wildcard might fail with `Argument
1776 ;; list too long' error in some corner cases; if
1777 ;; `ls' fails after `cd' succeeded, chances are
1778 ;; that's the case, so let's retry without
1779 ;; wildcard. This will return "too many" entries
1780 ;; but that isn't harmful.
1781 " || %s -a 2>/dev/null)"
1782 " | while IFS= read f; do"
1783 " if %s -d \"$f\" 2>/dev/null;"
1784 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
1785 " && \\echo ok) || \\echo fail")
1786 (tramp-shell-quote-argument localname)
1787 (tramp-get-ls-command v)
1788 ;; When `filename' is empty, just `ls' without
1789 ;; `filename' argument is more efficient than `ls *'
1790 ;; for very large directories and might avoid the
1791 ;; `Argument list too long' error.
1793 ;; With and only with wildcard, we need to add
1794 ;; `-d' to prevent `ls' from descending into
1796 (if (zerop (length filename))
1798 (concat (tramp-shell-quote-argument filename) "* -d"))
1799 (tramp-get-ls-command v)
1800 (tramp-get-test-command v))))
1802 ;; Now grab the output.
1803 (with-current-buffer (tramp-get-buffer v)
1804 (goto-char (point-max))
1806 ;; Check result code, found in last line of output.
1808 (if (looking-at "^fail$")
1810 ;; Grab error message from line before last line
1811 ;; (it was put there by `cd 2>&1').
1815 "tramp-sh-handle-file-name-all-completions: %s"
1816 (buffer-substring (point) (point-at-eol))))
1817 ;; For peace of mind, if buffer doesn't end in `fail'
1818 ;; then it should end in `ok'. If neither are in the
1819 ;; buffer something went seriously wrong on the remote
1821 (unless (looking-at "^ok$")
1825 tramp-sh-handle-file-name-all-completions: internal error accessing `%s': `%s'"
1826 (tramp-shell-quote-argument localname) (buffer-string))))
1828 (while (zerop (forward-line -1))
1829 (push (buffer-substring (point) (point-at-eol)) result)))
1831 ;; Because the remote op went through OK we know the
1832 ;; directory we `cd'-ed to exists.
1833 (tramp-set-file-property v localname "file-exists-p" t)
1835 ;; Because the remote op went through OK we know every
1836 ;; file listed by `ls' exists.
1837 (mapc (lambda (entry)
1838 (tramp-set-file-property
1839 v (concat localname entry) "file-exists-p" t))
1842 ;; Store result in the cache.
1843 (tramp-set-file-property
1844 v (concat localname filename)
1845 "file-name-all-completions" result))))))))
1849 (defun tramp-sh-handle-add-name-to-file
1850 (filename newname &optional ok-if-already-exists)
1851 "Like `add-name-to-file' for Tramp files."
1852 (unless (tramp-equal-remote filename newname)
1853 (with-parsed-tramp-file-name
1854 (if (tramp-tramp-file-p filename) filename newname) nil
1857 "add-name-to-file: %s"
1858 "only implemented for same method, same user, same host")))
1859 (with-parsed-tramp-file-name filename v1
1860 (with-parsed-tramp-file-name newname v2
1861 (let ((ln (when v1 (tramp-get-remote-ln v1))))
1862 (when (and (numberp ok-if-already-exists)
1863 (file-exists-p newname)
1866 "File %s already exists; make it a new name anyway? "
1869 v2 'file-error "add-name-to-file: file %s already exists" newname))
1870 (when ok-if-already-exists (setq ln (concat ln " -f")))
1871 (tramp-flush-file-property v2 (file-name-directory v2-localname))
1872 (tramp-flush-file-property v2 v2-localname)
1873 (tramp-barf-unless-okay
1875 (format "%s %s %s" ln
1876 (tramp-shell-quote-argument v1-localname)
1877 (tramp-shell-quote-argument v2-localname))
1878 "error with add-name-to-file, see buffer `%s' for details"
1881 (defun tramp-sh-handle-copy-file
1882 (filename newname &optional ok-if-already-exists keep-date
1883 preserve-uid-gid preserve-extended-attributes)
1884 "Like `copy-file' for Tramp files."
1885 (setq filename (expand-file-name filename))
1886 (setq newname (expand-file-name newname))
1888 ;; At least one file a Tramp file?
1889 ((or (tramp-tramp-file-p filename)
1890 (tramp-tramp-file-p newname))
1891 (tramp-do-copy-or-rename-file
1892 'copy filename newname ok-if-already-exists keep-date
1893 preserve-uid-gid preserve-extended-attributes))
1895 (preserve-extended-attributes
1896 (tramp-run-real-handler
1898 (list filename newname ok-if-already-exists keep-date
1899 preserve-uid-gid preserve-extended-attributes)))
1901 (tramp-run-real-handler
1903 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
1905 (tramp-run-real-handler
1906 'copy-file (list filename newname ok-if-already-exists keep-date)))))
1908 (defun tramp-sh-handle-copy-directory
1909 (dirname newname &optional keep-date parents copy-contents)
1910 "Like `copy-directory' for Tramp files."
1911 (let ((t1 (tramp-tramp-file-p dirname))
1912 (t2 (tramp-tramp-file-p newname)))
1913 (with-parsed-tramp-file-name (if t1 dirname newname) nil
1914 (if (and (not copy-contents)
1915 (tramp-get-method-parameter method 'tramp-copy-recursive)
1916 ;; When DIRNAME and NEWNAME are remote, they must have
1918 (or (null t1) (null t2)
1920 (tramp-file-name-method (tramp-dissect-file-name dirname))
1921 (tramp-file-name-method
1922 (tramp-dissect-file-name newname)))))
1923 ;; scp or rsync DTRT.
1925 (setq dirname (directory-file-name (expand-file-name dirname))
1926 newname (directory-file-name (expand-file-name newname)))
1927 (if (and (file-directory-p newname)
1928 (not (string-equal (file-name-nondirectory dirname)
1929 (file-name-nondirectory newname))))
1932 (file-name-nondirectory dirname) newname)))
1933 (if (not (file-directory-p (file-name-directory newname)))
1934 (make-directory (file-name-directory newname) parents))
1935 (tramp-do-copy-or-rename-file-out-of-band
1936 'copy dirname newname keep-date))
1937 ;; We must do it file-wise.
1938 (tramp-run-real-handler
1941 (list dirname newname keep-date parents copy-contents)
1942 (list dirname newname keep-date parents))))
1944 ;; When newname did exist, we have wrong cached values.
1946 (with-parsed-tramp-file-name newname nil
1947 (tramp-flush-file-property v (file-name-directory localname))
1948 (tramp-flush-file-property v localname))))))
1950 (defun tramp-sh-handle-rename-file
1951 (filename newname &optional ok-if-already-exists)
1952 "Like `rename-file' for Tramp files."
1953 ;; Check if both files are local -- invoke normal rename-file.
1954 ;; Otherwise, use Tramp from local system.
1955 (setq filename (expand-file-name filename))
1956 (setq newname (expand-file-name newname))
1957 ;; At least one file a Tramp file?
1958 (if (or (tramp-tramp-file-p filename)
1959 (tramp-tramp-file-p newname))
1960 (tramp-do-copy-or-rename-file
1961 'rename filename newname ok-if-already-exists t t)
1962 (tramp-run-real-handler
1963 'rename-file (list filename newname ok-if-already-exists))))
1965 (defun tramp-do-copy-or-rename-file
1966 (op filename newname &optional ok-if-already-exists keep-date
1967 preserve-uid-gid preserve-extended-attributes)
1968 "Copy or rename a remote file.
1969 OP must be `copy' or `rename' and indicates the operation to perform.
1970 FILENAME specifies the file to copy or rename, NEWNAME is the name of
1971 the new file (for copy) or the new name of the file (for rename).
1972 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
1973 KEEP-DATE means to make sure that NEWNAME has the same timestamp
1974 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
1975 the uid and gid if both files are on the same host.
1976 PRESERVE-EXTENDED-ATTRIBUTES activates selinux and acl commands.
1978 This function is invoked by `tramp-sh-handle-copy-file' and
1979 `tramp-sh-handle-rename-file'. It is an error if OP is neither
1980 of `copy' and `rename'. FILENAME and NEWNAME must be absolute
1982 (unless (memq op '(copy rename))
1983 (error "Unknown operation `%s', must be `copy' or `rename'" op))
1984 (let ((t1 (tramp-tramp-file-p filename))
1985 (t2 (tramp-tramp-file-p newname))
1986 (length (nth 7 (file-attributes (file-truename filename))))
1987 (attributes (and preserve-extended-attributes
1988 (apply 'file-extended-attributes (list filename)))))
1990 (with-parsed-tramp-file-name (if t1 filename newname) nil
1991 (when (and (not ok-if-already-exists) (file-exists-p newname))
1993 v 'file-already-exists "File %s already exists" newname))
1995 (with-tramp-progress-reporter
1996 v 0 (format "%s %s to %s"
1997 (if (eq op 'copy) "Copying" "Renaming")
2001 ;; Both are Tramp files.
2003 (with-parsed-tramp-file-name filename v1
2004 (with-parsed-tramp-file-name newname v2
2006 ;; Shortcut: if method, host, user are the same for
2007 ;; both files, we invoke `cp' or `mv' on the remote
2009 ((tramp-equal-remote filename newname)
2010 (tramp-do-copy-or-rename-file-directly
2012 ok-if-already-exists keep-date preserve-uid-gid))
2014 ;; Try out-of-band operation.
2016 (tramp-method-out-of-band-p v1 length)
2017 (tramp-method-out-of-band-p v2 length))
2018 (tramp-do-copy-or-rename-file-out-of-band
2019 op filename newname keep-date))
2021 ;; No shortcut was possible. So we copy the file
2022 ;; first. If the operation was `rename', we go back
2023 ;; and delete the original file (if the copy was
2024 ;; successful). The approach is simple-minded: we
2025 ;; create a new buffer, insert the contents of the
2026 ;; source file into it, then write out the buffer to
2027 ;; the target file. The advantage is that it doesn't
2028 ;; matter which file name handlers are used for the
2029 ;; source and target file.
2031 (tramp-do-copy-or-rename-file-via-buffer
2032 op filename newname keep-date))))))
2034 ;; One file is a Tramp file, the other one is local.
2037 ;; Fast track on local machine.
2038 ((tramp-local-host-p v)
2039 (tramp-do-copy-or-rename-file-directly
2041 ok-if-already-exists keep-date preserve-uid-gid))
2043 ;; If the Tramp file has an out-of-band method, the
2044 ;; corresponding copy-program can be invoked.
2045 ((tramp-method-out-of-band-p v length)
2046 (tramp-do-copy-or-rename-file-out-of-band
2047 op filename newname keep-date))
2049 ;; Use the inline method via a Tramp buffer.
2050 (t (tramp-do-copy-or-rename-file-via-buffer
2051 op filename newname keep-date))))
2054 ;; One of them must be a Tramp file.
2055 (error "Tramp implementation says this cannot happen")))
2057 ;; Handle `preserve-extended-attributes'. We ignore possible
2058 ;; errors, because ACL strings could be incompatible.
2061 (apply 'set-file-extended-attributes (list newname attributes))))
2063 ;; In case of `rename', we must flush the cache of the source file.
2064 (when (and t1 (eq op 'rename))
2065 (with-parsed-tramp-file-name filename v1
2066 (tramp-flush-file-property v1 (file-name-directory v1-localname))
2067 (tramp-flush-file-property v1 v1-localname)))
2069 ;; When newname did exist, we have wrong cached values.
2071 (with-parsed-tramp-file-name newname v2
2072 (tramp-flush-file-property v2 (file-name-directory v2-localname))
2073 (tramp-flush-file-property v2 v2-localname)))))))
2075 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
2076 "Use an Emacs buffer to copy or rename a file.
2077 First arg OP is either `copy' or `rename' and indicates the operation.
2078 FILENAME is the source file, NEWNAME the target file.
2079 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
2081 ;; We must disable multibyte, because binary data shall not be
2082 ;; converted. We remove `tramp-file-name-handler' from
2083 ;; `inhibit-file-name-handlers'; otherwise the file name handler
2084 ;; for `insert-file-contents' might be deactivated in some corner
2086 (set-buffer-multibyte nil)
2087 (let ((coding-system-for-read 'binary)
2088 (jka-compr-inhibit t)
2089 (inhibit-file-name-handlers
2090 (remq 'tramp-file-name-handler inhibit-file-name-handlers)))
2091 (insert-file-contents-literally filename))
2092 ;; We don't want the target file to be compressed, so we let-bind
2093 ;; `jka-compr-inhibit' to t.
2094 (let ((coding-system-for-write 'binary)
2095 (jka-compr-inhibit t))
2096 (write-region (point-min) (point-max) newname nil 'no-message)))
2097 ;; KEEP-DATE handling.
2098 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
2100 (set-file-modes newname (tramp-default-file-modes filename))
2101 ;; If the operation was `rename', delete the original file.
2102 (unless (eq op 'copy) (delete-file filename)))
2104 (defun tramp-do-copy-or-rename-file-directly
2105 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
2106 "Invokes `cp' or `mv' on the remote system.
2107 OP must be one of `copy' or `rename', indicating `cp' or `mv',
2108 respectively. FILENAME specifies the file to copy or rename,
2109 NEWNAME is the name of the new file (for copy) or the new name of
2110 the file (for rename). Both files must reside on the same host.
2111 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2112 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2113 the uid and gid from FILENAME."
2114 (let ((t1 (tramp-tramp-file-p filename))
2115 (t2 (tramp-tramp-file-p newname))
2116 (file-times (nth 5 (file-attributes filename)))
2117 (file-modes (tramp-default-file-modes filename)))
2118 (with-parsed-tramp-file-name (if t1 filename newname) nil
2119 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
2120 ((eq op 'copy) "cp -f")
2121 ((eq op 'rename) "mv -f")
2124 "Unknown operation `%s', must be `copy' or `rename'"
2128 (tramp-file-name-handler 'file-remote-p filename 'localname)
2132 (tramp-file-name-handler 'file-remote-p newname 'localname)
2134 (prefix (file-remote-p (if t1 filename newname)))
2138 ;; Both files are on a remote host, with same user.
2141 (tramp-send-command-and-check
2142 v (format "%s %s %s" cmd
2143 (tramp-shell-quote-argument localname1)
2144 (tramp-shell-quote-argument localname2))))
2145 (with-current-buffer (tramp-get-buffer v)
2146 (goto-char (point-min))
2150 ;; Mask cp -f error.
2152 tramp-operation-not-permitted-regexp nil t))
2154 (tramp-error-with-buffer
2156 "Copying directly failed, see buffer `%s' for details."
2159 ;; We are on the local host.
2162 ;; We can do it directly.
2163 ((let (file-name-handler-alist)
2164 (and (file-readable-p localname1)
2165 ;; No sticky bit when renaming.
2169 (file-modes (file-name-directory localname1))
2170 (tramp-compat-octal-to-decimal "1000"))))
2171 (file-writable-p (file-name-directory localname2))
2172 (or (file-directory-p localname2)
2173 (file-writable-p localname2))))
2175 (tramp-compat-copy-file
2176 localname1 localname2 ok-if-already-exists
2177 keep-date preserve-uid-gid)
2178 (tramp-run-real-handler
2179 'rename-file (list localname1 localname2 ok-if-already-exists))))
2181 ;; We can do it directly with `tramp-send-command'
2182 ((and (file-readable-p (concat prefix localname1))
2184 (file-name-directory (concat prefix localname2)))
2185 (or (file-directory-p (concat prefix localname2))
2186 (file-writable-p (concat prefix localname2))))
2187 (tramp-do-copy-or-rename-file-directly
2188 op (concat prefix localname1) (concat prefix localname2)
2189 ok-if-already-exists keep-date t)
2190 ;; We must change the ownership to the local user.
2191 (tramp-set-file-uid-gid
2192 (concat prefix localname2)
2193 (tramp-get-local-uid 'integer)
2194 (tramp-get-local-gid 'integer)))
2196 ;; We need a temporary file in between.
2198 ;; Create the temporary file.
2199 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
2204 (tramp-barf-unless-okay
2207 (tramp-shell-quote-argument localname1)
2208 (tramp-shell-quote-argument tmpfile))
2209 "Copying directly failed, see buffer `%s' for details."
2210 (tramp-get-buffer v))
2211 ;; We must change the ownership as remote user.
2212 ;; Since this does not work reliable, we also
2213 ;; give read permissions.
2215 (concat prefix tmpfile)
2216 (tramp-compat-octal-to-decimal "0777"))
2217 (tramp-set-file-uid-gid
2218 (concat prefix tmpfile)
2219 (tramp-get-local-uid 'integer)
2220 (tramp-get-local-gid 'integer)))
2223 (tramp-compat-copy-file
2224 localname1 tmpfile t
2225 keep-date preserve-uid-gid)
2226 (tramp-run-real-handler
2228 (list localname1 tmpfile t)))
2229 ;; We must change the ownership as local user.
2230 ;; Since this does not work reliable, we also
2231 ;; give read permissions.
2233 tmpfile (tramp-compat-octal-to-decimal "0777"))
2234 (tramp-set-file-uid-gid
2236 (tramp-get-remote-uid v 'integer)
2237 (tramp-get-remote-gid v 'integer))))
2239 ;; Move the temporary file to its destination.
2242 (tramp-barf-unless-okay
2245 (tramp-shell-quote-argument tmpfile)
2246 (tramp-shell-quote-argument localname2))
2247 "Copying directly failed, see buffer `%s' for details."
2248 (tramp-get-buffer v)))
2250 (tramp-run-real-handler
2252 (list tmpfile localname2 ok-if-already-exists)))))
2255 (ignore-errors (delete-file tmpfile)))))))))
2257 ;; Set the time and mode. Mask possible errors.
2260 (set-file-times newname file-times)
2261 (set-file-modes newname file-modes))))))
2263 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
2264 "Invoke `scp' program to copy.
2265 The method used must be an out-of-band method."
2266 (let* ((t1 (tramp-tramp-file-p filename))
2267 (t2 (tramp-tramp-file-p newname))
2268 (orig-vec (tramp-dissect-file-name (if t1 filename newname)))
2269 copy-program copy-args copy-env copy-keep-date port listener spec
2270 options source target remote-copy-program remote-copy-args)
2272 (with-parsed-tramp-file-name (if t1 filename newname) nil
2275 ;; Both are Tramp files. We shall optimize it when the
2276 ;; methods for FILENAME and NEWNAME are the same.
2277 (let* ((dir-flag (file-directory-p filename))
2278 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
2282 (file-name-nondirectory newname) tmpfile)))
2285 (tramp-do-copy-or-rename-file-out-of-band
2286 op filename tmpfile keep-date)
2287 (tramp-do-copy-or-rename-file-out-of-band
2288 'rename tmpfile newname keep-date))
2292 (tramp-compat-delete-directory
2293 (expand-file-name ".." tmpfile) 'recursive)
2294 (delete-file tmpfile)))))
2296 ;; Set variables for computing the prompt for reading
2298 (setq tramp-current-method (tramp-file-name-method v)
2299 tramp-current-user (or (tramp-file-name-user v)
2300 (tramp-get-connection-property
2302 tramp-current-host (tramp-file-name-real-host v))
2304 ;; Expand hops. Might be necessary for gateway methods.
2305 (setq v (car (tramp-compute-multi-hops v)))
2306 (aset v 3 localname)
2308 ;; Check which ones of source and target are Tramp files.
2310 (tramp-make-copy-program-file-name v)
2311 (shell-quote-argument filename))
2313 (if (and (file-directory-p filename)
2315 (file-name-nondirectory filename)
2316 (file-name-nondirectory newname)))
2317 'file-name-directory
2320 (tramp-make-copy-program-file-name v)
2321 (shell-quote-argument newname))))
2323 ;; Check for host and port number. We cannot use
2324 ;; `tramp-file-name-port', because this returns also
2325 ;; `tramp-default-port', which might clash with settings in
2327 (setq host (tramp-file-name-host v)
2329 (when (string-match tramp-host-with-port-regexp host)
2330 (setq port (string-to-number (match-string 2 host))
2331 host (string-to-number (match-string 1 host))))
2333 ;; Check for user. There might be an interactive setting.
2334 (setq user (or (tramp-file-name-user v)
2335 (tramp-get-connection-property v "login-as" nil)))
2337 ;; Check for listener port.
2338 (when (tramp-get-method-parameter method 'tramp-remote-copy-args)
2339 (setq listener (number-to-string (+ 50000 (random 10000))))
2341 (zerop (tramp-call-process v "nc" nil nil nil "-z" host listener))
2342 (setq listener (number-to-string (+ 50000 (random 10000))))))
2344 ;; Compose copy command.
2345 (setq host (or host "")
2348 spec (format-spec-make
2349 ?t (tramp-get-connection-property
2350 (tramp-get-connection-process v) "temp-file" ""))
2351 options (format-spec
2352 (if tramp-use-ssh-controlmaster-options
2353 tramp-ssh-controlmaster-options "")
2355 spec (format-spec-make
2356 ?h host ?u user ?p port ?r listener ?c options
2357 ?k (if keep-date " " ""))
2358 copy-program (tramp-get-method-parameter
2359 method 'tramp-copy-program)
2360 copy-keep-date (tramp-get-method-parameter
2361 method 'tramp-copy-keep-date)
2365 ;; " " has either been a replacement of "%k" (when
2366 ;; keep-date argument is non-nil), or a replacement
2367 ;; for the whole keep-date sublist.
2371 (tramp-get-method-parameter method 'tramp-copy-args)
2376 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2377 (if (member "" y) '(" ") y))))))
2384 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
2385 (unless (member "" x) (mapconcat 'identity x " ")))
2386 (tramp-get-method-parameter method 'tramp-copy-env)))
2389 (tramp-get-method-parameter method 'tramp-remote-copy-program))
2394 (tramp-get-connection-property v "remote-copy-args" nil)
2395 (tramp-get-method-parameter method 'tramp-remote-copy-args)))
2396 (setq remote-copy-args
2399 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2400 (if (member "" y) '(" ") y)))))
2402 ;; Check for local copy program.
2403 (unless (executable-find copy-program)
2405 v 'file-error "Cannot find local copy program: %s" copy-program))
2407 ;; Install listener on the remote side. The prompt must be
2408 ;; consumed later on, when the process does not listen anymore.
2409 (when remote-copy-program
2410 (unless (with-tramp-connection-property
2411 v (concat "remote-copy-program-" remote-copy-program)
2412 (tramp-find-executable
2413 v remote-copy-program (tramp-get-remote-path v)))
2416 "Cannot find remote listener: %s" remote-copy-program))
2417 (setq remote-copy-program
2421 (list remote-copy-program) remote-copy-args
2422 (list (if t1 (concat "<" source) (concat ">" target)) "&"))
2424 (tramp-send-command v remote-copy-program)
2428 "Listener process not running on remote host: `%s'"
2429 remote-copy-program))
2430 (tramp-send-command v (format "netstat -l | grep -q :%s" listener))
2431 (while (not (tramp-send-command-and-check v nil))
2433 v (format "netstat -l | grep -q :%s" listener)))))
2437 ;; The default directory must be remote.
2438 (let ((default-directory
2439 (file-name-directory (if t1 filename newname)))
2440 (process-environment (copy-sequence process-environment)))
2441 ;; Set the transfer process properties.
2442 (tramp-set-connection-property
2443 v "process-name" (buffer-name (current-buffer)))
2444 (tramp-set-connection-property
2445 v "process-buffer" (current-buffer))
2448 orig-vec 6 "%s=\"%s\"" (car copy-env) (cadr copy-env))
2449 (setenv (pop copy-env) (pop copy-env)))
2454 (if remote-copy-program
2455 (list (if t1 (concat ">" target) (concat "<" source)))
2456 (list source target))))
2458 ;; Use an asynchronous process. By this, password can
2459 ;; be handled. We don't set a timeout, because the
2460 ;; copying of large files can last longer than 60
2462 (let ((p (apply 'start-process-shell-command
2463 (tramp-get-connection-name v)
2464 (tramp-get-connection-buffer v)
2468 (list "&&" "echo" "tramp_exit_status" "0"
2469 "||" "echo" "tramp_exit_status" "1")))))
2472 (mapconcat 'identity (process-command p) " "))
2473 (tramp-set-connection-property p "vector" orig-vec)
2474 (tramp-compat-set-process-query-on-exit-flag p nil)
2476 ;; We must adapt `tramp-local-end-of-line' for
2477 ;; sending the password.
2478 (let ((tramp-local-end-of-line tramp-rsh-end-of-line))
2479 (tramp-process-actions
2480 p v nil tramp-actions-copy-out-of-band))
2482 ;; Check the return code.
2483 (goto-char (point-max))
2485 (re-search-backward "tramp_exit_status [0-9]+" nil t)
2487 orig-vec 'file-error
2488 "Couldn't find exit status of `%s'"
2489 (mapconcat 'identity (process-command p) " ")))
2490 (skip-chars-forward "^ ")
2491 (unless (zerop (read (current-buffer)))
2494 orig-vec 'file-error
2495 "Error copying: `%s'"
2496 (buffer-substring (point-min) (point-at-eol))))))
2498 ;; Reset the transfer process properties.
2499 (tramp-set-connection-property v "process-name" nil)
2500 (tramp-set-connection-property v "process-buffer" nil)
2501 ;; Clear the remote prompt.
2502 (when (and remote-copy-program
2503 (not (tramp-send-command-and-check v nil)))
2504 ;; Houston, we have a problem! Likely, the listener is
2505 ;; still running, so let's clear everything (but the
2506 ;; cached password).
2507 (tramp-cleanup-connection v 'keep-debug 'keep-password))))
2509 ;; Handle KEEP-DATE argument.
2510 (when (and keep-date (not copy-keep-date))
2511 (set-file-times newname (nth 5 (file-attributes filename))))
2514 (unless (and keep-date copy-keep-date)
2516 (set-file-modes newname (tramp-default-file-modes filename)))))
2518 ;; If the operation was `rename', delete the original file.
2519 (unless (eq op 'copy)
2520 (if (file-regular-p filename)
2521 (delete-file filename)
2522 (tramp-compat-delete-directory filename 'recursive))))))
2524 (defun tramp-sh-handle-make-directory (dir &optional parents)
2525 "Like `make-directory' for Tramp files."
2526 (setq dir (expand-file-name dir))
2527 (with-parsed-tramp-file-name dir nil
2528 (tramp-flush-directory-property v (file-name-directory localname))
2530 (tramp-barf-unless-okay
2532 (if parents "mkdir -p" "mkdir")
2533 (tramp-shell-quote-argument localname))
2534 "Couldn't make directory %s" dir))))
2536 (defun tramp-sh-handle-delete-directory (directory &optional recursive)
2537 "Like `delete-directory' for Tramp files."
2538 (setq directory (expand-file-name directory))
2539 (with-parsed-tramp-file-name directory nil
2540 (tramp-flush-file-property v (file-name-directory localname))
2541 (tramp-flush-directory-property v localname)
2542 (tramp-barf-unless-okay
2544 (if recursive "rm -rf" "rmdir")
2545 (tramp-shell-quote-argument localname))
2546 "Couldn't delete %s" directory)))
2548 (defun tramp-sh-handle-delete-file (filename &optional trash)
2549 "Like `delete-file' for Tramp files."
2550 (setq filename (expand-file-name filename))
2551 (with-parsed-tramp-file-name filename nil
2552 (tramp-flush-file-property v (file-name-directory localname))
2553 (tramp-flush-file-property v localname)
2554 (tramp-barf-unless-okay
2556 (or (and trash (tramp-get-remote-trash v)) "rm -f")
2557 (tramp-shell-quote-argument localname))
2558 "Couldn't delete %s" filename)))
2562 ;; CCC: This does not seem to be enough. Something dies when
2563 ;; we try and delete two directories under Tramp :/
2564 (defun tramp-sh-handle-dired-recursive-delete-directory (filename)
2565 "Recursively delete the directory given.
2566 This is like `dired-recursive-delete-directory' for Tramp files."
2567 (with-parsed-tramp-file-name filename nil
2568 ;; Run a shell command 'rm -r <localname>'.
2569 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
2570 (unless (file-exists-p filename)
2571 (tramp-error v 'file-error "No such directory: %s" filename))
2572 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>).
2575 (format "rm -rf %s" (tramp-shell-quote-argument localname))
2576 ;; Don't read the output, do it explicitly.
2578 ;; Wait for the remote system to return to us...
2579 ;; This might take a while, allow it plenty of time.
2580 (tramp-wait-for-output (tramp-get-connection-process v) 120)
2581 ;; Make sure that it worked...
2582 (tramp-flush-file-property v (file-name-directory localname))
2583 (tramp-flush-directory-property v localname)
2584 (and (file-exists-p filename)
2586 v 'file-error "Failed to recursively delete %s" filename))))
2588 (defun tramp-sh-handle-dired-compress-file (file &rest _ok-flag)
2589 "Like `dired-compress-file' for Tramp files."
2590 ;; OK-FLAG is valid for XEmacs only, but not implemented.
2591 ;; Code stolen mainly from dired-aux.el.
2592 (with-parsed-tramp-file-name file nil
2593 (tramp-flush-file-property v localname)
2596 (if (not (featurep 'xemacs))
2598 (symbol-value 'dired-compress-file-suffixes)
2599 ;; XEmacs has `dired-compression-method-alist', which is
2600 ;; transformed into `dired-compress-file-suffixes' structure.
2603 (list (concat (regexp-quote (nth 1 x)) "\\'")
2605 (mapconcat 'identity (nth 3 x) " ")))
2606 (symbol-value 'dired-compression-method-alist))))
2608 ;; See if any suffix rule matches this file name.
2610 (let (case-fold-search)
2611 (if (string-match (car (car suffixes)) localname)
2612 (setq suffix (car suffixes) suffixes nil))
2613 (setq suffixes (cdr suffixes))))
2615 (cond ((file-symlink-p file)
2617 ((and suffix (nth 2 suffix))
2618 ;; We found an uncompression rule.
2619 (with-tramp-progress-reporter
2620 v 0 (format "Uncompressing %s" file)
2621 (when (tramp-send-command-and-check
2622 v (concat (nth 2 suffix) " "
2623 (tramp-shell-quote-argument localname)))
2624 ;; `dired-remove-file' is not defined in XEmacs.
2625 (tramp-compat-funcall 'dired-remove-file file)
2626 (string-match (car suffix) file)
2627 (concat (substring file 0 (match-beginning 0))))))
2629 ;; We don't recognize the file as compressed, so compress it.
2631 (with-tramp-progress-reporter v 0 (format "Compressing %s" file)
2632 (when (tramp-send-command-and-check
2633 v (concat "gzip -f "
2634 (tramp-shell-quote-argument localname)))
2635 ;; `dired-remove-file' is not defined in XEmacs.
2636 (tramp-compat-funcall 'dired-remove-file file)
2637 (cond ((file-exists-p (concat file ".gz"))
2638 (concat file ".gz"))
2639 ((file-exists-p (concat file ".z"))
2643 (defun tramp-sh-handle-insert-directory
2644 (filename switches &optional wildcard full-directory-p)
2645 "Like `insert-directory' for Tramp files."
2646 (setq filename (expand-file-name filename))
2647 (unless switches (setq switches ""))
2648 (with-parsed-tramp-file-name filename nil
2649 (if (and (featurep 'ls-lisp)
2650 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
2651 (tramp-handle-insert-directory
2652 filename switches wildcard full-directory-p)
2653 (when (stringp switches)
2654 (setq switches (split-string switches)))
2655 (when (and (member "--dired" switches)
2656 (not (tramp-get-ls-command-with-dired v)))
2657 (setq switches (delete "--dired" switches)))
2659 (setq wildcard (tramp-run-real-handler
2660 'file-name-nondirectory (list localname)))
2661 (setq localname (tramp-run-real-handler
2662 'file-name-directory (list localname))))
2663 (unless (or full-directory-p (member "-d" switches))
2664 (setq switches (append switches '("-d"))))
2665 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
2667 (setq switches (concat switches " " wildcard)))
2669 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
2670 switches filename (if wildcard "yes" "no")
2671 (if full-directory-p "yes" "no"))
2672 ;; If `full-directory-p', we just say `ls -l FILENAME'.
2673 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
2674 (if full-directory-p
2677 (format "%s %s %s 2>/dev/null"
2678 (tramp-get-ls-command v)
2682 (tramp-shell-quote-argument (concat localname ".")))))
2683 (tramp-barf-unless-okay
2685 (format "cd %s" (tramp-shell-quote-argument
2686 (tramp-run-real-handler
2687 'file-name-directory (list localname))))
2689 (tramp-shell-quote-argument
2690 (tramp-run-real-handler 'file-name-directory (list localname))))
2693 (format "%s %s %s 2>/dev/null"
2694 (tramp-get-ls-command v)
2698 (tramp-run-real-handler
2699 'file-name-nondirectory (list localname)))))
2701 (tramp-shell-quote-argument
2702 (tramp-run-real-handler
2703 'file-name-nondirectory (list localname)))))))
2706 (let ((beg (point)))
2707 (narrow-to-region (point) (point))
2708 ;; We cannot use `insert-buffer-substring' because the Tramp
2709 ;; buffer changes its contents before insertion due to calling
2710 ;; `expand-file' and alike.
2712 (with-current-buffer (tramp-get-buffer v)
2715 ;; Check for "--dired" output.
2717 (when (looking-at "//SUBDIRED//")
2719 (when (looking-at "//DIRED//\\s-+")
2720 (let ((databeg (match-end 0))
2721 (end (point-at-eol)))
2722 ;; Now read the numeric positions of file names.
2724 (while (< (point) end)
2725 (let ((start (+ beg (read (current-buffer))))
2726 (end (+ beg (read (current-buffer)))))
2727 (if (memq (char-after end) '(?\n ?\ ))
2728 ;; End is followed by \n or by " -> ".
2729 (put-text-property start end 'dired-filename t))))))
2730 ;; Remove trailing lines.
2731 (goto-char (point-at-bol))
2732 (while (looking-at "//")
2734 (delete-region (match-beginning 0) (point)))
2736 ;; Some busyboxes are reluctant to discard colors.
2738 (string-match "color" (tramp-get-connection-property v "ls" ""))
2740 (while (re-search-forward tramp-color-escape-sequence-regexp nil t)
2741 (replace-match "")))
2743 ;; Decode the output, it could be multibyte.
2744 (decode-coding-region
2746 (or file-name-coding-system
2747 (and (boundp 'default-file-name-coding-system)
2748 (symbol-value 'default-file-name-coding-system))))
2750 ;; The inserted file could be from somewhere else.
2751 (when (and (not wildcard) (not full-directory-p))
2752 (goto-char (point-max))
2753 (when (file-symlink-p filename)
2754 (goto-char (search-backward "->" beg 'noerror)))
2756 (if (zerop (length (file-name-nondirectory filename)))
2758 (file-name-nondirectory filename))
2760 (replace-match (file-relative-name filename) t))
2762 (goto-char (point-max)))))))
2764 ;; Canonicalization of file names.
2766 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2767 "Like `expand-file-name' for Tramp files.
2768 If the localname part of the given file name starts with \"/../\" then
2769 the result will be a local, non-Tramp, file name."
2770 ;; If DIR is not given, use `default-directory' or "/".
2771 (setq dir (or dir default-directory "/"))
2772 ;; Unless NAME is absolute, concat DIR and NAME.
2773 (unless (file-name-absolute-p name)
2774 (setq name (concat (file-name-as-directory dir) name)))
2775 ;; If NAME is not a Tramp file, run the real handler.
2776 (if (not (tramp-connectable-p name))
2777 (tramp-run-real-handler 'expand-file-name (list name nil))
2779 (with-parsed-tramp-file-name name nil
2780 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2781 (setq localname (concat "~/" localname)))
2782 ;; Tilde expansion if necessary. This needs a shell which
2783 ;; groks tilde expansion! The function `tramp-find-shell' is
2784 ;; supposed to find such a shell on the remote host. Please
2785 ;; tell me about it when this doesn't work on your system.
2786 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2787 (let ((uname (match-string 1 localname))
2788 (fname (match-string 2 localname)))
2789 ;; We cannot simply apply "~/", because under sudo "~/" is
2790 ;; expanded to the local user home directory but to the
2791 ;; root home directory. On the other hand, using always
2792 ;; the default user name for tilde expansion is not
2793 ;; appropriate either, because ssh and companions might
2794 ;; use a user name from the config file.
2795 (when (and (string-equal uname "~")
2796 (string-match "\\`su\\(do\\)?\\'" method))
2797 (setq uname (concat uname user)))
2799 (with-tramp-connection-property v uname
2801 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
2802 (with-current-buffer (tramp-get-buffer v)
2803 (goto-char (point-min))
2804 (buffer-substring (point) (point-at-eol)))))
2805 (setq localname (concat uname fname))))
2806 ;; There might be a double slash, for example when "~/"
2807 ;; expands to "/". Remove this.
2808 (while (string-match "//" localname)
2809 (setq localname (replace-match "/" t t localname)))
2810 ;; No tilde characters in file name, do normal
2811 ;; `expand-file-name' (this does "/./" and "/../"). We bind
2812 ;; `directory-sep-char' here for XEmacs on Windows, which would
2813 ;; otherwise use backslash. `default-directory' is bound,
2814 ;; because on Windows there would be problems with UNC shares or
2816 (let ((directory-sep-char ?/)
2817 (default-directory (tramp-compat-temporary-file-directory)))
2818 (tramp-make-tramp-file-name
2820 (tramp-drop-volume-letter
2821 (tramp-run-real-handler
2822 'expand-file-name (list localname)))
2825 ;;; Remote commands:
2827 (defun tramp-process-sentinel (proc event)
2828 "Flush file caches."
2829 (unless (memq (process-status proc) '(run open))
2830 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2832 (tramp-message vec 5 "Sentinel called: `%S' `%s'" proc event)
2833 (tramp-flush-connection-property proc)
2834 (tramp-flush-directory-property vec "")))))
2836 ;; We use BUFFER also as connection buffer during setup. Because of
2837 ;; this, its original contents must be saved, and restored once
2838 ;; connection has been setup.
2839 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2840 "Like `start-file-process' for Tramp files."
2841 (with-parsed-tramp-file-name (expand-file-name default-directory) nil
2842 (let* (;; When PROGRAM matches "*sh", and the first arg is "-c",
2843 ;; it might be that the arguments exceed the command line
2844 ;; length. Therefore, we modify the command.
2845 (heredoc (and (stringp program)
2846 (string-match "sh$" program)
2847 (string-equal "-c" (car args))
2848 (= (length args) 2)))
2849 ;; When PROGRAM is nil, we just provide a tty.
2850 (args (if (not heredoc) args
2852 (while (and (< i (length (cadr args)))
2853 (string-match " " (cadr args) i))
2856 (list (replace-match " \\\\\n" nil nil (cadr args))))
2857 (setq i (+ i 250))))
2859 ;; Use a human-friendly prompt, for example for `shell'.
2860 (prompt (format "PS1=%s"
2862 (file-remote-p default-directory)
2863 tramp-initial-end-of-output)))
2864 ;; We use as environment the difference to toplevel
2865 ;; `process-environment'.
2870 (cons prompt (nreverse (copy-sequence process-environment)))
2872 (or (member elt (default-toplevel-value 'process-environment))
2873 (setq env (cons elt env)))))
2875 (when (stringp program)
2876 (format "cd %s && exec %s env %s %s"
2877 (tramp-shell-quote-argument localname)
2878 (if heredoc (format "<<'%s'" tramp-end-of-heredoc) "")
2879 (mapconcat 'tramp-shell-quote-argument env " ")
2881 (format "%s\n(\n%s\n) </dev/tty\n%s"
2882 program (car args) tramp-end-of-heredoc)
2883 (mapconcat 'tramp-shell-quote-argument
2884 (cons program args) " ")))))
2885 (tramp-process-connection-type
2886 (or (null program) tramp-process-connection-type))
2887 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2890 ;; We do not want to raise an error when
2891 ;; `start-file-process' has been started several times in
2892 ;; `eshell' and friends.
2893 (tramp-current-connection nil))
2896 ;; BUFFER can be nil. We use a temporary buffer.
2897 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
2898 (while (get-process name1)
2899 ;; NAME must be unique as process name.
2901 name1 (format "%s<%d>" name i)))
2903 ;; Set the new process properties.
2904 (tramp-set-connection-property v "process-name" name)
2905 (tramp-set-connection-property v "process-buffer" buffer)
2907 (with-current-buffer (tramp-get-connection-buffer v)
2909 ;; We catch this event. Otherwise, `start-process' could
2910 ;; be called on the local host.
2913 ;; Activate narrowing in order to save BUFFER
2914 ;; contents. Clear also the modification time;
2915 ;; otherwise we might be interrupted by
2916 ;; `verify-visited-file-modtime'.
2917 (let ((buffer-undo-list t)
2918 (buffer-read-only nil)
2920 (clear-visited-file-modtime)
2921 (narrow-to-region (point-max) (point-max))
2922 ;; We call `tramp-maybe-open-connection', in order
2923 ;; to cleanup the prompt afterwards.
2925 (tramp-maybe-open-connection v)
2927 (delete-region mark (point))
2928 (narrow-to-region (point-max) (point-max))
2931 ;; Send the command.
2932 (tramp-send-command v command nil t) ; nooutput
2933 ;; Check, whether a pty is associated.
2934 (unless (tramp-compat-process-get
2935 (tramp-get-connection-process v) 'remote-tty)
2938 "pty association is not supported for `%s'" name))))
2939 (let ((p (tramp-get-connection-process v)))
2940 ;; Set query flag and process marker for this
2941 ;; process. We ignore errors, because the process
2942 ;; could have finished already.
2944 (tramp-compat-set-process-query-on-exit-flag p t)
2945 (set-marker (process-mark p) (point)))
2950 (if (string-match tramp-temp-buffer-name (buffer-name))
2952 (set-process-buffer (tramp-get-connection-process v) nil)
2953 (kill-buffer (current-buffer)))
2954 (set-buffer-modified-p bmp))
2955 (tramp-set-connection-property v "process-name" nil)
2956 (tramp-set-connection-property v "process-buffer" nil))))))
2958 (defun tramp-sh-handle-process-file
2959 (program &optional infile destination display &rest args)
2960 "Like `process-file' for Tramp files."
2961 ;; The implementation is not complete yet.
2962 (when (and (numberp destination) (zerop destination))
2963 (error "Implementation does not handle immediate return"))
2965 (with-parsed-tramp-file-name default-directory nil
2966 (let (command env input tmpinput stderr tmpstderr outbuf ret)
2968 (setq command (mapconcat 'tramp-shell-quote-argument
2969 (cons program args) " "))
2970 ;; We use as environment the difference to toplevel `process-environment'.
2972 (dolist (elt (nreverse (copy-sequence process-environment)) env)
2973 (or (member elt (default-toplevel-value 'process-environment))
2974 (setq env (cons elt env)))))
2979 (mapconcat 'tramp-shell-quote-argument env " ") command)))
2982 (setq input "/dev/null")
2983 (setq infile (expand-file-name infile))
2984 (if (tramp-equal-remote default-directory infile)
2985 ;; INFILE is on the same remote host.
2986 (setq input (with-parsed-tramp-file-name infile nil localname))
2987 ;; INFILE must be copied to remote host.
2988 (setq input (tramp-make-tramp-temp-file v)
2989 tmpinput (tramp-make-tramp-file-name method user host input))
2990 (copy-file infile tmpinput t)))
2991 (when input (setq command (format "%s <%s" command input)))
2993 ;; Determine output.
2996 ((bufferp destination)
2997 (setq outbuf destination))
2999 ((stringp destination)
3000 (setq outbuf (get-buffer-create destination)))
3001 ;; (REAL-DESTINATION ERROR-DESTINATION)
3002 ((consp destination)
3005 ((bufferp (car destination))
3006 (setq outbuf (car destination)))
3007 ((stringp (car destination))
3008 (setq outbuf (get-buffer-create (car destination))))
3010 (setq outbuf (current-buffer))))
3013 ((stringp (cadr destination))
3014 (setcar (cdr destination) (expand-file-name (cadr destination)))
3015 (if (tramp-equal-remote default-directory (cadr destination))
3016 ;; stderr is on the same remote host.
3017 (setq stderr (with-parsed-tramp-file-name
3018 (cadr destination) nil localname))
3019 ;; stderr must be copied to remote host. The temporary
3020 ;; file must be deleted after execution.
3021 (setq stderr (tramp-make-tramp-temp-file v)
3022 tmpstderr (tramp-make-tramp-file-name
3023 method user host stderr))))
3024 ;; stderr to be discarded.
3025 ((null (cadr destination))
3026 (setq stderr "/dev/null"))))
3029 (setq outbuf (current-buffer))))
3030 (when stderr (setq command (format "%s 2>%s" command stderr)))
3032 ;; Send the command. It might not return in time, so we protect
3033 ;; it. Call it in a subshell, in order to preserve working
3038 (if (tramp-send-command-and-check
3039 v (format "\\cd %s; %s"
3040 (tramp-shell-quote-argument localname)
3044 ;; We should add the output anyway.
3046 (with-current-buffer outbuf
3048 (with-current-buffer (tramp-get-connection-buffer v)
3050 (when (and display (get-buffer-window outbuf t)) (redisplay))))
3051 ;; When the user did interrupt, we should do it also. We use
3052 ;; return code -1 as marker.
3054 (kill-buffer (tramp-get-connection-buffer v))
3058 (kill-buffer (tramp-get-connection-buffer v))
3061 ;; Provide error file.
3062 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3064 ;; Cleanup. We remove all file cache values for the connection,
3065 ;; because the remote process could have changed them.
3066 (when tmpinput (delete-file tmpinput))
3068 ;; `process-file-side-effects' has been introduced with GNU
3069 ;; Emacs 23.2. If set to `nil', no remote file will be changed
3070 ;; by `program'. If it doesn't exist, we assume its default
3072 (unless (and (boundp 'process-file-side-effects)
3073 (not (symbol-value 'process-file-side-effects)))
3074 (tramp-flush-directory-property v ""))
3076 ;; Return exit status.
3081 (defun tramp-sh-handle-file-local-copy (filename)
3082 "Like `file-local-copy' for Tramp files."
3083 (with-parsed-tramp-file-name filename nil
3084 (unless (file-exists-p filename)
3087 "Cannot make local copy of non-existing file `%s'" filename))
3089 (let* ((size (nth 7 (file-attributes (file-truename filename))))
3090 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
3091 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
3092 (tmpfile (tramp-compat-make-temp-file filename)))
3096 ;; `copy-file' handles direct copy and out-of-band methods.
3097 ((or (tramp-local-host-p v)
3098 (tramp-method-out-of-band-p v size))
3099 (copy-file filename tmpfile t t))
3101 ;; Use inline encoding for file transfer.
3104 (with-tramp-progress-reporter
3106 (format "Encoding remote file `%s' with `%s'" filename rem-enc)
3107 (tramp-barf-unless-okay
3108 v (format rem-enc (tramp-shell-quote-argument localname))
3109 "Encoding remote file failed"))
3111 (with-tramp-progress-reporter
3112 v 3 (format "Decoding local file `%s' with `%s'"
3114 (if (functionp loc-dec)
3115 ;; If local decoding is a function, we call it.
3116 ;; We must disable multibyte, because
3117 ;; `uudecode-decode-region' doesn't handle it
3120 (set-buffer-multibyte nil)
3121 (insert-buffer-substring (tramp-get-buffer v))
3122 (funcall loc-dec (point-min) (point-max))
3123 ;; Unset `file-name-handler-alist'. Otherwise,
3124 ;; epa-file gets confused.
3125 (let (file-name-handler-alist
3126 (coding-system-for-write 'binary))
3128 (point-min) (point-max) tmpfile nil 'no-message)))
3130 ;; If tramp-decoding-function is not defined for this
3131 ;; method, we invoke tramp-decoding-command instead.
3132 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3133 ;; Unset `file-name-handler-alist'. Otherwise,
3134 ;; epa-file gets confused.
3135 (let (file-name-handler-alist
3136 (coding-system-for-write 'binary))
3137 (with-current-buffer (tramp-get-buffer v)
3139 (point-min) (point-max) tmpfile2 nil 'no-message)))
3141 (tramp-call-local-coding-command
3142 loc-dec tmpfile2 tmpfile)
3143 (delete-file tmpfile2)))))
3145 ;; Set proper permissions.
3146 (set-file-modes tmpfile (tramp-default-file-modes filename))
3147 ;; Set local user ownership.
3148 (tramp-set-file-uid-gid tmpfile)))
3150 ;; Oops, I don't know what to do.
3152 v 'file-error "Wrong method specification for `%s'" method)))
3156 (delete-file tmpfile)
3157 (signal (car err) (cdr err))))
3159 (run-hooks 'tramp-handle-file-local-copy-hook)
3162 ;; This is needed for XEmacs only. Code stolen from files.el.
3163 (defun tramp-sh-handle-insert-file-contents-literally
3164 (filename &optional visit beg end replace)
3165 "Like `insert-file-contents-literally' for Tramp files."
3166 (let ((format-alist nil)
3167 (after-insert-file-functions nil)
3168 (coding-system-for-read 'no-conversion)
3169 (coding-system-for-write 'no-conversion)
3170 (find-buffer-file-type-function
3171 (if (fboundp 'find-buffer-file-type)
3172 (symbol-function 'find-buffer-file-type)
3174 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
3175 (inhibit-file-name-operation 'insert-file-contents))
3178 (fset 'find-buffer-file-type (lambda (_filename) t))
3179 (insert-file-contents filename visit beg end replace))
3181 (if find-buffer-file-type-function
3182 (fset 'find-buffer-file-type find-buffer-file-type-function)
3183 (fmakunbound 'find-buffer-file-type)))))
3185 ;; CCC grok LOCKNAME
3186 (defun tramp-sh-handle-write-region
3187 (start end filename &optional append visit lockname confirm)
3188 "Like `write-region' for Tramp files."
3189 (setq filename (expand-file-name filename))
3190 (with-parsed-tramp-file-name filename nil
3191 ;; Following part commented out because we don't know what to do about
3192 ;; file locking, and it does not appear to be a problem to ignore it.
3193 ;; Ange-ftp ignores it, too.
3194 ;; (when (and lockname (stringp lockname))
3195 ;; (setq lockname (expand-file-name lockname)))
3196 ;; (unless (or (eq lockname nil)
3197 ;; (string= lockname filename))
3199 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3201 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
3202 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
3203 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3204 (tramp-error v 'file-error "File not overwritten")))
3206 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
3207 (tramp-get-remote-uid v 'integer)))
3208 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
3209 (tramp-get-remote-gid v 'integer))))
3211 (if (and (tramp-local-host-p v)
3212 ;; `file-writable-p' calls `file-expand-file-name'. We
3213 ;; cannot use `tramp-run-real-handler' therefore.
3214 (let (file-name-handler-alist)
3216 (file-writable-p (file-name-directory localname))
3217 (or (file-directory-p localname)
3218 (file-writable-p localname)))))
3219 ;; Short track: if we are on the local host, we can run directly.
3220 (tramp-run-real-handler
3222 (list start end localname append 'no-message lockname confirm))
3224 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3225 ;; We use this to save the value of
3226 ;; `last-coding-system-used' after writing the tmp
3227 ;; file. At the end of the function, we set
3228 ;; `last-coding-system-used' to this saved value. This
3229 ;; way, any intermediary coding systems used while
3230 ;; talking to the remote shell or suchlike won't hose
3231 ;; this variable. This approach was snarfed from
3234 ;; Write region into a tmp file. This isn't really
3235 ;; needed if we use an encoding function, but currently
3236 ;; we use it always because this makes the logic
3237 ;; simpler. We must also set `temporary-file-directory',
3238 ;; because it could point to a remote directory.
3239 (temporary-file-directory
3240 (tramp-compat-temporary-file-directory))
3241 (tmpfile (or tramp-temp-buffer-file-name
3242 (tramp-compat-make-temp-file filename))))
3244 ;; If `append' is non-nil, we copy the file locally, and let
3245 ;; the native `write-region' implementation do the job.
3246 (when append (copy-file filename tmpfile 'ok))
3248 ;; We say `no-message' here because we don't want the
3249 ;; visited file modtime data to be clobbered from the temp
3250 ;; file. We call `set-visited-file-modtime' ourselves later
3251 ;; on. We must ensure that `file-coding-system-alist'
3252 ;; matches `tmpfile'.
3253 (let (file-name-handler-alist
3254 (file-coding-system-alist
3255 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3257 (tramp-run-real-handler
3259 (list start end tmpfile append 'no-message lockname confirm))
3261 (setq tramp-temp-buffer-file-name nil)
3262 (delete-file tmpfile)
3263 (signal (car err) (cdr err))))
3265 ;; Now, `last-coding-system-used' has the right value. Remember it.
3266 (when (boundp 'last-coding-system-used)
3267 (setq coding-system-used
3268 (symbol-value 'last-coding-system-used))))
3270 ;; The permissions of the temporary file should be set. If
3271 ;; FILENAME does not exist (eq modes nil) it has been
3272 ;; renamed to the backup file. This case `save-buffer'
3273 ;; handles permissions.
3274 ;; Ensure that it is still readable.
3278 (logior (or modes 0) (tramp-compat-octal-to-decimal "0400"))))
3280 ;; This is a bit lengthy due to the different methods
3281 ;; possible for file transfer. First, we check whether the
3282 ;; method uses an scp program. If so, we call it.
3283 ;; Otherwise, both encoding and decoding command must be
3284 ;; specified. However, if the method _also_ specifies an
3285 ;; encoding function, then that is used for encoding the
3286 ;; contents of the tmp file.
3287 (let* ((size (nth 7 (file-attributes tmpfile)))
3288 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3289 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3291 ;; `copy-file' handles direct copy and out-of-band methods.
3292 ((or (tramp-local-host-p v)
3293 (tramp-method-out-of-band-p v size))
3294 (if (and (not (stringp start))
3295 (= (or end (point-max)) (point-max))
3296 (= (or start (point-min)) (point-min))
3297 (tramp-get-method-parameter
3298 method 'tramp-copy-keep-tmpfile))
3300 (setq tramp-temp-buffer-file-name tmpfile)
3302 ;; We keep the local file for performance
3303 ;; reasons, useful for "rsync".
3304 (copy-file tmpfile filename t)
3306 (setq tramp-temp-buffer-file-name nil)
3307 (delete-file tmpfile)
3308 (signal (car err) (cdr err)))))
3309 (setq tramp-temp-buffer-file-name nil)
3310 ;; Don't rename, in order to keep context in SELinux.
3312 (copy-file tmpfile filename t)
3313 (delete-file tmpfile))))
3315 ;; Use inline file transfer.
3320 (set-buffer-multibyte nil)
3321 ;; Use encoding function or command.
3322 (with-tramp-progress-reporter
3323 v 3 (format "Encoding local file `%s' using `%s'"
3325 (if (functionp loc-enc)
3326 ;; The following `let' is a workaround for
3327 ;; the base64.el that comes with pgnus-0.84.
3328 ;; If both of the following conditions are
3329 ;; satisfied, it tries to write to a local
3330 ;; file in default-directory, but at this
3331 ;; point, default-directory is remote.
3332 ;; (`call-process-region' can't write to
3333 ;; remote files, it seems.) The file in
3334 ;; question is a tmp file anyway.
3335 (let ((coding-system-for-read 'binary)
3337 (tramp-compat-temporary-file-directory)))
3338 (insert-file-contents-literally tmpfile)
3339 (funcall loc-enc (point-min) (point-max)))
3341 (unless (zerop (tramp-call-local-coding-command
3345 (concat "Cannot write to `%s', "
3346 "local encoding command `%s' failed")
3347 filename loc-enc))))
3349 ;; Send buffer into remote decoding command which
3350 ;; writes to remote file. Because this happens on
3351 ;; the remote host, we cannot use the function.
3352 (with-tramp-progress-reporter
3353 v 3 (format "Decoding remote file `%s' using `%s'"
3355 (goto-char (point-max))
3356 (unless (bolp) (newline))
3360 (concat rem-dec " <<'%s'\n%s%s")
3361 (tramp-shell-quote-argument localname)
3362 tramp-end-of-heredoc
3364 tramp-end-of-heredoc))
3365 (tramp-barf-unless-okay
3367 "Couldn't write region to `%s', decode using `%s' failed"
3369 ;; When `file-precious-flag' is set, the region is
3370 ;; written to a temporary file. Check that the
3371 ;; checksum is equal to that from the local tmpfile.
3372 (when file-precious-flag
3375 ;; cksum runs locally, if possible.
3376 (zerop (tramp-call-process v "cksum" tmpfile t))
3377 ;; cksum runs remotely.
3378 (tramp-send-command-and-check
3381 "cksum <%s" (tramp-shell-quote-argument localname)))
3382 ;; ... they are different.
3386 (with-current-buffer (tramp-get-buffer v)
3390 (concat "Couldn't write region to `%s',"
3391 " decode using `%s' failed")
3392 filename rem-dec)))))
3395 (delete-file tmpfile)))
3397 ;; That's not expected.
3401 (concat "Method `%s' should specify both encoding and "
3402 "decoding command or an scp program")
3405 ;; Make `last-coding-system-used' have the right value.
3406 (when coding-system-used
3407 (set 'last-coding-system-used coding-system-used))))
3409 (tramp-flush-file-property v (file-name-directory localname))
3410 (tramp-flush-file-property v localname)
3412 ;; We must protect `last-coding-system-used', now we have set it
3413 ;; to its correct value.
3414 (let (last-coding-system-used (need-chown t))
3415 ;; Set file modification time.
3416 (when (or (eq visit t) (stringp visit))
3417 (let ((file-attr (tramp-compat-file-attributes filename 'integer)))
3418 (set-visited-file-modtime
3419 ;; We must pass modtime explicitly, because FILENAME can
3420 ;; be different from (buffer-file-name), f.e. if
3421 ;; `file-precious-flag' is set.
3423 (when (and (= (nth 2 file-attr) uid)
3424 (= (nth 3 file-attr) gid))
3425 (setq need-chown nil))))
3427 ;; Set the ownership.
3429 (tramp-set-file-uid-gid filename uid gid))
3430 (when (or (eq visit t) (null visit) (stringp visit))
3431 (tramp-message v 0 "Wrote %s" filename))
3432 (run-hooks 'tramp-handle-write-region-hook)))))
3434 (defvar tramp-vc-registered-file-names nil
3435 "List used to collect file names, which are checked during `vc-registered'.")
3437 ;; VC backends check for the existence of various different special
3438 ;; files. This is very time consuming, because every single check
3439 ;; requires a remote command (the file cache must be invalidated).
3440 ;; Therefore, we apply a kind of optimization. We install the file
3441 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3442 ;; remembers all file names for which `file-exists-p' or
3443 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3444 ;; is performed. Afterwards, a script is applied for all collected
3445 ;; file names, using just one remote command. The result of this
3446 ;; script is used to fill the file cache with actual values. Now we
3447 ;; can reset the file name handlers, and we make a second run of
3448 ;; `vc-registered', which returns the expected result without sending
3449 ;; any other remote command.
3450 (defun tramp-sh-handle-vc-registered (file)
3451 "Like `vc-registered' for Tramp files."
3452 (tramp-compat-with-temp-message ""
3453 (with-parsed-tramp-file-name file nil
3454 (with-tramp-progress-reporter
3455 v 3 (format "Checking `vc-registered' for %s" file)
3457 ;; There could be new files, created by the vc backend. We
3458 ;; cannot reuse the old cache entries, therefore. In
3459 ;; `tramp-get-file-property', `remote-file-name-inhibit-cache'
3460 ;; could also be a timestamp as `current-time' returns. This
3461 ;; means invalidate all cache entries with an older timestamp.
3462 (let (tramp-vc-registered-file-names
3463 (remote-file-name-inhibit-cache (current-time))
3464 (file-name-handler-alist
3465 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3467 ;; Here we collect only file names, which need an operation.
3468 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3469 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3471 ;; Send just one command, in order to fill the cache.
3472 (when tramp-vc-registered-file-names
3473 (tramp-maybe-send-script
3475 (format tramp-vc-registered-read-file-names
3476 (tramp-get-file-exists-command v)
3477 (format "%s -r" (tramp-get-test-command v)))
3478 "tramp_vc_registered_read_file_names")
3483 ;; We cannot use `tramp-send-command-and-read',
3484 ;; because this does not cooperate well with
3485 ;; heredoc documents.
3489 "tramp_vc_registered_read_file_names <<'%s'\n%s\n%s\n"
3490 tramp-end-of-heredoc
3491 (mapconcat 'tramp-shell-quote-argument
3492 tramp-vc-registered-file-names
3494 tramp-end-of-heredoc))
3495 (with-current-buffer (tramp-get-connection-buffer v)
3496 ;; Read the expression.
3497 (goto-char (point-min))
3498 (read (current-buffer)))))
3500 (tramp-set-file-property
3501 v (car elt) (cadr elt) (cadr (cdr elt))))))
3503 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3504 ;; calls shall be answered from the file cache. We unset
3505 ;; `process-file-side-effects' and `remote-file-name-inhibit-cache'
3506 ;; in order to keep the cache.
3507 (let ((vc-handled-backends vc-handled-backends)
3508 remote-file-name-inhibit-cache process-file-side-effects)
3509 ;; Reduce `vc-handled-backends' in order to minimize process calls.
3510 (when (and (memq 'Bzr vc-handled-backends)
3511 (boundp 'vc-bzr-program)
3512 (not (with-tramp-connection-property v vc-bzr-program
3513 (tramp-find-executable
3514 v vc-bzr-program (tramp-get-remote-path v)))))
3515 (setq vc-handled-backends (remq 'Bzr vc-handled-backends)))
3516 (when (and (memq 'Git vc-handled-backends)
3517 (boundp 'vc-git-program)
3518 (not (with-tramp-connection-property v vc-git-program
3519 (tramp-find-executable
3520 v vc-git-program (tramp-get-remote-path v)))))
3521 (setq vc-handled-backends (remq 'Git vc-handled-backends)))
3522 (when (and (memq 'Hg vc-handled-backends)
3523 (boundp 'vc-hg-program)
3524 (not (with-tramp-connection-property v vc-hg-program
3525 (tramp-find-executable
3526 v vc-hg-program (tramp-get-remote-path v)))))
3527 (setq vc-handled-backends (remq 'Hg vc-handled-backends)))
3530 (tramp-run-real-handler 'vc-registered (list file))))))))
3532 ;;;###tramp-autoload
3533 (defun tramp-sh-file-name-handler (operation &rest args)
3534 "Invoke remote-shell Tramp file name handler.
3535 Fall back to normal file name handler if no Tramp handler exists."
3536 (when (and tramp-locked (not tramp-locker))
3537 (setq tramp-locked nil)
3539 (car-safe tramp-current-connection) 'file-error
3540 "Forbidden reentrant call of Tramp"))
3541 (let ((tl tramp-locked))
3542 (setq tramp-locked t)
3544 (let ((tramp-locker t))
3546 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3548 (apply (cdr fn) args)
3549 (tramp-run-real-handler operation args)))))
3550 (setq tramp-locked tl))))
3552 (defun tramp-vc-file-name-handler (operation &rest args)
3553 "Invoke special file name handler, which collects files to be handled."
3556 (tramp-replace-environment-variables
3557 (apply 'tramp-file-name-for-operation operation args)))
3558 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3559 (with-parsed-tramp-file-name filename nil
3561 ;; That's what we want: file names, for which checks are
3562 ;; applied. We assume that VC uses only `file-exists-p' and
3563 ;; `file-readable-p' checks; otherwise we must extend the
3564 ;; list. We do not perform any action, but return nil, in
3565 ;; order to keep `vc-registered' running.
3566 ((and fn (memq operation '(file-exists-p file-readable-p)))
3567 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3569 ;; `process-file' and `start-file-process' shall be ignored.
3570 ((and fn (eq operation 'process-file) 0))
3571 ((and fn (eq operation 'start-file-process) nil))
3572 ;; Tramp file name handlers like `expand-file-name'. They
3574 (fn (save-match-data (apply (cdr fn) args)))
3575 ;; Default file name handlers, we don't care.
3576 (t (tramp-run-real-handler operation args)))))))
3578 (defun tramp-sh-handle-file-notify-add-watch (file-name flags _callback)
3579 "Like `file-notify-add-watch' for Tramp files."
3580 (setq file-name (expand-file-name file-name))
3581 (with-parsed-tramp-file-name file-name nil
3582 (let* ((default-directory (file-name-directory file-name))
3583 command events filter p sequence)
3585 ;; gvfs-monitor-dir.
3586 ((setq command (tramp-get-remote-gvfs-monitor-dir v))
3587 (setq filter 'tramp-sh-file-gvfs-monitor-dir-process-filter
3588 sequence `(,command ,localname)))
3590 ((setq command (tramp-get-remote-inotifywait v))
3591 (setq filter 'tramp-sh-file-inotifywait-process-filter
3594 ((and (memq 'change flags) (memq 'attribute-change flags))
3595 "create,modify,move,delete,attrib")
3596 ((memq 'change flags) "create,modify,move,delete")
3597 ((memq 'attribute-change flags) "attrib"))
3598 sequence `(,command "-mq" "-e" ,events ,localname)))
3601 v 'file-notify-error
3602 "No file notification program found on %s"
3603 (file-remote-p file-name))))
3607 (file-name-nondirectory command)
3608 (generate-new-buffer
3609 (format " *%s*" (file-name-nondirectory command)))
3611 ;; Return the process object as watch-descriptor.
3612 (if (not (processp p))
3614 v 'file-notify-error
3615 "`%s' failed to start on remote host"
3616 (mapconcat 'identity sequence " "))
3617 (tramp-message v 6 "Run `%s', %S" (mapconcat 'identity sequence " ") p)
3618 (tramp-set-connection-property p "vector" v)
3619 (tramp-compat-set-process-query-on-exit-flag p nil)
3620 (set-process-filter p filter)
3623 (defun tramp-sh-file-gvfs-monitor-dir-process-filter (proc string)
3624 "Read output from \"gvfs-monitor-dir\" and add corresponding file-notify events."
3625 (let ((remote-prefix
3626 (with-current-buffer (process-buffer proc)
3627 (file-remote-p default-directory)))
3628 (rest-string (tramp-compat-process-get proc 'rest-string)))
3630 (tramp-message proc 10 "Previous string:\n%s" rest-string))
3631 (tramp-message proc 6 "%S\n%s" proc string)
3632 (setq string (concat rest-string string)
3633 ;; Attribute change is returned in unused wording.
3634 string (tramp-compat-replace-regexp-in-string
3635 "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))
3637 (while (string-match
3639 "Directory Monitor Event:[\n\r]+"
3640 "Child = \\([^\n\r]+\\)[\n\r]+"
3641 "\\(Other = \\([^\n\r]+\\)[\n\r]+\\)?"
3642 "Event = \\([^[:blank:]]+\\)[\n\r]+")
3648 (tramp-compat-replace-regexp-in-string
3649 "_" "-" (downcase (match-string 4 string))))
3650 ;; File names are returned as absolute paths. We must
3651 ;; add the remote prefix.
3652 (concat remote-prefix (match-string 1 string))
3653 (when (match-string 3 string)
3654 (concat remote-prefix (match-string 3 string))))))
3655 (setq string (replace-match "" nil nil string))
3656 ;; Usually, we would add an Emacs event now. Unfortunately,
3657 ;; `unread-command-events' does not accept several events at
3658 ;; once. Therefore, we apply the callback directly.
3659 (tramp-compat-funcall 'file-notify-callback object)))
3661 ;; Save rest of the string.
3662 (when (zerop (length string)) (setq string nil))
3663 (when string (tramp-message proc 10 "Rest string:\n%s" string))
3664 (tramp-compat-process-put proc 'rest-string string)))
3666 (defun tramp-sh-file-inotifywait-process-filter (proc string)
3667 "Read output from \"inotifywait\" and add corresponding file-notify events."
3668 (tramp-message proc 6 "%S\n%s" proc string)
3669 (dolist (line (split-string string "[\n\r]+" 'omit-nulls))
3670 ;; Check, whether there is a problem.
3673 (concat "^[^[:blank:]]+"
3674 "[[:blank:]]+\\([^[:blank:]]+\\)+"
3675 "\\([[:blank:]]+\\([^\n\r]+\\)\\)?")
3677 (tramp-error proc 'file-notify-error "%s" line))
3685 (tramp-compat-replace-regexp-in-string "_" "-" (downcase x))))
3686 (split-string (match-string 1 line) "," 'omit-nulls))
3687 (match-string 3 line))))
3688 ;; Usually, we would add an Emacs event now. Unfortunately,
3689 ;; `unread-command-events' does not accept several events at
3690 ;; once. Therefore, we apply the callback directly.
3691 (tramp-compat-funcall 'file-notify-callback object))))
3693 ;;; Internal Functions:
3695 (defun tramp-maybe-send-script (vec script name)
3696 "Define in remote shell function NAME implemented as SCRIPT.
3697 Only send the definition if it has not already been done."
3698 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3700 (let ((scripts (tramp-get-connection-property
3701 (tramp-get-connection-process vec) "scripts" nil)))
3702 (unless (member name scripts)
3703 (with-tramp-progress-reporter vec 5 (format "Sending script `%s'" name)
3704 ;; The script could contain a call of Perl. This is masked with `%s'.
3705 (when (and (string-match "%s" script)
3706 (not (tramp-get-remote-perl vec)))
3707 (tramp-error vec 'file-error "No Perl available on remote host"))
3708 (tramp-barf-unless-okay
3710 (format "%s () {\n%s\n}" name
3711 (format script (tramp-get-remote-perl vec)))
3712 "Script %s sending failed" name)
3713 (tramp-set-connection-property
3714 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3716 (defun tramp-set-auto-save ()
3717 (when (and ;; ange-ftp has its own auto-save mechanism
3718 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
3719 'tramp-sh-file-name-handler)
3721 (auto-save-mode 1)))
3722 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
3723 (add-hook 'tramp-unload-hook
3725 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
3727 (defun tramp-run-test (switch filename)
3728 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3729 Returns the exit code of the `test' program."
3730 (with-parsed-tramp-file-name filename nil
3731 (tramp-send-command-and-check
3735 (tramp-get-test-command v)
3737 (tramp-shell-quote-argument localname)))))
3739 (defun tramp-run-test2 (format-string file1 file2)
3740 "Run `test'-like program on the remote system, given FILE1, FILE2.
3741 FORMAT-STRING contains the program name, switches, and place holders.
3742 Returns the exit code of the `test' program. Barfs if the methods,
3743 hosts, or files, disagree."
3744 (unless (tramp-equal-remote file1 file2)
3745 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3748 "tramp-run-test2 only implemented for same method, user, host")))
3749 (with-parsed-tramp-file-name file1 v1
3750 (with-parsed-tramp-file-name file1 v2
3751 (tramp-send-command-and-check
3753 (format format-string
3754 (tramp-shell-quote-argument v1-localname)
3755 (tramp-shell-quote-argument v2-localname))))))
3757 (defun tramp-find-executable
3758 (vec progname dirlist &optional ignore-tilde ignore-path)
3759 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3760 First arg VEC specifies the connection, PROGNAME is the program
3761 to search for, and DIRLIST gives the list of directories to
3762 search. If IGNORE-TILDE is non-nil, directory names starting
3763 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3766 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3768 This function expects to be in the right *tramp* buffer."
3769 (with-current-buffer (tramp-get-connection-buffer vec)
3771 ;; Check whether the executable is in $PATH. "which(1)" does not
3772 ;; report always a correct error code; therefore we check the
3773 ;; number of words it returns. "SunOS 5.10" (and maybe "SunOS
3774 ;; 5.11") have problems with this command, we disable the call
3776 (unless (or ignore-path
3778 (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3779 (tramp-get-connection-property vec "uname" "")))
3780 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3781 (goto-char (point-min))
3782 (if (looking-at "^\\s-*1$")
3783 (setq result (concat "\\" progname))))
3786 ;; Remove all ~/foo directories from dirlist. In XEmacs,
3787 ;; `remove' is in CL, and we want to avoid CL dependencies.
3790 (setq d (car dirlist))
3791 (setq dirlist (cdr dirlist))
3792 (unless (char-equal ?~ (aref d 0))
3793 (setq newdl (cons d newdl))))
3794 (setq dirlist (nreverse newdl))))
3797 (format (concat "while read d; "
3798 "do if test -x $d/%s -a -f $d/%s; "
3799 "then echo tramp_executable $d/%s; "
3800 "break; fi; done <<'%s'\n"
3802 progname progname progname
3803 tramp-end-of-heredoc
3804 (mapconcat 'identity dirlist "\n")
3805 tramp-end-of-heredoc))
3806 (goto-char (point-max))
3807 (when (search-backward "tramp_executable " nil t)
3808 (skip-chars-forward "^ ")
3809 (skip-chars-forward " ")
3810 (setq result (buffer-substring (point) (point-at-eol)))))
3813 (defun tramp-set-remote-path (vec)
3814 "Sets the remote environment PATH to existing directories.
3815 I.e., for each directory in `tramp-remote-path', it is tested
3816 whether it exists and if so, it is added to the environment
3818 (tramp-message vec 5 "Setting $PATH environment variable")
3820 vec (format "PATH=%s; export PATH"
3821 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3823 ;; ------------------------------------------------------------
3824 ;; -- Communication with external shell --
3825 ;; ------------------------------------------------------------
3827 (defun tramp-find-file-exists-command (vec)
3828 "Find a command on the remote host for checking if a file exists.
3829 Here, we are looking for a command which has zero exit status if the
3830 file exists and nonzero exit status otherwise."
3831 (let ((existing "/")
3833 (tramp-shell-quote-argument "/ this file does not exist "))
3835 ;; The algorithm is as follows: we try a list of several commands.
3836 ;; For each command, we first run `$cmd /' -- this should return
3837 ;; true, as the root directory always exists. And then we run
3838 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3839 ;; does not exist. This should return false. We use the first
3840 ;; command we find that seems to work.
3841 ;; The list of commands to try is as follows:
3842 ;; `ls -d' This works on most systems, but NetBSD 1.4
3843 ;; has a bug: `ls' always returns zero exit
3844 ;; status, even for files which don't exist.
3845 ;; `test -e' Some Bourne shells have a `test' builtin
3846 ;; which does not know the `-e' option.
3847 ;; `/bin/test -e' For those, the `test' binary on disk normally
3848 ;; provides the option. Alas, the binary
3849 ;; is sometimes `/bin/test' and sometimes it's
3851 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3854 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3855 (tramp-send-command-and-check
3856 vec (format "%s %s" result existing))
3857 (not (tramp-send-command-and-check
3858 vec (format "%s %s" result nonexistent)))))
3860 (and (setq result "/bin/test -e")
3861 (tramp-send-command-and-check
3862 vec (format "%s %s" result existing))
3863 (not (tramp-send-command-and-check
3864 vec (format "%s %s" result nonexistent)))))
3866 (and (setq result "/usr/bin/test -e")
3867 (tramp-send-command-and-check
3868 vec (format "%s %s" result existing))
3869 (not (tramp-send-command-and-check
3870 vec (format "%s %s" result nonexistent)))))
3872 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3873 (tramp-send-command-and-check
3874 vec (format "%s %s" result existing))
3875 (not (tramp-send-command-and-check
3876 vec (format "%s %s" result nonexistent))))))
3878 vec 'file-error "Couldn't find command to check if file exists"))
3881 (defun tramp-open-shell (vec shell)
3882 "Opens shell SHELL."
3883 (with-tramp-progress-reporter
3884 vec 5 (format "Opening remote shell `%s'" shell)
3885 ;; Find arguments for this shell.
3886 (let ((alist tramp-sh-extra-args)
3888 (while (and alist (null extra-args))
3889 (setq item (pop alist))
3890 (when (string-match (car item) shell)
3891 (setq extra-args (cdr item))))
3892 ;; It is useful to set the prompt in the following command
3893 ;; because some people have a setting for $PS1 which /bin/sh
3894 ;; doesn't know about and thus /bin/sh will display a strange
3895 ;; prompt. For example, if $PS1 has "${CWD}" in the value, then
3896 ;; ksh will display the current working directory but /bin/sh
3897 ;; will display a dollar sign. The following command line sets
3898 ;; $PS1 to a sane value, and works under Bourne-ish shells as
3899 ;; well as csh-like shells. We also unset the variable $ENV
3900 ;; because that is read by some sh implementations (eg, bash
3901 ;; when called as sh) on startup; this way, we avoid the startup
3902 ;; file clobbering $PS1. $PROMPT_COMMAND is another way to set
3903 ;; the prompt in /bin/bash, it must be discarded as well.
3906 "exec env ENV='' %s PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3907 (if tramp-histfile-override
3910 (if (stringp tramp-histfile-override)
3911 (tramp-shell-quote-argument tramp-histfile-override) ""))
3913 (tramp-shell-quote-argument tramp-end-of-output)
3914 shell (or extra-args ""))
3916 (tramp-set-connection-property
3917 (tramp-get-connection-process vec) "remote-shell" shell)))
3919 (defun tramp-find-shell (vec)
3920 "Opens a shell on the remote host which groks tilde expansion."
3921 (with-current-buffer (tramp-get-buffer vec)
3922 (let ((default-shell
3924 (tramp-get-connection-property
3925 (tramp-get-connection-process vec) "remote-shell" nil)
3926 (tramp-get-method-parameter
3927 (tramp-file-name-method vec) 'tramp-remote-shell)))
3930 (with-tramp-connection-property vec "remote-shell"
3931 ;; CCC: "root" does not exist always, see QNAP 459.
3932 ;; Which check could we apply instead?
3933 (tramp-send-command vec "echo ~root" t)
3934 (if (or (string-match "^~root$" (buffer-string))
3935 ;; The default shell (ksh93) of OpenSolaris and
3936 ;; Solaris is buggy. We've got reports for
3937 ;; "SunOS 5.10" and "SunOS 5.11" so far.
3938 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3939 (tramp-get-connection-property
3942 (or (tramp-find-executable
3943 vec "bash" (tramp-get-remote-path vec) t t)
3944 (tramp-find-executable
3945 vec "ksh" (tramp-get-remote-path vec) t t)
3946 ;; Maybe it works at least for some other commands.
3952 "Couldn't find a remote shell which groks tilde "
3953 "expansion, using `%s'")
3958 ;; Open a new shell if needed.
3959 (unless (string-equal shell default-shell)
3961 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
3962 (tramp-open-shell vec shell)))))
3964 ;; Utility functions.
3966 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
3967 "Wait for shell prompt and barf if none appears.
3968 Looks at process PROC to see if a shell prompt appears in TIMEOUT
3969 seconds. If not, it produces an error message with the given ERROR-ARGS."
3970 (let ((vec (tramp-get-connection-property proc "vector" nil)))
3972 (tramp-wait-for-regexp
3975 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
3977 (delete-process proc)
3978 (apply 'tramp-error-with-buffer
3979 (tramp-get-connection-buffer vec) vec 'file-error error-args)))))
3981 (defun tramp-open-connection-setup-interactive-shell (proc vec)
3982 "Set up an interactive shell.
3983 Mainly sets the prompt and the echo correctly. PROC is the shell
3984 process to set up. VEC specifies the connection."
3985 (let ((tramp-end-of-output tramp-initial-end-of-output))
3988 (or (tramp-get-connection-property vec "remote-shell" nil)
3989 (tramp-get-method-parameter
3990 (tramp-file-name-method vec) 'tramp-remote-shell)))
3993 (tramp-message vec 5 "Setting up remote shell environment")
3994 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
3995 ;; Check whether the echo has really been disabled. Some
3996 ;; implementations, like busybox of embedded GNU/Linux, don't
3997 ;; support disabling.
3998 (tramp-send-command vec "echo foo" t)
3999 (with-current-buffer (process-buffer proc)
4000 (goto-char (point-min))
4001 (when (looking-at "echo foo")
4002 (tramp-set-connection-property proc "remote-echo" t)
4003 (tramp-message vec 5 "Remote echo still on. Ok.")
4004 ;; Make sure backspaces and their echo are enabled and no line
4005 ;; width magic interferes with them.
4006 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
4008 (tramp-message vec 5 "Setting shell prompt")
4010 vec (format "PS1=%s PS2='' PS3='' PROMPT_COMMAND=''"
4011 (tramp-shell-quote-argument tramp-end-of-output)) t)
4013 ;; Try to set up the coding system correctly.
4014 ;; CCC this can't be the right way to do it. Hm.
4015 (tramp-message vec 5 "Determining coding system")
4016 (with-current-buffer (process-buffer proc)
4017 (if (featurep 'mule)
4018 ;; Use MULE to select the right EOL convention for communicating
4019 ;; with the process.
4020 (let ((cs (or (and (memq 'utf-8 (coding-system-list))
4021 (string-match "utf8" (tramp-get-remote-locale vec))
4022 (cons 'utf-8 'utf-8))
4023 (tramp-compat-funcall 'process-coding-system proc)
4024 (cons 'undecided 'undecided)))
4025 cs-decode cs-encode)
4026 (when (symbolp cs) (setq cs (cons cs cs)))
4027 (setq cs-decode (car cs))
4028 (setq cs-encode (cdr cs))
4029 (unless cs-decode (setq cs-decode 'undecided))
4030 (unless cs-encode (setq cs-encode 'undecided))
4031 (setq cs-encode (tramp-compat-coding-system-change-eol-conversion
4033 (tramp-send-command vec "echo foo ; echo bar" t)
4034 (goto-char (point-min))
4035 (when (search-forward "\r" nil t)
4036 (setq cs-decode (tramp-compat-coding-system-change-eol-conversion
4038 (tramp-compat-funcall
4039 'set-buffer-process-coding-system cs-decode cs-encode)
4041 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
4042 ;; Look for ^M and do something useful if found.
4043 (when (search-forward "\r" nil t)
4044 ;; We have found a ^M but cannot frob the process coding system
4045 ;; because we're running on a non-MULE Emacs. Let's try
4047 (tramp-send-command vec "stty -onlcr" t))))
4049 (tramp-send-command vec "set +o vi +o emacs" t)
4051 ;; Check whether the output of "uname -sr" has been changed. If
4052 ;; yes, this is a strong indication that we must expire all
4053 ;; connection properties. We start again with
4054 ;; `tramp-maybe-open-connection', it will be caught there.
4055 (tramp-message vec 5 "Checking system information")
4056 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
4058 (tramp-set-connection-property
4060 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
4061 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
4064 "Connection reset, because remote host changed from `%s' to `%s'"
4065 old-uname new-uname)
4066 ;; We want to keep the password.
4067 (tramp-cleanup-connection vec t t)
4068 (throw 'uname-changed (tramp-maybe-open-connection vec))))
4070 ;; Check whether the remote host suffers from buggy
4071 ;; `send-process-string'. This is known for FreeBSD (see comment in
4072 ;; `send_process', file process.c). I've tested sending 624 bytes
4073 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
4074 ;; this host type is detected locally. It cannot handle remote
4076 (with-tramp-connection-property proc "chunksize"
4078 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
4082 vec 5 "Checking remote host type for `send-process-string' bug")
4084 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
4087 ;; Set remote PATH variable.
4088 (tramp-set-remote-path vec)
4090 ;; Search for a good shell before searching for a command which
4091 ;; checks if a file exists. This is done because Tramp wants to use
4092 ;; "test foo; echo $?" to check if various conditions hold, and
4093 ;; there are buggy /bin/sh implementations which don't execute the
4094 ;; "echo $?" part if the "test" part has an error. In particular,
4095 ;; the OpenSolaris /bin/sh is a problem. There are also other
4096 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
4097 ;; in function declarations, or changing HISTFILE in place.
4098 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
4100 (tramp-find-shell vec)
4102 ;; Disable unexpected output.
4103 (tramp-send-command vec "mesg n; biff n" t)
4105 ;; IRIX64 bash expands "!" even when in single quotes. This
4106 ;; destroys our shell functions, we must disable it. See
4107 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
4108 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
4109 (tramp-send-command vec "set +H" t))
4111 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
4112 (when (string-match "BSD\\|Darwin"
4113 (tramp-get-connection-property vec "uname" ""))
4114 (tramp-send-command vec "stty -oxtabs" t))
4116 ;; Set `remote-tty' process property.
4117 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
4118 (unless (zerop (length tty))
4119 (tramp-compat-process-put proc 'remote-tty tty)))
4121 ;; Dump stty settings in the traces.
4122 (when (>= tramp-verbose 9)
4123 (tramp-send-command vec "stty -a" t))
4125 ;; Set the environment.
4126 (tramp-message vec 5 "Setting default environment")
4128 (let ((env (append `(,(tramp-get-remote-locale vec))
4129 (copy-sequence tramp-remote-process-environment)))
4132 (setq item (tramp-compat-split-string (car env) "="))
4133 (setcdr item (mapconcat 'identity (cdr item) "="))
4134 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
4135 (push (format "%s %s" (car item) (cdr item)) vars)
4136 (push (car item) unset))
4137 (setq env (cdr env)))
4141 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
4142 tramp-end-of-heredoc
4143 (mapconcat 'identity vars "\n")
4144 tramp-end-of-heredoc)
4148 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
4150 ;; Old text from documentation of tramp-methods:
4151 ;; Using a uuencode/uudecode inline method is discouraged, please use one
4152 ;; of the base64 methods instead since base64 encoding is much more
4153 ;; reliable and the commands are more standardized between the different
4154 ;; Unix versions. But if you can't use base64 for some reason, please
4155 ;; note that the default uudecode command does not work well for some
4156 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
4157 ;; the following command for uudecode:
4159 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
4161 ;; For Irix, no solution is known yet.
4163 (autoload 'uudecode-decode-region "uudecode")
4165 (defconst tramp-local-coding-commands
4166 `((b64 base64-encode-region base64-decode-region)
4167 (uu tramp-uuencode-region uudecode-decode-region)
4168 (pack ,(format tramp-perl-pack "perl") ,(format tramp-perl-unpack "perl")))
4169 "List of local coding commands for inline transfer.
4170 Each item is a list that looks like this:
4172 \(FORMAT ENCODING DECODING\)
4174 FORMAT is symbol describing the encoding/decoding format. It can be
4175 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4177 ENCODING and DECODING can be strings, giving commands, or symbols,
4178 giving functions. If they are strings, then they can contain
4179 the \"%s\" format specifier. If that specifier is present, the input
4180 file name will be put into the command line at that spot. If the
4181 specifier is not present, the input should be read from standard
4184 If they are functions, they will be called with two arguments, start
4185 and end of region, and are expected to replace the region contents
4186 with the encoded or decoded results, respectively.")
4188 (defconst tramp-remote-coding-commands
4189 '((b64 "base64" "base64 -d -i")
4190 ;; "-i" is more robust with older base64 from GNU coreutils.
4191 ;; However, I don't know whether all base64 versions do supports
4193 (b64 "base64" "base64 -d")
4194 (b64 "mimencode -b" "mimencode -u -b")
4195 (b64 "mmencode -b" "mmencode -u -b")
4196 (b64 "recode data..base64" "recode base64..data")
4197 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
4198 (b64 tramp-perl-encode tramp-perl-decode)
4199 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
4200 (uu "uuencode xxx" "uudecode -o -")
4201 (uu "uuencode xxx" "uudecode -p")
4202 (uu "uuencode xxx" tramp-uudecode)
4203 (pack tramp-perl-pack tramp-perl-unpack))
4204 "List of remote coding commands for inline transfer.
4205 Each item is a list that looks like this:
4207 \(FORMAT ENCODING DECODING [TEST]\)
4209 FORMAT is a symbol describing the encoding/decoding format. It can be
4210 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4212 ENCODING and DECODING can be strings, giving commands, or symbols,
4213 giving variables. If they are strings, then they can contain
4214 the \"%s\" format specifier. If that specifier is present, the input
4215 file name will be put into the command line at that spot. If the
4216 specifier is not present, the input should be read from standard
4219 If they are variables, this variable is a string containing a
4220 Perl or Shell implementation for this functionality. This
4221 program will be transferred to the remote host, and it is
4222 available as shell function with the same name. A \"%t\" format
4223 specifier in the variable value denotes a temporary file.
4225 The optional TEST command can be used for further tests, whether
4226 ENCODING and DECODING are applicable.")
4228 (defun tramp-find-inline-encoding (vec)
4229 "Find an inline transfer encoding that works.
4230 Goes through the list `tramp-local-coding-commands' and
4231 `tramp-remote-coding-commands'."
4233 (let ((local-commands tramp-local-coding-commands)
4235 (p (tramp-get-connection-process vec))
4236 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4237 (while (and local-commands (not found))
4238 (setq litem (pop local-commands))
4239 (catch 'wont-work-local
4240 (let ((format (nth 0 litem))
4241 (remote-commands tramp-remote-coding-commands))
4242 (setq loc-enc (nth 1 litem))
4243 (setq loc-dec (nth 2 litem))
4244 ;; If the local encoder or decoder is a string, the
4245 ;; corresponding command has to work locally.
4246 (if (not (stringp loc-enc))
4248 vec 5 "Checking local encoding function `%s'" loc-enc)
4250 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4251 (unless (zerop (tramp-call-local-coding-command
4253 (throw 'wont-work-local nil)))
4254 (if (not (stringp loc-dec))
4256 vec 5 "Checking local decoding function `%s'" loc-dec)
4258 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4259 (unless (zerop (tramp-call-local-coding-command
4261 (throw 'wont-work-local nil)))
4262 ;; Search for remote coding commands with the same format
4263 (while (and remote-commands (not found))
4264 (setq ritem (pop remote-commands))
4265 (catch 'wont-work-remote
4266 (when (equal format (nth 0 ritem))
4267 (setq rem-enc (nth 1 ritem))
4268 (setq rem-dec (nth 2 ritem))
4269 (setq rem-test (nth 3 ritem))
4270 ;; Check the remote test command if exists.
4271 (when (stringp rem-test)
4273 vec 5 "Checking remote test command `%s'" rem-test)
4274 (unless (tramp-send-command-and-check vec rem-test t)
4275 (throw 'wont-work-remote nil)))
4276 ;; Check if remote perl exists when necessary.
4277 (when (and (not (stringp rem-enc))
4278 (not (tramp-get-remote-perl vec)))
4279 (throw 'wont-work-remote nil))
4280 ;; Check if remote encoding and decoding commands can be
4281 ;; called remotely with null input and output. This makes
4282 ;; sure there are no syntax errors and the command is really
4283 ;; found. Note that we do not redirect stdout to /dev/null,
4284 ;; for two reasons: when checking the decoding command, we
4285 ;; actually check the output it gives. And also, when
4286 ;; redirecting "mimencode" output to /dev/null, then as root
4287 ;; it might change the permissions of /dev/null!
4288 (when (not (stringp rem-enc))
4289 (let ((name (symbol-name rem-enc)))
4290 (while (string-match (regexp-quote "-") name)
4291 (setq name (replace-match "_" nil t name)))
4292 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4293 (setq rem-enc name)))
4296 "Checking remote encoding command `%s' for sanity" rem-enc)
4297 (unless (tramp-send-command-and-check
4298 vec (format "%s </dev/null" rem-enc) t)
4299 (throw 'wont-work-remote nil))
4301 (when (not (stringp rem-dec))
4302 (let ((name (symbol-name rem-dec))
4303 (value (symbol-value rem-dec))
4305 (while (string-match (regexp-quote "-") name)
4306 (setq name (replace-match "_" nil t name)))
4307 (when (string-match "\\(^\\|[^%]\\)%t" value)
4311 tramp-temp-name-prefix
4312 (tramp-get-remote-tmpdir vec)))
4318 (tramp-file-name-handler
4319 'file-remote-p tmpfile 'localname)))))
4320 (tramp-maybe-send-script vec value name)
4321 (setq rem-dec name)))
4324 "Checking remote decoding command `%s' for sanity" rem-dec)
4325 (unless (tramp-send-command-and-check
4327 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4329 (throw 'wont-work-remote nil))
4331 (with-current-buffer (tramp-get-buffer vec)
4332 (goto-char (point-min))
4333 (unless (looking-at (regexp-quote magic))
4334 (throw 'wont-work-remote nil)))
4336 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4337 (setq rem-enc (nth 1 ritem))
4338 (setq rem-dec (nth 2 ritem))
4339 (setq found t)))))))
4342 ;; Set connection properties. Since the commands are risky
4343 ;; (due to output direction), we cache them in the process cache.
4344 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4345 (tramp-set-connection-property p "local-encoding" loc-enc)
4346 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4347 (tramp-set-connection-property p "local-decoding" loc-dec)
4348 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4349 (tramp-set-connection-property p "remote-encoding" rem-enc)
4350 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4351 (tramp-set-connection-property p "remote-decoding" rem-dec)))))
4353 (defun tramp-call-local-coding-command (cmd input output)
4354 "Call the local encoding or decoding command.
4355 If CMD contains \"%s\", provide input file INPUT there in command.
4356 Otherwise, INPUT is passed via standard input.
4357 INPUT can also be nil which means `/dev/null'.
4358 OUTPUT can be a string (which specifies a file name), or t (which
4359 means standard output and thus the current buffer), or nil (which
4362 nil tramp-encoding-shell
4363 (when (and input (not (string-match "%s" cmd))) input)
4364 (if (eq output t) t nil)
4366 tramp-encoding-command-switch
4368 (if (string-match "%s" cmd) (format cmd input) cmd)
4369 (if (stringp output) (concat " >" output) ""))))
4371 (defconst tramp-inline-compress-commands
4372 '(("gzip" "gzip -d")
4373 ("bzip2" "bzip2 -d")
4375 ("compress" "compress -d"))
4376 "List of compress and decompress commands for inline transfer.
4377 Each item is a list that looks like this:
4379 \(COMPRESS DECOMPRESS\)
4381 COMPRESS or DECOMPRESS are strings with the respective commands.")
4383 (defun tramp-find-inline-compress (vec)
4384 "Find an inline transfer compress command that works.
4385 Goes through the list `tramp-inline-compress-commands'."
4387 (let ((commands tramp-inline-compress-commands)
4389 (p (tramp-get-connection-process vec))
4390 item compress decompress found)
4391 (while (and commands (not found))
4393 (setq item (pop commands)
4394 compress (nth 0 item)
4395 decompress (nth 1 item))
4398 "Checking local compress commands `%s', `%s' for sanity"
4399 compress decompress)
4402 (tramp-call-local-coding-command
4404 ;; Windows shells need the program file name after
4405 ;; the pipe symbol be quoted if they use forward
4406 ;; slashes as directory separators.
4407 (if (memq system-type '(windows-nt))
4408 "echo %s | \"%s\" | \"%s\""
4409 "echo %s | %s | %s")
4410 magic compress decompress) nil nil))
4414 "Checking remote compress commands `%s', `%s' for sanity"
4415 compress decompress)
4416 (unless (tramp-send-command-and-check
4417 vec (format "echo %s | %s | %s" magic compress decompress) t)
4421 ;; Did we find something?
4424 ;; Set connection properties. Since the commands are
4425 ;; risky (due to output direction), we cache them in the
4428 vec 5 "Using inline transfer compress command `%s'" compress)
4429 (tramp-set-connection-property p "inline-compress" compress)
4431 vec 5 "Using inline transfer decompress command `%s'" decompress)
4432 (tramp-set-connection-property p "inline-decompress" decompress))
4434 (tramp-set-connection-property p "inline-compress" nil)
4435 (tramp-set-connection-property p "inline-decompress" nil)
4437 vec 2 "Couldn't find an inline transfer compress command")))))
4439 (defun tramp-compute-multi-hops (vec)
4440 "Expands VEC according to `tramp-default-proxies-alist'.
4441 Gateway hops are already opened."
4442 (let ((target-alist `(,vec))
4443 (hops (or (tramp-file-name-hop vec) ""))
4447 ;; Ad-hoc proxy definitions.
4448 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4449 (let ((user (tramp-file-name-user item))
4450 (host (tramp-file-name-host item))
4452 tramp-prefix-format proxy tramp-postfix-host-format)))
4454 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4455 (and (stringp host) (regexp-quote host))
4456 (and (stringp user) (regexp-quote user))
4460 'tramp-default-proxies-alist
4461 (list (and (stringp host) (regexp-quote host))
4462 (and (stringp user) (regexp-quote user))
4464 (setq item (tramp-dissect-file-name proxy))))
4465 ;; Save the new value.
4466 (when (and hops tramp-save-ad-hoc-proxies)
4467 (customize-save-variable
4468 'tramp-default-proxies-alist tramp-default-proxies-alist))
4470 ;; Look for proxy hosts to be passed.
4471 (setq choices tramp-default-proxies-alist)
4473 (setq item (pop choices)
4474 proxy (eval (nth 2 item)))
4477 (string-match (or (eval (nth 0 item)) "")
4478 (or (tramp-file-name-host (car target-alist)) ""))
4480 (string-match (or (eval (nth 1 item)) "")
4481 (or (tramp-file-name-user (car target-alist)) "")))
4483 ;; No more hops needed.
4485 ;; Replace placeholders.
4490 ?u (or (tramp-file-name-user (car target-alist)) "")
4491 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4492 (with-parsed-tramp-file-name proxy l
4494 (push l target-alist)
4495 ;; Start next search.
4496 (setq choices tramp-default-proxies-alist)))))
4499 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4502 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4503 (tramp-file-name-method (car target-alist))))
4504 (let ((gw (pop target-alist))
4505 (hop (pop target-alist)))
4506 ;; Is the method prepared for gateways?
4507 (unless (tramp-file-name-port hop)
4510 "Connection `%s' is not supported for gateway access." hop))
4511 ;; Open the gateway connection.
4514 (tramp-file-name-method hop) (tramp-file-name-user hop)
4515 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil nil)
4517 ;; For the password prompt, we need the correct values.
4518 ;; Therefore, we must remember the gateway vector. But we
4519 ;; cannot do it as connection property, because it shouldn't
4520 ;; be persistent. And we have no started process yet either.
4521 (let ((tramp-verbose 0))
4522 (tramp-set-file-property (car target-alist) "" "gateway" hop))))
4524 ;; Foreign and out-of-band methods are not supported for multi-hops.
4525 (when (cdr target-alist)
4526 (setq choices target-alist)
4528 (setq item (pop choices))
4532 (tramp-get-method-parameter
4533 (tramp-file-name-method item) 'tramp-login-program))
4534 (tramp-get-method-parameter
4535 (tramp-file-name-method item) 'tramp-copy-program))
4538 "Method `%s' is not supported for multi-hops."
4539 (tramp-file-name-method item)))))
4541 ;; In case the host name is not used for the remote shell
4542 ;; command, the user could be misguided by applying a random
4544 (let* ((v (car target-alist))
4545 (method (tramp-file-name-method v))
4546 (host (tramp-file-name-host v)))
4549 ;; There are multi-hops.
4551 ;; The host name is used for the remote shell command.
4553 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
4554 ;; The host is local. We cannot use `tramp-local-host-p'
4555 ;; here, because it opens a connection as well.
4556 (string-match tramp-local-host-regexp host))
4559 "Host `%s' looks like a remote host, `%s' can only use the local host"
4565 (defun tramp-maybe-open-connection (vec)
4566 "Maybe open a connection VEC.
4567 Does not do anything if a connection is already open, but re-opens the
4568 connection if a previous connection has died for some reason."
4569 (tramp-check-proper-method-and-host vec)
4571 (let ((p (tramp-get-connection-process vec))
4572 (process-name (tramp-get-connection-property vec "process-name" nil))
4573 (process-environment (copy-sequence process-environment))
4574 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4576 ;; If Tramp opens the same connection within a short time frame,
4577 ;; there is a problem. We shall signal this.
4578 (unless (or (and p (processp p) (memq (process-status p) '(run open)))
4579 (not (equal (butlast (append vec nil) 2)
4580 (car tramp-current-connection)))
4582 (current-time) (cdr tramp-current-connection))
4583 (or tramp-connection-min-time-diff 0)))
4584 (throw 'suppress 'suppress))
4586 ;; If too much time has passed since last command was sent, look
4587 ;; whether process is still alive. If it isn't, kill it. When
4588 ;; using ssh, it can sometimes happen that the remote end has hung
4589 ;; up but the local ssh client doesn't recognize this until it
4590 ;; tries to send some data to the remote end. So that's why we
4591 ;; try to send a command from time to time, then look again
4592 ;; whether the process is really alive.
4594 (when (and (> (tramp-time-diff
4596 (tramp-get-connection-property
4597 p "last-cmd-time" '(0 0 0)))
4599 p (processp p) (memq (process-status p) '(run open)))
4600 (tramp-send-command vec "echo are you awake" t t)
4601 (unless (and (memq (process-status p) '(run open))
4602 (tramp-wait-for-output p 10))
4603 ;; The error will be caught locally.
4604 (tramp-error vec 'file-error "Awake did fail")))
4606 (tramp-cleanup-connection vec t)
4609 ;; New connection must be opened.
4611 (unless (and p (processp p) (memq (process-status p) '(run open)))
4613 ;; If `non-essential' is non-nil, don't reopen a new connection.
4614 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4615 (throw 'non-essential 'non-essential))
4617 (with-tramp-progress-reporter
4619 (if (zerop (length (tramp-file-name-user vec)))
4620 (format "Opening connection for %s using %s"
4621 (tramp-file-name-host vec)
4622 (tramp-file-name-method vec))
4623 (format "Opening connection for %s@%s using %s"
4624 (tramp-file-name-user vec)
4625 (tramp-file-name-host vec)
4626 (tramp-file-name-method vec)))
4628 (catch 'uname-changed
4629 ;; Start new process.
4630 (when (and p (processp p))
4632 (setenv "TERM" tramp-terminal-type)
4633 (setenv "LC_ALL" "en_US.utf8")
4634 (when tramp-histfile-override
4636 (and (stringp tramp-histfile-override)
4637 tramp-histfile-override)))
4638 (setenv "PROMPT_COMMAND")
4639 (setenv "PS1" tramp-initial-end-of-output)
4640 (let* ((target-alist (tramp-compute-multi-hops vec))
4641 ;; We will apply `tramp-ssh-controlmaster-options'
4642 ;; only for the first hop.
4643 (options (if tramp-use-ssh-controlmaster-options
4644 tramp-ssh-controlmaster-options ""))
4645 (process-connection-type tramp-process-connection-type)
4646 (process-adaptive-read-buffering nil)
4647 (coding-system-for-read nil)
4648 ;; This must be done in order to avoid our file
4650 (p (let ((default-directory
4651 (tramp-compat-temporary-file-directory)))
4654 (tramp-get-connection-name vec)
4655 (tramp-get-connection-buffer vec)
4656 (if tramp-encoding-command-interactive
4657 (list tramp-encoding-shell
4658 tramp-encoding-command-interactive)
4659 (list tramp-encoding-shell))))))
4661 ;; Set sentinel and query flag.
4662 (tramp-set-connection-property p "vector" vec)
4663 (set-process-sentinel p 'tramp-process-sentinel)
4664 (tramp-compat-set-process-query-on-exit-flag p nil)
4665 (setq tramp-current-connection
4666 (cons (butlast (append vec nil) 2) (current-time))
4667 tramp-current-host (system-name))
4670 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4672 ;; Check whether process is alive.
4673 (tramp-barf-if-no-shell-prompt
4675 "Couldn't find local shell prompt for %s" tramp-encoding-shell)
4677 ;; Now do all the connections as specified.
4679 (let* ((hop (car target-alist))
4680 (l-method (tramp-file-name-method hop))
4681 (l-user (tramp-file-name-user hop))
4682 (l-host (tramp-file-name-host hop))
4685 (tramp-get-method-parameter
4686 l-method 'tramp-login-program))
4688 (tramp-get-method-parameter
4689 l-method 'tramp-login-args))
4691 (tramp-get-method-parameter
4692 l-method 'tramp-login-env))
4694 (tramp-get-method-parameter
4695 l-method 'tramp-async-args))
4697 (tramp-get-method-parameter
4698 l-method 'tramp-connection-timeout))
4700 (tramp-get-method-parameter l-method 'tramp-gw-args))
4701 (gw (let ((tramp-verbose 0))
4702 (tramp-get-file-property hop "" "gateway" nil)))
4703 (g-method (and gw (tramp-file-name-method gw)))
4704 (g-user (and gw (tramp-file-name-user gw)))
4705 (g-host (and gw (tramp-file-name-real-host gw)))
4706 (command login-program)
4707 ;; We don't create the temporary file. In
4708 ;; fact, it is just a prefix for the
4709 ;; ControlPath option of ssh; the real
4710 ;; temporary file has another name, and it is
4711 ;; created and protected by ssh. It is also
4712 ;; removed by ssh when the connection is
4713 ;; closed. The temporary file name is cached
4714 ;; in the main connection process, therefore
4715 ;; we cannot use `tramp-get-connection-process'.
4717 (with-tramp-connection-property
4718 (get-process (tramp-buffer-name vec)) "temp-file"
4721 tramp-temp-name-prefix
4722 (tramp-compat-temporary-file-directory)))))
4725 ;; Add arguments for asynchronous processes.
4726 (when (and process-name async-args)
4727 (setq login-args (append async-args login-args)))
4729 ;; Add gateway arguments if necessary.
4731 (tramp-set-connection-property p "gateway" t)
4733 (setq login-args (append gw-args login-args))))
4735 ;; Check for port number. Until now, there's no
4736 ;; need for handling like method, user, host.
4737 (when (string-match tramp-host-with-port-regexp l-host)
4738 (setq l-port (match-string 2 l-host)
4739 l-host (match-string 1 l-host)))
4741 ;; Check, whether there is a restricted shell.
4742 (dolist (elt tramp-restricted-shell-hosts-alist)
4743 (when (string-match elt tramp-current-host)
4746 ;; Set variables for computing the prompt for
4747 ;; reading password. They can also be derived
4749 (setq tramp-current-method (or g-method l-method)
4750 tramp-current-user (or g-user l-user)
4751 tramp-current-host (or g-host l-host))
4753 ;; Add login environment.
4759 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4760 (unless (member "" x) (mapconcat 'identity x " ")))
4767 (tramp-shell-quote-argument (pop login-env))
4769 (setq command (concat "env " command)))
4771 ;; Replace `login-args' place holders.
4773 l-host (or l-host "")
4774 l-user (or l-user "")
4775 l-port (or l-port "")
4776 spec (format-spec-make ?t tmpfile)
4777 options (format-spec options spec)
4778 spec (format-spec-make
4779 ?h l-host ?u l-user ?p l-port ?c options)
4782 ;; We do not want to see the trailing local
4783 ;; prompt in `start-file-process'.
4784 (unless r-shell "exec ")
4788 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4789 (unless (member "" x) (mapconcat 'identity x " ")))
4791 ;; Local shell could be a Windows COMSPEC. It
4792 ;; doesn't know the ";" syntax, but we must exit
4793 ;; always for `start-file-process'. It could
4794 ;; also be a restricted shell, which does not
4796 (when r-shell " && exit || exit")))
4798 ;; Send the command.
4799 (tramp-message vec 3 "Sending command `%s'" command)
4800 (tramp-send-command vec command t t)
4801 (tramp-process-actions
4802 p vec pos tramp-actions-before-shell
4803 (or connection-timeout tramp-connection-timeout))
4805 vec 3 "Found remote shell prompt on `%s'" l-host))
4808 target-alist (cdr target-alist)))
4810 ;; Make initial shell settings.
4811 (tramp-open-connection-setup-interactive-shell p vec)))))
4813 ;; When the user did interrupt, we must cleanup.
4815 (tramp-cleanup-connection vec t)
4816 ;; Propagate the quit signal.
4817 (signal (car err) (cdr err))))))
4819 (defun tramp-send-command (vec command &optional neveropen nooutput)
4820 "Send the COMMAND to connection VEC.
4821 Erases temporary buffer before sending the command. If optional
4822 arg NEVEROPEN is non-nil, never try to open the connection. This
4823 is meant to be used from `tramp-maybe-open-connection' only. The
4824 function waits for output unless NOOUTPUT is set."
4825 (unless neveropen (tramp-maybe-open-connection vec))
4826 (let ((p (tramp-get-connection-process vec)))
4827 (when (tramp-get-connection-property p "remote-echo" nil)
4828 ;; We mark the command string that it can be erased in the output buffer.
4829 (tramp-set-connection-property p "check-remote-echo" t)
4830 ;; If we put `tramp-echo-mark' after a trailing newline (which
4831 ;; is assumed to be unquoted) `tramp-send-string' doesn't see
4832 ;; that newline and adds `tramp-rsh-end-of-line' right after
4833 ;; `tramp-echo-mark', so the remote shell sees two consecutive
4834 ;; trailing line endings and sends two prompts after executing
4835 ;; the command, which confuses `tramp-wait-for-output'.
4836 (when (and (not (string= command ""))
4837 (string-equal (substring command -1) "\n"))
4838 (setq command (substring command 0 -1)))
4839 ;; No need to restore a trailing newline here since `tramp-send-string'
4840 ;; makes sure that the string ends in `tramp-rsh-end-of-line', anyway.
4841 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4842 ;; Send the command.
4843 (tramp-message vec 6 "%s" command)
4844 (tramp-send-string vec command)
4845 (unless nooutput (tramp-wait-for-output p))))
4847 (defun tramp-wait-for-output (proc &optional timeout)
4848 "Wait for output from remote command."
4849 (unless (buffer-live-p (process-buffer proc))
4850 (delete-process proc)
4851 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4852 (with-current-buffer (process-buffer proc)
4853 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4854 ;; be leading escape sequences, which must be ignored.
4855 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
4856 ;; Sometimes, the commands do not return a newline but a
4857 ;; null byte before the shell prompt, for example "git
4858 ;; ls-files -c -z ...".
4859 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4860 (found (tramp-wait-for-regexp proc timeout regexp1)))
4862 (let (buffer-read-only)
4863 ;; A simple-minded busybox has sent " ^H" sequences.
4865 (goto-char (point-min))
4866 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4868 (delete-region (point-min) (point)))
4869 ;; Delete the prompt.
4870 (goto-char (point-max))
4871 (re-search-backward regexp nil t)
4872 (delete-region (point) (point-max)))
4876 "[[Remote prompt `%s' not found in %d secs]]"
4877 tramp-end-of-output timeout)
4880 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
4881 ;; Return value is whether end-of-output sentinel was found.
4884 (defun tramp-send-command-and-check
4885 (vec command &optional subshell dont-suppress-err)
4886 "Run COMMAND and check its exit status.
4887 Sends `echo $?' along with the COMMAND for checking the exit status.
4888 If COMMAND is nil, just sends `echo $?'. Returns `t' if the exit
4889 status is 0, and `nil' otherwise.
4891 If the optional argument SUBSHELL is non-nil, the command is
4892 executed in a subshell, ie surrounded by parentheses. If
4893 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
4896 (concat (if subshell "( " "")
4898 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
4899 "echo tramp_exit_status $?"
4900 (if subshell " )" "")))
4901 (with-current-buffer (tramp-get-connection-buffer vec)
4902 (goto-char (point-max))
4903 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
4905 vec 'file-error "Couldn't find exit status of `%s'" command))
4906 (skip-chars-forward "^ ")
4908 (zerop (read (current-buffer)))
4909 (let (buffer-read-only)
4910 (delete-region (match-beginning 0) (point-max))))))
4912 (defun tramp-barf-unless-okay (vec command fmt &rest args)
4913 "Run COMMAND, check exit status, throw error if exit status not okay.
4914 Similar to `tramp-send-command-and-check' but accepts two more arguments
4915 FMT and ARGS which are passed to `error'."
4916 (or (tramp-send-command-and-check vec command)
4917 (apply 'tramp-error vec 'file-error fmt args)))
4919 (defun tramp-send-command-and-read (vec command &optional noerror marker)
4920 "Run COMMAND and return the output, which must be a Lisp expression.
4921 If MARKER is a regexp, read the output after that string.
4922 In case there is no valid Lisp expression and NOERROR is nil, it
4925 (tramp-send-command-and-check vec command)
4926 (tramp-barf-unless-okay
4927 vec command "`%s' returns with error" command))
4928 (with-current-buffer (tramp-get-connection-buffer vec)
4929 (goto-char (point-min))
4931 (when (stringp marker)
4933 (re-search-forward marker)
4934 (error (unless noerror
4937 "`%s' does not return the marker `%s': `%s'"
4938 command marker (buffer-string))))))
4939 ;; Read the expression.
4941 (prog1 (read (current-buffer))
4943 (when (re-search-forward "\\S-" (point-at-eol) t)
4945 (error (unless noerror
4948 "`%s' does not return a valid Lisp expression: `%s'"
4949 command (buffer-string))))))))
4951 (defun tramp-convert-file-attributes (vec attr)
4952 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
4953 Convert file mode bits to string and set virtual device number.
4956 ;; Remove color escape sequences from symlink.
4957 (when (stringp (car attr))
4958 (while (string-match tramp-color-escape-sequence-regexp (car attr))
4959 (setcar attr (replace-match "" nil nil (car attr)))))
4960 ;; Convert uid and gid. Use -1 as indication of unusable value.
4961 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
4962 (setcar (nthcdr 2 attr) -1))
4963 (when (and (floatp (nth 2 attr))
4964 (<= (nth 2 attr) (tramp-compat-most-positive-fixnum)))
4965 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
4966 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
4967 (setcar (nthcdr 3 attr) -1))
4968 (when (and (floatp (nth 3 attr))
4969 (<= (nth 3 attr) (tramp-compat-most-positive-fixnum)))
4970 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
4971 ;; Convert last access time.
4972 (unless (listp (nth 4 attr))
4973 (setcar (nthcdr 4 attr)
4974 (list (floor (nth 4 attr) 65536)
4975 (floor (mod (nth 4 attr) 65536)))))
4976 ;; Convert last modification time.
4977 (unless (listp (nth 5 attr))
4978 (setcar (nthcdr 5 attr)
4979 (list (floor (nth 5 attr) 65536)
4980 (floor (mod (nth 5 attr) 65536)))))
4981 ;; Convert last status change time.
4982 (unless (listp (nth 6 attr))
4983 (setcar (nthcdr 6 attr)
4984 (list (floor (nth 6 attr) 65536)
4985 (floor (mod (nth 6 attr) 65536)))))
4986 ;; Convert file size.
4987 (when (< (nth 7 attr) 0)
4988 (setcar (nthcdr 7 attr) -1))
4989 (when (and (floatp (nth 7 attr))
4990 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
4991 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
4992 ;; Convert file mode bits to string.
4993 (unless (stringp (nth 8 attr))
4994 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
4995 (when (stringp (car attr))
4996 (aset (nth 8 attr) 0 ?l)))
4997 ;; Convert directory indication bit.
4998 (when (string-match "^d" (nth 8 attr))
5000 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
5001 (when (consp (car attr))
5002 (if (and (stringp (caar attr))
5003 (string-match ".+ -> .\\(.+\\)." (caar attr)))
5004 (setcar attr (match-string 1 (caar attr)))
5006 ;; Set file's gid change bit.
5007 (setcar (nthcdr 9 attr)
5008 (if (numberp (nth 3 attr))
5009 (not (= (nth 3 attr)
5010 (tramp-get-remote-gid vec 'integer)))
5013 (tramp-get-remote-gid vec 'string)))))
5015 (unless (listp (nth 10 attr))
5016 (setcar (nthcdr 10 attr)
5018 (cons (floor (nth 10 attr) 65536)
5019 (floor (mod (nth 10 attr) 65536)))
5020 ;; Inodes can be incredible huge. We must hide this.
5021 (error (tramp-get-inode vec)))))
5022 ;; Set virtual device number.
5023 (setcar (nthcdr 11 attr)
5024 (tramp-get-device vec))
5027 (defun tramp-shell-case-fold (string)
5028 "Converts STRING to shell glob pattern which ignores case."
5031 (if (equal (downcase c) (upcase c))
5033 (format "[%c%c]" (downcase c) (upcase c))))
5037 (defun tramp-make-copy-program-file-name (vec)
5038 "Create a file name suitable to be passed to `scp' or `nc' and workalikes."
5039 (let ((method (tramp-file-name-method vec))
5040 (user (tramp-file-name-user vec))
5041 (host (tramp-file-name-real-host vec))
5042 (localname (tramp-shell-quote-argument
5043 (tramp-file-name-localname vec))))
5045 ((tramp-get-method-parameter method 'tramp-remote-copy-program)
5047 ((not (zerop (length user)))
5048 (shell-quote-argument (format "%s@%s:%s" user host localname)))
5049 (t (shell-quote-argument (format "%s:%s" host localname))))))
5051 (defun tramp-method-out-of-band-p (vec size)
5052 "Return t if this is an out-of-band method, nil otherwise."
5054 ;; It shall be an out-of-band method.
5055 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
5056 ;; There must be a size, otherwise the file doesn't exist.
5058 ;; Either the file size is large enough, or (in rare cases) there
5059 ;; does not exist a remote encoding.
5060 (or (null tramp-copy-size-limit)
5061 (> size tramp-copy-size-limit)
5062 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
5064 ;; Variables local to connection.
5066 (defun tramp-get-remote-path (vec)
5067 (with-tramp-connection-property
5068 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
5069 ;; cache the result for the session only. Otherwise, the result
5070 ;; is cached persistently.
5071 (if (memq 'tramp-own-remote-path tramp-remote-path)
5072 (tramp-get-connection-process vec)
5075 (let* ((remote-path (copy-tree tramp-remote-path))
5076 (elt1 (memq 'tramp-default-remote-path remote-path))
5077 (elt2 (memq 'tramp-own-remote-path remote-path))
5078 (default-remote-path
5081 (tramp-send-command-and-read
5082 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
5083 ;; Default if "getconf" is not available.
5087 "`getconf PATH' not successful, using default value \"%s\"."
5091 ;; The login shell could return more than just the $PATH
5092 ;; string. So we use `tramp-end-of-heredoc' as marker.
5094 (tramp-send-command-and-read
5097 "%s -l %s 'echo %s \\\"$PATH\\\"'"
5098 (tramp-get-method-parameter
5099 (tramp-file-name-method vec) 'tramp-remote-shell)
5102 (tramp-get-method-parameter
5103 (tramp-file-name-method vec) 'tramp-remote-shell-args)
5105 (tramp-shell-quote-argument tramp-end-of-heredoc))
5106 nil (regexp-quote tramp-end-of-heredoc)))))
5108 ;; Replace place holder `tramp-default-remote-path'.
5112 (tramp-compat-split-string (or default-remote-path "") ":")
5114 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
5116 ;; Replace place holder `tramp-own-remote-path'.
5120 (tramp-compat-split-string (or own-remote-path "") ":")
5122 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
5124 ;; Remove double entries.
5125 (setq elt1 remote-path)
5127 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
5129 (setq elt1 (cdr elt1)))
5131 ;; Remove non-existing directories.
5139 (tramp-make-tramp-file-name
5140 (tramp-file-name-method vec)
5141 (tramp-file-name-user vec)
5142 (tramp-file-name-host vec)
5147 (defun tramp-get-remote-locale (vec)
5148 (with-tramp-connection-property vec "locale"
5149 (tramp-send-command vec "locale -a")
5150 (let ((candidates '("en_US.utf8" "C.utf8"))
5152 (with-current-buffer (tramp-get-connection-buffer vec)
5154 (goto-char (point-min))
5155 (if (string-match (concat "^" (car candidates) "$") (buffer-string))
5156 (setq locale (car candidates)
5158 (setq candidates (cdr candidates)))))
5160 (format "LC_ALL=%s" (or locale "C")))))
5162 (defun tramp-get-ls-command (vec)
5163 (with-tramp-connection-property vec "ls"
5164 (tramp-message vec 5 "Finding a suitable `ls' command")
5167 (dolist (cmd '("ls" "gnuls" "gls"))
5168 (let ((dl (tramp-get-remote-path vec))
5170 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5171 ;; Check parameters. On busybox, "ls" output coloring is
5172 ;; enabled by default sometimes. So we try to disable it
5173 ;; when possible. $LS_COLORING is not supported there.
5174 ;; Some "ls" versions are sensible wrt the order of
5175 ;; arguments, they fail when "-al" is after the
5176 ;; "--color=never" argument (for example on FreeBSD).
5177 (when (tramp-send-command-and-check
5178 vec (format "%s -lnd /" result))
5179 (when (tramp-send-command-and-check
5181 "%s --color=never -al /dev/null" result))
5182 (setq result (concat result " --color=never")))
5183 (throw 'ls-found result))
5184 (setq dl (cdr dl))))))
5185 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
5187 (defun tramp-get-ls-command-with-dired (vec)
5189 (with-tramp-connection-property vec "ls-dired"
5190 (tramp-message vec 5 "Checking, whether `ls --dired' works")
5191 ;; Some "ls" versions are sensible wrt the order of arguments,
5192 ;; they fail when "-al" is after the "--dired" argument (for
5193 ;; example on FreeBSD).
5194 (tramp-send-command-and-check
5195 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
5197 (defun tramp-get-test-command (vec)
5198 (with-tramp-connection-property vec "test"
5199 (tramp-message vec 5 "Finding a suitable `test' command")
5200 (if (tramp-send-command-and-check vec "test 0")
5202 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
5204 (defun tramp-get-test-nt-command (vec)
5205 ;; Does `test A -nt B' work? Use abominable `find' construct if it
5206 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
5207 ;; for otherwise the shell crashes.
5208 (with-tramp-connection-property vec "test-nt"
5212 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
5213 (with-current-buffer (tramp-get-buffer vec)
5214 (goto-char (point-min))
5215 (when (looking-at (regexp-quote tramp-end-of-output))
5216 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
5221 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
5222 (tramp-get-test-command vec)))
5223 "tramp_test_nt %s %s"))))
5225 (defun tramp-get-file-exists-command (vec)
5226 (with-tramp-connection-property vec "file-exists"
5227 (tramp-message vec 5 "Finding command to check if file exists")
5228 (tramp-find-file-exists-command vec)))
5230 (defun tramp-get-remote-ln (vec)
5231 (with-tramp-connection-property vec "ln"
5232 (tramp-message vec 5 "Finding a suitable `ln' command")
5233 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
5235 (defun tramp-get-remote-perl (vec)
5236 (with-tramp-connection-property vec "perl"
5237 (tramp-message vec 5 "Finding a suitable `perl' command")
5239 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
5240 (tramp-find-executable
5241 vec "perl" (tramp-get-remote-path vec)))))
5242 ;; We must check also for some Perl modules.
5244 (with-tramp-connection-property vec "perl-file-spec"
5245 (tramp-send-command-and-check
5246 vec (format "%s -e 'use File::Spec;'" result)))
5247 (with-tramp-connection-property vec "perl-cwd-realpath"
5248 (tramp-send-command-and-check
5249 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
5252 (defun tramp-get-remote-stat (vec)
5253 (with-tramp-connection-property vec "stat"
5254 (tramp-message vec 5 "Finding a suitable `stat' command")
5255 (let ((result (tramp-find-executable
5256 vec "stat" (tramp-get-remote-path vec)))
5258 ;; Check whether stat(1) returns usable syntax. "%s" does not
5259 ;; work on older AIX systems.
5262 (tramp-send-command-and-read
5263 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5264 (unless (and (listp tmp) (stringp (car tmp))
5265 (string-match "^./.$" (car tmp))
5266 (integerp (cadr tmp)))
5270 (defun tramp-get-remote-readlink (vec)
5271 (with-tramp-connection-property vec "readlink"
5272 (tramp-message vec 5 "Finding a suitable `readlink' command")
5273 (let ((result (tramp-find-executable
5274 vec "readlink" (tramp-get-remote-path vec))))
5276 (tramp-send-command-and-check
5277 vec (format "%s --canonicalize-missing /" result)))
5280 (defun tramp-get-remote-trash (vec)
5281 (with-tramp-connection-property vec "trash"
5282 (tramp-message vec 5 "Finding a suitable `trash' command")
5283 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5285 (defun tramp-get-remote-touch (vec)
5286 (with-tramp-connection-property vec "touch"
5287 (tramp-message vec 5 "Finding a suitable `touch' command")
5288 (let ((result (tramp-find-executable
5289 vec "touch" (tramp-get-remote-path vec)))
5293 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
5294 ;; Busyboxes do support the "-t" option only when they have been
5295 ;; built with the DESKTOP config option. Let's check it.
5297 (tramp-set-connection-property
5299 (tramp-send-command-and-check
5304 (format-time-string "%Y%m%d%H%M.%S")
5305 (tramp-file-name-handler 'file-remote-p tmpfile 'localname))))
5306 (delete-file tmpfile))
5309 (defun tramp-get-remote-gvfs-monitor-dir (vec)
5310 (with-tramp-connection-property vec "gvfs-monitor-dir"
5311 (tramp-message vec 5 "Finding a suitable `gvfs-monitor-dir' command")
5312 (tramp-find-executable
5313 vec "gvfs-monitor-dir" (tramp-get-remote-path vec) t t)))
5315 (defun tramp-get-remote-inotifywait (vec)
5316 (with-tramp-connection-property vec "inotifywait"
5317 (tramp-message vec 5 "Finding a suitable `inotifywait' command")
5318 (tramp-find-executable vec "inotifywait" (tramp-get-remote-path vec) t t)))
5320 (defun tramp-get-remote-id (vec)
5321 (with-tramp-connection-property vec "id"
5322 (tramp-message vec 5 "Finding POSIX `id' command")
5324 (dolist (cmd '("id" "gid"))
5325 (let ((dl (tramp-get-remote-path vec))
5327 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5328 ;; Check POSIX parameter.
5329 (when (tramp-send-command-and-check vec (format "%s -u" result))
5330 (throw 'id-found result))
5331 (setq dl (cdr dl))))))))
5333 (defun tramp-get-remote-uid-with-id (vec id-format)
5334 (tramp-send-command-and-read
5336 (format "%s -u%s %s"
5337 (tramp-get-remote-id vec)
5338 (if (equal id-format 'integer) "" "n")
5339 (if (equal id-format 'integer)
5340 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/"))))
5342 (defun tramp-get-remote-uid-with-perl (vec id-format)
5343 (tramp-send-command-and-read
5345 (format "%s -le '%s'"
5346 (tramp-get-remote-perl vec)
5347 (if (equal id-format 'integer)
5349 "print \"\\\"\", scalar getpwuid($>), \"\\\"\""))))
5351 (defun tramp-get-remote-python (vec)
5352 (with-tramp-connection-property vec "python"
5353 (tramp-message vec 5 "Finding a suitable `python' command")
5354 (or (tramp-find-executable vec "python" (tramp-get-remote-path vec))
5355 (tramp-find-executable vec "python2" (tramp-get-remote-path vec))
5356 (tramp-find-executable vec "python3" (tramp-get-remote-path vec)))))
5358 (defun tramp-get-remote-uid-with-python (vec id-format)
5359 (tramp-send-command-and-read
5361 (format "%s -c \"%s\""
5362 (tramp-get-remote-python vec)
5363 (if (equal id-format 'integer)
5364 "import os; print (os.getuid())"
5365 "import os, pwd; print ('\\\"' + pwd.getpwuid(os.getuid())[0] + '\\\"')"))))
5367 (defun tramp-get-remote-uid (vec id-format)
5368 (with-tramp-connection-property vec (format "uid-%s" id-format)
5372 ((tramp-get-remote-id vec)
5373 (tramp-get-remote-uid-with-id vec id-format))
5374 ((tramp-get-remote-perl vec)
5375 (tramp-get-remote-uid-with-perl vec id-format))
5376 ((tramp-get-remote-python vec)
5377 (tramp-get-remote-uid-with-python vec id-format))))))
5378 ;; Ensure there is a valid result.
5380 ((and (equal id-format 'integer) (not (integerp res))) -1)
5381 ((and (equal id-format 'string) (not (stringp res))) "UNKNOWN")
5384 (defun tramp-get-remote-gid-with-id (vec id-format)
5385 (tramp-send-command-and-read
5387 (format "%s -g%s %s"
5388 (tramp-get-remote-id vec)
5389 (if (equal id-format 'integer) "" "n")
5390 (if (equal id-format 'integer)
5391 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/"))))
5393 (defun tramp-get-remote-gid-with-perl (vec id-format)
5394 (tramp-send-command-and-read
5396 (format "%s -le '%s'"
5397 (tramp-get-remote-perl vec)
5398 (if (equal id-format 'integer)
5399 "print ($)=~/(\\d+)/)"
5400 "print \"\\\"\", scalar getgrgid($)), \"\\\"\""))))
5402 (defun tramp-get-remote-gid-with-python (vec id-format)
5403 (tramp-send-command-and-read
5405 (format "%s -c \"%s\""
5406 (tramp-get-remote-python vec)
5407 (if (equal id-format 'integer)
5408 "import os; print (os.getgid())"
5409 "import os, grp; print ('\\\"' + grp.getgrgid(os.getgid())[0] + '\\\"')"))))
5411 (defun tramp-get-remote-gid (vec id-format)
5412 (with-tramp-connection-property vec (format "gid-%s" id-format)
5416 ((tramp-get-remote-id vec)
5417 (tramp-get-remote-gid-with-id vec id-format))
5418 ((tramp-get-remote-perl vec)
5419 (tramp-get-remote-gid-with-perl vec id-format))
5420 ((tramp-get-remote-python vec)
5421 (tramp-get-remote-gid-with-python vec id-format))))))
5422 ;; Ensure there is a valid result.
5424 ((and (equal id-format 'integer) (not (integerp res))) -1)
5425 ((and (equal id-format 'string) (not (stringp res))) "UNKNOWN")
5428 ;; Some predefined connection properties.
5429 (defun tramp-get-inline-compress (vec prop size)
5430 "Return the compress command related to PROP.
5431 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5432 the length of the file to be compressed.
5434 If no corresponding command is found, nil is returned."
5435 (when (and (integerp tramp-inline-compress-start-size)
5436 (> size tramp-inline-compress-start-size))
5437 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5438 (tramp-find-inline-compress vec)
5439 (tramp-get-connection-property
5440 (tramp-get-connection-process vec) prop nil))))
5442 (defun tramp-get-inline-coding (vec prop size)
5443 "Return the coding command related to PROP.
5444 PROP is either `remote-encoding', `remote-decoding',
5445 `local-encoding' or `local-decoding'.
5447 SIZE is the length of the file to be coded. Depending on SIZE,
5448 compression might be applied.
5450 If no corresponding command is found, nil is returned.
5451 Otherwise, either a string is returned which contains a `%s' mark
5452 to be used for the respective input or output file; or a Lisp
5453 function cell is returned to be applied on a buffer."
5454 ;; We must catch the errors, because we want to return `nil', when
5455 ;; no inline coding is found.
5458 (with-tramp-connection-property
5459 (tramp-get-connection-process vec) prop
5460 (tramp-find-inline-encoding vec)
5461 (tramp-get-connection-property
5462 (tramp-get-connection-process vec) prop nil)))
5463 (prop1 (if (string-match "encoding" prop)
5464 "inline-compress" "inline-decompress"))
5466 ;; The connection property might have been cached. So we must
5467 ;; send the script to the remote side - maybe.
5468 (when (and coding (symbolp coding) (string-match "remote" prop))
5469 (let ((name (symbol-name coding)))
5470 (while (string-match (regexp-quote "-") name)
5471 (setq name (replace-match "_" nil t name)))
5472 (tramp-maybe-send-script vec (symbol-value coding) name)
5473 (setq coding name)))
5475 ;; Check for the `compress' command.
5476 (setq compress (tramp-get-inline-compress vec prop1 size))
5477 ;; Return the value.
5479 ((and compress (symbolp coding))
5480 (if (string-match "decompress" prop1)
5483 (let ((coding-system-for-write 'binary)
5484 (coding-system-for-read 'binary))
5486 'call-process-region (point-min) (point-max)
5487 (car (split-string ,compress)) t t nil
5488 (cdr (split-string ,compress)))))
5490 (let ((coding-system-for-write 'binary)
5491 (coding-system-for-read 'binary))
5493 'call-process-region beg end
5494 (car (split-string ,compress)) t t nil
5495 (cdr (split-string ,compress))))
5496 (,coding (point-min) (point-max)))))
5499 ((and compress (string-match "decoding" prop))
5501 ;; Windows shells need the program file name after
5502 ;; the pipe symbol be quoted if they use forward
5503 ;; slashes as directory separators.
5505 ((and (string-match "local" prop)
5506 (memq system-type '(windows-nt)))
5508 ((string-match "local" prop) "(%s | %s)")
5509 (t "(%s | %s >%%s)"))
5513 ;; Windows shells need the program file name after
5514 ;; the pipe symbol be quoted if they use forward
5515 ;; slashes as directory separators.
5516 (if (and (string-match "local" prop)
5517 (memq system-type '(windows-nt)))
5518 "(%s <%%s | \"%s\")"
5521 ((string-match "decoding" prop)
5523 ((string-match "local" prop) (format "%s" coding))
5524 (t (format "%s >%%s" coding))))
5526 (format "%s <%%s" coding)))))))
5528 (add-hook 'tramp-unload-hook
5530 (unload-feature 'tramp-sh 'force)))
5536 ;; * Don't use globbing for directories with many files, as this is
5537 ;; likely to produce long command lines, and some shells choke on
5538 ;; long command lines.
5539 ;; * Make it work for different encodings, and for different file name
5540 ;; encodings, too. (Daniel Pittman)
5541 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5542 ;; then look if it's the right version (with `perl -v').
5543 ;; * When editing a remote CVS controlled file as a different user, VC
5544 ;; gets confused about the file locking status. Try to find out why
5545 ;; the workaround doesn't work.
5546 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5547 ;; until the last but one hop via `start-file-process'. Apply it
5548 ;; also for ftp and smb.
5549 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5550 ;; some shell with root privileges, it would be nice if I could
5552 ;; trampclient filename.c
5553 ;; as an editor, and the _current_ shell would connect to an Emacs
5554 ;; server and would be used in an existing non-privileged Emacs
5555 ;; session for doing the editing in question.
5556 ;; That way, I need not tell Emacs my password again and be afraid
5557 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5558 ;; once display a just typed password in the context of a keyboard
5559 ;; sequence prompt for a question immediately following in a shell
5560 ;; script run within Emacs -- nasty).
5561 ;; And if I have some ssh session running to a different computer,
5562 ;; having the possibility of passing a local file there to a local
5563 ;; Emacs session (in case I can arrange for a connection back) would
5565 ;; Likely the corresponding Tramp server should not allow the
5566 ;; equivalent of the emacsclient -eval option in order to make this
5567 ;; reasonably unproblematic. And maybe trampclient should have some
5568 ;; way of passing credentials, like by using an SSL socket or
5569 ;; something. (David Kastrup)
5570 ;; * Reconnect directly to a compliant shell without first going
5571 ;; through the user's default shell. (Pete Forman)
5572 ;; * How can I interrupt the remote process with a signal
5573 ;; (interrupt-process seems not to work)? (Markus Triska)
5574 ;; * Avoid the local shell entirely for starting remote processes. If
5575 ;; so, I think even a signal, when delivered directly to the local
5576 ;; SSH instance, would correctly be propagated to the remote process
5577 ;; automatically; possibly SSH would have to be started with
5578 ;; "-t". (Markus Triska)
5579 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5580 ;; isn't on the remote host. (Mark A. Hershberger)
5581 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5582 ;; * Optimize out-of-band copying when both methods are scp-like (not
5584 ;; * Keep a second connection open for out-of-band methods like scp or
5587 ;;; tramp-sh.el ends here