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