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