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