* net/tramp-sh.el (tramp-open-connection-setup-interactive-shell):
[emacs.git] / lisp / net / tramp-sh.el
blobee37373a0fa020b13ca5a1f410625a0b7e694edb
1 ;;; tramp-sh.el --- Tramp access functions for (s)sh-like connections
3 ;; Copyright (C) 1998-2014 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
10 ;; Package: tramp
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/>.
27 ;;; Code:
29 (require 'tramp)
31 ;; Pacify byte-compiler.
32 (eval-when-compile
33 (require 'cl)
34 (require 'dired))
35 (defvar directory-sep-char)
36 (defvar tramp-gw-tunnel-method)
37 (defvar tramp-gw-socks-method)
39 (defcustom tramp-inline-compress-start-size 4096
40 "The minimum size of compressing where inline transfer.
41 When inline transfer, compress transferred data of file
42 whose size is this value or above (up to `tramp-copy-size-limit').
43 If it is nil, no compression at all will be applied."
44 :group 'tramp
45 :type '(choice (const nil) integer))
47 (defcustom tramp-copy-size-limit 10240
48 "The maximum file size where inline copying is preferred over an \
49 out-of-the-band copy.
50 If it is nil, out-of-the-band copy will be used without a check."
51 :group 'tramp
52 :type '(choice (const nil) integer))
54 ;;;###tramp-autoload
55 (defcustom tramp-terminal-type "dumb"
56 "Value of TERM environment variable for logging in to remote host.
57 Because Tramp wants to parse the output of the remote shell, it is easily
58 confused by ANSI color escape sequences and suchlike. Often, shell init
59 files conditionalize this setup based on the TERM environment variable."
60 :group 'tramp
61 :type 'string)
63 ;;;###tramp-autoload
64 (defconst tramp-color-escape-sequence-regexp "\e[[;0-9]+m"
65 "Escape sequences produced by the \"ls\" command.")
67 ;; ksh on OpenBSD 4.5 requires that $PS1 contains a `#' character for
68 ;; root users. It uses the `$' character for other users. In order
69 ;; to guarantee a proper prompt, we use "#$ " for the prompt.
71 (defvar tramp-end-of-output
72 (format
73 "///%s#$"
74 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
75 "String used to recognize end of output.
76 The '$' character at the end is quoted; the string cannot be
77 detected as prompt when being sent on echoing hosts, therefore.")
79 ;;;###tramp-autoload
80 (defconst tramp-initial-end-of-output "#$ "
81 "Prompt when establishing a connection.")
83 (defconst tramp-end-of-heredoc (md5 tramp-end-of-output)
84 "String used to recognize end of heredoc strings.")
86 ;; Initialize `tramp-methods' with the supported methods.
87 ;;;###tramp-autoload
88 (add-to-list 'tramp-methods
89 '("rcp"
90 (tramp-login-program "rsh")
91 (tramp-login-args (("%h") ("-l" "%u")))
92 (tramp-remote-shell "/bin/sh")
93 (tramp-remote-shell-args ("-c"))
94 (tramp-copy-program "rcp")
95 (tramp-copy-args (("-p" "%k") ("-r")))
96 (tramp-copy-keep-date t)
97 (tramp-copy-recursive t)))
98 ;;;###tramp-autoload
99 (add-to-list 'tramp-methods
100 '("remcp"
101 (tramp-login-program "remsh")
102 (tramp-login-args (("%h") ("-l" "%u")))
103 (tramp-remote-shell "/bin/sh")
104 (tramp-remote-shell-args ("-c"))
105 (tramp-copy-program "rcp")
106 (tramp-copy-args (("-p" "%k")))
107 (tramp-copy-keep-date t)))
108 ;;;###tramp-autoload
109 (add-to-list 'tramp-methods
110 '("scp"
111 (tramp-login-program "ssh")
112 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
113 ("-e" "none") ("%h")))
114 (tramp-async-args (("-q")))
115 (tramp-remote-shell "/bin/sh")
116 (tramp-remote-shell-args ("-c"))
117 (tramp-copy-program "scp")
118 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q") ("-r") ("%c")))
119 (tramp-copy-keep-date t)
120 (tramp-copy-recursive t)
121 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
122 ("-o" "UserKnownHostsFile=/dev/null")
123 ("-o" "StrictHostKeyChecking=no")))
124 (tramp-default-port 22)))
125 ;;;###tramp-autoload
126 (add-to-list 'tramp-methods
127 '("scpx"
128 (tramp-login-program "ssh")
129 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
130 ("-e" "none") ("-t" "-t") ("%h") ("/bin/sh")))
131 (tramp-async-args (("-q")))
132 (tramp-remote-shell "/bin/sh")
133 (tramp-remote-shell-args ("-c"))
134 (tramp-copy-program "scp")
135 (tramp-copy-args (("-P" "%p") ("-p" "%k")
136 ("-q") ("-r") ("%c")))
137 (tramp-copy-keep-date t)
138 (tramp-copy-recursive t)
139 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
140 ("-o" "UserKnownHostsFile=/dev/null")
141 ("-o" "StrictHostKeyChecking=no")))
142 (tramp-default-port 22)))
143 ;;;###tramp-autoload
144 (add-to-list 'tramp-methods
145 '("sftp"
146 (tramp-login-program "ssh")
147 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
148 ("-e" "none") ("%h")))
149 (tramp-async-args (("-q")))
150 (tramp-remote-shell "/bin/sh")
151 (tramp-remote-shell-args ("-c"))
152 (tramp-copy-program "sftp")
153 (tramp-copy-args ("%c"))))
154 ;;;###tramp-autoload
155 (add-to-list 'tramp-methods
156 '("rsync"
157 (tramp-login-program "ssh")
158 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
159 ("-e" "none") ("%h")))
160 (tramp-async-args (("-q")))
161 (tramp-remote-shell "/bin/sh")
162 (tramp-remote-shell-args ("-c"))
163 (tramp-copy-program "rsync")
164 (tramp-copy-args (("-t" "%k") ("-r")))
165 (tramp-copy-env (("RSYNC_RSH") ("ssh" "%c")))
166 (tramp-copy-keep-date t)
167 (tramp-copy-keep-tmpfile t)
168 (tramp-copy-recursive t)))
169 ;;;###tramp-autoload
170 (add-to-list 'tramp-methods
171 '("rsh"
172 (tramp-login-program "rsh")
173 (tramp-login-args (("%h") ("-l" "%u")))
174 (tramp-remote-shell "/bin/sh")
175 (tramp-remote-shell-args ("-c"))))
176 ;;;###tramp-autoload
177 (add-to-list 'tramp-methods
178 '("remsh"
179 (tramp-login-program "remsh")
180 (tramp-login-args (("%h") ("-l" "%u")))
181 (tramp-remote-shell "/bin/sh")
182 (tramp-remote-shell-args ("-c"))))
183 ;;;###tramp-autoload
184 (add-to-list 'tramp-methods
185 '("ssh"
186 (tramp-login-program "ssh")
187 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
188 ("-e" "none") ("%h")))
189 (tramp-async-args (("-q")))
190 (tramp-remote-shell "/bin/sh")
191 (tramp-remote-shell-args ("-c"))
192 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
193 ("-o" "UserKnownHostsFile=/dev/null")
194 ("-o" "StrictHostKeyChecking=no")))
195 (tramp-default-port 22)))
196 ;;;###tramp-autoload
197 (add-to-list 'tramp-methods
198 '("sshx"
199 (tramp-login-program "ssh")
200 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
201 ("-e" "none") ("-t" "-t") ("%h") ("/bin/sh")))
202 (tramp-async-args (("-q")))
203 (tramp-remote-shell "/bin/sh")
204 (tramp-remote-shell-args ("-c"))
205 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
206 ("-o" "UserKnownHostsFile=/dev/null")
207 ("-o" "StrictHostKeyChecking=no")))
208 (tramp-default-port 22)))
209 ;;;###tramp-autoload
210 (add-to-list 'tramp-methods
211 '("telnet"
212 (tramp-login-program "telnet")
213 (tramp-login-args (("%h") ("%p")))
214 (tramp-remote-shell "/bin/sh")
215 (tramp-remote-shell-args ("-c"))
216 (tramp-default-port 23)))
217 ;;;###tramp-autoload
218 (add-to-list 'tramp-methods
219 '("su"
220 (tramp-login-program "su")
221 (tramp-login-args (("-") ("%u")))
222 (tramp-remote-shell "/bin/sh")
223 (tramp-remote-shell-args ("-c"))
224 (tramp-connection-timeout 10)))
225 ;;;###tramp-autoload
226 (add-to-list 'tramp-methods
227 '("sudo"
228 (tramp-login-program "sudo")
229 (tramp-login-args (("-u" "%u") ("-s") ("-H") ("-p" "Password:")))
230 (tramp-remote-shell "/bin/sh")
231 (tramp-remote-shell-args ("-c"))
232 (tramp-connection-timeout 10)))
233 ;;;###tramp-autoload
234 (add-to-list 'tramp-methods
235 '("ksu"
236 (tramp-login-program "ksu")
237 (tramp-login-args (("%u") ("-q")))
238 (tramp-remote-shell "/bin/sh")
239 (tramp-remote-shell-args ("-c"))
240 (tramp-connection-timeout 10)))
241 ;;;###tramp-autoload
242 (add-to-list 'tramp-methods
243 '("krlogin"
244 (tramp-login-program "krlogin")
245 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
246 (tramp-remote-shell "/bin/sh")
247 (tramp-remote-shell-args ("-c"))))
248 ;;;###tramp-autoload
249 (add-to-list 'tramp-methods
250 '("plink"
251 (tramp-login-program "plink")
252 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("%h")))
253 (tramp-remote-shell "/bin/sh")
254 (tramp-remote-shell-args ("-c"))
255 (tramp-default-port 22)))
256 ;;;###tramp-autoload
257 (add-to-list 'tramp-methods
258 `("plinkx"
259 (tramp-login-program "plink")
260 ;; ("%h") must be a single element, see
261 ;; `tramp-compute-multi-hops'.
262 (tramp-login-args (("-load") ("%h") ("-t")
263 (,(format
264 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
265 tramp-terminal-type
266 tramp-initial-end-of-output))
267 ("/bin/sh")))
268 (tramp-remote-shell "/bin/sh")
269 (tramp-remote-shell-args ("-c"))))
270 ;;;###tramp-autoload
271 (add-to-list 'tramp-methods
272 '("pscp"
273 (tramp-login-program "plink")
274 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("%h")))
275 (tramp-remote-shell "/bin/sh")
276 (tramp-remote-shell-args ("-c"))
277 (tramp-copy-program "pscp")
278 (tramp-copy-args (("-l" "%u") ("-P" "%p") ("-scp") ("-p" "%k")
279 ("-q") ("-r")))
280 (tramp-copy-keep-date t)
281 (tramp-copy-recursive t)
282 (tramp-default-port 22)))
283 ;;;###tramp-autoload
284 (add-to-list 'tramp-methods
285 '("psftp"
286 (tramp-login-program "plink")
287 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("%h")))
288 (tramp-remote-shell "/bin/sh")
289 (tramp-remote-shell-args ("-c"))
290 (tramp-copy-program "pscp")
291 (tramp-copy-args (("-l" "%u") ("-P" "%p") ("-sftp") ("-p" "%k")
292 ("-q") ("-r")))
293 (tramp-copy-keep-date t)
294 (tramp-copy-recursive t)))
295 ;;;###tramp-autoload
296 (add-to-list 'tramp-methods
297 '("fcp"
298 (tramp-login-program "fsh")
299 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
300 (tramp-remote-shell "/bin/sh")
301 (tramp-remote-shell-args ("-i") ("-c"))
302 (tramp-copy-program "fcp")
303 (tramp-copy-args (("-p" "%k")))
304 (tramp-copy-keep-date t)))
306 ;;;###tramp-autoload
307 (add-to-list 'tramp-default-method-alist
308 `(,tramp-local-host-regexp "\\`root\\'" "su"))
310 ;;;###tramp-autoload
311 (add-to-list 'tramp-default-user-alist
312 `(,(concat "\\`" (regexp-opt '("su" "sudo" "ksu")) "\\'")
313 nil "root"))
314 ;; Do not add "ssh" based methods, otherwise ~/.ssh/config would be ignored.
315 ;; Do not add "plink" based methods, they ask interactively for the user.
316 ;;;###tramp-autoload
317 (add-to-list 'tramp-default-user-alist
318 `(,(concat
319 "\\`"
320 (regexp-opt '("rcp" "remcp" "rsh" "telnet" "krlogin" "fcp"))
321 "\\'")
322 nil ,(user-login-name)))
324 ;;;###tramp-autoload
325 (defconst tramp-completion-function-alist-rsh
326 '((tramp-parse-rhosts "/etc/hosts.equiv")
327 (tramp-parse-rhosts "~/.rhosts"))
328 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
330 ;;;###tramp-autoload
331 (defconst tramp-completion-function-alist-ssh
332 '((tramp-parse-rhosts "/etc/hosts.equiv")
333 (tramp-parse-rhosts "/etc/shosts.equiv")
334 (tramp-parse-shosts "/etc/ssh_known_hosts")
335 (tramp-parse-sconfig "/etc/ssh_config")
336 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
337 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
338 (tramp-parse-rhosts "~/.rhosts")
339 (tramp-parse-rhosts "~/.shosts")
340 (tramp-parse-shosts "~/.ssh/known_hosts")
341 (tramp-parse-sconfig "~/.ssh/config")
342 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
343 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
344 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
346 ;;;###tramp-autoload
347 (defconst tramp-completion-function-alist-telnet
348 '((tramp-parse-hosts "/etc/hosts"))
349 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
351 ;;;###tramp-autoload
352 (defconst tramp-completion-function-alist-su
353 '((tramp-parse-passwd "/etc/passwd"))
354 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
356 ;;;###tramp-autoload
357 (defconst tramp-completion-function-alist-putty
358 `((tramp-parse-putty
359 ,(if (memq system-type '(windows-nt))
360 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"
361 "~/.putty/sessions")))
362 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty sessions.")
364 ;;;###tramp-autoload
365 (eval-after-load 'tramp
366 '(progn
367 (tramp-set-completion-function "rcp" tramp-completion-function-alist-rsh)
368 (tramp-set-completion-function "remcp" tramp-completion-function-alist-rsh)
369 (tramp-set-completion-function "scp" tramp-completion-function-alist-ssh)
370 (tramp-set-completion-function "scpx" tramp-completion-function-alist-ssh)
371 (tramp-set-completion-function "sftp" tramp-completion-function-alist-ssh)
372 (tramp-set-completion-function "rsync" tramp-completion-function-alist-ssh)
373 (tramp-set-completion-function "rsh" tramp-completion-function-alist-rsh)
374 (tramp-set-completion-function "remsh" tramp-completion-function-alist-rsh)
375 (tramp-set-completion-function "ssh" tramp-completion-function-alist-ssh)
376 (tramp-set-completion-function "sshx" tramp-completion-function-alist-ssh)
377 (tramp-set-completion-function
378 "telnet" tramp-completion-function-alist-telnet)
379 (tramp-set-completion-function "su" tramp-completion-function-alist-su)
380 (tramp-set-completion-function "sudo" tramp-completion-function-alist-su)
381 (tramp-set-completion-function "ksu" tramp-completion-function-alist-su)
382 (tramp-set-completion-function
383 "krlogin" tramp-completion-function-alist-rsh)
384 (tramp-set-completion-function "plink" tramp-completion-function-alist-ssh)
385 (tramp-set-completion-function
386 "plinkx" tramp-completion-function-alist-putty)
387 (tramp-set-completion-function "pscp" tramp-completion-function-alist-ssh)
388 (tramp-set-completion-function "fcp" tramp-completion-function-alist-ssh)))
390 ;; "getconf PATH" yields:
391 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
392 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
393 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
394 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
395 ;; IRIX64: /usr/bin
396 ;;;###tramp-autoload
397 (defcustom tramp-remote-path
398 '(tramp-default-remote-path "/bin" "/usr/bin" "/sbin" "/usr/sbin"
399 "/usr/local/bin" "/usr/local/sbin" "/local/bin" "/local/freeware/bin"
400 "/local/gnu/bin" "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin"
401 "/opt/bin" "/opt/sbin" "/opt/local/bin")
402 "List of directories to search for executables on remote host.
403 For every remote host, this variable will be set buffer local,
404 keeping the list of existing directories on that host.
406 You can use `~' in this list, but when searching for a shell which groks
407 tilde expansion, all directory names starting with `~' will be ignored.
409 `Default Directories' represent the list of directories given by
410 the command \"getconf PATH\". It is recommended to use this
411 entry on top of this list, because these are the default
412 directories for POSIX compatible commands. On remote hosts which
413 do not offer the getconf command (like cygwin), the value
414 \"/bin:/usr/bin\" is used instead of.
416 `Private Directories' are the settings of the $PATH environment,
417 as given in your `~/.profile'."
418 :group 'tramp
419 :type '(repeat (choice
420 (const :tag "Default Directories" tramp-default-remote-path)
421 (const :tag "Private Directories" tramp-own-remote-path)
422 (string :tag "Directory"))))
424 ;;;###tramp-autoload
425 (defcustom tramp-remote-process-environment
426 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "TMOUT=0" "LC_CTYPE=''"
427 ,(format "TERM=%s" tramp-terminal-type)
428 "EMACS=t" ;; Deprecated.
429 ,(format "INSIDE_EMACS='%s,tramp:%s'" emacs-version tramp-version)
430 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH=" "PAGER=\"\""
431 "autocorrect=" "correct=")
432 "List of environment variables to be set on the remote host.
434 Each element should be a string of the form ENVVARNAME=VALUE. An
435 entry ENVVARNAME= disables the corresponding environment variable,
436 which might have been set in the init files like ~/.profile.
438 Special handling is applied to the PATH environment, which should
439 not be set here. Instead, it should be set via `tramp-remote-path'."
440 :group 'tramp
441 :type '(repeat string))
443 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
444 "Alist specifying extra arguments to pass to the remote shell.
445 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
446 matching the shell file name and ARGS is a string specifying the
447 arguments.
449 This variable is only used when Tramp needs to start up another shell
450 for tilde expansion. The extra arguments should typically prevent the
451 shell from reading its init file."
452 :group 'tramp
453 ;; This might be the wrong way to test whether the widget type
454 ;; `alist' is available. Who knows the right way to test it?
455 :type (if (get 'alist 'widget-type)
456 '(alist :key-type string :value-type string)
457 '(repeat (cons string string))))
459 (defconst tramp-actions-before-shell
460 '((tramp-login-prompt-regexp tramp-action-login)
461 (tramp-password-prompt-regexp tramp-action-password)
462 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
463 (shell-prompt-pattern tramp-action-succeed)
464 (tramp-shell-prompt-pattern tramp-action-succeed)
465 (tramp-yesno-prompt-regexp tramp-action-yesno)
466 (tramp-yn-prompt-regexp tramp-action-yn)
467 (tramp-terminal-prompt-regexp tramp-action-terminal)
468 (tramp-process-alive-regexp tramp-action-process-alive))
469 "List of pattern/action pairs.
470 Whenever a pattern matches, the corresponding action is performed.
471 Each item looks like (PATTERN ACTION).
473 The PATTERN should be a symbol, a variable. The value of this
474 variable gives the regular expression to search for. Note that the
475 regexp must match at the end of the buffer, \"\\'\" is implicitly
476 appended to it.
478 The ACTION should also be a symbol, but a function. When the
479 corresponding PATTERN matches, the ACTION function is called.")
481 (defconst tramp-actions-copy-out-of-band
482 '((tramp-password-prompt-regexp tramp-action-password)
483 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
484 (tramp-copy-failed-regexp tramp-action-permission-denied)
485 (tramp-process-alive-regexp tramp-action-out-of-band))
486 "List of pattern/action pairs.
487 This list is used for copying/renaming with out-of-band methods.
489 See `tramp-actions-before-shell' for more info.")
491 (defconst tramp-uudecode
492 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
493 cat /tmp/tramp.$$
494 rm -f /tmp/tramp.$$"
495 "Shell function to implement `uudecode' to standard output.
496 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
497 for this or `uudecode -p', but some systems don't, and for them
498 we have this shell function.")
500 (defconst tramp-perl-file-truename
501 "%s -e '
502 use File::Spec;
503 use Cwd \"realpath\";
505 sub recursive {
506 my ($volume, @dirs) = @_;
507 my $real = realpath(File::Spec->catpath(
508 $volume, File::Spec->catdir(@dirs), \"\"));
509 if ($real) {
510 my ($vol, $dir) = File::Spec->splitpath($real, 1);
511 return ($vol, File::Spec->splitdir($dir));
513 else {
514 my $last = pop(@dirs);
515 ($volume, @dirs) = recursive($volume, @dirs);
516 push(@dirs, $last);
517 return ($volume, @dirs);
521 $result = realpath($ARGV[0]);
522 if (!$result) {
523 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
524 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
526 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
529 if ($ARGV[0] =~ /\\/$/) {
530 $result = $result . \"/\";
533 print \"\\\"$result\\\"\\n\";
534 ' \"$1\" 2>/dev/null"
535 "Perl script to produce output suitable for use with `file-truename'
536 on the remote file system.
537 Escape sequence %s is replaced with name of Perl binary.
538 This string is passed to `format', so percent characters need to be doubled.")
540 (defconst tramp-perl-file-name-all-completions
541 "%s -e 'sub case {
542 my $str = shift;
543 if ($ARGV[2]) {
544 return lc($str);
546 else {
547 return $str;
550 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
551 @files = readdir(d); closedir(d);
552 foreach $f (@files) {
553 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
554 if (-d \"$ARGV[0]/$f\") {
555 print \"$f/\\n\";
557 else {
558 print \"$f\\n\";
562 print \"ok\\n\"
563 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
564 "Perl script to produce output suitable for use with
565 `file-name-all-completions' on the remote file system. Escape
566 sequence %s is replaced with name of Perl binary. This string is
567 passed to `format', so percent characters need to be doubled.")
569 ;; Perl script to implement `file-attributes' in a Lisp `read'able
570 ;; output. If you are hacking on this, note that you get *no* output
571 ;; unless this spits out a complete line, including the '\n' at the
572 ;; end.
573 ;; The device number is returned as "-1", because there will be a virtual
574 ;; device number set in `tramp-sh-handle-file-attributes'.
575 (defconst tramp-perl-file-attributes
576 "%s -e '
577 @stat = lstat($ARGV[0]);
578 if (!@stat) {
579 print \"nil\\n\";
580 exit 0;
582 if (($stat[2] & 0170000) == 0120000)
584 $type = readlink($ARGV[0]);
585 $type = \"\\\"$type\\\"\";
587 elsif (($stat[2] & 0170000) == 040000)
589 $type = \"t\";
591 else
593 $type = \"nil\"
595 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
596 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
597 printf(
598 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
599 $type,
600 $stat[3],
601 $uid,
602 $gid,
603 $stat[8] >> 16 & 0xffff,
604 $stat[8] & 0xffff,
605 $stat[9] >> 16 & 0xffff,
606 $stat[9] & 0xffff,
607 $stat[10] >> 16 & 0xffff,
608 $stat[10] & 0xffff,
609 $stat[7],
610 $stat[2],
611 $stat[1] >> 16 & 0xffff,
612 $stat[1] & 0xffff
613 );' \"$1\" \"$2\" 2>/dev/null"
614 "Perl script to produce output suitable for use with `file-attributes'
615 on the remote file system.
616 Escape sequence %s is replaced with name of Perl binary.
617 This string is passed to `format', so percent characters need to be doubled.")
619 (defconst tramp-perl-directory-files-and-attributes
620 "%s -e '
621 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
622 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
623 @list = readdir(DIR);
624 closedir(DIR);
625 $n = scalar(@list);
626 printf(\"(\\n\");
627 for($i = 0; $i < $n; $i++)
629 $filename = $list[$i];
630 @stat = lstat($filename);
631 if (($stat[2] & 0170000) == 0120000)
633 $type = readlink($filename);
634 $type = \"\\\"$type\\\"\";
636 elsif (($stat[2] & 0170000) == 040000)
638 $type = \"t\";
640 else
642 $type = \"nil\"
644 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
645 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
646 printf(
647 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
648 $filename,
649 $type,
650 $stat[3],
651 $uid,
652 $gid,
653 $stat[8] >> 16 & 0xffff,
654 $stat[8] & 0xffff,
655 $stat[9] >> 16 & 0xffff,
656 $stat[9] & 0xffff,
657 $stat[10] >> 16 & 0xffff,
658 $stat[10] & 0xffff,
659 $stat[7],
660 $stat[2],
661 $stat[1] >> 16 & 0xffff,
662 $stat[1] & 0xffff,
663 $stat[0] >> 16 & 0xffff,
664 $stat[0] & 0xffff);
666 printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
667 "Perl script implementing `directory-files-attributes' as Lisp `read'able
668 output.
669 Escape sequence %s is replaced with name of Perl binary.
670 This string is passed to `format', so percent characters need to be doubled.")
672 ;; These two use base64 encoding.
673 (defconst tramp-perl-encode-with-module
674 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
675 "Perl program to use for encoding a file.
676 Escape sequence %s is replaced with name of Perl binary.
677 This string is passed to `format', so percent characters need to be doubled.
678 This implementation requires the MIME::Base64 Perl module to be installed
679 on the remote host.")
681 (defconst tramp-perl-decode-with-module
682 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
683 "Perl program to use for decoding a file.
684 Escape sequence %s is replaced with name of Perl binary.
685 This string is passed to `format', so percent characters need to be doubled.
686 This implementation requires the MIME::Base64 Perl module to be installed
687 on the remote host.")
689 (defconst tramp-perl-encode
690 "%s -e '
691 # This script contributed by Juanma Barranquero <lektu@terra.es>.
692 # Copyright (C) 2002-2014 Free Software Foundation, Inc.
693 use strict;
695 my %%trans = do {
696 my $i = 0;
697 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
698 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
700 my $data;
702 # We read in chunks of 54 bytes, to generate output lines
703 # of 72 chars (plus end of line)
704 while (read STDIN, $data, 54) {
705 my $pad = q();
707 # Only for the last chunk, and only if did not fill the last three-byte packet
708 if (eof) {
709 my $mod = length($data) %% 3;
710 $pad = q(=) x (3 - $mod) if $mod;
713 # Not the fastest method, but it is simple: unpack to binary string, split
714 # by groups of 6 bits and convert back from binary to byte; then map into
715 # the translation table
716 print
717 join q(),
718 map($trans{$_},
719 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
720 $pad,
721 qq(\\n);
722 }' 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.")
727 (defconst tramp-perl-decode
728 "%s -e '
729 # This script contributed by Juanma Barranquero <lektu@terra.es>.
730 # Copyright (C) 2002-2014 Free Software Foundation, Inc.
731 use strict;
733 my %%trans = do {
734 my $i = 0;
735 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
736 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
739 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
741 binmode(\\*STDOUT);
743 # We are going to accumulate into $pending to accept any line length
744 # (we do not check they are <= 76 chars as the RFC says)
745 my $pending = q();
747 while (my $data = <STDIN>) {
748 chomp $data;
750 # If we find one or two =, we have reached the end and
751 # any following data is to be discarded
752 my $finished = $data =~ s/(==?).*/$1/;
753 $pending .= $data;
755 my $len = length($pending);
756 my $chunk = substr($pending, 0, $len & ~3);
757 $pending = substr($pending, $len & ~3 + 1);
759 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
760 # split in 8-bit chunks and convert back to char.
761 print join q(),
762 map $bytes{$_},
763 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
765 last if $finished;
766 }' 2>/dev/null"
767 "Perl program to use for decoding a file.
768 Escape sequence %s is replaced with name of Perl binary.
769 This string is passed to `format', so percent characters need to be doubled.")
771 (defconst tramp-perl-pack
772 "%s -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
773 "Perl program to use for encoding a file.
774 Escape sequence %s is replaced with name of Perl binary.")
776 (defconst tramp-perl-unpack
777 "%s -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"
778 "Perl program to use for decoding a file.
779 Escape sequence %s is replaced with name of Perl binary.")
781 (defconst tramp-vc-registered-read-file-names
782 "echo \"(\"
783 while read file; do
784 if %s \"$file\"; then
785 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
786 else
787 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
789 if %s \"$file\"; then
790 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
791 else
792 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
794 done
795 echo \")\""
796 "Script to check existence of VC related files.
797 It must be send formatted with two strings; the tests for file
798 existence, and file readability. Input shall be read via
799 here-document, otherwise the command could exceed maximum length
800 of command line.")
802 ;; New handlers should be added here.
803 (defconst tramp-sh-file-name-handler-alist
804 '(;; `access-file' performed by default handler.
805 (add-name-to-file . tramp-sh-handle-add-name-to-file)
806 ;; `byte-compiler-base-file-name' performed by default handler.
807 (copy-directory . tramp-sh-handle-copy-directory)
808 (copy-file . tramp-sh-handle-copy-file)
809 (delete-directory . tramp-sh-handle-delete-directory)
810 (delete-file . tramp-sh-handle-delete-file)
811 ;; `diff-latest-backup-file' performed by default handler.
812 (directory-file-name . tramp-handle-directory-file-name)
813 (directory-files . tramp-handle-directory-files)
814 (directory-files-and-attributes
815 . tramp-sh-handle-directory-files-and-attributes)
816 ;; `dired-call-process' performed by default handler.
817 (dired-compress-file . tramp-sh-handle-dired-compress-file)
818 (dired-recursive-delete-directory
819 . tramp-sh-handle-dired-recursive-delete-directory)
820 (dired-uncache . tramp-handle-dired-uncache)
821 (expand-file-name . tramp-sh-handle-expand-file-name)
822 (file-accessible-directory-p . tramp-handle-file-accessible-directory-p)
823 (file-acl . tramp-sh-handle-file-acl)
824 (file-attributes . tramp-sh-handle-file-attributes)
825 (file-directory-p . tramp-sh-handle-file-directory-p)
826 ;; `file-equal-p' performed by default handler.
827 (file-executable-p . tramp-sh-handle-file-executable-p)
828 (file-exists-p . tramp-sh-handle-file-exists-p)
829 ;; `file-in-directory-p' performed by default handler.
830 (file-local-copy . tramp-sh-handle-file-local-copy)
831 (file-modes . tramp-handle-file-modes)
832 (file-name-all-completions . tramp-sh-handle-file-name-all-completions)
833 (file-name-as-directory . tramp-handle-file-name-as-directory)
834 (file-name-completion . tramp-handle-file-name-completion)
835 (file-name-directory . tramp-handle-file-name-directory)
836 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
837 ;; `file-name-sans-versions' performed by default handler.
838 (file-newer-than-file-p . tramp-sh-handle-file-newer-than-file-p)
839 (file-notify-add-watch . tramp-sh-handle-file-notify-add-watch)
840 (file-notify-rm-watch . tramp-handle-file-notify-rm-watch)
841 (file-ownership-preserved-p . tramp-sh-handle-file-ownership-preserved-p)
842 (file-readable-p . tramp-sh-handle-file-readable-p)
843 (file-regular-p . tramp-handle-file-regular-p)
844 (file-remote-p . tramp-handle-file-remote-p)
845 (file-selinux-context . tramp-sh-handle-file-selinux-context)
846 (file-symlink-p . tramp-handle-file-symlink-p)
847 (file-truename . tramp-sh-handle-file-truename)
848 (file-writable-p . tramp-sh-handle-file-writable-p)
849 (find-backup-file-name . tramp-handle-find-backup-file-name)
850 ;; `find-file-noselect' performed by default handler.
851 ;; `get-file-buffer' performed by default handler.
852 (insert-directory . tramp-sh-handle-insert-directory)
853 (insert-file-contents . tramp-handle-insert-file-contents)
854 (insert-file-contents-literally
855 . tramp-sh-handle-insert-file-contents-literally)
856 (load . tramp-handle-load)
857 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
858 (make-directory . tramp-sh-handle-make-directory)
859 (make-symbolic-link . tramp-sh-handle-make-symbolic-link)
860 (process-file . tramp-sh-handle-process-file)
861 (rename-file . tramp-sh-handle-rename-file)
862 (set-file-acl . tramp-sh-handle-set-file-acl)
863 (set-file-modes . tramp-sh-handle-set-file-modes)
864 (set-file-selinux-context . tramp-sh-handle-set-file-selinux-context)
865 (set-file-times . tramp-sh-handle-set-file-times)
866 (set-visited-file-modtime . tramp-sh-handle-set-visited-file-modtime)
867 (shell-command . tramp-handle-shell-command)
868 (start-file-process . tramp-sh-handle-start-file-process)
869 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
870 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
871 (vc-registered . tramp-sh-handle-vc-registered)
872 (verify-visited-file-modtime . tramp-sh-handle-verify-visited-file-modtime)
873 (write-region . tramp-sh-handle-write-region))
874 "Alist of handler functions.
875 Operations not mentioned here will be handled by the normal Emacs functions.")
877 ;; This must be the last entry, because `identity' always matches.
878 ;;;###tramp-autoload
879 (add-to-list 'tramp-foreign-file-name-handler-alist
880 '(identity . tramp-sh-file-name-handler) 'append)
882 ;;; File Name Handler Functions:
884 (defun tramp-sh-handle-make-symbolic-link
885 (filename linkname &optional ok-if-already-exists)
886 "Like `make-symbolic-link' for Tramp files.
887 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
888 the symlink. If LINKNAME is a Tramp file, only the localname component is
889 used as the target of the symlink.
891 If LINKNAME is a Tramp file and the localname component is relative, then
892 it is expanded first, before the localname component is taken. Note that
893 this can give surprising results if the user/host for the source and
894 target of the symlink differ."
895 (with-parsed-tramp-file-name linkname l
896 (let ((ln (tramp-get-remote-ln l))
897 (cwd (tramp-run-real-handler
898 'file-name-directory (list l-localname))))
899 (unless ln
900 (tramp-error
901 l 'file-error
902 "Making a symbolic link. ln(1) does not exist on the remote host."))
904 ;; Do the 'confirm if exists' thing.
905 (when (file-exists-p linkname)
906 ;; What to do?
907 (if (or (null ok-if-already-exists) ; not allowed to exist
908 (and (numberp ok-if-already-exists)
909 (not (yes-or-no-p
910 (format
911 "File %s already exists; make it a link anyway? "
912 l-localname)))))
913 (tramp-error
914 l 'file-already-exists "File %s already exists" l-localname)
915 (delete-file linkname)))
917 ;; If FILENAME is a Tramp name, use just the localname component.
918 (when (tramp-tramp-file-p filename)
919 (setq filename
920 (tramp-file-name-localname
921 (tramp-dissect-file-name (expand-file-name filename)))))
923 (tramp-flush-file-property l (file-name-directory l-localname))
924 (tramp-flush-file-property l l-localname)
926 ;; Right, they are on the same host, regardless of user, method,
927 ;; etc. We now make the link on the remote machine. This will
928 ;; occur as the user that FILENAME belongs to.
929 (tramp-send-command-and-check
931 (format
932 "cd %s && %s -sf %s %s"
933 (tramp-shell-quote-argument cwd)
935 (tramp-shell-quote-argument filename)
936 (tramp-shell-quote-argument l-localname))
937 t))))
939 (defun tramp-sh-handle-file-truename (filename)
940 "Like `file-truename' for Tramp files."
941 (format
942 "%s%s"
943 (with-parsed-tramp-file-name (expand-file-name filename) nil
944 (tramp-make-tramp-file-name
945 method user host
946 (with-tramp-file-property v localname "file-truename"
947 (let ((result nil)) ; result steps in reverse order
948 (tramp-message v 4 "Finding true name for `%s'" filename)
949 (cond
950 ;; Use GNU readlink --canonicalize-missing where available.
951 ((tramp-get-remote-readlink v)
952 (setq result
953 (tramp-send-command-and-read
955 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
956 (tramp-get-remote-readlink v)
957 (tramp-shell-quote-argument localname)))))
959 ;; Use Perl implementation.
960 ((and (tramp-get-remote-perl v)
961 (tramp-get-connection-property v "perl-file-spec" nil)
962 (tramp-get-connection-property v "perl-cwd-realpath" nil))
963 (tramp-maybe-send-script
964 v tramp-perl-file-truename "tramp_perl_file_truename")
965 (setq result
966 (tramp-send-command-and-read
968 (format "tramp_perl_file_truename %s"
969 (tramp-shell-quote-argument localname)))))
971 ;; Do it yourself. We bind `directory-sep-char' here for
972 ;; XEmacs on Windows, which would otherwise use backslash.
973 (t (let* ((directory-sep-char ?/)
974 (steps (tramp-compat-split-string localname "/"))
975 (localnamedir (tramp-run-real-handler
976 'file-name-as-directory (list localname)))
977 (is-dir (string= localname localnamedir))
978 (thisstep nil)
979 (numchase 0)
980 ;; Don't make the following value larger than
981 ;; necessary. People expect an error message in
982 ;; a timely fashion when something is wrong;
983 ;; otherwise they might think that Emacs is hung.
984 ;; Of course, correctness has to come first.
985 (numchase-limit 20)
986 symlink-target)
987 (while (and steps (< numchase numchase-limit))
988 (setq thisstep (pop steps))
989 (tramp-message
990 v 5 "Check %s"
991 (mapconcat 'identity
992 (append '("") (reverse result) (list thisstep))
993 "/"))
994 (setq symlink-target
995 (nth 0 (file-attributes
996 (tramp-make-tramp-file-name
997 method user host
998 (mapconcat 'identity
999 (append '("")
1000 (reverse result)
1001 (list thisstep))
1002 "/")))))
1003 (cond ((string= "." thisstep)
1004 (tramp-message v 5 "Ignoring step `.'"))
1005 ((string= ".." thisstep)
1006 (tramp-message v 5 "Processing step `..'")
1007 (pop result))
1008 ((stringp symlink-target)
1009 ;; It's a symlink, follow it.
1010 (tramp-message
1011 v 5 "Follow symlink to %s" symlink-target)
1012 (setq numchase (1+ numchase))
1013 (when (file-name-absolute-p symlink-target)
1014 (setq result nil))
1015 ;; If the symlink was absolute, we'll get a
1016 ;; string like "/user@host:/some/target";
1017 ;; extract the "/some/target" part from it.
1018 (when (tramp-tramp-file-p symlink-target)
1019 (unless (tramp-equal-remote filename symlink-target)
1020 (tramp-error
1021 v 'file-error
1022 "Symlink target `%s' on wrong host"
1023 symlink-target))
1024 (setq symlink-target localname))
1025 (setq steps
1026 (append (tramp-compat-split-string
1027 symlink-target "/")
1028 steps)))
1030 ;; It's a file.
1031 (setq result (cons thisstep result)))))
1032 (when (>= numchase numchase-limit)
1033 (tramp-error
1034 v 'file-error
1035 "Maximum number (%d) of symlinks exceeded" numchase-limit))
1036 (setq result (reverse result))
1037 ;; Combine list to form string.
1038 (setq result
1039 (if result
1040 (mapconcat 'identity (cons "" result) "/")
1041 "/"))
1042 (when (and is-dir
1043 (or (string= "" result)
1044 (not (string= (substring result -1) "/"))))
1045 (setq result (concat result "/"))))))
1047 (tramp-message v 4 "True name of `%s' is `%s'" localname result)
1048 result))))
1050 ;; Preserve trailing "/".
1051 (if (string-equal (file-name-nondirectory filename) "") "/" "")))
1053 ;; Basic functions.
1055 (defun tramp-sh-handle-file-exists-p (filename)
1056 "Like `file-exists-p' for Tramp files."
1057 (with-parsed-tramp-file-name filename nil
1058 (with-tramp-file-property v localname "file-exists-p"
1059 (or (not (null (tramp-get-file-property
1060 v localname "file-attributes-integer" nil)))
1061 (not (null (tramp-get-file-property
1062 v localname "file-attributes-string" nil)))
1063 (tramp-send-command-and-check
1065 (format
1066 "%s %s"
1067 (tramp-get-file-exists-command v)
1068 (tramp-shell-quote-argument localname)))))))
1070 (defun tramp-sh-handle-file-attributes (filename &optional id-format)
1071 "Like `file-attributes' for Tramp files."
1072 (unless id-format (setq id-format 'integer))
1073 ;; Don't modify `last-coding-system-used' by accident.
1074 (let ((last-coding-system-used last-coding-system-used))
1075 (with-parsed-tramp-file-name (expand-file-name filename) nil
1076 (with-tramp-file-property
1077 v localname (format "file-attributes-%s" id-format)
1078 (save-excursion
1079 (tramp-convert-file-attributes
1082 (cond
1083 ((tramp-get-remote-stat v)
1084 (tramp-do-file-attributes-with-stat v localname id-format))
1085 ((tramp-get-remote-perl v)
1086 (tramp-do-file-attributes-with-perl v localname id-format))
1087 (t nil))
1088 ;; The scripts could fail, for example with huge file size.
1089 (tramp-do-file-attributes-with-ls v localname id-format))))))))
1091 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
1092 "Implement `file-attributes' for Tramp files using the ls(1) command."
1093 (let (symlinkp dirp
1094 res-inode res-filemodes res-numlinks
1095 res-uid res-gid res-size res-symlink-target)
1096 (tramp-message vec 5 "file attributes with ls: %s" localname)
1097 (tramp-send-command
1099 (format "(%s %s || %s -h %s) && %s %s %s"
1100 (tramp-get-file-exists-command vec)
1101 (tramp-shell-quote-argument localname)
1102 (tramp-get-test-command vec)
1103 (tramp-shell-quote-argument localname)
1104 (tramp-get-ls-command vec)
1105 (if (eq id-format 'integer) "-ildn" "-ild")
1106 (tramp-shell-quote-argument localname)))
1107 ;; parse `ls -l' output ...
1108 (with-current-buffer (tramp-get-buffer vec)
1109 (when (> (buffer-size) 0)
1110 (goto-char (point-min))
1111 ;; ... inode
1112 (setq res-inode
1113 (condition-case err
1114 (read (current-buffer))
1115 (invalid-read-syntax
1116 (when (and (equal (cadr err)
1117 "Integer constant overflow in reader")
1118 (string-match
1119 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
1120 (car (cddr err))))
1121 (let* ((big (read (substring (car (cddr err)) 0
1122 (match-beginning 1))))
1123 (small (read (match-string 1 (car (cddr err)))))
1124 (twiddle (/ small 65536)))
1125 (cons (+ big twiddle)
1126 (- small (* twiddle 65536))))))))
1127 ;; ... file mode flags
1128 (setq res-filemodes (symbol-name (read (current-buffer))))
1129 ;; ... number links
1130 (setq res-numlinks (read (current-buffer)))
1131 ;; ... uid and gid
1132 (setq res-uid (read (current-buffer)))
1133 (setq res-gid (read (current-buffer)))
1134 (if (eq id-format 'integer)
1135 (progn
1136 (unless (numberp res-uid) (setq res-uid -1))
1137 (unless (numberp res-gid) (setq res-gid -1)))
1138 (progn
1139 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
1140 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
1141 ;; ... size
1142 (setq res-size (read (current-buffer)))
1143 ;; From the file modes, figure out other stuff.
1144 (setq symlinkp (eq ?l (aref res-filemodes 0)))
1145 (setq dirp (eq ?d (aref res-filemodes 0)))
1146 ;; if symlink, find out file name pointed to
1147 (when symlinkp
1148 (search-forward "-> ")
1149 (setq res-symlink-target (buffer-substring (point) (point-at-eol))))
1150 ;; return data gathered
1151 (list
1152 ;; 0. t for directory, string (name linked to) for symbolic
1153 ;; link, or nil.
1154 (or dirp res-symlink-target)
1155 ;; 1. Number of links to file.
1156 res-numlinks
1157 ;; 2. File uid.
1158 res-uid
1159 ;; 3. File gid.
1160 res-gid
1161 ;; 4. Last access time, as a list of integers. Normally this
1162 ;; would be in the same format as `current-time', but the
1163 ;; subseconds part is not currently implemented, and (0 0)
1164 ;; denotes an unknown time.
1165 ;; 5. Last modification time, likewise.
1166 ;; 6. Last status change time, likewise.
1167 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
1168 ;; 7. Size in bytes (-1, if number is out of range).
1169 res-size
1170 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
1171 res-filemodes
1172 ;; 9. t if file's gid would change if file were deleted and
1173 ;; recreated. Will be set in `tramp-convert-file-attributes'
1175 ;; 10. inode number.
1176 res-inode
1177 ;; 11. Device number. Will be replaced by a virtual device number.
1179 )))))
1181 (defun tramp-do-file-attributes-with-perl
1182 (vec localname &optional id-format)
1183 "Implement `file-attributes' for Tramp files using a Perl script."
1184 (tramp-message vec 5 "file attributes with perl: %s" localname)
1185 (tramp-maybe-send-script
1186 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
1187 (tramp-send-command-and-read
1189 (format "tramp_perl_file_attributes %s %s"
1190 (tramp-shell-quote-argument localname) id-format)))
1192 (defun tramp-do-file-attributes-with-stat
1193 (vec localname &optional id-format)
1194 "Implement `file-attributes' for Tramp files using stat(1) command."
1195 (tramp-message vec 5 "file attributes with stat: %s" localname)
1196 (tramp-send-command-and-read
1198 (format
1199 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
1200 ;; parse correctly the sequence "((". Therefore, we add a space.
1201 "( (%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)' %s || echo nil)"
1202 (tramp-get-file-exists-command vec)
1203 (tramp-shell-quote-argument localname)
1204 (tramp-get-test-command vec)
1205 (tramp-shell-quote-argument localname)
1206 (tramp-get-remote-stat vec)
1207 (if (eq id-format 'integer) "%ue0" "\"%U\"")
1208 (if (eq id-format 'integer) "%ge0" "\"%G\"")
1209 (tramp-shell-quote-argument localname))))
1211 (defun tramp-sh-handle-set-visited-file-modtime (&optional time-list)
1212 "Like `set-visited-file-modtime' for Tramp files."
1213 (unless (buffer-file-name)
1214 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
1215 (buffer-name)))
1216 (if time-list
1217 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
1218 (let ((f (buffer-file-name))
1219 coding-system-used)
1220 (with-parsed-tramp-file-name f nil
1221 (let* ((remote-file-name-inhibit-cache t)
1222 (attr (file-attributes f))
1223 ;; '(-1 65535) means file doesn't exists yet.
1224 (modtime (or (nth 5 attr) '(-1 65535))))
1225 (when (boundp 'last-coding-system-used)
1226 (setq coding-system-used (symbol-value 'last-coding-system-used)))
1227 ;; We use '(0 0) as a don't-know value. See also
1228 ;; `tramp-do-file-attributes-with-ls'.
1229 (if (not (equal modtime '(0 0)))
1230 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
1231 (progn
1232 (tramp-send-command
1234 (format "%s -ild %s"
1235 (tramp-get-ls-command v)
1236 (tramp-shell-quote-argument localname)))
1237 (setq attr (buffer-substring (point)
1238 (progn (end-of-line) (point)))))
1239 (tramp-set-file-property
1240 v localname "visited-file-modtime-ild" attr))
1241 (when (boundp 'last-coding-system-used)
1242 (set 'last-coding-system-used coding-system-used))
1243 nil)))))
1245 ;; This function makes the same assumption as
1246 ;; `tramp-sh-handle-set-visited-file-modtime'.
1247 (defun tramp-sh-handle-verify-visited-file-modtime (&optional buf)
1248 "Like `verify-visited-file-modtime' for Tramp files.
1249 At the time `verify-visited-file-modtime' calls this function, we
1250 already know that the buffer is visiting a file and that
1251 `visited-file-modtime' does not return 0. Do not call this
1252 function directly, unless those two cases are already taken care
1253 of."
1254 (with-current-buffer (or buf (current-buffer))
1255 (let ((f (buffer-file-name)))
1256 ;; There is no file visiting the buffer, or the buffer has no
1257 ;; recorded last modification time, or there is no established
1258 ;; connection.
1259 (if (or (not f)
1260 (eq (visited-file-modtime) 0)
1261 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
1263 (with-parsed-tramp-file-name f nil
1264 (let* ((remote-file-name-inhibit-cache t)
1265 (attr (file-attributes f))
1266 (modtime (nth 5 attr))
1267 (mt (visited-file-modtime)))
1269 (cond
1270 ;; File exists, and has a known modtime.
1271 ((and attr (not (equal modtime '(0 0))))
1272 (< (abs (tramp-time-diff
1273 modtime
1274 ;; For compatibility, deal with both the old
1275 ;; (HIGH . LOW) and the new (HIGH LOW) return
1276 ;; values of `visited-file-modtime'.
1277 (if (atom (cdr mt))
1278 (list (car mt) (cdr mt))
1279 mt)))
1281 ;; Modtime has the don't know value.
1282 (attr
1283 (tramp-send-command
1285 (format "%s -ild %s"
1286 (tramp-get-ls-command v)
1287 (tramp-shell-quote-argument localname)))
1288 (with-current-buffer (tramp-get-buffer v)
1289 (setq attr (buffer-substring
1290 (point) (progn (end-of-line) (point)))))
1291 (equal
1292 attr
1293 (tramp-get-file-property
1294 v localname "visited-file-modtime-ild" "")))
1295 ;; If file does not exist, say it is not modified if and
1296 ;; only if that agrees with the buffer's record.
1297 (t (equal mt '(-1 65535))))))))))
1299 (defun tramp-sh-handle-set-file-modes (filename mode)
1300 "Like `set-file-modes' for Tramp files."
1301 (with-parsed-tramp-file-name filename nil
1302 (tramp-flush-file-property v localname)
1303 ;; FIXME: extract the proper text from chmod's stderr.
1304 (tramp-barf-unless-okay
1306 (format "chmod %s %s"
1307 (tramp-compat-decimal-to-octal mode)
1308 (tramp-shell-quote-argument localname))
1309 "Error while changing file's mode %s" filename)))
1311 (defun tramp-sh-handle-set-file-times (filename &optional time)
1312 "Like `set-file-times' for Tramp files."
1313 (if (tramp-tramp-file-p filename)
1314 (with-parsed-tramp-file-name filename nil
1315 (when (tramp-get-remote-touch v)
1316 (tramp-flush-file-property v localname)
1317 (let ((time (if (or (null time) (equal time '(0 0)))
1318 (current-time)
1319 time))
1320 ;; With GNU Emacs, `format-time-string' has an
1321 ;; optional parameter UNIVERSAL. This is preferred,
1322 ;; because we could handle the case when the remote
1323 ;; host is located in a different time zone as the
1324 ;; local host.
1325 (utc (not (featurep 'xemacs))))
1326 (tramp-send-command-and-check
1327 v (format
1328 "%s %s %s %s"
1329 (if utc "env TZ=UTC" "")
1330 (tramp-get-remote-touch v)
1331 (if (tramp-get-connection-property v "touch-t" nil)
1332 (format "-t %s"
1333 (if utc
1334 (format-time-string "%Y%m%d%H%M.%S" time t)
1335 (format-time-string "%Y%m%d%H%M.%S" time)))
1337 (tramp-shell-quote-argument localname))))))
1339 ;; We handle also the local part, because in older Emacsen,
1340 ;; without `set-file-times', this function is an alias for this.
1341 ;; We are local, so we don't need the UTC settings.
1342 (zerop
1343 (tramp-call-process
1344 "touch" nil nil nil "-t"
1345 (format-time-string "%Y%m%d%H%M.%S" time)
1346 (tramp-shell-quote-argument filename)))))
1348 (defun tramp-set-file-uid-gid (filename &optional uid gid)
1349 "Set the ownership for FILENAME.
1350 If UID and GID are provided, these values are used; otherwise uid
1351 and gid of the corresponding user is taken. Both parameters must
1352 be non-negative integers."
1353 ;; Modern Unices allow chown only for root. So we might need
1354 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
1355 ;; working with su(do)? when it is needed, so it shall succeed in
1356 ;; the majority of cases.
1357 ;; Don't modify `last-coding-system-used' by accident.
1358 (let ((last-coding-system-used last-coding-system-used))
1359 (if (tramp-tramp-file-p filename)
1360 (with-parsed-tramp-file-name filename nil
1361 (if (and (zerop (user-uid)) (tramp-local-host-p v))
1362 ;; If we are root on the local host, we can do it directly.
1363 (tramp-set-file-uid-gid localname uid gid)
1364 (let ((uid (or (and (natnump uid) uid)
1365 (tramp-get-remote-uid v 'integer)))
1366 (gid (or (and (natnump gid) gid)
1367 (tramp-get-remote-gid v 'integer))))
1368 (tramp-send-command
1369 v (format
1370 "chown %d:%d %s" uid gid
1371 (tramp-shell-quote-argument localname))))))
1373 ;; We handle also the local part, because there doesn't exist
1374 ;; `set-file-uid-gid'. On W32 "chown" might not work.
1375 (let ((uid (or (and (natnump uid) uid) (tramp-get-local-uid 'integer)))
1376 (gid (or (and (natnump gid) gid) (tramp-get-local-gid 'integer))))
1377 (tramp-call-process
1378 "chown" nil nil nil
1379 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
1381 (defun tramp-remote-selinux-p (vec)
1382 "Check, whether SELINUX is enabled on the remote host."
1383 (with-tramp-connection-property
1384 (tramp-get-connection-process vec) "selinux-p"
1385 (let ((result (tramp-find-executable
1386 vec "getenforce" (tramp-get-remote-path vec) t t)))
1387 (and result
1388 (string-equal
1389 (tramp-send-command-and-read
1390 vec (format "echo \\\"`%S`\\\"" result))
1391 "Enforcing")))))
1393 (defun tramp-sh-handle-file-selinux-context (filename)
1394 "Like `file-selinux-context' for Tramp files."
1395 (with-parsed-tramp-file-name filename nil
1396 (with-tramp-file-property v localname "file-selinux-context"
1397 (let ((context '(nil nil nil nil))
1398 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
1399 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
1400 (when (and (tramp-remote-selinux-p v)
1401 (tramp-send-command-and-check
1402 v (format
1403 "%s -d -Z %s"
1404 (tramp-get-ls-command v)
1405 (tramp-shell-quote-argument localname))))
1406 (with-current-buffer (tramp-get-connection-buffer v)
1407 (goto-char (point-min))
1408 (when (re-search-forward regexp (point-at-eol) t)
1409 (setq context (list (match-string 1) (match-string 2)
1410 (match-string 3) (match-string 4))))))
1411 ;; Return the context.
1412 context))))
1414 (defun tramp-sh-handle-set-file-selinux-context (filename context)
1415 "Like `set-file-selinux-context' for Tramp files."
1416 (with-parsed-tramp-file-name filename nil
1417 (if (and (consp context)
1418 (tramp-remote-selinux-p v)
1419 (tramp-send-command-and-check
1420 v (format "chcon %s %s %s %s %s"
1421 (if (stringp (nth 0 context))
1422 (format "--user=%s" (nth 0 context)) "")
1423 (if (stringp (nth 1 context))
1424 (format "--role=%s" (nth 1 context)) "")
1425 (if (stringp (nth 2 context))
1426 (format "--type=%s" (nth 2 context)) "")
1427 (if (stringp (nth 3 context))
1428 (format "--range=%s" (nth 3 context)) "")
1429 (tramp-shell-quote-argument localname))))
1430 (progn
1431 (tramp-set-file-property v localname "file-selinux-context" context)
1433 (tramp-set-file-property v localname "file-selinux-context" 'undef)
1434 nil)))
1436 (defun tramp-remote-acl-p (vec)
1437 "Check, whether ACL is enabled on the remote host."
1438 (with-tramp-connection-property (tramp-get-connection-process vec) "acl-p"
1439 (tramp-send-command-and-check vec "getfacl /")))
1441 (defun tramp-sh-handle-file-acl (filename)
1442 "Like `file-acl' for Tramp files."
1443 (with-parsed-tramp-file-name filename nil
1444 (with-tramp-file-property v localname "file-acl"
1445 (when (and (tramp-remote-acl-p v)
1446 (tramp-send-command-and-check
1447 v (format
1448 "getfacl -ac %s 2>/dev/null"
1449 (tramp-shell-quote-argument localname))))
1450 (with-current-buffer (tramp-get-connection-buffer v)
1451 (goto-char (point-max))
1452 (delete-blank-lines)
1453 (when (> (point-max) (point-min))
1454 (tramp-compat-funcall
1455 'substring-no-properties (buffer-string))))))))
1457 (defun tramp-sh-handle-set-file-acl (filename acl-string)
1458 "Like `set-file-acl' for Tramp files."
1459 (with-parsed-tramp-file-name (expand-file-name filename) nil
1460 (if (and (stringp acl-string) (tramp-remote-acl-p v)
1461 (progn
1462 (tramp-send-command
1463 v (format "setfacl --set-file=- %s <<'%s'\n%s\n%s\n"
1464 (tramp-shell-quote-argument localname)
1465 tramp-end-of-heredoc
1466 acl-string
1467 tramp-end-of-heredoc))
1468 (tramp-send-command-and-check v nil)))
1469 ;; Success.
1470 (progn
1471 (tramp-set-file-property v localname "file-acl" acl-string)
1473 ;; In case of errors, we return `nil'.
1474 (tramp-set-file-property v localname "file-acl-string" 'undef)
1475 nil)))
1477 ;; Simple functions using the `test' command.
1479 (defun tramp-sh-handle-file-executable-p (filename)
1480 "Like `file-executable-p' for Tramp files."
1481 (with-parsed-tramp-file-name filename nil
1482 (with-tramp-file-property v localname "file-executable-p"
1483 ;; Examine `file-attributes' cache to see if request can be
1484 ;; satisfied without remote operation.
1485 (or (tramp-check-cached-permissions v ?x)
1486 (tramp-run-test "-x" filename)))))
1488 (defun tramp-sh-handle-file-readable-p (filename)
1489 "Like `file-readable-p' for Tramp files."
1490 (with-parsed-tramp-file-name filename nil
1491 (with-tramp-file-property v localname "file-readable-p"
1492 ;; Examine `file-attributes' cache to see if request can be
1493 ;; satisfied without remote operation.
1494 (or (tramp-check-cached-permissions v ?r)
1495 (tramp-run-test "-r" filename)))))
1497 ;; When the remote shell is started, it looks for a shell which groks
1498 ;; tilde expansion. Here, we assume that all shells which grok tilde
1499 ;; expansion will also provide a `test' command which groks `-nt' (for
1500 ;; newer than). If this breaks, tell me about it and I'll try to do
1501 ;; something smarter about it.
1502 (defun tramp-sh-handle-file-newer-than-file-p (file1 file2)
1503 "Like `file-newer-than-file-p' for Tramp files."
1504 (cond ((not (file-exists-p file1))
1505 nil)
1506 ((not (file-exists-p file2))
1508 ;; We are sure both files exist at this point.
1510 (save-excursion
1511 ;; We try to get the mtime of both files. If they are not
1512 ;; equal to the "dont-know" value, then we subtract the times
1513 ;; and obtain the result.
1514 (let ((fa1 (file-attributes file1))
1515 (fa2 (file-attributes file2)))
1516 (if (and (not (equal (nth 5 fa1) '(0 0)))
1517 (not (equal (nth 5 fa2) '(0 0))))
1518 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
1519 ;; If one of them is the dont-know value, then we can
1520 ;; still try to run a shell command on the remote host.
1521 ;; However, this only works if both files are Tramp
1522 ;; files and both have the same method, same user, same
1523 ;; host.
1524 (unless (tramp-equal-remote file1 file2)
1525 (with-parsed-tramp-file-name
1526 (if (tramp-tramp-file-p file1) file1 file2) nil
1527 (tramp-error
1528 v 'file-error
1529 "Files %s and %s must have same method, user, host"
1530 file1 file2)))
1531 (with-parsed-tramp-file-name file1 nil
1532 (tramp-run-test2
1533 (tramp-get-test-nt-command v) file1 file2))))))))
1535 ;; Functions implemented using the basic functions above.
1537 (defun tramp-sh-handle-file-directory-p (filename)
1538 "Like `file-directory-p' for Tramp files."
1539 (with-parsed-tramp-file-name filename nil
1540 ;; `file-directory-p' is used as predicate for filename completion.
1541 ;; Sometimes, when a connection is not established yet, it is
1542 ;; desirable to return t immediately for "/method:foo:". It can
1543 ;; be expected that this is always a directory.
1544 (or (zerop (length localname))
1545 (with-tramp-file-property v localname "file-directory-p"
1546 (tramp-run-test "-d" filename)))))
1548 (defun tramp-sh-handle-file-writable-p (filename)
1549 "Like `file-writable-p' for Tramp files."
1550 (with-parsed-tramp-file-name filename nil
1551 (with-tramp-file-property v localname "file-writable-p"
1552 (if (file-exists-p filename)
1553 ;; Examine `file-attributes' cache to see if request can be
1554 ;; satisfied without remote operation.
1555 (or (tramp-check-cached-permissions v ?w)
1556 (tramp-run-test "-w" filename))
1557 ;; If file doesn't exist, check if directory is writable.
1558 (and (tramp-run-test "-d" (file-name-directory filename))
1559 (tramp-run-test "-w" (file-name-directory filename)))))))
1561 (defun tramp-sh-handle-file-ownership-preserved-p (filename &optional group)
1562 "Like `file-ownership-preserved-p' for Tramp files."
1563 (with-parsed-tramp-file-name filename nil
1564 (with-tramp-file-property v localname "file-ownership-preserved-p"
1565 (let ((attributes (file-attributes filename)))
1566 ;; Return t if the file doesn't exist, since it's true that no
1567 ;; information would be lost by an (attempted) delete and create.
1568 (or (null attributes)
1569 (and
1570 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer))
1571 (or (not group)
1572 (= (nth 3 attributes) (tramp-get-remote-gid v 'integer)))))))))
1574 ;; Directory listings.
1576 (defun tramp-sh-handle-directory-files-and-attributes
1577 (directory &optional full match nosort id-format)
1578 "Like `directory-files-and-attributes' for Tramp files."
1579 (if (with-parsed-tramp-file-name directory nil
1580 (not (or (tramp-get-remote-stat v) (tramp-get-remote-perl v))))
1581 (tramp-handle-directory-files-and-attributes
1582 directory full match nosort id-format)
1584 ;; Do it directly.
1585 (unless id-format (setq id-format 'integer))
1586 (when (file-directory-p directory)
1587 (setq directory (expand-file-name directory))
1588 (let* ((temp
1589 (copy-tree
1590 (with-parsed-tramp-file-name directory nil
1591 (with-tramp-file-property
1592 v localname
1593 (format "directory-files-and-attributes-%s" id-format)
1594 (save-excursion
1595 (mapcar
1596 (lambda (x)
1597 (cons (car x)
1598 (tramp-convert-file-attributes v (cdr x))))
1599 (cond
1600 ((tramp-get-remote-stat v)
1601 (tramp-do-directory-files-and-attributes-with-stat
1602 v localname id-format))
1603 ((tramp-get-remote-perl v)
1604 (tramp-do-directory-files-and-attributes-with-perl
1605 v localname id-format)))))))))
1606 result item)
1608 (while temp
1609 (setq item (pop temp))
1610 (when (or (null match) (string-match match (car item)))
1611 (when full
1612 (setcar item (expand-file-name (car item) directory)))
1613 (push item result)))
1615 (if nosort
1616 result
1617 (sort result (lambda (x y) (string< (car x) (car y)))))))))
1619 (defun tramp-do-directory-files-and-attributes-with-perl
1620 (vec localname &optional id-format)
1621 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
1622 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
1623 (tramp-maybe-send-script
1624 vec tramp-perl-directory-files-and-attributes
1625 "tramp_perl_directory_files_and_attributes")
1626 (let ((object
1627 (tramp-send-command-and-read
1629 (format "tramp_perl_directory_files_and_attributes %s %s"
1630 (tramp-shell-quote-argument localname) id-format))))
1631 (when (stringp object) (tramp-error vec 'file-error object))
1632 object))
1634 (defun tramp-do-directory-files-and-attributes-with-stat
1635 (vec localname &optional id-format)
1636 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
1637 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
1638 (tramp-send-command-and-read
1640 (format
1641 (concat
1642 ;; We must care about filenames with spaces, or starting with
1643 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
1644 ;; but it does not work on all remote systems. Therefore, we
1645 ;; quote the filenames via sed.
1646 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | "
1647 "xargs %s -c "
1648 "'(\"%%n\" (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)'"
1649 " 2>/dev/null); echo \")\"")
1650 (tramp-shell-quote-argument localname)
1651 (tramp-get-ls-command vec)
1652 (tramp-get-remote-stat vec)
1653 (if (eq id-format 'integer) "%ue0" "\"%U\"")
1654 (if (eq id-format 'integer) "%ge0" "\"%G\""))))
1656 ;; This function should return "foo/" for directories and "bar" for
1657 ;; files.
1658 (defun tramp-sh-handle-file-name-all-completions (filename directory)
1659 "Like `file-name-all-completions' for Tramp files."
1660 (unless (save-match-data (string-match "/" filename))
1661 (with-parsed-tramp-file-name (expand-file-name directory) nil
1663 (all-completions
1664 filename
1665 (mapcar
1666 'list
1668 ;; Try cache entries for filename, filename with last
1669 ;; character removed, filename with last two characters
1670 ;; removed, ..., and finally the empty string - all
1671 ;; concatenated to the local directory name.
1672 (let ((remote-file-name-inhibit-cache
1673 (or remote-file-name-inhibit-cache
1674 tramp-completion-reread-directory-timeout)))
1676 ;; This is inefficient for very long filenames, pity
1677 ;; `reduce' is not available...
1678 (car
1679 (apply
1680 'append
1681 (mapcar
1682 (lambda (x)
1683 (let ((cache-hit
1684 (tramp-get-file-property
1686 (concat localname (substring filename 0 x))
1687 "file-name-all-completions"
1688 nil)))
1689 (when cache-hit (list cache-hit))))
1690 ;; We cannot use a length of 0, because file properties
1691 ;; for "foo" and "foo/" are identical.
1692 (tramp-compat-number-sequence (length filename) 1 -1)))))
1694 ;; Cache expired or no matching cache entry found so we need
1695 ;; to perform a remote operation.
1696 (let (result)
1697 ;; Get a list of directories and files, including reliably
1698 ;; tagging the directories with a trailing '/'. Because I
1699 ;; rock. --daniel@danann.net
1701 ;; Changed to perform `cd' in the same remote op and only
1702 ;; get entries starting with `filename'. Capture any `cd'
1703 ;; error messages. Ensure any `cd' and `echo' aliases are
1704 ;; ignored.
1705 (tramp-send-command
1707 (if (tramp-get-remote-perl v)
1708 (progn
1709 (tramp-maybe-send-script
1710 v tramp-perl-file-name-all-completions
1711 "tramp_perl_file_name_all_completions")
1712 (format "tramp_perl_file_name_all_completions %s %s %d"
1713 (tramp-shell-quote-argument localname)
1714 (tramp-shell-quote-argument filename)
1715 (if (symbol-value
1716 ;; `read-file-name-completion-ignore-case'
1717 ;; is introduced with Emacs 22.1.
1718 (if (boundp
1719 'read-file-name-completion-ignore-case)
1720 'read-file-name-completion-ignore-case
1721 'completion-ignore-case))
1722 1 0)))
1724 (format (concat
1725 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
1726 ;; `ls' with wildcard might fail with `Argument
1727 ;; list too long' error in some corner cases; if
1728 ;; `ls' fails after `cd' succeeded, chances are
1729 ;; that's the case, so let's retry without
1730 ;; wildcard. This will return "too many" entries
1731 ;; but that isn't harmful.
1732 " || %s -a 2>/dev/null)"
1733 " | while read f; do"
1734 " if %s -d \"$f\" 2>/dev/null;"
1735 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
1736 " && \\echo ok) || \\echo fail")
1737 (tramp-shell-quote-argument localname)
1738 (tramp-get-ls-command v)
1739 ;; When `filename' is empty, just `ls' without
1740 ;; filename argument is more efficient than `ls *'
1741 ;; for very large directories and might avoid the
1742 ;; `Argument list too long' error.
1744 ;; With and only with wildcard, we need to add
1745 ;; `-d' to prevent `ls' from descending into
1746 ;; sub-directories.
1747 (if (zerop (length filename))
1749 (concat (tramp-shell-quote-argument filename) "* -d"))
1750 (tramp-get-ls-command v)
1751 (tramp-get-test-command v))))
1753 ;; Now grab the output.
1754 (with-current-buffer (tramp-get-buffer v)
1755 (goto-char (point-max))
1757 ;; Check result code, found in last line of output.
1758 (forward-line -1)
1759 (if (looking-at "^fail$")
1760 (progn
1761 ;; Grab error message from line before last line
1762 ;; (it was put there by `cd 2>&1').
1763 (forward-line -1)
1764 (tramp-error
1765 v 'file-error
1766 "tramp-sh-handle-file-name-all-completions: %s"
1767 (buffer-substring (point) (point-at-eol))))
1768 ;; For peace of mind, if buffer doesn't end in `fail'
1769 ;; then it should end in `ok'. If neither are in the
1770 ;; buffer something went seriously wrong on the remote
1771 ;; side.
1772 (unless (looking-at "^ok$")
1773 (tramp-error
1774 v 'file-error
1776 tramp-sh-handle-file-name-all-completions: internal error accessing `%s': `%s'"
1777 (tramp-shell-quote-argument localname) (buffer-string))))
1779 (while (zerop (forward-line -1))
1780 (push (buffer-substring (point) (point-at-eol)) result)))
1782 ;; Because the remote op went through OK we know the
1783 ;; directory we `cd'-ed to exists.
1784 (tramp-set-file-property v localname "file-exists-p" t)
1786 ;; Because the remote op went through OK we know every
1787 ;; file listed by `ls' exists.
1788 (mapc (lambda (entry)
1789 (tramp-set-file-property
1790 v (concat localname entry) "file-exists-p" t))
1791 result)
1793 ;; Store result in the cache.
1794 (tramp-set-file-property
1795 v (concat localname filename)
1796 "file-name-all-completions" result))))))))
1798 ;; cp, mv and ln
1800 (defun tramp-sh-handle-add-name-to-file
1801 (filename newname &optional ok-if-already-exists)
1802 "Like `add-name-to-file' for Tramp files."
1803 (unless (tramp-equal-remote filename newname)
1804 (with-parsed-tramp-file-name
1805 (if (tramp-tramp-file-p filename) filename newname) nil
1806 (tramp-error
1807 v 'file-error
1808 "add-name-to-file: %s"
1809 "only implemented for same method, same user, same host")))
1810 (with-parsed-tramp-file-name filename v1
1811 (with-parsed-tramp-file-name newname v2
1812 (let ((ln (when v1 (tramp-get-remote-ln v1))))
1813 (when (and (numberp ok-if-already-exists)
1814 (file-exists-p newname)
1815 (yes-or-no-p
1816 (format
1817 "File %s already exists; make it a new name anyway? "
1818 newname)))
1819 (tramp-error
1820 v2 'file-error "add-name-to-file: file %s already exists" newname))
1821 (when ok-if-already-exists (setq ln (concat ln " -f")))
1822 (tramp-flush-file-property v2 (file-name-directory v2-localname))
1823 (tramp-flush-file-property v2 v2-localname)
1824 (tramp-barf-unless-okay
1826 (format "%s %s %s" ln
1827 (tramp-shell-quote-argument v1-localname)
1828 (tramp-shell-quote-argument v2-localname))
1829 "error with add-name-to-file, see buffer `%s' for details"
1830 (buffer-name))))))
1832 (defun tramp-sh-handle-copy-file
1833 (filename newname &optional ok-if-already-exists keep-date
1834 preserve-uid-gid preserve-extended-attributes)
1835 "Like `copy-file' for Tramp files."
1836 (setq filename (expand-file-name filename))
1837 (setq newname (expand-file-name newname))
1838 (cond
1839 ;; At least one file a Tramp file?
1840 ((or (tramp-tramp-file-p filename)
1841 (tramp-tramp-file-p newname))
1842 (tramp-do-copy-or-rename-file
1843 'copy filename newname ok-if-already-exists keep-date
1844 preserve-uid-gid preserve-extended-attributes))
1845 ;; Compat section.
1846 (preserve-extended-attributes
1847 (tramp-run-real-handler
1848 'copy-file
1849 (list filename newname ok-if-already-exists keep-date
1850 preserve-uid-gid preserve-extended-attributes)))
1851 (preserve-uid-gid
1852 (tramp-run-real-handler
1853 'copy-file
1854 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
1856 (tramp-run-real-handler
1857 'copy-file (list filename newname ok-if-already-exists keep-date)))))
1859 (defun tramp-sh-handle-copy-directory
1860 (dirname newname &optional keep-date parents copy-contents)
1861 "Like `copy-directory' for Tramp files."
1862 (let ((t1 (tramp-tramp-file-p dirname))
1863 (t2 (tramp-tramp-file-p newname)))
1864 (with-parsed-tramp-file-name (if t1 dirname newname) nil
1865 (if (and (not copy-contents)
1866 (tramp-get-method-parameter method 'tramp-copy-recursive)
1867 ;; When DIRNAME and NEWNAME are remote, they must have
1868 ;; the same method.
1869 (or (null t1) (null t2)
1870 (string-equal
1871 (tramp-file-name-method (tramp-dissect-file-name dirname))
1872 (tramp-file-name-method
1873 (tramp-dissect-file-name newname)))))
1874 ;; scp or rsync DTRT.
1875 (progn
1876 (setq dirname (directory-file-name (expand-file-name dirname))
1877 newname (directory-file-name (expand-file-name newname)))
1878 (if (and (file-directory-p newname)
1879 (not (string-equal (file-name-nondirectory dirname)
1880 (file-name-nondirectory newname))))
1881 (setq newname
1882 (expand-file-name
1883 (file-name-nondirectory dirname) newname)))
1884 (if (not (file-directory-p (file-name-directory newname)))
1885 (make-directory (file-name-directory newname) parents))
1886 (tramp-do-copy-or-rename-file-out-of-band
1887 'copy dirname newname keep-date))
1888 ;; We must do it file-wise.
1889 (tramp-run-real-handler
1890 'copy-directory
1891 (if copy-contents
1892 (list dirname newname keep-date parents copy-contents)
1893 (list dirname newname keep-date parents))))
1895 ;; When newname did exist, we have wrong cached values.
1896 (when t2
1897 (with-parsed-tramp-file-name newname nil
1898 (tramp-flush-file-property v (file-name-directory localname))
1899 (tramp-flush-file-property v localname))))))
1901 (defun tramp-sh-handle-rename-file
1902 (filename newname &optional ok-if-already-exists)
1903 "Like `rename-file' for Tramp files."
1904 ;; Check if both files are local -- invoke normal rename-file.
1905 ;; Otherwise, use Tramp from local system.
1906 (setq filename (expand-file-name filename))
1907 (setq newname (expand-file-name newname))
1908 ;; At least one file a Tramp file?
1909 (if (or (tramp-tramp-file-p filename)
1910 (tramp-tramp-file-p newname))
1911 (tramp-do-copy-or-rename-file
1912 'rename filename newname ok-if-already-exists t t)
1913 (tramp-run-real-handler
1914 'rename-file (list filename newname ok-if-already-exists))))
1916 (defun tramp-do-copy-or-rename-file
1917 (op filename newname &optional ok-if-already-exists keep-date
1918 preserve-uid-gid preserve-extended-attributes)
1919 "Copy or rename a remote file.
1920 OP must be `copy' or `rename' and indicates the operation to perform.
1921 FILENAME specifies the file to copy or rename, NEWNAME is the name of
1922 the new file (for copy) or the new name of the file (for rename).
1923 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
1924 KEEP-DATE means to make sure that NEWNAME has the same timestamp
1925 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
1926 the uid and gid if both files are on the same host.
1927 PRESERVE-EXTENDED-ATTRIBUTES activates selinux and acl commands.
1929 This function is invoked by `tramp-sh-handle-copy-file' and
1930 `tramp-sh-handle-rename-file'. It is an error if OP is neither
1931 of `copy' and `rename'. FILENAME and NEWNAME must be absolute
1932 file names."
1933 (unless (memq op '(copy rename))
1934 (error "Unknown operation `%s', must be `copy' or `rename'" op))
1935 (let ((t1 (tramp-tramp-file-p filename))
1936 (t2 (tramp-tramp-file-p newname))
1937 (length (nth 7 (file-attributes (file-truename filename))))
1938 (attributes (and preserve-extended-attributes
1939 (apply 'file-extended-attributes (list filename)))))
1941 (with-parsed-tramp-file-name (if t1 filename newname) nil
1942 (when (and (not ok-if-already-exists) (file-exists-p newname))
1943 (tramp-error
1944 v 'file-already-exists "File %s already exists" newname))
1946 (with-tramp-progress-reporter
1947 v 0 (format "%s %s to %s"
1948 (if (eq op 'copy) "Copying" "Renaming")
1949 filename newname)
1951 (cond
1952 ;; Both are Tramp files.
1953 ((and t1 t2)
1954 (with-parsed-tramp-file-name filename v1
1955 (with-parsed-tramp-file-name newname v2
1956 (cond
1957 ;; Shortcut: if method, host, user are the same for
1958 ;; both files, we invoke `cp' or `mv' on the remote
1959 ;; host directly.
1960 ((tramp-equal-remote filename newname)
1961 (tramp-do-copy-or-rename-file-directly
1962 op filename newname
1963 ok-if-already-exists keep-date preserve-uid-gid))
1965 ;; Try out-of-band operation.
1966 ((and
1967 (tramp-method-out-of-band-p v1 length)
1968 (tramp-method-out-of-band-p v2 length))
1969 (tramp-do-copy-or-rename-file-out-of-band
1970 op filename newname keep-date))
1972 ;; No shortcut was possible. So we copy the file
1973 ;; first. If the operation was `rename', we go back
1974 ;; and delete the original file (if the copy was
1975 ;; successful). The approach is simple-minded: we
1976 ;; create a new buffer, insert the contents of the
1977 ;; source file into it, then write out the buffer to
1978 ;; the target file. The advantage is that it doesn't
1979 ;; matter which filename handlers are used for the
1980 ;; source and target file.
1982 (tramp-do-copy-or-rename-file-via-buffer
1983 op filename newname keep-date))))))
1985 ;; One file is a Tramp file, the other one is local.
1986 ((or t1 t2)
1987 (cond
1988 ;; Fast track on local machine.
1989 ((tramp-local-host-p v)
1990 (tramp-do-copy-or-rename-file-directly
1991 op filename newname
1992 ok-if-already-exists keep-date preserve-uid-gid))
1994 ;; If the Tramp file has an out-of-band method, the
1995 ;; corresponding copy-program can be invoked.
1996 ((tramp-method-out-of-band-p v length)
1997 (tramp-do-copy-or-rename-file-out-of-band
1998 op filename newname keep-date))
2000 ;; Use the inline method via a Tramp buffer.
2001 (t (tramp-do-copy-or-rename-file-via-buffer
2002 op filename newname keep-date))))
2005 ;; One of them must be a Tramp file.
2006 (error "Tramp implementation says this cannot happen")))
2008 ;; Handle `preserve-extended-attributes'. We ignore possible
2009 ;; errors, because ACL strings could be incompatible.
2010 (when attributes
2011 (ignore-errors
2012 (apply 'set-file-extended-attributes (list newname attributes))))
2014 ;; In case of `rename', we must flush the cache of the source file.
2015 (when (and t1 (eq op 'rename))
2016 (with-parsed-tramp-file-name filename v1
2017 (tramp-flush-file-property v1 (file-name-directory v1-localname))
2018 (tramp-flush-file-property v1 v1-localname)))
2020 ;; When newname did exist, we have wrong cached values.
2021 (when t2
2022 (with-parsed-tramp-file-name newname v2
2023 (tramp-flush-file-property v2 (file-name-directory v2-localname))
2024 (tramp-flush-file-property v2 v2-localname)))))))
2026 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
2027 "Use an Emacs buffer to copy or rename a file.
2028 First arg OP is either `copy' or `rename' and indicates the operation.
2029 FILENAME is the source file, NEWNAME the target file.
2030 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
2031 (with-temp-buffer
2032 ;; We must disable multibyte, because binary data shall not be
2033 ;; converted.
2034 (set-buffer-multibyte nil)
2035 (let ((coding-system-for-read 'binary)
2036 (jka-compr-inhibit t))
2037 (insert-file-contents-literally filename))
2038 ;; We don't want the target file to be compressed, so we let-bind
2039 ;; `jka-compr-inhibit' to t.
2040 (let ((coding-system-for-write 'binary)
2041 (jka-compr-inhibit t))
2042 (write-region (point-min) (point-max) newname nil 'no-message)))
2043 ;; KEEP-DATE handling.
2044 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
2045 ;; Set the mode.
2046 (set-file-modes newname (tramp-default-file-modes filename))
2047 ;; If the operation was `rename', delete the original file.
2048 (unless (eq op 'copy) (delete-file filename)))
2050 (defun tramp-do-copy-or-rename-file-directly
2051 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
2052 "Invokes `cp' or `mv' on the remote system.
2053 OP must be one of `copy' or `rename', indicating `cp' or `mv',
2054 respectively. FILENAME specifies the file to copy or rename,
2055 NEWNAME is the name of the new file (for copy) or the new name of
2056 the file (for rename). Both files must reside on the same host.
2057 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2058 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2059 the uid and gid from FILENAME."
2060 (let ((t1 (tramp-tramp-file-p filename))
2061 (t2 (tramp-tramp-file-p newname))
2062 (file-times (nth 5 (file-attributes filename)))
2063 (file-modes (tramp-default-file-modes filename)))
2064 (with-parsed-tramp-file-name (if t1 filename newname) nil
2065 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
2066 ((eq op 'copy) "cp -f")
2067 ((eq op 'rename) "mv -f")
2068 (t (tramp-error
2069 v 'file-error
2070 "Unknown operation `%s', must be `copy' or `rename'"
2071 op))))
2072 (localname1
2073 (if t1
2074 (tramp-file-name-handler 'file-remote-p filename 'localname)
2075 filename))
2076 (localname2
2077 (if t2
2078 (tramp-file-name-handler 'file-remote-p newname 'localname)
2079 newname))
2080 (prefix (file-remote-p (if t1 filename newname)))
2081 cmd-result)
2083 (cond
2084 ;; Both files are on a remote host, with same user.
2085 ((and t1 t2)
2086 (setq cmd-result
2087 (tramp-send-command-and-check
2088 v (format "%s %s %s" cmd
2089 (tramp-shell-quote-argument localname1)
2090 (tramp-shell-quote-argument localname2))))
2091 (with-current-buffer (tramp-get-buffer v)
2092 (goto-char (point-min))
2093 (unless
2095 (and keep-date
2096 ;; Mask cp -f error.
2097 (re-search-forward
2098 tramp-operation-not-permitted-regexp nil t))
2099 cmd-result)
2100 (tramp-error-with-buffer
2101 nil v 'file-error
2102 "Copying directly failed, see buffer `%s' for details."
2103 (buffer-name)))))
2105 ;; We are on the local host.
2106 ((or t1 t2)
2107 (cond
2108 ;; We can do it directly.
2109 ((let (file-name-handler-alist)
2110 (and (file-readable-p localname1)
2111 (file-writable-p (file-name-directory localname2))
2112 (or (file-directory-p localname2)
2113 (file-writable-p localname2))))
2114 (if (eq op 'copy)
2115 (tramp-compat-copy-file
2116 localname1 localname2 ok-if-already-exists
2117 keep-date preserve-uid-gid)
2118 (tramp-run-real-handler
2119 'rename-file (list localname1 localname2 ok-if-already-exists))))
2121 ;; We can do it directly with `tramp-send-command'
2122 ((and (file-readable-p (concat prefix localname1))
2123 (file-writable-p
2124 (file-name-directory (concat prefix localname2)))
2125 (or (file-directory-p (concat prefix localname2))
2126 (file-writable-p (concat prefix localname2))))
2127 (tramp-do-copy-or-rename-file-directly
2128 op (concat prefix localname1) (concat prefix localname2)
2129 ok-if-already-exists keep-date t)
2130 ;; We must change the ownership to the local user.
2131 (tramp-set-file-uid-gid
2132 (concat prefix localname2)
2133 (tramp-get-local-uid 'integer)
2134 (tramp-get-local-gid 'integer)))
2136 ;; We need a temporary file in between.
2138 ;; Create the temporary file.
2139 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
2140 (unwind-protect
2141 (progn
2142 (cond
2144 (tramp-barf-unless-okay
2145 v (format
2146 "%s %s %s" cmd
2147 (tramp-shell-quote-argument localname1)
2148 (tramp-shell-quote-argument tmpfile))
2149 "Copying directly failed, see buffer `%s' for details."
2150 (tramp-get-buffer v))
2151 ;; We must change the ownership as remote user.
2152 ;; Since this does not work reliable, we also
2153 ;; give read permissions.
2154 (set-file-modes
2155 (concat prefix tmpfile)
2156 (tramp-compat-octal-to-decimal "0777"))
2157 (tramp-set-file-uid-gid
2158 (concat prefix tmpfile)
2159 (tramp-get-local-uid 'integer)
2160 (tramp-get-local-gid 'integer)))
2162 (if (eq op 'copy)
2163 (tramp-compat-copy-file
2164 localname1 tmpfile t
2165 keep-date preserve-uid-gid)
2166 (tramp-run-real-handler
2167 'rename-file
2168 (list localname1 tmpfile t)))
2169 ;; We must change the ownership as local user.
2170 ;; Since this does not work reliable, we also
2171 ;; give read permissions.
2172 (set-file-modes
2173 tmpfile (tramp-compat-octal-to-decimal "0777"))
2174 (tramp-set-file-uid-gid
2175 tmpfile
2176 (tramp-get-remote-uid v 'integer)
2177 (tramp-get-remote-gid v 'integer))))
2179 ;; Move the temporary file to its destination.
2180 (cond
2182 (tramp-barf-unless-okay
2183 v (format
2184 "cp -f -p %s %s"
2185 (tramp-shell-quote-argument tmpfile)
2186 (tramp-shell-quote-argument localname2))
2187 "Copying directly failed, see buffer `%s' for details."
2188 (tramp-get-buffer v)))
2190 (tramp-run-real-handler
2191 'rename-file
2192 (list tmpfile localname2 ok-if-already-exists)))))
2194 ;; Save exit.
2195 (ignore-errors (delete-file tmpfile)))))))))
2197 ;; Set the time and mode. Mask possible errors.
2198 (ignore-errors
2199 (when keep-date
2200 (set-file-times newname file-times)
2201 (set-file-modes newname file-modes))))))
2203 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
2204 "Invoke rcp program to copy.
2205 The method used must be an out-of-band method."
2206 (let* ((t1 (tramp-tramp-file-p filename))
2207 (t2 (tramp-tramp-file-p newname))
2208 (orig-vec (tramp-dissect-file-name (if t1 filename newname)))
2209 copy-program copy-args copy-env copy-keep-date port spec
2210 options source target)
2212 (with-parsed-tramp-file-name (if t1 filename newname) nil
2213 (if (and t1 t2)
2215 ;; Both are Tramp files. We shall optimize it when the
2216 ;; methods for filename and newname are the same.
2217 (let* ((dir-flag (file-directory-p filename))
2218 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
2219 (if dir-flag
2220 (setq tmpfile
2221 (expand-file-name
2222 (file-name-nondirectory newname) tmpfile)))
2223 (unwind-protect
2224 (progn
2225 (tramp-do-copy-or-rename-file-out-of-band
2226 op filename tmpfile keep-date)
2227 (tramp-do-copy-or-rename-file-out-of-band
2228 'rename tmpfile newname keep-date))
2229 ;; Save exit.
2230 (ignore-errors
2231 (if dir-flag
2232 (tramp-compat-delete-directory
2233 (expand-file-name ".." tmpfile) 'recursive)
2234 (delete-file tmpfile)))))
2236 ;; Set variables for computing the prompt for reading
2237 ;; password.
2238 (setq tramp-current-method (tramp-file-name-method v)
2239 tramp-current-user (or (tramp-file-name-user v)
2240 (tramp-get-connection-property
2241 v "login-as" nil))
2242 tramp-current-host (tramp-file-name-real-host v))
2244 ;; Expand hops. Might be necessary for gateway methods.
2245 (setq v (car (tramp-compute-multi-hops v)))
2246 (aset v 3 localname)
2248 ;; Check which ones of source and target are Tramp files.
2249 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
2250 target (funcall
2251 (if (and (file-directory-p filename)
2252 (string-equal
2253 (file-name-nondirectory filename)
2254 (file-name-nondirectory newname)))
2255 'file-name-directory
2256 'identity)
2257 (if t2 (tramp-make-copy-program-file-name v) newname)))
2259 ;; Check for host and port number. We cannot use
2260 ;; `tramp-file-name-port', because this returns also
2261 ;; `tramp-default-port', which might clash with settings in
2262 ;; "~/.ssh/config".
2263 (setq host (tramp-file-name-host v)
2264 port "")
2265 (when (string-match tramp-host-with-port-regexp host)
2266 (setq port (string-to-number (match-string 2 host))
2267 host (string-to-number (match-string 1 host))))
2269 ;; Check for user. There might be an interactive setting.
2270 (setq user (or (tramp-file-name-user v)
2271 (tramp-get-connection-property v "login-as" nil)))
2273 ;; Compose copy command.
2274 (setq host (or host "")
2275 user (or user "")
2276 port (or port "")
2277 spec (format-spec-make
2278 ?t (tramp-get-connection-property
2279 (tramp-get-connection-process v) "temp-file" ""))
2280 options (format-spec
2281 (if tramp-use-ssh-controlmaster-options
2282 tramp-ssh-controlmaster-options "")
2283 spec)
2284 spec (format-spec-make
2285 ?h host ?u user ?p port ?c options
2286 ?k (if keep-date " " ""))
2287 copy-program (tramp-get-method-parameter
2288 method 'tramp-copy-program)
2289 copy-keep-date (tramp-get-method-parameter
2290 method 'tramp-copy-keep-date)
2291 copy-args
2292 (delete
2293 ;; " " has either been a replacement of "%k" (when
2294 ;; keep-date argument is non-nil), or a replacement
2295 ;; for the whole keep-date sublist.
2297 (dolist
2299 (tramp-get-method-parameter method 'tramp-copy-args)
2300 copy-args)
2301 (setq copy-args
2302 (append
2303 copy-args
2304 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2305 (if (member "" y) '(" ") y))))))
2306 copy-env
2307 (delq
2309 (mapcar
2310 (lambda (x)
2311 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
2312 (unless (member "" x) (mapconcat 'identity x " ")))
2313 (tramp-get-method-parameter method 'tramp-copy-env))))
2315 ;; Check for program.
2316 (unless (executable-find copy-program)
2317 (tramp-error
2318 v 'file-error "Cannot find copy program: %s" copy-program))
2320 (with-temp-buffer
2321 (unwind-protect
2322 ;; The default directory must be remote.
2323 (let ((default-directory
2324 (file-name-directory (if t1 filename newname)))
2325 (process-environment (copy-sequence process-environment)))
2326 ;; Set the transfer process properties.
2327 (tramp-set-connection-property
2328 v "process-name" (buffer-name (current-buffer)))
2329 (tramp-set-connection-property
2330 v "process-buffer" (current-buffer))
2331 (while copy-env
2332 (tramp-message
2333 orig-vec 6 "%s=\"%s\"" (car copy-env) (cadr copy-env))
2334 (setenv (pop copy-env) (pop copy-env)))
2336 ;; Use an asynchronous process. By this, password can
2337 ;; be handled. The default directory must be local, in
2338 ;; order to apply the correct `copy-program'. We don't
2339 ;; set a timeout, because the copying of large files can
2340 ;; last longer than 60 secs.
2341 (let ((p (let ((default-directory
2342 (tramp-compat-temporary-file-directory)))
2343 (apply 'start-process-shell-command
2344 (tramp-get-connection-name v)
2345 (tramp-get-connection-buffer v)
2346 copy-program
2347 (append
2348 copy-args
2349 (list
2350 (shell-quote-argument source)
2351 (shell-quote-argument target)
2352 "&&" "echo" "tramp_exit_status" "0"
2353 "||" "echo" "tramp_exit_status" "1"))))))
2354 (tramp-message
2355 orig-vec 6 "%s"
2356 (mapconcat 'identity (process-command p) " "))
2357 (tramp-set-connection-property p "vector" orig-vec)
2358 (tramp-compat-set-process-query-on-exit-flag p nil)
2359 (tramp-process-actions
2360 p v nil tramp-actions-copy-out-of-band)
2362 ;; Check the return code.
2363 (goto-char (point-max))
2364 (unless
2365 (re-search-backward "tramp_exit_status [0-9]+" nil t)
2366 (tramp-error
2367 orig-vec 'file-error
2368 "Couldn't find exit status of `%s'"
2369 (mapconcat 'identity (process-command p) " ")))
2370 (skip-chars-forward "^ ")
2371 (unless (zerop (read (current-buffer)))
2372 (forward-line -1)
2373 (tramp-error
2374 orig-vec 'file-error
2375 "Error copying: `%s'"
2376 (buffer-substring (point-min) (point-at-eol))))))
2378 ;; Reset the transfer process properties.
2379 (tramp-message orig-vec 6 "\n%s" (buffer-string))
2380 (tramp-set-connection-property v "process-name" nil)
2381 (tramp-set-connection-property v "process-buffer" nil)))
2383 ;; Handle KEEP-DATE argument.
2384 (when (and keep-date (not copy-keep-date))
2385 (set-file-times newname (nth 5 (file-attributes filename))))
2387 ;; Set the mode.
2388 (unless (and keep-date copy-keep-date)
2389 (ignore-errors
2390 (set-file-modes newname (tramp-default-file-modes filename)))))
2392 ;; If the operation was `rename', delete the original file.
2393 (unless (eq op 'copy)
2394 (if (file-regular-p filename)
2395 (delete-file filename)
2396 (tramp-compat-delete-directory filename 'recursive))))))
2398 (defun tramp-sh-handle-make-directory (dir &optional parents)
2399 "Like `make-directory' for Tramp files."
2400 (setq dir (expand-file-name dir))
2401 (with-parsed-tramp-file-name dir nil
2402 (tramp-flush-directory-property v (file-name-directory localname))
2403 (save-excursion
2404 (tramp-barf-unless-okay
2405 v (format "%s %s"
2406 (if parents "mkdir -p" "mkdir")
2407 (tramp-shell-quote-argument localname))
2408 "Couldn't make directory %s" dir))))
2410 (defun tramp-sh-handle-delete-directory (directory &optional recursive)
2411 "Like `delete-directory' for Tramp files."
2412 (setq directory (expand-file-name directory))
2413 (with-parsed-tramp-file-name directory nil
2414 (tramp-flush-file-property v (file-name-directory localname))
2415 (tramp-flush-directory-property v localname)
2416 (tramp-barf-unless-okay
2417 v (format "%s %s"
2418 (if recursive "rm -rf" "rmdir")
2419 (tramp-shell-quote-argument localname))
2420 "Couldn't delete %s" directory)))
2422 (defun tramp-sh-handle-delete-file (filename &optional trash)
2423 "Like `delete-file' for Tramp files."
2424 (setq filename (expand-file-name filename))
2425 (with-parsed-tramp-file-name filename nil
2426 (tramp-flush-file-property v (file-name-directory localname))
2427 (tramp-flush-file-property v localname)
2428 (tramp-barf-unless-okay
2429 v (format "%s %s"
2430 (or (and trash (tramp-get-remote-trash v)) "rm -f")
2431 (tramp-shell-quote-argument localname))
2432 "Couldn't delete %s" filename)))
2434 ;; Dired.
2436 ;; CCC: This does not seem to be enough. Something dies when
2437 ;; we try and delete two directories under Tramp :/
2438 (defun tramp-sh-handle-dired-recursive-delete-directory (filename)
2439 "Recursively delete the directory given.
2440 This is like `dired-recursive-delete-directory' for Tramp files."
2441 (with-parsed-tramp-file-name filename nil
2442 ;; Run a shell command 'rm -r <localname>'.
2443 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
2444 (unless (file-exists-p filename)
2445 (tramp-error v 'file-error "No such directory: %s" filename))
2446 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>).
2447 (tramp-send-command
2449 (format "rm -rf %s" (tramp-shell-quote-argument localname))
2450 ;; Don't read the output, do it explicitly.
2451 nil t)
2452 ;; Wait for the remote system to return to us...
2453 ;; This might take a while, allow it plenty of time.
2454 (tramp-wait-for-output (tramp-get-connection-process v) 120)
2455 ;; Make sure that it worked...
2456 (tramp-flush-file-property v (file-name-directory localname))
2457 (tramp-flush-directory-property v localname)
2458 (and (file-exists-p filename)
2459 (tramp-error
2460 v 'file-error "Failed to recursively delete %s" filename))))
2462 (defun tramp-sh-handle-dired-compress-file (file &rest _ok-flag)
2463 "Like `dired-compress-file' for Tramp files."
2464 ;; OK-FLAG is valid for XEmacs only, but not implemented.
2465 ;; Code stolen mainly from dired-aux.el.
2466 (with-parsed-tramp-file-name file nil
2467 (tramp-flush-file-property v localname)
2468 (save-excursion
2469 (let ((suffixes
2470 (if (not (featurep 'xemacs))
2471 ;; Emacs case
2472 (symbol-value 'dired-compress-file-suffixes)
2473 ;; XEmacs has `dired-compression-method-alist', which is
2474 ;; transformed into `dired-compress-file-suffixes' structure.
2475 (mapcar
2476 (lambda (x)
2477 (list (concat (regexp-quote (nth 1 x)) "\\'")
2479 (mapconcat 'identity (nth 3 x) " ")))
2480 (symbol-value 'dired-compression-method-alist))))
2481 suffix)
2482 ;; See if any suffix rule matches this file name.
2483 (while suffixes
2484 (let (case-fold-search)
2485 (if (string-match (car (car suffixes)) localname)
2486 (setq suffix (car suffixes) suffixes nil))
2487 (setq suffixes (cdr suffixes))))
2489 (cond ((file-symlink-p file)
2490 nil)
2491 ((and suffix (nth 2 suffix))
2492 ;; We found an uncompression rule.
2493 (with-tramp-progress-reporter
2494 v 0 (format "Uncompressing %s" file)
2495 (when (tramp-send-command-and-check
2496 v (concat (nth 2 suffix) " "
2497 (tramp-shell-quote-argument localname)))
2498 ;; `dired-remove-file' is not defined in XEmacs.
2499 (tramp-compat-funcall 'dired-remove-file file)
2500 (string-match (car suffix) file)
2501 (concat (substring file 0 (match-beginning 0))))))
2503 ;; We don't recognize the file as compressed, so compress it.
2504 ;; Try gzip.
2505 (with-tramp-progress-reporter v 0 (format "Compressing %s" file)
2506 (when (tramp-send-command-and-check
2507 v (concat "gzip -f "
2508 (tramp-shell-quote-argument localname)))
2509 ;; `dired-remove-file' is not defined in XEmacs.
2510 (tramp-compat-funcall 'dired-remove-file file)
2511 (cond ((file-exists-p (concat file ".gz"))
2512 (concat file ".gz"))
2513 ((file-exists-p (concat file ".z"))
2514 (concat file ".z"))
2515 (t nil))))))))))
2517 (defun tramp-sh-handle-insert-directory
2518 (filename switches &optional wildcard full-directory-p)
2519 "Like `insert-directory' for Tramp files."
2520 (setq filename (expand-file-name filename))
2521 (unless switches (setq switches ""))
2522 (with-parsed-tramp-file-name filename nil
2523 (if (and (featurep 'ls-lisp)
2524 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
2525 (tramp-handle-insert-directory
2526 filename switches wildcard full-directory-p)
2527 (when (stringp switches)
2528 (setq switches (split-string switches)))
2529 (when (and (member "--dired" switches)
2530 (not (tramp-get-ls-command-with-dired v)))
2531 (setq switches (delete "--dired" switches)))
2532 (when wildcard
2533 (setq wildcard (tramp-run-real-handler
2534 'file-name-nondirectory (list localname)))
2535 (setq localname (tramp-run-real-handler
2536 'file-name-directory (list localname))))
2537 (unless (or full-directory-p (member "-d" switches))
2538 (setq switches (append switches '("-d"))))
2539 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
2540 (when wildcard
2541 (setq switches (concat switches " " wildcard)))
2542 (tramp-message
2543 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
2544 switches filename (if wildcard "yes" "no")
2545 (if full-directory-p "yes" "no"))
2546 ;; If `full-directory-p', we just say `ls -l FILENAME'.
2547 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
2548 (if full-directory-p
2549 (tramp-send-command
2551 (format "%s %s %s 2>/dev/null"
2552 (tramp-get-ls-command v)
2553 switches
2554 (if wildcard
2555 localname
2556 (tramp-shell-quote-argument (concat localname ".")))))
2557 (tramp-barf-unless-okay
2559 (format "cd %s" (tramp-shell-quote-argument
2560 (tramp-run-real-handler
2561 'file-name-directory (list localname))))
2562 "Couldn't `cd %s'"
2563 (tramp-shell-quote-argument
2564 (tramp-run-real-handler 'file-name-directory (list localname))))
2565 (tramp-send-command
2567 (format "%s %s %s 2>/dev/null"
2568 (tramp-get-ls-command v)
2569 switches
2570 (if (or wildcard
2571 (zerop (length
2572 (tramp-run-real-handler
2573 'file-name-nondirectory (list localname)))))
2575 (tramp-shell-quote-argument
2576 (tramp-run-real-handler
2577 'file-name-nondirectory (list localname)))))))
2579 (save-restriction
2580 (let ((beg (point)))
2581 (narrow-to-region (point) (point))
2582 ;; We cannot use `insert-buffer-substring' because the Tramp
2583 ;; buffer changes its contents before insertion due to calling
2584 ;; `expand-file' and alike.
2585 (insert
2586 (with-current-buffer (tramp-get-buffer v)
2587 (buffer-string)))
2589 ;; Check for "--dired" output.
2590 (forward-line -2)
2591 (when (looking-at "//SUBDIRED//")
2592 (forward-line -1))
2593 (when (looking-at "//DIRED//\\s-+")
2594 (let ((databeg (match-end 0))
2595 (end (point-at-eol)))
2596 ;; Now read the numeric positions of file names.
2597 (goto-char databeg)
2598 (while (< (point) end)
2599 (let ((start (+ beg (read (current-buffer))))
2600 (end (+ beg (read (current-buffer)))))
2601 (if (memq (char-after end) '(?\n ?\ ))
2602 ;; End is followed by \n or by " -> ".
2603 (put-text-property start end 'dired-filename t))))))
2604 ;; Remove trailing lines.
2605 (goto-char (point-at-bol))
2606 (while (looking-at "//")
2607 (forward-line 1)
2608 (delete-region (match-beginning 0) (point)))
2610 ;; Some busyboxes are reluctant to discard colors.
2611 (unless (string-match "color" (tramp-get-connection-property v "ls" ""))
2612 (goto-char beg)
2613 (while (re-search-forward tramp-color-escape-sequence-regexp nil t)
2614 (replace-match "")))
2616 ;; Decode the output, it could be multibyte.
2617 (decode-coding-region
2618 beg (point-max)
2619 (or file-name-coding-system
2620 (and (boundp 'default-file-name-coding-system)
2621 (symbol-value 'default-file-name-coding-system))))
2623 ;; The inserted file could be from somewhere else.
2624 (when (and (not wildcard) (not full-directory-p))
2625 (goto-char (point-max))
2626 (when (file-symlink-p filename)
2627 (goto-char (search-backward "->" beg 'noerror)))
2628 (search-backward
2629 (if (zerop (length (file-name-nondirectory filename)))
2631 (file-name-nondirectory filename))
2632 beg 'noerror)
2633 (replace-match (file-relative-name filename) t))
2635 (goto-char (point-max)))))))
2637 ;; Canonicalization of file names.
2639 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2640 "Like `expand-file-name' for Tramp files.
2641 If the localname part of the given filename starts with \"/../\" then
2642 the result will be a local, non-Tramp, filename."
2643 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
2644 (setq dir (or dir default-directory "/"))
2645 ;; Unless NAME is absolute, concat DIR and NAME.
2646 (unless (file-name-absolute-p name)
2647 (setq name (concat (file-name-as-directory dir) name)))
2648 ;; If NAME is not a Tramp file, run the real handler.
2649 (if (not (tramp-connectable-p name))
2650 (tramp-run-real-handler 'expand-file-name (list name nil))
2651 ;; Dissect NAME.
2652 (with-parsed-tramp-file-name name nil
2653 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2654 (setq localname (concat "~/" localname)))
2655 ;; Tilde expansion if necessary. This needs a shell which
2656 ;; groks tilde expansion! The function `tramp-find-shell' is
2657 ;; supposed to find such a shell on the remote host. Please
2658 ;; tell me about it when this doesn't work on your system.
2659 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2660 (let ((uname (match-string 1 localname))
2661 (fname (match-string 2 localname)))
2662 ;; We cannot simply apply "~/", because under sudo "~/" is
2663 ;; expanded to the local user home directory but to the
2664 ;; root home directory. On the other hand, using always
2665 ;; the default user name for tilde expansion is not
2666 ;; appropriate either, because ssh and companions might
2667 ;; use a user name from the config file.
2668 (when (and (string-equal uname "~")
2669 (string-match "\\`su\\(do\\)?\\'" method))
2670 (setq uname (concat uname user)))
2671 (setq uname
2672 (with-tramp-connection-property v uname
2673 (tramp-send-command
2674 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
2675 (with-current-buffer (tramp-get-buffer v)
2676 (goto-char (point-min))
2677 (buffer-substring (point) (point-at-eol)))))
2678 (setq localname (concat uname fname))))
2679 ;; There might be a double slash, for example when "~/"
2680 ;; expands to "/". Remove this.
2681 (while (string-match "//" localname)
2682 (setq localname (replace-match "/" t t localname)))
2683 ;; No tilde characters in file name, do normal
2684 ;; `expand-file-name' (this does "/./" and "/../"). We bind
2685 ;; `directory-sep-char' here for XEmacs on Windows, which would
2686 ;; otherwise use backslash. `default-directory' is bound,
2687 ;; because on Windows there would be problems with UNC shares or
2688 ;; Cygwin mounts.
2689 (let ((directory-sep-char ?/)
2690 (default-directory (tramp-compat-temporary-file-directory)))
2691 (tramp-make-tramp-file-name
2692 method user host
2693 (tramp-drop-volume-letter
2694 (tramp-run-real-handler
2695 'expand-file-name (list localname)))
2696 hop)))))
2698 ;;; Remote commands:
2700 (defun tramp-process-sentinel (proc event)
2701 "Flush file caches."
2702 (unless (memq (process-status proc) '(run open))
2703 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2704 (when vec
2705 (tramp-message vec 5 "Sentinel called: `%S' `%s'" proc event)
2706 (tramp-flush-connection-property proc)
2707 (tramp-flush-directory-property vec "")))))
2709 ;; We use BUFFER also as connection buffer during setup. Because of
2710 ;; this, its original contents must be saved, and restored once
2711 ;; connection has been setup.
2712 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2713 "Like `start-file-process' for Tramp files."
2714 (with-parsed-tramp-file-name default-directory nil
2715 (let* (;; When PROGRAM matches "*sh", and the first arg is "-c",
2716 ;; it might be that the arguments exceed the command line
2717 ;; length. Therefore, we modify the command.
2718 (heredoc (and (stringp program)
2719 (string-match "sh$" program)
2720 (string-equal "-c" (car args))
2721 (= (length args) 2)))
2722 ;; When PROGRAM is nil, we just provide a tty.
2723 (args (if (not heredoc) args
2724 (let ((i 250))
2725 (while (and (< i (length (cadr args)))
2726 (string-match " " (cadr args) i))
2727 (setcdr
2728 args
2729 (list (replace-match " \\\\\n" nil nil (cadr args))))
2730 (setq i (+ i 250))))
2731 (cdr args)))
2732 (command
2733 (when (stringp program)
2734 (format "cd %s && exec %s env PS1=%s %s"
2735 (tramp-shell-quote-argument localname)
2736 (if heredoc (format "<<'%s'" tramp-end-of-heredoc) "")
2737 ;; Use a human-friendly prompt, for example for `shell'.
2738 (tramp-shell-quote-argument
2739 (format "%s %s"
2740 (file-remote-p default-directory)
2741 tramp-initial-end-of-output))
2742 (if heredoc
2743 (format "%s\n(\n%s\n) </dev/tty\n%s"
2744 program (car args) tramp-end-of-heredoc)
2745 (mapconcat 'tramp-shell-quote-argument
2746 (cons program args) " ")))))
2747 (tramp-process-connection-type
2748 (or (null program) tramp-process-connection-type))
2749 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2750 (name1 name)
2751 (i 0)
2752 ;; We do not want to raise an error when
2753 ;; `start-file-process' has been started several time in
2754 ;; `eshell' and friends.
2755 (tramp-current-connection nil))
2757 (unless buffer
2758 ;; BUFFER can be nil. We use a temporary buffer.
2759 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
2760 (while (get-process name1)
2761 ;; NAME must be unique as process name.
2762 (setq i (1+ i)
2763 name1 (format "%s<%d>" name i)))
2764 (setq name name1)
2765 ;; Set the new process properties.
2766 (tramp-set-connection-property v "process-name" name)
2767 (tramp-set-connection-property v "process-buffer" buffer)
2769 (with-current-buffer (tramp-get-connection-buffer v)
2770 (unwind-protect
2771 ;; We catch this event. Otherwise, `start-process' could
2772 ;; be called on the local host.
2773 (save-excursion
2774 (save-restriction
2775 ;; Activate narrowing in order to save BUFFER
2776 ;; contents. Clear also the modification time;
2777 ;; otherwise we might be interrupted by
2778 ;; `verify-visited-file-modtime'.
2779 (let ((buffer-undo-list t)
2780 (buffer-read-only nil)
2781 (mark (point-max)))
2782 (clear-visited-file-modtime)
2783 (narrow-to-region (point-max) (point-max))
2784 ;; We call `tramp-maybe-open-connection', in order
2785 ;; to cleanup the prompt afterwards.
2786 (catch 'suppress
2787 (tramp-maybe-open-connection v)
2788 (widen)
2789 (delete-region mark (point))
2790 (narrow-to-region (point-max) (point-max))
2791 ;; Now do it.
2792 (if command
2793 ;; Send the command.
2794 (tramp-send-command v command nil t) ; nooutput
2795 ;; Check, whether a pty is associated.
2796 (unless (tramp-compat-process-get
2797 (tramp-get-connection-process v) 'remote-tty)
2798 (tramp-error
2799 v 'file-error
2800 "pty association is not supported for `%s'" name))))
2801 (let ((p (tramp-get-connection-process v)))
2802 ;; Set query flag and process marker for this
2803 ;; process. We ignore errors, because the process
2804 ;; could have finished already.
2805 (ignore-errors
2806 (tramp-compat-set-process-query-on-exit-flag p t)
2807 (set-marker (process-mark p) (point)))
2808 ;; Return process.
2809 p))))
2811 ;; Save exit.
2812 (if (string-match tramp-temp-buffer-name (buffer-name))
2813 (ignore-errors
2814 (set-process-buffer (tramp-get-connection-process v) nil)
2815 (kill-buffer (current-buffer)))
2816 (set-buffer-modified-p bmp))
2817 (tramp-set-connection-property v "process-name" nil)
2818 (tramp-set-connection-property v "process-buffer" nil))))))
2820 (defun tramp-sh-handle-process-file
2821 (program &optional infile destination display &rest args)
2822 "Like `process-file' for Tramp files."
2823 ;; The implementation is not complete yet.
2824 (when (and (numberp destination) (zerop destination))
2825 (error "Implementation does not handle immediate return"))
2827 (with-parsed-tramp-file-name default-directory nil
2828 (let (command input tmpinput stderr tmpstderr outbuf ret)
2829 ;; Compute command.
2830 (setq command (mapconcat 'tramp-shell-quote-argument
2831 (cons program args) " "))
2832 ;; Determine input.
2833 (if (null infile)
2834 (setq input "/dev/null")
2835 (setq infile (expand-file-name infile))
2836 (if (tramp-equal-remote default-directory infile)
2837 ;; INFILE is on the same remote host.
2838 (setq input (with-parsed-tramp-file-name infile nil localname))
2839 ;; INFILE must be copied to remote host.
2840 (setq input (tramp-make-tramp-temp-file v)
2841 tmpinput (tramp-make-tramp-file-name method user host input))
2842 (copy-file infile tmpinput t)))
2843 (when input (setq command (format "%s <%s" command input)))
2845 ;; Determine output.
2846 (cond
2847 ;; Just a buffer.
2848 ((bufferp destination)
2849 (setq outbuf destination))
2850 ;; A buffer name.
2851 ((stringp destination)
2852 (setq outbuf (get-buffer-create destination)))
2853 ;; (REAL-DESTINATION ERROR-DESTINATION)
2854 ((consp destination)
2855 ;; output.
2856 (cond
2857 ((bufferp (car destination))
2858 (setq outbuf (car destination)))
2859 ((stringp (car destination))
2860 (setq outbuf (get-buffer-create (car destination))))
2861 ((car destination)
2862 (setq outbuf (current-buffer))))
2863 ;; stderr.
2864 (cond
2865 ((stringp (cadr destination))
2866 (setcar (cdr destination) (expand-file-name (cadr destination)))
2867 (if (tramp-equal-remote default-directory (cadr destination))
2868 ;; stderr is on the same remote host.
2869 (setq stderr (with-parsed-tramp-file-name
2870 (cadr destination) nil localname))
2871 ;; stderr must be copied to remote host. The temporary
2872 ;; file must be deleted after execution.
2873 (setq stderr (tramp-make-tramp-temp-file v)
2874 tmpstderr (tramp-make-tramp-file-name
2875 method user host stderr))))
2876 ;; stderr to be discarded.
2877 ((null (cadr destination))
2878 (setq stderr "/dev/null"))))
2879 ;; 't
2880 (destination
2881 (setq outbuf (current-buffer))))
2882 (when stderr (setq command (format "%s 2>%s" command stderr)))
2884 ;; Send the command. It might not return in time, so we protect
2885 ;; it. Call it in a subshell, in order to preserve working
2886 ;; directory.
2887 (condition-case nil
2888 (unwind-protect
2889 (setq ret
2890 (if (tramp-send-command-and-check
2891 v (format "\\cd %s; %s"
2892 (tramp-shell-quote-argument localname)
2893 command)
2894 t t)
2895 0 1))
2896 ;; We should show the output anyway.
2897 (when outbuf
2898 (with-current-buffer outbuf
2899 (insert
2900 (with-current-buffer (tramp-get-connection-buffer v)
2901 (buffer-string))))
2902 (when display (display-buffer outbuf))))
2903 ;; When the user did interrupt, we should do it also. We use
2904 ;; return code -1 as marker.
2905 (quit
2906 (kill-buffer (tramp-get-connection-buffer v))
2907 (setq ret -1))
2908 ;; Handle errors.
2909 (error
2910 (kill-buffer (tramp-get-connection-buffer v))
2911 (setq ret 1)))
2913 ;; Provide error file.
2914 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
2916 ;; Cleanup. We remove all file cache values for the connection,
2917 ;; because the remote process could have changed them.
2918 (when tmpinput (delete-file tmpinput))
2920 ;; `process-file-side-effects' has been introduced with GNU
2921 ;; Emacs 23.2. If set to `nil', no remote file will be changed
2922 ;; by `program'. If it doesn't exist, we assume its default
2923 ;; value `t'.
2924 (unless (and (boundp 'process-file-side-effects)
2925 (not (symbol-value 'process-file-side-effects)))
2926 (tramp-flush-directory-property v ""))
2928 ;; Return exit status.
2929 (if (equal ret -1)
2930 (keyboard-quit)
2931 ret))))
2933 (defun tramp-sh-handle-file-local-copy (filename)
2934 "Like `file-local-copy' for Tramp files."
2935 (with-parsed-tramp-file-name filename nil
2936 (unless (file-exists-p filename)
2937 (tramp-error
2938 v 'file-error
2939 "Cannot make local copy of non-existing file `%s'" filename))
2941 (let* ((size (nth 7 (file-attributes (file-truename filename))))
2942 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
2943 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
2944 (tmpfile (tramp-compat-make-temp-file filename)))
2946 (condition-case err
2947 (cond
2948 ;; `copy-file' handles direct copy and out-of-band methods.
2949 ((or (tramp-local-host-p v)
2950 (tramp-method-out-of-band-p v size))
2951 (copy-file filename tmpfile t t))
2953 ;; Use inline encoding for file transfer.
2954 (rem-enc
2955 (save-excursion
2956 (with-tramp-progress-reporter
2958 (format "Encoding remote file `%s' with `%s'" filename rem-enc)
2959 (tramp-barf-unless-okay
2960 v (format rem-enc (tramp-shell-quote-argument localname))
2961 "Encoding remote file failed"))
2963 (with-tramp-progress-reporter
2964 v 3 (format "Decoding local file `%s' with `%s'"
2965 tmpfile loc-dec)
2966 (if (functionp loc-dec)
2967 ;; If local decoding is a function, we call it.
2968 ;; We must disable multibyte, because
2969 ;; `uudecode-decode-region' doesn't handle it
2970 ;; correctly.
2971 (with-temp-buffer
2972 (set-buffer-multibyte nil)
2973 (insert-buffer-substring (tramp-get-buffer v))
2974 (funcall loc-dec (point-min) (point-max))
2975 ;; Unset `file-name-handler-alist'. Otherwise,
2976 ;; epa-file gets confused.
2977 (let (file-name-handler-alist
2978 (coding-system-for-write 'binary))
2979 (write-region
2980 (point-min) (point-max) tmpfile nil 'no-message)))
2982 ;; If tramp-decoding-function is not defined for this
2983 ;; method, we invoke tramp-decoding-command instead.
2984 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
2985 ;; Unset `file-name-handler-alist'. Otherwise,
2986 ;; epa-file gets confused.
2987 (let (file-name-handler-alist
2988 (coding-system-for-write 'binary))
2989 (with-current-buffer (tramp-get-buffer v)
2990 (write-region
2991 (point-min) (point-max) tmpfile2 nil 'no-message)))
2992 (unwind-protect
2993 (tramp-call-local-coding-command
2994 loc-dec tmpfile2 tmpfile)
2995 (delete-file tmpfile2)))))
2997 ;; Set proper permissions.
2998 (set-file-modes tmpfile (tramp-default-file-modes filename))
2999 ;; Set local user ownership.
3000 (tramp-set-file-uid-gid tmpfile)))
3002 ;; Oops, I don't know what to do.
3003 (t (tramp-error
3004 v 'file-error "Wrong method specification for `%s'" method)))
3006 ;; Error handling.
3007 ((error quit)
3008 (delete-file tmpfile)
3009 (signal (car err) (cdr err))))
3011 (run-hooks 'tramp-handle-file-local-copy-hook)
3012 tmpfile)))
3014 ;; This is needed for XEmacs only. Code stolen from files.el.
3015 (defun tramp-sh-handle-insert-file-contents-literally
3016 (filename &optional visit beg end replace)
3017 "Like `insert-file-contents-literally' for Tramp files."
3018 (let ((format-alist nil)
3019 (after-insert-file-functions nil)
3020 (coding-system-for-read 'no-conversion)
3021 (coding-system-for-write 'no-conversion)
3022 (find-buffer-file-type-function
3023 (if (fboundp 'find-buffer-file-type)
3024 (symbol-function 'find-buffer-file-type)
3025 nil))
3026 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
3027 (inhibit-file-name-operation 'insert-file-contents))
3028 (unwind-protect
3029 (progn
3030 (fset 'find-buffer-file-type (lambda (_filename) t))
3031 (insert-file-contents filename visit beg end replace))
3032 ;; Save exit.
3033 (if find-buffer-file-type-function
3034 (fset 'find-buffer-file-type find-buffer-file-type-function)
3035 (fmakunbound 'find-buffer-file-type)))))
3037 ;; CCC grok LOCKNAME
3038 (defun tramp-sh-handle-write-region
3039 (start end filename &optional append visit lockname confirm)
3040 "Like `write-region' for Tramp files."
3041 (setq filename (expand-file-name filename))
3042 (with-parsed-tramp-file-name filename nil
3043 ;; Following part commented out because we don't know what to do about
3044 ;; file locking, and it does not appear to be a problem to ignore it.
3045 ;; Ange-ftp ignores it, too.
3046 ;; (when (and lockname (stringp lockname))
3047 ;; (setq lockname (expand-file-name lockname)))
3048 ;; (unless (or (eq lockname nil)
3049 ;; (string= lockname filename))
3050 ;; (error
3051 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3053 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
3054 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
3055 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3056 (tramp-error v 'file-error "File not overwritten")))
3058 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
3059 (tramp-get-remote-uid v 'integer)))
3060 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
3061 (tramp-get-remote-gid v 'integer))))
3063 (if (and (tramp-local-host-p v)
3064 ;; `file-writable-p' calls `file-expand-file-name'. We
3065 ;; cannot use `tramp-run-real-handler' therefore.
3066 (let (file-name-handler-alist)
3067 (and
3068 (file-writable-p (file-name-directory localname))
3069 (or (file-directory-p localname)
3070 (file-writable-p localname)))))
3071 ;; Short track: if we are on the local host, we can run directly.
3072 (tramp-run-real-handler
3073 'write-region
3074 (list start end localname append 'no-message lockname confirm))
3076 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3077 ;; We use this to save the value of
3078 ;; `last-coding-system-used' after writing the tmp
3079 ;; file. At the end of the function, we set
3080 ;; `last-coding-system-used' to this saved value. This
3081 ;; way, any intermediary coding systems used while
3082 ;; talking to the remote shell or suchlike won't hose
3083 ;; this variable. This approach was snarfed from
3084 ;; ange-ftp.el.
3085 coding-system-used
3086 ;; Write region into a tmp file. This isn't really
3087 ;; needed if we use an encoding function, but currently
3088 ;; we use it always because this makes the logic
3089 ;; simpler. We must also set `temporary-file-directory',
3090 ;; because it could point to a remote directory.
3091 (temporary-file-directory
3092 (tramp-compat-temporary-file-directory))
3093 (tmpfile (or tramp-temp-buffer-file-name
3094 (tramp-compat-make-temp-file filename))))
3096 ;; If `append' is non-nil, we copy the file locally, and let
3097 ;; the native `write-region' implementation do the job.
3098 (when append (copy-file filename tmpfile 'ok))
3100 ;; We say `no-message' here because we don't want the
3101 ;; visited file modtime data to be clobbered from the temp
3102 ;; file. We call `set-visited-file-modtime' ourselves later
3103 ;; on. We must ensure that `file-coding-system-alist'
3104 ;; matches `tmpfile'.
3105 (let (file-name-handler-alist
3106 (file-coding-system-alist
3107 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3108 (condition-case err
3109 (tramp-run-real-handler
3110 'write-region
3111 (list start end tmpfile append 'no-message lockname confirm))
3112 ((error quit)
3113 (setq tramp-temp-buffer-file-name nil)
3114 (delete-file tmpfile)
3115 (signal (car err) (cdr err))))
3117 ;; Now, `last-coding-system-used' has the right value. Remember it.
3118 (when (boundp 'last-coding-system-used)
3119 (setq coding-system-used
3120 (symbol-value 'last-coding-system-used))))
3122 ;; The permissions of the temporary file should be set. If
3123 ;; filename does not exist (eq modes nil) it has been
3124 ;; renamed to the backup file. This case `save-buffer'
3125 ;; handles permissions.
3126 ;; Ensure that it is still readable.
3127 (when modes
3128 (set-file-modes
3129 tmpfile
3130 (logior (or modes 0) (tramp-compat-octal-to-decimal "0400"))))
3132 ;; This is a bit lengthy due to the different methods
3133 ;; possible for file transfer. First, we check whether the
3134 ;; method uses an rcp program. If so, we call it.
3135 ;; Otherwise, both encoding and decoding command must be
3136 ;; specified. However, if the method _also_ specifies an
3137 ;; encoding function, then that is used for encoding the
3138 ;; contents of the tmp file.
3139 (let* ((size (nth 7 (file-attributes tmpfile)))
3140 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3141 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3142 (cond
3143 ;; `copy-file' handles direct copy and out-of-band methods.
3144 ((or (tramp-local-host-p v)
3145 (tramp-method-out-of-band-p v size))
3146 (if (and (not (stringp start))
3147 (= (or end (point-max)) (point-max))
3148 (= (or start (point-min)) (point-min))
3149 (tramp-get-method-parameter
3150 method 'tramp-copy-keep-tmpfile))
3151 (progn
3152 (setq tramp-temp-buffer-file-name tmpfile)
3153 (condition-case err
3154 ;; We keep the local file for performance
3155 ;; reasons, useful for "rsync".
3156 (copy-file tmpfile filename t)
3157 ((error quit)
3158 (setq tramp-temp-buffer-file-name nil)
3159 (delete-file tmpfile)
3160 (signal (car err) (cdr err)))))
3161 (setq tramp-temp-buffer-file-name nil)
3162 ;; Don't rename, in order to keep context in SELinux.
3163 (unwind-protect
3164 (copy-file tmpfile filename t)
3165 (delete-file tmpfile))))
3167 ;; Use inline file transfer.
3168 (rem-dec
3169 ;; Encode tmpfile.
3170 (unwind-protect
3171 (with-temp-buffer
3172 (set-buffer-multibyte nil)
3173 ;; Use encoding function or command.
3174 (with-tramp-progress-reporter
3175 v 3 (format "Encoding local file `%s' using `%s'"
3176 tmpfile loc-enc)
3177 (if (functionp loc-enc)
3178 ;; The following `let' is a workaround for
3179 ;; the base64.el that comes with pgnus-0.84.
3180 ;; If both of the following conditions are
3181 ;; satisfied, it tries to write to a local
3182 ;; file in default-directory, but at this
3183 ;; point, default-directory is remote.
3184 ;; (`call-process-region' can't write to
3185 ;; remote files, it seems.) The file in
3186 ;; question is a tmp file anyway.
3187 (let ((coding-system-for-read 'binary)
3188 (default-directory
3189 (tramp-compat-temporary-file-directory)))
3190 (insert-file-contents-literally tmpfile)
3191 (funcall loc-enc (point-min) (point-max)))
3193 (unless (zerop (tramp-call-local-coding-command
3194 loc-enc tmpfile t))
3195 (tramp-error
3196 v 'file-error
3197 (concat "Cannot write to `%s', "
3198 "local encoding command `%s' failed")
3199 filename loc-enc))))
3201 ;; Send buffer into remote decoding command which
3202 ;; writes to remote file. Because this happens on
3203 ;; the remote host, we cannot use the function.
3204 (with-tramp-progress-reporter
3205 v 3 (format "Decoding remote file `%s' using `%s'"
3206 filename rem-dec)
3207 (goto-char (point-max))
3208 (unless (bolp) (newline))
3209 (tramp-send-command
3211 (format
3212 (concat rem-dec " <<'%s'\n%s%s")
3213 (tramp-shell-quote-argument localname)
3214 tramp-end-of-heredoc
3215 (buffer-string)
3216 tramp-end-of-heredoc))
3217 (tramp-barf-unless-okay
3218 v nil
3219 "Couldn't write region to `%s', decode using `%s' failed"
3220 filename rem-dec)
3221 ;; When `file-precious-flag' is set, the region is
3222 ;; written to a temporary file. Check that the
3223 ;; checksum is equal to that from the local tmpfile.
3224 (when file-precious-flag
3225 (erase-buffer)
3226 (and
3227 ;; cksum runs locally, if possible.
3228 (zerop (tramp-call-process "cksum" tmpfile t))
3229 ;; cksum runs remotely.
3230 (tramp-send-command-and-check
3232 (format
3233 "cksum <%s" (tramp-shell-quote-argument localname)))
3234 ;; ... they are different.
3235 (not
3236 (string-equal
3237 (buffer-string)
3238 (with-current-buffer (tramp-get-buffer v)
3239 (buffer-string))))
3240 (tramp-error
3241 v 'file-error
3242 (concat "Couldn't write region to `%s',"
3243 " decode using `%s' failed")
3244 filename rem-dec)))))
3246 ;; Save exit.
3247 (delete-file tmpfile)))
3249 ;; That's not expected.
3251 (tramp-error
3252 v 'file-error
3253 (concat "Method `%s' should specify both encoding and "
3254 "decoding command or an rcp program")
3255 method))))
3257 ;; Make `last-coding-system-used' have the right value.
3258 (when coding-system-used
3259 (set 'last-coding-system-used coding-system-used))))
3261 (tramp-flush-file-property v (file-name-directory localname))
3262 (tramp-flush-file-property v localname)
3264 ;; We must protect `last-coding-system-used', now we have set it
3265 ;; to its correct value.
3266 (let (last-coding-system-used (need-chown t))
3267 ;; Set file modification time.
3268 (when (or (eq visit t) (stringp visit))
3269 (let ((file-attr (tramp-compat-file-attributes filename 'integer)))
3270 (set-visited-file-modtime
3271 ;; We must pass modtime explicitly, because filename can
3272 ;; be different from (buffer-file-name), f.e. if
3273 ;; `file-precious-flag' is set.
3274 (nth 5 file-attr))
3275 (when (and (= (nth 2 file-attr) uid)
3276 (= (nth 3 file-attr) gid))
3277 (setq need-chown nil))))
3279 ;; Set the ownership.
3280 (when need-chown
3281 (tramp-set-file-uid-gid filename uid gid))
3282 (when (or (eq visit t) (null visit) (stringp visit))
3283 (tramp-message v 0 "Wrote %s" filename))
3284 (run-hooks 'tramp-handle-write-region-hook)))))
3286 (defvar tramp-vc-registered-file-names nil
3287 "List used to collect file names, which are checked during `vc-registered'.")
3289 ;; VC backends check for the existence of various different special
3290 ;; files. This is very time consuming, because every single check
3291 ;; requires a remote command (the file cache must be invalidated).
3292 ;; Therefore, we apply a kind of optimization. We install the file
3293 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3294 ;; remembers all file names for which `file-exists-p' or
3295 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3296 ;; is performed. Afterwards, a script is applied for all collected
3297 ;; file names, using just one remote command. The result of this
3298 ;; script is used to fill the file cache with actual values. Now we
3299 ;; can reset the file name handlers, and we make a second run of
3300 ;; `vc-registered', which returns the expected result without sending
3301 ;; any other remote command.
3302 (defun tramp-sh-handle-vc-registered (file)
3303 "Like `vc-registered' for Tramp files."
3304 (tramp-compat-with-temp-message ""
3305 (with-parsed-tramp-file-name file nil
3306 (with-tramp-progress-reporter
3307 v 3 (format "Checking `vc-registered' for %s" file)
3309 (unless remote-file-name-inhibit-cache
3310 ;; There could be new files, created by the vc backend. We
3311 ;; cannot reuse the old cache entries, therefore.
3312 (let (tramp-vc-registered-file-names
3313 (remote-file-name-inhibit-cache (current-time))
3314 (file-name-handler-alist
3315 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3317 ;; Here we collect only file names, which need an operation.
3318 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3319 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3321 ;; Send just one command, in order to fill the cache.
3322 (when tramp-vc-registered-file-names
3323 (tramp-maybe-send-script
3325 (format tramp-vc-registered-read-file-names
3326 (tramp-get-file-exists-command v)
3327 (format "%s -r" (tramp-get-test-command v)))
3328 "tramp_vc_registered_read_file_names")
3330 (dolist
3331 (elt
3332 (ignore-errors
3333 ;; We cannot use `tramp-send-command-and-read',
3334 ;; because this does not cooperate well with
3335 ;; heredoc documents.
3336 (tramp-send-command
3338 (format
3339 "tramp_vc_registered_read_file_names <<'%s'\n%s\n%s\n"
3340 tramp-end-of-heredoc
3341 (mapconcat 'tramp-shell-quote-argument
3342 tramp-vc-registered-file-names
3343 "\n")
3344 tramp-end-of-heredoc))
3345 (with-current-buffer (tramp-get-connection-buffer v)
3346 ;; Read the expression.
3347 (goto-char (point-min))
3348 (read (current-buffer)))))
3350 (tramp-set-file-property
3351 v (car elt) (cadr elt) (cadr (cdr elt)))))))
3353 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3354 ;; calls shall be answered from the file cache. We unset
3355 ;; `process-file-side-effects' in order to keep the cache when
3356 ;; `process-file' calls appear.
3357 (let (process-file-side-effects)
3358 (ignore-errors
3359 (tramp-run-real-handler 'vc-registered (list file))))))))
3361 ;;;###tramp-autoload
3362 (defun tramp-sh-file-name-handler (operation &rest args)
3363 "Invoke remote-shell Tramp file name handler.
3364 Fall back to normal file name handler if no Tramp handler exists."
3365 (when (and tramp-locked (not tramp-locker))
3366 (setq tramp-locked nil)
3367 (tramp-error
3368 (car-safe tramp-current-connection) 'file-error
3369 "Forbidden reentrant call of Tramp"))
3370 (let ((tl tramp-locked))
3371 (setq tramp-locked t)
3372 (unwind-protect
3373 (let ((tramp-locker t))
3374 (save-match-data
3375 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3376 (if fn
3377 (apply (cdr fn) args)
3378 (tramp-run-real-handler operation args)))))
3379 (setq tramp-locked tl))))
3381 (defun tramp-vc-file-name-handler (operation &rest args)
3382 "Invoke special file name handler, which collects files to be handled."
3383 (save-match-data
3384 (let ((filename
3385 (tramp-replace-environment-variables
3386 (apply 'tramp-file-name-for-operation operation args)))
3387 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3388 (with-parsed-tramp-file-name filename nil
3389 (cond
3390 ;; That's what we want: file names, for which checks are
3391 ;; applied. We assume that VC uses only `file-exists-p' and
3392 ;; `file-readable-p' checks; otherwise we must extend the
3393 ;; list. We do not perform any action, but return nil, in
3394 ;; order to keep `vc-registered' running.
3395 ((and fn (memq operation '(file-exists-p file-readable-p)))
3396 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3397 nil)
3398 ;; `process-file' and `start-file-process' shall be ignored.
3399 ((and fn (eq operation 'process-file) 0))
3400 ((and fn (eq operation 'start-file-process) nil))
3401 ;; Tramp file name handlers like `expand-file-name'. They
3402 ;; must still work.
3403 (fn (save-match-data (apply (cdr fn) args)))
3404 ;; Default file name handlers, we don't care.
3405 (t (tramp-run-real-handler operation args)))))))
3407 (defun tramp-sh-handle-file-notify-add-watch (file-name flags _callback)
3408 "Like `file-notify-add-watch' for Tramp files."
3409 (setq file-name (expand-file-name file-name))
3410 (with-parsed-tramp-file-name file-name nil
3411 (let* ((default-directory (file-name-directory file-name))
3412 command events filter p sequence)
3413 (cond
3414 ;; gvfs-monitor-dir.
3415 ((setq command (tramp-get-remote-gvfs-monitor-dir v))
3416 (setq filter 'tramp-sh-file-gvfs-monitor-dir-process-filter
3417 sequence `(,command ,localname)))
3418 ;; inotifywait.
3419 ((setq command (tramp-get-remote-inotifywait v))
3420 (setq filter 'tramp-sh-file-inotifywait-process-filter
3421 events
3422 (cond
3423 ((and (memq 'change flags) (memq 'attribute-change flags))
3424 "create,modify,move,delete,attrib")
3425 ((memq 'change flags) "create,modify,move,delete")
3426 ((memq 'attribute-change flags) "attrib"))
3427 sequence `(,command "-mq" "-e" ,events ,localname)))
3428 ;; None.
3429 (t (tramp-error
3430 v 'file-notify-error
3431 "No file notification program found on %s"
3432 (file-remote-p file-name))))
3433 ;; Start process.
3434 (setq p (apply
3435 'start-file-process
3436 (file-name-nondirectory command)
3437 (generate-new-buffer
3438 (format " *%s*" (file-name-nondirectory command)))
3439 sequence))
3440 ;; Return the process object as watch-descriptor.
3441 (if (not (processp p))
3442 (tramp-error
3443 v 'file-notify-error
3444 "`%s' failed to start on remote host"
3445 (mapconcat 'identity sequence " "))
3446 (tramp-message v 6 "Run `%s', %S" (mapconcat 'identity sequence " ") p)
3447 (tramp-set-connection-property p "vector" v)
3448 (tramp-compat-set-process-query-on-exit-flag p nil)
3449 (set-process-filter p filter)
3450 p))))
3452 (defun tramp-sh-file-gvfs-monitor-dir-process-filter (proc string)
3453 "Read output from \"gvfs-monitor-dir\" and add corresponding file-notify events."
3454 (let ((remote-prefix
3455 (with-current-buffer (process-buffer proc)
3456 (file-remote-p default-directory)))
3457 (rest-string (tramp-compat-process-get proc 'rest-string)))
3458 (when rest-string
3459 (tramp-message proc 10 "Previous string:\n%s" rest-string))
3460 (tramp-message proc 6 "%S\n%s" proc string)
3461 (setq string (concat rest-string string)
3462 ;; Attribute change is returned in unused wording.
3463 string (tramp-compat-replace-regexp-in-string
3464 "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))
3466 (while (string-match
3467 (concat "^[\n\r]*"
3468 "Directory Monitor Event:[\n\r]+"
3469 "Child = \\([^\n\r]+\\)[\n\r]+"
3470 "\\(Other = \\([^\n\r]+\\)[\n\r]+\\)?"
3471 "Event = \\([^[:blank:]]+\\)[\n\r]+")
3472 string)
3473 (let ((object
3474 (list
3475 proc
3476 (intern-soft
3477 (tramp-compat-replace-regexp-in-string
3478 "_" "-" (downcase (match-string 4 string))))
3479 ;; File names are returned as absolute paths. We must
3480 ;; add the remote prefix.
3481 (concat remote-prefix (match-string 1 string))
3482 (when (match-string 3 string)
3483 (concat remote-prefix (match-string 3 string))))))
3484 (setq string (replace-match "" nil nil string))
3485 ;; Usually, we would add an Emacs event now. Unfortunately,
3486 ;; `unread-command-events' does not accept several events at
3487 ;; once. Therefore, we apply the callback directly.
3488 (tramp-compat-funcall 'file-notify-callback object)))
3490 ;; Save rest of the string.
3491 (when (zerop (length string)) (setq string nil))
3492 (when string (tramp-message proc 10 "Rest string:\n%s" string))
3493 (tramp-compat-process-put proc 'rest-string string)))
3495 (defun tramp-sh-file-inotifywait-process-filter (proc string)
3496 "Read output from \"inotifywait\" and add corresponding file-notify events."
3497 (tramp-message proc 6 "%S\n%s" proc string)
3498 (dolist (line (split-string string "[\n\r]+" 'omit-nulls))
3499 ;; Check, whether there is a problem.
3500 (unless
3501 (string-match
3502 (concat "^[^[:blank:]]+"
3503 "[[:blank:]]+\\([^[:blank:]]+\\)+"
3504 "\\([[:blank:]]+\\([^\n\r]+\\)\\)?")
3505 line)
3506 (tramp-error proc 'file-notify-error "%s" line))
3508 (let ((object
3509 (list
3510 proc
3511 (mapcar
3512 (lambda (x)
3513 (intern-soft
3514 (tramp-compat-replace-regexp-in-string "_" "-" (downcase x))))
3515 (split-string (match-string 1 line) "," 'omit-nulls))
3516 (match-string 3 line))))
3517 ;; Usually, we would add an Emacs event now. Unfortunately,
3518 ;; `unread-command-events' does not accept several events at
3519 ;; once. Therefore, we apply the callback directly.
3520 (tramp-compat-funcall 'file-notify-callback object))))
3522 ;;; Internal Functions:
3524 (defun tramp-maybe-send-script (vec script name)
3525 "Define in remote shell function NAME implemented as SCRIPT.
3526 Only send the definition if it has not already been done."
3527 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3528 ;; might be nil.
3529 (let ((scripts (tramp-get-connection-property
3530 (tramp-get-connection-process vec) "scripts" nil)))
3531 (unless (member name scripts)
3532 (with-tramp-progress-reporter vec 5 (format "Sending script `%s'" name)
3533 ;; The script could contain a call of Perl. This is masked with `%s'.
3534 (when (and (string-match "%s" script)
3535 (not (tramp-get-remote-perl vec)))
3536 (tramp-error vec 'file-error "No Perl available on remote host"))
3537 (tramp-barf-unless-okay
3539 (format "%s () {\n%s\n}" name
3540 (format script (tramp-get-remote-perl vec)))
3541 "Script %s sending failed" name)
3542 (tramp-set-connection-property
3543 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3545 (defun tramp-set-auto-save ()
3546 (when (and ;; ange-ftp has its own auto-save mechanism
3547 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
3548 'tramp-sh-file-name-handler)
3549 auto-save-default)
3550 (auto-save-mode 1)))
3551 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
3552 (add-hook 'tramp-unload-hook
3553 (lambda ()
3554 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
3556 (defun tramp-run-test (switch filename)
3557 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3558 Returns the exit code of the `test' program."
3559 (with-parsed-tramp-file-name filename nil
3560 (tramp-send-command-and-check
3562 (format
3563 "%s %s %s"
3564 (tramp-get-test-command v)
3565 switch
3566 (tramp-shell-quote-argument localname)))))
3568 (defun tramp-run-test2 (format-string file1 file2)
3569 "Run `test'-like program on the remote system, given FILE1, FILE2.
3570 FORMAT-STRING contains the program name, switches, and place holders.
3571 Returns the exit code of the `test' program. Barfs if the methods,
3572 hosts, or files, disagree."
3573 (unless (tramp-equal-remote file1 file2)
3574 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3575 (tramp-error
3576 v 'file-error
3577 "tramp-run-test2 only implemented for same method, user, host")))
3578 (with-parsed-tramp-file-name file1 v1
3579 (with-parsed-tramp-file-name file1 v2
3580 (tramp-send-command-and-check
3582 (format format-string
3583 (tramp-shell-quote-argument v1-localname)
3584 (tramp-shell-quote-argument v2-localname))))))
3586 (defun tramp-find-executable
3587 (vec progname dirlist &optional ignore-tilde ignore-path)
3588 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3589 First arg VEC specifies the connection, PROGNAME is the program
3590 to search for, and DIRLIST gives the list of directories to
3591 search. If IGNORE-TILDE is non-nil, directory names starting
3592 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3593 only in DIRLIST.
3595 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3597 This function expects to be in the right *tramp* buffer."
3598 (with-current-buffer (tramp-get-connection-buffer vec)
3599 (let (result)
3600 ;; Check whether the executable is in $PATH. "which(1)" does not
3601 ;; report always a correct error code; therefore we check the
3602 ;; number of words it returns.
3603 (unless ignore-path
3604 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3605 (goto-char (point-min))
3606 (if (looking-at "^\\s-*1$")
3607 (setq result (concat "\\" progname))))
3608 (unless result
3609 (when ignore-tilde
3610 ;; Remove all ~/foo directories from dirlist. In XEmacs,
3611 ;; `remove' is in CL, and we want to avoid CL dependencies.
3612 (let (newdl d)
3613 (while dirlist
3614 (setq d (car dirlist))
3615 (setq dirlist (cdr dirlist))
3616 (unless (char-equal ?~ (aref d 0))
3617 (setq newdl (cons d newdl))))
3618 (setq dirlist (nreverse newdl))))
3619 (tramp-send-command
3621 (format (concat "while read d; "
3622 "do if test -x $d/%s -a -f $d/%s; "
3623 "then echo tramp_executable $d/%s; "
3624 "break; fi; done <<'%s'\n"
3625 "%s\n%s")
3626 progname progname progname
3627 tramp-end-of-heredoc
3628 (mapconcat 'identity dirlist "\n")
3629 tramp-end-of-heredoc))
3630 (goto-char (point-max))
3631 (when (search-backward "tramp_executable " nil t)
3632 (skip-chars-forward "^ ")
3633 (skip-chars-forward " ")
3634 (setq result (buffer-substring (point) (point-at-eol)))))
3635 result)))
3637 (defun tramp-set-remote-path (vec)
3638 "Sets the remote environment PATH to existing directories.
3639 I.e., for each directory in `tramp-remote-path', it is tested
3640 whether it exists and if so, it is added to the environment
3641 variable PATH."
3642 (tramp-message vec 5 "Setting $PATH environment variable")
3643 (tramp-send-command
3644 vec (format "PATH=%s; export PATH"
3645 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3647 ;; ------------------------------------------------------------
3648 ;; -- Communication with external shell --
3649 ;; ------------------------------------------------------------
3651 (defun tramp-find-file-exists-command (vec)
3652 "Find a command on the remote host for checking if a file exists.
3653 Here, we are looking for a command which has zero exit status if the
3654 file exists and nonzero exit status otherwise."
3655 (let ((existing "/")
3656 (nonexistent
3657 (tramp-shell-quote-argument "/ this file does not exist "))
3658 result)
3659 ;; The algorithm is as follows: we try a list of several commands.
3660 ;; For each command, we first run `$cmd /' -- this should return
3661 ;; true, as the root directory always exists. And then we run
3662 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3663 ;; does not exist. This should return false. We use the first
3664 ;; command we find that seems to work.
3665 ;; The list of commands to try is as follows:
3666 ;; `ls -d' This works on most systems, but NetBSD 1.4
3667 ;; has a bug: `ls' always returns zero exit
3668 ;; status, even for files which don't exist.
3669 ;; `test -e' Some Bourne shells have a `test' builtin
3670 ;; which does not know the `-e' option.
3671 ;; `/bin/test -e' For those, the `test' binary on disk normally
3672 ;; provides the option. Alas, the binary
3673 ;; is sometimes `/bin/test' and sometimes it's
3674 ;; `/usr/bin/test'.
3675 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3676 (unless (or
3677 (ignore-errors
3678 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3679 (tramp-send-command-and-check
3680 vec (format "%s %s" result existing))
3681 (not (tramp-send-command-and-check
3682 vec (format "%s %s" result nonexistent)))))
3683 (ignore-errors
3684 (and (setq result "/bin/test -e")
3685 (tramp-send-command-and-check
3686 vec (format "%s %s" result existing))
3687 (not (tramp-send-command-and-check
3688 vec (format "%s %s" result nonexistent)))))
3689 (ignore-errors
3690 (and (setq result "/usr/bin/test -e")
3691 (tramp-send-command-and-check
3692 vec (format "%s %s" result existing))
3693 (not (tramp-send-command-and-check
3694 vec (format "%s %s" result nonexistent)))))
3695 (ignore-errors
3696 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3697 (tramp-send-command-and-check
3698 vec (format "%s %s" result existing))
3699 (not (tramp-send-command-and-check
3700 vec (format "%s %s" result nonexistent))))))
3701 (tramp-error
3702 vec 'file-error "Couldn't find command to check if file exists"))
3703 result))
3705 (defun tramp-open-shell (vec shell)
3706 "Opens shell SHELL."
3707 (with-tramp-progress-reporter
3708 vec 5 (format "Opening remote shell `%s'" shell)
3709 ;; Find arguments for this shell.
3710 (let ((tramp-end-of-output tramp-initial-end-of-output)
3711 (alist tramp-sh-extra-args)
3712 item extra-args)
3713 (while (and alist (null extra-args))
3714 (setq item (pop alist))
3715 (when (string-match (car item) shell)
3716 (setq extra-args (cdr item))))
3717 (tramp-send-command
3718 vec (format
3719 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3720 (tramp-shell-quote-argument tramp-end-of-output)
3721 shell (or extra-args ""))
3723 (tramp-set-connection-property
3724 (tramp-get-connection-process vec) "remote-shell" shell)
3725 ;; Setting prompts.
3726 (tramp-send-command
3727 vec (format "PS1=%s" (tramp-shell-quote-argument tramp-end-of-output)) t)
3728 (tramp-send-command vec "PS2=''" t)
3729 (tramp-send-command vec "PS3=''" t)
3730 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
3732 (defun tramp-find-shell (vec)
3733 "Opens a shell on the remote host which groks tilde expansion."
3734 (with-current-buffer (tramp-get-buffer vec)
3735 (let ((default-shell
3737 (tramp-get-connection-property
3738 (tramp-get-connection-process vec) "remote-shell" nil)
3739 (tramp-get-method-parameter
3740 (tramp-file-name-method vec) 'tramp-remote-shell)))
3741 shell)
3742 (setq shell
3743 (with-tramp-connection-property vec "remote-shell"
3744 ;; CCC: "root" does not exist always, see QNAP 459.
3745 ;; Which check could we apply instead?
3746 (tramp-send-command vec "echo ~root" t)
3747 (if (or (string-match "^~root$" (buffer-string))
3748 ;; The default shell (ksh93) of OpenSolaris and
3749 ;; Solaris is buggy. We've got reports for
3750 ;; "SunOS 5.10" and "SunOS 5.11" so far.
3751 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3752 (tramp-get-connection-property
3753 vec "uname" "")))
3755 (or (tramp-find-executable
3756 vec "bash" (tramp-get-remote-path vec) t t)
3757 (tramp-find-executable
3758 vec "ksh" (tramp-get-remote-path vec) t t)
3759 ;; Maybe it works at least for some other commands.
3760 (prog1
3761 default-shell
3762 (tramp-message
3763 vec 2
3764 (concat
3765 "Couldn't find a remote shell which groks tilde "
3766 "expansion, using `%s'")
3767 default-shell)))
3769 default-shell)))
3771 ;; Open a new shell if needed.
3772 (unless (string-equal shell default-shell)
3773 (tramp-message
3774 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
3775 (tramp-open-shell vec shell)))))
3777 ;; Utility functions.
3779 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
3780 "Wait for shell prompt and barf if none appears.
3781 Looks at process PROC to see if a shell prompt appears in TIMEOUT
3782 seconds. If not, it produces an error message with the given ERROR-ARGS."
3783 (let ((vec (tramp-get-connection-property proc "vector" nil)))
3784 (condition-case nil
3785 (tramp-wait-for-regexp
3786 proc timeout
3787 (format
3788 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
3789 (error
3790 (delete-process proc)
3791 (apply 'tramp-error-with-buffer
3792 (tramp-get-connection-buffer vec) vec 'file-error error-args)))))
3794 (defun tramp-open-connection-setup-interactive-shell (proc vec)
3795 "Set up an interactive shell.
3796 Mainly sets the prompt and the echo correctly. PROC is the shell
3797 process to set up. VEC specifies the connection."
3798 (let ((tramp-end-of-output tramp-initial-end-of-output))
3799 ;; It is useful to set the prompt in the following command because
3800 ;; some people have a setting for $PS1 which /bin/sh doesn't know
3801 ;; about and thus /bin/sh will display a strange prompt. For
3802 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
3803 ;; display the current working directory but /bin/sh will display
3804 ;; a dollar sign. The following command line sets $PS1 to a sane
3805 ;; value, and works under Bourne-ish shells as well as csh-like
3806 ;; shells. Daniel Pittman reports that the unusual positioning of
3807 ;; the single quotes makes it work under `rc', too. We also unset
3808 ;; the variable $ENV because that is read by some sh
3809 ;; implementations (eg, bash when called as sh) on startup; this
3810 ;; way, we avoid the startup file clobbering $PS1. $PROMPT_COMMAND
3811 ;; is another way to set the prompt in /bin/bash, it must be
3812 ;; discarded as well.
3813 (tramp-open-shell
3815 (or (tramp-get-connection-property vec "remote-shell" nil)
3816 (tramp-get-method-parameter
3817 (tramp-file-name-method vec) 'tramp-remote-shell)))
3819 ;; Disable echo.
3820 (tramp-message vec 5 "Setting up remote shell environment")
3821 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
3822 ;; Check whether the echo has really been disabled. Some
3823 ;; implementations, like busybox of embedded GNU/Linux, don't
3824 ;; support disabling.
3825 (tramp-send-command vec "echo foo" t)
3826 (with-current-buffer (process-buffer proc)
3827 (goto-char (point-min))
3828 (when (looking-at "echo foo")
3829 (tramp-set-connection-property proc "remote-echo" t)
3830 (tramp-message vec 5 "Remote echo still on. Ok.")
3831 ;; Make sure backspaces and their echo are enabled and no line
3832 ;; width magic interferes with them.
3833 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
3835 (tramp-message vec 5 "Setting shell prompt")
3836 (tramp-send-command
3837 vec (format "PS1=%s" (tramp-shell-quote-argument tramp-end-of-output)) t)
3838 (tramp-send-command vec "PS2=''" t)
3839 (tramp-send-command vec "PS3=''" t)
3840 (tramp-send-command vec "PROMPT_COMMAND=''" t)
3842 ;; Try to set up the coding system correctly.
3843 ;; CCC this can't be the right way to do it. Hm.
3844 (tramp-message vec 5 "Determining coding system")
3845 (tramp-send-command vec "echo foo ; echo bar" t)
3846 (with-current-buffer (process-buffer proc)
3847 (goto-char (point-min))
3848 (if (featurep 'mule)
3849 ;; Use MULE to select the right EOL convention for communicating
3850 ;; with the process.
3851 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
3852 (cons 'undecided 'undecided)))
3853 cs-decode cs-encode)
3854 (when (symbolp cs) (setq cs (cons cs cs)))
3855 (setq cs-decode (car cs))
3856 (setq cs-encode (cdr cs))
3857 (unless cs-decode (setq cs-decode 'undecided))
3858 (unless cs-encode (setq cs-encode 'undecided))
3859 (setq cs-encode (tramp-compat-coding-system-change-eol-conversion
3860 cs-encode 'unix))
3861 (when (search-forward "\r" nil t)
3862 (setq cs-decode (tramp-compat-coding-system-change-eol-conversion
3863 cs-decode 'dos)))
3864 (tramp-compat-funcall
3865 'set-buffer-process-coding-system cs-decode cs-encode)
3866 (tramp-message
3867 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
3868 ;; Look for ^M and do something useful if found.
3869 (when (search-forward "\r" nil t)
3870 ;; We have found a ^M but cannot frob the process coding system
3871 ;; because we're running on a non-MULE Emacs. Let's try
3872 ;; stty, instead.
3873 (tramp-send-command vec "stty -onlcr" t))))
3875 (tramp-send-command vec "set +o vi +o emacs" t)
3877 ;; Check whether the output of "uname -sr" has been changed. If
3878 ;; yes, this is a strong indication that we must expire all
3879 ;; connection properties. We start again with
3880 ;; `tramp-maybe-open-connection', it will be caught there.
3881 (tramp-message vec 5 "Checking system information")
3882 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
3883 (new-uname
3884 (tramp-set-connection-property
3885 vec "uname"
3886 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
3887 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
3888 (tramp-message
3889 vec 3
3890 "Connection reset, because remote host changed from `%s' to `%s'"
3891 old-uname new-uname)
3892 ;; We want to keep the password.
3893 (tramp-cleanup-connection vec t t)
3894 (throw 'uname-changed (tramp-maybe-open-connection vec))))
3896 ;; Check whether the remote host suffers from buggy
3897 ;; `send-process-string'. This is known for FreeBSD (see comment in
3898 ;; `send_process', file process.c). I've tested sending 624 bytes
3899 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
3900 ;; this host type is detected locally. It cannot handle remote
3901 ;; hosts, though.
3902 (with-tramp-connection-property proc "chunksize"
3903 (cond
3904 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
3905 tramp-chunksize)
3907 (tramp-message
3908 vec 5 "Checking remote host type for `send-process-string' bug")
3909 (if (string-match
3910 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
3911 500 0))))
3913 ;; Set remote PATH variable.
3914 (tramp-set-remote-path vec)
3916 ;; Search for a good shell before searching for a command which
3917 ;; checks if a file exists. This is done because Tramp wants to use
3918 ;; "test foo; echo $?" to check if various conditions hold, and
3919 ;; there are buggy /bin/sh implementations which don't execute the
3920 ;; "echo $?" part if the "test" part has an error. In particular,
3921 ;; the OpenSolaris /bin/sh is a problem. There are also other
3922 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
3923 ;; in function declarations, or changing HISTFILE in place.
3924 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
3925 ;; detected.
3926 (tramp-find-shell vec)
3928 ;; Disable unexpected output.
3929 (tramp-send-command vec "mesg n; biff n" t)
3931 ;; IRIX64 bash expands "!" even when in single quotes. This
3932 ;; destroys our shell functions, we must disable it. See
3933 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
3934 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
3935 (tramp-send-command vec "set +H" t))
3937 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
3938 (when (string-match "BSD\\|Darwin"
3939 (tramp-get-connection-property vec "uname" ""))
3940 (tramp-send-command vec "stty -oxtabs" t))
3942 ;; Set `remote-tty' process property.
3943 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
3944 (unless (zerop (length tty))
3945 (tramp-compat-process-put proc 'remote-tty tty)))
3947 ;; Dump stty settings in the traces.
3948 (when (>= tramp-verbose 9)
3949 (tramp-send-command vec "stty -a" t))
3951 ;; Set the environment.
3952 (tramp-message vec 5 "Setting default environment")
3954 (let ((env (append (when (tramp-get-remote-locale vec) ; Discard `(nil)'.
3955 `(,(tramp-get-remote-locale vec)))
3956 (copy-sequence tramp-remote-process-environment)))
3957 unset item)
3958 (while env
3959 (setq item (tramp-compat-split-string (car env) "="))
3960 (setcdr item (mapconcat 'identity (cdr item) "="))
3961 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
3962 (tramp-send-command
3963 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
3964 (push (car item) unset))
3965 (setq env (cdr env)))
3966 (when unset
3967 (tramp-send-command
3968 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
3970 ;; Old text from documentation of tramp-methods:
3971 ;; Using a uuencode/uudecode inline method is discouraged, please use one
3972 ;; of the base64 methods instead since base64 encoding is much more
3973 ;; reliable and the commands are more standardized between the different
3974 ;; Unix versions. But if you can't use base64 for some reason, please
3975 ;; note that the default uudecode command does not work well for some
3976 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
3977 ;; the following command for uudecode:
3979 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
3981 ;; For Irix, no solution is known yet.
3983 (autoload 'uudecode-decode-region "uudecode")
3985 (defconst tramp-local-coding-commands
3986 `((b64 base64-encode-region base64-decode-region)
3987 (uu tramp-uuencode-region uudecode-decode-region)
3988 (pack ,(format tramp-perl-pack "perl") ,(format tramp-perl-unpack "perl")))
3989 "List of local coding commands for inline transfer.
3990 Each item is a list that looks like this:
3992 \(FORMAT ENCODING DECODING\)
3994 FORMAT is symbol describing the encoding/decoding format. It can be
3995 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
3997 ENCODING and DECODING can be strings, giving commands, or symbols,
3998 giving functions. If they are strings, then they can contain
3999 the \"%s\" format specifier. If that specifier is present, the input
4000 filename will be put into the command line at that spot. If the
4001 specifier is not present, the input should be read from standard
4002 input.
4004 If they are functions, they will be called with two arguments, start
4005 and end of region, and are expected to replace the region contents
4006 with the encoded or decoded results, respectively.")
4008 (defconst tramp-remote-coding-commands
4009 '((b64 "base64" "base64 -d -i")
4010 ;; "-i" is more robust with older base64 from GNU coreutils.
4011 ;; However, I don't know whether all base64 versions do supports
4012 ;; this option.
4013 (b64 "base64" "base64 -d")
4014 (b64 "mimencode -b" "mimencode -u -b")
4015 (b64 "mmencode -b" "mmencode -u -b")
4016 (b64 "recode data..base64" "recode base64..data")
4017 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
4018 (b64 tramp-perl-encode tramp-perl-decode)
4019 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
4020 (uu "uuencode xxx" "uudecode -o -")
4021 (uu "uuencode xxx" "uudecode -p")
4022 (uu "uuencode xxx" tramp-uudecode)
4023 (pack tramp-perl-pack tramp-perl-unpack))
4024 "List of remote coding commands for inline transfer.
4025 Each item is a list that looks like this:
4027 \(FORMAT ENCODING DECODING [TEST]\)
4029 FORMAT is symbol describing the encoding/decoding format. It can be
4030 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4032 ENCODING and DECODING can be strings, giving commands, or symbols,
4033 giving variables. If they are strings, then they can contain
4034 the \"%s\" format specifier. If that specifier is present, the input
4035 filename will be put into the command line at that spot. If the
4036 specifier is not present, the input should be read from standard
4037 input.
4039 If they are variables, this variable is a string containing a Perl
4040 implementation for this functionality. This Perl program will be transferred
4041 to the remote host, and it is available as shell function with the same name.
4043 The optional TEST command can be used for further tests, whether
4044 ENCODING and DECODING are applicable.")
4046 (defun tramp-find-inline-encoding (vec)
4047 "Find an inline transfer encoding that works.
4048 Goes through the list `tramp-local-coding-commands' and
4049 `tramp-remote-coding-commands'."
4050 (save-excursion
4051 (let ((local-commands tramp-local-coding-commands)
4052 (magic "xyzzy")
4053 (p (tramp-get-connection-process vec))
4054 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4055 (while (and local-commands (not found))
4056 (setq litem (pop local-commands))
4057 (catch 'wont-work-local
4058 (let ((format (nth 0 litem))
4059 (remote-commands tramp-remote-coding-commands))
4060 (setq loc-enc (nth 1 litem))
4061 (setq loc-dec (nth 2 litem))
4062 ;; If the local encoder or decoder is a string, the
4063 ;; corresponding command has to work locally.
4064 (if (not (stringp loc-enc))
4065 (tramp-message
4066 vec 5 "Checking local encoding function `%s'" loc-enc)
4067 (tramp-message
4068 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4069 (unless (zerop (tramp-call-local-coding-command
4070 loc-enc nil nil))
4071 (throw 'wont-work-local nil)))
4072 (if (not (stringp loc-dec))
4073 (tramp-message
4074 vec 5 "Checking local decoding function `%s'" loc-dec)
4075 (tramp-message
4076 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4077 (unless (zerop (tramp-call-local-coding-command
4078 loc-dec nil nil))
4079 (throw 'wont-work-local nil)))
4080 ;; Search for remote coding commands with the same format
4081 (while (and remote-commands (not found))
4082 (setq ritem (pop remote-commands))
4083 (catch 'wont-work-remote
4084 (when (equal format (nth 0 ritem))
4085 (setq rem-enc (nth 1 ritem))
4086 (setq rem-dec (nth 2 ritem))
4087 (setq rem-test (nth 3 ritem))
4088 ;; Check the remote test command if exists.
4089 (when (stringp rem-test)
4090 (tramp-message
4091 vec 5 "Checking remote test command `%s'" rem-test)
4092 (unless (tramp-send-command-and-check vec rem-test t)
4093 (throw 'wont-work-remote nil)))
4094 ;; Check if remote perl exists when necessary.
4095 (when (and (not (stringp rem-enc))
4096 (not (tramp-get-remote-perl vec)))
4097 (throw 'wont-work-remote nil))
4098 ;; Check if remote encoding and decoding commands can be
4099 ;; called remotely with null input and output. This makes
4100 ;; sure there are no syntax errors and the command is really
4101 ;; found. Note that we do not redirect stdout to /dev/null,
4102 ;; for two reasons: when checking the decoding command, we
4103 ;; actually check the output it gives. And also, when
4104 ;; redirecting "mimencode" output to /dev/null, then as root
4105 ;; it might change the permissions of /dev/null!
4106 (when (not (stringp rem-enc))
4107 (let ((name (symbol-name rem-enc)))
4108 (while (string-match (regexp-quote "-") name)
4109 (setq name (replace-match "_" nil t name)))
4110 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4111 (setq rem-enc name)))
4112 (tramp-message
4113 vec 5
4114 "Checking remote encoding command `%s' for sanity" rem-enc)
4115 (unless (tramp-send-command-and-check
4116 vec (format "%s </dev/null" rem-enc) t)
4117 (throw 'wont-work-remote nil))
4119 (when (not (stringp rem-dec))
4120 (let ((name (symbol-name rem-dec)))
4121 (while (string-match (regexp-quote "-") name)
4122 (setq name (replace-match "_" nil t name)))
4123 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
4124 (setq rem-dec name)))
4125 (tramp-message
4126 vec 5
4127 "Checking remote decoding command `%s' for sanity" rem-dec)
4128 (unless (tramp-send-command-and-check
4130 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4132 (throw 'wont-work-remote nil))
4134 (with-current-buffer (tramp-get-buffer vec)
4135 (goto-char (point-min))
4136 (unless (looking-at (regexp-quote magic))
4137 (throw 'wont-work-remote nil)))
4139 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4140 (setq rem-enc (nth 1 ritem))
4141 (setq rem-dec (nth 2 ritem))
4142 (setq found t)))))))
4144 ;; Did we find something?
4145 (unless found
4146 (tramp-error
4147 vec 'file-error "Couldn't find an inline transfer encoding"))
4149 ;; Set connection properties. Since the commands are risky (due
4150 ;; to output direction), we cache them in the process cache.
4151 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4152 (tramp-set-connection-property p "local-encoding" loc-enc)
4153 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4154 (tramp-set-connection-property p "local-decoding" loc-dec)
4155 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4156 (tramp-set-connection-property p "remote-encoding" rem-enc)
4157 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4158 (tramp-set-connection-property p "remote-decoding" rem-dec))))
4160 (defun tramp-call-local-coding-command (cmd input output)
4161 "Call the local encoding or decoding command.
4162 If CMD contains \"%s\", provide input file INPUT there in command.
4163 Otherwise, INPUT is passed via standard input.
4164 INPUT can also be nil which means `/dev/null'.
4165 OUTPUT can be a string (which specifies a filename), or t (which
4166 means standard output and thus the current buffer), or nil (which
4167 means discard it)."
4168 (tramp-call-process
4169 tramp-encoding-shell
4170 (when (and input (not (string-match "%s" cmd))) input)
4171 (if (eq output t) t nil)
4173 tramp-encoding-command-switch
4174 (concat
4175 (if (string-match "%s" cmd) (format cmd input) cmd)
4176 (if (stringp output) (concat " >" output) ""))))
4178 (defconst tramp-inline-compress-commands
4179 '(("gzip" "gzip -d")
4180 ("bzip2" "bzip2 -d")
4181 ("xz" "xz -d")
4182 ("compress" "compress -d"))
4183 "List of compress and decompress commands for inline transfer.
4184 Each item is a list that looks like this:
4186 \(COMPRESS DECOMPRESS\)
4188 COMPRESS or DECOMPRESS are strings with the respective commands.")
4190 (defun tramp-find-inline-compress (vec)
4191 "Find an inline transfer compress command that works.
4192 Goes through the list `tramp-inline-compress-commands'."
4193 (save-excursion
4194 (let ((commands tramp-inline-compress-commands)
4195 (magic "xyzzy")
4196 (p (tramp-get-connection-process vec))
4197 item compress decompress found)
4198 (while (and commands (not found))
4199 (catch 'next
4200 (setq item (pop commands)
4201 compress (nth 0 item)
4202 decompress (nth 1 item))
4203 (tramp-message
4204 vec 5
4205 "Checking local compress commands `%s', `%s' for sanity"
4206 compress decompress)
4207 (unless
4208 (zerop
4209 (tramp-call-local-coding-command
4210 (format
4211 ;; Windows shells need the program file name after
4212 ;; the pipe symbol be quoted if they use forward
4213 ;; slashes as directory separators.
4214 (if (memq system-type '(windows-nt))
4215 "echo %s | \"%s\" | \"%s\""
4216 "echo %s | %s | %s")
4217 magic compress decompress) nil nil))
4218 (throw 'next nil))
4219 (tramp-message
4220 vec 5
4221 "Checking remote compress commands `%s', `%s' for sanity"
4222 compress decompress)
4223 (unless (tramp-send-command-and-check
4224 vec (format "echo %s | %s | %s" magic compress decompress) t)
4225 (throw 'next nil))
4226 (setq found t)))
4228 ;; Did we find something?
4229 (if found
4230 (progn
4231 ;; Set connection properties. Since the commands are
4232 ;; risky (due to output direction), we cache them in the
4233 ;; process cache.
4234 (tramp-message
4235 vec 5 "Using inline transfer compress command `%s'" compress)
4236 (tramp-set-connection-property p "inline-compress" compress)
4237 (tramp-message
4238 vec 5 "Using inline transfer decompress command `%s'" decompress)
4239 (tramp-set-connection-property p "inline-decompress" decompress))
4241 (tramp-set-connection-property p "inline-compress" nil)
4242 (tramp-set-connection-property p "inline-decompress" nil)
4243 (tramp-message
4244 vec 2 "Couldn't find an inline transfer compress command")))))
4246 (defun tramp-compute-multi-hops (vec)
4247 "Expands VEC according to `tramp-default-proxies-alist'.
4248 Gateway hops are already opened."
4249 (let ((target-alist `(,vec))
4250 (hops (or (tramp-file-name-hop vec) ""))
4251 (item vec)
4252 choices proxy)
4254 ;; Ad-hoc proxy definitions.
4255 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4256 (let ((user (tramp-file-name-user item))
4257 (host (tramp-file-name-host item))
4258 (proxy (concat
4259 tramp-prefix-format proxy tramp-postfix-host-format)))
4260 (tramp-message
4261 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4262 (and (stringp host) (regexp-quote host))
4263 (and (stringp user) (regexp-quote user))
4264 proxy)
4265 ;; Add the hop.
4266 (add-to-list
4267 'tramp-default-proxies-alist
4268 (list (and (stringp host) (regexp-quote host))
4269 (and (stringp user) (regexp-quote user))
4270 proxy))
4271 (setq item (tramp-dissect-file-name proxy))))
4272 ;; Save the new value.
4273 (when (and hops tramp-save-ad-hoc-proxies)
4274 (customize-save-variable
4275 'tramp-default-proxies-alist tramp-default-proxies-alist))
4277 ;; Look for proxy hosts to be passed.
4278 (setq choices tramp-default-proxies-alist)
4279 (while choices
4280 (setq item (pop choices)
4281 proxy (eval (nth 2 item)))
4282 (when (and
4283 ;; Host.
4284 (string-match (or (eval (nth 0 item)) "")
4285 (or (tramp-file-name-host (car target-alist)) ""))
4286 ;; User.
4287 (string-match (or (eval (nth 1 item)) "")
4288 (or (tramp-file-name-user (car target-alist)) "")))
4289 (if (null proxy)
4290 ;; No more hops needed.
4291 (setq choices nil)
4292 ;; Replace placeholders.
4293 (setq proxy
4294 (format-spec
4295 proxy
4296 (format-spec-make
4297 ?u (or (tramp-file-name-user (car target-alist)) "")
4298 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4299 (with-parsed-tramp-file-name proxy l
4300 ;; Add the hop.
4301 (push l target-alist)
4302 ;; Start next search.
4303 (setq choices tramp-default-proxies-alist)))))
4305 ;; Handle gateways.
4306 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4307 (string-match
4308 (format
4309 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4310 (tramp-file-name-method (car target-alist))))
4311 (let ((gw (pop target-alist))
4312 (hop (pop target-alist)))
4313 ;; Is the method prepared for gateways?
4314 (unless (tramp-file-name-port hop)
4315 (tramp-error
4316 vec 'file-error
4317 "Connection `%s' is not supported for gateway access." hop))
4318 ;; Open the gateway connection.
4319 (push
4320 (vector
4321 (tramp-file-name-method hop) (tramp-file-name-user hop)
4322 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil nil)
4323 target-alist)
4324 ;; For the password prompt, we need the correct values.
4325 ;; Therefore, we must remember the gateway vector. But we
4326 ;; cannot do it as connection property, because it shouldn't
4327 ;; be persistent. And we have no started process yet either.
4328 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
4330 ;; Foreign and out-of-band methods are not supported for multi-hops.
4331 (when (cdr target-alist)
4332 (setq choices target-alist)
4333 (while choices
4334 (setq item (pop choices))
4335 (when
4337 (not
4338 (tramp-get-method-parameter
4339 (tramp-file-name-method item) 'tramp-login-program))
4340 (tramp-get-method-parameter
4341 (tramp-file-name-method item) 'tramp-copy-program))
4342 (tramp-error
4343 vec 'file-error
4344 "Method `%s' is not supported for multi-hops."
4345 (tramp-file-name-method item)))))
4347 ;; In case the host name is not used for the remote shell
4348 ;; command, the user could be misguided by applying a random
4349 ;; hostname.
4350 (let* ((v (car target-alist))
4351 (method (tramp-file-name-method v))
4352 (host (tramp-file-name-host v)))
4353 (unless
4355 ;; There are multi-hops.
4356 (cdr target-alist)
4357 ;; The host name is used for the remote shell command.
4358 (member
4359 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
4360 ;; The host is local. We cannot use `tramp-local-host-p'
4361 ;; here, because it opens a connection as well.
4362 (string-match tramp-local-host-regexp host))
4363 (tramp-error
4364 v 'file-error
4365 "Host `%s' looks like a remote host, `%s' can only use the local host"
4366 host method)))
4368 ;; Result.
4369 target-alist))
4371 (defun tramp-maybe-open-connection (vec)
4372 "Maybe open a connection VEC.
4373 Does not do anything if a connection is already open, but re-opens the
4374 connection if a previous connection has died for some reason."
4375 (tramp-check-proper-method-and-host vec)
4377 (let ((p (tramp-get-connection-process vec))
4378 (process-name (tramp-get-connection-property vec "process-name" nil))
4379 (process-environment (copy-sequence process-environment))
4380 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4382 ;; If Tramp opens the same connection within a short time frame,
4383 ;; there is a problem. We shall signal this.
4384 (unless (or (and p (processp p) (memq (process-status p) '(run open)))
4385 (not (equal (butlast (append vec nil) 2)
4386 (car tramp-current-connection)))
4387 (> (tramp-time-diff
4388 (current-time) (cdr tramp-current-connection))
4389 (or tramp-connection-min-time-diff 0)))
4390 (throw 'suppress 'suppress))
4392 ;; If too much time has passed since last command was sent, look
4393 ;; whether process is still alive. If it isn't, kill it. When
4394 ;; using ssh, it can sometimes happen that the remote end has hung
4395 ;; up but the local ssh client doesn't recognize this until it
4396 ;; tries to send some data to the remote end. So that's why we
4397 ;; try to send a command from time to time, then look again
4398 ;; whether the process is really alive.
4399 (condition-case nil
4400 (when (and (> (tramp-time-diff
4401 (current-time)
4402 (tramp-get-connection-property
4403 p "last-cmd-time" '(0 0 0)))
4405 p (processp p) (memq (process-status p) '(run open)))
4406 (tramp-send-command vec "echo are you awake" t t)
4407 (unless (and (memq (process-status p) '(run open))
4408 (tramp-wait-for-output p 10))
4409 ;; The error will be caught locally.
4410 (tramp-error vec 'file-error "Awake did fail")))
4411 (file-error
4412 (tramp-cleanup-connection vec t)
4413 (setq p nil)))
4415 ;; New connection must be opened.
4416 (condition-case err
4417 (unless (and p (processp p) (memq (process-status p) '(run open)))
4419 ;; If `non-essential' is non-nil, don't reopen a new connection.
4420 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4421 (throw 'non-essential 'non-essential))
4423 (with-tramp-progress-reporter
4424 vec 3
4425 (if (zerop (length (tramp-file-name-user vec)))
4426 (format "Opening connection for %s using %s"
4427 (tramp-file-name-host vec)
4428 (tramp-file-name-method vec))
4429 (format "Opening connection for %s@%s using %s"
4430 (tramp-file-name-user vec)
4431 (tramp-file-name-host vec)
4432 (tramp-file-name-method vec)))
4434 (catch 'uname-changed
4435 ;; Start new process.
4436 (when (and p (processp p))
4437 (delete-process p))
4438 (setenv "TERM" tramp-terminal-type)
4439 (setenv "LC_ALL" "en_US.utf8")
4440 (setenv "PROMPT_COMMAND")
4441 (setenv "PS1" tramp-initial-end-of-output)
4442 (let* ((target-alist (tramp-compute-multi-hops vec))
4443 ;; We will apply `tramp-ssh-controlmaster-options'
4444 ;; only for the first hop.
4445 (options (if tramp-use-ssh-controlmaster-options
4446 tramp-ssh-controlmaster-options ""))
4447 (process-connection-type tramp-process-connection-type)
4448 (process-adaptive-read-buffering nil)
4449 (coding-system-for-read nil)
4450 ;; This must be done in order to avoid our file
4451 ;; name handler.
4452 (p (let ((default-directory
4453 (tramp-compat-temporary-file-directory)))
4454 (apply
4455 'start-process
4456 (tramp-get-connection-name vec)
4457 (tramp-get-connection-buffer vec)
4458 (if tramp-encoding-command-interactive
4459 (list tramp-encoding-shell
4460 tramp-encoding-command-interactive)
4461 (list tramp-encoding-shell))))))
4463 ;; Set sentinel and query flag.
4464 (tramp-set-connection-property p "vector" vec)
4465 (set-process-sentinel p 'tramp-process-sentinel)
4466 (tramp-compat-set-process-query-on-exit-flag p nil)
4467 (setq tramp-current-connection
4468 (cons (butlast (append vec nil) 2) (current-time))
4469 tramp-current-host (system-name))
4471 (tramp-message
4472 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4474 ;; Check whether process is alive.
4475 (tramp-barf-if-no-shell-prompt
4476 p 10
4477 "Couldn't find local shell prompt for %s" tramp-encoding-shell)
4479 ;; Now do all the connections as specified.
4480 (while target-alist
4481 (let* ((hop (car target-alist))
4482 (l-method (tramp-file-name-method hop))
4483 (l-user (tramp-file-name-user hop))
4484 (l-host (tramp-file-name-host hop))
4485 (l-port nil)
4486 (login-program
4487 (tramp-get-method-parameter
4488 l-method 'tramp-login-program))
4489 (login-args
4490 (tramp-get-method-parameter
4491 l-method 'tramp-login-args))
4492 (async-args
4493 (tramp-get-method-parameter
4494 l-method 'tramp-async-args))
4495 (connection-timeout
4496 (tramp-get-method-parameter
4497 l-method 'tramp-connection-timeout))
4498 (gw-args
4499 (tramp-get-method-parameter l-method 'tramp-gw-args))
4500 (gw (tramp-get-file-property hop "" "gateway" nil))
4501 (g-method (and gw (tramp-file-name-method gw)))
4502 (g-user (and gw (tramp-file-name-user gw)))
4503 (g-host (and gw (tramp-file-name-real-host gw)))
4504 (command login-program)
4505 ;; We don't create the temporary file. In
4506 ;; fact, it is just a prefix for the
4507 ;; ControlPath option of ssh; the real
4508 ;; temporary file has another name, and it is
4509 ;; created and protected by ssh. It is also
4510 ;; removed by ssh when the connection is
4511 ;; closed. The temporary file name is cached
4512 ;; in the main connection process, therefore
4513 ;; we cannot use `tramp-get-connection-process'.
4514 (tmpfile
4515 (with-tramp-connection-property
4516 (get-process (tramp-buffer-name vec)) "temp-file"
4517 (make-temp-name
4518 (expand-file-name
4519 tramp-temp-name-prefix
4520 (tramp-compat-temporary-file-directory)))))
4521 spec r-shell)
4523 ;; Add arguments for asynchronous processes.
4524 (when (and process-name async-args)
4525 (setq login-args (append async-args login-args)))
4527 ;; Add gateway arguments if necessary.
4528 (when (and gw gw-args)
4529 (setq login-args (append gw-args login-args)))
4531 ;; Check for port number. Until now, there's no
4532 ;; need for handling like method, user, host.
4533 (when (string-match tramp-host-with-port-regexp l-host)
4534 (setq l-port (match-string 2 l-host)
4535 l-host (match-string 1 l-host)))
4537 ;; Check, whether there is a restricted shell.
4538 (dolist (elt tramp-restricted-shell-hosts-alist)
4539 (when (string-match elt tramp-current-host)
4540 (setq r-shell t)))
4542 ;; Set variables for computing the prompt for
4543 ;; reading password. They can also be derived
4544 ;; from a gateway.
4545 (setq tramp-current-method (or g-method l-method)
4546 tramp-current-user (or g-user l-user)
4547 tramp-current-host (or g-host l-host))
4549 ;; Replace `login-args' place holders.
4550 (setq
4551 l-host (or l-host "")
4552 l-user (or l-user "")
4553 l-port (or l-port "")
4554 spec (format-spec-make ?t tmpfile)
4555 options (format-spec options spec)
4556 spec (format-spec-make
4557 ?h l-host ?u l-user ?p l-port ?c options)
4558 command
4559 (concat
4560 ;; We do not want to see the trailing local
4561 ;; prompt in `start-file-process'.
4562 (unless r-shell "exec ")
4563 command " "
4564 (mapconcat
4565 (lambda (x)
4566 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4567 (unless (member "" x) (mapconcat 'identity x " ")))
4568 login-args " ")
4569 ;; Local shell could be a Windows COMSPEC. It
4570 ;; doesn't know the ";" syntax, but we must exit
4571 ;; always for `start-file-process'. It could
4572 ;; also be a restricted shell, which does not
4573 ;; allow "exec".
4574 (when r-shell " && exit || exit")))
4576 ;; Send the command.
4577 (tramp-message vec 3 "Sending command `%s'" command)
4578 (tramp-send-command vec command t t)
4579 (tramp-process-actions
4580 p vec pos tramp-actions-before-shell
4581 (or connection-timeout tramp-connection-timeout))
4582 (tramp-message
4583 vec 3 "Found remote shell prompt on `%s'" l-host))
4584 ;; Next hop.
4585 (setq options ""
4586 target-alist (cdr target-alist)))
4588 ;; Make initial shell settings.
4589 (tramp-open-connection-setup-interactive-shell p vec)))))
4591 ;; When the user did interrupt, we must cleanup.
4592 (quit
4593 (tramp-cleanup-connection vec t)
4594 ;; Propagate the quit signal.
4595 (signal (car err) (cdr err))))))
4597 (defun tramp-send-command (vec command &optional neveropen nooutput)
4598 "Send the COMMAND to connection VEC.
4599 Erases temporary buffer before sending the command. If optional
4600 arg NEVEROPEN is non-nil, never try to open the connection. This
4601 is meant to be used from `tramp-maybe-open-connection' only. The
4602 function waits for output unless NOOUTPUT is set."
4603 (unless neveropen (tramp-maybe-open-connection vec))
4604 (let ((p (tramp-get-connection-process vec)))
4605 (when (tramp-get-connection-property p "remote-echo" nil)
4606 ;; We mark the command string that it can be erased in the output buffer.
4607 (tramp-set-connection-property p "check-remote-echo" t)
4608 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4609 ;; Send the command.
4610 (tramp-message vec 6 "%s" command)
4611 (tramp-send-string vec command)
4612 (unless nooutput (tramp-wait-for-output p))))
4614 (defun tramp-wait-for-output (proc &optional timeout)
4615 "Wait for output from remote command."
4616 (unless (buffer-live-p (process-buffer proc))
4617 (delete-process proc)
4618 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4619 (with-current-buffer (process-buffer proc)
4620 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4621 ;; be leading escape sequences, which must be ignored.
4622 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
4623 ;; Sometimes, the commands do not return a newline but a
4624 ;; null byte before the shell prompt, for example "git
4625 ;; ls-files -c -z ...".
4626 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4627 (found (tramp-wait-for-regexp proc timeout regexp1)))
4628 (if found
4629 (let (buffer-read-only)
4630 ;; A simple-minded busybox has sent " ^H" sequences.
4631 ;; Delete them.
4632 (goto-char (point-min))
4633 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4634 (forward-line 1)
4635 (delete-region (point-min) (point)))
4636 ;; Delete the prompt.
4637 (goto-char (point-max))
4638 (re-search-backward regexp nil t)
4639 (delete-region (point) (point-max)))
4640 (if timeout
4641 (tramp-error
4642 proc 'file-error
4643 "[[Remote prompt `%s' not found in %d secs]]"
4644 tramp-end-of-output timeout)
4645 (tramp-error
4646 proc 'file-error
4647 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
4648 ;; Return value is whether end-of-output sentinel was found.
4649 found)))
4651 (defun tramp-send-command-and-check
4652 (vec command &optional subshell dont-suppress-err)
4653 "Run COMMAND and check its exit status.
4654 Sends `echo $?' along with the COMMAND for checking the exit status. If
4655 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
4657 If the optional argument SUBSHELL is non-nil, the command is
4658 executed in a subshell, ie surrounded by parentheses. If
4659 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
4660 (tramp-send-command
4662 (concat (if subshell "( " "")
4663 command
4664 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
4665 "echo tramp_exit_status $?"
4666 (if subshell " )" "")))
4667 (with-current-buffer (tramp-get-connection-buffer vec)
4668 (goto-char (point-max))
4669 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
4670 (tramp-error
4671 vec 'file-error "Couldn't find exit status of `%s'" command))
4672 (skip-chars-forward "^ ")
4673 (prog1
4674 (zerop (read (current-buffer)))
4675 (let (buffer-read-only)
4676 (delete-region (match-beginning 0) (point-max))))))
4678 (defun tramp-barf-unless-okay (vec command fmt &rest args)
4679 "Run COMMAND, check exit status, throw error if exit status not okay.
4680 Similar to `tramp-send-command-and-check' but accepts two more arguments
4681 FMT and ARGS which are passed to `error'."
4682 (or (tramp-send-command-and-check vec command)
4683 (apply 'tramp-error vec 'file-error fmt args)))
4685 (defun tramp-send-command-and-read (vec command &optional noerror)
4686 "Run COMMAND and return the output, which must be a Lisp expression.
4687 In case there is no valid Lisp expression and NOERROR is nil, it
4688 raises an error."
4689 (when (if noerror
4690 (tramp-send-command-and-check vec command)
4691 (tramp-barf-unless-okay
4692 vec command "`%s' returns with error" command))
4693 (with-current-buffer (tramp-get-connection-buffer vec)
4694 ;; Read the expression.
4695 (goto-char (point-min))
4696 (condition-case nil
4697 (prog1 (read (current-buffer))
4698 ;; Error handling.
4699 (when (re-search-forward "\\S-" (point-at-eol) t)
4700 (error nil)))
4701 (error (unless noerror
4702 (tramp-error
4703 vec 'file-error
4704 "`%s' does not return a valid Lisp expression: `%s'"
4705 command (buffer-string))))))))
4707 (defun tramp-convert-file-attributes (vec attr)
4708 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
4709 Convert file mode bits to string and set virtual device number.
4710 Return ATTR."
4711 (when attr
4712 ;; Remove color escape sequences from symlink.
4713 (when (stringp (car attr))
4714 (while (string-match tramp-color-escape-sequence-regexp (car attr))
4715 (setcar attr (replace-match "" nil nil (car attr)))))
4716 ;; Convert uid and gid. Use -1 as indication of unusable value.
4717 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
4718 (setcar (nthcdr 2 attr) -1))
4719 (when (and (floatp (nth 2 attr))
4720 (<= (nth 2 attr) (tramp-compat-most-positive-fixnum)))
4721 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
4722 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
4723 (setcar (nthcdr 3 attr) -1))
4724 (when (and (floatp (nth 3 attr))
4725 (<= (nth 3 attr) (tramp-compat-most-positive-fixnum)))
4726 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
4727 ;; Convert last access time.
4728 (unless (listp (nth 4 attr))
4729 (setcar (nthcdr 4 attr)
4730 (list (floor (nth 4 attr) 65536)
4731 (floor (mod (nth 4 attr) 65536)))))
4732 ;; Convert last modification time.
4733 (unless (listp (nth 5 attr))
4734 (setcar (nthcdr 5 attr)
4735 (list (floor (nth 5 attr) 65536)
4736 (floor (mod (nth 5 attr) 65536)))))
4737 ;; Convert last status change time.
4738 (unless (listp (nth 6 attr))
4739 (setcar (nthcdr 6 attr)
4740 (list (floor (nth 6 attr) 65536)
4741 (floor (mod (nth 6 attr) 65536)))))
4742 ;; Convert file size.
4743 (when (< (nth 7 attr) 0)
4744 (setcar (nthcdr 7 attr) -1))
4745 (when (and (floatp (nth 7 attr))
4746 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
4747 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
4748 ;; Convert file mode bits to string.
4749 (unless (stringp (nth 8 attr))
4750 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
4751 (when (stringp (car attr))
4752 (aset (nth 8 attr) 0 ?l)))
4753 ;; Convert directory indication bit.
4754 (when (string-match "^d" (nth 8 attr))
4755 (setcar attr t))
4756 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
4757 (when (consp (car attr))
4758 (if (and (stringp (caar attr))
4759 (string-match ".+ -> .\\(.+\\)." (caar attr)))
4760 (setcar attr (match-string 1 (caar attr)))
4761 (setcar attr nil)))
4762 ;; Set file's gid change bit.
4763 (setcar (nthcdr 9 attr)
4764 (if (numberp (nth 3 attr))
4765 (not (= (nth 3 attr)
4766 (tramp-get-remote-gid vec 'integer)))
4767 (not (string-equal
4768 (nth 3 attr)
4769 (tramp-get-remote-gid vec 'string)))))
4770 ;; Convert inode.
4771 (unless (listp (nth 10 attr))
4772 (setcar (nthcdr 10 attr)
4773 (condition-case nil
4774 (cons (floor (nth 10 attr) 65536)
4775 (floor (mod (nth 10 attr) 65536)))
4776 ;; Inodes can be incredible huge. We must hide this.
4777 (error (tramp-get-inode vec)))))
4778 ;; Set virtual device number.
4779 (setcar (nthcdr 11 attr)
4780 (tramp-get-device vec))
4781 attr))
4783 (defun tramp-shell-case-fold (string)
4784 "Converts STRING to shell glob pattern which ignores case."
4785 (mapconcat
4786 (lambda (c)
4787 (if (equal (downcase c) (upcase c))
4788 (vector c)
4789 (format "[%c%c]" (downcase c) (upcase c))))
4790 string
4791 ""))
4793 (defun tramp-make-copy-program-file-name (vec)
4794 "Create a file name suitable to be passed to `rcp' and workalikes."
4795 (let ((user (tramp-file-name-user vec))
4796 (host (tramp-file-name-real-host vec))
4797 (localname (tramp-shell-quote-argument
4798 (tramp-file-name-localname vec))))
4799 (if (not (zerop (length user)))
4800 (format "%s@%s:%s" user host localname)
4801 (format "%s:%s" host localname))))
4803 (defun tramp-method-out-of-band-p (vec size)
4804 "Return t if this is an out-of-band method, nil otherwise."
4805 (and
4806 ;; It shall be an out-of-band method.
4807 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
4808 ;; There must be a size, otherwise the file doesn't exist.
4809 (numberp size)
4810 ;; Either the file size is large enough, or (in rare cases) there
4811 ;; does not exist a remote encoding.
4812 (or (null tramp-copy-size-limit)
4813 (> size tramp-copy-size-limit)
4814 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
4816 ;; Variables local to connection.
4818 (defun tramp-get-remote-path (vec)
4819 (with-tramp-connection-property
4820 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
4821 ;; cache the result for the session only. Otherwise, the result
4822 ;; is cached persistently.
4823 (if (memq 'tramp-own-remote-path tramp-remote-path)
4824 (tramp-get-connection-process vec)
4825 vec)
4826 "remote-path"
4827 (let* ((remote-path (copy-tree tramp-remote-path))
4828 (elt1 (memq 'tramp-default-remote-path remote-path))
4829 (elt2 (memq 'tramp-own-remote-path remote-path))
4830 (default-remote-path
4831 (when elt1
4833 (tramp-send-command-and-read
4834 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
4835 ;; Default if "getconf" is not available.
4836 (progn
4837 (tramp-message
4838 vec 3
4839 "`getconf PATH' not successful, using default value \"%s\"."
4840 "/bin:/usr/bin")
4841 "/bin:/usr/bin"))))
4842 (own-remote-path
4843 (when elt2
4844 (condition-case nil
4845 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
4846 (error
4847 (tramp-message
4848 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
4849 nil)))))
4851 ;; Replace place holder `tramp-default-remote-path'.
4852 (when elt1
4853 (setcdr elt1
4854 (append
4855 (tramp-compat-split-string (or default-remote-path "") ":")
4856 (cdr elt1)))
4857 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
4859 ;; Replace place holder `tramp-own-remote-path'.
4860 (when elt2
4861 (setcdr elt2
4862 (append
4863 (tramp-compat-split-string (or own-remote-path "") ":")
4864 (cdr elt2)))
4865 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
4867 ;; Remove double entries.
4868 (setq elt1 remote-path)
4869 (while (consp elt1)
4870 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
4871 (setcar elt2 nil))
4872 (setq elt1 (cdr elt1)))
4874 ;; Remove non-existing directories.
4875 (delq
4877 (mapcar
4878 (lambda (x)
4879 (and
4880 (stringp x)
4881 (file-directory-p
4882 (tramp-make-tramp-file-name
4883 (tramp-file-name-method vec)
4884 (tramp-file-name-user vec)
4885 (tramp-file-name-host vec)
4888 remote-path)))))
4890 (defun tramp-get-remote-locale (vec)
4891 (with-tramp-connection-property vec "locale"
4892 (tramp-send-command vec "locale -a")
4893 (let ((candidates '("en_US.utf8" "C.utf8" "C"))
4894 locale)
4895 (with-current-buffer (tramp-get-connection-buffer vec)
4896 (while candidates
4897 (goto-char (point-min))
4898 (if (string-match (concat "^" (car candidates) "$") (buffer-string))
4899 (setq locale (car candidates)
4900 candidates nil)
4901 (setq candidates (cdr candidates)))))
4902 ;; Return value.
4903 (when locale (format "LC_ALL=%s" locale)))))
4905 (defun tramp-get-ls-command (vec)
4906 (with-tramp-connection-property vec "ls"
4907 (tramp-message vec 5 "Finding a suitable `ls' command")
4909 (catch 'ls-found
4910 (dolist (cmd '("ls" "gnuls" "gls"))
4911 (let ((dl (tramp-get-remote-path vec))
4912 result)
4913 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
4914 ;; Check parameters. On busybox, "ls" output coloring is
4915 ;; enabled by default sometimes. So we try to disable it
4916 ;; when possible. $LS_COLORING is not supported there.
4917 ;; Some "ls" versions are sensible wrt the order of
4918 ;; arguments, they fail when "-al" is after the
4919 ;; "--color=never" argument (for example on FreeBSD).
4920 (when (tramp-send-command-and-check
4921 vec (format "%s -lnd /" result))
4922 (when (tramp-send-command-and-check
4923 vec (format
4924 "%s --color=never -al /dev/null" result))
4925 (setq result (concat result " --color=never")))
4926 (throw 'ls-found result))
4927 (setq dl (cdr dl))))))
4928 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
4930 (defun tramp-get-ls-command-with-dired (vec)
4931 (save-match-data
4932 (with-tramp-connection-property vec "ls-dired"
4933 (tramp-message vec 5 "Checking, whether `ls --dired' works")
4934 ;; Some "ls" versions are sensible wrt the order of arguments,
4935 ;; they fail when "-al" is after the "--dired" argument (for
4936 ;; example on FreeBSD).
4937 (tramp-send-command-and-check
4938 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
4940 (defun tramp-get-test-command (vec)
4941 (with-tramp-connection-property vec "test"
4942 (tramp-message vec 5 "Finding a suitable `test' command")
4943 (if (tramp-send-command-and-check vec "test 0")
4944 "test"
4945 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
4947 (defun tramp-get-test-nt-command (vec)
4948 ;; Does `test A -nt B' work? Use abominable `find' construct if it
4949 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
4950 ;; for otherwise the shell crashes.
4951 (with-tramp-connection-property vec "test-nt"
4953 (progn
4954 (tramp-send-command
4955 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
4956 (with-current-buffer (tramp-get-buffer vec)
4957 (goto-char (point-min))
4958 (when (looking-at (regexp-quote tramp-end-of-output))
4959 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
4960 (progn
4961 (tramp-send-command
4963 (format
4964 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
4965 (tramp-get-test-command vec)))
4966 "tramp_test_nt %s %s"))))
4968 (defun tramp-get-file-exists-command (vec)
4969 (with-tramp-connection-property vec "file-exists"
4970 (tramp-message vec 5 "Finding command to check if file exists")
4971 (tramp-find-file-exists-command vec)))
4973 (defun tramp-get-remote-ln (vec)
4974 (with-tramp-connection-property vec "ln"
4975 (tramp-message vec 5 "Finding a suitable `ln' command")
4976 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
4978 (defun tramp-get-remote-perl (vec)
4979 (with-tramp-connection-property vec "perl"
4980 (tramp-message vec 5 "Finding a suitable `perl' command")
4981 (let ((result
4982 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
4983 (tramp-find-executable
4984 vec "perl" (tramp-get-remote-path vec)))))
4985 ;; We must check also for some Perl modules.
4986 (when result
4987 (with-tramp-connection-property vec "perl-file-spec"
4988 (tramp-send-command-and-check
4989 vec (format "%s -e 'use File::Spec;'" result)))
4990 (with-tramp-connection-property vec "perl-cwd-realpath"
4991 (tramp-send-command-and-check
4992 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
4993 result)))
4995 (defun tramp-get-remote-stat (vec)
4996 (with-tramp-connection-property vec "stat"
4997 (tramp-message vec 5 "Finding a suitable `stat' command")
4998 (let ((result (tramp-find-executable
4999 vec "stat" (tramp-get-remote-path vec)))
5000 tmp)
5001 ;; Check whether stat(1) returns usable syntax. "%s" does not
5002 ;; work on older AIX systems.
5003 (when result
5004 (setq tmp
5005 (tramp-send-command-and-read
5006 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5007 (unless (and (listp tmp) (stringp (car tmp))
5008 (string-match "^./.$" (car tmp))
5009 (integerp (cadr tmp)))
5010 (setq result nil)))
5011 result)))
5013 (defun tramp-get-remote-readlink (vec)
5014 (with-tramp-connection-property vec "readlink"
5015 (tramp-message vec 5 "Finding a suitable `readlink' command")
5016 (let ((result (tramp-find-executable
5017 vec "readlink" (tramp-get-remote-path vec))))
5018 (when (and result
5019 (tramp-send-command-and-check
5020 vec (format "%s --canonicalize-missing /" result)))
5021 result))))
5023 (defun tramp-get-remote-trash (vec)
5024 (with-tramp-connection-property vec "trash"
5025 (tramp-message vec 5 "Finding a suitable `trash' command")
5026 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5028 (defun tramp-get-remote-touch (vec)
5029 (with-tramp-connection-property vec "touch"
5030 (tramp-message vec 5 "Finding a suitable `touch' command")
5031 (let ((result (tramp-find-executable
5032 vec "touch" (tramp-get-remote-path vec)))
5033 (tmpfile
5034 (make-temp-name
5035 (expand-file-name
5036 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
5037 ;; Busyboxes do support the "-t" option only when they have been
5038 ;; built with the DESKTOP config option. Let's check it.
5039 (when result
5040 (tramp-set-connection-property
5041 vec "touch-t"
5042 (tramp-send-command-and-check
5044 (format
5045 "%s -t %s %s"
5046 result
5047 (format-time-string "%Y%m%d%H%M.%S" (current-time))
5048 (tramp-file-name-handler 'file-remote-p tmpfile 'localname))))
5049 (delete-file tmpfile))
5050 result)))
5052 (defun tramp-get-remote-gvfs-monitor-dir (vec)
5053 (with-tramp-connection-property vec "gvfs-monitor-dir"
5054 (tramp-message vec 5 "Finding a suitable `gvfs-monitor-dir' command")
5055 (tramp-find-executable
5056 vec "gvfs-monitor-dir" (tramp-get-remote-path vec) t t)))
5058 (defun tramp-get-remote-inotifywait (vec)
5059 (with-tramp-connection-property vec "inotifywait"
5060 (tramp-message vec 5 "Finding a suitable `inotifywait' command")
5061 (tramp-find-executable vec "inotifywait" (tramp-get-remote-path vec) t t)))
5063 (defun tramp-get-remote-id (vec)
5064 (with-tramp-connection-property vec "id"
5065 (tramp-message vec 5 "Finding POSIX `id' command")
5066 (catch 'id-found
5067 (let ((dl (tramp-get-remote-path vec))
5068 result)
5069 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
5070 ;; Check POSIX parameter.
5071 (when (tramp-send-command-and-check vec (format "%s -u" result))
5072 (throw 'id-found result))
5073 (setq dl (cdr dl)))))))
5075 (defun tramp-get-remote-uid-with-id (vec id-format)
5076 (tramp-send-command-and-read
5078 (format "%s -u%s %s"
5079 (tramp-get-remote-id vec)
5080 (if (equal id-format 'integer) "" "n")
5081 (if (equal id-format 'integer)
5082 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/"))))
5084 (defun tramp-get-remote-uid-with-perl (vec id-format)
5085 (tramp-send-command-and-read
5087 (format "%s -le '%s'"
5088 (tramp-get-remote-perl vec)
5089 (if (equal id-format 'integer)
5090 "print $>"
5091 "print \"\\\"\", scalar getpwuid($>), \"\\\"\""))))
5093 (defun tramp-get-remote-python (vec)
5094 (with-tramp-connection-property vec "python"
5095 (tramp-message vec 5 "Finding a suitable `python' command")
5096 (tramp-find-executable vec "python" (tramp-get-remote-path vec))))
5098 (defun tramp-get-remote-uid-with-python (vec id-format)
5099 (tramp-send-command-and-read
5101 (format "%s -c \"%s\""
5102 (tramp-get-remote-python vec)
5103 (if (equal id-format 'integer)
5104 "import os; print os.getuid()"
5105 "import os, pwd; print '\\\"' + pwd.getpwuid(os.getuid())[0] + '\\\"'"))))
5107 (defun tramp-get-remote-uid (vec id-format)
5108 (with-tramp-connection-property vec (format "uid-%s" id-format)
5109 (let ((res (cond
5110 ((tramp-get-remote-id vec)
5111 (tramp-get-remote-uid-with-id vec id-format))
5112 ((tramp-get-remote-perl vec)
5113 (tramp-get-remote-uid-with-perl vec id-format))
5114 ((tramp-get-remote-python vec)
5115 (tramp-get-remote-uid-with-python vec id-format))
5116 (t (tramp-error
5117 vec 'file-error "Cannot determine remote uid")))))
5118 ;; The command might not always return a number.
5119 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
5121 (defun tramp-get-remote-gid-with-id (vec id-format)
5122 (tramp-send-command-and-read
5124 (format "%s -g%s %s"
5125 (tramp-get-remote-id vec)
5126 (if (equal id-format 'integer) "" "n")
5127 (if (equal id-format 'integer)
5128 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/"))))
5130 (defun tramp-get-remote-gid-with-perl (vec id-format)
5131 (tramp-send-command-and-read
5133 (format "%s -le '%s'"
5134 (tramp-get-remote-perl vec)
5135 (if (equal id-format 'integer)
5136 "print ($)=~/(\\d+)/)"
5137 "print \"\\\"\", scalar getgrgid($)), \"\\\"\""))))
5139 (defun tramp-get-remote-gid-with-python (vec id-format)
5140 (tramp-send-command-and-read
5142 (format "%s -c \"%s\""
5143 (tramp-get-remote-python vec)
5144 (if (equal id-format 'integer)
5145 "import os; print os.getgid()"
5146 "import os, grp; print '\\\"' + grp.getgrgid(os.getgid())[0] + '\\\"'"))))
5148 (defun tramp-get-remote-gid (vec id-format)
5149 (with-tramp-connection-property vec (format "gid-%s" id-format)
5150 (let ((res (cond
5151 ((tramp-get-remote-id vec)
5152 (tramp-get-remote-gid-with-id vec id-format))
5153 ((tramp-get-remote-perl vec)
5154 (tramp-get-remote-gid-with-perl vec id-format))
5155 ((tramp-get-remote-python vec)
5156 (tramp-get-remote-gid-with-python vec id-format))
5157 (t (tramp-error
5158 vec 'file-error "Cannot determine remote gid")))))
5159 ;; The command might not always return a number.
5160 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
5162 ;; Some predefined connection properties.
5163 (defun tramp-get-inline-compress (vec prop size)
5164 "Return the compress command related to PROP.
5165 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5166 the length of the file to be compressed.
5168 If no corresponding command is found, nil is returned."
5169 (when (and (integerp tramp-inline-compress-start-size)
5170 (> size tramp-inline-compress-start-size))
5171 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5172 (tramp-find-inline-compress vec)
5173 (tramp-get-connection-property
5174 (tramp-get-connection-process vec) prop nil))))
5176 (defun tramp-get-inline-coding (vec prop size)
5177 "Return the coding command related to PROP.
5178 PROP is either `remote-encoding', `remote-decoding',
5179 `local-encoding' or `local-decoding'.
5181 SIZE is the length of the file to be coded. Depending on SIZE,
5182 compression might be applied.
5184 If no corresponding command is found, nil is returned.
5185 Otherwise, either a string is returned which contains a `%s' mark
5186 to be used for the respective input or output file; or a Lisp
5187 function cell is returned to be applied on a buffer."
5188 ;; We must catch the errors, because we want to return `nil', when
5189 ;; no inline coding is found.
5190 (ignore-errors
5191 (let ((coding
5192 (with-tramp-connection-property
5193 (tramp-get-connection-process vec) prop
5194 (tramp-find-inline-encoding vec)
5195 (tramp-get-connection-property
5196 (tramp-get-connection-process vec) prop nil)))
5197 (prop1 (if (string-match "encoding" prop)
5198 "inline-compress" "inline-decompress"))
5199 compress)
5200 ;; The connection property might have been cached. So we must
5201 ;; send the script to the remote side - maybe.
5202 (when (and coding (symbolp coding) (string-match "remote" prop))
5203 (let ((name (symbol-name coding)))
5204 (while (string-match (regexp-quote "-") name)
5205 (setq name (replace-match "_" nil t name)))
5206 (tramp-maybe-send-script vec (symbol-value coding) name)
5207 (setq coding name)))
5208 (when coding
5209 ;; Check for the `compress' command.
5210 (setq compress (tramp-get-inline-compress vec prop1 size))
5211 ;; Return the value.
5212 (cond
5213 ((and compress (symbolp coding))
5214 (if (string-match "decompress" prop1)
5215 `(lambda (beg end)
5216 (,coding beg end)
5217 (let ((coding-system-for-write 'binary)
5218 (coding-system-for-read 'binary))
5219 (apply
5220 'call-process-region (point-min) (point-max)
5221 (car (split-string ,compress)) t t nil
5222 (cdr (split-string ,compress)))))
5223 `(lambda (beg end)
5224 (let ((coding-system-for-write 'binary)
5225 (coding-system-for-read 'binary))
5226 (apply
5227 'call-process-region beg end
5228 (car (split-string ,compress)) t t nil
5229 (cdr (split-string ,compress))))
5230 (,coding (point-min) (point-max)))))
5231 ((symbolp coding)
5232 coding)
5233 ((and compress (string-match "decoding" prop))
5234 (format
5235 ;; Windows shells need the program file name after
5236 ;; the pipe symbol be quoted if they use forward
5237 ;; slashes as directory separators.
5238 (cond
5239 ((and (string-match "local" prop)
5240 (memq system-type '(windows-nt)))
5241 "(%s | \"%s\")")
5242 ((string-match "local" prop) "(%s | %s)")
5243 (t "(%s | %s >%%s)"))
5244 coding compress))
5245 (compress
5246 (format
5247 ;; Windows shells need the program file name after
5248 ;; the pipe symbol be quoted if they use forward
5249 ;; slashes as directory separators.
5250 (if (and (string-match "local" prop)
5251 (memq system-type '(windows-nt)))
5252 "(%s <%%s | \"%s\")"
5253 "(%s <%%s | %s)")
5254 compress coding))
5255 ((string-match "decoding" prop)
5256 (cond
5257 ((string-match "local" prop) (format "%s" coding))
5258 (t (format "%s >%%s" coding))))
5260 (format "%s <%%s" coding)))))))
5262 (add-hook 'tramp-unload-hook
5263 (lambda ()
5264 (unload-feature 'tramp-sh 'force)))
5266 (provide 'tramp-sh)
5268 ;;; TODO:
5270 ;; * Don't use globbing for directories with many files, as this is
5271 ;; likely to produce long command lines, and some shells choke on
5272 ;; long command lines.
5273 ;; * Make it work for different encodings, and for different file name
5274 ;; encodings, too. (Daniel Pittman)
5275 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5276 ;; then look if it's the right version (with `perl -v').
5277 ;; * When editing a remote CVS controlled file as a different user, VC
5278 ;; gets confused about the file locking status. Try to find out why
5279 ;; the workaround doesn't work.
5280 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5281 ;; until the last but one hop via `start-file-process'. Apply it
5282 ;; also for ftp and smb.
5283 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5284 ;; some shell with root privileges, it would be nice if I could
5285 ;; just call
5286 ;; trampclient filename.c
5287 ;; as an editor, and the _current_ shell would connect to an Emacs
5288 ;; server and would be used in an existing non-privileged Emacs
5289 ;; session for doing the editing in question.
5290 ;; That way, I need not tell Emacs my password again and be afraid
5291 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5292 ;; once display a just typed password in the context of a keyboard
5293 ;; sequence prompt for a question immediately following in a shell
5294 ;; script run within Emacs -- nasty).
5295 ;; And if I have some ssh session running to a different computer,
5296 ;; having the possibility of passing a local file there to a local
5297 ;; Emacs session (in case I can arrange for a connection back) would
5298 ;; be nice.
5299 ;; Likely the corresponding Tramp server should not allow the
5300 ;; equivalent of the emacsclient -eval option in order to make this
5301 ;; reasonably unproblematic. And maybe trampclient should have some
5302 ;; way of passing credentials, like by using an SSL socket or
5303 ;; something. (David Kastrup)
5304 ;; * Reconnect directly to a compliant shell without first going
5305 ;; through the user's default shell. (Pete Forman)
5306 ;; * How can I interrupt the remote process with a signal
5307 ;; (interrupt-process seems not to work)? (Markus Triska)
5308 ;; * Avoid the local shell entirely for starting remote processes. If
5309 ;; so, I think even a signal, when delivered directly to the local
5310 ;; SSH instance, would correctly be propagated to the remote process
5311 ;; automatically; possibly SSH would have to be started with
5312 ;; "-t". (Markus Triska)
5313 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5314 ;; isn't on the remote host. (Mark A. Hershberger)
5315 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5316 ;; * Optimize out-of-band copying when both methods are scp-like (not
5317 ;; rsync).
5318 ;; * Keep a second connection open for out-of-band methods like scp or
5319 ;; rsync.
5320 ;; * Try telnet+curl as new method. It might be useful for busybox,
5321 ;; without built-in uuencode/uudecode.
5322 ;; * Try telnet+nc as new method. It might be useful for busybox,
5323 ;; without built-in uuencode/uudecode.
5325 ;;; tramp-sh.el ends here