; Submit changes promised last commit already
[emacs.git] / lisp / net / tramp-sh.el
blob1753c73f8694ee8915e4ab2fb4984c190e6f7f00
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 (if t2
2461 (tramp-make-copy-program-file-name v)
2462 (shell-quote-argument
2463 (funcall
2464 (if (and (file-directory-p filename)
2465 (string-equal
2466 (file-name-nondirectory filename)
2467 (file-name-nondirectory newname)))
2468 'file-name-directory
2469 'identity)
2470 newname))))
2472 ;; Check for host and port number. We cannot use
2473 ;; `tramp-file-name-port', because this returns also
2474 ;; `tramp-default-port', which might clash with settings in
2475 ;; "~/.ssh/config".
2476 (setq host (tramp-file-name-host v)
2477 port "")
2478 (when (string-match tramp-host-with-port-regexp host)
2479 (setq port (string-to-number (match-string 2 host))
2480 host (string-to-number (match-string 1 host))))
2482 ;; Check for user. There might be an interactive setting.
2483 (setq user (or (tramp-file-name-user v)
2484 (tramp-get-connection-property v "login-as" nil)))
2486 ;; Check for listener port.
2487 (when (tramp-get-method-parameter v 'tramp-remote-copy-args)
2488 (setq listener (number-to-string (+ 50000 (random 10000))))
2489 (while
2490 (zerop (tramp-call-process v "nc" nil nil nil "-z" host listener))
2491 (setq listener (number-to-string (+ 50000 (random 10000))))))
2493 ;; Compose copy command.
2494 (setq host (or host "")
2495 user (or user "")
2496 port (or port "")
2497 spec (format-spec-make
2498 ?t (tramp-get-connection-property
2499 (tramp-get-connection-process v) "temp-file" ""))
2500 options (format-spec (tramp-ssh-controlmaster-options v) spec)
2501 spec (format-spec-make
2502 ?h host ?u user ?p port ?r listener ?c options
2503 ?k (if keep-date " " ""))
2504 copy-program (tramp-get-method-parameter v 'tramp-copy-program)
2505 copy-keep-date (tramp-get-method-parameter
2506 v 'tramp-copy-keep-date)
2508 copy-args
2509 (delete
2510 ;; " " has either been a replacement of "%k" (when
2511 ;; keep-date argument is non-nil), or a replacement
2512 ;; for the whole keep-date sublist.
2514 (dolist
2515 (x (tramp-get-method-parameter v 'tramp-copy-args) copy-args)
2516 (setq copy-args
2517 (append
2518 copy-args
2519 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2520 (if (member "" y) '(" ") y))))))
2522 copy-env
2523 (delq
2525 (mapcar
2526 (lambda (x)
2527 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
2528 (unless (member "" x) (mapconcat 'identity x " ")))
2529 (tramp-get-method-parameter v 'tramp-copy-env)))
2531 remote-copy-program
2532 (tramp-get-method-parameter v 'tramp-remote-copy-program))
2534 (dolist (x (tramp-get-method-parameter v 'tramp-remote-copy-args))
2535 (setq remote-copy-args
2536 (append
2537 remote-copy-args
2538 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2539 (if (member "" y) '(" ") y)))))
2541 ;; Check for local copy program.
2542 (unless (executable-find copy-program)
2543 (tramp-error
2544 v 'file-error "Cannot find local copy program: %s" copy-program))
2546 ;; Install listener on the remote side. The prompt must be
2547 ;; consumed later on, when the process does not listen anymore.
2548 (when remote-copy-program
2549 (unless (with-tramp-connection-property
2550 v (concat "remote-copy-program-" remote-copy-program)
2551 (tramp-find-executable
2552 v remote-copy-program (tramp-get-remote-path v)))
2553 (tramp-error
2554 v 'file-error
2555 "Cannot find remote listener: %s" remote-copy-program))
2556 (setq remote-copy-program
2557 (mapconcat
2558 'identity
2559 (append
2560 (list remote-copy-program) remote-copy-args
2561 (list (if t1 (concat "<" source) (concat ">" target)) "&"))
2562 " "))
2563 (tramp-send-command v remote-copy-program)
2564 (with-timeout
2565 (60 (tramp-error
2566 v 'file-error
2567 "Listener process not running on remote host: `%s'"
2568 remote-copy-program))
2569 (tramp-send-command v (format "netstat -l | grep -q :%s" listener))
2570 (while (not (tramp-send-command-and-check v nil))
2571 (tramp-send-command
2572 v (format "netstat -l | grep -q :%s" listener)))))
2574 (with-temp-buffer
2575 (unwind-protect
2576 ;; The default directory must be remote.
2577 (let ((default-directory
2578 (file-name-directory (if t1 filename newname)))
2579 (process-environment (copy-sequence process-environment)))
2580 ;; Set the transfer process properties.
2581 (tramp-set-connection-property
2582 v "process-name" (buffer-name (current-buffer)))
2583 (tramp-set-connection-property
2584 v "process-buffer" (current-buffer))
2585 (while copy-env
2586 (tramp-message
2587 orig-vec 6 "%s=\"%s\"" (car copy-env) (cadr copy-env))
2588 (setenv (pop copy-env) (pop copy-env)))
2589 (setq
2590 copy-args
2591 (append
2592 copy-args
2593 (if remote-copy-program
2594 (list (if t1 (concat ">" target) (concat "<" source)))
2595 (list source target))))
2597 ;; Use an asynchronous process. By this, password can
2598 ;; be handled. We don't set a timeout, because the
2599 ;; copying of large files can last longer than 60
2600 ;; secs.
2601 (let ((p (apply 'start-process-shell-command
2602 (tramp-get-connection-name v)
2603 (tramp-get-connection-buffer v)
2604 copy-program
2605 (append
2606 copy-args
2607 (list "&&" "echo" "tramp_exit_status" "0"
2608 "||" "echo" "tramp_exit_status" "1")))))
2609 (tramp-message
2610 orig-vec 6 "%s"
2611 (mapconcat 'identity (process-command p) " "))
2612 (tramp-set-connection-property p "vector" orig-vec)
2613 (tramp-compat-set-process-query-on-exit-flag p nil)
2615 ;; We must adapt `tramp-local-end-of-line' for
2616 ;; sending the password.
2617 (let ((tramp-local-end-of-line tramp-rsh-end-of-line))
2618 (tramp-process-actions
2619 p v nil tramp-actions-copy-out-of-band))
2621 ;; Check the return code.
2622 (goto-char (point-max))
2623 (unless
2624 (re-search-backward "tramp_exit_status [0-9]+" nil t)
2625 (tramp-error
2626 orig-vec 'file-error
2627 "Couldn't find exit status of `%s'"
2628 (mapconcat 'identity (process-command p) " ")))
2629 (skip-chars-forward "^ ")
2630 (unless (zerop (read (current-buffer)))
2631 (forward-line -1)
2632 (tramp-error
2633 orig-vec 'file-error
2634 "Error copying: `%s'"
2635 (buffer-substring (point-min) (point-at-eol))))))
2637 ;; Reset the transfer process properties.
2638 (tramp-set-connection-property v "process-name" nil)
2639 (tramp-set-connection-property v "process-buffer" nil)
2640 ;; Clear the remote prompt.
2641 (when (and remote-copy-program
2642 (not (tramp-send-command-and-check v nil)))
2643 ;; Houston, we have a problem! Likely, the listener is
2644 ;; still running, so let's clear everything (but the
2645 ;; cached password).
2646 (tramp-cleanup-connection v 'keep-debug 'keep-password))))
2648 ;; Handle KEEP-DATE argument.
2649 (when (and keep-date (not copy-keep-date))
2650 (set-file-times newname (nth 5 (file-attributes filename))))
2652 ;; Set the mode.
2653 (unless (and keep-date copy-keep-date)
2654 (ignore-errors
2655 (set-file-modes newname (tramp-default-file-modes filename)))))
2657 ;; If the operation was `rename', delete the original file.
2658 (unless (eq op 'copy)
2659 (if (file-regular-p filename)
2660 (delete-file filename)
2661 (tramp-compat-delete-directory filename 'recursive))))))
2663 (defun tramp-sh-handle-make-directory (dir &optional parents)
2664 "Like `make-directory' for Tramp files."
2665 (setq dir (expand-file-name dir))
2666 (with-parsed-tramp-file-name dir nil
2667 (tramp-flush-directory-property v (file-name-directory localname))
2668 (save-excursion
2669 (tramp-barf-unless-okay
2670 v (format "%s %s"
2671 (if parents "mkdir -p" "mkdir")
2672 (tramp-shell-quote-argument localname))
2673 "Couldn't make directory %s" dir))))
2675 (defun tramp-sh-handle-delete-directory (directory &optional recursive)
2676 "Like `delete-directory' for Tramp files."
2677 (setq directory (expand-file-name directory))
2678 (with-parsed-tramp-file-name directory nil
2679 (tramp-flush-file-property v (file-name-directory localname))
2680 (tramp-flush-directory-property v localname)
2681 (tramp-barf-unless-okay
2682 v (format "cd / && %s %s"
2683 (if recursive "rm -rf" "rmdir")
2684 (tramp-shell-quote-argument localname))
2685 "Couldn't delete %s" directory)))
2687 (defun tramp-sh-handle-delete-file (filename &optional trash)
2688 "Like `delete-file' for Tramp files."
2689 (setq filename (expand-file-name filename))
2690 (with-parsed-tramp-file-name filename nil
2691 (tramp-flush-file-property v (file-name-directory localname))
2692 (tramp-flush-file-property v localname)
2693 (tramp-barf-unless-okay
2694 v (format "%s %s"
2695 (or (and trash (tramp-get-remote-trash v)) "rm -f")
2696 (tramp-shell-quote-argument localname))
2697 "Couldn't delete %s" filename)))
2699 ;; Dired.
2701 ;; CCC: This does not seem to be enough. Something dies when
2702 ;; we try and delete two directories under Tramp :/
2703 (defun tramp-sh-handle-dired-recursive-delete-directory (filename)
2704 "Recursively delete the directory given.
2705 This is like `dired-recursive-delete-directory' for Tramp files."
2706 (with-parsed-tramp-file-name filename nil
2707 ;; Run a shell command 'rm -r <localname>'.
2708 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
2709 (unless (file-exists-p filename)
2710 (tramp-error v 'file-error "No such directory: %s" filename))
2711 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>).
2712 (tramp-send-command
2714 (format "rm -rf %s" (tramp-shell-quote-argument localname))
2715 ;; Don't read the output, do it explicitly.
2716 nil t)
2717 ;; Wait for the remote system to return to us...
2718 ;; This might take a while, allow it plenty of time.
2719 (tramp-wait-for-output (tramp-get-connection-process v) 120)
2720 ;; Make sure that it worked...
2721 (tramp-flush-file-property v (file-name-directory localname))
2722 (tramp-flush-directory-property v localname)
2723 (and (file-exists-p filename)
2724 (tramp-error
2725 v 'file-error "Failed to recursively delete %s" filename))))
2727 (defun tramp-sh-handle-dired-compress-file (file &rest _ok-flag)
2728 "Like `dired-compress-file' for Tramp files."
2729 ;; OK-FLAG is valid for XEmacs only, but not implemented.
2730 ;; Code stolen mainly from dired-aux.el.
2731 (with-parsed-tramp-file-name file nil
2732 (tramp-flush-file-property v localname)
2733 (save-excursion
2734 (let ((suffixes
2735 (if (not (featurep 'xemacs))
2736 ;; Emacs case
2737 (symbol-value 'dired-compress-file-suffixes)
2738 ;; XEmacs has `dired-compression-method-alist', which is
2739 ;; transformed into `dired-compress-file-suffixes' structure.
2740 (mapcar
2741 (lambda (x)
2742 (list (concat (regexp-quote (nth 1 x)) "\\'")
2744 (mapconcat 'identity (nth 3 x) " ")))
2745 (symbol-value 'dired-compression-method-alist))))
2746 suffix)
2747 ;; See if any suffix rule matches this file name.
2748 (while suffixes
2749 (let (case-fold-search)
2750 (if (string-match (car (car suffixes)) localname)
2751 (setq suffix (car suffixes) suffixes nil))
2752 (setq suffixes (cdr suffixes))))
2754 (cond ((file-symlink-p file)
2755 nil)
2756 ((and suffix (nth 2 suffix))
2757 ;; We found an uncompression rule.
2758 (with-tramp-progress-reporter
2759 v 0 (format "Uncompressing %s" file)
2760 (when (tramp-send-command-and-check
2761 v (concat (nth 2 suffix) " "
2762 (tramp-shell-quote-argument localname)))
2763 ;; `dired-remove-file' is not defined in XEmacs.
2764 (tramp-compat-funcall 'dired-remove-file file)
2765 (string-match (car suffix) file)
2766 (concat (substring file 0 (match-beginning 0))))))
2768 ;; We don't recognize the file as compressed, so compress it.
2769 ;; Try gzip.
2770 (with-tramp-progress-reporter v 0 (format "Compressing %s" file)
2771 (when (tramp-send-command-and-check
2772 v (concat "gzip -f "
2773 (tramp-shell-quote-argument localname)))
2774 ;; `dired-remove-file' is not defined in XEmacs.
2775 (tramp-compat-funcall 'dired-remove-file file)
2776 (cond ((file-exists-p (concat file ".gz"))
2777 (concat file ".gz"))
2778 ((file-exists-p (concat file ".z"))
2779 (concat file ".z"))
2780 (t nil))))))))))
2782 (defun tramp-sh-handle-insert-directory
2783 (filename switches &optional wildcard full-directory-p)
2784 "Like `insert-directory' for Tramp files."
2785 (setq filename (expand-file-name filename))
2786 (unless switches (setq switches ""))
2787 (with-parsed-tramp-file-name filename nil
2788 (if (and (featurep 'ls-lisp)
2789 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
2790 (tramp-handle-insert-directory
2791 filename switches wildcard full-directory-p)
2792 (when (stringp switches)
2793 (setq switches (split-string switches)))
2794 (when (and (member "--dired" switches)
2795 (not (tramp-get-ls-command-with-dired v)))
2796 (setq switches (delete "--dired" switches)))
2797 (when wildcard
2798 (setq wildcard (tramp-run-real-handler
2799 'file-name-nondirectory (list localname)))
2800 (setq localname (tramp-run-real-handler
2801 'file-name-directory (list localname))))
2802 (unless (or full-directory-p (member "-d" switches))
2803 (setq switches (append switches '("-d"))))
2804 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
2805 (when wildcard
2806 (setq switches (concat switches " " wildcard)))
2807 (tramp-message
2808 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
2809 switches filename (if wildcard "yes" "no")
2810 (if full-directory-p "yes" "no"))
2811 ;; If `full-directory-p', we just say `ls -l FILENAME'.
2812 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
2813 (if full-directory-p
2814 (tramp-send-command
2816 (format "%s %s %s 2>/dev/null"
2817 (tramp-get-ls-command v)
2818 switches
2819 (if wildcard
2820 localname
2821 (tramp-shell-quote-argument (concat localname ".")))))
2822 (tramp-barf-unless-okay
2824 (format "cd %s" (tramp-shell-quote-argument
2825 (tramp-run-real-handler
2826 'file-name-directory (list localname))))
2827 "Couldn't `cd %s'"
2828 (tramp-shell-quote-argument
2829 (tramp-run-real-handler 'file-name-directory (list localname))))
2830 (tramp-send-command
2832 (format "%s %s %s 2>/dev/null"
2833 (tramp-get-ls-command v)
2834 switches
2835 (if (or wildcard
2836 (zerop (length
2837 (tramp-run-real-handler
2838 'file-name-nondirectory (list localname)))))
2840 (tramp-shell-quote-argument
2841 (tramp-run-real-handler
2842 'file-name-nondirectory (list localname)))))))
2844 (save-restriction
2845 (let ((beg (point)))
2846 (narrow-to-region (point) (point))
2847 ;; We cannot use `insert-buffer-substring' because the Tramp
2848 ;; buffer changes its contents before insertion due to calling
2849 ;; `expand-file' and alike.
2850 (insert
2851 (with-current-buffer (tramp-get-buffer v)
2852 (buffer-string)))
2854 ;; Check for "--dired" output.
2855 (forward-line -2)
2856 (when (looking-at "//SUBDIRED//")
2857 (forward-line -1))
2858 (when (looking-at "//DIRED//\\s-+")
2859 (let ((databeg (match-end 0))
2860 (end (point-at-eol)))
2861 ;; Now read the numeric positions of file names.
2862 (goto-char databeg)
2863 (while (< (point) end)
2864 (let ((start (+ beg (read (current-buffer))))
2865 (end (+ beg (read (current-buffer)))))
2866 (if (memq (char-after end) '(?\n ?\ ))
2867 ;; End is followed by \n or by " -> ".
2868 (put-text-property start end 'dired-filename t))))))
2869 ;; Remove trailing lines.
2870 (goto-char (point-at-bol))
2871 (while (looking-at "//")
2872 (forward-line 1)
2873 (delete-region (match-beginning 0) (point)))
2875 ;; Some busyboxes are reluctant to discard colors.
2876 (unless
2877 (string-match "color" (tramp-get-connection-property v "ls" ""))
2878 (goto-char beg)
2879 (while (re-search-forward tramp-color-escape-sequence-regexp nil t)
2880 (replace-match "")))
2882 ;; Decode the output, it could be multibyte.
2883 (decode-coding-region
2884 beg (point-max)
2885 (or file-name-coding-system
2886 (and (boundp 'default-file-name-coding-system)
2887 (symbol-value 'default-file-name-coding-system))))
2889 ;; The inserted file could be from somewhere else.
2890 (when (and (not wildcard) (not full-directory-p))
2891 (goto-char (point-max))
2892 (when (file-symlink-p filename)
2893 (goto-char (search-backward "->" beg 'noerror)))
2894 (search-backward
2895 (if (zerop (length (file-name-nondirectory filename)))
2897 (file-name-nondirectory filename))
2898 beg 'noerror)
2899 (replace-match (file-relative-name filename) t))
2901 (goto-char (point-max)))))))
2903 ;; Canonicalization of file names.
2905 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2906 "Like `expand-file-name' for Tramp files.
2907 If the localname part of the given file name starts with \"/../\" then
2908 the result will be a local, non-Tramp, file name."
2909 ;; If DIR is not given, use `default-directory' or "/".
2910 (setq dir (or dir default-directory "/"))
2911 ;; Unless NAME is absolute, concat DIR and NAME.
2912 (unless (file-name-absolute-p name)
2913 (setq name (concat (file-name-as-directory dir) name)))
2914 ;; If NAME is not a Tramp file, run the real handler.
2915 (if (not (tramp-connectable-p name))
2916 (tramp-run-real-handler 'expand-file-name (list name nil))
2917 ;; Dissect NAME.
2918 (with-parsed-tramp-file-name name nil
2919 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2920 (setq localname (concat "~/" localname)))
2921 ;; Tilde expansion if necessary. This needs a shell which
2922 ;; groks tilde expansion! The function `tramp-find-shell' is
2923 ;; supposed to find such a shell on the remote host. Please
2924 ;; tell me about it when this doesn't work on your system.
2925 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2926 (let ((uname (match-string 1 localname))
2927 (fname (match-string 2 localname)))
2928 ;; We cannot simply apply "~/", because under sudo "~/" is
2929 ;; expanded to the local user home directory but to the
2930 ;; root home directory. On the other hand, using always
2931 ;; the default user name for tilde expansion is not
2932 ;; appropriate either, because ssh and companions might
2933 ;; use a user name from the config file.
2934 (when (and (string-equal uname "~")
2935 (string-match "\\`su\\(do\\)?\\'" method))
2936 (setq uname (concat uname user)))
2937 (setq uname
2938 (with-tramp-connection-property v uname
2939 (tramp-send-command
2940 v (format "cd %s && pwd" (tramp-shell-quote-argument uname)))
2941 (with-current-buffer (tramp-get-buffer v)
2942 (goto-char (point-min))
2943 (buffer-substring (point) (point-at-eol)))))
2944 (setq localname (concat uname fname))))
2945 ;; There might be a double slash, for example when "~/"
2946 ;; expands to "/". Remove this.
2947 (while (string-match "//" localname)
2948 (setq localname (replace-match "/" t t localname)))
2949 ;; No tilde characters in file name, do normal
2950 ;; `expand-file-name' (this does "/./" and "/../"). We bind
2951 ;; `directory-sep-char' here for XEmacs on Windows, which would
2952 ;; otherwise use backslash. `default-directory' is bound,
2953 ;; because on Windows there would be problems with UNC shares or
2954 ;; Cygwin mounts.
2955 (let ((directory-sep-char ?/)
2956 (default-directory (tramp-compat-temporary-file-directory)))
2957 (tramp-make-tramp-file-name
2958 method user host
2959 (tramp-drop-volume-letter
2960 (tramp-run-real-handler
2961 'expand-file-name (list localname)))
2962 hop)))))
2964 ;;; Remote commands:
2966 (defun tramp-process-sentinel (proc event)
2967 "Flush file caches."
2968 (unless (memq (process-status proc) '(run open))
2969 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2970 (when vec
2971 (tramp-message vec 5 "Sentinel called: `%S' `%s'" proc event)
2972 (tramp-flush-connection-property proc)
2973 (tramp-flush-directory-property vec "")))))
2975 ;; We use BUFFER also as connection buffer during setup. Because of
2976 ;; this, its original contents must be saved, and restored once
2977 ;; connection has been setup.
2978 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2979 "Like `start-file-process' for Tramp files."
2980 (with-parsed-tramp-file-name (expand-file-name default-directory) nil
2981 (let* (;; When PROGRAM matches "*sh", and the first arg is "-c",
2982 ;; it might be that the arguments exceed the command line
2983 ;; length. Therefore, we modify the command.
2984 (heredoc (and (stringp program)
2985 (string-match "sh$" program)
2986 (string-equal "-c" (car args))
2987 (= (length args) 2)))
2988 ;; When PROGRAM is nil, we just provide a tty.
2989 (args (if (not heredoc) args
2990 (let ((i 250))
2991 (while (and (< i (length (cadr args)))
2992 (string-match " " (cadr args) i))
2993 (setcdr
2994 args
2995 (list (replace-match " \\\\\n" nil nil (cadr args))))
2996 (setq i (+ i 250))))
2997 (cdr args)))
2998 ;; Use a human-friendly prompt, for example for `shell'.
2999 ;; We discard hops, if existing, that's why we cannot use
3000 ;; `file-remote-p'.
3001 (prompt (format "PS1=%s %s"
3002 (tramp-make-tramp-file-name
3003 (tramp-file-name-method v)
3004 (tramp-file-name-user v)
3005 (tramp-file-name-host v)
3006 (tramp-file-name-localname v))
3007 tramp-initial-end-of-output))
3008 ;; We use as environment the difference to toplevel
3009 ;; `process-environment'.
3011 (env
3012 (dolist
3013 (elt
3014 (cons prompt (nreverse (copy-sequence process-environment)))
3015 env)
3016 (or (member elt (default-toplevel-value 'process-environment))
3017 (setq env (cons elt env)))))
3018 (command
3019 (when (stringp program)
3020 (format "cd %s && exec %s env %s %s"
3021 (tramp-shell-quote-argument localname)
3022 (if heredoc (format "<<'%s'" tramp-end-of-heredoc) "")
3023 (mapconcat 'tramp-shell-quote-argument env " ")
3024 (if heredoc
3025 (format "%s\n(\n%s\n) </dev/tty\n%s"
3026 program (car args) tramp-end-of-heredoc)
3027 (mapconcat 'tramp-shell-quote-argument
3028 (cons program args) " ")))))
3029 (tramp-process-connection-type
3030 (or (null program) tramp-process-connection-type))
3031 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
3032 (name1 name)
3033 (i 0)
3034 ;; We do not want to raise an error when
3035 ;; `start-file-process' has been started several times in
3036 ;; `eshell' and friends.
3037 (tramp-current-connection nil))
3039 (unless buffer
3040 ;; BUFFER can be nil. We use a temporary buffer.
3041 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
3042 (while (get-process name1)
3043 ;; NAME must be unique as process name.
3044 (setq i (1+ i)
3045 name1 (format "%s<%d>" name i)))
3046 (setq name name1)
3047 ;; Set the new process properties.
3048 (tramp-set-connection-property v "process-name" name)
3049 (tramp-set-connection-property v "process-buffer" buffer)
3051 (with-current-buffer (tramp-get-connection-buffer v)
3052 (unwind-protect
3053 ;; We catch this event. Otherwise, `start-process' could
3054 ;; be called on the local host.
3055 (save-excursion
3056 (save-restriction
3057 ;; Activate narrowing in order to save BUFFER
3058 ;; contents. Clear also the modification time;
3059 ;; otherwise we might be interrupted by
3060 ;; `verify-visited-file-modtime'.
3061 (let ((buffer-undo-list t)
3062 (buffer-read-only nil)
3063 (mark (point-max)))
3064 (clear-visited-file-modtime)
3065 (narrow-to-region (point-max) (point-max))
3066 ;; We call `tramp-maybe-open-connection', in order
3067 ;; to cleanup the prompt afterwards.
3068 (catch 'suppress
3069 (tramp-maybe-open-connection v)
3070 (widen)
3071 (delete-region mark (point))
3072 (narrow-to-region (point-max) (point-max))
3073 ;; Now do it.
3074 (if command
3075 ;; Send the command.
3076 (tramp-send-command v command nil t) ; nooutput
3077 ;; Check, whether a pty is associated.
3078 (unless (tramp-compat-process-get
3079 (tramp-get-connection-process v) 'remote-tty)
3080 (tramp-error
3081 v 'file-error
3082 "pty association is not supported for `%s'" name))))
3083 (let ((p (tramp-get-connection-process v)))
3084 ;; Set query flag and process marker for this
3085 ;; process. We ignore errors, because the process
3086 ;; could have finished already.
3087 (ignore-errors
3088 (tramp-compat-set-process-query-on-exit-flag p t)
3089 (set-marker (process-mark p) (point)))
3090 ;; Return process.
3091 p))))
3093 ;; Save exit.
3094 (if (string-match tramp-temp-buffer-name (buffer-name))
3095 (ignore-errors
3096 (set-process-buffer (tramp-get-connection-process v) nil)
3097 (kill-buffer (current-buffer)))
3098 (set-buffer-modified-p bmp))
3099 (tramp-set-connection-property v "process-name" nil)
3100 (tramp-set-connection-property v "process-buffer" nil))))))
3102 (defun tramp-sh-handle-process-file
3103 (program &optional infile destination display &rest args)
3104 "Like `process-file' for Tramp files."
3105 ;; The implementation is not complete yet.
3106 (when (and (numberp destination) (zerop destination))
3107 (error "Implementation does not handle immediate return"))
3109 (with-parsed-tramp-file-name default-directory nil
3110 (let (command env input tmpinput stderr tmpstderr outbuf ret)
3111 ;; Compute command.
3112 (setq command (mapconcat 'tramp-shell-quote-argument
3113 (cons program args) " "))
3114 ;; We use as environment the difference to toplevel `process-environment'.
3115 (setq env
3116 (dolist (elt (nreverse (copy-sequence process-environment)) env)
3117 (or (member elt (default-toplevel-value 'process-environment))
3118 (setq env (cons elt env)))))
3119 (when env
3120 (setq command
3121 (format
3122 "env %s %s"
3123 (mapconcat 'tramp-shell-quote-argument env " ") command)))
3124 ;; Determine input.
3125 (if (null infile)
3126 (setq input "/dev/null")
3127 (setq infile (expand-file-name infile))
3128 (if (tramp-equal-remote default-directory infile)
3129 ;; INFILE is on the same remote host.
3130 (setq input (with-parsed-tramp-file-name infile nil localname))
3131 ;; INFILE must be copied to remote host.
3132 (setq input (tramp-make-tramp-temp-file v)
3133 tmpinput (tramp-make-tramp-file-name method user host input))
3134 (copy-file infile tmpinput t)))
3135 (when input (setq command (format "%s <%s" command input)))
3137 ;; Determine output.
3138 (cond
3139 ;; Just a buffer.
3140 ((bufferp destination)
3141 (setq outbuf destination))
3142 ;; A buffer name.
3143 ((stringp destination)
3144 (setq outbuf (get-buffer-create destination)))
3145 ;; (REAL-DESTINATION ERROR-DESTINATION)
3146 ((consp destination)
3147 ;; output.
3148 (cond
3149 ((bufferp (car destination))
3150 (setq outbuf (car destination)))
3151 ((stringp (car destination))
3152 (setq outbuf (get-buffer-create (car destination))))
3153 ((car destination)
3154 (setq outbuf (current-buffer))))
3155 ;; stderr.
3156 (cond
3157 ((stringp (cadr destination))
3158 (setcar (cdr destination) (expand-file-name (cadr destination)))
3159 (if (tramp-equal-remote default-directory (cadr destination))
3160 ;; stderr is on the same remote host.
3161 (setq stderr (with-parsed-tramp-file-name
3162 (cadr destination) nil localname))
3163 ;; stderr must be copied to remote host. The temporary
3164 ;; file must be deleted after execution.
3165 (setq stderr (tramp-make-tramp-temp-file v)
3166 tmpstderr (tramp-make-tramp-file-name
3167 method user host stderr))))
3168 ;; stderr to be discarded.
3169 ((null (cadr destination))
3170 (setq stderr "/dev/null"))))
3171 ;; 't
3172 (destination
3173 (setq outbuf (current-buffer))))
3174 (when stderr (setq command (format "%s 2>%s" command stderr)))
3176 ;; Send the command. It might not return in time, so we protect
3177 ;; it. Call it in a subshell, in order to preserve working
3178 ;; directory.
3179 (condition-case nil
3180 (unwind-protect
3181 (setq ret
3182 (if (tramp-send-command-and-check
3183 v (format "cd %s && %s"
3184 (tramp-shell-quote-argument localname)
3185 command)
3186 t t)
3187 0 1))
3188 ;; We should add the output anyway.
3189 (when outbuf
3190 (with-current-buffer outbuf
3191 (insert
3192 (with-current-buffer (tramp-get-connection-buffer v)
3193 (buffer-string))))
3194 (when (and display (get-buffer-window outbuf t)) (redisplay))))
3195 ;; When the user did interrupt, we should do it also. We use
3196 ;; return code -1 as marker.
3197 (quit
3198 (kill-buffer (tramp-get-connection-buffer v))
3199 (setq ret -1))
3200 ;; Handle errors.
3201 (error
3202 (kill-buffer (tramp-get-connection-buffer v))
3203 (setq ret 1)))
3205 ;; Provide error file.
3206 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3208 ;; Cleanup. We remove all file cache values for the connection,
3209 ;; because the remote process could have changed them.
3210 (when tmpinput (delete-file tmpinput))
3212 ;; `process-file-side-effects' has been introduced with GNU
3213 ;; Emacs 23.2. If set to nil, no remote file will be changed
3214 ;; by `program'. If it doesn't exist, we assume its default
3215 ;; value t.
3216 (unless (and (boundp 'process-file-side-effects)
3217 (not (symbol-value 'process-file-side-effects)))
3218 (tramp-flush-directory-property v ""))
3220 ;; Return exit status.
3221 (if (equal ret -1)
3222 (keyboard-quit)
3223 ret))))
3225 (defun tramp-sh-handle-file-local-copy (filename)
3226 "Like `file-local-copy' for Tramp files."
3227 (with-parsed-tramp-file-name filename nil
3228 (unless (file-exists-p filename)
3229 (tramp-error
3230 v 'file-error
3231 "Cannot make local copy of non-existing file `%s'" filename))
3233 (let* ((size (nth 7 (file-attributes (file-truename filename))))
3234 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
3235 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
3236 (tmpfile (tramp-compat-make-temp-file filename)))
3238 (condition-case err
3239 (cond
3240 ;; `copy-file' handles direct copy and out-of-band methods.
3241 ((or (tramp-local-host-p v)
3242 (tramp-method-out-of-band-p v size))
3243 (copy-file filename tmpfile t t))
3245 ;; Use inline encoding for file transfer.
3246 (rem-enc
3247 (save-excursion
3248 (with-tramp-progress-reporter
3250 (format-message "Encoding remote file `%s' with `%s'"
3251 filename rem-enc)
3252 (tramp-barf-unless-okay
3253 v (format rem-enc (tramp-shell-quote-argument localname))
3254 "Encoding remote file failed"))
3256 (with-tramp-progress-reporter
3257 v 3 (format-message "Decoding local file `%s' with `%s'"
3258 tmpfile loc-dec)
3259 (if (functionp loc-dec)
3260 ;; If local decoding is a function, we call it.
3261 ;; We must disable multibyte, because
3262 ;; `uudecode-decode-region' doesn't handle it
3263 ;; correctly. Unset `file-name-handler-alist'.
3264 ;; Otherwise, epa-file gets confused.
3265 (let (file-name-handler-alist
3266 (coding-system-for-write 'binary))
3267 (with-temp-file tmpfile
3268 (set-buffer-multibyte nil)
3269 (insert-buffer-substring (tramp-get-buffer v))
3270 (funcall loc-dec (point-min) (point-max))))
3272 ;; If tramp-decoding-function is not defined for this
3273 ;; method, we invoke tramp-decoding-command instead.
3274 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3275 ;; Unset `file-name-handler-alist'. Otherwise,
3276 ;; epa-file gets confused.
3277 (let (file-name-handler-alist
3278 (coding-system-for-write 'binary))
3279 (with-current-buffer (tramp-get-buffer v)
3280 (write-region
3281 (point-min) (point-max) tmpfile2 nil 'no-message)))
3282 (unwind-protect
3283 (tramp-call-local-coding-command
3284 loc-dec tmpfile2 tmpfile)
3285 (delete-file tmpfile2)))))
3287 ;; Set proper permissions.
3288 (set-file-modes tmpfile (tramp-default-file-modes filename))
3289 ;; Set local user ownership.
3290 (tramp-set-file-uid-gid tmpfile)))
3292 ;; Oops, I don't know what to do.
3293 (t (tramp-error
3294 v 'file-error "Wrong method specification for `%s'" method)))
3296 ;; Error handling.
3297 ((error quit)
3298 (delete-file tmpfile)
3299 (signal (car err) (cdr err))))
3301 (run-hooks 'tramp-handle-file-local-copy-hook)
3302 tmpfile)))
3304 ;; This is needed for XEmacs only. Code stolen from files.el.
3305 (defun tramp-sh-handle-insert-file-contents-literally
3306 (filename &optional visit beg end replace)
3307 "Like `insert-file-contents-literally' for Tramp files."
3308 (let ((format-alist nil)
3309 (after-insert-file-functions nil)
3310 (coding-system-for-read 'no-conversion)
3311 (coding-system-for-write 'no-conversion)
3312 (find-buffer-file-type-function
3313 (if (fboundp 'find-buffer-file-type)
3314 (symbol-function 'find-buffer-file-type)
3315 nil))
3316 (inhibit-file-name-handlers
3317 '(epa-file-handler image-file-handler jka-compr-handler))
3318 (inhibit-file-name-operation 'insert-file-contents))
3319 (unwind-protect
3320 (progn
3321 (fset 'find-buffer-file-type (lambda (_filename) t))
3322 (insert-file-contents filename visit beg end replace))
3323 ;; Save exit.
3324 (if find-buffer-file-type-function
3325 (fset 'find-buffer-file-type find-buffer-file-type-function)
3326 (fmakunbound 'find-buffer-file-type)))))
3328 ;; CCC grok LOCKNAME
3329 (defun tramp-sh-handle-write-region
3330 (start end filename &optional append visit lockname confirm)
3331 "Like `write-region' for Tramp files."
3332 (setq filename (expand-file-name filename))
3333 (with-parsed-tramp-file-name filename nil
3334 ;; Following part commented out because we don't know what to do about
3335 ;; file locking, and it does not appear to be a problem to ignore it.
3336 ;; Ange-ftp ignores it, too.
3337 ;; (when (and lockname (stringp lockname))
3338 ;; (setq lockname (expand-file-name lockname)))
3339 ;; (unless (or (eq lockname nil)
3340 ;; (string= lockname filename))
3341 ;; (error
3342 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3344 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
3345 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
3346 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3347 (tramp-error v 'file-error "File not overwritten")))
3349 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
3350 (tramp-get-remote-uid v 'integer)))
3351 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
3352 (tramp-get-remote-gid v 'integer))))
3354 (if (and (tramp-local-host-p v)
3355 ;; `file-writable-p' calls `file-expand-file-name'. We
3356 ;; cannot use `tramp-run-real-handler' therefore.
3357 (let (file-name-handler-alist)
3358 (and
3359 (file-writable-p (file-name-directory localname))
3360 (or (file-directory-p localname)
3361 (file-writable-p localname)))))
3362 ;; Short track: if we are on the local host, we can run directly.
3363 (tramp-run-real-handler
3364 'write-region
3365 (list start end localname append 'no-message lockname confirm))
3367 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3368 ;; We use this to save the value of
3369 ;; `last-coding-system-used' after writing the tmp
3370 ;; file. At the end of the function, we set
3371 ;; `last-coding-system-used' to this saved value. This
3372 ;; way, any intermediary coding systems used while
3373 ;; talking to the remote shell or suchlike won't hose
3374 ;; this variable. This approach was snarfed from
3375 ;; ange-ftp.el.
3376 coding-system-used
3377 ;; Write region into a tmp file. This isn't really
3378 ;; needed if we use an encoding function, but currently
3379 ;; we use it always because this makes the logic
3380 ;; simpler. We must also set `temporary-file-directory',
3381 ;; because it could point to a remote directory.
3382 (temporary-file-directory
3383 (tramp-compat-temporary-file-directory))
3384 (tmpfile (or tramp-temp-buffer-file-name
3385 (tramp-compat-make-temp-file filename))))
3387 ;; If `append' is non-nil, we copy the file locally, and let
3388 ;; the native `write-region' implementation do the job.
3389 (when append (copy-file filename tmpfile 'ok))
3391 ;; We say `no-message' here because we don't want the
3392 ;; visited file modtime data to be clobbered from the temp
3393 ;; file. We call `set-visited-file-modtime' ourselves later
3394 ;; on. We must ensure that `file-coding-system-alist'
3395 ;; matches `tmpfile'.
3396 (let (file-name-handler-alist
3397 (file-coding-system-alist
3398 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3399 (condition-case err
3400 (tramp-run-real-handler
3401 'write-region
3402 (list start end tmpfile append 'no-message lockname confirm))
3403 ((error quit)
3404 (setq tramp-temp-buffer-file-name nil)
3405 (delete-file tmpfile)
3406 (signal (car err) (cdr err))))
3408 ;; Now, `last-coding-system-used' has the right value. Remember it.
3409 (when (boundp 'last-coding-system-used)
3410 (setq coding-system-used
3411 (symbol-value 'last-coding-system-used))))
3413 ;; The permissions of the temporary file should be set. If
3414 ;; FILENAME does not exist (eq modes nil) it has been
3415 ;; renamed to the backup file. This case `save-buffer'
3416 ;; handles permissions.
3417 ;; Ensure that it is still readable.
3418 (when modes
3419 (set-file-modes
3420 tmpfile
3421 (logior (or modes 0) (tramp-compat-octal-to-decimal "0400"))))
3423 ;; This is a bit lengthy due to the different methods
3424 ;; possible for file transfer. First, we check whether the
3425 ;; method uses an scp program. If so, we call it.
3426 ;; Otherwise, both encoding and decoding command must be
3427 ;; specified. However, if the method _also_ specifies an
3428 ;; encoding function, then that is used for encoding the
3429 ;; contents of the tmp file.
3430 (let* ((size (nth 7 (file-attributes tmpfile)))
3431 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3432 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3433 (cond
3434 ;; `copy-file' handles direct copy and out-of-band methods.
3435 ((or (tramp-local-host-p v)
3436 (tramp-method-out-of-band-p v size))
3437 (if (and (not (stringp start))
3438 (= (or end (point-max)) (point-max))
3439 (= (or start (point-min)) (point-min))
3440 (tramp-get-method-parameter v 'tramp-copy-keep-tmpfile))
3441 (progn
3442 (setq tramp-temp-buffer-file-name tmpfile)
3443 (condition-case err
3444 ;; We keep the local file for performance
3445 ;; reasons, useful for "rsync".
3446 (copy-file tmpfile filename t)
3447 ((error quit)
3448 (setq tramp-temp-buffer-file-name nil)
3449 (delete-file tmpfile)
3450 (signal (car err) (cdr err)))))
3451 (setq tramp-temp-buffer-file-name nil)
3452 ;; Don't rename, in order to keep context in SELinux.
3453 (unwind-protect
3454 (copy-file tmpfile filename t)
3455 (delete-file tmpfile))))
3457 ;; Use inline file transfer.
3458 (rem-dec
3459 ;; Encode tmpfile.
3460 (unwind-protect
3461 (with-temp-buffer
3462 (set-buffer-multibyte nil)
3463 ;; Use encoding function or command.
3464 (with-tramp-progress-reporter
3465 v 3 (format-message
3466 "Encoding local file `%s' using `%s'"
3467 tmpfile loc-enc)
3468 (if (functionp loc-enc)
3469 ;; The following `let' is a workaround for
3470 ;; the base64.el that comes with pgnus-0.84.
3471 ;; If both of the following conditions are
3472 ;; satisfied, it tries to write to a local
3473 ;; file in default-directory, but at this
3474 ;; point, default-directory is remote.
3475 ;; (`call-process-region' can't write to
3476 ;; remote files, it seems.) The file in
3477 ;; question is a tmp file anyway.
3478 (let ((coding-system-for-read 'binary)
3479 (default-directory
3480 (tramp-compat-temporary-file-directory)))
3481 (insert-file-contents-literally tmpfile)
3482 (funcall loc-enc (point-min) (point-max)))
3484 (unless (zerop (tramp-call-local-coding-command
3485 loc-enc tmpfile t))
3486 (tramp-error
3487 v 'file-error
3488 (concat "Cannot write to `%s', "
3489 "local encoding command `%s' failed")
3490 filename loc-enc))))
3492 ;; Send buffer into remote decoding command which
3493 ;; writes to remote file. Because this happens on
3494 ;; the remote host, we cannot use the function.
3495 (with-tramp-progress-reporter
3496 v 3 (format-message
3497 "Decoding remote file `%s' using `%s'"
3498 filename rem-dec)
3499 (goto-char (point-max))
3500 (unless (bolp) (newline))
3501 (tramp-send-command
3503 (format
3504 (concat rem-dec " <<'%s'\n%s%s")
3505 (tramp-shell-quote-argument localname)
3506 tramp-end-of-heredoc
3507 (buffer-string)
3508 tramp-end-of-heredoc))
3509 (tramp-barf-unless-okay
3510 v nil
3511 "Couldn't write region to `%s', decode using `%s' failed"
3512 filename rem-dec)
3513 ;; When `file-precious-flag' is set, the region is
3514 ;; written to a temporary file. Check that the
3515 ;; checksum is equal to that from the local tmpfile.
3516 (when file-precious-flag
3517 (erase-buffer)
3518 (and
3519 ;; cksum runs locally, if possible.
3520 (zerop (tramp-call-process v "cksum" tmpfile t))
3521 ;; cksum runs remotely.
3522 (tramp-send-command-and-check
3524 (format
3525 "cksum <%s" (tramp-shell-quote-argument localname)))
3526 ;; ... they are different.
3527 (not
3528 (string-equal
3529 (buffer-string)
3530 (with-current-buffer (tramp-get-buffer v)
3531 (buffer-string))))
3532 (tramp-error
3533 v 'file-error
3534 (concat "Couldn't write region to `%s',"
3535 " decode using `%s' failed")
3536 filename rem-dec)))))
3538 ;; Save exit.
3539 (delete-file tmpfile)))
3541 ;; That's not expected.
3543 (tramp-error
3544 v 'file-error
3545 (concat "Method `%s' should specify both encoding and "
3546 "decoding command or an scp program")
3547 method))))
3549 ;; Make `last-coding-system-used' have the right value.
3550 (when coding-system-used
3551 (set 'last-coding-system-used coding-system-used))))
3553 (tramp-flush-file-property v (file-name-directory localname))
3554 (tramp-flush-file-property v localname)
3556 ;; We must protect `last-coding-system-used', now we have set it
3557 ;; to its correct value.
3558 (let (last-coding-system-used (need-chown t))
3559 ;; Set file modification time.
3560 (when (or (eq visit t) (stringp visit))
3561 (let ((file-attr (tramp-compat-file-attributes filename 'integer)))
3562 (set-visited-file-modtime
3563 ;; We must pass modtime explicitly, because FILENAME can
3564 ;; be different from (buffer-file-name), f.e. if
3565 ;; `file-precious-flag' is set.
3566 (nth 5 file-attr))
3567 (when (and (= (nth 2 file-attr) uid)
3568 (= (nth 3 file-attr) gid))
3569 (setq need-chown nil))))
3571 ;; Set the ownership.
3572 (when need-chown
3573 (tramp-set-file-uid-gid filename uid gid))
3574 (when (or (eq visit t) (null visit) (stringp visit))
3575 (tramp-message v 0 "Wrote %s" filename))
3576 (run-hooks 'tramp-handle-write-region-hook)))))
3578 (defvar tramp-vc-registered-file-names nil
3579 "List used to collect file names, which are checked during `vc-registered'.")
3581 ;; VC backends check for the existence of various different special
3582 ;; files. This is very time consuming, because every single check
3583 ;; requires a remote command (the file cache must be invalidated).
3584 ;; Therefore, we apply a kind of optimization. We install the file
3585 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3586 ;; remembers all file names for which `file-exists-p' or
3587 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3588 ;; is performed. Afterwards, a script is applied for all collected
3589 ;; file names, using just one remote command. The result of this
3590 ;; script is used to fill the file cache with actual values. Now we
3591 ;; can reset the file name handlers, and we make a second run of
3592 ;; `vc-registered', which returns the expected result without sending
3593 ;; any other remote command.
3594 (defun tramp-sh-handle-vc-registered (file)
3595 "Like `vc-registered' for Tramp files."
3596 (tramp-compat-with-temp-message ""
3597 (with-parsed-tramp-file-name file nil
3598 (with-tramp-progress-reporter
3599 v 3 (format-message "Checking `vc-registered' for %s" file)
3601 ;; There could be new files, created by the vc backend. We
3602 ;; cannot reuse the old cache entries, therefore. In
3603 ;; `tramp-get-file-property', `remote-file-name-inhibit-cache'
3604 ;; could also be a timestamp as `current-time' returns. This
3605 ;; means invalidate all cache entries with an older timestamp.
3606 (let (tramp-vc-registered-file-names
3607 (remote-file-name-inhibit-cache (current-time))
3608 (file-name-handler-alist
3609 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3611 ;; Here we collect only file names, which need an operation.
3612 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3613 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3615 ;; Send just one command, in order to fill the cache.
3616 (when tramp-vc-registered-file-names
3617 (tramp-maybe-send-script
3619 (format tramp-vc-registered-read-file-names
3620 (tramp-get-file-exists-command v)
3621 (format "%s -r" (tramp-get-test-command v)))
3622 "tramp_vc_registered_read_file_names")
3624 (dolist
3625 (elt
3626 (ignore-errors
3627 ;; We cannot use `tramp-send-command-and-read',
3628 ;; because this does not cooperate well with
3629 ;; heredoc documents.
3630 (tramp-send-command
3632 (format
3633 "tramp_vc_registered_read_file_names <<'%s'\n%s\n%s\n"
3634 tramp-end-of-heredoc
3635 (mapconcat 'tramp-shell-quote-argument
3636 tramp-vc-registered-file-names
3637 "\n")
3638 tramp-end-of-heredoc))
3639 (with-current-buffer (tramp-get-connection-buffer v)
3640 ;; Read the expression.
3641 (goto-char (point-min))
3642 (read (current-buffer)))))
3644 (tramp-set-file-property
3645 v (car elt) (cadr elt) (cadr (cdr elt))))))
3647 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3648 ;; calls shall be answered from the file cache. We unset
3649 ;; `process-file-side-effects' and `remote-file-name-inhibit-cache'
3650 ;; in order to keep the cache.
3651 (let ((vc-handled-backends vc-handled-backends)
3652 remote-file-name-inhibit-cache process-file-side-effects)
3653 ;; Reduce `vc-handled-backends' in order to minimize process calls.
3654 (when (and (memq 'Bzr vc-handled-backends)
3655 (boundp 'vc-bzr-program)
3656 (not (with-tramp-connection-property v vc-bzr-program
3657 (tramp-find-executable
3658 v vc-bzr-program (tramp-get-remote-path v)))))
3659 (setq vc-handled-backends (remq 'Bzr vc-handled-backends)))
3660 (when (and (memq 'Git vc-handled-backends)
3661 (boundp 'vc-git-program)
3662 (not (with-tramp-connection-property v vc-git-program
3663 (tramp-find-executable
3664 v vc-git-program (tramp-get-remote-path v)))))
3665 (setq vc-handled-backends (remq 'Git vc-handled-backends)))
3666 (when (and (memq 'Hg vc-handled-backends)
3667 (boundp 'vc-hg-program)
3668 (not (with-tramp-connection-property v vc-hg-program
3669 (tramp-find-executable
3670 v vc-hg-program (tramp-get-remote-path v)))))
3671 (setq vc-handled-backends (remq 'Hg vc-handled-backends)))
3672 ;; Run.
3673 (ignore-errors
3674 (tramp-run-real-handler 'vc-registered (list file))))))))
3676 ;;;###tramp-autoload
3677 (defun tramp-sh-file-name-handler (operation &rest args)
3678 "Invoke remote-shell Tramp file name handler.
3679 Fall back to normal file name handler if no Tramp handler exists."
3680 (when (and tramp-locked (not tramp-locker))
3681 (setq tramp-locked nil)
3682 (tramp-error
3683 (car-safe tramp-current-connection) 'file-error
3684 "Forbidden reentrant call of Tramp"))
3685 (let ((tl tramp-locked))
3686 (setq tramp-locked t)
3687 (unwind-protect
3688 (let ((tramp-locker t))
3689 (save-match-data
3690 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3691 (if fn
3692 (apply (cdr fn) args)
3693 (tramp-run-real-handler operation args)))))
3694 (setq tramp-locked tl))))
3696 (defun tramp-vc-file-name-handler (operation &rest args)
3697 "Invoke special file name handler, which collects files to be handled."
3698 (save-match-data
3699 (let ((filename
3700 (tramp-replace-environment-variables
3701 (apply 'tramp-file-name-for-operation operation args)))
3702 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3703 (with-parsed-tramp-file-name filename nil
3704 (cond
3705 ;; That's what we want: file names, for which checks are
3706 ;; applied. We assume that VC uses only `file-exists-p' and
3707 ;; `file-readable-p' checks; otherwise we must extend the
3708 ;; list. We do not perform any action, but return nil, in
3709 ;; order to keep `vc-registered' running.
3710 ((and fn (memq operation '(file-exists-p file-readable-p)))
3711 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3712 nil)
3713 ;; `process-file' and `start-file-process' shall be ignored.
3714 ((and fn (eq operation 'process-file) 0))
3715 ((and fn (eq operation 'start-file-process) nil))
3716 ;; Tramp file name handlers like `expand-file-name'. They
3717 ;; must still work.
3718 (fn (save-match-data (apply (cdr fn) args)))
3719 ;; Default file name handlers, we don't care.
3720 (t (tramp-run-real-handler operation args)))))))
3722 (defun tramp-sh-handle-file-notify-add-watch (file-name flags _callback)
3723 "Like `file-notify-add-watch' for Tramp files."
3724 (setq file-name (expand-file-name file-name))
3725 (with-parsed-tramp-file-name file-name nil
3726 (let ((default-directory (file-name-directory file-name))
3727 command events filter p sequence)
3728 (cond
3729 ;; gvfs-monitor-dir.
3730 ((setq command (tramp-get-remote-gvfs-monitor-dir v))
3731 (setq filter 'tramp-sh-gvfs-monitor-dir-process-filter
3732 events
3733 (cond
3734 ((and (memq 'change flags) (memq 'attribute-change flags))
3735 '(created changed changes-done-hint moved deleted
3736 attribute-changed))
3737 ((memq 'change flags)
3738 '(created changed changes-done-hint moved deleted))
3739 ((memq 'attribute-change flags) '(attribute-changed)))
3740 sequence `(,command ,localname)))
3741 ;; inotifywait.
3742 ((setq command (tramp-get-remote-inotifywait v))
3743 (setq filter 'tramp-sh-inotifywait-process-filter
3744 events
3745 (cond
3746 ((and (memq 'change flags) (memq 'attribute-change flags))
3747 (concat "create,modify,move,moved_from,moved_to,move_self,"
3748 "delete,delete_self,attrib,ignored"))
3749 ((memq 'change flags)
3750 (concat "create,modify,move,moved_from,moved_to,move_self,"
3751 "delete,delete_self,ignored"))
3752 ((memq 'attribute-change flags) "attrib,ignored"))
3753 sequence `(,command "-mq" "-e" ,events ,localname)))
3754 ;; None.
3755 (t (tramp-error
3756 v 'file-notify-error
3757 "No file notification program found on %s"
3758 (file-remote-p file-name))))
3759 ;; Start process.
3760 (setq p (apply
3761 'start-file-process
3762 (file-name-nondirectory command)
3763 (generate-new-buffer
3764 (format " *%s*" (file-name-nondirectory command)))
3765 sequence))
3766 ;; Return the process object as watch-descriptor.
3767 (if (not (processp p))
3768 (tramp-error
3769 v 'file-notify-error
3770 "`%s' failed to start on remote host"
3771 (mapconcat 'identity sequence " "))
3772 (tramp-message v 6 "Run `%s', %S" (mapconcat 'identity sequence " ") p)
3773 (tramp-set-connection-property p "vector" v)
3774 ;; Needed for `tramp-sh-gvfs-monitor-dir-process-filter'.
3775 (tramp-compat-process-put p 'events events)
3776 (tramp-compat-process-put p 'watch-name localname)
3777 (tramp-compat-set-process-query-on-exit-flag p nil)
3778 (set-process-filter p filter)
3779 ;; There might be an error if the monitor is not supported.
3780 ;; Give the filter a chance to read the output.
3781 (tramp-accept-process-output p 1)
3782 (unless (memq (process-status p) '(run open))
3783 (tramp-error
3784 v 'file-notify-error "Monitoring not supported for `%s'" file-name))
3785 p))))
3787 (defun tramp-sh-gvfs-monitor-dir-process-filter (proc string)
3788 "Read output from \"gvfs-monitor-dir\" and add corresponding \
3789 file-notify events."
3790 (let ((remote-prefix
3791 (with-current-buffer (process-buffer proc)
3792 (file-remote-p default-directory)))
3793 (rest-string (tramp-compat-process-get proc 'rest-string)))
3794 (when rest-string
3795 (tramp-message proc 10 "Previous string:\n%s" rest-string))
3796 (tramp-message proc 6 "%S\n%s" proc string)
3797 (setq string (concat rest-string string)
3798 ;; Attribute change is returned in unused wording.
3799 string (tramp-compat-replace-regexp-in-string
3800 "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))
3801 (when (string-match "Monitoring not supported" string)
3802 (delete-process proc))
3804 (while (string-match
3805 (concat "^[\n\r]*"
3806 "Directory Monitor Event:[\n\r]+"
3807 "Child = \\([^\n\r]+\\)[\n\r]+"
3808 "\\(Other = \\([^\n\r]+\\)[\n\r]+\\)?"
3809 "Event = \\([^[:blank:]]+\\)[\n\r]+")
3810 string)
3811 (let* ((file (match-string 1 string))
3812 (file1 (match-string 3 string))
3813 (object
3814 (list
3815 proc
3816 (intern-soft
3817 (tramp-compat-replace-regexp-in-string
3818 "_" "-" (downcase (match-string 4 string))))
3819 ;; File names are returned as absolute paths. We must
3820 ;; add the remote prefix.
3821 (concat remote-prefix file)
3822 (when file1 (concat remote-prefix file1)))))
3823 (setq string (replace-match "" nil nil string))
3824 ;; Remove watch when file or directory to be watched is deleted.
3825 (when (and (member (cadr object) '(moved deleted))
3826 (string-equal
3827 file (tramp-compat-process-get proc 'watch-name)))
3828 (delete-process proc))
3829 ;; Usually, we would add an Emacs event now. Unfortunately,
3830 ;; `unread-command-events' does not accept several events at
3831 ;; once. Therefore, we apply the callback directly.
3832 (when (member (cadr object) (tramp-compat-process-get proc 'events))
3833 (tramp-compat-funcall 'file-notify-callback object))))
3835 ;; Save rest of the string.
3836 (when (zerop (length string)) (setq string nil))
3837 (when string (tramp-message proc 10 "Rest string:\n%s" string))
3838 (tramp-compat-process-put proc 'rest-string string)))
3840 (defun tramp-sh-inotifywait-process-filter (proc string)
3841 "Read output from \"inotifywait\" and add corresponding file-notify events."
3842 (tramp-message proc 6 "%S\n%s" proc string)
3843 (dolist (line (split-string string "[\n\r]+" 'omit-nulls))
3844 ;; Check, whether there is a problem.
3845 (unless
3846 (string-match
3847 (concat "^[^[:blank:]]+"
3848 "[[:blank:]]+\\([^[:blank:]]+\\)+"
3849 "\\([[:blank:]]+\\([^\n\r]+\\)\\)?")
3850 line)
3851 (tramp-error proc 'file-notify-error "%s" line))
3853 (let ((object
3854 (list
3855 proc
3856 (mapcar
3857 (lambda (x)
3858 (intern-soft
3859 (tramp-compat-replace-regexp-in-string "_" "-" (downcase x))))
3860 (split-string (match-string 1 line) "," 'omit-nulls))
3861 (match-string 3 line))))
3862 ;; Remove watch when file or directory to be watched is deleted.
3863 (when (equal (cadr object) 'ignored)
3864 (delete-process proc))
3865 ;; Usually, we would add an Emacs event now. Unfortunately,
3866 ;; `unread-command-events' does not accept several events at
3867 ;; once. Therefore, we apply the callback directly.
3868 (tramp-compat-funcall 'file-notify-callback object))))
3870 ;;; Internal Functions:
3872 (defun tramp-maybe-send-script (vec script name)
3873 "Define in remote shell function NAME implemented as SCRIPT.
3874 Only send the definition if it has not already been done."
3875 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3876 ;; might be nil.
3877 (let ((scripts (tramp-get-connection-property
3878 (tramp-get-connection-process vec) "scripts" nil)))
3879 (unless (member name scripts)
3880 (with-tramp-progress-reporter
3881 vec 5 (format-message "Sending script `%s'" name)
3882 ;; In bash, leading TABs like in `tramp-vc-registered-read-file-names'
3883 ;; could result in unwanted command expansion. Avoid this.
3884 (setq script (tramp-compat-replace-regexp-in-string
3885 (make-string 1 ?\t) (make-string 8 ? ) script))
3886 ;; The script could contain a call of Perl. This is masked with `%s'.
3887 (when (and (string-match "%s" script)
3888 (not (tramp-get-remote-perl vec)))
3889 (tramp-error vec 'file-error "No Perl available on remote host"))
3890 (tramp-barf-unless-okay
3892 (format "%s () {\n%s\n}"
3893 name (format script (tramp-get-remote-perl vec)))
3894 "Script %s sending failed" name)
3895 (tramp-set-connection-property
3896 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3898 (defun tramp-run-test (switch filename)
3899 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3900 Returns the exit code of the `test' program."
3901 (with-parsed-tramp-file-name filename nil
3902 (tramp-send-command-and-check
3904 (format
3905 "%s %s %s"
3906 (tramp-get-test-command v)
3907 switch
3908 (tramp-shell-quote-argument localname)))))
3910 (defun tramp-run-test2 (format-string file1 file2)
3911 "Run `test'-like program on the remote system, given FILE1, FILE2.
3912 FORMAT-STRING contains the program name, switches, and place holders.
3913 Returns the exit code of the `test' program. Barfs if the methods,
3914 hosts, or files, disagree."
3915 (unless (tramp-equal-remote file1 file2)
3916 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3917 (tramp-error
3918 v 'file-error
3919 "tramp-run-test2 only implemented for same method, user, host")))
3920 (with-parsed-tramp-file-name file1 v1
3921 (with-parsed-tramp-file-name file1 v2
3922 (tramp-send-command-and-check
3924 (format format-string
3925 (tramp-shell-quote-argument v1-localname)
3926 (tramp-shell-quote-argument v2-localname))))))
3928 (defun tramp-find-executable
3929 (vec progname dirlist &optional ignore-tilde ignore-path)
3930 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3931 First arg VEC specifies the connection, PROGNAME is the program
3932 to search for, and DIRLIST gives the list of directories to
3933 search. If IGNORE-TILDE is non-nil, directory names starting
3934 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3935 only in DIRLIST.
3937 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3939 This function expects to be in the right *tramp* buffer."
3940 (with-current-buffer (tramp-get-connection-buffer vec)
3941 (let (result)
3942 ;; Check whether the executable is in $PATH. "which(1)" does not
3943 ;; report always a correct error code; therefore we check the
3944 ;; number of words it returns. "SunOS 5.10" (and maybe "SunOS
3945 ;; 5.11") have problems with this command, we disable the call
3946 ;; therefore.
3947 (unless (or ignore-path
3948 (string-match
3949 (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3950 (tramp-get-connection-property vec "uname" "")))
3951 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3952 (goto-char (point-min))
3953 (if (looking-at "^\\s-*1$")
3954 (setq result (concat "\\" progname))))
3955 (unless result
3956 (when ignore-tilde
3957 ;; Remove all ~/foo directories from dirlist. In XEmacs,
3958 ;; `remove' is in CL, and we want to avoid CL dependencies.
3959 (let (newdl d)
3960 (while dirlist
3961 (setq d (car dirlist))
3962 (setq dirlist (cdr dirlist))
3963 (unless (char-equal ?~ (aref d 0))
3964 (setq newdl (cons d newdl))))
3965 (setq dirlist (nreverse newdl))))
3966 (tramp-send-command
3968 (format (concat "while read d; "
3969 "do if test -x $d/%s && test -f $d/%s; "
3970 "then echo tramp_executable $d/%s; "
3971 "break; fi; done <<'%s'\n"
3972 "%s\n%s")
3973 progname progname progname
3974 tramp-end-of-heredoc
3975 (mapconcat 'identity dirlist "\n")
3976 tramp-end-of-heredoc))
3977 (goto-char (point-max))
3978 (when (search-backward "tramp_executable " nil t)
3979 (skip-chars-forward "^ ")
3980 (skip-chars-forward " ")
3981 (setq result (buffer-substring (point) (point-at-eol)))))
3982 result)))
3984 (defun tramp-set-remote-path (vec)
3985 "Sets the remote environment PATH to existing directories.
3986 I.e., for each directory in `tramp-remote-path', it is tested
3987 whether it exists and if so, it is added to the environment
3988 variable PATH."
3989 (tramp-message vec 5 "Setting $PATH environment variable")
3990 (tramp-send-command
3991 vec (format "PATH=%s; export PATH"
3992 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3994 ;; ------------------------------------------------------------
3995 ;; -- Communication with external shell --
3996 ;; ------------------------------------------------------------
3998 (defun tramp-find-file-exists-command (vec)
3999 "Find a command on the remote host for checking if a file exists.
4000 Here, we are looking for a command which has zero exit status if the
4001 file exists and nonzero exit status otherwise."
4002 (let ((existing "/")
4003 (nonexistent
4004 (tramp-shell-quote-argument "/ this file does not exist "))
4005 result)
4006 ;; The algorithm is as follows: we try a list of several commands.
4007 ;; For each command, we first run `$cmd /' -- this should return
4008 ;; true, as the root directory always exists. And then we run
4009 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
4010 ;; does not exist. This should return false. We use the first
4011 ;; command we find that seems to work.
4012 ;; The list of commands to try is as follows:
4013 ;; `ls -d' This works on most systems, but NetBSD 1.4
4014 ;; has a bug: `ls' always returns zero exit
4015 ;; status, even for files which don't exist.
4016 ;; `test -e' Some Bourne shells have a `test' builtin
4017 ;; which does not know the `-e' option.
4018 ;; `/bin/test -e' For those, the `test' binary on disk normally
4019 ;; provides the option. Alas, the binary
4020 ;; is sometimes `/bin/test' and sometimes it's
4021 ;; `/usr/bin/test'.
4022 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
4023 (unless (or
4024 (ignore-errors
4025 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
4026 (tramp-send-command-and-check
4027 vec (format "%s %s" result existing))
4028 (not (tramp-send-command-and-check
4029 vec (format "%s %s" result nonexistent)))))
4030 (ignore-errors
4031 (and (setq result "/bin/test -e")
4032 (tramp-send-command-and-check
4033 vec (format "%s %s" result existing))
4034 (not (tramp-send-command-and-check
4035 vec (format "%s %s" result nonexistent)))))
4036 (ignore-errors
4037 (and (setq result "/usr/bin/test -e")
4038 (tramp-send-command-and-check
4039 vec (format "%s %s" result existing))
4040 (not (tramp-send-command-and-check
4041 vec (format "%s %s" result nonexistent)))))
4042 (ignore-errors
4043 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
4044 (tramp-send-command-and-check
4045 vec (format "%s %s" result existing))
4046 (not (tramp-send-command-and-check
4047 vec (format "%s %s" result nonexistent))))))
4048 (tramp-error
4049 vec 'file-error "Couldn't find command to check if file exists"))
4050 result))
4052 (defun tramp-open-shell (vec shell)
4053 "Opens shell SHELL."
4054 (with-tramp-progress-reporter
4055 vec 5 (format-message "Opening remote shell `%s'" shell)
4056 ;; Find arguments for this shell.
4057 (let ((alist tramp-sh-extra-args)
4058 item extra-args)
4059 (while (and alist (null extra-args))
4060 (setq item (pop alist))
4061 (when (string-match (car item) shell)
4062 (setq extra-args (cdr item))))
4063 ;; It is useful to set the prompt in the following command
4064 ;; because some people have a setting for $PS1 which /bin/sh
4065 ;; doesn't know about and thus /bin/sh will display a strange
4066 ;; prompt. For example, if $PS1 has "${CWD}" in the value, then
4067 ;; ksh will display the current working directory but /bin/sh
4068 ;; will display a dollar sign. The following command line sets
4069 ;; $PS1 to a sane value, and works under Bourne-ish shells as
4070 ;; well as csh-like shells. We also unset the variable $ENV
4071 ;; because that is read by some sh implementations (eg, bash
4072 ;; when called as sh) on startup; this way, we avoid the startup
4073 ;; file clobbering $PS1. $PROMPT_COMMAND is another way to set
4074 ;; the prompt in /bin/bash, it must be discarded as well.
4075 ;; $HISTFILE is set according to `tramp-histfile-override'.
4076 (tramp-send-command
4077 vec (format
4078 "exec env ENV='' %s PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
4079 (if (stringp tramp-histfile-override)
4080 (format "HISTFILE=%s"
4081 (tramp-shell-quote-argument tramp-histfile-override))
4082 (if tramp-histfile-override
4083 "HISTFILE='' HISTFILESIZE=0 HISTSIZE=0"
4084 ""))
4085 (tramp-shell-quote-argument tramp-end-of-output)
4086 shell (or extra-args ""))
4088 (tramp-set-connection-property
4089 (tramp-get-connection-process vec) "remote-shell" shell)))
4091 (defun tramp-find-shell (vec)
4092 "Opens a shell on the remote host which groks tilde expansion."
4093 (with-current-buffer (tramp-get-buffer vec)
4094 (let ((default-shell (tramp-get-method-parameter vec 'tramp-remote-shell))
4095 shell)
4096 (setq shell
4097 (with-tramp-connection-property vec "remote-shell"
4098 ;; CCC: "root" does not exist always, see QNAP 459.
4099 ;; Which check could we apply instead?
4100 (tramp-send-command vec "echo ~root" t)
4101 (if (or (string-match "^~root$" (buffer-string))
4102 ;; The default shell (ksh93) of OpenSolaris and
4103 ;; Solaris is buggy. We've got reports for
4104 ;; "SunOS 5.10" and "SunOS 5.11" so far.
4105 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
4106 (tramp-get-connection-property
4107 vec "uname" "")))
4109 (or (tramp-find-executable
4110 vec "bash" (tramp-get-remote-path vec) t t)
4111 (tramp-find-executable
4112 vec "ksh" (tramp-get-remote-path vec) t t)
4113 ;; Maybe it works at least for some other commands.
4114 (prog1
4115 default-shell
4116 (tramp-message
4117 vec 2
4118 (concat
4119 "Couldn't find a remote shell which groks tilde "
4120 "expansion, using `%s'")
4121 default-shell)))
4123 default-shell)))
4125 ;; Open a new shell if needed.
4126 (unless (string-equal shell default-shell)
4127 (tramp-message
4128 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
4129 (tramp-open-shell vec shell)))))
4131 ;; Utility functions.
4133 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
4134 "Wait for shell prompt and barf if none appears.
4135 Looks at process PROC to see if a shell prompt appears in TIMEOUT
4136 seconds. If not, it produces an error message with the given ERROR-ARGS."
4137 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4138 (condition-case nil
4139 (tramp-wait-for-regexp
4140 proc timeout
4141 (format
4142 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
4143 (error
4144 (delete-process proc)
4145 (apply 'tramp-error-with-buffer
4146 (tramp-get-connection-buffer vec) vec 'file-error error-args)))))
4148 (defun tramp-open-connection-setup-interactive-shell (proc vec)
4149 "Set up an interactive shell.
4150 Mainly sets the prompt and the echo correctly. PROC is the shell
4151 process to set up. VEC specifies the connection."
4152 (let ((tramp-end-of-output tramp-initial-end-of-output))
4153 (tramp-open-shell vec (tramp-get-method-parameter vec 'tramp-remote-shell))
4155 ;; Disable tab and echo expansion.
4156 (tramp-message vec 5 "Setting up remote shell environment")
4157 (tramp-send-command
4158 vec "stty tab0 -inlcr -onlcr -echo kill '^U' erase '^H'" t)
4159 ;; Check whether the echo has really been disabled. Some
4160 ;; implementations, like busybox of embedded GNU/Linux, don't
4161 ;; support disabling.
4162 (tramp-send-command vec "echo foo" t)
4163 (with-current-buffer (process-buffer proc)
4164 (goto-char (point-min))
4165 (when (looking-at "echo foo")
4166 (tramp-set-connection-property proc "remote-echo" t)
4167 (tramp-message vec 5 "Remote echo still on. Ok.")
4168 ;; Make sure backspaces and their echo are enabled and no line
4169 ;; width magic interferes with them.
4170 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
4172 (tramp-message vec 5 "Setting shell prompt")
4173 (tramp-send-command
4174 vec (format "PS1=%s PS2='' PS3='' PROMPT_COMMAND=''"
4175 (tramp-shell-quote-argument tramp-end-of-output)) t)
4177 ;; Try to set up the coding system correctly.
4178 ;; CCC this can't be the right way to do it. Hm.
4179 (tramp-message vec 5 "Determining coding system")
4180 (with-current-buffer (process-buffer proc)
4181 (if (featurep 'mule)
4182 ;; Use MULE to select the right EOL convention for communicating
4183 ;; with the process.
4184 (let ((cs (or (and (memq 'utf-8 (coding-system-list))
4185 (string-match "utf8" (tramp-get-remote-locale vec))
4186 (cons 'utf-8 'utf-8))
4187 (tramp-compat-funcall 'process-coding-system proc)
4188 (cons 'undecided 'undecided)))
4189 cs-decode cs-encode)
4190 (when (symbolp cs) (setq cs (cons cs cs)))
4191 (setq cs-decode (car cs))
4192 (setq cs-encode (cdr cs))
4193 (unless cs-decode (setq cs-decode 'undecided))
4194 (unless cs-encode (setq cs-encode 'undecided))
4195 (setq cs-encode (tramp-compat-coding-system-change-eol-conversion
4196 cs-encode 'unix))
4197 (tramp-send-command vec "echo foo ; echo bar" t)
4198 (goto-char (point-min))
4199 (when (search-forward "\r" nil t)
4200 (setq cs-decode (tramp-compat-coding-system-change-eol-conversion
4201 cs-decode 'dos)))
4202 (tramp-compat-funcall
4203 'set-buffer-process-coding-system cs-decode cs-encode)
4204 (tramp-message
4205 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
4206 ;; Look for ^M and do something useful if found.
4207 (when (search-forward "\r" nil t)
4208 ;; We have found a ^M but cannot frob the process coding system
4209 ;; because we're running on a non-MULE Emacs. Let's try
4210 ;; stty, instead.
4211 (tramp-send-command vec "stty -onlcr" t))))
4213 (tramp-send-command vec "set +o vi +o emacs" t)
4215 ;; Check whether the output of "uname -sr" has been changed. If
4216 ;; yes, this is a strong indication that we must expire all
4217 ;; connection properties. We start again with
4218 ;; `tramp-maybe-open-connection', it will be caught there.
4219 (tramp-message vec 5 "Checking system information")
4220 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
4221 (new-uname
4222 (tramp-set-connection-property
4223 vec "uname"
4224 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
4225 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
4226 (tramp-message
4227 vec 3
4228 "Connection reset, because remote host changed from `%s' to `%s'"
4229 old-uname new-uname)
4230 ;; We want to keep the password.
4231 (tramp-cleanup-connection vec t t)
4232 (throw 'uname-changed (tramp-maybe-open-connection vec))))
4234 ;; Check whether the remote host suffers from buggy
4235 ;; `send-process-string'. This is known for FreeBSD (see comment in
4236 ;; `send_process', file process.c). I've tested sending 624 bytes
4237 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
4238 ;; this host type is detected locally. It cannot handle remote
4239 ;; hosts, though.
4240 (with-tramp-connection-property proc "chunksize"
4241 (cond
4242 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
4243 tramp-chunksize)
4245 (tramp-message
4246 vec 5 "Checking remote host type for `send-process-string' bug")
4247 (if (string-match
4248 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
4249 500 0))))
4251 ;; Set remote PATH variable.
4252 (tramp-set-remote-path vec)
4254 ;; Search for a good shell before searching for a command which
4255 ;; checks if a file exists. This is done because Tramp wants to use
4256 ;; "test foo; echo $?" to check if various conditions hold, and
4257 ;; there are buggy /bin/sh implementations which don't execute the
4258 ;; "echo $?" part if the "test" part has an error. In particular,
4259 ;; the OpenSolaris /bin/sh is a problem. There are also other
4260 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
4261 ;; in function declarations, or changing HISTFILE in place.
4262 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
4263 ;; detected.
4264 (tramp-find-shell vec)
4266 ;; Disable unexpected output.
4267 (tramp-send-command vec "mesg n; biff n" t)
4269 ;; IRIX64 bash expands "!" even when in single quotes. This
4270 ;; destroys our shell functions, we must disable it. See
4271 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
4272 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
4273 (tramp-send-command vec "set +H" t))
4275 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
4276 (when (string-match "BSD\\|Darwin"
4277 (tramp-get-connection-property vec "uname" ""))
4278 (tramp-send-command vec "stty -oxtabs" t))
4280 ;; Set `remote-tty' process property.
4281 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
4282 (unless (zerop (length tty))
4283 (tramp-compat-process-put proc 'remote-tty tty)))
4285 ;; Dump stty settings in the traces.
4286 (when (>= tramp-verbose 9)
4287 (tramp-send-command vec "stty -a" t))
4289 ;; Set the environment.
4290 (tramp-message vec 5 "Setting default environment")
4292 (let ((env (append `(,(tramp-get-remote-locale vec))
4293 (copy-sequence tramp-remote-process-environment)))
4294 unset vars item)
4295 (while env
4296 (setq item (tramp-compat-split-string (car env) "="))
4297 (setcdr item (mapconcat 'identity (cdr item) "="))
4298 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
4299 (push (format "%s %s" (car item) (cdr item)) vars)
4300 (push (car item) unset))
4301 (setq env (cdr env)))
4302 (when vars
4303 (tramp-send-command
4305 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
4306 tramp-end-of-heredoc
4307 (mapconcat 'identity vars "\n")
4308 tramp-end-of-heredoc)
4310 (when unset
4311 (tramp-send-command
4312 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
4314 ;; Old text from documentation of tramp-methods:
4315 ;; Using a uuencode/uudecode inline method is discouraged, please use one
4316 ;; of the base64 methods instead since base64 encoding is much more
4317 ;; reliable and the commands are more standardized between the different
4318 ;; Unix versions. But if you can't use base64 for some reason, please
4319 ;; note that the default uudecode command does not work well for some
4320 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
4321 ;; the following command for uudecode:
4323 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
4325 ;; For Irix, no solution is known yet.
4327 (autoload 'uudecode-decode-region "uudecode")
4329 (defconst tramp-local-coding-commands
4330 `((b64 base64-encode-region base64-decode-region)
4331 (uu tramp-uuencode-region uudecode-decode-region)
4332 (pack ,(format tramp-perl-pack "perl") ,(format tramp-perl-unpack "perl")))
4333 "List of local coding commands for inline transfer.
4334 Each item is a list that looks like this:
4336 \(FORMAT ENCODING DECODING)
4338 FORMAT is symbol describing the encoding/decoding format. It can be
4339 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4341 ENCODING and DECODING can be strings, giving commands, or symbols,
4342 giving functions. If they are strings, then they can contain
4343 the \"%s\" format specifier. If that specifier is present, the input
4344 file name will be put into the command line at that spot. If the
4345 specifier is not present, the input should be read from standard
4346 input.
4348 If they are functions, they will be called with two arguments, start
4349 and end of region, and are expected to replace the region contents
4350 with the encoded or decoded results, respectively.")
4352 (defconst tramp-remote-coding-commands
4353 `((b64 "base64" "base64 -d -i")
4354 ;; "-i" is more robust with older base64 from GNU coreutils.
4355 ;; However, I don't know whether all base64 versions do supports
4356 ;; this option.
4357 (b64 "base64" "base64 -d")
4358 (b64 "openssl enc -base64" "openssl enc -d -base64")
4359 (b64 "mimencode -b" "mimencode -u -b")
4360 (b64 "mmencode -b" "mmencode -u -b")
4361 (b64 "recode data..base64" "recode base64..data")
4362 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
4363 (b64 tramp-perl-encode tramp-perl-decode)
4364 ;; This is painful slow, so we put it on the end.
4365 (b64 tramp-awk-encode tramp-awk-decode ,tramp-awk-coding-test)
4366 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
4367 (uu "uuencode xxx" "uudecode -o -")
4368 (uu "uuencode xxx" "uudecode -p")
4369 (uu "uuencode xxx" tramp-uudecode)
4370 (pack tramp-perl-pack tramp-perl-unpack))
4371 "List of remote coding commands for inline transfer.
4372 Each item is a list that looks like this:
4374 \(FORMAT ENCODING DECODING [TEST])
4376 FORMAT is a symbol describing the encoding/decoding format. It can be
4377 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4379 ENCODING and DECODING can be strings, giving commands, or symbols,
4380 giving variables. If they are strings, then they can contain
4381 the \"%s\" format specifier. If that specifier is present, the input
4382 file name will be put into the command line at that spot. If the
4383 specifier is not present, the input should be read from standard
4384 input.
4386 If they are variables, this variable is a string containing a
4387 Perl or Shell implementation for this functionality. This
4388 program will be transferred to the remote host, and it is
4389 available as shell function with the same name. A \"%t\" format
4390 specifier in the variable value denotes a temporary file.
4392 The optional TEST command can be used for further tests, whether
4393 ENCODING and DECODING are applicable.")
4395 (defun tramp-find-inline-encoding (vec)
4396 "Find an inline transfer encoding that works.
4397 Goes through the list `tramp-local-coding-commands' and
4398 `tramp-remote-coding-commands'."
4399 (save-excursion
4400 (let ((local-commands tramp-local-coding-commands)
4401 (magic "xyzzy")
4402 (p (tramp-get-connection-process vec))
4403 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4404 (while (and local-commands (not found))
4405 (setq litem (pop local-commands))
4406 (catch 'wont-work-local
4407 (let ((format (nth 0 litem))
4408 (remote-commands tramp-remote-coding-commands))
4409 (setq loc-enc (nth 1 litem))
4410 (setq loc-dec (nth 2 litem))
4411 ;; If the local encoder or decoder is a string, the
4412 ;; corresponding command has to work locally.
4413 (if (not (stringp loc-enc))
4414 (tramp-message
4415 vec 5 "Checking local encoding function `%s'" loc-enc)
4416 (tramp-message
4417 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4418 (unless (zerop (tramp-call-local-coding-command
4419 loc-enc nil nil))
4420 (throw 'wont-work-local nil)))
4421 (if (not (stringp loc-dec))
4422 (tramp-message
4423 vec 5 "Checking local decoding function `%s'" loc-dec)
4424 (tramp-message
4425 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4426 (unless (zerop (tramp-call-local-coding-command
4427 loc-dec nil nil))
4428 (throw 'wont-work-local nil)))
4429 ;; Search for remote coding commands with the same format
4430 (while (and remote-commands (not found))
4431 (setq ritem (pop remote-commands))
4432 (catch 'wont-work-remote
4433 (when (equal format (nth 0 ritem))
4434 (setq rem-enc (nth 1 ritem))
4435 (setq rem-dec (nth 2 ritem))
4436 (setq rem-test (nth 3 ritem))
4437 ;; Check the remote test command if exists.
4438 (when (stringp rem-test)
4439 (tramp-message
4440 vec 5 "Checking remote test command `%s'" rem-test)
4441 (unless (tramp-send-command-and-check vec rem-test t)
4442 (throw 'wont-work-remote nil)))
4443 ;; Check if remote perl exists when necessary.
4444 (when (and (symbolp rem-enc)
4445 (string-match "perl" (symbol-name rem-enc))
4446 (not (tramp-get-remote-perl vec)))
4447 (throw 'wont-work-remote nil))
4448 ;; Check if remote encoding and decoding commands can be
4449 ;; called remotely with null input and output. This makes
4450 ;; sure there are no syntax errors and the command is really
4451 ;; found. Note that we do not redirect stdout to /dev/null,
4452 ;; for two reasons: when checking the decoding command, we
4453 ;; actually check the output it gives. And also, when
4454 ;; redirecting "mimencode" output to /dev/null, then as root
4455 ;; it might change the permissions of /dev/null!
4456 (when (not (stringp rem-enc))
4457 (let ((name (symbol-name rem-enc)))
4458 (while (string-match (regexp-quote "-") name)
4459 (setq name (replace-match "_" nil t name)))
4460 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4461 (setq rem-enc name)))
4462 (tramp-message
4463 vec 5
4464 "Checking remote encoding command `%s' for sanity" rem-enc)
4465 (unless (tramp-send-command-and-check
4466 vec (format "%s </dev/null" rem-enc) t)
4467 (throw 'wont-work-remote nil))
4469 (when (not (stringp rem-dec))
4470 (let ((name (symbol-name rem-dec))
4471 (value (symbol-value rem-dec))
4472 tmpfile)
4473 (while (string-match (regexp-quote "-") name)
4474 (setq name (replace-match "_" nil t name)))
4475 (when (string-match "\\(^\\|[^%]\\)%t" value)
4476 (setq tmpfile
4477 (make-temp-name
4478 (expand-file-name
4479 tramp-temp-name-prefix
4480 (tramp-get-remote-tmpdir vec)))
4481 value
4482 (format-spec
4483 value
4484 (format-spec-make
4486 (tramp-file-name-handler
4487 'file-remote-p tmpfile 'localname)))))
4488 (tramp-maybe-send-script vec value name)
4489 (setq rem-dec name)))
4490 (tramp-message
4491 vec 5
4492 "Checking remote decoding command `%s' for sanity" rem-dec)
4493 (unless (tramp-send-command-and-check
4495 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4497 (throw 'wont-work-remote nil))
4499 (with-current-buffer (tramp-get-buffer vec)
4500 (goto-char (point-min))
4501 (unless (looking-at (regexp-quote magic))
4502 (throw 'wont-work-remote nil)))
4504 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4505 (setq rem-enc (nth 1 ritem))
4506 (setq rem-dec (nth 2 ritem))
4507 (setq found t)))))))
4509 (when found
4510 ;; Set connection properties. Since the commands are risky
4511 ;; (due to output direction), we cache them in the process cache.
4512 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4513 (tramp-set-connection-property p "local-encoding" loc-enc)
4514 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4515 (tramp-set-connection-property p "local-decoding" loc-dec)
4516 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4517 (tramp-set-connection-property p "remote-encoding" rem-enc)
4518 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4519 (tramp-set-connection-property p "remote-decoding" rem-dec)))))
4521 (defun tramp-call-local-coding-command (cmd input output)
4522 "Call the local encoding or decoding command.
4523 If CMD contains \"%s\", provide input file INPUT there in command.
4524 Otherwise, INPUT is passed via standard input.
4525 INPUT can also be nil which means `/dev/null'.
4526 OUTPUT can be a string (which specifies a file name), or t (which
4527 means standard output and thus the current buffer), or nil (which
4528 means discard it)."
4529 (tramp-call-process
4530 nil tramp-encoding-shell
4531 (when (and input (not (string-match "%s" cmd))) input)
4532 (if (eq output t) t nil)
4534 tramp-encoding-command-switch
4535 (concat
4536 (if (string-match "%s" cmd) (format cmd input) cmd)
4537 (if (stringp output) (concat " >" output) ""))))
4539 (defconst tramp-inline-compress-commands
4540 '(("gzip" "gzip -d")
4541 ("bzip2" "bzip2 -d")
4542 ("xz" "xz -d")
4543 ("compress" "compress -d"))
4544 "List of compress and decompress commands for inline transfer.
4545 Each item is a list that looks like this:
4547 \(COMPRESS DECOMPRESS)
4549 COMPRESS or DECOMPRESS are strings with the respective commands.")
4551 (defun tramp-find-inline-compress (vec)
4552 "Find an inline transfer compress command that works.
4553 Goes through the list `tramp-inline-compress-commands'."
4554 (save-excursion
4555 (let ((commands tramp-inline-compress-commands)
4556 (magic "xyzzy")
4557 (p (tramp-get-connection-process vec))
4558 item compress decompress found)
4559 (while (and commands (not found))
4560 (catch 'next
4561 (setq item (pop commands)
4562 compress (nth 0 item)
4563 decompress (nth 1 item))
4564 (tramp-message
4565 vec 5
4566 "Checking local compress commands `%s', `%s' for sanity"
4567 compress decompress)
4568 (unless
4569 (zerop
4570 (tramp-call-local-coding-command
4571 (format
4572 ;; Windows shells need the program file name after
4573 ;; the pipe symbol be quoted if they use forward
4574 ;; slashes as directory separators.
4575 (if (memq system-type '(windows-nt))
4576 "echo %s | \"%s\" | \"%s\""
4577 "echo %s | %s | %s")
4578 magic compress decompress) nil nil))
4579 (throw 'next nil))
4580 (tramp-message
4581 vec 5
4582 "Checking remote compress commands `%s', `%s' for sanity"
4583 compress decompress)
4584 (unless (tramp-send-command-and-check
4585 vec (format "echo %s | %s | %s" magic compress decompress) t)
4586 (throw 'next nil))
4587 (setq found t)))
4589 ;; Did we find something?
4590 (if found
4591 (progn
4592 ;; Set connection properties. Since the commands are
4593 ;; risky (due to output direction), we cache them in the
4594 ;; process cache.
4595 (tramp-message
4596 vec 5 "Using inline transfer compress command `%s'" compress)
4597 (tramp-set-connection-property p "inline-compress" compress)
4598 (tramp-message
4599 vec 5 "Using inline transfer decompress command `%s'" decompress)
4600 (tramp-set-connection-property p "inline-decompress" decompress))
4602 (tramp-set-connection-property p "inline-compress" nil)
4603 (tramp-set-connection-property p "inline-decompress" nil)
4604 (tramp-message
4605 vec 2 "Couldn't find an inline transfer compress command")))))
4607 (defun tramp-compute-multi-hops (vec)
4608 "Expands VEC according to `tramp-default-proxies-alist'.
4609 Gateway hops are already opened."
4610 (let ((target-alist `(,vec))
4611 (hops (or (tramp-file-name-hop vec) ""))
4612 (item vec)
4613 choices proxy)
4615 ;; Ad-hoc proxy definitions.
4616 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4617 (let ((user (tramp-file-name-user item))
4618 (host (tramp-file-name-host item))
4619 (proxy (concat
4620 tramp-prefix-format proxy tramp-postfix-host-format)))
4621 (tramp-message
4622 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4623 (and (stringp host) (regexp-quote host))
4624 (and (stringp user) (regexp-quote user))
4625 proxy)
4626 ;; Add the hop.
4627 (add-to-list
4628 'tramp-default-proxies-alist
4629 (list (and (stringp host) (regexp-quote host))
4630 (and (stringp user) (regexp-quote user))
4631 proxy))
4632 (setq item (tramp-dissect-file-name proxy))))
4633 ;; Save the new value.
4634 (when (and hops tramp-save-ad-hoc-proxies)
4635 (customize-save-variable
4636 'tramp-default-proxies-alist tramp-default-proxies-alist))
4638 ;; Look for proxy hosts to be passed.
4639 (setq choices tramp-default-proxies-alist)
4640 (while choices
4641 (setq item (pop choices)
4642 proxy (eval (nth 2 item)))
4643 (when (and
4644 ;; Host.
4645 (string-match (or (eval (nth 0 item)) "")
4646 (or (tramp-file-name-host (car target-alist)) ""))
4647 ;; User.
4648 (string-match (or (eval (nth 1 item)) "")
4649 (or (tramp-file-name-user (car target-alist)) "")))
4650 (if (null proxy)
4651 ;; No more hops needed.
4652 (setq choices nil)
4653 ;; Replace placeholders.
4654 (setq proxy
4655 (format-spec
4656 proxy
4657 (format-spec-make
4658 ?u (or (tramp-file-name-user (car target-alist)) "")
4659 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4660 (with-parsed-tramp-file-name proxy l
4661 ;; Add the hop.
4662 (push l target-alist)
4663 ;; Start next search.
4664 (setq choices tramp-default-proxies-alist)))))
4666 ;; Handle gateways.
4667 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4668 (string-match
4669 (format
4670 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4671 (tramp-file-name-method (car target-alist))))
4672 (let ((gw (pop target-alist))
4673 (hop (pop target-alist)))
4674 ;; Is the method prepared for gateways?
4675 (unless (tramp-file-name-port hop)
4676 (tramp-error
4677 vec 'file-error
4678 "Connection `%s' is not supported for gateway access." hop))
4679 ;; Open the gateway connection.
4680 (push
4681 (vector
4682 (tramp-file-name-method hop) (tramp-file-name-user hop)
4683 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil nil)
4684 target-alist)
4685 ;; For the password prompt, we need the correct values.
4686 ;; Therefore, we must remember the gateway vector. But we
4687 ;; cannot do it as connection property, because it shouldn't
4688 ;; be persistent. And we have no started process yet either.
4689 (let ((tramp-verbose 0))
4690 (tramp-set-file-property (car target-alist) "" "gateway" hop))))
4692 ;; Foreign and out-of-band methods are not supported for multi-hops.
4693 (when (cdr target-alist)
4694 (setq choices target-alist)
4695 (while (setq item (pop choices))
4696 (when (or (not (tramp-get-method-parameter item 'tramp-login-program))
4697 (tramp-get-method-parameter item 'tramp-copy-program))
4698 (tramp-error
4699 vec 'file-error
4700 "Method `%s' is not supported for multi-hops."
4701 (tramp-file-name-method item)))))
4703 ;; In case the host name is not used for the remote shell
4704 ;; command, the user could be misguided by applying a random
4705 ;; host name.
4706 (let* ((v (car target-alist))
4707 (method (tramp-file-name-method v))
4708 (host (tramp-file-name-host v)))
4709 (unless
4711 ;; There are multi-hops.
4712 (cdr target-alist)
4713 ;; The host name is used for the remote shell command.
4714 (member '("%h") (tramp-get-method-parameter v 'tramp-login-args))
4715 ;; The host is local. We cannot use `tramp-local-host-p'
4716 ;; here, because it opens a connection as well.
4717 (string-match tramp-local-host-regexp host))
4718 (tramp-error
4719 v 'file-error
4720 "Host `%s' looks like a remote host, `%s' can only use the local host"
4721 host method)))
4723 ;; Result.
4724 target-alist))
4726 (defun tramp-ssh-controlmaster-options (vec)
4727 "Return the Control* arguments of the local ssh."
4728 (cond
4729 ;; No options to be computed.
4730 ((or (null tramp-use-ssh-controlmaster-options)
4731 (null (assoc "%c" (tramp-get-method-parameter vec 'tramp-login-args))))
4734 ;; There is already a value to be used.
4735 ((stringp tramp-ssh-controlmaster-options) tramp-ssh-controlmaster-options)
4737 ;; Determine the options.
4738 (t (setq tramp-ssh-controlmaster-options "")
4739 (let ((case-fold-search t))
4740 (ignore-errors
4741 (when (executable-find "ssh")
4742 (with-temp-buffer
4743 (tramp-call-process vec "ssh" nil t nil "-o" "ControlMaster")
4744 (goto-char (point-min))
4745 (when (search-forward-regexp "missing.+argument" nil t)
4746 (setq tramp-ssh-controlmaster-options "-o ControlMaster=auto")))
4747 (unless (zerop (length tramp-ssh-controlmaster-options))
4748 (with-temp-buffer
4749 ;; We use a non-existing IP address, in order to avoid
4750 ;; useless connections, and DNS timeouts.
4751 (tramp-call-process
4752 vec "ssh" nil t nil "-o" "ControlPath=%C" "0.0.0.1")
4753 (goto-char (point-min))
4754 (setq tramp-ssh-controlmaster-options
4755 (concat tramp-ssh-controlmaster-options
4756 (if (search-forward-regexp "unknown.+key" nil t)
4757 " -o ControlPath='tramp.%%r@%%h:%%p'"
4758 " -o ControlPath='tramp.%%C'"))))
4759 (with-temp-buffer
4760 (tramp-call-process vec "ssh" nil t nil "-o" "ControlPersist")
4761 (goto-char (point-min))
4762 (when (search-forward-regexp "missing.+argument" nil t)
4763 (setq tramp-ssh-controlmaster-options
4764 (concat tramp-ssh-controlmaster-options
4765 " -o ControlPersist=no"))))))))
4766 tramp-ssh-controlmaster-options)))
4768 (defun tramp-maybe-open-connection (vec)
4769 "Maybe open a connection VEC.
4770 Does not do anything if a connection is already open, but re-opens the
4771 connection if a previous connection has died for some reason."
4772 (tramp-check-proper-method-and-host vec)
4774 (let ((p (tramp-get-connection-process vec))
4775 (process-name (tramp-get-connection-property vec "process-name" nil))
4776 (process-environment (copy-sequence process-environment))
4777 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4779 ;; If Tramp opens the same connection within a short time frame,
4780 ;; there is a problem. We shall signal this.
4781 (unless (or (and p (processp p) (memq (process-status p) '(run open)))
4782 (not (equal (butlast (append vec nil) 2)
4783 (car tramp-current-connection)))
4784 (> (tramp-time-diff
4785 (current-time) (cdr tramp-current-connection))
4786 (or tramp-connection-min-time-diff 0)))
4787 (throw 'suppress 'suppress))
4789 ;; If too much time has passed since last command was sent, look
4790 ;; whether process is still alive. If it isn't, kill it. When
4791 ;; using ssh, it can sometimes happen that the remote end has hung
4792 ;; up but the local ssh client doesn't recognize this until it
4793 ;; tries to send some data to the remote end. So that's why we
4794 ;; try to send a command from time to time, then look again
4795 ;; whether the process is really alive.
4796 (condition-case nil
4797 (when (and (> (tramp-time-diff
4798 (current-time)
4799 (tramp-get-connection-property
4800 p "last-cmd-time" '(0 0 0)))
4802 p (processp p) (memq (process-status p) '(run open)))
4803 (tramp-send-command vec "echo are you awake" t t)
4804 (unless (and (memq (process-status p) '(run open))
4805 (tramp-wait-for-output p 10))
4806 ;; The error will be caught locally.
4807 (tramp-error vec 'file-error "Awake did fail")))
4808 (file-error
4809 (tramp-cleanup-connection vec t)
4810 (setq p nil)))
4812 ;; New connection must be opened.
4813 (condition-case err
4814 (unless (and p (processp p) (memq (process-status p) '(run open)))
4816 ;; If `non-essential' is non-nil, don't reopen a new connection.
4817 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4818 (throw 'non-essential 'non-essential))
4820 (with-tramp-progress-reporter
4821 vec 3
4822 (if (zerop (length (tramp-file-name-user vec)))
4823 (format "Opening connection for %s using %s"
4824 (tramp-file-name-host vec)
4825 (tramp-file-name-method vec))
4826 (format "Opening connection for %s@%s using %s"
4827 (tramp-file-name-user vec)
4828 (tramp-file-name-host vec)
4829 (tramp-file-name-method vec)))
4831 (catch 'uname-changed
4832 ;; Start new process.
4833 (when (and p (processp p))
4834 (delete-process p))
4835 (setenv "TERM" tramp-terminal-type)
4836 (setenv "LC_ALL" "en_US.utf8")
4837 (if (stringp tramp-histfile-override)
4838 (setenv "HISTFILE" tramp-histfile-override)
4839 (if tramp-histfile-override
4840 (progn
4841 (setenv "HISTFILE")
4842 (setenv "HISTFILESIZE" "0")
4843 (setenv "HISTSIZE" "0"))))
4844 (setenv "PROMPT_COMMAND")
4845 (setenv "PS1" tramp-initial-end-of-output)
4846 (let* ((target-alist (tramp-compute-multi-hops vec))
4847 ;; We will apply `tramp-ssh-controlmaster-options'
4848 ;; only for the first hop.
4849 (options (tramp-ssh-controlmaster-options vec))
4850 (process-connection-type tramp-process-connection-type)
4851 (process-adaptive-read-buffering nil)
4852 (coding-system-for-read nil)
4853 ;; This must be done in order to avoid our file
4854 ;; name handler.
4855 (p (let ((default-directory
4856 (tramp-compat-temporary-file-directory)))
4857 (apply
4858 'start-process
4859 (tramp-get-connection-name vec)
4860 (tramp-get-connection-buffer vec)
4861 (if tramp-encoding-command-interactive
4862 (list tramp-encoding-shell
4863 tramp-encoding-command-interactive)
4864 (list tramp-encoding-shell))))))
4866 ;; Set sentinel and query flag.
4867 (tramp-set-connection-property p "vector" vec)
4868 (set-process-sentinel p 'tramp-process-sentinel)
4869 (tramp-compat-set-process-query-on-exit-flag p nil)
4870 (setq tramp-current-connection
4871 (cons (butlast (append vec nil) 2) (current-time))
4872 tramp-current-host (system-name))
4874 (tramp-message
4875 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4877 ;; Check whether process is alive.
4878 (tramp-barf-if-no-shell-prompt
4879 p 10
4880 "Couldn't find local shell prompt for %s" tramp-encoding-shell)
4882 ;; Now do all the connections as specified.
4883 (while target-alist
4884 (let* ((hop (car target-alist))
4885 (l-method (tramp-file-name-method hop))
4886 (l-user (tramp-file-name-user hop))
4887 (l-host (tramp-file-name-host hop))
4888 (l-port nil)
4889 (login-program
4890 (tramp-get-method-parameter hop 'tramp-login-program))
4891 (login-args
4892 (tramp-get-method-parameter hop 'tramp-login-args))
4893 (login-env
4894 (tramp-get-method-parameter hop 'tramp-login-env))
4895 (async-args
4896 (tramp-get-method-parameter hop 'tramp-async-args))
4897 (connection-timeout
4898 (tramp-get-method-parameter
4899 hop 'tramp-connection-timeout))
4900 (gw-args
4901 (tramp-get-method-parameter hop 'tramp-gw-args))
4902 (gw (let ((tramp-verbose 0))
4903 (tramp-get-file-property hop "" "gateway" nil)))
4904 (g-method (and gw (tramp-file-name-method gw)))
4905 (g-user (and gw (tramp-file-name-user gw)))
4906 (g-host (and gw (tramp-file-name-real-host gw)))
4907 (command login-program)
4908 ;; We don't create the temporary file. In
4909 ;; fact, it is just a prefix for the
4910 ;; ControlPath option of ssh; the real
4911 ;; temporary file has another name, and it is
4912 ;; created and protected by ssh. It is also
4913 ;; removed by ssh when the connection is
4914 ;; closed. The temporary file name is cached
4915 ;; in the main connection process, therefore
4916 ;; we cannot use `tramp-get-connection-process'.
4917 (tmpfile
4918 (with-tramp-connection-property
4919 (get-process (tramp-buffer-name vec)) "temp-file"
4920 (make-temp-name
4921 (expand-file-name
4922 tramp-temp-name-prefix
4923 (tramp-compat-temporary-file-directory)))))
4924 spec r-shell)
4926 ;; Add arguments for asynchronous processes.
4927 (when (and process-name async-args)
4928 (setq login-args (append async-args login-args)))
4930 ;; Add gateway arguments if necessary.
4931 (when gw
4932 (tramp-set-connection-property p "gateway" t)
4933 (when gw-args
4934 (setq login-args (append gw-args login-args))))
4936 ;; Check for port number. Until now, there's no
4937 ;; need for handling like method, user, host.
4938 (when (string-match tramp-host-with-port-regexp l-host)
4939 (setq l-port (match-string 2 l-host)
4940 l-host (match-string 1 l-host)))
4942 ;; Check, whether there is a restricted shell.
4943 (dolist (elt tramp-restricted-shell-hosts-alist)
4944 (when (string-match elt tramp-current-host)
4945 (setq r-shell t)))
4947 ;; Set variables for computing the prompt for
4948 ;; reading password. They can also be derived
4949 ;; from a gateway.
4950 (setq tramp-current-method (or g-method l-method)
4951 tramp-current-user (or g-user l-user)
4952 tramp-current-host (or g-host l-host))
4954 ;; Add login environment.
4955 (when login-env
4956 (setq
4957 login-env
4958 (mapcar
4959 (lambda (x)
4960 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4961 (unless (member "" x) (mapconcat 'identity x " ")))
4962 login-env))
4963 (while login-env
4964 (setq command
4965 (format
4966 "%s=%s %s"
4967 (pop login-env)
4968 (tramp-shell-quote-argument (pop login-env))
4969 command)))
4970 (setq command (concat "env " command)))
4972 ;; Replace `login-args' place holders.
4973 (setq
4974 l-host (or l-host "")
4975 l-user (or l-user "")
4976 l-port (or l-port "")
4977 spec (format-spec-make ?t tmpfile)
4978 options (format-spec options spec)
4979 spec (format-spec-make
4980 ?h l-host ?u l-user ?p l-port ?c options)
4981 command
4982 (concat
4983 ;; We do not want to see the trailing local
4984 ;; prompt in `start-file-process'.
4985 (unless r-shell "exec ")
4986 command " "
4987 (mapconcat
4988 (lambda (x)
4989 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4990 (unless (member "" x) (mapconcat 'identity x " ")))
4991 login-args " ")
4992 ;; Local shell could be a Windows COMSPEC. It
4993 ;; doesn't know the ";" syntax, but we must exit
4994 ;; always for `start-file-process'. It could
4995 ;; also be a restricted shell, which does not
4996 ;; allow "exec".
4997 (when r-shell " && exit || exit")))
4999 ;; Send the command.
5000 (tramp-message vec 3 "Sending command `%s'" command)
5001 (tramp-send-command vec command t t)
5002 (tramp-process-actions
5003 p vec pos tramp-actions-before-shell
5004 (or connection-timeout tramp-connection-timeout))
5005 (tramp-message
5006 vec 3 "Found remote shell prompt on `%s'" l-host))
5007 ;; Next hop.
5008 (setq options ""
5009 target-alist (cdr target-alist)))
5011 ;; Make initial shell settings.
5012 (tramp-open-connection-setup-interactive-shell p vec)))))
5014 ;; When the user did interrupt, we must cleanup.
5015 (quit
5016 (tramp-cleanup-connection vec t)
5017 ;; Propagate the quit signal.
5018 (signal (car err) (cdr err))))))
5020 (defun tramp-send-command (vec command &optional neveropen nooutput)
5021 "Send the COMMAND to connection VEC.
5022 Erases temporary buffer before sending the command. If optional
5023 arg NEVEROPEN is non-nil, never try to open the connection. This
5024 is meant to be used from `tramp-maybe-open-connection' only. The
5025 function waits for output unless NOOUTPUT is set."
5026 (unless neveropen (tramp-maybe-open-connection vec))
5027 (let ((p (tramp-get-connection-process vec)))
5028 (when (tramp-get-connection-property p "remote-echo" nil)
5029 ;; We mark the command string that it can be erased in the output buffer.
5030 (tramp-set-connection-property p "check-remote-echo" t)
5031 ;; If we put `tramp-echo-mark' after a trailing newline (which
5032 ;; is assumed to be unquoted) `tramp-send-string' doesn't see
5033 ;; that newline and adds `tramp-rsh-end-of-line' right after
5034 ;; `tramp-echo-mark', so the remote shell sees two consecutive
5035 ;; trailing line endings and sends two prompts after executing
5036 ;; the command, which confuses `tramp-wait-for-output'.
5037 (when (and (not (string= command ""))
5038 (string-equal (substring command -1) "\n"))
5039 (setq command (substring command 0 -1)))
5040 ;; No need to restore a trailing newline here since `tramp-send-string'
5041 ;; makes sure that the string ends in `tramp-rsh-end-of-line', anyway.
5042 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
5043 ;; Send the command.
5044 (tramp-message vec 6 "%s" command)
5045 (tramp-send-string vec command)
5046 (unless nooutput (tramp-wait-for-output p))))
5048 (defun tramp-wait-for-output (proc &optional timeout)
5049 "Wait for output from remote command."
5050 (unless (buffer-live-p (process-buffer proc))
5051 (delete-process proc)
5052 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
5053 (with-current-buffer (process-buffer proc)
5054 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
5055 ;; be leading escape sequences, which must be ignored.
5056 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
5057 ;; Sometimes, the commands do not return a newline but a
5058 ;; null byte before the shell prompt, for example "git
5059 ;; ls-files -c -z ...".
5060 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
5061 (found (tramp-wait-for-regexp proc timeout regexp1)))
5062 (if found
5063 (let (buffer-read-only)
5064 ;; A simple-minded busybox has sent " ^H" sequences.
5065 ;; Delete them.
5066 (goto-char (point-min))
5067 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
5068 (forward-line 1)
5069 (delete-region (point-min) (point)))
5070 ;; Delete the prompt.
5071 (goto-char (point-max))
5072 (re-search-backward regexp nil t)
5073 (delete-region (point) (point-max)))
5074 (if timeout
5075 (tramp-error
5076 proc 'file-error
5077 "[[Remote prompt `%s' not found in %d secs]]"
5078 tramp-end-of-output timeout)
5079 (tramp-error
5080 proc 'file-error
5081 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
5082 ;; Return value is whether end-of-output sentinel was found.
5083 found)))
5085 (defun tramp-send-command-and-check
5086 (vec command &optional subshell dont-suppress-err)
5087 "Run COMMAND and check its exit status.
5088 Sends `echo $?' along with the COMMAND for checking the exit status.
5089 If COMMAND is nil, just sends `echo $?'. Returns t if the exit
5090 status is 0, and nil otherwise.
5092 If the optional argument SUBSHELL is non-nil, the command is
5093 executed in a subshell, ie surrounded by parentheses. If
5094 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
5095 (tramp-send-command
5097 (concat (if subshell "( " "")
5098 command
5099 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
5100 "echo tramp_exit_status $?"
5101 (if subshell " )" "")))
5102 (with-current-buffer (tramp-get-connection-buffer vec)
5103 (goto-char (point-max))
5104 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
5105 (tramp-error
5106 vec 'file-error "Couldn't find exit status of `%s'" command))
5107 (skip-chars-forward "^ ")
5108 (prog1
5109 (zerop (read (current-buffer)))
5110 (let (buffer-read-only)
5111 (delete-region (match-beginning 0) (point-max))))))
5113 (defun tramp-barf-unless-okay (vec command fmt &rest args)
5114 "Run COMMAND, check exit status, throw error if exit status not okay.
5115 Similar to `tramp-send-command-and-check' but accepts two more arguments
5116 FMT and ARGS which are passed to `error'."
5117 (or (tramp-send-command-and-check vec command)
5118 (apply 'tramp-error vec 'file-error fmt args)))
5120 (defun tramp-send-command-and-read (vec command &optional noerror marker)
5121 "Run COMMAND and return the output, which must be a Lisp expression.
5122 If MARKER is a regexp, read the output after that string.
5123 In case there is no valid Lisp expression and NOERROR is nil, it
5124 raises an error."
5125 (when (if noerror
5126 (tramp-send-command-and-check vec command)
5127 (tramp-barf-unless-okay
5128 vec command "`%s' returns with error" command))
5129 (with-current-buffer (tramp-get-connection-buffer vec)
5130 (goto-char (point-min))
5131 ;; Read the marker.
5132 (when (stringp marker)
5133 (condition-case nil
5134 (re-search-forward marker)
5135 (error (unless noerror
5136 (tramp-error
5137 vec 'file-error
5138 "`%s' does not return the marker `%s': `%s'"
5139 command marker (buffer-string))))))
5140 ;; Read the expression.
5141 (condition-case nil
5142 (prog1 (read (current-buffer))
5143 ;; Error handling.
5144 (when (re-search-forward "\\S-" (point-at-eol) t)
5145 (error nil)))
5146 (error (unless noerror
5147 (tramp-error
5148 vec 'file-error
5149 "`%s' does not return a valid Lisp expression: `%s'"
5150 command (buffer-string))))))))
5152 (defun tramp-convert-file-attributes (vec attr)
5153 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
5154 Convert file mode bits to string and set virtual device number.
5155 Return ATTR."
5156 (when attr
5157 ;; Remove color escape sequences from symlink.
5158 (when (stringp (car attr))
5159 (while (string-match tramp-color-escape-sequence-regexp (car attr))
5160 (setcar attr (replace-match "" nil nil (car attr)))))
5161 ;; Convert uid and gid. Use -1 as indication of unusable value.
5162 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
5163 (setcar (nthcdr 2 attr) -1))
5164 (when (and (floatp (nth 2 attr))
5165 (<= (nth 2 attr) (tramp-compat-most-positive-fixnum)))
5166 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
5167 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
5168 (setcar (nthcdr 3 attr) -1))
5169 (when (and (floatp (nth 3 attr))
5170 (<= (nth 3 attr) (tramp-compat-most-positive-fixnum)))
5171 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
5172 ;; Convert last access time.
5173 (unless (listp (nth 4 attr))
5174 (setcar (nthcdr 4 attr)
5175 (list (floor (nth 4 attr) 65536)
5176 (floor (mod (nth 4 attr) 65536)))))
5177 ;; Convert last modification time.
5178 (unless (listp (nth 5 attr))
5179 (setcar (nthcdr 5 attr)
5180 (list (floor (nth 5 attr) 65536)
5181 (floor (mod (nth 5 attr) 65536)))))
5182 ;; Convert last status change time.
5183 (unless (listp (nth 6 attr))
5184 (setcar (nthcdr 6 attr)
5185 (list (floor (nth 6 attr) 65536)
5186 (floor (mod (nth 6 attr) 65536)))))
5187 ;; Convert file size.
5188 (when (< (nth 7 attr) 0)
5189 (setcar (nthcdr 7 attr) -1))
5190 (when (and (floatp (nth 7 attr))
5191 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
5192 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
5193 ;; Convert file mode bits to string.
5194 (unless (stringp (nth 8 attr))
5195 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
5196 (when (stringp (car attr))
5197 (aset (nth 8 attr) 0 ?l)))
5198 ;; Convert directory indication bit.
5199 (when (string-match "^d" (nth 8 attr))
5200 (setcar attr t))
5201 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
5202 (when (consp (car attr))
5203 (if (and (stringp (caar attr))
5204 (string-match ".+ -> .\\(.+\\)." (caar attr)))
5205 (setcar attr (match-string 1 (caar attr)))
5206 (setcar attr nil)))
5207 ;; Set file's gid change bit.
5208 (setcar (nthcdr 9 attr)
5209 (if (numberp (nth 3 attr))
5210 (not (= (nth 3 attr)
5211 (tramp-get-remote-gid vec 'integer)))
5212 (not (string-equal
5213 (nth 3 attr)
5214 (tramp-get-remote-gid vec 'string)))))
5215 ;; Convert inode.
5216 (unless (listp (nth 10 attr))
5217 (setcar (nthcdr 10 attr)
5218 (condition-case nil
5219 (cons (floor (nth 10 attr) 65536)
5220 (floor (mod (nth 10 attr) 65536)))
5221 ;; Inodes can be incredible huge. We must hide this.
5222 (error (tramp-get-inode vec)))))
5223 ;; Set virtual device number.
5224 (setcar (nthcdr 11 attr)
5225 (tramp-get-device vec))
5226 attr))
5228 (defun tramp-shell-case-fold (string)
5229 "Converts STRING to shell glob pattern which ignores case."
5230 (mapconcat
5231 (lambda (c)
5232 (if (equal (downcase c) (upcase c))
5233 (vector c)
5234 (format "[%c%c]" (downcase c) (upcase c))))
5235 string
5236 ""))
5238 (defun tramp-make-copy-program-file-name (vec)
5239 "Create a file name suitable for `scp', `pscp', or `nc' and workalikes."
5240 (let ((method (tramp-file-name-method vec))
5241 (user (tramp-file-name-user vec))
5242 (host (tramp-file-name-real-host vec))
5243 (localname (tramp-file-name-localname vec)))
5244 (when (string-match tramp-ipv6-regexp host)
5245 (setq host (format "[%s]" host)))
5246 (unless (string-match "ftp$" method)
5247 (setq localname (tramp-shell-quote-argument localname)))
5248 (cond
5249 ((tramp-get-method-parameter vec 'tramp-remote-copy-program)
5250 localname)
5251 ((not (zerop (length user)))
5252 (shell-quote-argument (format "%s@%s:%s" user host localname)))
5253 (t (shell-quote-argument (format "%s:%s" host localname))))))
5255 (defun tramp-method-out-of-band-p (vec size)
5256 "Return t if this is an out-of-band method, nil otherwise."
5257 (and
5258 ;; It shall be an out-of-band method.
5259 (tramp-get-method-parameter vec 'tramp-copy-program)
5260 ;; There must be a size, otherwise the file doesn't exist.
5261 (numberp size)
5262 ;; Either the file size is large enough, or (in rare cases) there
5263 ;; does not exist a remote encoding.
5264 (or (null tramp-copy-size-limit)
5265 (> size tramp-copy-size-limit)
5266 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
5268 ;; Variables local to connection.
5270 (defun tramp-get-remote-path (vec)
5271 (with-tramp-connection-property
5272 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
5273 ;; cache the result for the session only. Otherwise, the result
5274 ;; is cached persistently.
5275 (if (memq 'tramp-own-remote-path tramp-remote-path)
5276 (tramp-get-connection-process vec)
5277 vec)
5278 "remote-path"
5279 (let* ((remote-path (copy-tree tramp-remote-path))
5280 (elt1 (memq 'tramp-default-remote-path remote-path))
5281 (elt2 (memq 'tramp-own-remote-path remote-path))
5282 (default-remote-path
5283 (when elt1
5285 (tramp-send-command-and-read
5286 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
5287 ;; Default if "getconf" is not available.
5288 (progn
5289 (tramp-message
5290 vec 3
5291 "`getconf PATH' not successful, using default value \"%s\"."
5292 "/bin:/usr/bin")
5293 "/bin:/usr/bin"))))
5294 (own-remote-path
5295 ;; The login shell could return more than just the $PATH
5296 ;; string. So we use `tramp-end-of-heredoc' as marker.
5297 (when elt2
5298 (tramp-send-command-and-read
5300 (format
5301 "%s %s %s 'echo %s \\\"$PATH\\\"'"
5302 (tramp-get-method-parameter vec 'tramp-remote-shell)
5303 (mapconcat
5304 'identity
5305 (tramp-get-method-parameter vec 'tramp-remote-shell-login)
5306 " ")
5307 (mapconcat
5308 'identity
5309 (tramp-get-method-parameter vec 'tramp-remote-shell-args)
5310 " ")
5311 (tramp-shell-quote-argument tramp-end-of-heredoc))
5312 nil (regexp-quote tramp-end-of-heredoc)))))
5314 ;; Replace place holder `tramp-default-remote-path'.
5315 (when elt1
5316 (setcdr elt1
5317 (append
5318 (tramp-compat-split-string (or default-remote-path "") ":")
5319 (cdr elt1)))
5320 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
5322 ;; Replace place holder `tramp-own-remote-path'.
5323 (when elt2
5324 (setcdr elt2
5325 (append
5326 (tramp-compat-split-string (or own-remote-path "") ":")
5327 (cdr elt2)))
5328 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
5330 ;; Remove double entries.
5331 (setq elt1 remote-path)
5332 (while (consp elt1)
5333 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
5334 (setcar elt2 nil))
5335 (setq elt1 (cdr elt1)))
5337 ;; Remove non-existing directories.
5338 (delq
5340 (mapcar
5341 (lambda (x)
5342 (and
5343 (stringp x)
5344 (file-directory-p
5345 (tramp-make-tramp-file-name
5346 (tramp-file-name-method vec)
5347 (tramp-file-name-user vec)
5348 (tramp-file-name-host vec)
5351 remote-path)))))
5353 (defun tramp-get-remote-locale (vec)
5354 (with-tramp-connection-property vec "locale"
5355 (tramp-send-command vec "locale -a")
5356 (let ((candidates '("en_US.utf8" "C.utf8"))
5357 locale)
5358 (with-current-buffer (tramp-get-connection-buffer vec)
5359 (while candidates
5360 (goto-char (point-min))
5361 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
5362 (buffer-string))
5363 (setq locale (car candidates)
5364 candidates nil)
5365 (setq candidates (cdr candidates)))))
5366 ;; Return value.
5367 (format "LC_ALL=%s" (or locale "C")))))
5369 (defun tramp-get-ls-command (vec)
5370 (with-tramp-connection-property vec "ls"
5371 (tramp-message vec 5 "Finding a suitable `ls' command")
5373 (catch 'ls-found
5374 (dolist (cmd '("ls" "gnuls" "gls"))
5375 (let ((dl (tramp-get-remote-path vec))
5376 result)
5377 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5378 ;; Check parameters. On busybox, "ls" output coloring is
5379 ;; enabled by default sometimes. So we try to disable it
5380 ;; when possible. $LS_COLORING is not supported there.
5381 ;; Some "ls" versions are sensible wrt the order of
5382 ;; arguments, they fail when "-al" is after the
5383 ;; "--color=never" argument (for example on FreeBSD).
5384 (when (tramp-send-command-and-check
5385 vec (format "%s -lnd /" result))
5386 (when (tramp-send-command-and-check
5387 vec (format
5388 "%s --color=never -al /dev/null" result))
5389 (setq result (concat result " --color=never")))
5390 (throw 'ls-found result))
5391 (setq dl (cdr dl))))))
5392 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
5394 (defun tramp-get-ls-command-with-dired (vec)
5395 (save-match-data
5396 (with-tramp-connection-property vec "ls-dired"
5397 (tramp-message vec 5 "Checking, whether `ls --dired' works")
5398 ;; Some "ls" versions are sensible wrt the order of arguments,
5399 ;; they fail when "-al" is after the "--dired" argument (for
5400 ;; example on FreeBSD).
5401 (tramp-send-command-and-check
5402 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
5404 (defun tramp-get-ls-command-with-quoting-style (vec)
5405 (save-match-data
5406 (with-tramp-connection-property vec "ls-quoting-style"
5407 (tramp-message vec 5 "Checking, whether `ls --quoting-style=shell' works")
5408 ;; Some "ls" versions are sensible wrt the order of arguments,
5409 ;; they fail when "-al" is after the "--dired" argument (for
5410 ;; example on FreeBSD).
5411 (tramp-send-command-and-check
5412 vec (format "%s --quoting-style=shell -al /dev/null"
5413 (tramp-get-ls-command vec))))))
5415 (defun tramp-get-test-command (vec)
5416 (with-tramp-connection-property vec "test"
5417 (tramp-message vec 5 "Finding a suitable `test' command")
5418 (if (tramp-send-command-and-check vec "test 0")
5419 "test"
5420 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
5422 (defun tramp-get-test-nt-command (vec)
5423 ;; Does `test A -nt B' work? Use abominable `find' construct if it
5424 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
5425 ;; for otherwise the shell crashes.
5426 (with-tramp-connection-property vec "test-nt"
5428 (progn
5429 (tramp-send-command
5430 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
5431 (with-current-buffer (tramp-get-buffer vec)
5432 (goto-char (point-min))
5433 (when (looking-at (regexp-quote tramp-end-of-output))
5434 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
5435 (progn
5436 (tramp-send-command
5438 (format
5439 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
5440 (tramp-get-test-command vec)))
5441 "tramp_test_nt %s %s"))))
5443 (defun tramp-get-file-exists-command (vec)
5444 (with-tramp-connection-property vec "file-exists"
5445 (tramp-message vec 5 "Finding command to check if file exists")
5446 (tramp-find-file-exists-command vec)))
5448 (defun tramp-get-remote-ln (vec)
5449 (with-tramp-connection-property vec "ln"
5450 (tramp-message vec 5 "Finding a suitable `ln' command")
5451 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
5453 (defun tramp-get-remote-perl (vec)
5454 (with-tramp-connection-property vec "perl"
5455 (tramp-message vec 5 "Finding a suitable `perl' command")
5456 (let ((result
5457 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
5458 (tramp-find-executable
5459 vec "perl" (tramp-get-remote-path vec)))))
5460 ;; We must check also for some Perl modules.
5461 (when result
5462 (with-tramp-connection-property vec "perl-file-spec"
5463 (tramp-send-command-and-check
5464 vec (format "%s -e 'use File::Spec;'" result)))
5465 (with-tramp-connection-property vec "perl-cwd-realpath"
5466 (tramp-send-command-and-check
5467 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
5468 result)))
5470 (defun tramp-get-remote-stat (vec)
5471 (with-tramp-connection-property vec "stat"
5472 (tramp-message vec 5 "Finding a suitable `stat' command")
5473 (let ((result (tramp-find-executable
5474 vec "stat" (tramp-get-remote-path vec)))
5475 tmp)
5476 ;; Check whether stat(1) returns usable syntax. "%s" does not
5477 ;; work on older AIX systems.
5478 (when result
5479 (setq tmp
5480 (tramp-send-command-and-read
5481 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5482 (unless (and (listp tmp) (stringp (car tmp))
5483 (string-match "^./.$" (car tmp))
5484 (integerp (cadr tmp)))
5485 (setq result nil)))
5486 result)))
5488 (defun tramp-get-remote-readlink (vec)
5489 (with-tramp-connection-property vec "readlink"
5490 (tramp-message vec 5 "Finding a suitable `readlink' command")
5491 (let ((result (tramp-find-executable
5492 vec "readlink" (tramp-get-remote-path vec))))
5493 (when (and result
5494 (tramp-send-command-and-check
5495 vec (format "%s --canonicalize-missing /" result)))
5496 result))))
5498 (defun tramp-get-remote-trash (vec)
5499 (with-tramp-connection-property vec "trash"
5500 (tramp-message vec 5 "Finding a suitable `trash' command")
5501 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5503 (defun tramp-get-remote-touch (vec)
5504 (with-tramp-connection-property vec "touch"
5505 (tramp-message vec 5 "Finding a suitable `touch' command")
5506 (let ((result (tramp-find-executable
5507 vec "touch" (tramp-get-remote-path vec)))
5508 (tmpfile
5509 (make-temp-name
5510 (expand-file-name
5511 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
5512 ;; Busyboxes do support the "-t" option only when they have been
5513 ;; built with the DESKTOP config option. Let's check it.
5514 (when result
5515 (tramp-set-connection-property
5516 vec "touch-t"
5517 (tramp-send-command-and-check
5519 (format
5520 "%s -t %s %s"
5521 result
5522 (format-time-string "%Y%m%d%H%M.%S")
5523 (tramp-file-name-handler 'file-remote-p tmpfile 'localname))))
5524 (delete-file tmpfile))
5525 result)))
5527 (defun tramp-get-remote-gvfs-monitor-dir (vec)
5528 (with-tramp-connection-property vec "gvfs-monitor-dir"
5529 (tramp-message vec 5 "Finding a suitable `gvfs-monitor-dir' command")
5530 (tramp-find-executable
5531 vec "gvfs-monitor-dir" (tramp-get-remote-path vec) t t)))
5533 (defun tramp-get-remote-inotifywait (vec)
5534 (with-tramp-connection-property vec "inotifywait"
5535 (tramp-message vec 5 "Finding a suitable `inotifywait' command")
5536 (tramp-find-executable vec "inotifywait" (tramp-get-remote-path vec) t t)))
5538 (defun tramp-get-remote-id (vec)
5539 (with-tramp-connection-property vec "id"
5540 (tramp-message vec 5 "Finding POSIX `id' command")
5541 (catch 'id-found
5542 (dolist (cmd '("id" "gid"))
5543 (let ((dl (tramp-get-remote-path vec))
5544 result)
5545 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5546 ;; Check POSIX parameter.
5547 (when (tramp-send-command-and-check vec (format "%s -u" result))
5548 (throw 'id-found result))
5549 (setq dl (cdr dl))))))))
5551 (defun tramp-get-remote-uid-with-id (vec id-format)
5552 (tramp-send-command-and-read
5554 (format "%s -u%s %s"
5555 (tramp-get-remote-id vec)
5556 (if (equal id-format 'integer) "" "n")
5557 (if (equal id-format 'integer)
5558 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5560 (defun tramp-get-remote-uid-with-perl (vec id-format)
5561 (tramp-send-command-and-read
5563 (format "%s -le '%s'"
5564 (tramp-get-remote-perl vec)
5565 (if (equal id-format 'integer)
5566 "print $>"
5567 "print \"\\\"\", scalar getpwuid($>), \"\\\"\""))))
5569 (defun tramp-get-remote-python (vec)
5570 (with-tramp-connection-property vec "python"
5571 (tramp-message vec 5 "Finding a suitable `python' command")
5572 (or (tramp-find-executable vec "python" (tramp-get-remote-path vec))
5573 (tramp-find-executable vec "python2" (tramp-get-remote-path vec))
5574 (tramp-find-executable vec "python3" (tramp-get-remote-path vec)))))
5576 (defun tramp-get-remote-uid-with-python (vec id-format)
5577 (tramp-send-command-and-read
5579 (format "%s -c \"%s\""
5580 (tramp-get-remote-python vec)
5581 (if (equal id-format 'integer)
5582 "import os; print (os.getuid())"
5583 "import os, pwd; print ('\\\"' + pwd.getpwuid(os.getuid())[0] + '\\\"')"))))
5585 (defun tramp-get-remote-uid (vec id-format)
5586 (with-tramp-connection-property vec (format "uid-%s" id-format)
5587 (let ((res
5588 (ignore-errors
5589 (cond
5590 ((tramp-get-remote-id vec)
5591 (tramp-get-remote-uid-with-id vec id-format))
5592 ((tramp-get-remote-perl vec)
5593 (tramp-get-remote-uid-with-perl vec id-format))
5594 ((tramp-get-remote-python vec)
5595 (tramp-get-remote-uid-with-python vec id-format))))))
5596 ;; Ensure there is a valid result.
5597 (cond
5598 ((and (equal id-format 'integer) (not (integerp res))) -1)
5599 ((and (equal id-format 'string) (not (stringp res))) "UNKNOWN")
5600 (t res)))))
5602 (defun tramp-get-remote-gid-with-id (vec id-format)
5603 (tramp-send-command-and-read
5605 (format "%s -g%s %s"
5606 (tramp-get-remote-id vec)
5607 (if (equal id-format 'integer) "" "n")
5608 (if (equal id-format 'integer)
5609 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5611 (defun tramp-get-remote-gid-with-perl (vec id-format)
5612 (tramp-send-command-and-read
5614 (format "%s -le '%s'"
5615 (tramp-get-remote-perl vec)
5616 (if (equal id-format 'integer)
5617 "print ($)=~/(\\d+)/)"
5618 "print \"\\\"\", scalar getgrgid($)), \"\\\"\""))))
5620 (defun tramp-get-remote-gid-with-python (vec id-format)
5621 (tramp-send-command-and-read
5623 (format "%s -c \"%s\""
5624 (tramp-get-remote-python vec)
5625 (if (equal id-format 'integer)
5626 "import os; print (os.getgid())"
5627 "import os, grp; print ('\\\"' + grp.getgrgid(os.getgid())[0] + '\\\"')"))))
5629 (defun tramp-get-remote-gid (vec id-format)
5630 (with-tramp-connection-property vec (format "gid-%s" id-format)
5631 (let ((res
5632 (ignore-errors
5633 (cond
5634 ((tramp-get-remote-id vec)
5635 (tramp-get-remote-gid-with-id vec id-format))
5636 ((tramp-get-remote-perl vec)
5637 (tramp-get-remote-gid-with-perl vec id-format))
5638 ((tramp-get-remote-python vec)
5639 (tramp-get-remote-gid-with-python vec id-format))))))
5640 ;; Ensure there is a valid result.
5641 (cond
5642 ((and (equal id-format 'integer) (not (integerp res))) -1)
5643 ((and (equal id-format 'string) (not (stringp res))) "UNKNOWN")
5644 (t res)))))
5646 ;; Some predefined connection properties.
5647 (defun tramp-get-inline-compress (vec prop size)
5648 "Return the compress command related to PROP.
5649 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5650 the length of the file to be compressed.
5652 If no corresponding command is found, nil is returned."
5653 (when (and (integerp tramp-inline-compress-start-size)
5654 (> size tramp-inline-compress-start-size))
5655 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5656 (tramp-find-inline-compress vec)
5657 (tramp-get-connection-property
5658 (tramp-get-connection-process vec) prop nil))))
5660 (defun tramp-get-inline-coding (vec prop size)
5661 "Return the coding command related to PROP.
5662 PROP is either `remote-encoding', `remote-decoding',
5663 `local-encoding' or `local-decoding'.
5665 SIZE is the length of the file to be coded. Depending on SIZE,
5666 compression might be applied.
5668 If no corresponding command is found, nil is returned.
5669 Otherwise, either a string is returned which contains a `%s' mark
5670 to be used for the respective input or output file; or a Lisp
5671 function cell is returned to be applied on a buffer."
5672 ;; We must catch the errors, because we want to return nil, when
5673 ;; no inline coding is found.
5674 (ignore-errors
5675 (let ((coding
5676 (with-tramp-connection-property
5677 (tramp-get-connection-process vec) prop
5678 (tramp-find-inline-encoding vec)
5679 (tramp-get-connection-property
5680 (tramp-get-connection-process vec) prop nil)))
5681 (prop1 (if (string-match "encoding" prop)
5682 "inline-compress" "inline-decompress"))
5683 compress)
5684 ;; The connection property might have been cached. So we must
5685 ;; send the script to the remote side - maybe.
5686 (when (and coding (symbolp coding) (string-match "remote" prop))
5687 (let ((name (symbol-name coding)))
5688 (while (string-match (regexp-quote "-") name)
5689 (setq name (replace-match "_" nil t name)))
5690 (tramp-maybe-send-script vec (symbol-value coding) name)
5691 (setq coding name)))
5692 (when coding
5693 ;; Check for the `compress' command.
5694 (setq compress (tramp-get-inline-compress vec prop1 size))
5695 ;; Return the value.
5696 (cond
5697 ((and compress (symbolp coding))
5698 (if (string-match "decompress" prop1)
5699 `(lambda (beg end)
5700 (,coding beg end)
5701 (let ((coding-system-for-write 'binary)
5702 (coding-system-for-read 'binary)
5703 (default-directory
5704 (tramp-compat-temporary-file-directory)))
5705 (apply
5706 'tramp-call-process-region ,vec (point-min) (point-max)
5707 (car (split-string ,compress)) t t nil
5708 (cdr (split-string ,compress)))))
5709 `(lambda (beg end)
5710 (let ((coding-system-for-write 'binary)
5711 (coding-system-for-read 'binary)
5712 (default-directory
5713 (tramp-compat-temporary-file-directory)))
5714 (apply
5715 'tramp-call-process-region ,vec beg end
5716 (car (split-string ,compress)) t t nil
5717 (cdr (split-string ,compress))))
5718 (,coding (point-min) (point-max)))))
5719 ((symbolp coding)
5720 coding)
5721 ((and compress (string-match "decoding" prop))
5722 (format
5723 ;; Windows shells need the program file name after
5724 ;; the pipe symbol be quoted if they use forward
5725 ;; slashes as directory separators.
5726 (cond
5727 ((and (string-match "local" prop)
5728 (memq system-type '(windows-nt)))
5729 "(%s | \"%s\")")
5730 ((string-match "local" prop) "(%s | %s)")
5731 (t "(%s | %s >%%s)"))
5732 coding compress))
5733 (compress
5734 (format
5735 ;; Windows shells need the program file name after
5736 ;; the pipe symbol be quoted if they use forward
5737 ;; slashes as directory separators.
5738 (if (and (string-match "local" prop)
5739 (memq system-type '(windows-nt)))
5740 "(%s <%%s | \"%s\")"
5741 "(%s <%%s | %s)")
5742 compress coding))
5743 ((string-match "decoding" prop)
5744 (cond
5745 ((string-match "local" prop) (format "%s" coding))
5746 (t (format "%s >%%s" coding))))
5748 (format "%s <%%s" coding)))))))
5750 (add-hook 'tramp-unload-hook
5751 (lambda ()
5752 (unload-feature 'tramp-sh 'force)))
5754 (provide 'tramp-sh)
5756 ;;; TODO:
5758 ;; * Don't use globbing for directories with many files, as this is
5759 ;; likely to produce long command lines, and some shells choke on
5760 ;; long command lines.
5761 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5762 ;; then look if it's the right version (with `perl -v').
5763 ;; * When editing a remote CVS controlled file as a different user, VC
5764 ;; gets confused about the file locking status. Try to find out why
5765 ;; the workaround doesn't work.
5766 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5767 ;; until the last but one hop via `start-file-process'. Apply it
5768 ;; also for ftp and smb.
5769 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5770 ;; some shell with root privileges, it would be nice if I could
5771 ;; just call
5772 ;; trampclient filename.c
5773 ;; as an editor, and the _current_ shell would connect to an Emacs
5774 ;; server and would be used in an existing non-privileged Emacs
5775 ;; session for doing the editing in question.
5776 ;; That way, I need not tell Emacs my password again and be afraid
5777 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5778 ;; once display a just typed password in the context of a keyboard
5779 ;; sequence prompt for a question immediately following in a shell
5780 ;; script run within Emacs -- nasty).
5781 ;; And if I have some ssh session running to a different computer,
5782 ;; having the possibility of passing a local file there to a local
5783 ;; Emacs session (in case I can arrange for a connection back) would
5784 ;; be nice.
5785 ;; Likely the corresponding Tramp server should not allow the
5786 ;; equivalent of the emacsclient -eval option in order to make this
5787 ;; reasonably unproblematic. And maybe trampclient should have some
5788 ;; way of passing credentials, like by using an SSL socket or
5789 ;; something. (David Kastrup)
5790 ;; * Reconnect directly to a compliant shell without first going
5791 ;; through the user's default shell. (Pete Forman)
5792 ;; * How can I interrupt the remote process with a signal
5793 ;; (interrupt-process seems not to work)? (Markus Triska)
5794 ;; * Avoid the local shell entirely for starting remote processes. If
5795 ;; so, I think even a signal, when delivered directly to the local
5796 ;; SSH instance, would correctly be propagated to the remote process
5797 ;; automatically; possibly SSH would have to be started with
5798 ;; "-t". (Markus Triska)
5799 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5800 ;; isn't on the remote host. (Mark A. Hershberger)
5801 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5802 ;; * Optimize out-of-band copying when both methods are scp-like (not
5803 ;; rsync).
5804 ;; * Keep a second connection open for out-of-band methods like scp or
5805 ;; rsync.
5807 ;;; tramp-sh.el ends here