Merge branch 'master' into comment-cache
[emacs.git] / lisp / net / tramp-sh.el
bloba3641c6c401d642ed4d53f4cede8e653beb52866
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 (invalid-read-syntax
1311 (when (and (equal (cadr err)
1312 "Integer constant overflow in reader")
1313 (string-match
1314 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
1315 (car (cddr err))))
1316 (let* ((big (read (substring (car (cddr err)) 0
1317 (match-beginning 1))))
1318 (small (read (match-string 1 (car (cddr err)))))
1319 (twiddle (/ small 65536)))
1320 (cons (+ big twiddle)
1321 (- small (* twiddle 65536))))))))
1322 ;; ... file mode flags
1323 (setq res-filemodes (symbol-name (read (current-buffer))))
1324 ;; ... number links
1325 (setq res-numlinks (read (current-buffer)))
1326 ;; ... uid and gid
1327 (setq res-uid (read (current-buffer)))
1328 (setq res-gid (read (current-buffer)))
1329 (if (eq id-format 'integer)
1330 (progn
1331 (unless (numberp res-uid)
1332 (setq res-uid tramp-unknown-id-integer))
1333 (unless (numberp res-gid)
1334 (setq res-gid tramp-unknown-id-integer)))
1335 (progn
1336 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
1337 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
1338 ;; ... size
1339 (setq res-size (read (current-buffer)))
1340 ;; From the file modes, figure out other stuff.
1341 (setq symlinkp (eq ?l (aref res-filemodes 0)))
1342 (setq dirp (eq ?d (aref res-filemodes 0)))
1343 ;; If symlink, find out file name pointed to.
1344 (when symlinkp
1345 (search-forward "-> ")
1346 (setq res-symlink-target
1347 (if (tramp-get-ls-command-with-quoting-style vec)
1348 (read (current-buffer))
1349 (buffer-substring (point) (point-at-eol)))))
1350 ;; Return data gathered.
1351 (list
1352 ;; 0. t for directory, string (name linked to) for symbolic
1353 ;; link, or nil.
1354 (or dirp res-symlink-target)
1355 ;; 1. Number of links to file.
1356 res-numlinks
1357 ;; 2. File uid.
1358 res-uid
1359 ;; 3. File gid.
1360 res-gid
1361 ;; 4. Last access time, as a list of integers. Normally
1362 ;; this would be in the same format as `current-time', but
1363 ;; the subseconds part is not currently implemented, and
1364 ;; (0 0) denotes an unknown time.
1365 ;; 5. Last modification time, likewise.
1366 ;; 6. Last status change time, likewise.
1367 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
1368 ;; 7. Size in bytes (-1, if number is out of range).
1369 res-size
1370 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
1371 res-filemodes
1372 ;; 9. t if file's gid would change if file were deleted and
1373 ;; recreated. Will be set in `tramp-convert-file-attributes'.
1375 ;; 10. Inode number.
1376 res-inode
1377 ;; 11. Device number. Will be replaced by a virtual device number.
1378 -1))))))
1380 (defun tramp-do-file-attributes-with-perl
1381 (vec localname &optional id-format)
1382 "Implement `file-attributes' for Tramp files using a Perl script."
1383 (tramp-message vec 5 "file attributes with perl: %s" localname)
1384 (tramp-maybe-send-script
1385 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
1386 (tramp-send-command-and-read
1388 (format "tramp_perl_file_attributes %s %s"
1389 (tramp-shell-quote-argument localname) id-format)))
1391 (defun tramp-do-file-attributes-with-stat
1392 (vec localname &optional id-format)
1393 "Implement `file-attributes' for Tramp files using stat(1) command."
1394 (tramp-message vec 5 "file attributes with stat: %s" localname)
1395 (tramp-send-command-and-read
1397 (format
1398 (concat
1399 ;; On Opsware, pdksh (which is the true name of ksh there)
1400 ;; doesn't parse correctly the sequence "((". Therefore, we add
1401 ;; a space. Apostrophes in the stat output are masked as
1402 ;; `tramp-stat-marker', in order to make a proper shell escape of
1403 ;; them in file names.
1404 "( (%s %s || %s -h %s) && (%s -c "
1405 "'((%s%%N%s) %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 %s%%A%s t %%ie0 -1)' "
1406 "%s | sed -e 's/\"/\\\\\"/g' -e 's/%s/\"/g') || echo nil)")
1407 (tramp-get-file-exists-command vec)
1408 (tramp-shell-quote-argument localname)
1409 (tramp-get-test-command vec)
1410 (tramp-shell-quote-argument localname)
1411 (tramp-get-remote-stat vec)
1412 tramp-stat-marker tramp-stat-marker
1413 (if (eq id-format 'integer)
1414 "%ue0" (concat tramp-stat-marker "%U" tramp-stat-marker))
1415 (if (eq id-format 'integer)
1416 "%ge0" (concat tramp-stat-marker "%G" tramp-stat-marker))
1417 tramp-stat-marker tramp-stat-marker
1418 (tramp-shell-quote-argument localname)
1419 tramp-stat-quoted-marker)))
1421 (defun tramp-sh-handle-set-visited-file-modtime (&optional time-list)
1422 "Like `set-visited-file-modtime' for Tramp files."
1423 (unless (buffer-file-name)
1424 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
1425 (buffer-name)))
1426 (if time-list
1427 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
1428 (let ((f (buffer-file-name))
1429 coding-system-used)
1430 (with-parsed-tramp-file-name f nil
1431 (let* ((remote-file-name-inhibit-cache t)
1432 (attr (file-attributes f))
1433 ;; '(-1 65535) means file doesn't exists yet.
1434 (modtime (or (tramp-compat-file-attribute-modification-time attr)
1435 '(-1 65535))))
1436 (setq coding-system-used last-coding-system-used)
1437 ;; We use '(0 0) as a don't-know value. See also
1438 ;; `tramp-do-file-attributes-with-ls'.
1439 (if (not (equal modtime '(0 0)))
1440 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
1441 (progn
1442 (tramp-send-command
1444 (format "%s -ild %s"
1445 (tramp-get-ls-command v)
1446 (tramp-shell-quote-argument localname)))
1447 (setq attr (buffer-substring (point) (point-at-eol))))
1448 (tramp-set-file-property
1449 v localname "visited-file-modtime-ild" attr))
1450 (setq last-coding-system-used coding-system-used)
1451 nil)))))
1453 ;; This function makes the same assumption as
1454 ;; `tramp-sh-handle-set-visited-file-modtime'.
1455 (defun tramp-sh-handle-verify-visited-file-modtime (&optional buf)
1456 "Like `verify-visited-file-modtime' for Tramp files.
1457 At the time `verify-visited-file-modtime' calls this function, we
1458 already know that the buffer is visiting a file and that
1459 `visited-file-modtime' does not return 0. Do not call this
1460 function directly, unless those two cases are already taken care
1461 of."
1462 (with-current-buffer (or buf (current-buffer))
1463 (let ((f (buffer-file-name)))
1464 ;; There is no file visiting the buffer, or the buffer has no
1465 ;; recorded last modification time, or there is no established
1466 ;; connection.
1467 (if (or (not f)
1468 (eq (visited-file-modtime) 0)
1469 (not (file-remote-p f nil 'connected)))
1471 (with-parsed-tramp-file-name f nil
1472 (let* ((remote-file-name-inhibit-cache t)
1473 (attr (file-attributes f))
1474 (modtime (tramp-compat-file-attribute-modification-time attr))
1475 (mt (visited-file-modtime)))
1477 (cond
1478 ;; File exists, and has a known modtime.
1479 ((and attr (not (equal modtime '(0 0))))
1480 (< (abs (tramp-time-diff
1481 modtime
1482 ;; For compatibility, deal with both the old
1483 ;; (HIGH . LOW) and the new (HIGH LOW) return
1484 ;; values of `visited-file-modtime'.
1485 (if (atom (cdr mt))
1486 (list (car mt) (cdr mt))
1487 mt)))
1489 ;; Modtime has the don't know value.
1490 (attr
1491 (tramp-send-command
1493 (format "%s -ild %s"
1494 (tramp-get-ls-command v)
1495 (tramp-shell-quote-argument localname)))
1496 (with-current-buffer (tramp-get-buffer v)
1497 (setq attr (buffer-substring (point) (point-at-eol))))
1498 (equal
1499 attr
1500 (tramp-get-file-property
1501 v localname "visited-file-modtime-ild" "")))
1502 ;; If file does not exist, say it is not modified if and
1503 ;; only if that agrees with the buffer's record.
1504 (t (equal mt '(-1 65535))))))))))
1506 (defun tramp-sh-handle-set-file-modes (filename mode)
1507 "Like `set-file-modes' for Tramp files."
1508 (with-parsed-tramp-file-name filename nil
1509 (tramp-flush-file-property v (file-name-directory localname))
1510 (tramp-flush-file-property v localname)
1511 ;; FIXME: extract the proper text from chmod's stderr.
1512 (tramp-barf-unless-okay
1514 (format "chmod %o %s" mode (tramp-shell-quote-argument localname))
1515 "Error while changing file's mode %s" filename)))
1517 (defun tramp-sh-handle-set-file-times (filename &optional time)
1518 "Like `set-file-times' for Tramp files."
1519 (with-parsed-tramp-file-name filename nil
1520 (when (tramp-get-remote-touch v)
1521 (tramp-flush-file-property v (file-name-directory localname))
1522 (tramp-flush-file-property v localname)
1523 (let ((time (if (or (null time) (equal time '(0 0)))
1524 (current-time)
1525 time)))
1526 (tramp-send-command-and-check
1527 v (format
1528 "env TZ=UTC %s %s %s"
1529 (tramp-get-remote-touch v)
1530 (if (tramp-get-connection-property v "touch-t" nil)
1531 (format "-t %s" (format-time-string "%Y%m%d%H%M.%S" time t))
1533 (tramp-shell-quote-argument localname)))))))
1535 (defun tramp-set-file-uid-gid (filename &optional uid gid)
1536 "Set the ownership for FILENAME.
1537 If UID and GID are provided, these values are used; otherwise uid
1538 and gid of the corresponding user is taken. Both parameters must
1539 be non-negative integers."
1540 ;; Modern Unices allow chown only for root. So we might need
1541 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
1542 ;; working with su(do)? when it is needed, so it shall succeed in
1543 ;; the majority of cases.
1544 ;; Don't modify `last-coding-system-used' by accident.
1545 (let ((last-coding-system-used last-coding-system-used))
1546 (if (tramp-tramp-file-p filename)
1547 (with-parsed-tramp-file-name filename nil
1548 (if (and (zerop (user-uid)) (tramp-local-host-p v))
1549 ;; If we are root on the local host, we can do it directly.
1550 (tramp-set-file-uid-gid localname uid gid)
1551 (let ((uid (or (and (natnump uid) uid)
1552 (tramp-get-remote-uid v 'integer)))
1553 (gid (or (and (natnump gid) gid)
1554 (tramp-get-remote-gid v 'integer))))
1555 (tramp-send-command
1556 v (format
1557 "chown %d:%d %s" uid gid
1558 (tramp-shell-quote-argument localname))))))
1560 ;; We handle also the local part, because there doesn't exist
1561 ;; `set-file-uid-gid'. On W32 "chown" might not work. We add a
1562 ;; timeout for this.
1563 (with-timeout (5 nil)
1564 (let ((uid (or (and (natnump uid) uid) (tramp-get-local-uid 'integer)))
1565 (gid (or (and (natnump gid) gid) (tramp-get-local-gid 'integer))))
1566 (tramp-call-process
1567 nil "chown" nil nil nil
1568 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename)))))))
1570 (defun tramp-remote-selinux-p (vec)
1571 "Check, whether SELINUX is enabled on the remote host."
1572 (with-tramp-connection-property (tramp-get-connection-process vec) "selinux-p"
1573 (tramp-send-command-and-check vec "selinuxenabled")))
1575 (defun tramp-sh-handle-file-selinux-context (filename)
1576 "Like `file-selinux-context' for Tramp files."
1577 (with-parsed-tramp-file-name filename nil
1578 (with-tramp-file-property v localname "file-selinux-context"
1579 (let ((context '(nil nil nil nil))
1580 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
1581 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
1582 (when (and (tramp-remote-selinux-p v)
1583 (tramp-send-command-and-check
1584 v (format
1585 "%s -d -Z %s"
1586 (tramp-get-ls-command v)
1587 (tramp-shell-quote-argument localname))))
1588 (with-current-buffer (tramp-get-connection-buffer v)
1589 (goto-char (point-min))
1590 (when (re-search-forward regexp (point-at-eol) t)
1591 (setq context (list (match-string 1) (match-string 2)
1592 (match-string 3) (match-string 4))))))
1593 ;; Return the context.
1594 context))))
1596 (defun tramp-sh-handle-set-file-selinux-context (filename context)
1597 "Like `set-file-selinux-context' for Tramp files."
1598 (with-parsed-tramp-file-name filename nil
1599 (when (and (consp context)
1600 (tramp-remote-selinux-p v))
1601 (let ((user (and (stringp (nth 0 context)) (nth 0 context)))
1602 (role (and (stringp (nth 1 context)) (nth 1 context)))
1603 (type (and (stringp (nth 2 context)) (nth 2 context)))
1604 (range (and (stringp (nth 3 context)) (nth 3 context))))
1605 (when (tramp-send-command-and-check
1606 v (format "chcon %s %s %s %s %s"
1607 (if user (format "--user=%s" user) "")
1608 (if role (format "--role=%s" role) "")
1609 (if type (format "--type=%s" type) "")
1610 (if range (format "--range=%s" range) "")
1611 (tramp-shell-quote-argument localname)))
1612 (if (and user role type range)
1613 (tramp-set-file-property
1614 v localname "file-selinux-context" context)
1615 (tramp-set-file-property
1616 v localname "file-selinux-context" 'undef))
1617 t)))))
1619 (defun tramp-remote-acl-p (vec)
1620 "Check, whether ACL is enabled on the remote host."
1621 (with-tramp-connection-property (tramp-get-connection-process vec) "acl-p"
1622 (tramp-send-command-and-check vec "getfacl /")))
1624 (defun tramp-sh-handle-file-acl (filename)
1625 "Like `file-acl' for Tramp files."
1626 (with-parsed-tramp-file-name filename nil
1627 (with-tramp-file-property v localname "file-acl"
1628 (when (and (tramp-remote-acl-p v)
1629 (tramp-send-command-and-check
1630 v (format
1631 "getfacl -ac %s"
1632 (tramp-shell-quote-argument localname))))
1633 (with-current-buffer (tramp-get-connection-buffer v)
1634 (goto-char (point-max))
1635 (delete-blank-lines)
1636 (when (> (point-max) (point-min))
1637 (substring-no-properties (buffer-string))))))))
1639 (defun tramp-sh-handle-set-file-acl (filename acl-string)
1640 "Like `set-file-acl' for Tramp files."
1641 (with-parsed-tramp-file-name (expand-file-name filename) nil
1642 (if (and (stringp acl-string) (tramp-remote-acl-p v)
1643 (progn
1644 (tramp-send-command
1645 v (format "setfacl --set-file=- %s <<'%s'\n%s\n%s\n"
1646 (tramp-shell-quote-argument localname)
1647 tramp-end-of-heredoc
1648 acl-string
1649 tramp-end-of-heredoc))
1650 (tramp-send-command-and-check v nil)))
1651 ;; Success.
1652 (progn
1653 (tramp-set-file-property v localname "file-acl" acl-string)
1655 ;; In case of errors, we return nil.
1656 (tramp-set-file-property v localname "file-acl-string" 'undef)
1657 nil)))
1659 ;; Simple functions using the `test' command.
1661 (defun tramp-sh-handle-file-executable-p (filename)
1662 "Like `file-executable-p' for Tramp files."
1663 (with-parsed-tramp-file-name filename nil
1664 (with-tramp-file-property v localname "file-executable-p"
1665 ;; Examine `file-attributes' cache to see if request can be
1666 ;; satisfied without remote operation.
1667 (or (tramp-check-cached-permissions v ?x)
1668 (tramp-run-test "-x" filename)))))
1670 (defun tramp-sh-handle-file-readable-p (filename)
1671 "Like `file-readable-p' for Tramp files."
1672 (with-parsed-tramp-file-name filename nil
1673 (with-tramp-file-property v localname "file-readable-p"
1674 ;; Examine `file-attributes' cache to see if request can be
1675 ;; satisfied without remote operation.
1676 (or (tramp-check-cached-permissions v ?r)
1677 (tramp-run-test "-r" filename)))))
1679 ;; When the remote shell is started, it looks for a shell which groks
1680 ;; tilde expansion. Here, we assume that all shells which grok tilde
1681 ;; expansion will also provide a `test' command which groks `-nt' (for
1682 ;; newer than). If this breaks, tell me about it and I'll try to do
1683 ;; something smarter about it.
1684 (defun tramp-sh-handle-file-newer-than-file-p (file1 file2)
1685 "Like `file-newer-than-file-p' for Tramp files."
1686 (cond ((not (file-exists-p file1))
1687 nil)
1688 ((not (file-exists-p file2))
1690 ;; We are sure both files exist at this point.
1692 (save-excursion
1693 ;; We try to get the mtime of both files. If they are not
1694 ;; equal to the "dont-know" value, then we subtract the times
1695 ;; and obtain the result.
1696 (let ((fa1 (file-attributes file1))
1697 (fa2 (file-attributes file2)))
1698 (if (and
1699 (not
1700 (equal (tramp-compat-file-attribute-modification-time fa1)
1701 '(0 0)))
1702 (not
1703 (equal (tramp-compat-file-attribute-modification-time fa2)
1704 '(0 0))))
1705 (> 0 (tramp-time-diff
1706 (tramp-compat-file-attribute-modification-time fa2)
1707 (tramp-compat-file-attribute-modification-time fa1)))
1708 ;; If one of them is the dont-know value, then we can
1709 ;; still try to run a shell command on the remote host.
1710 ;; However, this only works if both files are Tramp
1711 ;; files and both have the same method, same user, same
1712 ;; host.
1713 (unless (tramp-equal-remote file1 file2)
1714 (with-parsed-tramp-file-name
1715 (if (tramp-tramp-file-p file1) file1 file2) nil
1716 (tramp-error
1717 v 'file-error
1718 "Files %s and %s must have same method, user, host"
1719 file1 file2)))
1720 (with-parsed-tramp-file-name file1 nil
1721 (tramp-run-test2
1722 (tramp-get-test-nt-command v) file1 file2))))))))
1724 ;; Functions implemented using the basic functions above.
1726 (defun tramp-sh-handle-file-directory-p (filename)
1727 "Like `file-directory-p' for Tramp files."
1728 (with-parsed-tramp-file-name filename nil
1729 ;; `file-directory-p' is used as predicate for file name completion.
1730 ;; Sometimes, when a connection is not established yet, it is
1731 ;; desirable to return t immediately for "/method:foo:". It can
1732 ;; be expected that this is always a directory.
1733 (or (zerop (length localname))
1734 (with-tramp-file-property v localname "file-directory-p"
1735 (tramp-run-test "-d" filename)))))
1737 (defun tramp-sh-handle-file-writable-p (filename)
1738 "Like `file-writable-p' for Tramp files."
1739 (with-parsed-tramp-file-name filename nil
1740 (with-tramp-file-property v localname "file-writable-p"
1741 (if (file-exists-p filename)
1742 ;; Examine `file-attributes' cache to see if request can be
1743 ;; satisfied without remote operation.
1744 (or (tramp-check-cached-permissions v ?w)
1745 (tramp-run-test "-w" filename))
1746 ;; If file doesn't exist, check if directory is writable.
1747 (and (tramp-run-test "-d" (file-name-directory filename))
1748 (tramp-run-test "-w" (file-name-directory filename)))))))
1750 (defun tramp-sh-handle-file-ownership-preserved-p (filename &optional group)
1751 "Like `file-ownership-preserved-p' for Tramp files."
1752 (with-parsed-tramp-file-name filename nil
1753 (with-tramp-file-property v localname "file-ownership-preserved-p"
1754 (let ((attributes (file-attributes filename)))
1755 ;; Return t if the file doesn't exist, since it's true that no
1756 ;; information would be lost by an (attempted) delete and create.
1757 (or (null attributes)
1758 (and
1759 (= (tramp-compat-file-attribute-user-id attributes)
1760 (tramp-get-remote-uid v 'integer))
1761 (or (not group)
1762 (= (tramp-compat-file-attribute-group-id attributes)
1763 (tramp-get-remote-gid v 'integer)))))))))
1765 ;; Directory listings.
1767 (defun tramp-sh-handle-directory-files-and-attributes
1768 (directory &optional full match nosort id-format)
1769 "Like `directory-files-and-attributes' for Tramp files."
1770 (unless id-format (setq id-format 'integer))
1771 (when (file-directory-p directory)
1772 (setq directory (expand-file-name directory))
1773 (let* ((temp
1774 (copy-tree
1775 (with-parsed-tramp-file-name directory nil
1776 (with-tramp-file-property
1777 v localname
1778 (format "directory-files-and-attributes-%s" id-format)
1779 (save-excursion
1780 (mapcar
1781 (lambda (x)
1782 (cons (car x)
1783 (tramp-convert-file-attributes v (cdr x))))
1785 (cond
1786 ((tramp-get-remote-stat v)
1787 (tramp-do-directory-files-and-attributes-with-stat
1788 v localname id-format))
1789 ((tramp-get-remote-perl v)
1790 (tramp-do-directory-files-and-attributes-with-perl
1791 v localname id-format))
1792 (t nil)))))))))
1793 result item)
1795 (while temp
1796 (setq item (pop temp))
1797 (when (or (null match) (string-match match (car item)))
1798 (when full
1799 (setcar item (expand-file-name (car item) directory)))
1800 (push item result)))
1802 (or (if nosort
1803 result
1804 (sort result (lambda (x y) (string< (car x) (car y)))))
1805 ;; The scripts could fail, for example with huge file size.
1806 (tramp-handle-directory-files-and-attributes
1807 directory full match nosort id-format)))))
1809 (defun tramp-do-directory-files-and-attributes-with-perl
1810 (vec localname &optional id-format)
1811 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
1812 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
1813 (tramp-maybe-send-script
1814 vec tramp-perl-directory-files-and-attributes
1815 "tramp_perl_directory_files_and_attributes")
1816 (let ((object
1817 (tramp-send-command-and-read
1819 (format "tramp_perl_directory_files_and_attributes %s %s"
1820 (tramp-shell-quote-argument localname) id-format))))
1821 (when (stringp object) (tramp-error vec 'file-error object))
1822 object))
1824 (defun tramp-do-directory-files-and-attributes-with-stat
1825 (vec localname &optional id-format)
1826 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
1827 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
1828 (tramp-send-command-and-read
1830 (format
1831 (concat
1832 ;; We must care about file names with spaces, or starting with
1833 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
1834 ;; but it does not work on all remote systems. Apostrophes in
1835 ;; the stat output are masked as `tramp-stat-marker', in order to
1836 ;; make a proper shell escape of them in file names.
1837 "cd %s && echo \"(\"; (%s %s -a | "
1838 "xargs %s -c "
1839 "'(%s%%n%s (%s%%N%s) %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 %s%%A%s t %%ie0 -1)' "
1840 "-- 2>/dev/null | sed -e 's/\"/\\\\\"/g' -e 's/%s/\"/g'); echo \")\"")
1841 (tramp-shell-quote-argument localname)
1842 (tramp-get-ls-command vec)
1843 ;; On systems which have no quoting style, file names with special
1844 ;; characters could fail.
1845 (cond
1846 ((tramp-get-ls-command-with-quoting-style vec)
1847 "--quoting-style=shell")
1848 ((tramp-get-ls-command-with-w-option vec)
1849 "-w")
1850 (t ""))
1851 (tramp-get-remote-stat vec)
1852 tramp-stat-marker tramp-stat-marker
1853 tramp-stat-marker tramp-stat-marker
1854 (if (eq id-format 'integer)
1855 "%ue0" (concat tramp-stat-marker "%U" tramp-stat-marker))
1856 (if (eq id-format 'integer)
1857 "%ge0" (concat tramp-stat-marker "%G" tramp-stat-marker))
1858 tramp-stat-marker tramp-stat-marker
1859 tramp-stat-quoted-marker)))
1861 ;; This function should return "foo/" for directories and "bar" for
1862 ;; files.
1863 (defun tramp-sh-handle-file-name-all-completions (filename directory)
1864 "Like `file-name-all-completions' for Tramp files."
1865 (unless (save-match-data (string-match "/" filename))
1866 (all-completions
1867 filename
1868 (with-parsed-tramp-file-name (expand-file-name directory) nil
1869 (with-tramp-file-property v localname "file-name-all-completions"
1870 (let (result)
1871 ;; Get a list of directories and files, including reliably
1872 ;; tagging the directories with a trailing "/". Because I
1873 ;; rock. --daniel@danann.net
1874 (tramp-send-command
1876 (if (tramp-get-remote-perl v)
1877 (progn
1878 (tramp-maybe-send-script
1879 v tramp-perl-file-name-all-completions
1880 "tramp_perl_file_name_all_completions")
1881 (format "tramp_perl_file_name_all_completions %s"
1882 (tramp-shell-quote-argument localname)))
1884 (format (concat
1885 "(cd %s 2>&1 && %s -a 2>/dev/null"
1886 " | while IFS= read f; do"
1887 " if %s -d \"$f\" 2>/dev/null;"
1888 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
1889 " && \\echo ok) || \\echo fail")
1890 (tramp-shell-quote-argument localname)
1891 (tramp-get-ls-command v)
1892 (tramp-get-test-command v))))
1894 ;; Now grab the output.
1895 (with-current-buffer (tramp-get-buffer v)
1896 (goto-char (point-max))
1898 ;; Check result code, found in last line of output.
1899 (forward-line -1)
1900 (if (looking-at "^fail$")
1901 (progn
1902 ;; Grab error message from line before last line
1903 ;; (it was put there by `cd 2>&1').
1904 (forward-line -1)
1905 (tramp-error
1906 v 'file-error
1907 "tramp-sh-handle-file-name-all-completions: %s"
1908 (buffer-substring (point) (point-at-eol))))
1909 ;; For peace of mind, if buffer doesn't end in `fail'
1910 ;; then it should end in `ok'. If neither are in the
1911 ;; buffer something went seriously wrong on the remote
1912 ;; side.
1913 (unless (looking-at "^ok$")
1914 (tramp-error
1915 v 'file-error "\
1916 tramp-sh-handle-file-name-all-completions: internal error accessing `%s': `%s'"
1917 (tramp-shell-quote-argument localname) (buffer-string))))
1919 (while (zerop (forward-line -1))
1920 (push (buffer-substring (point) (point-at-eol)) result)))
1921 result))))))
1923 ;; cp, mv and ln
1925 (defun tramp-sh-handle-add-name-to-file
1926 (filename newname &optional ok-if-already-exists)
1927 "Like `add-name-to-file' for Tramp files."
1928 (unless (tramp-equal-remote filename newname)
1929 (with-parsed-tramp-file-name
1930 (if (tramp-tramp-file-p filename) filename newname) nil
1931 (tramp-error
1932 v 'file-error
1933 "add-name-to-file: %s"
1934 "only implemented for same method, same user, same host")))
1935 (with-parsed-tramp-file-name filename v1
1936 (with-parsed-tramp-file-name newname v2
1937 (let ((ln (when v1 (tramp-get-remote-ln v1))))
1938 (when (and (numberp ok-if-already-exists)
1939 (file-exists-p newname)
1940 (yes-or-no-p
1941 (format
1942 "File %s already exists; make it a new name anyway? "
1943 newname)))
1944 (tramp-error
1945 v2 'file-already-exists
1946 "add-name-to-file: file %s already exists" newname))
1947 (when ok-if-already-exists (setq ln (concat ln " -f")))
1948 (tramp-flush-file-property v2 (file-name-directory v2-localname))
1949 (tramp-flush-file-property v2 v2-localname)
1950 (tramp-barf-unless-okay
1952 (format "%s %s %s" ln
1953 (tramp-shell-quote-argument v1-localname)
1954 (tramp-shell-quote-argument v2-localname))
1955 "error with add-name-to-file, see buffer `%s' for details"
1956 (buffer-name))))))
1958 (defun tramp-sh-handle-copy-file
1959 (filename newname &optional ok-if-already-exists keep-date
1960 preserve-uid-gid preserve-extended-attributes)
1961 "Like `copy-file' for Tramp files."
1962 (setq filename (expand-file-name filename))
1963 (setq newname (expand-file-name newname))
1964 (cond
1965 ;; At least one file a Tramp file?
1966 ((or (tramp-tramp-file-p filename)
1967 (tramp-tramp-file-p newname))
1968 (tramp-do-copy-or-rename-file
1969 'copy filename newname ok-if-already-exists keep-date
1970 preserve-uid-gid preserve-extended-attributes))
1971 ;; Compat section. PRESERVE-EXTENDED-ATTRIBUTES has been
1972 ;; introduced with Emacs 24.1 (as PRESERVE-SELINUX-CONTEXT), and
1973 ;; renamed in Emacs 24.3.
1974 (preserve-extended-attributes
1975 (tramp-run-real-handler
1976 'copy-file
1977 (list filename newname ok-if-already-exists keep-date
1978 preserve-uid-gid preserve-extended-attributes)))
1980 (tramp-run-real-handler
1981 'copy-file
1982 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))))
1984 (defun tramp-sh-handle-copy-directory
1985 (dirname newname &optional keep-date parents copy-contents)
1986 "Like `copy-directory' for Tramp files."
1987 (let ((t1 (tramp-tramp-file-p dirname))
1988 (t2 (tramp-tramp-file-p newname)))
1989 (with-parsed-tramp-file-name (if t1 dirname newname) nil
1990 (if (and (not copy-contents)
1991 (tramp-get-method-parameter v 'tramp-copy-recursive)
1992 ;; When DIRNAME and NEWNAME are remote, they must have
1993 ;; the same method.
1994 (or (null t1) (null t2)
1995 (string-equal
1996 (tramp-file-name-method (tramp-dissect-file-name dirname))
1997 (tramp-file-name-method
1998 (tramp-dissect-file-name newname)))))
1999 ;; scp or rsync DTRT.
2000 (progn
2001 (setq dirname (directory-file-name (expand-file-name dirname))
2002 newname (directory-file-name (expand-file-name newname)))
2003 (if (and (file-directory-p newname)
2004 (not (string-equal (file-name-nondirectory dirname)
2005 (file-name-nondirectory newname))))
2006 (setq newname
2007 (expand-file-name
2008 (file-name-nondirectory dirname) newname)))
2009 (if (not (file-directory-p (file-name-directory newname)))
2010 (make-directory (file-name-directory newname) parents))
2011 (tramp-do-copy-or-rename-file-out-of-band
2012 'copy dirname newname keep-date))
2013 ;; We must do it file-wise.
2014 (tramp-run-real-handler
2015 'copy-directory
2016 (if copy-contents
2017 (list dirname newname keep-date parents copy-contents)
2018 (list dirname newname keep-date parents))))
2020 ;; When newname did exist, we have wrong cached values.
2021 (when t2
2022 (with-parsed-tramp-file-name newname nil
2023 (tramp-flush-file-property v (file-name-directory localname))
2024 (tramp-flush-file-property v localname))))))
2026 (defun tramp-sh-handle-rename-file
2027 (filename newname &optional ok-if-already-exists)
2028 "Like `rename-file' for Tramp files."
2029 ;; Check if both files are local -- invoke normal rename-file.
2030 ;; Otherwise, use Tramp from local system.
2031 (setq filename (expand-file-name filename))
2032 (setq newname (expand-file-name newname))
2033 ;; At least one file a Tramp file?
2034 (if (or (tramp-tramp-file-p filename)
2035 (tramp-tramp-file-p newname))
2036 (tramp-do-copy-or-rename-file
2037 'rename filename newname ok-if-already-exists
2038 'keep-time 'preserve-uid-gid)
2039 (tramp-run-real-handler
2040 'rename-file (list filename newname ok-if-already-exists))))
2042 (defun tramp-do-copy-or-rename-file
2043 (op filename newname &optional ok-if-already-exists keep-date
2044 preserve-uid-gid preserve-extended-attributes)
2045 "Copy or rename a remote file.
2046 OP must be `copy' or `rename' and indicates the operation to perform.
2047 FILENAME specifies the file to copy or rename, NEWNAME is the name of
2048 the new file (for copy) or the new name of the file (for rename).
2049 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
2050 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2051 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2052 the uid and gid if both files are on the same host.
2053 PRESERVE-EXTENDED-ATTRIBUTES activates selinux and acl commands.
2055 This function is invoked by `tramp-sh-handle-copy-file' and
2056 `tramp-sh-handle-rename-file'. It is an error if OP is neither
2057 of `copy' and `rename'. FILENAME and NEWNAME must be absolute
2058 file names."
2059 (unless (memq op '(copy rename))
2060 (error "Unknown operation `%s', must be `copy' or `rename'" op))
2061 (let ((t1 (tramp-tramp-file-p filename))
2062 (t2 (tramp-tramp-file-p newname))
2063 (length (tramp-compat-file-attribute-size
2064 (file-attributes (file-truename filename))))
2065 (attributes (and preserve-extended-attributes
2066 (apply 'file-extended-attributes (list filename)))))
2068 (with-parsed-tramp-file-name (if t1 filename newname) nil
2069 (when (and (not ok-if-already-exists) (file-exists-p newname))
2070 (tramp-error
2071 v 'file-already-exists "File %s already exists" newname))
2073 (with-tramp-progress-reporter
2074 v 0 (format "%s %s to %s"
2075 (if (eq op 'copy) "Copying" "Renaming")
2076 filename newname)
2078 (cond
2079 ;; Both are Tramp files.
2080 ((and t1 t2)
2081 (with-parsed-tramp-file-name filename v1
2082 (with-parsed-tramp-file-name newname v2
2083 (cond
2084 ;; Shortcut: if method, host, user are the same for
2085 ;; both files, we invoke `cp' or `mv' on the remote
2086 ;; host directly.
2087 ((tramp-equal-remote filename newname)
2088 (tramp-do-copy-or-rename-file-directly
2089 op filename newname
2090 ok-if-already-exists keep-date preserve-uid-gid))
2092 ;; Try out-of-band operation.
2093 ((and
2094 (tramp-method-out-of-band-p v1 length)
2095 (tramp-method-out-of-band-p v2 length))
2096 (tramp-do-copy-or-rename-file-out-of-band
2097 op filename newname keep-date))
2099 ;; No shortcut was possible. So we copy the file
2100 ;; first. If the operation was `rename', we go back
2101 ;; and delete the original file (if the copy was
2102 ;; successful). The approach is simple-minded: we
2103 ;; create a new buffer, insert the contents of the
2104 ;; source file into it, then write out the buffer to
2105 ;; the target file. The advantage is that it doesn't
2106 ;; matter which file name handlers are used for the
2107 ;; source and target file.
2109 (tramp-do-copy-or-rename-file-via-buffer
2110 op filename newname keep-date))))))
2112 ;; One file is a Tramp file, the other one is local.
2113 ((or t1 t2)
2114 (cond
2115 ;; Fast track on local machine.
2116 ((tramp-local-host-p v)
2117 (tramp-do-copy-or-rename-file-directly
2118 op filename newname
2119 ok-if-already-exists keep-date preserve-uid-gid))
2121 ;; If the Tramp file has an out-of-band method, the
2122 ;; corresponding copy-program can be invoked.
2123 ((tramp-method-out-of-band-p v length)
2124 (tramp-do-copy-or-rename-file-out-of-band
2125 op filename newname keep-date))
2127 ;; Use the inline method via a Tramp buffer.
2128 (t (tramp-do-copy-or-rename-file-via-buffer
2129 op filename newname keep-date))))
2132 ;; One of them must be a Tramp file.
2133 (error "Tramp implementation says this cannot happen")))
2135 ;; Handle `preserve-extended-attributes'. We ignore possible
2136 ;; errors, because ACL strings could be incompatible.
2137 (when attributes
2138 (ignore-errors
2139 (apply 'set-file-extended-attributes (list newname attributes))))
2141 ;; In case of `rename', we must flush the cache of the source file.
2142 (when (and t1 (eq op 'rename))
2143 (with-parsed-tramp-file-name filename v1
2144 (tramp-flush-file-property v1 (file-name-directory v1-localname))
2145 (tramp-flush-file-property v1 v1-localname)))
2147 ;; When newname did exist, we have wrong cached values.
2148 (when t2
2149 (with-parsed-tramp-file-name newname v2
2150 (tramp-flush-file-property v2 (file-name-directory v2-localname))
2151 (tramp-flush-file-property v2 v2-localname)))))))
2153 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
2154 "Use an Emacs buffer to copy or rename a file.
2155 First arg OP is either `copy' or `rename' and indicates the operation.
2156 FILENAME is the source file, NEWNAME the target file.
2157 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
2158 ;; We must disable multibyte, because binary data shall not be
2159 ;; converted. We don't want the target file to be compressed, so we
2160 ;; let-bind `jka-compr-inhibit' to t. `epa-file-handler' shall not
2161 ;; be called either. We remove `tramp-file-name-handler' from
2162 ;; `inhibit-file-name-handlers'; otherwise the file name handler for
2163 ;; `insert-file-contents' might be deactivated in some corner cases.
2164 (let ((coding-system-for-read 'binary)
2165 (coding-system-for-write 'binary)
2166 (jka-compr-inhibit t)
2167 (inhibit-file-name-operation 'write-region)
2168 (inhibit-file-name-handlers
2169 (cons 'epa-file-handler
2170 (remq 'tramp-file-name-handler inhibit-file-name-handlers))))
2171 (with-temp-file newname
2172 (set-buffer-multibyte nil)
2173 (insert-file-contents-literally filename)))
2174 ;; KEEP-DATE handling.
2175 (when keep-date
2176 (set-file-times
2177 newname
2178 (tramp-compat-file-attribute-modification-time
2179 (file-attributes filename))))
2180 ;; Set the mode.
2181 (set-file-modes newname (tramp-default-file-modes filename))
2182 ;; If the operation was `rename', delete the original file.
2183 (unless (eq op 'copy) (delete-file filename)))
2185 (defun tramp-do-copy-or-rename-file-directly
2186 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
2187 "Invokes `cp' or `mv' on the remote system.
2188 OP must be one of `copy' or `rename', indicating `cp' or `mv',
2189 respectively. FILENAME specifies the file to copy or rename,
2190 NEWNAME is the name of the new file (for copy) or the new name of
2191 the file (for rename). Both files must reside on the same host.
2192 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2193 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2194 the uid and gid from FILENAME."
2195 (let ((t1 (tramp-tramp-file-p filename))
2196 (t2 (tramp-tramp-file-p newname))
2197 (file-times (tramp-compat-file-attribute-modification-time
2198 (file-attributes filename)))
2199 (file-modes (tramp-default-file-modes filename)))
2200 (with-parsed-tramp-file-name (if t1 filename newname) nil
2201 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
2202 ((eq op 'copy) "cp -f")
2203 ((eq op 'rename) "mv -f")
2204 (t (tramp-error
2205 v 'file-error
2206 "Unknown operation `%s', must be `copy' or `rename'"
2207 op))))
2208 (localname1 (if t1 (file-remote-p filename 'localname) filename))
2209 (localname2 (if t2 (file-remote-p newname 'localname) newname))
2210 (prefix (file-remote-p (if t1 filename newname)))
2211 cmd-result)
2213 (cond
2214 ;; Both files are on a remote host, with same user.
2215 ((and t1 t2)
2216 (setq cmd-result
2217 (tramp-send-command-and-check
2218 v (format "%s %s %s" cmd
2219 (tramp-shell-quote-argument localname1)
2220 (tramp-shell-quote-argument localname2))))
2221 (with-current-buffer (tramp-get-buffer v)
2222 (goto-char (point-min))
2223 (unless
2225 (and keep-date
2226 ;; Mask cp -f error.
2227 (re-search-forward
2228 tramp-operation-not-permitted-regexp nil t))
2229 cmd-result)
2230 (tramp-error-with-buffer
2231 nil v 'file-error
2232 "Copying directly failed, see buffer `%s' for details."
2233 (buffer-name)))))
2235 ;; We are on the local host.
2236 ((or t1 t2)
2237 (cond
2238 ;; We can do it directly.
2239 ((let (file-name-handler-alist)
2240 (and (file-readable-p localname1)
2241 ;; No sticky bit when renaming.
2242 (or (eq op 'copy)
2243 (zerop
2244 (logand
2245 (file-modes (file-name-directory localname1))
2246 (string-to-number "1000" 8))))
2247 (file-writable-p (file-name-directory localname2))
2248 (or (file-directory-p localname2)
2249 (file-writable-p localname2))))
2250 (if (eq op 'copy)
2251 (copy-file
2252 localname1 localname2 ok-if-already-exists
2253 keep-date preserve-uid-gid)
2254 (tramp-run-real-handler
2255 'rename-file (list localname1 localname2 ok-if-already-exists))))
2257 ;; We can do it directly with `tramp-send-command'
2258 ((and (file-readable-p (concat prefix localname1))
2259 (file-writable-p
2260 (file-name-directory (concat prefix localname2)))
2261 (or (file-directory-p (concat prefix localname2))
2262 (file-writable-p (concat prefix localname2))))
2263 (tramp-do-copy-or-rename-file-directly
2264 op (concat prefix localname1) (concat prefix localname2)
2265 ok-if-already-exists keep-date t)
2266 ;; We must change the ownership to the local user.
2267 (tramp-set-file-uid-gid
2268 (concat prefix localname2)
2269 (tramp-get-local-uid 'integer)
2270 (tramp-get-local-gid 'integer)))
2272 ;; We need a temporary file in between.
2274 ;; Create the temporary file.
2275 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
2276 (unwind-protect
2277 (progn
2278 (cond
2280 (tramp-barf-unless-okay
2281 v (format
2282 "%s %s %s" cmd
2283 (tramp-shell-quote-argument localname1)
2284 (tramp-shell-quote-argument tmpfile))
2285 "Copying directly failed, see buffer `%s' for details."
2286 (tramp-get-buffer v))
2287 ;; We must change the ownership as remote user.
2288 ;; Since this does not work reliable, we also
2289 ;; give read permissions.
2290 (set-file-modes
2291 (concat prefix tmpfile) (string-to-number "0777" 8))
2292 (tramp-set-file-uid-gid
2293 (concat prefix tmpfile)
2294 (tramp-get-local-uid 'integer)
2295 (tramp-get-local-gid 'integer)))
2297 (if (eq op 'copy)
2298 (copy-file
2299 localname1 tmpfile t keep-date preserve-uid-gid)
2300 (tramp-run-real-handler
2301 'rename-file (list localname1 tmpfile t)))
2302 ;; We must change the ownership as local user.
2303 ;; Since this does not work reliable, we also
2304 ;; give read permissions.
2305 (set-file-modes tmpfile (string-to-number "0777" 8))
2306 (tramp-set-file-uid-gid
2307 tmpfile
2308 (tramp-get-remote-uid v 'integer)
2309 (tramp-get-remote-gid v 'integer))))
2311 ;; Move the temporary file to its destination.
2312 (cond
2314 (tramp-barf-unless-okay
2315 v (format
2316 "cp -f -p %s %s"
2317 (tramp-shell-quote-argument tmpfile)
2318 (tramp-shell-quote-argument localname2))
2319 "Copying directly failed, see buffer `%s' for details."
2320 (tramp-get-buffer v)))
2322 (tramp-run-real-handler
2323 'rename-file
2324 (list tmpfile localname2 ok-if-already-exists)))))
2326 ;; Save exit.
2327 (ignore-errors (delete-file tmpfile)))))))))
2329 ;; Set the time and mode. Mask possible errors.
2330 (ignore-errors
2331 (when keep-date
2332 (set-file-times newname file-times)
2333 (set-file-modes newname file-modes))))))
2335 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
2336 "Invoke `scp' program to copy.
2337 The method used must be an out-of-band method."
2338 (let* ((t1 (tramp-tramp-file-p filename))
2339 (t2 (tramp-tramp-file-p newname))
2340 (orig-vec (tramp-dissect-file-name (if t1 filename newname)))
2341 copy-program copy-args copy-env copy-keep-date port listener spec
2342 options source target remote-copy-program remote-copy-args)
2344 (with-parsed-tramp-file-name (if t1 filename newname) nil
2345 (if (and t1 t2)
2347 ;; Both are Tramp files. We shall optimize it when the
2348 ;; methods for FILENAME and NEWNAME are the same.
2349 (let* ((dir-flag (file-directory-p filename))
2350 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
2351 (if dir-flag
2352 (setq tmpfile
2353 (expand-file-name
2354 (file-name-nondirectory newname) tmpfile)))
2355 (unwind-protect
2356 (progn
2357 (tramp-do-copy-or-rename-file-out-of-band
2358 op filename tmpfile keep-date)
2359 (tramp-do-copy-or-rename-file-out-of-band
2360 'rename tmpfile newname keep-date))
2361 ;; Save exit.
2362 (ignore-errors
2363 (if dir-flag
2364 (delete-directory
2365 (expand-file-name ".." tmpfile) 'recursive)
2366 (delete-file tmpfile)))))
2368 ;; Set variables for computing the prompt for reading
2369 ;; password.
2370 (setq tramp-current-method (tramp-file-name-method v)
2371 tramp-current-user (or (tramp-file-name-user v)
2372 (tramp-get-connection-property
2373 v "login-as" nil))
2374 tramp-current-host (tramp-file-name-real-host v))
2376 ;; Check which ones of source and target are Tramp files.
2377 (setq source (funcall
2378 (if (and (file-directory-p filename)
2379 (not (file-exists-p newname)))
2380 'file-name-as-directory
2381 'identity)
2382 (if t1
2383 (tramp-make-copy-program-file-name v)
2384 (tramp-unquote-shell-quote-argument filename)))
2385 target (if t2
2386 (tramp-make-copy-program-file-name v)
2387 (tramp-unquote-shell-quote-argument newname)))
2389 ;; Check for host and port number.
2390 (setq host (tramp-file-name-real-host v)
2391 port (tramp-file-name-port v))
2393 ;; Check for user. There might be an interactive setting.
2394 (setq user (or (tramp-file-name-user v)
2395 (tramp-get-connection-property v "login-as" nil)))
2397 ;; Check for listener port.
2398 (when (tramp-get-method-parameter v 'tramp-remote-copy-args)
2399 (setq listener (number-to-string (+ 50000 (random 10000))))
2400 (while
2401 (zerop (tramp-call-process v "nc" nil nil nil "-z" host listener))
2402 (setq listener (number-to-string (+ 50000 (random 10000))))))
2404 ;; Compose copy command.
2405 (setq host (or host "")
2406 user (or user "")
2407 port (or port "")
2408 spec (format-spec-make
2409 ?t (tramp-get-connection-property
2410 (tramp-get-connection-process v) "temp-file" ""))
2411 options (format-spec (tramp-ssh-controlmaster-options v) spec)
2412 spec (format-spec-make
2413 ?h host ?u user ?p port ?r listener ?c options
2414 ?k (if keep-date " " ""))
2415 copy-program (tramp-get-method-parameter v 'tramp-copy-program)
2416 copy-keep-date (tramp-get-method-parameter
2417 v 'tramp-copy-keep-date)
2419 copy-args
2420 (delete
2421 ;; " " has either been a replacement of "%k" (when
2422 ;; keep-date argument is non-nil), or a replacement
2423 ;; for the whole keep-date sublist.
2425 (dolist
2426 (x (tramp-get-method-parameter v 'tramp-copy-args) copy-args)
2427 (setq copy-args
2428 (append
2429 copy-args
2430 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2431 (if (member "" y) '(" ") y))))))
2433 copy-env
2434 (delq
2436 (mapcar
2437 (lambda (x)
2438 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
2439 (unless (member "" x) (mapconcat 'identity x " ")))
2440 (tramp-get-method-parameter v 'tramp-copy-env)))
2442 remote-copy-program
2443 (tramp-get-method-parameter v 'tramp-remote-copy-program))
2445 (dolist (x (tramp-get-method-parameter v 'tramp-remote-copy-args))
2446 (setq remote-copy-args
2447 (append
2448 remote-copy-args
2449 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2450 (if (member "" y) '(" ") y)))))
2452 ;; Check for local copy program.
2453 (unless (executable-find copy-program)
2454 (tramp-error
2455 v 'file-error "Cannot find local copy program: %s" copy-program))
2457 ;; Install listener on the remote side. The prompt must be
2458 ;; consumed later on, when the process does not listen anymore.
2459 (when remote-copy-program
2460 (unless (with-tramp-connection-property
2461 v (concat "remote-copy-program-" remote-copy-program)
2462 (tramp-find-executable
2463 v remote-copy-program (tramp-get-remote-path v)))
2464 (tramp-error
2465 v 'file-error
2466 "Cannot find remote listener: %s" remote-copy-program))
2467 (setq remote-copy-program
2468 (mapconcat
2469 'identity
2470 (append
2471 (list remote-copy-program) remote-copy-args
2472 (list (if t1 (concat "<" source) (concat ">" target)) "&"))
2473 " "))
2474 (tramp-send-command v remote-copy-program)
2475 (with-timeout
2476 (60 (tramp-error
2477 v 'file-error
2478 "Listener process not running on remote host: `%s'"
2479 remote-copy-program))
2480 (tramp-send-command v (format "netstat -l | grep -q :%s" listener))
2481 (while (not (tramp-send-command-and-check v nil))
2482 (tramp-send-command
2483 v (format "netstat -l | grep -q :%s" listener)))))
2485 (with-temp-buffer
2486 (unwind-protect
2487 ;; The default directory must be remote.
2488 (let ((default-directory
2489 (file-name-directory (if t1 filename newname)))
2490 (process-environment (copy-sequence process-environment)))
2491 ;; Set the transfer process properties.
2492 (tramp-set-connection-property
2493 v "process-name" (buffer-name (current-buffer)))
2494 (tramp-set-connection-property
2495 v "process-buffer" (current-buffer))
2496 (while copy-env
2497 (tramp-message
2498 orig-vec 6 "%s=\"%s\"" (car copy-env) (cadr copy-env))
2499 (setenv (pop copy-env) (pop copy-env)))
2500 (setq
2501 copy-args
2502 (append
2503 copy-args
2504 (if remote-copy-program
2505 (list (if t1 (concat ">" target) (concat "<" source)))
2506 (list source target))))
2508 ;; Use an asynchronous process. By this, password can
2509 ;; be handled. We don't set a timeout, because the
2510 ;; copying of large files can last longer than 60 secs.
2511 (let* ((command
2512 (mapconcat
2513 'identity (append (list copy-program) copy-args)
2514 " "))
2515 (p (let ((default-directory
2516 (tramp-compat-temporary-file-directory)))
2517 (start-process-shell-command
2518 (tramp-get-connection-name v)
2519 (tramp-get-connection-buffer v)
2520 command))))
2521 (tramp-message orig-vec 6 "%s" command)
2522 (tramp-set-connection-property p "vector" orig-vec)
2523 (set-process-query-on-exit-flag p nil)
2525 ;; We must adapt `tramp-local-end-of-line' for
2526 ;; sending the password.
2527 (let ((tramp-local-end-of-line tramp-rsh-end-of-line))
2528 (tramp-process-actions
2529 p v nil tramp-actions-copy-out-of-band))))
2531 ;; Reset the transfer process properties.
2532 (tramp-set-connection-property v "process-name" nil)
2533 (tramp-set-connection-property v "process-buffer" nil)
2534 ;; Clear the remote prompt.
2535 (when (and remote-copy-program
2536 (not (tramp-send-command-and-check v nil)))
2537 ;; Houston, we have a problem! Likely, the listener is
2538 ;; still running, so let's clear everything (but the
2539 ;; cached password).
2540 (tramp-cleanup-connection v 'keep-debug 'keep-password))))
2542 ;; Handle KEEP-DATE argument.
2543 (when (and keep-date (not copy-keep-date))
2544 (set-file-times
2545 newname
2546 (tramp-compat-file-attribute-modification-time
2547 (file-attributes filename))))
2549 ;; Set the mode.
2550 (unless (and keep-date copy-keep-date)
2551 (ignore-errors
2552 (set-file-modes newname (tramp-default-file-modes filename)))))
2554 ;; If the operation was `rename', delete the original file.
2555 (unless (eq op 'copy)
2556 (if (file-regular-p filename)
2557 (delete-file filename)
2558 (delete-directory filename 'recursive))))))
2560 (defun tramp-sh-handle-make-directory (dir &optional parents)
2561 "Like `make-directory' for Tramp files."
2562 (setq dir (expand-file-name dir))
2563 (with-parsed-tramp-file-name dir nil
2564 (tramp-flush-directory-property v (file-name-directory localname))
2565 (save-excursion
2566 (tramp-barf-unless-okay
2567 v (format "%s %s"
2568 (if parents "mkdir -p" "mkdir")
2569 (tramp-shell-quote-argument localname))
2570 "Couldn't make directory %s" dir))))
2572 (defun tramp-sh-handle-delete-directory (directory &optional recursive)
2573 "Like `delete-directory' for Tramp files."
2574 (setq directory (expand-file-name directory))
2575 (with-parsed-tramp-file-name directory nil
2576 (tramp-flush-file-property v (file-name-directory localname))
2577 (tramp-flush-directory-property v localname)
2578 (tramp-barf-unless-okay
2579 v (format "cd / && %s %s"
2580 (if recursive "rm -rf" "rmdir")
2581 (tramp-shell-quote-argument localname))
2582 "Couldn't delete %s" directory)))
2584 (defun tramp-sh-handle-delete-file (filename &optional trash)
2585 "Like `delete-file' for Tramp files."
2586 (setq filename (expand-file-name filename))
2587 (with-parsed-tramp-file-name filename nil
2588 (tramp-flush-file-property v (file-name-directory localname))
2589 (tramp-flush-file-property v localname)
2590 (tramp-barf-unless-okay
2591 v (format "%s %s"
2592 (or (and trash (tramp-get-remote-trash v)) "rm -f")
2593 (tramp-shell-quote-argument localname))
2594 "Couldn't delete %s" filename)))
2596 ;; Dired.
2598 (defvar dired-compress-file-suffixes)
2599 (declare-function dired-remove-file "dired-aux")
2601 (defun tramp-sh-handle-dired-compress-file (file)
2602 "Like `dired-compress-file' for Tramp files."
2603 ;; Code stolen mainly from dired-aux.el.
2604 (with-parsed-tramp-file-name file nil
2605 (tramp-flush-file-property v localname)
2606 (save-excursion
2607 (let ((suffixes dired-compress-file-suffixes)
2608 suffix)
2609 ;; See if any suffix rule matches this file name.
2610 (while suffixes
2611 (let (case-fold-search)
2612 (if (string-match (car (car suffixes)) localname)
2613 (setq suffix (car suffixes) suffixes nil))
2614 (setq suffixes (cdr suffixes))))
2616 (cond ((file-symlink-p file)
2617 nil)
2618 ((and suffix (nth 2 suffix))
2619 ;; We found an uncompression rule.
2620 (with-tramp-progress-reporter
2621 v 0 (format "Uncompressing %s" file)
2622 (when (tramp-send-command-and-check
2623 v (concat (nth 2 suffix) " "
2624 (tramp-shell-quote-argument localname)))
2625 (dired-remove-file file)
2626 (string-match (car suffix) file)
2627 (concat (substring file 0 (match-beginning 0))))))
2629 ;; We don't recognize the file as compressed, so compress it.
2630 ;; Try gzip.
2631 (with-tramp-progress-reporter v 0 (format "Compressing %s" file)
2632 (when (tramp-send-command-and-check
2633 v (concat "gzip -f "
2634 (tramp-shell-quote-argument localname)))
2635 (dired-remove-file file)
2636 (cond ((file-exists-p (concat file ".gz"))
2637 (concat file ".gz"))
2638 ((file-exists-p (concat file ".z"))
2639 (concat file ".z"))
2640 (t nil))))))))))
2642 (defun tramp-sh-handle-insert-directory
2643 (filename switches &optional wildcard full-directory-p)
2644 "Like `insert-directory' for Tramp files."
2645 (setq filename (expand-file-name filename))
2646 (unless switches (setq switches ""))
2647 (with-parsed-tramp-file-name filename nil
2648 (if (and (featurep 'ls-lisp)
2649 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
2650 (tramp-handle-insert-directory
2651 filename switches wildcard full-directory-p)
2652 (when (stringp switches)
2653 (setq switches (split-string switches)))
2654 (when (tramp-get-ls-command-with-quoting-style v)
2655 (setq switches (append switches '("--quoting-style=literal"))))
2656 (when (and (member "--dired" switches)
2657 (not (tramp-get-ls-command-with-dired v)))
2658 (setq switches (delete "--dired" switches)))
2659 (when wildcard
2660 (setq wildcard (tramp-run-real-handler
2661 'file-name-nondirectory (list localname)))
2662 (setq localname (tramp-run-real-handler
2663 'file-name-directory (list localname))))
2664 (unless (or full-directory-p (member "-d" switches))
2665 (setq switches (append switches '("-d"))))
2666 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
2667 (when wildcard
2668 (setq switches (concat switches " " wildcard)))
2669 (tramp-message
2670 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
2671 switches filename (if wildcard "yes" "no")
2672 (if full-directory-p "yes" "no"))
2673 ;; If `full-directory-p', we just say `ls -l FILENAME'.
2674 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
2675 (if full-directory-p
2676 (tramp-send-command
2678 (format "%s %s %s 2>/dev/null"
2679 (tramp-get-ls-command v)
2680 switches
2681 (if wildcard
2682 localname
2683 (tramp-shell-quote-argument (concat localname ".")))))
2684 (tramp-barf-unless-okay
2686 (format "cd %s" (tramp-shell-quote-argument
2687 (tramp-run-real-handler
2688 'file-name-directory (list localname))))
2689 "Couldn't `cd %s'"
2690 (tramp-shell-quote-argument
2691 (tramp-run-real-handler 'file-name-directory (list localname))))
2692 (tramp-send-command
2694 (format "%s %s %s 2>/dev/null"
2695 (tramp-get-ls-command v)
2696 switches
2697 (if (or wildcard
2698 (zerop (length
2699 (tramp-run-real-handler
2700 'file-name-nondirectory (list localname)))))
2702 (tramp-shell-quote-argument
2703 (tramp-run-real-handler
2704 'file-name-nondirectory (list localname)))))))
2706 (save-restriction
2707 (let ((beg (point)))
2708 (narrow-to-region (point) (point))
2709 ;; We cannot use `insert-buffer-substring' because the Tramp
2710 ;; buffer changes its contents before insertion due to calling
2711 ;; `expand-file-name' and alike.
2712 (insert
2713 (with-current-buffer (tramp-get-buffer v)
2714 (buffer-string)))
2716 ;; Check for "--dired" output.
2717 (forward-line -2)
2718 (when (looking-at "//SUBDIRED//")
2719 (forward-line -1))
2720 (when (looking-at "//DIRED//\\s-+")
2721 (let ((databeg (match-end 0))
2722 (end (point-at-eol)))
2723 ;; Now read the numeric positions of file names.
2724 (goto-char databeg)
2725 (while (< (point) end)
2726 (let ((start (+ beg (read (current-buffer))))
2727 (end (+ beg (read (current-buffer)))))
2728 (if (memq (char-after end) '(?\n ?\ ))
2729 ;; End is followed by \n or by " -> ".
2730 (put-text-property start end 'dired-filename t))))))
2731 ;; Remove trailing lines.
2732 (goto-char (point-at-bol))
2733 (while (looking-at "//")
2734 (forward-line 1)
2735 (delete-region (match-beginning 0) (point)))
2737 ;; Some busyboxes are reluctant to discard colors.
2738 (unless
2739 (string-match "color" (tramp-get-connection-property v "ls" ""))
2740 (goto-char beg)
2741 (while
2742 (re-search-forward tramp-display-escape-sequence-regexp nil t)
2743 (replace-match "")))
2745 ;; Decode the output, it could be multibyte.
2746 (decode-coding-region
2747 beg (point-max)
2748 (or file-name-coding-system default-file-name-coding-system))
2750 ;; The inserted file could be from somewhere else.
2751 (when (and (not wildcard) (not full-directory-p))
2752 (goto-char (point-max))
2753 (when (file-symlink-p filename)
2754 (goto-char (search-backward "->" beg 'noerror)))
2755 (search-backward
2756 (if (zerop (length (file-name-nondirectory filename)))
2758 (file-name-nondirectory filename))
2759 beg 'noerror)
2760 (replace-match (file-relative-name filename) t))
2762 (goto-char (point-max)))))))
2764 ;; Canonicalization of file names.
2766 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2767 "Like `expand-file-name' for Tramp files.
2768 If the localname part of the given file name starts with \"/../\" then
2769 the result will be a local, non-Tramp, file name."
2770 ;; If DIR is not given, use `default-directory' or "/".
2771 (setq dir (or dir default-directory "/"))
2772 ;; Unless NAME is absolute, concat DIR and NAME.
2773 (unless (file-name-absolute-p name)
2774 (setq name (concat (file-name-as-directory dir) name)))
2775 ;; If connection is not established yet, run the real handler.
2776 (if (not (tramp-connectable-p name))
2777 (tramp-run-real-handler 'expand-file-name (list name nil))
2778 ;; Dissect NAME.
2779 (with-parsed-tramp-file-name name nil
2780 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2781 (setq localname (concat "~/" localname)))
2782 ;; Tilde expansion if necessary. This needs a shell which
2783 ;; groks tilde expansion! The function `tramp-find-shell' is
2784 ;; supposed to find such a shell on the remote host. Please
2785 ;; tell me about it when this doesn't work on your system.
2786 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2787 (let ((uname (match-string 1 localname))
2788 (fname (match-string 2 localname)))
2789 ;; We cannot simply apply "~/", because under sudo "~/" is
2790 ;; expanded to the local user home directory but to the
2791 ;; root home directory. On the other hand, using always
2792 ;; the default user name for tilde expansion is not
2793 ;; appropriate either, because ssh and companions might
2794 ;; use a user name from the config file.
2795 (when (and (string-equal uname "~")
2796 (string-match "\\`su\\(do\\)?\\'" method))
2797 (setq uname (concat uname user)))
2798 (setq uname
2799 (with-tramp-connection-property v uname
2800 (tramp-send-command
2801 v (format "cd %s && pwd" (tramp-shell-quote-argument uname)))
2802 (with-current-buffer (tramp-get-buffer v)
2803 (goto-char (point-min))
2804 (buffer-substring (point) (point-at-eol)))))
2805 (setq localname (concat uname fname))))
2806 ;; There might be a double slash, for example when "~/"
2807 ;; expands to "/". Remove this.
2808 (while (string-match "//" localname)
2809 (setq localname (replace-match "/" t t localname)))
2810 ;; No tilde characters in file name, do normal
2811 ;; `expand-file-name' (this does "/./" and "/../").
2812 ;; `default-directory' is bound, because on Windows there would
2813 ;; be problems with UNC shares or Cygwin mounts.
2814 (let ((default-directory (tramp-compat-temporary-file-directory)))
2815 (tramp-make-tramp-file-name
2816 method user host
2817 (tramp-drop-volume-letter
2818 (tramp-run-real-handler
2819 'expand-file-name (list localname)))
2820 hop)))))
2822 ;;; Remote commands:
2824 (defun tramp-process-sentinel (proc event)
2825 "Flush file caches."
2826 (unless (tramp-compat-process-live-p proc)
2827 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2828 (when vec
2829 (tramp-message vec 5 "Sentinel called: `%S' `%s'" proc event)
2830 (tramp-flush-connection-property proc)
2831 (tramp-flush-directory-property vec "")))))
2833 ;; We use BUFFER also as connection buffer during setup. Because of
2834 ;; this, its original contents must be saved, and restored once
2835 ;; connection has been setup.
2836 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2837 "Like `start-file-process' for Tramp files."
2838 (with-parsed-tramp-file-name (expand-file-name default-directory) nil
2839 (let* ((buffer
2840 (if buffer
2841 (get-buffer-create buffer)
2842 ;; BUFFER can be nil. We use a temporary buffer.
2843 (generate-new-buffer tramp-temp-buffer-name)))
2844 ;; When PROGRAM matches "*sh", and the first arg is "-c",
2845 ;; it might be that the arguments exceed the command line
2846 ;; length. Therefore, we modify the command.
2847 (heredoc (and (stringp program)
2848 (string-match "sh$" program)
2849 (string-equal "-c" (car args))
2850 (= (length args) 2)))
2851 ;; When PROGRAM is nil, we just provide a tty.
2852 (args (if (not heredoc) args
2853 (let ((i 250))
2854 (while (and (< i (length (cadr args)))
2855 (string-match " " (cadr args) i))
2856 (setcdr
2857 args
2858 (list (replace-match " \\\\\n" nil nil (cadr args))))
2859 (setq i (+ i 250))))
2860 (cdr args)))
2861 ;; Use a human-friendly prompt, for example for `shell'.
2862 ;; We discard hops, if existing, that's why we cannot use
2863 ;; `file-remote-p'.
2864 (prompt (format "PS1=%s %s"
2865 (tramp-make-tramp-file-name
2866 (tramp-file-name-method v)
2867 (tramp-file-name-user v)
2868 (tramp-file-name-host v)
2869 (tramp-file-name-localname v))
2870 tramp-initial-end-of-output))
2871 ;; We use as environment the difference to toplevel
2872 ;; `process-environment'.
2873 env uenv
2874 (env (dolist (elt (cons prompt process-environment) env)
2875 (or (member elt (default-toplevel-value 'process-environment))
2876 (if (string-match "=" elt)
2877 (setq env (append env `(,elt)))
2878 (if (tramp-get-env-with-u-option v)
2879 (setq env (append `("-u" ,elt) env))
2880 (setq uenv (cons elt uenv)))))))
2881 (command
2882 (when (stringp program)
2883 (format "cd %s && %s exec %s env %s %s"
2884 (tramp-shell-quote-argument localname)
2885 (if uenv
2886 (format
2887 "unset %s &&"
2888 (mapconcat 'tramp-shell-quote-argument uenv " "))
2890 (if heredoc (format "<<'%s'" tramp-end-of-heredoc) "")
2891 (mapconcat 'tramp-shell-quote-argument env " ")
2892 (if heredoc
2893 (format "%s\n(\n%s\n) </dev/tty\n%s"
2894 program (car args) tramp-end-of-heredoc)
2895 (mapconcat 'tramp-shell-quote-argument
2896 (cons program args) " ")))))
2897 (tramp-process-connection-type
2898 (or (null program) tramp-process-connection-type))
2899 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2900 (name1 name)
2901 (i 0)
2902 ;; We do not want to raise an error when
2903 ;; `start-file-process' has been started several times in
2904 ;; `eshell' and friends.
2905 (tramp-current-connection nil))
2907 (while (get-process name1)
2908 ;; NAME must be unique as process name.
2909 (setq i (1+ i)
2910 name1 (format "%s<%d>" name i)))
2911 (setq name name1)
2912 ;; Set the new process properties.
2913 (tramp-set-connection-property v "process-name" name)
2914 (tramp-set-connection-property v "process-buffer" buffer)
2916 (with-current-buffer (tramp-get-connection-buffer v)
2917 (unwind-protect
2918 ;; We catch this event. Otherwise, `start-process' could
2919 ;; be called on the local host.
2920 (save-excursion
2921 (save-restriction
2922 ;; Activate narrowing in order to save BUFFER
2923 ;; contents. Clear also the modification time;
2924 ;; otherwise we might be interrupted by
2925 ;; `verify-visited-file-modtime'.
2926 (let ((buffer-undo-list t)
2927 (buffer-read-only nil)
2928 (mark (point-max)))
2929 (clear-visited-file-modtime)
2930 (narrow-to-region (point-max) (point-max))
2931 ;; We call `tramp-maybe-open-connection', in order
2932 ;; to cleanup the prompt afterwards.
2933 (catch 'suppress
2934 (tramp-maybe-open-connection v)
2935 (widen)
2936 (delete-region mark (point))
2937 (narrow-to-region (point-max) (point-max))
2938 ;; Now do it.
2939 (if command
2940 ;; Send the command.
2941 (tramp-send-command v command nil t) ; nooutput
2942 ;; Check, whether a pty is associated.
2943 (unless (process-get
2944 (tramp-get-connection-process v) 'remote-tty)
2945 (tramp-error
2946 v 'file-error
2947 "pty association is not supported for `%s'" name))))
2948 (let ((p (tramp-get-connection-process v)))
2949 ;; Set query flag and process marker for this
2950 ;; process. We ignore errors, because the process
2951 ;; could have finished already.
2952 (ignore-errors
2953 (set-process-query-on-exit-flag p t)
2954 (set-marker (process-mark p) (point)))
2955 ;; Return process.
2956 p))))
2958 ;; Save exit.
2959 (if (string-match tramp-temp-buffer-name (buffer-name))
2960 (ignore-errors
2961 (set-process-buffer (tramp-get-connection-process v) nil)
2962 (kill-buffer (current-buffer)))
2963 (set-buffer-modified-p bmp))
2964 (tramp-set-connection-property v "process-name" nil)
2965 (tramp-set-connection-property v "process-buffer" nil))))))
2967 (defun tramp-sh-handle-process-file
2968 (program &optional infile destination display &rest args)
2969 "Like `process-file' for Tramp files."
2970 ;; The implementation is not complete yet.
2971 (when (and (numberp destination) (zerop destination))
2972 (error "Implementation does not handle immediate return"))
2974 (with-parsed-tramp-file-name default-directory nil
2975 (let (command env uenv input tmpinput stderr tmpstderr outbuf ret)
2976 ;; Compute command.
2977 (setq command (mapconcat 'tramp-shell-quote-argument
2978 (cons program args) " "))
2979 ;; We use as environment the difference to toplevel `process-environment'.
2980 (dolist (elt process-environment)
2981 (or (member elt (default-toplevel-value 'process-environment))
2982 (if (string-match "=" elt)
2983 (setq env (append env `(,elt)))
2984 (if (tramp-get-env-with-u-option v)
2985 (setq env (append `("-u" ,elt) env))
2986 (setq uenv (cons elt uenv))))))
2987 (when env
2988 (setq command
2989 (format
2990 "env %s %s"
2991 (mapconcat 'tramp-shell-quote-argument env " ") command)))
2992 (when uenv
2993 (setq command
2994 (format
2995 "unset %s && %s"
2996 (mapconcat 'tramp-shell-quote-argument uenv " ") command)))
2997 ;; Determine input.
2998 (if (null infile)
2999 (setq input "/dev/null")
3000 (setq infile (expand-file-name infile))
3001 (if (tramp-equal-remote default-directory infile)
3002 ;; INFILE is on the same remote host.
3003 (setq input (with-parsed-tramp-file-name infile nil localname))
3004 ;; INFILE must be copied to remote host.
3005 (setq input (tramp-make-tramp-temp-file v)
3006 tmpinput (tramp-make-tramp-file-name method user host input))
3007 (copy-file infile tmpinput t)))
3008 (when input (setq command (format "%s <%s" command input)))
3010 ;; Determine output.
3011 (cond
3012 ;; Just a buffer.
3013 ((bufferp destination)
3014 (setq outbuf destination))
3015 ;; A buffer name.
3016 ((stringp destination)
3017 (setq outbuf (get-buffer-create destination)))
3018 ;; (REAL-DESTINATION ERROR-DESTINATION)
3019 ((consp destination)
3020 ;; output.
3021 (cond
3022 ((bufferp (car destination))
3023 (setq outbuf (car destination)))
3024 ((stringp (car destination))
3025 (setq outbuf (get-buffer-create (car destination))))
3026 ((car destination)
3027 (setq outbuf (current-buffer))))
3028 ;; stderr.
3029 (cond
3030 ((stringp (cadr destination))
3031 (setcar (cdr destination) (expand-file-name (cadr destination)))
3032 (if (tramp-equal-remote default-directory (cadr destination))
3033 ;; stderr is on the same remote host.
3034 (setq stderr (with-parsed-tramp-file-name
3035 (cadr destination) nil localname))
3036 ;; stderr must be copied to remote host. The temporary
3037 ;; file must be deleted after execution.
3038 (setq stderr (tramp-make-tramp-temp-file v)
3039 tmpstderr (tramp-make-tramp-file-name
3040 method user host stderr))))
3041 ;; stderr to be discarded.
3042 ((null (cadr destination))
3043 (setq stderr "/dev/null"))))
3044 ;; 't
3045 (destination
3046 (setq outbuf (current-buffer))))
3047 (when stderr (setq command (format "%s 2>%s" command stderr)))
3049 ;; Send the command. It might not return in time, so we protect
3050 ;; it. Call it in a subshell, in order to preserve working
3051 ;; directory.
3052 (condition-case nil
3053 (unwind-protect
3054 (setq ret
3055 (if (tramp-send-command-and-check
3056 v (format "cd %s && %s"
3057 (tramp-shell-quote-argument localname)
3058 command)
3059 t t)
3060 0 1))
3061 ;; We should add the output anyway.
3062 (when outbuf
3063 (with-current-buffer outbuf
3064 (insert
3065 (with-current-buffer (tramp-get-connection-buffer v)
3066 (buffer-string))))
3067 (when (and display (get-buffer-window outbuf t)) (redisplay))))
3068 ;; When the user did interrupt, we should do it also. We use
3069 ;; return code -1 as marker.
3070 (quit
3071 (kill-buffer (tramp-get-connection-buffer v))
3072 (setq ret -1))
3073 ;; Handle errors.
3074 (error
3075 (kill-buffer (tramp-get-connection-buffer v))
3076 (setq ret 1)))
3078 ;; Provide error file.
3079 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3081 ;; Cleanup. We remove all file cache values for the connection,
3082 ;; because the remote process could have changed them.
3083 (when tmpinput (delete-file tmpinput))
3085 (unless process-file-side-effects
3086 (tramp-flush-directory-property v ""))
3088 ;; Return exit status.
3089 (if (equal ret -1)
3090 (keyboard-quit)
3091 ret))))
3093 (defun tramp-sh-handle-file-local-copy (filename)
3094 "Like `file-local-copy' for Tramp files."
3095 (with-parsed-tramp-file-name filename nil
3096 (unless (file-exists-p filename)
3097 (tramp-error
3098 v tramp-file-missing
3099 "Cannot make local copy of non-existing file `%s'" filename))
3101 (let* ((size (tramp-compat-file-attribute-size
3102 (file-attributes (file-truename filename))))
3103 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
3104 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
3105 (tmpfile (tramp-compat-make-temp-file filename)))
3107 (condition-case err
3108 (cond
3109 ;; `copy-file' handles direct copy and out-of-band methods.
3110 ((or (tramp-local-host-p v)
3111 (tramp-method-out-of-band-p v size))
3112 (copy-file filename tmpfile 'ok-if-already-exists 'keep-time))
3114 ;; Use inline encoding for file transfer.
3115 (rem-enc
3116 (save-excursion
3117 (with-tramp-progress-reporter
3119 (format-message "Encoding remote file `%s' with `%s'"
3120 filename rem-enc)
3121 (tramp-barf-unless-okay
3122 v (format rem-enc (tramp-shell-quote-argument localname))
3123 "Encoding remote file failed"))
3125 (with-tramp-progress-reporter
3126 v 3 (format-message "Decoding local file `%s' with `%s'"
3127 tmpfile loc-dec)
3128 (if (functionp loc-dec)
3129 ;; If local decoding is a function, we call it.
3130 ;; We must disable multibyte, because
3131 ;; `uudecode-decode-region' doesn't handle it
3132 ;; correctly. Unset `file-name-handler-alist'.
3133 ;; Otherwise, epa-file gets confused.
3134 (let (file-name-handler-alist
3135 (coding-system-for-write 'binary))
3136 (with-temp-file tmpfile
3137 (set-buffer-multibyte nil)
3138 (insert-buffer-substring (tramp-get-buffer v))
3139 (funcall loc-dec (point-min) (point-max))))
3141 ;; If tramp-decoding-function is not defined for this
3142 ;; method, we invoke tramp-decoding-command instead.
3143 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3144 ;; Unset `file-name-handler-alist'. Otherwise,
3145 ;; epa-file gets confused.
3146 (let (file-name-handler-alist
3147 (coding-system-for-write 'binary))
3148 (with-current-buffer (tramp-get-buffer v)
3149 (write-region
3150 (point-min) (point-max) tmpfile2 nil 'no-message)))
3151 (unwind-protect
3152 (tramp-call-local-coding-command
3153 loc-dec tmpfile2 tmpfile)
3154 (delete-file tmpfile2)))))
3156 ;; Set proper permissions.
3157 (set-file-modes tmpfile (tramp-default-file-modes filename))
3158 ;; Set local user ownership.
3159 (tramp-set-file-uid-gid tmpfile)))
3161 ;; Oops, I don't know what to do.
3162 (t (tramp-error
3163 v 'file-error "Wrong method specification for `%s'" method)))
3165 ;; Error handling.
3166 ((error quit)
3167 (delete-file tmpfile)
3168 (signal (car err) (cdr err))))
3170 (run-hooks 'tramp-handle-file-local-copy-hook)
3171 tmpfile)))
3173 ;; CCC grok LOCKNAME
3174 (defun tramp-sh-handle-write-region
3175 (start end filename &optional append visit lockname confirm)
3176 "Like `write-region' for Tramp files."
3177 (setq filename (expand-file-name filename))
3178 (with-parsed-tramp-file-name filename nil
3179 ;; Following part commented out because we don't know what to do about
3180 ;; file locking, and it does not appear to be a problem to ignore it.
3181 ;; Ange-ftp ignores it, too.
3182 ;; (when (and lockname (stringp lockname))
3183 ;; (setq lockname (expand-file-name lockname)))
3184 ;; (unless (or (eq lockname nil)
3185 ;; (string= lockname filename))
3186 ;; (error
3187 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3189 (when (and confirm (file-exists-p filename))
3190 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3191 (tramp-error v 'file-error "File not overwritten")))
3193 (let ((uid (or (tramp-compat-file-attribute-user-id
3194 (file-attributes filename 'integer))
3195 (tramp-get-remote-uid v 'integer)))
3196 (gid (or (tramp-compat-file-attribute-group-id
3197 (file-attributes filename 'integer))
3198 (tramp-get-remote-gid v 'integer))))
3200 (if (and (tramp-local-host-p v)
3201 ;; `file-writable-p' calls `file-expand-file-name'. We
3202 ;; cannot use `tramp-run-real-handler' therefore.
3203 (let (file-name-handler-alist)
3204 (and
3205 (file-writable-p (file-name-directory localname))
3206 (or (file-directory-p localname)
3207 (file-writable-p localname)))))
3208 ;; Short track: if we are on the local host, we can run directly.
3209 (tramp-run-real-handler
3210 'write-region
3211 (list start end localname append 'no-message lockname confirm))
3213 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3214 ;; We use this to save the value of
3215 ;; `last-coding-system-used' after writing the tmp
3216 ;; file. At the end of the function, we set
3217 ;; `last-coding-system-used' to this saved value. This
3218 ;; way, any intermediary coding systems used while
3219 ;; talking to the remote shell or suchlike won't hose
3220 ;; this variable. This approach was snarfed from
3221 ;; ange-ftp.el.
3222 coding-system-used
3223 ;; Write region into a tmp file. This isn't really
3224 ;; needed if we use an encoding function, but currently
3225 ;; we use it always because this makes the logic
3226 ;; simpler. We must also set `temporary-file-directory',
3227 ;; because it could point to a remote directory.
3228 (temporary-file-directory
3229 (tramp-compat-temporary-file-directory))
3230 (tmpfile (or tramp-temp-buffer-file-name
3231 (tramp-compat-make-temp-file filename))))
3233 ;; If `append' is non-nil, we copy the file locally, and let
3234 ;; the native `write-region' implementation do the job.
3235 (when append (copy-file filename tmpfile 'ok))
3237 ;; We say `no-message' here because we don't want the
3238 ;; visited file modtime data to be clobbered from the temp
3239 ;; file. We call `set-visited-file-modtime' ourselves later
3240 ;; on. We must ensure that `file-coding-system-alist'
3241 ;; matches `tmpfile'.
3242 (let (file-name-handler-alist
3243 (file-coding-system-alist
3244 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3245 (condition-case err
3246 (tramp-run-real-handler
3247 'write-region
3248 (list start end tmpfile append 'no-message lockname confirm))
3249 ((error quit)
3250 (setq tramp-temp-buffer-file-name nil)
3251 (delete-file tmpfile)
3252 (signal (car err) (cdr err))))
3254 ;; Now, `last-coding-system-used' has the right value. Remember it.
3255 (setq coding-system-used last-coding-system-used))
3257 ;; The permissions of the temporary file should be set. If
3258 ;; FILENAME does not exist (eq modes nil) it has been
3259 ;; renamed to the backup file. This case `save-buffer'
3260 ;; handles permissions.
3261 ;; Ensure that it is still readable.
3262 (when modes
3263 (set-file-modes
3264 tmpfile
3265 (logior (or modes 0) (string-to-number "0400" 8))))
3267 ;; This is a bit lengthy due to the different methods
3268 ;; possible for file transfer. First, we check whether the
3269 ;; method uses an scp program. If so, we call it.
3270 ;; Otherwise, both encoding and decoding command must be
3271 ;; specified. However, if the method _also_ specifies an
3272 ;; encoding function, then that is used for encoding the
3273 ;; contents of the tmp file.
3274 (let* ((size (tramp-compat-file-attribute-size
3275 (file-attributes tmpfile)))
3276 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3277 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3278 (cond
3279 ;; `copy-file' handles direct copy and out-of-band methods.
3280 ((or (tramp-local-host-p v)
3281 (tramp-method-out-of-band-p v size))
3282 (if (and (not (stringp start))
3283 (= (or end (point-max)) (point-max))
3284 (= (or start (point-min)) (point-min))
3285 (tramp-get-method-parameter v 'tramp-copy-keep-tmpfile))
3286 (progn
3287 (setq tramp-temp-buffer-file-name tmpfile)
3288 (condition-case err
3289 ;; We keep the local file for performance
3290 ;; reasons, useful for "rsync".
3291 (copy-file tmpfile filename t)
3292 ((error quit)
3293 (setq tramp-temp-buffer-file-name nil)
3294 (delete-file tmpfile)
3295 (signal (car err) (cdr err)))))
3296 (setq tramp-temp-buffer-file-name nil)
3297 ;; Don't rename, in order to keep context in SELinux.
3298 (unwind-protect
3299 (copy-file tmpfile filename t)
3300 (delete-file tmpfile))))
3302 ;; Use inline file transfer.
3303 (rem-dec
3304 ;; Encode tmpfile.
3305 (unwind-protect
3306 (with-temp-buffer
3307 (set-buffer-multibyte nil)
3308 ;; Use encoding function or command.
3309 (with-tramp-progress-reporter
3310 v 3 (format-message
3311 "Encoding local file `%s' using `%s'"
3312 tmpfile loc-enc)
3313 (if (functionp loc-enc)
3314 ;; The following `let' is a workaround for
3315 ;; the base64.el that comes with pgnus-0.84.
3316 ;; If both of the following conditions are
3317 ;; satisfied, it tries to write to a local
3318 ;; file in default-directory, but at this
3319 ;; point, default-directory is remote.
3320 ;; (`call-process-region' can't write to
3321 ;; remote files, it seems.) The file in
3322 ;; question is a tmp file anyway.
3323 (let ((coding-system-for-read 'binary)
3324 (default-directory
3325 (tramp-compat-temporary-file-directory)))
3326 (insert-file-contents-literally tmpfile)
3327 (funcall loc-enc (point-min) (point-max)))
3329 (unless (zerop (tramp-call-local-coding-command
3330 loc-enc tmpfile t))
3331 (tramp-error
3332 v 'file-error
3333 (concat "Cannot write to `%s', "
3334 "local encoding command `%s' failed")
3335 filename loc-enc))))
3337 ;; Send buffer into remote decoding command which
3338 ;; writes to remote file. Because this happens on
3339 ;; the remote host, we cannot use the function.
3340 (with-tramp-progress-reporter
3341 v 3 (format-message
3342 "Decoding remote file `%s' using `%s'"
3343 filename rem-dec)
3344 (goto-char (point-max))
3345 (unless (bolp) (newline))
3346 (tramp-send-command
3348 (format
3349 (concat rem-dec " <<'%s'\n%s%s")
3350 (tramp-shell-quote-argument localname)
3351 tramp-end-of-heredoc
3352 (buffer-string)
3353 tramp-end-of-heredoc))
3354 (tramp-barf-unless-okay
3355 v nil
3356 "Couldn't write region to `%s', decode using `%s' failed"
3357 filename rem-dec)
3358 ;; When `file-precious-flag' is set, the region is
3359 ;; written to a temporary file. Check that the
3360 ;; checksum is equal to that from the local tmpfile.
3361 (when file-precious-flag
3362 (erase-buffer)
3363 (and
3364 ;; cksum runs locally, if possible.
3365 (zerop (tramp-call-process v "cksum" tmpfile t))
3366 ;; cksum runs remotely.
3367 (tramp-send-command-and-check
3369 (format
3370 "cksum <%s" (tramp-shell-quote-argument localname)))
3371 ;; ... they are different.
3372 (not
3373 (string-equal
3374 (buffer-string)
3375 (with-current-buffer (tramp-get-buffer v)
3376 (buffer-string))))
3377 (tramp-error
3378 v 'file-error
3379 (concat "Couldn't write region to `%s',"
3380 " decode using `%s' failed")
3381 filename rem-dec)))))
3383 ;; Save exit.
3384 (delete-file tmpfile)))
3386 ;; That's not expected.
3388 (tramp-error
3389 v 'file-error
3390 (concat "Method `%s' should specify both encoding and "
3391 "decoding command or an scp program")
3392 method))))
3394 ;; Make `last-coding-system-used' have the right value.
3395 (when coding-system-used
3396 (set 'last-coding-system-used coding-system-used))))
3398 (tramp-flush-file-property v (file-name-directory localname))
3399 (tramp-flush-file-property v localname)
3401 ;; We must protect `last-coding-system-used', now we have set it
3402 ;; to its correct value.
3403 (let (last-coding-system-used (need-chown t))
3404 ;; Set file modification time.
3405 (when (or (eq visit t) (stringp visit))
3406 (let ((file-attr (file-attributes filename 'integer)))
3407 (set-visited-file-modtime
3408 ;; We must pass modtime explicitly, because FILENAME can
3409 ;; be different from (buffer-file-name), f.e. if
3410 ;; `file-precious-flag' is set.
3411 (tramp-compat-file-attribute-modification-time file-attr))
3412 (when (and (= (tramp-compat-file-attribute-user-id file-attr) uid)
3413 (= (tramp-compat-file-attribute-group-id file-attr) gid))
3414 (setq need-chown nil))))
3416 ;; Set the ownership.
3417 (when need-chown
3418 (tramp-set-file-uid-gid filename uid gid))
3419 (when (or (eq visit t) (null visit) (stringp visit))
3420 (tramp-message v 0 "Wrote %s" filename))
3421 (run-hooks 'tramp-handle-write-region-hook)))))
3423 (defvar tramp-vc-registered-file-names nil
3424 "List used to collect file names, which are checked during `vc-registered'.")
3426 ;; VC backends check for the existence of various different special
3427 ;; files. This is very time consuming, because every single check
3428 ;; requires a remote command (the file cache must be invalidated).
3429 ;; Therefore, we apply a kind of optimization. We install the file
3430 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3431 ;; remembers all file names for which `file-exists-p' or
3432 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3433 ;; is performed. Afterwards, a script is applied for all collected
3434 ;; file names, using just one remote command. The result of this
3435 ;; script is used to fill the file cache with actual values. Now we
3436 ;; can reset the file name handlers, and we make a second run of
3437 ;; `vc-registered', which returns the expected result without sending
3438 ;; any other remote command.
3439 (defun tramp-sh-handle-vc-registered (file)
3440 "Like `vc-registered' for Tramp files."
3441 (with-temp-message ""
3442 (with-parsed-tramp-file-name file nil
3443 (with-tramp-progress-reporter
3444 v 3 (format-message "Checking `vc-registered' for %s" file)
3446 ;; There could be new files, created by the vc backend. We
3447 ;; cannot reuse the old cache entries, therefore. In
3448 ;; `tramp-get-file-property', `remote-file-name-inhibit-cache'
3449 ;; could also be a timestamp as `current-time' returns. This
3450 ;; means invalidate all cache entries with an older timestamp.
3451 (let (tramp-vc-registered-file-names
3452 (remote-file-name-inhibit-cache (current-time))
3453 (file-name-handler-alist
3454 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3456 ;; Here we collect only file names, which need an operation.
3457 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3458 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3460 ;; Send just one command, in order to fill the cache.
3461 (when tramp-vc-registered-file-names
3462 (tramp-maybe-send-script
3464 (format tramp-vc-registered-read-file-names
3465 (tramp-get-file-exists-command v)
3466 (format "%s -r" (tramp-get-test-command v)))
3467 "tramp_vc_registered_read_file_names")
3469 (dolist
3470 (elt
3471 (ignore-errors
3472 ;; We cannot use `tramp-send-command-and-read',
3473 ;; because this does not cooperate well with
3474 ;; heredoc documents.
3475 (tramp-send-command
3477 (format
3478 "tramp_vc_registered_read_file_names <<'%s'\n%s\n%s\n"
3479 tramp-end-of-heredoc
3480 (mapconcat 'tramp-shell-quote-argument
3481 tramp-vc-registered-file-names
3482 "\n")
3483 tramp-end-of-heredoc))
3484 (with-current-buffer (tramp-get-connection-buffer v)
3485 ;; Read the expression.
3486 (goto-char (point-min))
3487 (read (current-buffer)))))
3489 (tramp-set-file-property
3490 v (car elt) (cadr elt) (cadr (cdr elt))))))
3492 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3493 ;; calls shall be answered from the file cache. We unset
3494 ;; `process-file-side-effects' and `remote-file-name-inhibit-cache'
3495 ;; in order to keep the cache.
3496 (let ((vc-handled-backends vc-handled-backends)
3497 remote-file-name-inhibit-cache process-file-side-effects)
3498 ;; Reduce `vc-handled-backends' in order to minimize process calls.
3499 (when (and (memq 'Bzr vc-handled-backends)
3500 (boundp 'vc-bzr-program)
3501 (not (with-tramp-connection-property v vc-bzr-program
3502 (tramp-find-executable
3503 v vc-bzr-program (tramp-get-remote-path v)))))
3504 (setq vc-handled-backends (remq 'Bzr vc-handled-backends)))
3505 (when (and (memq 'Git vc-handled-backends)
3506 (boundp 'vc-git-program)
3507 (not (with-tramp-connection-property v vc-git-program
3508 (tramp-find-executable
3509 v vc-git-program (tramp-get-remote-path v)))))
3510 (setq vc-handled-backends (remq 'Git vc-handled-backends)))
3511 (when (and (memq 'Hg vc-handled-backends)
3512 (boundp 'vc-hg-program)
3513 (not (with-tramp-connection-property v vc-hg-program
3514 (tramp-find-executable
3515 v vc-hg-program (tramp-get-remote-path v)))))
3516 (setq vc-handled-backends (remq 'Hg vc-handled-backends)))
3517 ;; Run.
3518 (ignore-errors
3519 (tramp-run-real-handler 'vc-registered (list file))))))))
3521 ;;;###tramp-autoload
3522 (defun tramp-sh-file-name-handler (operation &rest args)
3523 "Invoke remote-shell Tramp file name handler.
3524 Fall back to normal file name handler if no Tramp handler exists."
3525 (when (and tramp-locked (not tramp-locker))
3526 (setq tramp-locked nil)
3527 (tramp-error
3528 (car-safe tramp-current-connection) 'file-error
3529 "Forbidden reentrant call of Tramp"))
3530 (let ((tl tramp-locked))
3531 (setq tramp-locked t)
3532 (unwind-protect
3533 (let ((tramp-locker t))
3534 (save-match-data
3535 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3536 (if fn
3537 (apply (cdr fn) args)
3538 (tramp-run-real-handler operation args)))))
3539 (setq tramp-locked tl))))
3541 (defun tramp-vc-file-name-handler (operation &rest args)
3542 "Invoke special file name handler, which collects files to be handled."
3543 (save-match-data
3544 (let ((filename
3545 (tramp-replace-environment-variables
3546 (apply 'tramp-file-name-for-operation operation args)))
3547 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3548 (with-parsed-tramp-file-name filename nil
3549 (cond
3550 ;; That's what we want: file names, for which checks are
3551 ;; applied. We assume that VC uses only `file-exists-p' and
3552 ;; `file-readable-p' checks; otherwise we must extend the
3553 ;; list. We do not perform any action, but return nil, in
3554 ;; order to keep `vc-registered' running.
3555 ((and fn (memq operation '(file-exists-p file-readable-p)))
3556 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3557 nil)
3558 ;; `process-file' and `start-file-process' shall be ignored.
3559 ((and fn (eq operation 'process-file) 0))
3560 ((and fn (eq operation 'start-file-process) nil))
3561 ;; Tramp file name handlers like `expand-file-name'. They
3562 ;; must still work.
3563 (fn (save-match-data (apply (cdr fn) args)))
3564 ;; Default file name handlers, we don't care.
3565 (t (tramp-run-real-handler operation args)))))))
3567 (defun tramp-sh-handle-file-notify-add-watch (file-name flags _callback)
3568 "Like `file-notify-add-watch' for Tramp files."
3569 (setq file-name (expand-file-name file-name))
3570 (with-parsed-tramp-file-name file-name nil
3571 (let ((default-directory (file-name-directory file-name))
3572 command events filter p sequence)
3573 (cond
3574 ;; gvfs-monitor-dir.
3575 ((setq command (tramp-get-remote-gvfs-monitor-dir v))
3576 (setq filter 'tramp-sh-gvfs-monitor-dir-process-filter
3577 events
3578 (cond
3579 ((and (memq 'change flags) (memq 'attribute-change flags))
3580 '(created changed changes-done-hint moved deleted
3581 attribute-changed))
3582 ((memq 'change flags)
3583 '(created changed changes-done-hint moved deleted))
3584 ((memq 'attribute-change flags) '(attribute-changed)))
3585 sequence `(,command ,localname)))
3586 ;; inotifywait.
3587 ((setq command (tramp-get-remote-inotifywait v))
3588 (setq filter 'tramp-sh-inotifywait-process-filter
3589 events
3590 (cond
3591 ((and (memq 'change flags) (memq 'attribute-change flags))
3592 (concat "create,modify,move,moved_from,moved_to,move_self,"
3593 "delete,delete_self,attrib,ignored"))
3594 ((memq 'change flags)
3595 (concat "create,modify,move,moved_from,moved_to,move_self,"
3596 "delete,delete_self,ignored"))
3597 ((memq 'attribute-change flags) "attrib,ignored"))
3598 sequence `(,command "-mq" "-e" ,events ,localname)
3599 ;; Make events a list of symbols.
3600 events
3601 (mapcar
3602 (lambda (x) (intern-soft (replace-regexp-in-string "_" "-" x)))
3603 (split-string events "," 'omit))))
3604 ;; None.
3605 (t (tramp-error
3606 v 'file-notify-error
3607 "No file notification program found on %s"
3608 (file-remote-p file-name))))
3609 ;; Start process.
3610 (setq p (apply
3611 'start-file-process
3612 (file-name-nondirectory command)
3613 (generate-new-buffer
3614 (format " *%s*" (file-name-nondirectory command)))
3615 sequence))
3616 ;; Return the process object as watch-descriptor.
3617 (if (not (processp p))
3618 (tramp-error
3619 v 'file-notify-error
3620 "`%s' failed to start on remote host"
3621 (mapconcat 'identity sequence " "))
3622 (tramp-message v 6 "Run `%s', %S" (mapconcat 'identity sequence " ") p)
3623 (tramp-set-connection-property p "vector" v)
3624 ;; Needed for process filter.
3625 (process-put p 'events events)
3626 (process-put p 'watch-name localname)
3627 (set-process-query-on-exit-flag p nil)
3628 (set-process-filter p filter)
3629 ;; There might be an error if the monitor is not supported.
3630 ;; Give the filter a chance to read the output.
3631 (tramp-accept-process-output p 1)
3632 (unless (tramp-compat-process-live-p p)
3633 (tramp-error
3634 v 'file-notify-error "Monitoring not supported for `%s'" file-name))
3635 p))))
3637 (defun tramp-sh-gvfs-monitor-dir-process-filter (proc string)
3638 "Read output from \"gvfs-monitor-dir\" and add corresponding \
3639 file-notify events."
3640 (let ((events (process-get proc 'events))
3641 (remote-prefix
3642 (with-current-buffer (process-buffer proc)
3643 (file-remote-p default-directory)))
3644 (rest-string (process-get proc 'rest-string)))
3645 (when rest-string
3646 (tramp-message proc 10 "Previous string:\n%s" rest-string))
3647 (tramp-message proc 6 "%S\n%s" proc string)
3648 (setq string (concat rest-string string)
3649 ;; Attribute change is returned in unused wording.
3650 string (replace-regexp-in-string
3651 "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))
3652 (when (string-match "Monitoring not supported" string)
3653 (delete-process proc))
3655 (while (string-match
3656 (concat "^[\n\r]*"
3657 "Directory Monitor Event:[\n\r]+"
3658 "Child = \\([^\n\r]+\\)[\n\r]+"
3659 "\\(Other = \\([^\n\r]+\\)[\n\r]+\\)?"
3660 "Event = \\([^[:blank:]]+\\)[\n\r]+")
3661 string)
3662 (let* ((file (match-string 1 string))
3663 (file1 (match-string 3 string))
3664 (object
3665 (list
3666 proc
3667 (list
3668 (intern-soft
3669 (replace-regexp-in-string
3670 "_" "-" (downcase (match-string 4 string)))))
3671 ;; File names are returned as absolute paths. We must
3672 ;; add the remote prefix.
3673 (concat remote-prefix file)
3674 (when file1 (concat remote-prefix file1)))))
3675 (setq string (replace-match "" nil nil string))
3676 ;; Remove watch when file or directory to be watched is deleted.
3677 (when (and (member (caadr object) '(moved deleted))
3678 (string-equal file (process-get proc 'watch-name)))
3679 (delete-process proc))
3680 ;; Usually, we would add an Emacs event now. Unfortunately,
3681 ;; `unread-command-events' does not accept several events at
3682 ;; once. Therefore, we apply the handler directly.
3683 (when (member (caadr object) events)
3684 (tramp-compat-funcall
3685 'file-notify-handle-event
3686 `(file-notify ,object file-notify-callback)))))
3688 ;; Save rest of the string.
3689 (when (zerop (length string)) (setq string nil))
3690 (when string (tramp-message proc 10 "Rest string:\n%s" string))
3691 (process-put proc 'rest-string string)))
3693 (defun tramp-sh-inotifywait-process-filter (proc string)
3694 "Read output from \"inotifywait\" and add corresponding file-notify events."
3695 (let ((events (process-get proc 'events)))
3696 (tramp-message proc 6 "%S\n%s" proc string)
3697 (dolist (line (split-string string "[\n\r]+" 'omit))
3698 ;; Check, whether there is a problem.
3699 (unless
3700 (string-match
3701 (concat "^[^[:blank:]]+"
3702 "[[:blank:]]+\\([^[:blank:]]+\\)+"
3703 "\\([[:blank:]]+\\([^\n\r]+\\)\\)?")
3704 line)
3705 (tramp-error proc 'file-notify-error "%s" line))
3707 (let ((object
3708 (list
3709 proc
3710 (mapcar
3711 (lambda (x)
3712 (intern-soft
3713 (replace-regexp-in-string "_" "-" (downcase x))))
3714 (split-string (match-string 1 line) "," 'omit))
3715 (match-string 3 line))))
3716 ;; Remove watch when file or directory to be watched is deleted.
3717 (when (member (caadr object) '(move-self delete-self ignored))
3718 (delete-process proc))
3719 ;; Usually, we would add an Emacs event now. Unfortunately,
3720 ;; `unread-command-events' does not accept several events at
3721 ;; once. Therefore, we apply the handler directly.
3722 (when (member (caadr object) events)
3723 (tramp-compat-funcall
3724 'file-notify-handle-event
3725 `(file-notify ,object file-notify-callback)))))))
3727 ;;; Internal Functions:
3729 (defun tramp-maybe-send-script (vec script name)
3730 "Define in remote shell function NAME implemented as SCRIPT.
3731 Only send the definition if it has not already been done."
3732 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3733 ;; might be nil.
3734 (let ((scripts (tramp-get-connection-property
3735 (tramp-get-connection-process vec) "scripts" nil)))
3736 (unless (member name scripts)
3737 (with-tramp-progress-reporter
3738 vec 5 (format-message "Sending script `%s'" name)
3739 ;; In bash, leading TABs like in `tramp-vc-registered-read-file-names'
3740 ;; could result in unwanted command expansion. Avoid this.
3741 (setq script (replace-regexp-in-string
3742 (make-string 1 ?\t) (make-string 8 ? ) script))
3743 ;; The script could contain a call of Perl. This is masked with `%s'.
3744 (when (and (string-match "%s" script)
3745 (not (tramp-get-remote-perl vec)))
3746 (tramp-error vec 'file-error "No Perl available on remote host"))
3747 (tramp-barf-unless-okay
3749 (format "%s () {\n%s\n}"
3750 name (format script (tramp-get-remote-perl vec)))
3751 "Script %s sending failed" name)
3752 (tramp-set-connection-property
3753 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3755 (defun tramp-run-test (switch filename)
3756 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3757 Returns the exit code of the `test' program."
3758 (with-parsed-tramp-file-name filename nil
3759 (tramp-send-command-and-check
3761 (format
3762 "%s %s %s"
3763 (tramp-get-test-command v)
3764 switch
3765 (tramp-shell-quote-argument localname)))))
3767 (defun tramp-run-test2 (format-string file1 file2)
3768 "Run `test'-like program on the remote system, given FILE1, FILE2.
3769 FORMAT-STRING contains the program name, switches, and place holders.
3770 Returns the exit code of the `test' program. Barfs if the methods,
3771 hosts, or files, disagree."
3772 (unless (tramp-equal-remote file1 file2)
3773 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3774 (tramp-error
3775 v 'file-error
3776 "tramp-run-test2 only implemented for same method, user, host")))
3777 (with-parsed-tramp-file-name file1 v1
3778 (with-parsed-tramp-file-name file1 v2
3779 (tramp-send-command-and-check
3781 (format format-string
3782 (tramp-shell-quote-argument v1-localname)
3783 (tramp-shell-quote-argument v2-localname))))))
3785 (defun tramp-find-executable
3786 (vec progname dirlist &optional ignore-tilde ignore-path)
3787 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3788 First arg VEC specifies the connection, PROGNAME is the program
3789 to search for, and DIRLIST gives the list of directories to
3790 search. If IGNORE-TILDE is non-nil, directory names starting
3791 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3792 only in DIRLIST.
3794 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3796 This function expects to be in the right *tramp* buffer."
3797 (with-current-buffer (tramp-get-connection-buffer vec)
3798 (let (result)
3799 ;; Check whether the executable is in $PATH. "which(1)" does not
3800 ;; report always a correct error code; therefore we check the
3801 ;; number of words it returns. "SunOS 5.10" (and maybe "SunOS
3802 ;; 5.11") have problems with this command, we disable the call
3803 ;; therefore.
3804 (unless (or ignore-path
3805 (string-match
3806 (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3807 (tramp-get-connection-property vec "uname" "")))
3808 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3809 (goto-char (point-min))
3810 (if (looking-at "^\\s-*1$")
3811 (setq result (concat "\\" progname))))
3812 (unless result
3813 (when ignore-tilde
3814 ;; Remove all ~/foo directories from dirlist.
3815 (let (newdl d)
3816 (while dirlist
3817 (setq d (car dirlist))
3818 (setq dirlist (cdr dirlist))
3819 (unless (char-equal ?~ (aref d 0))
3820 (setq newdl (cons d newdl))))
3821 (setq dirlist (nreverse newdl))))
3822 (tramp-send-command
3824 (format (concat "while read d; "
3825 "do if test -x $d/%s && test -f $d/%s; "
3826 "then echo tramp_executable $d/%s; "
3827 "break; fi; done <<'%s'\n"
3828 "%s\n%s")
3829 progname progname progname
3830 tramp-end-of-heredoc
3831 (mapconcat 'identity dirlist "\n")
3832 tramp-end-of-heredoc))
3833 (goto-char (point-max))
3834 (when (search-backward "tramp_executable " nil t)
3835 (skip-chars-forward "^ ")
3836 (skip-chars-forward " ")
3837 (setq result (buffer-substring (point) (point-at-eol)))))
3838 result)))
3840 (defun tramp-set-remote-path (vec)
3841 "Sets the remote environment PATH to existing directories.
3842 I.e., for each directory in `tramp-remote-path', it is tested
3843 whether it exists and if so, it is added to the environment
3844 variable PATH."
3845 (tramp-message vec 5 "Setting $PATH environment variable")
3846 (tramp-send-command
3847 vec (format "PATH=%s; export PATH"
3848 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3850 ;; ------------------------------------------------------------
3851 ;; -- Communication with external shell --
3852 ;; ------------------------------------------------------------
3854 (defun tramp-find-file-exists-command (vec)
3855 "Find a command on the remote host for checking if a file exists.
3856 Here, we are looking for a command which has zero exit status if the
3857 file exists and nonzero exit status otherwise."
3858 (let ((existing "/")
3859 (nonexistent
3860 (tramp-shell-quote-argument "/ this file does not exist "))
3861 result)
3862 ;; The algorithm is as follows: we try a list of several commands.
3863 ;; For each command, we first run `$cmd /' -- this should return
3864 ;; true, as the root directory always exists. And then we run
3865 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3866 ;; does not exist. This should return false. We use the first
3867 ;; command we find that seems to work.
3868 ;; The list of commands to try is as follows:
3869 ;; `ls -d' This works on most systems, but NetBSD 1.4
3870 ;; has a bug: `ls' always returns zero exit
3871 ;; status, even for files which don't exist.
3872 ;; `test -e' Some Bourne shells have a `test' builtin
3873 ;; which does not know the `-e' option.
3874 ;; `/bin/test -e' For those, the `test' binary on disk normally
3875 ;; provides the option. Alas, the binary
3876 ;; is sometimes `/bin/test' and sometimes it's
3877 ;; `/usr/bin/test'.
3878 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3879 (unless (or
3880 (ignore-errors
3881 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3882 (tramp-send-command-and-check
3883 vec (format "%s %s" result existing))
3884 (not (tramp-send-command-and-check
3885 vec (format "%s %s" result nonexistent)))))
3886 (ignore-errors
3887 (and (setq result "/bin/test -e")
3888 (tramp-send-command-and-check
3889 vec (format "%s %s" result existing))
3890 (not (tramp-send-command-and-check
3891 vec (format "%s %s" result nonexistent)))))
3892 (ignore-errors
3893 (and (setq result "/usr/bin/test -e")
3894 (tramp-send-command-and-check
3895 vec (format "%s %s" result existing))
3896 (not (tramp-send-command-and-check
3897 vec (format "%s %s" result nonexistent)))))
3898 (ignore-errors
3899 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3900 (tramp-send-command-and-check
3901 vec (format "%s %s" result existing))
3902 (not (tramp-send-command-and-check
3903 vec (format "%s %s" result nonexistent))))))
3904 (tramp-error
3905 vec 'file-error "Couldn't find command to check if file exists"))
3906 result))
3908 (defun tramp-open-shell (vec shell)
3909 "Opens shell SHELL."
3910 (with-tramp-progress-reporter
3911 vec 5 (format-message "Opening remote shell `%s'" shell)
3912 ;; Find arguments for this shell.
3913 (let ((alist tramp-sh-extra-args)
3914 item extra-args)
3915 (while (and alist (null extra-args))
3916 (setq item (pop alist))
3917 (when (string-match (car item) shell)
3918 (setq extra-args (cdr item))))
3919 ;; It is useful to set the prompt in the following command
3920 ;; because some people have a setting for $PS1 which /bin/sh
3921 ;; doesn't know about and thus /bin/sh will display a strange
3922 ;; prompt. For example, if $PS1 has "${CWD}" in the value, then
3923 ;; ksh will display the current working directory but /bin/sh
3924 ;; will display a dollar sign. The following command line sets
3925 ;; $PS1 to a sane value, and works under Bourne-ish shells as
3926 ;; well as csh-like shells. We also unset the variable $ENV
3927 ;; because that is read by some sh implementations (eg, bash
3928 ;; when called as sh) on startup; this way, we avoid the startup
3929 ;; file clobbering $PS1. $PROMPT_COMMAND is another way to set
3930 ;; the prompt in /bin/bash, it must be discarded as well.
3931 ;; $HISTFILE is set according to `tramp-histfile-override'.
3932 (tramp-send-command
3933 vec (format
3934 "exec env ENV=%s %s PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3935 (or (getenv-internal "ENV" tramp-remote-process-environment) "")
3936 (if (stringp tramp-histfile-override)
3937 (format "HISTFILE=%s"
3938 (tramp-shell-quote-argument tramp-histfile-override))
3939 (if tramp-histfile-override
3940 "HISTFILE='' HISTFILESIZE=0 HISTSIZE=0"
3941 ""))
3942 (tramp-shell-quote-argument tramp-end-of-output)
3943 shell (or extra-args ""))
3945 ;; Check proper HISTFILE setting. We give up when not working.
3946 (when (and (stringp tramp-histfile-override)
3947 (file-name-directory tramp-histfile-override))
3948 (tramp-barf-unless-okay
3950 (format
3951 "(cd %s)"
3952 (tramp-shell-quote-argument
3953 (file-name-directory tramp-histfile-override)))
3954 "`tramp-histfile-override' uses invalid file `%s'"
3955 tramp-histfile-override)))
3957 (tramp-set-connection-property
3958 (tramp-get-connection-process vec) "remote-shell" shell)))
3960 (defun tramp-find-shell (vec)
3961 "Opens a shell on the remote host which groks tilde expansion."
3962 (with-current-buffer (tramp-get-buffer vec)
3963 (let ((default-shell (tramp-get-method-parameter vec 'tramp-remote-shell))
3964 shell)
3965 (setq shell
3966 (with-tramp-connection-property vec "remote-shell"
3967 ;; CCC: "root" does not exist always, see my QNAP TS-459.
3968 ;; Which check could we apply instead?
3969 (tramp-send-command vec "echo ~root" t)
3970 (if (or (string-match "^~root$" (buffer-string))
3971 ;; The default shell (ksh93) of OpenSolaris and
3972 ;; Solaris is buggy. We've got reports for
3973 ;; "SunOS 5.10" and "SunOS 5.11" so far.
3974 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3975 (tramp-get-connection-property
3976 vec "uname" "")))
3978 (or (tramp-find-executable
3979 vec "bash" (tramp-get-remote-path vec) t t)
3980 (tramp-find-executable
3981 vec "ksh" (tramp-get-remote-path vec) t t)
3982 ;; Maybe it works at least for some other commands.
3983 (prog1
3984 default-shell
3985 (tramp-message
3986 vec 2
3987 (concat
3988 "Couldn't find a remote shell which groks tilde "
3989 "expansion, using `%s'")
3990 default-shell)))
3992 default-shell)))
3994 ;; Open a new shell if needed.
3995 (unless (string-equal shell default-shell)
3996 (tramp-message
3997 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
3998 (tramp-open-shell vec shell)))))
4000 ;; Utility functions.
4002 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
4003 "Wait for shell prompt and barf if none appears.
4004 Looks at process PROC to see if a shell prompt appears in TIMEOUT
4005 seconds. If not, it produces an error message with the given ERROR-ARGS."
4006 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4007 (condition-case nil
4008 (tramp-wait-for-regexp
4009 proc timeout
4010 (format
4011 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
4012 (error
4013 (delete-process proc)
4014 (apply 'tramp-error-with-buffer
4015 (tramp-get-connection-buffer vec) vec 'file-error error-args)))))
4017 (defun tramp-open-connection-setup-interactive-shell (proc vec)
4018 "Set up an interactive shell.
4019 Mainly sets the prompt and the echo correctly. PROC is the shell
4020 process to set up. VEC specifies the connection."
4021 (let ((tramp-end-of-output tramp-initial-end-of-output)
4022 (case-fold-search t))
4023 (tramp-open-shell vec (tramp-get-method-parameter vec 'tramp-remote-shell))
4025 ;; Disable echo expansion.
4026 (tramp-message vec 5 "Setting up remote shell environment")
4027 (tramp-send-command
4028 vec "stty -inlcr -onlcr -echo kill '^U' erase '^H'" t)
4029 ;; Check whether the echo has really been disabled. Some
4030 ;; implementations, like busybox of embedded GNU/Linux, don't
4031 ;; support disabling.
4032 (tramp-send-command vec "echo foo" t)
4033 (with-current-buffer (process-buffer proc)
4034 (goto-char (point-min))
4035 (when (looking-at "echo foo")
4036 (tramp-set-connection-property proc "remote-echo" t)
4037 (tramp-message vec 5 "Remote echo still on. Ok.")
4038 ;; Make sure backspaces and their echo are enabled and no line
4039 ;; width magic interferes with them.
4040 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
4042 (tramp-message vec 5 "Setting shell prompt")
4043 (tramp-send-command
4044 vec (format "PS1=%s PS2='' PS3='' PROMPT_COMMAND=''"
4045 (tramp-shell-quote-argument tramp-end-of-output))
4048 ;; Check whether the output of "uname -sr" has been changed. If
4049 ;; yes, this is a strong indication that we must expire all
4050 ;; connection properties. We start again with
4051 ;; `tramp-maybe-open-connection', it will be caught there.
4052 (tramp-message vec 5 "Checking system information")
4053 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
4054 (uname
4055 (tramp-set-connection-property
4056 vec "uname"
4057 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
4058 (when (and (stringp old-uname) (not (string-equal old-uname uname)))
4059 (tramp-message
4060 vec 3
4061 "Connection reset, because remote host changed from `%s' to `%s'"
4062 old-uname uname)
4063 ;; We want to keep the password.
4064 (tramp-cleanup-connection vec t t)
4065 (throw 'uname-changed (tramp-maybe-open-connection vec)))
4067 ;; Try to set up the coding system correctly.
4068 ;; CCC this can't be the right way to do it. Hm.
4069 (tramp-message vec 5 "Determining coding system")
4070 (with-current-buffer (process-buffer proc)
4071 ;; Use MULE to select the right EOL convention for communicating
4072 ;; with the process.
4073 (let ((cs (or (and (memq 'utf-8 (coding-system-list))
4074 (string-match "utf-?8" (tramp-get-remote-locale vec))
4075 (cons 'utf-8 'utf-8))
4076 (process-coding-system proc)
4077 (cons 'undecided 'undecided)))
4078 cs-decode cs-encode)
4079 (when (symbolp cs) (setq cs (cons cs cs)))
4080 (setq cs-decode (or (car cs) 'undecided)
4081 cs-encode (or (cdr cs) 'undecided)
4082 cs-encode
4083 (coding-system-change-eol-conversion
4084 cs-encode (if (string-match "^Darwin" uname) 'mac 'unix)))
4085 (tramp-send-command vec "echo foo ; echo bar" t)
4086 (goto-char (point-min))
4087 (when (search-forward "\r" nil t)
4088 (setq cs-decode (coding-system-change-eol-conversion cs-decode 'dos)))
4089 ;; Special setting for macOS.
4090 (when (and (string-match "^Darwin" uname)
4091 (memq 'utf-8-hfs (coding-system-list)))
4092 (setq cs-decode 'utf-8-hfs
4093 cs-encode 'utf-8-hfs))
4094 (set-buffer-process-coding-system cs-decode cs-encode)
4095 (tramp-message
4096 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode)))
4098 (tramp-send-command vec "set +o vi +o emacs" t)
4100 ;; Check whether the remote host suffers from buggy
4101 ;; `send-process-string'. This is known for FreeBSD (see comment
4102 ;; in `send_process', file process.c). I've tested sending 624
4103 ;; bytes successfully, sending 625 bytes failed. Emacs makes a
4104 ;; hack when this host type is detected locally. It cannot handle
4105 ;; remote hosts, though.
4106 (with-tramp-connection-property proc "chunksize"
4107 (cond
4108 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
4109 tramp-chunksize)
4111 (tramp-message
4112 vec 5 "Checking remote host type for `send-process-string' bug")
4113 (if (string-match "^FreeBSD" uname) 500 0))))
4115 ;; Set remote PATH variable.
4116 (tramp-set-remote-path vec)
4118 ;; Search for a good shell before searching for a command which
4119 ;; checks if a file exists. This is done because Tramp wants to
4120 ;; use "test foo; echo $?" to check if various conditions hold,
4121 ;; and there are buggy /bin/sh implementations which don't execute
4122 ;; the "echo $?" part if the "test" part has an error. In
4123 ;; particular, the OpenSolaris /bin/sh is a problem. There are
4124 ;; also other problems with /bin/sh of OpenSolaris, like
4125 ;; redirection of stderr in function declarations, or changing
4126 ;; HISTFILE in place. Therefore, OpenSolaris' /bin/sh is replaced
4127 ;; by bash, when detected.
4128 (tramp-find-shell vec)
4130 ;; Disable unexpected output.
4131 (tramp-send-command vec "mesg n 2>/dev/null; biff n 2>/dev/null" t)
4133 ;; IRIX64 bash expands "!" even when in single quotes. This
4134 ;; destroys our shell functions, we must disable it. See
4135 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
4136 (when (string-match "^IRIX64" uname)
4137 (tramp-send-command vec "set +H" t))
4139 ;; Disable tab expansion.
4140 (if (string-match "BSD\\|Darwin" uname)
4141 (tramp-send-command vec "stty tabs" t)
4142 (tramp-send-command vec "stty tab0" t))
4144 ;; Set utf8 encoding. Needed for macOS, for example. This is
4145 ;; non-POSIX, so we must expect errors on some systems.
4146 (tramp-send-command vec "stty iutf8 2>/dev/null" t)
4148 ;; Set `remote-tty' process property.
4149 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
4150 (unless (zerop (length tty))
4151 (process-put proc 'remote-tty tty)))
4153 ;; Dump stty settings in the traces.
4154 (when (>= tramp-verbose 9)
4155 (tramp-send-command vec "stty -a" t))
4157 ;; Set the environment.
4158 (tramp-message vec 5 "Setting default environment")
4160 (let (unset vars)
4161 (dolist (item (reverse
4162 (append `(,(tramp-get-remote-locale vec))
4163 (copy-sequence tramp-remote-process-environment))))
4164 (setq item (split-string item "=" 'omit))
4165 (setcdr item (mapconcat 'identity (cdr item) "="))
4166 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
4167 (push (format "%s %s" (car item) (cdr item)) vars)
4168 (push (car item) unset)))
4169 (when vars
4170 (tramp-send-command
4172 (format
4173 "while read var val; do export $var=\"$val\"; done <<'%s'\n%s\n%s"
4174 tramp-end-of-heredoc
4175 (mapconcat 'identity vars "\n")
4176 tramp-end-of-heredoc)
4178 (when unset
4179 (tramp-send-command
4180 vec (format "unset %s" (mapconcat 'identity unset " ")) t)))))
4182 ;; Old text from documentation of tramp-methods:
4183 ;; Using a uuencode/uudecode inline method is discouraged, please use one
4184 ;; of the base64 methods instead since base64 encoding is much more
4185 ;; reliable and the commands are more standardized between the different
4186 ;; Unix versions. But if you can't use base64 for some reason, please
4187 ;; note that the default uudecode command does not work well for some
4188 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
4189 ;; the following command for uudecode:
4191 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
4193 ;; For Irix, no solution is known yet.
4195 (autoload 'uudecode-decode-region "uudecode")
4197 (defconst tramp-local-coding-commands
4198 `((b64 base64-encode-region base64-decode-region)
4199 (uu tramp-uuencode-region uudecode-decode-region)
4200 (pack ,(format tramp-perl-pack "perl") ,(format tramp-perl-unpack "perl")))
4201 "List of local coding commands for inline transfer.
4202 Each item is a list that looks like this:
4204 \(FORMAT ENCODING DECODING)
4206 FORMAT is symbol describing the encoding/decoding format. It can be
4207 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4209 ENCODING and DECODING can be strings, giving commands, or symbols,
4210 giving functions. If they are strings, then they can contain
4211 the \"%s\" format specifier. If that specifier is present, the input
4212 file name will be put into the command line at that spot. If the
4213 specifier is not present, the input should be read from standard
4214 input.
4216 If they are functions, they will be called with two arguments, start
4217 and end of region, and are expected to replace the region contents
4218 with the encoded or decoded results, respectively.")
4220 (defconst tramp-remote-coding-commands
4221 `((b64 "base64" "base64 -d -i")
4222 ;; "-i" is more robust with older base64 from GNU coreutils.
4223 ;; However, I don't know whether all base64 versions do supports
4224 ;; this option.
4225 (b64 "base64" "base64 -d")
4226 (b64 "openssl enc -base64" "openssl enc -d -base64")
4227 (b64 "mimencode -b" "mimencode -u -b")
4228 (b64 "mmencode -b" "mmencode -u -b")
4229 (b64 "recode data..base64" "recode base64..data")
4230 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
4231 (b64 tramp-perl-encode tramp-perl-decode)
4232 ;; This is painful slow, so we put it on the end.
4233 (b64 tramp-awk-encode tramp-awk-decode ,tramp-awk-coding-test)
4234 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
4235 (uu "uuencode xxx" "uudecode -o -")
4236 (uu "uuencode xxx" "uudecode -p")
4237 (uu "uuencode xxx" tramp-uudecode)
4238 (pack tramp-perl-pack tramp-perl-unpack))
4239 "List of remote coding commands for inline transfer.
4240 Each item is a list that looks like this:
4242 \(FORMAT ENCODING DECODING [TEST])
4244 FORMAT is a symbol describing the encoding/decoding format. It can be
4245 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4247 ENCODING and DECODING can be strings, giving commands, or symbols,
4248 giving variables. If they are strings, then they can contain
4249 the \"%s\" format specifier. If that specifier is present, the input
4250 file name will be put into the command line at that spot. If the
4251 specifier is not present, the input should be read from standard
4252 input.
4254 If they are variables, this variable is a string containing a
4255 Perl or Shell implementation for this functionality. This
4256 program will be transferred to the remote host, and it is
4257 available as shell function with the same name. A \"%t\" format
4258 specifier in the variable value denotes a temporary file.
4260 The optional TEST command can be used for further tests, whether
4261 ENCODING and DECODING are applicable.")
4263 (defun tramp-find-inline-encoding (vec)
4264 "Find an inline transfer encoding that works.
4265 Goes through the list `tramp-local-coding-commands' and
4266 `tramp-remote-coding-commands'."
4267 (save-excursion
4268 (let ((local-commands tramp-local-coding-commands)
4269 (magic "xyzzy")
4270 (p (tramp-get-connection-process vec))
4271 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4272 (while (and local-commands (not found))
4273 (setq litem (pop local-commands))
4274 (catch 'wont-work-local
4275 (let ((format (nth 0 litem))
4276 (remote-commands tramp-remote-coding-commands))
4277 (setq loc-enc (nth 1 litem))
4278 (setq loc-dec (nth 2 litem))
4279 ;; If the local encoder or decoder is a string, the
4280 ;; corresponding command has to work locally.
4281 (if (not (stringp loc-enc))
4282 (tramp-message
4283 vec 5 "Checking local encoding function `%s'" loc-enc)
4284 (tramp-message
4285 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4286 (unless (zerop (tramp-call-local-coding-command
4287 loc-enc nil nil))
4288 (throw 'wont-work-local nil)))
4289 (if (not (stringp loc-dec))
4290 (tramp-message
4291 vec 5 "Checking local decoding function `%s'" loc-dec)
4292 (tramp-message
4293 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4294 (unless (zerop (tramp-call-local-coding-command
4295 loc-dec nil nil))
4296 (throw 'wont-work-local nil)))
4297 ;; Search for remote coding commands with the same format
4298 (while (and remote-commands (not found))
4299 (setq ritem (pop remote-commands))
4300 (catch 'wont-work-remote
4301 (when (equal format (nth 0 ritem))
4302 (setq rem-enc (nth 1 ritem))
4303 (setq rem-dec (nth 2 ritem))
4304 (setq rem-test (nth 3 ritem))
4305 ;; Check the remote test command if exists.
4306 (when (stringp rem-test)
4307 (tramp-message
4308 vec 5 "Checking remote test command `%s'" rem-test)
4309 (unless (tramp-send-command-and-check vec rem-test t)
4310 (throw 'wont-work-remote nil)))
4311 ;; Check if remote perl exists when necessary.
4312 (when (and (symbolp rem-enc)
4313 (string-match "perl" (symbol-name rem-enc))
4314 (not (tramp-get-remote-perl vec)))
4315 (throw 'wont-work-remote nil))
4316 ;; Check if remote encoding and decoding commands can be
4317 ;; called remotely with null input and output. This makes
4318 ;; sure there are no syntax errors and the command is really
4319 ;; found. Note that we do not redirect stdout to /dev/null,
4320 ;; for two reasons: when checking the decoding command, we
4321 ;; actually check the output it gives. And also, when
4322 ;; redirecting "mimencode" output to /dev/null, then as root
4323 ;; it might change the permissions of /dev/null!
4324 (when (not (stringp rem-enc))
4325 (let ((name (symbol-name rem-enc)))
4326 (while (string-match (regexp-quote "-") name)
4327 (setq name (replace-match "_" nil t name)))
4328 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4329 (setq rem-enc name)))
4330 (tramp-message
4331 vec 5
4332 "Checking remote encoding command `%s' for sanity" rem-enc)
4333 (unless (tramp-send-command-and-check
4334 vec (format "%s </dev/null" rem-enc) t)
4335 (throw 'wont-work-remote nil))
4337 (when (not (stringp rem-dec))
4338 (let ((name (symbol-name rem-dec))
4339 (value (symbol-value rem-dec))
4340 tmpfile)
4341 (while (string-match (regexp-quote "-") name)
4342 (setq name (replace-match "_" nil t name)))
4343 (when (string-match "\\(^\\|[^%]\\)%t" value)
4344 (setq tmpfile
4345 (make-temp-name
4346 (expand-file-name
4347 tramp-temp-name-prefix
4348 (tramp-get-remote-tmpdir vec)))
4349 value
4350 (format-spec
4351 value
4352 (format-spec-make
4354 (file-remote-p tmpfile 'localname)))))
4355 (tramp-maybe-send-script vec value name)
4356 (setq rem-dec name)))
4357 (tramp-message
4358 vec 5
4359 "Checking remote decoding command `%s' for sanity" rem-dec)
4360 (unless (tramp-send-command-and-check
4362 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4364 (throw 'wont-work-remote nil))
4366 (with-current-buffer (tramp-get-buffer vec)
4367 (goto-char (point-min))
4368 (unless (looking-at (regexp-quote magic))
4369 (throw 'wont-work-remote nil)))
4371 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4372 (setq rem-enc (nth 1 ritem))
4373 (setq rem-dec (nth 2 ritem))
4374 (setq found t)))))))
4376 (when found
4377 ;; Set connection properties. Since the commands are risky
4378 ;; (due to output direction), we cache them in the process cache.
4379 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4380 (tramp-set-connection-property p "local-encoding" loc-enc)
4381 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4382 (tramp-set-connection-property p "local-decoding" loc-dec)
4383 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4384 (tramp-set-connection-property p "remote-encoding" rem-enc)
4385 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4386 (tramp-set-connection-property p "remote-decoding" rem-dec)))))
4388 (defun tramp-call-local-coding-command (cmd input output)
4389 "Call the local encoding or decoding command.
4390 If CMD contains \"%s\", provide input file INPUT there in command.
4391 Otherwise, INPUT is passed via standard input.
4392 INPUT can also be nil which means `/dev/null'.
4393 OUTPUT can be a string (which specifies a file name), or t (which
4394 means standard output and thus the current buffer), or nil (which
4395 means discard it)."
4396 (tramp-call-process
4397 nil tramp-encoding-shell
4398 (when (and input (not (string-match "%s" cmd))) input)
4399 (if (eq output t) t nil)
4401 tramp-encoding-command-switch
4402 (concat
4403 (if (string-match "%s" cmd) (format cmd input) cmd)
4404 (if (stringp output) (concat " >" output) ""))))
4406 (defconst tramp-inline-compress-commands
4407 '(("gzip" "gzip -d")
4408 ("bzip2" "bzip2 -d")
4409 ("xz" "xz -d")
4410 ("compress" "compress -d"))
4411 "List of compress and decompress commands for inline transfer.
4412 Each item is a list that looks like this:
4414 \(COMPRESS DECOMPRESS)
4416 COMPRESS or DECOMPRESS are strings with the respective commands.")
4418 (defun tramp-find-inline-compress (vec)
4419 "Find an inline transfer compress command that works.
4420 Goes through the list `tramp-inline-compress-commands'."
4421 (save-excursion
4422 (let ((commands tramp-inline-compress-commands)
4423 (magic "xyzzy")
4424 (p (tramp-get-connection-process vec))
4425 item compress decompress found)
4426 (while (and commands (not found))
4427 (catch 'next
4428 (setq item (pop commands)
4429 compress (nth 0 item)
4430 decompress (nth 1 item))
4431 (tramp-message
4432 vec 5
4433 "Checking local compress commands `%s', `%s' for sanity"
4434 compress decompress)
4435 (unless
4436 (zerop
4437 (tramp-call-local-coding-command
4438 (format
4439 ;; Windows shells need the program file name after
4440 ;; the pipe symbol be quoted if they use forward
4441 ;; slashes as directory separators.
4442 (if (memq system-type '(windows-nt))
4443 "echo %s | \"%s\" | \"%s\""
4444 "echo %s | %s | %s")
4445 magic compress decompress) nil nil))
4446 (throw 'next nil))
4447 (tramp-message
4448 vec 5
4449 "Checking remote compress commands `%s', `%s' for sanity"
4450 compress decompress)
4451 (unless (tramp-send-command-and-check
4452 vec (format "echo %s | %s | %s" magic compress decompress) t)
4453 (throw 'next nil))
4454 (setq found t)))
4456 ;; Did we find something?
4457 (if found
4458 (progn
4459 ;; Set connection properties. Since the commands are
4460 ;; risky (due to output direction), we cache them in the
4461 ;; process cache.
4462 (tramp-message
4463 vec 5 "Using inline transfer compress command `%s'" compress)
4464 (tramp-set-connection-property p "inline-compress" compress)
4465 (tramp-message
4466 vec 5 "Using inline transfer decompress command `%s'" decompress)
4467 (tramp-set-connection-property p "inline-decompress" decompress))
4469 (tramp-set-connection-property p "inline-compress" nil)
4470 (tramp-set-connection-property p "inline-decompress" nil)
4471 (tramp-message
4472 vec 2 "Couldn't find an inline transfer compress command")))))
4474 (defun tramp-compute-multi-hops (vec)
4475 "Expands VEC according to `tramp-default-proxies-alist'."
4476 (let ((target-alist `(,vec))
4477 (hops (or (tramp-file-name-hop vec) ""))
4478 (item vec)
4479 choices proxy)
4481 ;; Ad-hoc proxy definitions.
4482 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4483 (let ((user (tramp-file-name-user item))
4484 (host (tramp-file-name-host item))
4485 (proxy (concat
4486 tramp-prefix-format proxy tramp-postfix-host-format)))
4487 (tramp-message
4488 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4489 (and (stringp host) (regexp-quote host))
4490 (and (stringp user) (regexp-quote user))
4491 proxy)
4492 ;; Add the hop.
4493 (add-to-list
4494 'tramp-default-proxies-alist
4495 (list (and (stringp host) (regexp-quote host))
4496 (and (stringp user) (regexp-quote user))
4497 proxy))
4498 (setq item (tramp-dissect-file-name proxy))))
4499 ;; Save the new value.
4500 (when (and hops tramp-save-ad-hoc-proxies)
4501 (customize-save-variable
4502 'tramp-default-proxies-alist tramp-default-proxies-alist))
4504 ;; Look for proxy hosts to be passed.
4505 (setq choices tramp-default-proxies-alist)
4506 (while choices
4507 (setq item (pop choices)
4508 proxy (eval (nth 2 item)))
4509 (when (and
4510 ;; Host.
4511 (string-match (or (eval (nth 0 item)) "")
4512 (or (tramp-file-name-host (car target-alist)) ""))
4513 ;; User.
4514 (string-match (or (eval (nth 1 item)) "")
4515 (or (tramp-file-name-user (car target-alist)) "")))
4516 (if (null proxy)
4517 ;; No more hops needed.
4518 (setq choices nil)
4519 ;; Replace placeholders.
4520 (setq proxy
4521 (format-spec
4522 proxy
4523 (format-spec-make
4524 ?u (or (tramp-file-name-user (car target-alist)) "")
4525 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4526 (with-parsed-tramp-file-name proxy l
4527 ;; Add the hop.
4528 (push l target-alist)
4529 ;; Start next search.
4530 (setq choices tramp-default-proxies-alist)))))
4532 ;; Foreign and out-of-band methods are not supported for multi-hops.
4533 (when (cdr target-alist)
4534 (setq choices target-alist)
4535 (while (setq item (pop choices))
4536 (when (or (not (tramp-get-method-parameter item 'tramp-login-program))
4537 (tramp-get-method-parameter item 'tramp-copy-program))
4538 (tramp-error
4539 vec 'file-error
4540 "Method `%s' is not supported for multi-hops."
4541 (tramp-file-name-method item)))))
4543 ;; In case the host name is not used for the remote shell
4544 ;; command, the user could be misguided by applying a random
4545 ;; host name.
4546 (let* ((v (car target-alist))
4547 (method (tramp-file-name-method v))
4548 (host (tramp-file-name-host v)))
4549 (unless
4551 ;; There are multi-hops.
4552 (cdr target-alist)
4553 ;; The host name is used for the remote shell command.
4554 (member '("%h") (tramp-get-method-parameter v 'tramp-login-args))
4555 ;; The host is local. We cannot use `tramp-local-host-p'
4556 ;; here, because it opens a connection as well.
4557 (string-match tramp-local-host-regexp host))
4558 (tramp-error
4559 v 'file-error
4560 "Host `%s' looks like a remote host, `%s' can only use the local host"
4561 host method)))
4563 ;; Result.
4564 target-alist))
4566 (defun tramp-ssh-controlmaster-options (vec)
4567 "Return the Control* arguments of the local ssh."
4568 (cond
4569 ;; No options to be computed.
4570 ((or (null tramp-use-ssh-controlmaster-options)
4571 (null (assoc "%c" (tramp-get-method-parameter vec 'tramp-login-args))))
4574 ;; There is already a value to be used.
4575 ((stringp tramp-ssh-controlmaster-options) tramp-ssh-controlmaster-options)
4577 ;; Determine the options.
4578 (t (setq tramp-ssh-controlmaster-options "")
4579 (let ((case-fold-search t))
4580 (ignore-errors
4581 (when (executable-find "ssh")
4582 (with-temp-buffer
4583 (tramp-call-process vec "ssh" nil t nil "-o" "ControlMaster")
4584 (goto-char (point-min))
4585 (when (search-forward-regexp "missing.+argument" nil t)
4586 (setq tramp-ssh-controlmaster-options "-o ControlMaster=auto")))
4587 (unless (zerop (length tramp-ssh-controlmaster-options))
4588 (with-temp-buffer
4589 ;; We use a non-existing IP address, in order to avoid
4590 ;; useless connections, and DNS timeouts.
4591 (tramp-call-process
4592 vec "ssh" nil t nil "-o" "ControlPath=%C" "0.0.0.1")
4593 (goto-char (point-min))
4594 (setq tramp-ssh-controlmaster-options
4595 (concat tramp-ssh-controlmaster-options
4596 (if (search-forward-regexp "unknown.+key" nil t)
4597 " -o ControlPath='tramp.%%r@%%h:%%p'"
4598 " -o ControlPath='tramp.%%C'"))))
4599 (with-temp-buffer
4600 (tramp-call-process vec "ssh" nil t nil "-o" "ControlPersist")
4601 (goto-char (point-min))
4602 (when (search-forward-regexp "missing.+argument" nil t)
4603 (setq tramp-ssh-controlmaster-options
4604 (concat tramp-ssh-controlmaster-options
4605 " -o ControlPersist=no"))))))))
4606 tramp-ssh-controlmaster-options)))
4608 (defun tramp-maybe-open-connection (vec)
4609 "Maybe open a connection VEC.
4610 Does not do anything if a connection is already open, but re-opens the
4611 connection if a previous connection has died for some reason."
4612 (tramp-check-proper-method-and-host vec)
4614 (let ((p (tramp-get-connection-process vec))
4615 (process-name (tramp-get-connection-property vec "process-name" nil))
4616 (process-environment (copy-sequence process-environment))
4617 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4619 ;; If Tramp opens the same connection within a short time frame,
4620 ;; there is a problem. We shall signal this.
4621 (unless (or (tramp-compat-process-live-p p)
4622 (not (equal (butlast (append vec nil) 2)
4623 (car tramp-current-connection)))
4624 (> (tramp-time-diff
4625 (current-time) (cdr tramp-current-connection))
4626 (or tramp-connection-min-time-diff 0)))
4627 (throw 'suppress 'suppress))
4629 ;; If too much time has passed since last command was sent, look
4630 ;; whether process is still alive. If it isn't, kill it. When
4631 ;; using ssh, it can sometimes happen that the remote end has hung
4632 ;; up but the local ssh client doesn't recognize this until it
4633 ;; tries to send some data to the remote end. So that's why we
4634 ;; try to send a command from time to time, then look again
4635 ;; whether the process is really alive.
4636 (condition-case nil
4637 (when (and (> (tramp-time-diff
4638 (current-time)
4639 (tramp-get-connection-property
4640 p "last-cmd-time" '(0 0 0)))
4642 (tramp-compat-process-live-p p))
4643 (tramp-send-command vec "echo are you awake" t t)
4644 (unless (and (tramp-compat-process-live-p p)
4645 (tramp-wait-for-output p 10))
4646 ;; The error will be caught locally.
4647 (tramp-error vec 'file-error "Awake did fail")))
4648 (file-error
4649 (tramp-cleanup-connection vec t)
4650 (setq p nil)))
4652 ;; New connection must be opened.
4653 (condition-case err
4654 (unless (tramp-compat-process-live-p p)
4656 ;; If `non-essential' is non-nil, don't reopen a new connection.
4657 ;; This variable has been introduced with Emacs 24.1.
4658 ;; We check this for the process related to
4659 ;; `tramp-buffer-name'; otherwise `start-file-process'
4660 ;; wouldn't run ever when `non-essential' is non-nil.
4661 (when (and (boundp 'non-essential) (symbol-value 'non-essential)
4662 (null (get-process (tramp-buffer-name vec))))
4663 (throw 'non-essential 'non-essential))
4665 (with-tramp-progress-reporter
4666 vec 3
4667 (if (zerop (length (tramp-file-name-user vec)))
4668 (format "Opening connection for %s using %s"
4669 (tramp-file-name-host vec)
4670 (tramp-file-name-method vec))
4671 (format "Opening connection for %s@%s using %s"
4672 (tramp-file-name-user vec)
4673 (tramp-file-name-host vec)
4674 (tramp-file-name-method vec)))
4676 (catch 'uname-changed
4677 ;; Start new process.
4678 (when (and p (processp p))
4679 (delete-process p))
4680 (setenv "TERM" tramp-terminal-type)
4681 (setenv "LC_ALL" (tramp-get-local-locale vec))
4682 (if (stringp tramp-histfile-override)
4683 (setenv "HISTFILE" tramp-histfile-override)
4684 (if tramp-histfile-override
4685 (progn
4686 (setenv "HISTFILE")
4687 (setenv "HISTFILESIZE" "0")
4688 (setenv "HISTSIZE" "0"))))
4689 (setenv "PROMPT_COMMAND")
4690 (setenv "PS1" tramp-initial-end-of-output)
4691 (unless (stringp tramp-encoding-shell)
4692 (tramp-error vec 'file-error "`tramp-encoding-shell' not set"))
4693 (let* ((target-alist (tramp-compute-multi-hops vec))
4694 ;; We will apply `tramp-ssh-controlmaster-options'
4695 ;; only for the first hop.
4696 (options (tramp-ssh-controlmaster-options vec))
4697 (process-connection-type tramp-process-connection-type)
4698 (process-adaptive-read-buffering nil)
4699 ;; There are unfortunate settings for "cmdproxy" on
4700 ;; W32 systems.
4701 (process-coding-system-alist nil)
4702 (coding-system-for-read nil)
4703 ;; This must be done in order to avoid our file
4704 ;; name handler.
4705 (p (let ((default-directory
4706 (tramp-compat-temporary-file-directory)))
4707 (apply
4708 'start-process
4709 (tramp-get-connection-name vec)
4710 (tramp-get-connection-buffer vec)
4711 (if tramp-encoding-command-interactive
4712 (list tramp-encoding-shell
4713 tramp-encoding-command-interactive)
4714 (list tramp-encoding-shell))))))
4716 ;; Set sentinel and query flag.
4717 (tramp-set-connection-property p "vector" vec)
4718 (set-process-sentinel p 'tramp-process-sentinel)
4719 (set-process-query-on-exit-flag p nil)
4720 (setq tramp-current-connection
4721 (cons (butlast (append vec nil) 2) (current-time))
4722 tramp-current-host (system-name))
4724 (tramp-message
4725 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4727 ;; Check whether process is alive.
4728 (tramp-barf-if-no-shell-prompt
4729 p 10
4730 "Couldn't find local shell prompt for %s" tramp-encoding-shell)
4732 ;; Now do all the connections as specified.
4733 (while target-alist
4734 (let* ((hop (car target-alist))
4735 (l-method (tramp-file-name-method hop))
4736 (l-user (tramp-file-name-user hop))
4737 (l-host (tramp-file-name-host hop))
4738 (l-port nil)
4739 (login-program
4740 (tramp-get-method-parameter hop 'tramp-login-program))
4741 (login-args
4742 (tramp-get-method-parameter hop 'tramp-login-args))
4743 (login-env
4744 (tramp-get-method-parameter hop 'tramp-login-env))
4745 (async-args
4746 (tramp-get-method-parameter hop 'tramp-async-args))
4747 (connection-timeout
4748 (tramp-get-method-parameter
4749 hop 'tramp-connection-timeout))
4750 (command login-program)
4751 ;; We don't create the temporary file. In
4752 ;; fact, it is just a prefix for the
4753 ;; ControlPath option of ssh; the real
4754 ;; temporary file has another name, and it is
4755 ;; created and protected by ssh. It is also
4756 ;; removed by ssh when the connection is
4757 ;; closed. The temporary file name is cached
4758 ;; in the main connection process, therefore
4759 ;; we cannot use `tramp-get-connection-process'.
4760 (tmpfile
4761 (with-tramp-connection-property
4762 (get-process (tramp-buffer-name vec)) "temp-file"
4763 (make-temp-name
4764 (expand-file-name
4765 tramp-temp-name-prefix
4766 (tramp-compat-temporary-file-directory)))))
4767 spec r-shell)
4769 ;; Add arguments for asynchronous processes.
4770 (when (and process-name async-args)
4771 (setq login-args (append async-args login-args)))
4773 ;; Check for port number. Until now, there's no
4774 ;; need for handling like method, user, host.
4775 (when (string-match tramp-host-with-port-regexp l-host)
4776 (setq l-port (match-string 2 l-host)
4777 l-host (match-string 1 l-host)))
4779 ;; Check, whether there is a restricted shell.
4780 (dolist (elt tramp-restricted-shell-hosts-alist)
4781 (when (string-match elt tramp-current-host)
4782 (setq r-shell t)))
4784 ;; Set variables for computing the prompt for
4785 ;; reading password.
4786 (setq tramp-current-method l-method
4787 tramp-current-user l-user
4788 tramp-current-host l-host)
4790 ;; Add login environment.
4791 (when login-env
4792 (setq
4793 login-env
4794 (mapcar
4795 (lambda (x)
4796 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4797 (unless (member "" x) (mapconcat 'identity x " ")))
4798 login-env))
4799 (while login-env
4800 (setq command
4801 (format
4802 "%s=%s %s"
4803 (pop login-env)
4804 (tramp-shell-quote-argument (pop login-env))
4805 command)))
4806 (setq command (concat "env " command)))
4808 ;; Replace `login-args' place holders.
4809 (setq
4810 l-host (or l-host "")
4811 l-user (or l-user "")
4812 l-port (or l-port "")
4813 spec (format-spec-make ?t tmpfile)
4814 options (format-spec options spec)
4815 spec (format-spec-make
4816 ?h l-host ?u l-user ?p l-port ?c options)
4817 command
4818 (concat
4819 ;; We do not want to see the trailing local
4820 ;; prompt in `start-file-process'.
4821 (unless r-shell "exec ")
4822 command " "
4823 (mapconcat
4824 (lambda (x)
4825 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4826 (unless (member "" x) (mapconcat 'identity x " ")))
4827 login-args " ")
4828 ;; Local shell could be a Windows COMSPEC. It
4829 ;; doesn't know the ";" syntax, but we must exit
4830 ;; always for `start-file-process'. It could
4831 ;; also be a restricted shell, which does not
4832 ;; allow "exec".
4833 (when r-shell " && exit || exit")))
4835 ;; Send the command.
4836 (tramp-message vec 3 "Sending command `%s'" command)
4837 (tramp-send-command vec command t t)
4838 (tramp-process-actions
4839 p vec
4840 (min
4841 pos (with-current-buffer (process-buffer p) (point-max)))
4842 tramp-actions-before-shell
4843 (or connection-timeout tramp-connection-timeout))
4844 (tramp-message
4845 vec 3 "Found remote shell prompt on `%s'" l-host))
4846 ;; Next hop.
4847 (setq options ""
4848 target-alist (cdr target-alist)))
4850 ;; Set connection-local variables.
4851 (tramp-set-connection-local-variables vec)
4853 ;; Make initial shell settings.
4854 (tramp-open-connection-setup-interactive-shell p vec)
4856 ;; Mark it as connected.
4857 (tramp-set-connection-property p "connected" t)))))
4859 ;; Cleanup, and propagate the signal.
4860 ((error quit)
4861 (tramp-cleanup-connection vec t)
4862 (signal (car err) (cdr err))))))
4864 (defun tramp-send-command (vec command &optional neveropen nooutput)
4865 "Send the COMMAND to connection VEC.
4866 Erases temporary buffer before sending the command. If optional
4867 arg NEVEROPEN is non-nil, never try to open the connection. This
4868 is meant to be used from `tramp-maybe-open-connection' only. The
4869 function waits for output unless NOOUTPUT is set."
4870 (unless neveropen (tramp-maybe-open-connection vec))
4871 (let ((p (tramp-get-connection-process vec)))
4872 (when (tramp-get-connection-property p "remote-echo" nil)
4873 ;; We mark the command string that it can be erased in the output buffer.
4874 (tramp-set-connection-property p "check-remote-echo" t)
4875 ;; If we put `tramp-echo-mark' after a trailing newline (which
4876 ;; is assumed to be unquoted) `tramp-send-string' doesn't see
4877 ;; that newline and adds `tramp-rsh-end-of-line' right after
4878 ;; `tramp-echo-mark', so the remote shell sees two consecutive
4879 ;; trailing line endings and sends two prompts after executing
4880 ;; the command, which confuses `tramp-wait-for-output'.
4881 (when (and (not (string= command ""))
4882 (string-equal (substring command -1) "\n"))
4883 (setq command (substring command 0 -1)))
4884 ;; No need to restore a trailing newline here since `tramp-send-string'
4885 ;; makes sure that the string ends in `tramp-rsh-end-of-line', anyway.
4886 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4887 ;; Send the command.
4888 (tramp-message vec 6 "%s" command)
4889 (tramp-send-string vec command)
4890 (unless nooutput (tramp-wait-for-output p))))
4892 (defun tramp-wait-for-output (proc &optional timeout)
4893 "Wait for output from remote command."
4894 (unless (buffer-live-p (process-buffer proc))
4895 (delete-process proc)
4896 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4897 (with-current-buffer (process-buffer proc)
4898 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4899 ;; be leading escape sequences, which must be ignored.
4900 ;; Busyboxes built with the EDITING_ASK_TERMINAL config
4901 ;; option send also escape sequences, which must be
4902 ;; ignored.
4903 (regexp (format "[^#$\n]*%s\\(%s\\)?\r?$"
4904 (regexp-quote tramp-end-of-output)
4905 tramp-device-escape-sequence-regexp))
4906 ;; Sometimes, the commands do not return a newline but a
4907 ;; null byte before the shell prompt, for example "git
4908 ;; ls-files -c -z ...".
4909 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4910 (found (tramp-wait-for-regexp proc timeout regexp1)))
4911 (if found
4912 (let (buffer-read-only)
4913 ;; A simple-minded busybox has sent " ^H" sequences.
4914 ;; Delete them.
4915 (goto-char (point-min))
4916 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4917 (forward-line 1)
4918 (delete-region (point-min) (point)))
4919 ;; Delete the prompt.
4920 (goto-char (point-max))
4921 (re-search-backward regexp nil t)
4922 (delete-region (point) (point-max)))
4923 (if timeout
4924 (tramp-error
4925 proc 'file-error
4926 "[[Remote prompt `%s' not found in %d secs]]"
4927 tramp-end-of-output timeout)
4928 (tramp-error
4929 proc 'file-error
4930 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
4931 ;; Return value is whether end-of-output sentinel was found.
4932 found)))
4934 (defun tramp-send-command-and-check
4935 (vec command &optional subshell dont-suppress-err)
4936 "Run COMMAND and check its exit status.
4937 Sends `echo $?' along with the COMMAND for checking the exit status.
4938 If COMMAND is nil, just sends `echo $?'. Returns t if the exit
4939 status is 0, and nil otherwise.
4941 If the optional argument SUBSHELL is non-nil, the command is
4942 executed in a subshell, ie surrounded by parentheses. If
4943 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
4944 (tramp-send-command
4946 (concat (if subshell "( " "")
4947 command
4948 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
4949 "echo tramp_exit_status $?"
4950 (if subshell " )" "")))
4951 (with-current-buffer (tramp-get-connection-buffer vec)
4952 (goto-char (point-max))
4953 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
4954 (tramp-error
4955 vec 'file-error "Couldn't find exit status of `%s'" command))
4956 (skip-chars-forward "^ ")
4957 (prog1
4958 (zerop (read (current-buffer)))
4959 (let (buffer-read-only)
4960 (delete-region (match-beginning 0) (point-max))))))
4962 (defun tramp-barf-unless-okay (vec command fmt &rest args)
4963 "Run COMMAND, check exit status, throw error if exit status not okay.
4964 Similar to `tramp-send-command-and-check' but accepts two more arguments
4965 FMT and ARGS which are passed to `error'."
4966 (or (tramp-send-command-and-check vec command)
4967 (apply 'tramp-error vec 'file-error fmt args)))
4969 (defun tramp-send-command-and-read (vec command &optional noerror marker)
4970 "Run COMMAND and return the output, which must be a Lisp expression.
4971 If MARKER is a regexp, read the output after that string.
4972 In case there is no valid Lisp expression and NOERROR is nil, it
4973 raises an error."
4974 (when (if noerror
4975 (tramp-send-command-and-check vec command)
4976 (tramp-barf-unless-okay
4977 vec command "`%s' returns with error" command))
4978 (with-current-buffer (tramp-get-connection-buffer vec)
4979 (goto-char (point-min))
4980 ;; Read the marker.
4981 (when (stringp marker)
4982 (condition-case nil
4983 (re-search-forward marker)
4984 (error (unless noerror
4985 (tramp-error
4986 vec 'file-error
4987 "`%s' does not return the marker `%s': `%s'"
4988 command marker (buffer-string))))))
4989 ;; Read the expression.
4990 (condition-case nil
4991 (prog1 (read (current-buffer))
4992 ;; Error handling.
4993 (when (re-search-forward "\\S-" (point-at-eol) t)
4994 (error nil)))
4995 (error (unless noerror
4996 (tramp-error
4997 vec 'file-error
4998 "`%s' does not return a valid Lisp expression: `%s'"
4999 command (buffer-string))))))))
5001 (defun tramp-convert-file-attributes (vec attr)
5002 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
5003 Convert file mode bits to string and set virtual device number.
5004 Return ATTR."
5005 (when attr
5006 ;; Remove color escape sequences from symlink.
5007 (when (stringp (car attr))
5008 (while (string-match tramp-display-escape-sequence-regexp (car attr))
5009 (setcar attr (replace-match "" nil nil (car attr)))))
5010 ;; Convert uid and gid. Use `tramp-unknown-id-integer' as
5011 ;; indication of unusable value.
5012 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
5013 (setcar (nthcdr 2 attr) tramp-unknown-id-integer))
5014 (when (and (floatp (nth 2 attr))
5015 (<= (nth 2 attr) most-positive-fixnum))
5016 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
5017 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
5018 (setcar (nthcdr 3 attr) tramp-unknown-id-integer))
5019 (when (and (floatp (nth 3 attr))
5020 (<= (nth 3 attr) most-positive-fixnum))
5021 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
5022 ;; Convert last access time.
5023 (unless (listp (nth 4 attr))
5024 (setcar (nthcdr 4 attr)
5025 (list (floor (nth 4 attr) 65536)
5026 (floor (mod (nth 4 attr) 65536)))))
5027 ;; Convert last modification time.
5028 (unless (listp (nth 5 attr))
5029 (setcar (nthcdr 5 attr)
5030 (list (floor (nth 5 attr) 65536)
5031 (floor (mod (nth 5 attr) 65536)))))
5032 ;; Convert last status change time.
5033 (unless (listp (nth 6 attr))
5034 (setcar (nthcdr 6 attr)
5035 (list (floor (nth 6 attr) 65536)
5036 (floor (mod (nth 6 attr) 65536)))))
5037 ;; Convert file size.
5038 (when (< (nth 7 attr) 0)
5039 (setcar (nthcdr 7 attr) -1))
5040 (when (and (floatp (nth 7 attr))
5041 (<= (nth 7 attr) most-positive-fixnum))
5042 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
5043 ;; Convert file mode bits to string.
5044 (unless (stringp (nth 8 attr))
5045 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
5046 (when (stringp (car attr))
5047 (aset (nth 8 attr) 0 ?l)))
5048 ;; Convert directory indication bit.
5049 (when (string-match "^d" (nth 8 attr))
5050 (setcar attr t))
5051 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
5052 (when (consp (car attr))
5053 (if (and (stringp (caar attr))
5054 (string-match ".+ -> .\\(.+\\)." (caar attr)))
5055 (setcar attr (match-string 1 (caar attr)))
5056 (setcar attr nil)))
5057 ;; Set file's gid change bit.
5058 (setcar (nthcdr 9 attr)
5059 (if (numberp (nth 3 attr))
5060 (not (= (nth 3 attr)
5061 (tramp-get-remote-gid vec 'integer)))
5062 (not (string-equal
5063 (nth 3 attr)
5064 (tramp-get-remote-gid vec 'string)))))
5065 ;; Convert inode.
5066 (unless (listp (nth 10 attr))
5067 (setcar (nthcdr 10 attr)
5068 (condition-case nil
5069 (cons (floor (nth 10 attr) 65536)
5070 (floor (mod (nth 10 attr) 65536)))
5071 ;; Inodes can be incredible huge. We must hide this.
5072 (error (tramp-get-inode vec)))))
5073 ;; Set virtual device number.
5074 (setcar (nthcdr 11 attr)
5075 (tramp-get-device vec))
5076 attr))
5078 (defun tramp-shell-case-fold (string)
5079 "Converts STRING to shell glob pattern which ignores case."
5080 (mapconcat
5081 (lambda (c)
5082 (if (equal (downcase c) (upcase c))
5083 (vector c)
5084 (format "[%c%c]" (downcase c) (upcase c))))
5085 string
5086 ""))
5088 (defun tramp-make-copy-program-file-name (vec)
5089 "Create a file name suitable for `scp', `pscp', or `nc' and workalikes."
5090 (let ((method (tramp-file-name-method vec))
5091 (user (tramp-file-name-user vec))
5092 (host (tramp-file-name-real-host vec))
5093 (localname
5094 (directory-file-name (tramp-file-name-unquote-localname vec))))
5095 (when (string-match tramp-ipv6-regexp host)
5096 (setq host (format "[%s]" host)))
5097 (unless (string-match "ftp$" method)
5098 (setq localname (tramp-shell-quote-argument localname)))
5099 (cond
5100 ((tramp-get-method-parameter vec 'tramp-remote-copy-program)
5101 localname)
5102 ((not (zerop (length user)))
5103 (format "%s@%s:%s" user host (shell-quote-argument localname)))
5104 (t (format "%s:%s" host (shell-quote-argument localname))))))
5106 (defun tramp-method-out-of-band-p (vec size)
5107 "Return t if this is an out-of-band method, nil otherwise."
5108 (and
5109 ;; It shall be an out-of-band method.
5110 (tramp-get-method-parameter vec 'tramp-copy-program)
5111 ;; There must be a size, otherwise the file doesn't exist.
5112 (numberp size)
5113 ;; Either the file size is large enough, or (in rare cases) there
5114 ;; does not exist a remote encoding.
5115 (or (null tramp-copy-size-limit)
5116 (> size tramp-copy-size-limit)
5117 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
5119 ;; Variables local to connection.
5121 (defun tramp-get-remote-path (vec)
5122 "Compile list of remote directories for $PATH.
5123 Nonexistent directories are removed from spec."
5124 (with-tramp-connection-property
5125 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
5126 ;; cache the result for the session only. Otherwise, the result
5127 ;; is cached persistently.
5128 (if (memq 'tramp-own-remote-path tramp-remote-path)
5129 (tramp-get-connection-process vec)
5130 vec)
5131 "remote-path"
5132 (let* ((remote-path (copy-tree tramp-remote-path))
5133 (elt1 (memq 'tramp-default-remote-path remote-path))
5134 (elt2 (memq 'tramp-own-remote-path remote-path))
5135 (default-remote-path
5136 (when elt1
5138 (tramp-send-command-and-read
5139 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
5140 ;; Default if "getconf" is not available.
5141 (progn
5142 (tramp-message
5143 vec 3
5144 "`getconf PATH' not successful, using default value \"%s\"."
5145 "/bin:/usr/bin")
5146 "/bin:/usr/bin"))))
5147 (own-remote-path
5148 ;; The login shell could return more than just the $PATH
5149 ;; string. So we use `tramp-end-of-heredoc' as marker.
5150 (when elt2
5152 (tramp-send-command-and-read
5154 (format
5155 "%s %s %s 'echo %s \\\"$PATH\\\"'"
5156 (tramp-get-method-parameter vec 'tramp-remote-shell)
5157 (mapconcat
5158 'identity
5159 (tramp-get-method-parameter vec 'tramp-remote-shell-login)
5160 " ")
5161 (mapconcat
5162 'identity
5163 (tramp-get-method-parameter vec 'tramp-remote-shell-args)
5164 " ")
5165 (tramp-shell-quote-argument tramp-end-of-heredoc))
5166 'noerror (regexp-quote tramp-end-of-heredoc))
5167 (progn
5168 (tramp-message
5169 vec 2 "Could not retrieve `tramp-own-remote-path'")
5170 nil)))))
5172 ;; Replace place holder `tramp-default-remote-path'.
5173 (when elt1
5174 (setcdr elt1
5175 (append
5176 (split-string (or default-remote-path "") ":" 'omit)
5177 (cdr elt1)))
5178 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
5180 ;; Replace place holder `tramp-own-remote-path'.
5181 (when elt2
5182 (setcdr elt2
5183 (append
5184 (split-string (or own-remote-path "") ":" 'omit)
5185 (cdr elt2)))
5186 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
5188 ;; Remove double entries.
5189 (setq elt1 remote-path)
5190 (while (consp elt1)
5191 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
5192 (setcar elt2 nil))
5193 (setq elt1 (cdr elt1)))
5195 ;; Remove non-existing directories.
5196 (delq
5198 (mapcar
5199 (lambda (x)
5200 (and
5201 (stringp x)
5202 (file-directory-p
5203 (tramp-make-tramp-file-name
5204 (tramp-file-name-method vec)
5205 (tramp-file-name-user vec)
5206 (tramp-file-name-host vec)
5209 remote-path)))))
5211 (defun tramp-get-remote-locale (vec)
5212 "Determine remote locale, supporting UTF8 if possible."
5213 (with-tramp-connection-property vec "locale"
5214 (tramp-send-command vec "locale -a")
5215 (let ((candidates '("en_US.utf8" "C.utf8" "en_US.UTF-8"))
5216 locale)
5217 (with-current-buffer (tramp-get-connection-buffer vec)
5218 (while candidates
5219 (goto-char (point-min))
5220 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
5221 (buffer-string))
5222 (setq locale (car candidates)
5223 candidates nil)
5224 (setq candidates (cdr candidates)))))
5225 ;; Return value.
5226 (format "LC_ALL=%s" (or locale "C")))))
5228 (defun tramp-get-ls-command (vec)
5229 "Determine remote `ls' command."
5230 (with-tramp-connection-property vec "ls"
5231 (tramp-message vec 5 "Finding a suitable `ls' command")
5233 (catch 'ls-found
5234 (dolist (cmd '("ls" "gnuls" "gls"))
5235 (let ((dl (tramp-get-remote-path vec))
5236 result)
5237 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5238 ;; Check parameters. On busybox, "ls" output coloring is
5239 ;; enabled by default sometimes. So we try to disable it
5240 ;; when possible. $LS_COLORING is not supported there.
5241 ;; Some "ls" versions are sensible wrt the order of
5242 ;; arguments, they fail when "-al" is after the
5243 ;; "--color=never" argument (for example on FreeBSD).
5244 (when (tramp-send-command-and-check
5245 vec (format "%s -lnd /" result))
5246 (when (tramp-send-command-and-check
5247 vec (format
5248 "%s --color=never -al /dev/null" result))
5249 (setq result (concat result " --color=never")))
5250 (throw 'ls-found result))
5251 (setq dl (cdr dl))))))
5252 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
5254 (defun tramp-get-ls-command-with-dired (vec)
5255 "Check, whether the remote `ls' command supports the --dired option."
5256 (save-match-data
5257 (with-tramp-connection-property vec "ls-dired"
5258 (tramp-message vec 5 "Checking, whether `ls --dired' works")
5259 ;; Some "ls" versions are sensible wrt the order of arguments,
5260 ;; they fail when "-al" is after the "--dired" argument (for
5261 ;; example on FreeBSD).
5262 (tramp-send-command-and-check
5263 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
5265 (defun tramp-get-ls-command-with-quoting-style (vec)
5266 "Check, whether the remote `ls' command supports the --quoting-style option."
5267 (save-match-data
5268 (with-tramp-connection-property vec "ls-quoting-style"
5269 (tramp-message vec 5 "Checking, whether `ls --quoting-style=shell' works")
5270 (tramp-send-command-and-check
5271 vec (format "%s --quoting-style=shell -al /dev/null"
5272 (tramp-get-ls-command vec))))))
5274 (defun tramp-get-ls-command-with-w-option (vec)
5275 "Check, whether the remote `ls' command supports the -w option."
5276 (save-match-data
5277 (with-tramp-connection-property vec "ls-w-option"
5278 (tramp-message vec 5 "Checking, whether `ls -w' works")
5279 ;; Option "-w" is available on BSD systems. No argument is
5280 ;; given, because this could return wrong results in case "ls"
5281 ;; supports the "-w NUM" argument, as for busyboxes.
5282 (tramp-send-command-and-check
5283 vec (format "%s -alw" (tramp-get-ls-command vec))))))
5285 (defun tramp-get-test-command (vec)
5286 "Determine remote `test' command."
5287 (with-tramp-connection-property vec "test"
5288 (tramp-message vec 5 "Finding a suitable `test' command")
5289 (if (tramp-send-command-and-check vec "test 0")
5290 "test"
5291 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
5293 (defun tramp-get-test-nt-command (vec)
5294 "Check, whether the remote `test' command supports the -nt option."
5295 ;; Does `test A -nt B' work? Use abominable `find' construct if it
5296 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
5297 ;; for otherwise the shell crashes.
5298 (with-tramp-connection-property vec "test-nt"
5300 (progn
5301 (tramp-send-command
5302 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
5303 (with-current-buffer (tramp-get-buffer vec)
5304 (goto-char (point-min))
5305 (when (looking-at (regexp-quote tramp-end-of-output))
5306 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
5307 (progn
5308 (tramp-send-command
5310 (format
5311 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
5312 (tramp-get-test-command vec)))
5313 "tramp_test_nt %s %s"))))
5315 (defun tramp-get-file-exists-command (vec)
5316 "Determine remote command for file existing check."
5317 (with-tramp-connection-property vec "file-exists"
5318 (tramp-message vec 5 "Finding command to check if file exists")
5319 (tramp-find-file-exists-command vec)))
5321 (defun tramp-get-remote-ln (vec)
5322 "Determine remote `ln' command."
5323 (with-tramp-connection-property vec "ln"
5324 (tramp-message vec 5 "Finding a suitable `ln' command")
5325 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
5327 (defun tramp-get-remote-perl (vec)
5328 "Determine remote `perl' command."
5329 (with-tramp-connection-property vec "perl"
5330 (tramp-message vec 5 "Finding a suitable `perl' command")
5331 (let ((result
5332 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
5333 (tramp-find-executable vec "perl" (tramp-get-remote-path vec)))))
5334 ;; Perform a basic check.
5335 (and result
5336 (null (tramp-send-command-and-check
5337 vec (format "%s -e 'print \"Hello\n\";'" result)))
5338 (setq result nil))
5339 ;; We must check also for some Perl modules.
5340 (when result
5341 (with-tramp-connection-property vec "perl-file-spec"
5342 (tramp-send-command-and-check
5343 vec (format "%s -e 'use File::Spec;'" result)))
5344 (with-tramp-connection-property vec "perl-cwd-realpath"
5345 (tramp-send-command-and-check
5346 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
5347 result)))
5349 (defun tramp-get-remote-stat (vec)
5350 "Determine remote `stat' command."
5351 (with-tramp-connection-property vec "stat"
5352 (tramp-message vec 5 "Finding a suitable `stat' command")
5353 (let ((result (tramp-find-executable
5354 vec "stat" (tramp-get-remote-path vec)))
5355 tmp)
5356 ;; Check whether stat(1) returns usable syntax. "%s" does not
5357 ;; work on older AIX systems. Recent GNU stat versions (8.24?)
5358 ;; use shell quoted format for "%N", we check the boundaries "`"
5359 ;; and "'", therefore. See Bug#23422 in coreutils.
5360 ;; Since GNU stat 8.26, environment variable QUOTING_STYLE is
5361 ;; supported.
5362 (when result
5363 (setq result (concat "env QUOTING_STYLE=locale " result)
5364 tmp (tramp-send-command-and-read
5365 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5366 (unless (and (listp tmp) (stringp (car tmp))
5367 (string-match "^\\(`/'\\|‘/’\\)$" (car tmp))
5368 (integerp (cadr tmp)))
5369 (setq result nil)))
5370 result)))
5372 (defun tramp-get-remote-readlink (vec)
5373 "Determine remote `readlink' command."
5374 (with-tramp-connection-property vec "readlink"
5375 (tramp-message vec 5 "Finding a suitable `readlink' command")
5376 (let ((result (tramp-find-executable
5377 vec "readlink" (tramp-get-remote-path vec))))
5378 (when (and result
5379 (tramp-send-command-and-check
5380 vec (format "%s --canonicalize-missing /" result)))
5381 result))))
5383 (defun tramp-get-remote-trash (vec)
5384 "Determine remote `trash' command."
5385 (with-tramp-connection-property vec "trash"
5386 (tramp-message vec 5 "Finding a suitable `trash' command")
5387 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5389 (defun tramp-get-remote-touch (vec)
5390 "Determine remote `touch' command."
5391 (with-tramp-connection-property vec "touch"
5392 (tramp-message vec 5 "Finding a suitable `touch' command")
5393 (let ((result (tramp-find-executable
5394 vec "touch" (tramp-get-remote-path vec)))
5395 (tmpfile
5396 (make-temp-name
5397 (expand-file-name
5398 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
5399 ;; Busyboxes do support the "-t" option only when they have been
5400 ;; built with the DESKTOP config option. Let's check it.
5401 (when result
5402 (tramp-set-connection-property
5403 vec "touch-t"
5404 (tramp-send-command-and-check
5406 (format
5407 "%s -t %s %s"
5408 result
5409 (format-time-string "%Y%m%d%H%M.%S")
5410 (file-remote-p tmpfile 'localname))))
5411 (delete-file tmpfile))
5412 result)))
5414 (defun tramp-get-remote-gvfs-monitor-dir (vec)
5415 "Determine remote `gvfs-monitor-dir' command."
5416 (with-tramp-connection-property vec "gvfs-monitor-dir"
5417 (tramp-message vec 5 "Finding a suitable `gvfs-monitor-dir' command")
5418 ;; We distinguish "gvfs-monitor-dir.exe" from cygwin in order to
5419 ;; establish better timeouts in filenotify-tests.el. Any better
5420 ;; distinction approach would be welcome!
5421 (or (tramp-find-executable
5422 vec "gvfs-monitor-dir.exe" (tramp-get-remote-path vec) t t)
5423 (tramp-find-executable
5424 vec "gvfs-monitor-dir" (tramp-get-remote-path vec) t t))))
5426 (defun tramp-get-remote-inotifywait (vec)
5427 "Determine remote `inotifywait' command."
5428 (with-tramp-connection-property vec "inotifywait"
5429 (tramp-message vec 5 "Finding a suitable `inotifywait' command")
5430 (tramp-find-executable vec "inotifywait" (tramp-get-remote-path vec) t t)))
5432 (defun tramp-get-remote-id (vec)
5433 "Determine remote `id' command."
5434 (with-tramp-connection-property vec "id"
5435 (tramp-message vec 5 "Finding POSIX `id' command")
5436 (catch 'id-found
5437 (dolist (cmd '("id" "gid"))
5438 (let ((dl (tramp-get-remote-path vec))
5439 result)
5440 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5441 ;; Check POSIX parameter.
5442 (when (tramp-send-command-and-check vec (format "%s -u" result))
5443 (throw 'id-found result))
5444 (setq dl (cdr dl))))))))
5446 (defun tramp-get-remote-uid-with-id (vec id-format)
5447 "Implement `tramp-get-remote-uid' for Tramp files using `id'."
5448 (tramp-send-command-and-read
5450 (format "%s -u%s %s"
5451 (tramp-get-remote-id vec)
5452 (if (equal id-format 'integer) "" "n")
5453 (if (equal id-format 'integer)
5454 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5456 (defun tramp-get-remote-uid-with-perl (vec id-format)
5457 "Implement `tramp-get-remote-uid' for Tramp files using a Perl script."
5458 (tramp-send-command-and-read
5460 (format "%s -le '%s'"
5461 (tramp-get-remote-perl vec)
5462 (if (equal id-format 'integer)
5463 "print $>"
5464 "print \"\\\"\", scalar getpwuid($>), \"\\\"\""))))
5466 (defun tramp-get-remote-python (vec)
5467 "Determine remote `python' command."
5468 (with-tramp-connection-property vec "python"
5469 (tramp-message vec 5 "Finding a suitable `python' command")
5470 (or (tramp-find-executable vec "python" (tramp-get-remote-path vec))
5471 (tramp-find-executable vec "python2" (tramp-get-remote-path vec))
5472 (tramp-find-executable vec "python3" (tramp-get-remote-path vec)))))
5474 (defun tramp-get-remote-uid-with-python (vec id-format)
5475 "Implement `tramp-get-remote-uid' for Tramp files using `python'."
5476 (tramp-send-command-and-read
5478 (format "%s -c \"%s\""
5479 (tramp-get-remote-python vec)
5480 (if (equal id-format 'integer)
5481 "import os; print (os.getuid())"
5482 "import os, pwd; print ('\\\"' + pwd.getpwuid(os.getuid())[0] + '\\\"')"))))
5484 (defun tramp-get-remote-uid (vec id-format)
5485 "The uid of the remote connection VEC, in ID-FORMAT.
5486 ID-FORMAT valid values are `string' and `integer'."
5487 (with-tramp-connection-property vec (format "uid-%s" id-format)
5488 (let ((res
5489 (ignore-errors
5490 (cond
5491 ((tramp-get-remote-id vec)
5492 (tramp-get-remote-uid-with-id vec id-format))
5493 ((tramp-get-remote-perl vec)
5494 (tramp-get-remote-uid-with-perl vec id-format))
5495 ((tramp-get-remote-python vec)
5496 (tramp-get-remote-uid-with-python vec id-format))))))
5497 ;; Ensure there is a valid result.
5498 (cond
5499 ((and (equal id-format 'integer) (not (integerp res)))
5500 tramp-unknown-id-integer)
5501 ((and (equal id-format 'string) (not (stringp res)))
5502 tramp-unknown-id-string)
5503 (t res)))))
5505 (defun tramp-get-remote-gid-with-id (vec id-format)
5506 "Implement `tramp-get-remote-gid' for Tramp files using `id'."
5507 (tramp-send-command-and-read
5509 (format "%s -g%s %s"
5510 (tramp-get-remote-id vec)
5511 (if (equal id-format 'integer) "" "n")
5512 (if (equal id-format 'integer)
5513 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5515 (defun tramp-get-remote-gid-with-perl (vec id-format)
5516 "Implement `tramp-get-remote-gid' for Tramp files using a Perl script."
5517 (tramp-send-command-and-read
5519 (format "%s -le '%s'"
5520 (tramp-get-remote-perl vec)
5521 (if (equal id-format 'integer)
5522 "print ($)=~/(\\d+)/)"
5523 "print \"\\\"\", scalar getgrgid($)), \"\\\"\""))))
5525 (defun tramp-get-remote-gid-with-python (vec id-format)
5526 "Implement `tramp-get-remote-gid' for Tramp files using `python'."
5527 (tramp-send-command-and-read
5529 (format "%s -c \"%s\""
5530 (tramp-get-remote-python vec)
5531 (if (equal id-format 'integer)
5532 "import os; print (os.getgid())"
5533 "import os, grp; print ('\\\"' + grp.getgrgid(os.getgid())[0] + '\\\"')"))))
5535 (defun tramp-get-remote-gid (vec id-format)
5536 "The gid of the remote connection VEC, in ID-FORMAT.
5537 ID-FORMAT valid values are `string' and `integer'."
5538 (with-tramp-connection-property vec (format "gid-%s" id-format)
5539 (let ((res
5540 (ignore-errors
5541 (cond
5542 ((tramp-get-remote-id vec)
5543 (tramp-get-remote-gid-with-id vec id-format))
5544 ((tramp-get-remote-perl vec)
5545 (tramp-get-remote-gid-with-perl vec id-format))
5546 ((tramp-get-remote-python vec)
5547 (tramp-get-remote-gid-with-python vec id-format))))))
5548 ;; Ensure there is a valid result.
5549 (cond
5550 ((and (equal id-format 'integer) (not (integerp res)))
5551 tramp-unknown-id-integer)
5552 ((and (equal id-format 'string) (not (stringp res)))
5553 tramp-unknown-id-string)
5554 (t res)))))
5556 (defun tramp-get-env-with-u-option (vec)
5557 "Check, whether the remote `env' command supports the -u option."
5558 (with-tramp-connection-property vec "env-u-option"
5559 (tramp-message vec 5 "Checking, whether `env -u' works")
5560 ;; Option "-u" is a GNU extension.
5561 (tramp-send-command-and-check
5562 vec "env FOO=foo env -u FOO 2>/dev/null | grep -qv FOO" t)))
5564 ;; Some predefined connection properties.
5565 (defun tramp-get-inline-compress (vec prop size)
5566 "Return the compress command related to PROP.
5567 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5568 the length of the file to be compressed.
5570 If no corresponding command is found, nil is returned."
5571 (when (and (integerp tramp-inline-compress-start-size)
5572 (> size tramp-inline-compress-start-size))
5573 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5574 (tramp-find-inline-compress vec)
5575 (tramp-get-connection-property
5576 (tramp-get-connection-process vec) prop nil))))
5578 (defun tramp-get-inline-coding (vec prop size)
5579 "Return the coding command related to PROP.
5580 PROP is either `remote-encoding', `remote-decoding',
5581 `local-encoding' or `local-decoding'.
5583 SIZE is the length of the file to be coded. Depending on SIZE,
5584 compression might be applied.
5586 If no corresponding command is found, nil is returned.
5587 Otherwise, either a string is returned which contains a `%s' mark
5588 to be used for the respective input or output file; or a Lisp
5589 function cell is returned to be applied on a buffer."
5590 ;; We must catch the errors, because we want to return nil, when
5591 ;; no inline coding is found.
5592 (ignore-errors
5593 (let ((coding
5594 (with-tramp-connection-property
5595 (tramp-get-connection-process vec) prop
5596 (tramp-find-inline-encoding vec)
5597 (tramp-get-connection-property
5598 (tramp-get-connection-process vec) prop nil)))
5599 (prop1 (if (string-match "encoding" prop)
5600 "inline-compress" "inline-decompress"))
5601 compress)
5602 ;; The connection property might have been cached. So we must
5603 ;; send the script to the remote side - maybe.
5604 (when (and coding (symbolp coding) (string-match "remote" prop))
5605 (let ((name (symbol-name coding)))
5606 (while (string-match (regexp-quote "-") name)
5607 (setq name (replace-match "_" nil t name)))
5608 (tramp-maybe-send-script vec (symbol-value coding) name)
5609 (setq coding name)))
5610 (when coding
5611 ;; Check for the `compress' command.
5612 (setq compress (tramp-get-inline-compress vec prop1 size))
5613 ;; Return the value.
5614 (cond
5615 ((and compress (symbolp coding))
5616 (if (string-match "decompress" prop1)
5617 `(lambda (beg end)
5618 (,coding beg end)
5619 (let ((coding-system-for-write 'binary)
5620 (coding-system-for-read 'binary))
5621 (apply
5622 'tramp-call-process-region ,vec (point-min) (point-max)
5623 (car (split-string ,compress)) t t nil
5624 (cdr (split-string ,compress)))))
5625 `(lambda (beg end)
5626 (let ((coding-system-for-write 'binary)
5627 (coding-system-for-read 'binary))
5628 (apply
5629 'tramp-call-process-region ,vec beg end
5630 (car (split-string ,compress)) t t nil
5631 (cdr (split-string ,compress))))
5632 (,coding (point-min) (point-max)))))
5633 ((symbolp coding)
5634 coding)
5635 ((and compress (string-match "decoding" prop))
5636 (format
5637 ;; Windows shells need the program file name after
5638 ;; the pipe symbol be quoted if they use forward
5639 ;; slashes as directory separators.
5640 (cond
5641 ((and (string-match "local" prop)
5642 (memq system-type '(windows-nt)))
5643 "(%s | \"%s\")")
5644 ((string-match "local" prop) "(%s | %s)")
5645 (t "(%s | %s >%%s)"))
5646 coding compress))
5647 (compress
5648 (format
5649 ;; Windows shells need the program file name after
5650 ;; the pipe symbol be quoted if they use forward
5651 ;; slashes as directory separators.
5652 (if (and (string-match "local" prop)
5653 (memq system-type '(windows-nt)))
5654 "(%s <%%s | \"%s\")"
5655 "(%s <%%s | %s)")
5656 compress coding))
5657 ((string-match "decoding" prop)
5658 (cond
5659 ((string-match "local" prop) (format "%s" coding))
5660 (t (format "%s >%%s" coding))))
5662 (format "%s <%%s" coding)))))))
5664 (add-hook 'tramp-unload-hook
5665 (lambda ()
5666 (unload-feature 'tramp-sh 'force)))
5668 (provide 'tramp-sh)
5670 ;;; TODO:
5672 ;; * Don't use globbing for directories with many files, as this is
5673 ;; likely to produce long command lines, and some shells choke on
5674 ;; long command lines.
5676 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5677 ;; then look if it's the right version (with `perl -v').
5679 ;; * When editing a remote CVS controlled file as a different user, VC
5680 ;; gets confused about the file locking status. Try to find out why
5681 ;; the workaround doesn't work.
5683 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5684 ;; until the last but one hop via `start-file-process'. Apply it
5685 ;; also for ftp and smb.
5687 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5688 ;; some shell with root privileges, it would be nice if I could
5689 ;; just call
5690 ;; trampclient filename.c
5691 ;; as an editor, and the _current_ shell would connect to an Emacs
5692 ;; server and would be used in an existing non-privileged Emacs
5693 ;; session for doing the editing in question.
5694 ;; That way, I need not tell Emacs my password again and be afraid
5695 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5696 ;; once display a just typed password in the context of a keyboard
5697 ;; sequence prompt for a question immediately following in a shell
5698 ;; script run within Emacs -- nasty).
5699 ;; And if I have some ssh session running to a different computer,
5700 ;; having the possibility of passing a local file there to a local
5701 ;; Emacs session (in case I can arrange for a connection back) would
5702 ;; be nice.
5703 ;; Likely the corresponding Tramp server should not allow the
5704 ;; equivalent of the emacsclient -eval option in order to make this
5705 ;; reasonably unproblematic. And maybe trampclient should have some
5706 ;; way of passing credentials, like by using an SSL socket or
5707 ;; something. (David Kastrup)
5709 ;; * Reconnect directly to a compliant shell without first going
5710 ;; through the user's default shell. (Pete Forman)
5712 ;; * How can I interrupt the remote process with a signal
5713 ;; (interrupt-process seems not to work)? (Markus Triska)
5715 ;; * Avoid the local shell entirely for starting remote processes. If
5716 ;; so, I think even a signal, when delivered directly to the local
5717 ;; SSH instance, would correctly be propagated to the remote process
5718 ;; automatically; possibly SSH would have to be started with
5719 ;; "-t". (Markus Triska)
5721 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5722 ;; isn't on the remote host. (Mark A. Hershberger)
5724 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5726 ;; * Optimize out-of-band copying when both methods are scp-like (not
5727 ;; rsync).
5729 ;; * Keep a second connection open for out-of-band methods like scp or
5730 ;; rsync.
5732 ;; * Implement completion for "/method:user@host:~<abc> TAB".
5734 ;; * I think you could get the best of both worlds by using an
5735 ;; approach similar to Tramp but running a little tramp-daemon on
5736 ;; the other end, such that we can use a more efficient
5737 ;; communication protocol (e.g. when saving a file we could locally
5738 ;; diff it against the last version (of which the remote daemon
5739 ;; would also keep a copy), and then only send the diff).
5741 ;; This said, even using such a daemon it might be difficult to get
5742 ;; good performance: part of the problem is the number of
5743 ;; round-trips. E.g. when saving a file we have to check if the
5744 ;; file was modified in the mean time and whether saving into a new
5745 ;; inode would change the owner (etc...), which each require a
5746 ;; round-trip. To get rid of these round-trips, we'd have to
5747 ;; shortcut this code and delegate the higher-level "save file"
5748 ;; operation to the remote server, which then has to perform those
5749 ;; tasks but still obeying the locally set customizations about how
5750 ;; to do each one of those tasks.
5752 ;; We could either put higher-level ops in there (like
5753 ;; `save-buffer'), which implies replicating the whole `save-buffer'
5754 ;; behavior, which is a lot of work and likely to be not 100%
5755 ;; faithful.
5757 ;; Or we could introduce new low-level ops that are asynchronous,
5758 ;; and then rewrite save-buffer to use them. IOW save-buffer would
5759 ;; start with a bunch of calls like `start-getting-file-attributes'
5760 ;; which could immediately be passed on to the remote side, and
5761 ;; later on checks the return value of those calls as and when
5762 ;; needed. (Stefan Monnier)
5764 ;;; tramp-sh.el ends here