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