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