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