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