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