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