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