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