Fix problems in quoting Tramp file names
[emacs.git] / lisp / net / tramp-sh.el
bloba2949f1f204d7f8549e83cdff6bbab2899b29f62
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 unsets any setting of HISTFILE, and sets both
79 HISTFILESIZE and HISTSIZE to 0. If you set this variable to nil,
80 however, the *override* is disabled, so the history will go to
81 the default storage location, e.g. \"$HOME/.sh_history\"."
82 :group 'tramp
83 :version "25.2"
84 :type '(choice (const :tag "Do not override HISTFILE" nil)
85 (const :tag "Unset HISTFILE" t)
86 (string :tag "Redirect to a file"))
87 :require 'tramp)
89 ;;;###tramp-autoload
90 (defconst tramp-display-escape-sequence-regexp "\e[[;0-9]+m"
91 "Terminal control escape sequences for display attributes.")
93 ;;;###tramp-autoload
94 (defconst tramp-device-escape-sequence-regexp "\e[[0-9]+n"
95 "Terminal control escape sequences for device status.")
97 ;; ksh on OpenBSD 4.5 requires that $PS1 contains a `#' character for
98 ;; root users. It uses the `$' character for other users. In order
99 ;; to guarantee a proper prompt, we use "#$ " for the prompt.
101 (defvar tramp-end-of-output
102 (format
103 "///%s#$"
104 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
105 "String used to recognize end of output.
106 The `$' character at the end is quoted; the string cannot be
107 detected as prompt when being sent on echoing hosts, therefore.")
109 ;;;###tramp-autoload
110 (defconst tramp-initial-end-of-output "#$ "
111 "Prompt when establishing a connection.")
113 (defconst tramp-end-of-heredoc (md5 tramp-end-of-output)
114 "String used to recognize end of heredoc strings.")
116 ;;;###tramp-autoload
117 (defcustom tramp-use-ssh-controlmaster-options t
118 "Whether to use `tramp-ssh-controlmaster-options'."
119 :group 'tramp
120 :version "24.4"
121 :type 'boolean
122 :require 'tramp)
124 (defvar tramp-ssh-controlmaster-options nil
125 "Which ssh Control* arguments to use.
127 If it is a string, it should have the form
128 \"-o ControlMaster=auto -o ControlPath=\\='tramp.%%r@%%h:%%p\\='
129 -o ControlPersist=no\". Percent characters in the ControlPath
130 spec must be doubled, because the string is used as format string.
132 Otherwise, it will be auto-detected by Tramp, if
133 `tramp-use-ssh-controlmaster-options' is non-nil. The value
134 depends on the installed local ssh version.
136 The string is used in `tramp-methods'.")
138 ;; Initialize `tramp-methods' with the supported methods.
139 ;;;###tramp-autoload
140 (add-to-list 'tramp-methods
141 '("rcp"
142 (tramp-login-program "rsh")
143 (tramp-login-args (("%h") ("-l" "%u")))
144 (tramp-remote-shell "/bin/sh")
145 (tramp-remote-shell-login ("-l"))
146 (tramp-remote-shell-args ("-c"))
147 (tramp-copy-program "rcp")
148 (tramp-copy-args (("-p" "%k") ("-r")))
149 (tramp-copy-keep-date t)
150 (tramp-copy-recursive t)))
151 ;;;###tramp-autoload
152 (add-to-list 'tramp-methods
153 '("remcp"
154 (tramp-login-program "remsh")
155 (tramp-login-args (("%h") ("-l" "%u")))
156 (tramp-remote-shell "/bin/sh")
157 (tramp-remote-shell-login ("-l"))
158 (tramp-remote-shell-args ("-c"))
159 (tramp-copy-program "rcp")
160 (tramp-copy-args (("-p" "%k")))
161 (tramp-copy-keep-date t)))
162 ;;;###tramp-autoload
163 (add-to-list 'tramp-methods
164 '("scp"
165 (tramp-login-program "ssh")
166 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
167 ("-e" "none") ("%h")))
168 (tramp-async-args (("-q")))
169 (tramp-remote-shell "/bin/sh")
170 (tramp-remote-shell-login ("-l"))
171 (tramp-remote-shell-args ("-c"))
172 (tramp-copy-program "scp")
173 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q") ("-r") ("%c")))
174 (tramp-copy-keep-date t)
175 (tramp-copy-recursive t)
176 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
177 ("-o" "UserKnownHostsFile=/dev/null")
178 ("-o" "StrictHostKeyChecking=no")))
179 (tramp-default-port 22)))
180 ;;;###tramp-autoload
181 (add-to-list 'tramp-methods
182 '("scpx"
183 (tramp-login-program "ssh")
184 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
185 ("-e" "none") ("-t" "-t") ("%h") ("/bin/sh")))
186 (tramp-async-args (("-q")))
187 (tramp-remote-shell "/bin/sh")
188 (tramp-remote-shell-login ("-l"))
189 (tramp-remote-shell-args ("-c"))
190 (tramp-copy-program "scp")
191 (tramp-copy-args (("-P" "%p") ("-p" "%k")
192 ("-q") ("-r") ("%c")))
193 (tramp-copy-keep-date t)
194 (tramp-copy-recursive t)
195 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
196 ("-o" "UserKnownHostsFile=/dev/null")
197 ("-o" "StrictHostKeyChecking=no")))
198 (tramp-default-port 22)))
199 ;;;###tramp-autoload
200 (add-to-list 'tramp-methods
201 '("rsync"
202 (tramp-login-program "ssh")
203 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
204 ("-e" "none") ("%h")))
205 (tramp-async-args (("-q")))
206 (tramp-remote-shell "/bin/sh")
207 (tramp-remote-shell-login ("-l"))
208 (tramp-remote-shell-args ("-c"))
209 (tramp-copy-program "rsync")
210 (tramp-copy-args (("-t" "%k") ("-p") ("-r") ("-s")))
211 (tramp-copy-env (("RSYNC_RSH") ("ssh" "%c")))
212 (tramp-copy-keep-date t)
213 (tramp-copy-keep-tmpfile t)
214 (tramp-copy-recursive t)))
215 ;;;###tramp-autoload
216 (add-to-list 'tramp-methods
217 '("rsh"
218 (tramp-login-program "rsh")
219 (tramp-login-args (("%h") ("-l" "%u")))
220 (tramp-remote-shell "/bin/sh")
221 (tramp-remote-shell-login ("-l"))
222 (tramp-remote-shell-args ("-c"))))
223 ;;;###tramp-autoload
224 (add-to-list 'tramp-methods
225 '("remsh"
226 (tramp-login-program "remsh")
227 (tramp-login-args (("%h") ("-l" "%u")))
228 (tramp-remote-shell "/bin/sh")
229 (tramp-remote-shell-login ("-l"))
230 (tramp-remote-shell-args ("-c"))))
231 ;;;###tramp-autoload
232 (add-to-list 'tramp-methods
233 '("ssh"
234 (tramp-login-program "ssh")
235 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
236 ("-e" "none") ("%h")))
237 (tramp-async-args (("-q")))
238 (tramp-remote-shell "/bin/sh")
239 (tramp-remote-shell-login ("-l"))
240 (tramp-remote-shell-args ("-c"))
241 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
242 ("-o" "UserKnownHostsFile=/dev/null")
243 ("-o" "StrictHostKeyChecking=no")))
244 (tramp-default-port 22)))
245 ;;;###tramp-autoload
246 (add-to-list 'tramp-methods
247 '("sshx"
248 (tramp-login-program "ssh")
249 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
250 ("-e" "none") ("-t" "-t") ("%h") ("/bin/sh")))
251 (tramp-async-args (("-q")))
252 (tramp-remote-shell "/bin/sh")
253 (tramp-remote-shell-login ("-l"))
254 (tramp-remote-shell-args ("-c"))
255 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
256 ("-o" "UserKnownHostsFile=/dev/null")
257 ("-o" "StrictHostKeyChecking=no")))
258 (tramp-default-port 22)))
259 ;;;###tramp-autoload
260 (add-to-list 'tramp-methods
261 '("telnet"
262 (tramp-login-program "telnet")
263 (tramp-login-args (("%h") ("%p") ("2>/dev/null")))
264 (tramp-remote-shell "/bin/sh")
265 (tramp-remote-shell-login ("-l"))
266 (tramp-remote-shell-args ("-c"))
267 (tramp-default-port 23)))
268 ;;;###tramp-autoload
269 (add-to-list 'tramp-methods
270 '("nc"
271 (tramp-login-program "telnet")
272 (tramp-login-args (("%h") ("%p") ("2>/dev/null")))
273 (tramp-remote-shell "/bin/sh")
274 (tramp-remote-shell-login ("-l"))
275 (tramp-remote-shell-args ("-c"))
276 (tramp-copy-program "nc")
277 ;; We use "-v" for better error tracking.
278 (tramp-copy-args (("-w" "1") ("-v") ("%h") ("%r")))
279 (tramp-remote-copy-program "nc")
280 ;; We use "-p" as required for newer busyboxes. For older
281 ;; busybox/nc versions, the value must be (("-l") ("%r")). This
282 ;; can be achieved by tweaking `tramp-connection-properties'.
283 (tramp-remote-copy-args (("-l") ("-p" "%r") ("2>/dev/null")))
284 (tramp-default-port 23)))
285 ;;;###tramp-autoload
286 (add-to-list 'tramp-methods
287 '("su"
288 (tramp-login-program "su")
289 (tramp-login-args (("-") ("%u")))
290 (tramp-remote-shell "/bin/sh")
291 (tramp-remote-shell-login ("-l"))
292 (tramp-remote-shell-args ("-c"))
293 (tramp-connection-timeout 10)))
294 ;;;###tramp-autoload
295 (add-to-list
296 'tramp-methods
297 '("sg"
298 (tramp-login-program "sg")
299 (tramp-login-args (("-") ("%u")))
300 (tramp-remote-shell "/bin/sh")
301 (tramp-remote-shell-args ("-c"))
302 (tramp-connection-timeout 10)))
303 ;;;###tramp-autoload
304 (add-to-list 'tramp-methods
305 '("sudo"
306 (tramp-login-program "sudo")
307 ;; The password template must be masked. Otherwise, it could be
308 ;; interpreted as password prompt if the remote host echoes the command.
309 (tramp-login-args (("-u" "%u") ("-s") ("-H")
310 ("-p" "P\"\"a\"\"s\"\"s\"\"w\"\"o\"\"r\"\"d\"\":")))
311 ;; Local $SHELL could be a nasty one, like zsh or fish. Let's override it.
312 (tramp-login-env (("SHELL") ("/bin/sh")))
313 (tramp-remote-shell "/bin/sh")
314 (tramp-remote-shell-login ("-l"))
315 (tramp-remote-shell-args ("-c"))
316 (tramp-connection-timeout 10)))
317 ;;;###tramp-autoload
318 (add-to-list 'tramp-methods
319 '("doas"
320 (tramp-login-program "doas")
321 (tramp-login-args (("-u" "%u") ("-s")))
322 (tramp-remote-shell "/bin/sh")
323 (tramp-remote-shell-args ("-c"))
324 (tramp-connection-timeout 10)))
325 ;;;###tramp-autoload
326 (add-to-list 'tramp-methods
327 '("ksu"
328 (tramp-login-program "ksu")
329 (tramp-login-args (("%u") ("-q")))
330 (tramp-remote-shell "/bin/sh")
331 (tramp-remote-shell-login ("-l"))
332 (tramp-remote-shell-args ("-c"))
333 (tramp-connection-timeout 10)))
334 ;;;###tramp-autoload
335 (add-to-list 'tramp-methods
336 '("krlogin"
337 (tramp-login-program "krlogin")
338 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
339 (tramp-remote-shell "/bin/sh")
340 (tramp-remote-shell-login ("-l"))
341 (tramp-remote-shell-args ("-c"))))
342 ;;;###tramp-autoload
343 (add-to-list 'tramp-methods
344 `("plink"
345 (tramp-login-program "plink")
346 ;; ("%h") must be a single element, see `tramp-compute-multi-hops'.
347 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("-t")
348 ("%h") ("\"")
349 (,(format
350 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
351 tramp-terminal-type
352 tramp-initial-end-of-output))
353 ("/bin/sh") ("\"")))
354 (tramp-remote-shell "/bin/sh")
355 (tramp-remote-shell-login ("-l"))
356 (tramp-remote-shell-args ("-c"))
357 (tramp-default-port 22)))
358 ;;;###tramp-autoload
359 (add-to-list 'tramp-methods
360 `("plinkx"
361 (tramp-login-program "plink")
362 (tramp-login-args (("-load") ("%h") ("-t") ("\"")
363 (,(format
364 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
365 tramp-terminal-type
366 tramp-initial-end-of-output))
367 ("/bin/sh") ("\"")))
368 (tramp-remote-shell "/bin/sh")
369 (tramp-remote-shell-login ("-l"))
370 (tramp-remote-shell-args ("-c"))))
371 ;;;###tramp-autoload
372 (add-to-list 'tramp-methods
373 `("pscp"
374 (tramp-login-program "plink")
375 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("-t")
376 ("%h") ("\"")
377 (,(format
378 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
379 tramp-terminal-type
380 tramp-initial-end-of-output))
381 ("/bin/sh") ("\"")))
382 (tramp-remote-shell "/bin/sh")
383 (tramp-remote-shell-login ("-l"))
384 (tramp-remote-shell-args ("-c"))
385 (tramp-copy-program "pscp")
386 (tramp-copy-args (("-l" "%u") ("-P" "%p") ("-scp") ("-p" "%k")
387 ("-q") ("-r")))
388 (tramp-copy-keep-date t)
389 (tramp-copy-recursive t)
390 (tramp-default-port 22)))
391 ;;;###tramp-autoload
392 (add-to-list 'tramp-methods
393 `("psftp"
394 (tramp-login-program "plink")
395 (tramp-login-args (("-l" "%u") ("-P" "%p") ("-ssh") ("-t")
396 ("%h") ("\"")
397 (,(format
398 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
399 tramp-terminal-type
400 tramp-initial-end-of-output))
401 ("/bin/sh") ("\"")))
402 (tramp-remote-shell "/bin/sh")
403 (tramp-remote-shell-login ("-l"))
404 (tramp-remote-shell-args ("-c"))
405 (tramp-copy-program "pscp")
406 (tramp-copy-args (("-l" "%u") ("-P" "%p") ("-sftp") ("-p" "%k")
407 ("-q")))
408 (tramp-copy-keep-date t)))
409 ;;;###tramp-autoload
410 (add-to-list 'tramp-methods
411 '("fcp"
412 (tramp-login-program "fsh")
413 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
414 (tramp-remote-shell "/bin/sh")
415 (tramp-remote-shell-login ("-l"))
416 (tramp-remote-shell-args ("-i") ("-c"))
417 (tramp-copy-program "fcp")
418 (tramp-copy-args (("-p" "%k")))
419 (tramp-copy-keep-date t)))
421 ;;;###tramp-autoload
422 (add-to-list 'tramp-default-method-alist
423 `(,tramp-local-host-regexp "\\`root\\'" "su"))
425 ;;;###tramp-autoload
426 (add-to-list 'tramp-default-user-alist
427 `(,(concat "\\`" (regexp-opt '("su" "sudo" "doas" "ksu")) "\\'")
428 nil "root"))
429 ;; Do not add "ssh" based methods, otherwise ~/.ssh/config would be ignored.
430 ;; Do not add "plink" based methods, they ask interactively for the user.
431 ;;;###tramp-autoload
432 (add-to-list 'tramp-default-user-alist
433 `(,(concat
434 "\\`"
435 (regexp-opt
436 '("rcp" "remcp" "rsh" "telnet" "nc" "krlogin" "fcp"))
437 "\\'")
438 nil ,(user-login-name)))
440 ;;;###tramp-autoload
441 (defconst tramp-completion-function-alist-rsh
442 '((tramp-parse-rhosts "/etc/hosts.equiv")
443 (tramp-parse-rhosts "~/.rhosts"))
444 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
446 ;;;###tramp-autoload
447 (defconst tramp-completion-function-alist-ssh
448 '((tramp-parse-rhosts "/etc/hosts.equiv")
449 (tramp-parse-rhosts "/etc/shosts.equiv")
450 (tramp-parse-shosts "/etc/ssh_known_hosts")
451 (tramp-parse-sconfig "/etc/ssh_config")
452 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
453 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
454 (tramp-parse-rhosts "~/.rhosts")
455 (tramp-parse-rhosts "~/.shosts")
456 (tramp-parse-shosts "~/.ssh/known_hosts")
457 (tramp-parse-sconfig "~/.ssh/config")
458 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
459 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
460 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
462 ;;;###tramp-autoload
463 (defconst tramp-completion-function-alist-telnet
464 '((tramp-parse-hosts "/etc/hosts"))
465 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
467 ;;;###tramp-autoload
468 (defconst tramp-completion-function-alist-su
469 '((tramp-parse-passwd "/etc/passwd"))
470 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
472 ;;;###tramp-autoload
473 (defconst tramp-completion-function-alist-sg
474 '((tramp-parse-etc-group "/etc/group"))
475 "Default list of (FUNCTION FILE) pairs to be examined for sg methods.")
477 ;;;###tramp-autoload
478 (defconst tramp-completion-function-alist-putty
479 `((tramp-parse-putty
480 ,(if (memq system-type '(windows-nt))
481 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"
482 "~/.putty/sessions")))
483 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty sessions.")
485 ;;;###tramp-autoload
486 (eval-after-load 'tramp
487 '(progn
488 (tramp-set-completion-function "rcp" tramp-completion-function-alist-rsh)
489 (tramp-set-completion-function "remcp" tramp-completion-function-alist-rsh)
490 (tramp-set-completion-function "scp" tramp-completion-function-alist-ssh)
491 (tramp-set-completion-function "scpx" tramp-completion-function-alist-ssh)
492 (tramp-set-completion-function "rsync" tramp-completion-function-alist-ssh)
493 (tramp-set-completion-function "rsh" tramp-completion-function-alist-rsh)
494 (tramp-set-completion-function "remsh" tramp-completion-function-alist-rsh)
495 (tramp-set-completion-function "ssh" tramp-completion-function-alist-ssh)
496 (tramp-set-completion-function "sshx" tramp-completion-function-alist-ssh)
497 (tramp-set-completion-function
498 "telnet" tramp-completion-function-alist-telnet)
499 (tramp-set-completion-function "nc" tramp-completion-function-alist-telnet)
500 (tramp-set-completion-function "su" tramp-completion-function-alist-su)
501 (tramp-set-completion-function "sudo" tramp-completion-function-alist-su)
502 (tramp-set-completion-function "doas" tramp-completion-function-alist-su)
503 (tramp-set-completion-function "ksu" tramp-completion-function-alist-su)
504 (tramp-set-completion-function "sg" tramp-completion-function-alist-sg)
505 (tramp-set-completion-function
506 "krlogin" tramp-completion-function-alist-rsh)
507 (tramp-set-completion-function "plink" tramp-completion-function-alist-ssh)
508 (tramp-set-completion-function
509 "plinkx" tramp-completion-function-alist-putty)
510 (tramp-set-completion-function "pscp" tramp-completion-function-alist-ssh)
511 (tramp-set-completion-function "psftp" tramp-completion-function-alist-ssh)
512 (tramp-set-completion-function "fcp" tramp-completion-function-alist-ssh)))
514 ;; "getconf PATH" yields:
515 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
516 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
517 ;; GNU/Linux (Debian, Suse, RHEL): /bin:/usr/bin
518 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
519 ;; Darwin: /usr/bin:/bin:/usr/sbin:/sbin
520 ;; IRIX64: /usr/bin
521 ;; QNAP QTS: ---
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 "26.1"
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-case-insensitive-p . tramp-handle-file-name-case-insensitive-p)
1031 (file-name-completion . tramp-handle-file-name-completion)
1032 (file-name-directory . tramp-handle-file-name-directory)
1033 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1034 ;; `file-name-sans-versions' performed by default handler.
1035 (file-newer-than-file-p . tramp-sh-handle-file-newer-than-file-p)
1036 (file-notify-add-watch . tramp-sh-handle-file-notify-add-watch)
1037 (file-notify-rm-watch . tramp-handle-file-notify-rm-watch)
1038 (file-notify-valid-p . tramp-handle-file-notify-valid-p)
1039 (file-ownership-preserved-p . tramp-sh-handle-file-ownership-preserved-p)
1040 (file-readable-p . tramp-sh-handle-file-readable-p)
1041 (file-regular-p . tramp-handle-file-regular-p)
1042 (file-remote-p . tramp-handle-file-remote-p)
1043 (file-selinux-context . tramp-sh-handle-file-selinux-context)
1044 (file-symlink-p . tramp-handle-file-symlink-p)
1045 (file-truename . tramp-sh-handle-file-truename)
1046 (file-writable-p . tramp-sh-handle-file-writable-p)
1047 (find-backup-file-name . tramp-handle-find-backup-file-name)
1048 ;; `find-file-noselect' performed by default handler.
1049 ;; `get-file-buffer' performed by default handler.
1050 (insert-directory . tramp-sh-handle-insert-directory)
1051 (insert-file-contents . tramp-handle-insert-file-contents)
1052 (load . tramp-handle-load)
1053 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
1054 (make-directory . tramp-sh-handle-make-directory)
1055 (make-nearby-temp-file . tramp-handle-make-nearby-temp-file)
1056 (make-symbolic-link . tramp-sh-handle-make-symbolic-link)
1057 (process-file . tramp-sh-handle-process-file)
1058 (rename-file . tramp-sh-handle-rename-file)
1059 (set-file-acl . tramp-sh-handle-set-file-acl)
1060 (set-file-modes . tramp-sh-handle-set-file-modes)
1061 (set-file-selinux-context . tramp-sh-handle-set-file-selinux-context)
1062 (set-file-times . tramp-sh-handle-set-file-times)
1063 (set-visited-file-modtime . tramp-sh-handle-set-visited-file-modtime)
1064 (shell-command . tramp-handle-shell-command)
1065 (start-file-process . tramp-sh-handle-start-file-process)
1066 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
1067 (temporary-file-directory . tramp-handle-temporary-file-directory)
1068 (unhandled-file-name-directory . ignore)
1069 (vc-registered . tramp-sh-handle-vc-registered)
1070 (verify-visited-file-modtime . tramp-sh-handle-verify-visited-file-modtime)
1071 (write-region . tramp-sh-handle-write-region))
1072 "Alist of handler functions.
1073 Operations not mentioned here will be handled by the normal Emacs functions.")
1075 ;; This must be the last entry, because `identity' always matches.
1076 ;;;###tramp-autoload
1077 (add-to-list 'tramp-foreign-file-name-handler-alist
1078 '(identity . tramp-sh-file-name-handler) 'append)
1080 ;;; File Name Handler Functions:
1082 (defun tramp-sh-handle-make-symbolic-link
1083 (filename linkname &optional ok-if-already-exists)
1084 "Like `make-symbolic-link' for Tramp files.
1085 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
1086 the symlink. If LINKNAME is a Tramp file, only the localname component is
1087 used as the target of the symlink.
1089 If LINKNAME is a Tramp file and the localname component is relative, then
1090 it is expanded first, before the localname component is taken. Note that
1091 this can give surprising results if the user/host for the source and
1092 target of the symlink differ."
1093 (with-parsed-tramp-file-name linkname l
1094 (let ((ln (tramp-get-remote-ln l))
1095 (cwd (tramp-run-real-handler
1096 'file-name-directory (list l-localname))))
1097 (unless ln
1098 (tramp-error
1099 l 'file-error
1100 "Making a symbolic link. ln(1) does not exist on the remote host."))
1102 ;; Do the 'confirm if exists' thing.
1103 (when (file-exists-p linkname)
1104 ;; What to do?
1105 (if (or (null ok-if-already-exists) ; not allowed to exist
1106 (and (numberp ok-if-already-exists)
1107 (not (yes-or-no-p
1108 (format
1109 "File %s already exists; make it a link anyway? "
1110 l-localname)))))
1111 (tramp-error
1112 l 'file-already-exists "File %s already exists" l-localname)
1113 (delete-file linkname)))
1115 ;; If FILENAME is a Tramp name, use just the localname component.
1116 (when (tramp-tramp-file-p filename)
1117 (setq filename
1118 (tramp-file-name-localname
1119 (tramp-dissect-file-name (expand-file-name filename)))))
1121 (tramp-flush-file-property l (file-name-directory l-localname))
1122 (tramp-flush-file-property l l-localname)
1124 ;; Right, they are on the same host, regardless of user, method,
1125 ;; etc. We now make the link on the remote machine. This will
1126 ;; occur as the user that FILENAME belongs to.
1127 (and (tramp-send-command-and-check
1128 l (format "cd %s" (tramp-shell-quote-argument cwd)))
1129 (tramp-send-command-and-check
1130 l (format
1131 "%s -sf %s %s"
1133 (tramp-shell-quote-argument filename)
1134 ;; The command could exceed PATH_MAX, so we use
1135 ;; relative file names. However, relative file names
1136 ;; could start with "-". `tramp-shell-quote-argument'
1137 ;; does not handle this, we must do it ourselves.
1138 (tramp-shell-quote-argument
1139 (concat "./" (file-name-nondirectory l-localname)))))))))
1141 (defun tramp-sh-handle-file-truename (filename)
1142 "Like `file-truename' for Tramp files."
1143 (format
1144 "%s%s"
1145 (with-parsed-tramp-file-name (expand-file-name filename) nil
1146 (tramp-make-tramp-file-name
1147 method user host
1148 (with-tramp-file-property v localname "file-truename"
1149 (let ((result nil) ; result steps in reverse order
1150 (quoted (tramp-quoted-name-p localname))
1151 (localname (tramp-unquote-name localname)))
1152 (tramp-message v 4 "Finding true name for `%s'" filename)
1153 (cond
1154 ;; Use GNU readlink --canonicalize-missing where available.
1155 ((tramp-get-remote-readlink v)
1156 (tramp-send-command-and-check
1158 (format "%s --canonicalize-missing %s"
1159 (tramp-get-remote-readlink v)
1160 (tramp-shell-quote-argument localname)))
1161 (with-current-buffer (tramp-get-connection-buffer v)
1162 (goto-char (point-min))
1163 (setq result (buffer-substring (point-min) (point-at-eol)))))
1165 ;; Use Perl implementation.
1166 ((and (tramp-get-remote-perl v)
1167 (tramp-get-connection-property v "perl-file-spec" nil)
1168 (tramp-get-connection-property v "perl-cwd-realpath" nil))
1169 (tramp-maybe-send-script
1170 v tramp-perl-file-truename "tramp_perl_file_truename")
1171 (setq result
1172 (tramp-send-command-and-read
1174 (format "tramp_perl_file_truename %s"
1175 (tramp-shell-quote-argument localname)))))
1177 ;; Do it yourself.
1178 (t (let ((steps (split-string localname "/" 'omit))
1179 (thisstep nil)
1180 (numchase 0)
1181 ;; Don't make the following value larger than
1182 ;; necessary. People expect an error message in a
1183 ;; timely fashion when something is wrong;
1184 ;; otherwise they might think that Emacs is hung.
1185 ;; Of course, correctness has to come first.
1186 (numchase-limit 20)
1187 symlink-target)
1188 (while (and steps (< numchase numchase-limit))
1189 (setq thisstep (pop steps))
1190 (tramp-message
1191 v 5 "Check %s"
1192 (mapconcat 'identity
1193 (append '("") (reverse result) (list thisstep))
1194 "/"))
1195 (setq symlink-target
1196 (tramp-compat-file-attribute-type
1197 (file-attributes
1198 (tramp-make-tramp-file-name
1199 method user host
1200 (mapconcat 'identity
1201 (append '("")
1202 (reverse result)
1203 (list thisstep))
1204 "/")))))
1205 (cond ((string= "." thisstep)
1206 (tramp-message v 5 "Ignoring step `.'"))
1207 ((string= ".." thisstep)
1208 (tramp-message v 5 "Processing step `..'")
1209 (pop result))
1210 ((stringp symlink-target)
1211 ;; It's a symlink, follow it.
1212 (tramp-message
1213 v 5 "Follow symlink to %s" symlink-target)
1214 (setq numchase (1+ numchase))
1215 (when (file-name-absolute-p symlink-target)
1216 (setq result nil))
1217 ;; If the symlink was absolute, we'll get a
1218 ;; string like "/user@host:/some/target";
1219 ;; extract the "/some/target" part from it.
1220 (when (tramp-tramp-file-p symlink-target)
1221 (unless (tramp-equal-remote filename symlink-target)
1222 (tramp-error
1223 v 'file-error
1224 "Symlink target `%s' on wrong host"
1225 symlink-target))
1226 (setq symlink-target localname))
1227 (setq steps
1228 (append
1229 (split-string symlink-target "/" 'omit) steps)))
1231 ;; It's a file.
1232 (setq result (cons thisstep result)))))
1233 (when (>= numchase numchase-limit)
1234 (tramp-error
1235 v 'file-error
1236 "Maximum number (%d) of symlinks exceeded" numchase-limit))
1237 (setq result (reverse result))
1238 ;; Combine list to form string.
1239 (setq result
1240 (if result
1241 (mapconcat 'identity (cons "" result) "/")
1242 "/"))
1243 (when (string= "" result)
1244 (setq result "/")))))
1246 (when quoted (setq result (tramp-quote-name result)))
1247 (tramp-message v 4 "True name of `%s' is `%s'" localname result)
1248 result))))
1250 ;; Preserve trailing "/".
1251 (if (string-equal (file-name-nondirectory filename) "") "/" "")))
1253 ;; Basic functions.
1255 (defun tramp-sh-handle-file-exists-p (filename)
1256 "Like `file-exists-p' for Tramp files."
1257 (with-parsed-tramp-file-name filename nil
1258 (with-tramp-file-property v localname "file-exists-p"
1259 (or (not (null (tramp-get-file-property
1260 v localname "file-attributes-integer" nil)))
1261 (not (null (tramp-get-file-property
1262 v localname "file-attributes-string" nil)))
1263 (tramp-send-command-and-check
1265 (format
1266 "%s %s"
1267 (tramp-get-file-exists-command v)
1268 (tramp-shell-quote-argument localname)))))))
1270 (defun tramp-sh-handle-file-attributes (filename &optional id-format)
1271 "Like `file-attributes' for Tramp files."
1272 (unless id-format (setq id-format 'integer))
1273 (ignore-errors
1274 ;; Don't modify `last-coding-system-used' by accident.
1275 (let ((last-coding-system-used last-coding-system-used))
1276 (with-parsed-tramp-file-name (expand-file-name filename) nil
1277 (with-tramp-file-property
1278 v localname (format "file-attributes-%s" id-format)
1279 (save-excursion
1280 (tramp-convert-file-attributes
1283 (cond
1284 ((tramp-get-remote-stat v)
1285 (tramp-do-file-attributes-with-stat v localname id-format))
1286 ((tramp-get-remote-perl v)
1287 (tramp-do-file-attributes-with-perl v localname id-format))
1288 (t nil))
1289 ;; The scripts could fail, for example with huge file size.
1290 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
1292 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
1293 "Implement `file-attributes' for Tramp files using the ls(1) command."
1294 (let (symlinkp dirp
1295 res-inode res-filemodes res-numlinks
1296 res-uid res-gid res-size res-symlink-target)
1297 (tramp-message vec 5 "file attributes with ls: %s" localname)
1298 ;; We cannot send all three commands combined, it could exceed
1299 ;; NAME_MAX or PATH_MAX. Happened on macOS, for example.
1300 (when (or (tramp-send-command-and-check
1302 (format "%s %s"
1303 (tramp-get-file-exists-command vec)
1304 (tramp-shell-quote-argument localname)))
1305 (tramp-send-command-and-check
1307 (format "%s -h %s"
1308 (tramp-get-test-command vec)
1309 (tramp-shell-quote-argument localname))))
1310 (tramp-send-command
1312 (format "%s %s %s %s"
1313 (tramp-get-ls-command vec)
1314 (if (eq id-format 'integer) "-ildn" "-ild")
1315 ;; On systems which have no quoting style, file names
1316 ;; with special characters could fail.
1317 (cond
1318 ((tramp-get-ls-command-with-quoting-style vec)
1319 "--quoting-style=c")
1320 ((tramp-get-ls-command-with-w-option vec)
1321 "-w")
1322 (t ""))
1323 (tramp-shell-quote-argument localname)))
1324 ;; Parse `ls -l' output ...
1325 (with-current-buffer (tramp-get-buffer vec)
1326 (when (> (buffer-size) 0)
1327 (goto-char (point-min))
1328 ;; ... inode
1329 (setq res-inode
1330 (condition-case err
1331 (read (current-buffer))
1332 (invalid-read-syntax
1333 (when (and (equal (cadr err)
1334 "Integer constant overflow in reader")
1335 (string-match
1336 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
1337 (car (cddr err))))
1338 (let* ((big (read (substring (car (cddr err)) 0
1339 (match-beginning 1))))
1340 (small (read (match-string 1 (car (cddr err)))))
1341 (twiddle (/ small 65536)))
1342 (cons (+ big twiddle)
1343 (- small (* twiddle 65536))))))))
1344 ;; ... file mode flags
1345 (setq res-filemodes (symbol-name (read (current-buffer))))
1346 ;; ... number links
1347 (setq res-numlinks (read (current-buffer)))
1348 ;; ... uid and gid
1349 (setq res-uid (read (current-buffer)))
1350 (setq res-gid (read (current-buffer)))
1351 (if (eq id-format 'integer)
1352 (progn
1353 (unless (numberp res-uid)
1354 (setq res-uid tramp-unknown-id-integer))
1355 (unless (numberp res-gid)
1356 (setq res-gid tramp-unknown-id-integer)))
1357 (progn
1358 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
1359 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
1360 ;; ... size
1361 (setq res-size (read (current-buffer)))
1362 ;; From the file modes, figure out other stuff.
1363 (setq symlinkp (eq ?l (aref res-filemodes 0)))
1364 (setq dirp (eq ?d (aref res-filemodes 0)))
1365 ;; If symlink, find out file name pointed to.
1366 (when symlinkp
1367 (search-forward "-> ")
1368 (setq res-symlink-target
1369 (if (tramp-get-ls-command-with-quoting-style vec)
1370 (read (current-buffer))
1371 (buffer-substring (point) (point-at-eol)))))
1372 ;; Return data gathered.
1373 (list
1374 ;; 0. t for directory, string (name linked to) for symbolic
1375 ;; link, or nil.
1376 (or dirp res-symlink-target)
1377 ;; 1. Number of links to file.
1378 res-numlinks
1379 ;; 2. File uid.
1380 res-uid
1381 ;; 3. File gid.
1382 res-gid
1383 ;; 4. Last access time, as a list of integers. Normally
1384 ;; this would be in the same format as `current-time', but
1385 ;; the subseconds part is not currently implemented, and
1386 ;; (0 0) denotes an unknown time.
1387 ;; 5. Last modification time, likewise.
1388 ;; 6. Last status change time, likewise.
1389 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
1390 ;; 7. Size in bytes (-1, if number is out of range).
1391 res-size
1392 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
1393 res-filemodes
1394 ;; 9. t if file's gid would change if file were deleted and
1395 ;; recreated. Will be set in `tramp-convert-file-attributes'.
1397 ;; 10. Inode number.
1398 res-inode
1399 ;; 11. Device number. Will be replaced by a virtual device number.
1400 -1))))))
1402 (defun tramp-do-file-attributes-with-perl
1403 (vec localname &optional id-format)
1404 "Implement `file-attributes' for Tramp files using a Perl script."
1405 (tramp-message vec 5 "file attributes with perl: %s" localname)
1406 (tramp-maybe-send-script
1407 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
1408 (tramp-send-command-and-read
1410 (format "tramp_perl_file_attributes %s %s"
1411 (tramp-shell-quote-argument localname) id-format)))
1413 (defun tramp-do-file-attributes-with-stat
1414 (vec localname &optional id-format)
1415 "Implement `file-attributes' for Tramp files using stat(1) command."
1416 (tramp-message vec 5 "file attributes with stat: %s" localname)
1417 (tramp-send-command-and-read
1419 (format
1420 (concat
1421 ;; On Opsware, pdksh (which is the true name of ksh there)
1422 ;; doesn't parse correctly the sequence "((". Therefore, we add
1423 ;; a space. Apostrophes in the stat output are masked as
1424 ;; `tramp-stat-marker', in order to make a proper shell escape of
1425 ;; them in file names.
1426 "( (%s %s || %s -h %s) && (%s -c "
1427 "'((%s%%N%s) %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 %s%%A%s t %%ie0 -1)' "
1428 "%s | sed -e 's/\"/\\\\\"/g' -e 's/%s/\"/g') || echo nil)")
1429 (tramp-get-file-exists-command vec)
1430 (tramp-shell-quote-argument localname)
1431 (tramp-get-test-command vec)
1432 (tramp-shell-quote-argument localname)
1433 (tramp-get-remote-stat vec)
1434 tramp-stat-marker tramp-stat-marker
1435 (if (eq id-format 'integer)
1436 "%ue0" (concat tramp-stat-marker "%U" tramp-stat-marker))
1437 (if (eq id-format 'integer)
1438 "%ge0" (concat tramp-stat-marker "%G" tramp-stat-marker))
1439 tramp-stat-marker tramp-stat-marker
1440 (tramp-shell-quote-argument localname)
1441 tramp-stat-quoted-marker)))
1443 (defun tramp-sh-handle-set-visited-file-modtime (&optional time-list)
1444 "Like `set-visited-file-modtime' for Tramp files."
1445 (unless (buffer-file-name)
1446 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
1447 (buffer-name)))
1448 (if time-list
1449 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
1450 (let ((f (buffer-file-name))
1451 coding-system-used)
1452 (with-parsed-tramp-file-name f nil
1453 (let* ((remote-file-name-inhibit-cache t)
1454 (attr (file-attributes f))
1455 ;; '(-1 65535) means file doesn't exists yet.
1456 (modtime (or (tramp-compat-file-attribute-modification-time attr)
1457 '(-1 65535))))
1458 (setq coding-system-used last-coding-system-used)
1459 ;; We use '(0 0) as a don't-know value. See also
1460 ;; `tramp-do-file-attributes-with-ls'.
1461 (if (not (equal modtime '(0 0)))
1462 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
1463 (progn
1464 (tramp-send-command
1466 (format "%s -ild %s"
1467 (tramp-get-ls-command v)
1468 (tramp-shell-quote-argument localname)))
1469 (setq attr (buffer-substring (point) (point-at-eol))))
1470 (tramp-set-file-property
1471 v localname "visited-file-modtime-ild" attr))
1472 (setq last-coding-system-used coding-system-used)
1473 nil)))))
1475 ;; This function makes the same assumption as
1476 ;; `tramp-sh-handle-set-visited-file-modtime'.
1477 (defun tramp-sh-handle-verify-visited-file-modtime (&optional buf)
1478 "Like `verify-visited-file-modtime' for Tramp files.
1479 At the time `verify-visited-file-modtime' calls this function, we
1480 already know that the buffer is visiting a file and that
1481 `visited-file-modtime' does not return 0. Do not call this
1482 function directly, unless those two cases are already taken care
1483 of."
1484 (with-current-buffer (or buf (current-buffer))
1485 (let ((f (buffer-file-name)))
1486 ;; There is no file visiting the buffer, or the buffer has no
1487 ;; recorded last modification time, or there is no established
1488 ;; connection.
1489 (if (or (not f)
1490 (eq (visited-file-modtime) 0)
1491 (not (file-remote-p f nil 'connected)))
1493 (with-parsed-tramp-file-name f nil
1494 (let* ((remote-file-name-inhibit-cache t)
1495 (attr (file-attributes f))
1496 (modtime (tramp-compat-file-attribute-modification-time attr))
1497 (mt (visited-file-modtime)))
1499 (cond
1500 ;; File exists, and has a known modtime.
1501 ((and attr (not (equal modtime '(0 0))))
1502 (< (abs (tramp-time-diff
1503 modtime
1504 ;; For compatibility, deal with both the old
1505 ;; (HIGH . LOW) and the new (HIGH LOW) return
1506 ;; values of `visited-file-modtime'.
1507 (if (atom (cdr mt))
1508 (list (car mt) (cdr mt))
1509 mt)))
1511 ;; Modtime has the don't know value.
1512 (attr
1513 (tramp-send-command
1515 (format "%s -ild %s"
1516 (tramp-get-ls-command v)
1517 (tramp-shell-quote-argument localname)))
1518 (with-current-buffer (tramp-get-buffer v)
1519 (setq attr (buffer-substring (point) (point-at-eol))))
1520 (equal
1521 attr
1522 (tramp-get-file-property
1523 v localname "visited-file-modtime-ild" "")))
1524 ;; If file does not exist, say it is not modified if and
1525 ;; only if that agrees with the buffer's record.
1526 (t (equal mt '(-1 65535))))))))))
1528 (defun tramp-sh-handle-set-file-modes (filename mode)
1529 "Like `set-file-modes' for Tramp files."
1530 (with-parsed-tramp-file-name filename nil
1531 (tramp-flush-file-property v (file-name-directory localname))
1532 (tramp-flush-file-property v localname)
1533 ;; FIXME: extract the proper text from chmod's stderr.
1534 (tramp-barf-unless-okay
1536 (format "chmod %o %s" mode (tramp-shell-quote-argument localname))
1537 "Error while changing file's mode %s" filename)))
1539 (defun tramp-sh-handle-set-file-times (filename &optional time)
1540 "Like `set-file-times' for Tramp files."
1541 (with-parsed-tramp-file-name filename nil
1542 (when (tramp-get-remote-touch v)
1543 (tramp-flush-file-property v (file-name-directory localname))
1544 (tramp-flush-file-property v localname)
1545 (let ((time (if (or (null time) (equal time '(0 0)))
1546 (current-time)
1547 time)))
1548 (tramp-send-command-and-check
1549 v (format
1550 "env TZ=UTC %s %s %s"
1551 (tramp-get-remote-touch v)
1552 (if (tramp-get-connection-property v "touch-t" nil)
1553 (format "-t %s" (format-time-string "%Y%m%d%H%M.%S" time t))
1555 (tramp-shell-quote-argument localname)))))))
1557 (defun tramp-set-file-uid-gid (filename &optional uid gid)
1558 "Set the ownership for FILENAME.
1559 If UID and GID are provided, these values are used; otherwise uid
1560 and gid of the corresponding user is taken. Both parameters must
1561 be non-negative integers."
1562 ;; Modern Unices allow chown only for root. So we might need
1563 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
1564 ;; working with su(do)? when it is needed, so it shall succeed in
1565 ;; the majority of cases.
1566 ;; Don't modify `last-coding-system-used' by accident.
1567 (let ((last-coding-system-used last-coding-system-used))
1568 (if (tramp-tramp-file-p filename)
1569 (with-parsed-tramp-file-name filename nil
1570 (if (and (zerop (user-uid)) (tramp-local-host-p v))
1571 ;; If we are root on the local host, we can do it directly.
1572 (tramp-set-file-uid-gid localname uid gid)
1573 (let ((uid (or (and (natnump uid) uid)
1574 (tramp-get-remote-uid v 'integer)))
1575 (gid (or (and (natnump gid) gid)
1576 (tramp-get-remote-gid v 'integer))))
1577 (tramp-send-command
1578 v (format
1579 "chown %d:%d %s" uid gid
1580 (tramp-shell-quote-argument localname))))))
1582 ;; We handle also the local part, because there doesn't exist
1583 ;; `set-file-uid-gid'. On W32 "chown" might not work. We add a
1584 ;; timeout for this.
1585 (with-timeout (5 nil)
1586 (let ((uid (or (and (natnump uid) uid) (tramp-get-local-uid 'integer)))
1587 (gid (or (and (natnump gid) gid) (tramp-get-local-gid 'integer))))
1588 (tramp-call-process
1589 nil "chown" nil nil nil
1590 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename)))))))
1592 (defun tramp-remote-selinux-p (vec)
1593 "Check, whether SELINUX is enabled on the remote host."
1594 (with-tramp-connection-property (tramp-get-connection-process vec) "selinux-p"
1595 (tramp-send-command-and-check vec "selinuxenabled")))
1597 (defun tramp-sh-handle-file-selinux-context (filename)
1598 "Like `file-selinux-context' for Tramp files."
1599 (with-parsed-tramp-file-name filename nil
1600 (with-tramp-file-property v localname "file-selinux-context"
1601 (let ((context '(nil nil nil nil))
1602 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
1603 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
1604 (when (and (tramp-remote-selinux-p v)
1605 (tramp-send-command-and-check
1606 v (format
1607 "%s -d -Z %s"
1608 (tramp-get-ls-command v)
1609 (tramp-shell-quote-argument localname))))
1610 (with-current-buffer (tramp-get-connection-buffer v)
1611 (goto-char (point-min))
1612 (when (re-search-forward regexp (point-at-eol) t)
1613 (setq context (list (match-string 1) (match-string 2)
1614 (match-string 3) (match-string 4))))))
1615 ;; Return the context.
1616 context))))
1618 (defun tramp-sh-handle-set-file-selinux-context (filename context)
1619 "Like `set-file-selinux-context' for Tramp files."
1620 (with-parsed-tramp-file-name filename nil
1621 (when (and (consp context)
1622 (tramp-remote-selinux-p v))
1623 (let ((user (and (stringp (nth 0 context)) (nth 0 context)))
1624 (role (and (stringp (nth 1 context)) (nth 1 context)))
1625 (type (and (stringp (nth 2 context)) (nth 2 context)))
1626 (range (and (stringp (nth 3 context)) (nth 3 context))))
1627 (when (tramp-send-command-and-check
1628 v (format "chcon %s %s %s %s %s"
1629 (if user (format "--user=%s" user) "")
1630 (if role (format "--role=%s" role) "")
1631 (if type (format "--type=%s" type) "")
1632 (if range (format "--range=%s" range) "")
1633 (tramp-shell-quote-argument localname)))
1634 (if (and user role type range)
1635 (tramp-set-file-property
1636 v localname "file-selinux-context" context)
1637 (tramp-set-file-property
1638 v localname "file-selinux-context" 'undef))
1639 t)))))
1641 (defun tramp-remote-acl-p (vec)
1642 "Check, whether ACL is enabled on the remote host."
1643 (with-tramp-connection-property (tramp-get-connection-process vec) "acl-p"
1644 (tramp-send-command-and-check vec "getfacl /")))
1646 (defun tramp-sh-handle-file-acl (filename)
1647 "Like `file-acl' for Tramp files."
1648 (with-parsed-tramp-file-name filename nil
1649 (with-tramp-file-property v localname "file-acl"
1650 (when (and (tramp-remote-acl-p v)
1651 (tramp-send-command-and-check
1652 v (format
1653 "getfacl -ac %s"
1654 (tramp-shell-quote-argument localname))))
1655 (with-current-buffer (tramp-get-connection-buffer v)
1656 (goto-char (point-max))
1657 (delete-blank-lines)
1658 (when (> (point-max) (point-min))
1659 (substring-no-properties (buffer-string))))))))
1661 (defun tramp-sh-handle-set-file-acl (filename acl-string)
1662 "Like `set-file-acl' for Tramp files."
1663 (with-parsed-tramp-file-name (expand-file-name filename) nil
1664 (if (and (stringp acl-string) (tramp-remote-acl-p v)
1665 (progn
1666 (tramp-send-command
1667 v (format "setfacl --set-file=- %s <<'%s'\n%s\n%s\n"
1668 (tramp-shell-quote-argument localname)
1669 tramp-end-of-heredoc
1670 acl-string
1671 tramp-end-of-heredoc))
1672 (tramp-send-command-and-check v nil)))
1673 ;; Success.
1674 (progn
1675 (tramp-set-file-property v localname "file-acl" acl-string)
1677 ;; In case of errors, we return nil.
1678 (tramp-set-file-property v localname "file-acl-string" 'undef)
1679 nil)))
1681 ;; Simple functions using the `test' command.
1683 (defun tramp-sh-handle-file-executable-p (filename)
1684 "Like `file-executable-p' for Tramp files."
1685 (with-parsed-tramp-file-name filename nil
1686 (with-tramp-file-property v localname "file-executable-p"
1687 ;; Examine `file-attributes' cache to see if request can be
1688 ;; satisfied without remote operation.
1689 (or (tramp-check-cached-permissions v ?x)
1690 (tramp-run-test "-x" filename)))))
1692 (defun tramp-sh-handle-file-readable-p (filename)
1693 "Like `file-readable-p' for Tramp files."
1694 (with-parsed-tramp-file-name filename nil
1695 (with-tramp-file-property v localname "file-readable-p"
1696 ;; Examine `file-attributes' cache to see if request can be
1697 ;; satisfied without remote operation.
1698 (or (tramp-check-cached-permissions v ?r)
1699 (tramp-run-test "-r" filename)))))
1701 ;; When the remote shell is started, it looks for a shell which groks
1702 ;; tilde expansion. Here, we assume that all shells which grok tilde
1703 ;; expansion will also provide a `test' command which groks `-nt' (for
1704 ;; newer than). If this breaks, tell me about it and I'll try to do
1705 ;; something smarter about it.
1706 (defun tramp-sh-handle-file-newer-than-file-p (file1 file2)
1707 "Like `file-newer-than-file-p' for Tramp files."
1708 (cond ((not (file-exists-p file1))
1709 nil)
1710 ((not (file-exists-p file2))
1712 ;; We are sure both files exist at this point.
1714 (save-excursion
1715 ;; We try to get the mtime of both files. If they are not
1716 ;; equal to the "dont-know" value, then we subtract the times
1717 ;; and obtain the result.
1718 (let ((fa1 (file-attributes file1))
1719 (fa2 (file-attributes file2)))
1720 (if (and
1721 (not
1722 (equal (tramp-compat-file-attribute-modification-time fa1)
1723 '(0 0)))
1724 (not
1725 (equal (tramp-compat-file-attribute-modification-time fa2)
1726 '(0 0))))
1727 (> 0 (tramp-time-diff
1728 (tramp-compat-file-attribute-modification-time fa2)
1729 (tramp-compat-file-attribute-modification-time fa1)))
1730 ;; If one of them is the dont-know value, then we can
1731 ;; still try to run a shell command on the remote host.
1732 ;; However, this only works if both files are Tramp
1733 ;; files and both have the same method, same user, same
1734 ;; host.
1735 (unless (tramp-equal-remote file1 file2)
1736 (with-parsed-tramp-file-name
1737 (if (tramp-tramp-file-p file1) file1 file2) nil
1738 (tramp-error
1739 v 'file-error
1740 "Files %s and %s must have same method, user, host"
1741 file1 file2)))
1742 (with-parsed-tramp-file-name file1 nil
1743 (tramp-run-test2
1744 (tramp-get-test-nt-command v) file1 file2))))))))
1746 ;; Functions implemented using the basic functions above.
1748 (defun tramp-sh-handle-file-directory-p (filename)
1749 "Like `file-directory-p' for Tramp files."
1750 (with-parsed-tramp-file-name filename nil
1751 ;; `file-directory-p' is used as predicate for file name completion.
1752 ;; Sometimes, when a connection is not established yet, it is
1753 ;; desirable to return t immediately for "/method:foo:". It can
1754 ;; be expected that this is always a directory.
1755 (or (zerop (length localname))
1756 (with-tramp-file-property v localname "file-directory-p"
1757 (tramp-run-test "-d" filename)))))
1759 (defun tramp-sh-handle-file-writable-p (filename)
1760 "Like `file-writable-p' for Tramp files."
1761 (with-parsed-tramp-file-name filename nil
1762 (with-tramp-file-property v localname "file-writable-p"
1763 (if (file-exists-p filename)
1764 ;; Examine `file-attributes' cache to see if request can be
1765 ;; satisfied without remote operation.
1766 (or (tramp-check-cached-permissions v ?w)
1767 (tramp-run-test "-w" filename))
1768 ;; If file doesn't exist, check if directory is writable.
1769 (and (tramp-run-test "-d" (file-name-directory filename))
1770 (tramp-run-test "-w" (file-name-directory filename)))))))
1772 (defun tramp-sh-handle-file-ownership-preserved-p (filename &optional group)
1773 "Like `file-ownership-preserved-p' for Tramp files."
1774 (with-parsed-tramp-file-name filename nil
1775 (with-tramp-file-property v localname "file-ownership-preserved-p"
1776 (let ((attributes (file-attributes filename)))
1777 ;; Return t if the file doesn't exist, since it's true that no
1778 ;; information would be lost by an (attempted) delete and create.
1779 (or (null attributes)
1780 (and
1781 (= (tramp-compat-file-attribute-user-id attributes)
1782 (tramp-get-remote-uid v 'integer))
1783 (or (not group)
1784 (= (tramp-compat-file-attribute-group-id attributes)
1785 (tramp-get-remote-gid v 'integer)))))))))
1787 ;; Directory listings.
1789 (defun tramp-sh-handle-directory-files-and-attributes
1790 (directory &optional full match nosort id-format)
1791 "Like `directory-files-and-attributes' for Tramp files."
1792 (unless id-format (setq id-format 'integer))
1793 (when (file-directory-p directory)
1794 (setq directory (expand-file-name directory))
1795 (let* ((temp
1796 (copy-tree
1797 (with-parsed-tramp-file-name directory nil
1798 (with-tramp-file-property
1799 v localname
1800 (format "directory-files-and-attributes-%s" id-format)
1801 (save-excursion
1802 (mapcar
1803 (lambda (x)
1804 (cons (car x)
1805 (tramp-convert-file-attributes v (cdr x))))
1807 (cond
1808 ((tramp-get-remote-stat v)
1809 (tramp-do-directory-files-and-attributes-with-stat
1810 v localname id-format))
1811 ((tramp-get-remote-perl v)
1812 (tramp-do-directory-files-and-attributes-with-perl
1813 v localname id-format))
1814 (t nil)))))))))
1815 result item)
1817 (while temp
1818 (setq item (pop temp))
1819 (when (or (null match) (string-match match (car item)))
1820 (when full
1821 (setcar item (expand-file-name (car item) directory)))
1822 (push item result)))
1824 (or (if nosort
1825 result
1826 (sort result (lambda (x y) (string< (car x) (car y)))))
1827 ;; The scripts could fail, for example with huge file size.
1828 (tramp-handle-directory-files-and-attributes
1829 directory full match nosort id-format)))))
1831 (defun tramp-do-directory-files-and-attributes-with-perl
1832 (vec localname &optional id-format)
1833 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
1834 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
1835 (tramp-maybe-send-script
1836 vec tramp-perl-directory-files-and-attributes
1837 "tramp_perl_directory_files_and_attributes")
1838 (let ((object
1839 (tramp-send-command-and-read
1841 (format "tramp_perl_directory_files_and_attributes %s %s"
1842 (tramp-shell-quote-argument localname) id-format))))
1843 (when (stringp object) (tramp-error vec 'file-error object))
1844 object))
1846 (defun tramp-do-directory-files-and-attributes-with-stat
1847 (vec localname &optional id-format)
1848 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
1849 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
1850 (tramp-send-command-and-read
1852 (format
1853 (concat
1854 ;; We must care about file names with spaces, or starting with
1855 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
1856 ;; but it does not work on all remote systems. Apostrophes in
1857 ;; the stat output are masked as `tramp-stat-marker', in order to
1858 ;; make a proper shell escape of them in file names.
1859 "cd %s && echo \"(\"; (%s %s -a | "
1860 "xargs %s -c "
1861 "'(%s%%n%s (%s%%N%s) %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 %s%%A%s t %%ie0 -1)' "
1862 "-- 2>/dev/null | sed -e 's/\"/\\\\\"/g' -e 's/%s/\"/g'); echo \")\"")
1863 (tramp-shell-quote-argument localname)
1864 (tramp-get-ls-command vec)
1865 ;; On systems which have no quoting style, file names with special
1866 ;; characters could fail.
1867 (cond
1868 ((tramp-get-ls-command-with-quoting-style vec)
1869 "--quoting-style=shell")
1870 ((tramp-get-ls-command-with-w-option vec)
1871 "-w")
1872 (t ""))
1873 (tramp-get-remote-stat vec)
1874 tramp-stat-marker tramp-stat-marker
1875 tramp-stat-marker tramp-stat-marker
1876 (if (eq id-format 'integer)
1877 "%ue0" (concat tramp-stat-marker "%U" tramp-stat-marker))
1878 (if (eq id-format 'integer)
1879 "%ge0" (concat tramp-stat-marker "%G" tramp-stat-marker))
1880 tramp-stat-marker tramp-stat-marker
1881 tramp-stat-quoted-marker)))
1883 ;; This function should return "foo/" for directories and "bar" for
1884 ;; files.
1885 (defun tramp-sh-handle-file-name-all-completions (filename directory)
1886 "Like `file-name-all-completions' for Tramp files."
1887 (unless (save-match-data (string-match "/" filename))
1888 (all-completions
1889 filename
1890 (with-parsed-tramp-file-name (expand-file-name directory) nil
1891 (with-tramp-file-property v localname "file-name-all-completions"
1892 (let (result)
1893 ;; Get a list of directories and files, including reliably
1894 ;; tagging the directories with a trailing "/". Because I
1895 ;; rock. --daniel@danann.net
1896 (tramp-send-command
1898 (if (tramp-get-remote-perl v)
1899 (progn
1900 (tramp-maybe-send-script
1901 v tramp-perl-file-name-all-completions
1902 "tramp_perl_file_name_all_completions")
1903 (format "tramp_perl_file_name_all_completions %s"
1904 (tramp-shell-quote-argument localname)))
1906 (format (concat
1907 "(cd %s 2>&1 && %s -a 2>/dev/null"
1908 " | while IFS= read f; do"
1909 " if %s -d \"$f\" 2>/dev/null;"
1910 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
1911 " && \\echo ok) || \\echo fail")
1912 (tramp-shell-quote-argument localname)
1913 (tramp-get-ls-command v)
1914 (tramp-get-test-command v))))
1916 ;; Now grab the output.
1917 (with-current-buffer (tramp-get-buffer v)
1918 (goto-char (point-max))
1920 ;; Check result code, found in last line of output.
1921 (forward-line -1)
1922 (if (looking-at "^fail$")
1923 (progn
1924 ;; Grab error message from line before last line
1925 ;; (it was put there by `cd 2>&1').
1926 (forward-line -1)
1927 (tramp-error
1928 v 'file-error
1929 "tramp-sh-handle-file-name-all-completions: %s"
1930 (buffer-substring (point) (point-at-eol))))
1931 ;; For peace of mind, if buffer doesn't end in `fail'
1932 ;; then it should end in `ok'. If neither are in the
1933 ;; buffer something went seriously wrong on the remote
1934 ;; side.
1935 (unless (looking-at "^ok$")
1936 (tramp-error
1937 v 'file-error "\
1938 tramp-sh-handle-file-name-all-completions: internal error accessing `%s': `%s'"
1939 (tramp-shell-quote-argument localname) (buffer-string))))
1941 (while (zerop (forward-line -1))
1942 (push (buffer-substring (point) (point-at-eol)) result)))
1943 result))))))
1945 ;; cp, mv and ln
1947 (defun tramp-sh-handle-add-name-to-file
1948 (filename newname &optional ok-if-already-exists)
1949 "Like `add-name-to-file' for Tramp files."
1950 (unless (tramp-equal-remote filename newname)
1951 (with-parsed-tramp-file-name
1952 (if (tramp-tramp-file-p filename) filename newname) nil
1953 (tramp-error
1954 v 'file-error
1955 "add-name-to-file: %s"
1956 "only implemented for same method, same user, same host")))
1957 (with-parsed-tramp-file-name filename v1
1958 (with-parsed-tramp-file-name newname v2
1959 (let ((ln (when v1 (tramp-get-remote-ln v1))))
1960 (when (and (numberp ok-if-already-exists)
1961 (file-exists-p newname)
1962 (yes-or-no-p
1963 (format
1964 "File %s already exists; make it a new name anyway? "
1965 newname)))
1966 (tramp-error
1967 v2 'file-already-exists
1968 "add-name-to-file: file %s already exists" newname))
1969 (when ok-if-already-exists (setq ln (concat ln " -f")))
1970 (tramp-flush-file-property v2 (file-name-directory v2-localname))
1971 (tramp-flush-file-property v2 v2-localname)
1972 (tramp-barf-unless-okay
1974 (format "%s %s %s" ln
1975 (tramp-shell-quote-argument v1-localname)
1976 (tramp-shell-quote-argument v2-localname))
1977 "error with add-name-to-file, see buffer `%s' for details"
1978 (buffer-name))))))
1980 (defun tramp-sh-handle-copy-file
1981 (filename newname &optional ok-if-already-exists keep-date
1982 preserve-uid-gid preserve-extended-attributes)
1983 "Like `copy-file' for Tramp files."
1984 (setq filename (expand-file-name filename))
1985 (setq newname (expand-file-name newname))
1986 (cond
1987 ;; At least one file a Tramp file?
1988 ((or (tramp-tramp-file-p filename)
1989 (tramp-tramp-file-p newname))
1990 (tramp-do-copy-or-rename-file
1991 'copy filename newname ok-if-already-exists keep-date
1992 preserve-uid-gid preserve-extended-attributes))
1993 ;; Compat section. PRESERVE-EXTENDED-ATTRIBUTES has been
1994 ;; introduced with Emacs 24.1 (as PRESERVE-SELINUX-CONTEXT), and
1995 ;; renamed in Emacs 24.3.
1996 (preserve-extended-attributes
1997 (tramp-run-real-handler
1998 'copy-file
1999 (list filename newname ok-if-already-exists keep-date
2000 preserve-uid-gid preserve-extended-attributes)))
2002 (tramp-run-real-handler
2003 'copy-file
2004 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))))
2006 (defun tramp-sh-handle-copy-directory
2007 (dirname newname &optional keep-date parents copy-contents)
2008 "Like `copy-directory' for Tramp files."
2009 (let ((t1 (tramp-tramp-file-p dirname))
2010 (t2 (tramp-tramp-file-p newname)))
2011 (with-parsed-tramp-file-name (if t1 dirname newname) nil
2012 (if (and (not copy-contents)
2013 (tramp-get-method-parameter v 'tramp-copy-recursive)
2014 ;; When DIRNAME and NEWNAME are remote, they must have
2015 ;; the same method.
2016 (or (null t1) (null t2)
2017 (string-equal
2018 (tramp-file-name-method (tramp-dissect-file-name dirname))
2019 (tramp-file-name-method
2020 (tramp-dissect-file-name newname)))))
2021 ;; scp or rsync DTRT.
2022 (progn
2023 (setq dirname (directory-file-name (expand-file-name dirname))
2024 newname (directory-file-name (expand-file-name newname)))
2025 (if (and (file-directory-p newname)
2026 (not (string-equal (file-name-nondirectory dirname)
2027 (file-name-nondirectory newname))))
2028 (setq newname
2029 (expand-file-name
2030 (file-name-nondirectory dirname) newname)))
2031 (if (not (file-directory-p (file-name-directory newname)))
2032 (make-directory (file-name-directory newname) parents))
2033 (tramp-do-copy-or-rename-file-out-of-band
2034 'copy dirname newname keep-date))
2035 ;; We must do it file-wise.
2036 (tramp-run-real-handler
2037 'copy-directory
2038 (if copy-contents
2039 (list dirname newname keep-date parents copy-contents)
2040 (list dirname newname keep-date parents))))
2042 ;; When newname did exist, we have wrong cached values.
2043 (when t2
2044 (with-parsed-tramp-file-name newname nil
2045 (tramp-flush-file-property v (file-name-directory localname))
2046 (tramp-flush-file-property v localname))))))
2048 (defun tramp-sh-handle-rename-file
2049 (filename newname &optional ok-if-already-exists)
2050 "Like `rename-file' for Tramp files."
2051 ;; Check if both files are local -- invoke normal rename-file.
2052 ;; Otherwise, use Tramp from local system.
2053 (setq filename (expand-file-name filename))
2054 (setq newname (expand-file-name newname))
2055 ;; At least one file a Tramp file?
2056 (if (or (tramp-tramp-file-p filename)
2057 (tramp-tramp-file-p newname))
2058 (tramp-do-copy-or-rename-file
2059 'rename filename newname ok-if-already-exists
2060 'keep-time 'preserve-uid-gid)
2061 (tramp-run-real-handler
2062 'rename-file (list filename newname ok-if-already-exists))))
2064 (defun tramp-do-copy-or-rename-file
2065 (op filename newname &optional ok-if-already-exists keep-date
2066 preserve-uid-gid preserve-extended-attributes)
2067 "Copy or rename a remote file.
2068 OP must be `copy' or `rename' and indicates the operation to perform.
2069 FILENAME specifies the file to copy or rename, NEWNAME is the name of
2070 the new file (for copy) or the new name of the file (for rename).
2071 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
2072 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2073 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2074 the uid and gid if both files are on the same host.
2075 PRESERVE-EXTENDED-ATTRIBUTES activates selinux and acl commands.
2077 This function is invoked by `tramp-sh-handle-copy-file' and
2078 `tramp-sh-handle-rename-file'. It is an error if OP is neither
2079 of `copy' and `rename'. FILENAME and NEWNAME must be absolute
2080 file names."
2081 (unless (memq op '(copy rename))
2082 (error "Unknown operation `%s', must be `copy' or `rename'" op))
2083 (let ((t1 (tramp-tramp-file-p filename))
2084 (t2 (tramp-tramp-file-p newname))
2085 (length (tramp-compat-file-attribute-size
2086 (file-attributes (file-truename filename))))
2087 (attributes (and preserve-extended-attributes
2088 (apply 'file-extended-attributes (list filename)))))
2090 (with-parsed-tramp-file-name (if t1 filename newname) nil
2091 (when (and (not ok-if-already-exists) (file-exists-p newname))
2092 (tramp-error
2093 v 'file-already-exists "File %s already exists" newname))
2095 (with-tramp-progress-reporter
2096 v 0 (format "%s %s to %s"
2097 (if (eq op 'copy) "Copying" "Renaming")
2098 filename newname)
2100 (cond
2101 ;; Both are Tramp files.
2102 ((and t1 t2)
2103 (with-parsed-tramp-file-name filename v1
2104 (with-parsed-tramp-file-name newname v2
2105 (cond
2106 ;; Shortcut: if method, host, user are the same for
2107 ;; both files, we invoke `cp' or `mv' on the remote
2108 ;; host directly.
2109 ((tramp-equal-remote filename newname)
2110 (tramp-do-copy-or-rename-file-directly
2111 op filename newname
2112 ok-if-already-exists keep-date preserve-uid-gid))
2114 ;; Try out-of-band operation.
2115 ((and
2116 (tramp-method-out-of-band-p v1 length)
2117 (tramp-method-out-of-band-p v2 length))
2118 (tramp-do-copy-or-rename-file-out-of-band
2119 op filename newname keep-date))
2121 ;; No shortcut was possible. So we copy the file
2122 ;; first. If the operation was `rename', we go back
2123 ;; and delete the original file (if the copy was
2124 ;; successful). The approach is simple-minded: we
2125 ;; create a new buffer, insert the contents of the
2126 ;; source file into it, then write out the buffer to
2127 ;; the target file. The advantage is that it doesn't
2128 ;; matter which file name handlers are used for the
2129 ;; source and target file.
2131 (tramp-do-copy-or-rename-file-via-buffer
2132 op filename newname keep-date))))))
2134 ;; One file is a Tramp file, the other one is local.
2135 ((or t1 t2)
2136 (cond
2137 ;; Fast track on local machine.
2138 ((tramp-local-host-p v)
2139 (tramp-do-copy-or-rename-file-directly
2140 op filename newname
2141 ok-if-already-exists keep-date preserve-uid-gid))
2143 ;; If the Tramp file has an out-of-band method, the
2144 ;; corresponding copy-program can be invoked.
2145 ((tramp-method-out-of-band-p v length)
2146 (tramp-do-copy-or-rename-file-out-of-band
2147 op filename newname keep-date))
2149 ;; Use the inline method via a Tramp buffer.
2150 (t (tramp-do-copy-or-rename-file-via-buffer
2151 op filename newname keep-date))))
2154 ;; One of them must be a Tramp file.
2155 (error "Tramp implementation says this cannot happen")))
2157 ;; Handle `preserve-extended-attributes'. We ignore possible
2158 ;; errors, because ACL strings could be incompatible.
2159 (when attributes
2160 (ignore-errors
2161 (apply 'set-file-extended-attributes (list newname attributes))))
2163 ;; In case of `rename', we must flush the cache of the source file.
2164 (when (and t1 (eq op 'rename))
2165 (with-parsed-tramp-file-name filename v1
2166 (tramp-flush-file-property v1 (file-name-directory v1-localname))
2167 (tramp-flush-file-property v1 v1-localname)))
2169 ;; When newname did exist, we have wrong cached values.
2170 (when t2
2171 (with-parsed-tramp-file-name newname v2
2172 (tramp-flush-file-property v2 (file-name-directory v2-localname))
2173 (tramp-flush-file-property v2 v2-localname)))))))
2175 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
2176 "Use an Emacs buffer to copy or rename a file.
2177 First arg OP is either `copy' or `rename' and indicates the operation.
2178 FILENAME is the source file, NEWNAME the target file.
2179 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
2180 ;; We must disable multibyte, because binary data shall not be
2181 ;; converted. We don't want the target file to be compressed, so we
2182 ;; let-bind `jka-compr-inhibit' to t. `epa-file-handler' shall not
2183 ;; be called either. We remove `tramp-file-name-handler' from
2184 ;; `inhibit-file-name-handlers'; otherwise the file name handler for
2185 ;; `insert-file-contents' might be deactivated in some corner cases.
2186 (let ((coding-system-for-read 'binary)
2187 (coding-system-for-write 'binary)
2188 (jka-compr-inhibit t)
2189 (inhibit-file-name-operation 'write-region)
2190 (inhibit-file-name-handlers
2191 (cons 'epa-file-handler
2192 (remq 'tramp-file-name-handler inhibit-file-name-handlers))))
2193 (with-temp-file newname
2194 (set-buffer-multibyte nil)
2195 (insert-file-contents-literally filename)))
2196 ;; KEEP-DATE handling.
2197 (when keep-date
2198 (set-file-times
2199 newname
2200 (tramp-compat-file-attribute-modification-time
2201 (file-attributes filename))))
2202 ;; Set the mode.
2203 (set-file-modes newname (tramp-default-file-modes filename))
2204 ;; If the operation was `rename', delete the original file.
2205 (unless (eq op 'copy) (delete-file filename)))
2207 (defun tramp-do-copy-or-rename-file-directly
2208 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
2209 "Invokes `cp' or `mv' on the remote system.
2210 OP must be one of `copy' or `rename', indicating `cp' or `mv',
2211 respectively. FILENAME specifies the file to copy or rename,
2212 NEWNAME is the name of the new file (for copy) or the new name of
2213 the file (for rename). Both files must reside on the same host.
2214 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2215 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2216 the uid and gid from FILENAME."
2217 (let ((t1 (tramp-tramp-file-p filename))
2218 (t2 (tramp-tramp-file-p newname))
2219 (file-times (tramp-compat-file-attribute-modification-time
2220 (file-attributes filename)))
2221 (file-modes (tramp-default-file-modes filename)))
2222 (with-parsed-tramp-file-name (if t1 filename newname) nil
2223 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
2224 ((eq op 'copy) "cp -f")
2225 ((eq op 'rename) "mv -f")
2226 (t (tramp-error
2227 v 'file-error
2228 "Unknown operation `%s', must be `copy' or `rename'"
2229 op))))
2230 (localname1
2231 (if t1
2232 (file-remote-p filename 'localname)
2233 filename))
2234 (localname2
2235 (if t2
2236 (file-remote-p newname 'localname)
2237 newname))
2238 (prefix (file-remote-p (if t1 filename newname)))
2239 cmd-result)
2241 (cond
2242 ;; Both files are on a remote host, with same user.
2243 ((and t1 t2)
2244 (setq cmd-result
2245 (tramp-send-command-and-check
2246 v (format "%s %s %s" cmd
2247 (tramp-shell-quote-argument localname1)
2248 (tramp-shell-quote-argument localname2))))
2249 (with-current-buffer (tramp-get-buffer v)
2250 (goto-char (point-min))
2251 (unless
2253 (and keep-date
2254 ;; Mask cp -f error.
2255 (re-search-forward
2256 tramp-operation-not-permitted-regexp nil t))
2257 cmd-result)
2258 (tramp-error-with-buffer
2259 nil v 'file-error
2260 "Copying directly failed, see buffer `%s' for details."
2261 (buffer-name)))))
2263 ;; We are on the local host.
2264 ((or t1 t2)
2265 (cond
2266 ;; We can do it directly.
2267 ((let (file-name-handler-alist)
2268 (and (file-readable-p localname1)
2269 ;; No sticky bit when renaming.
2270 (or (eq op 'copy)
2271 (zerop
2272 (logand
2273 (file-modes (file-name-directory localname1))
2274 (string-to-number "1000" 8))))
2275 (file-writable-p (file-name-directory localname2))
2276 (or (file-directory-p localname2)
2277 (file-writable-p localname2))))
2278 (if (eq op 'copy)
2279 (copy-file
2280 localname1 localname2 ok-if-already-exists
2281 keep-date preserve-uid-gid)
2282 (tramp-run-real-handler
2283 'rename-file (list localname1 localname2 ok-if-already-exists))))
2285 ;; We can do it directly with `tramp-send-command'
2286 ((and (file-readable-p (concat prefix localname1))
2287 (file-writable-p
2288 (file-name-directory (concat prefix localname2)))
2289 (or (file-directory-p (concat prefix localname2))
2290 (file-writable-p (concat prefix localname2))))
2291 (tramp-do-copy-or-rename-file-directly
2292 op (concat prefix localname1) (concat prefix localname2)
2293 ok-if-already-exists keep-date t)
2294 ;; We must change the ownership to the local user.
2295 (tramp-set-file-uid-gid
2296 (concat prefix localname2)
2297 (tramp-get-local-uid 'integer)
2298 (tramp-get-local-gid 'integer)))
2300 ;; We need a temporary file in between.
2302 ;; Create the temporary file.
2303 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
2304 (unwind-protect
2305 (progn
2306 (cond
2308 (tramp-barf-unless-okay
2309 v (format
2310 "%s %s %s" cmd
2311 (tramp-shell-quote-argument localname1)
2312 (tramp-shell-quote-argument tmpfile))
2313 "Copying directly failed, see buffer `%s' for details."
2314 (tramp-get-buffer v))
2315 ;; We must change the ownership as remote user.
2316 ;; Since this does not work reliable, we also
2317 ;; give read permissions.
2318 (set-file-modes
2319 (concat prefix tmpfile) (string-to-number "0777" 8))
2320 (tramp-set-file-uid-gid
2321 (concat prefix tmpfile)
2322 (tramp-get-local-uid 'integer)
2323 (tramp-get-local-gid 'integer)))
2325 (if (eq op 'copy)
2326 (copy-file
2327 localname1 tmpfile t
2328 keep-date preserve-uid-gid)
2329 (tramp-run-real-handler
2330 'rename-file
2331 (list localname1 tmpfile t)))
2332 ;; We must change the ownership as local user.
2333 ;; Since this does not work reliable, we also
2334 ;; give read permissions.
2335 (set-file-modes tmpfile (string-to-number "0777" 8))
2336 (tramp-set-file-uid-gid
2337 tmpfile
2338 (tramp-get-remote-uid v 'integer)
2339 (tramp-get-remote-gid v 'integer))))
2341 ;; Move the temporary file to its destination.
2342 (cond
2344 (tramp-barf-unless-okay
2345 v (format
2346 "cp -f -p %s %s"
2347 (tramp-shell-quote-argument tmpfile)
2348 (tramp-shell-quote-argument localname2))
2349 "Copying directly failed, see buffer `%s' for details."
2350 (tramp-get-buffer v)))
2352 (tramp-run-real-handler
2353 'rename-file
2354 (list tmpfile localname2 ok-if-already-exists)))))
2356 ;; Save exit.
2357 (ignore-errors (delete-file tmpfile)))))))))
2359 ;; Set the time and mode. Mask possible errors.
2360 (ignore-errors
2361 (when keep-date
2362 (set-file-times newname file-times)
2363 (set-file-modes newname file-modes))))))
2365 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
2366 "Invoke `scp' program to copy.
2367 The method used must be an out-of-band method."
2368 (let* ((t1 (tramp-tramp-file-p filename))
2369 (t2 (tramp-tramp-file-p newname))
2370 (orig-vec (tramp-dissect-file-name (if t1 filename newname)))
2371 copy-program copy-args copy-env copy-keep-date port listener spec
2372 options source target remote-copy-program remote-copy-args)
2374 (with-parsed-tramp-file-name (if t1 filename newname) nil
2375 (if (and t1 t2)
2377 ;; Both are Tramp files. We shall optimize it when the
2378 ;; methods for FILENAME and NEWNAME are the same.
2379 (let* ((dir-flag (file-directory-p filename))
2380 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
2381 (if dir-flag
2382 (setq tmpfile
2383 (expand-file-name
2384 (file-name-nondirectory newname) tmpfile)))
2385 (unwind-protect
2386 (progn
2387 (tramp-do-copy-or-rename-file-out-of-band
2388 op filename tmpfile keep-date)
2389 (tramp-do-copy-or-rename-file-out-of-band
2390 'rename tmpfile newname keep-date))
2391 ;; Save exit.
2392 (ignore-errors
2393 (if dir-flag
2394 (delete-directory
2395 (expand-file-name ".." tmpfile) 'recursive)
2396 (delete-file tmpfile)))))
2398 ;; Set variables for computing the prompt for reading
2399 ;; password.
2400 (setq tramp-current-method (tramp-file-name-method v)
2401 tramp-current-user (or (tramp-file-name-user v)
2402 (tramp-get-connection-property
2403 v "login-as" nil))
2404 tramp-current-host (tramp-file-name-real-host v))
2406 ;; Expand hops. Might be necessary for gateway methods.
2407 (setq v (car (tramp-compute-multi-hops v)))
2408 (aset v 3 localname)
2410 ;; Check which ones of source and target are Tramp files.
2411 (setq source (funcall
2412 (if (and (file-directory-p filename)
2413 (not (file-exists-p newname)))
2414 'file-name-as-directory
2415 'identity)
2416 (if t1
2417 (tramp-make-copy-program-file-name v)
2418 (tramp-unquote-shell-quote-argument filename)))
2419 target (if t2
2420 (tramp-make-copy-program-file-name v)
2421 (tramp-unquote-shell-quote-argument newname)))
2423 ;; Check for host and port number. We cannot use
2424 ;; `tramp-file-name-port', because this returns also
2425 ;; `tramp-default-port', which might clash with settings in
2426 ;; "~/.ssh/config".
2427 (setq host (tramp-file-name-host v)
2428 port "")
2429 (when (string-match tramp-host-with-port-regexp host)
2430 (setq port (string-to-number (match-string 2 host))
2431 host (string-to-number (match-string 1 host))))
2433 ;; Check for user. There might be an interactive setting.
2434 (setq user (or (tramp-file-name-user v)
2435 (tramp-get-connection-property v "login-as" nil)))
2437 ;; Check for listener port.
2438 (when (tramp-get-method-parameter v 'tramp-remote-copy-args)
2439 (setq listener (number-to-string (+ 50000 (random 10000))))
2440 (while
2441 (zerop (tramp-call-process v "nc" nil nil nil "-z" host listener))
2442 (setq listener (number-to-string (+ 50000 (random 10000))))))
2444 ;; Compose copy command.
2445 (setq host (or host "")
2446 user (or user "")
2447 port (or port "")
2448 spec (format-spec-make
2449 ?t (tramp-get-connection-property
2450 (tramp-get-connection-process v) "temp-file" ""))
2451 options (format-spec (tramp-ssh-controlmaster-options v) spec)
2452 spec (format-spec-make
2453 ?h host ?u user ?p port ?r listener ?c options
2454 ?k (if keep-date " " ""))
2455 copy-program (tramp-get-method-parameter v 'tramp-copy-program)
2456 copy-keep-date (tramp-get-method-parameter
2457 v 'tramp-copy-keep-date)
2459 copy-args
2460 (delete
2461 ;; " " has either been a replacement of "%k" (when
2462 ;; keep-date argument is non-nil), or a replacement
2463 ;; for the whole keep-date sublist.
2465 (dolist
2466 (x (tramp-get-method-parameter v 'tramp-copy-args) copy-args)
2467 (setq copy-args
2468 (append
2469 copy-args
2470 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2471 (if (member "" y) '(" ") y))))))
2473 copy-env
2474 (delq
2476 (mapcar
2477 (lambda (x)
2478 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
2479 (unless (member "" x) (mapconcat 'identity x " ")))
2480 (tramp-get-method-parameter v 'tramp-copy-env)))
2482 remote-copy-program
2483 (tramp-get-method-parameter v 'tramp-remote-copy-program))
2485 (dolist (x (tramp-get-method-parameter v 'tramp-remote-copy-args))
2486 (setq remote-copy-args
2487 (append
2488 remote-copy-args
2489 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2490 (if (member "" y) '(" ") y)))))
2492 ;; Check for local copy program.
2493 (unless (executable-find copy-program)
2494 (tramp-error
2495 v 'file-error "Cannot find local copy program: %s" copy-program))
2497 ;; Install listener on the remote side. The prompt must be
2498 ;; consumed later on, when the process does not listen anymore.
2499 (when remote-copy-program
2500 (unless (with-tramp-connection-property
2501 v (concat "remote-copy-program-" remote-copy-program)
2502 (tramp-find-executable
2503 v remote-copy-program (tramp-get-remote-path v)))
2504 (tramp-error
2505 v 'file-error
2506 "Cannot find remote listener: %s" remote-copy-program))
2507 (setq remote-copy-program
2508 (mapconcat
2509 'identity
2510 (append
2511 (list remote-copy-program) remote-copy-args
2512 (list (if t1 (concat "<" source) (concat ">" target)) "&"))
2513 " "))
2514 (tramp-send-command v remote-copy-program)
2515 (with-timeout
2516 (60 (tramp-error
2517 v 'file-error
2518 "Listener process not running on remote host: `%s'"
2519 remote-copy-program))
2520 (tramp-send-command v (format "netstat -l | grep -q :%s" listener))
2521 (while (not (tramp-send-command-and-check v nil))
2522 (tramp-send-command
2523 v (format "netstat -l | grep -q :%s" listener)))))
2525 (with-temp-buffer
2526 (unwind-protect
2527 ;; The default directory must be remote.
2528 (let ((default-directory
2529 (file-name-directory (if t1 filename newname)))
2530 (process-environment (copy-sequence process-environment)))
2531 ;; Set the transfer process properties.
2532 (tramp-set-connection-property
2533 v "process-name" (buffer-name (current-buffer)))
2534 (tramp-set-connection-property
2535 v "process-buffer" (current-buffer))
2536 (while copy-env
2537 (tramp-message
2538 orig-vec 6 "%s=\"%s\"" (car copy-env) (cadr copy-env))
2539 (setenv (pop copy-env) (pop copy-env)))
2540 (setq
2541 copy-args
2542 (append
2543 copy-args
2544 (if remote-copy-program
2545 (list (if t1 (concat ">" target) (concat "<" source)))
2546 (list source target))))
2548 ;; Use an asynchronous process. By this, password can
2549 ;; be handled. We don't set a timeout, because the
2550 ;; copying of large files can last longer than 60 secs.
2551 (let* ((command
2552 (mapconcat
2553 'identity (append (list copy-program) copy-args)
2554 " "))
2555 (p (let ((default-directory
2556 (tramp-compat-temporary-file-directory)))
2557 (start-process-shell-command
2558 (tramp-get-connection-name v)
2559 (tramp-get-connection-buffer v)
2560 command))))
2561 (tramp-message orig-vec 6 "%s" command)
2562 (tramp-set-connection-property p "vector" orig-vec)
2563 (set-process-query-on-exit-flag p nil)
2565 ;; We must adapt `tramp-local-end-of-line' for
2566 ;; sending the password.
2567 (let ((tramp-local-end-of-line tramp-rsh-end-of-line))
2568 (tramp-process-actions
2569 p v nil tramp-actions-copy-out-of-band))))
2571 ;; Reset the transfer process properties.
2572 (tramp-set-connection-property v "process-name" nil)
2573 (tramp-set-connection-property v "process-buffer" nil)
2574 ;; Clear the remote prompt.
2575 (when (and remote-copy-program
2576 (not (tramp-send-command-and-check v nil)))
2577 ;; Houston, we have a problem! Likely, the listener is
2578 ;; still running, so let's clear everything (but the
2579 ;; cached password).
2580 (tramp-cleanup-connection v 'keep-debug 'keep-password))))
2582 ;; Handle KEEP-DATE argument.
2583 (when (and keep-date (not copy-keep-date))
2584 (set-file-times
2585 newname
2586 (tramp-compat-file-attribute-modification-time
2587 (file-attributes filename))))
2589 ;; Set the mode.
2590 (unless (and keep-date copy-keep-date)
2591 (ignore-errors
2592 (set-file-modes newname (tramp-default-file-modes filename)))))
2594 ;; If the operation was `rename', delete the original file.
2595 (unless (eq op 'copy)
2596 (if (file-regular-p filename)
2597 (delete-file filename)
2598 (delete-directory filename 'recursive))))))
2600 (defun tramp-sh-handle-make-directory (dir &optional parents)
2601 "Like `make-directory' for Tramp files."
2602 (setq dir (expand-file-name dir))
2603 (with-parsed-tramp-file-name dir nil
2604 (tramp-flush-directory-property v (file-name-directory localname))
2605 (save-excursion
2606 (tramp-barf-unless-okay
2607 v (format "%s %s"
2608 (if parents "mkdir -p" "mkdir")
2609 (tramp-shell-quote-argument localname))
2610 "Couldn't make directory %s" dir))))
2612 (defun tramp-sh-handle-delete-directory (directory &optional recursive)
2613 "Like `delete-directory' for Tramp files."
2614 (setq directory (expand-file-name directory))
2615 (with-parsed-tramp-file-name directory nil
2616 (tramp-flush-file-property v (file-name-directory localname))
2617 (tramp-flush-directory-property v localname)
2618 (tramp-barf-unless-okay
2619 v (format "cd / && %s %s"
2620 (if recursive "rm -rf" "rmdir")
2621 (tramp-shell-quote-argument localname))
2622 "Couldn't delete %s" directory)))
2624 (defun tramp-sh-handle-delete-file (filename &optional trash)
2625 "Like `delete-file' for Tramp files."
2626 (setq filename (expand-file-name filename))
2627 (with-parsed-tramp-file-name filename nil
2628 (tramp-flush-file-property v (file-name-directory localname))
2629 (tramp-flush-file-property v localname)
2630 (tramp-barf-unless-okay
2631 v (format "%s %s"
2632 (or (and trash (tramp-get-remote-trash v)) "rm -f")
2633 (tramp-shell-quote-argument localname))
2634 "Couldn't delete %s" filename)))
2636 ;; Dired.
2638 (defvar dired-compress-file-suffixes)
2639 (declare-function dired-remove-file "dired-aux")
2641 (defun tramp-sh-handle-dired-compress-file (file)
2642 "Like `dired-compress-file' for Tramp files."
2643 ;; Code stolen mainly from dired-aux.el.
2644 (with-parsed-tramp-file-name file nil
2645 (tramp-flush-file-property v localname)
2646 (save-excursion
2647 (let ((suffixes dired-compress-file-suffixes)
2648 suffix)
2649 ;; See if any suffix rule matches this file name.
2650 (while suffixes
2651 (let (case-fold-search)
2652 (if (string-match (car (car suffixes)) localname)
2653 (setq suffix (car suffixes) suffixes nil))
2654 (setq suffixes (cdr suffixes))))
2656 (cond ((file-symlink-p file)
2657 nil)
2658 ((and suffix (nth 2 suffix))
2659 ;; We found an uncompression rule.
2660 (with-tramp-progress-reporter
2661 v 0 (format "Uncompressing %s" file)
2662 (when (tramp-send-command-and-check
2663 v (concat (nth 2 suffix) " "
2664 (tramp-shell-quote-argument localname)))
2665 (dired-remove-file file)
2666 (string-match (car suffix) file)
2667 (concat (substring file 0 (match-beginning 0))))))
2669 ;; We don't recognize the file as compressed, so compress it.
2670 ;; Try gzip.
2671 (with-tramp-progress-reporter v 0 (format "Compressing %s" file)
2672 (when (tramp-send-command-and-check
2673 v (concat "gzip -f "
2674 (tramp-shell-quote-argument localname)))
2675 (dired-remove-file file)
2676 (cond ((file-exists-p (concat file ".gz"))
2677 (concat file ".gz"))
2678 ((file-exists-p (concat file ".z"))
2679 (concat file ".z"))
2680 (t nil))))))))))
2682 (defun tramp-sh-handle-insert-directory
2683 (filename switches &optional wildcard full-directory-p)
2684 "Like `insert-directory' for Tramp files."
2685 (setq filename (expand-file-name filename))
2686 (unless switches (setq switches ""))
2687 (with-parsed-tramp-file-name filename nil
2688 (if (and (featurep 'ls-lisp)
2689 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
2690 (tramp-handle-insert-directory
2691 filename switches wildcard full-directory-p)
2692 (when (stringp switches)
2693 (setq switches (split-string switches)))
2694 (when (tramp-get-ls-command-with-quoting-style v)
2695 (setq switches (append switches '("--quoting-style=literal"))))
2696 (when (and (member "--dired" switches)
2697 (not (tramp-get-ls-command-with-dired v)))
2698 (setq switches (delete "--dired" switches)))
2699 (when wildcard
2700 (setq wildcard (tramp-run-real-handler
2701 'file-name-nondirectory (list localname)))
2702 (setq localname (tramp-run-real-handler
2703 'file-name-directory (list localname))))
2704 (unless (or full-directory-p (member "-d" switches))
2705 (setq switches (append switches '("-d"))))
2706 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
2707 (when wildcard
2708 (setq switches (concat switches " " wildcard)))
2709 (tramp-message
2710 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
2711 switches filename (if wildcard "yes" "no")
2712 (if full-directory-p "yes" "no"))
2713 ;; If `full-directory-p', we just say `ls -l FILENAME'.
2714 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
2715 (if full-directory-p
2716 (tramp-send-command
2718 (format "%s %s %s 2>/dev/null"
2719 (tramp-get-ls-command v)
2720 switches
2721 (if wildcard
2722 localname
2723 (tramp-shell-quote-argument (concat localname ".")))))
2724 (tramp-barf-unless-okay
2726 (format "cd %s" (tramp-shell-quote-argument
2727 (tramp-run-real-handler
2728 'file-name-directory (list localname))))
2729 "Couldn't `cd %s'"
2730 (tramp-shell-quote-argument
2731 (tramp-run-real-handler 'file-name-directory (list localname))))
2732 (tramp-send-command
2734 (format "%s %s %s 2>/dev/null"
2735 (tramp-get-ls-command v)
2736 switches
2737 (if (or wildcard
2738 (zerop (length
2739 (tramp-run-real-handler
2740 'file-name-nondirectory (list localname)))))
2742 (tramp-shell-quote-argument
2743 (tramp-run-real-handler
2744 'file-name-nondirectory (list localname)))))))
2746 (save-restriction
2747 (let ((beg (point)))
2748 (narrow-to-region (point) (point))
2749 ;; We cannot use `insert-buffer-substring' because the Tramp
2750 ;; buffer changes its contents before insertion due to calling
2751 ;; `expand-file-name' and alike.
2752 (insert
2753 (with-current-buffer (tramp-get-buffer v)
2754 (buffer-string)))
2756 ;; Check for "--dired" output.
2757 (forward-line -2)
2758 (when (looking-at "//SUBDIRED//")
2759 (forward-line -1))
2760 (when (looking-at "//DIRED//\\s-+")
2761 (let ((databeg (match-end 0))
2762 (end (point-at-eol)))
2763 ;; Now read the numeric positions of file names.
2764 (goto-char databeg)
2765 (while (< (point) end)
2766 (let ((start (+ beg (read (current-buffer))))
2767 (end (+ beg (read (current-buffer)))))
2768 (if (memq (char-after end) '(?\n ?\ ))
2769 ;; End is followed by \n or by " -> ".
2770 (put-text-property start end 'dired-filename t))))))
2771 ;; Remove trailing lines.
2772 (goto-char (point-at-bol))
2773 (while (looking-at "//")
2774 (forward-line 1)
2775 (delete-region (match-beginning 0) (point)))
2777 ;; Some busyboxes are reluctant to discard colors.
2778 (unless
2779 (string-match "color" (tramp-get-connection-property v "ls" ""))
2780 (goto-char beg)
2781 (while
2782 (re-search-forward tramp-display-escape-sequence-regexp nil t)
2783 (replace-match "")))
2785 ;; Decode the output, it could be multibyte.
2786 (decode-coding-region
2787 beg (point-max)
2788 (or file-name-coding-system default-file-name-coding-system))
2790 ;; The inserted file could be from somewhere else.
2791 (when (and (not wildcard) (not full-directory-p))
2792 (goto-char (point-max))
2793 (when (file-symlink-p filename)
2794 (goto-char (search-backward "->" beg 'noerror)))
2795 (search-backward
2796 (if (zerop (length (file-name-nondirectory filename)))
2798 (file-name-nondirectory filename))
2799 beg 'noerror)
2800 (replace-match (file-relative-name filename) t))
2802 (goto-char (point-max)))))))
2804 ;; Canonicalization of file names.
2806 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2807 "Like `expand-file-name' for Tramp files.
2808 If the localname part of the given file name starts with \"/../\" then
2809 the result will be a local, non-Tramp, file name."
2810 ;; If DIR is not given, use `default-directory' or "/".
2811 (setq dir (or dir default-directory "/"))
2812 ;; Unless NAME is absolute, concat DIR and NAME.
2813 (unless (file-name-absolute-p name)
2814 (setq name (concat (file-name-as-directory dir) name)))
2815 ;; If connection is not established yet, run the real handler.
2816 (if (not (tramp-connectable-p name))
2817 (tramp-run-real-handler 'expand-file-name (list name nil))
2818 ;; Dissect NAME.
2819 (with-parsed-tramp-file-name name nil
2820 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2821 (setq localname (concat "~/" localname)))
2822 ;; Tilde expansion if necessary. This needs a shell which
2823 ;; groks tilde expansion! The function `tramp-find-shell' is
2824 ;; supposed to find such a shell on the remote host. Please
2825 ;; tell me about it when this doesn't work on your system.
2826 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2827 (let ((uname (match-string 1 localname))
2828 (fname (match-string 2 localname)))
2829 ;; We cannot simply apply "~/", because under sudo "~/" is
2830 ;; expanded to the local user home directory but to the
2831 ;; root home directory. On the other hand, using always
2832 ;; the default user name for tilde expansion is not
2833 ;; appropriate either, because ssh and companions might
2834 ;; use a user name from the config file.
2835 (when (and (string-equal uname "~")
2836 (string-match "\\`su\\(do\\)?\\'" method))
2837 (setq uname (concat uname user)))
2838 (setq uname
2839 (with-tramp-connection-property v uname
2840 (tramp-send-command
2841 v (format "cd %s && pwd" (tramp-shell-quote-argument uname)))
2842 (with-current-buffer (tramp-get-buffer v)
2843 (goto-char (point-min))
2844 (buffer-substring (point) (point-at-eol)))))
2845 (setq localname (concat uname fname))))
2846 ;; There might be a double slash, for example when "~/"
2847 ;; expands to "/". Remove this.
2848 (while (string-match "//" localname)
2849 (setq localname (replace-match "/" t t localname)))
2850 ;; No tilde characters in file name, do normal
2851 ;; `expand-file-name' (this does "/./" and "/../").
2852 ;; `default-directory' is bound, because on Windows there would
2853 ;; be problems with UNC shares or Cygwin mounts.
2854 (let ((default-directory (tramp-compat-temporary-file-directory)))
2855 (tramp-make-tramp-file-name
2856 method user host
2857 (tramp-drop-volume-letter
2858 (tramp-run-real-handler
2859 'expand-file-name (list localname)))
2860 hop)))))
2862 ;;; Remote commands:
2864 (defun tramp-process-sentinel (proc event)
2865 "Flush file caches."
2866 (unless (tramp-compat-process-live-p proc)
2867 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2868 (when vec
2869 (tramp-message vec 5 "Sentinel called: `%S' `%s'" proc event)
2870 (tramp-flush-connection-property proc)
2871 (tramp-flush-directory-property vec "")))))
2873 ;; We use BUFFER also as connection buffer during setup. Because of
2874 ;; this, its original contents must be saved, and restored once
2875 ;; connection has been setup.
2876 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2877 "Like `start-file-process' for Tramp files."
2878 (with-parsed-tramp-file-name (expand-file-name default-directory) nil
2879 (let* ((buffer
2880 (if buffer
2881 (get-buffer-create buffer)
2882 ;; BUFFER can be nil. We use a temporary buffer.
2883 (generate-new-buffer tramp-temp-buffer-name)))
2884 ;; When PROGRAM matches "*sh", and the first arg is "-c",
2885 ;; it might be that the arguments exceed the command line
2886 ;; length. Therefore, we modify the command.
2887 (heredoc (and (stringp program)
2888 (string-match "sh$" program)
2889 (string-equal "-c" (car args))
2890 (= (length args) 2)))
2891 ;; When PROGRAM is nil, we just provide a tty.
2892 (args (if (not heredoc) args
2893 (let ((i 250))
2894 (while (and (< i (length (cadr args)))
2895 (string-match " " (cadr args) i))
2896 (setcdr
2897 args
2898 (list (replace-match " \\\\\n" nil nil (cadr args))))
2899 (setq i (+ i 250))))
2900 (cdr args)))
2901 ;; Use a human-friendly prompt, for example for `shell'.
2902 ;; We discard hops, if existing, that's why we cannot use
2903 ;; `file-remote-p'.
2904 (prompt (format "PS1=%s %s"
2905 (tramp-make-tramp-file-name
2906 (tramp-file-name-method v)
2907 (tramp-file-name-user v)
2908 (tramp-file-name-host v)
2909 (tramp-file-name-localname v))
2910 tramp-initial-end-of-output))
2911 ;; We use as environment the difference to toplevel
2912 ;; `process-environment'.
2913 env uenv
2914 (env (dolist (elt (cons prompt process-environment) env)
2915 (or (member elt (default-toplevel-value 'process-environment))
2916 (if (string-match "=" elt)
2917 (setq env (append env `(,elt)))
2918 (if (tramp-get-env-with-u-option v)
2919 (setq env (append `("-u" ,elt) env))
2920 (setq uenv (cons elt uenv)))))))
2921 (command
2922 (when (stringp program)
2923 (format "cd %s && %s exec %s env %s %s"
2924 (tramp-shell-quote-argument localname)
2925 (if uenv
2926 (format
2927 "unset %s &&"
2928 (mapconcat 'tramp-shell-quote-argument uenv " "))
2930 (if heredoc (format "<<'%s'" tramp-end-of-heredoc) "")
2931 (mapconcat 'tramp-shell-quote-argument env " ")
2932 (if heredoc
2933 (format "%s\n(\n%s\n) </dev/tty\n%s"
2934 program (car args) tramp-end-of-heredoc)
2935 (mapconcat 'tramp-shell-quote-argument
2936 (cons program args) " ")))))
2937 (tramp-process-connection-type
2938 (or (null program) tramp-process-connection-type))
2939 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2940 (name1 name)
2941 (i 0)
2942 ;; We do not want to raise an error when
2943 ;; `start-file-process' has been started several times in
2944 ;; `eshell' and friends.
2945 (tramp-current-connection nil))
2947 (while (get-process name1)
2948 ;; NAME must be unique as process name.
2949 (setq i (1+ i)
2950 name1 (format "%s<%d>" name i)))
2951 (setq name name1)
2952 ;; Set the new process properties.
2953 (tramp-set-connection-property v "process-name" name)
2954 (tramp-set-connection-property v "process-buffer" buffer)
2956 (with-current-buffer (tramp-get-connection-buffer v)
2957 (unwind-protect
2958 ;; We catch this event. Otherwise, `start-process' could
2959 ;; be called on the local host.
2960 (save-excursion
2961 (save-restriction
2962 ;; Activate narrowing in order to save BUFFER
2963 ;; contents. Clear also the modification time;
2964 ;; otherwise we might be interrupted by
2965 ;; `verify-visited-file-modtime'.
2966 (let ((buffer-undo-list t)
2967 (buffer-read-only nil)
2968 (mark (point-max)))
2969 (clear-visited-file-modtime)
2970 (narrow-to-region (point-max) (point-max))
2971 ;; We call `tramp-maybe-open-connection', in order
2972 ;; to cleanup the prompt afterwards.
2973 (catch 'suppress
2974 (tramp-maybe-open-connection v)
2975 (widen)
2976 (delete-region mark (point))
2977 (narrow-to-region (point-max) (point-max))
2978 ;; Now do it.
2979 (if command
2980 ;; Send the command.
2981 (tramp-send-command v command nil t) ; nooutput
2982 ;; Check, whether a pty is associated.
2983 (unless (process-get
2984 (tramp-get-connection-process v) 'remote-tty)
2985 (tramp-error
2986 v 'file-error
2987 "pty association is not supported for `%s'" name))))
2988 (let ((p (tramp-get-connection-process v)))
2989 ;; Set query flag and process marker for this
2990 ;; process. We ignore errors, because the process
2991 ;; could have finished already.
2992 (ignore-errors
2993 (set-process-query-on-exit-flag p t)
2994 (set-marker (process-mark p) (point)))
2995 ;; Return process.
2996 p))))
2998 ;; Save exit.
2999 (if (string-match tramp-temp-buffer-name (buffer-name))
3000 (ignore-errors
3001 (set-process-buffer (tramp-get-connection-process v) nil)
3002 (kill-buffer (current-buffer)))
3003 (set-buffer-modified-p bmp))
3004 (tramp-set-connection-property v "process-name" nil)
3005 (tramp-set-connection-property v "process-buffer" nil))))))
3007 (defun tramp-sh-handle-process-file
3008 (program &optional infile destination display &rest args)
3009 "Like `process-file' for Tramp files."
3010 ;; The implementation is not complete yet.
3011 (when (and (numberp destination) (zerop destination))
3012 (error "Implementation does not handle immediate return"))
3014 (with-parsed-tramp-file-name default-directory nil
3015 (let (command env uenv input tmpinput stderr tmpstderr outbuf ret)
3016 ;; Compute command.
3017 (setq command (mapconcat 'tramp-shell-quote-argument
3018 (cons program args) " "))
3019 ;; We use as environment the difference to toplevel `process-environment'.
3020 (dolist (elt process-environment)
3021 (or (member elt (default-toplevel-value 'process-environment))
3022 (if (string-match "=" elt)
3023 (setq env (append env `(,elt)))
3024 (if (tramp-get-env-with-u-option v)
3025 (setq env (append `("-u" ,elt) env))
3026 (setq uenv (cons elt uenv))))))
3027 (when env
3028 (setq command
3029 (format
3030 "env %s %s"
3031 (mapconcat 'tramp-shell-quote-argument env " ") command)))
3032 (when uenv
3033 (setq command
3034 (format
3035 "unset %s && %s"
3036 (mapconcat 'tramp-shell-quote-argument uenv " ") command)))
3037 ;; Determine input.
3038 (if (null infile)
3039 (setq input "/dev/null")
3040 (setq infile (expand-file-name infile))
3041 (if (tramp-equal-remote default-directory infile)
3042 ;; INFILE is on the same remote host.
3043 (setq input (with-parsed-tramp-file-name infile nil localname))
3044 ;; INFILE must be copied to remote host.
3045 (setq input (tramp-make-tramp-temp-file v)
3046 tmpinput (tramp-make-tramp-file-name method user host input))
3047 (copy-file infile tmpinput t)))
3048 (when input (setq command (format "%s <%s" command input)))
3050 ;; Determine output.
3051 (cond
3052 ;; Just a buffer.
3053 ((bufferp destination)
3054 (setq outbuf destination))
3055 ;; A buffer name.
3056 ((stringp destination)
3057 (setq outbuf (get-buffer-create destination)))
3058 ;; (REAL-DESTINATION ERROR-DESTINATION)
3059 ((consp destination)
3060 ;; output.
3061 (cond
3062 ((bufferp (car destination))
3063 (setq outbuf (car destination)))
3064 ((stringp (car destination))
3065 (setq outbuf (get-buffer-create (car destination))))
3066 ((car destination)
3067 (setq outbuf (current-buffer))))
3068 ;; stderr.
3069 (cond
3070 ((stringp (cadr destination))
3071 (setcar (cdr destination) (expand-file-name (cadr destination)))
3072 (if (tramp-equal-remote default-directory (cadr destination))
3073 ;; stderr is on the same remote host.
3074 (setq stderr (with-parsed-tramp-file-name
3075 (cadr destination) nil localname))
3076 ;; stderr must be copied to remote host. The temporary
3077 ;; file must be deleted after execution.
3078 (setq stderr (tramp-make-tramp-temp-file v)
3079 tmpstderr (tramp-make-tramp-file-name
3080 method user host stderr))))
3081 ;; stderr to be discarded.
3082 ((null (cadr destination))
3083 (setq stderr "/dev/null"))))
3084 ;; 't
3085 (destination
3086 (setq outbuf (current-buffer))))
3087 (when stderr (setq command (format "%s 2>%s" command stderr)))
3089 ;; Send the command. It might not return in time, so we protect
3090 ;; it. Call it in a subshell, in order to preserve working
3091 ;; directory.
3092 (condition-case nil
3093 (unwind-protect
3094 (setq ret
3095 (if (tramp-send-command-and-check
3096 v (format "cd %s && %s"
3097 (tramp-shell-quote-argument localname)
3098 command)
3099 t t)
3100 0 1))
3101 ;; We should add the output anyway.
3102 (when outbuf
3103 (with-current-buffer outbuf
3104 (insert
3105 (with-current-buffer (tramp-get-connection-buffer v)
3106 (buffer-string))))
3107 (when (and display (get-buffer-window outbuf t)) (redisplay))))
3108 ;; When the user did interrupt, we should do it also. We use
3109 ;; return code -1 as marker.
3110 (quit
3111 (kill-buffer (tramp-get-connection-buffer v))
3112 (setq ret -1))
3113 ;; Handle errors.
3114 (error
3115 (kill-buffer (tramp-get-connection-buffer v))
3116 (setq ret 1)))
3118 ;; Provide error file.
3119 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3121 ;; Cleanup. We remove all file cache values for the connection,
3122 ;; because the remote process could have changed them.
3123 (when tmpinput (delete-file tmpinput))
3125 (unless process-file-side-effects
3126 (tramp-flush-directory-property v ""))
3128 ;; Return exit status.
3129 (if (equal ret -1)
3130 (keyboard-quit)
3131 ret))))
3133 (defun tramp-sh-handle-file-local-copy (filename)
3134 "Like `file-local-copy' for Tramp files."
3135 (with-parsed-tramp-file-name filename nil
3136 (unless (file-exists-p filename)
3137 (tramp-error
3138 v tramp-file-missing
3139 "Cannot make local copy of non-existing file `%s'" filename))
3141 (let* ((size (tramp-compat-file-attribute-size
3142 (file-attributes (file-truename filename))))
3143 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
3144 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
3145 (tmpfile (tramp-compat-make-temp-file filename)))
3147 (condition-case err
3148 (cond
3149 ;; `copy-file' handles direct copy and out-of-band methods.
3150 ((or (tramp-local-host-p v)
3151 (tramp-method-out-of-band-p v size))
3152 (copy-file filename tmpfile 'ok-if-already-exists 'keep-time))
3154 ;; Use inline encoding for file transfer.
3155 (rem-enc
3156 (save-excursion
3157 (with-tramp-progress-reporter
3159 (format-message "Encoding remote file `%s' with `%s'"
3160 filename rem-enc)
3161 (tramp-barf-unless-okay
3162 v (format rem-enc (tramp-shell-quote-argument localname))
3163 "Encoding remote file failed"))
3165 (with-tramp-progress-reporter
3166 v 3 (format-message "Decoding local file `%s' with `%s'"
3167 tmpfile loc-dec)
3168 (if (functionp loc-dec)
3169 ;; If local decoding is a function, we call it.
3170 ;; We must disable multibyte, because
3171 ;; `uudecode-decode-region' doesn't handle it
3172 ;; correctly. Unset `file-name-handler-alist'.
3173 ;; Otherwise, epa-file gets confused.
3174 (let (file-name-handler-alist
3175 (coding-system-for-write 'binary))
3176 (with-temp-file tmpfile
3177 (set-buffer-multibyte nil)
3178 (insert-buffer-substring (tramp-get-buffer v))
3179 (funcall loc-dec (point-min) (point-max))))
3181 ;; If tramp-decoding-function is not defined for this
3182 ;; method, we invoke tramp-decoding-command instead.
3183 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3184 ;; Unset `file-name-handler-alist'. Otherwise,
3185 ;; epa-file gets confused.
3186 (let (file-name-handler-alist
3187 (coding-system-for-write 'binary))
3188 (with-current-buffer (tramp-get-buffer v)
3189 (write-region
3190 (point-min) (point-max) tmpfile2 nil 'no-message)))
3191 (unwind-protect
3192 (tramp-call-local-coding-command
3193 loc-dec tmpfile2 tmpfile)
3194 (delete-file tmpfile2)))))
3196 ;; Set proper permissions.
3197 (set-file-modes tmpfile (tramp-default-file-modes filename))
3198 ;; Set local user ownership.
3199 (tramp-set-file-uid-gid tmpfile)))
3201 ;; Oops, I don't know what to do.
3202 (t (tramp-error
3203 v 'file-error "Wrong method specification for `%s'" method)))
3205 ;; Error handling.
3206 ((error quit)
3207 (delete-file tmpfile)
3208 (signal (car err) (cdr err))))
3210 (run-hooks 'tramp-handle-file-local-copy-hook)
3211 tmpfile)))
3213 ;; CCC grok LOCKNAME
3214 (defun tramp-sh-handle-write-region
3215 (start end filename &optional append visit lockname confirm)
3216 "Like `write-region' for Tramp files."
3217 (setq filename (expand-file-name filename))
3218 (with-parsed-tramp-file-name filename nil
3219 ;; Following part commented out because we don't know what to do about
3220 ;; file locking, and it does not appear to be a problem to ignore it.
3221 ;; Ange-ftp ignores it, too.
3222 ;; (when (and lockname (stringp lockname))
3223 ;; (setq lockname (expand-file-name lockname)))
3224 ;; (unless (or (eq lockname nil)
3225 ;; (string= lockname filename))
3226 ;; (error
3227 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3229 (when (and confirm (file-exists-p filename))
3230 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3231 (tramp-error v 'file-error "File not overwritten")))
3233 (let ((uid (or (tramp-compat-file-attribute-user-id
3234 (file-attributes filename 'integer))
3235 (tramp-get-remote-uid v 'integer)))
3236 (gid (or (tramp-compat-file-attribute-group-id
3237 (file-attributes filename 'integer))
3238 (tramp-get-remote-gid v 'integer))))
3240 (if (and (tramp-local-host-p v)
3241 ;; `file-writable-p' calls `file-expand-file-name'. We
3242 ;; cannot use `tramp-run-real-handler' therefore.
3243 (let (file-name-handler-alist)
3244 (and
3245 (file-writable-p (file-name-directory localname))
3246 (or (file-directory-p localname)
3247 (file-writable-p localname)))))
3248 ;; Short track: if we are on the local host, we can run directly.
3249 (tramp-run-real-handler
3250 'write-region
3251 (list start end localname append 'no-message lockname confirm))
3253 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3254 ;; We use this to save the value of
3255 ;; `last-coding-system-used' after writing the tmp
3256 ;; file. At the end of the function, we set
3257 ;; `last-coding-system-used' to this saved value. This
3258 ;; way, any intermediary coding systems used while
3259 ;; talking to the remote shell or suchlike won't hose
3260 ;; this variable. This approach was snarfed from
3261 ;; ange-ftp.el.
3262 coding-system-used
3263 ;; Write region into a tmp file. This isn't really
3264 ;; needed if we use an encoding function, but currently
3265 ;; we use it always because this makes the logic
3266 ;; simpler. We must also set `temporary-file-directory',
3267 ;; because it could point to a remote directory.
3268 (temporary-file-directory
3269 (tramp-compat-temporary-file-directory))
3270 (tmpfile (or tramp-temp-buffer-file-name
3271 (tramp-compat-make-temp-file filename))))
3273 ;; If `append' is non-nil, we copy the file locally, and let
3274 ;; the native `write-region' implementation do the job.
3275 (when append (copy-file filename tmpfile 'ok))
3277 ;; We say `no-message' here because we don't want the
3278 ;; visited file modtime data to be clobbered from the temp
3279 ;; file. We call `set-visited-file-modtime' ourselves later
3280 ;; on. We must ensure that `file-coding-system-alist'
3281 ;; matches `tmpfile'.
3282 (let (file-name-handler-alist
3283 (file-coding-system-alist
3284 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3285 (condition-case err
3286 (tramp-run-real-handler
3287 'write-region
3288 (list start end tmpfile append 'no-message lockname confirm))
3289 ((error quit)
3290 (setq tramp-temp-buffer-file-name nil)
3291 (delete-file tmpfile)
3292 (signal (car err) (cdr err))))
3294 ;; Now, `last-coding-system-used' has the right value. Remember it.
3295 (setq coding-system-used last-coding-system-used))
3297 ;; The permissions of the temporary file should be set. If
3298 ;; FILENAME does not exist (eq modes nil) it has been
3299 ;; renamed to the backup file. This case `save-buffer'
3300 ;; handles permissions.
3301 ;; Ensure that it is still readable.
3302 (when modes
3303 (set-file-modes
3304 tmpfile
3305 (logior (or modes 0) (string-to-number "0400" 8))))
3307 ;; This is a bit lengthy due to the different methods
3308 ;; possible for file transfer. First, we check whether the
3309 ;; method uses an scp program. If so, we call it.
3310 ;; Otherwise, both encoding and decoding command must be
3311 ;; specified. However, if the method _also_ specifies an
3312 ;; encoding function, then that is used for encoding the
3313 ;; contents of the tmp file.
3314 (let* ((size (tramp-compat-file-attribute-size
3315 (file-attributes tmpfile)))
3316 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3317 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3318 (cond
3319 ;; `copy-file' handles direct copy and out-of-band methods.
3320 ((or (tramp-local-host-p v)
3321 (tramp-method-out-of-band-p v size))
3322 (if (and (not (stringp start))
3323 (= (or end (point-max)) (point-max))
3324 (= (or start (point-min)) (point-min))
3325 (tramp-get-method-parameter v 'tramp-copy-keep-tmpfile))
3326 (progn
3327 (setq tramp-temp-buffer-file-name tmpfile)
3328 (condition-case err
3329 ;; We keep the local file for performance
3330 ;; reasons, useful for "rsync".
3331 (copy-file tmpfile filename t)
3332 ((error quit)
3333 (setq tramp-temp-buffer-file-name nil)
3334 (delete-file tmpfile)
3335 (signal (car err) (cdr err)))))
3336 (setq tramp-temp-buffer-file-name nil)
3337 ;; Don't rename, in order to keep context in SELinux.
3338 (unwind-protect
3339 (copy-file tmpfile filename t)
3340 (delete-file tmpfile))))
3342 ;; Use inline file transfer.
3343 (rem-dec
3344 ;; Encode tmpfile.
3345 (unwind-protect
3346 (with-temp-buffer
3347 (set-buffer-multibyte nil)
3348 ;; Use encoding function or command.
3349 (with-tramp-progress-reporter
3350 v 3 (format-message
3351 "Encoding local file `%s' using `%s'"
3352 tmpfile loc-enc)
3353 (if (functionp loc-enc)
3354 ;; The following `let' is a workaround for
3355 ;; the base64.el that comes with pgnus-0.84.
3356 ;; If both of the following conditions are
3357 ;; satisfied, it tries to write to a local
3358 ;; file in default-directory, but at this
3359 ;; point, default-directory is remote.
3360 ;; (`call-process-region' can't write to
3361 ;; remote files, it seems.) The file in
3362 ;; question is a tmp file anyway.
3363 (let ((coding-system-for-read 'binary)
3364 (default-directory
3365 (tramp-compat-temporary-file-directory)))
3366 (insert-file-contents-literally tmpfile)
3367 (funcall loc-enc (point-min) (point-max)))
3369 (unless (zerop (tramp-call-local-coding-command
3370 loc-enc tmpfile t))
3371 (tramp-error
3372 v 'file-error
3373 (concat "Cannot write to `%s', "
3374 "local encoding command `%s' failed")
3375 filename loc-enc))))
3377 ;; Send buffer into remote decoding command which
3378 ;; writes to remote file. Because this happens on
3379 ;; the remote host, we cannot use the function.
3380 (with-tramp-progress-reporter
3381 v 3 (format-message
3382 "Decoding remote file `%s' using `%s'"
3383 filename rem-dec)
3384 (goto-char (point-max))
3385 (unless (bolp) (newline))
3386 (tramp-send-command
3388 (format
3389 (concat rem-dec " <<'%s'\n%s%s")
3390 (tramp-shell-quote-argument localname)
3391 tramp-end-of-heredoc
3392 (buffer-string)
3393 tramp-end-of-heredoc))
3394 (tramp-barf-unless-okay
3395 v nil
3396 "Couldn't write region to `%s', decode using `%s' failed"
3397 filename rem-dec)
3398 ;; When `file-precious-flag' is set, the region is
3399 ;; written to a temporary file. Check that the
3400 ;; checksum is equal to that from the local tmpfile.
3401 (when file-precious-flag
3402 (erase-buffer)
3403 (and
3404 ;; cksum runs locally, if possible.
3405 (zerop (tramp-call-process v "cksum" tmpfile t))
3406 ;; cksum runs remotely.
3407 (tramp-send-command-and-check
3409 (format
3410 "cksum <%s" (tramp-shell-quote-argument localname)))
3411 ;; ... they are different.
3412 (not
3413 (string-equal
3414 (buffer-string)
3415 (with-current-buffer (tramp-get-buffer v)
3416 (buffer-string))))
3417 (tramp-error
3418 v 'file-error
3419 (concat "Couldn't write region to `%s',"
3420 " decode using `%s' failed")
3421 filename rem-dec)))))
3423 ;; Save exit.
3424 (delete-file tmpfile)))
3426 ;; That's not expected.
3428 (tramp-error
3429 v 'file-error
3430 (concat "Method `%s' should specify both encoding and "
3431 "decoding command or an scp program")
3432 method))))
3434 ;; Make `last-coding-system-used' have the right value.
3435 (when coding-system-used
3436 (set 'last-coding-system-used coding-system-used))))
3438 (tramp-flush-file-property v (file-name-directory localname))
3439 (tramp-flush-file-property v localname)
3441 ;; We must protect `last-coding-system-used', now we have set it
3442 ;; to its correct value.
3443 (let (last-coding-system-used (need-chown t))
3444 ;; Set file modification time.
3445 (when (or (eq visit t) (stringp visit))
3446 (let ((file-attr (file-attributes filename 'integer)))
3447 (set-visited-file-modtime
3448 ;; We must pass modtime explicitly, because FILENAME can
3449 ;; be different from (buffer-file-name), f.e. if
3450 ;; `file-precious-flag' is set.
3451 (tramp-compat-file-attribute-modification-time file-attr))
3452 (when (and (= (tramp-compat-file-attribute-user-id file-attr) uid)
3453 (= (tramp-compat-file-attribute-group-id file-attr) gid))
3454 (setq need-chown nil))))
3456 ;; Set the ownership.
3457 (when need-chown
3458 (tramp-set-file-uid-gid filename uid gid))
3459 (when (or (eq visit t) (null visit) (stringp visit))
3460 (tramp-message v 0 "Wrote %s" filename))
3461 (run-hooks 'tramp-handle-write-region-hook)))))
3463 (defvar tramp-vc-registered-file-names nil
3464 "List used to collect file names, which are checked during `vc-registered'.")
3466 ;; VC backends check for the existence of various different special
3467 ;; files. This is very time consuming, because every single check
3468 ;; requires a remote command (the file cache must be invalidated).
3469 ;; Therefore, we apply a kind of optimization. We install the file
3470 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3471 ;; remembers all file names for which `file-exists-p' or
3472 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3473 ;; is performed. Afterwards, a script is applied for all collected
3474 ;; file names, using just one remote command. The result of this
3475 ;; script is used to fill the file cache with actual values. Now we
3476 ;; can reset the file name handlers, and we make a second run of
3477 ;; `vc-registered', which returns the expected result without sending
3478 ;; any other remote command.
3479 (defun tramp-sh-handle-vc-registered (file)
3480 "Like `vc-registered' for Tramp files."
3481 (with-temp-message ""
3482 (with-parsed-tramp-file-name file nil
3483 (with-tramp-progress-reporter
3484 v 3 (format-message "Checking `vc-registered' for %s" file)
3486 ;; There could be new files, created by the vc backend. We
3487 ;; cannot reuse the old cache entries, therefore. In
3488 ;; `tramp-get-file-property', `remote-file-name-inhibit-cache'
3489 ;; could also be a timestamp as `current-time' returns. This
3490 ;; means invalidate all cache entries with an older timestamp.
3491 (let (tramp-vc-registered-file-names
3492 (remote-file-name-inhibit-cache (current-time))
3493 (file-name-handler-alist
3494 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3496 ;; Here we collect only file names, which need an operation.
3497 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3498 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3500 ;; Send just one command, in order to fill the cache.
3501 (when tramp-vc-registered-file-names
3502 (tramp-maybe-send-script
3504 (format tramp-vc-registered-read-file-names
3505 (tramp-get-file-exists-command v)
3506 (format "%s -r" (tramp-get-test-command v)))
3507 "tramp_vc_registered_read_file_names")
3509 (dolist
3510 (elt
3511 (ignore-errors
3512 ;; We cannot use `tramp-send-command-and-read',
3513 ;; because this does not cooperate well with
3514 ;; heredoc documents.
3515 (tramp-send-command
3517 (format
3518 "tramp_vc_registered_read_file_names <<'%s'\n%s\n%s\n"
3519 tramp-end-of-heredoc
3520 (mapconcat 'tramp-shell-quote-argument
3521 tramp-vc-registered-file-names
3522 "\n")
3523 tramp-end-of-heredoc))
3524 (with-current-buffer (tramp-get-connection-buffer v)
3525 ;; Read the expression.
3526 (goto-char (point-min))
3527 (read (current-buffer)))))
3529 (tramp-set-file-property
3530 v (car elt) (cadr elt) (cadr (cdr elt))))))
3532 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3533 ;; calls shall be answered from the file cache. We unset
3534 ;; `process-file-side-effects' and `remote-file-name-inhibit-cache'
3535 ;; in order to keep the cache.
3536 (let ((vc-handled-backends vc-handled-backends)
3537 remote-file-name-inhibit-cache process-file-side-effects)
3538 ;; Reduce `vc-handled-backends' in order to minimize process calls.
3539 (when (and (memq 'Bzr vc-handled-backends)
3540 (boundp 'vc-bzr-program)
3541 (not (with-tramp-connection-property v vc-bzr-program
3542 (tramp-find-executable
3543 v vc-bzr-program (tramp-get-remote-path v)))))
3544 (setq vc-handled-backends (remq 'Bzr vc-handled-backends)))
3545 (when (and (memq 'Git vc-handled-backends)
3546 (boundp 'vc-git-program)
3547 (not (with-tramp-connection-property v vc-git-program
3548 (tramp-find-executable
3549 v vc-git-program (tramp-get-remote-path v)))))
3550 (setq vc-handled-backends (remq 'Git vc-handled-backends)))
3551 (when (and (memq 'Hg vc-handled-backends)
3552 (boundp 'vc-hg-program)
3553 (not (with-tramp-connection-property v vc-hg-program
3554 (tramp-find-executable
3555 v vc-hg-program (tramp-get-remote-path v)))))
3556 (setq vc-handled-backends (remq 'Hg vc-handled-backends)))
3557 ;; Run.
3558 (ignore-errors
3559 (tramp-run-real-handler 'vc-registered (list file))))))))
3561 ;;;###tramp-autoload
3562 (defun tramp-sh-file-name-handler (operation &rest args)
3563 "Invoke remote-shell Tramp file name handler.
3564 Fall back to normal file name handler if no Tramp handler exists."
3565 (when (and tramp-locked (not tramp-locker))
3566 (setq tramp-locked nil)
3567 (tramp-error
3568 (car-safe tramp-current-connection) 'file-error
3569 "Forbidden reentrant call of Tramp"))
3570 (let ((tl tramp-locked))
3571 (setq tramp-locked t)
3572 (unwind-protect
3573 (let ((tramp-locker t))
3574 (save-match-data
3575 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3576 (if fn
3577 (apply (cdr fn) args)
3578 (tramp-run-real-handler operation args)))))
3579 (setq tramp-locked tl))))
3581 (defun tramp-vc-file-name-handler (operation &rest args)
3582 "Invoke special file name handler, which collects files to be handled."
3583 (save-match-data
3584 (let ((filename
3585 (tramp-replace-environment-variables
3586 (apply 'tramp-file-name-for-operation operation args)))
3587 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3588 (with-parsed-tramp-file-name filename nil
3589 (cond
3590 ;; That's what we want: file names, for which checks are
3591 ;; applied. We assume that VC uses only `file-exists-p' and
3592 ;; `file-readable-p' checks; otherwise we must extend the
3593 ;; list. We do not perform any action, but return nil, in
3594 ;; order to keep `vc-registered' running.
3595 ((and fn (memq operation '(file-exists-p file-readable-p)))
3596 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3597 nil)
3598 ;; `process-file' and `start-file-process' shall be ignored.
3599 ((and fn (eq operation 'process-file) 0))
3600 ((and fn (eq operation 'start-file-process) nil))
3601 ;; Tramp file name handlers like `expand-file-name'. They
3602 ;; must still work.
3603 (fn (save-match-data (apply (cdr fn) args)))
3604 ;; Default file name handlers, we don't care.
3605 (t (tramp-run-real-handler operation args)))))))
3607 (defun tramp-sh-handle-file-notify-add-watch (file-name flags _callback)
3608 "Like `file-notify-add-watch' for Tramp files."
3609 (setq file-name (expand-file-name file-name))
3610 (with-parsed-tramp-file-name file-name nil
3611 (let ((default-directory (file-name-directory file-name))
3612 command events filter p sequence)
3613 (cond
3614 ;; gvfs-monitor-dir.
3615 ((setq command (tramp-get-remote-gvfs-monitor-dir v))
3616 (setq filter 'tramp-sh-gvfs-monitor-dir-process-filter
3617 events
3618 (cond
3619 ((and (memq 'change flags) (memq 'attribute-change flags))
3620 '(created changed changes-done-hint moved deleted
3621 attribute-changed))
3622 ((memq 'change flags)
3623 '(created changed changes-done-hint moved deleted))
3624 ((memq 'attribute-change flags) '(attribute-changed)))
3625 sequence `(,command ,localname)))
3626 ;; inotifywait.
3627 ((setq command (tramp-get-remote-inotifywait v))
3628 (setq filter 'tramp-sh-inotifywait-process-filter
3629 events
3630 (cond
3631 ((and (memq 'change flags) (memq 'attribute-change flags))
3632 (concat "create,modify,move,moved_from,moved_to,move_self,"
3633 "delete,delete_self,attrib,ignored"))
3634 ((memq 'change flags)
3635 (concat "create,modify,move,moved_from,moved_to,move_self,"
3636 "delete,delete_self,ignored"))
3637 ((memq 'attribute-change flags) "attrib,ignored"))
3638 sequence `(,command "-mq" "-e" ,events ,localname)
3639 ;; Make events a list of symbols.
3640 events
3641 (mapcar
3642 (lambda (x) (intern-soft (replace-regexp-in-string "_" "-" x)))
3643 (split-string events "," 'omit))))
3644 ;; None.
3645 (t (tramp-error
3646 v 'file-notify-error
3647 "No file notification program found on %s"
3648 (file-remote-p file-name))))
3649 ;; Start process.
3650 (setq p (apply
3651 'start-file-process
3652 (file-name-nondirectory command)
3653 (generate-new-buffer
3654 (format " *%s*" (file-name-nondirectory command)))
3655 sequence))
3656 ;; Return the process object as watch-descriptor.
3657 (if (not (processp p))
3658 (tramp-error
3659 v 'file-notify-error
3660 "`%s' failed to start on remote host"
3661 (mapconcat 'identity sequence " "))
3662 (tramp-message v 6 "Run `%s', %S" (mapconcat 'identity sequence " ") p)
3663 (tramp-set-connection-property p "vector" v)
3664 ;; Needed for process filter.
3665 (process-put p 'events events)
3666 (process-put p 'watch-name localname)
3667 (set-process-query-on-exit-flag p nil)
3668 (set-process-filter p filter)
3669 ;; There might be an error if the monitor is not supported.
3670 ;; Give the filter a chance to read the output.
3671 (tramp-accept-process-output p 1)
3672 (unless (tramp-compat-process-live-p p)
3673 (tramp-error
3674 v 'file-notify-error "Monitoring not supported for `%s'" file-name))
3675 p))))
3677 (defun tramp-sh-gvfs-monitor-dir-process-filter (proc string)
3678 "Read output from \"gvfs-monitor-dir\" and add corresponding \
3679 file-notify events."
3680 (let ((events (process-get proc 'events))
3681 (remote-prefix
3682 (with-current-buffer (process-buffer proc)
3683 (file-remote-p default-directory)))
3684 (rest-string (process-get proc 'rest-string)))
3685 (when rest-string
3686 (tramp-message proc 10 "Previous string:\n%s" rest-string))
3687 (tramp-message proc 6 "%S\n%s" proc string)
3688 (setq string (concat rest-string string)
3689 ;; Attribute change is returned in unused wording.
3690 string (replace-regexp-in-string
3691 "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))
3692 (when (string-match "Monitoring not supported" string)
3693 (delete-process proc))
3695 (while (string-match
3696 (concat "^[\n\r]*"
3697 "Directory Monitor Event:[\n\r]+"
3698 "Child = \\([^\n\r]+\\)[\n\r]+"
3699 "\\(Other = \\([^\n\r]+\\)[\n\r]+\\)?"
3700 "Event = \\([^[:blank:]]+\\)[\n\r]+")
3701 string)
3702 (let* ((file (match-string 1 string))
3703 (file1 (match-string 3 string))
3704 (object
3705 (list
3706 proc
3707 (list
3708 (intern-soft
3709 (replace-regexp-in-string
3710 "_" "-" (downcase (match-string 4 string)))))
3711 ;; File names are returned as absolute paths. We must
3712 ;; add the remote prefix.
3713 (concat remote-prefix file)
3714 (when file1 (concat remote-prefix file1)))))
3715 (setq string (replace-match "" nil nil string))
3716 ;; Remove watch when file or directory to be watched is deleted.
3717 (when (and (member (caadr object) '(moved deleted))
3718 (string-equal file (process-get proc 'watch-name)))
3719 (delete-process proc))
3720 ;; Usually, we would add an Emacs event now. Unfortunately,
3721 ;; `unread-command-events' does not accept several events at
3722 ;; once. Therefore, we apply the handler directly.
3723 (when (member (caadr object) events)
3724 (tramp-compat-funcall
3725 'file-notify-handle-event
3726 `(file-notify ,object file-notify-callback)))))
3728 ;; Save rest of the string.
3729 (when (zerop (length string)) (setq string nil))
3730 (when string (tramp-message proc 10 "Rest string:\n%s" string))
3731 (process-put proc 'rest-string string)))
3733 (defun tramp-sh-inotifywait-process-filter (proc string)
3734 "Read output from \"inotifywait\" and add corresponding file-notify events."
3735 (let ((events (process-get proc 'events)))
3736 (tramp-message proc 6 "%S\n%s" proc string)
3737 (dolist (line (split-string string "[\n\r]+" 'omit))
3738 ;; Check, whether there is a problem.
3739 (unless
3740 (string-match
3741 (concat "^[^[:blank:]]+"
3742 "[[:blank:]]+\\([^[:blank:]]+\\)+"
3743 "\\([[:blank:]]+\\([^\n\r]+\\)\\)?")
3744 line)
3745 (tramp-error proc 'file-notify-error "%s" line))
3747 (let ((object
3748 (list
3749 proc
3750 (mapcar
3751 (lambda (x)
3752 (intern-soft
3753 (replace-regexp-in-string "_" "-" (downcase x))))
3754 (split-string (match-string 1 line) "," 'omit))
3755 (match-string 3 line))))
3756 ;; Remove watch when file or directory to be watched is deleted.
3757 (when (member (caadr object) '(move-self delete-self ignored))
3758 (delete-process proc))
3759 ;; Usually, we would add an Emacs event now. Unfortunately,
3760 ;; `unread-command-events' does not accept several events at
3761 ;; once. Therefore, we apply the handler directly.
3762 (when (member (caadr object) events)
3763 (tramp-compat-funcall
3764 'file-notify-handle-event
3765 `(file-notify ,object file-notify-callback)))))))
3767 ;;; Internal Functions:
3769 (defun tramp-maybe-send-script (vec script name)
3770 "Define in remote shell function NAME implemented as SCRIPT.
3771 Only send the definition if it has not already been done."
3772 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3773 ;; might be nil.
3774 (let ((scripts (tramp-get-connection-property
3775 (tramp-get-connection-process vec) "scripts" nil)))
3776 (unless (member name scripts)
3777 (with-tramp-progress-reporter
3778 vec 5 (format-message "Sending script `%s'" name)
3779 ;; In bash, leading TABs like in `tramp-vc-registered-read-file-names'
3780 ;; could result in unwanted command expansion. Avoid this.
3781 (setq script (replace-regexp-in-string
3782 (make-string 1 ?\t) (make-string 8 ? ) script))
3783 ;; The script could contain a call of Perl. This is masked with `%s'.
3784 (when (and (string-match "%s" script)
3785 (not (tramp-get-remote-perl vec)))
3786 (tramp-error vec 'file-error "No Perl available on remote host"))
3787 (tramp-barf-unless-okay
3789 (format "%s () {\n%s\n}"
3790 name (format script (tramp-get-remote-perl vec)))
3791 "Script %s sending failed" name)
3792 (tramp-set-connection-property
3793 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3795 (defun tramp-run-test (switch filename)
3796 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3797 Returns the exit code of the `test' program."
3798 (with-parsed-tramp-file-name filename nil
3799 (tramp-send-command-and-check
3801 (format
3802 "%s %s %s"
3803 (tramp-get-test-command v)
3804 switch
3805 (tramp-shell-quote-argument localname)))))
3807 (defun tramp-run-test2 (format-string file1 file2)
3808 "Run `test'-like program on the remote system, given FILE1, FILE2.
3809 FORMAT-STRING contains the program name, switches, and place holders.
3810 Returns the exit code of the `test' program. Barfs if the methods,
3811 hosts, or files, disagree."
3812 (unless (tramp-equal-remote file1 file2)
3813 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3814 (tramp-error
3815 v 'file-error
3816 "tramp-run-test2 only implemented for same method, user, host")))
3817 (with-parsed-tramp-file-name file1 v1
3818 (with-parsed-tramp-file-name file1 v2
3819 (tramp-send-command-and-check
3821 (format format-string
3822 (tramp-shell-quote-argument v1-localname)
3823 (tramp-shell-quote-argument v2-localname))))))
3825 (defun tramp-find-executable
3826 (vec progname dirlist &optional ignore-tilde ignore-path)
3827 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3828 First arg VEC specifies the connection, PROGNAME is the program
3829 to search for, and DIRLIST gives the list of directories to
3830 search. If IGNORE-TILDE is non-nil, directory names starting
3831 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3832 only in DIRLIST.
3834 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3836 This function expects to be in the right *tramp* buffer."
3837 (with-current-buffer (tramp-get-connection-buffer vec)
3838 (let (result)
3839 ;; Check whether the executable is in $PATH. "which(1)" does not
3840 ;; report always a correct error code; therefore we check the
3841 ;; number of words it returns. "SunOS 5.10" (and maybe "SunOS
3842 ;; 5.11") have problems with this command, we disable the call
3843 ;; therefore.
3844 (unless (or ignore-path
3845 (string-match
3846 (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3847 (tramp-get-connection-property vec "uname" "")))
3848 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3849 (goto-char (point-min))
3850 (if (looking-at "^\\s-*1$")
3851 (setq result (concat "\\" progname))))
3852 (unless result
3853 (when ignore-tilde
3854 ;; Remove all ~/foo directories from dirlist.
3855 (let (newdl d)
3856 (while dirlist
3857 (setq d (car dirlist))
3858 (setq dirlist (cdr dirlist))
3859 (unless (char-equal ?~ (aref d 0))
3860 (setq newdl (cons d newdl))))
3861 (setq dirlist (nreverse newdl))))
3862 (tramp-send-command
3864 (format (concat "while read d; "
3865 "do if test -x $d/%s && test -f $d/%s; "
3866 "then echo tramp_executable $d/%s; "
3867 "break; fi; done <<'%s'\n"
3868 "%s\n%s")
3869 progname progname progname
3870 tramp-end-of-heredoc
3871 (mapconcat 'identity dirlist "\n")
3872 tramp-end-of-heredoc))
3873 (goto-char (point-max))
3874 (when (search-backward "tramp_executable " nil t)
3875 (skip-chars-forward "^ ")
3876 (skip-chars-forward " ")
3877 (setq result (buffer-substring (point) (point-at-eol)))))
3878 result)))
3880 (defun tramp-set-remote-path (vec)
3881 "Sets the remote environment PATH to existing directories.
3882 I.e., for each directory in `tramp-remote-path', it is tested
3883 whether it exists and if so, it is added to the environment
3884 variable PATH."
3885 (tramp-message vec 5 "Setting $PATH environment variable")
3886 (tramp-send-command
3887 vec (format "PATH=%s; export PATH"
3888 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3890 ;; ------------------------------------------------------------
3891 ;; -- Communication with external shell --
3892 ;; ------------------------------------------------------------
3894 (defun tramp-find-file-exists-command (vec)
3895 "Find a command on the remote host for checking if a file exists.
3896 Here, we are looking for a command which has zero exit status if the
3897 file exists and nonzero exit status otherwise."
3898 (let ((existing "/")
3899 (nonexistent
3900 (tramp-shell-quote-argument "/ this file does not exist "))
3901 result)
3902 ;; The algorithm is as follows: we try a list of several commands.
3903 ;; For each command, we first run `$cmd /' -- this should return
3904 ;; true, as the root directory always exists. And then we run
3905 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3906 ;; does not exist. This should return false. We use the first
3907 ;; command we find that seems to work.
3908 ;; The list of commands to try is as follows:
3909 ;; `ls -d' This works on most systems, but NetBSD 1.4
3910 ;; has a bug: `ls' always returns zero exit
3911 ;; status, even for files which don't exist.
3912 ;; `test -e' Some Bourne shells have a `test' builtin
3913 ;; which does not know the `-e' option.
3914 ;; `/bin/test -e' For those, the `test' binary on disk normally
3915 ;; provides the option. Alas, the binary
3916 ;; is sometimes `/bin/test' and sometimes it's
3917 ;; `/usr/bin/test'.
3918 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3919 (unless (or
3920 (ignore-errors
3921 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3922 (tramp-send-command-and-check
3923 vec (format "%s %s" result existing))
3924 (not (tramp-send-command-and-check
3925 vec (format "%s %s" result nonexistent)))))
3926 (ignore-errors
3927 (and (setq result "/bin/test -e")
3928 (tramp-send-command-and-check
3929 vec (format "%s %s" result existing))
3930 (not (tramp-send-command-and-check
3931 vec (format "%s %s" result nonexistent)))))
3932 (ignore-errors
3933 (and (setq result "/usr/bin/test -e")
3934 (tramp-send-command-and-check
3935 vec (format "%s %s" result existing))
3936 (not (tramp-send-command-and-check
3937 vec (format "%s %s" result nonexistent)))))
3938 (ignore-errors
3939 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3940 (tramp-send-command-and-check
3941 vec (format "%s %s" result existing))
3942 (not (tramp-send-command-and-check
3943 vec (format "%s %s" result nonexistent))))))
3944 (tramp-error
3945 vec 'file-error "Couldn't find command to check if file exists"))
3946 result))
3948 (defun tramp-open-shell (vec shell)
3949 "Opens shell SHELL."
3950 (with-tramp-progress-reporter
3951 vec 5 (format-message "Opening remote shell `%s'" shell)
3952 ;; Find arguments for this shell.
3953 (let ((alist tramp-sh-extra-args)
3954 item extra-args)
3955 (while (and alist (null extra-args))
3956 (setq item (pop alist))
3957 (when (string-match (car item) shell)
3958 (setq extra-args (cdr item))))
3959 ;; It is useful to set the prompt in the following command
3960 ;; because some people have a setting for $PS1 which /bin/sh
3961 ;; doesn't know about and thus /bin/sh will display a strange
3962 ;; prompt. For example, if $PS1 has "${CWD}" in the value, then
3963 ;; ksh will display the current working directory but /bin/sh
3964 ;; will display a dollar sign. The following command line sets
3965 ;; $PS1 to a sane value, and works under Bourne-ish shells as
3966 ;; well as csh-like shells. We also unset the variable $ENV
3967 ;; because that is read by some sh implementations (eg, bash
3968 ;; when called as sh) on startup; this way, we avoid the startup
3969 ;; file clobbering $PS1. $PROMPT_COMMAND is another way to set
3970 ;; the prompt in /bin/bash, it must be discarded as well.
3971 ;; $HISTFILE is set according to `tramp-histfile-override'.
3972 (tramp-send-command
3973 vec (format
3974 "exec env ENV=%s %s PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3975 (or (getenv-internal "ENV" tramp-remote-process-environment) "")
3976 (if (stringp tramp-histfile-override)
3977 (format "HISTFILE=%s"
3978 (tramp-shell-quote-argument tramp-histfile-override))
3979 (if tramp-histfile-override
3980 "HISTFILE='' HISTFILESIZE=0 HISTSIZE=0"
3981 ""))
3982 (tramp-shell-quote-argument tramp-end-of-output)
3983 shell (or extra-args ""))
3985 ;; Check proper HISTFILE setting. We give up when not working.
3986 (when (and (stringp tramp-histfile-override)
3987 (file-name-directory tramp-histfile-override))
3988 (tramp-barf-unless-okay
3990 (format
3991 "(cd %s)"
3992 (tramp-shell-quote-argument
3993 (file-name-directory tramp-histfile-override)))
3994 "`tramp-histfile-override' uses invalid file `%s'"
3995 tramp-histfile-override)))
3997 (tramp-set-connection-property
3998 (tramp-get-connection-process vec) "remote-shell" shell)))
4000 (defun tramp-find-shell (vec)
4001 "Opens a shell on the remote host which groks tilde expansion."
4002 (with-current-buffer (tramp-get-buffer vec)
4003 (let ((default-shell (tramp-get-method-parameter vec 'tramp-remote-shell))
4004 shell)
4005 (setq shell
4006 (with-tramp-connection-property vec "remote-shell"
4007 ;; CCC: "root" does not exist always, see my QNAP TS-459.
4008 ;; Which check could we apply instead?
4009 (tramp-send-command vec "echo ~root" t)
4010 (if (or (string-match "^~root$" (buffer-string))
4011 ;; The default shell (ksh93) of OpenSolaris and
4012 ;; Solaris is buggy. We've got reports for
4013 ;; "SunOS 5.10" and "SunOS 5.11" so far.
4014 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
4015 (tramp-get-connection-property
4016 vec "uname" "")))
4018 (or (tramp-find-executable
4019 vec "bash" (tramp-get-remote-path vec) t t)
4020 (tramp-find-executable
4021 vec "ksh" (tramp-get-remote-path vec) t t)
4022 ;; Maybe it works at least for some other commands.
4023 (prog1
4024 default-shell
4025 (tramp-message
4026 vec 2
4027 (concat
4028 "Couldn't find a remote shell which groks tilde "
4029 "expansion, using `%s'")
4030 default-shell)))
4032 default-shell)))
4034 ;; Open a new shell if needed.
4035 (unless (string-equal shell default-shell)
4036 (tramp-message
4037 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
4038 (tramp-open-shell vec shell)))))
4040 ;; Utility functions.
4042 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
4043 "Wait for shell prompt and barf if none appears.
4044 Looks at process PROC to see if a shell prompt appears in TIMEOUT
4045 seconds. If not, it produces an error message with the given ERROR-ARGS."
4046 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4047 (condition-case nil
4048 (tramp-wait-for-regexp
4049 proc timeout
4050 (format
4051 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
4052 (error
4053 (delete-process proc)
4054 (apply 'tramp-error-with-buffer
4055 (tramp-get-connection-buffer vec) vec 'file-error error-args)))))
4057 (defun tramp-open-connection-setup-interactive-shell (proc vec)
4058 "Set up an interactive shell.
4059 Mainly sets the prompt and the echo correctly. PROC is the shell
4060 process to set up. VEC specifies the connection."
4061 (let ((tramp-end-of-output tramp-initial-end-of-output)
4062 (case-fold-search t))
4063 (tramp-open-shell vec (tramp-get-method-parameter vec 'tramp-remote-shell))
4065 ;; Disable echo expansion.
4066 (tramp-message vec 5 "Setting up remote shell environment")
4067 (tramp-send-command
4068 vec "stty -inlcr -onlcr -echo kill '^U' erase '^H'" t)
4069 ;; Check whether the echo has really been disabled. Some
4070 ;; implementations, like busybox of embedded GNU/Linux, don't
4071 ;; support disabling.
4072 (tramp-send-command vec "echo foo" t)
4073 (with-current-buffer (process-buffer proc)
4074 (goto-char (point-min))
4075 (when (looking-at "echo foo")
4076 (tramp-set-connection-property proc "remote-echo" t)
4077 (tramp-message vec 5 "Remote echo still on. Ok.")
4078 ;; Make sure backspaces and their echo are enabled and no line
4079 ;; width magic interferes with them.
4080 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
4082 (tramp-message vec 5 "Setting shell prompt")
4083 (tramp-send-command
4084 vec (format "PS1=%s PS2='' PS3='' PROMPT_COMMAND=''"
4085 (tramp-shell-quote-argument tramp-end-of-output))
4088 ;; Check whether the output of "uname -sr" has been changed. If
4089 ;; yes, this is a strong indication that we must expire all
4090 ;; connection properties. We start again with
4091 ;; `tramp-maybe-open-connection', it will be caught there.
4092 (tramp-message vec 5 "Checking system information")
4093 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
4094 (uname
4095 (tramp-set-connection-property
4096 vec "uname"
4097 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
4098 (when (and (stringp old-uname) (not (string-equal old-uname uname)))
4099 (tramp-message
4100 vec 3
4101 "Connection reset, because remote host changed from `%s' to `%s'"
4102 old-uname uname)
4103 ;; We want to keep the password.
4104 (tramp-cleanup-connection vec t t)
4105 (throw 'uname-changed (tramp-maybe-open-connection vec)))
4107 ;; Try to set up the coding system correctly.
4108 ;; CCC this can't be the right way to do it. Hm.
4109 (tramp-message vec 5 "Determining coding system")
4110 (with-current-buffer (process-buffer proc)
4111 ;; Use MULE to select the right EOL convention for communicating
4112 ;; with the process.
4113 (let ((cs (or (and (memq 'utf-8 (coding-system-list))
4114 (string-match "utf-?8" (tramp-get-remote-locale vec))
4115 (cons 'utf-8 'utf-8))
4116 (process-coding-system proc)
4117 (cons 'undecided 'undecided)))
4118 cs-decode cs-encode)
4119 (when (symbolp cs) (setq cs (cons cs cs)))
4120 (setq cs-decode (or (car cs) 'undecided)
4121 cs-encode (or (cdr cs) 'undecided)
4122 cs-encode
4123 (coding-system-change-eol-conversion
4124 cs-encode (if (string-match "^Darwin" uname) 'mac 'unix)))
4125 (tramp-send-command vec "echo foo ; echo bar" t)
4126 (goto-char (point-min))
4127 (when (search-forward "\r" nil t)
4128 (setq cs-decode (coding-system-change-eol-conversion cs-decode 'dos)))
4129 ;; Special setting for macOS.
4130 (when (and (string-match "^Darwin" uname)
4131 (memq 'utf-8-hfs (coding-system-list)))
4132 (setq cs-decode 'utf-8-hfs
4133 cs-encode 'utf-8-hfs))
4134 (set-buffer-process-coding-system cs-decode cs-encode)
4135 (tramp-message
4136 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode)))
4138 (tramp-send-command vec "set +o vi +o emacs" t)
4140 ;; Check whether the remote host suffers from buggy
4141 ;; `send-process-string'. This is known for FreeBSD (see comment
4142 ;; in `send_process', file process.c). I've tested sending 624
4143 ;; bytes successfully, sending 625 bytes failed. Emacs makes a
4144 ;; hack when this host type is detected locally. It cannot handle
4145 ;; remote hosts, though.
4146 (with-tramp-connection-property proc "chunksize"
4147 (cond
4148 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
4149 tramp-chunksize)
4151 (tramp-message
4152 vec 5 "Checking remote host type for `send-process-string' bug")
4153 (if (string-match "^FreeBSD" uname) 500 0))))
4155 ;; Set remote PATH variable.
4156 (tramp-set-remote-path vec)
4158 ;; Search for a good shell before searching for a command which
4159 ;; checks if a file exists. This is done because Tramp wants to
4160 ;; use "test foo; echo $?" to check if various conditions hold,
4161 ;; and there are buggy /bin/sh implementations which don't execute
4162 ;; the "echo $?" part if the "test" part has an error. In
4163 ;; particular, the OpenSolaris /bin/sh is a problem. There are
4164 ;; also other problems with /bin/sh of OpenSolaris, like
4165 ;; redirection of stderr in function declarations, or changing
4166 ;; HISTFILE in place. Therefore, OpenSolaris' /bin/sh is replaced
4167 ;; by bash, when detected.
4168 (tramp-find-shell vec)
4170 ;; Disable unexpected output.
4171 (tramp-send-command vec "mesg n 2>/dev/null; biff n 2>/dev/null" t)
4173 ;; IRIX64 bash expands "!" even when in single quotes. This
4174 ;; destroys our shell functions, we must disable it. See
4175 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
4176 (when (string-match "^IRIX64" uname)
4177 (tramp-send-command vec "set +H" t))
4179 ;; Disable tab expansion.
4180 (if (string-match "BSD\\|Darwin" uname)
4181 (tramp-send-command vec "stty tabs" t)
4182 (tramp-send-command vec "stty tab0" t))
4184 ;; Set utf8 encoding. Needed for macOS, for example. This is
4185 ;; non-POSIX, so we must expect errors on some systems.
4186 (tramp-send-command vec "stty iutf8 2>/dev/null" t)
4188 ;; Set `remote-tty' process property.
4189 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
4190 (unless (zerop (length tty))
4191 (process-put proc 'remote-tty tty)))
4193 ;; Dump stty settings in the traces.
4194 (when (>= tramp-verbose 9)
4195 (tramp-send-command vec "stty -a" t))
4197 ;; Set the environment.
4198 (tramp-message vec 5 "Setting default environment")
4200 (let (unset vars)
4201 (dolist (item (reverse
4202 (append `(,(tramp-get-remote-locale vec))
4203 (copy-sequence tramp-remote-process-environment))))
4204 (setq item (split-string item "=" 'omit))
4205 (setcdr item (mapconcat 'identity (cdr item) "="))
4206 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
4207 (push (format "%s %s" (car item) (cdr item)) vars)
4208 (push (car item) unset)))
4209 (when vars
4210 (tramp-send-command
4212 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
4213 tramp-end-of-heredoc
4214 (mapconcat 'identity vars "\n")
4215 tramp-end-of-heredoc)
4217 (when unset
4218 (tramp-send-command
4219 vec (format "unset %s" (mapconcat 'identity unset " ")) t)))))
4221 ;; Old text from documentation of tramp-methods:
4222 ;; Using a uuencode/uudecode inline method is discouraged, please use one
4223 ;; of the base64 methods instead since base64 encoding is much more
4224 ;; reliable and the commands are more standardized between the different
4225 ;; Unix versions. But if you can't use base64 for some reason, please
4226 ;; note that the default uudecode command does not work well for some
4227 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
4228 ;; the following command for uudecode:
4230 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
4232 ;; For Irix, no solution is known yet.
4234 (autoload 'uudecode-decode-region "uudecode")
4236 (defconst tramp-local-coding-commands
4237 `((b64 base64-encode-region base64-decode-region)
4238 (uu tramp-uuencode-region uudecode-decode-region)
4239 (pack ,(format tramp-perl-pack "perl") ,(format tramp-perl-unpack "perl")))
4240 "List of local coding commands for inline transfer.
4241 Each item is a list that looks like this:
4243 \(FORMAT ENCODING DECODING)
4245 FORMAT is symbol describing the encoding/decoding format. It can be
4246 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4248 ENCODING and DECODING can be strings, giving commands, or symbols,
4249 giving functions. If they are strings, then they can contain
4250 the \"%s\" format specifier. If that specifier is present, the input
4251 file name will be put into the command line at that spot. If the
4252 specifier is not present, the input should be read from standard
4253 input.
4255 If they are functions, they will be called with two arguments, start
4256 and end of region, and are expected to replace the region contents
4257 with the encoded or decoded results, respectively.")
4259 (defconst tramp-remote-coding-commands
4260 `((b64 "base64" "base64 -d -i")
4261 ;; "-i" is more robust with older base64 from GNU coreutils.
4262 ;; However, I don't know whether all base64 versions do supports
4263 ;; this option.
4264 (b64 "base64" "base64 -d")
4265 (b64 "openssl enc -base64" "openssl enc -d -base64")
4266 (b64 "mimencode -b" "mimencode -u -b")
4267 (b64 "mmencode -b" "mmencode -u -b")
4268 (b64 "recode data..base64" "recode base64..data")
4269 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
4270 (b64 tramp-perl-encode tramp-perl-decode)
4271 ;; This is painful slow, so we put it on the end.
4272 (b64 tramp-awk-encode tramp-awk-decode ,tramp-awk-coding-test)
4273 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
4274 (uu "uuencode xxx" "uudecode -o -")
4275 (uu "uuencode xxx" "uudecode -p")
4276 (uu "uuencode xxx" tramp-uudecode)
4277 (pack tramp-perl-pack tramp-perl-unpack))
4278 "List of remote coding commands for inline transfer.
4279 Each item is a list that looks like this:
4281 \(FORMAT ENCODING DECODING [TEST])
4283 FORMAT is a symbol describing the encoding/decoding format. It can be
4284 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4286 ENCODING and DECODING can be strings, giving commands, or symbols,
4287 giving variables. If they are strings, then they can contain
4288 the \"%s\" format specifier. If that specifier is present, the input
4289 file name will be put into the command line at that spot. If the
4290 specifier is not present, the input should be read from standard
4291 input.
4293 If they are variables, this variable is a string containing a
4294 Perl or Shell implementation for this functionality. This
4295 program will be transferred to the remote host, and it is
4296 available as shell function with the same name. A \"%t\" format
4297 specifier in the variable value denotes a temporary file.
4299 The optional TEST command can be used for further tests, whether
4300 ENCODING and DECODING are applicable.")
4302 (defun tramp-find-inline-encoding (vec)
4303 "Find an inline transfer encoding that works.
4304 Goes through the list `tramp-local-coding-commands' and
4305 `tramp-remote-coding-commands'."
4306 (save-excursion
4307 (let ((local-commands tramp-local-coding-commands)
4308 (magic "xyzzy")
4309 (p (tramp-get-connection-process vec))
4310 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4311 (while (and local-commands (not found))
4312 (setq litem (pop local-commands))
4313 (catch 'wont-work-local
4314 (let ((format (nth 0 litem))
4315 (remote-commands tramp-remote-coding-commands))
4316 (setq loc-enc (nth 1 litem))
4317 (setq loc-dec (nth 2 litem))
4318 ;; If the local encoder or decoder is a string, the
4319 ;; corresponding command has to work locally.
4320 (if (not (stringp loc-enc))
4321 (tramp-message
4322 vec 5 "Checking local encoding function `%s'" loc-enc)
4323 (tramp-message
4324 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4325 (unless (zerop (tramp-call-local-coding-command
4326 loc-enc nil nil))
4327 (throw 'wont-work-local nil)))
4328 (if (not (stringp loc-dec))
4329 (tramp-message
4330 vec 5 "Checking local decoding function `%s'" loc-dec)
4331 (tramp-message
4332 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4333 (unless (zerop (tramp-call-local-coding-command
4334 loc-dec nil nil))
4335 (throw 'wont-work-local nil)))
4336 ;; Search for remote coding commands with the same format
4337 (while (and remote-commands (not found))
4338 (setq ritem (pop remote-commands))
4339 (catch 'wont-work-remote
4340 (when (equal format (nth 0 ritem))
4341 (setq rem-enc (nth 1 ritem))
4342 (setq rem-dec (nth 2 ritem))
4343 (setq rem-test (nth 3 ritem))
4344 ;; Check the remote test command if exists.
4345 (when (stringp rem-test)
4346 (tramp-message
4347 vec 5 "Checking remote test command `%s'" rem-test)
4348 (unless (tramp-send-command-and-check vec rem-test t)
4349 (throw 'wont-work-remote nil)))
4350 ;; Check if remote perl exists when necessary.
4351 (when (and (symbolp rem-enc)
4352 (string-match "perl" (symbol-name rem-enc))
4353 (not (tramp-get-remote-perl vec)))
4354 (throw 'wont-work-remote nil))
4355 ;; Check if remote encoding and decoding commands can be
4356 ;; called remotely with null input and output. This makes
4357 ;; sure there are no syntax errors and the command is really
4358 ;; found. Note that we do not redirect stdout to /dev/null,
4359 ;; for two reasons: when checking the decoding command, we
4360 ;; actually check the output it gives. And also, when
4361 ;; redirecting "mimencode" output to /dev/null, then as root
4362 ;; it might change the permissions of /dev/null!
4363 (when (not (stringp rem-enc))
4364 (let ((name (symbol-name rem-enc)))
4365 (while (string-match (regexp-quote "-") name)
4366 (setq name (replace-match "_" nil t name)))
4367 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4368 (setq rem-enc name)))
4369 (tramp-message
4370 vec 5
4371 "Checking remote encoding command `%s' for sanity" rem-enc)
4372 (unless (tramp-send-command-and-check
4373 vec (format "%s </dev/null" rem-enc) t)
4374 (throw 'wont-work-remote nil))
4376 (when (not (stringp rem-dec))
4377 (let ((name (symbol-name rem-dec))
4378 (value (symbol-value rem-dec))
4379 tmpfile)
4380 (while (string-match (regexp-quote "-") name)
4381 (setq name (replace-match "_" nil t name)))
4382 (when (string-match "\\(^\\|[^%]\\)%t" value)
4383 (setq tmpfile
4384 (make-temp-name
4385 (expand-file-name
4386 tramp-temp-name-prefix
4387 (tramp-get-remote-tmpdir vec)))
4388 value
4389 (format-spec
4390 value
4391 (format-spec-make
4393 (file-remote-p tmpfile 'localname)))))
4394 (tramp-maybe-send-script vec value name)
4395 (setq rem-dec name)))
4396 (tramp-message
4397 vec 5
4398 "Checking remote decoding command `%s' for sanity" rem-dec)
4399 (unless (tramp-send-command-and-check
4401 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4403 (throw 'wont-work-remote nil))
4405 (with-current-buffer (tramp-get-buffer vec)
4406 (goto-char (point-min))
4407 (unless (looking-at (regexp-quote magic))
4408 (throw 'wont-work-remote nil)))
4410 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4411 (setq rem-enc (nth 1 ritem))
4412 (setq rem-dec (nth 2 ritem))
4413 (setq found t)))))))
4415 (when found
4416 ;; Set connection properties. Since the commands are risky
4417 ;; (due to output direction), we cache them in the process cache.
4418 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4419 (tramp-set-connection-property p "local-encoding" loc-enc)
4420 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4421 (tramp-set-connection-property p "local-decoding" loc-dec)
4422 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4423 (tramp-set-connection-property p "remote-encoding" rem-enc)
4424 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4425 (tramp-set-connection-property p "remote-decoding" rem-dec)))))
4427 (defun tramp-call-local-coding-command (cmd input output)
4428 "Call the local encoding or decoding command.
4429 If CMD contains \"%s\", provide input file INPUT there in command.
4430 Otherwise, INPUT is passed via standard input.
4431 INPUT can also be nil which means `/dev/null'.
4432 OUTPUT can be a string (which specifies a file name), or t (which
4433 means standard output and thus the current buffer), or nil (which
4434 means discard it)."
4435 (tramp-call-process
4436 nil tramp-encoding-shell
4437 (when (and input (not (string-match "%s" cmd))) input)
4438 (if (eq output t) t nil)
4440 tramp-encoding-command-switch
4441 (concat
4442 (if (string-match "%s" cmd) (format cmd input) cmd)
4443 (if (stringp output) (concat " >" output) ""))))
4445 (defconst tramp-inline-compress-commands
4446 '(("gzip" "gzip -d")
4447 ("bzip2" "bzip2 -d")
4448 ("xz" "xz -d")
4449 ("compress" "compress -d"))
4450 "List of compress and decompress commands for inline transfer.
4451 Each item is a list that looks like this:
4453 \(COMPRESS DECOMPRESS)
4455 COMPRESS or DECOMPRESS are strings with the respective commands.")
4457 (defun tramp-find-inline-compress (vec)
4458 "Find an inline transfer compress command that works.
4459 Goes through the list `tramp-inline-compress-commands'."
4460 (save-excursion
4461 (let ((commands tramp-inline-compress-commands)
4462 (magic "xyzzy")
4463 (p (tramp-get-connection-process vec))
4464 item compress decompress found)
4465 (while (and commands (not found))
4466 (catch 'next
4467 (setq item (pop commands)
4468 compress (nth 0 item)
4469 decompress (nth 1 item))
4470 (tramp-message
4471 vec 5
4472 "Checking local compress commands `%s', `%s' for sanity"
4473 compress decompress)
4474 (unless
4475 (zerop
4476 (tramp-call-local-coding-command
4477 (format
4478 ;; Windows shells need the program file name after
4479 ;; the pipe symbol be quoted if they use forward
4480 ;; slashes as directory separators.
4481 (if (memq system-type '(windows-nt))
4482 "echo %s | \"%s\" | \"%s\""
4483 "echo %s | %s | %s")
4484 magic compress decompress) nil nil))
4485 (throw 'next nil))
4486 (tramp-message
4487 vec 5
4488 "Checking remote compress commands `%s', `%s' for sanity"
4489 compress decompress)
4490 (unless (tramp-send-command-and-check
4491 vec (format "echo %s | %s | %s" magic compress decompress) t)
4492 (throw 'next nil))
4493 (setq found t)))
4495 ;; Did we find something?
4496 (if found
4497 (progn
4498 ;; Set connection properties. Since the commands are
4499 ;; risky (due to output direction), we cache them in the
4500 ;; process cache.
4501 (tramp-message
4502 vec 5 "Using inline transfer compress command `%s'" compress)
4503 (tramp-set-connection-property p "inline-compress" compress)
4504 (tramp-message
4505 vec 5 "Using inline transfer decompress command `%s'" decompress)
4506 (tramp-set-connection-property p "inline-decompress" decompress))
4508 (tramp-set-connection-property p "inline-compress" nil)
4509 (tramp-set-connection-property p "inline-decompress" nil)
4510 (tramp-message
4511 vec 2 "Couldn't find an inline transfer compress command")))))
4513 (defun tramp-compute-multi-hops (vec)
4514 "Expands VEC according to `tramp-default-proxies-alist'.
4515 Gateway hops are already opened."
4516 (let ((target-alist `(,vec))
4517 (hops (or (tramp-file-name-hop vec) ""))
4518 (item vec)
4519 choices proxy)
4521 ;; Ad-hoc proxy definitions.
4522 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4523 (let ((user (tramp-file-name-user item))
4524 (host (tramp-file-name-host item))
4525 (proxy (concat
4526 tramp-prefix-format proxy tramp-postfix-host-format)))
4527 (tramp-message
4528 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4529 (and (stringp host) (regexp-quote host))
4530 (and (stringp user) (regexp-quote user))
4531 proxy)
4532 ;; Add the hop.
4533 (add-to-list
4534 'tramp-default-proxies-alist
4535 (list (and (stringp host) (regexp-quote host))
4536 (and (stringp user) (regexp-quote user))
4537 proxy))
4538 (setq item (tramp-dissect-file-name proxy))))
4539 ;; Save the new value.
4540 (when (and hops tramp-save-ad-hoc-proxies)
4541 (customize-save-variable
4542 'tramp-default-proxies-alist tramp-default-proxies-alist))
4544 ;; Look for proxy hosts to be passed.
4545 (setq choices tramp-default-proxies-alist)
4546 (while choices
4547 (setq item (pop choices)
4548 proxy (eval (nth 2 item)))
4549 (when (and
4550 ;; Host.
4551 (string-match (or (eval (nth 0 item)) "")
4552 (or (tramp-file-name-host (car target-alist)) ""))
4553 ;; User.
4554 (string-match (or (eval (nth 1 item)) "")
4555 (or (tramp-file-name-user (car target-alist)) "")))
4556 (if (null proxy)
4557 ;; No more hops needed.
4558 (setq choices nil)
4559 ;; Replace placeholders.
4560 (setq proxy
4561 (format-spec
4562 proxy
4563 (format-spec-make
4564 ?u (or (tramp-file-name-user (car target-alist)) "")
4565 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4566 (with-parsed-tramp-file-name proxy l
4567 ;; Add the hop.
4568 (push l target-alist)
4569 ;; Start next search.
4570 (setq choices tramp-default-proxies-alist)))))
4572 ;; Handle gateways.
4573 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4574 (string-match
4575 (format
4576 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4577 (tramp-file-name-method (car target-alist))))
4578 (let ((gw (pop target-alist))
4579 (hop (pop target-alist)))
4580 ;; Is the method prepared for gateways?
4581 (unless (tramp-file-name-port hop)
4582 (tramp-error
4583 vec 'file-error
4584 "Connection `%s' is not supported for gateway access." hop))
4585 ;; Open the gateway connection.
4586 (push
4587 (vector
4588 (tramp-file-name-method hop) (tramp-file-name-user hop)
4589 (tramp-gw-open-connection vec gw hop) nil nil)
4590 target-alist)
4591 ;; For the password prompt, we need the correct values.
4592 ;; Therefore, we must remember the gateway vector. But we
4593 ;; cannot do it as connection property, because it shouldn't
4594 ;; be persistent. And we have no started process yet either.
4595 (let ((tramp-verbose 0))
4596 (tramp-set-file-property (car target-alist) "" "gateway" hop))))
4598 ;; Foreign and out-of-band methods are not supported for multi-hops.
4599 (when (cdr target-alist)
4600 (setq choices target-alist)
4601 (while (setq item (pop choices))
4602 (when (or (not (tramp-get-method-parameter item 'tramp-login-program))
4603 (tramp-get-method-parameter item 'tramp-copy-program))
4604 (tramp-error
4605 vec 'file-error
4606 "Method `%s' is not supported for multi-hops."
4607 (tramp-file-name-method item)))))
4609 ;; In case the host name is not used for the remote shell
4610 ;; command, the user could be misguided by applying a random
4611 ;; host name.
4612 (let* ((v (car target-alist))
4613 (method (tramp-file-name-method v))
4614 (host (tramp-file-name-host v)))
4615 (unless
4617 ;; There are multi-hops.
4618 (cdr target-alist)
4619 ;; The host name is used for the remote shell command.
4620 (member '("%h") (tramp-get-method-parameter v 'tramp-login-args))
4621 ;; The host is local. We cannot use `tramp-local-host-p'
4622 ;; here, because it opens a connection as well.
4623 (string-match tramp-local-host-regexp host))
4624 (tramp-error
4625 v 'file-error
4626 "Host `%s' looks like a remote host, `%s' can only use the local host"
4627 host method)))
4629 ;; Result.
4630 target-alist))
4632 (defun tramp-ssh-controlmaster-options (vec)
4633 "Return the Control* arguments of the local ssh."
4634 (cond
4635 ;; No options to be computed.
4636 ((or (null tramp-use-ssh-controlmaster-options)
4637 (null (assoc "%c" (tramp-get-method-parameter vec 'tramp-login-args))))
4640 ;; There is already a value to be used.
4641 ((stringp tramp-ssh-controlmaster-options) tramp-ssh-controlmaster-options)
4643 ;; Determine the options.
4644 (t (setq tramp-ssh-controlmaster-options "")
4645 (let ((case-fold-search t))
4646 (ignore-errors
4647 (when (executable-find "ssh")
4648 (with-temp-buffer
4649 (tramp-call-process vec "ssh" nil t nil "-o" "ControlMaster")
4650 (goto-char (point-min))
4651 (when (search-forward-regexp "missing.+argument" nil t)
4652 (setq tramp-ssh-controlmaster-options "-o ControlMaster=auto")))
4653 (unless (zerop (length tramp-ssh-controlmaster-options))
4654 (with-temp-buffer
4655 ;; We use a non-existing IP address, in order to avoid
4656 ;; useless connections, and DNS timeouts.
4657 (tramp-call-process
4658 vec "ssh" nil t nil "-o" "ControlPath=%C" "0.0.0.1")
4659 (goto-char (point-min))
4660 (setq tramp-ssh-controlmaster-options
4661 (concat tramp-ssh-controlmaster-options
4662 (if (search-forward-regexp "unknown.+key" nil t)
4663 " -o ControlPath='tramp.%%r@%%h:%%p'"
4664 " -o ControlPath='tramp.%%C'"))))
4665 (with-temp-buffer
4666 (tramp-call-process vec "ssh" nil t nil "-o" "ControlPersist")
4667 (goto-char (point-min))
4668 (when (search-forward-regexp "missing.+argument" nil t)
4669 (setq tramp-ssh-controlmaster-options
4670 (concat tramp-ssh-controlmaster-options
4671 " -o ControlPersist=no"))))))))
4672 tramp-ssh-controlmaster-options)))
4674 (defun tramp-maybe-open-connection (vec)
4675 "Maybe open a connection VEC.
4676 Does not do anything if a connection is already open, but re-opens the
4677 connection if a previous connection has died for some reason."
4678 (tramp-check-proper-method-and-host vec)
4680 (let ((p (tramp-get-connection-process vec))
4681 (process-name (tramp-get-connection-property vec "process-name" nil))
4682 (process-environment (copy-sequence process-environment))
4683 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4685 ;; If Tramp opens the same connection within a short time frame,
4686 ;; there is a problem. We shall signal this.
4687 (unless (or (tramp-compat-process-live-p p)
4688 (not (equal (butlast (append vec nil) 2)
4689 (car tramp-current-connection)))
4690 (> (tramp-time-diff
4691 (current-time) (cdr tramp-current-connection))
4692 (or tramp-connection-min-time-diff 0)))
4693 (throw 'suppress 'suppress))
4695 ;; If too much time has passed since last command was sent, look
4696 ;; whether process is still alive. If it isn't, kill it. When
4697 ;; using ssh, it can sometimes happen that the remote end has hung
4698 ;; up but the local ssh client doesn't recognize this until it
4699 ;; tries to send some data to the remote end. So that's why we
4700 ;; try to send a command from time to time, then look again
4701 ;; whether the process is really alive.
4702 (condition-case nil
4703 (when (and (> (tramp-time-diff
4704 (current-time)
4705 (tramp-get-connection-property
4706 p "last-cmd-time" '(0 0 0)))
4708 (tramp-compat-process-live-p p))
4709 (tramp-send-command vec "echo are you awake" t t)
4710 (unless (and (tramp-compat-process-live-p p)
4711 (tramp-wait-for-output p 10))
4712 ;; The error will be caught locally.
4713 (tramp-error vec 'file-error "Awake did fail")))
4714 (file-error
4715 (tramp-cleanup-connection vec t)
4716 (setq p nil)))
4718 ;; New connection must be opened.
4719 (condition-case err
4720 (unless (tramp-compat-process-live-p p)
4722 ;; If `non-essential' is non-nil, don't reopen a new connection.
4723 ;; This variable has been introduced with Emacs 24.1.
4724 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4725 (throw 'non-essential 'non-essential))
4727 (with-tramp-progress-reporter
4728 vec 3
4729 (if (zerop (length (tramp-file-name-user vec)))
4730 (format "Opening connection for %s using %s"
4731 (tramp-file-name-host vec)
4732 (tramp-file-name-method vec))
4733 (format "Opening connection for %s@%s using %s"
4734 (tramp-file-name-user vec)
4735 (tramp-file-name-host vec)
4736 (tramp-file-name-method vec)))
4738 (catch 'uname-changed
4739 ;; Start new process.
4740 (when (and p (processp p))
4741 (delete-process p))
4742 (setenv "TERM" tramp-terminal-type)
4743 (setenv "LC_ALL" (tramp-get-local-locale vec))
4744 (if (stringp tramp-histfile-override)
4745 (setenv "HISTFILE" tramp-histfile-override)
4746 (if tramp-histfile-override
4747 (progn
4748 (setenv "HISTFILE")
4749 (setenv "HISTFILESIZE" "0")
4750 (setenv "HISTSIZE" "0"))))
4751 (setenv "PROMPT_COMMAND")
4752 (setenv "PS1" tramp-initial-end-of-output)
4753 (unless (stringp tramp-encoding-shell)
4754 (tramp-error vec 'file-error "`tramp-encoding-shell' not set"))
4755 (let* ((target-alist (tramp-compute-multi-hops vec))
4756 ;; We will apply `tramp-ssh-controlmaster-options'
4757 ;; only for the first hop.
4758 (options (tramp-ssh-controlmaster-options vec))
4759 (process-connection-type tramp-process-connection-type)
4760 (process-adaptive-read-buffering nil)
4761 ;; There are unfortunate settings for "cmdproxy" on
4762 ;; W32 systems.
4763 (process-coding-system-alist nil)
4764 (coding-system-for-read nil)
4765 ;; This must be done in order to avoid our file
4766 ;; name handler.
4767 (p (let ((default-directory
4768 (tramp-compat-temporary-file-directory)))
4769 (apply
4770 'start-process
4771 (tramp-get-connection-name vec)
4772 (tramp-get-connection-buffer vec)
4773 (if tramp-encoding-command-interactive
4774 (list tramp-encoding-shell
4775 tramp-encoding-command-interactive)
4776 (list tramp-encoding-shell))))))
4778 ;; Set sentinel and query flag.
4779 (tramp-set-connection-property p "vector" vec)
4780 (set-process-sentinel p 'tramp-process-sentinel)
4781 (set-process-query-on-exit-flag p nil)
4782 (setq tramp-current-connection
4783 (cons (butlast (append vec nil) 2) (current-time))
4784 tramp-current-host (system-name))
4786 (tramp-message
4787 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4789 ;; Check whether process is alive.
4790 (tramp-barf-if-no-shell-prompt
4791 p 10
4792 "Couldn't find local shell prompt for %s" tramp-encoding-shell)
4794 ;; Now do all the connections as specified.
4795 (while target-alist
4796 (let* ((hop (car target-alist))
4797 (l-method (tramp-file-name-method hop))
4798 (l-user (tramp-file-name-user hop))
4799 (l-host (tramp-file-name-host hop))
4800 (l-port nil)
4801 (login-program
4802 (tramp-get-method-parameter hop 'tramp-login-program))
4803 (login-args
4804 (tramp-get-method-parameter hop 'tramp-login-args))
4805 (login-env
4806 (tramp-get-method-parameter hop 'tramp-login-env))
4807 (async-args
4808 (tramp-get-method-parameter hop 'tramp-async-args))
4809 (connection-timeout
4810 (tramp-get-method-parameter
4811 hop 'tramp-connection-timeout))
4812 (gw-args
4813 (tramp-get-method-parameter hop 'tramp-gw-args))
4814 (gw (let ((tramp-verbose 0))
4815 (tramp-get-file-property hop "" "gateway" nil)))
4816 (g-method (and gw (tramp-file-name-method gw)))
4817 (g-user (and gw (tramp-file-name-user gw)))
4818 (g-host (and gw (tramp-file-name-real-host gw)))
4819 (command login-program)
4820 ;; We don't create the temporary file. In
4821 ;; fact, it is just a prefix for the
4822 ;; ControlPath option of ssh; the real
4823 ;; temporary file has another name, and it is
4824 ;; created and protected by ssh. It is also
4825 ;; removed by ssh when the connection is
4826 ;; closed. The temporary file name is cached
4827 ;; in the main connection process, therefore
4828 ;; we cannot use `tramp-get-connection-process'.
4829 (tmpfile
4830 (with-tramp-connection-property
4831 (get-process (tramp-buffer-name vec)) "temp-file"
4832 (make-temp-name
4833 (expand-file-name
4834 tramp-temp-name-prefix
4835 (tramp-compat-temporary-file-directory)))))
4836 spec r-shell)
4838 ;; Add arguments for asynchronous processes.
4839 (when (and process-name async-args)
4840 (setq login-args (append async-args login-args)))
4842 ;; Add gateway arguments if necessary.
4843 (when gw
4844 (tramp-set-connection-property p "gateway" t)
4845 (when gw-args
4846 (setq login-args (append gw-args login-args))))
4848 ;; Check for port number. Until now, there's no
4849 ;; need for handling like method, user, host.
4850 (when (string-match tramp-host-with-port-regexp l-host)
4851 (setq l-port (match-string 2 l-host)
4852 l-host (match-string 1 l-host)))
4854 ;; Check, whether there is a restricted shell.
4855 (dolist (elt tramp-restricted-shell-hosts-alist)
4856 (when (string-match elt tramp-current-host)
4857 (setq r-shell t)))
4859 ;; Set variables for computing the prompt for
4860 ;; reading password. They can also be derived
4861 ;; from a gateway.
4862 (setq tramp-current-method (or g-method l-method)
4863 tramp-current-user (or g-user l-user)
4864 tramp-current-host (or g-host l-host))
4866 ;; Add login environment.
4867 (when login-env
4868 (setq
4869 login-env
4870 (mapcar
4871 (lambda (x)
4872 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4873 (unless (member "" x) (mapconcat 'identity x " ")))
4874 login-env))
4875 (while login-env
4876 (setq command
4877 (format
4878 "%s=%s %s"
4879 (pop login-env)
4880 (tramp-shell-quote-argument (pop login-env))
4881 command)))
4882 (setq command (concat "env " command)))
4884 ;; Replace `login-args' place holders.
4885 (setq
4886 l-host (or l-host "")
4887 l-user (or l-user "")
4888 l-port (or l-port "")
4889 spec (format-spec-make ?t tmpfile)
4890 options (format-spec options spec)
4891 spec (format-spec-make
4892 ?h l-host ?u l-user ?p l-port ?c options)
4893 command
4894 (concat
4895 ;; We do not want to see the trailing local
4896 ;; prompt in `start-file-process'.
4897 (unless r-shell "exec ")
4898 command " "
4899 (mapconcat
4900 (lambda (x)
4901 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4902 (unless (member "" x) (mapconcat 'identity x " ")))
4903 login-args " ")
4904 ;; Local shell could be a Windows COMSPEC. It
4905 ;; doesn't know the ";" syntax, but we must exit
4906 ;; always for `start-file-process'. It could
4907 ;; also be a restricted shell, which does not
4908 ;; allow "exec".
4909 (when r-shell " && exit || exit")))
4911 ;; Send the command.
4912 (tramp-message vec 3 "Sending command `%s'" command)
4913 (tramp-send-command vec command t t)
4914 (tramp-process-actions
4915 p vec
4916 (min
4917 pos (with-current-buffer (process-buffer p) (point-max)))
4918 tramp-actions-before-shell
4919 (or connection-timeout tramp-connection-timeout))
4920 (tramp-message
4921 vec 3 "Found remote shell prompt on `%s'" l-host))
4922 ;; Next hop.
4923 (setq options ""
4924 target-alist (cdr target-alist)))
4926 ;; Set connection-local variables.
4927 (tramp-set-connection-local-variables vec)
4929 ;; Make initial shell settings.
4930 (tramp-open-connection-setup-interactive-shell p vec)
4932 ;; Mark it as connected.
4933 (tramp-set-connection-property p "connected" t)))))
4935 ;; Cleanup, and propagate the signal.
4936 ((error quit)
4937 (tramp-cleanup-connection vec t)
4938 (signal (car err) (cdr err))))))
4940 (defun tramp-send-command (vec command &optional neveropen nooutput)
4941 "Send the COMMAND to connection VEC.
4942 Erases temporary buffer before sending the command. If optional
4943 arg NEVEROPEN is non-nil, never try to open the connection. This
4944 is meant to be used from `tramp-maybe-open-connection' only. The
4945 function waits for output unless NOOUTPUT is set."
4946 (unless neveropen (tramp-maybe-open-connection vec))
4947 (let ((p (tramp-get-connection-process vec)))
4948 (when (tramp-get-connection-property p "remote-echo" nil)
4949 ;; We mark the command string that it can be erased in the output buffer.
4950 (tramp-set-connection-property p "check-remote-echo" t)
4951 ;; If we put `tramp-echo-mark' after a trailing newline (which
4952 ;; is assumed to be unquoted) `tramp-send-string' doesn't see
4953 ;; that newline and adds `tramp-rsh-end-of-line' right after
4954 ;; `tramp-echo-mark', so the remote shell sees two consecutive
4955 ;; trailing line endings and sends two prompts after executing
4956 ;; the command, which confuses `tramp-wait-for-output'.
4957 (when (and (not (string= command ""))
4958 (string-equal (substring command -1) "\n"))
4959 (setq command (substring command 0 -1)))
4960 ;; No need to restore a trailing newline here since `tramp-send-string'
4961 ;; makes sure that the string ends in `tramp-rsh-end-of-line', anyway.
4962 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4963 ;; Send the command.
4964 (tramp-message vec 6 "%s" command)
4965 (tramp-send-string vec command)
4966 (unless nooutput (tramp-wait-for-output p))))
4968 (defun tramp-wait-for-output (proc &optional timeout)
4969 "Wait for output from remote command."
4970 (unless (buffer-live-p (process-buffer proc))
4971 (delete-process proc)
4972 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4973 (with-current-buffer (process-buffer proc)
4974 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4975 ;; be leading escape sequences, which must be ignored.
4976 ;; Busyboxes built with the EDITING_ASK_TERMINAL config
4977 ;; option send also escape sequences, which must be
4978 ;; ignored.
4979 (regexp (format "[^#$\n]*%s\\(%s\\)?\r?$"
4980 (regexp-quote tramp-end-of-output)
4981 tramp-device-escape-sequence-regexp))
4982 ;; Sometimes, the commands do not return a newline but a
4983 ;; null byte before the shell prompt, for example "git
4984 ;; ls-files -c -z ...".
4985 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4986 (found (tramp-wait-for-regexp proc timeout regexp1)))
4987 (if found
4988 (let (buffer-read-only)
4989 ;; A simple-minded busybox has sent " ^H" sequences.
4990 ;; Delete them.
4991 (goto-char (point-min))
4992 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4993 (forward-line 1)
4994 (delete-region (point-min) (point)))
4995 ;; Delete the prompt.
4996 (goto-char (point-max))
4997 (re-search-backward regexp nil t)
4998 (delete-region (point) (point-max)))
4999 (if timeout
5000 (tramp-error
5001 proc 'file-error
5002 "[[Remote prompt `%s' not found in %d secs]]"
5003 tramp-end-of-output timeout)
5004 (tramp-error
5005 proc 'file-error
5006 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
5007 ;; Return value is whether end-of-output sentinel was found.
5008 found)))
5010 (defun tramp-send-command-and-check
5011 (vec command &optional subshell dont-suppress-err)
5012 "Run COMMAND and check its exit status.
5013 Sends `echo $?' along with the COMMAND for checking the exit status.
5014 If COMMAND is nil, just sends `echo $?'. Returns t if the exit
5015 status is 0, and nil otherwise.
5017 If the optional argument SUBSHELL is non-nil, the command is
5018 executed in a subshell, ie surrounded by parentheses. If
5019 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
5020 (tramp-send-command
5022 (concat (if subshell "( " "")
5023 command
5024 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
5025 "echo tramp_exit_status $?"
5026 (if subshell " )" "")))
5027 (with-current-buffer (tramp-get-connection-buffer vec)
5028 (goto-char (point-max))
5029 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
5030 (tramp-error
5031 vec 'file-error "Couldn't find exit status of `%s'" command))
5032 (skip-chars-forward "^ ")
5033 (prog1
5034 (zerop (read (current-buffer)))
5035 (let (buffer-read-only)
5036 (delete-region (match-beginning 0) (point-max))))))
5038 (defun tramp-barf-unless-okay (vec command fmt &rest args)
5039 "Run COMMAND, check exit status, throw error if exit status not okay.
5040 Similar to `tramp-send-command-and-check' but accepts two more arguments
5041 FMT and ARGS which are passed to `error'."
5042 (or (tramp-send-command-and-check vec command)
5043 (apply 'tramp-error vec 'file-error fmt args)))
5045 (defun tramp-send-command-and-read (vec command &optional noerror marker)
5046 "Run COMMAND and return the output, which must be a Lisp expression.
5047 If MARKER is a regexp, read the output after that string.
5048 In case there is no valid Lisp expression and NOERROR is nil, it
5049 raises an error."
5050 (when (if noerror
5051 (tramp-send-command-and-check vec command)
5052 (tramp-barf-unless-okay
5053 vec command "`%s' returns with error" command))
5054 (with-current-buffer (tramp-get-connection-buffer vec)
5055 (goto-char (point-min))
5056 ;; Read the marker.
5057 (when (stringp marker)
5058 (condition-case nil
5059 (re-search-forward marker)
5060 (error (unless noerror
5061 (tramp-error
5062 vec 'file-error
5063 "`%s' does not return the marker `%s': `%s'"
5064 command marker (buffer-string))))))
5065 ;; Read the expression.
5066 (condition-case nil
5067 (prog1 (read (current-buffer))
5068 ;; Error handling.
5069 (when (re-search-forward "\\S-" (point-at-eol) t)
5070 (error nil)))
5071 (error (unless noerror
5072 (tramp-error
5073 vec 'file-error
5074 "`%s' does not return a valid Lisp expression: `%s'"
5075 command (buffer-string))))))))
5077 (defun tramp-convert-file-attributes (vec attr)
5078 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
5079 Convert file mode bits to string and set virtual device number.
5080 Return ATTR."
5081 (when attr
5082 ;; Remove color escape sequences from symlink.
5083 (when (stringp (car attr))
5084 (while (string-match tramp-display-escape-sequence-regexp (car attr))
5085 (setcar attr (replace-match "" nil nil (car attr)))))
5086 ;; Convert uid and gid. Use `tramp-unknown-id-integer' as
5087 ;; indication of unusable value.
5088 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
5089 (setcar (nthcdr 2 attr) tramp-unknown-id-integer))
5090 (when (and (floatp (nth 2 attr))
5091 (<= (nth 2 attr) most-positive-fixnum))
5092 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
5093 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
5094 (setcar (nthcdr 3 attr) tramp-unknown-id-integer))
5095 (when (and (floatp (nth 3 attr))
5096 (<= (nth 3 attr) most-positive-fixnum))
5097 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
5098 ;; Convert last access time.
5099 (unless (listp (nth 4 attr))
5100 (setcar (nthcdr 4 attr)
5101 (list (floor (nth 4 attr) 65536)
5102 (floor (mod (nth 4 attr) 65536)))))
5103 ;; Convert last modification time.
5104 (unless (listp (nth 5 attr))
5105 (setcar (nthcdr 5 attr)
5106 (list (floor (nth 5 attr) 65536)
5107 (floor (mod (nth 5 attr) 65536)))))
5108 ;; Convert last status change time.
5109 (unless (listp (nth 6 attr))
5110 (setcar (nthcdr 6 attr)
5111 (list (floor (nth 6 attr) 65536)
5112 (floor (mod (nth 6 attr) 65536)))))
5113 ;; Convert file size.
5114 (when (< (nth 7 attr) 0)
5115 (setcar (nthcdr 7 attr) -1))
5116 (when (and (floatp (nth 7 attr))
5117 (<= (nth 7 attr) most-positive-fixnum))
5118 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
5119 ;; Convert file mode bits to string.
5120 (unless (stringp (nth 8 attr))
5121 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
5122 (when (stringp (car attr))
5123 (aset (nth 8 attr) 0 ?l)))
5124 ;; Convert directory indication bit.
5125 (when (string-match "^d" (nth 8 attr))
5126 (setcar attr t))
5127 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
5128 (when (consp (car attr))
5129 (if (and (stringp (caar attr))
5130 (string-match ".+ -> .\\(.+\\)." (caar attr)))
5131 (setcar attr (match-string 1 (caar attr)))
5132 (setcar attr nil)))
5133 ;; Set file's gid change bit.
5134 (setcar (nthcdr 9 attr)
5135 (if (numberp (nth 3 attr))
5136 (not (= (nth 3 attr)
5137 (tramp-get-remote-gid vec 'integer)))
5138 (not (string-equal
5139 (nth 3 attr)
5140 (tramp-get-remote-gid vec 'string)))))
5141 ;; Convert inode.
5142 (unless (listp (nth 10 attr))
5143 (setcar (nthcdr 10 attr)
5144 (condition-case nil
5145 (cons (floor (nth 10 attr) 65536)
5146 (floor (mod (nth 10 attr) 65536)))
5147 ;; Inodes can be incredible huge. We must hide this.
5148 (error (tramp-get-inode vec)))))
5149 ;; Set virtual device number.
5150 (setcar (nthcdr 11 attr)
5151 (tramp-get-device vec))
5152 attr))
5154 (defun tramp-shell-case-fold (string)
5155 "Converts STRING to shell glob pattern which ignores case."
5156 (mapconcat
5157 (lambda (c)
5158 (if (equal (downcase c) (upcase c))
5159 (vector c)
5160 (format "[%c%c]" (downcase c) (upcase c))))
5161 string
5162 ""))
5164 (defun tramp-make-copy-program-file-name (vec)
5165 "Create a file name suitable for `scp', `pscp', or `nc' and workalikes."
5166 (let ((method (tramp-file-name-method vec))
5167 (user (tramp-file-name-user vec))
5168 (host (tramp-file-name-real-host vec))
5169 (localname (directory-file-name (tramp-file-name-localname vec))))
5170 (when (string-match tramp-ipv6-regexp host)
5171 (setq host (format "[%s]" host)))
5172 (unless (string-match "ftp$" method)
5173 (setq localname (tramp-shell-quote-argument localname)))
5174 (cond
5175 ((tramp-get-method-parameter vec 'tramp-remote-copy-program)
5176 localname)
5177 ((not (zerop (length user)))
5178 (tramp-unquote-shell-quote-argument
5179 (format "%s@%s:%s" user host localname)))
5180 (t (tramp-unquote-shell-quote-argument (format "%s:%s" host localname))))))
5182 (defun tramp-method-out-of-band-p (vec size)
5183 "Return t if this is an out-of-band method, nil otherwise."
5184 (and
5185 ;; It shall be an out-of-band method.
5186 (tramp-get-method-parameter vec 'tramp-copy-program)
5187 ;; There must be a size, otherwise the file doesn't exist.
5188 (numberp size)
5189 ;; Either the file size is large enough, or (in rare cases) there
5190 ;; does not exist a remote encoding.
5191 (or (null tramp-copy-size-limit)
5192 (> size tramp-copy-size-limit)
5193 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
5195 ;; Variables local to connection.
5197 (defun tramp-get-remote-path (vec)
5198 "Compile list of remote directories for $PATH.
5199 Nonexistent directories are removed from spec."
5200 (with-tramp-connection-property
5201 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
5202 ;; cache the result for the session only. Otherwise, the result
5203 ;; is cached persistently.
5204 (if (memq 'tramp-own-remote-path tramp-remote-path)
5205 (tramp-get-connection-process vec)
5206 vec)
5207 "remote-path"
5208 (let* ((remote-path (copy-tree tramp-remote-path))
5209 (elt1 (memq 'tramp-default-remote-path remote-path))
5210 (elt2 (memq 'tramp-own-remote-path remote-path))
5211 (default-remote-path
5212 (when elt1
5214 (tramp-send-command-and-read
5215 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
5216 ;; Default if "getconf" is not available.
5217 (progn
5218 (tramp-message
5219 vec 3
5220 "`getconf PATH' not successful, using default value \"%s\"."
5221 "/bin:/usr/bin")
5222 "/bin:/usr/bin"))))
5223 (own-remote-path
5224 ;; The login shell could return more than just the $PATH
5225 ;; string. So we use `tramp-end-of-heredoc' as marker.
5226 (when elt2
5228 (tramp-send-command-and-read
5230 (format
5231 "%s %s %s 'echo %s \\\"$PATH\\\"'"
5232 (tramp-get-method-parameter vec 'tramp-remote-shell)
5233 (mapconcat
5234 'identity
5235 (tramp-get-method-parameter vec 'tramp-remote-shell-login)
5236 " ")
5237 (mapconcat
5238 'identity
5239 (tramp-get-method-parameter vec 'tramp-remote-shell-args)
5240 " ")
5241 (tramp-shell-quote-argument tramp-end-of-heredoc))
5242 'noerror (regexp-quote tramp-end-of-heredoc))
5243 (progn
5244 (tramp-message
5245 vec 2 "Could not retrieve `tramp-own-remote-path'")
5246 nil)))))
5248 ;; Replace place holder `tramp-default-remote-path'.
5249 (when elt1
5250 (setcdr elt1
5251 (append
5252 (split-string (or default-remote-path "") ":" 'omit)
5253 (cdr elt1)))
5254 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
5256 ;; Replace place holder `tramp-own-remote-path'.
5257 (when elt2
5258 (setcdr elt2
5259 (append
5260 (split-string (or own-remote-path "") ":" 'omit)
5261 (cdr elt2)))
5262 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
5264 ;; Remove double entries.
5265 (setq elt1 remote-path)
5266 (while (consp elt1)
5267 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
5268 (setcar elt2 nil))
5269 (setq elt1 (cdr elt1)))
5271 ;; Remove non-existing directories.
5272 (delq
5274 (mapcar
5275 (lambda (x)
5276 (and
5277 (stringp x)
5278 (file-directory-p
5279 (tramp-make-tramp-file-name
5280 (tramp-file-name-method vec)
5281 (tramp-file-name-user vec)
5282 (tramp-file-name-host vec)
5285 remote-path)))))
5287 (defun tramp-get-remote-locale (vec)
5288 "Determine remote locale, supporting UTF8 if possible."
5289 (with-tramp-connection-property vec "locale"
5290 (tramp-send-command vec "locale -a")
5291 (let ((candidates '("en_US.utf8" "C.utf8" "en_US.UTF-8"))
5292 locale)
5293 (with-current-buffer (tramp-get-connection-buffer vec)
5294 (while candidates
5295 (goto-char (point-min))
5296 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
5297 (buffer-string))
5298 (setq locale (car candidates)
5299 candidates nil)
5300 (setq candidates (cdr candidates)))))
5301 ;; Return value.
5302 (format "LC_ALL=%s" (or locale "C")))))
5304 (defun tramp-get-ls-command (vec)
5305 "Determine remote `ls' command."
5306 (with-tramp-connection-property vec "ls"
5307 (tramp-message vec 5 "Finding a suitable `ls' command")
5309 (catch 'ls-found
5310 (dolist (cmd '("ls" "gnuls" "gls"))
5311 (let ((dl (tramp-get-remote-path vec))
5312 result)
5313 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5314 ;; Check parameters. On busybox, "ls" output coloring is
5315 ;; enabled by default sometimes. So we try to disable it
5316 ;; when possible. $LS_COLORING is not supported there.
5317 ;; Some "ls" versions are sensible wrt the order of
5318 ;; arguments, they fail when "-al" is after the
5319 ;; "--color=never" argument (for example on FreeBSD).
5320 (when (tramp-send-command-and-check
5321 vec (format "%s -lnd /" result))
5322 (when (tramp-send-command-and-check
5323 vec (format
5324 "%s --color=never -al /dev/null" result))
5325 (setq result (concat result " --color=never")))
5326 (throw 'ls-found result))
5327 (setq dl (cdr dl))))))
5328 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
5330 (defun tramp-get-ls-command-with-dired (vec)
5331 "Check, whether the remote `ls' command supports the --dired option."
5332 (save-match-data
5333 (with-tramp-connection-property vec "ls-dired"
5334 (tramp-message vec 5 "Checking, whether `ls --dired' works")
5335 ;; Some "ls" versions are sensible wrt the order of arguments,
5336 ;; they fail when "-al" is after the "--dired" argument (for
5337 ;; example on FreeBSD).
5338 (tramp-send-command-and-check
5339 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
5341 (defun tramp-get-ls-command-with-quoting-style (vec)
5342 "Check, whether the remote `ls' command supports the --quoting-style option."
5343 (save-match-data
5344 (with-tramp-connection-property vec "ls-quoting-style"
5345 (tramp-message vec 5 "Checking, whether `ls --quoting-style=shell' works")
5346 (tramp-send-command-and-check
5347 vec (format "%s --quoting-style=shell -al /dev/null"
5348 (tramp-get-ls-command vec))))))
5350 (defun tramp-get-ls-command-with-w-option (vec)
5351 "Check, whether the remote `ls' command supports the -w option."
5352 (save-match-data
5353 (with-tramp-connection-property vec "ls-w-option"
5354 (tramp-message vec 5 "Checking, whether `ls -w' works")
5355 ;; Option "-w" is available on BSD systems. No argument is
5356 ;; given, because this could return wrong results in case "ls"
5357 ;; supports the "-w NUM" argument, as for busyboxes.
5358 (tramp-send-command-and-check
5359 vec (format "%s -alw" (tramp-get-ls-command vec))))))
5361 (defun tramp-get-test-command (vec)
5362 "Determine remote `test' command."
5363 (with-tramp-connection-property vec "test"
5364 (tramp-message vec 5 "Finding a suitable `test' command")
5365 (if (tramp-send-command-and-check vec "test 0")
5366 "test"
5367 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
5369 (defun tramp-get-test-nt-command (vec)
5370 "Check, whether the remote `test' command supports the -nt option."
5371 ;; Does `test A -nt B' work? Use abominable `find' construct if it
5372 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
5373 ;; for otherwise the shell crashes.
5374 (with-tramp-connection-property vec "test-nt"
5376 (progn
5377 (tramp-send-command
5378 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
5379 (with-current-buffer (tramp-get-buffer vec)
5380 (goto-char (point-min))
5381 (when (looking-at (regexp-quote tramp-end-of-output))
5382 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
5383 (progn
5384 (tramp-send-command
5386 (format
5387 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
5388 (tramp-get-test-command vec)))
5389 "tramp_test_nt %s %s"))))
5391 (defun tramp-get-file-exists-command (vec)
5392 "Determine remote command for file existing check."
5393 (with-tramp-connection-property vec "file-exists"
5394 (tramp-message vec 5 "Finding command to check if file exists")
5395 (tramp-find-file-exists-command vec)))
5397 (defun tramp-get-remote-ln (vec)
5398 "Determine remote `ln' command."
5399 (with-tramp-connection-property vec "ln"
5400 (tramp-message vec 5 "Finding a suitable `ln' command")
5401 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
5403 (defun tramp-get-remote-perl (vec)
5404 "Determine remote `perl' command."
5405 (with-tramp-connection-property vec "perl"
5406 (tramp-message vec 5 "Finding a suitable `perl' command")
5407 (let ((result
5408 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
5409 (tramp-find-executable vec "perl" (tramp-get-remote-path vec)))))
5410 ;; Perform a basic check.
5411 (and result
5412 (null (tramp-send-command-and-check
5413 vec (format "%s -e 'print \"Hello\n\";'" result)))
5414 (setq result nil))
5415 ;; We must check also for some Perl modules.
5416 (when result
5417 (with-tramp-connection-property vec "perl-file-spec"
5418 (tramp-send-command-and-check
5419 vec (format "%s -e 'use File::Spec;'" result)))
5420 (with-tramp-connection-property vec "perl-cwd-realpath"
5421 (tramp-send-command-and-check
5422 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
5423 result)))
5425 (defun tramp-get-remote-stat (vec)
5426 "Determine remote `stat' command."
5427 (with-tramp-connection-property vec "stat"
5428 (tramp-message vec 5 "Finding a suitable `stat' command")
5429 (let ((result (tramp-find-executable
5430 vec "stat" (tramp-get-remote-path vec)))
5431 tmp)
5432 ;; Check whether stat(1) returns usable syntax. "%s" does not
5433 ;; work on older AIX systems. Recent GNU stat versions (8.24?)
5434 ;; use shell quoted format for "%N", we check the boundaries "`"
5435 ;; and "'", therefore. See Bug#23422 in coreutils.
5436 (when result
5437 (setq tmp
5438 (tramp-send-command-and-read
5439 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5440 (unless (and (listp tmp) (stringp (car tmp))
5441 (string-match "^`/'$" (car tmp))
5442 (integerp (cadr tmp)))
5443 (setq result nil)))
5444 result)))
5446 (defun tramp-get-remote-readlink (vec)
5447 "Determine remote `readlink' command."
5448 (with-tramp-connection-property vec "readlink"
5449 (tramp-message vec 5 "Finding a suitable `readlink' command")
5450 (let ((result (tramp-find-executable
5451 vec "readlink" (tramp-get-remote-path vec))))
5452 (when (and result
5453 (tramp-send-command-and-check
5454 vec (format "%s --canonicalize-missing /" result)))
5455 result))))
5457 (defun tramp-get-remote-trash (vec)
5458 "Determine remote `trash' command."
5459 (with-tramp-connection-property vec "trash"
5460 (tramp-message vec 5 "Finding a suitable `trash' command")
5461 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5463 (defun tramp-get-remote-touch (vec)
5464 "Determine remote `touch' command."
5465 (with-tramp-connection-property vec "touch"
5466 (tramp-message vec 5 "Finding a suitable `touch' command")
5467 (let ((result (tramp-find-executable
5468 vec "touch" (tramp-get-remote-path vec)))
5469 (tmpfile
5470 (make-temp-name
5471 (expand-file-name
5472 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
5473 ;; Busyboxes do support the "-t" option only when they have been
5474 ;; built with the DESKTOP config option. Let's check it.
5475 (when result
5476 (tramp-set-connection-property
5477 vec "touch-t"
5478 (tramp-send-command-and-check
5480 (format
5481 "%s -t %s %s"
5482 result
5483 (format-time-string "%Y%m%d%H%M.%S")
5484 (file-remote-p tmpfile 'localname))))
5485 (delete-file tmpfile))
5486 result)))
5488 (defun tramp-get-remote-gvfs-monitor-dir (vec)
5489 "Determine remote `gvfs-monitor-dir' command."
5490 (with-tramp-connection-property vec "gvfs-monitor-dir"
5491 (tramp-message vec 5 "Finding a suitable `gvfs-monitor-dir' command")
5492 (tramp-find-executable
5493 vec "gvfs-monitor-dir" (tramp-get-remote-path vec) t t)))
5495 (defun tramp-get-remote-inotifywait (vec)
5496 "Determine remote `inotifywait' command."
5497 (with-tramp-connection-property vec "inotifywait"
5498 (tramp-message vec 5 "Finding a suitable `inotifywait' command")
5499 (tramp-find-executable vec "inotifywait" (tramp-get-remote-path vec) t t)))
5501 (defun tramp-get-remote-id (vec)
5502 "Determine remote `id' command."
5503 (with-tramp-connection-property vec "id"
5504 (tramp-message vec 5 "Finding POSIX `id' command")
5505 (catch 'id-found
5506 (dolist (cmd '("id" "gid"))
5507 (let ((dl (tramp-get-remote-path vec))
5508 result)
5509 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5510 ;; Check POSIX parameter.
5511 (when (tramp-send-command-and-check vec (format "%s -u" result))
5512 (throw 'id-found result))
5513 (setq dl (cdr dl))))))))
5515 (defun tramp-get-remote-uid-with-id (vec id-format)
5516 "Implement `tramp-get-remote-uid' for Tramp files using `id'."
5517 (tramp-send-command-and-read
5519 (format "%s -u%s %s"
5520 (tramp-get-remote-id vec)
5521 (if (equal id-format 'integer) "" "n")
5522 (if (equal id-format 'integer)
5523 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5525 (defun tramp-get-remote-uid-with-perl (vec id-format)
5526 "Implement `tramp-get-remote-uid' for Tramp files using a Perl script."
5527 (tramp-send-command-and-read
5529 (format "%s -le '%s'"
5530 (tramp-get-remote-perl vec)
5531 (if (equal id-format 'integer)
5532 "print $>"
5533 "print \"\\\"\", scalar getpwuid($>), \"\\\"\""))))
5535 (defun tramp-get-remote-python (vec)
5536 "Determine remote `python' command."
5537 (with-tramp-connection-property vec "python"
5538 (tramp-message vec 5 "Finding a suitable `python' command")
5539 (or (tramp-find-executable vec "python" (tramp-get-remote-path vec))
5540 (tramp-find-executable vec "python2" (tramp-get-remote-path vec))
5541 (tramp-find-executable vec "python3" (tramp-get-remote-path vec)))))
5543 (defun tramp-get-remote-uid-with-python (vec id-format)
5544 "Implement `tramp-get-remote-uid' for Tramp files using `python'."
5545 (tramp-send-command-and-read
5547 (format "%s -c \"%s\""
5548 (tramp-get-remote-python vec)
5549 (if (equal id-format 'integer)
5550 "import os; print (os.getuid())"
5551 "import os, pwd; print ('\\\"' + pwd.getpwuid(os.getuid())[0] + '\\\"')"))))
5553 (defun tramp-get-remote-uid (vec id-format)
5554 "The uid of the remote connection VEC, in ID-FORMAT.
5555 ID-FORMAT valid values are `string' and `integer'."
5556 (with-tramp-connection-property vec (format "uid-%s" id-format)
5557 (let ((res
5558 (ignore-errors
5559 (cond
5560 ((tramp-get-remote-id vec)
5561 (tramp-get-remote-uid-with-id vec id-format))
5562 ((tramp-get-remote-perl vec)
5563 (tramp-get-remote-uid-with-perl vec id-format))
5564 ((tramp-get-remote-python vec)
5565 (tramp-get-remote-uid-with-python vec id-format))))))
5566 ;; Ensure there is a valid result.
5567 (cond
5568 ((and (equal id-format 'integer) (not (integerp res)))
5569 tramp-unknown-id-integer)
5570 ((and (equal id-format 'string) (not (stringp res)))
5571 tramp-unknown-id-string)
5572 (t res)))))
5574 (defun tramp-get-remote-gid-with-id (vec id-format)
5575 "Implement `tramp-get-remote-gid' for Tramp files using `id'."
5576 (tramp-send-command-and-read
5578 (format "%s -g%s %s"
5579 (tramp-get-remote-id vec)
5580 (if (equal id-format 'integer) "" "n")
5581 (if (equal id-format 'integer)
5582 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5584 (defun tramp-get-remote-gid-with-perl (vec id-format)
5585 "Implement `tramp-get-remote-gid' for Tramp files using a Perl script."
5586 (tramp-send-command-and-read
5588 (format "%s -le '%s'"
5589 (tramp-get-remote-perl vec)
5590 (if (equal id-format 'integer)
5591 "print ($)=~/(\\d+)/)"
5592 "print \"\\\"\", scalar getgrgid($)), \"\\\"\""))))
5594 (defun tramp-get-remote-gid-with-python (vec id-format)
5595 "Implement `tramp-get-remote-gid' for Tramp files using `python'."
5596 (tramp-send-command-and-read
5598 (format "%s -c \"%s\""
5599 (tramp-get-remote-python vec)
5600 (if (equal id-format 'integer)
5601 "import os; print (os.getgid())"
5602 "import os, grp; print ('\\\"' + grp.getgrgid(os.getgid())[0] + '\\\"')"))))
5604 (defun tramp-get-remote-gid (vec id-format)
5605 "The gid of the remote connection VEC, in ID-FORMAT.
5606 ID-FORMAT valid values are `string' and `integer'."
5607 (with-tramp-connection-property vec (format "gid-%s" id-format)
5608 (let ((res
5609 (ignore-errors
5610 (cond
5611 ((tramp-get-remote-id vec)
5612 (tramp-get-remote-gid-with-id vec id-format))
5613 ((tramp-get-remote-perl vec)
5614 (tramp-get-remote-gid-with-perl vec id-format))
5615 ((tramp-get-remote-python vec)
5616 (tramp-get-remote-gid-with-python vec id-format))))))
5617 ;; Ensure there is a valid result.
5618 (cond
5619 ((and (equal id-format 'integer) (not (integerp res)))
5620 tramp-unknown-id-integer)
5621 ((and (equal id-format 'string) (not (stringp res)))
5622 tramp-unknown-id-string)
5623 (t res)))))
5625 (defun tramp-get-env-with-u-option (vec)
5626 "Check, whether the remote `env' command supports the -u option."
5627 (with-tramp-connection-property vec "env-u-option"
5628 (tramp-message vec 5 "Checking, whether `env -u' works")
5629 ;; Option "-u" is a GNU extension.
5630 (tramp-send-command-and-check
5631 vec "env FOO=foo env -u FOO 2>/dev/null | grep -qv FOO" t)))
5633 ;; Some predefined connection properties.
5634 (defun tramp-get-inline-compress (vec prop size)
5635 "Return the compress command related to PROP.
5636 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5637 the length of the file to be compressed.
5639 If no corresponding command is found, nil is returned."
5640 (when (and (integerp tramp-inline-compress-start-size)
5641 (> size tramp-inline-compress-start-size))
5642 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5643 (tramp-find-inline-compress vec)
5644 (tramp-get-connection-property
5645 (tramp-get-connection-process vec) prop nil))))
5647 (defun tramp-get-inline-coding (vec prop size)
5648 "Return the coding command related to PROP.
5649 PROP is either `remote-encoding', `remote-decoding',
5650 `local-encoding' or `local-decoding'.
5652 SIZE is the length of the file to be coded. Depending on SIZE,
5653 compression might be applied.
5655 If no corresponding command is found, nil is returned.
5656 Otherwise, either a string is returned which contains a `%s' mark
5657 to be used for the respective input or output file; or a Lisp
5658 function cell is returned to be applied on a buffer."
5659 ;; We must catch the errors, because we want to return nil, when
5660 ;; no inline coding is found.
5661 (ignore-errors
5662 (let ((coding
5663 (with-tramp-connection-property
5664 (tramp-get-connection-process vec) prop
5665 (tramp-find-inline-encoding vec)
5666 (tramp-get-connection-property
5667 (tramp-get-connection-process vec) prop nil)))
5668 (prop1 (if (string-match "encoding" prop)
5669 "inline-compress" "inline-decompress"))
5670 compress)
5671 ;; The connection property might have been cached. So we must
5672 ;; send the script to the remote side - maybe.
5673 (when (and coding (symbolp coding) (string-match "remote" prop))
5674 (let ((name (symbol-name coding)))
5675 (while (string-match (regexp-quote "-") name)
5676 (setq name (replace-match "_" nil t name)))
5677 (tramp-maybe-send-script vec (symbol-value coding) name)
5678 (setq coding name)))
5679 (when coding
5680 ;; Check for the `compress' command.
5681 (setq compress (tramp-get-inline-compress vec prop1 size))
5682 ;; Return the value.
5683 (cond
5684 ((and compress (symbolp coding))
5685 (if (string-match "decompress" prop1)
5686 `(lambda (beg end)
5687 (,coding beg end)
5688 (let ((coding-system-for-write 'binary)
5689 (coding-system-for-read 'binary))
5690 (apply
5691 'tramp-call-process-region ,vec (point-min) (point-max)
5692 (car (split-string ,compress)) t t nil
5693 (cdr (split-string ,compress)))))
5694 `(lambda (beg end)
5695 (let ((coding-system-for-write 'binary)
5696 (coding-system-for-read 'binary))
5697 (apply
5698 'tramp-call-process-region ,vec beg end
5699 (car (split-string ,compress)) t t nil
5700 (cdr (split-string ,compress))))
5701 (,coding (point-min) (point-max)))))
5702 ((symbolp coding)
5703 coding)
5704 ((and compress (string-match "decoding" prop))
5705 (format
5706 ;; Windows shells need the program file name after
5707 ;; the pipe symbol be quoted if they use forward
5708 ;; slashes as directory separators.
5709 (cond
5710 ((and (string-match "local" prop)
5711 (memq system-type '(windows-nt)))
5712 "(%s | \"%s\")")
5713 ((string-match "local" prop) "(%s | %s)")
5714 (t "(%s | %s >%%s)"))
5715 coding compress))
5716 (compress
5717 (format
5718 ;; Windows shells need the program file name after
5719 ;; the pipe symbol be quoted if they use forward
5720 ;; slashes as directory separators.
5721 (if (and (string-match "local" prop)
5722 (memq system-type '(windows-nt)))
5723 "(%s <%%s | \"%s\")"
5724 "(%s <%%s | %s)")
5725 compress coding))
5726 ((string-match "decoding" prop)
5727 (cond
5728 ((string-match "local" prop) (format "%s" coding))
5729 (t (format "%s >%%s" coding))))
5731 (format "%s <%%s" coding)))))))
5733 (add-hook 'tramp-unload-hook
5734 (lambda ()
5735 (unload-feature 'tramp-sh 'force)))
5737 (provide 'tramp-sh)
5739 ;;; TODO:
5741 ;; * Don't use globbing for directories with many files, as this is
5742 ;; likely to produce long command lines, and some shells choke on
5743 ;; long command lines.
5745 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5746 ;; then look if it's the right version (with `perl -v').
5748 ;; * When editing a remote CVS controlled file as a different user, VC
5749 ;; gets confused about the file locking status. Try to find out why
5750 ;; the workaround doesn't work.
5752 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5753 ;; until the last but one hop via `start-file-process'. Apply it
5754 ;; also for ftp and smb.
5756 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5757 ;; some shell with root privileges, it would be nice if I could
5758 ;; just call
5759 ;; trampclient filename.c
5760 ;; as an editor, and the _current_ shell would connect to an Emacs
5761 ;; server and would be used in an existing non-privileged Emacs
5762 ;; session for doing the editing in question.
5763 ;; That way, I need not tell Emacs my password again and be afraid
5764 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5765 ;; once display a just typed password in the context of a keyboard
5766 ;; sequence prompt for a question immediately following in a shell
5767 ;; script run within Emacs -- nasty).
5768 ;; And if I have some ssh session running to a different computer,
5769 ;; having the possibility of passing a local file there to a local
5770 ;; Emacs session (in case I can arrange for a connection back) would
5771 ;; be nice.
5772 ;; Likely the corresponding Tramp server should not allow the
5773 ;; equivalent of the emacsclient -eval option in order to make this
5774 ;; reasonably unproblematic. And maybe trampclient should have some
5775 ;; way of passing credentials, like by using an SSL socket or
5776 ;; something. (David Kastrup)
5778 ;; * Reconnect directly to a compliant shell without first going
5779 ;; through the user's default shell. (Pete Forman)
5781 ;; * How can I interrupt the remote process with a signal
5782 ;; (interrupt-process seems not to work)? (Markus Triska)
5784 ;; * Avoid the local shell entirely for starting remote processes. If
5785 ;; so, I think even a signal, when delivered directly to the local
5786 ;; SSH instance, would correctly be propagated to the remote process
5787 ;; automatically; possibly SSH would have to be started with
5788 ;; "-t". (Markus Triska)
5790 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5791 ;; isn't on the remote host. (Mark A. Hershberger)
5793 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5795 ;; * Optimize out-of-band copying when both methods are scp-like (not
5796 ;; rsync).
5798 ;; * Keep a second connection open for out-of-band methods like scp or
5799 ;; rsync.
5801 ;; * Implement completion for "/method:user@host:~<abc> TAB".
5803 ;; * I think you could get the best of both worlds by using an
5804 ;; approach similar to Tramp but running a little tramp-daemon on
5805 ;; the other end, such that we can use a more efficient
5806 ;; communication protocol (e.g. when saving a file we could locally
5807 ;; diff it against the last version (of which the remote daemon
5808 ;; would also keep a copy), and then only send the diff).
5810 ;; This said, even using such a daemon it might be difficult to get
5811 ;; good performance: part of the problem is the number of
5812 ;; round-trips. E.g. when saving a file we have to check if the
5813 ;; file was modified in the mean time and whether saving into a new
5814 ;; inode would change the owner (etc...), which each require a
5815 ;; round-trip. To get rid of these round-trips, we'd have to
5816 ;; shortcut this code and delegate the higher-level "save file"
5817 ;; operation to the remote server, which then has to perform those
5818 ;; tasks but still obeying the locally set customizations about how
5819 ;; to do each one of those tasks.
5821 ;; We could either put higher-level ops in there (like
5822 ;; `save-buffer'), which implies replicating the whole `save-buffer'
5823 ;; behavior, which is a lot of work and likely to be not 100%
5824 ;; faithful.
5826 ;; Or we could introduce new low-level ops that are asynchronous,
5827 ;; and then rewrite save-buffer to use them. IOW save-buffer would
5828 ;; start with a bunch of calls like `start-getting-file-attributes'
5829 ;; which could immediately be passed on to the remote side, and
5830 ;; later on checks the return value of those calls as and when
5831 ;; needed. (Stefan Monnier)
5833 ;;; tramp-sh.el ends here