]> code.delx.au - gnu-emacs/blob - lisp/net/tramp-sh.el
Fix an error in Tramp for rsync
[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") ("-p") ("-r") ("-s")))
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 (funcall
2379 (if (and (file-directory-p filename)
2380 (not (file-exists-p newname)))
2381 'file-name-as-directory
2382 'identity)
2383 (if t1
2384 (tramp-make-copy-program-file-name v)
2385 (shell-quote-argument filename)))
2386 target (if t2
2387 (tramp-make-copy-program-file-name v)
2388 (shell-quote-argument newname)))
2389
2390 ;; Check for host and port number. We cannot use
2391 ;; `tramp-file-name-port', because this returns also
2392 ;; `tramp-default-port', which might clash with settings in
2393 ;; "~/.ssh/config".
2394 (setq host (tramp-file-name-host v)
2395 port "")
2396 (when (string-match tramp-host-with-port-regexp host)
2397 (setq port (string-to-number (match-string 2 host))
2398 host (string-to-number (match-string 1 host))))
2399
2400 ;; Check for user. There might be an interactive setting.
2401 (setq user (or (tramp-file-name-user v)
2402 (tramp-get-connection-property v "login-as" nil)))
2403
2404 ;; Check for listener port.
2405 (when (tramp-get-method-parameter v 'tramp-remote-copy-args)
2406 (setq listener (number-to-string (+ 50000 (random 10000))))
2407 (while
2408 (zerop (tramp-call-process v "nc" nil nil nil "-z" host listener))
2409 (setq listener (number-to-string (+ 50000 (random 10000))))))
2410
2411 ;; Compose copy command.
2412 (setq host (or host "")
2413 user (or user "")
2414 port (or port "")
2415 spec (format-spec-make
2416 ?t (tramp-get-connection-property
2417 (tramp-get-connection-process v) "temp-file" ""))
2418 options (format-spec (tramp-ssh-controlmaster-options v) spec)
2419 spec (format-spec-make
2420 ?h host ?u user ?p port ?r listener ?c options
2421 ?k (if keep-date " " ""))
2422 copy-program (tramp-get-method-parameter v 'tramp-copy-program)
2423 copy-keep-date (tramp-get-method-parameter
2424 v 'tramp-copy-keep-date)
2425
2426 copy-args
2427 (delete
2428 ;; " " has either been a replacement of "%k" (when
2429 ;; keep-date argument is non-nil), or a replacement
2430 ;; for the whole keep-date sublist.
2431 " "
2432 (dolist
2433 (x (tramp-get-method-parameter v 'tramp-copy-args) copy-args)
2434 (setq copy-args
2435 (append
2436 copy-args
2437 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2438 (if (member "" y) '(" ") y))))))
2439
2440 copy-env
2441 (delq
2442 nil
2443 (mapcar
2444 (lambda (x)
2445 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
2446 (unless (member "" x) (mapconcat 'identity x " ")))
2447 (tramp-get-method-parameter v 'tramp-copy-env)))
2448
2449 remote-copy-program
2450 (tramp-get-method-parameter v 'tramp-remote-copy-program))
2451
2452 (dolist (x (tramp-get-method-parameter v 'tramp-remote-copy-args))
2453 (setq remote-copy-args
2454 (append
2455 remote-copy-args
2456 (let ((y (mapcar (lambda (z) (format-spec z spec)) x)))
2457 (if (member "" y) '(" ") y)))))
2458
2459 ;; Check for local copy program.
2460 (unless (executable-find copy-program)
2461 (tramp-error
2462 v 'file-error "Cannot find local copy program: %s" copy-program))
2463
2464 ;; Install listener on the remote side. The prompt must be
2465 ;; consumed later on, when the process does not listen anymore.
2466 (when remote-copy-program
2467 (unless (with-tramp-connection-property
2468 v (concat "remote-copy-program-" remote-copy-program)
2469 (tramp-find-executable
2470 v remote-copy-program (tramp-get-remote-path v)))
2471 (tramp-error
2472 v 'file-error
2473 "Cannot find remote listener: %s" remote-copy-program))
2474 (setq remote-copy-program
2475 (mapconcat
2476 'identity
2477 (append
2478 (list remote-copy-program) remote-copy-args
2479 (list (if t1 (concat "<" source) (concat ">" target)) "&"))
2480 " "))
2481 (tramp-send-command v remote-copy-program)
2482 (with-timeout
2483 (60 (tramp-error
2484 v 'file-error
2485 "Listener process not running on remote host: `%s'"
2486 remote-copy-program))
2487 (tramp-send-command v (format "netstat -l | grep -q :%s" listener))
2488 (while (not (tramp-send-command-and-check v nil))
2489 (tramp-send-command
2490 v (format "netstat -l | grep -q :%s" listener)))))
2491
2492 (with-temp-buffer
2493 (unwind-protect
2494 ;; The default directory must be remote.
2495 (let ((default-directory
2496 (file-name-directory (if t1 filename newname)))
2497 (process-environment (copy-sequence process-environment)))
2498 ;; Set the transfer process properties.
2499 (tramp-set-connection-property
2500 v "process-name" (buffer-name (current-buffer)))
2501 (tramp-set-connection-property
2502 v "process-buffer" (current-buffer))
2503 (while copy-env
2504 (tramp-message
2505 orig-vec 6 "%s=\"%s\"" (car copy-env) (cadr copy-env))
2506 (setenv (pop copy-env) (pop copy-env)))
2507 (setq
2508 copy-args
2509 (append
2510 copy-args
2511 (if remote-copy-program
2512 (list (if t1 (concat ">" target) (concat "<" source)))
2513 (list source target))))
2514
2515 ;; Use an asynchronous process. By this, password can
2516 ;; be handled. We don't set a timeout, because the
2517 ;; copying of large files can last longer than 60 secs.
2518 (let* ((command
2519 (mapconcat
2520 'identity (append (list copy-program) copy-args)
2521 " "))
2522 (p (let ((default-directory
2523 (tramp-compat-temporary-file-directory)))
2524 (start-process-shell-command
2525 (tramp-get-connection-name v)
2526 (tramp-get-connection-buffer v)
2527 command))))
2528 (tramp-message orig-vec 6 "%s" command)
2529 (tramp-set-connection-property p "vector" orig-vec)
2530 (set-process-query-on-exit-flag p nil)
2531
2532 ;; We must adapt `tramp-local-end-of-line' for
2533 ;; sending the password.
2534 (let ((tramp-local-end-of-line tramp-rsh-end-of-line))
2535 (tramp-process-actions
2536 p v nil tramp-actions-copy-out-of-band))))
2537
2538 ;; Reset the transfer process properties.
2539 (tramp-set-connection-property v "process-name" nil)
2540 (tramp-set-connection-property v "process-buffer" nil)
2541 ;; Clear the remote prompt.
2542 (when (and remote-copy-program
2543 (not (tramp-send-command-and-check v nil)))
2544 ;; Houston, we have a problem! Likely, the listener is
2545 ;; still running, so let's clear everything (but the
2546 ;; cached password).
2547 (tramp-cleanup-connection v 'keep-debug 'keep-password))))
2548
2549 ;; Handle KEEP-DATE argument.
2550 (when (and keep-date (not copy-keep-date))
2551 (set-file-times newname (nth 5 (file-attributes filename))))
2552
2553 ;; Set the mode.
2554 (unless (and keep-date copy-keep-date)
2555 (ignore-errors
2556 (set-file-modes newname (tramp-default-file-modes filename)))))
2557
2558 ;; If the operation was `rename', delete the original file.
2559 (unless (eq op 'copy)
2560 (if (file-regular-p filename)
2561 (delete-file filename)
2562 (delete-directory filename 'recursive))))))
2563
2564 (defun tramp-sh-handle-make-directory (dir &optional parents)
2565 "Like `make-directory' for Tramp files."
2566 (setq dir (expand-file-name dir))
2567 (with-parsed-tramp-file-name dir nil
2568 (tramp-flush-directory-property v (file-name-directory localname))
2569 (save-excursion
2570 (tramp-barf-unless-okay
2571 v (format "%s %s"
2572 (if parents "mkdir -p" "mkdir")
2573 (tramp-shell-quote-argument localname))
2574 "Couldn't make directory %s" dir))))
2575
2576 (defun tramp-sh-handle-delete-directory (directory &optional recursive)
2577 "Like `delete-directory' for Tramp files."
2578 (setq directory (expand-file-name directory))
2579 (with-parsed-tramp-file-name directory nil
2580 (tramp-flush-file-property v (file-name-directory localname))
2581 (tramp-flush-directory-property v localname)
2582 (tramp-barf-unless-okay
2583 v (format "cd / && %s %s"
2584 (if recursive "rm -rf" "rmdir")
2585 (tramp-shell-quote-argument localname))
2586 "Couldn't delete %s" directory)))
2587
2588 (defun tramp-sh-handle-delete-file (filename &optional trash)
2589 "Like `delete-file' for Tramp files."
2590 (setq filename (expand-file-name filename))
2591 (with-parsed-tramp-file-name filename nil
2592 (tramp-flush-file-property v (file-name-directory localname))
2593 (tramp-flush-file-property v localname)
2594 (tramp-barf-unless-okay
2595 v (format "%s %s"
2596 (or (and trash (tramp-get-remote-trash v)) "rm -f")
2597 (tramp-shell-quote-argument localname))
2598 "Couldn't delete %s" filename)))
2599
2600 ;; Dired.
2601
2602 (defvar dired-compress-file-suffixes)
2603 (declare-function dired-remove-file "dired-aux")
2604
2605 (defun tramp-sh-handle-dired-compress-file (file)
2606 "Like `dired-compress-file' for Tramp files."
2607 ;; Code stolen mainly from dired-aux.el.
2608 (with-parsed-tramp-file-name file nil
2609 (tramp-flush-file-property v localname)
2610 (save-excursion
2611 (let ((suffixes dired-compress-file-suffixes)
2612 suffix)
2613 ;; See if any suffix rule matches this file name.
2614 (while suffixes
2615 (let (case-fold-search)
2616 (if (string-match (car (car suffixes)) localname)
2617 (setq suffix (car suffixes) suffixes nil))
2618 (setq suffixes (cdr suffixes))))
2619
2620 (cond ((file-symlink-p file)
2621 nil)
2622 ((and suffix (nth 2 suffix))
2623 ;; We found an uncompression rule.
2624 (with-tramp-progress-reporter
2625 v 0 (format "Uncompressing %s" file)
2626 (when (tramp-send-command-and-check
2627 v (concat (nth 2 suffix) " "
2628 (tramp-shell-quote-argument localname)))
2629 (dired-remove-file file)
2630 (string-match (car suffix) file)
2631 (concat (substring file 0 (match-beginning 0))))))
2632 (t
2633 ;; We don't recognize the file as compressed, so compress it.
2634 ;; Try gzip.
2635 (with-tramp-progress-reporter v 0 (format "Compressing %s" file)
2636 (when (tramp-send-command-and-check
2637 v (concat "gzip -f "
2638 (tramp-shell-quote-argument localname)))
2639 (dired-remove-file file)
2640 (cond ((file-exists-p (concat file ".gz"))
2641 (concat file ".gz"))
2642 ((file-exists-p (concat file ".z"))
2643 (concat file ".z"))
2644 (t nil))))))))))
2645
2646 (defun tramp-sh-handle-insert-directory
2647 (filename switches &optional wildcard full-directory-p)
2648 "Like `insert-directory' for Tramp files."
2649 (setq filename (expand-file-name filename))
2650 (unless switches (setq switches ""))
2651 (with-parsed-tramp-file-name filename nil
2652 (if (and (featurep 'ls-lisp)
2653 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
2654 (tramp-handle-insert-directory
2655 filename switches wildcard full-directory-p)
2656 (when (stringp switches)
2657 (setq switches (split-string switches)))
2658 (when (and (member "--dired" switches)
2659 (not (tramp-get-ls-command-with-dired v)))
2660 (setq switches (delete "--dired" switches)))
2661 (when wildcard
2662 (setq wildcard (tramp-run-real-handler
2663 'file-name-nondirectory (list localname)))
2664 (setq localname (tramp-run-real-handler
2665 'file-name-directory (list localname))))
2666 (unless (or full-directory-p (member "-d" switches))
2667 (setq switches (append switches '("-d"))))
2668 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
2669 (when wildcard
2670 (setq switches (concat switches " " wildcard)))
2671 (tramp-message
2672 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
2673 switches filename (if wildcard "yes" "no")
2674 (if full-directory-p "yes" "no"))
2675 ;; If `full-directory-p', we just say `ls -l FILENAME'.
2676 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
2677 (if full-directory-p
2678 (tramp-send-command
2679 v
2680 (format "%s %s %s 2>/dev/null"
2681 (tramp-get-ls-command v)
2682 switches
2683 (if wildcard
2684 localname
2685 (tramp-shell-quote-argument (concat localname ".")))))
2686 (tramp-barf-unless-okay
2687 v
2688 (format "cd %s" (tramp-shell-quote-argument
2689 (tramp-run-real-handler
2690 'file-name-directory (list localname))))
2691 "Couldn't `cd %s'"
2692 (tramp-shell-quote-argument
2693 (tramp-run-real-handler 'file-name-directory (list localname))))
2694 (tramp-send-command
2695 v
2696 (format "%s %s %s 2>/dev/null"
2697 (tramp-get-ls-command v)
2698 switches
2699 (if (or wildcard
2700 (zerop (length
2701 (tramp-run-real-handler
2702 'file-name-nondirectory (list localname)))))
2703 ""
2704 (tramp-shell-quote-argument
2705 (tramp-run-real-handler
2706 'file-name-nondirectory (list localname)))))))
2707
2708 (save-restriction
2709 (let ((beg (point)))
2710 (narrow-to-region (point) (point))
2711 ;; We cannot use `insert-buffer-substring' because the Tramp
2712 ;; buffer changes its contents before insertion due to calling
2713 ;; `expand-file-name' and alike.
2714 (insert
2715 (with-current-buffer (tramp-get-buffer v)
2716 (buffer-string)))
2717
2718 ;; Check for "--dired" output.
2719 (forward-line -2)
2720 (when (looking-at "//SUBDIRED//")
2721 (forward-line -1))
2722 (when (looking-at "//DIRED//\\s-+")
2723 (let ((databeg (match-end 0))
2724 (end (point-at-eol)))
2725 ;; Now read the numeric positions of file names.
2726 (goto-char databeg)
2727 (while (< (point) end)
2728 (let ((start (+ beg (read (current-buffer))))
2729 (end (+ beg (read (current-buffer)))))
2730 (if (memq (char-after end) '(?\n ?\ ))
2731 ;; End is followed by \n or by " -> ".
2732 (put-text-property start end 'dired-filename t))))))
2733 ;; Remove trailing lines.
2734 (goto-char (point-at-bol))
2735 (while (looking-at "//")
2736 (forward-line 1)
2737 (delete-region (match-beginning 0) (point)))
2738
2739 ;; Some busyboxes are reluctant to discard colors.
2740 (unless
2741 (string-match "color" (tramp-get-connection-property v "ls" ""))
2742 (goto-char beg)
2743 (while
2744 (re-search-forward tramp-display-escape-sequence-regexp nil t)
2745 (replace-match "")))
2746
2747 ;; Decode the output, it could be multibyte.
2748 (decode-coding-region
2749 beg (point-max)
2750 (or file-name-coding-system default-file-name-coding-system))
2751
2752 ;; The inserted file could be from somewhere else.
2753 (when (and (not wildcard) (not full-directory-p))
2754 (goto-char (point-max))
2755 (when (file-symlink-p filename)
2756 (goto-char (search-backward "->" beg 'noerror)))
2757 (search-backward
2758 (if (zerop (length (file-name-nondirectory filename)))
2759 "."
2760 (file-name-nondirectory filename))
2761 beg 'noerror)
2762 (replace-match (file-relative-name filename) t))
2763
2764 (goto-char (point-max)))))))
2765
2766 ;; Canonicalization of file names.
2767
2768 (defun tramp-sh-handle-expand-file-name (name &optional dir)
2769 "Like `expand-file-name' for Tramp files.
2770 If the localname part of the given file name starts with \"/../\" then
2771 the result will be a local, non-Tramp, file name."
2772 ;; If DIR is not given, use `default-directory' or "/".
2773 (setq dir (or dir default-directory "/"))
2774 ;; Unless NAME is absolute, concat DIR and NAME.
2775 (unless (file-name-absolute-p name)
2776 (setq name (concat (file-name-as-directory dir) name)))
2777 ;; If connection is not established yet, run the real handler.
2778 (if (not (tramp-connectable-p name))
2779 (tramp-drop-volume-letter
2780 (tramp-run-real-handler 'expand-file-name (list name nil)))
2781 ;; Dissect NAME.
2782 (with-parsed-tramp-file-name name nil
2783 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2784 (setq localname (concat "~/" localname)))
2785 ;; Tilde expansion if necessary. This needs a shell which
2786 ;; groks tilde expansion! The function `tramp-find-shell' is
2787 ;; supposed to find such a shell on the remote host. Please
2788 ;; tell me about it when this doesn't work on your system.
2789 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2790 (let ((uname (match-string 1 localname))
2791 (fname (match-string 2 localname)))
2792 ;; We cannot simply apply "~/", because under sudo "~/" is
2793 ;; expanded to the local user home directory but to the
2794 ;; root home directory. On the other hand, using always
2795 ;; the default user name for tilde expansion is not
2796 ;; appropriate either, because ssh and companions might
2797 ;; use a user name from the config file.
2798 (when (and (string-equal uname "~")
2799 (string-match "\\`su\\(do\\)?\\'" method))
2800 (setq uname (concat uname user)))
2801 (setq uname
2802 (with-tramp-connection-property v uname
2803 (tramp-send-command
2804 v (format "cd %s && pwd" (tramp-shell-quote-argument uname)))
2805 (with-current-buffer (tramp-get-buffer v)
2806 (goto-char (point-min))
2807 (buffer-substring (point) (point-at-eol)))))
2808 (setq localname (concat uname fname))))
2809 ;; There might be a double slash, for example when "~/"
2810 ;; expands to "/". Remove this.
2811 (while (string-match "//" localname)
2812 (setq localname (replace-match "/" t t localname)))
2813 ;; No tilde characters in file name, do normal
2814 ;; `expand-file-name' (this does "/./" and "/../").
2815 ;; `default-directory' is bound, because on Windows there would
2816 ;; be problems with UNC shares or Cygwin mounts.
2817 (let ((default-directory (tramp-compat-temporary-file-directory)))
2818 (tramp-make-tramp-file-name
2819 method user host
2820 (tramp-drop-volume-letter
2821 (tramp-run-real-handler
2822 'expand-file-name (list localname)))
2823 hop)))))
2824
2825 ;;; Remote commands:
2826
2827 (defun tramp-process-sentinel (proc event)
2828 "Flush file caches."
2829 (unless (memq (process-status proc) '(run open))
2830 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2831 (when vec
2832 (tramp-message vec 5 "Sentinel called: `%S' `%s'" proc event)
2833 (tramp-flush-connection-property proc)
2834 (tramp-flush-directory-property vec "")))))
2835
2836 ;; We use BUFFER also as connection buffer during setup. Because of
2837 ;; this, its original contents must be saved, and restored once
2838 ;; connection has been setup.
2839 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2840 "Like `start-file-process' for Tramp files."
2841 (with-parsed-tramp-file-name (expand-file-name default-directory) nil
2842 (let* ((buffer
2843 (if buffer
2844 (get-buffer-create buffer)
2845 ;; BUFFER can be nil. We use a temporary buffer.
2846 (generate-new-buffer tramp-temp-buffer-name)))
2847 ;; When PROGRAM matches "*sh", and the first arg is "-c",
2848 ;; it might be that the arguments exceed the command line
2849 ;; length. Therefore, we modify the command.
2850 (heredoc (and (stringp program)
2851 (string-match "sh$" program)
2852 (string-equal "-c" (car args))
2853 (= (length args) 2)))
2854 ;; When PROGRAM is nil, we just provide a tty.
2855 (args (if (not heredoc) args
2856 (let ((i 250))
2857 (while (and (< i (length (cadr args)))
2858 (string-match " " (cadr args) i))
2859 (setcdr
2860 args
2861 (list (replace-match " \\\\\n" nil nil (cadr args))))
2862 (setq i (+ i 250))))
2863 (cdr args)))
2864 ;; Use a human-friendly prompt, for example for `shell'.
2865 ;; We discard hops, if existing, that's why we cannot use
2866 ;; `file-remote-p'.
2867 (prompt (format "PS1=%s %s"
2868 (tramp-make-tramp-file-name
2869 (tramp-file-name-method v)
2870 (tramp-file-name-user v)
2871 (tramp-file-name-host v)
2872 (tramp-file-name-localname v))
2873 tramp-initial-end-of-output))
2874 ;; We use as environment the difference to toplevel
2875 ;; `process-environment'.
2876 env
2877 (env
2878 (dolist
2879 (elt
2880 (cons prompt (nreverse (copy-sequence process-environment)))
2881 env)
2882 (or (member elt (default-toplevel-value 'process-environment))
2883 (setq env (cons elt env)))))
2884 (command
2885 (when (stringp program)
2886 (format "cd %s && exec %s env %s %s"
2887 (tramp-shell-quote-argument localname)
2888 (if heredoc (format "<<'%s'" tramp-end-of-heredoc) "")
2889 (mapconcat 'tramp-shell-quote-argument env " ")
2890 (if heredoc
2891 (format "%s\n(\n%s\n) </dev/tty\n%s"
2892 program (car args) tramp-end-of-heredoc)
2893 (mapconcat 'tramp-shell-quote-argument
2894 (cons program args) " ")))))
2895 (tramp-process-connection-type
2896 (or (null program) tramp-process-connection-type))
2897 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2898 (name1 name)
2899 (i 0)
2900 ;; We do not want to raise an error when
2901 ;; `start-file-process' has been started several times in
2902 ;; `eshell' and friends.
2903 (tramp-current-connection nil))
2904
2905 (while (get-process name1)
2906 ;; NAME must be unique as process name.
2907 (setq i (1+ i)
2908 name1 (format "%s<%d>" name i)))
2909 (setq name name1)
2910 ;; Set the new process properties.
2911 (tramp-set-connection-property v "process-name" name)
2912 (tramp-set-connection-property v "process-buffer" buffer)
2913
2914 (with-current-buffer (tramp-get-connection-buffer v)
2915 (unwind-protect
2916 ;; We catch this event. Otherwise, `start-process' could
2917 ;; be called on the local host.
2918 (save-excursion
2919 (save-restriction
2920 ;; Activate narrowing in order to save BUFFER
2921 ;; contents. Clear also the modification time;
2922 ;; otherwise we might be interrupted by
2923 ;; `verify-visited-file-modtime'.
2924 (let ((buffer-undo-list t)
2925 (buffer-read-only nil)
2926 (mark (point-max)))
2927 (clear-visited-file-modtime)
2928 (narrow-to-region (point-max) (point-max))
2929 ;; We call `tramp-maybe-open-connection', in order
2930 ;; to cleanup the prompt afterwards.
2931 (catch 'suppress
2932 (tramp-maybe-open-connection v)
2933 (widen)
2934 (delete-region mark (point))
2935 (narrow-to-region (point-max) (point-max))
2936 ;; Now do it.
2937 (if command
2938 ;; Send the command.
2939 (tramp-send-command v command nil t) ; nooutput
2940 ;; Check, whether a pty is associated.
2941 (unless (process-get
2942 (tramp-get-connection-process v) 'remote-tty)
2943 (tramp-error
2944 v 'file-error
2945 "pty association is not supported for `%s'" name))))
2946 (let ((p (tramp-get-connection-process v)))
2947 ;; Set query flag and process marker for this
2948 ;; process. We ignore errors, because the process
2949 ;; could have finished already.
2950 (ignore-errors
2951 (set-process-query-on-exit-flag p t)
2952 (set-marker (process-mark p) (point)))
2953 ;; Return process.
2954 p))))
2955
2956 ;; Save exit.
2957 (if (string-match tramp-temp-buffer-name (buffer-name))
2958 (ignore-errors
2959 (set-process-buffer (tramp-get-connection-process v) nil)
2960 (kill-buffer (current-buffer)))
2961 (set-buffer-modified-p bmp))
2962 (tramp-set-connection-property v "process-name" nil)
2963 (tramp-set-connection-property v "process-buffer" nil))))))
2964
2965 (defun tramp-sh-handle-process-file
2966 (program &optional infile destination display &rest args)
2967 "Like `process-file' for Tramp files."
2968 ;; The implementation is not complete yet.
2969 (when (and (numberp destination) (zerop destination))
2970 (error "Implementation does not handle immediate return"))
2971
2972 (with-parsed-tramp-file-name default-directory nil
2973 (let (command env input tmpinput stderr tmpstderr outbuf ret)
2974 ;; Compute command.
2975 (setq command (mapconcat 'tramp-shell-quote-argument
2976 (cons program args) " "))
2977 ;; We use as environment the difference to toplevel `process-environment'.
2978 (setq env
2979 (dolist (elt (nreverse (copy-sequence process-environment)) env)
2980 (or (member elt (default-toplevel-value 'process-environment))
2981 (setq env (cons elt env)))))
2982 (when env
2983 (setq command
2984 (format
2985 "env %s %s"
2986 (mapconcat 'tramp-shell-quote-argument env " ") command)))
2987 ;; Determine input.
2988 (if (null infile)
2989 (setq input "/dev/null")
2990 (setq infile (expand-file-name infile))
2991 (if (tramp-equal-remote default-directory infile)
2992 ;; INFILE is on the same remote host.
2993 (setq input (with-parsed-tramp-file-name infile nil localname))
2994 ;; INFILE must be copied to remote host.
2995 (setq input (tramp-make-tramp-temp-file v)
2996 tmpinput (tramp-make-tramp-file-name method user host input))
2997 (copy-file infile tmpinput t)))
2998 (when input (setq command (format "%s <%s" command input)))
2999
3000 ;; Determine output.
3001 (cond
3002 ;; Just a buffer.
3003 ((bufferp destination)
3004 (setq outbuf destination))
3005 ;; A buffer name.
3006 ((stringp destination)
3007 (setq outbuf (get-buffer-create destination)))
3008 ;; (REAL-DESTINATION ERROR-DESTINATION)
3009 ((consp destination)
3010 ;; output.
3011 (cond
3012 ((bufferp (car destination))
3013 (setq outbuf (car destination)))
3014 ((stringp (car destination))
3015 (setq outbuf (get-buffer-create (car destination))))
3016 ((car destination)
3017 (setq outbuf (current-buffer))))
3018 ;; stderr.
3019 (cond
3020 ((stringp (cadr destination))
3021 (setcar (cdr destination) (expand-file-name (cadr destination)))
3022 (if (tramp-equal-remote default-directory (cadr destination))
3023 ;; stderr is on the same remote host.
3024 (setq stderr (with-parsed-tramp-file-name
3025 (cadr destination) nil localname))
3026 ;; stderr must be copied to remote host. The temporary
3027 ;; file must be deleted after execution.
3028 (setq stderr (tramp-make-tramp-temp-file v)
3029 tmpstderr (tramp-make-tramp-file-name
3030 method user host stderr))))
3031 ;; stderr to be discarded.
3032 ((null (cadr destination))
3033 (setq stderr "/dev/null"))))
3034 ;; 't
3035 (destination
3036 (setq outbuf (current-buffer))))
3037 (when stderr (setq command (format "%s 2>%s" command stderr)))
3038
3039 ;; Send the command. It might not return in time, so we protect
3040 ;; it. Call it in a subshell, in order to preserve working
3041 ;; directory.
3042 (condition-case nil
3043 (unwind-protect
3044 (setq ret
3045 (if (tramp-send-command-and-check
3046 v (format "cd %s && %s"
3047 (tramp-shell-quote-argument localname)
3048 command)
3049 t t)
3050 0 1))
3051 ;; We should add the output anyway.
3052 (when outbuf
3053 (with-current-buffer outbuf
3054 (insert
3055 (with-current-buffer (tramp-get-connection-buffer v)
3056 (buffer-string))))
3057 (when (and display (get-buffer-window outbuf t)) (redisplay))))
3058 ;; When the user did interrupt, we should do it also. We use
3059 ;; return code -1 as marker.
3060 (quit
3061 (kill-buffer (tramp-get-connection-buffer v))
3062 (setq ret -1))
3063 ;; Handle errors.
3064 (error
3065 (kill-buffer (tramp-get-connection-buffer v))
3066 (setq ret 1)))
3067
3068 ;; Provide error file.
3069 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3070
3071 ;; Cleanup. We remove all file cache values for the connection,
3072 ;; because the remote process could have changed them.
3073 (when tmpinput (delete-file tmpinput))
3074
3075 (unless process-file-side-effects
3076 (tramp-flush-directory-property v ""))
3077
3078 ;; Return exit status.
3079 (if (equal ret -1)
3080 (keyboard-quit)
3081 ret))))
3082
3083 (defun tramp-sh-handle-file-local-copy (filename)
3084 "Like `file-local-copy' for Tramp files."
3085 (with-parsed-tramp-file-name filename nil
3086 (unless (file-exists-p filename)
3087 (tramp-error
3088 v 'file-error
3089 "Cannot make local copy of non-existing file `%s'" filename))
3090
3091 (let* ((size (nth 7 (file-attributes (file-truename filename))))
3092 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
3093 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
3094 (tmpfile (tramp-compat-make-temp-file filename)))
3095
3096 (condition-case err
3097 (cond
3098 ;; `copy-file' handles direct copy and out-of-band methods.
3099 ((or (tramp-local-host-p v)
3100 (tramp-method-out-of-band-p v size))
3101 (copy-file filename tmpfile 'ok-if-already-exists 'keep-time))
3102
3103 ;; Use inline encoding for file transfer.
3104 (rem-enc
3105 (save-excursion
3106 (with-tramp-progress-reporter
3107 v 3
3108 (format-message "Encoding remote file `%s' with `%s'"
3109 filename rem-enc)
3110 (tramp-barf-unless-okay
3111 v (format rem-enc (tramp-shell-quote-argument localname))
3112 "Encoding remote file failed"))
3113
3114 (with-tramp-progress-reporter
3115 v 3 (format-message "Decoding local file `%s' with `%s'"
3116 tmpfile loc-dec)
3117 (if (functionp loc-dec)
3118 ;; If local decoding is a function, we call it.
3119 ;; We must disable multibyte, because
3120 ;; `uudecode-decode-region' doesn't handle it
3121 ;; correctly. Unset `file-name-handler-alist'.
3122 ;; Otherwise, epa-file gets confused.
3123 (let (file-name-handler-alist
3124 (coding-system-for-write 'binary))
3125 (with-temp-file tmpfile
3126 (set-buffer-multibyte nil)
3127 (insert-buffer-substring (tramp-get-buffer v))
3128 (funcall loc-dec (point-min) (point-max))))
3129
3130 ;; If tramp-decoding-function is not defined for this
3131 ;; method, we invoke tramp-decoding-command instead.
3132 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3133 ;; Unset `file-name-handler-alist'. Otherwise,
3134 ;; epa-file gets confused.
3135 (let (file-name-handler-alist
3136 (coding-system-for-write 'binary))
3137 (with-current-buffer (tramp-get-buffer v)
3138 (write-region
3139 (point-min) (point-max) tmpfile2 nil 'no-message)))
3140 (unwind-protect
3141 (tramp-call-local-coding-command
3142 loc-dec tmpfile2 tmpfile)
3143 (delete-file tmpfile2)))))
3144
3145 ;; Set proper permissions.
3146 (set-file-modes tmpfile (tramp-default-file-modes filename))
3147 ;; Set local user ownership.
3148 (tramp-set-file-uid-gid tmpfile)))
3149
3150 ;; Oops, I don't know what to do.
3151 (t (tramp-error
3152 v 'file-error "Wrong method specification for `%s'" method)))
3153
3154 ;; Error handling.
3155 ((error quit)
3156 (delete-file tmpfile)
3157 (signal (car err) (cdr err))))
3158
3159 (run-hooks 'tramp-handle-file-local-copy-hook)
3160 tmpfile)))
3161
3162 ;; CCC grok LOCKNAME
3163 (defun tramp-sh-handle-write-region
3164 (start end filename &optional append visit lockname confirm)
3165 "Like `write-region' for Tramp files."
3166 (setq filename (expand-file-name filename))
3167 (with-parsed-tramp-file-name filename nil
3168 ;; Following part commented out because we don't know what to do about
3169 ;; file locking, and it does not appear to be a problem to ignore it.
3170 ;; Ange-ftp ignores it, too.
3171 ;; (when (and lockname (stringp lockname))
3172 ;; (setq lockname (expand-file-name lockname)))
3173 ;; (unless (or (eq lockname nil)
3174 ;; (string= lockname filename))
3175 ;; (error
3176 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3177
3178 (when (and confirm (file-exists-p filename))
3179 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3180 (tramp-error v 'file-error "File not overwritten")))
3181
3182 (let ((uid (or (nth 2 (file-attributes filename 'integer))
3183 (tramp-get-remote-uid v 'integer)))
3184 (gid (or (nth 3 (file-attributes filename 'integer))
3185 (tramp-get-remote-gid v 'integer))))
3186
3187 (if (and (tramp-local-host-p v)
3188 ;; `file-writable-p' calls `file-expand-file-name'. We
3189 ;; cannot use `tramp-run-real-handler' therefore.
3190 (let (file-name-handler-alist)
3191 (and
3192 (file-writable-p (file-name-directory localname))
3193 (or (file-directory-p localname)
3194 (file-writable-p localname)))))
3195 ;; Short track: if we are on the local host, we can run directly.
3196 (tramp-run-real-handler
3197 'write-region
3198 (list start end localname append 'no-message lockname confirm))
3199
3200 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3201 ;; We use this to save the value of
3202 ;; `last-coding-system-used' after writing the tmp
3203 ;; file. At the end of the function, we set
3204 ;; `last-coding-system-used' to this saved value. This
3205 ;; way, any intermediary coding systems used while
3206 ;; talking to the remote shell or suchlike won't hose
3207 ;; this variable. This approach was snarfed from
3208 ;; ange-ftp.el.
3209 coding-system-used
3210 ;; Write region into a tmp file. This isn't really
3211 ;; needed if we use an encoding function, but currently
3212 ;; we use it always because this makes the logic
3213 ;; simpler. We must also set `temporary-file-directory',
3214 ;; because it could point to a remote directory.
3215 (temporary-file-directory
3216 (tramp-compat-temporary-file-directory))
3217 (tmpfile (or tramp-temp-buffer-file-name
3218 (tramp-compat-make-temp-file filename))))
3219
3220 ;; If `append' is non-nil, we copy the file locally, and let
3221 ;; the native `write-region' implementation do the job.
3222 (when append (copy-file filename tmpfile 'ok))
3223
3224 ;; We say `no-message' here because we don't want the
3225 ;; visited file modtime data to be clobbered from the temp
3226 ;; file. We call `set-visited-file-modtime' ourselves later
3227 ;; on. We must ensure that `file-coding-system-alist'
3228 ;; matches `tmpfile'.
3229 (let (file-name-handler-alist
3230 (file-coding-system-alist
3231 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3232 (condition-case err
3233 (tramp-run-real-handler
3234 'write-region
3235 (list start end tmpfile append 'no-message lockname confirm))
3236 ((error quit)
3237 (setq tramp-temp-buffer-file-name nil)
3238 (delete-file tmpfile)
3239 (signal (car err) (cdr err))))
3240
3241 ;; Now, `last-coding-system-used' has the right value. Remember it.
3242 (setq coding-system-used last-coding-system-used))
3243
3244 ;; The permissions of the temporary file should be set. If
3245 ;; FILENAME does not exist (eq modes nil) it has been
3246 ;; renamed to the backup file. This case `save-buffer'
3247 ;; handles permissions.
3248 ;; Ensure that it is still readable.
3249 (when modes
3250 (set-file-modes
3251 tmpfile
3252 (logior (or modes 0) (string-to-number "0400" 8))))
3253
3254 ;; This is a bit lengthy due to the different methods
3255 ;; possible for file transfer. First, we check whether the
3256 ;; method uses an scp program. If so, we call it.
3257 ;; Otherwise, both encoding and decoding command must be
3258 ;; specified. However, if the method _also_ specifies an
3259 ;; encoding function, then that is used for encoding the
3260 ;; contents of the tmp file.
3261 (let* ((size (nth 7 (file-attributes tmpfile)))
3262 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3263 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3264 (cond
3265 ;; `copy-file' handles direct copy and out-of-band methods.
3266 ((or (tramp-local-host-p v)
3267 (tramp-method-out-of-band-p v size))
3268 (if (and (not (stringp start))
3269 (= (or end (point-max)) (point-max))
3270 (= (or start (point-min)) (point-min))
3271 (tramp-get-method-parameter v 'tramp-copy-keep-tmpfile))
3272 (progn
3273 (setq tramp-temp-buffer-file-name tmpfile)
3274 (condition-case err
3275 ;; We keep the local file for performance
3276 ;; reasons, useful for "rsync".
3277 (copy-file tmpfile filename t)
3278 ((error quit)
3279 (setq tramp-temp-buffer-file-name nil)
3280 (delete-file tmpfile)
3281 (signal (car err) (cdr err)))))
3282 (setq tramp-temp-buffer-file-name nil)
3283 ;; Don't rename, in order to keep context in SELinux.
3284 (unwind-protect
3285 (copy-file tmpfile filename t)
3286 (delete-file tmpfile))))
3287
3288 ;; Use inline file transfer.
3289 (rem-dec
3290 ;; Encode tmpfile.
3291 (unwind-protect
3292 (with-temp-buffer
3293 (set-buffer-multibyte nil)
3294 ;; Use encoding function or command.
3295 (with-tramp-progress-reporter
3296 v 3 (format-message
3297 "Encoding local file `%s' using `%s'"
3298 tmpfile loc-enc)
3299 (if (functionp loc-enc)
3300 ;; The following `let' is a workaround for
3301 ;; the base64.el that comes with pgnus-0.84.
3302 ;; If both of the following conditions are
3303 ;; satisfied, it tries to write to a local
3304 ;; file in default-directory, but at this
3305 ;; point, default-directory is remote.
3306 ;; (`call-process-region' can't write to
3307 ;; remote files, it seems.) The file in
3308 ;; question is a tmp file anyway.
3309 (let ((coding-system-for-read 'binary)
3310 (default-directory
3311 (tramp-compat-temporary-file-directory)))
3312 (insert-file-contents-literally tmpfile)
3313 (funcall loc-enc (point-min) (point-max)))
3314
3315 (unless (zerop (tramp-call-local-coding-command
3316 loc-enc tmpfile t))
3317 (tramp-error
3318 v 'file-error
3319 (concat "Cannot write to `%s', "
3320 "local encoding command `%s' failed")
3321 filename loc-enc))))
3322
3323 ;; Send buffer into remote decoding command which
3324 ;; writes to remote file. Because this happens on
3325 ;; the remote host, we cannot use the function.
3326 (with-tramp-progress-reporter
3327 v 3 (format-message
3328 "Decoding remote file `%s' using `%s'"
3329 filename rem-dec)
3330 (goto-char (point-max))
3331 (unless (bolp) (newline))
3332 (tramp-send-command
3333 v
3334 (format
3335 (concat rem-dec " <<'%s'\n%s%s")
3336 (tramp-shell-quote-argument localname)
3337 tramp-end-of-heredoc
3338 (buffer-string)
3339 tramp-end-of-heredoc))
3340 (tramp-barf-unless-okay
3341 v nil
3342 "Couldn't write region to `%s', decode using `%s' failed"
3343 filename rem-dec)
3344 ;; When `file-precious-flag' is set, the region is
3345 ;; written to a temporary file. Check that the
3346 ;; checksum is equal to that from the local tmpfile.
3347 (when file-precious-flag
3348 (erase-buffer)
3349 (and
3350 ;; cksum runs locally, if possible.
3351 (zerop (tramp-call-process v "cksum" tmpfile t))
3352 ;; cksum runs remotely.
3353 (tramp-send-command-and-check
3354 v
3355 (format
3356 "cksum <%s" (tramp-shell-quote-argument localname)))
3357 ;; ... they are different.
3358 (not
3359 (string-equal
3360 (buffer-string)
3361 (with-current-buffer (tramp-get-buffer v)
3362 (buffer-string))))
3363 (tramp-error
3364 v 'file-error
3365 (concat "Couldn't write region to `%s',"
3366 " decode using `%s' failed")
3367 filename rem-dec)))))
3368
3369 ;; Save exit.
3370 (delete-file tmpfile)))
3371
3372 ;; That's not expected.
3373 (t
3374 (tramp-error
3375 v 'file-error
3376 (concat "Method `%s' should specify both encoding and "
3377 "decoding command or an scp program")
3378 method))))
3379
3380 ;; Make `last-coding-system-used' have the right value.
3381 (when coding-system-used
3382 (set 'last-coding-system-used coding-system-used))))
3383
3384 (tramp-flush-file-property v (file-name-directory localname))
3385 (tramp-flush-file-property v localname)
3386
3387 ;; We must protect `last-coding-system-used', now we have set it
3388 ;; to its correct value.
3389 (let (last-coding-system-used (need-chown t))
3390 ;; Set file modification time.
3391 (when (or (eq visit t) (stringp visit))
3392 (let ((file-attr (file-attributes filename 'integer)))
3393 (set-visited-file-modtime
3394 ;; We must pass modtime explicitly, because FILENAME can
3395 ;; be different from (buffer-file-name), f.e. if
3396 ;; `file-precious-flag' is set.
3397 (nth 5 file-attr))
3398 (when (and (= (nth 2 file-attr) uid)
3399 (= (nth 3 file-attr) gid))
3400 (setq need-chown nil))))
3401
3402 ;; Set the ownership.
3403 (when need-chown
3404 (tramp-set-file-uid-gid filename uid gid))
3405 (when (or (eq visit t) (null visit) (stringp visit))
3406 (tramp-message v 0 "Wrote %s" filename))
3407 (run-hooks 'tramp-handle-write-region-hook)))))
3408
3409 (defvar tramp-vc-registered-file-names nil
3410 "List used to collect file names, which are checked during `vc-registered'.")
3411
3412 ;; VC backends check for the existence of various different special
3413 ;; files. This is very time consuming, because every single check
3414 ;; requires a remote command (the file cache must be invalidated).
3415 ;; Therefore, we apply a kind of optimization. We install the file
3416 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3417 ;; remembers all file names for which `file-exists-p' or
3418 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3419 ;; is performed. Afterwards, a script is applied for all collected
3420 ;; file names, using just one remote command. The result of this
3421 ;; script is used to fill the file cache with actual values. Now we
3422 ;; can reset the file name handlers, and we make a second run of
3423 ;; `vc-registered', which returns the expected result without sending
3424 ;; any other remote command.
3425 (defun tramp-sh-handle-vc-registered (file)
3426 "Like `vc-registered' for Tramp files."
3427 (with-temp-message ""
3428 (with-parsed-tramp-file-name file nil
3429 (with-tramp-progress-reporter
3430 v 3 (format-message "Checking `vc-registered' for %s" file)
3431
3432 ;; There could be new files, created by the vc backend. We
3433 ;; cannot reuse the old cache entries, therefore. In
3434 ;; `tramp-get-file-property', `remote-file-name-inhibit-cache'
3435 ;; could also be a timestamp as `current-time' returns. This
3436 ;; means invalidate all cache entries with an older timestamp.
3437 (let (tramp-vc-registered-file-names
3438 (remote-file-name-inhibit-cache (current-time))
3439 (file-name-handler-alist
3440 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3441
3442 ;; Here we collect only file names, which need an operation.
3443 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3444 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3445
3446 ;; Send just one command, in order to fill the cache.
3447 (when tramp-vc-registered-file-names
3448 (tramp-maybe-send-script
3449 v
3450 (format tramp-vc-registered-read-file-names
3451 (tramp-get-file-exists-command v)
3452 (format "%s -r" (tramp-get-test-command v)))
3453 "tramp_vc_registered_read_file_names")
3454
3455 (dolist
3456 (elt
3457 (ignore-errors
3458 ;; We cannot use `tramp-send-command-and-read',
3459 ;; because this does not cooperate well with
3460 ;; heredoc documents.
3461 (tramp-send-command
3462 v
3463 (format
3464 "tramp_vc_registered_read_file_names <<'%s'\n%s\n%s\n"
3465 tramp-end-of-heredoc
3466 (mapconcat 'tramp-shell-quote-argument
3467 tramp-vc-registered-file-names
3468 "\n")
3469 tramp-end-of-heredoc))
3470 (with-current-buffer (tramp-get-connection-buffer v)
3471 ;; Read the expression.
3472 (goto-char (point-min))
3473 (read (current-buffer)))))
3474
3475 (tramp-set-file-property
3476 v (car elt) (cadr elt) (cadr (cdr elt))))))
3477
3478 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3479 ;; calls shall be answered from the file cache. We unset
3480 ;; `process-file-side-effects' and `remote-file-name-inhibit-cache'
3481 ;; in order to keep the cache.
3482 (let ((vc-handled-backends vc-handled-backends)
3483 remote-file-name-inhibit-cache process-file-side-effects)
3484 ;; Reduce `vc-handled-backends' in order to minimize process calls.
3485 (when (and (memq 'Bzr vc-handled-backends)
3486 (boundp 'vc-bzr-program)
3487 (not (with-tramp-connection-property v vc-bzr-program
3488 (tramp-find-executable
3489 v vc-bzr-program (tramp-get-remote-path v)))))
3490 (setq vc-handled-backends (remq 'Bzr vc-handled-backends)))
3491 (when (and (memq 'Git vc-handled-backends)
3492 (boundp 'vc-git-program)
3493 (not (with-tramp-connection-property v vc-git-program
3494 (tramp-find-executable
3495 v vc-git-program (tramp-get-remote-path v)))))
3496 (setq vc-handled-backends (remq 'Git vc-handled-backends)))
3497 (when (and (memq 'Hg vc-handled-backends)
3498 (boundp 'vc-hg-program)
3499 (not (with-tramp-connection-property v vc-hg-program
3500 (tramp-find-executable
3501 v vc-hg-program (tramp-get-remote-path v)))))
3502 (setq vc-handled-backends (remq 'Hg vc-handled-backends)))
3503 ;; Run.
3504 (ignore-errors
3505 (tramp-run-real-handler 'vc-registered (list file))))))))
3506
3507 ;;;###tramp-autoload
3508 (defun tramp-sh-file-name-handler (operation &rest args)
3509 "Invoke remote-shell Tramp file name handler.
3510 Fall back to normal file name handler if no Tramp handler exists."
3511 (when (and tramp-locked (not tramp-locker))
3512 (setq tramp-locked nil)
3513 (tramp-error
3514 (car-safe tramp-current-connection) 'file-error
3515 "Forbidden reentrant call of Tramp"))
3516 (let ((tl tramp-locked))
3517 (setq tramp-locked t)
3518 (unwind-protect
3519 (let ((tramp-locker t))
3520 (save-match-data
3521 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3522 (if fn
3523 (apply (cdr fn) args)
3524 (tramp-run-real-handler operation args)))))
3525 (setq tramp-locked tl))))
3526
3527 (defun tramp-vc-file-name-handler (operation &rest args)
3528 "Invoke special file name handler, which collects files to be handled."
3529 (save-match-data
3530 (let ((filename
3531 (tramp-replace-environment-variables
3532 (apply 'tramp-file-name-for-operation operation args)))
3533 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3534 (with-parsed-tramp-file-name filename nil
3535 (cond
3536 ;; That's what we want: file names, for which checks are
3537 ;; applied. We assume that VC uses only `file-exists-p' and
3538 ;; `file-readable-p' checks; otherwise we must extend the
3539 ;; list. We do not perform any action, but return nil, in
3540 ;; order to keep `vc-registered' running.
3541 ((and fn (memq operation '(file-exists-p file-readable-p)))
3542 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3543 nil)
3544 ;; `process-file' and `start-file-process' shall be ignored.
3545 ((and fn (eq operation 'process-file) 0))
3546 ((and fn (eq operation 'start-file-process) nil))
3547 ;; Tramp file name handlers like `expand-file-name'. They
3548 ;; must still work.
3549 (fn (save-match-data (apply (cdr fn) args)))
3550 ;; Default file name handlers, we don't care.
3551 (t (tramp-run-real-handler operation args)))))))
3552
3553 (defun tramp-sh-handle-file-notify-add-watch (file-name flags _callback)
3554 "Like `file-notify-add-watch' for Tramp files."
3555 (setq file-name (expand-file-name file-name))
3556 (with-parsed-tramp-file-name file-name nil
3557 (let ((default-directory (file-name-directory file-name))
3558 command events filter p sequence)
3559 (cond
3560 ;; gvfs-monitor-dir.
3561 ((setq command (tramp-get-remote-gvfs-monitor-dir v))
3562 (setq filter 'tramp-sh-gvfs-monitor-dir-process-filter
3563 events
3564 (cond
3565 ((and (memq 'change flags) (memq 'attribute-change flags))
3566 '(created changed changes-done-hint moved deleted
3567 attribute-changed))
3568 ((memq 'change flags)
3569 '(created changed changes-done-hint moved deleted))
3570 ((memq 'attribute-change flags) '(attribute-changed)))
3571 sequence `(,command ,localname)))
3572 ;; inotifywait.
3573 ((setq command (tramp-get-remote-inotifywait v))
3574 (setq filter 'tramp-sh-inotifywait-process-filter
3575 events
3576 (cond
3577 ((and (memq 'change flags) (memq 'attribute-change flags))
3578 (concat "create,modify,move,moved_from,moved_to,move_self,"
3579 "delete,delete_self,attrib,ignored"))
3580 ((memq 'change flags)
3581 (concat "create,modify,move,moved_from,moved_to,move_self,"
3582 "delete,delete_self,ignored"))
3583 ((memq 'attribute-change flags) "attrib,ignored"))
3584 sequence `(,command "-mq" "-e" ,events ,localname)
3585 ;; Make events a list of symbols.
3586 events
3587 (mapcar
3588 (lambda (x) (intern-soft (replace-regexp-in-string "_" "-" x)))
3589 (split-string events "," 'omit))))
3590 ;; None.
3591 (t (tramp-error
3592 v 'file-notify-error
3593 "No file notification program found on %s"
3594 (file-remote-p file-name))))
3595 ;; Start process.
3596 (setq p (apply
3597 'start-file-process
3598 (file-name-nondirectory command)
3599 (generate-new-buffer
3600 (format " *%s*" (file-name-nondirectory command)))
3601 sequence))
3602 ;; Return the process object as watch-descriptor.
3603 (if (not (processp p))
3604 (tramp-error
3605 v 'file-notify-error
3606 "`%s' failed to start on remote host"
3607 (mapconcat 'identity sequence " "))
3608 (tramp-message v 6 "Run `%s', %S" (mapconcat 'identity sequence " ") p)
3609 (tramp-set-connection-property p "vector" v)
3610 ;; Needed for process filter.
3611 (process-put p 'events events)
3612 (process-put p 'watch-name localname)
3613 (set-process-query-on-exit-flag p nil)
3614 (set-process-filter p filter)
3615 ;; There might be an error if the monitor is not supported.
3616 ;; Give the filter a chance to read the output.
3617 (tramp-accept-process-output p 1)
3618 (unless (memq (process-status p) '(run open))
3619 (tramp-error
3620 v 'file-notify-error "Monitoring not supported for `%s'" file-name))
3621 p))))
3622
3623 (defun tramp-sh-gvfs-monitor-dir-process-filter (proc string)
3624 "Read output from \"gvfs-monitor-dir\" and add corresponding \
3625 file-notify events."
3626 (let ((events (process-get proc 'events))
3627 (remote-prefix
3628 (with-current-buffer (process-buffer proc)
3629 (file-remote-p default-directory)))
3630 (rest-string (process-get proc 'rest-string)))
3631 (when rest-string
3632 (tramp-message proc 10 "Previous string:\n%s" rest-string))
3633 (tramp-message proc 6 "%S\n%s" proc string)
3634 (setq string (concat rest-string string)
3635 ;; Attribute change is returned in unused wording.
3636 string (replace-regexp-in-string
3637 "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))
3638 (when (string-match "Monitoring not supported" string)
3639 (delete-process proc))
3640
3641 (while (string-match
3642 (concat "^[\n\r]*"
3643 "Directory Monitor Event:[\n\r]+"
3644 "Child = \\([^\n\r]+\\)[\n\r]+"
3645 "\\(Other = \\([^\n\r]+\\)[\n\r]+\\)?"
3646 "Event = \\([^[:blank:]]+\\)[\n\r]+")
3647 string)
3648 (let* ((file (match-string 1 string))
3649 (file1 (match-string 3 string))
3650 (object
3651 (list
3652 proc
3653 (list
3654 (intern-soft
3655 (replace-regexp-in-string
3656 "_" "-" (downcase (match-string 4 string)))))
3657 ;; File names are returned as absolute paths. We must
3658 ;; add the remote prefix.
3659 (concat remote-prefix file)
3660 (when file1 (concat remote-prefix file1)))))
3661 (setq string (replace-match "" nil nil string))
3662 ;; Remove watch when file or directory to be watched is deleted.
3663 (when (and (member (caadr object) '(moved deleted))
3664 (string-equal file (process-get proc 'watch-name)))
3665 (delete-process proc))
3666 ;; Usually, we would add an Emacs event now. Unfortunately,
3667 ;; `unread-command-events' does not accept several events at
3668 ;; once. Therefore, we apply the handler directly.
3669 (when (member (caadr object) events)
3670 (tramp-compat-funcall
3671 'file-notify-handle-event
3672 `(file-notify ,object file-notify-callback)))))
3673
3674 ;; Save rest of the string.
3675 (when (zerop (length string)) (setq string nil))
3676 (when string (tramp-message proc 10 "Rest string:\n%s" string))
3677 (process-put proc 'rest-string string)))
3678
3679 (defun tramp-sh-inotifywait-process-filter (proc string)
3680 "Read output from \"inotifywait\" and add corresponding file-notify events."
3681 (let ((events (process-get proc 'events)))
3682 (tramp-message proc 6 "%S\n%s" proc string)
3683 (dolist (line (split-string string "[\n\r]+" 'omit))
3684 ;; Check, whether there is a problem.
3685 (unless
3686 (string-match
3687 (concat "^[^[:blank:]]+"
3688 "[[:blank:]]+\\([^[:blank:]]+\\)+"
3689 "\\([[:blank:]]+\\([^\n\r]+\\)\\)?")
3690 line)
3691 (tramp-error proc 'file-notify-error "%s" line))
3692
3693 (let ((object
3694 (list
3695 proc
3696 (mapcar
3697 (lambda (x)
3698 (intern-soft
3699 (replace-regexp-in-string "_" "-" (downcase x))))
3700 (split-string (match-string 1 line) "," 'omit))
3701 (match-string 3 line))))
3702 ;; Remove watch when file or directory to be watched is deleted.
3703 (when (member (caadr object) '(move-self delete-self ignored))
3704 (delete-process proc))
3705 ;; Usually, we would add an Emacs event now. Unfortunately,
3706 ;; `unread-command-events' does not accept several events at
3707 ;; once. Therefore, we apply the handler directly.
3708 (when (member (caadr object) events)
3709 (tramp-compat-funcall
3710 'file-notify-handle-event
3711 `(file-notify ,object file-notify-callback)))))))
3712
3713 ;;; Internal Functions:
3714
3715 (defun tramp-maybe-send-script (vec script name)
3716 "Define in remote shell function NAME implemented as SCRIPT.
3717 Only send the definition if it has not already been done."
3718 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3719 ;; might be nil.
3720 (let ((scripts (tramp-get-connection-property
3721 (tramp-get-connection-process vec) "scripts" nil)))
3722 (unless (member name scripts)
3723 (with-tramp-progress-reporter
3724 vec 5 (format-message "Sending script `%s'" name)
3725 ;; In bash, leading TABs like in `tramp-vc-registered-read-file-names'
3726 ;; could result in unwanted command expansion. Avoid this.
3727 (setq script (replace-regexp-in-string
3728 (make-string 1 ?\t) (make-string 8 ? ) script))
3729 ;; The script could contain a call of Perl. This is masked with `%s'.
3730 (when (and (string-match "%s" script)
3731 (not (tramp-get-remote-perl vec)))
3732 (tramp-error vec 'file-error "No Perl available on remote host"))
3733 (tramp-barf-unless-okay
3734 vec
3735 (format "%s () {\n%s\n}"
3736 name (format script (tramp-get-remote-perl vec)))
3737 "Script %s sending failed" name)
3738 (tramp-set-connection-property
3739 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3740
3741 (defun tramp-run-test (switch filename)
3742 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3743 Returns the exit code of the `test' program."
3744 (with-parsed-tramp-file-name filename nil
3745 (tramp-send-command-and-check
3746 v
3747 (format
3748 "%s %s %s"
3749 (tramp-get-test-command v)
3750 switch
3751 (tramp-shell-quote-argument localname)))))
3752
3753 (defun tramp-run-test2 (format-string file1 file2)
3754 "Run `test'-like program on the remote system, given FILE1, FILE2.
3755 FORMAT-STRING contains the program name, switches, and place holders.
3756 Returns the exit code of the `test' program. Barfs if the methods,
3757 hosts, or files, disagree."
3758 (unless (tramp-equal-remote file1 file2)
3759 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3760 (tramp-error
3761 v 'file-error
3762 "tramp-run-test2 only implemented for same method, user, host")))
3763 (with-parsed-tramp-file-name file1 v1
3764 (with-parsed-tramp-file-name file1 v2
3765 (tramp-send-command-and-check
3766 v1
3767 (format format-string
3768 (tramp-shell-quote-argument v1-localname)
3769 (tramp-shell-quote-argument v2-localname))))))
3770
3771 (defun tramp-find-executable
3772 (vec progname dirlist &optional ignore-tilde ignore-path)
3773 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3774 First arg VEC specifies the connection, PROGNAME is the program
3775 to search for, and DIRLIST gives the list of directories to
3776 search. If IGNORE-TILDE is non-nil, directory names starting
3777 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3778 only in DIRLIST.
3779
3780 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3781
3782 This function expects to be in the right *tramp* buffer."
3783 (with-current-buffer (tramp-get-connection-buffer vec)
3784 (let (result)
3785 ;; Check whether the executable is in $PATH. "which(1)" does not
3786 ;; report always a correct error code; therefore we check the
3787 ;; number of words it returns. "SunOS 5.10" (and maybe "SunOS
3788 ;; 5.11") have problems with this command, we disable the call
3789 ;; therefore.
3790 (unless (or ignore-path
3791 (string-match
3792 (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3793 (tramp-get-connection-property vec "uname" "")))
3794 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3795 (goto-char (point-min))
3796 (if (looking-at "^\\s-*1$")
3797 (setq result (concat "\\" progname))))
3798 (unless result
3799 (when ignore-tilde
3800 ;; Remove all ~/foo directories from dirlist.
3801 (let (newdl d)
3802 (while dirlist
3803 (setq d (car dirlist))
3804 (setq dirlist (cdr dirlist))
3805 (unless (char-equal ?~ (aref d 0))
3806 (setq newdl (cons d newdl))))
3807 (setq dirlist (nreverse newdl))))
3808 (tramp-send-command
3809 vec
3810 (format (concat "while read d; "
3811 "do if test -x $d/%s && test -f $d/%s; "
3812 "then echo tramp_executable $d/%s; "
3813 "break; fi; done <<'%s'\n"
3814 "%s\n%s")
3815 progname progname progname
3816 tramp-end-of-heredoc
3817 (mapconcat 'identity dirlist "\n")
3818 tramp-end-of-heredoc))
3819 (goto-char (point-max))
3820 (when (search-backward "tramp_executable " nil t)
3821 (skip-chars-forward "^ ")
3822 (skip-chars-forward " ")
3823 (setq result (buffer-substring (point) (point-at-eol)))))
3824 result)))
3825
3826 (defun tramp-set-remote-path (vec)
3827 "Sets the remote environment PATH to existing directories.
3828 I.e., for each directory in `tramp-remote-path', it is tested
3829 whether it exists and if so, it is added to the environment
3830 variable PATH."
3831 (tramp-message vec 5 "Setting $PATH environment variable")
3832 (tramp-send-command
3833 vec (format "PATH=%s; export PATH"
3834 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3835
3836 ;; ------------------------------------------------------------
3837 ;; -- Communication with external shell --
3838 ;; ------------------------------------------------------------
3839
3840 (defun tramp-find-file-exists-command (vec)
3841 "Find a command on the remote host for checking if a file exists.
3842 Here, we are looking for a command which has zero exit status if the
3843 file exists and nonzero exit status otherwise."
3844 (let ((existing "/")
3845 (nonexistent
3846 (tramp-shell-quote-argument "/ this file does not exist "))
3847 result)
3848 ;; The algorithm is as follows: we try a list of several commands.
3849 ;; For each command, we first run `$cmd /' -- this should return
3850 ;; true, as the root directory always exists. And then we run
3851 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3852 ;; does not exist. This should return false. We use the first
3853 ;; command we find that seems to work.
3854 ;; The list of commands to try is as follows:
3855 ;; `ls -d' This works on most systems, but NetBSD 1.4
3856 ;; has a bug: `ls' always returns zero exit
3857 ;; status, even for files which don't exist.
3858 ;; `test -e' Some Bourne shells have a `test' builtin
3859 ;; which does not know the `-e' option.
3860 ;; `/bin/test -e' For those, the `test' binary on disk normally
3861 ;; provides the option. Alas, the binary
3862 ;; is sometimes `/bin/test' and sometimes it's
3863 ;; `/usr/bin/test'.
3864 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3865 (unless (or
3866 (ignore-errors
3867 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3868 (tramp-send-command-and-check
3869 vec (format "%s %s" result existing))
3870 (not (tramp-send-command-and-check
3871 vec (format "%s %s" result nonexistent)))))
3872 (ignore-errors
3873 (and (setq result "/bin/test -e")
3874 (tramp-send-command-and-check
3875 vec (format "%s %s" result existing))
3876 (not (tramp-send-command-and-check
3877 vec (format "%s %s" result nonexistent)))))
3878 (ignore-errors
3879 (and (setq result "/usr/bin/test -e")
3880 (tramp-send-command-and-check
3881 vec (format "%s %s" result existing))
3882 (not (tramp-send-command-and-check
3883 vec (format "%s %s" result nonexistent)))))
3884 (ignore-errors
3885 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3886 (tramp-send-command-and-check
3887 vec (format "%s %s" result existing))
3888 (not (tramp-send-command-and-check
3889 vec (format "%s %s" result nonexistent))))))
3890 (tramp-error
3891 vec 'file-error "Couldn't find command to check if file exists"))
3892 result))
3893
3894 (defun tramp-open-shell (vec shell)
3895 "Opens shell SHELL."
3896 (with-tramp-progress-reporter
3897 vec 5 (format-message "Opening remote shell `%s'" shell)
3898 ;; Find arguments for this shell.
3899 (let ((alist tramp-sh-extra-args)
3900 item extra-args)
3901 (while (and alist (null extra-args))
3902 (setq item (pop alist))
3903 (when (string-match (car item) shell)
3904 (setq extra-args (cdr item))))
3905 ;; It is useful to set the prompt in the following command
3906 ;; because some people have a setting for $PS1 which /bin/sh
3907 ;; doesn't know about and thus /bin/sh will display a strange
3908 ;; prompt. For example, if $PS1 has "${CWD}" in the value, then
3909 ;; ksh will display the current working directory but /bin/sh
3910 ;; will display a dollar sign. The following command line sets
3911 ;; $PS1 to a sane value, and works under Bourne-ish shells as
3912 ;; well as csh-like shells. We also unset the variable $ENV
3913 ;; because that is read by some sh implementations (eg, bash
3914 ;; when called as sh) on startup; this way, we avoid the startup
3915 ;; file clobbering $PS1. $PROMPT_COMMAND is another way to set
3916 ;; the prompt in /bin/bash, it must be discarded as well.
3917 ;; $HISTFILE is set according to `tramp-histfile-override'.
3918 (tramp-send-command
3919 vec (format
3920 "exec env ENV='' %s PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3921 (if (stringp tramp-histfile-override)
3922 (format "HISTFILE=%s"
3923 (tramp-shell-quote-argument tramp-histfile-override))
3924 (if tramp-histfile-override
3925 "HISTFILE='' HISTFILESIZE=0 HISTSIZE=0"
3926 ""))
3927 (tramp-shell-quote-argument tramp-end-of-output)
3928 shell (or extra-args ""))
3929 t))
3930 (tramp-set-connection-property
3931 (tramp-get-connection-process vec) "remote-shell" shell)))
3932
3933 (defun tramp-find-shell (vec)
3934 "Opens a shell on the remote host which groks tilde expansion."
3935 (with-current-buffer (tramp-get-buffer vec)
3936 (let ((default-shell (tramp-get-method-parameter vec 'tramp-remote-shell))
3937 shell)
3938 (setq shell
3939 (with-tramp-connection-property vec "remote-shell"
3940 ;; CCC: "root" does not exist always, see my QNAP TS-459.
3941 ;; Which check could we apply instead?
3942 (tramp-send-command vec "echo ~root" t)
3943 (if (or (string-match "^~root$" (buffer-string))
3944 ;; The default shell (ksh93) of OpenSolaris and
3945 ;; Solaris is buggy. We've got reports for
3946 ;; "SunOS 5.10" and "SunOS 5.11" so far.
3947 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3948 (tramp-get-connection-property
3949 vec "uname" "")))
3950
3951 (or (tramp-find-executable
3952 vec "bash" (tramp-get-remote-path vec) t t)
3953 (tramp-find-executable
3954 vec "ksh" (tramp-get-remote-path vec) t t)
3955 ;; Maybe it works at least for some other commands.
3956 (prog1
3957 default-shell
3958 (tramp-message
3959 vec 2
3960 (concat
3961 "Couldn't find a remote shell which groks tilde "
3962 "expansion, using `%s'")
3963 default-shell)))
3964
3965 default-shell)))
3966
3967 ;; Open a new shell if needed.
3968 (unless (string-equal shell default-shell)
3969 (tramp-message
3970 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
3971 (tramp-open-shell vec shell)))))
3972
3973 ;; Utility functions.
3974
3975 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
3976 "Wait for shell prompt and barf if none appears.
3977 Looks at process PROC to see if a shell prompt appears in TIMEOUT
3978 seconds. If not, it produces an error message with the given ERROR-ARGS."
3979 (let ((vec (tramp-get-connection-property proc "vector" nil)))
3980 (condition-case nil
3981 (tramp-wait-for-regexp
3982 proc timeout
3983 (format
3984 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
3985 (error
3986 (delete-process proc)
3987 (apply 'tramp-error-with-buffer
3988 (tramp-get-connection-buffer vec) vec 'file-error error-args)))))
3989
3990 (defun tramp-open-connection-setup-interactive-shell (proc vec)
3991 "Set up an interactive shell.
3992 Mainly sets the prompt and the echo correctly. PROC is the shell
3993 process to set up. VEC specifies the connection."
3994 (let ((tramp-end-of-output tramp-initial-end-of-output)
3995 (case-fold-search t))
3996 (tramp-open-shell vec (tramp-get-method-parameter vec 'tramp-remote-shell))
3997
3998 ;; Disable tab and echo expansion.
3999 (tramp-message vec 5 "Setting up remote shell environment")
4000 (tramp-send-command
4001 vec "stty tab0 -inlcr -onlcr -echo kill '^U' erase '^H'" t)
4002 ;; Check whether the echo has really been disabled. Some
4003 ;; implementations, like busybox of embedded GNU/Linux, don't
4004 ;; support disabling.
4005 (tramp-send-command vec "echo foo" t)
4006 (with-current-buffer (process-buffer proc)
4007 (goto-char (point-min))
4008 (when (looking-at "echo foo")
4009 (tramp-set-connection-property proc "remote-echo" t)
4010 (tramp-message vec 5 "Remote echo still on. Ok.")
4011 ;; Make sure backspaces and their echo are enabled and no line
4012 ;; width magic interferes with them.
4013 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
4014
4015 (tramp-message vec 5 "Setting shell prompt")
4016 (tramp-send-command
4017 vec (format "PS1=%s PS2='' PS3='' PROMPT_COMMAND=''"
4018 (tramp-shell-quote-argument tramp-end-of-output)) t)
4019
4020 ;; Check whether the output of "uname -sr" has been changed. If
4021 ;; yes, this is a strong indication that we must expire all
4022 ;; connection properties. We start again with
4023 ;; `tramp-maybe-open-connection', it will be caught there.
4024 (tramp-message vec 5 "Checking system information")
4025 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
4026 (new-uname
4027 (tramp-set-connection-property
4028 vec "uname"
4029 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
4030 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
4031 (tramp-message
4032 vec 3
4033 "Connection reset, because remote host changed from `%s' to `%s'"
4034 old-uname new-uname)
4035 ;; We want to keep the password.
4036 (tramp-cleanup-connection vec t t)
4037 (throw 'uname-changed (tramp-maybe-open-connection vec))))
4038
4039 ;; Try to set up the coding system correctly.
4040 ;; CCC this can't be the right way to do it. Hm.
4041 (tramp-message vec 5 "Determining coding system")
4042 (with-current-buffer (process-buffer proc)
4043 ;; Use MULE to select the right EOL convention for communicating
4044 ;; with the process.
4045 (let ((cs (or (and (memq 'utf-8 (coding-system-list))
4046 (string-match "utf-?8" (tramp-get-remote-locale vec))
4047 (cons 'utf-8 'utf-8))
4048 (process-coding-system proc)
4049 (cons 'undecided 'undecided)))
4050 cs-decode cs-encode)
4051 (when (symbolp cs) (setq cs (cons cs cs)))
4052 (setq cs-decode (or (car cs) 'undecided)
4053 cs-encode (or (cdr cs) 'undecided)
4054 cs-encode
4055 (coding-system-change-eol-conversion
4056 cs-encode
4057 (if (string-match
4058 "^Darwin" (tramp-get-connection-property vec "uname" ""))
4059 'mac 'unix)))
4060 (tramp-send-command vec "echo foo ; echo bar" t)
4061 (goto-char (point-min))
4062 (when (search-forward "\r" nil t)
4063 (setq cs-decode (coding-system-change-eol-conversion cs-decode 'dos)))
4064 ;; Special setting for Mac OS X.
4065 (when (and (string-match
4066 "^Darwin" (tramp-get-connection-property vec "uname" ""))
4067 (memq 'utf-8-hfs (coding-system-list)))
4068 (setq cs-decode 'utf-8-hfs
4069 cs-encode 'utf-8-hfs))
4070 (set-buffer-process-coding-system cs-decode cs-encode)
4071 (tramp-message
4072 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode)))
4073
4074 (tramp-send-command vec "set +o vi +o emacs" t)
4075
4076 ;; Check whether the remote host suffers from buggy
4077 ;; `send-process-string'. This is known for FreeBSD (see comment in
4078 ;; `send_process', file process.c). I've tested sending 624 bytes
4079 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
4080 ;; this host type is detected locally. It cannot handle remote
4081 ;; hosts, though.
4082 (with-tramp-connection-property proc "chunksize"
4083 (cond
4084 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
4085 tramp-chunksize)
4086 (t
4087 (tramp-message
4088 vec 5 "Checking remote host type for `send-process-string' bug")
4089 (if (string-match
4090 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
4091 500 0))))
4092
4093 ;; Set remote PATH variable.
4094 (tramp-set-remote-path vec)
4095
4096 ;; Search for a good shell before searching for a command which
4097 ;; checks if a file exists. This is done because Tramp wants to use
4098 ;; "test foo; echo $?" to check if various conditions hold, and
4099 ;; there are buggy /bin/sh implementations which don't execute the
4100 ;; "echo $?" part if the "test" part has an error. In particular,
4101 ;; the OpenSolaris /bin/sh is a problem. There are also other
4102 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
4103 ;; in function declarations, or changing HISTFILE in place.
4104 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
4105 ;; detected.
4106 (tramp-find-shell vec)
4107
4108 ;; Disable unexpected output.
4109 (tramp-send-command vec "mesg n 2>/dev/null; biff n 2>/dev/null" t)
4110
4111 ;; IRIX64 bash expands "!" even when in single quotes. This
4112 ;; destroys our shell functions, we must disable it. See
4113 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
4114 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
4115 (tramp-send-command vec "set +H" t))
4116
4117 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
4118 (when (string-match "BSD\\|Darwin"
4119 (tramp-get-connection-property vec "uname" ""))
4120 (tramp-send-command vec "stty -oxtabs" t))
4121
4122 ;; Set utf8 encoding. Needed for Mac OS X, for example. This is
4123 ;; non-POSIX, so we must expect errors on some systems.
4124 (tramp-send-command vec "stty iutf8 2>/dev/null" t)
4125
4126 ;; Set `remote-tty' process property.
4127 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
4128 (unless (zerop (length tty))
4129 (process-put proc 'remote-tty tty)))
4130
4131 ;; Dump stty settings in the traces.
4132 (when (>= tramp-verbose 9)
4133 (tramp-send-command vec "stty -a" t))
4134
4135 ;; Set the environment.
4136 (tramp-message vec 5 "Setting default environment")
4137
4138 (let ((env (append `(,(tramp-get-remote-locale vec))
4139 (copy-sequence tramp-remote-process-environment)))
4140 unset vars item)
4141 (while env
4142 (setq item (split-string (car env) "=" 'omit))
4143 (setcdr item (mapconcat 'identity (cdr item) "="))
4144 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
4145 (push (format "%s %s" (car item) (cdr item)) vars)
4146 (push (car item) unset))
4147 (setq env (cdr env)))
4148 (when vars
4149 (tramp-send-command
4150 vec
4151 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
4152 tramp-end-of-heredoc
4153 (mapconcat 'identity vars "\n")
4154 tramp-end-of-heredoc)
4155 t))
4156 (when unset
4157 (tramp-send-command
4158 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
4159
4160 ;; Old text from documentation of tramp-methods:
4161 ;; Using a uuencode/uudecode inline method is discouraged, please use one
4162 ;; of the base64 methods instead since base64 encoding is much more
4163 ;; reliable and the commands are more standardized between the different
4164 ;; Unix versions. But if you can't use base64 for some reason, please
4165 ;; note that the default uudecode command does not work well for some
4166 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
4167 ;; the following command for uudecode:
4168 ;;
4169 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
4170 ;;
4171 ;; For Irix, no solution is known yet.
4172
4173 (autoload 'uudecode-decode-region "uudecode")
4174
4175 (defconst tramp-local-coding-commands
4176 `((b64 base64-encode-region base64-decode-region)
4177 (uu tramp-uuencode-region uudecode-decode-region)
4178 (pack ,(format tramp-perl-pack "perl") ,(format tramp-perl-unpack "perl")))
4179 "List of local coding commands for inline transfer.
4180 Each item is a list that looks like this:
4181
4182 \(FORMAT ENCODING DECODING)
4183
4184 FORMAT is symbol describing the encoding/decoding format. It can be
4185 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4186
4187 ENCODING and DECODING can be strings, giving commands, or symbols,
4188 giving functions. If they are strings, then they can contain
4189 the \"%s\" format specifier. If that specifier is present, the input
4190 file name will be put into the command line at that spot. If the
4191 specifier is not present, the input should be read from standard
4192 input.
4193
4194 If they are functions, they will be called with two arguments, start
4195 and end of region, and are expected to replace the region contents
4196 with the encoded or decoded results, respectively.")
4197
4198 (defconst tramp-remote-coding-commands
4199 `((b64 "base64" "base64 -d -i")
4200 ;; "-i" is more robust with older base64 from GNU coreutils.
4201 ;; However, I don't know whether all base64 versions do supports
4202 ;; this option.
4203 (b64 "base64" "base64 -d")
4204 (b64 "openssl enc -base64" "openssl enc -d -base64")
4205 (b64 "mimencode -b" "mimencode -u -b")
4206 (b64 "mmencode -b" "mmencode -u -b")
4207 (b64 "recode data..base64" "recode base64..data")
4208 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
4209 (b64 tramp-perl-encode tramp-perl-decode)
4210 ;; This is painful slow, so we put it on the end.
4211 (b64 tramp-awk-encode tramp-awk-decode ,tramp-awk-coding-test)
4212 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
4213 (uu "uuencode xxx" "uudecode -o -")
4214 (uu "uuencode xxx" "uudecode -p")
4215 (uu "uuencode xxx" tramp-uudecode)
4216 (pack tramp-perl-pack tramp-perl-unpack))
4217 "List of remote coding commands for inline transfer.
4218 Each item is a list that looks like this:
4219
4220 \(FORMAT ENCODING DECODING [TEST])
4221
4222 FORMAT is a symbol describing the encoding/decoding format. It can be
4223 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4224
4225 ENCODING and DECODING can be strings, giving commands, or symbols,
4226 giving variables. If they are strings, then they can contain
4227 the \"%s\" format specifier. If that specifier is present, the input
4228 file name will be put into the command line at that spot. If the
4229 specifier is not present, the input should be read from standard
4230 input.
4231
4232 If they are variables, this variable is a string containing a
4233 Perl or Shell implementation for this functionality. This
4234 program will be transferred to the remote host, and it is
4235 available as shell function with the same name. A \"%t\" format
4236 specifier in the variable value denotes a temporary file.
4237
4238 The optional TEST command can be used for further tests, whether
4239 ENCODING and DECODING are applicable.")
4240
4241 (defun tramp-find-inline-encoding (vec)
4242 "Find an inline transfer encoding that works.
4243 Goes through the list `tramp-local-coding-commands' and
4244 `tramp-remote-coding-commands'."
4245 (save-excursion
4246 (let ((local-commands tramp-local-coding-commands)
4247 (magic "xyzzy")
4248 (p (tramp-get-connection-process vec))
4249 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4250 (while (and local-commands (not found))
4251 (setq litem (pop local-commands))
4252 (catch 'wont-work-local
4253 (let ((format (nth 0 litem))
4254 (remote-commands tramp-remote-coding-commands))
4255 (setq loc-enc (nth 1 litem))
4256 (setq loc-dec (nth 2 litem))
4257 ;; If the local encoder or decoder is a string, the
4258 ;; corresponding command has to work locally.
4259 (if (not (stringp loc-enc))
4260 (tramp-message
4261 vec 5 "Checking local encoding function `%s'" loc-enc)
4262 (tramp-message
4263 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4264 (unless (zerop (tramp-call-local-coding-command
4265 loc-enc nil nil))
4266 (throw 'wont-work-local nil)))
4267 (if (not (stringp loc-dec))
4268 (tramp-message
4269 vec 5 "Checking local decoding function `%s'" loc-dec)
4270 (tramp-message
4271 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4272 (unless (zerop (tramp-call-local-coding-command
4273 loc-dec nil nil))
4274 (throw 'wont-work-local nil)))
4275 ;; Search for remote coding commands with the same format
4276 (while (and remote-commands (not found))
4277 (setq ritem (pop remote-commands))
4278 (catch 'wont-work-remote
4279 (when (equal format (nth 0 ritem))
4280 (setq rem-enc (nth 1 ritem))
4281 (setq rem-dec (nth 2 ritem))
4282 (setq rem-test (nth 3 ritem))
4283 ;; Check the remote test command if exists.
4284 (when (stringp rem-test)
4285 (tramp-message
4286 vec 5 "Checking remote test command `%s'" rem-test)
4287 (unless (tramp-send-command-and-check vec rem-test t)
4288 (throw 'wont-work-remote nil)))
4289 ;; Check if remote perl exists when necessary.
4290 (when (and (symbolp rem-enc)
4291 (string-match "perl" (symbol-name rem-enc))
4292 (not (tramp-get-remote-perl vec)))
4293 (throw 'wont-work-remote nil))
4294 ;; Check if remote encoding and decoding commands can be
4295 ;; called remotely with null input and output. This makes
4296 ;; sure there are no syntax errors and the command is really
4297 ;; found. Note that we do not redirect stdout to /dev/null,
4298 ;; for two reasons: when checking the decoding command, we
4299 ;; actually check the output it gives. And also, when
4300 ;; redirecting "mimencode" output to /dev/null, then as root
4301 ;; it might change the permissions of /dev/null!
4302 (when (not (stringp rem-enc))
4303 (let ((name (symbol-name rem-enc)))
4304 (while (string-match (regexp-quote "-") name)
4305 (setq name (replace-match "_" nil t name)))
4306 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4307 (setq rem-enc name)))
4308 (tramp-message
4309 vec 5
4310 "Checking remote encoding command `%s' for sanity" rem-enc)
4311 (unless (tramp-send-command-and-check
4312 vec (format "%s </dev/null" rem-enc) t)
4313 (throw 'wont-work-remote nil))
4314
4315 (when (not (stringp rem-dec))
4316 (let ((name (symbol-name rem-dec))
4317 (value (symbol-value rem-dec))
4318 tmpfile)
4319 (while (string-match (regexp-quote "-") name)
4320 (setq name (replace-match "_" nil t name)))
4321 (when (string-match "\\(^\\|[^%]\\)%t" value)
4322 (setq tmpfile
4323 (make-temp-name
4324 (expand-file-name
4325 tramp-temp-name-prefix
4326 (tramp-get-remote-tmpdir vec)))
4327 value
4328 (format-spec
4329 value
4330 (format-spec-make
4331 ?t
4332 (file-remote-p tmpfile 'localname)))))
4333 (tramp-maybe-send-script vec value name)
4334 (setq rem-dec name)))
4335 (tramp-message
4336 vec 5
4337 "Checking remote decoding command `%s' for sanity" rem-dec)
4338 (unless (tramp-send-command-and-check
4339 vec
4340 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4341 t)
4342 (throw 'wont-work-remote nil))
4343
4344 (with-current-buffer (tramp-get-buffer vec)
4345 (goto-char (point-min))
4346 (unless (looking-at (regexp-quote magic))
4347 (throw 'wont-work-remote nil)))
4348
4349 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4350 (setq rem-enc (nth 1 ritem))
4351 (setq rem-dec (nth 2 ritem))
4352 (setq found t)))))))
4353
4354 (when found
4355 ;; Set connection properties. Since the commands are risky
4356 ;; (due to output direction), we cache them in the process cache.
4357 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4358 (tramp-set-connection-property p "local-encoding" loc-enc)
4359 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4360 (tramp-set-connection-property p "local-decoding" loc-dec)
4361 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4362 (tramp-set-connection-property p "remote-encoding" rem-enc)
4363 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4364 (tramp-set-connection-property p "remote-decoding" rem-dec)))))
4365
4366 (defun tramp-call-local-coding-command (cmd input output)
4367 "Call the local encoding or decoding command.
4368 If CMD contains \"%s\", provide input file INPUT there in command.
4369 Otherwise, INPUT is passed via standard input.
4370 INPUT can also be nil which means `/dev/null'.
4371 OUTPUT can be a string (which specifies a file name), or t (which
4372 means standard output and thus the current buffer), or nil (which
4373 means discard it)."
4374 (tramp-call-process
4375 nil tramp-encoding-shell
4376 (when (and input (not (string-match "%s" cmd))) input)
4377 (if (eq output t) t nil)
4378 nil
4379 tramp-encoding-command-switch
4380 (concat
4381 (if (string-match "%s" cmd) (format cmd input) cmd)
4382 (if (stringp output) (concat " >" output) ""))))
4383
4384 (defconst tramp-inline-compress-commands
4385 '(("gzip" "gzip -d")
4386 ("bzip2" "bzip2 -d")
4387 ("xz" "xz -d")
4388 ("compress" "compress -d"))
4389 "List of compress and decompress commands for inline transfer.
4390 Each item is a list that looks like this:
4391
4392 \(COMPRESS DECOMPRESS)
4393
4394 COMPRESS or DECOMPRESS are strings with the respective commands.")
4395
4396 (defun tramp-find-inline-compress (vec)
4397 "Find an inline transfer compress command that works.
4398 Goes through the list `tramp-inline-compress-commands'."
4399 (save-excursion
4400 (let ((commands tramp-inline-compress-commands)
4401 (magic "xyzzy")
4402 (p (tramp-get-connection-process vec))
4403 item compress decompress found)
4404 (while (and commands (not found))
4405 (catch 'next
4406 (setq item (pop commands)
4407 compress (nth 0 item)
4408 decompress (nth 1 item))
4409 (tramp-message
4410 vec 5
4411 "Checking local compress commands `%s', `%s' for sanity"
4412 compress decompress)
4413 (unless
4414 (zerop
4415 (tramp-call-local-coding-command
4416 (format
4417 ;; Windows shells need the program file name after
4418 ;; the pipe symbol be quoted if they use forward
4419 ;; slashes as directory separators.
4420 (if (memq system-type '(windows-nt))
4421 "echo %s | \"%s\" | \"%s\""
4422 "echo %s | %s | %s")
4423 magic compress decompress) nil nil))
4424 (throw 'next nil))
4425 (tramp-message
4426 vec 5
4427 "Checking remote compress commands `%s', `%s' for sanity"
4428 compress decompress)
4429 (unless (tramp-send-command-and-check
4430 vec (format "echo %s | %s | %s" magic compress decompress) t)
4431 (throw 'next nil))
4432 (setq found t)))
4433
4434 ;; Did we find something?
4435 (if found
4436 (progn
4437 ;; Set connection properties. Since the commands are
4438 ;; risky (due to output direction), we cache them in the
4439 ;; process cache.
4440 (tramp-message
4441 vec 5 "Using inline transfer compress command `%s'" compress)
4442 (tramp-set-connection-property p "inline-compress" compress)
4443 (tramp-message
4444 vec 5 "Using inline transfer decompress command `%s'" decompress)
4445 (tramp-set-connection-property p "inline-decompress" decompress))
4446
4447 (tramp-set-connection-property p "inline-compress" nil)
4448 (tramp-set-connection-property p "inline-decompress" nil)
4449 (tramp-message
4450 vec 2 "Couldn't find an inline transfer compress command")))))
4451
4452 (defun tramp-compute-multi-hops (vec)
4453 "Expands VEC according to `tramp-default-proxies-alist'.
4454 Gateway hops are already opened."
4455 (let ((target-alist `(,vec))
4456 (hops (or (tramp-file-name-hop vec) ""))
4457 (item vec)
4458 choices proxy)
4459
4460 ;; Ad-hoc proxy definitions.
4461 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4462 (let ((user (tramp-file-name-user item))
4463 (host (tramp-file-name-host item))
4464 (proxy (concat
4465 tramp-prefix-format proxy tramp-postfix-host-format)))
4466 (tramp-message
4467 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4468 (and (stringp host) (regexp-quote host))
4469 (and (stringp user) (regexp-quote user))
4470 proxy)
4471 ;; Add the hop.
4472 (add-to-list
4473 'tramp-default-proxies-alist
4474 (list (and (stringp host) (regexp-quote host))
4475 (and (stringp user) (regexp-quote user))
4476 proxy))
4477 (setq item (tramp-dissect-file-name proxy))))
4478 ;; Save the new value.
4479 (when (and hops tramp-save-ad-hoc-proxies)
4480 (customize-save-variable
4481 'tramp-default-proxies-alist tramp-default-proxies-alist))
4482
4483 ;; Look for proxy hosts to be passed.
4484 (setq choices tramp-default-proxies-alist)
4485 (while choices
4486 (setq item (pop choices)
4487 proxy (eval (nth 2 item)))
4488 (when (and
4489 ;; Host.
4490 (string-match (or (eval (nth 0 item)) "")
4491 (or (tramp-file-name-host (car target-alist)) ""))
4492 ;; User.
4493 (string-match (or (eval (nth 1 item)) "")
4494 (or (tramp-file-name-user (car target-alist)) "")))
4495 (if (null proxy)
4496 ;; No more hops needed.
4497 (setq choices nil)
4498 ;; Replace placeholders.
4499 (setq proxy
4500 (format-spec
4501 proxy
4502 (format-spec-make
4503 ?u (or (tramp-file-name-user (car target-alist)) "")
4504 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4505 (with-parsed-tramp-file-name proxy l
4506 ;; Add the hop.
4507 (push l target-alist)
4508 ;; Start next search.
4509 (setq choices tramp-default-proxies-alist)))))
4510
4511 ;; Handle gateways.
4512 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4513 (string-match
4514 (format
4515 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4516 (tramp-file-name-method (car target-alist))))
4517 (let ((gw (pop target-alist))
4518 (hop (pop target-alist)))
4519 ;; Is the method prepared for gateways?
4520 (unless (tramp-file-name-port hop)
4521 (tramp-error
4522 vec 'file-error
4523 "Connection `%s' is not supported for gateway access." hop))
4524 ;; Open the gateway connection.
4525 (push
4526 (vector
4527 (tramp-file-name-method hop) (tramp-file-name-user hop)
4528 (tramp-gw-open-connection vec gw hop) nil nil)
4529 target-alist)
4530 ;; For the password prompt, we need the correct values.
4531 ;; Therefore, we must remember the gateway vector. But we
4532 ;; cannot do it as connection property, because it shouldn't
4533 ;; be persistent. And we have no started process yet either.
4534 (let ((tramp-verbose 0))
4535 (tramp-set-file-property (car target-alist) "" "gateway" hop))))
4536
4537 ;; Foreign and out-of-band methods are not supported for multi-hops.
4538 (when (cdr target-alist)
4539 (setq choices target-alist)
4540 (while (setq item (pop choices))
4541 (when (or (not (tramp-get-method-parameter item 'tramp-login-program))
4542 (tramp-get-method-parameter item 'tramp-copy-program))
4543 (tramp-error
4544 vec 'file-error
4545 "Method `%s' is not supported for multi-hops."
4546 (tramp-file-name-method item)))))
4547
4548 ;; In case the host name is not used for the remote shell
4549 ;; command, the user could be misguided by applying a random
4550 ;; host name.
4551 (let* ((v (car target-alist))
4552 (method (tramp-file-name-method v))
4553 (host (tramp-file-name-host v)))
4554 (unless
4555 (or
4556 ;; There are multi-hops.
4557 (cdr target-alist)
4558 ;; The host name is used for the remote shell command.
4559 (member '("%h") (tramp-get-method-parameter v 'tramp-login-args))
4560 ;; The host is local. We cannot use `tramp-local-host-p'
4561 ;; here, because it opens a connection as well.
4562 (string-match tramp-local-host-regexp host))
4563 (tramp-error
4564 v 'file-error
4565 "Host `%s' looks like a remote host, `%s' can only use the local host"
4566 host method)))
4567
4568 ;; Result.
4569 target-alist))
4570
4571 (defun tramp-ssh-controlmaster-options (vec)
4572 "Return the Control* arguments of the local ssh."
4573 (cond
4574 ;; No options to be computed.
4575 ((or (null tramp-use-ssh-controlmaster-options)
4576 (null (assoc "%c" (tramp-get-method-parameter vec 'tramp-login-args))))
4577 "")
4578
4579 ;; There is already a value to be used.
4580 ((stringp tramp-ssh-controlmaster-options) tramp-ssh-controlmaster-options)
4581
4582 ;; Determine the options.
4583 (t (setq tramp-ssh-controlmaster-options "")
4584 (let ((case-fold-search t))
4585 (ignore-errors
4586 (when (executable-find "ssh")
4587 (with-temp-buffer
4588 (tramp-call-process vec "ssh" nil t nil "-o" "ControlMaster")
4589 (goto-char (point-min))
4590 (when (search-forward-regexp "missing.+argument" nil t)
4591 (setq tramp-ssh-controlmaster-options "-o ControlMaster=auto")))
4592 (unless (zerop (length tramp-ssh-controlmaster-options))
4593 (with-temp-buffer
4594 ;; We use a non-existing IP address, in order to avoid
4595 ;; useless connections, and DNS timeouts.
4596 (tramp-call-process
4597 vec "ssh" nil t nil "-o" "ControlPath=%C" "0.0.0.1")
4598 (goto-char (point-min))
4599 (setq tramp-ssh-controlmaster-options
4600 (concat tramp-ssh-controlmaster-options
4601 (if (search-forward-regexp "unknown.+key" nil t)
4602 " -o ControlPath='tramp.%%r@%%h:%%p'"
4603 " -o ControlPath='tramp.%%C'"))))
4604 (with-temp-buffer
4605 (tramp-call-process vec "ssh" nil t nil "-o" "ControlPersist")
4606 (goto-char (point-min))
4607 (when (search-forward-regexp "missing.+argument" nil t)
4608 (setq tramp-ssh-controlmaster-options
4609 (concat tramp-ssh-controlmaster-options
4610 " -o ControlPersist=no"))))))))
4611 tramp-ssh-controlmaster-options)))
4612
4613 (defun tramp-maybe-open-connection (vec)
4614 "Maybe open a connection VEC.
4615 Does not do anything if a connection is already open, but re-opens the
4616 connection if a previous connection has died for some reason."
4617 (tramp-check-proper-method-and-host vec)
4618
4619 (let ((p (tramp-get-connection-process vec))
4620 (process-name (tramp-get-connection-property vec "process-name" nil))
4621 (process-environment (copy-sequence process-environment))
4622 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4623
4624 ;; If Tramp opens the same connection within a short time frame,
4625 ;; there is a problem. We shall signal this.
4626 (unless (or (and p (processp p) (memq (process-status p) '(run open)))
4627 (not (equal (butlast (append vec nil) 2)
4628 (car tramp-current-connection)))
4629 (> (tramp-time-diff
4630 (current-time) (cdr tramp-current-connection))
4631 (or tramp-connection-min-time-diff 0)))
4632 (throw 'suppress 'suppress))
4633
4634 ;; If too much time has passed since last command was sent, look
4635 ;; whether process is still alive. If it isn't, kill it. When
4636 ;; using ssh, it can sometimes happen that the remote end has hung
4637 ;; up but the local ssh client doesn't recognize this until it
4638 ;; tries to send some data to the remote end. So that's why we
4639 ;; try to send a command from time to time, then look again
4640 ;; whether the process is really alive.
4641 (condition-case nil
4642 (when (and (> (tramp-time-diff
4643 (current-time)
4644 (tramp-get-connection-property
4645 p "last-cmd-time" '(0 0 0)))
4646 60)
4647 p (processp p) (memq (process-status p) '(run open)))
4648 (tramp-send-command vec "echo are you awake" t t)
4649 (unless (and (memq (process-status p) '(run open))
4650 (tramp-wait-for-output p 10))
4651 ;; The error will be caught locally.
4652 (tramp-error vec 'file-error "Awake did fail")))
4653 (file-error
4654 (tramp-cleanup-connection vec t)
4655 (setq p nil)))
4656
4657 ;; New connection must be opened.
4658 (condition-case err
4659 (unless (and p (processp p) (memq (process-status p) '(run open)))
4660
4661 ;; If `non-essential' is non-nil, don't reopen a new connection.
4662 ;; This variable has been introduced with Emacs 24.1.
4663 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4664 (throw 'non-essential 'non-essential))
4665
4666 (with-tramp-progress-reporter
4667 vec 3
4668 (if (zerop (length (tramp-file-name-user vec)))
4669 (format "Opening connection for %s using %s"
4670 (tramp-file-name-host vec)
4671 (tramp-file-name-method vec))
4672 (format "Opening connection for %s@%s using %s"
4673 (tramp-file-name-user vec)
4674 (tramp-file-name-host vec)
4675 (tramp-file-name-method vec)))
4676
4677 (catch 'uname-changed
4678 ;; Start new process.
4679 (when (and p (processp p))
4680 (delete-process p))
4681 (setenv "TERM" tramp-terminal-type)
4682 (setenv "LC_ALL" (tramp-get-local-locale vec))
4683 (if (stringp tramp-histfile-override)
4684 (setenv "HISTFILE" tramp-histfile-override)
4685 (if tramp-histfile-override
4686 (progn
4687 (setenv "HISTFILE")
4688 (setenv "HISTFILESIZE" "0")
4689 (setenv "HISTSIZE" "0"))))
4690 (setenv "PROMPT_COMMAND")
4691 (setenv "PS1" tramp-initial-end-of-output)
4692 (unless (stringp tramp-encoding-shell)
4693 (tramp-error vec 'file-error "`tramp-encoding-shell' not set"))
4694 (let* ((target-alist (tramp-compute-multi-hops vec))
4695 ;; We will apply `tramp-ssh-controlmaster-options'
4696 ;; only for the first hop.
4697 (options (tramp-ssh-controlmaster-options vec))
4698 (process-connection-type tramp-process-connection-type)
4699 (process-adaptive-read-buffering nil)
4700 ;; There are unfortunate settings for "cmdproxy" on
4701 ;; W32 systems.
4702 (process-coding-system-alist nil)
4703 (coding-system-for-read nil)
4704 ;; This must be done in order to avoid our file
4705 ;; name handler.
4706 (p (let ((default-directory
4707 (tramp-compat-temporary-file-directory)))
4708 (apply
4709 'start-process
4710 (tramp-get-connection-name vec)
4711 (tramp-get-connection-buffer vec)
4712 (if tramp-encoding-command-interactive
4713 (list tramp-encoding-shell
4714 tramp-encoding-command-interactive)
4715 (list tramp-encoding-shell))))))
4716
4717 ;; Set sentinel and query flag.
4718 (tramp-set-connection-property p "vector" vec)
4719 (set-process-sentinel p 'tramp-process-sentinel)
4720 (set-process-query-on-exit-flag p nil)
4721 (setq tramp-current-connection
4722 (cons (butlast (append vec nil) 2) (current-time))
4723 tramp-current-host (system-name))
4724
4725 (tramp-message
4726 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4727
4728 ;; Check whether process is alive.
4729 (tramp-barf-if-no-shell-prompt
4730 p 10
4731 "Couldn't find local shell prompt for %s" tramp-encoding-shell)
4732
4733 ;; Now do all the connections as specified.
4734 (while target-alist
4735 (let* ((hop (car target-alist))
4736 (l-method (tramp-file-name-method hop))
4737 (l-user (tramp-file-name-user hop))
4738 (l-host (tramp-file-name-host hop))
4739 (l-port nil)
4740 (login-program
4741 (tramp-get-method-parameter hop 'tramp-login-program))
4742 (login-args
4743 (tramp-get-method-parameter hop 'tramp-login-args))
4744 (login-env
4745 (tramp-get-method-parameter hop 'tramp-login-env))
4746 (async-args
4747 (tramp-get-method-parameter hop 'tramp-async-args))
4748 (connection-timeout
4749 (tramp-get-method-parameter
4750 hop 'tramp-connection-timeout))
4751 (gw-args
4752 (tramp-get-method-parameter hop 'tramp-gw-args))
4753 (gw (let ((tramp-verbose 0))
4754 (tramp-get-file-property hop "" "gateway" nil)))
4755 (g-method (and gw (tramp-file-name-method gw)))
4756 (g-user (and gw (tramp-file-name-user gw)))
4757 (g-host (and gw (tramp-file-name-real-host gw)))
4758 (command login-program)
4759 ;; We don't create the temporary file. In
4760 ;; fact, it is just a prefix for the
4761 ;; ControlPath option of ssh; the real
4762 ;; temporary file has another name, and it is
4763 ;; created and protected by ssh. It is also
4764 ;; removed by ssh when the connection is
4765 ;; closed. The temporary file name is cached
4766 ;; in the main connection process, therefore
4767 ;; we cannot use `tramp-get-connection-process'.
4768 (tmpfile
4769 (with-tramp-connection-property
4770 (get-process (tramp-buffer-name vec)) "temp-file"
4771 (make-temp-name
4772 (expand-file-name
4773 tramp-temp-name-prefix
4774 (tramp-compat-temporary-file-directory)))))
4775 spec r-shell)
4776
4777 ;; Add arguments for asynchronous processes.
4778 (when (and process-name async-args)
4779 (setq login-args (append async-args login-args)))
4780
4781 ;; Add gateway arguments if necessary.
4782 (when gw
4783 (tramp-set-connection-property p "gateway" t)
4784 (when gw-args
4785 (setq login-args (append gw-args login-args))))
4786
4787 ;; Check for port number. Until now, there's no
4788 ;; need for handling like method, user, host.
4789 (when (string-match tramp-host-with-port-regexp l-host)
4790 (setq l-port (match-string 2 l-host)
4791 l-host (match-string 1 l-host)))
4792
4793 ;; Check, whether there is a restricted shell.
4794 (dolist (elt tramp-restricted-shell-hosts-alist)
4795 (when (string-match elt tramp-current-host)
4796 (setq r-shell t)))
4797
4798 ;; Set variables for computing the prompt for
4799 ;; reading password. They can also be derived
4800 ;; from a gateway.
4801 (setq tramp-current-method (or g-method l-method)
4802 tramp-current-user (or g-user l-user)
4803 tramp-current-host (or g-host l-host))
4804
4805 ;; Add login environment.
4806 (when login-env
4807 (setq
4808 login-env
4809 (mapcar
4810 (lambda (x)
4811 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4812 (unless (member "" x) (mapconcat 'identity x " ")))
4813 login-env))
4814 (while login-env
4815 (setq command
4816 (format
4817 "%s=%s %s"
4818 (pop login-env)
4819 (tramp-shell-quote-argument (pop login-env))
4820 command)))
4821 (setq command (concat "env " command)))
4822
4823 ;; Replace `login-args' place holders.
4824 (setq
4825 l-host (or l-host "")
4826 l-user (or l-user "")
4827 l-port (or l-port "")
4828 spec (format-spec-make ?t tmpfile)
4829 options (format-spec options spec)
4830 spec (format-spec-make
4831 ?h l-host ?u l-user ?p l-port ?c options)
4832 command
4833 (concat
4834 ;; We do not want to see the trailing local
4835 ;; prompt in `start-file-process'.
4836 (unless r-shell "exec ")
4837 command " "
4838 (mapconcat
4839 (lambda (x)
4840 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4841 (unless (member "" x) (mapconcat 'identity x " ")))
4842 login-args " ")
4843 ;; Local shell could be a Windows COMSPEC. It
4844 ;; doesn't know the ";" syntax, but we must exit
4845 ;; always for `start-file-process'. It could
4846 ;; also be a restricted shell, which does not
4847 ;; allow "exec".
4848 (when r-shell " && exit || exit")))
4849
4850 ;; Send the command.
4851 (tramp-message vec 3 "Sending command `%s'" command)
4852 (tramp-send-command vec command t t)
4853 (tramp-process-actions
4854 p vec pos tramp-actions-before-shell
4855 (or connection-timeout tramp-connection-timeout))
4856 (tramp-message
4857 vec 3 "Found remote shell prompt on `%s'" l-host))
4858 ;; Next hop.
4859 (setq options ""
4860 target-alist (cdr target-alist)))
4861
4862 ;; Make initial shell settings.
4863 (tramp-open-connection-setup-interactive-shell p vec)
4864
4865 ;; Mark it as connected.
4866 (tramp-set-connection-property p "connected" t)))))
4867
4868 ;; When the user did interrupt, we must cleanup.
4869 (quit
4870 (tramp-cleanup-connection vec t)
4871 ;; Propagate the quit signal.
4872 (signal (car err) (cdr err))))))
4873
4874 (defun tramp-send-command (vec command &optional neveropen nooutput)
4875 "Send the COMMAND to connection VEC.
4876 Erases temporary buffer before sending the command. If optional
4877 arg NEVEROPEN is non-nil, never try to open the connection. This
4878 is meant to be used from `tramp-maybe-open-connection' only. The
4879 function waits for output unless NOOUTPUT is set."
4880 (unless neveropen (tramp-maybe-open-connection vec))
4881 (let ((p (tramp-get-connection-process vec)))
4882 (when (tramp-get-connection-property p "remote-echo" nil)
4883 ;; We mark the command string that it can be erased in the output buffer.
4884 (tramp-set-connection-property p "check-remote-echo" t)
4885 ;; If we put `tramp-echo-mark' after a trailing newline (which
4886 ;; is assumed to be unquoted) `tramp-send-string' doesn't see
4887 ;; that newline and adds `tramp-rsh-end-of-line' right after
4888 ;; `tramp-echo-mark', so the remote shell sees two consecutive
4889 ;; trailing line endings and sends two prompts after executing
4890 ;; the command, which confuses `tramp-wait-for-output'.
4891 (when (and (not (string= command ""))
4892 (string-equal (substring command -1) "\n"))
4893 (setq command (substring command 0 -1)))
4894 ;; No need to restore a trailing newline here since `tramp-send-string'
4895 ;; makes sure that the string ends in `tramp-rsh-end-of-line', anyway.
4896 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4897 ;; Send the command.
4898 (tramp-message vec 6 "%s" command)
4899 (tramp-send-string vec command)
4900 (unless nooutput (tramp-wait-for-output p))))
4901
4902 (defun tramp-wait-for-output (proc &optional timeout)
4903 "Wait for output from remote command."
4904 (unless (buffer-live-p (process-buffer proc))
4905 (delete-process proc)
4906 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4907 (with-current-buffer (process-buffer proc)
4908 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4909 ;; be leading escape sequences, which must be ignored.
4910 ;; Busyboxes built with the EDITING_ASK_TERMINAL config
4911 ;; option send also escape sequences, which must be
4912 ;; ignored.
4913 (regexp (format "[^#$\n]*%s\\(%s\\)?\r?$"
4914 (regexp-quote tramp-end-of-output)
4915 tramp-device-escape-sequence-regexp))
4916 ;; Sometimes, the commands do not return a newline but a
4917 ;; null byte before the shell prompt, for example "git
4918 ;; ls-files -c -z ...".
4919 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4920 (found (tramp-wait-for-regexp proc timeout regexp1)))
4921 (if found
4922 (let (buffer-read-only)
4923 ;; A simple-minded busybox has sent " ^H" sequences.
4924 ;; Delete them.
4925 (goto-char (point-min))
4926 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4927 (forward-line 1)
4928 (delete-region (point-min) (point)))
4929 ;; Delete the prompt.
4930 (goto-char (point-max))
4931 (re-search-backward regexp nil t)
4932 (delete-region (point) (point-max)))
4933 (if timeout
4934 (tramp-error
4935 proc 'file-error
4936 "[[Remote prompt `%s' not found in %d secs]]"
4937 tramp-end-of-output timeout)
4938 (tramp-error
4939 proc 'file-error
4940 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
4941 ;; Return value is whether end-of-output sentinel was found.
4942 found)))
4943
4944 (defun tramp-send-command-and-check
4945 (vec command &optional subshell dont-suppress-err)
4946 "Run COMMAND and check its exit status.
4947 Sends `echo $?' along with the COMMAND for checking the exit status.
4948 If COMMAND is nil, just sends `echo $?'. Returns t if the exit
4949 status is 0, and nil otherwise.
4950
4951 If the optional argument SUBSHELL is non-nil, the command is
4952 executed in a subshell, ie surrounded by parentheses. If
4953 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
4954 (tramp-send-command
4955 vec
4956 (concat (if subshell "( " "")
4957 command
4958 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
4959 "echo tramp_exit_status $?"
4960 (if subshell " )" "")))
4961 (with-current-buffer (tramp-get-connection-buffer vec)
4962 (goto-char (point-max))
4963 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
4964 (tramp-error
4965 vec 'file-error "Couldn't find exit status of `%s'" command))
4966 (skip-chars-forward "^ ")
4967 (prog1
4968 (zerop (read (current-buffer)))
4969 (let (buffer-read-only)
4970 (delete-region (match-beginning 0) (point-max))))))
4971
4972 (defun tramp-barf-unless-okay (vec command fmt &rest args)
4973 "Run COMMAND, check exit status, throw error if exit status not okay.
4974 Similar to `tramp-send-command-and-check' but accepts two more arguments
4975 FMT and ARGS which are passed to `error'."
4976 (or (tramp-send-command-and-check vec command)
4977 (apply 'tramp-error vec 'file-error fmt args)))
4978
4979 (defun tramp-send-command-and-read (vec command &optional noerror marker)
4980 "Run COMMAND and return the output, which must be a Lisp expression.
4981 If MARKER is a regexp, read the output after that string.
4982 In case there is no valid Lisp expression and NOERROR is nil, it
4983 raises an error."
4984 (when (if noerror
4985 (tramp-send-command-and-check vec command)
4986 (tramp-barf-unless-okay
4987 vec command "`%s' returns with error" command))
4988 (with-current-buffer (tramp-get-connection-buffer vec)
4989 (goto-char (point-min))
4990 ;; Read the marker.
4991 (when (stringp marker)
4992 (condition-case nil
4993 (re-search-forward marker)
4994 (error (unless noerror
4995 (tramp-error
4996 vec 'file-error
4997 "`%s' does not return the marker `%s': `%s'"
4998 command marker (buffer-string))))))
4999 ;; Read the expression.
5000 (condition-case nil
5001 (prog1 (read (current-buffer))
5002 ;; Error handling.
5003 (when (re-search-forward "\\S-" (point-at-eol) t)
5004 (error nil)))
5005 (error (unless noerror
5006 (tramp-error
5007 vec 'file-error
5008 "`%s' does not return a valid Lisp expression: `%s'"
5009 command (buffer-string))))))))
5010
5011 (defun tramp-convert-file-attributes (vec attr)
5012 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
5013 Convert file mode bits to string and set virtual device number.
5014 Return ATTR."
5015 (when attr
5016 ;; Remove color escape sequences from symlink.
5017 (when (stringp (car attr))
5018 (while (string-match tramp-display-escape-sequence-regexp (car attr))
5019 (setcar attr (replace-match "" nil nil (car attr)))))
5020 ;; Convert uid and gid. Use `tramp-unknown-id-integer' as
5021 ;; indication of unusable value.
5022 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
5023 (setcar (nthcdr 2 attr) tramp-unknown-id-integer))
5024 (when (and (floatp (nth 2 attr))
5025 (<= (nth 2 attr) most-positive-fixnum))
5026 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
5027 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
5028 (setcar (nthcdr 3 attr) tramp-unknown-id-integer))
5029 (when (and (floatp (nth 3 attr))
5030 (<= (nth 3 attr) most-positive-fixnum))
5031 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
5032 ;; Convert last access time.
5033 (unless (listp (nth 4 attr))
5034 (setcar (nthcdr 4 attr)
5035 (list (floor (nth 4 attr) 65536)
5036 (floor (mod (nth 4 attr) 65536)))))
5037 ;; Convert last modification time.
5038 (unless (listp (nth 5 attr))
5039 (setcar (nthcdr 5 attr)
5040 (list (floor (nth 5 attr) 65536)
5041 (floor (mod (nth 5 attr) 65536)))))
5042 ;; Convert last status change time.
5043 (unless (listp (nth 6 attr))
5044 (setcar (nthcdr 6 attr)
5045 (list (floor (nth 6 attr) 65536)
5046 (floor (mod (nth 6 attr) 65536)))))
5047 ;; Convert file size.
5048 (when (< (nth 7 attr) 0)
5049 (setcar (nthcdr 7 attr) -1))
5050 (when (and (floatp (nth 7 attr))
5051 (<= (nth 7 attr) most-positive-fixnum))
5052 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
5053 ;; Convert file mode bits to string.
5054 (unless (stringp (nth 8 attr))
5055 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
5056 (when (stringp (car attr))
5057 (aset (nth 8 attr) 0 ?l)))
5058 ;; Convert directory indication bit.
5059 (when (string-match "^d" (nth 8 attr))
5060 (setcar attr t))
5061 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
5062 (when (consp (car attr))
5063 (if (and (stringp (caar attr))
5064 (string-match ".+ -> .\\(.+\\)." (caar attr)))
5065 (setcar attr (match-string 1 (caar attr)))
5066 (setcar attr nil)))
5067 ;; Set file's gid change bit.
5068 (setcar (nthcdr 9 attr)
5069 (if (numberp (nth 3 attr))
5070 (not (= (nth 3 attr)
5071 (tramp-get-remote-gid vec 'integer)))
5072 (not (string-equal
5073 (nth 3 attr)
5074 (tramp-get-remote-gid vec 'string)))))
5075 ;; Convert inode.
5076 (unless (listp (nth 10 attr))
5077 (setcar (nthcdr 10 attr)
5078 (condition-case nil
5079 (cons (floor (nth 10 attr) 65536)
5080 (floor (mod (nth 10 attr) 65536)))
5081 ;; Inodes can be incredible huge. We must hide this.
5082 (error (tramp-get-inode vec)))))
5083 ;; Set virtual device number.
5084 (setcar (nthcdr 11 attr)
5085 (tramp-get-device vec))
5086 attr))
5087
5088 (defun tramp-shell-case-fold (string)
5089 "Converts STRING to shell glob pattern which ignores case."
5090 (mapconcat
5091 (lambda (c)
5092 (if (equal (downcase c) (upcase c))
5093 (vector c)
5094 (format "[%c%c]" (downcase c) (upcase c))))
5095 string
5096 ""))
5097
5098 (defun tramp-make-copy-program-file-name (vec)
5099 "Create a file name suitable for `scp', `pscp', or `nc' and workalikes."
5100 (let ((method (tramp-file-name-method vec))
5101 (user (tramp-file-name-user vec))
5102 (host (tramp-file-name-real-host vec))
5103 (localname (directory-file-name (tramp-file-name-localname vec))))
5104 (when (string-match tramp-ipv6-regexp host)
5105 (setq host (format "[%s]" host)))
5106 (unless (string-match "ftp$" method)
5107 (setq localname (tramp-shell-quote-argument localname)))
5108 (cond
5109 ((tramp-get-method-parameter vec 'tramp-remote-copy-program)
5110 localname)
5111 ((not (zerop (length user)))
5112 (shell-quote-argument (format "%s@%s:%s" user host localname)))
5113 (t (shell-quote-argument (format "%s:%s" host localname))))))
5114
5115 (defun tramp-method-out-of-band-p (vec size)
5116 "Return t if this is an out-of-band method, nil otherwise."
5117 (and
5118 ;; It shall be an out-of-band method.
5119 (tramp-get-method-parameter vec 'tramp-copy-program)
5120 ;; There must be a size, otherwise the file doesn't exist.
5121 (numberp size)
5122 ;; Either the file size is large enough, or (in rare cases) there
5123 ;; does not exist a remote encoding.
5124 (or (null tramp-copy-size-limit)
5125 (> size tramp-copy-size-limit)
5126 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
5127
5128 ;; Variables local to connection.
5129
5130 (defun tramp-get-remote-path (vec)
5131 (with-tramp-connection-property
5132 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
5133 ;; cache the result for the session only. Otherwise, the result
5134 ;; is cached persistently.
5135 (if (memq 'tramp-own-remote-path tramp-remote-path)
5136 (tramp-get-connection-process vec)
5137 vec)
5138 "remote-path"
5139 (let* ((remote-path (copy-tree tramp-remote-path))
5140 (elt1 (memq 'tramp-default-remote-path remote-path))
5141 (elt2 (memq 'tramp-own-remote-path remote-path))
5142 (default-remote-path
5143 (when elt1
5144 (or
5145 (tramp-send-command-and-read
5146 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
5147 ;; Default if "getconf" is not available.
5148 (progn
5149 (tramp-message
5150 vec 3
5151 "`getconf PATH' not successful, using default value \"%s\"."
5152 "/bin:/usr/bin")
5153 "/bin:/usr/bin"))))
5154 (own-remote-path
5155 ;; The login shell could return more than just the $PATH
5156 ;; string. So we use `tramp-end-of-heredoc' as marker.
5157 (when elt2
5158 (or
5159 (tramp-send-command-and-read
5160 vec
5161 (format
5162 "%s %s %s 'echo %s \\\"$PATH\\\"'"
5163 (tramp-get-method-parameter vec 'tramp-remote-shell)
5164 (mapconcat
5165 'identity
5166 (tramp-get-method-parameter vec 'tramp-remote-shell-login)
5167 " ")
5168 (mapconcat
5169 'identity
5170 (tramp-get-method-parameter vec 'tramp-remote-shell-args)
5171 " ")
5172 (tramp-shell-quote-argument tramp-end-of-heredoc))
5173 'noerror (regexp-quote tramp-end-of-heredoc))
5174 (progn
5175 (tramp-message
5176 vec 2 "Could not retrieve `tramp-own-remote-path'")
5177 nil)))))
5178
5179 ;; Replace place holder `tramp-default-remote-path'.
5180 (when elt1
5181 (setcdr elt1
5182 (append
5183 (split-string (or default-remote-path "") ":" 'omit)
5184 (cdr elt1)))
5185 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
5186
5187 ;; Replace place holder `tramp-own-remote-path'.
5188 (when elt2
5189 (setcdr elt2
5190 (append
5191 (split-string (or own-remote-path "") ":" 'omit)
5192 (cdr elt2)))
5193 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
5194
5195 ;; Remove double entries.
5196 (setq elt1 remote-path)
5197 (while (consp elt1)
5198 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
5199 (setcar elt2 nil))
5200 (setq elt1 (cdr elt1)))
5201
5202 ;; Remove non-existing directories.
5203 (delq
5204 nil
5205 (mapcar
5206 (lambda (x)
5207 (and
5208 (stringp x)
5209 (file-directory-p
5210 (tramp-make-tramp-file-name
5211 (tramp-file-name-method vec)
5212 (tramp-file-name-user vec)
5213 (tramp-file-name-host vec)
5214 x))
5215 x))
5216 remote-path)))))
5217
5218 (defun tramp-get-remote-locale (vec)
5219 (with-tramp-connection-property vec "locale"
5220 (tramp-send-command vec "locale -a")
5221 (let ((candidates '("en_US.utf8" "C.utf8" "en_US.UTF-8"))
5222 locale)
5223 (with-current-buffer (tramp-get-connection-buffer vec)
5224 (while candidates
5225 (goto-char (point-min))
5226 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
5227 (buffer-string))
5228 (setq locale (car candidates)
5229 candidates nil)
5230 (setq candidates (cdr candidates)))))
5231 ;; Return value.
5232 (format "LC_ALL=%s" (or locale "C")))))
5233
5234 (defun tramp-get-ls-command (vec)
5235 (with-tramp-connection-property vec "ls"
5236 (tramp-message vec 5 "Finding a suitable `ls' command")
5237 (or
5238 (catch 'ls-found
5239 (dolist (cmd '("ls" "gnuls" "gls"))
5240 (let ((dl (tramp-get-remote-path vec))
5241 result)
5242 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5243 ;; Check parameters. On busybox, "ls" output coloring is
5244 ;; enabled by default sometimes. So we try to disable it
5245 ;; when possible. $LS_COLORING is not supported there.
5246 ;; Some "ls" versions are sensible wrt the order of
5247 ;; arguments, they fail when "-al" is after the
5248 ;; "--color=never" argument (for example on FreeBSD).
5249 (when (tramp-send-command-and-check
5250 vec (format "%s -lnd /" result))
5251 (when (tramp-send-command-and-check
5252 vec (format
5253 "%s --color=never -al /dev/null" result))
5254 (setq result (concat result " --color=never")))
5255 (throw 'ls-found result))
5256 (setq dl (cdr dl))))))
5257 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
5258
5259 (defun tramp-get-ls-command-with-dired (vec)
5260 (save-match-data
5261 (with-tramp-connection-property vec "ls-dired"
5262 (tramp-message vec 5 "Checking, whether `ls --dired' works")
5263 ;; Some "ls" versions are sensible wrt the order of arguments,
5264 ;; they fail when "-al" is after the "--dired" argument (for
5265 ;; example on FreeBSD).
5266 (tramp-send-command-and-check
5267 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
5268
5269 (defun tramp-get-ls-command-with-quoting-style (vec)
5270 (save-match-data
5271 (with-tramp-connection-property vec "ls-quoting-style"
5272 (tramp-message vec 5 "Checking, whether `ls --quoting-style=shell' works")
5273 (tramp-send-command-and-check
5274 vec (format "%s --quoting-style=shell -al /dev/null"
5275 (tramp-get-ls-command vec))))))
5276
5277 (defun tramp-get-ls-command-with-w-option (vec)
5278 (save-match-data
5279 (with-tramp-connection-property vec "ls-w-option"
5280 (tramp-message vec 5 "Checking, whether `ls -w' works")
5281 ;; Option "-w" is available on BSD systems. No argument is
5282 ;; given, because this could return wrong results in case "ls"
5283 ;; supports the "-w NUM" argument, as for busyboxes.
5284 (tramp-send-command-and-check
5285 vec (format "%s -alw" (tramp-get-ls-command vec))))))
5286
5287 (defun tramp-get-test-command (vec)
5288 (with-tramp-connection-property vec "test"
5289 (tramp-message vec 5 "Finding a suitable `test' command")
5290 (if (tramp-send-command-and-check vec "test 0")
5291 "test"
5292 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
5293
5294 (defun tramp-get-test-nt-command (vec)
5295 ;; Does `test A -nt B' work? Use abominable `find' construct if it
5296 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
5297 ;; for otherwise the shell crashes.
5298 (with-tramp-connection-property vec "test-nt"
5299 (or
5300 (progn
5301 (tramp-send-command
5302 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
5303 (with-current-buffer (tramp-get-buffer vec)
5304 (goto-char (point-min))
5305 (when (looking-at (regexp-quote tramp-end-of-output))
5306 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
5307 (progn
5308 (tramp-send-command
5309 vec
5310 (format
5311 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
5312 (tramp-get-test-command vec)))
5313 "tramp_test_nt %s %s"))))
5314
5315 (defun tramp-get-file-exists-command (vec)
5316 (with-tramp-connection-property vec "file-exists"
5317 (tramp-message vec 5 "Finding command to check if file exists")
5318 (tramp-find-file-exists-command vec)))
5319
5320 (defun tramp-get-remote-ln (vec)
5321 (with-tramp-connection-property vec "ln"
5322 (tramp-message vec 5 "Finding a suitable `ln' command")
5323 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
5324
5325 (defun tramp-get-remote-perl (vec)
5326 (with-tramp-connection-property vec "perl"
5327 (tramp-message vec 5 "Finding a suitable `perl' command")
5328 (let ((result
5329 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
5330 (tramp-find-executable
5331 vec "perl" (tramp-get-remote-path vec)))))
5332 ;; We must check also for some Perl modules.
5333 (when result
5334 (with-tramp-connection-property vec "perl-file-spec"
5335 (tramp-send-command-and-check
5336 vec (format "%s -e 'use File::Spec;'" result)))
5337 (with-tramp-connection-property vec "perl-cwd-realpath"
5338 (tramp-send-command-and-check
5339 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
5340 result)))
5341
5342 (defun tramp-get-remote-stat (vec)
5343 (with-tramp-connection-property vec "stat"
5344 (tramp-message vec 5 "Finding a suitable `stat' command")
5345 (let ((result (tramp-find-executable
5346 vec "stat" (tramp-get-remote-path vec)))
5347 tmp)
5348 ;; Check whether stat(1) returns usable syntax. "%s" does not
5349 ;; work on older AIX systems. Recent GNU stat versions (8.24?)
5350 ;; use shell quoted format for "%N", we check the boundaries "`"
5351 ;; and "'", therefore. See Bug#23422 in coreutils.
5352 (when result
5353 (setq tmp
5354 (tramp-send-command-and-read
5355 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5356 (unless (and (listp tmp) (stringp (car tmp))
5357 (string-match "^`/'$" (car tmp))
5358 (integerp (cadr tmp)))
5359 (setq result nil)))
5360 result)))
5361
5362 (defun tramp-get-remote-readlink (vec)
5363 (with-tramp-connection-property vec "readlink"
5364 (tramp-message vec 5 "Finding a suitable `readlink' command")
5365 (let ((result (tramp-find-executable
5366 vec "readlink" (tramp-get-remote-path vec))))
5367 (when (and result
5368 (tramp-send-command-and-check
5369 vec (format "%s --canonicalize-missing /" result)))
5370 result))))
5371
5372 (defun tramp-get-remote-trash (vec)
5373 (with-tramp-connection-property vec "trash"
5374 (tramp-message vec 5 "Finding a suitable `trash' command")
5375 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5376
5377 (defun tramp-get-remote-touch (vec)
5378 (with-tramp-connection-property vec "touch"
5379 (tramp-message vec 5 "Finding a suitable `touch' command")
5380 (let ((result (tramp-find-executable
5381 vec "touch" (tramp-get-remote-path vec)))
5382 (tmpfile
5383 (make-temp-name
5384 (expand-file-name
5385 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
5386 ;; Busyboxes do support the "-t" option only when they have been
5387 ;; built with the DESKTOP config option. Let's check it.
5388 (when result
5389 (tramp-set-connection-property
5390 vec "touch-t"
5391 (tramp-send-command-and-check
5392 vec
5393 (format
5394 "%s -t %s %s"
5395 result
5396 (format-time-string "%Y%m%d%H%M.%S")
5397 (file-remote-p tmpfile 'localname))))
5398 (delete-file tmpfile))
5399 result)))
5400
5401 (defun tramp-get-remote-gvfs-monitor-dir (vec)
5402 (with-tramp-connection-property vec "gvfs-monitor-dir"
5403 (tramp-message vec 5 "Finding a suitable `gvfs-monitor-dir' command")
5404 (tramp-find-executable
5405 vec "gvfs-monitor-dir" (tramp-get-remote-path vec) t t)))
5406
5407 (defun tramp-get-remote-inotifywait (vec)
5408 (with-tramp-connection-property vec "inotifywait"
5409 (tramp-message vec 5 "Finding a suitable `inotifywait' command")
5410 (tramp-find-executable vec "inotifywait" (tramp-get-remote-path vec) t t)))
5411
5412 (defun tramp-get-remote-id (vec)
5413 (with-tramp-connection-property vec "id"
5414 (tramp-message vec 5 "Finding POSIX `id' command")
5415 (catch 'id-found
5416 (dolist (cmd '("id" "gid"))
5417 (let ((dl (tramp-get-remote-path vec))
5418 result)
5419 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5420 ;; Check POSIX parameter.
5421 (when (tramp-send-command-and-check vec (format "%s -u" result))
5422 (throw 'id-found result))
5423 (setq dl (cdr dl))))))))
5424
5425 (defun tramp-get-remote-uid-with-id (vec id-format)
5426 (tramp-send-command-and-read
5427 vec
5428 (format "%s -u%s %s"
5429 (tramp-get-remote-id vec)
5430 (if (equal id-format 'integer) "" "n")
5431 (if (equal id-format 'integer)
5432 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5433
5434 (defun tramp-get-remote-uid-with-perl (vec id-format)
5435 (tramp-send-command-and-read
5436 vec
5437 (format "%s -le '%s'"
5438 (tramp-get-remote-perl vec)
5439 (if (equal id-format 'integer)
5440 "print $>"
5441 "print \"\\\"\", scalar getpwuid($>), \"\\\"\""))))
5442
5443 (defun tramp-get-remote-python (vec)
5444 (with-tramp-connection-property vec "python"
5445 (tramp-message vec 5 "Finding a suitable `python' command")
5446 (or (tramp-find-executable vec "python" (tramp-get-remote-path vec))
5447 (tramp-find-executable vec "python2" (tramp-get-remote-path vec))
5448 (tramp-find-executable vec "python3" (tramp-get-remote-path vec)))))
5449
5450 (defun tramp-get-remote-uid-with-python (vec id-format)
5451 (tramp-send-command-and-read
5452 vec
5453 (format "%s -c \"%s\""
5454 (tramp-get-remote-python vec)
5455 (if (equal id-format 'integer)
5456 "import os; print (os.getuid())"
5457 "import os, pwd; print ('\\\"' + pwd.getpwuid(os.getuid())[0] + '\\\"')"))))
5458
5459 (defun tramp-get-remote-uid (vec id-format)
5460 (with-tramp-connection-property vec (format "uid-%s" id-format)
5461 (let ((res
5462 (ignore-errors
5463 (cond
5464 ((tramp-get-remote-id vec)
5465 (tramp-get-remote-uid-with-id vec id-format))
5466 ((tramp-get-remote-perl vec)
5467 (tramp-get-remote-uid-with-perl vec id-format))
5468 ((tramp-get-remote-python vec)
5469 (tramp-get-remote-uid-with-python vec id-format))))))
5470 ;; Ensure there is a valid result.
5471 (cond
5472 ((and (equal id-format 'integer) (not (integerp res)))
5473 tramp-unknown-id-integer)
5474 ((and (equal id-format 'string) (not (stringp res)))
5475 tramp-unknown-id-string)
5476 (t res)))))
5477
5478 (defun tramp-get-remote-gid-with-id (vec id-format)
5479 (tramp-send-command-and-read
5480 vec
5481 (format "%s -g%s %s"
5482 (tramp-get-remote-id vec)
5483 (if (equal id-format 'integer) "" "n")
5484 (if (equal id-format 'integer)
5485 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5486
5487 (defun tramp-get-remote-gid-with-perl (vec id-format)
5488 (tramp-send-command-and-read
5489 vec
5490 (format "%s -le '%s'"
5491 (tramp-get-remote-perl vec)
5492 (if (equal id-format 'integer)
5493 "print ($)=~/(\\d+)/)"
5494 "print \"\\\"\", scalar getgrgid($)), \"\\\"\""))))
5495
5496 (defun tramp-get-remote-gid-with-python (vec id-format)
5497 (tramp-send-command-and-read
5498 vec
5499 (format "%s -c \"%s\""
5500 (tramp-get-remote-python vec)
5501 (if (equal id-format 'integer)
5502 "import os; print (os.getgid())"
5503 "import os, grp; print ('\\\"' + grp.getgrgid(os.getgid())[0] + '\\\"')"))))
5504
5505 (defun tramp-get-remote-gid (vec id-format)
5506 (with-tramp-connection-property vec (format "gid-%s" id-format)
5507 (let ((res
5508 (ignore-errors
5509 (cond
5510 ((tramp-get-remote-id vec)
5511 (tramp-get-remote-gid-with-id vec id-format))
5512 ((tramp-get-remote-perl vec)
5513 (tramp-get-remote-gid-with-perl vec id-format))
5514 ((tramp-get-remote-python vec)
5515 (tramp-get-remote-gid-with-python vec id-format))))))
5516 ;; Ensure there is a valid result.
5517 (cond
5518 ((and (equal id-format 'integer) (not (integerp res)))
5519 tramp-unknown-id-integer)
5520 ((and (equal id-format 'string) (not (stringp res)))
5521 tramp-unknown-id-string)
5522 (t res)))))
5523
5524 ;; Some predefined connection properties.
5525 (defun tramp-get-inline-compress (vec prop size)
5526 "Return the compress command related to PROP.
5527 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5528 the length of the file to be compressed.
5529
5530 If no corresponding command is found, nil is returned."
5531 (when (and (integerp tramp-inline-compress-start-size)
5532 (> size tramp-inline-compress-start-size))
5533 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5534 (tramp-find-inline-compress vec)
5535 (tramp-get-connection-property
5536 (tramp-get-connection-process vec) prop nil))))
5537
5538 (defun tramp-get-inline-coding (vec prop size)
5539 "Return the coding command related to PROP.
5540 PROP is either `remote-encoding', `remote-decoding',
5541 `local-encoding' or `local-decoding'.
5542
5543 SIZE is the length of the file to be coded. Depending on SIZE,
5544 compression might be applied.
5545
5546 If no corresponding command is found, nil is returned.
5547 Otherwise, either a string is returned which contains a `%s' mark
5548 to be used for the respective input or output file; or a Lisp
5549 function cell is returned to be applied on a buffer."
5550 ;; We must catch the errors, because we want to return nil, when
5551 ;; no inline coding is found.
5552 (ignore-errors
5553 (let ((coding
5554 (with-tramp-connection-property
5555 (tramp-get-connection-process vec) prop
5556 (tramp-find-inline-encoding vec)
5557 (tramp-get-connection-property
5558 (tramp-get-connection-process vec) prop nil)))
5559 (prop1 (if (string-match "encoding" prop)
5560 "inline-compress" "inline-decompress"))
5561 compress)
5562 ;; The connection property might have been cached. So we must
5563 ;; send the script to the remote side - maybe.
5564 (when (and coding (symbolp coding) (string-match "remote" prop))
5565 (let ((name (symbol-name coding)))
5566 (while (string-match (regexp-quote "-") name)
5567 (setq name (replace-match "_" nil t name)))
5568 (tramp-maybe-send-script vec (symbol-value coding) name)
5569 (setq coding name)))
5570 (when coding
5571 ;; Check for the `compress' command.
5572 (setq compress (tramp-get-inline-compress vec prop1 size))
5573 ;; Return the value.
5574 (cond
5575 ((and compress (symbolp coding))
5576 (if (string-match "decompress" prop1)
5577 `(lambda (beg end)
5578 (,coding beg end)
5579 (let ((coding-system-for-write 'binary)
5580 (coding-system-for-read 'binary))
5581 (apply
5582 'tramp-call-process-region ,vec (point-min) (point-max)
5583 (car (split-string ,compress)) t t nil
5584 (cdr (split-string ,compress)))))
5585 `(lambda (beg end)
5586 (let ((coding-system-for-write 'binary)
5587 (coding-system-for-read 'binary))
5588 (apply
5589 'tramp-call-process-region ,vec beg end
5590 (car (split-string ,compress)) t t nil
5591 (cdr (split-string ,compress))))
5592 (,coding (point-min) (point-max)))))
5593 ((symbolp coding)
5594 coding)
5595 ((and compress (string-match "decoding" prop))
5596 (format
5597 ;; Windows shells need the program file name after
5598 ;; the pipe symbol be quoted if they use forward
5599 ;; slashes as directory separators.
5600 (cond
5601 ((and (string-match "local" prop)
5602 (memq system-type '(windows-nt)))
5603 "(%s | \"%s\")")
5604 ((string-match "local" prop) "(%s | %s)")
5605 (t "(%s | %s >%%s)"))
5606 coding compress))
5607 (compress
5608 (format
5609 ;; Windows shells need the program file name after
5610 ;; the pipe symbol be quoted if they use forward
5611 ;; slashes as directory separators.
5612 (if (and (string-match "local" prop)
5613 (memq system-type '(windows-nt)))
5614 "(%s <%%s | \"%s\")"
5615 "(%s <%%s | %s)")
5616 compress coding))
5617 ((string-match "decoding" prop)
5618 (cond
5619 ((string-match "local" prop) (format "%s" coding))
5620 (t (format "%s >%%s" coding))))
5621 (t
5622 (format "%s <%%s" coding)))))))
5623
5624 (add-hook 'tramp-unload-hook
5625 (lambda ()
5626 (unload-feature 'tramp-sh 'force)))
5627
5628 (provide 'tramp-sh)
5629
5630 ;;; TODO:
5631
5632 ;; * Don't use globbing for directories with many files, as this is
5633 ;; likely to produce long command lines, and some shells choke on
5634 ;; long command lines.
5635 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5636 ;; then look if it's the right version (with `perl -v').
5637 ;; * When editing a remote CVS controlled file as a different user, VC
5638 ;; gets confused about the file locking status. Try to find out why
5639 ;; the workaround doesn't work.
5640 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5641 ;; until the last but one hop via `start-file-process'. Apply it
5642 ;; also for ftp and smb.
5643 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5644 ;; some shell with root privileges, it would be nice if I could
5645 ;; just call
5646 ;; trampclient filename.c
5647 ;; as an editor, and the _current_ shell would connect to an Emacs
5648 ;; server and would be used in an existing non-privileged Emacs
5649 ;; session for doing the editing in question.
5650 ;; That way, I need not tell Emacs my password again and be afraid
5651 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5652 ;; once display a just typed password in the context of a keyboard
5653 ;; sequence prompt for a question immediately following in a shell
5654 ;; script run within Emacs -- nasty).
5655 ;; And if I have some ssh session running to a different computer,
5656 ;; having the possibility of passing a local file there to a local
5657 ;; Emacs session (in case I can arrange for a connection back) would
5658 ;; be nice.
5659 ;; Likely the corresponding Tramp server should not allow the
5660 ;; equivalent of the emacsclient -eval option in order to make this
5661 ;; reasonably unproblematic. And maybe trampclient should have some
5662 ;; way of passing credentials, like by using an SSL socket or
5663 ;; something. (David Kastrup)
5664 ;; * Reconnect directly to a compliant shell without first going
5665 ;; through the user's default shell. (Pete Forman)
5666 ;; * How can I interrupt the remote process with a signal
5667 ;; (interrupt-process seems not to work)? (Markus Triska)
5668 ;; * Avoid the local shell entirely for starting remote processes. If
5669 ;; so, I think even a signal, when delivered directly to the local
5670 ;; SSH instance, would correctly be propagated to the remote process
5671 ;; automatically; possibly SSH would have to be started with
5672 ;; "-t". (Markus Triska)
5673 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5674 ;; isn't on the remote host. (Mark A. Hershberger)
5675 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5676 ;; * Optimize out-of-band copying when both methods are scp-like (not
5677 ;; rsync).
5678 ;; * Keep a second connection open for out-of-band methods like scp or
5679 ;; rsync.
5680
5681 ;;; tramp-sh.el ends here