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