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