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