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