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