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