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