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