]> code.delx.au - gnu-emacs/blob - lisp/net/tramp-sh.el
merge trunk
[gnu-emacs] / 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" "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 default-file-name-coding-system))
2572
2573 ;; The inserted file could be from somewhere else.
2574 (when (and (not wildcard) (not full-directory-p))
2575 (goto-char (point-max))
2576 (when (file-symlink-p filename)
2577 (goto-char (search-backward "->" beg 'noerror)))
2578 (search-backward
2579 (if (zerop (length (file-name-nondirectory filename)))
2580 "."
2581 (file-name-nondirectory filename))
2582 beg 'noerror)
2583 (replace-match (file-relative-name filename) t))
2584
2585 (goto-char (point-max))))))
2586
2587 ;; Canonicalization of file names.
2588
2589 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2590 "Like `expand-file-name' for Tramp files.
2591 If the localname part of the given filename starts with \"/../\" then
2592 the result will be a local, non-Tramp, filename."
2593 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
2594 (setq dir (or dir default-directory "/"))
2595 ;; Unless NAME is absolute, concat DIR and NAME.
2596 (unless (file-name-absolute-p name)
2597 (setq name (concat (file-name-as-directory dir) name)))
2598 ;; If NAME is not a Tramp file, run the real handler.
2599 (if (not (tramp-connectable-p name))
2600 (tramp-run-real-handler 'expand-file-name (list name nil))
2601 ;; Dissect NAME.
2602 (with-parsed-tramp-file-name name nil
2603 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2604 (setq localname (concat "~/" localname)))
2605 ;; Tilde expansion if necessary. This needs a shell which
2606 ;; groks tilde expansion! The function `tramp-find-shell' is
2607 ;; supposed to find such a shell on the remote host. Please
2608 ;; tell me about it when this doesn't work on your system.
2609 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2610 (let ((uname (match-string 1 localname))
2611 (fname (match-string 2 localname)))
2612 ;; We cannot simply apply "~/", because under sudo "~/" is
2613 ;; expanded to the local user home directory but to the
2614 ;; root home directory. On the other hand, using always
2615 ;; the default user name for tilde expansion is not
2616 ;; appropriate either, because ssh and companions might
2617 ;; use a user name from the config file.
2618 (when (and (string-equal uname "~")
2619 (string-match "\\`su\\(do\\)?\\'" method))
2620 (setq uname (concat uname user)))
2621 (setq uname
2622 (with-tramp-connection-property v uname
2623 (tramp-send-command
2624 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
2625 (with-current-buffer (tramp-get-buffer v)
2626 (goto-char (point-min))
2627 (buffer-substring (point) (point-at-eol)))))
2628 (setq localname (concat uname fname))))
2629 ;; There might be a double slash, for example when "~/"
2630 ;; expands to "/". Remove this.
2631 (while (string-match "//" localname)
2632 (setq localname (replace-match "/" t t localname)))
2633 ;; No tilde characters in file name, do normal
2634 ;; `expand-file-name' (this does "/./" and "/../"). We bind
2635 ;; `directory-sep-char' here for XEmacs on Windows, which would
2636 ;; otherwise use backslash. `default-directory' is bound,
2637 ;; because on Windows there would be problems with UNC shares or
2638 ;; Cygwin mounts.
2639 (let ((directory-sep-char ?/)
2640 (default-directory (tramp-compat-temporary-file-directory)))
2641 (tramp-make-tramp-file-name
2642 method user host
2643 (tramp-drop-volume-letter
2644 (tramp-run-real-handler
2645 'expand-file-name (list localname)))
2646 hop)))))
2647
2648 ;;; Remote commands:
2649
2650 (defun tramp-sh-handle-executable-find (command)
2651 "Like `executable-find' for Tramp files."
2652 (with-parsed-tramp-file-name default-directory nil
2653 (tramp-find-executable v command (tramp-get-remote-path v) t)))
2654
2655 (defun tramp-process-sentinel (proc event)
2656 "Flush file caches."
2657 (unless (memq (process-status proc) '(run open))
2658 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2659 (when vec
2660 (tramp-message vec 5 "Sentinel called: `%s' `%s'" proc event)
2661 (tramp-flush-connection-property proc)
2662 (tramp-flush-directory-property vec "")))))
2663
2664 ;; We use BUFFER also as connection buffer during setup. Because of
2665 ;; this, its original contents must be saved, and restored once
2666 ;; connection has been setup.
2667 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2668 "Like `start-file-process' for Tramp files."
2669 (with-parsed-tramp-file-name default-directory nil
2670 ;; When PROGRAM is nil, we just provide a tty.
2671 (let ((command
2672 (when (stringp program)
2673 (format "cd %s; exec env PS1=%s %s"
2674 (tramp-shell-quote-argument localname)
2675 ;; Use a human-friendly prompt, for example for `shell'.
2676 (tramp-shell-quote-argument
2677 (format "%s %s"
2678 (file-remote-p default-directory)
2679 tramp-initial-end-of-output))
2680 (mapconcat 'tramp-shell-quote-argument
2681 (cons program args) " "))))
2682 (tramp-process-connection-type
2683 (or (null program) tramp-process-connection-type))
2684 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2685 (name1 name)
2686 (i 0)
2687 ;; We do not want to raise an error when
2688 ;; `start-file-process' has been started several time in
2689 ;; `eshell' and friends.
2690 (tramp-current-connection nil))
2691
2692 (unless buffer
2693 ;; BUFFER can be nil. We use a temporary buffer.
2694 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
2695 (while (get-process name1)
2696 ;; NAME must be unique as process name.
2697 (setq i (1+ i)
2698 name1 (format "%s<%d>" name i)))
2699 (setq name name1)
2700 ;; Set the new process properties.
2701 (tramp-set-connection-property v "process-name" name)
2702 (tramp-set-connection-property v "process-buffer" buffer)
2703
2704 (with-current-buffer (tramp-get-connection-buffer v)
2705 (unwind-protect
2706 ;; We catch this event. Otherwise, `start-process' could
2707 ;; be called on the local host.
2708 (save-excursion
2709 (save-restriction
2710 ;; Activate narrowing in order to save BUFFER
2711 ;; contents. Clear also the modification time;
2712 ;; otherwise we might be interrupted by
2713 ;; `verify-visited-file-modtime'.
2714 (let ((buffer-undo-list t)
2715 (buffer-read-only nil)
2716 (mark (point)))
2717 (clear-visited-file-modtime)
2718 (narrow-to-region (point-max) (point-max))
2719 ;; We call `tramp-maybe-open-connection', in order
2720 ;; to cleanup the prompt afterwards.
2721 (catch 'suppress
2722 (tramp-maybe-open-connection v)
2723 (widen)
2724 (delete-region mark (point))
2725 (narrow-to-region (point-max) (point-max))
2726 ;; Now do it.
2727 (if command
2728 ;; Send the command.
2729 (tramp-send-command v command nil t) ; nooutput
2730 ;; Check, whether a pty is associated.
2731 (unless (tramp-compat-process-get
2732 (tramp-get-connection-process v) 'remote-tty)
2733 (tramp-error
2734 v 'file-error
2735 "pty association is not supported for `%s'" name))))
2736 (let ((p (tramp-get-connection-process v)))
2737 ;; Set query flag and process marker for this
2738 ;; process. We ignore errors, because the process
2739 ;; could have finished already.
2740 (ignore-errors
2741 (tramp-compat-set-process-query-on-exit-flag p t)
2742 (set-marker (process-mark p) (point)))
2743 ;; Return process.
2744 p))))
2745
2746 ;; Save exit.
2747 (if (string-match tramp-temp-buffer-name (buffer-name))
2748 (ignore-errors
2749 (set-process-buffer (tramp-get-connection-process v) nil)
2750 (kill-buffer (current-buffer)))
2751 (set-buffer-modified-p bmp))
2752 (tramp-set-connection-property v "process-name" nil)
2753 (tramp-set-connection-property v "process-buffer" nil))))))
2754
2755 (defun tramp-sh-handle-process-file
2756 (program &optional infile destination display &rest args)
2757 "Like `process-file' for Tramp files."
2758 ;; The implementation is not complete yet.
2759 (when (and (numberp destination) (zerop destination))
2760 (error "Implementation does not handle immediate return"))
2761
2762 (with-parsed-tramp-file-name default-directory nil
2763 (let (command input tmpinput stderr tmpstderr outbuf ret)
2764 ;; Compute command.
2765 (setq command (mapconcat 'tramp-shell-quote-argument
2766 (cons program args) " "))
2767 ;; Determine input.
2768 (if (null infile)
2769 (setq input "/dev/null")
2770 (setq infile (expand-file-name infile))
2771 (if (tramp-equal-remote default-directory infile)
2772 ;; INFILE is on the same remote host.
2773 (setq input (with-parsed-tramp-file-name infile nil localname))
2774 ;; INFILE must be copied to remote host.
2775 (setq input (tramp-make-tramp-temp-file v)
2776 tmpinput (tramp-make-tramp-file-name method user host input))
2777 (copy-file infile tmpinput t)))
2778 (when input (setq command (format "%s <%s" command input)))
2779
2780 ;; Determine output.
2781 (cond
2782 ;; Just a buffer.
2783 ((bufferp destination)
2784 (setq outbuf destination))
2785 ;; A buffer name.
2786 ((stringp destination)
2787 (setq outbuf (get-buffer-create destination)))
2788 ;; (REAL-DESTINATION ERROR-DESTINATION)
2789 ((consp destination)
2790 ;; output.
2791 (cond
2792 ((bufferp (car destination))
2793 (setq outbuf (car destination)))
2794 ((stringp (car destination))
2795 (setq outbuf (get-buffer-create (car destination))))
2796 ((car destination)
2797 (setq outbuf (current-buffer))))
2798 ;; stderr.
2799 (cond
2800 ((stringp (cadr destination))
2801 (setcar (cdr destination) (expand-file-name (cadr destination)))
2802 (if (tramp-equal-remote default-directory (cadr destination))
2803 ;; stderr is on the same remote host.
2804 (setq stderr (with-parsed-tramp-file-name
2805 (cadr destination) nil localname))
2806 ;; stderr must be copied to remote host. The temporary
2807 ;; file must be deleted after execution.
2808 (setq stderr (tramp-make-tramp-temp-file v)
2809 tmpstderr (tramp-make-tramp-file-name
2810 method user host stderr))))
2811 ;; stderr to be discarded.
2812 ((null (cadr destination))
2813 (setq stderr "/dev/null"))))
2814 ;; 't
2815 (destination
2816 (setq outbuf (current-buffer))))
2817 (when stderr (setq command (format "%s 2>%s" command stderr)))
2818
2819 ;; Send the command. It might not return in time, so we protect
2820 ;; it. Call it in a subshell, in order to preserve working
2821 ;; directory.
2822 (condition-case nil
2823 (unwind-protect
2824 (setq ret
2825 (if (tramp-send-command-and-check
2826 v (format "\\cd %s; %s"
2827 (tramp-shell-quote-argument localname)
2828 command)
2829 t t)
2830 0 1))
2831 ;; We should show the output anyway.
2832 (when outbuf
2833 (with-current-buffer outbuf
2834 (insert
2835 (with-current-buffer (tramp-get-connection-buffer v)
2836 (buffer-string))))
2837 (when display (display-buffer outbuf))))
2838 ;; When the user did interrupt, we should do it also. We use
2839 ;; return code -1 as marker.
2840 (quit
2841 (kill-buffer (tramp-get-connection-buffer v))
2842 (setq ret -1))
2843 ;; Handle errors.
2844 (error
2845 (kill-buffer (tramp-get-connection-buffer v))
2846 (setq ret 1)))
2847
2848 ;; Provide error file.
2849 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
2850
2851 ;; Cleanup. We remove all file cache values for the connection,
2852 ;; because the remote process could have changed them.
2853 (when tmpinput (delete-file tmpinput))
2854
2855 ;; `process-file-side-effects' has been introduced with GNU
2856 ;; Emacs 23.2. If set to `nil', no remote file will be changed
2857 ;; by `program'. If it doesn't exist, we assume its default
2858 ;; value `t'.
2859 (unless (and (boundp 'process-file-side-effects)
2860 (not (symbol-value 'process-file-side-effects)))
2861 (tramp-flush-directory-property v ""))
2862
2863 ;; Return exit status.
2864 (if (equal ret -1)
2865 (keyboard-quit)
2866 ret))))
2867
2868 (defun tramp-sh-handle-file-local-copy (filename)
2869 "Like `file-local-copy' for Tramp files."
2870 (with-parsed-tramp-file-name filename nil
2871 (unless (file-exists-p filename)
2872 (tramp-error
2873 v 'file-error
2874 "Cannot make local copy of non-existing file `%s'" filename))
2875
2876 (let* ((size (nth 7 (file-attributes (file-truename filename))))
2877 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
2878 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
2879 (tmpfile (tramp-compat-make-temp-file filename)))
2880
2881 (condition-case err
2882 (cond
2883 ;; `copy-file' handles direct copy and out-of-band methods.
2884 ((or (tramp-local-host-p v)
2885 (tramp-method-out-of-band-p v size))
2886 (copy-file filename tmpfile t t))
2887
2888 ;; Use inline encoding for file transfer.
2889 (rem-enc
2890 (save-excursion
2891 (with-tramp-progress-reporter
2892 v 3 (format "Encoding remote file %s" filename)
2893 (tramp-barf-unless-okay
2894 v (format rem-enc (tramp-shell-quote-argument localname))
2895 "Encoding remote file failed"))
2896
2897 (if (functionp loc-dec)
2898 ;; If local decoding is a function, we call it. We
2899 ;; must disable multibyte, because
2900 ;; `uudecode-decode-region' doesn't handle it
2901 ;; correctly.
2902 (with-temp-buffer
2903 (set-buffer-multibyte nil)
2904 (insert-buffer-substring (tramp-get-buffer v))
2905 (with-tramp-progress-reporter
2906 v 3 (format "Decoding remote file %s with function %s"
2907 filename loc-dec)
2908 (funcall loc-dec (point-min) (point-max))
2909 ;; Unset `file-name-handler-alist'. Otherwise,
2910 ;; epa-file gets confused.
2911 (let (file-name-handler-alist
2912 (coding-system-for-write 'binary))
2913 (write-region (point-min) (point-max) tmpfile))))
2914
2915 ;; If tramp-decoding-function is not defined for this
2916 ;; method, we invoke tramp-decoding-command instead.
2917 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
2918 ;; Unset `file-name-handler-alist'. Otherwise,
2919 ;; epa-file gets confused.
2920 (let (file-name-handler-alist
2921 (coding-system-for-write 'binary))
2922 (write-region (point-min) (point-max) tmpfile2))
2923 (with-tramp-progress-reporter
2924 v 3 (format "Decoding remote file %s with command %s"
2925 filename loc-dec)
2926 (unwind-protect
2927 (tramp-call-local-coding-command
2928 loc-dec tmpfile2 tmpfile)
2929 (delete-file tmpfile2)))))
2930
2931 ;; Set proper permissions.
2932 (set-file-modes tmpfile (tramp-default-file-modes filename))
2933 ;; Set local user ownership.
2934 (tramp-set-file-uid-gid tmpfile)))
2935
2936 ;; Oops, I don't know what to do.
2937 (t (tramp-error
2938 v 'file-error "Wrong method specification for `%s'" method)))
2939
2940 ;; Error handling.
2941 ((error quit)
2942 (delete-file tmpfile)
2943 (signal (car err) (cdr err))))
2944
2945 (run-hooks 'tramp-handle-file-local-copy-hook)
2946 tmpfile)))
2947
2948 ;; This is needed for XEmacs only. Code stolen from files.el.
2949 (defun tramp-sh-handle-insert-file-contents-literally
2950 (filename &optional visit beg end replace)
2951 "Like `insert-file-contents-literally' for Tramp files."
2952 (let ((format-alist nil)
2953 (after-insert-file-functions nil)
2954 (coding-system-for-read 'no-conversion)
2955 (coding-system-for-write 'no-conversion)
2956 (find-buffer-file-type-function
2957 (if (fboundp 'find-buffer-file-type)
2958 (symbol-function 'find-buffer-file-type)
2959 nil))
2960 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
2961 (inhibit-file-name-operation 'insert-file-contents))
2962 (unwind-protect
2963 (progn
2964 (fset 'find-buffer-file-type (lambda (filename) t))
2965 (insert-file-contents filename visit beg end replace))
2966 ;; Save exit.
2967 (if find-buffer-file-type-function
2968 (fset 'find-buffer-file-type find-buffer-file-type-function)
2969 (fmakunbound 'find-buffer-file-type)))))
2970
2971 (defun tramp-sh-handle-make-auto-save-file-name ()
2972 "Like `make-auto-save-file-name' for Tramp files.
2973 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
2974 (let ((tramp-auto-save-directory tramp-auto-save-directory)
2975 (buffer-file-name
2976 (tramp-subst-strs-in-string
2977 '(("_" . "|")
2978 ("/" . "_a")
2979 (":" . "_b")
2980 ("|" . "__")
2981 ("[" . "_l")
2982 ("]" . "_r"))
2983 (buffer-file-name))))
2984 ;; File name must be unique. This is ensured with Emacs 22 (see
2985 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
2986 ;; all other cases we must do it ourselves.
2987 (when (boundp 'auto-save-file-name-transforms)
2988 (mapc
2989 (lambda (x)
2990 (when (and (string-match (car x) buffer-file-name)
2991 (not (car (cddr x))))
2992 (setq tramp-auto-save-directory
2993 (or tramp-auto-save-directory
2994 (tramp-compat-temporary-file-directory)))))
2995 (symbol-value 'auto-save-file-name-transforms)))
2996 ;; Create directory.
2997 (when tramp-auto-save-directory
2998 (setq buffer-file-name
2999 (expand-file-name buffer-file-name tramp-auto-save-directory))
3000 (unless (file-exists-p tramp-auto-save-directory)
3001 (make-directory tramp-auto-save-directory t)))
3002 ;; Run plain `make-auto-save-file-name'. There might be an advice when
3003 ;; it is not a magic file name operation (since Emacs 22).
3004 ;; We must deactivate it temporarily.
3005 (if (not (ad-is-active 'make-auto-save-file-name))
3006 (tramp-run-real-handler 'make-auto-save-file-name nil)
3007 ;; else
3008 (ad-deactivate 'make-auto-save-file-name)
3009 (prog1
3010 (tramp-run-real-handler 'make-auto-save-file-name nil)
3011 (ad-activate 'make-auto-save-file-name)))))
3012
3013 ;; CCC grok LOCKNAME
3014 (defun tramp-sh-handle-write-region
3015 (start end filename &optional append visit lockname confirm)
3016 "Like `write-region' for Tramp files."
3017 (setq filename (expand-file-name filename))
3018 (with-parsed-tramp-file-name filename nil
3019 ;; Following part commented out because we don't know what to do about
3020 ;; file locking, and it does not appear to be a problem to ignore it.
3021 ;; Ange-ftp ignores it, too.
3022 ;; (when (and lockname (stringp lockname))
3023 ;; (setq lockname (expand-file-name lockname)))
3024 ;; (unless (or (eq lockname nil)
3025 ;; (string= lockname filename))
3026 ;; (error
3027 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3028
3029 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
3030 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
3031 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3032 (tramp-error v 'file-error "File not overwritten")))
3033
3034 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
3035 (tramp-get-remote-uid v 'integer)))
3036 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
3037 (tramp-get-remote-gid v 'integer))))
3038
3039 (if (and (tramp-local-host-p v)
3040 ;; `file-writable-p' calls `file-expand-file-name'. We
3041 ;; cannot use `tramp-run-real-handler' therefore.
3042 (let (file-name-handler-alist)
3043 (and
3044 (file-writable-p (file-name-directory localname))
3045 (or (file-directory-p localname)
3046 (file-writable-p localname)))))
3047 ;; Short track: if we are on the local host, we can run directly.
3048 (tramp-run-real-handler
3049 'write-region
3050 (list start end localname append 'no-message lockname confirm))
3051
3052 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3053 ;; We use this to save the value of
3054 ;; `last-coding-system-used' after writing the tmp
3055 ;; file. At the end of the function, we set
3056 ;; `last-coding-system-used' to this saved value. This
3057 ;; way, any intermediary coding systems used while
3058 ;; talking to the remote shell or suchlike won't hose
3059 ;; this variable. This approach was snarfed from
3060 ;; ange-ftp.el.
3061 coding-system-used
3062 ;; Write region into a tmp file. This isn't really
3063 ;; needed if we use an encoding function, but currently
3064 ;; we use it always because this makes the logic
3065 ;; simpler. We must also set `temporary-file-directory',
3066 ;; because it could point to a remote directory.
3067 (temporary-file-directory
3068 (tramp-compat-temporary-file-directory))
3069 (tmpfile (or tramp-temp-buffer-file-name
3070 (tramp-compat-make-temp-file filename))))
3071
3072 ;; If `append' is non-nil, we copy the file locally, and let
3073 ;; the native `write-region' implementation do the job.
3074 (when append (copy-file filename tmpfile 'ok))
3075
3076 ;; We say `no-message' here because we don't want the
3077 ;; visited file modtime data to be clobbered from the temp
3078 ;; file. We call `set-visited-file-modtime' ourselves later
3079 ;; on. We must ensure that `file-coding-system-alist'
3080 ;; matches `tmpfile'.
3081 (let (file-name-handler-alist
3082 (file-coding-system-alist
3083 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3084 (condition-case err
3085 (tramp-run-real-handler
3086 'write-region
3087 (list start end tmpfile append 'no-message lockname confirm))
3088 ((error quit)
3089 (setq tramp-temp-buffer-file-name nil)
3090 (delete-file tmpfile)
3091 (signal (car err) (cdr err))))
3092
3093 ;; Now, `last-coding-system-used' has the right value. Remember it.
3094 (when (boundp 'last-coding-system-used)
3095 (setq coding-system-used
3096 (symbol-value 'last-coding-system-used))))
3097
3098 ;; The permissions of the temporary file should be set. If
3099 ;; filename does not exist (eq modes nil) it has been
3100 ;; renamed to the backup file. This case `save-buffer'
3101 ;; handles permissions.
3102 ;; Ensure that it is still readable.
3103 (when modes
3104 (set-file-modes
3105 tmpfile
3106 (logior (or modes 0) (tramp-compat-octal-to-decimal "0400"))))
3107
3108 ;; This is a bit lengthy due to the different methods
3109 ;; possible for file transfer. First, we check whether the
3110 ;; method uses an rcp program. If so, we call it.
3111 ;; Otherwise, both encoding and decoding command must be
3112 ;; specified. However, if the method _also_ specifies an
3113 ;; encoding function, then that is used for encoding the
3114 ;; contents of the tmp file.
3115 (let* ((size (nth 7 (file-attributes tmpfile)))
3116 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3117 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3118 (cond
3119 ;; `copy-file' handles direct copy and out-of-band methods.
3120 ((or (tramp-local-host-p v)
3121 (tramp-method-out-of-band-p v size))
3122 (if (and (not (stringp start))
3123 (= (or end (point-max)) (point-max))
3124 (= (or start (point-min)) (point-min))
3125 (tramp-get-method-parameter
3126 method 'tramp-copy-keep-tmpfile))
3127 (progn
3128 (setq tramp-temp-buffer-file-name tmpfile)
3129 (condition-case err
3130 ;; We keep the local file for performance
3131 ;; reasons, useful for "rsync".
3132 (copy-file tmpfile filename t)
3133 ((error quit)
3134 (setq tramp-temp-buffer-file-name nil)
3135 (delete-file tmpfile)
3136 (signal (car err) (cdr err)))))
3137 (setq tramp-temp-buffer-file-name nil)
3138 ;; Don't rename, in order to keep context in SELinux.
3139 (unwind-protect
3140 (copy-file tmpfile filename t)
3141 (delete-file tmpfile))))
3142
3143 ;; Use inline file transfer.
3144 (rem-dec
3145 ;; Encode tmpfile.
3146 (unwind-protect
3147 (with-temp-buffer
3148 (set-buffer-multibyte nil)
3149 ;; Use encoding function or command.
3150 (if (functionp loc-enc)
3151 (with-tramp-progress-reporter
3152 v 3 (format "Encoding region using function `%s'"
3153 loc-enc)
3154 (let ((coding-system-for-read 'binary))
3155 (insert-file-contents-literally tmpfile))
3156 ;; The following `let' is a workaround for the
3157 ;; base64.el that comes with pgnus-0.84. If
3158 ;; both of the following conditions are
3159 ;; satisfied, it tries to write to a local
3160 ;; file in default-directory, but at this
3161 ;; point, default-directory is remote.
3162 ;; (`call-process-region' can't write to
3163 ;; remote files, it seems.) The file in
3164 ;; question is a tmp file anyway.
3165 (let ((default-directory
3166 (tramp-compat-temporary-file-directory)))
3167 (funcall loc-enc (point-min) (point-max))))
3168
3169 (with-tramp-progress-reporter
3170 v 3 (format "Encoding region using command `%s'"
3171 loc-enc)
3172 (unless (zerop (tramp-call-local-coding-command
3173 loc-enc tmpfile t))
3174 (tramp-error
3175 v 'file-error
3176 (concat "Cannot write to `%s', "
3177 "local encoding command `%s' failed")
3178 filename loc-enc))))
3179
3180 ;; Send buffer into remote decoding command which
3181 ;; writes to remote file. Because this happens on
3182 ;; the remote host, we cannot use the function.
3183 (with-tramp-progress-reporter
3184 v 3
3185 (format "Decoding region into remote file %s" filename)
3186 (goto-char (point-max))
3187 (unless (bolp) (newline))
3188 (tramp-send-command
3189 v
3190 (format
3191 (concat rem-dec " <<'EOF'\n%sEOF")
3192 (tramp-shell-quote-argument localname)
3193 (buffer-string)))
3194 (tramp-barf-unless-okay
3195 v nil
3196 "Couldn't write region to `%s', decode using `%s' failed"
3197 filename rem-dec)
3198 ;; When `file-precious-flag' is set, the region is
3199 ;; written to a temporary file. Check that the
3200 ;; checksum is equal to that from the local tmpfile.
3201 (when file-precious-flag
3202 (erase-buffer)
3203 (and
3204 ;; cksum runs locally, if possible.
3205 (zerop (tramp-compat-call-process "cksum" tmpfile t))
3206 ;; cksum runs remotely.
3207 (tramp-send-command-and-check
3208 v
3209 (format
3210 "cksum <%s" (tramp-shell-quote-argument localname)))
3211 ;; ... they are different.
3212 (not
3213 (string-equal
3214 (buffer-string)
3215 (with-current-buffer (tramp-get-buffer v)
3216 (buffer-string))))
3217 (tramp-error
3218 v 'file-error
3219 (concat "Couldn't write region to `%s',"
3220 " decode using `%s' failed")
3221 filename rem-dec)))))
3222
3223 ;; Save exit.
3224 (delete-file tmpfile)))
3225
3226 ;; That's not expected.
3227 (t
3228 (tramp-error
3229 v 'file-error
3230 (concat "Method `%s' should specify both encoding and "
3231 "decoding command or an rcp program")
3232 method))))
3233
3234 ;; Make `last-coding-system-used' have the right value.
3235 (when coding-system-used
3236 (set 'last-coding-system-used coding-system-used))))
3237
3238 (tramp-flush-file-property v (file-name-directory localname))
3239 (tramp-flush-file-property v localname)
3240
3241 ;; We must protect `last-coding-system-used', now we have set it
3242 ;; to its correct value.
3243 (let (last-coding-system-used (need-chown t))
3244 ;; Set file modification time.
3245 (when (or (eq visit t) (stringp visit))
3246 (let ((file-attr (tramp-compat-file-attributes filename 'integer)))
3247 (set-visited-file-modtime
3248 ;; We must pass modtime explicitly, because filename can
3249 ;; be different from (buffer-file-name), f.e. if
3250 ;; `file-precious-flag' is set.
3251 (nth 5 file-attr))
3252 (when (and (= (nth 2 file-attr) uid)
3253 (= (nth 3 file-attr) gid))
3254 (setq need-chown nil))))
3255
3256 ;; Set the ownership.
3257 (when need-chown
3258 (tramp-set-file-uid-gid filename uid gid))
3259 (when (or (eq visit t) (null visit) (stringp visit))
3260 (tramp-message v 0 "Wrote %s" filename))
3261 (run-hooks 'tramp-handle-write-region-hook)))))
3262
3263 (defvar tramp-vc-registered-file-names nil
3264 "List used to collect file names, which are checked during `vc-registered'.")
3265
3266 ;; VC backends check for the existence of various different special
3267 ;; files. This is very time consuming, because every single check
3268 ;; requires a remote command (the file cache must be invalidated).
3269 ;; Therefore, we apply a kind of optimization. We install the file
3270 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3271 ;; remembers all file names for which `file-exists-p' or
3272 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3273 ;; is performed. Afterwards, a script is applied for all collected
3274 ;; file names, using just one remote command. The result of this
3275 ;; script is used to fill the file cache with actual values. Now we
3276 ;; can reset the file name handlers, and we make a second run of
3277 ;; `vc-registered', which returns the expected result without sending
3278 ;; any other remote command.
3279 (defun tramp-sh-handle-vc-registered (file)
3280 "Like `vc-registered' for Tramp files."
3281 (tramp-compat-with-temp-message ""
3282 (with-parsed-tramp-file-name file nil
3283 (with-tramp-progress-reporter
3284 v 3 (format "Checking `vc-registered' for %s" file)
3285
3286 ;; There could be new files, created by the vc backend. We
3287 ;; cannot reuse the old cache entries, therefore.
3288 (let (tramp-vc-registered-file-names
3289 (remote-file-name-inhibit-cache (current-time))
3290 (file-name-handler-alist
3291 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3292
3293 ;; Here we collect only file names, which need an operation.
3294 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3295 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3296
3297 ;; Send just one command, in order to fill the cache.
3298 (when tramp-vc-registered-file-names
3299 (tramp-maybe-send-script
3300 v
3301 (format tramp-vc-registered-read-file-names
3302 (tramp-get-file-exists-command v)
3303 (format "%s -r" (tramp-get-test-command v)))
3304 "tramp_vc_registered_read_file_names")
3305
3306 (dolist
3307 (elt
3308 (tramp-send-command-and-read
3309 v
3310 (format
3311 "tramp_vc_registered_read_file_names <<'EOF'\n%s\nEOF\n"
3312 (mapconcat 'tramp-shell-quote-argument
3313 tramp-vc-registered-file-names
3314 "\n"))))
3315
3316 (tramp-set-file-property
3317 v (car elt) (cadr elt) (cadr (cdr elt))))))
3318
3319 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3320 ;; calls shall be answered from the file cache. We unset
3321 ;; `process-file-side-effects' in order to keep the cache when
3322 ;; `process-file' calls appear.
3323 (let (process-file-side-effects)
3324 (tramp-run-real-handler 'vc-registered (list file)))))))
3325
3326 ;;;###tramp-autoload
3327 (defun tramp-sh-file-name-handler (operation &rest args)
3328 "Invoke remote-shell Tramp file name handler.
3329 Fall back to normal file name handler if no Tramp handler exists."
3330 (when (and tramp-locked (not tramp-locker))
3331 (setq tramp-locked nil)
3332 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
3333 (let ((tl tramp-locked))
3334 (unwind-protect
3335 (progn
3336 (setq tramp-locked t)
3337 (let ((tramp-locker t))
3338 (save-match-data
3339 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3340 (if fn
3341 (apply (cdr fn) args)
3342 (tramp-run-real-handler operation args))))))
3343 (setq tramp-locked tl))))
3344
3345 (defun tramp-vc-file-name-handler (operation &rest args)
3346 "Invoke special file name handler, which collects files to be handled."
3347 (save-match-data
3348 (let ((filename
3349 (tramp-replace-environment-variables
3350 (apply 'tramp-file-name-for-operation operation args)))
3351 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3352 (with-parsed-tramp-file-name filename nil
3353 (cond
3354 ;; That's what we want: file names, for which checks are
3355 ;; applied. We assume that VC uses only `file-exists-p' and
3356 ;; `file-readable-p' checks; otherwise we must extend the
3357 ;; list. We do not perform any action, but return nil, in
3358 ;; order to keep `vc-registered' running.
3359 ((and fn (memq operation '(file-exists-p file-readable-p)))
3360 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3361 nil)
3362 ;; `process-file' and `start-file-process' shall be ignored.
3363 ((and fn (eq operation 'process-file) 0))
3364 ((and fn (eq operation 'start-file-process) nil))
3365 ;; Tramp file name handlers like `expand-file-name'. They
3366 ;; must still work.
3367 (fn (save-match-data (apply (cdr fn) args)))
3368 ;; Default file name handlers, we don't care.
3369 (t (tramp-run-real-handler operation args)))))))
3370
3371 ;;; Internal Functions:
3372
3373 (defun tramp-maybe-send-script (vec script name)
3374 "Define in remote shell function NAME implemented as SCRIPT.
3375 Only send the definition if it has not already been done."
3376 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3377 ;; might be nil.
3378 (let ((scripts (tramp-get-connection-property
3379 (tramp-get-connection-process vec) "scripts" nil)))
3380 (unless (member name scripts)
3381 (with-tramp-progress-reporter vec 5 (format "Sending script `%s'" name)
3382 ;; The script could contain a call of Perl. This is masked with `%s'.
3383 (tramp-barf-unless-okay
3384 vec
3385 (format "%s () {\n%s\n}" name
3386 (format script (tramp-get-remote-perl vec)))
3387 "Script %s sending failed" name)
3388 (tramp-set-connection-property
3389 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3390
3391 (defun tramp-set-auto-save ()
3392 (when (and ;; ange-ftp has its own auto-save mechanism
3393 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
3394 'tramp-sh-file-name-handler)
3395 auto-save-default)
3396 (auto-save-mode 1)))
3397 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
3398 (add-hook 'tramp-unload-hook
3399 (lambda ()
3400 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
3401
3402 (defun tramp-run-test (switch filename)
3403 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3404 Returns the exit code of the `test' program."
3405 (with-parsed-tramp-file-name filename nil
3406 (tramp-send-command-and-check
3407 v
3408 (format
3409 "%s %s %s"
3410 (tramp-get-test-command v)
3411 switch
3412 (tramp-shell-quote-argument localname)))))
3413
3414 (defun tramp-run-test2 (format-string file1 file2)
3415 "Run `test'-like program on the remote system, given FILE1, FILE2.
3416 FORMAT-STRING contains the program name, switches, and place holders.
3417 Returns the exit code of the `test' program. Barfs if the methods,
3418 hosts, or files, disagree."
3419 (unless (tramp-equal-remote file1 file2)
3420 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3421 (tramp-error
3422 v 'file-error
3423 "tramp-run-test2 only implemented for same method, user, host")))
3424 (with-parsed-tramp-file-name file1 v1
3425 (with-parsed-tramp-file-name file1 v2
3426 (tramp-send-command-and-check
3427 v1
3428 (format format-string
3429 (tramp-shell-quote-argument v1-localname)
3430 (tramp-shell-quote-argument v2-localname))))))
3431
3432 (defun tramp-find-executable
3433 (vec progname dirlist &optional ignore-tilde ignore-path)
3434 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3435 First arg VEC specifies the connection, PROGNAME is the program
3436 to search for, and DIRLIST gives the list of directories to
3437 search. If IGNORE-TILDE is non-nil, directory names starting
3438 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3439 only in DIRLIST.
3440
3441 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3442
3443 This function expects to be in the right *tramp* buffer."
3444 (with-current-buffer (tramp-get-connection-buffer vec)
3445 (let (result)
3446 ;; Check whether the executable is in $PATH. "which(1)" does not
3447 ;; report always a correct error code; therefore we check the
3448 ;; number of words it returns.
3449 (unless ignore-path
3450 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3451 (goto-char (point-min))
3452 (if (looking-at "^\\s-*1$")
3453 (setq result (concat "\\" progname))))
3454 (unless result
3455 (when ignore-tilde
3456 ;; Remove all ~/foo directories from dirlist. In XEmacs,
3457 ;; `remove' is in CL, and we want to avoid CL dependencies.
3458 (let (newdl d)
3459 (while dirlist
3460 (setq d (car dirlist))
3461 (setq dirlist (cdr dirlist))
3462 (unless (char-equal ?~ (aref d 0))
3463 (setq newdl (cons d newdl))))
3464 (setq dirlist (nreverse newdl))))
3465 (tramp-send-command
3466 vec
3467 (format (concat "while read d; "
3468 "do if test -x $d/%s -a -f $d/%s; "
3469 "then echo tramp_executable $d/%s; "
3470 "break; fi; done <<'EOF'\n"
3471 "%s\nEOF")
3472 progname progname progname (mapconcat 'identity dirlist "\n")))
3473 (goto-char (point-max))
3474 (when (search-backward "tramp_executable " nil t)
3475 (skip-chars-forward "^ ")
3476 (skip-chars-forward " ")
3477 (setq result (buffer-substring (point) (point-at-eol)))))
3478 result)))
3479
3480 (defun tramp-set-remote-path (vec)
3481 "Sets the remote environment PATH to existing directories.
3482 I.e., for each directory in `tramp-remote-path', it is tested
3483 whether it exists and if so, it is added to the environment
3484 variable PATH."
3485 (tramp-message vec 5 (format "Setting $PATH environment variable"))
3486 (tramp-send-command
3487 vec (format "PATH=%s; export PATH"
3488 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3489
3490 ;; ------------------------------------------------------------
3491 ;; -- Communication with external shell --
3492 ;; ------------------------------------------------------------
3493
3494 (defun tramp-find-file-exists-command (vec)
3495 "Find a command on the remote host for checking if a file exists.
3496 Here, we are looking for a command which has zero exit status if the
3497 file exists and nonzero exit status otherwise."
3498 (let ((existing "/")
3499 (nonexistent
3500 (tramp-shell-quote-argument "/ this file does not exist "))
3501 result)
3502 ;; The algorithm is as follows: we try a list of several commands.
3503 ;; For each command, we first run `$cmd /' -- this should return
3504 ;; true, as the root directory always exists. And then we run
3505 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3506 ;; does not exist. This should return false. We use the first
3507 ;; command we find that seems to work.
3508 ;; The list of commands to try is as follows:
3509 ;; `ls -d' This works on most systems, but NetBSD 1.4
3510 ;; has a bug: `ls' always returns zero exit
3511 ;; status, even for files which don't exist.
3512 ;; `test -e' Some Bourne shells have a `test' builtin
3513 ;; which does not know the `-e' option.
3514 ;; `/bin/test -e' For those, the `test' binary on disk normally
3515 ;; provides the option. Alas, the binary
3516 ;; is sometimes `/bin/test' and sometimes it's
3517 ;; `/usr/bin/test'.
3518 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3519 (unless (or
3520 (ignore-errors
3521 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3522 (tramp-send-command-and-check
3523 vec (format "%s %s" result existing))
3524 (not (tramp-send-command-and-check
3525 vec (format "%s %s" result nonexistent)))))
3526 (ignore-errors
3527 (and (setq result "/bin/test -e")
3528 (tramp-send-command-and-check
3529 vec (format "%s %s" result existing))
3530 (not (tramp-send-command-and-check
3531 vec (format "%s %s" result nonexistent)))))
3532 (ignore-errors
3533 (and (setq result "/usr/bin/test -e")
3534 (tramp-send-command-and-check
3535 vec (format "%s %s" result existing))
3536 (not (tramp-send-command-and-check
3537 vec (format "%s %s" result nonexistent)))))
3538 (ignore-errors
3539 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3540 (tramp-send-command-and-check
3541 vec (format "%s %s" result existing))
3542 (not (tramp-send-command-and-check
3543 vec (format "%s %s" result nonexistent))))))
3544 (tramp-error
3545 vec 'file-error "Couldn't find command to check if file exists"))
3546 result))
3547
3548 (defun tramp-open-shell (vec shell)
3549 "Opens shell SHELL."
3550 (with-tramp-progress-reporter
3551 vec 5 (format "Opening remote shell `%s'" shell)
3552 ;; Find arguments for this shell.
3553 (let ((tramp-end-of-output tramp-initial-end-of-output)
3554 (alist tramp-sh-extra-args)
3555 item extra-args)
3556 (while (and alist (null extra-args))
3557 (setq item (pop alist))
3558 (when (string-match (car item) shell)
3559 (setq extra-args (cdr item))))
3560 (tramp-send-command
3561 vec (format
3562 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3563 (tramp-shell-quote-argument tramp-end-of-output)
3564 shell (or extra-args ""))
3565 t))
3566 (tramp-set-connection-property
3567 (tramp-get-connection-process vec) "remote-shell" shell)
3568 ;; Setting prompts.
3569 (tramp-send-command
3570 vec (format "PS1=%s" (tramp-shell-quote-argument tramp-end-of-output)) t)
3571 (tramp-send-command vec "PS2=''" t)
3572 (tramp-send-command vec "PS3=''" t)
3573 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
3574
3575 (defun tramp-find-shell (vec)
3576 "Opens a shell on the remote host which groks tilde expansion."
3577 (with-current-buffer (tramp-get-buffer vec)
3578 (let ((default-shell
3579 (or
3580 (tramp-get-connection-property
3581 (tramp-get-connection-process vec) "remote-shell" nil)
3582 (tramp-get-method-parameter
3583 (tramp-file-name-method vec) 'tramp-remote-shell)))
3584 shell)
3585 (setq shell
3586 (with-tramp-connection-property vec "remote-shell"
3587 ;; CCC: "root" does not exist always, see QNAP 459.
3588 ;; Which check could we apply instead?
3589 (tramp-send-command vec "echo ~root" t)
3590 (if (or (string-match "^~root$" (buffer-string))
3591 ;; The default shell (ksh93) of OpenSolaris and
3592 ;; Solaris is buggy. We've got reports for
3593 ;; "SunOS 5.10" and "SunOS 5.11" so far.
3594 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3595 (tramp-get-connection-property
3596 vec "uname" "")))
3597
3598 (or (tramp-find-executable
3599 vec "bash" (tramp-get-remote-path vec) t t)
3600 (tramp-find-executable
3601 vec "ksh" (tramp-get-remote-path vec) t t)
3602 ;; Maybe it works at least for some other commands.
3603 (prog1
3604 default-shell
3605 (tramp-message
3606 vec 2
3607 (concat
3608 "Couldn't find a remote shell which groks tilde "
3609 "expansion, using `%s'")
3610 default-shell)))
3611
3612 default-shell)))
3613
3614 ;; Open a new shell if needed.
3615 (unless (string-equal shell default-shell)
3616 (tramp-message
3617 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
3618 (tramp-open-shell vec shell))
3619
3620 ;; Busyboxes tend to behave strange. We check for the existence.
3621 (with-tramp-connection-property vec "busybox"
3622 (tramp-send-command vec (format "%s --version" shell) t)
3623 (let ((case-fold-search t))
3624 (and (string-match "busybox" (buffer-string)) t))))))
3625
3626 ;; Utility functions.
3627
3628 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
3629 "Wait for shell prompt and barf if none appears.
3630 Looks at process PROC to see if a shell prompt appears in TIMEOUT
3631 seconds. If not, it produces an error message with the given ERROR-ARGS."
3632 (unless
3633 (tramp-wait-for-regexp
3634 proc timeout
3635 (format
3636 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
3637 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
3638
3639 (defun tramp-open-connection-setup-interactive-shell (proc vec)
3640 "Set up an interactive shell.
3641 Mainly sets the prompt and the echo correctly. PROC is the shell
3642 process to set up. VEC specifies the connection."
3643 (let ((tramp-end-of-output tramp-initial-end-of-output))
3644 ;; It is useful to set the prompt in the following command because
3645 ;; some people have a setting for $PS1 which /bin/sh doesn't know
3646 ;; about and thus /bin/sh will display a strange prompt. For
3647 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
3648 ;; display the current working directory but /bin/sh will display
3649 ;; a dollar sign. The following command line sets $PS1 to a sane
3650 ;; value, and works under Bourne-ish shells as well as csh-like
3651 ;; shells. Daniel Pittman reports that the unusual positioning of
3652 ;; the single quotes makes it work under `rc', too. We also unset
3653 ;; the variable $ENV because that is read by some sh
3654 ;; implementations (eg, bash when called as sh) on startup; this
3655 ;; way, we avoid the startup file clobbering $PS1. $PROMPT_COMMAND
3656 ;; is another way to set the prompt in /bin/bash, it must be
3657 ;; discarded as well.
3658 (tramp-open-shell
3659 vec
3660 (or (tramp-get-connection-property vec "remote-shell" nil)
3661 (tramp-get-method-parameter
3662 (tramp-file-name-method vec) 'tramp-remote-shell)))
3663
3664 ;; Disable echo.
3665 (tramp-message vec 5 "Setting up remote shell environment")
3666 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
3667 ;; Check whether the echo has really been disabled. Some
3668 ;; implementations, like busybox of embedded GNU/Linux, don't
3669 ;; support disabling.
3670 (tramp-send-command vec "echo foo" t)
3671 (with-current-buffer (process-buffer proc)
3672 (goto-char (point-min))
3673 (when (looking-at "echo foo")
3674 (tramp-set-connection-property proc "remote-echo" t)
3675 (tramp-message vec 5 "Remote echo still on. Ok.")
3676 ;; Make sure backspaces and their echo are enabled and no line
3677 ;; width magic interferes with them.
3678 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
3679
3680 (tramp-message vec 5 "Setting shell prompt")
3681 (tramp-send-command
3682 vec (format "PS1=%s" (tramp-shell-quote-argument tramp-end-of-output)) t)
3683 (tramp-send-command vec "PS2=''" t)
3684 (tramp-send-command vec "PS3=''" t)
3685 (tramp-send-command vec "PROMPT_COMMAND=''" t)
3686
3687 ;; Try to set up the coding system correctly.
3688 ;; CCC this can't be the right way to do it. Hm.
3689 (tramp-message vec 5 "Determining coding system")
3690 (tramp-send-command vec "echo foo ; echo bar" t)
3691 (with-current-buffer (process-buffer proc)
3692 (goto-char (point-min))
3693 (if (featurep 'mule)
3694 ;; Use MULE to select the right EOL convention for communicating
3695 ;; with the process.
3696 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
3697 (cons 'undecided 'undecided)))
3698 cs-decode cs-encode)
3699 (when (symbolp cs) (setq cs (cons cs cs)))
3700 (setq cs-decode (car cs))
3701 (setq cs-encode (cdr cs))
3702 (unless cs-decode (setq cs-decode 'undecided))
3703 (unless cs-encode (setq cs-encode 'undecided))
3704 (setq cs-encode (tramp-compat-coding-system-change-eol-conversion
3705 cs-encode 'unix))
3706 (when (search-forward "\r" nil t)
3707 (setq cs-decode (tramp-compat-coding-system-change-eol-conversion
3708 cs-decode 'dos)))
3709 (tramp-compat-funcall
3710 'set-buffer-process-coding-system cs-decode cs-encode)
3711 (tramp-message
3712 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
3713 ;; Look for ^M and do something useful if found.
3714 (when (search-forward "\r" nil t)
3715 ;; We have found a ^M but cannot frob the process coding system
3716 ;; because we're running on a non-MULE Emacs. Let's try
3717 ;; stty, instead.
3718 (tramp-send-command vec "stty -onlcr" t))))
3719
3720 (tramp-send-command vec "set +o vi +o emacs" t)
3721
3722 ;; Check whether the output of "uname -sr" has been changed. If
3723 ;; yes, this is a strong indication that we must expire all
3724 ;; connection properties. We start again with
3725 ;; `tramp-maybe-open-connection', it will be caught there.
3726 (tramp-message vec 5 "Checking system information")
3727 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
3728 (new-uname
3729 (tramp-set-connection-property
3730 vec "uname"
3731 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
3732 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
3733 (tramp-cleanup vec)
3734 (tramp-message
3735 vec 3
3736 "Connection reset, because remote host changed from `%s' to `%s'"
3737 old-uname new-uname)
3738 (throw 'uname-changed (tramp-maybe-open-connection vec))))
3739
3740 ;; Check whether the remote host suffers from buggy
3741 ;; `send-process-string'. This is known for FreeBSD (see comment in
3742 ;; `send_process', file process.c). I've tested sending 624 bytes
3743 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
3744 ;; this host type is detected locally. It cannot handle remote
3745 ;; hosts, though.
3746 (with-tramp-connection-property proc "chunksize"
3747 (cond
3748 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
3749 tramp-chunksize)
3750 (t
3751 (tramp-message
3752 vec 5 "Checking remote host type for `send-process-string' bug")
3753 (if (string-match
3754 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
3755 500 0))))
3756
3757 ;; Set remote PATH variable.
3758 (tramp-set-remote-path vec)
3759
3760 ;; Search for a good shell before searching for a command which
3761 ;; checks if a file exists. This is done because Tramp wants to use
3762 ;; "test foo; echo $?" to check if various conditions hold, and
3763 ;; there are buggy /bin/sh implementations which don't execute the
3764 ;; "echo $?" part if the "test" part has an error. In particular,
3765 ;; the OpenSolaris /bin/sh is a problem. There are also other
3766 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
3767 ;; in function declarations, or changing HISTFILE in place.
3768 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
3769 ;; detected.
3770 (tramp-find-shell vec)
3771
3772 ;; Disable unexpected output.
3773 (tramp-send-command vec "mesg n; biff n" t)
3774
3775 ;; IRIX64 bash expands "!" even when in single quotes. This
3776 ;; destroys our shell functions, we must disable it. See
3777 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
3778 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
3779 (tramp-send-command vec "set +H" t))
3780
3781 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
3782 (when (string-match "BSD\\|Darwin"
3783 (tramp-get-connection-property vec "uname" ""))
3784 (tramp-send-command vec "stty -oxtabs" t))
3785
3786 ;; Set `remote-tty' process property.
3787 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
3788 (unless (zerop (length tty))
3789 (tramp-compat-process-put proc 'remote-tty tty)))
3790
3791 ;; Dump stty settings in the traces.
3792 (when (>= tramp-verbose 9)
3793 (tramp-send-command vec "stty -a" t))
3794
3795 ;; Set the environment.
3796 (tramp-message vec 5 "Setting default environment")
3797
3798 (let ((env (copy-sequence tramp-remote-process-environment))
3799 unset item)
3800 (while env
3801 (setq item (tramp-compat-split-string (car env) "="))
3802 (setcdr item (mapconcat 'identity (cdr item) "="))
3803 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
3804 (tramp-send-command
3805 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
3806 (push (car item) unset))
3807 (setq env (cdr env)))
3808 (when unset
3809 (tramp-send-command
3810 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
3811
3812 ;; CCC: We should either implement a Perl version of base64 encoding
3813 ;; and decoding. Then we just use that in the last item. The other
3814 ;; alternative is to use the Perl version of UU encoding. But then
3815 ;; we need a Lisp version of uuencode.
3816 ;;
3817 ;; Old text from documentation of tramp-methods:
3818 ;; Using a uuencode/uudecode inline method is discouraged, please use one
3819 ;; of the base64 methods instead since base64 encoding is much more
3820 ;; reliable and the commands are more standardized between the different
3821 ;; Unix versions. But if you can't use base64 for some reason, please
3822 ;; note that the default uudecode command does not work well for some
3823 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
3824 ;; the following command for uudecode:
3825 ;;
3826 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
3827 ;;
3828 ;; For Irix, no solution is known yet.
3829
3830 (autoload 'uudecode-decode-region "uudecode")
3831
3832 (defconst tramp-local-coding-commands
3833 '((b64 base64-encode-region base64-decode-region)
3834 (uu tramp-uuencode-region uudecode-decode-region)
3835 (pack
3836 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
3837 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
3838 "List of local coding commands for inline transfer.
3839 Each item is a list that looks like this:
3840
3841 \(FORMAT ENCODING DECODING\)
3842
3843 FORMAT is symbol describing the encoding/decoding format. It can be
3844 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
3845
3846 ENCODING and DECODING can be strings, giving commands, or symbols,
3847 giving functions. If they are strings, then they can contain
3848 the \"%s\" format specifier. If that specifier is present, the input
3849 filename will be put into the command line at that spot. If the
3850 specifier is not present, the input should be read from standard
3851 input.
3852
3853 If they are functions, they will be called with two arguments, start
3854 and end of region, and are expected to replace the region contents
3855 with the encoded or decoded results, respectively.")
3856
3857 (defconst tramp-remote-coding-commands
3858 '((b64 "base64" "base64 -d -i")
3859 ;; "-i" is more robust with older base64 from GNU coreutils.
3860 ;; However, I don't know whether all base64 versions do supports
3861 ;; this option.
3862 (b64 "base64" "base64 -d")
3863 (b64 "mimencode -b" "mimencode -u -b")
3864 (b64 "mmencode -b" "mmencode -u -b")
3865 (b64 "recode data..base64" "recode base64..data")
3866 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
3867 (b64 tramp-perl-encode tramp-perl-decode)
3868 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
3869 (uu "uuencode xxx" "uudecode -o -")
3870 (uu "uuencode xxx" "uudecode -p")
3871 (uu "uuencode xxx" tramp-uudecode)
3872 (pack
3873 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
3874 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
3875 "List of remote coding commands for inline transfer.
3876 Each item is a list that looks like this:
3877
3878 \(FORMAT ENCODING DECODING [TEST]\)
3879
3880 FORMAT is symbol describing the encoding/decoding format. It can be
3881 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
3882
3883 ENCODING and DECODING can be strings, giving commands, or symbols,
3884 giving variables. If they are strings, then they can contain
3885 the \"%s\" format specifier. If that specifier is present, the input
3886 filename will be put into the command line at that spot. If the
3887 specifier is not present, the input should be read from standard
3888 input.
3889
3890 If they are variables, this variable is a string containing a Perl
3891 implementation for this functionality. This Perl program will be transferred
3892 to the remote host, and it is available as shell function with the same name.
3893
3894 The optional TEST command can be used for further tests, whether
3895 ENCODING and DECODING are applicable.")
3896
3897 (defun tramp-find-inline-encoding (vec)
3898 "Find an inline transfer encoding that works.
3899 Goes through the list `tramp-local-coding-commands' and
3900 `tramp-remote-coding-commands'."
3901 (save-excursion
3902 (let ((local-commands tramp-local-coding-commands)
3903 (magic "xyzzy")
3904 (p (tramp-get-connection-process vec))
3905 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
3906 (while (and local-commands (not found))
3907 (setq litem (pop local-commands))
3908 (catch 'wont-work-local
3909 (let ((format (nth 0 litem))
3910 (remote-commands tramp-remote-coding-commands))
3911 (setq loc-enc (nth 1 litem))
3912 (setq loc-dec (nth 2 litem))
3913 ;; If the local encoder or decoder is a string, the
3914 ;; corresponding command has to work locally.
3915 (if (not (stringp loc-enc))
3916 (tramp-message
3917 vec 5 "Checking local encoding function `%s'" loc-enc)
3918 (tramp-message
3919 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
3920 (unless (zerop (tramp-call-local-coding-command
3921 loc-enc nil nil))
3922 (throw 'wont-work-local nil)))
3923 (if (not (stringp loc-dec))
3924 (tramp-message
3925 vec 5 "Checking local decoding function `%s'" loc-dec)
3926 (tramp-message
3927 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
3928 (unless (zerop (tramp-call-local-coding-command
3929 loc-dec nil nil))
3930 (throw 'wont-work-local nil)))
3931 ;; Search for remote coding commands with the same format
3932 (while (and remote-commands (not found))
3933 (setq ritem (pop remote-commands))
3934 (catch 'wont-work-remote
3935 (when (equal format (nth 0 ritem))
3936 (setq rem-enc (nth 1 ritem))
3937 (setq rem-dec (nth 2 ritem))
3938 (setq rem-test (nth 3 ritem))
3939 ;; Check the remote test command if exists.
3940 (when (stringp rem-test)
3941 (tramp-message
3942 vec 5 "Checking remote test command `%s'" rem-test)
3943 (unless (tramp-send-command-and-check vec rem-test t)
3944 (throw 'wont-work-remote nil)))
3945 ;; Check if remote encoding and decoding commands can be
3946 ;; called remotely with null input and output. This makes
3947 ;; sure there are no syntax errors and the command is really
3948 ;; found. Note that we do not redirect stdout to /dev/null,
3949 ;; for two reasons: when checking the decoding command, we
3950 ;; actually check the output it gives. And also, when
3951 ;; redirecting "mimencode" output to /dev/null, then as root
3952 ;; it might change the permissions of /dev/null!
3953 (when (not (stringp rem-enc))
3954 (let ((name (symbol-name rem-enc)))
3955 (while (string-match (regexp-quote "-") name)
3956 (setq name (replace-match "_" nil t name)))
3957 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
3958 (setq rem-enc name)))
3959 (tramp-message
3960 vec 5
3961 "Checking remote encoding command `%s' for sanity" rem-enc)
3962 (unless (tramp-send-command-and-check
3963 vec (format "%s </dev/null" rem-enc) t)
3964 (throw 'wont-work-remote nil))
3965
3966 (when (not (stringp rem-dec))
3967 (let ((name (symbol-name rem-dec)))
3968 (while (string-match (regexp-quote "-") name)
3969 (setq name (replace-match "_" nil t name)))
3970 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
3971 (setq rem-dec name)))
3972 (tramp-message
3973 vec 5
3974 "Checking remote decoding command `%s' for sanity" rem-dec)
3975 (unless (tramp-send-command-and-check
3976 vec
3977 (format "echo %s | %s | %s" magic rem-enc rem-dec)
3978 t)
3979 (throw 'wont-work-remote nil))
3980
3981 (with-current-buffer (tramp-get-buffer vec)
3982 (goto-char (point-min))
3983 (unless (looking-at (regexp-quote magic))
3984 (throw 'wont-work-remote nil)))
3985
3986 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
3987 (setq rem-enc (nth 1 ritem))
3988 (setq rem-dec (nth 2 ritem))
3989 (setq found t)))))))
3990
3991 ;; Did we find something?
3992 (unless found
3993 (tramp-error
3994 vec 'file-error "Couldn't find an inline transfer encoding"))
3995
3996 ;; Set connection properties. Since the commands are risky (due
3997 ;; to output direction), we cache them in the process cache.
3998 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
3999 (tramp-set-connection-property p "local-encoding" loc-enc)
4000 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4001 (tramp-set-connection-property p "local-decoding" loc-dec)
4002 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4003 (tramp-set-connection-property p "remote-encoding" rem-enc)
4004 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4005 (tramp-set-connection-property p "remote-decoding" rem-dec))))
4006
4007 (defun tramp-call-local-coding-command (cmd input output)
4008 "Call the local encoding or decoding command.
4009 If CMD contains \"%s\", provide input file INPUT there in command.
4010 Otherwise, INPUT is passed via standard input.
4011 INPUT can also be nil which means `/dev/null'.
4012 OUTPUT can be a string (which specifies a filename), or t (which
4013 means standard output and thus the current buffer), or nil (which
4014 means discard it)."
4015 (tramp-compat-call-process
4016 tramp-encoding-shell
4017 (when (and input (not (string-match "%s" cmd))) input)
4018 (if (eq output t) t nil)
4019 nil
4020 tramp-encoding-command-switch
4021 (concat
4022 (if (string-match "%s" cmd) (format cmd input) cmd)
4023 (if (stringp output) (concat "> " output) ""))))
4024
4025 (defconst tramp-inline-compress-commands
4026 '(("gzip" "gzip -d")
4027 ("bzip2" "bzip2 -d")
4028 ("xz" "xz -d")
4029 ("compress" "compress -d"))
4030 "List of compress and decompress commands for inline transfer.
4031 Each item is a list that looks like this:
4032
4033 \(COMPRESS DECOMPRESS\)
4034
4035 COMPRESS or DECOMPRESS are strings with the respective commands.")
4036
4037 (defun tramp-find-inline-compress (vec)
4038 "Find an inline transfer compress command that works.
4039 Goes through the list `tramp-inline-compress-commands'."
4040 (save-excursion
4041 (let ((commands tramp-inline-compress-commands)
4042 (magic "xyzzy")
4043 (p (tramp-get-connection-process vec))
4044 item compress decompress found)
4045 (while (and commands (not found))
4046 (catch 'next
4047 (setq item (pop commands)
4048 compress (nth 0 item)
4049 decompress (nth 1 item))
4050 (tramp-message
4051 vec 5
4052 "Checking local compress command `%s', `%s' for sanity"
4053 compress decompress)
4054 (unless
4055 (zerop
4056 (tramp-call-local-coding-command
4057 (format
4058 ;; Windows shells need the program file name after
4059 ;; the pipe symbol be quoted if they use forward
4060 ;; slashes as directory separators.
4061 (if (memq system-type '(windows-nt))
4062 "echo %s | \"%s\" | \"%s\""
4063 "echo %s | %s | %s")
4064 magic compress decompress) nil nil))
4065 (throw 'next nil))
4066 (tramp-message
4067 vec 5
4068 "Checking remote compress command `%s', `%s' for sanity"
4069 compress decompress)
4070 (unless (tramp-send-command-and-check
4071 vec (format "echo %s | %s | %s" magic compress decompress) t)
4072 (throw 'next nil))
4073 (setq found t)))
4074
4075 ;; Did we find something?
4076 (if found
4077 (progn
4078 ;; Set connection properties. Since the commands are
4079 ;; risky (due to output direction), we cache them in the
4080 ;; process cache.
4081 (tramp-message
4082 vec 5 "Using inline transfer compress command `%s'" compress)
4083 (tramp-set-connection-property p "inline-compress" compress)
4084 (tramp-message
4085 vec 5 "Using inline transfer decompress command `%s'" decompress)
4086 (tramp-set-connection-property p "inline-decompress" decompress))
4087
4088 (tramp-set-connection-property p "inline-compress" nil)
4089 (tramp-set-connection-property p "inline-decompress" nil)
4090 (tramp-message
4091 vec 2 "Couldn't find an inline transfer compress command")))))
4092
4093 (defvar tramp-gw-tunnel-method)
4094 (defvar tramp-gw-socks-method)
4095
4096 (defun tramp-compute-multi-hops (vec)
4097 "Expands VEC according to `tramp-default-proxies-alist'.
4098 Gateway hops are already opened."
4099 (let ((target-alist `(,vec))
4100 (hops (or (tramp-file-name-hop vec) ""))
4101 (item vec)
4102 choices proxy)
4103
4104 ;; Ad-hoc proxy definitions.
4105 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4106 (let ((user (tramp-file-name-user item))
4107 (host (tramp-file-name-host item))
4108 (proxy (concat
4109 tramp-prefix-format proxy tramp-postfix-host-format)))
4110 (tramp-message
4111 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4112 (and (stringp host) (regexp-quote host))
4113 (and (stringp user) (regexp-quote user))
4114 proxy)
4115 ;; Add the hop.
4116 (add-to-list
4117 'tramp-default-proxies-alist
4118 (list (and (stringp host) (regexp-quote host))
4119 (and (stringp user) (regexp-quote user))
4120 proxy))
4121 (setq item (tramp-dissect-file-name proxy))))
4122 ;; Save the new value.
4123 (when (and hops tramp-save-ad-hoc-proxies)
4124 (customize-save-variable
4125 'tramp-default-proxies-alist tramp-default-proxies-alist))
4126
4127 ;; Look for proxy hosts to be passed.
4128 (setq choices tramp-default-proxies-alist)
4129 (while choices
4130 (setq item (pop choices)
4131 proxy (eval (nth 2 item)))
4132 (when (and
4133 ;; Host.
4134 (string-match (or (eval (nth 0 item)) "")
4135 (or (tramp-file-name-host (car target-alist)) ""))
4136 ;; User.
4137 (string-match (or (eval (nth 1 item)) "")
4138 (or (tramp-file-name-user (car target-alist)) "")))
4139 (if (null proxy)
4140 ;; No more hops needed.
4141 (setq choices nil)
4142 ;; Replace placeholders.
4143 (setq proxy
4144 (format-spec
4145 proxy
4146 (format-spec-make
4147 ?u (or (tramp-file-name-user (car target-alist)) "")
4148 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4149 (with-parsed-tramp-file-name proxy l
4150 ;; Add the hop.
4151 (add-to-list 'target-alist l)
4152 ;; Start next search.
4153 (setq choices tramp-default-proxies-alist)))))
4154
4155 ;; Handle gateways.
4156 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4157 (string-match
4158 (format
4159 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4160 (tramp-file-name-method (car target-alist))))
4161 (let ((gw (pop target-alist))
4162 (hop (pop target-alist)))
4163 ;; Is the method prepared for gateways?
4164 (unless (tramp-file-name-port hop)
4165 (tramp-error
4166 vec 'file-error
4167 "Connection `%s' is not supported for gateway access." hop))
4168 ;; Open the gateway connection.
4169 (add-to-list
4170 'target-alist
4171 (vector
4172 (tramp-file-name-method hop) (tramp-file-name-user hop)
4173 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil nil))
4174 ;; For the password prompt, we need the correct values.
4175 ;; Therefore, we must remember the gateway vector. But we
4176 ;; cannot do it as connection property, because it shouldn't
4177 ;; be persistent. And we have no started process yet either.
4178 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
4179
4180 ;; Foreign and out-of-band methods are not supported for multi-hops.
4181 (when (cdr target-alist)
4182 (setq choices target-alist)
4183 (while choices
4184 (setq item (pop choices))
4185 (when
4186 (or
4187 (not
4188 (tramp-get-method-parameter
4189 (tramp-file-name-method item) 'tramp-login-program))
4190 (tramp-get-method-parameter
4191 (tramp-file-name-method item) 'tramp-copy-program))
4192 (tramp-error
4193 vec 'file-error
4194 "Method `%s' is not supported for multi-hops."
4195 (tramp-file-name-method item)))))
4196
4197 ;; In case the host name is not used for the remote shell
4198 ;; command, the user could be misguided by applying a random
4199 ;; hostname.
4200 (let* ((v (car target-alist))
4201 (method (tramp-file-name-method v))
4202 (host (tramp-file-name-host v)))
4203 (unless
4204 (or
4205 ;; There are multi-hops.
4206 (cdr target-alist)
4207 ;; The host name is used for the remote shell command.
4208 (member
4209 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
4210 ;; The host is local. We cannot use `tramp-local-host-p'
4211 ;; here, because it opens a connection as well.
4212 (string-match tramp-local-host-regexp host))
4213 (tramp-error
4214 v 'file-error
4215 "Host `%s' looks like a remote host, `%s' can only use the local host"
4216 host method)))
4217
4218 ;; Result.
4219 target-alist))
4220
4221 (defvar tramp-current-connection nil
4222 "Last connection timestamp.")
4223
4224 (defun tramp-maybe-open-connection (vec)
4225 "Maybe open a connection VEC.
4226 Does not do anything if a connection is already open, but re-opens the
4227 connection if a previous connection has died for some reason."
4228 (catch 'uname-changed
4229 (let ((p (tramp-get-connection-process vec))
4230 (process-name (tramp-get-connection-property vec "process-name" nil))
4231 (process-environment (copy-sequence process-environment))
4232 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4233
4234 ;; If Tramp opens the same connection within a short time frame,
4235 ;; there is a problem. We shall signal this.
4236 (unless (or (and p (processp p) (memq (process-status p) '(run open)))
4237 (not (equal (butlast (append vec nil))
4238 (car tramp-current-connection)))
4239 (> (tramp-time-diff
4240 (current-time) (cdr tramp-current-connection))
4241 (or tramp-connection-min-time-diff 0)))
4242 (throw 'suppress 'suppress))
4243
4244 ;; If too much time has passed since last command was sent, look
4245 ;; whether process is still alive. If it isn't, kill it. When
4246 ;; using ssh, it can sometimes happen that the remote end has
4247 ;; hung up but the local ssh client doesn't recognize this until
4248 ;; it tries to send some data to the remote end. So that's why
4249 ;; we try to send a command from time to time, then look again
4250 ;; whether the process is really alive.
4251 (condition-case nil
4252 (when (and (> (tramp-time-diff
4253 (current-time)
4254 (tramp-get-connection-property
4255 p "last-cmd-time" '(0 0 0)))
4256 60)
4257 p (processp p) (memq (process-status p) '(run open)))
4258 (tramp-send-command vec "echo are you awake" t t)
4259 (unless (and (memq (process-status p) '(run open))
4260 (tramp-wait-for-output p 10))
4261 ;; The error will be caught locally.
4262 (tramp-error vec 'file-error "Awake did fail")))
4263 (file-error
4264 (tramp-cleanup vec)
4265 (setq p nil)))
4266
4267 ;; New connection must be opened.
4268 (condition-case err
4269 (unless (and p (processp p) (memq (process-status p) '(run open)))
4270
4271 ;; We call `tramp-get-buffer' in order to get a debug
4272 ;; buffer for messages from the beginning.
4273 (tramp-get-buffer vec)
4274
4275 ;; If `non-essential' is non-nil, don't reopen a new connection.
4276 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4277 (throw 'non-essential 'non-essential))
4278
4279 (with-tramp-progress-reporter
4280 vec 3
4281 (if (zerop (length (tramp-file-name-user vec)))
4282 (format "Opening connection for %s using %s"
4283 (tramp-file-name-host vec)
4284 (tramp-file-name-method vec))
4285 (format "Opening connection for %s@%s using %s"
4286 (tramp-file-name-user vec)
4287 (tramp-file-name-host vec)
4288 (tramp-file-name-method vec)))
4289
4290 ;; Start new process.
4291 (when (and p (processp p))
4292 (delete-process p))
4293 (setenv "TERM" tramp-terminal-type)
4294 (setenv "LC_ALL" "C")
4295 (setenv "PROMPT_COMMAND")
4296 (setenv "PS1" tramp-initial-end-of-output)
4297 (let* ((target-alist (tramp-compute-multi-hops vec))
4298 ;; We will apply `tramp-ssh-controlmaster-options'
4299 ;; only for the first hop.
4300 (options tramp-ssh-controlmaster-options)
4301 (process-connection-type tramp-process-connection-type)
4302 (process-adaptive-read-buffering nil)
4303 (coding-system-for-read nil)
4304 ;; This must be done in order to avoid our file
4305 ;; name handler.
4306 (p (let ((default-directory
4307 (tramp-compat-temporary-file-directory)))
4308 (apply
4309 'start-process
4310 (tramp-get-connection-name vec)
4311 (tramp-get-connection-buffer vec)
4312 (if tramp-encoding-command-interactive
4313 (list tramp-encoding-shell
4314 tramp-encoding-command-interactive)
4315 (list tramp-encoding-shell))))))
4316
4317 ;; Set sentinel and query flag.
4318 (tramp-set-connection-property p "vector" vec)
4319 (set-process-sentinel p 'tramp-process-sentinel)
4320 (tramp-compat-set-process-query-on-exit-flag p nil)
4321 (setq tramp-current-connection
4322 (cons (butlast (append vec nil)) (current-time))
4323 tramp-current-host (system-name))
4324
4325 (tramp-message
4326 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4327
4328 ;; Check whether process is alive.
4329 (tramp-barf-if-no-shell-prompt
4330 p 60
4331 "Couldn't find local shell prompt %s" tramp-encoding-shell)
4332
4333 ;; Now do all the connections as specified.
4334 (while target-alist
4335 (let* ((hop (car target-alist))
4336 (l-method (tramp-file-name-method hop))
4337 (l-user (tramp-file-name-user hop))
4338 (l-host (tramp-file-name-host hop))
4339 (l-port nil)
4340 (login-program
4341 (tramp-get-method-parameter
4342 l-method 'tramp-login-program))
4343 (login-args
4344 (tramp-get-method-parameter
4345 l-method 'tramp-login-args))
4346 (async-args
4347 (tramp-get-method-parameter
4348 l-method 'tramp-async-args))
4349 (gw-args
4350 (tramp-get-method-parameter l-method 'tramp-gw-args))
4351 (gw (tramp-get-file-property hop "" "gateway" nil))
4352 (g-method (and gw (tramp-file-name-method gw)))
4353 (g-user (and gw (tramp-file-name-user gw)))
4354 (g-host (and gw (tramp-file-name-real-host gw)))
4355 (command login-program)
4356 ;; We don't create the temporary file. In
4357 ;; fact, it is just a prefix for the
4358 ;; ControlPath option of ssh; the real
4359 ;; temporary file has another name, and it is
4360 ;; created and protected by ssh. It is also
4361 ;; removed by ssh when the connection is
4362 ;; closed. The temporary file name is cached
4363 ;; in the main connection process, therefore
4364 ;; we cannot use `tramp-get-connection-process'.
4365 (tmpfile
4366 (with-tramp-connection-property
4367 (get-process (tramp-buffer-name vec)) "temp-file"
4368 (make-temp-name
4369 (expand-file-name
4370 tramp-temp-name-prefix
4371 (tramp-compat-temporary-file-directory)))))
4372 spec r-shell)
4373
4374 ;; Add arguments for asynchronous processes.
4375 (when (and process-name async-args)
4376 (setq login-args (append async-args login-args)))
4377
4378 ;; Add gateway arguments if necessary.
4379 (when (and gw gw-args)
4380 (setq login-args (append gw-args login-args)))
4381
4382 ;; Check for port number. Until now, there's no
4383 ;; need for handling like method, user, host.
4384 (when (string-match tramp-host-with-port-regexp l-host)
4385 (setq l-port (match-string 2 l-host)
4386 l-host (match-string 1 l-host)))
4387
4388 ;; Check, whether there is a restricted shell.
4389 (dolist (elt tramp-restricted-shell-hosts-alist)
4390 (when (string-match elt tramp-current-host)
4391 (setq r-shell t)))
4392
4393 ;; Set variables for computing the prompt for
4394 ;; reading password. They can also be derived
4395 ;; from a gateway.
4396 (setq tramp-current-method (or g-method l-method)
4397 tramp-current-user (or g-user l-user)
4398 tramp-current-host (or g-host l-host))
4399
4400 ;; Replace login-args place holders.
4401 (setq
4402 l-host (or l-host "")
4403 l-user (or l-user "")
4404 l-port (or l-port "")
4405 spec (format-spec-make ?t tmpfile)
4406 options (format-spec options spec)
4407 spec (format-spec-make
4408 ?h l-host ?u l-user ?p l-port ?c options)
4409 command
4410 (concat
4411 ;; We do not want to see the trailing local
4412 ;; prompt in `start-file-process'.
4413 (unless r-shell "exec ")
4414 command " "
4415 (mapconcat
4416 (lambda (x)
4417 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4418 (unless (member "" x) (mapconcat 'identity x " ")))
4419 login-args " ")
4420 ;; Local shell could be a Windows COMSPEC. It
4421 ;; doesn't know the ";" syntax, but we must exit
4422 ;; always for `start-file-process'. It could
4423 ;; also be a restricted shell, which does not
4424 ;; allow "exec".
4425 (when r-shell " && exit || exit")))
4426
4427 ;; Send the command.
4428 (tramp-message vec 3 "Sending command `%s'" command)
4429 (tramp-send-command vec command t t)
4430 (tramp-process-actions
4431 p vec pos tramp-actions-before-shell 60)
4432 (tramp-message
4433 vec 3 "Found remote shell prompt on `%s'" l-host))
4434 ;; Next hop.
4435 (setq options ""
4436 target-alist (cdr target-alist)))
4437
4438 ;; Make initial shell settings.
4439 (tramp-open-connection-setup-interactive-shell p vec))))
4440
4441 ;; When the user did interrupt, we must cleanup.
4442 (quit
4443 (tramp-cleanup vec)
4444 ;; Propagate the quit signal.
4445 (signal (car err) (cdr err)))))))
4446
4447 (defun tramp-send-command (vec command &optional neveropen nooutput)
4448 "Send the COMMAND to connection VEC.
4449 Erases temporary buffer before sending the command. If optional
4450 arg NEVEROPEN is non-nil, never try to open the connection. This
4451 is meant to be used from `tramp-maybe-open-connection' only. The
4452 function waits for output unless NOOUTPUT is set."
4453 (unless neveropen (tramp-maybe-open-connection vec))
4454 (let ((p (tramp-get-connection-process vec)))
4455 (when (tramp-get-connection-property p "remote-echo" nil)
4456 ;; We mark the command string that it can be erased in the output buffer.
4457 (tramp-set-connection-property p "check-remote-echo" t)
4458 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4459 (when (and (string-match "<<'EOF'" command)
4460 (not (tramp-get-connection-property vec "busybox" nil)))
4461 ;; Unset $PS1 when using here documents, in order to avoid
4462 ;; multiple prompts.
4463 (setq command (concat "(PS1= ; " command "\n)")))
4464 ;; Send the command.
4465 (tramp-message vec 6 "%s" command)
4466 (tramp-send-string vec command)
4467 (unless nooutput (tramp-wait-for-output p))))
4468
4469 (defun tramp-wait-for-output (proc &optional timeout)
4470 "Wait for output from remote command."
4471 (unless (buffer-live-p (process-buffer proc))
4472 (delete-process proc)
4473 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4474 (with-current-buffer (process-buffer proc)
4475 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4476 ;; be leading escape sequences, which must be ignored.
4477 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
4478 ;; Sometimes, the commands do not return a newline but a
4479 ;; null byte before the shell prompt, for example "git
4480 ;; ls-files -c -z ...".
4481 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4482 (found (tramp-wait-for-regexp proc timeout regexp1)))
4483 (if found
4484 (let (buffer-read-only)
4485 ;; A simple-minded busybox has sent " ^H" sequences.
4486 ;; Delete them.
4487 (goto-char (point-min))
4488 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4489 (forward-line 1)
4490 (delete-region (point-min) (point)))
4491 ;; Delete the prompt.
4492 (goto-char (point-max))
4493 (re-search-backward regexp nil t)
4494 (delete-region (point) (point-max)))
4495 (if timeout
4496 (tramp-error
4497 proc 'file-error
4498 "[[Remote prompt `%s' not found in %d secs]]"
4499 tramp-end-of-output timeout)
4500 (tramp-error
4501 proc 'file-error
4502 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
4503 ;; Return value is whether end-of-output sentinel was found.
4504 found)))
4505
4506 (defun tramp-send-command-and-check
4507 (vec command &optional subshell dont-suppress-err)
4508 "Run COMMAND and check its exit status.
4509 Sends `echo $?' along with the COMMAND for checking the exit status. If
4510 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
4511
4512 If the optional argument SUBSHELL is non-nil, the command is
4513 executed in a subshell, ie surrounded by parentheses. If
4514 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
4515 (tramp-send-command
4516 vec
4517 (concat (if subshell "( " "")
4518 command
4519 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
4520 "echo tramp_exit_status $?"
4521 (if subshell " )" "")))
4522 (with-current-buffer (tramp-get-connection-buffer vec)
4523 (goto-char (point-max))
4524 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
4525 (tramp-error
4526 vec 'file-error "Couldn't find exit status of `%s'" command))
4527 (skip-chars-forward "^ ")
4528 (prog1
4529 (zerop (read (current-buffer)))
4530 (let (buffer-read-only)
4531 (delete-region (match-beginning 0) (point-max))))))
4532
4533 (defun tramp-barf-unless-okay (vec command fmt &rest args)
4534 "Run COMMAND, check exit status, throw error if exit status not okay.
4535 Similar to `tramp-send-command-and-check' but accepts two more arguments
4536 FMT and ARGS which are passed to `error'."
4537 (or (tramp-send-command-and-check vec command)
4538 (apply 'tramp-error vec 'file-error fmt args)))
4539
4540 (defun tramp-send-command-and-read (vec command &optional noerror)
4541 "Run COMMAND and return the output, which must be a Lisp expression.
4542 In case there is no valid Lisp expression and NOERROR is nil, it
4543 raises an error."
4544 (when (if noerror
4545 (tramp-send-command-and-check vec command)
4546 (tramp-barf-unless-okay
4547 vec command "`%s' returns with error" command))
4548 (with-current-buffer (tramp-get-connection-buffer vec)
4549 ;; Read the expression.
4550 (goto-char (point-min))
4551 (condition-case nil
4552 (prog1 (read (current-buffer))
4553 ;; Error handling.
4554 (when (re-search-forward "\\S-" (point-at-eol) t)
4555 (error nil)))
4556 (error (unless noerror
4557 (tramp-error
4558 vec 'file-error
4559 "`%s' does not return a valid Lisp expression: `%s'"
4560 command (buffer-string))))))))
4561
4562 (defun tramp-convert-file-attributes (vec attr)
4563 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
4564 Convert file mode bits to string and set virtual device number.
4565 Return ATTR."
4566 (when attr
4567 ;; Remove color escape sequences from symlink.
4568 (when (stringp (car attr))
4569 (while (string-match tramp-color-escape-sequence-regexp (car attr))
4570 (setcar attr (replace-match "" nil nil (car attr)))))
4571 ;; Convert uid and gid. Use -1 as indication of unusable value.
4572 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
4573 (setcar (nthcdr 2 attr) -1))
4574 (when (and (floatp (nth 2 attr))
4575 (<= (nth 2 attr) (tramp-compat-most-positive-fixnum)))
4576 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
4577 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
4578 (setcar (nthcdr 3 attr) -1))
4579 (when (and (floatp (nth 3 attr))
4580 (<= (nth 3 attr) (tramp-compat-most-positive-fixnum)))
4581 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
4582 ;; Convert last access time.
4583 (unless (listp (nth 4 attr))
4584 (setcar (nthcdr 4 attr)
4585 (list (floor (nth 4 attr) 65536)
4586 (floor (mod (nth 4 attr) 65536)))))
4587 ;; Convert last modification time.
4588 (unless (listp (nth 5 attr))
4589 (setcar (nthcdr 5 attr)
4590 (list (floor (nth 5 attr) 65536)
4591 (floor (mod (nth 5 attr) 65536)))))
4592 ;; Convert last status change time.
4593 (unless (listp (nth 6 attr))
4594 (setcar (nthcdr 6 attr)
4595 (list (floor (nth 6 attr) 65536)
4596 (floor (mod (nth 6 attr) 65536)))))
4597 ;; Convert file size.
4598 (when (< (nth 7 attr) 0)
4599 (setcar (nthcdr 7 attr) -1))
4600 (when (and (floatp (nth 7 attr))
4601 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
4602 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
4603 ;; Convert file mode bits to string.
4604 (unless (stringp (nth 8 attr))
4605 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
4606 (when (stringp (car attr))
4607 (aset (nth 8 attr) 0 ?l)))
4608 ;; Convert directory indication bit.
4609 (when (string-match "^d" (nth 8 attr))
4610 (setcar attr t))
4611 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
4612 (when (consp (car attr))
4613 (if (and (stringp (caar attr))
4614 (string-match ".+ -> .\\(.+\\)." (caar attr)))
4615 (setcar attr (match-string 1 (caar attr)))
4616 (setcar attr nil)))
4617 ;; Set file's gid change bit.
4618 (setcar (nthcdr 9 attr)
4619 (if (numberp (nth 3 attr))
4620 (not (= (nth 3 attr)
4621 (tramp-get-remote-gid vec 'integer)))
4622 (not (string-equal
4623 (nth 3 attr)
4624 (tramp-get-remote-gid vec 'string)))))
4625 ;; Convert inode.
4626 (unless (listp (nth 10 attr))
4627 (setcar (nthcdr 10 attr)
4628 (condition-case nil
4629 (cons (floor (nth 10 attr) 65536)
4630 (floor (mod (nth 10 attr) 65536)))
4631 ;; Inodes can be incredible huge. We must hide this.
4632 (error (tramp-get-inode vec)))))
4633 ;; Set virtual device number.
4634 (setcar (nthcdr 11 attr)
4635 (tramp-get-device vec))
4636 attr))
4637
4638 (defun tramp-shell-case-fold (string)
4639 "Converts STRING to shell glob pattern which ignores case."
4640 (mapconcat
4641 (lambda (c)
4642 (if (equal (downcase c) (upcase c))
4643 (vector c)
4644 (format "[%c%c]" (downcase c) (upcase c))))
4645 string
4646 ""))
4647
4648 (defun tramp-make-copy-program-file-name (vec)
4649 "Create a file name suitable to be passed to `rcp' and workalikes."
4650 (let ((user (tramp-file-name-user vec))
4651 (host (tramp-file-name-real-host vec))
4652 (localname (tramp-shell-quote-argument
4653 (tramp-file-name-localname vec))))
4654 (if (not (zerop (length user)))
4655 (format "%s@%s:%s" user host localname)
4656 (format "%s:%s" host localname))))
4657
4658 (defun tramp-method-out-of-band-p (vec size)
4659 "Return t if this is an out-of-band method, nil otherwise."
4660 (and
4661 ;; It shall be an out-of-band method.
4662 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
4663 ;; There must be a size, otherwise the file doesn't exist.
4664 (numberp size)
4665 ;; Either the file size is large enough, or (in rare cases) there
4666 ;; does not exist a remote encoding.
4667 (or (null tramp-copy-size-limit)
4668 (> size tramp-copy-size-limit)
4669 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
4670
4671 ;; Variables local to connection.
4672
4673 (defun tramp-get-remote-path (vec)
4674 (with-tramp-connection-property
4675 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
4676 ;; cache the result for the session only. Otherwise, the result
4677 ;; is cached persistently.
4678 (if (memq 'tramp-own-remote-path tramp-remote-path)
4679 (tramp-get-connection-process vec)
4680 vec)
4681 "remote-path"
4682 (let* ((remote-path (copy-tree tramp-remote-path))
4683 (elt1 (memq 'tramp-default-remote-path remote-path))
4684 (elt2 (memq 'tramp-own-remote-path remote-path))
4685 (default-remote-path
4686 (when elt1
4687 (or
4688 (tramp-send-command-and-read
4689 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
4690 ;; Default if "getconf" is not available.
4691 (progn
4692 (tramp-message
4693 vec 3
4694 "`getconf PATH' not successful, using default value \"%s\"."
4695 "/bin:/usr/bin")
4696 "/bin:/usr/bin"))))
4697 (own-remote-path
4698 (when elt2
4699 (condition-case nil
4700 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
4701 (error
4702 (tramp-message
4703 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
4704 nil)))))
4705
4706 ;; Replace place holder `tramp-default-remote-path'.
4707 (when elt1
4708 (setcdr elt1
4709 (append
4710 (tramp-compat-split-string default-remote-path ":")
4711 (cdr elt1)))
4712 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
4713
4714 ;; Replace place holder `tramp-own-remote-path'.
4715 (when elt2
4716 (setcdr elt2
4717 (append
4718 (tramp-compat-split-string own-remote-path ":")
4719 (cdr elt2)))
4720 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
4721
4722 ;; Remove double entries.
4723 (setq elt1 remote-path)
4724 (while (consp elt1)
4725 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
4726 (setcar elt2 nil))
4727 (setq elt1 (cdr elt1)))
4728
4729 ;; Remove non-existing directories.
4730 (delq
4731 nil
4732 (mapcar
4733 (lambda (x)
4734 (and
4735 (stringp x)
4736 (file-directory-p
4737 (tramp-make-tramp-file-name
4738 (tramp-file-name-method vec)
4739 (tramp-file-name-user vec)
4740 (tramp-file-name-host vec)
4741 x))
4742 x))
4743 remote-path)))))
4744
4745 (defun tramp-get-ls-command (vec)
4746 (with-tramp-connection-property vec "ls"
4747 (tramp-message vec 5 "Finding a suitable `ls' command")
4748 (or
4749 (catch 'ls-found
4750 (dolist (cmd '("ls" "gnuls" "gls"))
4751 (let ((dl (tramp-get-remote-path vec))
4752 result)
4753 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
4754 ;; Check parameters. On busybox, "ls" output coloring is
4755 ;; enabled by default sometimes. So we try to disable it
4756 ;; when possible. $LS_COLORING is not supported there.
4757 ;; Some "ls" versions are sensible wrt the order of
4758 ;; arguments, they fail when "-al" is after the
4759 ;; "--color=never" argument (for example on FreeBSD).
4760 (when (tramp-send-command-and-check
4761 vec (format "%s -lnd /" result))
4762 (when (tramp-send-command-and-check
4763 vec (format
4764 "%s --color=never -al /dev/null" result))
4765 (setq result (concat result " --color=never")))
4766 (throw 'ls-found result))
4767 (setq dl (cdr dl))))))
4768 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
4769
4770 (defun tramp-get-ls-command-with-dired (vec)
4771 (save-match-data
4772 (with-tramp-connection-property vec "ls-dired"
4773 (tramp-message vec 5 "Checking, whether `ls --dired' works")
4774 ;; Some "ls" versions are sensible wrt the order of arguments,
4775 ;; they fail when "-al" is after the "--dired" argument (for
4776 ;; example on FreeBSD).
4777 (tramp-send-command-and-check
4778 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
4779
4780 (defun tramp-get-test-command (vec)
4781 (with-tramp-connection-property vec "test"
4782 (tramp-message vec 5 "Finding a suitable `test' command")
4783 (if (tramp-send-command-and-check vec "test 0")
4784 "test"
4785 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
4786
4787 (defun tramp-get-test-nt-command (vec)
4788 ;; Does `test A -nt B' work? Use abominable `find' construct if it
4789 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
4790 ;; for otherwise the shell crashes.
4791 (with-tramp-connection-property vec "test-nt"
4792 (or
4793 (progn
4794 (tramp-send-command
4795 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
4796 (with-current-buffer (tramp-get-buffer vec)
4797 (goto-char (point-min))
4798 (when (looking-at (regexp-quote tramp-end-of-output))
4799 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
4800 (progn
4801 (tramp-send-command
4802 vec
4803 (format
4804 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
4805 (tramp-get-test-command vec)))
4806 "tramp_test_nt %s %s"))))
4807
4808 (defun tramp-get-file-exists-command (vec)
4809 (with-tramp-connection-property vec "file-exists"
4810 (tramp-message vec 5 "Finding command to check if file exists")
4811 (tramp-find-file-exists-command vec)))
4812
4813 (defun tramp-get-remote-ln (vec)
4814 (with-tramp-connection-property vec "ln"
4815 (tramp-message vec 5 "Finding a suitable `ln' command")
4816 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
4817
4818 (defun tramp-get-remote-perl (vec)
4819 (with-tramp-connection-property vec "perl"
4820 (tramp-message vec 5 "Finding a suitable `perl' command")
4821 (let ((result
4822 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
4823 (tramp-find-executable
4824 vec "perl" (tramp-get-remote-path vec)))))
4825 ;; We must check also for some Perl modules.
4826 (when result
4827 (with-tramp-connection-property vec "perl-file-spec"
4828 (tramp-send-command-and-check
4829 vec (format "%s -e 'use File::Spec;'" result)))
4830 (with-tramp-connection-property vec "perl-cwd-realpath"
4831 (tramp-send-command-and-check
4832 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
4833 result)))
4834
4835 (defun tramp-get-remote-stat (vec)
4836 (with-tramp-connection-property vec "stat"
4837 (tramp-message vec 5 "Finding a suitable `stat' command")
4838 (let ((result (tramp-find-executable
4839 vec "stat" (tramp-get-remote-path vec)))
4840 tmp)
4841 ;; Check whether stat(1) returns usable syntax. "%s" does not
4842 ;; work on older AIX systems.
4843 (when result
4844 (setq tmp
4845 (tramp-send-command-and-read
4846 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
4847 (unless (and (listp tmp) (stringp (car tmp))
4848 (string-match "^./.$" (car tmp))
4849 (integerp (cadr tmp)))
4850 (setq result nil)))
4851 result)))
4852
4853 (defun tramp-get-remote-readlink (vec)
4854 (with-tramp-connection-property vec "readlink"
4855 (tramp-message vec 5 "Finding a suitable `readlink' command")
4856 (let ((result (tramp-find-executable
4857 vec "readlink" (tramp-get-remote-path vec))))
4858 (when (and result
4859 (tramp-send-command-and-check
4860 vec (format "%s --canonicalize-missing /" result)))
4861 result))))
4862
4863 (defun tramp-get-remote-trash (vec)
4864 (with-tramp-connection-property vec "trash"
4865 (tramp-message vec 5 "Finding a suitable `trash' command")
4866 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
4867
4868 (defun tramp-get-remote-id (vec)
4869 (with-tramp-connection-property vec "id"
4870 (tramp-message vec 5 "Finding POSIX `id' command")
4871 (or
4872 (catch 'id-found
4873 (let ((dl (tramp-get-remote-path vec))
4874 result)
4875 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
4876 ;; Check POSIX parameter.
4877 (when (tramp-send-command-and-check vec (format "%s -u" result))
4878 (throw 'id-found result))
4879 (setq dl (cdr dl)))))
4880 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
4881
4882 (defun tramp-get-remote-uid (vec id-format)
4883 (with-tramp-connection-property vec (format "uid-%s" id-format)
4884 (let ((res (tramp-send-command-and-read
4885 vec
4886 (format "%s -u%s %s"
4887 (tramp-get-remote-id vec)
4888 (if (equal id-format 'integer) "" "n")
4889 (if (equal id-format 'integer)
4890 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
4891 ;; The command might not always return a number.
4892 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
4893
4894 (defun tramp-get-remote-gid (vec id-format)
4895 (with-tramp-connection-property vec (format "gid-%s" id-format)
4896 (let ((res (tramp-send-command-and-read
4897 vec
4898 (format "%s -g%s %s"
4899 (tramp-get-remote-id vec)
4900 (if (equal id-format 'integer) "" "n")
4901 (if (equal id-format 'integer)
4902 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
4903 ;; The command might not always return a number.
4904 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
4905
4906 ;; Some predefined connection properties.
4907 (defun tramp-get-inline-compress (vec prop size)
4908 "Return the compress command related to PROP.
4909 PROP is either `inline-compress' or `inline-decompress'. SIZE is
4910 the length of the file to be compressed.
4911
4912 If no corresponding command is found, nil is returned."
4913 (when (and (integerp tramp-inline-compress-start-size)
4914 (> size tramp-inline-compress-start-size))
4915 (with-tramp-connection-property (tramp-get-connection-process vec) prop
4916 (tramp-find-inline-compress vec)
4917 (tramp-get-connection-property
4918 (tramp-get-connection-process vec) prop nil))))
4919
4920 (defun tramp-get-inline-coding (vec prop size)
4921 "Return the coding command related to PROP.
4922 PROP is either `remote-encoding', `remote-decoding',
4923 `local-encoding' or `local-decoding'.
4924
4925 SIZE is the length of the file to be coded. Depending on SIZE,
4926 compression might be applied.
4927
4928 If no corresponding command is found, nil is returned.
4929 Otherwise, either a string is returned which contains a `%s' mark
4930 to be used for the respective input or output file; or a Lisp
4931 function cell is returned to be applied on a buffer."
4932 ;; We must catch the errors, because we want to return `nil', when
4933 ;; no inline coding is found.
4934 (ignore-errors
4935 (let ((coding
4936 (with-tramp-connection-property
4937 (tramp-get-connection-process vec) prop
4938 (tramp-find-inline-encoding vec)
4939 (tramp-get-connection-property
4940 (tramp-get-connection-process vec) prop nil)))
4941 (prop1 (if (string-match "encoding" prop)
4942 "inline-compress" "inline-decompress"))
4943 compress)
4944 ;; The connection property might have been cached. So we must
4945 ;; send the script to the remote side - maybe.
4946 (when (and coding (symbolp coding) (string-match "remote" prop))
4947 (let ((name (symbol-name coding)))
4948 (while (string-match (regexp-quote "-") name)
4949 (setq name (replace-match "_" nil t name)))
4950 (tramp-maybe-send-script vec (symbol-value coding) name)
4951 (setq coding name)))
4952 (when coding
4953 ;; Check for the `compress' command.
4954 (setq compress (tramp-get-inline-compress vec prop1 size))
4955 ;; Return the value.
4956 (cond
4957 ((and compress (symbolp coding))
4958 (if (string-match "decompress" prop1)
4959 `(lambda (beg end)
4960 (,coding beg end)
4961 (let ((coding-system-for-write 'binary)
4962 (coding-system-for-read 'binary))
4963 (apply
4964 'call-process-region (point-min) (point-max)
4965 (car (split-string ,compress)) t t nil
4966 (cdr (split-string ,compress)))))
4967 `(lambda (beg end)
4968 (let ((coding-system-for-write 'binary)
4969 (coding-system-for-read 'binary))
4970 (apply
4971 'call-process-region beg end
4972 (car (split-string ,compress)) t t nil
4973 (cdr (split-string ,compress))))
4974 (,coding (point-min) (point-max)))))
4975 ((symbolp coding)
4976 coding)
4977 ((and compress (string-match "decoding" prop))
4978 (format
4979 ;; Windows shells need the program file name after
4980 ;; the pipe symbol be quoted if they use forward
4981 ;; slashes as directory separators.
4982 (if (and (string-match "local" prop)
4983 (memq system-type '(windows-nt)))
4984 "(%s | \"%s\" >%%s)"
4985 "(%s | %s >%%s)")
4986 coding compress))
4987 (compress
4988 (format
4989 ;; Windows shells need the program file name after
4990 ;; the pipe symbol be quoted if they use forward
4991 ;; slashes as directory separators.
4992 (if (and (string-match "local" prop)
4993 (memq system-type '(windows-nt)))
4994 "(%s <%%s | \"%s\")"
4995 "(%s <%%s | %s)")
4996 compress coding))
4997 ((string-match "decoding" prop)
4998 (format "%s >%%s" coding))
4999 (t
5000 (format "%s <%%s" coding)))))))
5001
5002 (add-hook 'tramp-unload-hook
5003 (lambda ()
5004 (unload-feature 'tramp-sh 'force)))
5005
5006 (provide 'tramp-sh)
5007
5008 ;;; TODO:
5009
5010 ;; * Don't use globbing for directories with many files, as this is
5011 ;; likely to produce long command lines, and some shells choke on
5012 ;; long command lines.
5013 ;; * Make it work for different encodings, and for different file name
5014 ;; encodings, too. (Daniel Pittman)
5015 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5016 ;; then look if it's the right version (with `perl -v').
5017 ;; * When editing a remote CVS controlled file as a different user, VC
5018 ;; gets confused about the file locking status. Try to find out why
5019 ;; the workaround doesn't work.
5020 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5021 ;; until the last but one hop via `start-file-process'. Apply it
5022 ;; also for ftp and smb.
5023 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5024 ;; some shell with root privileges, it would be nice if I could
5025 ;; just call
5026 ;; trampclient filename.c
5027 ;; as an editor, and the _current_ shell would connect to an Emacs
5028 ;; server and would be used in an existing non-privileged Emacs
5029 ;; session for doing the editing in question.
5030 ;; That way, I need not tell Emacs my password again and be afraid
5031 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5032 ;; once display a just typed password in the context of a keyboard
5033 ;; sequence prompt for a question immediately following in a shell
5034 ;; script run within Emacs -- nasty).
5035 ;; And if I have some ssh session running to a different computer,
5036 ;; having the possibility of passing a local file there to a local
5037 ;; Emacs session (in case I can arrange for a connection back) would
5038 ;; be nice.
5039 ;; Likely the corresponding Tramp server should not allow the
5040 ;; equivalent of the emacsclient -eval option in order to make this
5041 ;; reasonably unproblematic. And maybe trampclient should have some
5042 ;; way of passing credentials, like by using an SSL socket or
5043 ;; something. (David Kastrup)
5044 ;; * Reconnect directly to a compliant shell without first going
5045 ;; through the user's default shell. (Pete Forman)
5046 ;; * How can I interrupt the remote process with a signal
5047 ;; (interrupt-process seems not to work)? (Markus Triska)
5048 ;; * Avoid the local shell entirely for starting remote processes. If
5049 ;; so, I think even a signal, when delivered directly to the local
5050 ;; SSH instance, would correctly be propagated to the remote process
5051 ;; automatically; possibly SSH would have to be started with
5052 ;; "-t". (Markus Triska)
5053 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5054 ;; isn't on the remote host. (Mark A. Hershberger)
5055 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5056 ;; * Optimize out-of-band copying when both methods are scp-like (not
5057 ;; rsync).
5058 ;; * Keep a second connection open for out-of-band methods like scp or
5059 ;; rsync.
5060 ;; * Try telnet+curl as new method. It might be useful for busybox,
5061 ;; without built-in uuencode/uudecode.
5062
5063 ;;; tramp-sh.el ends here