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