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