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