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