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