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