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