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