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