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