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