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