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