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