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