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