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