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