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