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