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