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