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