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