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