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