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