]> code.delx.au - gnu-emacs/blob - lisp/net/tramp-sh.el
Merge from emacs-24; up to 2012-12-21T07:35:02Z!ueno@gnu.org
[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 (if full-directory-p
2610 (tramp-send-command
2611 v
2612 (format "%s %s %s 2>/dev/null"
2613 (tramp-get-ls-command v)
2614 switches
2615 (if wildcard
2616 localname
2617 (tramp-shell-quote-argument (concat localname ".")))))
2618 (tramp-barf-unless-okay
2619 v
2620 (format "cd %s" (tramp-shell-quote-argument
2621 (tramp-run-real-handler
2622 'file-name-directory (list localname))))
2623 "Couldn't `cd %s'"
2624 (tramp-shell-quote-argument
2625 (tramp-run-real-handler 'file-name-directory (list localname))))
2626 (tramp-send-command
2627 v
2628 (format "%s %s %s"
2629 (tramp-get-ls-command v)
2630 switches
2631 (if (or wildcard
2632 (zerop (length
2633 (tramp-run-real-handler
2634 'file-name-nondirectory (list localname)))))
2635 ""
2636 (tramp-shell-quote-argument
2637 (tramp-run-real-handler
2638 'file-name-nondirectory (list localname)))))))
2639 (let ((beg (point)))
2640 ;; We cannot use `insert-buffer-substring' because the Tramp
2641 ;; buffer changes its contents before insertion due to calling
2642 ;; `expand-file' and alike.
2643 (insert
2644 (with-current-buffer (tramp-get-buffer v)
2645 (buffer-string)))
2646
2647 ;; Check for "--dired" output.
2648 (forward-line -2)
2649 (when (looking-at "//SUBDIRED//")
2650 (forward-line -1))
2651 (when (looking-at "//DIRED//\\s-+")
2652 (let ((databeg (match-end 0))
2653 (end (point-at-eol)))
2654 ;; Now read the numeric positions of file names.
2655 (goto-char databeg)
2656 (while (< (point) end)
2657 (let ((start (+ beg (read (current-buffer))))
2658 (end (+ beg (read (current-buffer)))))
2659 (if (memq (char-after end) '(?\n ?\ ))
2660 ;; End is followed by \n or by " -> ".
2661 (put-text-property start end 'dired-filename t))))))
2662 ;; Remove trailing lines.
2663 (goto-char (point-at-bol))
2664 (while (looking-at "//")
2665 (forward-line 1)
2666 (delete-region (match-beginning 0) (point)))
2667
2668 ;; Some busyboxes are reluctant to discard colors.
2669 (unless (string-match "color" (tramp-get-connection-property v "ls" ""))
2670 (goto-char beg)
2671 (while (re-search-forward tramp-color-escape-sequence-regexp nil t)
2672 (replace-match "")))
2673
2674 ;; The inserted file could be from somewhere else.
2675 (when (and (not wildcard) (not full-directory-p))
2676 (goto-char (point-max))
2677 (when (file-symlink-p filename)
2678 (goto-char (search-backward "->" beg 'noerror)))
2679 (search-backward
2680 (if (zerop (length (file-name-nondirectory filename)))
2681 "."
2682 (file-name-nondirectory filename))
2683 beg 'noerror)
2684 (replace-match (file-relative-name filename) t))
2685
2686 (goto-char (point-max))))))
2687
2688 ;; Canonicalization of file names.
2689
2690 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2691 "Like `expand-file-name' for Tramp files.
2692 If the localname part of the given filename starts with \"/../\" then
2693 the result will be a local, non-Tramp, filename."
2694 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
2695 (setq dir (or dir default-directory "/"))
2696 ;; Unless NAME is absolute, concat DIR and NAME.
2697 (unless (file-name-absolute-p name)
2698 (setq name (concat (file-name-as-directory dir) name)))
2699 ;; If NAME is not a Tramp file, run the real handler.
2700 (if (not (tramp-connectable-p name))
2701 (tramp-run-real-handler 'expand-file-name (list name nil))
2702 ;; Dissect NAME.
2703 (with-parsed-tramp-file-name name nil
2704 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2705 (setq localname (concat "~/" localname)))
2706 ;; Tilde expansion if necessary. This needs a shell which
2707 ;; groks tilde expansion! The function `tramp-find-shell' is
2708 ;; supposed to find such a shell on the remote host. Please
2709 ;; tell me about it when this doesn't work on your system.
2710 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2711 (let ((uname (match-string 1 localname))
2712 (fname (match-string 2 localname)))
2713 ;; We cannot simply apply "~/", because under sudo "~/" is
2714 ;; expanded to the local user home directory but to the
2715 ;; root home directory. On the other hand, using always
2716 ;; the default user name for tilde expansion is not
2717 ;; appropriate either, because ssh and companions might
2718 ;; use a user name from the config file.
2719 (when (and (string-equal uname "~")
2720 (string-match "\\`su\\(do\\)?\\'" method))
2721 (setq uname (concat uname user)))
2722 (setq uname
2723 (with-tramp-connection-property v uname
2724 (tramp-send-command
2725 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
2726 (with-current-buffer (tramp-get-buffer v)
2727 (goto-char (point-min))
2728 (buffer-substring (point) (point-at-eol)))))
2729 (setq localname (concat uname fname))))
2730 ;; There might be a double slash, for example when "~/"
2731 ;; expands to "/". Remove this.
2732 (while (string-match "//" localname)
2733 (setq localname (replace-match "/" t t localname)))
2734 ;; No tilde characters in file name, do normal
2735 ;; `expand-file-name' (this does "/./" and "/../"). We bind
2736 ;; `directory-sep-char' here for XEmacs on Windows, which would
2737 ;; otherwise use backslash. `default-directory' is bound,
2738 ;; because on Windows there would be problems with UNC shares or
2739 ;; Cygwin mounts.
2740 (let ((directory-sep-char ?/)
2741 (default-directory (tramp-compat-temporary-file-directory)))
2742 (tramp-make-tramp-file-name
2743 method user host
2744 (tramp-drop-volume-letter
2745 (tramp-run-real-handler
2746 'expand-file-name (list localname)))
2747 hop)))))
2748
2749 ;;; Remote commands:
2750
2751 (defun tramp-sh-handle-executable-find (command)
2752 "Like `executable-find' for Tramp files."
2753 (with-parsed-tramp-file-name default-directory nil
2754 (tramp-find-executable v command (tramp-get-remote-path v) t)))
2755
2756 (defun tramp-process-sentinel (proc event)
2757 "Flush file caches."
2758 (unless (memq (process-status proc) '(run open))
2759 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2760 (when vec
2761 (tramp-message vec 5 "Sentinel called: `%s' `%s'" proc event)
2762 (tramp-flush-connection-property proc)
2763 (tramp-flush-directory-property vec "")))))
2764
2765 ;; We use BUFFER also as connection buffer during setup. Because of
2766 ;; this, its original contents must be saved, and restored once
2767 ;; connection has been setup.
2768 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2769 "Like `start-file-process' for Tramp files."
2770 (with-parsed-tramp-file-name default-directory nil
2771 ;; When PROGRAM is nil, we just provide a tty.
2772 (let ((command
2773 (when (stringp program)
2774 (format "cd %s; exec env PS1=%s %s"
2775 (tramp-shell-quote-argument localname)
2776 ;; Use a human-friendly prompt, for example for `shell'.
2777 (tramp-shell-quote-argument
2778 (format "%s %s"
2779 (file-remote-p default-directory)
2780 tramp-initial-end-of-output))
2781 (mapconcat 'tramp-shell-quote-argument
2782 (cons program args) " "))))
2783 (tramp-process-connection-type
2784 (or (null program) tramp-process-connection-type))
2785 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2786 (name1 name)
2787 (i 0)
2788 ;; We do not want to raise an error when
2789 ;; `start-file-process' has been started several time in
2790 ;; `eshell' and friends.
2791 (tramp-current-connection nil))
2792
2793 (unless buffer
2794 ;; BUFFER can be nil. We use a temporary buffer.
2795 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
2796 (while (get-process name1)
2797 ;; NAME must be unique as process name.
2798 (setq i (1+ i)
2799 name1 (format "%s<%d>" name i)))
2800 (setq name name1)
2801 ;; Set the new process properties.
2802 (tramp-set-connection-property v "process-name" name)
2803 (tramp-set-connection-property v "process-buffer" buffer)
2804
2805 (with-current-buffer (tramp-get-connection-buffer v)
2806 (unwind-protect
2807 ;; We catch this event. Otherwise, `start-process' could
2808 ;; be called on the local host.
2809 (save-excursion
2810 (save-restriction
2811 ;; Activate narrowing in order to save BUFFER
2812 ;; contents. Clear also the modification time;
2813 ;; otherwise we might be interrupted by
2814 ;; `verify-visited-file-modtime'.
2815 (let ((buffer-undo-list t)
2816 (buffer-read-only nil)
2817 (mark (point)))
2818 (clear-visited-file-modtime)
2819 (narrow-to-region (point-max) (point-max))
2820 ;; We call `tramp-maybe-open-connection', in order
2821 ;; to cleanup the prompt afterwards.
2822 (catch 'suppress
2823 (tramp-maybe-open-connection v)
2824 (widen)
2825 (delete-region mark (point))
2826 (narrow-to-region (point-max) (point-max))
2827 ;; Now do it.
2828 (if command
2829 ;; Send the command.
2830 (tramp-send-command v command nil t) ; nooutput
2831 ;; Check, whether a pty is associated.
2832 (unless (tramp-compat-process-get
2833 (tramp-get-connection-process v) 'remote-tty)
2834 (tramp-error
2835 v 'file-error
2836 "pty association is not supported for `%s'" name))))
2837 (let ((p (tramp-get-connection-process v)))
2838 ;; Set query flag and process marker for this
2839 ;; process. We ignore errors, because the process
2840 ;; could have finished already.
2841 (ignore-errors
2842 (tramp-compat-set-process-query-on-exit-flag p t)
2843 (set-marker (process-mark p) (point)))
2844 ;; Return process.
2845 p))))
2846
2847 ;; Save exit.
2848 (if (string-match tramp-temp-buffer-name (buffer-name))
2849 (ignore-errors
2850 (set-process-buffer (tramp-get-connection-process v) nil)
2851 (kill-buffer (current-buffer)))
2852 (set-buffer-modified-p bmp))
2853 (tramp-set-connection-property v "process-name" nil)
2854 (tramp-set-connection-property v "process-buffer" nil))))))
2855
2856 (defun tramp-sh-handle-process-file
2857 (program &optional infile destination display &rest args)
2858 "Like `process-file' for Tramp files."
2859 ;; The implementation is not complete yet.
2860 (when (and (numberp destination) (zerop destination))
2861 (error "Implementation does not handle immediate return"))
2862
2863 (with-parsed-tramp-file-name default-directory nil
2864 (let (command input tmpinput stderr tmpstderr outbuf ret)
2865 ;; Compute command.
2866 (setq command (mapconcat 'tramp-shell-quote-argument
2867 (cons program args) " "))
2868 ;; Determine input.
2869 (if (null infile)
2870 (setq input "/dev/null")
2871 (setq infile (expand-file-name infile))
2872 (if (tramp-equal-remote default-directory infile)
2873 ;; INFILE is on the same remote host.
2874 (setq input (with-parsed-tramp-file-name infile nil localname))
2875 ;; INFILE must be copied to remote host.
2876 (setq input (tramp-make-tramp-temp-file v)
2877 tmpinput (tramp-make-tramp-file-name method user host input))
2878 (copy-file infile tmpinput t)))
2879 (when input (setq command (format "%s <%s" command input)))
2880
2881 ;; Determine output.
2882 (cond
2883 ;; Just a buffer.
2884 ((bufferp destination)
2885 (setq outbuf destination))
2886 ;; A buffer name.
2887 ((stringp destination)
2888 (setq outbuf (get-buffer-create destination)))
2889 ;; (REAL-DESTINATION ERROR-DESTINATION)
2890 ((consp destination)
2891 ;; output.
2892 (cond
2893 ((bufferp (car destination))
2894 (setq outbuf (car destination)))
2895 ((stringp (car destination))
2896 (setq outbuf (get-buffer-create (car destination))))
2897 ((car destination)
2898 (setq outbuf (current-buffer))))
2899 ;; stderr.
2900 (cond
2901 ((stringp (cadr destination))
2902 (setcar (cdr destination) (expand-file-name (cadr destination)))
2903 (if (tramp-equal-remote default-directory (cadr destination))
2904 ;; stderr is on the same remote host.
2905 (setq stderr (with-parsed-tramp-file-name
2906 (cadr destination) nil localname))
2907 ;; stderr must be copied to remote host. The temporary
2908 ;; file must be deleted after execution.
2909 (setq stderr (tramp-make-tramp-temp-file v)
2910 tmpstderr (tramp-make-tramp-file-name
2911 method user host stderr))))
2912 ;; stderr to be discarded.
2913 ((null (cadr destination))
2914 (setq stderr "/dev/null"))))
2915 ;; 't
2916 (destination
2917 (setq outbuf (current-buffer))))
2918 (when stderr (setq command (format "%s 2>%s" command stderr)))
2919
2920 ;; Send the command. It might not return in time, so we protect
2921 ;; it. Call it in a subshell, in order to preserve working
2922 ;; directory.
2923 (condition-case nil
2924 (unwind-protect
2925 (setq ret
2926 (if (tramp-send-command-and-check
2927 v (format "\\cd %s; %s"
2928 (tramp-shell-quote-argument localname)
2929 command)
2930 t t)
2931 0 1))
2932 ;; We should show the output anyway.
2933 (when outbuf
2934 (with-current-buffer outbuf
2935 (insert
2936 (with-current-buffer (tramp-get-connection-buffer v)
2937 (buffer-string))))
2938 (when display (display-buffer outbuf))))
2939 ;; When the user did interrupt, we should do it also. We use
2940 ;; return code -1 as marker.
2941 (quit
2942 (kill-buffer (tramp-get-connection-buffer v))
2943 (setq ret -1))
2944 ;; Handle errors.
2945 (error
2946 (kill-buffer (tramp-get-connection-buffer v))
2947 (setq ret 1)))
2948
2949 ;; Provide error file.
2950 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
2951
2952 ;; Cleanup. We remove all file cache values for the connection,
2953 ;; because the remote process could have changed them.
2954 (when tmpinput (delete-file tmpinput))
2955
2956 ;; `process-file-side-effects' has been introduced with GNU
2957 ;; Emacs 23.2. If set to `nil', no remote file will be changed
2958 ;; by `program'. If it doesn't exist, we assume its default
2959 ;; value `t'.
2960 (unless (and (boundp 'process-file-side-effects)
2961 (not (symbol-value 'process-file-side-effects)))
2962 (tramp-flush-directory-property v ""))
2963
2964 ;; Return exit status.
2965 (if (equal ret -1)
2966 (keyboard-quit)
2967 ret))))
2968
2969 (defun tramp-sh-handle-file-local-copy (filename)
2970 "Like `file-local-copy' for Tramp files."
2971 (with-parsed-tramp-file-name filename nil
2972 (unless (file-exists-p filename)
2973 (tramp-error
2974 v 'file-error
2975 "Cannot make local copy of non-existing file `%s'" filename))
2976
2977 (let* ((size (nth 7 (file-attributes (file-truename filename))))
2978 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
2979 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
2980 (tmpfile (tramp-compat-make-temp-file filename)))
2981
2982 (condition-case err
2983 (cond
2984 ;; `copy-file' handles direct copy and out-of-band methods.
2985 ((or (tramp-local-host-p v)
2986 (tramp-method-out-of-band-p v size))
2987 (copy-file filename tmpfile t t))
2988
2989 ;; Use inline encoding for file transfer.
2990 (rem-enc
2991 (save-excursion
2992 (with-tramp-progress-reporter
2993 v 3 (format "Encoding remote file %s" filename)
2994 (tramp-barf-unless-okay
2995 v (format rem-enc (tramp-shell-quote-argument localname))
2996 "Encoding remote file failed"))
2997
2998 (if (functionp loc-dec)
2999 ;; If local decoding is a function, we call it. We
3000 ;; must disable multibyte, because
3001 ;; `uudecode-decode-region' doesn't handle it
3002 ;; correctly.
3003 (with-temp-buffer
3004 (set-buffer-multibyte nil)
3005 (insert-buffer-substring (tramp-get-buffer v))
3006 (with-tramp-progress-reporter
3007 v 3 (format "Decoding remote file %s with function %s"
3008 filename loc-dec)
3009 (funcall loc-dec (point-min) (point-max))
3010 ;; Unset `file-name-handler-alist'. Otherwise,
3011 ;; epa-file gets confused.
3012 (let (file-name-handler-alist
3013 (coding-system-for-write 'binary))
3014 (write-region (point-min) (point-max) tmpfile))))
3015
3016 ;; If tramp-decoding-function is not defined for this
3017 ;; method, we invoke tramp-decoding-command instead.
3018 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3019 ;; Unset `file-name-handler-alist'. Otherwise,
3020 ;; epa-file gets confused.
3021 (let (file-name-handler-alist
3022 (coding-system-for-write 'binary))
3023 (write-region (point-min) (point-max) tmpfile2))
3024 (with-tramp-progress-reporter
3025 v 3 (format "Decoding remote file %s with command %s"
3026 filename loc-dec)
3027 (unwind-protect
3028 (tramp-call-local-coding-command
3029 loc-dec tmpfile2 tmpfile)
3030 (delete-file tmpfile2)))))
3031
3032 ;; Set proper permissions.
3033 (set-file-modes tmpfile (tramp-default-file-modes filename))
3034 ;; Set local user ownership.
3035 (tramp-set-file-uid-gid tmpfile)))
3036
3037 ;; Oops, I don't know what to do.
3038 (t (tramp-error
3039 v 'file-error "Wrong method specification for `%s'" method)))
3040
3041 ;; Error handling.
3042 ((error quit)
3043 (delete-file tmpfile)
3044 (signal (car err) (cdr err))))
3045
3046 (run-hooks 'tramp-handle-file-local-copy-hook)
3047 tmpfile)))
3048
3049 ;; This is needed for XEmacs only. Code stolen from files.el.
3050 (defun tramp-sh-handle-insert-file-contents-literally
3051 (filename &optional visit beg end replace)
3052 "Like `insert-file-contents-literally' for Tramp files."
3053 (let ((format-alist nil)
3054 (after-insert-file-functions nil)
3055 (coding-system-for-read 'no-conversion)
3056 (coding-system-for-write 'no-conversion)
3057 (find-buffer-file-type-function
3058 (if (fboundp 'find-buffer-file-type)
3059 (symbol-function 'find-buffer-file-type)
3060 nil))
3061 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
3062 (inhibit-file-name-operation 'insert-file-contents))
3063 (unwind-protect
3064 (progn
3065 (fset 'find-buffer-file-type (lambda (filename) t))
3066 (insert-file-contents filename visit beg end replace))
3067 ;; Save exit.
3068 (if find-buffer-file-type-function
3069 (fset 'find-buffer-file-type find-buffer-file-type-function)
3070 (fmakunbound 'find-buffer-file-type)))))
3071
3072 (defun tramp-sh-handle-make-auto-save-file-name ()
3073 "Like `make-auto-save-file-name' for Tramp files.
3074 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
3075 (let ((tramp-auto-save-directory tramp-auto-save-directory)
3076 (buffer-file-name
3077 (tramp-subst-strs-in-string
3078 '(("_" . "|")
3079 ("/" . "_a")
3080 (":" . "_b")
3081 ("|" . "__")
3082 ("[" . "_l")
3083 ("]" . "_r"))
3084 (buffer-file-name))))
3085 ;; File name must be unique. This is ensured with Emacs 22 (see
3086 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
3087 ;; all other cases we must do it ourselves.
3088 (when (boundp 'auto-save-file-name-transforms)
3089 (mapc
3090 (lambda (x)
3091 (when (and (string-match (car x) buffer-file-name)
3092 (not (car (cddr x))))
3093 (setq tramp-auto-save-directory
3094 (or tramp-auto-save-directory
3095 (tramp-compat-temporary-file-directory)))))
3096 (symbol-value 'auto-save-file-name-transforms)))
3097 ;; Create directory.
3098 (when tramp-auto-save-directory
3099 (setq buffer-file-name
3100 (expand-file-name buffer-file-name tramp-auto-save-directory))
3101 (unless (file-exists-p tramp-auto-save-directory)
3102 (make-directory tramp-auto-save-directory t)))
3103 ;; Run plain `make-auto-save-file-name'. There might be an advice when
3104 ;; it is not a magic file name operation (since Emacs 22).
3105 ;; We must deactivate it temporarily.
3106 (if (not (ad-is-active 'make-auto-save-file-name))
3107 (tramp-run-real-handler 'make-auto-save-file-name nil)
3108 ;; else
3109 (ad-deactivate 'make-auto-save-file-name)
3110 (prog1
3111 (tramp-run-real-handler 'make-auto-save-file-name nil)
3112 (ad-activate 'make-auto-save-file-name)))))
3113
3114 ;; CCC grok LOCKNAME
3115 (defun tramp-sh-handle-write-region
3116 (start end filename &optional append visit lockname confirm)
3117 "Like `write-region' for Tramp files."
3118 (setq filename (expand-file-name filename))
3119 (with-parsed-tramp-file-name filename nil
3120 ;; Following part commented out because we don't know what to do about
3121 ;; file locking, and it does not appear to be a problem to ignore it.
3122 ;; Ange-ftp ignores it, too.
3123 ;; (when (and lockname (stringp lockname))
3124 ;; (setq lockname (expand-file-name lockname)))
3125 ;; (unless (or (eq lockname nil)
3126 ;; (string= lockname filename))
3127 ;; (error
3128 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3129
3130 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
3131 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
3132 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3133 (tramp-error v 'file-error "File not overwritten")))
3134
3135 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
3136 (tramp-get-remote-uid v 'integer)))
3137 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
3138 (tramp-get-remote-gid v 'integer))))
3139
3140 (if (and (tramp-local-host-p v)
3141 ;; `file-writable-p' calls `file-expand-file-name'. We
3142 ;; cannot use `tramp-run-real-handler' therefore.
3143 (let (file-name-handler-alist)
3144 (and
3145 (file-writable-p (file-name-directory localname))
3146 (or (file-directory-p localname)
3147 (file-writable-p localname)))))
3148 ;; Short track: if we are on the local host, we can run directly.
3149 (tramp-run-real-handler
3150 'write-region
3151 (list start end localname append 'no-message lockname confirm))
3152
3153 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3154 ;; We use this to save the value of
3155 ;; `last-coding-system-used' after writing the tmp
3156 ;; file. At the end of the function, we set
3157 ;; `last-coding-system-used' to this saved value. This
3158 ;; way, any intermediary coding systems used while
3159 ;; talking to the remote shell or suchlike won't hose
3160 ;; this variable. This approach was snarfed from
3161 ;; ange-ftp.el.
3162 coding-system-used
3163 ;; Write region into a tmp file. This isn't really
3164 ;; needed if we use an encoding function, but currently
3165 ;; we use it always because this makes the logic
3166 ;; simpler. We must also set `temporary-file-directory',
3167 ;; because it could point to a remote directory.
3168 (temporary-file-directory
3169 (tramp-compat-temporary-file-directory))
3170 (tmpfile (or tramp-temp-buffer-file-name
3171 (tramp-compat-make-temp-file filename))))
3172
3173 ;; If `append' is non-nil, we copy the file locally, and let
3174 ;; the native `write-region' implementation do the job.
3175 (when append (copy-file filename tmpfile 'ok))
3176
3177 ;; We say `no-message' here because we don't want the
3178 ;; visited file modtime data to be clobbered from the temp
3179 ;; file. We call `set-visited-file-modtime' ourselves later
3180 ;; on. We must ensure that `file-coding-system-alist'
3181 ;; matches `tmpfile'.
3182 (let (file-name-handler-alist
3183 (file-coding-system-alist
3184 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3185 (condition-case err
3186 (tramp-run-real-handler
3187 'write-region
3188 (list start end tmpfile append 'no-message lockname confirm))
3189 ((error quit)
3190 (setq tramp-temp-buffer-file-name nil)
3191 (delete-file tmpfile)
3192 (signal (car err) (cdr err))))
3193
3194 ;; Now, `last-coding-system-used' has the right value. Remember it.
3195 (when (boundp 'last-coding-system-used)
3196 (setq coding-system-used
3197 (symbol-value 'last-coding-system-used))))
3198
3199 ;; The permissions of the temporary file should be set. If
3200 ;; filename does not exist (eq modes nil) it has been
3201 ;; renamed to the backup file. This case `save-buffer'
3202 ;; handles permissions.
3203 ;; Ensure that it is still readable.
3204 (when modes
3205 (set-file-modes
3206 tmpfile
3207 (logior (or modes 0) (tramp-compat-octal-to-decimal "0400"))))
3208
3209 ;; This is a bit lengthy due to the different methods
3210 ;; possible for file transfer. First, we check whether the
3211 ;; method uses an rcp program. If so, we call it.
3212 ;; Otherwise, both encoding and decoding command must be
3213 ;; specified. However, if the method _also_ specifies an
3214 ;; encoding function, then that is used for encoding the
3215 ;; contents of the tmp file.
3216 (let* ((size (nth 7 (file-attributes tmpfile)))
3217 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3218 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3219 (cond
3220 ;; `copy-file' handles direct copy and out-of-band methods.
3221 ((or (tramp-local-host-p v)
3222 (tramp-method-out-of-band-p v size))
3223 (if (and (not (stringp start))
3224 (= (or end (point-max)) (point-max))
3225 (= (or start (point-min)) (point-min))
3226 (tramp-get-method-parameter
3227 method 'tramp-copy-keep-tmpfile))
3228 (progn
3229 (setq tramp-temp-buffer-file-name tmpfile)
3230 (condition-case err
3231 ;; We keep the local file for performance
3232 ;; reasons, useful for "rsync".
3233 (copy-file tmpfile filename t)
3234 ((error quit)
3235 (setq tramp-temp-buffer-file-name nil)
3236 (delete-file tmpfile)
3237 (signal (car err) (cdr err)))))
3238 (setq tramp-temp-buffer-file-name nil)
3239 ;; Don't rename, in order to keep context in SELinux.
3240 (unwind-protect
3241 (copy-file tmpfile filename t)
3242 (delete-file tmpfile))))
3243
3244 ;; Use inline file transfer.
3245 (rem-dec
3246 ;; Encode tmpfile.
3247 (unwind-protect
3248 (with-temp-buffer
3249 (set-buffer-multibyte nil)
3250 ;; Use encoding function or command.
3251 (if (functionp loc-enc)
3252 (with-tramp-progress-reporter
3253 v 3 (format "Encoding region using function `%s'"
3254 loc-enc)
3255 (let ((coding-system-for-read 'binary))
3256 (insert-file-contents-literally tmpfile))
3257 ;; The following `let' is a workaround for the
3258 ;; base64.el that comes with pgnus-0.84. If
3259 ;; both of the following conditions are
3260 ;; satisfied, it tries to write to a local
3261 ;; file in default-directory, but at this
3262 ;; point, default-directory is remote.
3263 ;; (`call-process-region' can't write to
3264 ;; remote files, it seems.) The file in
3265 ;; question is a tmp file anyway.
3266 (let ((default-directory
3267 (tramp-compat-temporary-file-directory)))
3268 (funcall loc-enc (point-min) (point-max))))
3269
3270 (with-tramp-progress-reporter
3271 v 3 (format "Encoding region using command `%s'"
3272 loc-enc)
3273 (unless (zerop (tramp-call-local-coding-command
3274 loc-enc tmpfile t))
3275 (tramp-error
3276 v 'file-error
3277 (concat "Cannot write to `%s', "
3278 "local encoding command `%s' failed")
3279 filename loc-enc))))
3280
3281 ;; Send buffer into remote decoding command which
3282 ;; writes to remote file. Because this happens on
3283 ;; the remote host, we cannot use the function.
3284 (with-tramp-progress-reporter
3285 v 3
3286 (format "Decoding region into remote file %s" filename)
3287 (goto-char (point-max))
3288 (unless (bolp) (newline))
3289 (tramp-send-command
3290 v
3291 (format
3292 (concat rem-dec " <<'EOF'\n%sEOF")
3293 (tramp-shell-quote-argument localname)
3294 (buffer-string)))
3295 (tramp-barf-unless-okay
3296 v nil
3297 "Couldn't write region to `%s', decode using `%s' failed"
3298 filename rem-dec)
3299 ;; When `file-precious-flag' is set, the region is
3300 ;; written to a temporary file. Check that the
3301 ;; checksum is equal to that from the local tmpfile.
3302 (when file-precious-flag
3303 (erase-buffer)
3304 (and
3305 ;; cksum runs locally, if possible.
3306 (zerop (tramp-compat-call-process "cksum" tmpfile t))
3307 ;; cksum runs remotely.
3308 (tramp-send-command-and-check
3309 v
3310 (format
3311 "cksum <%s" (tramp-shell-quote-argument localname)))
3312 ;; ... they are different.
3313 (not
3314 (string-equal
3315 (buffer-string)
3316 (with-current-buffer (tramp-get-buffer v)
3317 (buffer-string))))
3318 (tramp-error
3319 v 'file-error
3320 (concat "Couldn't write region to `%s',"
3321 " decode using `%s' failed")
3322 filename rem-dec)))))
3323
3324 ;; Save exit.
3325 (delete-file tmpfile)))
3326
3327 ;; That's not expected.
3328 (t
3329 (tramp-error
3330 v 'file-error
3331 (concat "Method `%s' should specify both encoding and "
3332 "decoding command or an rcp program")
3333 method))))
3334
3335 ;; Make `last-coding-system-used' have the right value.
3336 (when coding-system-used
3337 (set 'last-coding-system-used coding-system-used))))
3338
3339 (tramp-flush-file-property v (file-name-directory localname))
3340 (tramp-flush-file-property v localname)
3341
3342 ;; We must protect `last-coding-system-used', now we have set it
3343 ;; to its correct value.
3344 (let (last-coding-system-used (need-chown t))
3345 ;; Set file modification time.
3346 (when (or (eq visit t) (stringp visit))
3347 (let ((file-attr (tramp-compat-file-attributes filename 'integer)))
3348 (set-visited-file-modtime
3349 ;; We must pass modtime explicitly, because filename can
3350 ;; be different from (buffer-file-name), f.e. if
3351 ;; `file-precious-flag' is set.
3352 (nth 5 file-attr))
3353 (when (and (= (nth 2 file-attr) uid)
3354 (= (nth 3 file-attr) gid))
3355 (setq need-chown nil))))
3356
3357 ;; Set the ownership.
3358 (when need-chown
3359 (tramp-set-file-uid-gid filename uid gid))
3360 (when (or (eq visit t) (null visit) (stringp visit))
3361 (tramp-message v 0 "Wrote %s" filename))
3362 (run-hooks 'tramp-handle-write-region-hook)))))
3363
3364 (defvar tramp-vc-registered-file-names nil
3365 "List used to collect file names, which are checked during `vc-registered'.")
3366
3367 ;; VC backends check for the existence of various different special
3368 ;; files. This is very time consuming, because every single check
3369 ;; requires a remote command (the file cache must be invalidated).
3370 ;; Therefore, we apply a kind of optimization. We install the file
3371 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3372 ;; remembers all file names for which `file-exists-p' or
3373 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3374 ;; is performed. Afterwards, a script is applied for all collected
3375 ;; file names, using just one remote command. The result of this
3376 ;; script is used to fill the file cache with actual values. Now we
3377 ;; can reset the file name handlers, and we make a second run of
3378 ;; `vc-registered', which returns the expected result without sending
3379 ;; any other remote command.
3380 (defun tramp-sh-handle-vc-registered (file)
3381 "Like `vc-registered' for Tramp files."
3382 (tramp-compat-with-temp-message ""
3383 (with-parsed-tramp-file-name file nil
3384 (with-tramp-progress-reporter
3385 v 3 (format "Checking `vc-registered' for %s" file)
3386
3387 ;; There could be new files, created by the vc backend. We
3388 ;; cannot reuse the old cache entries, therefore.
3389 (let (tramp-vc-registered-file-names
3390 (remote-file-name-inhibit-cache (current-time))
3391 (file-name-handler-alist
3392 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3393
3394 ;; Here we collect only file names, which need an operation.
3395 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3396 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3397
3398 ;; Send just one command, in order to fill the cache.
3399 (when tramp-vc-registered-file-names
3400 (tramp-maybe-send-script
3401 v
3402 (format tramp-vc-registered-read-file-names
3403 (tramp-get-file-exists-command v)
3404 (format "%s -r" (tramp-get-test-command v)))
3405 "tramp_vc_registered_read_file_names")
3406
3407 (dolist
3408 (elt
3409 (tramp-send-command-and-read
3410 v
3411 (format
3412 "tramp_vc_registered_read_file_names <<'EOF'\n%s\nEOF\n"
3413 (mapconcat 'tramp-shell-quote-argument
3414 tramp-vc-registered-file-names
3415 "\n"))))
3416
3417 (tramp-set-file-property
3418 v (car elt) (cadr elt) (cadr (cdr elt))))))
3419
3420 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3421 ;; calls shall be answered from the file cache. We unset
3422 ;; `process-file-side-effects' in order to keep the cache when
3423 ;; `process-file' calls appear.
3424 (let (process-file-side-effects)
3425 (tramp-run-real-handler 'vc-registered (list file)))))))
3426
3427 ;;;###tramp-autoload
3428 (defun tramp-sh-file-name-handler (operation &rest args)
3429 "Invoke remote-shell Tramp file name handler.
3430 Fall back to normal file name handler if no Tramp handler exists."
3431 (when (and tramp-locked (not tramp-locker))
3432 (setq tramp-locked nil)
3433 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
3434 (let ((tl tramp-locked))
3435 (unwind-protect
3436 (progn
3437 (setq tramp-locked t)
3438 (let ((tramp-locker t))
3439 (save-match-data
3440 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3441 (if fn
3442 (apply (cdr fn) args)
3443 (tramp-run-real-handler operation args))))))
3444 (setq tramp-locked tl))))
3445
3446 (defun tramp-vc-file-name-handler (operation &rest args)
3447 "Invoke special file name handler, which collects files to be handled."
3448 (save-match-data
3449 (let ((filename
3450 (tramp-replace-environment-variables
3451 (apply 'tramp-file-name-for-operation operation args)))
3452 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3453 (with-parsed-tramp-file-name filename nil
3454 (cond
3455 ;; That's what we want: file names, for which checks are
3456 ;; applied. We assume that VC uses only `file-exists-p' and
3457 ;; `file-readable-p' checks; otherwise we must extend the
3458 ;; list. We do not perform any action, but return nil, in
3459 ;; order to keep `vc-registered' running.
3460 ((and fn (memq operation '(file-exists-p file-readable-p)))
3461 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3462 nil)
3463 ;; `process-file' and `start-file-process' shall be ignored.
3464 ((and fn (eq operation 'process-file) 0))
3465 ((and fn (eq operation 'start-file-process) nil))
3466 ;; Tramp file name handlers like `expand-file-name'. They
3467 ;; must still work.
3468 (fn (save-match-data (apply (cdr fn) args)))
3469 ;; Default file name handlers, we don't care.
3470 (t (tramp-run-real-handler operation args)))))))
3471
3472 ;;; Internal Functions:
3473
3474 (defun tramp-maybe-send-script (vec script name)
3475 "Define in remote shell function NAME implemented as SCRIPT.
3476 Only send the definition if it has not already been done."
3477 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3478 ;; might be nil.
3479 (let ((scripts (tramp-get-connection-property
3480 (tramp-get-connection-process vec) "scripts" nil)))
3481 (unless (member name scripts)
3482 (with-tramp-progress-reporter vec 5 (format "Sending script `%s'" name)
3483 ;; The script could contain a call of Perl. This is masked with `%s'.
3484 (tramp-barf-unless-okay
3485 vec
3486 (format "%s () {\n%s\n}" name
3487 (format script (tramp-get-remote-perl vec)))
3488 "Script %s sending failed" name)
3489 (tramp-set-connection-property
3490 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3491
3492 (defun tramp-set-auto-save ()
3493 (when (and ;; ange-ftp has its own auto-save mechanism
3494 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
3495 'tramp-sh-file-name-handler)
3496 auto-save-default)
3497 (auto-save-mode 1)))
3498 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
3499 (add-hook 'tramp-unload-hook
3500 (lambda ()
3501 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
3502
3503 (defun tramp-run-test (switch filename)
3504 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3505 Returns the exit code of the `test' program."
3506 (with-parsed-tramp-file-name filename nil
3507 (tramp-send-command-and-check
3508 v
3509 (format
3510 "%s %s %s"
3511 (tramp-get-test-command v)
3512 switch
3513 (tramp-shell-quote-argument localname)))))
3514
3515 (defun tramp-run-test2 (format-string file1 file2)
3516 "Run `test'-like program on the remote system, given FILE1, FILE2.
3517 FORMAT-STRING contains the program name, switches, and place holders.
3518 Returns the exit code of the `test' program. Barfs if the methods,
3519 hosts, or files, disagree."
3520 (unless (tramp-equal-remote file1 file2)
3521 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3522 (tramp-error
3523 v 'file-error
3524 "tramp-run-test2 only implemented for same method, user, host")))
3525 (with-parsed-tramp-file-name file1 v1
3526 (with-parsed-tramp-file-name file1 v2
3527 (tramp-send-command-and-check
3528 v1
3529 (format format-string
3530 (tramp-shell-quote-argument v1-localname)
3531 (tramp-shell-quote-argument v2-localname))))))
3532
3533 (defun tramp-find-executable
3534 (vec progname dirlist &optional ignore-tilde ignore-path)
3535 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3536 First arg VEC specifies the connection, PROGNAME is the program
3537 to search for, and DIRLIST gives the list of directories to
3538 search. If IGNORE-TILDE is non-nil, directory names starting
3539 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3540 only in DIRLIST.
3541
3542 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3543
3544 This function expects to be in the right *tramp* buffer."
3545 (with-current-buffer (tramp-get-connection-buffer vec)
3546 (let (result)
3547 ;; Check whether the executable is in $PATH. "which(1)" does not
3548 ;; report always a correct error code; therefore we check the
3549 ;; number of words it returns.
3550 (unless ignore-path
3551 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3552 (goto-char (point-min))
3553 (if (looking-at "^\\s-*1$")
3554 (setq result (concat "\\" progname))))
3555 (unless result
3556 (when ignore-tilde
3557 ;; Remove all ~/foo directories from dirlist. In XEmacs,
3558 ;; `remove' is in CL, and we want to avoid CL dependencies.
3559 (let (newdl d)
3560 (while dirlist
3561 (setq d (car dirlist))
3562 (setq dirlist (cdr dirlist))
3563 (unless (char-equal ?~ (aref d 0))
3564 (setq newdl (cons d newdl))))
3565 (setq dirlist (nreverse newdl))))
3566 (tramp-send-command
3567 vec
3568 (format (concat "while read d; "
3569 "do if test -x $d/%s -a -f $d/%s; "
3570 "then echo tramp_executable $d/%s; "
3571 "break; fi; done <<'EOF'\n"
3572 "%s\nEOF")
3573 progname progname progname (mapconcat 'identity dirlist "\n")))
3574 (goto-char (point-max))
3575 (when (search-backward "tramp_executable " nil t)
3576 (skip-chars-forward "^ ")
3577 (skip-chars-forward " ")
3578 (setq result (buffer-substring (point) (point-at-eol)))))
3579 result)))
3580
3581 (defun tramp-set-remote-path (vec)
3582 "Sets the remote environment PATH to existing directories.
3583 I.e., for each directory in `tramp-remote-path', it is tested
3584 whether it exists and if so, it is added to the environment
3585 variable PATH."
3586 (tramp-message vec 5 (format "Setting $PATH environment variable"))
3587 (tramp-send-command
3588 vec (format "PATH=%s; export PATH"
3589 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3590
3591 ;; ------------------------------------------------------------
3592 ;; -- Communication with external shell --
3593 ;; ------------------------------------------------------------
3594
3595 (defun tramp-find-file-exists-command (vec)
3596 "Find a command on the remote host for checking if a file exists.
3597 Here, we are looking for a command which has zero exit status if the
3598 file exists and nonzero exit status otherwise."
3599 (let ((existing "/")
3600 (nonexistent
3601 (tramp-shell-quote-argument "/ this file does not exist "))
3602 result)
3603 ;; The algorithm is as follows: we try a list of several commands.
3604 ;; For each command, we first run `$cmd /' -- this should return
3605 ;; true, as the root directory always exists. And then we run
3606 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3607 ;; does not exist. This should return false. We use the first
3608 ;; command we find that seems to work.
3609 ;; The list of commands to try is as follows:
3610 ;; `ls -d' This works on most systems, but NetBSD 1.4
3611 ;; has a bug: `ls' always returns zero exit
3612 ;; status, even for files which don't exist.
3613 ;; `test -e' Some Bourne shells have a `test' builtin
3614 ;; which does not know the `-e' option.
3615 ;; `/bin/test -e' For those, the `test' binary on disk normally
3616 ;; provides the option. Alas, the binary
3617 ;; is sometimes `/bin/test' and sometimes it's
3618 ;; `/usr/bin/test'.
3619 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3620 (unless (or
3621 (ignore-errors
3622 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3623 (tramp-send-command-and-check
3624 vec (format "%s %s" result existing))
3625 (not (tramp-send-command-and-check
3626 vec (format "%s %s" result nonexistent)))))
3627 (ignore-errors
3628 (and (setq result "/bin/test -e")
3629 (tramp-send-command-and-check
3630 vec (format "%s %s" result existing))
3631 (not (tramp-send-command-and-check
3632 vec (format "%s %s" result nonexistent)))))
3633 (ignore-errors
3634 (and (setq result "/usr/bin/test -e")
3635 (tramp-send-command-and-check
3636 vec (format "%s %s" result existing))
3637 (not (tramp-send-command-and-check
3638 vec (format "%s %s" result nonexistent)))))
3639 (ignore-errors
3640 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3641 (tramp-send-command-and-check
3642 vec (format "%s %s" result existing))
3643 (not (tramp-send-command-and-check
3644 vec (format "%s %s" result nonexistent))))))
3645 (tramp-error
3646 vec 'file-error "Couldn't find command to check if file exists"))
3647 result))
3648
3649 (defun tramp-open-shell (vec shell)
3650 "Opens shell SHELL."
3651 (with-tramp-progress-reporter
3652 vec 5 (format "Opening remote shell `%s'" shell)
3653 ;; Find arguments for this shell.
3654 (let ((tramp-end-of-output tramp-initial-end-of-output)
3655 (alist tramp-sh-extra-args)
3656 item extra-args)
3657 (while (and alist (null extra-args))
3658 (setq item (pop alist))
3659 (when (string-match (car item) shell)
3660 (setq extra-args (cdr item))))
3661 (tramp-send-command
3662 vec (format
3663 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3664 (tramp-shell-quote-argument tramp-end-of-output)
3665 shell (or extra-args ""))
3666 t))
3667 (tramp-set-connection-property
3668 (tramp-get-connection-process vec) "remote-shell" shell)
3669 ;; Setting prompts.
3670 (tramp-send-command
3671 vec (format "PS1=%s" (tramp-shell-quote-argument tramp-end-of-output)) t)
3672 (tramp-send-command vec "PS2=''" t)
3673 (tramp-send-command vec "PS3=''" t)
3674 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
3675
3676 (defun tramp-find-shell (vec)
3677 "Opens a shell on the remote host which groks tilde expansion."
3678 (with-current-buffer (tramp-get-buffer vec)
3679 (let ((default-shell
3680 (or
3681 (tramp-get-connection-property
3682 (tramp-get-connection-process vec) "remote-shell" nil)
3683 (tramp-get-method-parameter
3684 (tramp-file-name-method vec) 'tramp-remote-shell)))
3685 shell)
3686 (setq shell
3687 (with-tramp-connection-property vec "remote-shell"
3688 ;; CCC: "root" does not exist always, see QNAP 459.
3689 ;; Which check could we apply instead?
3690 (tramp-send-command vec "echo ~root" t)
3691 (if (or (string-match "^~root$" (buffer-string))
3692 ;; The default shell (ksh93) of OpenSolaris and
3693 ;; Solaris is buggy. We've got reports for
3694 ;; "SunOS 5.10" and "SunOS 5.11" so far.
3695 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3696 (tramp-get-connection-property
3697 vec "uname" "")))
3698
3699 (or (tramp-find-executable
3700 vec "bash" (tramp-get-remote-path vec) t t)
3701 (tramp-find-executable
3702 vec "ksh" (tramp-get-remote-path vec) t t)
3703 ;; Maybe it works at least for some other commands.
3704 (prog1
3705 default-shell
3706 (tramp-message
3707 vec 2
3708 (concat
3709 "Couldn't find a remote shell which groks tilde "
3710 "expansion, using `%s'")
3711 default-shell)))
3712
3713 default-shell)))
3714
3715 ;; Open a new shell if needed.
3716 (unless (string-equal shell default-shell)
3717 (tramp-message
3718 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
3719 (tramp-open-shell vec shell))
3720
3721 ;; Busyboxes tend to behave strange. We check for the existence.
3722 (with-tramp-connection-property vec "busybox"
3723 (tramp-send-command vec (format "%s --version" shell) t)
3724 (let ((case-fold-search t))
3725 (and (string-match "busybox" (buffer-string)) t))))))
3726
3727 ;; Utility functions.
3728
3729 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
3730 "Wait for shell prompt and barf if none appears.
3731 Looks at process PROC to see if a shell prompt appears in TIMEOUT
3732 seconds. If not, it produces an error message with the given ERROR-ARGS."
3733 (unless
3734 (tramp-wait-for-regexp
3735 proc timeout
3736 (format
3737 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
3738 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
3739
3740 (defun tramp-open-connection-setup-interactive-shell (proc vec)
3741 "Set up an interactive shell.
3742 Mainly sets the prompt and the echo correctly. PROC is the shell
3743 process to set up. VEC specifies the connection."
3744 (let ((tramp-end-of-output tramp-initial-end-of-output))
3745 ;; It is useful to set the prompt in the following command because
3746 ;; some people have a setting for $PS1 which /bin/sh doesn't know
3747 ;; about and thus /bin/sh will display a strange prompt. For
3748 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
3749 ;; display the current working directory but /bin/sh will display
3750 ;; a dollar sign. The following command line sets $PS1 to a sane
3751 ;; value, and works under Bourne-ish shells as well as csh-like
3752 ;; shells. Daniel Pittman reports that the unusual positioning of
3753 ;; the single quotes makes it work under `rc', too. We also unset
3754 ;; the variable $ENV because that is read by some sh
3755 ;; implementations (eg, bash when called as sh) on startup; this
3756 ;; way, we avoid the startup file clobbering $PS1. $PROMPT_COMMAND
3757 ;; is another way to set the prompt in /bin/bash, it must be
3758 ;; discarded as well.
3759 (tramp-open-shell
3760 vec
3761 (or (tramp-get-connection-property vec "remote-shell" nil)
3762 (tramp-get-method-parameter
3763 (tramp-file-name-method vec) 'tramp-remote-shell)))
3764
3765 ;; Disable echo.
3766 (tramp-message vec 5 "Setting up remote shell environment")
3767 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
3768 ;; Check whether the echo has really been disabled. Some
3769 ;; implementations, like busybox of embedded GNU/Linux, don't
3770 ;; support disabling.
3771 (tramp-send-command vec "echo foo" t)
3772 (with-current-buffer (process-buffer proc)
3773 (goto-char (point-min))
3774 (when (looking-at "echo foo")
3775 (tramp-set-connection-property proc "remote-echo" t)
3776 (tramp-message vec 5 "Remote echo still on. Ok.")
3777 ;; Make sure backspaces and their echo are enabled and no line
3778 ;; width magic interferes with them.
3779 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
3780
3781 (tramp-message vec 5 "Setting shell prompt")
3782 (tramp-send-command
3783 vec (format "PS1=%s" (tramp-shell-quote-argument tramp-end-of-output)) t)
3784 (tramp-send-command vec "PS2=''" t)
3785 (tramp-send-command vec "PS3=''" t)
3786 (tramp-send-command vec "PROMPT_COMMAND=''" t)
3787
3788 ;; Try to set up the coding system correctly.
3789 ;; CCC this can't be the right way to do it. Hm.
3790 (tramp-message vec 5 "Determining coding system")
3791 (tramp-send-command vec "echo foo ; echo bar" t)
3792 (with-current-buffer (process-buffer proc)
3793 (goto-char (point-min))
3794 (if (featurep 'mule)
3795 ;; Use MULE to select the right EOL convention for communicating
3796 ;; with the process.
3797 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
3798 (cons 'undecided 'undecided)))
3799 cs-decode cs-encode)
3800 (when (symbolp cs) (setq cs (cons cs cs)))
3801 (setq cs-decode (car cs))
3802 (setq cs-encode (cdr cs))
3803 (unless cs-decode (setq cs-decode 'undecided))
3804 (unless cs-encode (setq cs-encode 'undecided))
3805 (setq cs-encode (tramp-compat-coding-system-change-eol-conversion
3806 cs-encode 'unix))
3807 (when (search-forward "\r" nil t)
3808 (setq cs-decode (tramp-compat-coding-system-change-eol-conversion
3809 cs-decode 'dos)))
3810 (tramp-compat-funcall
3811 'set-buffer-process-coding-system cs-decode cs-encode)
3812 (tramp-message
3813 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
3814 ;; Look for ^M and do something useful if found.
3815 (when (search-forward "\r" nil t)
3816 ;; We have found a ^M but cannot frob the process coding system
3817 ;; because we're running on a non-MULE Emacs. Let's try
3818 ;; stty, instead.
3819 (tramp-send-command vec "stty -onlcr" t))))
3820
3821 (tramp-send-command vec "set +o vi +o emacs" t)
3822
3823 ;; Check whether the output of "uname -sr" has been changed. If
3824 ;; yes, this is a strong indication that we must expire all
3825 ;; connection properties. We start again with
3826 ;; `tramp-maybe-open-connection', it will be caught there.
3827 (tramp-message vec 5 "Checking system information")
3828 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
3829 (new-uname
3830 (tramp-set-connection-property
3831 vec "uname"
3832 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
3833 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
3834 (tramp-cleanup vec)
3835 (tramp-message
3836 vec 3
3837 "Connection reset, because remote host changed from `%s' to `%s'"
3838 old-uname new-uname)
3839 (throw 'uname-changed (tramp-maybe-open-connection vec))))
3840
3841 ;; Check whether the remote host suffers from buggy
3842 ;; `send-process-string'. This is known for FreeBSD (see comment in
3843 ;; `send_process', file process.c). I've tested sending 624 bytes
3844 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
3845 ;; this host type is detected locally. It cannot handle remote
3846 ;; hosts, though.
3847 (with-tramp-connection-property proc "chunksize"
3848 (cond
3849 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
3850 tramp-chunksize)
3851 (t
3852 (tramp-message
3853 vec 5 "Checking remote host type for `send-process-string' bug")
3854 (if (string-match
3855 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
3856 500 0))))
3857
3858 ;; Set remote PATH variable.
3859 (tramp-set-remote-path vec)
3860
3861 ;; Search for a good shell before searching for a command which
3862 ;; checks if a file exists. This is done because Tramp wants to use
3863 ;; "test foo; echo $?" to check if various conditions hold, and
3864 ;; there are buggy /bin/sh implementations which don't execute the
3865 ;; "echo $?" part if the "test" part has an error. In particular,
3866 ;; the OpenSolaris /bin/sh is a problem. There are also other
3867 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
3868 ;; in function declarations, or changing HISTFILE in place.
3869 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
3870 ;; detected.
3871 (tramp-find-shell vec)
3872
3873 ;; Disable unexpected output.
3874 (tramp-send-command vec "mesg n; biff n" t)
3875
3876 ;; IRIX64 bash expands "!" even when in single quotes. This
3877 ;; destroys our shell functions, we must disable it. See
3878 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
3879 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
3880 (tramp-send-command vec "set +H" t))
3881
3882 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
3883 (when (string-match "BSD\\|Darwin"
3884 (tramp-get-connection-property vec "uname" ""))
3885 (tramp-send-command vec "stty -oxtabs" t))
3886
3887 ;; Set `remote-tty' process property.
3888 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
3889 (unless (zerop (length tty))
3890 (tramp-compat-process-put proc 'remote-tty tty)))
3891
3892 ;; Dump stty settings in the traces.
3893 (when (>= tramp-verbose 9)
3894 (tramp-send-command vec "stty -a" t))
3895
3896 ;; Set the environment.
3897 (tramp-message vec 5 "Setting default environment")
3898
3899 (let ((env (copy-sequence tramp-remote-process-environment))
3900 unset item)
3901 (while env
3902 (setq item (tramp-compat-split-string (car env) "="))
3903 (setcdr item (mapconcat 'identity (cdr item) "="))
3904 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
3905 (tramp-send-command
3906 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
3907 (push (car item) unset))
3908 (setq env (cdr env)))
3909 (when unset
3910 (tramp-send-command
3911 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
3912
3913 ;; CCC: We should either implement a Perl version of base64 encoding
3914 ;; and decoding. Then we just use that in the last item. The other
3915 ;; alternative is to use the Perl version of UU encoding. But then
3916 ;; we need a Lisp version of uuencode.
3917 ;;
3918 ;; Old text from documentation of tramp-methods:
3919 ;; Using a uuencode/uudecode inline method is discouraged, please use one
3920 ;; of the base64 methods instead since base64 encoding is much more
3921 ;; reliable and the commands are more standardized between the different
3922 ;; Unix versions. But if you can't use base64 for some reason, please
3923 ;; note that the default uudecode command does not work well for some
3924 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
3925 ;; the following command for uudecode:
3926 ;;
3927 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
3928 ;;
3929 ;; For Irix, no solution is known yet.
3930
3931 (autoload 'uudecode-decode-region "uudecode")
3932
3933 (defconst tramp-local-coding-commands
3934 '((b64 base64-encode-region base64-decode-region)
3935 (uu tramp-uuencode-region uudecode-decode-region)
3936 (pack
3937 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
3938 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
3939 "List of local coding commands for inline transfer.
3940 Each item is a list that looks like this:
3941
3942 \(FORMAT ENCODING DECODING\)
3943
3944 FORMAT is symbol describing the encoding/decoding format. It can be
3945 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
3946
3947 ENCODING and DECODING can be strings, giving commands, or symbols,
3948 giving functions. If they are strings, then they can contain
3949 the \"%s\" format specifier. If that specifier is present, the input
3950 filename will be put into the command line at that spot. If the
3951 specifier is not present, the input should be read from standard
3952 input.
3953
3954 If they are functions, they will be called with two arguments, start
3955 and end of region, and are expected to replace the region contents
3956 with the encoded or decoded results, respectively.")
3957
3958 (defconst tramp-remote-coding-commands
3959 '((b64 "base64" "base64 -d -i")
3960 ;; "-i" is more robust with older base64 from GNU coreutils.
3961 ;; However, I don't know whether all base64 versions do supports
3962 ;; this option.
3963 (b64 "base64" "base64 -d")
3964 (b64 "mimencode -b" "mimencode -u -b")
3965 (b64 "mmencode -b" "mmencode -u -b")
3966 (b64 "recode data..base64" "recode base64..data")
3967 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
3968 (b64 tramp-perl-encode tramp-perl-decode)
3969 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
3970 (uu "uuencode xxx" "uudecode -o -")
3971 (uu "uuencode xxx" "uudecode -p")
3972 (uu "uuencode xxx" tramp-uudecode)
3973 (pack
3974 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
3975 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
3976 "List of remote coding commands for inline transfer.
3977 Each item is a list that looks like this:
3978
3979 \(FORMAT ENCODING DECODING [TEST]\)
3980
3981 FORMAT is symbol describing the encoding/decoding format. It can be
3982 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
3983
3984 ENCODING and DECODING can be strings, giving commands, or symbols,
3985 giving variables. If they are strings, then they can contain
3986 the \"%s\" format specifier. If that specifier is present, the input
3987 filename will be put into the command line at that spot. If the
3988 specifier is not present, the input should be read from standard
3989 input.
3990
3991 If they are variables, this variable is a string containing a Perl
3992 implementation for this functionality. This Perl program will be transferred
3993 to the remote host, and it is available as shell function with the same name.
3994
3995 The optional TEST command can be used for further tests, whether
3996 ENCODING and DECODING are applicable.")
3997
3998 (defun tramp-find-inline-encoding (vec)
3999 "Find an inline transfer encoding that works.
4000 Goes through the list `tramp-local-coding-commands' and
4001 `tramp-remote-coding-commands'."
4002 (save-excursion
4003 (let ((local-commands tramp-local-coding-commands)
4004 (magic "xyzzy")
4005 (p (tramp-get-connection-process vec))
4006 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4007 (while (and local-commands (not found))
4008 (setq litem (pop local-commands))
4009 (catch 'wont-work-local
4010 (let ((format (nth 0 litem))
4011 (remote-commands tramp-remote-coding-commands))
4012 (setq loc-enc (nth 1 litem))
4013 (setq loc-dec (nth 2 litem))
4014 ;; If the local encoder or decoder is a string, the
4015 ;; corresponding command has to work locally.
4016 (if (not (stringp loc-enc))
4017 (tramp-message
4018 vec 5 "Checking local encoding function `%s'" loc-enc)
4019 (tramp-message
4020 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4021 (unless (zerop (tramp-call-local-coding-command
4022 loc-enc nil nil))
4023 (throw 'wont-work-local nil)))
4024 (if (not (stringp loc-dec))
4025 (tramp-message
4026 vec 5 "Checking local decoding function `%s'" loc-dec)
4027 (tramp-message
4028 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4029 (unless (zerop (tramp-call-local-coding-command
4030 loc-dec nil nil))
4031 (throw 'wont-work-local nil)))
4032 ;; Search for remote coding commands with the same format
4033 (while (and remote-commands (not found))
4034 (setq ritem (pop remote-commands))
4035 (catch 'wont-work-remote
4036 (when (equal format (nth 0 ritem))
4037 (setq rem-enc (nth 1 ritem))
4038 (setq rem-dec (nth 2 ritem))
4039 (setq rem-test (nth 3 ritem))
4040 ;; Check the remote test command if exists.
4041 (when (stringp rem-test)
4042 (tramp-message
4043 vec 5 "Checking remote test command `%s'" rem-test)
4044 (unless (tramp-send-command-and-check vec rem-test t)
4045 (throw 'wont-work-remote nil)))
4046 ;; Check if remote encoding and decoding commands can be
4047 ;; called remotely with null input and output. This makes
4048 ;; sure there are no syntax errors and the command is really
4049 ;; found. Note that we do not redirect stdout to /dev/null,
4050 ;; for two reasons: when checking the decoding command, we
4051 ;; actually check the output it gives. And also, when
4052 ;; redirecting "mimencode" output to /dev/null, then as root
4053 ;; it might change the permissions of /dev/null!
4054 (when (not (stringp rem-enc))
4055 (let ((name (symbol-name rem-enc)))
4056 (while (string-match (regexp-quote "-") name)
4057 (setq name (replace-match "_" nil t name)))
4058 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4059 (setq rem-enc name)))
4060 (tramp-message
4061 vec 5
4062 "Checking remote encoding command `%s' for sanity" rem-enc)
4063 (unless (tramp-send-command-and-check
4064 vec (format "%s </dev/null" rem-enc) t)
4065 (throw 'wont-work-remote nil))
4066
4067 (when (not (stringp rem-dec))
4068 (let ((name (symbol-name rem-dec)))
4069 (while (string-match (regexp-quote "-") name)
4070 (setq name (replace-match "_" nil t name)))
4071 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
4072 (setq rem-dec name)))
4073 (tramp-message
4074 vec 5
4075 "Checking remote decoding command `%s' for sanity" rem-dec)
4076 (unless (tramp-send-command-and-check
4077 vec
4078 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4079 t)
4080 (throw 'wont-work-remote nil))
4081
4082 (with-current-buffer (tramp-get-buffer vec)
4083 (goto-char (point-min))
4084 (unless (looking-at (regexp-quote magic))
4085 (throw 'wont-work-remote nil)))
4086
4087 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4088 (setq rem-enc (nth 1 ritem))
4089 (setq rem-dec (nth 2 ritem))
4090 (setq found t)))))))
4091
4092 ;; Did we find something?
4093 (unless found
4094 (tramp-error
4095 vec 'file-error "Couldn't find an inline transfer encoding"))
4096
4097 ;; Set connection properties. Since the commands are risky (due
4098 ;; to output direction), we cache them in the process cache.
4099 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4100 (tramp-set-connection-property p "local-encoding" loc-enc)
4101 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4102 (tramp-set-connection-property p "local-decoding" loc-dec)
4103 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4104 (tramp-set-connection-property p "remote-encoding" rem-enc)
4105 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4106 (tramp-set-connection-property p "remote-decoding" rem-dec))))
4107
4108 (defun tramp-call-local-coding-command (cmd input output)
4109 "Call the local encoding or decoding command.
4110 If CMD contains \"%s\", provide input file INPUT there in command.
4111 Otherwise, INPUT is passed via standard input.
4112 INPUT can also be nil which means `/dev/null'.
4113 OUTPUT can be a string (which specifies a filename), or t (which
4114 means standard output and thus the current buffer), or nil (which
4115 means discard it)."
4116 (tramp-compat-call-process
4117 tramp-encoding-shell
4118 (when (and input (not (string-match "%s" cmd))) input)
4119 (if (eq output t) t nil)
4120 nil
4121 tramp-encoding-command-switch
4122 (concat
4123 (if (string-match "%s" cmd) (format cmd input) cmd)
4124 (if (stringp output) (concat "> " output) ""))))
4125
4126 (defconst tramp-inline-compress-commands
4127 '(("gzip" "gzip -d")
4128 ("bzip2" "bzip2 -d")
4129 ("xz" "xz -d")
4130 ("compress" "compress -d"))
4131 "List of compress and decompress commands for inline transfer.
4132 Each item is a list that looks like this:
4133
4134 \(COMPRESS DECOMPRESS\)
4135
4136 COMPRESS or DECOMPRESS are strings with the respective commands.")
4137
4138 (defun tramp-find-inline-compress (vec)
4139 "Find an inline transfer compress command that works.
4140 Goes through the list `tramp-inline-compress-commands'."
4141 (save-excursion
4142 (let ((commands tramp-inline-compress-commands)
4143 (magic "xyzzy")
4144 (p (tramp-get-connection-process vec))
4145 item compress decompress found)
4146 (while (and commands (not found))
4147 (catch 'next
4148 (setq item (pop commands)
4149 compress (nth 0 item)
4150 decompress (nth 1 item))
4151 (tramp-message
4152 vec 5
4153 "Checking local compress command `%s', `%s' for sanity"
4154 compress decompress)
4155 (unless
4156 (zerop
4157 (tramp-call-local-coding-command
4158 (format
4159 ;; Windows shells need the program file name after
4160 ;; the pipe symbol be quoted if they use forward
4161 ;; slashes as directory separators.
4162 (if (memq system-type '(windows-nt))
4163 "echo %s | \"%s\" | \"%s\""
4164 "echo %s | %s | %s")
4165 magic compress decompress) nil nil))
4166 (throw 'next nil))
4167 (tramp-message
4168 vec 5
4169 "Checking remote compress command `%s', `%s' for sanity"
4170 compress decompress)
4171 (unless (tramp-send-command-and-check
4172 vec (format "echo %s | %s | %s" magic compress decompress) t)
4173 (throw 'next nil))
4174 (setq found t)))
4175
4176 ;; Did we find something?
4177 (if found
4178 (progn
4179 ;; Set connection properties. Since the commands are
4180 ;; risky (due to output direction), we cache them in the
4181 ;; process cache.
4182 (tramp-message
4183 vec 5 "Using inline transfer compress command `%s'" compress)
4184 (tramp-set-connection-property p "inline-compress" compress)
4185 (tramp-message
4186 vec 5 "Using inline transfer decompress command `%s'" decompress)
4187 (tramp-set-connection-property p "inline-decompress" decompress))
4188
4189 (tramp-set-connection-property p "inline-compress" nil)
4190 (tramp-set-connection-property p "inline-decompress" nil)
4191 (tramp-message
4192 vec 2 "Couldn't find an inline transfer compress command")))))
4193
4194 (defvar tramp-gw-tunnel-method)
4195 (defvar tramp-gw-socks-method)
4196
4197 (defun tramp-compute-multi-hops (vec)
4198 "Expands VEC according to `tramp-default-proxies-alist'.
4199 Gateway hops are already opened."
4200 (let ((target-alist `(,vec))
4201 (hops (or (tramp-file-name-hop vec) ""))
4202 (item vec)
4203 choices proxy)
4204
4205 ;; Ad-hoc proxy definitions.
4206 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4207 (let ((user (tramp-file-name-user item))
4208 (host (tramp-file-name-host item))
4209 (proxy (concat
4210 tramp-prefix-format proxy tramp-postfix-host-format)))
4211 (tramp-message
4212 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4213 (and (stringp host) (regexp-quote host))
4214 (and (stringp user) (regexp-quote user))
4215 proxy)
4216 ;; Add the hop.
4217 (add-to-list
4218 'tramp-default-proxies-alist
4219 (list (and (stringp host) (regexp-quote host))
4220 (and (stringp user) (regexp-quote user))
4221 proxy))
4222 (setq item (tramp-dissect-file-name proxy))))
4223 ;; Save the new value.
4224 (when (and hops tramp-save-ad-hoc-proxies)
4225 (customize-save-variable
4226 'tramp-default-proxies-alist tramp-default-proxies-alist))
4227
4228 ;; Look for proxy hosts to be passed.
4229 (setq choices tramp-default-proxies-alist)
4230 (while choices
4231 (setq item (pop choices)
4232 proxy (eval (nth 2 item)))
4233 (when (and
4234 ;; Host.
4235 (string-match (or (eval (nth 0 item)) "")
4236 (or (tramp-file-name-host (car target-alist)) ""))
4237 ;; User.
4238 (string-match (or (eval (nth 1 item)) "")
4239 (or (tramp-file-name-user (car target-alist)) "")))
4240 (if (null proxy)
4241 ;; No more hops needed.
4242 (setq choices nil)
4243 ;; Replace placeholders.
4244 (setq proxy
4245 (format-spec
4246 proxy
4247 (format-spec-make
4248 ?u (or (tramp-file-name-user (car target-alist)) "")
4249 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4250 (with-parsed-tramp-file-name proxy l
4251 ;; Add the hop.
4252 (add-to-list 'target-alist l)
4253 ;; Start next search.
4254 (setq choices tramp-default-proxies-alist)))))
4255
4256 ;; Handle gateways.
4257 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4258 (string-match
4259 (format
4260 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4261 (tramp-file-name-method (car target-alist))))
4262 (let ((gw (pop target-alist))
4263 (hop (pop target-alist)))
4264 ;; Is the method prepared for gateways?
4265 (unless (tramp-file-name-port hop)
4266 (tramp-error
4267 vec 'file-error
4268 "Connection `%s' is not supported for gateway access." hop))
4269 ;; Open the gateway connection.
4270 (add-to-list
4271 'target-alist
4272 (vector
4273 (tramp-file-name-method hop) (tramp-file-name-user hop)
4274 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil nil))
4275 ;; For the password prompt, we need the correct values.
4276 ;; Therefore, we must remember the gateway vector. But we
4277 ;; cannot do it as connection property, because it shouldn't
4278 ;; be persistent. And we have no started process yet either.
4279 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
4280
4281 ;; Foreign and out-of-band methods are not supported for multi-hops.
4282 (when (cdr target-alist)
4283 (setq choices target-alist)
4284 (while choices
4285 (setq item (pop choices))
4286 (when
4287 (or
4288 (not
4289 (tramp-get-method-parameter
4290 (tramp-file-name-method item) 'tramp-login-program))
4291 (tramp-get-method-parameter
4292 (tramp-file-name-method item) 'tramp-copy-program))
4293 (tramp-error
4294 vec 'file-error
4295 "Method `%s' is not supported for multi-hops."
4296 (tramp-file-name-method item)))))
4297
4298 ;; In case the host name is not used for the remote shell
4299 ;; command, the user could be misguided by applying a random
4300 ;; hostname.
4301 (let* ((v (car target-alist))
4302 (method (tramp-file-name-method v))
4303 (host (tramp-file-name-host v)))
4304 (unless
4305 (or
4306 ;; There are multi-hops.
4307 (cdr target-alist)
4308 ;; The host name is used for the remote shell command.
4309 (member
4310 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
4311 ;; The host is local. We cannot use `tramp-local-host-p'
4312 ;; here, because it opens a connection as well.
4313 (string-match tramp-local-host-regexp host))
4314 (tramp-error
4315 v 'file-error
4316 "Host `%s' looks like a remote host, `%s' can only use the local host"
4317 host method)))
4318
4319 ;; Result.
4320 target-alist))
4321
4322 (defvar tramp-current-connection nil
4323 "Last connection timestamp.")
4324
4325 (defun tramp-maybe-open-connection (vec)
4326 "Maybe open a connection VEC.
4327 Does not do anything if a connection is already open, but re-opens the
4328 connection if a previous connection has died for some reason."
4329 (catch 'uname-changed
4330 (let ((p (tramp-get-connection-process vec))
4331 (process-name (tramp-get-connection-property vec "process-name" nil))
4332 (process-environment (copy-sequence process-environment))
4333 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4334
4335 ;; If Tramp opens the same connection within a short time frame,
4336 ;; there is a problem. We shall signal this.
4337 (unless (or (and p (processp p) (memq (process-status p) '(run open)))
4338 (not (equal (butlast (append vec nil))
4339 (car tramp-current-connection)))
4340 (> (tramp-time-diff
4341 (current-time) (cdr tramp-current-connection))
4342 (or tramp-connection-min-time-diff 0)))
4343 (throw 'suppress 'suppress))
4344
4345 ;; If too much time has passed since last command was sent, look
4346 ;; whether process is still alive. If it isn't, kill it. When
4347 ;; using ssh, it can sometimes happen that the remote end has
4348 ;; hung up but the local ssh client doesn't recognize this until
4349 ;; it tries to send some data to the remote end. So that's why
4350 ;; we try to send a command from time to time, then look again
4351 ;; whether the process is really alive.
4352 (condition-case nil
4353 (when (and (> (tramp-time-diff
4354 (current-time)
4355 (tramp-get-connection-property
4356 p "last-cmd-time" '(0 0 0)))
4357 60)
4358 p (processp p) (memq (process-status p) '(run open)))
4359 (tramp-send-command vec "echo are you awake" t t)
4360 (unless (and (memq (process-status p) '(run open))
4361 (tramp-wait-for-output p 10))
4362 ;; The error will be caught locally.
4363 (tramp-error vec 'file-error "Awake did fail")))
4364 (file-error
4365 (tramp-cleanup vec)
4366 (setq p nil)))
4367
4368 ;; New connection must be opened.
4369 (condition-case err
4370 (unless (and p (processp p) (memq (process-status p) '(run open)))
4371
4372 ;; We call `tramp-get-buffer' in order to get a debug
4373 ;; buffer for messages from the beginning.
4374 (tramp-get-buffer vec)
4375
4376 ;; If `non-essential' is non-nil, don't reopen a new connection.
4377 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4378 (throw 'non-essential 'non-essential))
4379
4380 (with-tramp-progress-reporter
4381 vec 3
4382 (if (zerop (length (tramp-file-name-user vec)))
4383 (format "Opening connection for %s using %s"
4384 (tramp-file-name-host vec)
4385 (tramp-file-name-method vec))
4386 (format "Opening connection for %s@%s using %s"
4387 (tramp-file-name-user vec)
4388 (tramp-file-name-host vec)
4389 (tramp-file-name-method vec)))
4390
4391 ;; Start new process.
4392 (when (and p (processp p))
4393 (delete-process p))
4394 (setenv "TERM" tramp-terminal-type)
4395 (setenv "LC_ALL" "C")
4396 (setenv "PROMPT_COMMAND")
4397 (setenv "PS1" tramp-initial-end-of-output)
4398 (let* ((target-alist (tramp-compute-multi-hops vec))
4399 (process-connection-type tramp-process-connection-type)
4400 (process-adaptive-read-buffering nil)
4401 (coding-system-for-read nil)
4402 ;; This must be done in order to avoid our file
4403 ;; name handler.
4404 (p (let ((default-directory
4405 (tramp-compat-temporary-file-directory)))
4406 (apply
4407 'start-process
4408 (tramp-get-connection-name vec)
4409 (tramp-get-connection-buffer vec)
4410 (if tramp-encoding-command-interactive
4411 (list tramp-encoding-shell
4412 tramp-encoding-command-interactive)
4413 (list tramp-encoding-shell))))))
4414
4415 ;; Set sentinel and query flag.
4416 (tramp-set-connection-property p "vector" vec)
4417 (set-process-sentinel p 'tramp-process-sentinel)
4418 (tramp-compat-set-process-query-on-exit-flag p nil)
4419 (setq tramp-current-connection
4420 (cons (butlast (append vec nil)) (current-time))
4421 tramp-current-host (system-name))
4422
4423 (tramp-message
4424 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4425
4426 ;; Check whether process is alive.
4427 (tramp-barf-if-no-shell-prompt
4428 p 60
4429 "Couldn't find local shell prompt %s" tramp-encoding-shell)
4430
4431 ;; Now do all the connections as specified.
4432 (while target-alist
4433 (let* ((hop (car target-alist))
4434 (l-method (tramp-file-name-method hop))
4435 (l-user (tramp-file-name-user hop))
4436 (l-host (tramp-file-name-host hop))
4437 (l-port nil)
4438 (login-program
4439 (tramp-get-method-parameter
4440 l-method 'tramp-login-program))
4441 (login-args
4442 (tramp-get-method-parameter
4443 l-method 'tramp-login-args))
4444 (async-args
4445 (tramp-get-method-parameter
4446 l-method 'tramp-async-args))
4447 (gw-args
4448 (tramp-get-method-parameter l-method 'tramp-gw-args))
4449 (gw (tramp-get-file-property hop "" "gateway" nil))
4450 (g-method (and gw (tramp-file-name-method gw)))
4451 (g-user (and gw (tramp-file-name-user gw)))
4452 (g-host (and gw (tramp-file-name-real-host gw)))
4453 (command login-program)
4454 ;; We don't create the temporary file. In
4455 ;; fact, it is just a prefix for the
4456 ;; ControlPath option of ssh; the real
4457 ;; temporary file has another name, and it is
4458 ;; created and protected by ssh. It is also
4459 ;; removed by ssh when the connection is
4460 ;; closed. The temporary file name is cached
4461 ;; in the main connection process, therefore
4462 ;; we cannot use `tramp-get-connection-process'.
4463 (tmpfile
4464 (with-tramp-connection-property
4465 (get-process (tramp-buffer-name vec)) "temp-file"
4466 (make-temp-name
4467 (expand-file-name
4468 tramp-temp-name-prefix
4469 (tramp-compat-temporary-file-directory)))))
4470 spec r-shell)
4471
4472 ;; Add arguments for asynchronous processes.
4473 (when (and process-name async-args)
4474 (setq login-args (append async-args login-args)))
4475
4476 ;; Add gateway arguments if necessary.
4477 (when (and gw gw-args)
4478 (setq login-args (append gw-args login-args)))
4479
4480 ;; Check for port number. Until now, there's no
4481 ;; need for handling like method, user, host.
4482 (when (string-match tramp-host-with-port-regexp l-host)
4483 (setq l-port (match-string 2 l-host)
4484 l-host (match-string 1 l-host)))
4485
4486 ;; Check, whether there is a restricted shell.
4487 (dolist (elt tramp-restricted-shell-hosts-alist)
4488 (when (string-match elt tramp-current-host)
4489 (setq r-shell t)))
4490
4491 ;; Set variables for computing the prompt for
4492 ;; reading password. They can also be derived
4493 ;; from a gateway.
4494 (setq tramp-current-method (or g-method l-method)
4495 tramp-current-user (or g-user l-user)
4496 tramp-current-host (or g-host l-host))
4497
4498 ;; Replace login-args place holders.
4499 (setq
4500 l-host (or l-host "")
4501 l-user (or l-user "")
4502 l-port (or l-port "")
4503 spec (format-spec-make
4504 ?h l-host ?u l-user ?p l-port ?t tmpfile)
4505 command
4506 (concat
4507 ;; We do not want to see the trailing local
4508 ;; prompt in `start-file-process'.
4509 (unless r-shell "exec ")
4510 command " "
4511 (mapconcat
4512 (lambda (x)
4513 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4514 (unless (member "" x) (mapconcat 'identity x " ")))
4515 login-args " ")
4516 ;; Local shell could be a Windows COMSPEC. It
4517 ;; doesn't know the ";" syntax, but we must exit
4518 ;; always for `start-file-process'. It could
4519 ;; also be a restricted shell, which does not
4520 ;; allow "exec".
4521 (when r-shell " && exit || exit")))
4522
4523 ;; Send the command.
4524 (tramp-message vec 3 "Sending command `%s'" command)
4525 (tramp-send-command vec command t t)
4526 (tramp-process-actions
4527 p vec pos tramp-actions-before-shell 60)
4528 (tramp-message
4529 vec 3 "Found remote shell prompt on `%s'" l-host))
4530 ;; Next hop.
4531 (setq target-alist (cdr target-alist)))
4532
4533 ;; Make initial shell settings.
4534 (tramp-open-connection-setup-interactive-shell p vec))))
4535
4536 ;; When the user did interrupt, we must cleanup.
4537 (quit
4538 (tramp-cleanup vec)
4539 ;; Propagate the quit signal.
4540 (signal (car err) (cdr err)))))))
4541
4542 (defun tramp-send-command (vec command &optional neveropen nooutput)
4543 "Send the COMMAND to connection VEC.
4544 Erases temporary buffer before sending the command. If optional
4545 arg NEVEROPEN is non-nil, never try to open the connection. This
4546 is meant to be used from `tramp-maybe-open-connection' only. The
4547 function waits for output unless NOOUTPUT is set."
4548 (unless neveropen (tramp-maybe-open-connection vec))
4549 (let ((p (tramp-get-connection-process vec)))
4550 (when (tramp-get-connection-property p "remote-echo" nil)
4551 ;; We mark the command string that it can be erased in the output buffer.
4552 (tramp-set-connection-property p "check-remote-echo" t)
4553 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4554 (when (and (string-match "<<'EOF'" command)
4555 (not (tramp-get-connection-property vec "busybox" nil)))
4556 ;; Unset $PS1 when using here documents, in order to avoid
4557 ;; multiple prompts.
4558 (setq command (concat "(PS1= ; " command "\n)")))
4559 ;; Send the command.
4560 (tramp-message vec 6 "%s" command)
4561 (tramp-send-string vec command)
4562 (unless nooutput (tramp-wait-for-output p))))
4563
4564 (defun tramp-wait-for-output (proc &optional timeout)
4565 "Wait for output from remote command."
4566 (unless (buffer-live-p (process-buffer proc))
4567 (delete-process proc)
4568 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4569 (with-current-buffer (process-buffer proc)
4570 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4571 ;; be leading escape sequences, which must be ignored.
4572 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
4573 ;; Sometimes, the commands do not return a newline but a
4574 ;; null byte before the shell prompt, for example "git
4575 ;; ls-files -c -z ...".
4576 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4577 (found (tramp-wait-for-regexp proc timeout regexp1)))
4578 (if found
4579 (let (buffer-read-only)
4580 ;; A simple-minded busybox has sent " ^H" sequences.
4581 ;; Delete them.
4582 (goto-char (point-min))
4583 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4584 (forward-line 1)
4585 (delete-region (point-min) (point)))
4586 ;; Delete the prompt.
4587 (goto-char (point-max))
4588 (re-search-backward regexp nil t)
4589 (delete-region (point) (point-max)))
4590 (if timeout
4591 (tramp-error
4592 proc 'file-error
4593 "[[Remote prompt `%s' not found in %d secs]]"
4594 tramp-end-of-output timeout)
4595 (tramp-error
4596 proc 'file-error
4597 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
4598 ;; Return value is whether end-of-output sentinel was found.
4599 found)))
4600
4601 (defun tramp-send-command-and-check
4602 (vec command &optional subshell dont-suppress-err)
4603 "Run COMMAND and check its exit status.
4604 Sends `echo $?' along with the COMMAND for checking the exit status. If
4605 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
4606
4607 If the optional argument SUBSHELL is non-nil, the command is
4608 executed in a subshell, ie surrounded by parentheses. If
4609 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
4610 (tramp-send-command
4611 vec
4612 (concat (if subshell "( " "")
4613 command
4614 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
4615 "echo tramp_exit_status $?"
4616 (if subshell " )" "")))
4617 (with-current-buffer (tramp-get-connection-buffer vec)
4618 (goto-char (point-max))
4619 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
4620 (tramp-error
4621 vec 'file-error "Couldn't find exit status of `%s'" command))
4622 (skip-chars-forward "^ ")
4623 (prog1
4624 (zerop (read (current-buffer)))
4625 (let (buffer-read-only)
4626 (delete-region (match-beginning 0) (point-max))))))
4627
4628 (defun tramp-barf-unless-okay (vec command fmt &rest args)
4629 "Run COMMAND, check exit status, throw error if exit status not okay.
4630 Similar to `tramp-send-command-and-check' but accepts two more arguments
4631 FMT and ARGS which are passed to `error'."
4632 (or (tramp-send-command-and-check vec command)
4633 (apply 'tramp-error vec 'file-error fmt args)))
4634
4635 (defun tramp-send-command-and-read (vec command &optional noerror)
4636 "Run COMMAND and return the output, which must be a Lisp expression.
4637 In case there is no valid Lisp expression and NOERROR is nil, it
4638 raises an error."
4639 (when (if noerror
4640 (tramp-send-command-and-check vec command)
4641 (tramp-barf-unless-okay
4642 vec command "`%s' returns with error" command))
4643 (with-current-buffer (tramp-get-connection-buffer vec)
4644 ;; Read the expression.
4645 (goto-char (point-min))
4646 (condition-case nil
4647 (prog1 (read (current-buffer))
4648 ;; Error handling.
4649 (when (re-search-forward "\\S-" (point-at-eol) t)
4650 (error nil)))
4651 (error (unless noerror
4652 (tramp-error
4653 vec 'file-error
4654 "`%s' does not return a valid Lisp expression: `%s'"
4655 command (buffer-string))))))))
4656
4657 (defun tramp-convert-file-attributes (vec attr)
4658 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
4659 Convert file mode bits to string and set virtual device number.
4660 Return ATTR."
4661 (when attr
4662 ;; Remove color escape sequences from symlink.
4663 (when (stringp (car attr))
4664 (while (string-match tramp-color-escape-sequence-regexp (car attr))
4665 (setcar attr (replace-match "" nil nil (car attr)))))
4666 ;; Convert uid and gid. Use -1 as indication of unusable value.
4667 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
4668 (setcar (nthcdr 2 attr) -1))
4669 (when (and (floatp (nth 2 attr))
4670 (<= (nth 2 attr) (tramp-compat-most-positive-fixnum)))
4671 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
4672 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
4673 (setcar (nthcdr 3 attr) -1))
4674 (when (and (floatp (nth 3 attr))
4675 (<= (nth 3 attr) (tramp-compat-most-positive-fixnum)))
4676 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
4677 ;; Convert last access time.
4678 (unless (listp (nth 4 attr))
4679 (setcar (nthcdr 4 attr)
4680 (list (floor (nth 4 attr) 65536)
4681 (floor (mod (nth 4 attr) 65536)))))
4682 ;; Convert last modification time.
4683 (unless (listp (nth 5 attr))
4684 (setcar (nthcdr 5 attr)
4685 (list (floor (nth 5 attr) 65536)
4686 (floor (mod (nth 5 attr) 65536)))))
4687 ;; Convert last status change time.
4688 (unless (listp (nth 6 attr))
4689 (setcar (nthcdr 6 attr)
4690 (list (floor (nth 6 attr) 65536)
4691 (floor (mod (nth 6 attr) 65536)))))
4692 ;; Convert file size.
4693 (when (< (nth 7 attr) 0)
4694 (setcar (nthcdr 7 attr) -1))
4695 (when (and (floatp (nth 7 attr))
4696 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
4697 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
4698 ;; Convert file mode bits to string.
4699 (unless (stringp (nth 8 attr))
4700 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
4701 (when (stringp (car attr))
4702 (aset (nth 8 attr) 0 ?l)))
4703 ;; Convert directory indication bit.
4704 (when (string-match "^d" (nth 8 attr))
4705 (setcar attr t))
4706 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
4707 (when (consp (car attr))
4708 (if (and (stringp (caar attr))
4709 (string-match ".+ -> .\\(.+\\)." (caar attr)))
4710 (setcar attr (match-string 1 (caar attr)))
4711 (setcar attr nil)))
4712 ;; Set file's gid change bit.
4713 (setcar (nthcdr 9 attr)
4714 (if (numberp (nth 3 attr))
4715 (not (= (nth 3 attr)
4716 (tramp-get-remote-gid vec 'integer)))
4717 (not (string-equal
4718 (nth 3 attr)
4719 (tramp-get-remote-gid vec 'string)))))
4720 ;; Convert inode.
4721 (unless (listp (nth 10 attr))
4722 (setcar (nthcdr 10 attr)
4723 (condition-case nil
4724 (cons (floor (nth 10 attr) 65536)
4725 (floor (mod (nth 10 attr) 65536)))
4726 ;; Inodes can be incredible huge. We must hide this.
4727 (error (tramp-get-inode vec)))))
4728 ;; Set virtual device number.
4729 (setcar (nthcdr 11 attr)
4730 (tramp-get-device vec))
4731 attr))
4732
4733 (defun tramp-check-cached-permissions (vec access)
4734 "Check `file-attributes' caches for VEC.
4735 Return t if according to the cache access type ACCESS is known to
4736 be granted."
4737 (let ((result nil)
4738 (offset (cond
4739 ((eq ?r access) 1)
4740 ((eq ?w access) 2)
4741 ((eq ?x access) 3))))
4742 (dolist (suffix '("string" "integer") result)
4743 (setq
4744 result
4745 (or
4746 result
4747 (let ((file-attr
4748 (tramp-get-file-property
4749 vec (tramp-file-name-localname vec)
4750 (concat "file-attributes-" suffix) nil))
4751 (remote-uid
4752 (tramp-get-connection-property
4753 vec (concat "uid-" suffix) nil))
4754 (remote-gid
4755 (tramp-get-connection-property
4756 vec (concat "gid-" suffix) nil)))
4757 (and
4758 file-attr
4759 (or
4760 ;; Not a symlink
4761 (eq t (car file-attr))
4762 (null (car file-attr)))
4763 (or
4764 ;; World accessible.
4765 (eq access (aref (nth 8 file-attr) (+ offset 6)))
4766 ;; User accessible and owned by user.
4767 (and
4768 (eq access (aref (nth 8 file-attr) offset))
4769 (equal remote-uid (nth 2 file-attr)))
4770 ;; Group accessible and owned by user's
4771 ;; principal group.
4772 (and
4773 (eq access (aref (nth 8 file-attr) (+ offset 3)))
4774 (equal remote-gid (nth 3 file-attr)))))))))))
4775
4776 (defun tramp-file-mode-from-int (mode)
4777 "Turn an integer representing a file mode into an ls(1)-like string."
4778 (let ((type (cdr
4779 (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
4780 (user (logand (lsh mode -6) 7))
4781 (group (logand (lsh mode -3) 7))
4782 (other (logand (lsh mode -0) 7))
4783 (suid (> (logand (lsh mode -9) 4) 0))
4784 (sgid (> (logand (lsh mode -9) 2) 0))
4785 (sticky (> (logand (lsh mode -9) 1) 0)))
4786 (setq user (tramp-file-mode-permissions user suid "s"))
4787 (setq group (tramp-file-mode-permissions group sgid "s"))
4788 (setq other (tramp-file-mode-permissions other sticky "t"))
4789 (concat type user group other)))
4790
4791 (defun tramp-file-mode-permissions (perm suid suid-text)
4792 "Convert a permission bitset into a string.
4793 This is used internally by `tramp-file-mode-from-int'."
4794 (let ((r (> (logand perm 4) 0))
4795 (w (> (logand perm 2) 0))
4796 (x (> (logand perm 1) 0)))
4797 (concat (or (and r "r") "-")
4798 (or (and w "w") "-")
4799 (or (and suid x suid-text) ; suid, execute
4800 (and suid (upcase suid-text)) ; suid, !execute
4801 (and x "x") "-")))) ; !suid
4802
4803 (defun tramp-shell-case-fold (string)
4804 "Converts STRING to shell glob pattern which ignores case."
4805 (mapconcat
4806 (lambda (c)
4807 (if (equal (downcase c) (upcase c))
4808 (vector c)
4809 (format "[%c%c]" (downcase c) (upcase c))))
4810 string
4811 ""))
4812
4813 (defun tramp-make-copy-program-file-name (vec)
4814 "Create a file name suitable to be passed to `rcp' and workalikes."
4815 (let ((user (tramp-file-name-user vec))
4816 (host (tramp-file-name-real-host vec))
4817 (localname (tramp-shell-quote-argument
4818 (tramp-file-name-localname vec))))
4819 (if (not (zerop (length user)))
4820 (format "%s@%s:%s" user host localname)
4821 (format "%s:%s" host localname))))
4822
4823 (defun tramp-method-out-of-band-p (vec size)
4824 "Return t if this is an out-of-band method, nil otherwise."
4825 (and
4826 ;; It shall be an out-of-band method.
4827 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
4828 ;; There must be a size, otherwise the file doesn't exist.
4829 (numberp size)
4830 ;; Either the file size is large enough, or (in rare cases) there
4831 ;; does not exist a remote encoding.
4832 (or (null tramp-copy-size-limit)
4833 (> size tramp-copy-size-limit)
4834 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
4835
4836 ;; Variables local to connection.
4837
4838 (defun tramp-get-remote-path (vec)
4839 (with-tramp-connection-property
4840 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
4841 ;; cache the result for the session only. Otherwise, the result
4842 ;; is cached persistently.
4843 (if (memq 'tramp-own-remote-path tramp-remote-path)
4844 (tramp-get-connection-process vec)
4845 vec)
4846 "remote-path"
4847 (let* ((remote-path (copy-tree tramp-remote-path))
4848 (elt1 (memq 'tramp-default-remote-path remote-path))
4849 (elt2 (memq 'tramp-own-remote-path remote-path))
4850 (default-remote-path
4851 (when elt1
4852 (or
4853 (tramp-send-command-and-read
4854 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
4855 ;; Default if "getconf" is not available.
4856 (progn
4857 (tramp-message
4858 vec 3
4859 "`getconf PATH' not successful, using default value \"%s\"."
4860 "/bin:/usr/bin")
4861 "/bin:/usr/bin"))))
4862 (own-remote-path
4863 (when elt2
4864 (condition-case nil
4865 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
4866 (error
4867 (tramp-message
4868 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
4869 nil)))))
4870
4871 ;; Replace place holder `tramp-default-remote-path'.
4872 (when elt1
4873 (setcdr elt1
4874 (append
4875 (tramp-compat-split-string default-remote-path ":")
4876 (cdr elt1)))
4877 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
4878
4879 ;; Replace place holder `tramp-own-remote-path'.
4880 (when elt2
4881 (setcdr elt2
4882 (append
4883 (tramp-compat-split-string own-remote-path ":")
4884 (cdr elt2)))
4885 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
4886
4887 ;; Remove double entries.
4888 (setq elt1 remote-path)
4889 (while (consp elt1)
4890 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
4891 (setcar elt2 nil))
4892 (setq elt1 (cdr elt1)))
4893
4894 ;; Remove non-existing directories.
4895 (delq
4896 nil
4897 (mapcar
4898 (lambda (x)
4899 (and
4900 (stringp x)
4901 (file-directory-p
4902 (tramp-make-tramp-file-name
4903 (tramp-file-name-method vec)
4904 (tramp-file-name-user vec)
4905 (tramp-file-name-host vec)
4906 x))
4907 x))
4908 remote-path)))))
4909
4910 (defun tramp-get-ls-command (vec)
4911 (with-tramp-connection-property vec "ls"
4912 (tramp-message vec 5 "Finding a suitable `ls' command")
4913 (or
4914 (catch 'ls-found
4915 (dolist (cmd '("ls" "gnuls" "gls"))
4916 (let ((dl (tramp-get-remote-path vec))
4917 result)
4918 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
4919 ;; Check parameters. On busybox, "ls" output coloring is
4920 ;; enabled by default sometimes. So we try to disable it
4921 ;; when possible. $LS_COLORING is not supported there.
4922 ;; Some "ls" versions are sensible wrt the order of
4923 ;; arguments, they fail when "-al" is after the
4924 ;; "--color=never" argument (for example on FreeBSD).
4925 (when (tramp-send-command-and-check
4926 vec (format "%s -lnd /" result))
4927 (when (tramp-send-command-and-check
4928 vec (format
4929 "%s --color=never -al /dev/null" result))
4930 (setq result (concat result " --color=never")))
4931 (throw 'ls-found result))
4932 (setq dl (cdr dl))))))
4933 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
4934
4935 (defun tramp-get-ls-command-with-dired (vec)
4936 (save-match-data
4937 (with-tramp-connection-property vec "ls-dired"
4938 (tramp-message vec 5 "Checking, whether `ls --dired' works")
4939 ;; Some "ls" versions are sensible wrt the order of arguments,
4940 ;; they fail when "-al" is after the "--dired" argument (for
4941 ;; example on FreeBSD).
4942 (tramp-send-command-and-check
4943 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
4944
4945 (defun tramp-get-test-command (vec)
4946 (with-tramp-connection-property vec "test"
4947 (tramp-message vec 5 "Finding a suitable `test' command")
4948 (if (tramp-send-command-and-check vec "test 0")
4949 "test"
4950 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
4951
4952 (defun tramp-get-test-nt-command (vec)
4953 ;; Does `test A -nt B' work? Use abominable `find' construct if it
4954 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
4955 ;; for otherwise the shell crashes.
4956 (with-tramp-connection-property vec "test-nt"
4957 (or
4958 (progn
4959 (tramp-send-command
4960 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
4961 (with-current-buffer (tramp-get-buffer vec)
4962 (goto-char (point-min))
4963 (when (looking-at (regexp-quote tramp-end-of-output))
4964 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
4965 (progn
4966 (tramp-send-command
4967 vec
4968 (format
4969 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
4970 (tramp-get-test-command vec)))
4971 "tramp_test_nt %s %s"))))
4972
4973 (defun tramp-get-file-exists-command (vec)
4974 (with-tramp-connection-property vec "file-exists"
4975 (tramp-message vec 5 "Finding command to check if file exists")
4976 (tramp-find-file-exists-command vec)))
4977
4978 (defun tramp-get-remote-ln (vec)
4979 (with-tramp-connection-property vec "ln"
4980 (tramp-message vec 5 "Finding a suitable `ln' command")
4981 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
4982
4983 (defun tramp-get-remote-perl (vec)
4984 (with-tramp-connection-property vec "perl"
4985 (tramp-message vec 5 "Finding a suitable `perl' command")
4986 (let ((result
4987 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
4988 (tramp-find-executable
4989 vec "perl" (tramp-get-remote-path vec)))))
4990 ;; We must check also for some Perl modules.
4991 (when result
4992 (with-tramp-connection-property vec "perl-file-spec"
4993 (tramp-send-command-and-check
4994 vec (format "%s -e 'use File::Spec;'" result)))
4995 (with-tramp-connection-property vec "perl-cwd-realpath"
4996 (tramp-send-command-and-check
4997 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
4998 result)))
4999
5000 (defun tramp-get-remote-stat (vec)
5001 (with-tramp-connection-property vec "stat"
5002 (tramp-message vec 5 "Finding a suitable `stat' command")
5003 (let ((result (tramp-find-executable
5004 vec "stat" (tramp-get-remote-path vec)))
5005 tmp)
5006 ;; Check whether stat(1) returns usable syntax. "%s" does not
5007 ;; work on older AIX systems.
5008 (when result
5009 (setq tmp
5010 (tramp-send-command-and-read
5011 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5012 (unless (and (listp tmp) (stringp (car tmp))
5013 (string-match "^./.$" (car tmp))
5014 (integerp (cadr tmp)))
5015 (setq result nil)))
5016 result)))
5017
5018 (defun tramp-get-remote-readlink (vec)
5019 (with-tramp-connection-property vec "readlink"
5020 (tramp-message vec 5 "Finding a suitable `readlink' command")
5021 (let ((result (tramp-find-executable
5022 vec "readlink" (tramp-get-remote-path vec))))
5023 (when (and result
5024 (tramp-send-command-and-check
5025 vec (format "%s --canonicalize-missing /" result)))
5026 result))))
5027
5028 (defun tramp-get-remote-trash (vec)
5029 (with-tramp-connection-property vec "trash"
5030 (tramp-message vec 5 "Finding a suitable `trash' command")
5031 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5032
5033 (defun tramp-get-remote-id (vec)
5034 (with-tramp-connection-property vec "id"
5035 (tramp-message vec 5 "Finding POSIX `id' command")
5036 (or
5037 (catch 'id-found
5038 (let ((dl (tramp-get-remote-path vec))
5039 result)
5040 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
5041 ;; Check POSIX parameter.
5042 (when (tramp-send-command-and-check vec (format "%s -u" result))
5043 (throw 'id-found result))
5044 (setq dl (cdr dl)))))
5045 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
5046
5047 (defun tramp-get-remote-uid (vec id-format)
5048 (with-tramp-connection-property vec (format "uid-%s" id-format)
5049 (let ((res (tramp-send-command-and-read
5050 vec
5051 (format "%s -u%s %s"
5052 (tramp-get-remote-id vec)
5053 (if (equal id-format 'integer) "" "n")
5054 (if (equal id-format 'integer)
5055 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
5056 ;; The command might not always return a number.
5057 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
5058
5059 (defun tramp-get-remote-gid (vec id-format)
5060 (with-tramp-connection-property vec (format "gid-%s" id-format)
5061 (let ((res (tramp-send-command-and-read
5062 vec
5063 (format "%s -g%s %s"
5064 (tramp-get-remote-id vec)
5065 (if (equal id-format 'integer) "" "n")
5066 (if (equal id-format 'integer)
5067 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
5068 ;; The command might not always return a number.
5069 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
5070
5071 (defun tramp-get-local-uid (id-format)
5072 (if (equal id-format 'integer) (user-uid) (user-login-name)))
5073
5074 (defun tramp-get-local-gid (id-format)
5075 (if (and (fboundp 'group-gid) (equal id-format 'integer))
5076 (tramp-compat-funcall 'group-gid)
5077 (nth 3 (tramp-compat-file-attributes "~/" id-format))))
5078
5079 ;; Some predefined connection properties.
5080 (defun tramp-get-inline-compress (vec prop size)
5081 "Return the compress command related to PROP.
5082 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5083 the length of the file to be compressed.
5084
5085 If no corresponding command is found, nil is returned."
5086 (when (and (integerp tramp-inline-compress-start-size)
5087 (> size tramp-inline-compress-start-size))
5088 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5089 (tramp-find-inline-compress vec)
5090 (tramp-get-connection-property
5091 (tramp-get-connection-process vec) prop nil))))
5092
5093 (defun tramp-get-inline-coding (vec prop size)
5094 "Return the coding command related to PROP.
5095 PROP is either `remote-encoding', `remote-decoding',
5096 `local-encoding' or `local-decoding'.
5097
5098 SIZE is the length of the file to be coded. Depending on SIZE,
5099 compression might be applied.
5100
5101 If no corresponding command is found, nil is returned.
5102 Otherwise, either a string is returned which contains a `%s' mark
5103 to be used for the respective input or output file; or a Lisp
5104 function cell is returned to be applied on a buffer."
5105 ;; We must catch the errors, because we want to return `nil', when
5106 ;; no inline coding is found.
5107 (ignore-errors
5108 (let ((coding
5109 (with-tramp-connection-property
5110 (tramp-get-connection-process vec) prop
5111 (tramp-find-inline-encoding vec)
5112 (tramp-get-connection-property
5113 (tramp-get-connection-process vec) prop nil)))
5114 (prop1 (if (string-match "encoding" prop)
5115 "inline-compress" "inline-decompress"))
5116 compress)
5117 ;; The connection property might have been cached. So we must
5118 ;; send the script to the remote side - maybe.
5119 (when (and coding (symbolp coding) (string-match "remote" prop))
5120 (let ((name (symbol-name coding)))
5121 (while (string-match (regexp-quote "-") name)
5122 (setq name (replace-match "_" nil t name)))
5123 (tramp-maybe-send-script vec (symbol-value coding) name)
5124 (setq coding name)))
5125 (when coding
5126 ;; Check for the `compress' command.
5127 (setq compress (tramp-get-inline-compress vec prop1 size))
5128 ;; Return the value.
5129 (cond
5130 ((and compress (symbolp coding))
5131 (if (string-match "decompress" prop1)
5132 `(lambda (beg end)
5133 (,coding beg end)
5134 (let ((coding-system-for-write 'binary)
5135 (coding-system-for-read 'binary))
5136 (apply
5137 'call-process-region (point-min) (point-max)
5138 (car (split-string ,compress)) t t nil
5139 (cdr (split-string ,compress)))))
5140 `(lambda (beg end)
5141 (let ((coding-system-for-write 'binary)
5142 (coding-system-for-read 'binary))
5143 (apply
5144 'call-process-region beg end
5145 (car (split-string ,compress)) t t nil
5146 (cdr (split-string ,compress))))
5147 (,coding (point-min) (point-max)))))
5148 ((symbolp coding)
5149 coding)
5150 ((and compress (string-match "decoding" prop))
5151 (format
5152 ;; Windows shells need the program file name after
5153 ;; the pipe symbol be quoted if they use forward
5154 ;; slashes as directory separators.
5155 (if (and (string-match "local" prop)
5156 (memq system-type '(windows-nt)))
5157 "(%s | \"%s\" >%%s)"
5158 "(%s | %s >%%s)")
5159 coding compress))
5160 (compress
5161 (format
5162 ;; Windows shells need the program file name after
5163 ;; the pipe symbol be quoted if they use forward
5164 ;; slashes as directory separators.
5165 (if (and (string-match "local" prop)
5166 (memq system-type '(windows-nt)))
5167 "(%s <%%s | \"%s\")"
5168 "(%s <%%s | %s)")
5169 compress coding))
5170 ((string-match "decoding" prop)
5171 (format "%s >%%s" coding))
5172 (t
5173 (format "%s <%%s" coding)))))))
5174
5175 (add-hook 'tramp-unload-hook
5176 (lambda ()
5177 (unload-feature 'tramp-sh 'force)))
5178
5179 (provide 'tramp-sh)
5180
5181 ;;; TODO:
5182
5183 ;; * Don't use globbing for directories with many files, as this is
5184 ;; likely to produce long command lines, and some shells choke on
5185 ;; long command lines.
5186 ;; * Make it work for different encodings, and for different file name
5187 ;; encodings, too. (Daniel Pittman)
5188 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5189 ;; then look if it's the right version (with `perl -v').
5190 ;; * When editing a remote CVS controlled file as a different user, VC
5191 ;; gets confused about the file locking status. Try to find out why
5192 ;; the workaround doesn't work.
5193 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5194 ;; until the last but one hop via `start-file-process'. Apply it
5195 ;; also for ftp and smb.
5196 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5197 ;; some shell with root privileges, it would be nice if I could
5198 ;; just call
5199 ;; trampclient filename.c
5200 ;; as an editor, and the _current_ shell would connect to an Emacs
5201 ;; server and would be used in an existing non-privileged Emacs
5202 ;; session for doing the editing in question.
5203 ;; That way, I need not tell Emacs my password again and be afraid
5204 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5205 ;; once display a just typed password in the context of a keyboard
5206 ;; sequence prompt for a question immediately following in a shell
5207 ;; script run within Emacs -- nasty).
5208 ;; And if I have some ssh session running to a different computer,
5209 ;; having the possibility of passing a local file there to a local
5210 ;; Emacs session (in case I can arrange for a connection back) would
5211 ;; be nice.
5212 ;; Likely the corresponding Tramp server should not allow the
5213 ;; equivalent of the emacsclient -eval option in order to make this
5214 ;; reasonably unproblematic. And maybe trampclient should have some
5215 ;; way of passing credentials, like by using an SSL socket or
5216 ;; something. (David Kastrup)
5217 ;; * Reconnect directly to a compliant shell without first going
5218 ;; through the user's default shell. (Pete Forman)
5219 ;; * How can I interrupt the remote process with a signal
5220 ;; (interrupt-process seems not to work)? (Markus Triska)
5221 ;; * Avoid the local shell entirely for starting remote processes. If
5222 ;; so, I think even a signal, when delivered directly to the local
5223 ;; SSH instance, would correctly be propagated to the remote process
5224 ;; automatically; possibly SSH would have to be started with
5225 ;; "-t". (Markus Triska)
5226 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5227 ;; isn't on the remote host. (Mark A. Hershberger)
5228 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5229 ;; * Optimize out-of-band copying when both methods are scp-like (not
5230 ;; rsync).
5231 ;; * Keep a second connection open for out-of-band methods like scp or
5232 ;; rsync.
5233 ;; * Try telnet+curl as new method. It might be useful for busybox,
5234 ;; without built-in uuencode/uudecode.
5235
5236 ;;; tramp-sh.el ends here