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