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