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