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