Merge from origin/emacs-25
[emacs.git] / lisp / net / tramp-sh.el
blobe907719469115508ff6a6f3b62da6f810a988c62
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 "26.1"
570 :type '(repeat string)
571 :require 'tramp)
573 ;;;###tramp-autoload
574 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
575 "Alist specifying extra arguments to pass to the remote shell.
576 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
577 matching the shell file name and ARGS is a string specifying the
578 arguments.
580 This variable is only used when Tramp needs to start up another shell
581 for tilde expansion. The extra arguments should typically prevent the
582 shell from reading its init file."
583 :group 'tramp
584 ;; This might be the wrong way to test whether the widget type
585 ;; `alist' is available. Who knows the right way to test it?
586 :type (if (get 'alist 'widget-type)
587 '(alist :key-type string :value-type string)
588 '(repeat (cons string string)))
589 :require 'tramp)
591 (defconst tramp-actions-before-shell
592 '((tramp-login-prompt-regexp tramp-action-login)
593 (tramp-password-prompt-regexp tramp-action-password)
594 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
595 (shell-prompt-pattern tramp-action-succeed)
596 (tramp-shell-prompt-pattern tramp-action-succeed)
597 (tramp-yesno-prompt-regexp tramp-action-yesno)
598 (tramp-yn-prompt-regexp tramp-action-yn)
599 (tramp-terminal-prompt-regexp tramp-action-terminal)
600 (tramp-process-alive-regexp tramp-action-process-alive))
601 "List of pattern/action pairs.
602 Whenever a pattern matches, the corresponding action is performed.
603 Each item looks like (PATTERN ACTION).
605 The PATTERN should be a symbol, a variable. The value of this
606 variable gives the regular expression to search for. Note that the
607 regexp must match at the end of the buffer, \"\\'\" is implicitly
608 appended to it.
610 The ACTION should also be a symbol, but a function. When the
611 corresponding PATTERN matches, the ACTION function is called.")
613 (defconst tramp-actions-copy-out-of-band
614 '((tramp-password-prompt-regexp tramp-action-password)
615 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
616 (tramp-copy-failed-regexp tramp-action-permission-denied)
617 (tramp-process-alive-regexp tramp-action-out-of-band))
618 "List of pattern/action pairs.
619 This list is used for copying/renaming with out-of-band methods.
621 See `tramp-actions-before-shell' for more info.")
623 (defconst tramp-uudecode
624 "(echo begin 600 %t; tail -n +2) | uudecode
625 cat %t
626 rm -f %t"
627 "Shell function to implement `uudecode' to standard output.
628 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
629 for this or `uudecode -p', but some systems don't, and for them
630 we have this shell function.")
632 (defconst tramp-perl-file-truename
633 "%s -e '
634 use File::Spec;
635 use Cwd \"realpath\";
637 sub myrealpath {
638 my ($file) = @_;
639 return realpath($file) if -e $file;
642 sub recursive {
643 my ($volume, @dirs) = @_;
644 my $real = myrealpath(File::Spec->catpath(
645 $volume, File::Spec->catdir(@dirs), \"\"));
646 if ($real) {
647 my ($vol, $dir) = File::Spec->splitpath($real, 1);
648 return ($vol, File::Spec->splitdir($dir));
650 else {
651 my $last = pop(@dirs);
652 ($volume, @dirs) = recursive($volume, @dirs);
653 push(@dirs, $last);
654 return ($volume, @dirs);
658 $result = myrealpath($ARGV[0]);
659 if (!$result) {
660 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
661 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
663 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
666 $result =~ s/\"/\\\\\"/g;
667 print \"\\\"$result\\\"\\n\";
668 ' \"$1\" 2>/dev/null"
669 "Perl script to produce output suitable for use with `file-truename'
670 on the remote file system.
671 Escape sequence %s is replaced with name of Perl binary.
672 This string is passed to `format', so percent characters need to be doubled.")
674 (defconst tramp-perl-file-name-all-completions
675 "%s -e '
676 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
677 @files = readdir(d); closedir(d);
678 foreach $f (@files) {
679 if (-d \"$ARGV[0]/$f\") {
680 print \"$f/\\n\";
682 else {
683 print \"$f\\n\";
686 print \"ok\\n\"
687 ' \"$1\" 2>/dev/null"
688 "Perl script to produce output suitable for use with
689 `file-name-all-completions' on the remote file system. Escape
690 sequence %s is replaced with name of Perl binary. This string is
691 passed to `format', so percent characters need to be doubled.")
693 ;; Perl script to implement `file-attributes' in a Lisp `read'able
694 ;; output. If you are hacking on this, note that you get *no* output
695 ;; unless this spits out a complete line, including the '\n' at the
696 ;; end.
697 ;; The device number is returned as "-1", because there will be a virtual
698 ;; device number set in `tramp-sh-handle-file-attributes'.
699 (defconst tramp-perl-file-attributes
700 "%s -e '
701 @stat = lstat($ARGV[0]);
702 if (!@stat) {
703 print \"nil\\n\";
704 exit 0;
706 if (($stat[2] & 0170000) == 0120000)
708 $type = readlink($ARGV[0]);
709 $type =~ s/\"/\\\\\"/g;
710 $type = \"\\\"$type\\\"\";
712 elsif (($stat[2] & 0170000) == 040000)
714 $type = \"t\";
716 else
718 $type = \"nil\"
720 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
721 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
722 printf(
723 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
724 $type,
725 $stat[3],
726 $uid,
727 $gid,
728 $stat[8] >> 16 & 0xffff,
729 $stat[8] & 0xffff,
730 $stat[9] >> 16 & 0xffff,
731 $stat[9] & 0xffff,
732 $stat[10] >> 16 & 0xffff,
733 $stat[10] & 0xffff,
734 $stat[7],
735 $stat[2],
736 $stat[1] >> 16 & 0xffff,
737 $stat[1] & 0xffff
738 );' \"$1\" \"$2\" 2>/dev/null"
739 "Perl script to produce output suitable for use with `file-attributes'
740 on the remote file system.
741 Escape sequence %s is replaced with name of Perl binary.
742 This string is passed to `format', so percent characters need to be doubled.")
744 (defconst tramp-perl-directory-files-and-attributes
745 "%s -e '
746 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
747 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
748 @list = readdir(DIR);
749 closedir(DIR);
750 $n = scalar(@list);
751 printf(\"(\\n\");
752 for($i = 0; $i < $n; $i++)
754 $filename = $list[$i];
755 @stat = lstat($filename);
756 if (($stat[2] & 0170000) == 0120000)
758 $type = readlink($filename);
759 $type =~ s/\"/\\\\\"/g;
760 $type = \"\\\"$type\\\"\";
762 elsif (($stat[2] & 0170000) == 040000)
764 $type = \"t\";
766 else
768 $type = \"nil\"
770 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
771 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
772 $filename =~ s/\"/\\\\\"/g;
773 printf(
774 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
775 $filename,
776 $type,
777 $stat[3],
778 $uid,
779 $gid,
780 $stat[8] >> 16 & 0xffff,
781 $stat[8] & 0xffff,
782 $stat[9] >> 16 & 0xffff,
783 $stat[9] & 0xffff,
784 $stat[10] >> 16 & 0xffff,
785 $stat[10] & 0xffff,
786 $stat[7],
787 $stat[2],
788 $stat[1] >> 16 & 0xffff,
789 $stat[1] & 0xffff,
790 $stat[0] >> 16 & 0xffff,
791 $stat[0] & 0xffff);
793 printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
794 "Perl script implementing `directory-files-attributes' as Lisp `read'able
795 output.
796 Escape sequence %s is replaced with name of Perl binary.
797 This string is passed to `format', so percent characters need to be doubled.")
799 ;; These two use base64 encoding.
800 (defconst tramp-perl-encode-with-module
801 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
802 "Perl program to use for encoding a file.
803 Escape sequence %s is replaced with name of Perl binary.
804 This string is passed to `format', so percent characters need to be doubled.
805 This implementation requires the MIME::Base64 Perl module to be installed
806 on the remote host.")
808 (defconst tramp-perl-decode-with-module
809 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
810 "Perl program to use for decoding a file.
811 Escape sequence %s is replaced with name of Perl binary.
812 This string is passed to `format', so percent characters need to be doubled.
813 This implementation requires the MIME::Base64 Perl module to be installed
814 on the remote host.")
816 (defconst tramp-perl-encode
817 "%s -e '
818 # This script contributed by Juanma Barranquero <lektu@terra.es>.
819 # Copyright (C) 2002-2016 Free Software Foundation, Inc.
820 use strict;
822 my %%trans = do {
823 my $i = 0;
824 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
825 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
827 my $data;
829 # We read in chunks of 54 bytes, to generate output lines
830 # of 72 chars (plus end of line)
831 while (read STDIN, $data, 54) {
832 my $pad = q();
834 # Only for the last chunk, and only if did not fill the last three-byte packet
835 if (eof) {
836 my $mod = length($data) %% 3;
837 $pad = q(=) x (3 - $mod) if $mod;
840 # Not the fastest method, but it is simple: unpack to binary string, split
841 # by groups of 6 bits and convert back from binary to byte; then map into
842 # the translation table
843 print
844 join q(),
845 map($trans{$_},
846 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
847 $pad,
848 qq(\\n);
849 }' 2>/dev/null"
850 "Perl program to use for encoding a file.
851 Escape sequence %s is replaced with name of Perl binary.
852 This string is passed to `format', so percent characters need to be doubled.")
854 (defconst tramp-perl-decode
855 "%s -e '
856 # This script contributed by Juanma Barranquero <lektu@terra.es>.
857 # Copyright (C) 2002-2016 Free Software Foundation, Inc.
858 use strict;
860 my %%trans = do {
861 my $i = 0;
862 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
863 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
866 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
868 binmode(\\*STDOUT);
870 # We are going to accumulate into $pending to accept any line length
871 # (we do not check they are <= 76 chars as the RFC says)
872 my $pending = q();
874 while (my $data = <STDIN>) {
875 chomp $data;
877 # If we find one or two =, we have reached the end and
878 # any following data is to be discarded
879 my $finished = $data =~ s/(==?).*/$1/;
880 $pending .= $data;
882 my $len = length($pending);
883 my $chunk = substr($pending, 0, $len & ~3);
884 $pending = substr($pending, $len & ~3 + 1);
886 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
887 # split in 8-bit chunks and convert back to char.
888 print join q(),
889 map $bytes{$_},
890 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
892 last if $finished;
893 }' 2>/dev/null"
894 "Perl program to use for decoding a file.
895 Escape sequence %s is replaced with name of Perl binary.
896 This string is passed to `format', so percent characters need to be doubled.")
898 (defconst tramp-perl-pack
899 "%s -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
900 "Perl program to use for encoding a file.
901 Escape sequence %s is replaced with name of Perl binary.")
903 (defconst tramp-perl-unpack
904 "%s -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"
905 "Perl program to use for decoding a file.
906 Escape sequence %s is replaced with name of Perl binary.")
908 (defconst tramp-awk-encode
909 "od -v -t x1 -A n | busybox awk '\\
910 BEGIN {
911 b64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"
912 b16 = \"0123456789abcdef\"
915 for (c=1; c<=length($0); c++) {
916 d=index(b16, substr($0,c,1))
917 if (d--) {
918 for (b=1; b<=4; b++) {
919 o=o*2+int(d/8); d=(d*2)%%16
920 if (++obc==6) {
921 printf substr(b64,o+1,1)
922 if (++rc>75) { printf \"\\n\"; rc=0 }
923 obc=0; o=0
929 END {
930 if (obc) {
931 tail=(obc==2) ? \"==\\n\" : \"=\\n\"
932 while (obc++<6) { o=o*2 }
933 printf \"%%c\", substr(b64,o+1,1)
934 } else {
935 tail=\"\\n\"
937 printf tail
939 "Awk program to use for encoding a file.
940 This string is passed to `format', so percent characters need to be doubled.")
942 (defconst tramp-awk-decode
943 "busybox awk '\\
944 BEGIN {
945 b64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"
948 for (i=1; i<=length($0); i++) {
949 c=index(b64, substr($0,i,1))
950 if(c--) {
951 for(b=0; b<6; b++) {
952 o=o*2+int(c/32); c=(c*2)%%64
953 if(++obc==8) {
954 if (o) {
955 printf \"%%c\", o
956 } else {
957 system(\"dd if=/dev/zero bs=1 count=1 2>/dev/null\")
959 obc=0; o=0
965 "Awk program to use for decoding a file.
966 This string is passed to `format', so percent characters need to be doubled.")
968 (defconst tramp-awk-coding-test
969 "test -c /dev/zero && \
970 od -v -t x1 -A n </dev/null && \
971 busybox awk '{}' </dev/null"
972 "Test command for checking `tramp-awk-encode' and `tramp-awk-decode'.")
974 (defconst tramp-stat-marker "/////"
975 "Marker in stat commands for file attributes.")
977 (defconst tramp-stat-quoted-marker "\\/\\/\\/\\/\\/"
978 "Quoted marker in stat commands for file attributes.")
980 (defconst tramp-vc-registered-read-file-names
981 "echo \"(\"
982 while read file; do
983 if %s \"$file\"; then
984 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
985 else
986 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
988 if %s \"$file\"; then
989 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
990 else
991 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
993 done
994 echo \")\""
995 "Script to check existence of VC related files.
996 It must be send formatted with two strings; the tests for file
997 existence, and file readability. Input shall be read via
998 here-document, otherwise the command could exceed maximum length
999 of command line.")
1001 ;; New handlers should be added here.
1002 (defconst tramp-sh-file-name-handler-alist
1003 '(;; `access-file' performed by default handler.
1004 (add-name-to-file . tramp-sh-handle-add-name-to-file)
1005 ;; `byte-compiler-base-file-name' performed by default handler.
1006 (copy-directory . tramp-sh-handle-copy-directory)
1007 (copy-file . tramp-sh-handle-copy-file)
1008 (delete-directory . tramp-sh-handle-delete-directory)
1009 (delete-file . tramp-sh-handle-delete-file)
1010 ;; `diff-latest-backup-file' performed by default handler.
1011 (directory-file-name . tramp-handle-directory-file-name)
1012 (directory-files . tramp-handle-directory-files)
1013 (directory-files-and-attributes
1014 . tramp-sh-handle-directory-files-and-attributes)
1015 (dired-compress-file . tramp-sh-handle-dired-compress-file)
1016 (dired-uncache . tramp-handle-dired-uncache)
1017 (expand-file-name . tramp-sh-handle-expand-file-name)
1018 (file-accessible-directory-p . tramp-handle-file-accessible-directory-p)
1019 (file-acl . tramp-sh-handle-file-acl)
1020 (file-attributes . tramp-sh-handle-file-attributes)
1021 (file-directory-p . tramp-sh-handle-file-directory-p)
1022 (file-equal-p . tramp-handle-file-equal-p)
1023 (file-executable-p . tramp-sh-handle-file-executable-p)
1024 (file-exists-p . tramp-sh-handle-file-exists-p)
1025 (file-in-directory-p . tramp-handle-file-in-directory-p)
1026 (file-local-copy . tramp-sh-handle-file-local-copy)
1027 (file-modes . tramp-handle-file-modes)
1028 (file-name-all-completions . tramp-sh-handle-file-name-all-completions)
1029 (file-name-as-directory . tramp-handle-file-name-as-directory)
1030 (file-name-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-already-exists
1964 "add-name-to-file: file %s already exists" newname))
1965 (when ok-if-already-exists (setq ln (concat ln " -f")))
1966 (tramp-flush-file-property v2 (file-name-directory v2-localname))
1967 (tramp-flush-file-property v2 v2-localname)
1968 (tramp-barf-unless-okay
1970 (format "%s %s %s" ln
1971 (tramp-shell-quote-argument v1-localname)
1972 (tramp-shell-quote-argument v2-localname))
1973 "error with add-name-to-file, see buffer `%s' for details"
1974 (buffer-name))))))
1976 (defun tramp-sh-handle-copy-file
1977 (filename newname &optional ok-if-already-exists keep-date
1978 preserve-uid-gid preserve-extended-attributes)
1979 "Like `copy-file' for Tramp files."
1980 (setq filename (expand-file-name filename))
1981 (setq newname (expand-file-name newname))
1982 (cond
1983 ;; At least one file a Tramp file?
1984 ((or (tramp-tramp-file-p filename)
1985 (tramp-tramp-file-p newname))
1986 (tramp-do-copy-or-rename-file
1987 'copy filename newname ok-if-already-exists keep-date
1988 preserve-uid-gid preserve-extended-attributes))
1989 ;; Compat section. PRESERVE-EXTENDED-ATTRIBUTES has been
1990 ;; introduced with Emacs 24.1 (as PRESERVE-SELINUX-CONTEXT), and
1991 ;; renamed in Emacs 24.3.
1992 (preserve-extended-attributes
1993 (tramp-run-real-handler
1994 'copy-file
1995 (list filename newname ok-if-already-exists keep-date
1996 preserve-uid-gid preserve-extended-attributes)))
1998 (tramp-run-real-handler
1999 'copy-file
2000 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))))
2002 (defun tramp-sh-handle-copy-directory
2003 (dirname newname &optional keep-date parents copy-contents)
2004 "Like `copy-directory' for Tramp files."
2005 (let ((t1 (tramp-tramp-file-p dirname))
2006 (t2 (tramp-tramp-file-p newname)))
2007 (with-parsed-tramp-file-name (if t1 dirname newname) nil
2008 (if (and (not copy-contents)
2009 (tramp-get-method-parameter v 'tramp-copy-recursive)
2010 ;; When DIRNAME and NEWNAME are remote, they must have
2011 ;; the same method.
2012 (or (null t1) (null t2)
2013 (string-equal
2014 (tramp-file-name-method (tramp-dissect-file-name dirname))
2015 (tramp-file-name-method
2016 (tramp-dissect-file-name newname)))))
2017 ;; scp or rsync DTRT.
2018 (progn
2019 (setq dirname (directory-file-name (expand-file-name dirname))
2020 newname (directory-file-name (expand-file-name newname)))
2021 (if (and (file-directory-p newname)
2022 (not (string-equal (file-name-nondirectory dirname)
2023 (file-name-nondirectory newname))))
2024 (setq newname
2025 (expand-file-name
2026 (file-name-nondirectory dirname) newname)))
2027 (if (not (file-directory-p (file-name-directory newname)))
2028 (make-directory (file-name-directory newname) parents))
2029 (tramp-do-copy-or-rename-file-out-of-band
2030 'copy dirname newname keep-date))
2031 ;; We must do it file-wise.
2032 (tramp-run-real-handler
2033 'copy-directory
2034 (if copy-contents
2035 (list dirname newname keep-date parents copy-contents)
2036 (list dirname newname keep-date parents))))
2038 ;; When newname did exist, we have wrong cached values.
2039 (when t2
2040 (with-parsed-tramp-file-name newname nil
2041 (tramp-flush-file-property v (file-name-directory localname))
2042 (tramp-flush-file-property v localname))))))
2044 (defun tramp-sh-handle-rename-file
2045 (filename newname &optional ok-if-already-exists)
2046 "Like `rename-file' for Tramp files."
2047 ;; Check if both files are local -- invoke normal rename-file.
2048 ;; Otherwise, use Tramp from local system.
2049 (setq filename (expand-file-name filename))
2050 (setq newname (expand-file-name newname))
2051 ;; At least one file a Tramp file?
2052 (if (or (tramp-tramp-file-p filename)
2053 (tramp-tramp-file-p newname))
2054 (tramp-do-copy-or-rename-file
2055 'rename filename newname ok-if-already-exists
2056 'keep-time 'preserve-uid-gid)
2057 (tramp-run-real-handler
2058 'rename-file (list filename newname ok-if-already-exists))))
2060 (defun tramp-do-copy-or-rename-file
2061 (op filename newname &optional ok-if-already-exists keep-date
2062 preserve-uid-gid preserve-extended-attributes)
2063 "Copy or rename a remote file.
2064 OP must be `copy' or `rename' and indicates the operation to perform.
2065 FILENAME specifies the file to copy or rename, NEWNAME is the name of
2066 the new file (for copy) or the new name of the file (for rename).
2067 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
2068 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2069 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2070 the uid and gid if both files are on the same host.
2071 PRESERVE-EXTENDED-ATTRIBUTES activates selinux and acl commands.
2073 This function is invoked by `tramp-sh-handle-copy-file' and
2074 `tramp-sh-handle-rename-file'. It is an error if OP is neither
2075 of `copy' and `rename'. FILENAME and NEWNAME must be absolute
2076 file names."
2077 (unless (memq op '(copy rename))
2078 (error "Unknown operation `%s', must be `copy' or `rename'" op))
2079 (let ((t1 (tramp-tramp-file-p filename))
2080 (t2 (tramp-tramp-file-p newname))
2081 (length (tramp-compat-file-attribute-size
2082 (file-attributes (file-truename filename))))
2083 (attributes (and preserve-extended-attributes
2084 (apply 'file-extended-attributes (list filename)))))
2086 (with-parsed-tramp-file-name (if t1 filename newname) nil
2087 (when (and (not ok-if-already-exists) (file-exists-p newname))
2088 (tramp-error
2089 v 'file-already-exists "File %s already exists" newname))
2091 (with-tramp-progress-reporter
2092 v 0 (format "%s %s to %s"
2093 (if (eq op 'copy) "Copying" "Renaming")
2094 filename newname)
2096 (cond
2097 ;; Both are Tramp files.
2098 ((and t1 t2)
2099 (with-parsed-tramp-file-name filename v1
2100 (with-parsed-tramp-file-name newname v2
2101 (cond
2102 ;; Shortcut: if method, host, user are the same for
2103 ;; both files, we invoke `cp' or `mv' on the remote
2104 ;; host directly.
2105 ((tramp-equal-remote filename newname)
2106 (tramp-do-copy-or-rename-file-directly
2107 op filename newname
2108 ok-if-already-exists keep-date preserve-uid-gid))
2110 ;; Try out-of-band operation.
2111 ((and
2112 (tramp-method-out-of-band-p v1 length)
2113 (tramp-method-out-of-band-p v2 length))
2114 (tramp-do-copy-or-rename-file-out-of-band
2115 op filename newname keep-date))
2117 ;; No shortcut was possible. So we copy the file
2118 ;; first. If the operation was `rename', we go back
2119 ;; and delete the original file (if the copy was
2120 ;; successful). The approach is simple-minded: we
2121 ;; create a new buffer, insert the contents of the
2122 ;; source file into it, then write out the buffer to
2123 ;; the target file. The advantage is that it doesn't
2124 ;; matter which file name handlers are used for the
2125 ;; source and target file.
2127 (tramp-do-copy-or-rename-file-via-buffer
2128 op filename newname keep-date))))))
2130 ;; One file is a Tramp file, the other one is local.
2131 ((or t1 t2)
2132 (cond
2133 ;; Fast track on local machine.
2134 ((tramp-local-host-p v)
2135 (tramp-do-copy-or-rename-file-directly
2136 op filename newname
2137 ok-if-already-exists keep-date preserve-uid-gid))
2139 ;; If the Tramp file has an out-of-band method, the
2140 ;; corresponding copy-program can be invoked.
2141 ((tramp-method-out-of-band-p v length)
2142 (tramp-do-copy-or-rename-file-out-of-band
2143 op filename newname keep-date))
2145 ;; Use the inline method via a Tramp buffer.
2146 (t (tramp-do-copy-or-rename-file-via-buffer
2147 op filename newname keep-date))))
2150 ;; One of them must be a Tramp file.
2151 (error "Tramp implementation says this cannot happen")))
2153 ;; Handle `preserve-extended-attributes'. We ignore possible
2154 ;; errors, because ACL strings could be incompatible.
2155 (when attributes
2156 (ignore-errors
2157 (apply 'set-file-extended-attributes (list newname attributes))))
2159 ;; In case of `rename', we must flush the cache of the source file.
2160 (when (and t1 (eq op 'rename))
2161 (with-parsed-tramp-file-name filename v1
2162 (tramp-flush-file-property v1 (file-name-directory v1-localname))
2163 (tramp-flush-file-property v1 v1-localname)))
2165 ;; When newname did exist, we have wrong cached values.
2166 (when t2
2167 (with-parsed-tramp-file-name newname v2
2168 (tramp-flush-file-property v2 (file-name-directory v2-localname))
2169 (tramp-flush-file-property v2 v2-localname)))))))
2171 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
2172 "Use an Emacs buffer to copy or rename a file.
2173 First arg OP is either `copy' or `rename' and indicates the operation.
2174 FILENAME is the source file, NEWNAME the target file.
2175 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
2176 ;; We must disable multibyte, because binary data shall not be
2177 ;; converted. We don't want the target file to be compressed, so we
2178 ;; let-bind `jka-compr-inhibit' to t. `epa-file-handler' shall not
2179 ;; be called either. We remove `tramp-file-name-handler' from
2180 ;; `inhibit-file-name-handlers'; otherwise the file name handler for
2181 ;; `insert-file-contents' might be deactivated in some corner cases.
2182 (let ((coding-system-for-read 'binary)
2183 (coding-system-for-write 'binary)
2184 (jka-compr-inhibit t)
2185 (inhibit-file-name-operation 'write-region)
2186 (inhibit-file-name-handlers
2187 (cons 'epa-file-handler
2188 (remq 'tramp-file-name-handler inhibit-file-name-handlers))))
2189 (with-temp-file newname
2190 (set-buffer-multibyte nil)
2191 (insert-file-contents-literally filename)))
2192 ;; KEEP-DATE handling.
2193 (when keep-date
2194 (set-file-times
2195 newname
2196 (tramp-compat-file-attribute-modification-time
2197 (file-attributes filename))))
2198 ;; Set the mode.
2199 (set-file-modes newname (tramp-default-file-modes filename))
2200 ;; If the operation was `rename', delete the original file.
2201 (unless (eq op 'copy) (delete-file filename)))
2203 (defun tramp-do-copy-or-rename-file-directly
2204 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
2205 "Invokes `cp' or `mv' on the remote system.
2206 OP must be one of `copy' or `rename', indicating `cp' or `mv',
2207 respectively. FILENAME specifies the file to copy or rename,
2208 NEWNAME is the name of the new file (for copy) or the new name of
2209 the file (for rename). Both files must reside on the same host.
2210 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2211 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2212 the uid and gid from FILENAME."
2213 (let ((t1 (tramp-tramp-file-p filename))
2214 (t2 (tramp-tramp-file-p newname))
2215 (file-times (tramp-compat-file-attribute-modification-time
2216 (file-attributes filename)))
2217 (file-modes (tramp-default-file-modes filename)))
2218 (with-parsed-tramp-file-name (if t1 filename newname) nil
2219 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
2220 ((eq op 'copy) "cp -f")
2221 ((eq op 'rename) "mv -f")
2222 (t (tramp-error
2223 v 'file-error
2224 "Unknown operation `%s', must be `copy' or `rename'"
2225 op))))
2226 (localname1
2227 (if t1
2228 (file-remote-p filename 'localname)
2229 filename))
2230 (localname2
2231 (if t2
2232 (file-remote-p newname 'localname)
2233 newname))
2234 (prefix (file-remote-p (if t1 filename newname)))
2235 cmd-result)
2237 (cond
2238 ;; Both files are on a remote host, with same user.
2239 ((and t1 t2)
2240 (setq cmd-result
2241 (tramp-send-command-and-check
2242 v (format "%s %s %s" cmd
2243 (tramp-shell-quote-argument localname1)
2244 (tramp-shell-quote-argument localname2))))
2245 (with-current-buffer (tramp-get-buffer v)
2246 (goto-char (point-min))
2247 (unless
2249 (and keep-date
2250 ;; Mask cp -f error.
2251 (re-search-forward
2252 tramp-operation-not-permitted-regexp nil t))
2253 cmd-result)
2254 (tramp-error-with-buffer
2255 nil v 'file-error
2256 "Copying directly failed, see buffer `%s' for details."
2257 (buffer-name)))))
2259 ;; We are on the local host.
2260 ((or t1 t2)
2261 (cond
2262 ;; We can do it directly.
2263 ((let (file-name-handler-alist)
2264 (and (file-readable-p localname1)
2265 ;; No sticky bit when renaming.
2266 (or (eq op 'copy)
2267 (zerop
2268 (logand
2269 (file-modes (file-name-directory localname1))
2270 (string-to-number "1000" 8))))
2271 (file-writable-p (file-name-directory localname2))
2272 (or (file-directory-p localname2)
2273 (file-writable-p localname2))))
2274 (if (eq op 'copy)
2275 (copy-file
2276 localname1 localname2 ok-if-already-exists
2277 keep-date preserve-uid-gid)
2278 (tramp-run-real-handler
2279 'rename-file (list localname1 localname2 ok-if-already-exists))))
2281 ;; We can do it directly with `tramp-send-command'
2282 ((and (file-readable-p (concat prefix localname1))
2283 (file-writable-p
2284 (file-name-directory (concat prefix localname2)))
2285 (or (file-directory-p (concat prefix localname2))
2286 (file-writable-p (concat prefix localname2))))
2287 (tramp-do-copy-or-rename-file-directly
2288 op (concat prefix localname1) (concat prefix localname2)
2289 ok-if-already-exists keep-date t)
2290 ;; We must change the ownership to the local user.
2291 (tramp-set-file-uid-gid
2292 (concat prefix localname2)
2293 (tramp-get-local-uid 'integer)
2294 (tramp-get-local-gid 'integer)))
2296 ;; We need a temporary file in between.
2298 ;; Create the temporary file.
2299 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
2300 (unwind-protect
2301 (progn
2302 (cond
2304 (tramp-barf-unless-okay
2305 v (format
2306 "%s %s %s" cmd
2307 (tramp-shell-quote-argument localname1)
2308 (tramp-shell-quote-argument tmpfile))
2309 "Copying directly failed, see buffer `%s' for details."
2310 (tramp-get-buffer v))
2311 ;; We must change the ownership as remote user.
2312 ;; Since this does not work reliable, we also
2313 ;; give read permissions.
2314 (set-file-modes
2315 (concat prefix tmpfile) (string-to-number "0777" 8))
2316 (tramp-set-file-uid-gid
2317 (concat prefix tmpfile)
2318 (tramp-get-local-uid 'integer)
2319 (tramp-get-local-gid 'integer)))
2321 (if (eq op 'copy)
2322 (copy-file
2323 localname1 tmpfile t
2324 keep-date preserve-uid-gid)
2325 (tramp-run-real-handler
2326 'rename-file
2327 (list localname1 tmpfile t)))
2328 ;; We must change the ownership as local user.
2329 ;; Since this does not work reliable, we also
2330 ;; give read permissions.
2331 (set-file-modes tmpfile (string-to-number "0777" 8))
2332 (tramp-set-file-uid-gid
2333 tmpfile
2334 (tramp-get-remote-uid v 'integer)
2335 (tramp-get-remote-gid v 'integer))))
2337 ;; Move the temporary file to its destination.
2338 (cond
2340 (tramp-barf-unless-okay
2341 v (format
2342 "cp -f -p %s %s"
2343 (tramp-shell-quote-argument tmpfile)
2344 (tramp-shell-quote-argument localname2))
2345 "Copying directly failed, see buffer `%s' for details."
2346 (tramp-get-buffer v)))
2348 (tramp-run-real-handler
2349 'rename-file
2350 (list tmpfile localname2 ok-if-already-exists)))))
2352 ;; Save exit.
2353 (ignore-errors (delete-file tmpfile)))))))))
2355 ;; Set the time and mode. Mask possible errors.
2356 (ignore-errors
2357 (when keep-date
2358 (set-file-times newname file-times)
2359 (set-file-modes newname file-modes))))))
2361 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
2362 "Invoke `scp' program to copy.
2363 The method used must be an out-of-band method."
2364 (let* ((t1 (tramp-tramp-file-p filename))
2365 (t2 (tramp-tramp-file-p newname))
2366 (orig-vec (tramp-dissect-file-name (if t1 filename newname)))
2367 copy-program copy-args copy-env copy-keep-date port listener spec
2368 options source target remote-copy-program remote-copy-args)
2370 (with-parsed-tramp-file-name (if t1 filename newname) nil
2371 (if (and t1 t2)
2373 ;; Both are Tramp files. We shall optimize it when the
2374 ;; methods for FILENAME and NEWNAME are the same.
2375 (let* ((dir-flag (file-directory-p filename))
2376 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
2377 (if dir-flag
2378 (setq tmpfile
2379 (expand-file-name
2380 (file-name-nondirectory newname) tmpfile)))
2381 (unwind-protect
2382 (progn
2383 (tramp-do-copy-or-rename-file-out-of-band
2384 op filename tmpfile keep-date)
2385 (tramp-do-copy-or-rename-file-out-of-band
2386 'rename tmpfile newname keep-date))
2387 ;; Save exit.
2388 (ignore-errors
2389 (if dir-flag
2390 (delete-directory
2391 (expand-file-name ".." tmpfile) 'recursive)
2392 (delete-file tmpfile)))))
2394 ;; Set variables for computing the prompt for reading
2395 ;; password.
2396 (setq tramp-current-method (tramp-file-name-method v)
2397 tramp-current-user (or (tramp-file-name-user v)
2398 (tramp-get-connection-property
2399 v "login-as" nil))
2400 tramp-current-host (tramp-file-name-real-host v))
2402 ;; Expand hops. Might be necessary for gateway methods.
2403 (setq v (car (tramp-compute-multi-hops v)))
2404 (aset v 3 localname)
2406 ;; Check which ones of source and target are Tramp files.
2407 (setq source (funcall
2408 (if (and (file-directory-p filename)
2409 (not (file-exists-p newname)))
2410 'file-name-as-directory
2411 'identity)
2412 (if t1
2413 (tramp-make-copy-program-file-name v)
2414 (shell-quote-argument filename)))
2415 target (if t2
2416 (tramp-make-copy-program-file-name v)
2417 (shell-quote-argument newname)))
2419 ;; Check for host and port number. We cannot use
2420 ;; `tramp-file-name-port', because this returns also
2421 ;; `tramp-default-port', which might clash with settings in
2422 ;; "~/.ssh/config".
2423 (setq host (tramp-file-name-host v)
2424 port "")
2425 (when (string-match tramp-host-with-port-regexp host)
2426 (setq port (string-to-number (match-string 2 host))
2427 host (string-to-number (match-string 1 host))))
2429 ;; Check for user. There might be an interactive setting.
2430 (setq user (or (tramp-file-name-user v)
2431 (tramp-get-connection-property v "login-as" nil)))
2433 ;; Check for listener port.
2434 (when (tramp-get-method-parameter v 'tramp-remote-copy-args)
2435 (setq listener (number-to-string (+ 50000 (random 10000))))
2436 (while
2437 (zerop (tramp-call-process v "nc" nil nil nil "-z" host listener))
2438 (setq listener (number-to-string (+ 50000 (random 10000))))))
2440 ;; Compose copy command.
2441 (setq host (or host "")
2442 user (or user "")
2443 port (or port "")
2444 spec (format-spec-make
2445 ?t (tramp-get-connection-property
2446 (tramp-get-connection-process v) "temp-file" ""))
2447 options (format-spec (tramp-ssh-controlmaster-options v) spec)
2448 spec (format-spec-make
2449 ?h host ?u user ?p port ?r listener ?c options
2450 ?k (if keep-date " " ""))
2451 copy-program (tramp-get-method-parameter v 'tramp-copy-program)
2452 copy-keep-date (tramp-get-method-parameter
2453 v 'tramp-copy-keep-date)
2455 copy-args
2456 (delete
2457 ;; " " has either been a replacement of "%k" (when
2458 ;; keep-date argument is non-nil), or a replacement
2459 ;; for the whole keep-date sublist.
2461 (dolist
2462 (x (tramp-get-method-parameter v 'tramp-copy-args) copy-args)
2463 (setq copy-args
2464 (append
2465 copy-args
2466 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2467 (if (member "" y) '(" ") y))))))
2469 copy-env
2470 (delq
2472 (mapcar
2473 (lambda (x)
2474 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
2475 (unless (member "" x) (mapconcat 'identity x " ")))
2476 (tramp-get-method-parameter v 'tramp-copy-env)))
2478 remote-copy-program
2479 (tramp-get-method-parameter v 'tramp-remote-copy-program))
2481 (dolist (x (tramp-get-method-parameter v 'tramp-remote-copy-args))
2482 (setq remote-copy-args
2483 (append
2484 remote-copy-args
2485 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2486 (if (member "" y) '(" ") y)))))
2488 ;; Check for local copy program.
2489 (unless (executable-find copy-program)
2490 (tramp-error
2491 v 'file-error "Cannot find local copy program: %s" copy-program))
2493 ;; Install listener on the remote side. The prompt must be
2494 ;; consumed later on, when the process does not listen anymore.
2495 (when remote-copy-program
2496 (unless (with-tramp-connection-property
2497 v (concat "remote-copy-program-" remote-copy-program)
2498 (tramp-find-executable
2499 v remote-copy-program (tramp-get-remote-path v)))
2500 (tramp-error
2501 v 'file-error
2502 "Cannot find remote listener: %s" remote-copy-program))
2503 (setq remote-copy-program
2504 (mapconcat
2505 'identity
2506 (append
2507 (list remote-copy-program) remote-copy-args
2508 (list (if t1 (concat "<" source) (concat ">" target)) "&"))
2509 " "))
2510 (tramp-send-command v remote-copy-program)
2511 (with-timeout
2512 (60 (tramp-error
2513 v 'file-error
2514 "Listener process not running on remote host: `%s'"
2515 remote-copy-program))
2516 (tramp-send-command v (format "netstat -l | grep -q :%s" listener))
2517 (while (not (tramp-send-command-and-check v nil))
2518 (tramp-send-command
2519 v (format "netstat -l | grep -q :%s" listener)))))
2521 (with-temp-buffer
2522 (unwind-protect
2523 ;; The default directory must be remote.
2524 (let ((default-directory
2525 (file-name-directory (if t1 filename newname)))
2526 (process-environment (copy-sequence process-environment)))
2527 ;; Set the transfer process properties.
2528 (tramp-set-connection-property
2529 v "process-name" (buffer-name (current-buffer)))
2530 (tramp-set-connection-property
2531 v "process-buffer" (current-buffer))
2532 (while copy-env
2533 (tramp-message
2534 orig-vec 6 "%s=\"%s\"" (car copy-env) (cadr copy-env))
2535 (setenv (pop copy-env) (pop copy-env)))
2536 (setq
2537 copy-args
2538 (append
2539 copy-args
2540 (if remote-copy-program
2541 (list (if t1 (concat ">" target) (concat "<" source)))
2542 (list source target))))
2544 ;; Use an asynchronous process. By this, password can
2545 ;; be handled. We don't set a timeout, because the
2546 ;; copying of large files can last longer than 60 secs.
2547 (let* ((command
2548 (mapconcat
2549 'identity (append (list copy-program) copy-args)
2550 " "))
2551 (p (let ((default-directory
2552 (tramp-compat-temporary-file-directory)))
2553 (start-process-shell-command
2554 (tramp-get-connection-name v)
2555 (tramp-get-connection-buffer v)
2556 command))))
2557 (tramp-message orig-vec 6 "%s" command)
2558 (tramp-set-connection-property p "vector" orig-vec)
2559 (set-process-query-on-exit-flag p nil)
2561 ;; We must adapt `tramp-local-end-of-line' for
2562 ;; sending the password.
2563 (let ((tramp-local-end-of-line tramp-rsh-end-of-line))
2564 (tramp-process-actions
2565 p v nil tramp-actions-copy-out-of-band))))
2567 ;; Reset the transfer process properties.
2568 (tramp-set-connection-property v "process-name" nil)
2569 (tramp-set-connection-property v "process-buffer" nil)
2570 ;; Clear the remote prompt.
2571 (when (and remote-copy-program
2572 (not (tramp-send-command-and-check v nil)))
2573 ;; Houston, we have a problem! Likely, the listener is
2574 ;; still running, so let's clear everything (but the
2575 ;; cached password).
2576 (tramp-cleanup-connection v 'keep-debug 'keep-password))))
2578 ;; Handle KEEP-DATE argument.
2579 (when (and keep-date (not copy-keep-date))
2580 (set-file-times
2581 newname
2582 (tramp-compat-file-attribute-modification-time
2583 (file-attributes filename))))
2585 ;; Set the mode.
2586 (unless (and keep-date copy-keep-date)
2587 (ignore-errors
2588 (set-file-modes newname (tramp-default-file-modes filename)))))
2590 ;; If the operation was `rename', delete the original file.
2591 (unless (eq op 'copy)
2592 (if (file-regular-p filename)
2593 (delete-file filename)
2594 (delete-directory filename 'recursive))))))
2596 (defun tramp-sh-handle-make-directory (dir &optional parents)
2597 "Like `make-directory' for Tramp files."
2598 (setq dir (expand-file-name dir))
2599 (with-parsed-tramp-file-name dir nil
2600 (tramp-flush-directory-property v (file-name-directory localname))
2601 (save-excursion
2602 (tramp-barf-unless-okay
2603 v (format "%s %s"
2604 (if parents "mkdir -p" "mkdir")
2605 (tramp-shell-quote-argument localname))
2606 "Couldn't make directory %s" dir))))
2608 (defun tramp-sh-handle-delete-directory (directory &optional recursive)
2609 "Like `delete-directory' for Tramp files."
2610 (setq directory (expand-file-name directory))
2611 (with-parsed-tramp-file-name directory nil
2612 (tramp-flush-file-property v (file-name-directory localname))
2613 (tramp-flush-directory-property v localname)
2614 (tramp-barf-unless-okay
2615 v (format "cd / && %s %s"
2616 (if recursive "rm -rf" "rmdir")
2617 (tramp-shell-quote-argument localname))
2618 "Couldn't delete %s" directory)))
2620 (defun tramp-sh-handle-delete-file (filename &optional trash)
2621 "Like `delete-file' for Tramp files."
2622 (setq filename (expand-file-name filename))
2623 (with-parsed-tramp-file-name filename nil
2624 (tramp-flush-file-property v (file-name-directory localname))
2625 (tramp-flush-file-property v localname)
2626 (tramp-barf-unless-okay
2627 v (format "%s %s"
2628 (or (and trash (tramp-get-remote-trash v)) "rm -f")
2629 (tramp-shell-quote-argument localname))
2630 "Couldn't delete %s" filename)))
2632 ;; Dired.
2634 (defvar dired-compress-file-suffixes)
2635 (declare-function dired-remove-file "dired-aux")
2637 (defun tramp-sh-handle-dired-compress-file (file)
2638 "Like `dired-compress-file' for Tramp files."
2639 ;; Code stolen mainly from dired-aux.el.
2640 (with-parsed-tramp-file-name file nil
2641 (tramp-flush-file-property v localname)
2642 (save-excursion
2643 (let ((suffixes dired-compress-file-suffixes)
2644 suffix)
2645 ;; See if any suffix rule matches this file name.
2646 (while suffixes
2647 (let (case-fold-search)
2648 (if (string-match (car (car suffixes)) localname)
2649 (setq suffix (car suffixes) suffixes nil))
2650 (setq suffixes (cdr suffixes))))
2652 (cond ((file-symlink-p file)
2653 nil)
2654 ((and suffix (nth 2 suffix))
2655 ;; We found an uncompression rule.
2656 (with-tramp-progress-reporter
2657 v 0 (format "Uncompressing %s" file)
2658 (when (tramp-send-command-and-check
2659 v (concat (nth 2 suffix) " "
2660 (tramp-shell-quote-argument localname)))
2661 (dired-remove-file file)
2662 (string-match (car suffix) file)
2663 (concat (substring file 0 (match-beginning 0))))))
2665 ;; We don't recognize the file as compressed, so compress it.
2666 ;; Try gzip.
2667 (with-tramp-progress-reporter v 0 (format "Compressing %s" file)
2668 (when (tramp-send-command-and-check
2669 v (concat "gzip -f "
2670 (tramp-shell-quote-argument localname)))
2671 (dired-remove-file file)
2672 (cond ((file-exists-p (concat file ".gz"))
2673 (concat file ".gz"))
2674 ((file-exists-p (concat file ".z"))
2675 (concat file ".z"))
2676 (t nil))))))))))
2678 (defun tramp-sh-handle-insert-directory
2679 (filename switches &optional wildcard full-directory-p)
2680 "Like `insert-directory' for Tramp files."
2681 (setq filename (expand-file-name filename))
2682 (unless switches (setq switches ""))
2683 (with-parsed-tramp-file-name filename nil
2684 (if (and (featurep 'ls-lisp)
2685 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
2686 (tramp-handle-insert-directory
2687 filename switches wildcard full-directory-p)
2688 (when (stringp switches)
2689 (setq switches (split-string switches)))
2690 (when (tramp-get-ls-command-with-quoting-style v)
2691 (setq switches (append switches '("--quoting-style=literal"))))
2692 (when (and (member "--dired" switches)
2693 (not (tramp-get-ls-command-with-dired v)))
2694 (setq switches (delete "--dired" switches)))
2695 (when wildcard
2696 (setq wildcard (tramp-run-real-handler
2697 'file-name-nondirectory (list localname)))
2698 (setq localname (tramp-run-real-handler
2699 'file-name-directory (list localname))))
2700 (unless (or full-directory-p (member "-d" switches))
2701 (setq switches (append switches '("-d"))))
2702 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
2703 (when wildcard
2704 (setq switches (concat switches " " wildcard)))
2705 (tramp-message
2706 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
2707 switches filename (if wildcard "yes" "no")
2708 (if full-directory-p "yes" "no"))
2709 ;; If `full-directory-p', we just say `ls -l FILENAME'.
2710 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
2711 (if full-directory-p
2712 (tramp-send-command
2714 (format "%s %s %s 2>/dev/null"
2715 (tramp-get-ls-command v)
2716 switches
2717 (if wildcard
2718 localname
2719 (tramp-shell-quote-argument (concat localname ".")))))
2720 (tramp-barf-unless-okay
2722 (format "cd %s" (tramp-shell-quote-argument
2723 (tramp-run-real-handler
2724 'file-name-directory (list localname))))
2725 "Couldn't `cd %s'"
2726 (tramp-shell-quote-argument
2727 (tramp-run-real-handler 'file-name-directory (list localname))))
2728 (tramp-send-command
2730 (format "%s %s %s 2>/dev/null"
2731 (tramp-get-ls-command v)
2732 switches
2733 (if (or wildcard
2734 (zerop (length
2735 (tramp-run-real-handler
2736 'file-name-nondirectory (list localname)))))
2738 (tramp-shell-quote-argument
2739 (tramp-run-real-handler
2740 'file-name-nondirectory (list localname)))))))
2742 (save-restriction
2743 (let ((beg (point)))
2744 (narrow-to-region (point) (point))
2745 ;; We cannot use `insert-buffer-substring' because the Tramp
2746 ;; buffer changes its contents before insertion due to calling
2747 ;; `expand-file-name' and alike.
2748 (insert
2749 (with-current-buffer (tramp-get-buffer v)
2750 (buffer-string)))
2752 ;; Check for "--dired" output.
2753 (forward-line -2)
2754 (when (looking-at "//SUBDIRED//")
2755 (forward-line -1))
2756 (when (looking-at "//DIRED//\\s-+")
2757 (let ((databeg (match-end 0))
2758 (end (point-at-eol)))
2759 ;; Now read the numeric positions of file names.
2760 (goto-char databeg)
2761 (while (< (point) end)
2762 (let ((start (+ beg (read (current-buffer))))
2763 (end (+ beg (read (current-buffer)))))
2764 (if (memq (char-after end) '(?\n ?\ ))
2765 ;; End is followed by \n or by " -> ".
2766 (put-text-property start end 'dired-filename t))))))
2767 ;; Remove trailing lines.
2768 (goto-char (point-at-bol))
2769 (while (looking-at "//")
2770 (forward-line 1)
2771 (delete-region (match-beginning 0) (point)))
2773 ;; Some busyboxes are reluctant to discard colors.
2774 (unless
2775 (string-match "color" (tramp-get-connection-property v "ls" ""))
2776 (goto-char beg)
2777 (while
2778 (re-search-forward tramp-display-escape-sequence-regexp nil t)
2779 (replace-match "")))
2781 ;; Decode the output, it could be multibyte.
2782 (decode-coding-region
2783 beg (point-max)
2784 (or file-name-coding-system default-file-name-coding-system))
2786 ;; The inserted file could be from somewhere else.
2787 (when (and (not wildcard) (not full-directory-p))
2788 (goto-char (point-max))
2789 (when (file-symlink-p filename)
2790 (goto-char (search-backward "->" beg 'noerror)))
2791 (search-backward
2792 (if (zerop (length (file-name-nondirectory filename)))
2794 (file-name-nondirectory filename))
2795 beg 'noerror)
2796 (replace-match (file-relative-name filename) t))
2798 (goto-char (point-max)))))))
2800 ;; Canonicalization of file names.
2802 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2803 "Like `expand-file-name' for Tramp files.
2804 If the localname part of the given file name starts with \"/../\" then
2805 the result will be a local, non-Tramp, file name."
2806 ;; If DIR is not given, use `default-directory' or "/".
2807 (setq dir (or dir default-directory "/"))
2808 ;; Unless NAME is absolute, concat DIR and NAME.
2809 (unless (file-name-absolute-p name)
2810 (setq name (concat (file-name-as-directory dir) name)))
2811 ;; If connection is not established yet, run the real handler.
2812 (if (not (tramp-connectable-p name))
2813 (tramp-run-real-handler 'expand-file-name (list name nil))
2814 ;; Dissect NAME.
2815 (with-parsed-tramp-file-name name nil
2816 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2817 (setq localname (concat "~/" localname)))
2818 ;; Tilde expansion if necessary. This needs a shell which
2819 ;; groks tilde expansion! The function `tramp-find-shell' is
2820 ;; supposed to find such a shell on the remote host. Please
2821 ;; tell me about it when this doesn't work on your system.
2822 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2823 (let ((uname (match-string 1 localname))
2824 (fname (match-string 2 localname)))
2825 ;; We cannot simply apply "~/", because under sudo "~/" is
2826 ;; expanded to the local user home directory but to the
2827 ;; root home directory. On the other hand, using always
2828 ;; the default user name for tilde expansion is not
2829 ;; appropriate either, because ssh and companions might
2830 ;; use a user name from the config file.
2831 (when (and (string-equal uname "~")
2832 (string-match "\\`su\\(do\\)?\\'" method))
2833 (setq uname (concat uname user)))
2834 (setq uname
2835 (with-tramp-connection-property v uname
2836 (tramp-send-command
2837 v (format "cd %s && pwd" (tramp-shell-quote-argument uname)))
2838 (with-current-buffer (tramp-get-buffer v)
2839 (goto-char (point-min))
2840 (buffer-substring (point) (point-at-eol)))))
2841 (setq localname (concat uname fname))))
2842 ;; There might be a double slash, for example when "~/"
2843 ;; expands to "/". Remove this.
2844 (while (string-match "//" localname)
2845 (setq localname (replace-match "/" t t localname)))
2846 ;; No tilde characters in file name, do normal
2847 ;; `expand-file-name' (this does "/./" and "/../").
2848 ;; `default-directory' is bound, because on Windows there would
2849 ;; be problems with UNC shares or Cygwin mounts.
2850 (let ((default-directory (tramp-compat-temporary-file-directory)))
2851 (tramp-make-tramp-file-name
2852 method user host
2853 (tramp-drop-volume-letter
2854 (tramp-run-real-handler
2855 'expand-file-name (list localname)))
2856 hop)))))
2858 ;;; Remote commands:
2860 (defun tramp-process-sentinel (proc event)
2861 "Flush file caches."
2862 (unless (tramp-compat-process-live-p proc)
2863 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2864 (when vec
2865 (tramp-message vec 5 "Sentinel called: `%S' `%s'" proc event)
2866 (tramp-flush-connection-property proc)
2867 (tramp-flush-directory-property vec "")))))
2869 ;; We use BUFFER also as connection buffer during setup. Because of
2870 ;; this, its original contents must be saved, and restored once
2871 ;; connection has been setup.
2872 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2873 "Like `start-file-process' for Tramp files."
2874 (with-parsed-tramp-file-name (expand-file-name default-directory) nil
2875 (let* ((buffer
2876 (if buffer
2877 (get-buffer-create buffer)
2878 ;; BUFFER can be nil. We use a temporary buffer.
2879 (generate-new-buffer tramp-temp-buffer-name)))
2880 ;; When PROGRAM matches "*sh", and the first arg is "-c",
2881 ;; it might be that the arguments exceed the command line
2882 ;; length. Therefore, we modify the command.
2883 (heredoc (and (stringp program)
2884 (string-match "sh$" program)
2885 (string-equal "-c" (car args))
2886 (= (length args) 2)))
2887 ;; When PROGRAM is nil, we just provide a tty.
2888 (args (if (not heredoc) args
2889 (let ((i 250))
2890 (while (and (< i (length (cadr args)))
2891 (string-match " " (cadr args) i))
2892 (setcdr
2893 args
2894 (list (replace-match " \\\\\n" nil nil (cadr args))))
2895 (setq i (+ i 250))))
2896 (cdr args)))
2897 ;; Use a human-friendly prompt, for example for `shell'.
2898 ;; We discard hops, if existing, that's why we cannot use
2899 ;; `file-remote-p'.
2900 (prompt (format "PS1=%s %s"
2901 (tramp-make-tramp-file-name
2902 (tramp-file-name-method v)
2903 (tramp-file-name-user v)
2904 (tramp-file-name-host v)
2905 (tramp-file-name-localname v))
2906 tramp-initial-end-of-output))
2907 ;; We use as environment the difference to toplevel
2908 ;; `process-environment'.
2909 env uenv
2910 (env (dolist (elt (cons prompt process-environment) env)
2911 (or (member elt (default-toplevel-value 'process-environment))
2912 (if (string-match "=" elt)
2913 (setq env (append env `(,elt)))
2914 (if (tramp-get-env-with-u-option v)
2915 (setq env (append `("-u" ,elt) env))
2916 (setq uenv (cons elt uenv)))))))
2917 (command
2918 (when (stringp program)
2919 (format "cd %s && %s exec %s env %s %s"
2920 (tramp-shell-quote-argument localname)
2921 (if uenv
2922 (format
2923 "unset %s &&"
2924 (mapconcat 'tramp-shell-quote-argument uenv " "))
2926 (if heredoc (format "<<'%s'" tramp-end-of-heredoc) "")
2927 (mapconcat 'tramp-shell-quote-argument env " ")
2928 (if heredoc
2929 (format "%s\n(\n%s\n) </dev/tty\n%s"
2930 program (car args) tramp-end-of-heredoc)
2931 (mapconcat 'tramp-shell-quote-argument
2932 (cons program args) " ")))))
2933 (tramp-process-connection-type
2934 (or (null program) tramp-process-connection-type))
2935 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2936 (name1 name)
2937 (i 0)
2938 ;; We do not want to raise an error when
2939 ;; `start-file-process' has been started several times in
2940 ;; `eshell' and friends.
2941 (tramp-current-connection nil))
2943 (while (get-process name1)
2944 ;; NAME must be unique as process name.
2945 (setq i (1+ i)
2946 name1 (format "%s<%d>" name i)))
2947 (setq name name1)
2948 ;; Set the new process properties.
2949 (tramp-set-connection-property v "process-name" name)
2950 (tramp-set-connection-property v "process-buffer" buffer)
2952 (with-current-buffer (tramp-get-connection-buffer v)
2953 (unwind-protect
2954 ;; We catch this event. Otherwise, `start-process' could
2955 ;; be called on the local host.
2956 (save-excursion
2957 (save-restriction
2958 ;; Activate narrowing in order to save BUFFER
2959 ;; contents. Clear also the modification time;
2960 ;; otherwise we might be interrupted by
2961 ;; `verify-visited-file-modtime'.
2962 (let ((buffer-undo-list t)
2963 (buffer-read-only nil)
2964 (mark (point-max)))
2965 (clear-visited-file-modtime)
2966 (narrow-to-region (point-max) (point-max))
2967 ;; We call `tramp-maybe-open-connection', in order
2968 ;; to cleanup the prompt afterwards.
2969 (catch 'suppress
2970 (tramp-maybe-open-connection v)
2971 (widen)
2972 (delete-region mark (point))
2973 (narrow-to-region (point-max) (point-max))
2974 ;; Now do it.
2975 (if command
2976 ;; Send the command.
2977 (tramp-send-command v command nil t) ; nooutput
2978 ;; Check, whether a pty is associated.
2979 (unless (process-get
2980 (tramp-get-connection-process v) 'remote-tty)
2981 (tramp-error
2982 v 'file-error
2983 "pty association is not supported for `%s'" name))))
2984 (let ((p (tramp-get-connection-process v)))
2985 ;; Set query flag and process marker for this
2986 ;; process. We ignore errors, because the process
2987 ;; could have finished already.
2988 (ignore-errors
2989 (set-process-query-on-exit-flag p t)
2990 (set-marker (process-mark p) (point)))
2991 ;; Return process.
2992 p))))
2994 ;; Save exit.
2995 (if (string-match tramp-temp-buffer-name (buffer-name))
2996 (ignore-errors
2997 (set-process-buffer (tramp-get-connection-process v) nil)
2998 (kill-buffer (current-buffer)))
2999 (set-buffer-modified-p bmp))
3000 (tramp-set-connection-property v "process-name" nil)
3001 (tramp-set-connection-property v "process-buffer" nil))))))
3003 (defun tramp-sh-handle-process-file
3004 (program &optional infile destination display &rest args)
3005 "Like `process-file' for Tramp files."
3006 ;; The implementation is not complete yet.
3007 (when (and (numberp destination) (zerop destination))
3008 (error "Implementation does not handle immediate return"))
3010 (with-parsed-tramp-file-name default-directory nil
3011 (let (command env uenv input tmpinput stderr tmpstderr outbuf ret)
3012 ;; Compute command.
3013 (setq command (mapconcat 'tramp-shell-quote-argument
3014 (cons program args) " "))
3015 ;; We use as environment the difference to toplevel `process-environment'.
3016 (dolist (elt process-environment)
3017 (or (member elt (default-toplevel-value 'process-environment))
3018 (if (string-match "=" elt)
3019 (setq env (append env `(,elt)))
3020 (if (tramp-get-env-with-u-option v)
3021 (setq env (append `("-u" ,elt) env))
3022 (setq uenv (cons elt uenv))))))
3023 (when env
3024 (setq command
3025 (format
3026 "env %s %s"
3027 (mapconcat 'tramp-shell-quote-argument env " ") command)))
3028 (when uenv
3029 (setq command
3030 (format
3031 "unset %s && %s"
3032 (mapconcat 'tramp-shell-quote-argument uenv " ") command)))
3033 ;; Determine input.
3034 (if (null infile)
3035 (setq input "/dev/null")
3036 (setq infile (expand-file-name infile))
3037 (if (tramp-equal-remote default-directory infile)
3038 ;; INFILE is on the same remote host.
3039 (setq input (with-parsed-tramp-file-name infile nil localname))
3040 ;; INFILE must be copied to remote host.
3041 (setq input (tramp-make-tramp-temp-file v)
3042 tmpinput (tramp-make-tramp-file-name method user host input))
3043 (copy-file infile tmpinput t)))
3044 (when input (setq command (format "%s <%s" command input)))
3046 ;; Determine output.
3047 (cond
3048 ;; Just a buffer.
3049 ((bufferp destination)
3050 (setq outbuf destination))
3051 ;; A buffer name.
3052 ((stringp destination)
3053 (setq outbuf (get-buffer-create destination)))
3054 ;; (REAL-DESTINATION ERROR-DESTINATION)
3055 ((consp destination)
3056 ;; output.
3057 (cond
3058 ((bufferp (car destination))
3059 (setq outbuf (car destination)))
3060 ((stringp (car destination))
3061 (setq outbuf (get-buffer-create (car destination))))
3062 ((car destination)
3063 (setq outbuf (current-buffer))))
3064 ;; stderr.
3065 (cond
3066 ((stringp (cadr destination))
3067 (setcar (cdr destination) (expand-file-name (cadr destination)))
3068 (if (tramp-equal-remote default-directory (cadr destination))
3069 ;; stderr is on the same remote host.
3070 (setq stderr (with-parsed-tramp-file-name
3071 (cadr destination) nil localname))
3072 ;; stderr must be copied to remote host. The temporary
3073 ;; file must be deleted after execution.
3074 (setq stderr (tramp-make-tramp-temp-file v)
3075 tmpstderr (tramp-make-tramp-file-name
3076 method user host stderr))))
3077 ;; stderr to be discarded.
3078 ((null (cadr destination))
3079 (setq stderr "/dev/null"))))
3080 ;; 't
3081 (destination
3082 (setq outbuf (current-buffer))))
3083 (when stderr (setq command (format "%s 2>%s" command stderr)))
3085 ;; Send the command. It might not return in time, so we protect
3086 ;; it. Call it in a subshell, in order to preserve working
3087 ;; directory.
3088 (condition-case nil
3089 (unwind-protect
3090 (setq ret
3091 (if (tramp-send-command-and-check
3092 v (format "cd %s && %s"
3093 (tramp-shell-quote-argument localname)
3094 command)
3095 t t)
3096 0 1))
3097 ;; We should add the output anyway.
3098 (when outbuf
3099 (with-current-buffer outbuf
3100 (insert
3101 (with-current-buffer (tramp-get-connection-buffer v)
3102 (buffer-string))))
3103 (when (and display (get-buffer-window outbuf t)) (redisplay))))
3104 ;; When the user did interrupt, we should do it also. We use
3105 ;; return code -1 as marker.
3106 (quit
3107 (kill-buffer (tramp-get-connection-buffer v))
3108 (setq ret -1))
3109 ;; Handle errors.
3110 (error
3111 (kill-buffer (tramp-get-connection-buffer v))
3112 (setq ret 1)))
3114 ;; Provide error file.
3115 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3117 ;; Cleanup. We remove all file cache values for the connection,
3118 ;; because the remote process could have changed them.
3119 (when tmpinput (delete-file tmpinput))
3121 (unless process-file-side-effects
3122 (tramp-flush-directory-property v ""))
3124 ;; Return exit status.
3125 (if (equal ret -1)
3126 (keyboard-quit)
3127 ret))))
3129 (defun tramp-sh-handle-file-local-copy (filename)
3130 "Like `file-local-copy' for Tramp files."
3131 (with-parsed-tramp-file-name filename nil
3132 (unless (file-exists-p filename)
3133 (tramp-error
3134 v tramp-file-missing
3135 "Cannot make local copy of non-existing file `%s'" filename))
3137 (let* ((size (tramp-compat-file-attribute-size
3138 (file-attributes (file-truename filename))))
3139 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
3140 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
3141 (tmpfile (tramp-compat-make-temp-file filename)))
3143 (condition-case err
3144 (cond
3145 ;; `copy-file' handles direct copy and out-of-band methods.
3146 ((or (tramp-local-host-p v)
3147 (tramp-method-out-of-band-p v size))
3148 (copy-file filename tmpfile 'ok-if-already-exists 'keep-time))
3150 ;; Use inline encoding for file transfer.
3151 (rem-enc
3152 (save-excursion
3153 (with-tramp-progress-reporter
3155 (format-message "Encoding remote file `%s' with `%s'"
3156 filename rem-enc)
3157 (tramp-barf-unless-okay
3158 v (format rem-enc (tramp-shell-quote-argument localname))
3159 "Encoding remote file failed"))
3161 (with-tramp-progress-reporter
3162 v 3 (format-message "Decoding local file `%s' with `%s'"
3163 tmpfile loc-dec)
3164 (if (functionp loc-dec)
3165 ;; If local decoding is a function, we call it.
3166 ;; We must disable multibyte, because
3167 ;; `uudecode-decode-region' doesn't handle it
3168 ;; correctly. Unset `file-name-handler-alist'.
3169 ;; Otherwise, epa-file gets confused.
3170 (let (file-name-handler-alist
3171 (coding-system-for-write 'binary))
3172 (with-temp-file tmpfile
3173 (set-buffer-multibyte nil)
3174 (insert-buffer-substring (tramp-get-buffer v))
3175 (funcall loc-dec (point-min) (point-max))))
3177 ;; If tramp-decoding-function is not defined for this
3178 ;; method, we invoke tramp-decoding-command instead.
3179 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3180 ;; Unset `file-name-handler-alist'. Otherwise,
3181 ;; epa-file gets confused.
3182 (let (file-name-handler-alist
3183 (coding-system-for-write 'binary))
3184 (with-current-buffer (tramp-get-buffer v)
3185 (write-region
3186 (point-min) (point-max) tmpfile2 nil 'no-message)))
3187 (unwind-protect
3188 (tramp-call-local-coding-command
3189 loc-dec tmpfile2 tmpfile)
3190 (delete-file tmpfile2)))))
3192 ;; Set proper permissions.
3193 (set-file-modes tmpfile (tramp-default-file-modes filename))
3194 ;; Set local user ownership.
3195 (tramp-set-file-uid-gid tmpfile)))
3197 ;; Oops, I don't know what to do.
3198 (t (tramp-error
3199 v 'file-error "Wrong method specification for `%s'" method)))
3201 ;; Error handling.
3202 ((error quit)
3203 (delete-file tmpfile)
3204 (signal (car err) (cdr err))))
3206 (run-hooks 'tramp-handle-file-local-copy-hook)
3207 tmpfile)))
3209 ;; CCC grok LOCKNAME
3210 (defun tramp-sh-handle-write-region
3211 (start end filename &optional append visit lockname confirm)
3212 "Like `write-region' for Tramp files."
3213 (setq filename (expand-file-name filename))
3214 (with-parsed-tramp-file-name filename nil
3215 ;; Following part commented out because we don't know what to do about
3216 ;; file locking, and it does not appear to be a problem to ignore it.
3217 ;; Ange-ftp ignores it, too.
3218 ;; (when (and lockname (stringp lockname))
3219 ;; (setq lockname (expand-file-name lockname)))
3220 ;; (unless (or (eq lockname nil)
3221 ;; (string= lockname filename))
3222 ;; (error
3223 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3225 (when (and confirm (file-exists-p filename))
3226 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3227 (tramp-error v 'file-error "File not overwritten")))
3229 (let ((uid (or (tramp-compat-file-attribute-user-id
3230 (file-attributes filename 'integer))
3231 (tramp-get-remote-uid v 'integer)))
3232 (gid (or (tramp-compat-file-attribute-group-id
3233 (file-attributes filename 'integer))
3234 (tramp-get-remote-gid v 'integer))))
3236 (if (and (tramp-local-host-p v)
3237 ;; `file-writable-p' calls `file-expand-file-name'. We
3238 ;; cannot use `tramp-run-real-handler' therefore.
3239 (let (file-name-handler-alist)
3240 (and
3241 (file-writable-p (file-name-directory localname))
3242 (or (file-directory-p localname)
3243 (file-writable-p localname)))))
3244 ;; Short track: if we are on the local host, we can run directly.
3245 (tramp-run-real-handler
3246 'write-region
3247 (list start end localname append 'no-message lockname confirm))
3249 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3250 ;; We use this to save the value of
3251 ;; `last-coding-system-used' after writing the tmp
3252 ;; file. At the end of the function, we set
3253 ;; `last-coding-system-used' to this saved value. This
3254 ;; way, any intermediary coding systems used while
3255 ;; talking to the remote shell or suchlike won't hose
3256 ;; this variable. This approach was snarfed from
3257 ;; ange-ftp.el.
3258 coding-system-used
3259 ;; Write region into a tmp file. This isn't really
3260 ;; needed if we use an encoding function, but currently
3261 ;; we use it always because this makes the logic
3262 ;; simpler. We must also set `temporary-file-directory',
3263 ;; because it could point to a remote directory.
3264 (temporary-file-directory
3265 (tramp-compat-temporary-file-directory))
3266 (tmpfile (or tramp-temp-buffer-file-name
3267 (tramp-compat-make-temp-file filename))))
3269 ;; If `append' is non-nil, we copy the file locally, and let
3270 ;; the native `write-region' implementation do the job.
3271 (when append (copy-file filename tmpfile 'ok))
3273 ;; We say `no-message' here because we don't want the
3274 ;; visited file modtime data to be clobbered from the temp
3275 ;; file. We call `set-visited-file-modtime' ourselves later
3276 ;; on. We must ensure that `file-coding-system-alist'
3277 ;; matches `tmpfile'.
3278 (let (file-name-handler-alist
3279 (file-coding-system-alist
3280 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3281 (condition-case err
3282 (tramp-run-real-handler
3283 'write-region
3284 (list start end tmpfile append 'no-message lockname confirm))
3285 ((error quit)
3286 (setq tramp-temp-buffer-file-name nil)
3287 (delete-file tmpfile)
3288 (signal (car err) (cdr err))))
3290 ;; Now, `last-coding-system-used' has the right value. Remember it.
3291 (setq coding-system-used last-coding-system-used))
3293 ;; The permissions of the temporary file should be set. If
3294 ;; FILENAME does not exist (eq modes nil) it has been
3295 ;; renamed to the backup file. This case `save-buffer'
3296 ;; handles permissions.
3297 ;; Ensure that it is still readable.
3298 (when modes
3299 (set-file-modes
3300 tmpfile
3301 (logior (or modes 0) (string-to-number "0400" 8))))
3303 ;; This is a bit lengthy due to the different methods
3304 ;; possible for file transfer. First, we check whether the
3305 ;; method uses an scp program. If so, we call it.
3306 ;; Otherwise, both encoding and decoding command must be
3307 ;; specified. However, if the method _also_ specifies an
3308 ;; encoding function, then that is used for encoding the
3309 ;; contents of the tmp file.
3310 (let* ((size (tramp-compat-file-attribute-size
3311 (file-attributes tmpfile)))
3312 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3313 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3314 (cond
3315 ;; `copy-file' handles direct copy and out-of-band methods.
3316 ((or (tramp-local-host-p v)
3317 (tramp-method-out-of-band-p v size))
3318 (if (and (not (stringp start))
3319 (= (or end (point-max)) (point-max))
3320 (= (or start (point-min)) (point-min))
3321 (tramp-get-method-parameter v 'tramp-copy-keep-tmpfile))
3322 (progn
3323 (setq tramp-temp-buffer-file-name tmpfile)
3324 (condition-case err
3325 ;; We keep the local file for performance
3326 ;; reasons, useful for "rsync".
3327 (copy-file tmpfile filename t)
3328 ((error quit)
3329 (setq tramp-temp-buffer-file-name nil)
3330 (delete-file tmpfile)
3331 (signal (car err) (cdr err)))))
3332 (setq tramp-temp-buffer-file-name nil)
3333 ;; Don't rename, in order to keep context in SELinux.
3334 (unwind-protect
3335 (copy-file tmpfile filename t)
3336 (delete-file tmpfile))))
3338 ;; Use inline file transfer.
3339 (rem-dec
3340 ;; Encode tmpfile.
3341 (unwind-protect
3342 (with-temp-buffer
3343 (set-buffer-multibyte nil)
3344 ;; Use encoding function or command.
3345 (with-tramp-progress-reporter
3346 v 3 (format-message
3347 "Encoding local file `%s' using `%s'"
3348 tmpfile loc-enc)
3349 (if (functionp loc-enc)
3350 ;; The following `let' is a workaround for
3351 ;; the base64.el that comes with pgnus-0.84.
3352 ;; If both of the following conditions are
3353 ;; satisfied, it tries to write to a local
3354 ;; file in default-directory, but at this
3355 ;; point, default-directory is remote.
3356 ;; (`call-process-region' can't write to
3357 ;; remote files, it seems.) The file in
3358 ;; question is a tmp file anyway.
3359 (let ((coding-system-for-read 'binary)
3360 (default-directory
3361 (tramp-compat-temporary-file-directory)))
3362 (insert-file-contents-literally tmpfile)
3363 (funcall loc-enc (point-min) (point-max)))
3365 (unless (zerop (tramp-call-local-coding-command
3366 loc-enc tmpfile t))
3367 (tramp-error
3368 v 'file-error
3369 (concat "Cannot write to `%s', "
3370 "local encoding command `%s' failed")
3371 filename loc-enc))))
3373 ;; Send buffer into remote decoding command which
3374 ;; writes to remote file. Because this happens on
3375 ;; the remote host, we cannot use the function.
3376 (with-tramp-progress-reporter
3377 v 3 (format-message
3378 "Decoding remote file `%s' using `%s'"
3379 filename rem-dec)
3380 (goto-char (point-max))
3381 (unless (bolp) (newline))
3382 (tramp-send-command
3384 (format
3385 (concat rem-dec " <<'%s'\n%s%s")
3386 (tramp-shell-quote-argument localname)
3387 tramp-end-of-heredoc
3388 (buffer-string)
3389 tramp-end-of-heredoc))
3390 (tramp-barf-unless-okay
3391 v nil
3392 "Couldn't write region to `%s', decode using `%s' failed"
3393 filename rem-dec)
3394 ;; When `file-precious-flag' is set, the region is
3395 ;; written to a temporary file. Check that the
3396 ;; checksum is equal to that from the local tmpfile.
3397 (when file-precious-flag
3398 (erase-buffer)
3399 (and
3400 ;; cksum runs locally, if possible.
3401 (zerop (tramp-call-process v "cksum" tmpfile t))
3402 ;; cksum runs remotely.
3403 (tramp-send-command-and-check
3405 (format
3406 "cksum <%s" (tramp-shell-quote-argument localname)))
3407 ;; ... they are different.
3408 (not
3409 (string-equal
3410 (buffer-string)
3411 (with-current-buffer (tramp-get-buffer v)
3412 (buffer-string))))
3413 (tramp-error
3414 v 'file-error
3415 (concat "Couldn't write region to `%s',"
3416 " decode using `%s' failed")
3417 filename rem-dec)))))
3419 ;; Save exit.
3420 (delete-file tmpfile)))
3422 ;; That's not expected.
3424 (tramp-error
3425 v 'file-error
3426 (concat "Method `%s' should specify both encoding and "
3427 "decoding command or an scp program")
3428 method))))
3430 ;; Make `last-coding-system-used' have the right value.
3431 (when coding-system-used
3432 (set 'last-coding-system-used coding-system-used))))
3434 (tramp-flush-file-property v (file-name-directory localname))
3435 (tramp-flush-file-property v localname)
3437 ;; We must protect `last-coding-system-used', now we have set it
3438 ;; to its correct value.
3439 (let (last-coding-system-used (need-chown t))
3440 ;; Set file modification time.
3441 (when (or (eq visit t) (stringp visit))
3442 (let ((file-attr (file-attributes filename 'integer)))
3443 (set-visited-file-modtime
3444 ;; We must pass modtime explicitly, because FILENAME can
3445 ;; be different from (buffer-file-name), f.e. if
3446 ;; `file-precious-flag' is set.
3447 (tramp-compat-file-attribute-modification-time file-attr))
3448 (when (and (= (tramp-compat-file-attribute-user-id file-attr) uid)
3449 (= (tramp-compat-file-attribute-group-id file-attr) gid))
3450 (setq need-chown nil))))
3452 ;; Set the ownership.
3453 (when need-chown
3454 (tramp-set-file-uid-gid filename uid gid))
3455 (when (or (eq visit t) (null visit) (stringp visit))
3456 (tramp-message v 0 "Wrote %s" filename))
3457 (run-hooks 'tramp-handle-write-region-hook)))))
3459 (defvar tramp-vc-registered-file-names nil
3460 "List used to collect file names, which are checked during `vc-registered'.")
3462 ;; VC backends check for the existence of various different special
3463 ;; files. This is very time consuming, because every single check
3464 ;; requires a remote command (the file cache must be invalidated).
3465 ;; Therefore, we apply a kind of optimization. We install the file
3466 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3467 ;; remembers all file names for which `file-exists-p' or
3468 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3469 ;; is performed. Afterwards, a script is applied for all collected
3470 ;; file names, using just one remote command. The result of this
3471 ;; script is used to fill the file cache with actual values. Now we
3472 ;; can reset the file name handlers, and we make a second run of
3473 ;; `vc-registered', which returns the expected result without sending
3474 ;; any other remote command.
3475 (defun tramp-sh-handle-vc-registered (file)
3476 "Like `vc-registered' for Tramp files."
3477 (with-temp-message ""
3478 (with-parsed-tramp-file-name file nil
3479 (with-tramp-progress-reporter
3480 v 3 (format-message "Checking `vc-registered' for %s" file)
3482 ;; There could be new files, created by the vc backend. We
3483 ;; cannot reuse the old cache entries, therefore. In
3484 ;; `tramp-get-file-property', `remote-file-name-inhibit-cache'
3485 ;; could also be a timestamp as `current-time' returns. This
3486 ;; means invalidate all cache entries with an older timestamp.
3487 (let (tramp-vc-registered-file-names
3488 (remote-file-name-inhibit-cache (current-time))
3489 (file-name-handler-alist
3490 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3492 ;; Here we collect only file names, which need an operation.
3493 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3494 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3496 ;; Send just one command, in order to fill the cache.
3497 (when tramp-vc-registered-file-names
3498 (tramp-maybe-send-script
3500 (format tramp-vc-registered-read-file-names
3501 (tramp-get-file-exists-command v)
3502 (format "%s -r" (tramp-get-test-command v)))
3503 "tramp_vc_registered_read_file_names")
3505 (dolist
3506 (elt
3507 (ignore-errors
3508 ;; We cannot use `tramp-send-command-and-read',
3509 ;; because this does not cooperate well with
3510 ;; heredoc documents.
3511 (tramp-send-command
3513 (format
3514 "tramp_vc_registered_read_file_names <<'%s'\n%s\n%s\n"
3515 tramp-end-of-heredoc
3516 (mapconcat 'tramp-shell-quote-argument
3517 tramp-vc-registered-file-names
3518 "\n")
3519 tramp-end-of-heredoc))
3520 (with-current-buffer (tramp-get-connection-buffer v)
3521 ;; Read the expression.
3522 (goto-char (point-min))
3523 (read (current-buffer)))))
3525 (tramp-set-file-property
3526 v (car elt) (cadr elt) (cadr (cdr elt))))))
3528 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3529 ;; calls shall be answered from the file cache. We unset
3530 ;; `process-file-side-effects' and `remote-file-name-inhibit-cache'
3531 ;; in order to keep the cache.
3532 (let ((vc-handled-backends vc-handled-backends)
3533 remote-file-name-inhibit-cache process-file-side-effects)
3534 ;; Reduce `vc-handled-backends' in order to minimize process calls.
3535 (when (and (memq 'Bzr vc-handled-backends)
3536 (boundp 'vc-bzr-program)
3537 (not (with-tramp-connection-property v vc-bzr-program
3538 (tramp-find-executable
3539 v vc-bzr-program (tramp-get-remote-path v)))))
3540 (setq vc-handled-backends (remq 'Bzr vc-handled-backends)))
3541 (when (and (memq 'Git vc-handled-backends)
3542 (boundp 'vc-git-program)
3543 (not (with-tramp-connection-property v vc-git-program
3544 (tramp-find-executable
3545 v vc-git-program (tramp-get-remote-path v)))))
3546 (setq vc-handled-backends (remq 'Git vc-handled-backends)))
3547 (when (and (memq 'Hg vc-handled-backends)
3548 (boundp 'vc-hg-program)
3549 (not (with-tramp-connection-property v vc-hg-program
3550 (tramp-find-executable
3551 v vc-hg-program (tramp-get-remote-path v)))))
3552 (setq vc-handled-backends (remq 'Hg vc-handled-backends)))
3553 ;; Run.
3554 (ignore-errors
3555 (tramp-run-real-handler 'vc-registered (list file))))))))
3557 ;;;###tramp-autoload
3558 (defun tramp-sh-file-name-handler (operation &rest args)
3559 "Invoke remote-shell Tramp file name handler.
3560 Fall back to normal file name handler if no Tramp handler exists."
3561 (when (and tramp-locked (not tramp-locker))
3562 (setq tramp-locked nil)
3563 (tramp-error
3564 (car-safe tramp-current-connection) 'file-error
3565 "Forbidden reentrant call of Tramp"))
3566 (let ((tl tramp-locked))
3567 (setq tramp-locked t)
3568 (unwind-protect
3569 (let ((tramp-locker t))
3570 (save-match-data
3571 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3572 (if fn
3573 (apply (cdr fn) args)
3574 (tramp-run-real-handler operation args)))))
3575 (setq tramp-locked tl))))
3577 (defun tramp-vc-file-name-handler (operation &rest args)
3578 "Invoke special file name handler, which collects files to be handled."
3579 (save-match-data
3580 (let ((filename
3581 (tramp-replace-environment-variables
3582 (apply 'tramp-file-name-for-operation operation args)))
3583 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3584 (with-parsed-tramp-file-name filename nil
3585 (cond
3586 ;; That's what we want: file names, for which checks are
3587 ;; applied. We assume that VC uses only `file-exists-p' and
3588 ;; `file-readable-p' checks; otherwise we must extend the
3589 ;; list. We do not perform any action, but return nil, in
3590 ;; order to keep `vc-registered' running.
3591 ((and fn (memq operation '(file-exists-p file-readable-p)))
3592 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3593 nil)
3594 ;; `process-file' and `start-file-process' shall be ignored.
3595 ((and fn (eq operation 'process-file) 0))
3596 ((and fn (eq operation 'start-file-process) nil))
3597 ;; Tramp file name handlers like `expand-file-name'. They
3598 ;; must still work.
3599 (fn (save-match-data (apply (cdr fn) args)))
3600 ;; Default file name handlers, we don't care.
3601 (t (tramp-run-real-handler operation args)))))))
3603 (defun tramp-sh-handle-file-notify-add-watch (file-name flags _callback)
3604 "Like `file-notify-add-watch' for Tramp files."
3605 (setq file-name (expand-file-name file-name))
3606 (with-parsed-tramp-file-name file-name nil
3607 (let ((default-directory (file-name-directory file-name))
3608 command events filter p sequence)
3609 (cond
3610 ;; gvfs-monitor-dir.
3611 ((setq command (tramp-get-remote-gvfs-monitor-dir v))
3612 (setq filter 'tramp-sh-gvfs-monitor-dir-process-filter
3613 events
3614 (cond
3615 ((and (memq 'change flags) (memq 'attribute-change flags))
3616 '(created changed changes-done-hint moved deleted
3617 attribute-changed))
3618 ((memq 'change flags)
3619 '(created changed changes-done-hint moved deleted))
3620 ((memq 'attribute-change flags) '(attribute-changed)))
3621 sequence `(,command ,localname)))
3622 ;; inotifywait.
3623 ((setq command (tramp-get-remote-inotifywait v))
3624 (setq filter 'tramp-sh-inotifywait-process-filter
3625 events
3626 (cond
3627 ((and (memq 'change flags) (memq 'attribute-change flags))
3628 (concat "create,modify,move,moved_from,moved_to,move_self,"
3629 "delete,delete_self,attrib,ignored"))
3630 ((memq 'change flags)
3631 (concat "create,modify,move,moved_from,moved_to,move_self,"
3632 "delete,delete_self,ignored"))
3633 ((memq 'attribute-change flags) "attrib,ignored"))
3634 sequence `(,command "-mq" "-e" ,events ,localname)
3635 ;; Make events a list of symbols.
3636 events
3637 (mapcar
3638 (lambda (x) (intern-soft (replace-regexp-in-string "_" "-" x)))
3639 (split-string events "," 'omit))))
3640 ;; None.
3641 (t (tramp-error
3642 v 'file-notify-error
3643 "No file notification program found on %s"
3644 (file-remote-p file-name))))
3645 ;; Start process.
3646 (setq p (apply
3647 'start-file-process
3648 (file-name-nondirectory command)
3649 (generate-new-buffer
3650 (format " *%s*" (file-name-nondirectory command)))
3651 sequence))
3652 ;; Return the process object as watch-descriptor.
3653 (if (not (processp p))
3654 (tramp-error
3655 v 'file-notify-error
3656 "`%s' failed to start on remote host"
3657 (mapconcat 'identity sequence " "))
3658 (tramp-message v 6 "Run `%s', %S" (mapconcat 'identity sequence " ") p)
3659 (tramp-set-connection-property p "vector" v)
3660 ;; Needed for process filter.
3661 (process-put p 'events events)
3662 (process-put p 'watch-name localname)
3663 (set-process-query-on-exit-flag p nil)
3664 (set-process-filter p filter)
3665 ;; There might be an error if the monitor is not supported.
3666 ;; Give the filter a chance to read the output.
3667 (tramp-accept-process-output p 1)
3668 (unless (tramp-compat-process-live-p p)
3669 (tramp-error
3670 v 'file-notify-error "Monitoring not supported for `%s'" file-name))
3671 p))))
3673 (defun tramp-sh-gvfs-monitor-dir-process-filter (proc string)
3674 "Read output from \"gvfs-monitor-dir\" and add corresponding \
3675 file-notify events."
3676 (let ((events (process-get proc 'events))
3677 (remote-prefix
3678 (with-current-buffer (process-buffer proc)
3679 (file-remote-p default-directory)))
3680 (rest-string (process-get proc 'rest-string)))
3681 (when rest-string
3682 (tramp-message proc 10 "Previous string:\n%s" rest-string))
3683 (tramp-message proc 6 "%S\n%s" proc string)
3684 (setq string (concat rest-string string)
3685 ;; Attribute change is returned in unused wording.
3686 string (replace-regexp-in-string
3687 "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))
3688 (when (string-match "Monitoring not supported" string)
3689 (delete-process proc))
3691 (while (string-match
3692 (concat "^[\n\r]*"
3693 "Directory Monitor Event:[\n\r]+"
3694 "Child = \\([^\n\r]+\\)[\n\r]+"
3695 "\\(Other = \\([^\n\r]+\\)[\n\r]+\\)?"
3696 "Event = \\([^[:blank:]]+\\)[\n\r]+")
3697 string)
3698 (let* ((file (match-string 1 string))
3699 (file1 (match-string 3 string))
3700 (object
3701 (list
3702 proc
3703 (list
3704 (intern-soft
3705 (replace-regexp-in-string
3706 "_" "-" (downcase (match-string 4 string)))))
3707 ;; File names are returned as absolute paths. We must
3708 ;; add the remote prefix.
3709 (concat remote-prefix file)
3710 (when file1 (concat remote-prefix file1)))))
3711 (setq string (replace-match "" nil nil string))
3712 ;; Remove watch when file or directory to be watched is deleted.
3713 (when (and (member (caadr object) '(moved deleted))
3714 (string-equal file (process-get proc 'watch-name)))
3715 (delete-process proc))
3716 ;; Usually, we would add an Emacs event now. Unfortunately,
3717 ;; `unread-command-events' does not accept several events at
3718 ;; once. Therefore, we apply the handler directly.
3719 (when (member (caadr object) events)
3720 (tramp-compat-funcall
3721 'file-notify-handle-event
3722 `(file-notify ,object file-notify-callback)))))
3724 ;; Save rest of the string.
3725 (when (zerop (length string)) (setq string nil))
3726 (when string (tramp-message proc 10 "Rest string:\n%s" string))
3727 (process-put proc 'rest-string string)))
3729 (defun tramp-sh-inotifywait-process-filter (proc string)
3730 "Read output from \"inotifywait\" and add corresponding file-notify events."
3731 (let ((events (process-get proc 'events)))
3732 (tramp-message proc 6 "%S\n%s" proc string)
3733 (dolist (line (split-string string "[\n\r]+" 'omit))
3734 ;; Check, whether there is a problem.
3735 (unless
3736 (string-match
3737 (concat "^[^[:blank:]]+"
3738 "[[:blank:]]+\\([^[:blank:]]+\\)+"
3739 "\\([[:blank:]]+\\([^\n\r]+\\)\\)?")
3740 line)
3741 (tramp-error proc 'file-notify-error "%s" line))
3743 (let ((object
3744 (list
3745 proc
3746 (mapcar
3747 (lambda (x)
3748 (intern-soft
3749 (replace-regexp-in-string "_" "-" (downcase x))))
3750 (split-string (match-string 1 line) "," 'omit))
3751 (match-string 3 line))))
3752 ;; Remove watch when file or directory to be watched is deleted.
3753 (when (member (caadr object) '(move-self delete-self ignored))
3754 (delete-process proc))
3755 ;; Usually, we would add an Emacs event now. Unfortunately,
3756 ;; `unread-command-events' does not accept several events at
3757 ;; once. Therefore, we apply the handler directly.
3758 (when (member (caadr object) events)
3759 (tramp-compat-funcall
3760 'file-notify-handle-event
3761 `(file-notify ,object file-notify-callback)))))))
3763 ;;; Internal Functions:
3765 (defun tramp-maybe-send-script (vec script name)
3766 "Define in remote shell function NAME implemented as SCRIPT.
3767 Only send the definition if it has not already been done."
3768 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3769 ;; might be nil.
3770 (let ((scripts (tramp-get-connection-property
3771 (tramp-get-connection-process vec) "scripts" nil)))
3772 (unless (member name scripts)
3773 (with-tramp-progress-reporter
3774 vec 5 (format-message "Sending script `%s'" name)
3775 ;; In bash, leading TABs like in `tramp-vc-registered-read-file-names'
3776 ;; could result in unwanted command expansion. Avoid this.
3777 (setq script (replace-regexp-in-string
3778 (make-string 1 ?\t) (make-string 8 ? ) script))
3779 ;; The script could contain a call of Perl. This is masked with `%s'.
3780 (when (and (string-match "%s" script)
3781 (not (tramp-get-remote-perl vec)))
3782 (tramp-error vec 'file-error "No Perl available on remote host"))
3783 (tramp-barf-unless-okay
3785 (format "%s () {\n%s\n}"
3786 name (format script (tramp-get-remote-perl vec)))
3787 "Script %s sending failed" name)
3788 (tramp-set-connection-property
3789 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3791 (defun tramp-run-test (switch filename)
3792 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3793 Returns the exit code of the `test' program."
3794 (with-parsed-tramp-file-name filename nil
3795 (tramp-send-command-and-check
3797 (format
3798 "%s %s %s"
3799 (tramp-get-test-command v)
3800 switch
3801 (tramp-shell-quote-argument localname)))))
3803 (defun tramp-run-test2 (format-string file1 file2)
3804 "Run `test'-like program on the remote system, given FILE1, FILE2.
3805 FORMAT-STRING contains the program name, switches, and place holders.
3806 Returns the exit code of the `test' program. Barfs if the methods,
3807 hosts, or files, disagree."
3808 (unless (tramp-equal-remote file1 file2)
3809 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3810 (tramp-error
3811 v 'file-error
3812 "tramp-run-test2 only implemented for same method, user, host")))
3813 (with-parsed-tramp-file-name file1 v1
3814 (with-parsed-tramp-file-name file1 v2
3815 (tramp-send-command-and-check
3817 (format format-string
3818 (tramp-shell-quote-argument v1-localname)
3819 (tramp-shell-quote-argument v2-localname))))))
3821 (defun tramp-find-executable
3822 (vec progname dirlist &optional ignore-tilde ignore-path)
3823 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3824 First arg VEC specifies the connection, PROGNAME is the program
3825 to search for, and DIRLIST gives the list of directories to
3826 search. If IGNORE-TILDE is non-nil, directory names starting
3827 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3828 only in DIRLIST.
3830 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3832 This function expects to be in the right *tramp* buffer."
3833 (with-current-buffer (tramp-get-connection-buffer vec)
3834 (let (result)
3835 ;; Check whether the executable is in $PATH. "which(1)" does not
3836 ;; report always a correct error code; therefore we check the
3837 ;; number of words it returns. "SunOS 5.10" (and maybe "SunOS
3838 ;; 5.11") have problems with this command, we disable the call
3839 ;; therefore.
3840 (unless (or ignore-path
3841 (string-match
3842 (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3843 (tramp-get-connection-property vec "uname" "")))
3844 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3845 (goto-char (point-min))
3846 (if (looking-at "^\\s-*1$")
3847 (setq result (concat "\\" progname))))
3848 (unless result
3849 (when ignore-tilde
3850 ;; Remove all ~/foo directories from dirlist.
3851 (let (newdl d)
3852 (while dirlist
3853 (setq d (car dirlist))
3854 (setq dirlist (cdr dirlist))
3855 (unless (char-equal ?~ (aref d 0))
3856 (setq newdl (cons d newdl))))
3857 (setq dirlist (nreverse newdl))))
3858 (tramp-send-command
3860 (format (concat "while read d; "
3861 "do if test -x $d/%s && test -f $d/%s; "
3862 "then echo tramp_executable $d/%s; "
3863 "break; fi; done <<'%s'\n"
3864 "%s\n%s")
3865 progname progname progname
3866 tramp-end-of-heredoc
3867 (mapconcat 'identity dirlist "\n")
3868 tramp-end-of-heredoc))
3869 (goto-char (point-max))
3870 (when (search-backward "tramp_executable " nil t)
3871 (skip-chars-forward "^ ")
3872 (skip-chars-forward " ")
3873 (setq result (buffer-substring (point) (point-at-eol)))))
3874 result)))
3876 (defun tramp-set-remote-path (vec)
3877 "Sets the remote environment PATH to existing directories.
3878 I.e., for each directory in `tramp-remote-path', it is tested
3879 whether it exists and if so, it is added to the environment
3880 variable PATH."
3881 (tramp-message vec 5 "Setting $PATH environment variable")
3882 (tramp-send-command
3883 vec (format "PATH=%s; export PATH"
3884 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3886 ;; ------------------------------------------------------------
3887 ;; -- Communication with external shell --
3888 ;; ------------------------------------------------------------
3890 (defun tramp-find-file-exists-command (vec)
3891 "Find a command on the remote host for checking if a file exists.
3892 Here, we are looking for a command which has zero exit status if the
3893 file exists and nonzero exit status otherwise."
3894 (let ((existing "/")
3895 (nonexistent
3896 (tramp-shell-quote-argument "/ this file does not exist "))
3897 result)
3898 ;; The algorithm is as follows: we try a list of several commands.
3899 ;; For each command, we first run `$cmd /' -- this should return
3900 ;; true, as the root directory always exists. And then we run
3901 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3902 ;; does not exist. This should return false. We use the first
3903 ;; command we find that seems to work.
3904 ;; The list of commands to try is as follows:
3905 ;; `ls -d' This works on most systems, but NetBSD 1.4
3906 ;; has a bug: `ls' always returns zero exit
3907 ;; status, even for files which don't exist.
3908 ;; `test -e' Some Bourne shells have a `test' builtin
3909 ;; which does not know the `-e' option.
3910 ;; `/bin/test -e' For those, the `test' binary on disk normally
3911 ;; provides the option. Alas, the binary
3912 ;; is sometimes `/bin/test' and sometimes it's
3913 ;; `/usr/bin/test'.
3914 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3915 (unless (or
3916 (ignore-errors
3917 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3918 (tramp-send-command-and-check
3919 vec (format "%s %s" result existing))
3920 (not (tramp-send-command-and-check
3921 vec (format "%s %s" result nonexistent)))))
3922 (ignore-errors
3923 (and (setq result "/bin/test -e")
3924 (tramp-send-command-and-check
3925 vec (format "%s %s" result existing))
3926 (not (tramp-send-command-and-check
3927 vec (format "%s %s" result nonexistent)))))
3928 (ignore-errors
3929 (and (setq result "/usr/bin/test -e")
3930 (tramp-send-command-and-check
3931 vec (format "%s %s" result existing))
3932 (not (tramp-send-command-and-check
3933 vec (format "%s %s" result nonexistent)))))
3934 (ignore-errors
3935 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3936 (tramp-send-command-and-check
3937 vec (format "%s %s" result existing))
3938 (not (tramp-send-command-and-check
3939 vec (format "%s %s" result nonexistent))))))
3940 (tramp-error
3941 vec 'file-error "Couldn't find command to check if file exists"))
3942 result))
3944 (defun tramp-open-shell (vec shell)
3945 "Opens shell SHELL."
3946 (with-tramp-progress-reporter
3947 vec 5 (format-message "Opening remote shell `%s'" shell)
3948 ;; Find arguments for this shell.
3949 (let ((alist tramp-sh-extra-args)
3950 item extra-args)
3951 (while (and alist (null extra-args))
3952 (setq item (pop alist))
3953 (when (string-match (car item) shell)
3954 (setq extra-args (cdr item))))
3955 ;; It is useful to set the prompt in the following command
3956 ;; because some people have a setting for $PS1 which /bin/sh
3957 ;; doesn't know about and thus /bin/sh will display a strange
3958 ;; prompt. For example, if $PS1 has "${CWD}" in the value, then
3959 ;; ksh will display the current working directory but /bin/sh
3960 ;; will display a dollar sign. The following command line sets
3961 ;; $PS1 to a sane value, and works under Bourne-ish shells as
3962 ;; well as csh-like shells. We also unset the variable $ENV
3963 ;; because that is read by some sh implementations (eg, bash
3964 ;; when called as sh) on startup; this way, we avoid the startup
3965 ;; file clobbering $PS1. $PROMPT_COMMAND is another way to set
3966 ;; the prompt in /bin/bash, it must be discarded as well.
3967 ;; $HISTFILE is set according to `tramp-histfile-override'.
3968 (tramp-send-command
3969 vec (format
3970 "exec env ENV=%s %s PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3971 (or (getenv-internal "ENV" tramp-remote-process-environment) "")
3972 (if (stringp tramp-histfile-override)
3973 (format "HISTFILE=%s"
3974 (tramp-shell-quote-argument tramp-histfile-override))
3975 (if tramp-histfile-override
3976 "HISTFILE='' HISTFILESIZE=0 HISTSIZE=0"
3977 ""))
3978 (tramp-shell-quote-argument tramp-end-of-output)
3979 shell (or extra-args ""))
3981 (tramp-set-connection-property
3982 (tramp-get-connection-process vec) "remote-shell" shell)))
3984 (defun tramp-find-shell (vec)
3985 "Opens a shell on the remote host which groks tilde expansion."
3986 (with-current-buffer (tramp-get-buffer vec)
3987 (let ((default-shell (tramp-get-method-parameter vec 'tramp-remote-shell))
3988 shell)
3989 (setq shell
3990 (with-tramp-connection-property vec "remote-shell"
3991 ;; CCC: "root" does not exist always, see my QNAP TS-459.
3992 ;; Which check could we apply instead?
3993 (tramp-send-command vec "echo ~root" t)
3994 (if (or (string-match "^~root$" (buffer-string))
3995 ;; The default shell (ksh93) of OpenSolaris and
3996 ;; Solaris is buggy. We've got reports for
3997 ;; "SunOS 5.10" and "SunOS 5.11" so far.
3998 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3999 (tramp-get-connection-property
4000 vec "uname" "")))
4002 (or (tramp-find-executable
4003 vec "bash" (tramp-get-remote-path vec) t t)
4004 (tramp-find-executable
4005 vec "ksh" (tramp-get-remote-path vec) t t)
4006 ;; Maybe it works at least for some other commands.
4007 (prog1
4008 default-shell
4009 (tramp-message
4010 vec 2
4011 (concat
4012 "Couldn't find a remote shell which groks tilde "
4013 "expansion, using `%s'")
4014 default-shell)))
4016 default-shell)))
4018 ;; Open a new shell if needed.
4019 (unless (string-equal shell default-shell)
4020 (tramp-message
4021 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
4022 (tramp-open-shell vec shell)))))
4024 ;; Utility functions.
4026 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
4027 "Wait for shell prompt and barf if none appears.
4028 Looks at process PROC to see if a shell prompt appears in TIMEOUT
4029 seconds. If not, it produces an error message with the given ERROR-ARGS."
4030 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4031 (condition-case nil
4032 (tramp-wait-for-regexp
4033 proc timeout
4034 (format
4035 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
4036 (error
4037 (delete-process proc)
4038 (apply 'tramp-error-with-buffer
4039 (tramp-get-connection-buffer vec) vec 'file-error error-args)))))
4041 (defun tramp-open-connection-setup-interactive-shell (proc vec)
4042 "Set up an interactive shell.
4043 Mainly sets the prompt and the echo correctly. PROC is the shell
4044 process to set up. VEC specifies the connection."
4045 (let ((tramp-end-of-output tramp-initial-end-of-output)
4046 (case-fold-search t))
4047 (tramp-open-shell vec (tramp-get-method-parameter vec 'tramp-remote-shell))
4049 ;; Disable echo expansion.
4050 (tramp-message vec 5 "Setting up remote shell environment")
4051 (tramp-send-command
4052 vec "stty -inlcr -onlcr -echo kill '^U' erase '^H'" t)
4053 ;; Check whether the echo has really been disabled. Some
4054 ;; implementations, like busybox of embedded GNU/Linux, don't
4055 ;; support disabling.
4056 (tramp-send-command vec "echo foo" t)
4057 (with-current-buffer (process-buffer proc)
4058 (goto-char (point-min))
4059 (when (looking-at "echo foo")
4060 (tramp-set-connection-property proc "remote-echo" t)
4061 (tramp-message vec 5 "Remote echo still on. Ok.")
4062 ;; Make sure backspaces and their echo are enabled and no line
4063 ;; width magic interferes with them.
4064 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
4066 (tramp-message vec 5 "Setting shell prompt")
4067 (tramp-send-command
4068 vec (format "PS1=%s PS2='' PS3='' PROMPT_COMMAND=''"
4069 (tramp-shell-quote-argument tramp-end-of-output))
4072 ;; Check whether the output of "uname -sr" has been changed. If
4073 ;; yes, this is a strong indication that we must expire all
4074 ;; connection properties. We start again with
4075 ;; `tramp-maybe-open-connection', it will be caught there.
4076 (tramp-message vec 5 "Checking system information")
4077 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
4078 (uname
4079 (tramp-set-connection-property
4080 vec "uname"
4081 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
4082 (when (and (stringp old-uname) (not (string-equal old-uname uname)))
4083 (tramp-message
4084 vec 3
4085 "Connection reset, because remote host changed from `%s' to `%s'"
4086 old-uname uname)
4087 ;; We want to keep the password.
4088 (tramp-cleanup-connection vec t t)
4089 (throw 'uname-changed (tramp-maybe-open-connection vec)))
4091 ;; Try to set up the coding system correctly.
4092 ;; CCC this can't be the right way to do it. Hm.
4093 (tramp-message vec 5 "Determining coding system")
4094 (with-current-buffer (process-buffer proc)
4095 ;; Use MULE to select the right EOL convention for
4096 ;; communicating with the process.
4097 (let ((cs (or (and (memq 'utf-8 (coding-system-list))
4098 (string-match "utf-?8" (tramp-get-remote-locale vec))
4099 (cons 'utf-8 'utf-8))
4100 (process-coding-system proc)
4101 (cons 'undecided 'undecided)))
4102 cs-decode cs-encode)
4103 (when (symbolp cs) (setq cs (cons cs cs)))
4104 (setq cs-decode (or (car cs) 'undecided)
4105 cs-encode (or (cdr cs) 'undecided)
4106 cs-encode
4107 (coding-system-change-eol-conversion
4108 cs-encode (if (string-match "^Darwin" uname) 'mac 'unix)))
4109 (tramp-send-command vec "echo foo ; echo bar" t)
4110 (goto-char (point-min))
4111 (when (search-forward "\r" nil t)
4112 (setq cs-decode (coding-system-change-eol-conversion cs-decode 'dos)))
4113 ;; Special setting for Mac OS X.
4114 (when (and (string-match "^Darwin" uname)
4115 (memq 'utf-8-hfs (coding-system-list)))
4116 (setq cs-decode 'utf-8-hfs
4117 cs-encode 'utf-8-hfs))
4118 (set-buffer-process-coding-system cs-decode cs-encode)
4119 (tramp-message
4120 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode)))
4122 (tramp-send-command vec "set +o vi +o emacs" t)
4124 ;; Check whether the remote host suffers from buggy
4125 ;; `send-process-string'. This is known for FreeBSD (see comment
4126 ;; in `send_process', file process.c). I've tested sending 624
4127 ;; bytes successfully, sending 625 bytes failed. Emacs makes a
4128 ;; hack when this host type is detected locally. It cannot handle
4129 ;; remote hosts, though.
4130 (with-tramp-connection-property proc "chunksize"
4131 (cond
4132 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
4133 tramp-chunksize)
4135 (tramp-message
4136 vec 5 "Checking remote host type for `send-process-string' bug")
4137 (if (string-match "^FreeBSD" uname) 500 0))))
4139 ;; Set remote PATH variable.
4140 (tramp-set-remote-path vec)
4142 ;; Search for a good shell before searching for a command which
4143 ;; checks if a file exists. This is done because Tramp wants to
4144 ;; use "test foo; echo $?" to check if various conditions hold,
4145 ;; and there are buggy /bin/sh implementations which don't execute
4146 ;; the "echo $?" part if the "test" part has an error. In
4147 ;; particular, the OpenSolaris /bin/sh is a problem. There are
4148 ;; also other problems with /bin/sh of OpenSolaris, like
4149 ;; redirection of stderr in function declarations, or changing
4150 ;; HISTFILE in place. Therefore, OpenSolaris' /bin/sh is replaced
4151 ;; by bash, when detected.
4152 (tramp-find-shell vec)
4154 ;; Disable unexpected output.
4155 (tramp-send-command vec "mesg n 2>/dev/null; biff n 2>/dev/null" t)
4157 ;; IRIX64 bash expands "!" even when in single quotes. This
4158 ;; destroys our shell functions, we must disable it. See
4159 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
4160 (when (string-match "^IRIX64" uname)
4161 (tramp-send-command vec "set +H" t))
4163 ;; Disable tab expansion.
4164 (if (string-match "BSD\\|Darwin" uname)
4165 (tramp-send-command vec "stty tabs" t)
4166 (tramp-send-command vec "stty tab0" t))
4168 ;; Set utf8 encoding. Needed for Mac OS X, for example. This is
4169 ;; non-POSIX, so we must expect errors on some systems.
4170 (tramp-send-command vec "stty iutf8 2>/dev/null" t)
4172 ;; Set `remote-tty' process property.
4173 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
4174 (unless (zerop (length tty))
4175 (process-put proc 'remote-tty tty)))
4177 ;; Dump stty settings in the traces.
4178 (when (>= tramp-verbose 9)
4179 (tramp-send-command vec "stty -a" t))
4181 ;; Set the environment.
4182 (tramp-message vec 5 "Setting default environment")
4184 (let (unset vars)
4185 (dolist (item (reverse
4186 (append `(,(tramp-get-remote-locale vec))
4187 (copy-sequence tramp-remote-process-environment))))
4188 (setq item (split-string item "=" 'omit))
4189 (setcdr item (mapconcat 'identity (cdr item) "="))
4190 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
4191 (push (format "%s %s" (car item) (cdr item)) vars)
4192 (push (car item) unset)))
4193 (when vars
4194 (tramp-send-command
4196 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
4197 tramp-end-of-heredoc
4198 (mapconcat 'identity vars "\n")
4199 tramp-end-of-heredoc)
4201 (when unset
4202 (tramp-send-command
4203 vec (format "unset %s" (mapconcat 'identity unset " ")) t)))))
4205 ;; Old text from documentation of tramp-methods:
4206 ;; Using a uuencode/uudecode inline method is discouraged, please use one
4207 ;; of the base64 methods instead since base64 encoding is much more
4208 ;; reliable and the commands are more standardized between the different
4209 ;; Unix versions. But if you can't use base64 for some reason, please
4210 ;; note that the default uudecode command does not work well for some
4211 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
4212 ;; the following command for uudecode:
4214 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
4216 ;; For Irix, no solution is known yet.
4218 (autoload 'uudecode-decode-region "uudecode")
4220 (defconst tramp-local-coding-commands
4221 `((b64 base64-encode-region base64-decode-region)
4222 (uu tramp-uuencode-region uudecode-decode-region)
4223 (pack ,(format tramp-perl-pack "perl") ,(format tramp-perl-unpack "perl")))
4224 "List of local coding commands for inline transfer.
4225 Each item is a list that looks like this:
4227 \(FORMAT ENCODING DECODING)
4229 FORMAT is symbol describing the encoding/decoding format. It can be
4230 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4232 ENCODING and DECODING can be strings, giving commands, or symbols,
4233 giving functions. If they are strings, then they can contain
4234 the \"%s\" format specifier. If that specifier is present, the input
4235 file name will be put into the command line at that spot. If the
4236 specifier is not present, the input should be read from standard
4237 input.
4239 If they are functions, they will be called with two arguments, start
4240 and end of region, and are expected to replace the region contents
4241 with the encoded or decoded results, respectively.")
4243 (defconst tramp-remote-coding-commands
4244 `((b64 "base64" "base64 -d -i")
4245 ;; "-i" is more robust with older base64 from GNU coreutils.
4246 ;; However, I don't know whether all base64 versions do supports
4247 ;; this option.
4248 (b64 "base64" "base64 -d")
4249 (b64 "openssl enc -base64" "openssl enc -d -base64")
4250 (b64 "mimencode -b" "mimencode -u -b")
4251 (b64 "mmencode -b" "mmencode -u -b")
4252 (b64 "recode data..base64" "recode base64..data")
4253 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
4254 (b64 tramp-perl-encode tramp-perl-decode)
4255 ;; This is painful slow, so we put it on the end.
4256 (b64 tramp-awk-encode tramp-awk-decode ,tramp-awk-coding-test)
4257 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
4258 (uu "uuencode xxx" "uudecode -o -")
4259 (uu "uuencode xxx" "uudecode -p")
4260 (uu "uuencode xxx" tramp-uudecode)
4261 (pack tramp-perl-pack tramp-perl-unpack))
4262 "List of remote coding commands for inline transfer.
4263 Each item is a list that looks like this:
4265 \(FORMAT ENCODING DECODING [TEST])
4267 FORMAT is a symbol describing the encoding/decoding format. It can be
4268 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4270 ENCODING and DECODING can be strings, giving commands, or symbols,
4271 giving variables. If they are strings, then they can contain
4272 the \"%s\" format specifier. If that specifier is present, the input
4273 file name will be put into the command line at that spot. If the
4274 specifier is not present, the input should be read from standard
4275 input.
4277 If they are variables, this variable is a string containing a
4278 Perl or Shell implementation for this functionality. This
4279 program will be transferred to the remote host, and it is
4280 available as shell function with the same name. A \"%t\" format
4281 specifier in the variable value denotes a temporary file.
4283 The optional TEST command can be used for further tests, whether
4284 ENCODING and DECODING are applicable.")
4286 (defun tramp-find-inline-encoding (vec)
4287 "Find an inline transfer encoding that works.
4288 Goes through the list `tramp-local-coding-commands' and
4289 `tramp-remote-coding-commands'."
4290 (save-excursion
4291 (let ((local-commands tramp-local-coding-commands)
4292 (magic "xyzzy")
4293 (p (tramp-get-connection-process vec))
4294 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4295 (while (and local-commands (not found))
4296 (setq litem (pop local-commands))
4297 (catch 'wont-work-local
4298 (let ((format (nth 0 litem))
4299 (remote-commands tramp-remote-coding-commands))
4300 (setq loc-enc (nth 1 litem))
4301 (setq loc-dec (nth 2 litem))
4302 ;; If the local encoder or decoder is a string, the
4303 ;; corresponding command has to work locally.
4304 (if (not (stringp loc-enc))
4305 (tramp-message
4306 vec 5 "Checking local encoding function `%s'" loc-enc)
4307 (tramp-message
4308 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4309 (unless (zerop (tramp-call-local-coding-command
4310 loc-enc nil nil))
4311 (throw 'wont-work-local nil)))
4312 (if (not (stringp loc-dec))
4313 (tramp-message
4314 vec 5 "Checking local decoding function `%s'" loc-dec)
4315 (tramp-message
4316 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4317 (unless (zerop (tramp-call-local-coding-command
4318 loc-dec nil nil))
4319 (throw 'wont-work-local nil)))
4320 ;; Search for remote coding commands with the same format
4321 (while (and remote-commands (not found))
4322 (setq ritem (pop remote-commands))
4323 (catch 'wont-work-remote
4324 (when (equal format (nth 0 ritem))
4325 (setq rem-enc (nth 1 ritem))
4326 (setq rem-dec (nth 2 ritem))
4327 (setq rem-test (nth 3 ritem))
4328 ;; Check the remote test command if exists.
4329 (when (stringp rem-test)
4330 (tramp-message
4331 vec 5 "Checking remote test command `%s'" rem-test)
4332 (unless (tramp-send-command-and-check vec rem-test t)
4333 (throw 'wont-work-remote nil)))
4334 ;; Check if remote perl exists when necessary.
4335 (when (and (symbolp rem-enc)
4336 (string-match "perl" (symbol-name rem-enc))
4337 (not (tramp-get-remote-perl vec)))
4338 (throw 'wont-work-remote nil))
4339 ;; Check if remote encoding and decoding commands can be
4340 ;; called remotely with null input and output. This makes
4341 ;; sure there are no syntax errors and the command is really
4342 ;; found. Note that we do not redirect stdout to /dev/null,
4343 ;; for two reasons: when checking the decoding command, we
4344 ;; actually check the output it gives. And also, when
4345 ;; redirecting "mimencode" output to /dev/null, then as root
4346 ;; it might change the permissions of /dev/null!
4347 (when (not (stringp rem-enc))
4348 (let ((name (symbol-name rem-enc)))
4349 (while (string-match (regexp-quote "-") name)
4350 (setq name (replace-match "_" nil t name)))
4351 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4352 (setq rem-enc name)))
4353 (tramp-message
4354 vec 5
4355 "Checking remote encoding command `%s' for sanity" rem-enc)
4356 (unless (tramp-send-command-and-check
4357 vec (format "%s </dev/null" rem-enc) t)
4358 (throw 'wont-work-remote nil))
4360 (when (not (stringp rem-dec))
4361 (let ((name (symbol-name rem-dec))
4362 (value (symbol-value rem-dec))
4363 tmpfile)
4364 (while (string-match (regexp-quote "-") name)
4365 (setq name (replace-match "_" nil t name)))
4366 (when (string-match "\\(^\\|[^%]\\)%t" value)
4367 (setq tmpfile
4368 (make-temp-name
4369 (expand-file-name
4370 tramp-temp-name-prefix
4371 (tramp-get-remote-tmpdir vec)))
4372 value
4373 (format-spec
4374 value
4375 (format-spec-make
4377 (file-remote-p tmpfile 'localname)))))
4378 (tramp-maybe-send-script vec value name)
4379 (setq rem-dec name)))
4380 (tramp-message
4381 vec 5
4382 "Checking remote decoding command `%s' for sanity" rem-dec)
4383 (unless (tramp-send-command-and-check
4385 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4387 (throw 'wont-work-remote nil))
4389 (with-current-buffer (tramp-get-buffer vec)
4390 (goto-char (point-min))
4391 (unless (looking-at (regexp-quote magic))
4392 (throw 'wont-work-remote nil)))
4394 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4395 (setq rem-enc (nth 1 ritem))
4396 (setq rem-dec (nth 2 ritem))
4397 (setq found t)))))))
4399 (when found
4400 ;; Set connection properties. Since the commands are risky
4401 ;; (due to output direction), we cache them in the process cache.
4402 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4403 (tramp-set-connection-property p "local-encoding" loc-enc)
4404 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4405 (tramp-set-connection-property p "local-decoding" loc-dec)
4406 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4407 (tramp-set-connection-property p "remote-encoding" rem-enc)
4408 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4409 (tramp-set-connection-property p "remote-decoding" rem-dec)))))
4411 (defun tramp-call-local-coding-command (cmd input output)
4412 "Call the local encoding or decoding command.
4413 If CMD contains \"%s\", provide input file INPUT there in command.
4414 Otherwise, INPUT is passed via standard input.
4415 INPUT can also be nil which means `/dev/null'.
4416 OUTPUT can be a string (which specifies a file name), or t (which
4417 means standard output and thus the current buffer), or nil (which
4418 means discard it)."
4419 (tramp-call-process
4420 nil tramp-encoding-shell
4421 (when (and input (not (string-match "%s" cmd))) input)
4422 (if (eq output t) t nil)
4424 tramp-encoding-command-switch
4425 (concat
4426 (if (string-match "%s" cmd) (format cmd input) cmd)
4427 (if (stringp output) (concat " >" output) ""))))
4429 (defconst tramp-inline-compress-commands
4430 '(("gzip" "gzip -d")
4431 ("bzip2" "bzip2 -d")
4432 ("xz" "xz -d")
4433 ("compress" "compress -d"))
4434 "List of compress and decompress commands for inline transfer.
4435 Each item is a list that looks like this:
4437 \(COMPRESS DECOMPRESS)
4439 COMPRESS or DECOMPRESS are strings with the respective commands.")
4441 (defun tramp-find-inline-compress (vec)
4442 "Find an inline transfer compress command that works.
4443 Goes through the list `tramp-inline-compress-commands'."
4444 (save-excursion
4445 (let ((commands tramp-inline-compress-commands)
4446 (magic "xyzzy")
4447 (p (tramp-get-connection-process vec))
4448 item compress decompress found)
4449 (while (and commands (not found))
4450 (catch 'next
4451 (setq item (pop commands)
4452 compress (nth 0 item)
4453 decompress (nth 1 item))
4454 (tramp-message
4455 vec 5
4456 "Checking local compress commands `%s', `%s' for sanity"
4457 compress decompress)
4458 (unless
4459 (zerop
4460 (tramp-call-local-coding-command
4461 (format
4462 ;; Windows shells need the program file name after
4463 ;; the pipe symbol be quoted if they use forward
4464 ;; slashes as directory separators.
4465 (if (memq system-type '(windows-nt))
4466 "echo %s | \"%s\" | \"%s\""
4467 "echo %s | %s | %s")
4468 magic compress decompress) nil nil))
4469 (throw 'next nil))
4470 (tramp-message
4471 vec 5
4472 "Checking remote compress commands `%s', `%s' for sanity"
4473 compress decompress)
4474 (unless (tramp-send-command-and-check
4475 vec (format "echo %s | %s | %s" magic compress decompress) t)
4476 (throw 'next nil))
4477 (setq found t)))
4479 ;; Did we find something?
4480 (if found
4481 (progn
4482 ;; Set connection properties. Since the commands are
4483 ;; risky (due to output direction), we cache them in the
4484 ;; process cache.
4485 (tramp-message
4486 vec 5 "Using inline transfer compress command `%s'" compress)
4487 (tramp-set-connection-property p "inline-compress" compress)
4488 (tramp-message
4489 vec 5 "Using inline transfer decompress command `%s'" decompress)
4490 (tramp-set-connection-property p "inline-decompress" decompress))
4492 (tramp-set-connection-property p "inline-compress" nil)
4493 (tramp-set-connection-property p "inline-decompress" nil)
4494 (tramp-message
4495 vec 2 "Couldn't find an inline transfer compress command")))))
4497 (defun tramp-compute-multi-hops (vec)
4498 "Expands VEC according to `tramp-default-proxies-alist'.
4499 Gateway hops are already opened."
4500 (let ((target-alist `(,vec))
4501 (hops (or (tramp-file-name-hop vec) ""))
4502 (item vec)
4503 choices proxy)
4505 ;; Ad-hoc proxy definitions.
4506 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4507 (let ((user (tramp-file-name-user item))
4508 (host (tramp-file-name-host item))
4509 (proxy (concat
4510 tramp-prefix-format proxy tramp-postfix-host-format)))
4511 (tramp-message
4512 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4513 (and (stringp host) (regexp-quote host))
4514 (and (stringp user) (regexp-quote user))
4515 proxy)
4516 ;; Add the hop.
4517 (add-to-list
4518 'tramp-default-proxies-alist
4519 (list (and (stringp host) (regexp-quote host))
4520 (and (stringp user) (regexp-quote user))
4521 proxy))
4522 (setq item (tramp-dissect-file-name proxy))))
4523 ;; Save the new value.
4524 (when (and hops tramp-save-ad-hoc-proxies)
4525 (customize-save-variable
4526 'tramp-default-proxies-alist tramp-default-proxies-alist))
4528 ;; Look for proxy hosts to be passed.
4529 (setq choices tramp-default-proxies-alist)
4530 (while choices
4531 (setq item (pop choices)
4532 proxy (eval (nth 2 item)))
4533 (when (and
4534 ;; Host.
4535 (string-match (or (eval (nth 0 item)) "")
4536 (or (tramp-file-name-host (car target-alist)) ""))
4537 ;; User.
4538 (string-match (or (eval (nth 1 item)) "")
4539 (or (tramp-file-name-user (car target-alist)) "")))
4540 (if (null proxy)
4541 ;; No more hops needed.
4542 (setq choices nil)
4543 ;; Replace placeholders.
4544 (setq proxy
4545 (format-spec
4546 proxy
4547 (format-spec-make
4548 ?u (or (tramp-file-name-user (car target-alist)) "")
4549 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4550 (with-parsed-tramp-file-name proxy l
4551 ;; Add the hop.
4552 (push l target-alist)
4553 ;; Start next search.
4554 (setq choices tramp-default-proxies-alist)))))
4556 ;; Handle gateways.
4557 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4558 (string-match
4559 (format
4560 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4561 (tramp-file-name-method (car target-alist))))
4562 (let ((gw (pop target-alist))
4563 (hop (pop target-alist)))
4564 ;; Is the method prepared for gateways?
4565 (unless (tramp-file-name-port hop)
4566 (tramp-error
4567 vec 'file-error
4568 "Connection `%s' is not supported for gateway access." hop))
4569 ;; Open the gateway connection.
4570 (push
4571 (vector
4572 (tramp-file-name-method hop) (tramp-file-name-user hop)
4573 (tramp-gw-open-connection vec gw hop) nil nil)
4574 target-alist)
4575 ;; For the password prompt, we need the correct values.
4576 ;; Therefore, we must remember the gateway vector. But we
4577 ;; cannot do it as connection property, because it shouldn't
4578 ;; be persistent. And we have no started process yet either.
4579 (let ((tramp-verbose 0))
4580 (tramp-set-file-property (car target-alist) "" "gateway" hop))))
4582 ;; Foreign and out-of-band methods are not supported for multi-hops.
4583 (when (cdr target-alist)
4584 (setq choices target-alist)
4585 (while (setq item (pop choices))
4586 (when (or (not (tramp-get-method-parameter item 'tramp-login-program))
4587 (tramp-get-method-parameter item 'tramp-copy-program))
4588 (tramp-error
4589 vec 'file-error
4590 "Method `%s' is not supported for multi-hops."
4591 (tramp-file-name-method item)))))
4593 ;; In case the host name is not used for the remote shell
4594 ;; command, the user could be misguided by applying a random
4595 ;; host name.
4596 (let* ((v (car target-alist))
4597 (method (tramp-file-name-method v))
4598 (host (tramp-file-name-host v)))
4599 (unless
4601 ;; There are multi-hops.
4602 (cdr target-alist)
4603 ;; The host name is used for the remote shell command.
4604 (member '("%h") (tramp-get-method-parameter v 'tramp-login-args))
4605 ;; The host is local. We cannot use `tramp-local-host-p'
4606 ;; here, because it opens a connection as well.
4607 (string-match tramp-local-host-regexp host))
4608 (tramp-error
4609 v 'file-error
4610 "Host `%s' looks like a remote host, `%s' can only use the local host"
4611 host method)))
4613 ;; Result.
4614 target-alist))
4616 (defun tramp-ssh-controlmaster-options (vec)
4617 "Return the Control* arguments of the local ssh."
4618 (cond
4619 ;; No options to be computed.
4620 ((or (null tramp-use-ssh-controlmaster-options)
4621 (null (assoc "%c" (tramp-get-method-parameter vec 'tramp-login-args))))
4624 ;; There is already a value to be used.
4625 ((stringp tramp-ssh-controlmaster-options) tramp-ssh-controlmaster-options)
4627 ;; Determine the options.
4628 (t (setq tramp-ssh-controlmaster-options "")
4629 (let ((case-fold-search t))
4630 (ignore-errors
4631 (when (executable-find "ssh")
4632 (with-temp-buffer
4633 (tramp-call-process vec "ssh" nil t nil "-o" "ControlMaster")
4634 (goto-char (point-min))
4635 (when (search-forward-regexp "missing.+argument" nil t)
4636 (setq tramp-ssh-controlmaster-options "-o ControlMaster=auto")))
4637 (unless (zerop (length tramp-ssh-controlmaster-options))
4638 (with-temp-buffer
4639 ;; We use a non-existing IP address, in order to avoid
4640 ;; useless connections, and DNS timeouts.
4641 (tramp-call-process
4642 vec "ssh" nil t nil "-o" "ControlPath=%C" "0.0.0.1")
4643 (goto-char (point-min))
4644 (setq tramp-ssh-controlmaster-options
4645 (concat tramp-ssh-controlmaster-options
4646 (if (search-forward-regexp "unknown.+key" nil t)
4647 " -o ControlPath='tramp.%%r@%%h:%%p'"
4648 " -o ControlPath='tramp.%%C'"))))
4649 (with-temp-buffer
4650 (tramp-call-process vec "ssh" nil t nil "-o" "ControlPersist")
4651 (goto-char (point-min))
4652 (when (search-forward-regexp "missing.+argument" nil t)
4653 (setq tramp-ssh-controlmaster-options
4654 (concat tramp-ssh-controlmaster-options
4655 " -o ControlPersist=no"))))))))
4656 tramp-ssh-controlmaster-options)))
4658 (defun tramp-maybe-open-connection (vec)
4659 "Maybe open a connection VEC.
4660 Does not do anything if a connection is already open, but re-opens the
4661 connection if a previous connection has died for some reason."
4662 (tramp-check-proper-method-and-host vec)
4664 (let ((p (tramp-get-connection-process vec))
4665 (process-name (tramp-get-connection-property vec "process-name" nil))
4666 (process-environment (copy-sequence process-environment))
4667 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4669 ;; If Tramp opens the same connection within a short time frame,
4670 ;; there is a problem. We shall signal this.
4671 (unless (or (tramp-compat-process-live-p p)
4672 (not (equal (butlast (append vec nil) 2)
4673 (car tramp-current-connection)))
4674 (> (tramp-time-diff
4675 (current-time) (cdr tramp-current-connection))
4676 (or tramp-connection-min-time-diff 0)))
4677 (throw 'suppress 'suppress))
4679 ;; If too much time has passed since last command was sent, look
4680 ;; whether process is still alive. If it isn't, kill it. When
4681 ;; using ssh, it can sometimes happen that the remote end has hung
4682 ;; up but the local ssh client doesn't recognize this until it
4683 ;; tries to send some data to the remote end. So that's why we
4684 ;; try to send a command from time to time, then look again
4685 ;; whether the process is really alive.
4686 (condition-case nil
4687 (when (and (> (tramp-time-diff
4688 (current-time)
4689 (tramp-get-connection-property
4690 p "last-cmd-time" '(0 0 0)))
4692 (tramp-compat-process-live-p p))
4693 (tramp-send-command vec "echo are you awake" t t)
4694 (unless (and (tramp-compat-process-live-p p)
4695 (tramp-wait-for-output p 10))
4696 ;; The error will be caught locally.
4697 (tramp-error vec 'file-error "Awake did fail")))
4698 (file-error
4699 (tramp-cleanup-connection vec t)
4700 (setq p nil)))
4702 ;; New connection must be opened.
4703 (condition-case err
4704 (unless (tramp-compat-process-live-p p)
4706 ;; If `non-essential' is non-nil, don't reopen a new connection.
4707 ;; This variable has been introduced with Emacs 24.1.
4708 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4709 (throw 'non-essential 'non-essential))
4711 (with-tramp-progress-reporter
4712 vec 3
4713 (if (zerop (length (tramp-file-name-user vec)))
4714 (format "Opening connection for %s using %s"
4715 (tramp-file-name-host vec)
4716 (tramp-file-name-method vec))
4717 (format "Opening connection for %s@%s using %s"
4718 (tramp-file-name-user vec)
4719 (tramp-file-name-host vec)
4720 (tramp-file-name-method vec)))
4722 (catch 'uname-changed
4723 ;; Start new process.
4724 (when (and p (processp p))
4725 (delete-process p))
4726 (setenv "TERM" tramp-terminal-type)
4727 (setenv "LC_ALL" (tramp-get-local-locale vec))
4728 (if (stringp tramp-histfile-override)
4729 (setenv "HISTFILE" tramp-histfile-override)
4730 (if tramp-histfile-override
4731 (progn
4732 (setenv "HISTFILE")
4733 (setenv "HISTFILESIZE" "0")
4734 (setenv "HISTSIZE" "0"))))
4735 (setenv "PROMPT_COMMAND")
4736 (setenv "PS1" tramp-initial-end-of-output)
4737 (unless (stringp tramp-encoding-shell)
4738 (tramp-error vec 'file-error "`tramp-encoding-shell' not set"))
4739 (let* ((target-alist (tramp-compute-multi-hops vec))
4740 ;; We will apply `tramp-ssh-controlmaster-options'
4741 ;; only for the first hop.
4742 (options (tramp-ssh-controlmaster-options vec))
4743 (process-connection-type tramp-process-connection-type)
4744 (process-adaptive-read-buffering nil)
4745 ;; There are unfortunate settings for "cmdproxy" on
4746 ;; W32 systems.
4747 (process-coding-system-alist nil)
4748 (coding-system-for-read nil)
4749 ;; This must be done in order to avoid our file
4750 ;; name handler.
4751 (p (let ((default-directory
4752 (tramp-compat-temporary-file-directory)))
4753 (apply
4754 'start-process
4755 (tramp-get-connection-name vec)
4756 (tramp-get-connection-buffer vec)
4757 (if tramp-encoding-command-interactive
4758 (list tramp-encoding-shell
4759 tramp-encoding-command-interactive)
4760 (list tramp-encoding-shell))))))
4762 ;; Set sentinel and query flag.
4763 (tramp-set-connection-property p "vector" vec)
4764 (set-process-sentinel p 'tramp-process-sentinel)
4765 (set-process-query-on-exit-flag p nil)
4766 (setq tramp-current-connection
4767 (cons (butlast (append vec nil) 2) (current-time))
4768 tramp-current-host (system-name))
4770 (tramp-message
4771 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4773 ;; Check whether process is alive.
4774 (tramp-barf-if-no-shell-prompt
4775 p 10
4776 "Couldn't find local shell prompt for %s" tramp-encoding-shell)
4778 ;; Now do all the connections as specified.
4779 (while target-alist
4780 (let* ((hop (car target-alist))
4781 (l-method (tramp-file-name-method hop))
4782 (l-user (tramp-file-name-user hop))
4783 (l-host (tramp-file-name-host hop))
4784 (l-port nil)
4785 (login-program
4786 (tramp-get-method-parameter hop 'tramp-login-program))
4787 (login-args
4788 (tramp-get-method-parameter hop 'tramp-login-args))
4789 (login-env
4790 (tramp-get-method-parameter hop 'tramp-login-env))
4791 (async-args
4792 (tramp-get-method-parameter hop 'tramp-async-args))
4793 (connection-timeout
4794 (tramp-get-method-parameter
4795 hop 'tramp-connection-timeout))
4796 (gw-args
4797 (tramp-get-method-parameter hop 'tramp-gw-args))
4798 (gw (let ((tramp-verbose 0))
4799 (tramp-get-file-property hop "" "gateway" nil)))
4800 (g-method (and gw (tramp-file-name-method gw)))
4801 (g-user (and gw (tramp-file-name-user gw)))
4802 (g-host (and gw (tramp-file-name-real-host gw)))
4803 (command login-program)
4804 ;; We don't create the temporary file. In
4805 ;; fact, it is just a prefix for the
4806 ;; ControlPath option of ssh; the real
4807 ;; temporary file has another name, and it is
4808 ;; created and protected by ssh. It is also
4809 ;; removed by ssh when the connection is
4810 ;; closed. The temporary file name is cached
4811 ;; in the main connection process, therefore
4812 ;; we cannot use `tramp-get-connection-process'.
4813 (tmpfile
4814 (with-tramp-connection-property
4815 (get-process (tramp-buffer-name vec)) "temp-file"
4816 (make-temp-name
4817 (expand-file-name
4818 tramp-temp-name-prefix
4819 (tramp-compat-temporary-file-directory)))))
4820 spec r-shell)
4822 ;; Add arguments for asynchronous processes.
4823 (when (and process-name async-args)
4824 (setq login-args (append async-args login-args)))
4826 ;; Add gateway arguments if necessary.
4827 (when gw
4828 (tramp-set-connection-property p "gateway" t)
4829 (when gw-args
4830 (setq login-args (append gw-args login-args))))
4832 ;; Check for port number. Until now, there's no
4833 ;; need for handling like method, user, host.
4834 (when (string-match tramp-host-with-port-regexp l-host)
4835 (setq l-port (match-string 2 l-host)
4836 l-host (match-string 1 l-host)))
4838 ;; Check, whether there is a restricted shell.
4839 (dolist (elt tramp-restricted-shell-hosts-alist)
4840 (when (string-match elt tramp-current-host)
4841 (setq r-shell t)))
4843 ;; Set variables for computing the prompt for
4844 ;; reading password. They can also be derived
4845 ;; from a gateway.
4846 (setq tramp-current-method (or g-method l-method)
4847 tramp-current-user (or g-user l-user)
4848 tramp-current-host (or g-host l-host))
4850 ;; Add login environment.
4851 (when login-env
4852 (setq
4853 login-env
4854 (mapcar
4855 (lambda (x)
4856 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4857 (unless (member "" x) (mapconcat 'identity x " ")))
4858 login-env))
4859 (while login-env
4860 (setq command
4861 (format
4862 "%s=%s %s"
4863 (pop login-env)
4864 (tramp-shell-quote-argument (pop login-env))
4865 command)))
4866 (setq command (concat "env " command)))
4868 ;; Replace `login-args' place holders.
4869 (setq
4870 l-host (or l-host "")
4871 l-user (or l-user "")
4872 l-port (or l-port "")
4873 spec (format-spec-make ?t tmpfile)
4874 options (format-spec options spec)
4875 spec (format-spec-make
4876 ?h l-host ?u l-user ?p l-port ?c options)
4877 command
4878 (concat
4879 ;; We do not want to see the trailing local
4880 ;; prompt in `start-file-process'.
4881 (unless r-shell "exec ")
4882 command " "
4883 (mapconcat
4884 (lambda (x)
4885 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4886 (unless (member "" x) (mapconcat 'identity x " ")))
4887 login-args " ")
4888 ;; Local shell could be a Windows COMSPEC. It
4889 ;; doesn't know the ";" syntax, but we must exit
4890 ;; always for `start-file-process'. It could
4891 ;; also be a restricted shell, which does not
4892 ;; allow "exec".
4893 (when r-shell " && exit || exit")))
4895 ;; Send the command.
4896 (tramp-message vec 3 "Sending command `%s'" command)
4897 (tramp-send-command vec command t t)
4898 (tramp-process-actions
4899 p vec
4900 (min
4901 pos (with-current-buffer (process-buffer p) (point-max)))
4902 tramp-actions-before-shell
4903 (or connection-timeout tramp-connection-timeout))
4904 (tramp-message
4905 vec 3 "Found remote shell prompt on `%s'" l-host))
4906 ;; Next hop.
4907 (setq options ""
4908 target-alist (cdr target-alist)))
4910 ;; Make initial shell settings.
4911 (tramp-open-connection-setup-interactive-shell p vec)
4913 ;; Mark it as connected.
4914 (tramp-set-connection-property p "connected" t)))))
4916 ;; When the user did interrupt, we must cleanup.
4917 (quit
4918 (tramp-cleanup-connection vec t)
4919 ;; Propagate the quit signal.
4920 (signal (car err) (cdr err))))))
4922 (defun tramp-send-command (vec command &optional neveropen nooutput)
4923 "Send the COMMAND to connection VEC.
4924 Erases temporary buffer before sending the command. If optional
4925 arg NEVEROPEN is non-nil, never try to open the connection. This
4926 is meant to be used from `tramp-maybe-open-connection' only. The
4927 function waits for output unless NOOUTPUT is set."
4928 (unless neveropen (tramp-maybe-open-connection vec))
4929 (let ((p (tramp-get-connection-process vec)))
4930 (when (tramp-get-connection-property p "remote-echo" nil)
4931 ;; We mark the command string that it can be erased in the output buffer.
4932 (tramp-set-connection-property p "check-remote-echo" t)
4933 ;; If we put `tramp-echo-mark' after a trailing newline (which
4934 ;; is assumed to be unquoted) `tramp-send-string' doesn't see
4935 ;; that newline and adds `tramp-rsh-end-of-line' right after
4936 ;; `tramp-echo-mark', so the remote shell sees two consecutive
4937 ;; trailing line endings and sends two prompts after executing
4938 ;; the command, which confuses `tramp-wait-for-output'.
4939 (when (and (not (string= command ""))
4940 (string-equal (substring command -1) "\n"))
4941 (setq command (substring command 0 -1)))
4942 ;; No need to restore a trailing newline here since `tramp-send-string'
4943 ;; makes sure that the string ends in `tramp-rsh-end-of-line', anyway.
4944 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4945 ;; Send the command.
4946 (tramp-message vec 6 "%s" command)
4947 (tramp-send-string vec command)
4948 (unless nooutput (tramp-wait-for-output p))))
4950 (defun tramp-wait-for-output (proc &optional timeout)
4951 "Wait for output from remote command."
4952 (unless (buffer-live-p (process-buffer proc))
4953 (delete-process proc)
4954 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4955 (with-current-buffer (process-buffer proc)
4956 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4957 ;; be leading escape sequences, which must be ignored.
4958 ;; Busyboxes built with the EDITING_ASK_TERMINAL config
4959 ;; option send also escape sequences, which must be
4960 ;; ignored.
4961 (regexp (format "[^#$\n]*%s\\(%s\\)?\r?$"
4962 (regexp-quote tramp-end-of-output)
4963 tramp-device-escape-sequence-regexp))
4964 ;; Sometimes, the commands do not return a newline but a
4965 ;; null byte before the shell prompt, for example "git
4966 ;; ls-files -c -z ...".
4967 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4968 (found (tramp-wait-for-regexp proc timeout regexp1)))
4969 (if found
4970 (let (buffer-read-only)
4971 ;; A simple-minded busybox has sent " ^H" sequences.
4972 ;; Delete them.
4973 (goto-char (point-min))
4974 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4975 (forward-line 1)
4976 (delete-region (point-min) (point)))
4977 ;; Delete the prompt.
4978 (goto-char (point-max))
4979 (re-search-backward regexp nil t)
4980 (delete-region (point) (point-max)))
4981 (if timeout
4982 (tramp-error
4983 proc 'file-error
4984 "[[Remote prompt `%s' not found in %d secs]]"
4985 tramp-end-of-output timeout)
4986 (tramp-error
4987 proc 'file-error
4988 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
4989 ;; Return value is whether end-of-output sentinel was found.
4990 found)))
4992 (defun tramp-send-command-and-check
4993 (vec command &optional subshell dont-suppress-err)
4994 "Run COMMAND and check its exit status.
4995 Sends `echo $?' along with the COMMAND for checking the exit status.
4996 If COMMAND is nil, just sends `echo $?'. Returns t if the exit
4997 status is 0, and nil otherwise.
4999 If the optional argument SUBSHELL is non-nil, the command is
5000 executed in a subshell, ie surrounded by parentheses. If
5001 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
5002 (tramp-send-command
5004 (concat (if subshell "( " "")
5005 command
5006 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
5007 "echo tramp_exit_status $?"
5008 (if subshell " )" "")))
5009 (with-current-buffer (tramp-get-connection-buffer vec)
5010 (goto-char (point-max))
5011 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
5012 (tramp-error
5013 vec 'file-error "Couldn't find exit status of `%s'" command))
5014 (skip-chars-forward "^ ")
5015 (prog1
5016 (zerop (read (current-buffer)))
5017 (let (buffer-read-only)
5018 (delete-region (match-beginning 0) (point-max))))))
5020 (defun tramp-barf-unless-okay (vec command fmt &rest args)
5021 "Run COMMAND, check exit status, throw error if exit status not okay.
5022 Similar to `tramp-send-command-and-check' but accepts two more arguments
5023 FMT and ARGS which are passed to `error'."
5024 (or (tramp-send-command-and-check vec command)
5025 (apply 'tramp-error vec 'file-error fmt args)))
5027 (defun tramp-send-command-and-read (vec command &optional noerror marker)
5028 "Run COMMAND and return the output, which must be a Lisp expression.
5029 If MARKER is a regexp, read the output after that string.
5030 In case there is no valid Lisp expression and NOERROR is nil, it
5031 raises an error."
5032 (when (if noerror
5033 (tramp-send-command-and-check vec command)
5034 (tramp-barf-unless-okay
5035 vec command "`%s' returns with error" command))
5036 (with-current-buffer (tramp-get-connection-buffer vec)
5037 (goto-char (point-min))
5038 ;; Read the marker.
5039 (when (stringp marker)
5040 (condition-case nil
5041 (re-search-forward marker)
5042 (error (unless noerror
5043 (tramp-error
5044 vec 'file-error
5045 "`%s' does not return the marker `%s': `%s'"
5046 command marker (buffer-string))))))
5047 ;; Read the expression.
5048 (condition-case nil
5049 (prog1 (read (current-buffer))
5050 ;; Error handling.
5051 (when (re-search-forward "\\S-" (point-at-eol) t)
5052 (error nil)))
5053 (error (unless noerror
5054 (tramp-error
5055 vec 'file-error
5056 "`%s' does not return a valid Lisp expression: `%s'"
5057 command (buffer-string))))))))
5059 (defun tramp-convert-file-attributes (vec attr)
5060 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
5061 Convert file mode bits to string and set virtual device number.
5062 Return ATTR."
5063 (when attr
5064 ;; Remove color escape sequences from symlink.
5065 (when (stringp (car attr))
5066 (while (string-match tramp-display-escape-sequence-regexp (car attr))
5067 (setcar attr (replace-match "" nil nil (car attr)))))
5068 ;; Convert uid and gid. Use `tramp-unknown-id-integer' as
5069 ;; indication of unusable value.
5070 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
5071 (setcar (nthcdr 2 attr) tramp-unknown-id-integer))
5072 (when (and (floatp (nth 2 attr))
5073 (<= (nth 2 attr) most-positive-fixnum))
5074 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
5075 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
5076 (setcar (nthcdr 3 attr) tramp-unknown-id-integer))
5077 (when (and (floatp (nth 3 attr))
5078 (<= (nth 3 attr) most-positive-fixnum))
5079 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
5080 ;; Convert last access time.
5081 (unless (listp (nth 4 attr))
5082 (setcar (nthcdr 4 attr)
5083 (list (floor (nth 4 attr) 65536)
5084 (floor (mod (nth 4 attr) 65536)))))
5085 ;; Convert last modification time.
5086 (unless (listp (nth 5 attr))
5087 (setcar (nthcdr 5 attr)
5088 (list (floor (nth 5 attr) 65536)
5089 (floor (mod (nth 5 attr) 65536)))))
5090 ;; Convert last status change time.
5091 (unless (listp (nth 6 attr))
5092 (setcar (nthcdr 6 attr)
5093 (list (floor (nth 6 attr) 65536)
5094 (floor (mod (nth 6 attr) 65536)))))
5095 ;; Convert file size.
5096 (when (< (nth 7 attr) 0)
5097 (setcar (nthcdr 7 attr) -1))
5098 (when (and (floatp (nth 7 attr))
5099 (<= (nth 7 attr) most-positive-fixnum))
5100 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
5101 ;; Convert file mode bits to string.
5102 (unless (stringp (nth 8 attr))
5103 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
5104 (when (stringp (car attr))
5105 (aset (nth 8 attr) 0 ?l)))
5106 ;; Convert directory indication bit.
5107 (when (string-match "^d" (nth 8 attr))
5108 (setcar attr t))
5109 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
5110 (when (consp (car attr))
5111 (if (and (stringp (caar attr))
5112 (string-match ".+ -> .\\(.+\\)." (caar attr)))
5113 (setcar attr (match-string 1 (caar attr)))
5114 (setcar attr nil)))
5115 ;; Set file's gid change bit.
5116 (setcar (nthcdr 9 attr)
5117 (if (numberp (nth 3 attr))
5118 (not (= (nth 3 attr)
5119 (tramp-get-remote-gid vec 'integer)))
5120 (not (string-equal
5121 (nth 3 attr)
5122 (tramp-get-remote-gid vec 'string)))))
5123 ;; Convert inode.
5124 (unless (listp (nth 10 attr))
5125 (setcar (nthcdr 10 attr)
5126 (condition-case nil
5127 (cons (floor (nth 10 attr) 65536)
5128 (floor (mod (nth 10 attr) 65536)))
5129 ;; Inodes can be incredible huge. We must hide this.
5130 (error (tramp-get-inode vec)))))
5131 ;; Set virtual device number.
5132 (setcar (nthcdr 11 attr)
5133 (tramp-get-device vec))
5134 attr))
5136 (defun tramp-shell-case-fold (string)
5137 "Converts STRING to shell glob pattern which ignores case."
5138 (mapconcat
5139 (lambda (c)
5140 (if (equal (downcase c) (upcase c))
5141 (vector c)
5142 (format "[%c%c]" (downcase c) (upcase c))))
5143 string
5144 ""))
5146 (defun tramp-make-copy-program-file-name (vec)
5147 "Create a file name suitable for `scp', `pscp', or `nc' and workalikes."
5148 (let ((method (tramp-file-name-method vec))
5149 (user (tramp-file-name-user vec))
5150 (host (tramp-file-name-real-host vec))
5151 (localname (directory-file-name (tramp-file-name-localname vec))))
5152 (when (string-match tramp-ipv6-regexp host)
5153 (setq host (format "[%s]" host)))
5154 (unless (string-match "ftp$" method)
5155 (setq localname (tramp-shell-quote-argument localname)))
5156 (cond
5157 ((tramp-get-method-parameter vec 'tramp-remote-copy-program)
5158 localname)
5159 ((not (zerop (length user)))
5160 (shell-quote-argument (format "%s@%s:%s" user host localname)))
5161 (t (shell-quote-argument (format "%s:%s" host localname))))))
5163 (defun tramp-method-out-of-band-p (vec size)
5164 "Return t if this is an out-of-band method, nil otherwise."
5165 (and
5166 ;; It shall be an out-of-band method.
5167 (tramp-get-method-parameter vec 'tramp-copy-program)
5168 ;; There must be a size, otherwise the file doesn't exist.
5169 (numberp size)
5170 ;; Either the file size is large enough, or (in rare cases) there
5171 ;; does not exist a remote encoding.
5172 (or (null tramp-copy-size-limit)
5173 (> size tramp-copy-size-limit)
5174 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
5176 ;; Variables local to connection.
5178 (defun tramp-get-remote-path (vec)
5179 "Compile list of remote directories for $PATH.
5180 Nonexistent directories are removed from spec."
5181 (with-tramp-connection-property
5182 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
5183 ;; cache the result for the session only. Otherwise, the result
5184 ;; is cached persistently.
5185 (if (memq 'tramp-own-remote-path tramp-remote-path)
5186 (tramp-get-connection-process vec)
5187 vec)
5188 "remote-path"
5189 (let* ((remote-path (copy-tree tramp-remote-path))
5190 (elt1 (memq 'tramp-default-remote-path remote-path))
5191 (elt2 (memq 'tramp-own-remote-path remote-path))
5192 (default-remote-path
5193 (when elt1
5195 (tramp-send-command-and-read
5196 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
5197 ;; Default if "getconf" is not available.
5198 (progn
5199 (tramp-message
5200 vec 3
5201 "`getconf PATH' not successful, using default value \"%s\"."
5202 "/bin:/usr/bin")
5203 "/bin:/usr/bin"))))
5204 (own-remote-path
5205 ;; The login shell could return more than just the $PATH
5206 ;; string. So we use `tramp-end-of-heredoc' as marker.
5207 (when elt2
5209 (tramp-send-command-and-read
5211 (format
5212 "%s %s %s 'echo %s \\\"$PATH\\\"'"
5213 (tramp-get-method-parameter vec 'tramp-remote-shell)
5214 (mapconcat
5215 'identity
5216 (tramp-get-method-parameter vec 'tramp-remote-shell-login)
5217 " ")
5218 (mapconcat
5219 'identity
5220 (tramp-get-method-parameter vec 'tramp-remote-shell-args)
5221 " ")
5222 (tramp-shell-quote-argument tramp-end-of-heredoc))
5223 'noerror (regexp-quote tramp-end-of-heredoc))
5224 (progn
5225 (tramp-message
5226 vec 2 "Could not retrieve `tramp-own-remote-path'")
5227 nil)))))
5229 ;; Replace place holder `tramp-default-remote-path'.
5230 (when elt1
5231 (setcdr elt1
5232 (append
5233 (split-string (or default-remote-path "") ":" 'omit)
5234 (cdr elt1)))
5235 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
5237 ;; Replace place holder `tramp-own-remote-path'.
5238 (when elt2
5239 (setcdr elt2
5240 (append
5241 (split-string (or own-remote-path "") ":" 'omit)
5242 (cdr elt2)))
5243 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
5245 ;; Remove double entries.
5246 (setq elt1 remote-path)
5247 (while (consp elt1)
5248 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
5249 (setcar elt2 nil))
5250 (setq elt1 (cdr elt1)))
5252 ;; Remove non-existing directories.
5253 (delq
5255 (mapcar
5256 (lambda (x)
5257 (and
5258 (stringp x)
5259 (file-directory-p
5260 (tramp-make-tramp-file-name
5261 (tramp-file-name-method vec)
5262 (tramp-file-name-user vec)
5263 (tramp-file-name-host vec)
5266 remote-path)))))
5268 (defun tramp-get-remote-locale (vec)
5269 "Determine remote locale, supporting UTF8 if possible."
5270 (with-tramp-connection-property vec "locale"
5271 (tramp-send-command vec "locale -a")
5272 (let ((candidates '("en_US.utf8" "C.utf8" "en_US.UTF-8"))
5273 locale)
5274 (with-current-buffer (tramp-get-connection-buffer vec)
5275 (while candidates
5276 (goto-char (point-min))
5277 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
5278 (buffer-string))
5279 (setq locale (car candidates)
5280 candidates nil)
5281 (setq candidates (cdr candidates)))))
5282 ;; Return value.
5283 (format "LC_ALL=%s" (or locale "C")))))
5285 (defun tramp-get-ls-command (vec)
5286 "Determine remote `ls' command."
5287 (with-tramp-connection-property vec "ls"
5288 (tramp-message vec 5 "Finding a suitable `ls' command")
5290 (catch 'ls-found
5291 (dolist (cmd '("ls" "gnuls" "gls"))
5292 (let ((dl (tramp-get-remote-path vec))
5293 result)
5294 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5295 ;; Check parameters. On busybox, "ls" output coloring is
5296 ;; enabled by default sometimes. So we try to disable it
5297 ;; when possible. $LS_COLORING is not supported there.
5298 ;; Some "ls" versions are sensible wrt the order of
5299 ;; arguments, they fail when "-al" is after the
5300 ;; "--color=never" argument (for example on FreeBSD).
5301 (when (tramp-send-command-and-check
5302 vec (format "%s -lnd /" result))
5303 (when (tramp-send-command-and-check
5304 vec (format
5305 "%s --color=never -al /dev/null" result))
5306 (setq result (concat result " --color=never")))
5307 (throw 'ls-found result))
5308 (setq dl (cdr dl))))))
5309 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
5311 (defun tramp-get-ls-command-with-dired (vec)
5312 "Check, whether the remote `ls' command supports the --dired option."
5313 (save-match-data
5314 (with-tramp-connection-property vec "ls-dired"
5315 (tramp-message vec 5 "Checking, whether `ls --dired' works")
5316 ;; Some "ls" versions are sensible wrt the order of arguments,
5317 ;; they fail when "-al" is after the "--dired" argument (for
5318 ;; example on FreeBSD).
5319 (tramp-send-command-and-check
5320 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
5322 (defun tramp-get-ls-command-with-quoting-style (vec)
5323 "Check, whether the remote `ls' command supports the --quoting-style option."
5324 (save-match-data
5325 (with-tramp-connection-property vec "ls-quoting-style"
5326 (tramp-message vec 5 "Checking, whether `ls --quoting-style=shell' works")
5327 (tramp-send-command-and-check
5328 vec (format "%s --quoting-style=shell -al /dev/null"
5329 (tramp-get-ls-command vec))))))
5331 (defun tramp-get-ls-command-with-w-option (vec)
5332 "Check, whether the remote `ls' command supports the -w option."
5333 (save-match-data
5334 (with-tramp-connection-property vec "ls-w-option"
5335 (tramp-message vec 5 "Checking, whether `ls -w' works")
5336 ;; Option "-w" is available on BSD systems. No argument is
5337 ;; given, because this could return wrong results in case "ls"
5338 ;; supports the "-w NUM" argument, as for busyboxes.
5339 (tramp-send-command-and-check
5340 vec (format "%s -alw" (tramp-get-ls-command vec))))))
5342 (defun tramp-get-test-command (vec)
5343 "Determine remote `test' command."
5344 (with-tramp-connection-property vec "test"
5345 (tramp-message vec 5 "Finding a suitable `test' command")
5346 (if (tramp-send-command-and-check vec "test 0")
5347 "test"
5348 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
5350 (defun tramp-get-test-nt-command (vec)
5351 "Check, whether the remote `test' command supports the -nt option."
5352 ;; Does `test A -nt B' work? Use abominable `find' construct if it
5353 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
5354 ;; for otherwise the shell crashes.
5355 (with-tramp-connection-property vec "test-nt"
5357 (progn
5358 (tramp-send-command
5359 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
5360 (with-current-buffer (tramp-get-buffer vec)
5361 (goto-char (point-min))
5362 (when (looking-at (regexp-quote tramp-end-of-output))
5363 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
5364 (progn
5365 (tramp-send-command
5367 (format
5368 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
5369 (tramp-get-test-command vec)))
5370 "tramp_test_nt %s %s"))))
5372 (defun tramp-get-file-exists-command (vec)
5373 "Determine remote command for file existing check."
5374 (with-tramp-connection-property vec "file-exists"
5375 (tramp-message vec 5 "Finding command to check if file exists")
5376 (tramp-find-file-exists-command vec)))
5378 (defun tramp-get-remote-ln (vec)
5379 "Determine remote `ln' command."
5380 (with-tramp-connection-property vec "ln"
5381 (tramp-message vec 5 "Finding a suitable `ln' command")
5382 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
5384 (defun tramp-get-remote-perl (vec)
5385 "Determine remote `perl' command."
5386 (with-tramp-connection-property vec "perl"
5387 (tramp-message vec 5 "Finding a suitable `perl' command")
5388 (let ((result
5389 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
5390 (tramp-find-executable vec "perl" (tramp-get-remote-path vec)))))
5391 ;; Perform a basic check.
5392 (and result
5393 (null (tramp-send-command-and-check
5394 vec (format "%s -e 'print \"Hello\n\";'" result)))
5395 (setq result nil))
5396 ;; We must check also for some Perl modules.
5397 (when result
5398 (with-tramp-connection-property vec "perl-file-spec"
5399 (tramp-send-command-and-check
5400 vec (format "%s -e 'use File::Spec;'" result)))
5401 (with-tramp-connection-property vec "perl-cwd-realpath"
5402 (tramp-send-command-and-check
5403 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
5404 result)))
5406 (defun tramp-get-remote-stat (vec)
5407 "Determine remote `stat' command."
5408 (with-tramp-connection-property vec "stat"
5409 (tramp-message vec 5 "Finding a suitable `stat' command")
5410 (let ((result (tramp-find-executable
5411 vec "stat" (tramp-get-remote-path vec)))
5412 tmp)
5413 ;; Check whether stat(1) returns usable syntax. "%s" does not
5414 ;; work on older AIX systems. Recent GNU stat versions (8.24?)
5415 ;; use shell quoted format for "%N", we check the boundaries "`"
5416 ;; and "'", therefore. See Bug#23422 in coreutils.
5417 (when result
5418 (setq tmp
5419 (tramp-send-command-and-read
5420 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5421 (unless (and (listp tmp) (stringp (car tmp))
5422 (string-match "^`/'$" (car tmp))
5423 (integerp (cadr tmp)))
5424 (setq result nil)))
5425 result)))
5427 (defun tramp-get-remote-readlink (vec)
5428 "Determine remote `readlink' command."
5429 (with-tramp-connection-property vec "readlink"
5430 (tramp-message vec 5 "Finding a suitable `readlink' command")
5431 (let ((result (tramp-find-executable
5432 vec "readlink" (tramp-get-remote-path vec))))
5433 (when (and result
5434 (tramp-send-command-and-check
5435 vec (format "%s --canonicalize-missing /" result)))
5436 result))))
5438 (defun tramp-get-remote-trash (vec)
5439 "Determine remote `trash' command."
5440 (with-tramp-connection-property vec "trash"
5441 (tramp-message vec 5 "Finding a suitable `trash' command")
5442 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5444 (defun tramp-get-remote-touch (vec)
5445 "Determine remote `touch' command."
5446 (with-tramp-connection-property vec "touch"
5447 (tramp-message vec 5 "Finding a suitable `touch' command")
5448 (let ((result (tramp-find-executable
5449 vec "touch" (tramp-get-remote-path vec)))
5450 (tmpfile
5451 (make-temp-name
5452 (expand-file-name
5453 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
5454 ;; Busyboxes do support the "-t" option only when they have been
5455 ;; built with the DESKTOP config option. Let's check it.
5456 (when result
5457 (tramp-set-connection-property
5458 vec "touch-t"
5459 (tramp-send-command-and-check
5461 (format
5462 "%s -t %s %s"
5463 result
5464 (format-time-string "%Y%m%d%H%M.%S")
5465 (file-remote-p tmpfile 'localname))))
5466 (delete-file tmpfile))
5467 result)))
5469 (defun tramp-get-remote-gvfs-monitor-dir (vec)
5470 "Determine remote `gvfs-monitor-dir' command."
5471 (with-tramp-connection-property vec "gvfs-monitor-dir"
5472 (tramp-message vec 5 "Finding a suitable `gvfs-monitor-dir' command")
5473 (tramp-find-executable
5474 vec "gvfs-monitor-dir" (tramp-get-remote-path vec) t t)))
5476 (defun tramp-get-remote-inotifywait (vec)
5477 "Determine remote `inotifywait' command."
5478 (with-tramp-connection-property vec "inotifywait"
5479 (tramp-message vec 5 "Finding a suitable `inotifywait' command")
5480 (tramp-find-executable vec "inotifywait" (tramp-get-remote-path vec) t t)))
5482 (defun tramp-get-remote-id (vec)
5483 "Determine remote `id' command."
5484 (with-tramp-connection-property vec "id"
5485 (tramp-message vec 5 "Finding POSIX `id' command")
5486 (catch 'id-found
5487 (dolist (cmd '("id" "gid"))
5488 (let ((dl (tramp-get-remote-path vec))
5489 result)
5490 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5491 ;; Check POSIX parameter.
5492 (when (tramp-send-command-and-check vec (format "%s -u" result))
5493 (throw 'id-found result))
5494 (setq dl (cdr dl))))))))
5496 (defun tramp-get-remote-uid-with-id (vec id-format)
5497 "Implement `tramp-get-remote-uid' for Tramp files using `id'."
5498 (tramp-send-command-and-read
5500 (format "%s -u%s %s"
5501 (tramp-get-remote-id vec)
5502 (if (equal id-format 'integer) "" "n")
5503 (if (equal id-format 'integer)
5504 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5506 (defun tramp-get-remote-uid-with-perl (vec id-format)
5507 "Implement `tramp-get-remote-uid' for Tramp files using a Perl script."
5508 (tramp-send-command-and-read
5510 (format "%s -le '%s'"
5511 (tramp-get-remote-perl vec)
5512 (if (equal id-format 'integer)
5513 "print $>"
5514 "print \"\\\"\", scalar getpwuid($>), \"\\\"\""))))
5516 (defun tramp-get-remote-python (vec)
5517 "Determine remote `python' command."
5518 (with-tramp-connection-property vec "python"
5519 (tramp-message vec 5 "Finding a suitable `python' command")
5520 (or (tramp-find-executable vec "python" (tramp-get-remote-path vec))
5521 (tramp-find-executable vec "python2" (tramp-get-remote-path vec))
5522 (tramp-find-executable vec "python3" (tramp-get-remote-path vec)))))
5524 (defun tramp-get-remote-uid-with-python (vec id-format)
5525 "Implement `tramp-get-remote-uid' for Tramp files using `python'."
5526 (tramp-send-command-and-read
5528 (format "%s -c \"%s\""
5529 (tramp-get-remote-python vec)
5530 (if (equal id-format 'integer)
5531 "import os; print (os.getuid())"
5532 "import os, pwd; print ('\\\"' + pwd.getpwuid(os.getuid())[0] + '\\\"')"))))
5534 (defun tramp-get-remote-uid (vec id-format)
5535 "The uid of the remote connection VEC, in ID-FORMAT.
5536 ID-FORMAT valid values are `string' and `integer'."
5537 (with-tramp-connection-property vec (format "uid-%s" id-format)
5538 (let ((res
5539 (ignore-errors
5540 (cond
5541 ((tramp-get-remote-id vec)
5542 (tramp-get-remote-uid-with-id vec id-format))
5543 ((tramp-get-remote-perl vec)
5544 (tramp-get-remote-uid-with-perl vec id-format))
5545 ((tramp-get-remote-python vec)
5546 (tramp-get-remote-uid-with-python vec id-format))))))
5547 ;; Ensure there is a valid result.
5548 (cond
5549 ((and (equal id-format 'integer) (not (integerp res)))
5550 tramp-unknown-id-integer)
5551 ((and (equal id-format 'string) (not (stringp res)))
5552 tramp-unknown-id-string)
5553 (t res)))))
5555 (defun tramp-get-remote-gid-with-id (vec id-format)
5556 "Implement `tramp-get-remote-gid' for Tramp files using `id'."
5557 (tramp-send-command-and-read
5559 (format "%s -g%s %s"
5560 (tramp-get-remote-id vec)
5561 (if (equal id-format 'integer) "" "n")
5562 (if (equal id-format 'integer)
5563 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5565 (defun tramp-get-remote-gid-with-perl (vec id-format)
5566 "Implement `tramp-get-remote-gid' for Tramp files using a Perl script."
5567 (tramp-send-command-and-read
5569 (format "%s -le '%s'"
5570 (tramp-get-remote-perl vec)
5571 (if (equal id-format 'integer)
5572 "print ($)=~/(\\d+)/)"
5573 "print \"\\\"\", scalar getgrgid($)), \"\\\"\""))))
5575 (defun tramp-get-remote-gid-with-python (vec id-format)
5576 "Implement `tramp-get-remote-gid' for Tramp files using `python'."
5577 (tramp-send-command-and-read
5579 (format "%s -c \"%s\""
5580 (tramp-get-remote-python vec)
5581 (if (equal id-format 'integer)
5582 "import os; print (os.getgid())"
5583 "import os, grp; print ('\\\"' + grp.getgrgid(os.getgid())[0] + '\\\"')"))))
5585 (defun tramp-get-remote-gid (vec id-format)
5586 "The gid of the remote connection VEC, in ID-FORMAT.
5587 ID-FORMAT valid values are `string' and `integer'."
5588 (with-tramp-connection-property vec (format "gid-%s" id-format)
5589 (let ((res
5590 (ignore-errors
5591 (cond
5592 ((tramp-get-remote-id vec)
5593 (tramp-get-remote-gid-with-id vec id-format))
5594 ((tramp-get-remote-perl vec)
5595 (tramp-get-remote-gid-with-perl vec id-format))
5596 ((tramp-get-remote-python vec)
5597 (tramp-get-remote-gid-with-python vec id-format))))))
5598 ;; Ensure there is a valid result.
5599 (cond
5600 ((and (equal id-format 'integer) (not (integerp res)))
5601 tramp-unknown-id-integer)
5602 ((and (equal id-format 'string) (not (stringp res)))
5603 tramp-unknown-id-string)
5604 (t res)))))
5606 (defun tramp-get-env-with-u-option (vec)
5607 "Check, whether the remote `env' command supports the -u option."
5608 (with-tramp-connection-property vec "env-u-option"
5609 (tramp-message vec 5 "Checking, whether `env -u' works")
5610 ;; Option "-u" is a GNU extension.
5611 (tramp-send-command-and-check
5612 vec "env FOO=foo env -u FOO 2>/dev/null | grep -qv FOO" t)))
5614 ;; Some predefined connection properties.
5615 (defun tramp-get-inline-compress (vec prop size)
5616 "Return the compress command related to PROP.
5617 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5618 the length of the file to be compressed.
5620 If no corresponding command is found, nil is returned."
5621 (when (and (integerp tramp-inline-compress-start-size)
5622 (> size tramp-inline-compress-start-size))
5623 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5624 (tramp-find-inline-compress vec)
5625 (tramp-get-connection-property
5626 (tramp-get-connection-process vec) prop nil))))
5628 (defun tramp-get-inline-coding (vec prop size)
5629 "Return the coding command related to PROP.
5630 PROP is either `remote-encoding', `remote-decoding',
5631 `local-encoding' or `local-decoding'.
5633 SIZE is the length of the file to be coded. Depending on SIZE,
5634 compression might be applied.
5636 If no corresponding command is found, nil is returned.
5637 Otherwise, either a string is returned which contains a `%s' mark
5638 to be used for the respective input or output file; or a Lisp
5639 function cell is returned to be applied on a buffer."
5640 ;; We must catch the errors, because we want to return nil, when
5641 ;; no inline coding is found.
5642 (ignore-errors
5643 (let ((coding
5644 (with-tramp-connection-property
5645 (tramp-get-connection-process vec) prop
5646 (tramp-find-inline-encoding vec)
5647 (tramp-get-connection-property
5648 (tramp-get-connection-process vec) prop nil)))
5649 (prop1 (if (string-match "encoding" prop)
5650 "inline-compress" "inline-decompress"))
5651 compress)
5652 ;; The connection property might have been cached. So we must
5653 ;; send the script to the remote side - maybe.
5654 (when (and coding (symbolp coding) (string-match "remote" prop))
5655 (let ((name (symbol-name coding)))
5656 (while (string-match (regexp-quote "-") name)
5657 (setq name (replace-match "_" nil t name)))
5658 (tramp-maybe-send-script vec (symbol-value coding) name)
5659 (setq coding name)))
5660 (when coding
5661 ;; Check for the `compress' command.
5662 (setq compress (tramp-get-inline-compress vec prop1 size))
5663 ;; Return the value.
5664 (cond
5665 ((and compress (symbolp coding))
5666 (if (string-match "decompress" prop1)
5667 `(lambda (beg end)
5668 (,coding beg end)
5669 (let ((coding-system-for-write 'binary)
5670 (coding-system-for-read 'binary))
5671 (apply
5672 'tramp-call-process-region ,vec (point-min) (point-max)
5673 (car (split-string ,compress)) t t nil
5674 (cdr (split-string ,compress)))))
5675 `(lambda (beg end)
5676 (let ((coding-system-for-write 'binary)
5677 (coding-system-for-read 'binary))
5678 (apply
5679 'tramp-call-process-region ,vec beg end
5680 (car (split-string ,compress)) t t nil
5681 (cdr (split-string ,compress))))
5682 (,coding (point-min) (point-max)))))
5683 ((symbolp coding)
5684 coding)
5685 ((and compress (string-match "decoding" prop))
5686 (format
5687 ;; Windows shells need the program file name after
5688 ;; the pipe symbol be quoted if they use forward
5689 ;; slashes as directory separators.
5690 (cond
5691 ((and (string-match "local" prop)
5692 (memq system-type '(windows-nt)))
5693 "(%s | \"%s\")")
5694 ((string-match "local" prop) "(%s | %s)")
5695 (t "(%s | %s >%%s)"))
5696 coding compress))
5697 (compress
5698 (format
5699 ;; Windows shells need the program file name after
5700 ;; the pipe symbol be quoted if they use forward
5701 ;; slashes as directory separators.
5702 (if (and (string-match "local" prop)
5703 (memq system-type '(windows-nt)))
5704 "(%s <%%s | \"%s\")"
5705 "(%s <%%s | %s)")
5706 compress coding))
5707 ((string-match "decoding" prop)
5708 (cond
5709 ((string-match "local" prop) (format "%s" coding))
5710 (t (format "%s >%%s" coding))))
5712 (format "%s <%%s" coding)))))))
5714 (add-hook 'tramp-unload-hook
5715 (lambda ()
5716 (unload-feature 'tramp-sh 'force)))
5718 (provide 'tramp-sh)
5720 ;;; TODO:
5722 ;; * Don't use globbing for directories with many files, as this is
5723 ;; likely to produce long command lines, and some shells choke on
5724 ;; long command lines.
5726 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5727 ;; then look if it's the right version (with `perl -v').
5729 ;; * When editing a remote CVS controlled file as a different user, VC
5730 ;; gets confused about the file locking status. Try to find out why
5731 ;; the workaround doesn't work.
5733 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5734 ;; until the last but one hop via `start-file-process'. Apply it
5735 ;; also for ftp and smb.
5737 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5738 ;; some shell with root privileges, it would be nice if I could
5739 ;; just call
5740 ;; trampclient filename.c
5741 ;; as an editor, and the _current_ shell would connect to an Emacs
5742 ;; server and would be used in an existing non-privileged Emacs
5743 ;; session for doing the editing in question.
5744 ;; That way, I need not tell Emacs my password again and be afraid
5745 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5746 ;; once display a just typed password in the context of a keyboard
5747 ;; sequence prompt for a question immediately following in a shell
5748 ;; script run within Emacs -- nasty).
5749 ;; And if I have some ssh session running to a different computer,
5750 ;; having the possibility of passing a local file there to a local
5751 ;; Emacs session (in case I can arrange for a connection back) would
5752 ;; be nice.
5753 ;; Likely the corresponding Tramp server should not allow the
5754 ;; equivalent of the emacsclient -eval option in order to make this
5755 ;; reasonably unproblematic. And maybe trampclient should have some
5756 ;; way of passing credentials, like by using an SSL socket or
5757 ;; something. (David Kastrup)
5759 ;; * Reconnect directly to a compliant shell without first going
5760 ;; through the user's default shell. (Pete Forman)
5762 ;; * How can I interrupt the remote process with a signal
5763 ;; (interrupt-process seems not to work)? (Markus Triska)
5765 ;; * Avoid the local shell entirely for starting remote processes. If
5766 ;; so, I think even a signal, when delivered directly to the local
5767 ;; SSH instance, would correctly be propagated to the remote process
5768 ;; automatically; possibly SSH would have to be started with
5769 ;; "-t". (Markus Triska)
5771 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5772 ;; isn't on the remote host. (Mark A. Hershberger)
5774 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5776 ;; * Optimize out-of-band copying when both methods are scp-like (not
5777 ;; rsync).
5779 ;; * Keep a second connection open for out-of-band methods like scp or
5780 ;; rsync.
5782 ;; * Implement completion for "/method:user@host:~<abc> TAB".
5784 ;; * I think you could get the best of both worlds by using an
5785 ;; approach similar to Tramp but running a little tramp-daemon on
5786 ;; the other end, such that we can use a more efficient
5787 ;; communication protocol (e.g. when saving a file we could locally
5788 ;; diff it against the last version (of which the remote daemon
5789 ;; would also keep a copy), and then only send the diff).
5791 ;; This said, even using such a daemon it might be difficult to get
5792 ;; good performance: part of the problem is the number of
5793 ;; round-trips. E.g. when saving a file we have to check if the
5794 ;; file was modified in the mean time and whether saving into a new
5795 ;; inode would change the owner (etc...), which each require a
5796 ;; round-trip. To get rid of these round-trips, we'd have to
5797 ;; shortcut this code and delegate the higher-level "save file"
5798 ;; operation to the remote server, which then has to perform those
5799 ;; tasks but still obeying the locally set customizations about how
5800 ;; to do each one of those tasks.
5802 ;; We could either put higher-level ops in there (like
5803 ;; `save-buffer'), which implies replicating the whole `save-buffer'
5804 ;; behavior, which is a lot of work and likely to be not 100%
5805 ;; faithful.
5807 ;; Or we could introduce new low-level ops that are asynchronous,
5808 ;; and then rewrite save-buffer to use them. IOW save-buffer would
5809 ;; start with a bunch of calls like `start-getting-file-attributes'
5810 ;; which could immediately be passed on to the remote side, and
5811 ;; later on checks the return value of those calls as and when
5812 ;; needed. (Stefan Monnier)
5814 ;;; tramp-sh.el ends here