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