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