* lisp/vc/vc-bzr.el (vc-bzr-revision-keywords): Remove svn, it's only
[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)
2693 (format "cd %s; exec %s"
2694 (tramp-shell-quote-argument localname)
2695 (mapconcat 'tramp-shell-quote-argument
2696 (cons program args) " "))))
2697 (tramp-process-connection-type
2698 (or (null program) tramp-process-connection-type))
2699 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2700 (name1 name)
2701 (i 0))
2702 (unwind-protect
2703 (save-excursion
2704 (save-restriction
2705 (unless buffer
2706 ;; BUFFER can be nil. We use a temporary buffer.
2707 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
2708 (while (get-process name1)
2709 ;; NAME must be unique as process name.
2710 (setq i (1+ i)
2711 name1 (format "%s<%d>" name i)))
2712 (setq name name1)
2713 ;; Set the new process properties.
2714 (tramp-set-connection-property v "process-name" name)
2715 (tramp-set-connection-property v "process-buffer" buffer)
2716 ;; Activate narrowing in order to save BUFFER contents.
2717 ;; Clear also the modification time; otherwise we might
2718 ;; be interrupted by `verify-visited-file-modtime'.
2719 (with-current-buffer (tramp-get-connection-buffer v)
2720 (let ((buffer-undo-list t))
2721 (clear-visited-file-modtime)
2722 (narrow-to-region (point-max) (point-max))
2723 (if command
2724 ;; Send the command.
d68b0220
MA
2725 (tramp-send-command v command nil t) ; nooutput
2726 ;; Check, whether a pty is associated.
2727 (tramp-maybe-open-connection v)
2728 (unless (tramp-compat-process-get
2729 (tramp-get-connection-process v) 'remote-tty)
2730 (tramp-error
f49d1f52
SM
2731 v 'file-error
2732 "pty association is not supported for `%s'" name)))))
d68b0220 2733 (let ((p (tramp-get-connection-process v)))
6d95bd46 2734 ;; Set query flag for this process.
d68b0220
MA
2735 (tramp-compat-set-process-query-on-exit-flag p t)
2736 ;; Return process.
f49d1f52
SM
2737 p)))
2738 ;; Save exit.
2739 (with-current-buffer (tramp-get-connection-buffer v)
2740 (if (string-match tramp-temp-buffer-name (buffer-name))
2741 (progn
2742 (set-process-buffer (tramp-get-connection-process v) nil)
2743 (kill-buffer (current-buffer)))
2744 (set-buffer-modified-p bmp)))
2745 (tramp-set-connection-property v "process-name" nil)
2746 (tramp-set-connection-property v "process-buffer" nil)))))
03c1ad43 2747
4a93e698 2748(defun tramp-sh-handle-process-file
03c1ad43
MA
2749 (program &optional infile destination display &rest args)
2750 "Like `process-file' for Tramp files."
2751 ;; The implementation is not complete yet.
2752 (when (and (numberp destination) (zerop destination))
2753 (error "Implementation does not handle immediate return"))
2754
2755 (with-parsed-tramp-file-name default-directory nil
2756 (let (command input tmpinput stderr tmpstderr outbuf ret)
2757 ;; Compute command.
2758 (setq command (mapconcat 'tramp-shell-quote-argument
2759 (cons program args) " "))
2760 ;; Determine input.
2761 (if (null infile)
2762 (setq input "/dev/null")
2763 (setq infile (expand-file-name infile))
2764 (if (tramp-equal-remote default-directory infile)
2765 ;; INFILE is on the same remote host.
2766 (setq input (with-parsed-tramp-file-name infile nil localname))
2767 ;; INFILE must be copied to remote host.
2768 (setq input (tramp-make-tramp-temp-file v)
2769 tmpinput (tramp-make-tramp-file-name method user host input))
2770 (copy-file infile tmpinput t)))
2771 (when input (setq command (format "%s <%s" command input)))
2772
2773 ;; Determine output.
2774 (cond
2775 ;; Just a buffer.
2776 ((bufferp destination)
2777 (setq outbuf destination))
2778 ;; A buffer name.
2779 ((stringp destination)
2780 (setq outbuf (get-buffer-create destination)))
2781 ;; (REAL-DESTINATION ERROR-DESTINATION)
2782 ((consp destination)
2783 ;; output.
2784 (cond
2785 ((bufferp (car destination))
2786 (setq outbuf (car destination)))
2787 ((stringp (car destination))
2788 (setq outbuf (get-buffer-create (car destination))))
2789 ((car destination)
2790 (setq outbuf (current-buffer))))
2791 ;; stderr.
2792 (cond
2793 ((stringp (cadr destination))
2794 (setcar (cdr destination) (expand-file-name (cadr destination)))
2795 (if (tramp-equal-remote default-directory (cadr destination))
2796 ;; stderr is on the same remote host.
2797 (setq stderr (with-parsed-tramp-file-name
2798 (cadr destination) nil localname))
2799 ;; stderr must be copied to remote host. The temporary
2800 ;; file must be deleted after execution.
2801 (setq stderr (tramp-make-tramp-temp-file v)
2802 tmpstderr (tramp-make-tramp-file-name
2803 method user host stderr))))
2804 ;; stderr to be discarded.
2805 ((null (cadr destination))
2806 (setq stderr "/dev/null"))))
2807 ;; 't
2808 (destination
2809 (setq outbuf (current-buffer))))
2810 (when stderr (setq command (format "%s 2>%s" command stderr)))
2811
2812 ;; Send the command. It might not return in time, so we protect
2813 ;; it. Call it in a subshell, in order to preserve working
2814 ;; directory.
2815 (condition-case nil
2816 (unwind-protect
2817 (setq ret
2818 (if (tramp-send-command-and-check
2819 v (format "\\cd %s; %s"
2820 (tramp-shell-quote-argument localname)
2821 command)
2822 t t)
2823 0 1))
2824 ;; We should show the output anyway.
2825 (when outbuf
2826 (with-current-buffer outbuf
2827 (insert
2828 (with-current-buffer (tramp-get-connection-buffer v)
2829 (buffer-string))))
2830 (when display (display-buffer outbuf))))
2831 ;; When the user did interrupt, we should do it also. We use
2832 ;; return code -1 as marker.
2833 (quit
2834 (kill-buffer (tramp-get-connection-buffer v))
2835 (setq ret -1))
2836 ;; Handle errors.
2837 (error
2838 (kill-buffer (tramp-get-connection-buffer v))
2839 (setq ret 1)))
2840
2841 ;; Provide error file.
2842 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
2843
2844 ;; Cleanup. We remove all file cache values for the connection,
2845 ;; because the remote process could have changed them.
2846 (when tmpinput (delete-file tmpinput))
2847
2848 ;; `process-file-side-effects' has been introduced with GNU
2849 ;; Emacs 23.2. If set to `nil', no remote file will be changed
2850 ;; by `program'. If it doesn't exist, we assume its default
2851 ;; value 't'.
2852 (unless (and (boundp 'process-file-side-effects)
2853 (not (symbol-value 'process-file-side-effects)))
2854 (tramp-flush-directory-property v ""))
2855
2856 ;; Return exit status.
2857 (if (equal ret -1)
2858 (keyboard-quit)
2859 ret))))
2860
4a93e698 2861(defun tramp-sh-handle-call-process-region
03c1ad43
MA
2862 (start end program &optional delete buffer display &rest args)
2863 "Like `call-process-region' for Tramp files."
2864 (let ((tmpfile (tramp-compat-make-temp-file "")))
2865 (write-region start end tmpfile)
2866 (when delete (delete-region start end))
2867 (unwind-protect
2868 (apply 'call-process program tmpfile buffer display args)
2869 (delete-file tmpfile))))
2870
4a93e698 2871(defun tramp-sh-handle-shell-command
03c1ad43
MA
2872 (command &optional output-buffer error-buffer)
2873 "Like `shell-command' for Tramp files."
2874 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
2875 ;; We cannot use `shell-file-name' and `shell-command-switch',
2876 ;; they are variables of the local host.
2877 (args (list
2878 (tramp-get-method-parameter
2879 (tramp-file-name-method
2880 (tramp-dissect-file-name default-directory))
2881 'tramp-remote-sh)
2882 "-c" (substring command 0 asynchronous)))
2883 current-buffer-p
2884 (output-buffer
2885 (cond
2886 ((bufferp output-buffer) output-buffer)
2887 ((stringp output-buffer) (get-buffer-create output-buffer))
2888 (output-buffer
2889 (setq current-buffer-p t)
2890 (current-buffer))
2891 (t (get-buffer-create
2892 (if asynchronous
2893 "*Async Shell Command*"
2894 "*Shell Command Output*")))))
2895 (error-buffer
2896 (cond
2897 ((bufferp error-buffer) error-buffer)
2898 ((stringp error-buffer) (get-buffer-create error-buffer))))
2899 (buffer
2900 (if (and (not asynchronous) error-buffer)
2901 (with-parsed-tramp-file-name default-directory nil
2902 (list output-buffer (tramp-make-tramp-temp-file v)))
2903 output-buffer))
2904 (p (get-buffer-process output-buffer)))
2905
2906 ;; Check whether there is another process running. Tramp does not
2907 ;; support 2 (asynchronous) processes in parallel.
2908 (when p
2909 (if (yes-or-no-p "A command is running. Kill it? ")
2910 (ignore-errors (kill-process p))
2911 (error "Shell command in progress")))
2912
2913 (if current-buffer-p
2914 (progn
2915 (barf-if-buffer-read-only)
2916 (push-mark nil t))
2917 (with-current-buffer output-buffer
2918 (setq buffer-read-only nil)
2919 (erase-buffer)))
2920
2921 (if (and (not current-buffer-p) (integerp asynchronous))
2922 (prog1
2923 ;; Run the process.
2924 (apply 'start-file-process "*Async Shell*" buffer args)
2925 ;; Display output.
2926 (pop-to-buffer output-buffer)
2927 (setq mode-line-process '(":%s"))
2928 (shell-mode))
2929
2930 (prog1
2931 ;; Run the process.
2932 (apply 'process-file (car args) nil buffer nil (cdr args))
2933 ;; Insert error messages if they were separated.
2934 (when (listp buffer)
2935 (with-current-buffer error-buffer
2936 (insert-file-contents (cadr buffer)))
2937 (delete-file (cadr buffer)))
2938 (if current-buffer-p
2939 ;; This is like exchange-point-and-mark, but doesn't
2940 ;; activate the mark. It is cleaner to avoid activation,
2941 ;; even though the command loop would deactivate the mark
2942 ;; because we inserted text.
2943 (goto-char (prog1 (mark t)
2944 (set-marker (mark-marker) (point)
2945 (current-buffer))))
2946 ;; There's some output, display it.
2947 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
2948 (if (functionp 'display-message-or-buffer)
2949 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
2950 (pop-to-buffer output-buffer))))))))
2951
4a93e698 2952(defun tramp-sh-handle-file-local-copy (filename)
03c1ad43 2953 "Like `file-local-copy' for Tramp files."
03c1ad43
MA
2954 (with-parsed-tramp-file-name filename nil
2955 (unless (file-exists-p filename)
2956 (tramp-error
2957 v 'file-error
2958 "Cannot make local copy of non-existing file `%s'" filename))
2959
66feec8b 2960 (let* ((size (nth 7 (file-attributes (file-truename filename))))
03c1ad43
MA
2961 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
2962 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
2963 (tmpfile (tramp-compat-make-temp-file filename)))
2964
2965 (condition-case err
2966 (cond
2967 ;; `copy-file' handles direct copy and out-of-band methods.
2968 ((or (tramp-local-host-p v)
2969 (tramp-method-out-of-band-p v size))
2970 (copy-file filename tmpfile t t))
2971
2972 ;; Use inline encoding for file transfer.
2973 (rem-enc
2974 (save-excursion
7d520089 2975 (tramp-with-progress-reporter
03c1ad43
MA
2976 v 3 (format "Encoding remote file %s" filename)
2977 (tramp-barf-unless-okay
2978 v (format rem-enc (tramp-shell-quote-argument localname))
2979 "Encoding remote file failed"))
2980
2981 (if (functionp loc-dec)
2982 ;; If local decoding is a function, we call it. We
2983 ;; must disable multibyte, because
2984 ;; `uudecode-decode-region' doesn't handle it
2985 ;; correctly.
2986 (with-temp-buffer
2987 (set-buffer-multibyte nil)
2988 (insert-buffer-substring (tramp-get-buffer v))
7d520089 2989 (tramp-with-progress-reporter
03c1ad43
MA
2990 v 3 (format "Decoding remote file %s with function %s"
2991 filename loc-dec)
2992 (funcall loc-dec (point-min) (point-max))
2993 ;; Unset `file-name-handler-alist'. Otherwise,
2994 ;; epa-file gets confused.
2995 (let (file-name-handler-alist
2996 (coding-system-for-write 'binary))
2997 (write-region (point-min) (point-max) tmpfile))))
2998
2999 ;; If tramp-decoding-function is not defined for this
3000 ;; method, we invoke tramp-decoding-command instead.
3001 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3002 ;; Unset `file-name-handler-alist'. Otherwise,
3003 ;; epa-file gets confused.
3004 (let (file-name-handler-alist
3005 (coding-system-for-write 'binary))
3006 (write-region (point-min) (point-max) tmpfile2))
7d520089 3007 (tramp-with-progress-reporter
03c1ad43
MA
3008 v 3 (format "Decoding remote file %s with command %s"
3009 filename loc-dec)
3010 (unwind-protect
3011 (tramp-call-local-coding-command
3012 loc-dec tmpfile2 tmpfile)
3013 (delete-file tmpfile2)))))
3014
3015 ;; Set proper permissions.
3016 (set-file-modes tmpfile (tramp-default-file-modes filename))
3017 ;; Set local user ownership.
3018 (tramp-set-file-uid-gid tmpfile)))
3019
3020 ;; Oops, I don't know what to do.
3021 (t (tramp-error
3022 v 'file-error "Wrong method specification for `%s'" method)))
3023
3024 ;; Error handling.
3025 ((error quit)
3026 (delete-file tmpfile)
3027 (signal (car err) (cdr err))))
3028
3029 (run-hooks 'tramp-handle-file-local-copy-hook)
3030 tmpfile)))
3031
03c1ad43 3032;; This is needed for XEmacs only. Code stolen from files.el.
4a93e698 3033(defun tramp-sh-handle-insert-file-contents-literally
03c1ad43
MA
3034 (filename &optional visit beg end replace)
3035 "Like `insert-file-contents-literally' for Tramp files."
3036 (let ((format-alist nil)
3037 (after-insert-file-functions nil)
3038 (coding-system-for-read 'no-conversion)
3039 (coding-system-for-write 'no-conversion)
3040 (find-buffer-file-type-function
3041 (if (fboundp 'find-buffer-file-type)
3042 (symbol-function 'find-buffer-file-type)
3043 nil))
3044 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
3045 (inhibit-file-name-operation 'insert-file-contents))
3046 (unwind-protect
3047 (progn
3048 (fset 'find-buffer-file-type (lambda (filename) t))
3049 (insert-file-contents filename visit beg end replace))
3050 ;; Save exit.
3051 (if find-buffer-file-type-function
3052 (fset 'find-buffer-file-type find-buffer-file-type-function)
3053 (fmakunbound 'find-buffer-file-type)))))
3054
4a93e698 3055(defun tramp-sh-handle-make-auto-save-file-name ()
03c1ad43
MA
3056 "Like `make-auto-save-file-name' for Tramp files.
3057Returns a file name in `tramp-auto-save-directory' for autosaving this file."
3058 (let ((tramp-auto-save-directory tramp-auto-save-directory)
3059 (buffer-file-name
3060 (tramp-subst-strs-in-string
3061 '(("_" . "|")
3062 ("/" . "_a")
3063 (":" . "_b")
3064 ("|" . "__")
3065 ("[" . "_l")
3066 ("]" . "_r"))
3067 (buffer-file-name))))
3068 ;; File name must be unique. This is ensured with Emacs 22 (see
3069 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
3070 ;; all other cases we must do it ourselves.
3071 (when (boundp 'auto-save-file-name-transforms)
3072 (mapc
3073 (lambda (x)
3074 (when (and (string-match (car x) buffer-file-name)
3075 (not (car (cddr x))))
3076 (setq tramp-auto-save-directory
3077 (or tramp-auto-save-directory
3078 (tramp-compat-temporary-file-directory)))))
3079 (symbol-value 'auto-save-file-name-transforms)))
3080 ;; Create directory.
3081 (when tramp-auto-save-directory
3082 (setq buffer-file-name
3083 (expand-file-name buffer-file-name tramp-auto-save-directory))
3084 (unless (file-exists-p tramp-auto-save-directory)
3085 (make-directory tramp-auto-save-directory t)))
3086 ;; Run plain `make-auto-save-file-name'. There might be an advice when
3087 ;; it is not a magic file name operation (since Emacs 22).
3088 ;; We must deactivate it temporarily.
3089 (if (not (ad-is-active 'make-auto-save-file-name))
3090 (tramp-run-real-handler 'make-auto-save-file-name nil)
3091 ;; else
3092 (ad-deactivate 'make-auto-save-file-name)
3093 (prog1
3094 (tramp-run-real-handler 'make-auto-save-file-name nil)
3095 (ad-activate 'make-auto-save-file-name)))))
3096
03c1ad43 3097;; CCC grok LOCKNAME
4a93e698 3098(defun tramp-sh-handle-write-region
03c1ad43
MA
3099 (start end filename &optional append visit lockname confirm)
3100 "Like `write-region' for Tramp files."
3101 (setq filename (expand-file-name filename))
3102 (with-parsed-tramp-file-name filename nil
3103 ;; Following part commented out because we don't know what to do about
3104 ;; file locking, and it does not appear to be a problem to ignore it.
3105 ;; Ange-ftp ignores it, too.
3106 ;; (when (and lockname (stringp lockname))
3107 ;; (setq lockname (expand-file-name lockname)))
3108 ;; (unless (or (eq lockname nil)
3109 ;; (string= lockname filename))
3110 ;; (error
4a93e698 3111 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
03c1ad43
MA
3112
3113 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
3114 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
3115 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3116 (tramp-error v 'file-error "File not overwritten")))
3117
3118 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
3119 (tramp-get-remote-uid v 'integer)))
3120 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
3121 (tramp-get-remote-gid v 'integer))))
3122
3123 (if (and (tramp-local-host-p v)
3124 ;; `file-writable-p' calls `file-expand-file-name'. We
3125 ;; cannot use `tramp-run-real-handler' therefore.
3126 (let (file-name-handler-alist)
3127 (and
3128 (file-writable-p (file-name-directory localname))
3129 (or (file-directory-p localname)
3130 (file-writable-p localname)))))
3131 ;; Short track: if we are on the local host, we can run directly.
3132 (tramp-run-real-handler
3133 'write-region
3134 (list start end localname append 'no-message lockname confirm))
3135
3136 (let ((modes (save-excursion (tramp-default-file-modes filename)))
3137 ;; We use this to save the value of
3138 ;; `last-coding-system-used' after writing the tmp
3139 ;; file. At the end of the function, we set
3140 ;; `last-coding-system-used' to this saved value. This
3141 ;; way, any intermediary coding systems used while
3142 ;; talking to the remote shell or suchlike won't hose
3143 ;; this variable. This approach was snarfed from
3144 ;; ange-ftp.el.
3145 coding-system-used
3146 ;; Write region into a tmp file. This isn't really
3147 ;; needed if we use an encoding function, but currently
3148 ;; we use it always because this makes the logic
3149 ;; simpler.
3150 (tmpfile (or tramp-temp-buffer-file-name
3151 (tramp-compat-make-temp-file filename))))
3152
3153 ;; If `append' is non-nil, we copy the file locally, and let
3154 ;; the native `write-region' implementation do the job.
3155 (when append (copy-file filename tmpfile 'ok))
3156
3157 ;; We say `no-message' here because we don't want the
3158 ;; visited file modtime data to be clobbered from the temp
3159 ;; file. We call `set-visited-file-modtime' ourselves later
3160 ;; on. We must ensure that `file-coding-system-alist'
3161 ;; matches `tmpfile'.
3162 (let (file-name-handler-alist
3163 (file-coding-system-alist
3164 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3165 (condition-case err
3166 (tramp-run-real-handler
3167 'write-region
3168 (list start end tmpfile append 'no-message lockname confirm))
3169 ((error quit)
3170 (setq tramp-temp-buffer-file-name nil)
3171 (delete-file tmpfile)
3172 (signal (car err) (cdr err))))
3173
3174 ;; Now, `last-coding-system-used' has the right value. Remember it.
3175 (when (boundp 'last-coding-system-used)
3176 (setq coding-system-used
3177 (symbol-value 'last-coding-system-used))))
3178
3179 ;; The permissions of the temporary file should be set. If
3180 ;; filename does not exist (eq modes nil) it has been
3181 ;; renamed to the backup file. This case `save-buffer'
3182 ;; handles permissions.
2c68ca0e 3183 ;; Ensure that it is still readable.
03c1ad43
MA
3184 (when modes
3185 (set-file-modes
3186 tmpfile
3187 (logior (or modes 0) (tramp-compat-octal-to-decimal "0400"))))
3188
3189 ;; This is a bit lengthy due to the different methods
3190 ;; possible for file transfer. First, we check whether the
3191 ;; method uses an rcp program. If so, we call it.
3192 ;; Otherwise, both encoding and decoding command must be
3193 ;; specified. However, if the method _also_ specifies an
3194 ;; encoding function, then that is used for encoding the
3195 ;; contents of the tmp file.
3196 (let* ((size (nth 7 (file-attributes tmpfile)))
3197 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3198 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3199 (cond
3200 ;; `copy-file' handles direct copy and out-of-band methods.
3201 ((or (tramp-local-host-p v)
3202 (tramp-method-out-of-band-p v size))
3203 (if (and (not (stringp start))
3204 (= (or end (point-max)) (point-max))
3205 (= (or start (point-min)) (point-min))
3206 (tramp-get-method-parameter
3207 method 'tramp-copy-keep-tmpfile))
3208 (progn
3209 (setq tramp-temp-buffer-file-name tmpfile)
3210 (condition-case err
3211 ;; We keep the local file for performance
3212 ;; reasons, useful for "rsync".
3213 (copy-file tmpfile filename t)
3214 ((error quit)
3215 (setq tramp-temp-buffer-file-name nil)
3216 (delete-file tmpfile)
3217 (signal (car err) (cdr err)))))
3218 (setq tramp-temp-buffer-file-name nil)
3219 ;; Don't rename, in order to keep context in SELinux.
3220 (unwind-protect
3221 (copy-file tmpfile filename t)
3222 (delete-file tmpfile))))
3223
3224 ;; Use inline file transfer.
3225 (rem-dec
3226 ;; Encode tmpfile.
3227 (unwind-protect
3228 (with-temp-buffer
3229 (set-buffer-multibyte nil)
3230 ;; Use encoding function or command.
3231 (if (functionp loc-enc)
7d520089 3232 (tramp-with-progress-reporter
03c1ad43
MA
3233 v 3 (format "Encoding region using function `%s'"
3234 loc-enc)
3235 (let ((coding-system-for-read 'binary))
3236 (insert-file-contents-literally tmpfile))
3237 ;; The following `let' is a workaround for the
3238 ;; base64.el that comes with pgnus-0.84. If
3239 ;; both of the following conditions are
3240 ;; satisfied, it tries to write to a local
3241 ;; file in default-directory, but at this
3242 ;; point, default-directory is remote.
3243 ;; (`call-process-region' can't write to
3244 ;; remote files, it seems.) The file in
3245 ;; question is a tmp file anyway.
3246 (let ((default-directory
3247 (tramp-compat-temporary-file-directory)))
3248 (funcall loc-enc (point-min) (point-max))))
3249
7d520089 3250 (tramp-with-progress-reporter
03c1ad43
MA
3251 v 3 (format "Encoding region using command `%s'"
3252 loc-enc)
3253 (unless (zerop (tramp-call-local-coding-command
3254 loc-enc tmpfile t))
3255 (tramp-error
3256 v 'file-error
3257 (concat "Cannot write to `%s', "
3258 "local encoding command `%s' failed")
3259 filename loc-enc))))
3260
3261 ;; Send buffer into remote decoding command which
3262 ;; writes to remote file. Because this happens on
3263 ;; the remote host, we cannot use the function.
7d520089 3264 (tramp-with-progress-reporter
03c1ad43
MA
3265 v 3
3266 (format "Decoding region into remote file %s" filename)
3267 (goto-char (point-max))
3268 (unless (bolp) (newline))
3269 (tramp-send-command
3270 v
3271 (format
3272 (concat rem-dec " <<'EOF'\n%sEOF")
3273 (tramp-shell-quote-argument localname)
3274 (buffer-string)))
3275 (tramp-barf-unless-okay
3276 v nil
3277 "Couldn't write region to `%s', decode using `%s' failed"
3278 filename rem-dec)
3279 ;; When `file-precious-flag' is set, the region is
3280 ;; written to a temporary file. Check that the
3281 ;; checksum is equal to that from the local tmpfile.
3282 (when file-precious-flag
3283 (erase-buffer)
3284 (and
3285 ;; cksum runs locally, if possible.
3286 (zerop (tramp-compat-call-process "cksum" tmpfile t))
3287 ;; cksum runs remotely.
3288 (tramp-send-command-and-check
3289 v
3290 (format
3291 "cksum <%s" (tramp-shell-quote-argument localname)))
3292 ;; ... they are different.
3293 (not
3294 (string-equal
3295 (buffer-string)
3296 (with-current-buffer (tramp-get-buffer v)
3297 (buffer-string))))
3298 (tramp-error
3299 v 'file-error
3300 (concat "Couldn't write region to `%s',"
3301 " decode using `%s' failed")
3302 filename rem-dec)))))
3303
3304 ;; Save exit.
3305 (delete-file tmpfile)))
3306
3307 ;; That's not expected.
3308 (t
3309 (tramp-error
3310 v 'file-error
3311 (concat "Method `%s' should specify both encoding and "
3312 "decoding command or an rcp program")
3313 method))))
3314
3315 ;; Make `last-coding-system-used' have the right value.
3316 (when coding-system-used
3317 (set 'last-coding-system-used coding-system-used))))
3318
3319 (tramp-flush-file-property v (file-name-directory localname))
3320 (tramp-flush-file-property v localname)
3321
3322 ;; We must protect `last-coding-system-used', now we have set it
3323 ;; to its correct value.
3324 (let (last-coding-system-used (need-chown t))
3325 ;; Set file modification time.
3326 (when (or (eq visit t) (stringp visit))
3327 (let ((file-attr (file-attributes filename)))
3328 (set-visited-file-modtime
2c68ca0e 3329 ;; We must pass modtime explicitly, because filename can
03c1ad43
MA
3330 ;; be different from (buffer-file-name), f.e. if
3331 ;; `file-precious-flag' is set.
3332 (nth 5 file-attr))
3333 (when (and (eq (nth 2 file-attr) uid)
3334 (eq (nth 3 file-attr) gid))
3335 (setq need-chown nil))))
3336
3337 ;; Set the ownership.
3338 (when need-chown
3339 (tramp-set-file-uid-gid filename uid gid))
3340 (when (or (eq visit t) (null visit) (stringp visit))
3341 (tramp-message v 0 "Wrote %s" filename))
3342 (run-hooks 'tramp-handle-write-region-hook)))))
3343
3344(defvar tramp-vc-registered-file-names nil
3345 "List used to collect file names, which are checked during `vc-registered'.")
3346
3347;; VC backends check for the existence of various different special
3348;; files. This is very time consuming, because every single check
3349;; requires a remote command (the file cache must be invalidated).
3350;; Therefore, we apply a kind of optimization. We install the file
3351;; name handler `tramp-vc-file-name-handler', which does nothing but
3352;; remembers all file names for which `file-exists-p' or
3353;; `file-readable-p' has been applied. A first run of `vc-registered'
3354;; is performed. Afterwards, a script is applied for all collected
3355;; file names, using just one remote command. The result of this
3356;; script is used to fill the file cache with actual values. Now we
3357;; can reset the file name handlers, and we make a second run of
3358;; `vc-registered', which returns the expected result without sending
3359;; any other remote command.
4a93e698 3360(defun tramp-sh-handle-vc-registered (file)
03c1ad43 3361 "Like `vc-registered' for Tramp files."
6139f995 3362 (tramp-compat-with-temp-message ""
03c1ad43 3363 (with-parsed-tramp-file-name file nil
7d520089 3364 (tramp-with-progress-reporter
03c1ad43
MA
3365 v 3 (format "Checking `vc-registered' for %s" file)
3366
3367 ;; There could be new files, created by the vc backend. We
3368 ;; cannot reuse the old cache entries, therefore.
3369 (let (tramp-vc-registered-file-names
4bc3c53d 3370 (remote-file-name-inhibit-cache (current-time))
03c1ad43
MA
3371 (file-name-handler-alist
3372 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3373
3374 ;; Here we collect only file names, which need an operation.
3375 (tramp-run-real-handler 'vc-registered (list file))
3376 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3377
3378 ;; Send just one command, in order to fill the cache.
3379 (when tramp-vc-registered-file-names
3380 (tramp-maybe-send-script
3381 v
3382 (format tramp-vc-registered-read-file-names
3383 (tramp-get-file-exists-command v)
3384 (format "%s -r" (tramp-get-test-command v)))
3385 "tramp_vc_registered_read_file_names")
3386
3387 (dolist
3388 (elt
3389 (tramp-send-command-and-read
3390 v
3391 (format
3392 "tramp_vc_registered_read_file_names <<'EOF'\n%s\nEOF\n"
3393 (mapconcat 'tramp-shell-quote-argument
3394 tramp-vc-registered-file-names
3395 "\n"))))
3396
3397 (tramp-set-file-property
3398 v (car elt) (cadr elt) (cadr (cdr elt))))))
3399
3400 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3401 ;; calls shall be answered from the file cache. We unset
3402 ;; `process-file-side-effects' in order to keep the cache when
3403 ;; `process-file' calls appear.
3404 (let (process-file-side-effects)
3405 (tramp-run-real-handler 'vc-registered (list file)))))))
3406
3407;;;###tramp-autoload
3408(defun tramp-sh-file-name-handler (operation &rest args)
3409 "Invoke remote-shell Tramp file name handler.
3410Fall back to normal file name handler if no Tramp handler exists."
3411 (when (and tramp-locked (not tramp-locker))
3412 (setq tramp-locked nil)
3413 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
3414 (let ((tl tramp-locked))
3415 (unwind-protect
3416 (progn
3417 (setq tramp-locked t)
3418 (let ((tramp-locker t))
3419 (save-match-data
3420 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3421 (if fn
3422 (apply (cdr fn) args)
3423 (tramp-run-real-handler operation args))))))
3424 (setq tramp-locked tl))))
3425
3426(defun tramp-vc-file-name-handler (operation &rest args)
3427 "Invoke special file name handler, which collects files to be handled."
3428 (save-match-data
3429 (let ((filename
3430 (tramp-replace-environment-variables
3431 (apply 'tramp-file-name-for-operation operation args)))
3432 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3433 (with-parsed-tramp-file-name filename nil
3434 (cond
3435 ;; That's what we want: file names, for which checks are
2c68ca0e 3436 ;; applied. We assume that VC uses only `file-exists-p' and
03c1ad43
MA
3437 ;; `file-readable-p' checks; otherwise we must extend the
3438 ;; list. We do not perform any action, but return nil, in
3439 ;; order to keep `vc-registered' running.
3440 ((and fn (memq operation '(file-exists-p file-readable-p)))
3441 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3442 nil)
3443 ;; Tramp file name handlers like `expand-file-name'. They
3444 ;; must still work.
3445 (fn
3446 (save-match-data (apply (cdr fn) args)))
3447 ;; Default file name handlers, we don't care.
3448 (t (tramp-run-real-handler operation args)))))))
3449
3450;;; Internal Functions:
3451
3452(defun tramp-maybe-send-script (vec script name)
3453 "Define in remote shell function NAME implemented as SCRIPT.
3454Only send the definition if it has not already been done."
3455 (let* ((p (tramp-get-connection-process vec))
3456 (scripts (tramp-get-connection-property p "scripts" nil)))
3457 (unless (member name scripts)
7d520089 3458 (tramp-with-progress-reporter vec 5 (format "Sending script `%s'" name)
03c1ad43
MA
3459 ;; The script could contain a call of Perl. This is masked with `%s'.
3460 (tramp-barf-unless-okay
3461 vec
3462 (format "%s () {\n%s\n}" name
3463 (format script (tramp-get-remote-perl vec)))
3464 "Script %s sending failed" name)
3465 (tramp-set-connection-property p "scripts" (cons name scripts))))))
3466
3467(defun tramp-set-auto-save ()
3468 (when (and ;; ange-ftp has its own auto-save mechanism
3469 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
3470 'tramp-sh-file-name-handler)
3471 auto-save-default)
3472 (auto-save-mode 1)))
3473(add-hook 'find-file-hooks 'tramp-set-auto-save t)
3474(add-hook 'tramp-unload-hook
3475 (lambda ()
3476 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
3477
3478(defun tramp-run-test (switch filename)
3479 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3480Returns the exit code of the `test' program."
3481 (with-parsed-tramp-file-name filename nil
3482 (tramp-send-command-and-check
3483 v
3484 (format
3485 "%s %s %s"
3486 (tramp-get-test-command v)
3487 switch
3488 (tramp-shell-quote-argument localname)))))
3489
3490(defun tramp-run-test2 (format-string file1 file2)
3491 "Run `test'-like program on the remote system, given FILE1, FILE2.
3492FORMAT-STRING contains the program name, switches, and place holders.
3493Returns the exit code of the `test' program. Barfs if the methods,
3494hosts, or files, disagree."
3495 (unless (tramp-equal-remote file1 file2)
3496 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3497 (tramp-error
3498 v 'file-error
3499 "tramp-run-test2 only implemented for same method, user, host")))
3500 (with-parsed-tramp-file-name file1 v1
3501 (with-parsed-tramp-file-name file1 v2
3502 (tramp-send-command-and-check
3503 v1
3504 (format format-string
3505 (tramp-shell-quote-argument v1-localname)
3506 (tramp-shell-quote-argument v2-localname))))))
3507
3508(defun tramp-find-executable
3509 (vec progname dirlist &optional ignore-tilde ignore-path)
3510 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3511First arg VEC specifies the connection, PROGNAME is the program
3512to search for, and DIRLIST gives the list of directories to
3513search. If IGNORE-TILDE is non-nil, directory names starting
3514with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3515only in DIRLIST.
3516
3517Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3518
3519This function expects to be in the right *tramp* buffer."
3520 (with-current-buffer (tramp-get-connection-buffer vec)
3521 (let (result)
3522 ;; Check whether the executable is in $PATH. "which(1)" does not
3523 ;; report always a correct error code; therefore we check the
3524 ;; number of words it returns.
3525 (unless ignore-path
3526 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3527 (goto-char (point-min))
3528 (if (looking-at "^\\s-*1$")
3529 (setq result (concat "\\" progname))))
3530 (unless result
3531 (when ignore-tilde
3532 ;; Remove all ~/foo directories from dirlist. In XEmacs,
3533 ;; `remove' is in CL, and we want to avoid CL dependencies.
3534 (let (newdl d)
3535 (while dirlist
3536 (setq d (car dirlist))
3537 (setq dirlist (cdr dirlist))
3538 (unless (char-equal ?~ (aref d 0))
3539 (setq newdl (cons d newdl))))
3540 (setq dirlist (nreverse newdl))))
3541 (tramp-send-command
3542 vec
3543 (format (concat "while read d; "
3544 "do if test -x $d/%s -a -f $d/%s; "
3545 "then echo tramp_executable $d/%s; "
3546 "break; fi; done <<'EOF'\n"
3547 "%s\nEOF")
3548 progname progname progname (mapconcat 'identity dirlist "\n")))
3549 (goto-char (point-max))
3550 (when (search-backward "tramp_executable " nil t)
3551 (skip-chars-forward "^ ")
3552 (skip-chars-forward " ")
6e060cee 3553 (setq result (buffer-substring (point) (point-at-eol)))))
03c1ad43
MA
3554 result)))
3555
3556(defun tramp-set-remote-path (vec)
3557 "Sets the remote environment PATH to existing directories.
3558I.e., for each directory in `tramp-remote-path', it is tested
3559whether it exists and if so, it is added to the environment
3560variable PATH."
3561 (tramp-message vec 5 (format "Setting $PATH environment variable"))
3562 (tramp-send-command
3563 vec (format "PATH=%s; export PATH"
3564 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3565
3566;; ------------------------------------------------------------
3567;; -- Communication with external shell --
3568;; ------------------------------------------------------------
3569
3570(defun tramp-find-file-exists-command (vec)
3571 "Find a command on the remote host for checking if a file exists.
3572Here, we are looking for a command which has zero exit status if the
3573file exists and nonzero exit status otherwise."
3574 (let ((existing "/")
3575 (nonexisting
3576 (tramp-shell-quote-argument "/ this file does not exist "))
3577 result)
3578 ;; The algorithm is as follows: we try a list of several commands.
3579 ;; For each command, we first run `$cmd /' -- this should return
3580 ;; true, as the root directory always exists. And then we run
3581 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3582 ;; does not exist. This should return false. We use the first
3583 ;; command we find that seems to work.
3584 ;; The list of commands to try is as follows:
3585 ;; `ls -d' This works on most systems, but NetBSD 1.4
3586 ;; has a bug: `ls' always returns zero exit
3587 ;; status, even for files which don't exist.
3588 ;; `test -e' Some Bourne shells have a `test' builtin
3589 ;; which does not know the `-e' option.
3590 ;; `/bin/test -e' For those, the `test' binary on disk normally
3591 ;; provides the option. Alas, the binary
3592 ;; is sometimes `/bin/test' and sometimes it's
3593 ;; `/usr/bin/test'.
3594 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3595 (unless (or
3596 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3597 (tramp-send-command-and-check
3598 vec (format "%s %s" result existing))
3599 (not (tramp-send-command-and-check
3600 vec (format "%s %s" result nonexisting))))
3601 (and (setq result "/bin/test -e")
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 "/usr/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 (format "%s -d" (tramp-get-ls-command vec)))
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 (tramp-error
3617 vec 'file-error "Couldn't find command to check if file exists"))
3618 result))
3619
3620(defun tramp-open-shell (vec shell)
3621 "Opens shell SHELL."
7d520089
SM
3622 (tramp-with-progress-reporter
3623 vec 5 (format "Opening remote shell `%s'" shell)
03c1ad43
MA
3624 ;; Find arguments for this shell.
3625 (let ((tramp-end-of-output tramp-initial-end-of-output)
3626 (alist tramp-sh-extra-args)
3627 item extra-args)
3628 (while (and alist (null extra-args))
3629 (setq item (pop alist))
3630 (when (string-match (car item) shell)
3631 (setq extra-args (cdr item))))
3632 (when extra-args (setq shell (concat shell " " extra-args)))
3633 (tramp-send-command
3634 vec (format "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
3635 (shell-quote-argument tramp-end-of-output) shell)
3636 t))
3637 ;; Setting prompts.
3638 (tramp-send-command
3639 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
3640 (tramp-send-command vec "PS2=''" t)
3641 (tramp-send-command vec "PS3=''" t)
3642 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
3643
3644(defun tramp-find-shell (vec)
3645 "Opens a shell on the remote host which groks tilde expansion."
3646 (unless (tramp-get-connection-property vec "remote-shell" nil)
3647 (let (shell)
3648 (with-current-buffer (tramp-get-buffer vec)
3649 (tramp-send-command vec "echo ~root" t)
3650 (cond
3651 ((or (string-match "^~root$" (buffer-string))
0c33dd17
MA
3652 ;; The default shell (ksh93) of OpenSolaris and Solaris
3653 ;; is buggy. We've got reports for "SunOS 5.10" and
3654 ;; "SunOS 5.11" so far.
3655 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3656 (tramp-get-connection-property vec "uname" "")))
03c1ad43
MA
3657 (setq shell
3658 (or (tramp-find-executable
3659 vec "bash" (tramp-get-remote-path vec) t t)
3660 (tramp-find-executable
3661 vec "ksh" (tramp-get-remote-path vec) t t)))
3662 (unless shell
3663 (tramp-error
3664 vec 'file-error
3665 "Couldn't find a shell which groks tilde expansion"))
3666 (tramp-message
3667 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
3668 (tramp-open-shell vec shell))
3669
3670 (t (tramp-message
3671 vec 5 "Remote `%s' groks tilde expansion, good"
3672 (tramp-set-connection-property
3673 vec "remote-shell"
3674 (tramp-get-method-parameter
3675 (tramp-file-name-method vec) 'tramp-remote-sh)))))))))
3676
3677;; Utility functions.
3678
3679(defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
3680 "Wait for shell prompt and barf if none appears.
3681Looks at process PROC to see if a shell prompt appears in TIMEOUT
3682seconds. If not, it produces an error message with the given ERROR-ARGS."
3683 (unless
3684 (tramp-wait-for-regexp
3685 proc timeout
3686 (format
3687 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
3688 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
3689
3690(defun tramp-open-connection-setup-interactive-shell (proc vec)
3691 "Set up an interactive shell.
3692Mainly sets the prompt and the echo correctly. PROC is the shell
3693process to set up. VEC specifies the connection."
3694 (let ((tramp-end-of-output tramp-initial-end-of-output))
3695 ;; It is useful to set the prompt in the following command because
3696 ;; some people have a setting for $PS1 which /bin/sh doesn't know
3697 ;; about and thus /bin/sh will display a strange prompt. For
3698 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
3699 ;; display the current working directory but /bin/sh will display
3700 ;; a dollar sign. The following command line sets $PS1 to a sane
3701 ;; value, and works under Bourne-ish shells as well as csh-like
3702 ;; shells. Daniel Pittman reports that the unusual positioning of
3703 ;; the single quotes makes it work under `rc', too. We also unset
3704 ;; the variable $ENV because that is read by some sh
3705 ;; implementations (eg, bash when called as sh) on startup; this
6e060cee 3706 ;; way, we avoid the startup file clobbering $PS1. $PROMPT_COMMAND
03c1ad43
MA
3707 ;; is another way to set the prompt in /bin/bash, it must be
3708 ;; discarded as well.
3709 (tramp-open-shell
3710 vec
3711 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-remote-sh))
3712
3713 ;; Disable echo.
3714 (tramp-message vec 5 "Setting up remote shell environment")
3715 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
3716 ;; Check whether the echo has really been disabled. Some
3717 ;; implementations, like busybox of embedded GNU/Linux, don't
3718 ;; support disabling.
3719 (tramp-send-command vec "echo foo" t)
3720 (with-current-buffer (process-buffer proc)
3721 (goto-char (point-min))
3722 (when (looking-at "echo foo")
3723 (tramp-set-connection-property proc "remote-echo" t)
3724 (tramp-message vec 5 "Remote echo still on. Ok.")
3725 ;; Make sure backspaces and their echo are enabled and no line
3726 ;; width magic interferes with them.
3727 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
3728
3729 (tramp-message vec 5 "Setting shell prompt")
3730 (tramp-send-command
3731 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
3732 (tramp-send-command vec "PS2=''" t)
3733 (tramp-send-command vec "PS3=''" t)
3734 (tramp-send-command vec "PROMPT_COMMAND=''" t)
3735
3736 ;; Try to set up the coding system correctly.
3737 ;; CCC this can't be the right way to do it. Hm.
3738 (tramp-message vec 5 "Determining coding system")
3739 (tramp-send-command vec "echo foo ; echo bar" t)
3740 (with-current-buffer (process-buffer proc)
3741 (goto-char (point-min))
3742 (if (featurep 'mule)
3743 ;; Use MULE to select the right EOL convention for communicating
3744 ;; with the process.
3745 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
3746 (cons 'undecided 'undecided)))
3747 cs-decode cs-encode)
3748 (when (symbolp cs) (setq cs (cons cs cs)))
3749 (setq cs-decode (car cs))
3750 (setq cs-encode (cdr cs))
3751 (unless cs-decode (setq cs-decode 'undecided))
3752 (unless cs-encode (setq cs-encode 'undecided))
bd8fadca 3753 (setq cs-encode (tramp-compat-coding-system-change-eol-conversion
03c1ad43
MA
3754 cs-encode 'unix))
3755 (when (search-forward "\r" nil t)
bd8fadca 3756 (setq cs-decode (tramp-compat-coding-system-change-eol-conversion
03c1ad43
MA
3757 cs-decode 'dos)))
3758 (tramp-compat-funcall
3759 'set-buffer-process-coding-system cs-decode cs-encode)
3760 (tramp-message
3761 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
3762 ;; Look for ^M and do something useful if found.
3763 (when (search-forward "\r" nil t)
3764 ;; We have found a ^M but cannot frob the process coding system
3765 ;; because we're running on a non-MULE Emacs. Let's try
3766 ;; stty, instead.
3767 (tramp-send-command vec "stty -onlcr" t))))
aa095b2d 3768
03c1ad43
MA
3769 (tramp-send-command vec "set +o vi +o emacs" t)
3770
3771 ;; Check whether the output of "uname -sr" has been changed. If
3772 ;; yes, this is a strong indication that we must expire all
3773 ;; connection properties. We start again with
3774 ;; `tramp-maybe-open-connection', it will be catched there.
3775 (tramp-message vec 5 "Checking system information")
3776 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
3777 (new-uname
3778 (tramp-set-connection-property
3779 vec "uname"
3780 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
3781 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
3782 (with-current-buffer (tramp-get-debug-buffer vec)
3783 ;; Keep the debug buffer.
3784 (rename-buffer
3785 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
4bc3c53d 3786 (tramp-cleanup-connection vec)
03c1ad43
MA
3787 (if (= (point-min) (point-max))
3788 (kill-buffer nil)
3789 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
3790 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
3791 (tramp-get-buffer vec)
3792 (tramp-message
3793 vec 3
3794 "Connection reset, because remote host changed from `%s' to `%s'"
3795 old-uname new-uname)
3796 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
3797
3798 ;; Check whether the remote host suffers from buggy
3799 ;; `send-process-string'. This is known for FreeBSD (see comment in
3800 ;; `send_process', file process.c). I've tested sending 624 bytes
3801 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
3802 ;; this host type is detected locally. It cannot handle remote
3803 ;; hosts, though.
3804 (with-connection-property proc "chunksize"
3805 (cond
3806 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
3807 tramp-chunksize)
3808 (t
3809 (tramp-message
3810 vec 5 "Checking remote host type for `send-process-string' bug")
3811 (if (string-match
3812 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
3813 500 0))))
3814
3815 ;; Set remote PATH variable.
3816 (tramp-set-remote-path vec)
3817
3818 ;; Search for a good shell before searching for a command which
3819 ;; checks if a file exists. This is done because Tramp wants to use
3820 ;; "test foo; echo $?" to check if various conditions hold, and
3821 ;; there are buggy /bin/sh implementations which don't execute the
3822 ;; "echo $?" part if the "test" part has an error. In particular,
3823 ;; the OpenSolaris /bin/sh is a problem. There are also other
3824 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
3825 ;; in function declarations, or changing HISTFILE in place.
3826 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
3827 ;; detected.
3828 (tramp-find-shell vec)
3829
3830 ;; Disable unexpected output.
3831 (tramp-send-command vec "mesg n; biff n" t)
3832
3833 ;; IRIX64 bash expands "!" even when in single quotes. This
3834 ;; destroys our shell functions, we must disable it. See
3835 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
3836 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
3837 (tramp-send-command vec "set +H" t))
3838
aa095b2d
MA
3839 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
3840 (when (string-match "BSD\\|Darwin"
3841 (tramp-get-connection-property vec "uname" ""))
3842 (tramp-send-command vec "stty -oxtabs" t))
3843
03c1ad43 3844 ;; Set `remote-tty' process property.
6d95bd46
MA
3845 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
3846 (unless (zerop (length tty))
3847 (tramp-compat-process-put proc 'remote-tty tty)))
03c1ad43 3848
aa095b2d
MA
3849 ;; Dump stty settings in the traces.
3850 (when (>= tramp-verbose 9)
3851 (tramp-send-command vec "stty -a" t))
3852
03c1ad43
MA
3853 ;; Set the environment.
3854 (tramp-message vec 5 "Setting default environment")
3855
3856 (let ((env (copy-sequence tramp-remote-process-environment))
3857 unset item)
3858 (while env
3859 (setq item (tramp-compat-split-string (car env) "="))
3860 (setcdr item (mapconcat 'identity (cdr item) "="))
3861 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
3862 (tramp-send-command
3863 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
3864 (push (car item) unset))
3865 (setq env (cdr env)))
3866 (when unset
3867 (tramp-send-command
3868 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
3869
3870;; CCC: We should either implement a Perl version of base64 encoding
3871;; and decoding. Then we just use that in the last item. The other
3872;; alternative is to use the Perl version of UU encoding. But then
3873;; we need a Lisp version of uuencode.
3874;;
3875;; Old text from documentation of tramp-methods:
3876;; Using a uuencode/uudecode inline method is discouraged, please use one
3877;; of the base64 methods instead since base64 encoding is much more
3878;; reliable and the commands are more standardized between the different
3879;; Unix versions. But if you can't use base64 for some reason, please
3880;; note that the default uudecode command does not work well for some
3881;; Unices, in particular AIX and Irix. For AIX, you might want to use
3882;; the following command for uudecode:
3883;;
3884;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
3885;;
3886;; For Irix, no solution is known yet.
3887
3888(autoload 'uudecode-decode-region "uudecode")
3889
3890(defconst tramp-local-coding-commands
3891 '((b64 base64-encode-region base64-decode-region)
3892 (uu tramp-uuencode-region uudecode-decode-region)
3893 (pack
3894 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
3895 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
3896 "List of local coding commands for inline transfer.
3897Each item is a list that looks like this:
3898
3899\(FORMAT ENCODING DECODING\)
3900
3901FORMAT is symbol describing the encoding/decoding format. It can be
3902`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
3903
3904ENCODING and DECODING can be strings, giving commands, or symbols,
3905giving functions. If they are strings, then they can contain
3906the \"%s\" format specifier. If that specifier is present, the input
3907filename will be put into the command line at that spot. If the
3908specifier is not present, the input should be read from standard
3909input.
3910
3911If they are functions, they will be called with two arguments, start
3912and end of region, and are expected to replace the region contents
3913with the encoded or decoded results, respectively.")
3914
3915(defconst tramp-remote-coding-commands
6e060cee
MA
3916 '((b64 "base64" "base64 -d -i")
3917 ;; "-i" is more robust with older base64 from GNU coreutils.
3918 ;; However, I don't know whether all base64 versions do supports
3919 ;; this option.
3920 (b64 "base64" "base64 -d")
03c1ad43
MA
3921 (b64 "mimencode -b" "mimencode -u -b")
3922 (b64 "mmencode -b" "mmencode -u -b")
3923 (b64 "recode data..base64" "recode base64..data")
3924 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
3925 (b64 tramp-perl-encode tramp-perl-decode)
3926 (uu "uuencode xxx" "uudecode -o /dev/stdout")
3927 (uu "uuencode xxx" "uudecode -o -")
3928 (uu "uuencode xxx" "uudecode -p")
3929 (uu "uuencode xxx" tramp-uudecode)
3930 (pack
3931 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
3932 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
3933 "List of remote coding commands for inline transfer.
3934Each item is a list that looks like this:
3935
3936\(FORMAT ENCODING DECODING\)
3937
3938FORMAT is symbol describing the encoding/decoding format. It can be
3939`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
3940
3941ENCODING and DECODING can be strings, giving commands, or symbols,
3942giving variables. If they are strings, then they can contain
3943the \"%s\" format specifier. If that specifier is present, the input
3944filename will be put into the command line at that spot. If the
3945specifier is not present, the input should be read from standard
3946input.
3947
3948If they are variables, this variable is a string containing a Perl
3949implementation for this functionality. This Perl program will be transferred
3950to the remote host, and it is available as shell function with the same name.")
3951
3952(defun tramp-find-inline-encoding (vec)
3953 "Find an inline transfer encoding that works.
3954Goes through the list `tramp-local-coding-commands' and
3955`tramp-remote-coding-commands'."
3956 (save-excursion
3957 (let ((local-commands tramp-local-coding-commands)
3958 (magic "xyzzy")
3959 loc-enc loc-dec rem-enc rem-dec litem ritem found)
3960 (while (and local-commands (not found))
3961 (setq litem (pop local-commands))
3962 (catch 'wont-work-local
3963 (let ((format (nth 0 litem))
3964 (remote-commands tramp-remote-coding-commands))
3965 (setq loc-enc (nth 1 litem))
3966 (setq loc-dec (nth 2 litem))
3967 ;; If the local encoder or decoder is a string, the
3968 ;; corresponding command has to work locally.
3969 (if (not (stringp loc-enc))
3970 (tramp-message
3971 vec 5 "Checking local encoding function `%s'" loc-enc)
3972 (tramp-message
3973 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
3974 (unless (zerop (tramp-call-local-coding-command
3975 loc-enc nil nil))
3976 (throw 'wont-work-local nil)))
3977 (if (not (stringp loc-dec))
3978 (tramp-message
3979 vec 5 "Checking local decoding function `%s'" loc-dec)
3980 (tramp-message
3981 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
3982 (unless (zerop (tramp-call-local-coding-command
3983 loc-dec nil nil))
3984 (throw 'wont-work-local nil)))
3985 ;; Search for remote coding commands with the same format
3986 (while (and remote-commands (not found))
3987 (setq ritem (pop remote-commands))
3988 (catch 'wont-work-remote
3989 (when (equal format (nth 0 ritem))
3990 (setq rem-enc (nth 1 ritem))
3991 (setq rem-dec (nth 2 ritem))
3992 ;; Check if remote encoding and decoding commands can be
3993 ;; called remotely with null input and output. This makes
3994 ;; sure there are no syntax errors and the command is really
3995 ;; found. Note that we do not redirect stdout to /dev/null,
3996 ;; for two reasons: when checking the decoding command, we
3997 ;; actually check the output it gives. And also, when
3998 ;; redirecting "mimencode" output to /dev/null, then as root
3999 ;; it might change the permissions of /dev/null!
4000 (when (not (stringp rem-enc))
4001 (let ((name (symbol-name rem-enc)))
4002 (while (string-match (regexp-quote "-") name)
4003 (setq name (replace-match "_" nil t name)))
4004 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4005 (setq rem-enc name)))
4006 (tramp-message
4007 vec 5
4008 "Checking remote encoding command `%s' for sanity" rem-enc)
4009 (unless (tramp-send-command-and-check
4010 vec (format "%s </dev/null" rem-enc) t)
4011 (throw 'wont-work-remote nil))
4012
4013 (when (not (stringp rem-dec))
4014 (let ((name (symbol-name rem-dec)))
4015 (while (string-match (regexp-quote "-") name)
4016 (setq name (replace-match "_" nil t name)))
4017 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
4018 (setq rem-dec name)))
4019 (tramp-message
4020 vec 5
4021 "Checking remote decoding command `%s' for sanity" rem-dec)
4022 (unless (tramp-send-command-and-check
4023 vec
4024 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4025 t)
4026 (throw 'wont-work-remote nil))
4027
4028 (with-current-buffer (tramp-get-buffer vec)
4029 (goto-char (point-min))
4030 (unless (looking-at (regexp-quote magic))
4031 (throw 'wont-work-remote nil)))
4032
4033 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4034 (setq rem-enc (nth 1 ritem))
4035 (setq rem-dec (nth 2 ritem))
4036 (setq found t)))))))
4037
4038 ;; Did we find something?
4039 (unless found
4040 (tramp-error
4041 vec 'file-error "Couldn't find an inline transfer encoding"))
4042
4043 ;; Set connection properties.
4044 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4045 (tramp-set-connection-property vec "local-encoding" loc-enc)
4046 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4047 (tramp-set-connection-property vec "local-decoding" loc-dec)
4048 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4049 (tramp-set-connection-property vec "remote-encoding" rem-enc)
4050 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4051 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
4052
4053(defun tramp-call-local-coding-command (cmd input output)
4054 "Call the local encoding or decoding command.
4055If CMD contains \"%s\", provide input file INPUT there in command.
4056Otherwise, INPUT is passed via standard input.
4057INPUT can also be nil which means `/dev/null'.
4058OUTPUT can be a string (which specifies a filename), or t (which
4059means standard output and thus the current buffer), or nil (which
4060means discard it)."
4061 (tramp-compat-call-process
4062 tramp-encoding-shell
4063 (when (and input (not (string-match "%s" cmd))) input)
4064 (if (eq output t) t nil)
4065 nil
4066 tramp-encoding-command-switch
4067 (concat
4068 (if (string-match "%s" cmd) (format cmd input) cmd)
4069 (if (stringp output) (concat "> " output) ""))))
4070
4071(defconst tramp-inline-compress-commands
4072 '(("gzip" "gzip -d")
4073 ("bzip2" "bzip2 -d")
4074 ("compress" "compress -d"))
4075 "List of compress and decompress commands for inline transfer.
4076Each item is a list that looks like this:
4077
4078\(COMPRESS DECOMPRESS\)
4079
4080COMPRESS or DECOMPRESS are strings with the respective commands.")
4081
4082(defun tramp-find-inline-compress (vec)
4083 "Find an inline transfer compress command that works.
4084Goes through the list `tramp-inline-compress-commands'."
4085 (save-excursion
4086 (let ((commands tramp-inline-compress-commands)
4087 (magic "xyzzy")
4088 item compress decompress
4089 found)
4090 (while (and commands (not found))
4091 (catch 'next
4092 (setq item (pop commands)
4093 compress (nth 0 item)
4094 decompress (nth 1 item))
4095 (tramp-message
4096 vec 5
4097 "Checking local compress command `%s', `%s' for sanity"
4098 compress decompress)
362b9d48
GM
4099 (unless
4100 (zerop
4101 (tramp-call-local-coding-command
4102 (format
4103 ;; Windows shells need the program file name after
4104 ;; the pipe symbol be quoted if they use forward
4105 ;; slashes as directory separators.
4106 (if (memq system-type '(windows-nt))
4107 "echo %s | \"%s\" | \"%s\""
4108 "echo %s | %s | %s")
4109 magic compress decompress) nil nil))
03c1ad43
MA
4110 (throw 'next nil))
4111 (tramp-message
4112 vec 5
4113 "Checking remote compress command `%s', `%s' for sanity"
4114 compress decompress)
4115 (unless (tramp-send-command-and-check
4116 vec (format "echo %s | %s | %s" magic compress decompress) t)
4117 (throw 'next nil))
4118 (setq found t)))
4119
4120 ;; Did we find something?
4121 (if found
4122 (progn
4123 ;; Set connection properties.
4124 (tramp-message
4125 vec 5 "Using inline transfer compress command `%s'" compress)
4126 (tramp-set-connection-property vec "inline-compress" compress)
4127 (tramp-message
4128 vec 5 "Using inline transfer decompress command `%s'" decompress)
4129 (tramp-set-connection-property vec "inline-decompress" decompress))
4130
4131 (tramp-set-connection-property vec "inline-compress" nil)
4132 (tramp-set-connection-property vec "inline-decompress" nil)
4133 (tramp-message
4134 vec 2 "Couldn't find an inline transfer compress command")))))
4135
4136(defun tramp-compute-multi-hops (vec)
4137 "Expands VEC according to `tramp-default-proxies-alist'.
4138Gateway hops are already opened."
4139 (let ((target-alist `(,vec))
4140 (choices tramp-default-proxies-alist)
4141 item proxy)
4142
4143 ;; Look for proxy hosts to be passed.
4144 (while choices
4145 (setq item (pop choices)
4146 proxy (eval (nth 2 item)))
4147 (when (and
4148 ;; host
4149 (string-match (or (eval (nth 0 item)) "")
4150 (or (tramp-file-name-host (car target-alist)) ""))
4151 ;; user
4152 (string-match (or (eval (nth 1 item)) "")
4153 (or (tramp-file-name-user (car target-alist)) "")))
4154 (if (null proxy)
4155 ;; No more hops needed.
4156 (setq choices nil)
4157 ;; Replace placeholders.
4158 (setq proxy
4159 (format-spec
4160 proxy
4161 (format-spec-make
4162 ?u (or (tramp-file-name-user (car target-alist)) "")
4163 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4164 (with-parsed-tramp-file-name proxy l
4165 ;; Add the hop.
4166 (add-to-list 'target-alist l)
4167 ;; Start next search.
4168 (setq choices tramp-default-proxies-alist)))))
4169
4170 ;; Handle gateways.
4171 (when (string-match
4172 (format
4173 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4174 (tramp-file-name-method (car target-alist)))
4175 (let ((gw (pop target-alist))
4176 (hop (pop target-alist)))
4177 ;; Is the method prepared for gateways?
66feec8b 4178 (unless (tramp-file-name-port hop)
03c1ad43
MA
4179 (tramp-error
4180 vec 'file-error
66feec8b 4181 "Connection `%s' is not supported for gateway access." hop))
03c1ad43
MA
4182 ;; Open the gateway connection.
4183 (add-to-list
4184 'target-alist
4185 (vector
4186 (tramp-file-name-method hop) (tramp-file-name-user hop)
4187 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil))
4188 ;; For the password prompt, we need the correct values.
4189 ;; Therefore, we must remember the gateway vector. But we
4190 ;; cannot do it as connection property, because it shouldn't
4191 ;; be persistent. And we have no started process yet either.
4192 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
4193
4194 ;; Foreign and out-of-band methods are not supported for multi-hops.
4195 (when (cdr target-alist)
4196 (setq choices target-alist)
4197 (while choices
4198 (setq item (pop choices))
4199 (when
4200 (or
4201 (not
4202 (tramp-get-method-parameter
4203 (tramp-file-name-method item) 'tramp-login-program))
4204 (tramp-get-method-parameter
4205 (tramp-file-name-method item) 'tramp-copy-program))
4206 (tramp-error
4207 vec 'file-error
4208 "Method `%s' is not supported for multi-hops."
4209 (tramp-file-name-method item)))))
4210
4211 ;; In case the host name is not used for the remote shell
4212 ;; command, the user could be misguided by applying a random
4213 ;; hostname.
4214 (let* ((v (car target-alist))
4215 (method (tramp-file-name-method v))
4216 (host (tramp-file-name-host v)))
4217 (unless
4218 (or
4219 ;; There are multi-hops.
4220 (cdr target-alist)
4221 ;; The host name is used for the remote shell command.
4222 (member
4223 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
4224 ;; The host is local. We cannot use `tramp-local-host-p'
4225 ;; here, because it opens a connection as well.
4226 (string-match tramp-local-host-regexp host))
4227 (tramp-error
4228 v 'file-error
4229 "Host `%s' looks like a remote host, `%s' can only use the local host"
4230 host method)))
4231
4232 ;; Result.
4233 target-alist))
4234
4235(defun tramp-maybe-open-connection (vec)
4236 "Maybe open a connection VEC.
4237Does not do anything if a connection is already open, but re-opens the
4238connection if a previous connection has died for some reason."
4239 (catch 'uname-changed
4240 (let ((p (tramp-get-connection-process vec))
4241 (process-name (tramp-get-connection-property vec "process-name" nil))
bfd31217
MA
4242 (process-environment (copy-sequence process-environment))
4243 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
03c1ad43
MA
4244
4245 ;; If too much time has passed since last command was sent, look
4246 ;; whether process is still alive. If it isn't, kill it. When
4247 ;; using ssh, it can sometimes happen that the remote end has
4248 ;; hung up but the local ssh client doesn't recognize this until
4249 ;; it tries to send some data to the remote end. So that's why
4250 ;; we try to send a command from time to time, then look again
4251 ;; whether the process is really alive.
4252 (condition-case nil
4253 (when (and (> (tramp-time-diff
4254 (current-time)
4255 (tramp-get-connection-property
4256 p "last-cmd-time" '(0 0 0)))
4257 60)
4258 p (processp p) (memq (process-status p) '(run open)))
4259 (tramp-send-command vec "echo are you awake" t t)
4260 (unless (and (memq (process-status p) '(run open))
4261 (tramp-wait-for-output p 10))
4262 ;; The error will be catched locally.
4263 (tramp-error vec 'file-error "Awake did fail")))
4264 (file-error
4265 (tramp-flush-connection-property vec)
4266 (tramp-flush-connection-property p)
4267 (delete-process p)
4268 (setq p nil)))
4269
4270 ;; New connection must be opened.
4271 (unless (and p (processp p) (memq (process-status p) '(run open)))
4272
4273 ;; We call `tramp-get-buffer' in order to get a debug buffer for
4274 ;; messages from the beginning.
4275 (tramp-get-buffer vec)
7d520089 4276 (tramp-with-progress-reporter
03c1ad43
MA
4277 vec 3
4278 (if (zerop (length (tramp-file-name-user vec)))
4279 (format "Opening connection for %s using %s"
4280 (tramp-file-name-host vec)
4281 (tramp-file-name-method vec))
4282 (format "Opening connection for %s@%s using %s"
4283 (tramp-file-name-user vec)
4284 (tramp-file-name-host vec)
4285 (tramp-file-name-method vec)))
4286
4287 ;; Start new process.
4288 (when (and p (processp p))
4289 (delete-process p))
4290 (setenv "TERM" tramp-terminal-type)
4291 (setenv "LC_ALL" "C")
4292 (setenv "PROMPT_COMMAND")
4293 (setenv "PS1" tramp-initial-end-of-output)
4294 (let* ((target-alist (tramp-compute-multi-hops vec))
4295 (process-connection-type tramp-process-connection-type)
4296 (process-adaptive-read-buffering nil)
4297 (coding-system-for-read nil)
4298 ;; This must be done in order to avoid our file name handler.
4299 (p (let ((default-directory
4300 (tramp-compat-temporary-file-directory)))
36b148cf
MA
4301 (apply
4302 'start-process
66feec8b 4303 (tramp-get-connection-name vec)
03c1ad43 4304 (tramp-get-connection-buffer vec)
36b148cf
MA
4305 (if tramp-encoding-command-interactive
4306 (list tramp-encoding-shell
4307 tramp-encoding-command-interactive)
4308 (list tramp-encoding-shell))))))
03c1ad43 4309
6d95bd46
MA
4310 ;; Set sentinel and query flag.
4311 (tramp-set-connection-property p "vector" vec)
4312 (set-process-sentinel p 'tramp-process-sentinel)
4313 (tramp-compat-set-process-query-on-exit-flag p nil)
4314
03c1ad43
MA
4315 (tramp-message
4316 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4317
4318 ;; Check whether process is alive.
03c1ad43
MA
4319 (tramp-barf-if-no-shell-prompt
4320 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
4321
4322 ;; Now do all the connections as specified.
4323 (while target-alist
4324 (let* ((hop (car target-alist))
4325 (l-method (tramp-file-name-method hop))
4326 (l-user (tramp-file-name-user hop))
4327 (l-host (tramp-file-name-host hop))
4328 (l-port nil)
4329 (login-program
4330 (tramp-get-method-parameter
4331 l-method 'tramp-login-program))
4332 (login-args
4333 (tramp-get-method-parameter l-method 'tramp-login-args))
4334 (async-args
4335 (tramp-get-method-parameter l-method 'tramp-async-args))
4336 (gw-args
4337 (tramp-get-method-parameter l-method 'tramp-gw-args))
4338 (gw (tramp-get-file-property hop "" "gateway" nil))
4339 (g-method (and gw (tramp-file-name-method gw)))
4340 (g-user (and gw (tramp-file-name-user gw)))
4341 (g-host (and gw (tramp-file-name-host gw)))
4342 (command login-program)
4343 ;; We don't create the temporary file. In fact,
4344 ;; it is just a prefix for the ControlPath option
4345 ;; of ssh; the real temporary file has another
4346 ;; name, and it is created and protected by ssh.
2c68ca0e 4347 ;; It is also removed by ssh when the connection
03c1ad43
MA
4348 ;; is closed.
4349 (tmpfile
4350 (tramp-set-connection-property
4351 p "temp-file"
4352 (make-temp-name
4353 (expand-file-name
4354 tramp-temp-name-prefix
4355 (tramp-compat-temporary-file-directory)))))
4356 spec)
4357
4358 ;; Add arguments for asynchrononous processes.
4359 (when (and process-name async-args)
4360 (setq login-args (append async-args login-args)))
4361
4362 ;; Add gateway arguments if necessary.
4363 (when (and gw gw-args)
4364 (setq login-args (append gw-args login-args)))
4365
4366 ;; Check for port number. Until now, there's no need
4367 ;; for handling like method, user, host.
4368 (when (string-match tramp-host-with-port-regexp l-host)
4369 (setq l-port (match-string 2 l-host)
4370 l-host (match-string 1 l-host)))
4371
4372 ;; Set variables for computing the prompt for reading
4373 ;; password. They can also be derived from a gateway.
4374 (setq tramp-current-method (or g-method l-method)
4375 tramp-current-user (or g-user l-user)
4376 tramp-current-host (or g-host l-host))
4377
4378 ;; Replace login-args place holders.
4379 (setq
4380 l-host (or l-host "")
4381 l-user (or l-user "")
4382 l-port (or l-port "")
4383 spec (format-spec-make
4384 ?h l-host ?u l-user ?p l-port ?t tmpfile)
4385 command
4386 (concat
4387 ;; We do not want to see the trailing local prompt in
4388 ;; `start-file-process'.
4389 (unless (memq system-type '(windows-nt)) "exec ")
4390 command " "
4391 (mapconcat
4392 (lambda (x)
4393 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4394 (unless (member "" x) (mapconcat 'identity x " ")))
4395 login-args " ")
4396 ;; Local shell could be a Windows COMSPEC. It
4397 ;; doesn't know the ";" syntax, but we must exit
4398 ;; always for `start-file-process'. "exec" does not
4399 ;; work either.
4400 (if (memq system-type '(windows-nt)) " && exit || exit")))
4401
4402 ;; Send the command.
4403 (tramp-message vec 3 "Sending command `%s'" command)
4404 (tramp-send-command vec command t t)
bfd31217 4405 (tramp-process-actions p vec pos tramp-actions-before-shell 60)
03c1ad43
MA
4406 (tramp-message
4407 vec 3 "Found remote shell prompt on `%s'" l-host))
4408 ;; Next hop.
4409 (setq target-alist (cdr target-alist)))
4410
4411 ;; Make initial shell settings.
4412 (tramp-open-connection-setup-interactive-shell p vec)))))))
4413
4414(defun tramp-send-command (vec command &optional neveropen nooutput)
4415 "Send the COMMAND to connection VEC.
4416Erases temporary buffer before sending the command. If optional
4417arg NEVEROPEN is non-nil, never try to open the connection. This
4418is meant to be used from `tramp-maybe-open-connection' only. The
4419function waits for output unless NOOUTPUT is set."
4420 (unless neveropen (tramp-maybe-open-connection vec))
4421 (let ((p (tramp-get-connection-process vec)))
4422 (when (tramp-get-connection-property p "remote-echo" nil)
4423 ;; We mark the command string that it can be erased in the output buffer.
4424 (tramp-set-connection-property p "check-remote-echo" t)
4425 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
01d884cf 4426 (when (string-match "<<'EOF'" command)
6e060cee
MA
4427 ;; Unset $PS1 when using here documents, in order to avoid
4428 ;; multiple prompts.
01d884cf
MA
4429 (setq command (concat "(PS1= ; " command "\n)")))
4430 ;; Send the command.
03c1ad43
MA
4431 (tramp-message vec 6 "%s" command)
4432 (tramp-send-string vec command)
4433 (unless nooutput (tramp-wait-for-output p))))
4434
4435(defun tramp-wait-for-output (proc &optional timeout)
4436 "Wait for output from remote command."
4437 (unless (buffer-live-p (process-buffer proc))
4438 (delete-process proc)
4439 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4440 (with-current-buffer (process-buffer proc)
4441 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4442 ;; be leading escape sequences, which must be ignored.
4443 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
4444 ;; Sometimes, the commands do not return a newline but a
4445 ;; null byte before the shell prompt, for example "git
4446 ;; ls-files -c -z ...".
4447 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4448 (found (tramp-wait-for-regexp proc timeout regexp1)))
4449 (if found
4450 (let (buffer-read-only)
4451 ;; A simple-minded busybox has sent " ^H" sequences.
4452 ;; Delete them.
4453 (goto-char (point-min))
6e060cee 4454 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
03c1ad43
MA
4455 (forward-line 1)
4456 (delete-region (point-min) (point)))
4457 ;; Delete the prompt.
4458 (goto-char (point-max))
4459 (re-search-backward regexp nil t)
4460 (delete-region (point) (point-max)))
4461 (if timeout
4462 (tramp-error
4463 proc 'file-error
4464 "[[Remote prompt `%s' not found in %d secs]]"
4465 tramp-end-of-output timeout)
4466 (tramp-error
4467 proc 'file-error
4468 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
4469 ;; Return value is whether end-of-output sentinel was found.
4470 found)))
4471
4472(defun tramp-send-command-and-check
4473 (vec command &optional subshell dont-suppress-err)
4474 "Run COMMAND and check its exit status.
4475Sends `echo $?' along with the COMMAND for checking the exit status. If
4476COMMAND is nil, just sends `echo $?'. Returns the exit status found.
4477
4478If the optional argument SUBSHELL is non-nil, the command is
4479executed in a subshell, ie surrounded by parentheses. If
4480DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
4481 (tramp-send-command
4482 vec
4483 (concat (if subshell "( " "")
4484 command
4485 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
4486 "echo tramp_exit_status $?"
4487 (if subshell " )" "")))
4488 (with-current-buffer (tramp-get-connection-buffer vec)
4489 (goto-char (point-max))
4490 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
4491 (tramp-error
4492 vec 'file-error "Couldn't find exit status of `%s'" command))
4493 (skip-chars-forward "^ ")
4494 (prog1
4495 (zerop (read (current-buffer)))
4496 (let (buffer-read-only)
4497 (delete-region (match-beginning 0) (point-max))))))
4498
4499(defun tramp-barf-unless-okay (vec command fmt &rest args)
4500 "Run COMMAND, check exit status, throw error if exit status not okay.
4501Similar to `tramp-send-command-and-check' but accepts two more arguments
4502FMT and ARGS which are passed to `error'."
4503 (unless (tramp-send-command-and-check vec command)
4504 (apply 'tramp-error vec 'file-error fmt args)))
4505
6d95bd46 4506(defun tramp-send-command-and-read (vec command &optional noerror)
03c1ad43 4507 "Run COMMAND and return the output, which must be a Lisp expression.
6d95bd46
MA
4508In case there is no valid Lisp expression and NOERROR is nil, it
4509raises an error."
03c1ad43
MA
4510 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
4511 (with-current-buffer (tramp-get-connection-buffer vec)
4512 ;; Read the expression.
4513 (goto-char (point-min))
4514 (condition-case nil
4515 (prog1 (read (current-buffer))
4516 ;; Error handling.
6e060cee 4517 (when (re-search-forward "\\S-" (point-at-eol) t)
03c1ad43 4518 (error nil)))
6d95bd46
MA
4519 (error (unless noerror
4520 (tramp-error
4521 vec 'file-error
4522 "`%s' does not return a valid Lisp expression: `%s'"
4523 command (buffer-string)))))))
03c1ad43 4524
03c1ad43
MA
4525(defun tramp-convert-file-attributes (vec attr)
4526 "Convert file-attributes ATTR generated by perl script, stat or ls.
4527Convert file mode bits to string and set virtual device number.
4528Return ATTR."
4529 (when attr
6d95bd46
MA
4530 ;; Remove color escape sequences from symlink.
4531 (when (stringp (car attr))
4532 (while (string-match tramp-color-escape-sequence-regexp (car attr))
4533 (setcar attr (replace-match "" nil nil (car attr)))))
03c1ad43
MA
4534 ;; Convert last access time.
4535 (unless (listp (nth 4 attr))
4536 (setcar (nthcdr 4 attr)
4537 (list (floor (nth 4 attr) 65536)
4538 (floor (mod (nth 4 attr) 65536)))))
4539 ;; Convert last modification time.
4540 (unless (listp (nth 5 attr))
4541 (setcar (nthcdr 5 attr)
4542 (list (floor (nth 5 attr) 65536)
4543 (floor (mod (nth 5 attr) 65536)))))
4544 ;; Convert last status change time.
4545 (unless (listp (nth 6 attr))
4546 (setcar (nthcdr 6 attr)
4547 (list (floor (nth 6 attr) 65536)
4548 (floor (mod (nth 6 attr) 65536)))))
4549 ;; Convert file size.
4550 (when (< (nth 7 attr) 0)
4551 (setcar (nthcdr 7 attr) -1))
4552 (when (and (floatp (nth 7 attr))
4553 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
4554 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
4555 ;; Convert file mode bits to string.
4556 (unless (stringp (nth 8 attr))
4557 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
4558 (when (stringp (car attr))
4559 (aset (nth 8 attr) 0 ?l)))
4560 ;; Convert directory indication bit.
4561 (when (string-match "^d" (nth 8 attr))
4562 (setcar attr t))
4563 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
4564 (when (consp (car attr))
4565 (if (and (stringp (caar attr))
4566 (string-match ".+ -> .\\(.+\\)." (caar attr)))
4567 (setcar attr (match-string 1 (caar attr)))
4568 (setcar attr nil)))
4569 ;; Set file's gid change bit.
4570 (setcar (nthcdr 9 attr)
4571 (if (numberp (nth 3 attr))
4572 (not (= (nth 3 attr)
4573 (tramp-get-remote-gid vec 'integer)))
4574 (not (string-equal
4575 (nth 3 attr)
4576 (tramp-get-remote-gid vec 'string)))))
4577 ;; Convert inode.
4578 (unless (listp (nth 10 attr))
4579 (setcar (nthcdr 10 attr)
4580 (condition-case nil
4581 (cons (floor (nth 10 attr) 65536)
4582 (floor (mod (nth 10 attr) 65536)))
4583 ;; Inodes can be incredible huge. We must hide this.
4584 (error (tramp-get-inode vec)))))
4585 ;; Set virtual device number.
4586 (setcar (nthcdr 11 attr)
4587 (tramp-get-device vec))
4588 attr))
4589
4590(defun tramp-check-cached-permissions (vec access)
4591 "Check `file-attributes' caches for VEC.
4592Return t if according to the cache access type ACCESS is known to
4593be granted."
4594 (let ((result nil)
4595 (offset (cond
4596 ((eq ?r access) 1)
4597 ((eq ?w access) 2)
4598 ((eq ?x access) 3))))
4599 (dolist (suffix '("string" "integer") result)
4600 (setq
4601 result
4602 (or
4603 result
4604 (let ((file-attr
4605 (tramp-get-file-property
4606 vec (tramp-file-name-localname vec)
4607 (concat "file-attributes-" suffix) nil))
4608 (remote-uid
4609 (tramp-get-connection-property
4610 vec (concat "uid-" suffix) nil))
4611 (remote-gid
4612 (tramp-get-connection-property
4613 vec (concat "gid-" suffix) nil)))
4614 (and
4615 file-attr
4616 (or
4617 ;; Not a symlink
4618 (eq t (car file-attr))
4619 (null (car file-attr)))
4620 (or
4621 ;; World accessible.
4622 (eq access (aref (nth 8 file-attr) (+ offset 6)))
4623 ;; User accessible and owned by user.
4624 (and
4625 (eq access (aref (nth 8 file-attr) offset))
4626 (equal remote-uid (nth 2 file-attr)))
4627 ;; Group accessible and owned by user's
4628 ;; principal group.
4629 (and
4630 (eq access (aref (nth 8 file-attr) (+ offset 3)))
4631 (equal remote-gid (nth 3 file-attr)))))))))))
4632
4633(defun tramp-file-mode-from-int (mode)
4634 "Turn an integer representing a file mode into an ls(1)-like string."
4635 (let ((type (cdr
4636 (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
4637 (user (logand (lsh mode -6) 7))
4638 (group (logand (lsh mode -3) 7))
4639 (other (logand (lsh mode -0) 7))
4640 (suid (> (logand (lsh mode -9) 4) 0))
4641 (sgid (> (logand (lsh mode -9) 2) 0))
4642 (sticky (> (logand (lsh mode -9) 1) 0)))
4643 (setq user (tramp-file-mode-permissions user suid "s"))
4644 (setq group (tramp-file-mode-permissions group sgid "s"))
4645 (setq other (tramp-file-mode-permissions other sticky "t"))
4646 (concat type user group other)))
4647
4648(defun tramp-file-mode-permissions (perm suid suid-text)
4649 "Convert a permission bitset into a string.
4650This is used internally by `tramp-file-mode-from-int'."
4651 (let ((r (> (logand perm 4) 0))
4652 (w (> (logand perm 2) 0))
4653 (x (> (logand perm 1) 0)))
4654 (concat (or (and r "r") "-")
4655 (or (and w "w") "-")
4656 (or (and suid x suid-text) ; suid, execute
4657 (and suid (upcase suid-text)) ; suid, !execute
4658 (and x "x") "-")))) ; !suid
4659
4660(defun tramp-shell-case-fold (string)
4661 "Converts STRING to shell glob pattern which ignores case."
4662 (mapconcat
4663 (lambda (c)
4664 (if (equal (downcase c) (upcase c))
4665 (vector c)
4666 (format "[%c%c]" (downcase c) (upcase c))))
4667 string
4668 ""))
4669
4670(defun tramp-make-copy-program-file-name (vec)
4671 "Create a file name suitable to be passed to `rcp' and workalikes."
4672 (let ((user (tramp-file-name-user vec))
4673 (host (tramp-file-name-real-host vec))
4674 (localname (tramp-shell-quote-argument
4675 (tramp-file-name-localname vec))))
4676 (if (not (zerop (length user)))
4677 (format "%s@%s:%s" user host localname)
4678 (format "%s:%s" host localname))))
4679
4680(defun tramp-method-out-of-band-p (vec size)
4681 "Return t if this is an out-of-band method, nil otherwise."
4682 (and
4683 ;; It shall be an out-of-band method.
4684 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
d59eb518
MA
4685 ;; There must be a size, otherwise the file doesn't exist.
4686 (numberp size)
03c1ad43
MA
4687 ;; Either the file size is large enough, or (in rare cases) there
4688 ;; does not exist a remote encoding.
4689 (or (null tramp-copy-size-limit)
4690 (> size tramp-copy-size-limit)
4691 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
4692
03c1ad43
MA
4693;; Variables local to connection.
4694
4695(defun tramp-get-remote-path (vec)
4696 (with-connection-property
4697 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
4698 ;; cache the result for the session only. Otherwise, the result
4699 ;; is cached persistently.
4700 (if (memq 'tramp-own-remote-path tramp-remote-path)
4701 (tramp-get-connection-process vec)
4702 vec)
4703 "remote-path"
4704 (let* ((remote-path (copy-tree tramp-remote-path))
4705 (elt1 (memq 'tramp-default-remote-path remote-path))
4706 (elt2 (memq 'tramp-own-remote-path remote-path))
4707 (default-remote-path
4708 (when elt1
a857d3c7
MA
4709 (or
4710 (tramp-send-command-and-read
6d95bd46 4711 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
a857d3c7
MA
4712 ;; Default if "getconf" is not available.
4713 (progn
03c1ad43
MA
4714 (tramp-message
4715 vec 3
4716 "`getconf PATH' not successful, using default value \"%s\"."
4717 "/bin:/usr/bin")
4718 "/bin:/usr/bin"))))
4719 (own-remote-path
4720 (when elt2
4721 (condition-case nil
4722 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
03c1ad43
MA
4723 (error
4724 (tramp-message
4725 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
4726 nil)))))
4727
4728 ;; Replace place holder `tramp-default-remote-path'.
4729 (when elt1
4730 (setcdr elt1
4731 (append
4732 (tramp-compat-split-string default-remote-path ":")
4733 (cdr elt1)))
4734 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
4735
4736 ;; Replace place holder `tramp-own-remote-path'.
4737 (when elt2
4738 (setcdr elt2
4739 (append
4740 (tramp-compat-split-string own-remote-path ":")
4741 (cdr elt2)))
4742 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
4743
4744 ;; Remove double entries.
4745 (setq elt1 remote-path)
4746 (while (consp elt1)
4747 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
4748 (setcar elt2 nil))
4749 (setq elt1 (cdr elt1)))
4750
4751 ;; Remove non-existing directories.
4752 (delq
4753 nil
4754 (mapcar
4755 (lambda (x)
4756 (and
4757 (stringp x)
4758 (file-directory-p
4759 (tramp-make-tramp-file-name
4760 (tramp-file-name-method vec)
4761 (tramp-file-name-user vec)
4762 (tramp-file-name-host vec)
4763 x))
4764 x))
4765 remote-path)))))
4766
4767(defun tramp-get-remote-tmpdir (vec)
4768 (with-connection-property vec "tmp-directory"
4769 (let ((dir (tramp-shell-quote-argument "/tmp")))
4770 (if (and (tramp-send-command-and-check
4771 vec (format "%s -d %s" (tramp-get-test-command vec) dir))
4772 (tramp-send-command-and-check
4773 vec (format "%s -w %s" (tramp-get-test-command vec) dir)))
4774 dir
4775 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
4776
03c1ad43
MA
4777(defun tramp-get-ls-command (vec)
4778 (with-connection-property vec "ls"
4779 (tramp-message vec 5 "Finding a suitable `ls' command")
4780 (or
4781 (catch 'ls-found
4782 (dolist (cmd '("ls" "gnuls" "gls"))
4783 (let ((dl (tramp-get-remote-path vec))
4784 result)
4785 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
4786 ;; Check parameters. On busybox, "ls" output coloring is
4787 ;; enabled by default sometimes. So we try to disable it
4788 ;; when possible. $LS_COLORING is not supported there.
4789 ;; Some "ls" versions are sensible wrt the order of
4790 ;; arguments, they fail when "-al" is after the
4791 ;; "--color=never" argument (for example on FreeBSD).
4792 (when (tramp-send-command-and-check
4793 vec (format "%s -lnd /" result))
4794 (when (tramp-send-command-and-check
4795 vec (format
4796 "%s --color=never -al /dev/null" result))
4797 (setq result (concat result " --color=never")))
4798 (throw 'ls-found result))
4799 (setq dl (cdr dl))))))
4800 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
4801
4802(defun tramp-get-ls-command-with-dired (vec)
4803 (save-match-data
4804 (with-connection-property vec "ls-dired"
4805 (tramp-message vec 5 "Checking, whether `ls --dired' works")
4806 ;; Some "ls" versions are sensible wrt the order of arguments,
4807 ;; they fail when "-al" is after the "--dired" argument (for
4808 ;; example on FreeBSD).
4809 (tramp-send-command-and-check
4810 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
4811
4812(defun tramp-get-test-command (vec)
4813 (with-connection-property vec "test"
4814 (tramp-message vec 5 "Finding a suitable `test' command")
4815 (if (tramp-send-command-and-check vec "test 0")
4816 "test"
4817 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
4818
4819(defun tramp-get-test-nt-command (vec)
4820 ;; Does `test A -nt B' work? Use abominable `find' construct if it
4821 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
4822 ;; for otherwise the shell crashes.
4823 (with-connection-property vec "test-nt"
4824 (or
4825 (progn
4826 (tramp-send-command
4827 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
4828 (with-current-buffer (tramp-get-buffer vec)
4829 (goto-char (point-min))
4830 (when (looking-at (regexp-quote tramp-end-of-output))
4831 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
4832 (progn
4833 (tramp-send-command
4834 vec
4835 (format
4836 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
4837 (tramp-get-test-command vec)))
4838 "tramp_test_nt %s %s"))))
4839
4840(defun tramp-get-file-exists-command (vec)
4841 (with-connection-property vec "file-exists"
4842 (tramp-message vec 5 "Finding command to check if file exists")
4843 (tramp-find-file-exists-command vec)))
4844
4845(defun tramp-get-remote-ln (vec)
4846 (with-connection-property vec "ln"
4847 (tramp-message vec 5 "Finding a suitable `ln' command")
4848 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
4849
4850(defun tramp-get-remote-perl (vec)
4851 (with-connection-property vec "perl"
4852 (tramp-message vec 5 "Finding a suitable `perl' command")
4853 (let ((result
4854 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
4855 (tramp-find-executable
4856 vec "perl" (tramp-get-remote-path vec)))))
4857 ;; We must check also for some Perl modules.
4858 (when result
4859 (with-connection-property vec "perl-file-spec"
4860 (tramp-send-command-and-check
4861 vec (format "%s -e 'use File::Spec;'" result)))
4862 (with-connection-property vec "perl-cwd-realpath"
4863 (tramp-send-command-and-check
4864 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
4865 result)))
4866
4867(defun tramp-get-remote-stat (vec)
4868 (with-connection-property vec "stat"
4869 (tramp-message vec 5 "Finding a suitable `stat' command")
4870 (let ((result (tramp-find-executable
4871 vec "stat" (tramp-get-remote-path vec)))
4872 tmp)
6d95bd46 4873 ;; Check whether stat(1) returns usable syntax. "%s" does not
03c1ad43
MA
4874 ;; work on older AIX systems.
4875 (when result
4876 (setq tmp
6d95bd46
MA
4877 (tramp-send-command-and-read
4878 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
03c1ad43
MA
4879 (unless (and (listp tmp) (stringp (car tmp))
4880 (string-match "^./.$" (car tmp))
4881 (integerp (cadr tmp)))
4882 (setq result nil)))
4883 result)))
4884
4885(defun tramp-get-remote-readlink (vec)
4886 (with-connection-property vec "readlink"
4887 (tramp-message vec 5 "Finding a suitable `readlink' command")
4888 (let ((result (tramp-find-executable
4889 vec "readlink" (tramp-get-remote-path vec))))
4890 (when (and result
6d95bd46
MA
4891 (tramp-send-command-and-check
4892 vec (format "%s --canonicalize-missing /" result)))
03c1ad43
MA
4893 result))))
4894
4895(defun tramp-get-remote-trash (vec)
4896 (with-connection-property vec "trash"
4897 (tramp-message vec 5 "Finding a suitable `trash' command")
4898 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
4899
4900(defun tramp-get-remote-id (vec)
4901 (with-connection-property vec "id"
4902 (tramp-message vec 5 "Finding POSIX `id' command")
4903 (or
4904 (catch 'id-found
4905 (let ((dl (tramp-get-remote-path vec))
4906 result)
4907 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
4908 ;; Check POSIX parameter.
4909 (when (tramp-send-command-and-check vec (format "%s -u" result))
4910 (throw 'id-found result))
4911 (setq dl (cdr dl)))))
4912 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
4913
4914(defun tramp-get-remote-uid (vec id-format)
4915 (with-connection-property vec (format "uid-%s" id-format)
4916 (let ((res (tramp-send-command-and-read
4917 vec
4918 (format "%s -u%s %s"
4919 (tramp-get-remote-id vec)
4920 (if (equal id-format 'integer) "" "n")
4921 (if (equal id-format 'integer)
4922 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
4923 ;; The command might not always return a number.
4924 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
4925
4926(defun tramp-get-remote-gid (vec id-format)
4927 (with-connection-property vec (format "gid-%s" id-format)
4928 (let ((res (tramp-send-command-and-read
4929 vec
4930 (format "%s -g%s %s"
4931 (tramp-get-remote-id vec)
4932 (if (equal id-format 'integer) "" "n")
4933 (if (equal id-format 'integer)
4934 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
4935 ;; The command might not always return a number.
4936 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
4937
4938(defun tramp-get-local-uid (id-format)
4939 (if (equal id-format 'integer) (user-uid) (user-login-name)))
4940
4941(defun tramp-get-local-gid (id-format)
4942 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
4943
4944;; Some predefined connection properties.
4945(defun tramp-get-inline-compress (vec prop size)
4946 "Return the compress command related to PROP.
4947PROP is either `inline-compress' or `inline-decompress'. SIZE is
4948the length of the file to be compressed.
4949
4950If no corresponding command is found, nil is returned."
4951 (when (and (integerp tramp-inline-compress-start-size)
4952 (> size tramp-inline-compress-start-size))
4953 (with-connection-property vec prop
4954 (tramp-find-inline-compress vec)
4955 (tramp-get-connection-property vec prop nil))))
4956
4957(defun tramp-get-inline-coding (vec prop size)
4958 "Return the coding command related to PROP.
4959PROP is either `remote-encoding', `remode-decoding',
4960`local-encoding' or `local-decoding'.
4961
4962SIZE is the length of the file to be coded. Depending on SIZE,
4963compression might be applied.
4964
4965If no corresponding command is found, nil is returned.
4966Otherwise, either a string is returned which contains a `%s' mark
4967to be used for the respective input or output file; or a Lisp
4968function cell is returned to be applied on a buffer."
01d884cf
MA
4969 ;; We must catch the errors, because we want to return `nil', when
4970 ;; no inline coding is found.
4971 (ignore-errors
4972 (let ((coding
4973 (with-connection-property vec prop
4974 (tramp-find-inline-encoding vec)
4975 (tramp-get-connection-property vec prop nil)))
4976 (prop1 (if (string-match "encoding" prop)
4977 "inline-compress" "inline-decompress"))
4978 compress)
4979 ;; The connection property might have been cached. So we must
4980 ;; send the script to the remote side - maybe.
4981 (when (and coding (symbolp coding) (string-match "remote" prop))
4982 (let ((name (symbol-name coding)))
4983 (while (string-match (regexp-quote "-") name)
4984 (setq name (replace-match "_" nil t name)))
4985 (tramp-maybe-send-script vec (symbol-value coding) name)
4986 (setq coding name)))
4987 (when coding
4988 ;; Check for the `compress' command.
4989 (setq compress (tramp-get-inline-compress vec prop1 size))
4990 ;; Return the value.
4991 (cond
4992 ((and compress (symbolp coding))
4993 (if (string-match "decompress" prop1)
4994 `(lambda (beg end)
4995 (,coding beg end)
4996 (let ((coding-system-for-write 'binary)
4997 (coding-system-for-read 'binary))
4998 (apply
4999 'call-process-region (point-min) (point-max)
5000 (car (split-string ,compress)) t t nil
5001 (cdr (split-string ,compress)))))
03c1ad43 5002 `(lambda (beg end)
03c1ad43
MA
5003 (let ((coding-system-for-write 'binary)
5004 (coding-system-for-read 'binary))
5005 (apply
01d884cf 5006 'call-process-region beg end
03c1ad43 5007 (car (split-string ,compress)) t t nil
01d884cf
MA
5008 (cdr (split-string ,compress))))
5009 (,coding (point-min) (point-max)))))
5010 ((symbolp coding)
5011 coding)
5012 ((and compress (string-match "decoding" prop))
362b9d48
GM
5013 (format
5014 ;; Windows shells need the program file name after
5015 ;; the pipe symbol be quoted if they use forward
5016 ;; slashes as directory separators.
5017 (if (and (string-match "local" prop)
5018 (memq system-type '(windows-nt)))
5019 "(%s | \"%s\" >%%s)"
5020 "(%s | %s >%%s)")
5021 coding compress))
01d884cf 5022 (compress
362b9d48
GM
5023 (format
5024 ;; Windows shells need the program file name after
5025 ;; the pipe symbol be quoted if they use forward
5026 ;; slashes as directory separators.
5027 (if (and (string-match "local" prop)
5028 (memq system-type '(windows-nt)))
5029 "(%s <%%s | \"%s\")"
5030 "(%s <%%s | %s)")
5031 compress coding))
01d884cf
MA
5032 ((string-match "decoding" prop)
5033 (format "%s >%%s" coding))
5034 (t
5035 (format "%s <%%s" coding)))))))
03c1ad43
MA
5036
5037;;; Integration of eshell.el:
5038
5039(eval-when-compile
5040 (defvar eshell-path-env))
5041
5042;; eshell.el keeps the path in `eshell-path-env'. We must change it
5043;; when `default-directory' points to another host.
5044(defun tramp-eshell-directory-change ()
5045 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
5046 (setq eshell-path-env
5047 (if (file-remote-p default-directory)
5048 (with-parsed-tramp-file-name default-directory nil
5049 (mapconcat
5050 'identity
5051 (tramp-get-remote-path v)
5052 ":"))
5053 (getenv "PATH"))))
5054
5055(eval-after-load "esh-util"
5056 '(progn
5057 (tramp-eshell-directory-change)
5058 (add-hook 'eshell-directory-change-hook
5059 'tramp-eshell-directory-change)
5060 (add-hook 'tramp-unload-hook
5061 (lambda ()
5062 (remove-hook 'eshell-directory-change-hook
5063 'tramp-eshell-directory-change)))))
5064
5065(add-hook 'tramp-unload-hook
5066 (lambda ()
5067 (unload-feature 'tramp-sh 'force)))
5068
5069(provide 'tramp-sh)
5070
5071;;; TODO:
5072
5073;; * Don't use globbing for directories with many files, as this is
5074;; likely to produce long command lines, and some shells choke on
5075;; long command lines.
5076;; * Make it work for different encodings, and for different file name
5077;; encodings, too. (Daniel Pittman)
5078;; * Don't search for perl5 and perl. Instead, only search for perl and
5079;; then look if it's the right version (with `perl -v').
5080;; * When editing a remote CVS controlled file as a different user, VC
5081;; gets confused about the file locking status. Try to find out why
5082;; the workaround doesn't work.
5083;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5084;; until the last but one hop via `start-file-process'. Apply it
5085;; also for ftp and smb.
5086;; * WIBNI if we had a command "trampclient"? If I was editing in
5087;; some shell with root priviledges, it would be nice if I could
5088;; just call
5089;; trampclient filename.c
5090;; as an editor, and the _current_ shell would connect to an Emacs
5091;; server and would be used in an existing non-priviledged Emacs
5092;; session for doing the editing in question.
5093;; That way, I need not tell Emacs my password again and be afraid
5094;; that it makes it into core dumps or other ugly stuff (I had Emacs
5095;; once display a just typed password in the context of a keyboard
5096;; sequence prompt for a question immediately following in a shell
5097;; script run within Emacs -- nasty).
5098;; And if I have some ssh session running to a different computer,
5099;; having the possibility of passing a local file there to a local
5100;; Emacs session (in case I can arrange for a connection back) would
5101;; be nice.
5102;; Likely the corresponding Tramp server should not allow the
5103;; equivalent of the emacsclient -eval option in order to make this
5104;; reasonably unproblematic. And maybe trampclient should have some
5105;; way of passing credentials, like by using an SSL socket or
5106;; something. (David Kastrup)
5107;; * Reconnect directly to a compliant shell without first going
5108;; through the user's default shell. (Pete Forman)
5109;; * How can I interrupt the remote process with a signal
5110;; (interrupt-process seems not to work)? (Markus Triska)
5111;; * Avoid the local shell entirely for starting remote processes. If
5112;; so, I think even a signal, when delivered directly to the local
5113;; SSH instance, would correctly be propagated to the remote process
5114;; automatically; possibly SSH would have to be started with
5115;; "-t". (Markus Triska)
5116;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5117;; isn't on the remote host. (Mark A. Hershberger)
5118;; * Use lsh instead of ssh. (Alfred M. Szmidt)
2c68ca0e 5119;; * Optimize out-of-band copying when both methods are scp-like (not
03c1ad43
MA
5120;; rsync).
5121;; * Keep a second connection open for out-of-band methods like scp or
5122;; rsync.
5123;; * Try telnet+curl as new method. It might be useful for busybox,
5124;; without built-in uuencode/uudecode.
5125
5126;;; tramp-sh.el ends here