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