]> code.delx.au - gnu-emacs/blob - lisp/net/tramp-sh.el
Add "sg" method to Tramp
[gnu-emacs] / lisp / net / tramp-sh.el
1 ;;; tramp-sh.el --- Tramp access functions for (s)sh-like connections
2
3 ;; Copyright (C) 1998-2016 Free Software Foundation, Inc.
4
5 ;; (copyright statements below in code to be updated with the above notice)
6
7 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
8 ;; Michael Albinus <michael.albinus@gmx.de>
9 ;; Keywords: comm, processes
10 ;; Package: tramp
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Code:
28
29 (require 'tramp)
30
31 ;; Pacify byte-compiler.
32 (eval-when-compile
33 (require 'cl)
34 (require 'dired))
35 (defvar tramp-gw-tunnel-method)
36 (defvar tramp-gw-socks-method)
37 (defvar vc-handled-backends)
38 (defvar vc-bzr-program)
39 (defvar vc-git-program)
40 (defvar vc-hg-program)
41
42 ;;;###tramp-autoload
43 (defcustom tramp-inline-compress-start-size 4096
44 "The minimum size of compressing where inline transfer.
45 When inline transfer, compress transferred data of file
46 whose size is this value or above (up to `tramp-copy-size-limit').
47 If it is nil, no compression at all will be applied."
48 :group 'tramp
49 :type '(choice (const nil) integer))
50
51 ;;;###tramp-autoload
52 (defcustom tramp-copy-size-limit 10240
53 "The maximum file size where inline copying is preferred over an \
54 out-of-the-band copy.
55 If it is nil, out-of-the-band copy will be used without a check."
56 :group 'tramp
57 :type '(choice (const nil) integer))
58
59 ;;;###tramp-autoload
60 (defcustom tramp-terminal-type "dumb"
61 "Value of TERM environment variable for logging in to remote host.
62 Because Tramp wants to parse the output of the remote shell, it is easily
63 confused by ANSI color escape sequences and suchlike. Often, shell init
64 files conditionalize this setup based on the TERM environment variable."
65 :group 'tramp
66 :type 'string)
67
68 ;;;###tramp-autoload
69 (defcustom tramp-histfile-override ".tramp_history"
70 "When invoking a shell, override the HISTFILE with this value.
71 When setting to a string, it redirects the shell history to that
72 file. Be careful when setting to \"/dev/null\"; this might
73 result in undesired results when using \"bash\" as shell.
74
75 The value t, the default value, unsets any setting of HISTFILE,
76 and sets both HISTFILESIZE and HISTSIZE to 0. If you set this
77 variable to nil, however, the *override* is disabled, so the
78 history will go to the default storage location,
79 e.g. \"$HOME/.sh_history\"."
80 :group 'tramp
81 :version "25.1"
82 :type '(choice (const :tag "Do not override HISTFILE" nil)
83 (const :tag "Unset HISTFILE" t)
84 (string :tag "Redirect to a file")))
85
86 ;;;###tramp-autoload
87 (defconst tramp-color-escape-sequence-regexp "\e[[;0-9]+m"
88 "Escape sequences produced by the \"ls\" command.")
89
90 ;; ksh on OpenBSD 4.5 requires that $PS1 contains a `#' character for
91 ;; root users. It uses the `$' character for other users. In order
92 ;; to guarantee a proper prompt, we use "#$ " for the prompt.
93
94 (defvar tramp-end-of-output
95 (format
96 "///%s#$"
97 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
98 "String used to recognize end of output.
99 The `$' character at the end is quoted; the string cannot be
100 detected as prompt when being sent on echoing hosts, therefore.")
101
102 ;;;###tramp-autoload
103 (defconst tramp-initial-end-of-output "#$ "
104 "Prompt when establishing a connection.")
105
106 (defconst tramp-end-of-heredoc (md5 tramp-end-of-output)
107 "String used to recognize end of heredoc strings.")
108
109 ;;;###tramp-autoload
110 (defcustom tramp-use-ssh-controlmaster-options t
111 "Whether to use `tramp-ssh-controlmaster-options'."
112 :group 'tramp
113 :version "24.4"
114 :type 'boolean)
115
116 (defvar tramp-ssh-controlmaster-options nil
117 "Which ssh Control* arguments to use.
118
119 If it is a string, it should have the form
120 \"-o ControlMaster=auto -o ControlPath='tramp.%%r@%%h:%%p'
121 -o ControlPersist=no\". Percent characters in the ControlPath
122 spec must be doubled, because the string is used as format string.
123
124 Otherwise, it will be auto-detected by Tramp, if
125 `tramp-use-ssh-controlmaster-options' is non-nil. The value
126 depends on the installed local ssh version.
127
128 The string is used in `tramp-methods'.")
129
130 ;; Initialize `tramp-methods' with the supported methods.
131 ;;;###tramp-autoload
132 (add-to-list 'tramp-methods
133 '("rcp"
134 (tramp-login-program "rsh")
135 (tramp-login-args (("%h") ("-l" "%u")))
136 (tramp-remote-shell "/bin/sh")
137 (tramp-remote-shell-login ("-l"))
138 (tramp-remote-shell-args ("-c"))
139 (tramp-copy-program "rcp")
140 (tramp-copy-args (("-p" "%k") ("-r")))
141 (tramp-copy-keep-date t)
142 (tramp-copy-recursive t)))
143 ;;;###tramp-autoload
144 (add-to-list 'tramp-methods
145 '("remcp"
146 (tramp-login-program "remsh")
147 (tramp-login-args (("%h") ("-l" "%u")))
148 (tramp-remote-shell "/bin/sh")
149 (tramp-remote-shell-login ("-l"))
150 (tramp-remote-shell-args ("-c"))
151 (tramp-copy-program "rcp")
152 (tramp-copy-args (("-p" "%k")))
153 (tramp-copy-keep-date t)))
154 ;;;###tramp-autoload
155 (add-to-list 'tramp-methods
156 '("scp"
157 (tramp-login-program "ssh")
158 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
159 ("-e" "none") ("%h")))
160 (tramp-async-args (("-q")))
161 (tramp-remote-shell "/bin/sh")
162 (tramp-remote-shell-login ("-l"))
163 (tramp-remote-shell-args ("-c"))
164 (tramp-copy-program "scp")
165 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q") ("-r") ("%c")))
166 (tramp-copy-keep-date t)
167 (tramp-copy-recursive t)
168 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
169 ("-o" "UserKnownHostsFile=/dev/null")
170 ("-o" "StrictHostKeyChecking=no")))
171 (tramp-default-port 22)))
172 ;;;###tramp-autoload
173 (add-to-list 'tramp-methods
174 '("scpx"
175 (tramp-login-program "ssh")
176 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
177 ("-e" "none") ("-t" "-t") ("%h") ("/bin/sh")))
178 (tramp-async-args (("-q")))
179 (tramp-remote-shell "/bin/sh")
180 (tramp-remote-shell-login ("-l"))
181 (tramp-remote-shell-args ("-c"))
182 (tramp-copy-program "scp")
183 (tramp-copy-args (("-P" "%p") ("-p" "%k")
184 ("-q") ("-r") ("%c")))
185 (tramp-copy-keep-date t)
186 (tramp-copy-recursive t)
187 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
188 ("-o" "UserKnownHostsFile=/dev/null")
189 ("-o" "StrictHostKeyChecking=no")))
190 (tramp-default-port 22)))
191 ;;;###tramp-autoload
192 (add-to-list 'tramp-methods
193 '("rsync"
194 (tramp-login-program "ssh")
195 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
196 ("-e" "none") ("%h")))
197 (tramp-async-args (("-q")))
198 (tramp-remote-shell "/bin/sh")
199 (tramp-remote-shell-login ("-l"))
200 (tramp-remote-shell-args ("-c"))
201 (tramp-copy-program "rsync")
202 (tramp-copy-args (("-t" "%k") ("-r")))
203 (tramp-copy-env (("RSYNC_RSH") ("ssh" "%c")))
204 (tramp-copy-keep-date t)
205 (tramp-copy-keep-tmpfile t)
206 (tramp-copy-recursive t)))
207 ;;;###tramp-autoload
208 (add-to-list 'tramp-methods
209 '("rsh"
210 (tramp-login-program "rsh")
211 (tramp-login-args (("%h") ("-l" "%u")))
212 (tramp-remote-shell "/bin/sh")
213 (tramp-remote-shell-login ("-l"))
214 (tramp-remote-shell-args ("-c"))))
215 ;;;###tramp-autoload
216 (add-to-list 'tramp-methods
217 '("remsh"
218 (tramp-login-program "remsh")
219 (tramp-login-args (("%h") ("-l" "%u")))
220 (tramp-remote-shell "/bin/sh")
221 (tramp-remote-shell-login ("-l"))
222 (tramp-remote-shell-args ("-c"))))
223 ;;;###tramp-autoload
224 (add-to-list 'tramp-methods
225 '("ssh"
226 (tramp-login-program "ssh")
227 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
228 ("-e" "none") ("%h")))
229 (tramp-async-args (("-q")))
230 (tramp-remote-shell "/bin/sh")
231 (tramp-remote-shell-login ("-l"))
232 (tramp-remote-shell-args ("-c"))
233 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
234 ("-o" "UserKnownHostsFile=/dev/null")
235 ("-o" "StrictHostKeyChecking=no")))
236 (tramp-default-port 22)))
237 ;;;###tramp-autoload
238 (add-to-list 'tramp-methods
239 '("sshx"
240 (tramp-login-program "ssh")
241 (tramp-login-args (("-l" "%u") ("-p" "%p") ("%c")
242 ("-e" "none") ("-t" "-t") ("%h") ("/bin/sh")))
243 (tramp-async-args (("-q")))
244 (tramp-remote-shell "/bin/sh")
245 (tramp-remote-shell-login ("-l"))
246 (tramp-remote-shell-args ("-c"))
247 (tramp-gw-args (("-o" "GlobalKnownHostsFile=/dev/null")
248 ("-o" "UserKnownHostsFile=/dev/null")
249 ("-o" "StrictHostKeyChecking=no")))
250 (tramp-default-port 22)))
251 ;;;###tramp-autoload
252 (add-to-list 'tramp-methods
253 '("telnet"
254 (tramp-login-program "telnet")
255 (tramp-login-args (("%h") ("%p") ("2>/dev/null")))
256 (tramp-remote-shell "/bin/sh")
257 (tramp-remote-shell-login ("-l"))
258 (tramp-remote-shell-args ("-c"))
259 (tramp-default-port 23)))
260 ;;;###tramp-autoload
261 (add-to-list 'tramp-methods
262 '("nc"
263 (tramp-login-program "telnet")
264 (tramp-login-args (("%h") ("%p") ("2>/dev/null")))
265 (tramp-remote-shell "/bin/sh")
266 (tramp-remote-shell-login ("-l"))
267 (tramp-remote-shell-args ("-c"))
268 (tramp-copy-program "nc")
269 ;; We use "-v" for better error tracking.
270 (tramp-copy-args (("-w" "1") ("-v") ("%h") ("%r")))
271 (tramp-remote-copy-program "nc")
272 ;; We use "-p" as required for newer busyboxes. For older
273 ;; busybox/nc versions, the value must be (("-l") ("%r")). This
274 ;; can be achieved by tweaking `tramp-connection-properties'.
275 (tramp-remote-copy-args (("-l") ("-p" "%r") ("2>/dev/null")))
276 (tramp-default-port 23)))
277 ;;;###tramp-autoload
278 (add-to-list 'tramp-methods
279 '("su"
280 (tramp-login-program "su")
281 (tramp-login-args (("-") ("%u")))
282 (tramp-remote-shell "/bin/sh")
283 (tramp-remote-shell-login ("-l"))
284 (tramp-remote-shell-args ("-c"))
285 (tramp-connection-timeout 10)))
286 ;;;###tramp-autoload
287 (add-to-list
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): /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' 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 NAME is not a Tramp file, run the real handler.
2864 (if (not (tramp-connectable-p name))
2865 (tramp-run-real-handler 'expand-file-name (list name nil))
2866 ;; Dissect NAME.
2867 (with-parsed-tramp-file-name name nil
2868 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
2869 (setq localname (concat "~/" localname)))
2870 ;; Tilde expansion if necessary. This needs a shell which
2871 ;; groks tilde expansion! The function `tramp-find-shell' is
2872 ;; supposed to find such a shell on the remote host. Please
2873 ;; tell me about it when this doesn't work on your system.
2874 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
2875 (let ((uname (match-string 1 localname))
2876 (fname (match-string 2 localname)))
2877 ;; We cannot simply apply "~/", because under sudo "~/" is
2878 ;; expanded to the local user home directory but to the
2879 ;; root home directory. On the other hand, using always
2880 ;; the default user name for tilde expansion is not
2881 ;; appropriate either, because ssh and companions might
2882 ;; use a user name from the config file.
2883 (when (and (string-equal uname "~")
2884 (string-match "\\`su\\(do\\)?\\'" method))
2885 (setq uname (concat uname user)))
2886 (setq uname
2887 (with-tramp-connection-property v uname
2888 (tramp-send-command
2889 v (format "cd %s && pwd" (tramp-shell-quote-argument uname)))
2890 (with-current-buffer (tramp-get-buffer v)
2891 (goto-char (point-min))
2892 (buffer-substring (point) (point-at-eol)))))
2893 (setq localname (concat uname fname))))
2894 ;; There might be a double slash, for example when "~/"
2895 ;; expands to "/". Remove this.
2896 (while (string-match "//" localname)
2897 (setq localname (replace-match "/" t t localname)))
2898 ;; No tilde characters in file name, do normal
2899 ;; `expand-file-name' (this does "/./" and "/../").
2900 ;; `default-directory' is bound, because on Windows there would
2901 ;; be problems with UNC shares or Cygwin mounts.
2902 (let ((default-directory (tramp-compat-temporary-file-directory)))
2903 (tramp-make-tramp-file-name
2904 method user host
2905 (tramp-drop-volume-letter
2906 (tramp-run-real-handler
2907 'expand-file-name (list localname)))
2908 hop)))))
2909
2910 ;;; Remote commands:
2911
2912 (defun tramp-process-sentinel (proc event)
2913 "Flush file caches."
2914 (unless (memq (process-status proc) '(run open))
2915 (let ((vec (tramp-get-connection-property proc "vector" nil)))
2916 (when vec
2917 (tramp-message vec 5 "Sentinel called: `%S' `%s'" proc event)
2918 (tramp-flush-connection-property proc)
2919 (tramp-flush-directory-property vec "")))))
2920
2921 ;; We use BUFFER also as connection buffer during setup. Because of
2922 ;; this, its original contents must be saved, and restored once
2923 ;; connection has been setup.
2924 (defun tramp-sh-handle-start-file-process (name buffer program &rest args)
2925 "Like `start-file-process' for Tramp files."
2926 (with-parsed-tramp-file-name (expand-file-name default-directory) nil
2927 (let* (;; When PROGRAM matches "*sh", and the first arg is "-c",
2928 ;; it might be that the arguments exceed the command line
2929 ;; length. Therefore, we modify the command.
2930 (heredoc (and (stringp program)
2931 (string-match "sh$" program)
2932 (string-equal "-c" (car args))
2933 (= (length args) 2)))
2934 ;; When PROGRAM is nil, we just provide a tty.
2935 (args (if (not heredoc) args
2936 (let ((i 250))
2937 (while (and (< i (length (cadr args)))
2938 (string-match " " (cadr args) i))
2939 (setcdr
2940 args
2941 (list (replace-match " \\\\\n" nil nil (cadr args))))
2942 (setq i (+ i 250))))
2943 (cdr args)))
2944 ;; Use a human-friendly prompt, for example for `shell'.
2945 ;; We discard hops, if existing, that's why we cannot use
2946 ;; `file-remote-p'.
2947 (prompt (format "PS1=%s %s"
2948 (tramp-make-tramp-file-name
2949 (tramp-file-name-method v)
2950 (tramp-file-name-user v)
2951 (tramp-file-name-host v)
2952 (tramp-file-name-localname v))
2953 tramp-initial-end-of-output))
2954 ;; We use as environment the difference to toplevel
2955 ;; `process-environment'.
2956 env
2957 (env
2958 (dolist
2959 (elt
2960 (cons prompt (nreverse (copy-sequence process-environment)))
2961 env)
2962 (or (member elt (default-toplevel-value 'process-environment))
2963 (setq env (cons elt env)))))
2964 (command
2965 (when (stringp program)
2966 (format "cd %s && exec %s env %s %s"
2967 (tramp-shell-quote-argument localname)
2968 (if heredoc (format "<<'%s'" tramp-end-of-heredoc) "")
2969 (mapconcat 'tramp-shell-quote-argument env " ")
2970 (if heredoc
2971 (format "%s\n(\n%s\n) </dev/tty\n%s"
2972 program (car args) tramp-end-of-heredoc)
2973 (mapconcat 'tramp-shell-quote-argument
2974 (cons program args) " ")))))
2975 (tramp-process-connection-type
2976 (or (null program) tramp-process-connection-type))
2977 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
2978 (name1 name)
2979 (i 0)
2980 ;; We do not want to raise an error when
2981 ;; `start-file-process' has been started several times in
2982 ;; `eshell' and friends.
2983 (tramp-current-connection nil))
2984
2985 (unless buffer
2986 ;; BUFFER can be nil. We use a temporary buffer.
2987 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
2988 (while (get-process name1)
2989 ;; NAME must be unique as process name.
2990 (setq i (1+ i)
2991 name1 (format "%s<%d>" name i)))
2992 (setq name name1)
2993 ;; Set the new process properties.
2994 (tramp-set-connection-property v "process-name" name)
2995 (tramp-set-connection-property v "process-buffer" buffer)
2996
2997 (with-current-buffer (tramp-get-connection-buffer v)
2998 (unwind-protect
2999 ;; We catch this event. Otherwise, `start-process' could
3000 ;; be called on the local host.
3001 (save-excursion
3002 (save-restriction
3003 ;; Activate narrowing in order to save BUFFER
3004 ;; contents. Clear also the modification time;
3005 ;; otherwise we might be interrupted by
3006 ;; `verify-visited-file-modtime'.
3007 (let ((buffer-undo-list t)
3008 (buffer-read-only nil)
3009 (mark (point-max)))
3010 (clear-visited-file-modtime)
3011 (narrow-to-region (point-max) (point-max))
3012 ;; We call `tramp-maybe-open-connection', in order
3013 ;; to cleanup the prompt afterwards.
3014 (catch 'suppress
3015 (tramp-maybe-open-connection v)
3016 (widen)
3017 (delete-region mark (point))
3018 (narrow-to-region (point-max) (point-max))
3019 ;; Now do it.
3020 (if command
3021 ;; Send the command.
3022 (tramp-send-command v command nil t) ; nooutput
3023 ;; Check, whether a pty is associated.
3024 (unless (process-get
3025 (tramp-get-connection-process v) 'remote-tty)
3026 (tramp-error
3027 v 'file-error
3028 "pty association is not supported for `%s'" name))))
3029 (let ((p (tramp-get-connection-process v)))
3030 ;; Set query flag and process marker for this
3031 ;; process. We ignore errors, because the process
3032 ;; could have finished already.
3033 (ignore-errors
3034 (set-process-query-on-exit-flag p t)
3035 (set-marker (process-mark p) (point)))
3036 ;; Return process.
3037 p))))
3038
3039 ;; Save exit.
3040 (if (string-match tramp-temp-buffer-name (buffer-name))
3041 (ignore-errors
3042 (set-process-buffer (tramp-get-connection-process v) nil)
3043 (kill-buffer (current-buffer)))
3044 (set-buffer-modified-p bmp))
3045 (tramp-set-connection-property v "process-name" nil)
3046 (tramp-set-connection-property v "process-buffer" nil))))))
3047
3048 (defun tramp-sh-handle-process-file
3049 (program &optional infile destination display &rest args)
3050 "Like `process-file' for Tramp files."
3051 ;; The implementation is not complete yet.
3052 (when (and (numberp destination) (zerop destination))
3053 (error "Implementation does not handle immediate return"))
3054
3055 (with-parsed-tramp-file-name default-directory nil
3056 (let (command env input tmpinput stderr tmpstderr outbuf ret)
3057 ;; Compute command.
3058 (setq command (mapconcat 'tramp-shell-quote-argument
3059 (cons program args) " "))
3060 ;; We use as environment the difference to toplevel `process-environment'.
3061 (setq env
3062 (dolist (elt (nreverse (copy-sequence process-environment)) env)
3063 (or (member elt (default-toplevel-value 'process-environment))
3064 (setq env (cons elt env)))))
3065 (when env
3066 (setq command
3067 (format
3068 "env %s %s"
3069 (mapconcat 'tramp-shell-quote-argument env " ") command)))
3070 ;; Determine input.
3071 (if (null infile)
3072 (setq input "/dev/null")
3073 (setq infile (expand-file-name infile))
3074 (if (tramp-equal-remote default-directory infile)
3075 ;; INFILE is on the same remote host.
3076 (setq input (with-parsed-tramp-file-name infile nil localname))
3077 ;; INFILE must be copied to remote host.
3078 (setq input (tramp-make-tramp-temp-file v)
3079 tmpinput (tramp-make-tramp-file-name method user host input))
3080 (copy-file infile tmpinput t)))
3081 (when input (setq command (format "%s <%s" command input)))
3082
3083 ;; Determine output.
3084 (cond
3085 ;; Just a buffer.
3086 ((bufferp destination)
3087 (setq outbuf destination))
3088 ;; A buffer name.
3089 ((stringp destination)
3090 (setq outbuf (get-buffer-create destination)))
3091 ;; (REAL-DESTINATION ERROR-DESTINATION)
3092 ((consp destination)
3093 ;; output.
3094 (cond
3095 ((bufferp (car destination))
3096 (setq outbuf (car destination)))
3097 ((stringp (car destination))
3098 (setq outbuf (get-buffer-create (car destination))))
3099 ((car destination)
3100 (setq outbuf (current-buffer))))
3101 ;; stderr.
3102 (cond
3103 ((stringp (cadr destination))
3104 (setcar (cdr destination) (expand-file-name (cadr destination)))
3105 (if (tramp-equal-remote default-directory (cadr destination))
3106 ;; stderr is on the same remote host.
3107 (setq stderr (with-parsed-tramp-file-name
3108 (cadr destination) nil localname))
3109 ;; stderr must be copied to remote host. The temporary
3110 ;; file must be deleted after execution.
3111 (setq stderr (tramp-make-tramp-temp-file v)
3112 tmpstderr (tramp-make-tramp-file-name
3113 method user host stderr))))
3114 ;; stderr to be discarded.
3115 ((null (cadr destination))
3116 (setq stderr "/dev/null"))))
3117 ;; 't
3118 (destination
3119 (setq outbuf (current-buffer))))
3120 (when stderr (setq command (format "%s 2>%s" command stderr)))
3121
3122 ;; Send the command. It might not return in time, so we protect
3123 ;; it. Call it in a subshell, in order to preserve working
3124 ;; directory.
3125 (condition-case nil
3126 (unwind-protect
3127 (setq ret
3128 (if (tramp-send-command-and-check
3129 v (format "cd %s && %s"
3130 (tramp-shell-quote-argument localname)
3131 command)
3132 t t)
3133 0 1))
3134 ;; We should add the output anyway.
3135 (when outbuf
3136 (with-current-buffer outbuf
3137 (insert
3138 (with-current-buffer (tramp-get-connection-buffer v)
3139 (buffer-string))))
3140 (when (and display (get-buffer-window outbuf t)) (redisplay))))
3141 ;; When the user did interrupt, we should do it also. We use
3142 ;; return code -1 as marker.
3143 (quit
3144 (kill-buffer (tramp-get-connection-buffer v))
3145 (setq ret -1))
3146 ;; Handle errors.
3147 (error
3148 (kill-buffer (tramp-get-connection-buffer v))
3149 (setq ret 1)))
3150
3151 ;; Provide error file.
3152 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3153
3154 ;; Cleanup. We remove all file cache values for the connection,
3155 ;; because the remote process could have changed them.
3156 (when tmpinput (delete-file tmpinput))
3157
3158 (unless process-file-side-effects
3159 (tramp-flush-directory-property v ""))
3160
3161 ;; Return exit status.
3162 (if (equal ret -1)
3163 (keyboard-quit)
3164 ret))))
3165
3166 (defun tramp-sh-handle-file-local-copy (filename)
3167 "Like `file-local-copy' for Tramp files."
3168 (with-parsed-tramp-file-name filename nil
3169 (unless (file-exists-p filename)
3170 (tramp-error
3171 v 'file-error
3172 "Cannot make local copy of non-existing file `%s'" filename))
3173
3174 (let* ((size (nth 7 (file-attributes (file-truename filename))))
3175 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
3176 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
3177 (tmpfile (tramp-compat-make-temp-file filename)))
3178
3179 (condition-case err
3180 (cond
3181 ;; `copy-file' handles direct copy and out-of-band methods.
3182 ((or (tramp-local-host-p v)
3183 (tramp-method-out-of-band-p v size))
3184 (copy-file filename tmpfile 'ok-if-already-exists 'keep-time))
3185
3186 ;; Use inline encoding for file transfer.
3187 (rem-enc
3188 (save-excursion
3189 (with-tramp-progress-reporter
3190 v 3
3191 (format-message "Encoding remote file `%s' with `%s'"
3192 filename rem-enc)
3193 (tramp-barf-unless-okay
3194 v (format rem-enc (tramp-shell-quote-argument localname))
3195 "Encoding remote file failed"))
3196
3197 (with-tramp-progress-reporter
3198 v 3 (format-message "Decoding local file `%s' with `%s'"
3199 tmpfile loc-dec)
3200 (if (functionp loc-dec)
3201 ;; If local decoding is a function, we call it.
3202 ;; We must disable multibyte, because
3203 ;; `uudecode-decode-region' doesn't handle it
3204 ;; correctly. Unset `file-name-handler-alist'.
3205 ;; Otherwise, epa-file gets confused.
3206 (let (file-name-handler-alist
3207 (coding-system-for-write 'binary))
3208 (with-temp-file tmpfile
3209 (set-buffer-multibyte nil)
3210 (insert-buffer-substring (tramp-get-buffer v))
3211 (funcall loc-dec (point-min) (point-max))))
3212
3213 ;; If tramp-decoding-function is not defined for this
3214 ;; method, we invoke tramp-decoding-command instead.
3215 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3216 ;; Unset `file-name-handler-alist'. Otherwise,
3217 ;; epa-file gets confused.
3218 (let (file-name-handler-alist
3219 (coding-system-for-write 'binary))
3220 (with-current-buffer (tramp-get-buffer v)
3221 (write-region
3222 (point-min) (point-max) tmpfile2 nil 'no-message)))
3223 (unwind-protect
3224 (tramp-call-local-coding-command
3225 loc-dec tmpfile2 tmpfile)
3226 (delete-file tmpfile2)))))
3227
3228 ;; Set proper permissions.
3229 (set-file-modes tmpfile (tramp-default-file-modes filename))
3230 ;; Set local user ownership.
3231 (tramp-set-file-uid-gid tmpfile)))
3232
3233 ;; Oops, I don't know what to do.
3234 (t (tramp-error
3235 v 'file-error "Wrong method specification for `%s'" method)))
3236
3237 ;; Error handling.
3238 ((error quit)
3239 (delete-file tmpfile)
3240 (signal (car err) (cdr err))))
3241
3242 (run-hooks 'tramp-handle-file-local-copy-hook)
3243 tmpfile)))
3244
3245 ;; CCC grok LOCKNAME
3246 (defun tramp-sh-handle-write-region
3247 (start end filename &optional append visit lockname confirm)
3248 "Like `write-region' for Tramp files."
3249 (setq filename (expand-file-name filename))
3250 (with-parsed-tramp-file-name filename nil
3251 ;; Following part commented out because we don't know what to do about
3252 ;; file locking, and it does not appear to be a problem to ignore it.
3253 ;; Ange-ftp ignores it, too.
3254 ;; (when (and lockname (stringp lockname))
3255 ;; (setq lockname (expand-file-name lockname)))
3256 ;; (unless (or (eq lockname nil)
3257 ;; (string= lockname filename))
3258 ;; (error
3259 ;; "tramp-sh-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
3260
3261 (when (and confirm (file-exists-p filename))
3262 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
3263 (tramp-error v 'file-error "File not overwritten")))
3264
3265 (let ((uid (or (nth 2 (file-attributes filename 'integer))
3266 (tramp-get-remote-uid v 'integer)))
3267 (gid (or (nth 3 (file-attributes filename 'integer))
3268 (tramp-get-remote-gid v 'integer))))
3269
3270 (if (and (tramp-local-host-p v)
3271 ;; `file-writable-p' calls `file-expand-file-name'. We
3272 ;; cannot use `tramp-run-real-handler' therefore.
3273 (let (file-name-handler-alist)
3274 (and
3275 (file-writable-p (file-name-directory localname))
3276 (or (file-directory-p localname)
3277 (file-writable-p localname)))))
3278 ;; Short track: if we are on the local host, we can run directly.
3279 (tramp-run-real-handler
3280 'write-region
3281 (list start end localname append 'no-message lockname confirm))
3282
3283 (let* ((modes (save-excursion (tramp-default-file-modes filename)))
3284 ;; We use this to save the value of
3285 ;; `last-coding-system-used' after writing the tmp
3286 ;; file. At the end of the function, we set
3287 ;; `last-coding-system-used' to this saved value. This
3288 ;; way, any intermediary coding systems used while
3289 ;; talking to the remote shell or suchlike won't hose
3290 ;; this variable. This approach was snarfed from
3291 ;; ange-ftp.el.
3292 coding-system-used
3293 ;; Write region into a tmp file. This isn't really
3294 ;; needed if we use an encoding function, but currently
3295 ;; we use it always because this makes the logic
3296 ;; simpler. We must also set `temporary-file-directory',
3297 ;; because it could point to a remote directory.
3298 (temporary-file-directory
3299 (tramp-compat-temporary-file-directory))
3300 (tmpfile (or tramp-temp-buffer-file-name
3301 (tramp-compat-make-temp-file filename))))
3302
3303 ;; If `append' is non-nil, we copy the file locally, and let
3304 ;; the native `write-region' implementation do the job.
3305 (when append (copy-file filename tmpfile 'ok))
3306
3307 ;; We say `no-message' here because we don't want the
3308 ;; visited file modtime data to be clobbered from the temp
3309 ;; file. We call `set-visited-file-modtime' ourselves later
3310 ;; on. We must ensure that `file-coding-system-alist'
3311 ;; matches `tmpfile'.
3312 (let (file-name-handler-alist
3313 (file-coding-system-alist
3314 (tramp-find-file-name-coding-system-alist filename tmpfile)))
3315 (condition-case err
3316 (tramp-run-real-handler
3317 'write-region
3318 (list start end tmpfile append 'no-message lockname confirm))
3319 ((error quit)
3320 (setq tramp-temp-buffer-file-name nil)
3321 (delete-file tmpfile)
3322 (signal (car err) (cdr err))))
3323
3324 ;; Now, `last-coding-system-used' has the right value. Remember it.
3325 (setq coding-system-used last-coding-system-used))
3326
3327 ;; The permissions of the temporary file should be set. If
3328 ;; FILENAME does not exist (eq modes nil) it has been
3329 ;; renamed to the backup file. This case `save-buffer'
3330 ;; handles permissions.
3331 ;; Ensure that it is still readable.
3332 (when modes
3333 (set-file-modes
3334 tmpfile
3335 (logior (or modes 0) (string-to-number "0400" 8))))
3336
3337 ;; This is a bit lengthy due to the different methods
3338 ;; possible for file transfer. First, we check whether the
3339 ;; method uses an scp program. If so, we call it.
3340 ;; Otherwise, both encoding and decoding command must be
3341 ;; specified. However, if the method _also_ specifies an
3342 ;; encoding function, then that is used for encoding the
3343 ;; contents of the tmp file.
3344 (let* ((size (nth 7 (file-attributes tmpfile)))
3345 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
3346 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
3347 (cond
3348 ;; `copy-file' handles direct copy and out-of-band methods.
3349 ((or (tramp-local-host-p v)
3350 (tramp-method-out-of-band-p v size))
3351 (if (and (not (stringp start))
3352 (= (or end (point-max)) (point-max))
3353 (= (or start (point-min)) (point-min))
3354 (tramp-get-method-parameter v 'tramp-copy-keep-tmpfile))
3355 (progn
3356 (setq tramp-temp-buffer-file-name tmpfile)
3357 (condition-case err
3358 ;; We keep the local file for performance
3359 ;; reasons, useful for "rsync".
3360 (copy-file tmpfile filename t)
3361 ((error quit)
3362 (setq tramp-temp-buffer-file-name nil)
3363 (delete-file tmpfile)
3364 (signal (car err) (cdr err)))))
3365 (setq tramp-temp-buffer-file-name nil)
3366 ;; Don't rename, in order to keep context in SELinux.
3367 (unwind-protect
3368 (copy-file tmpfile filename t)
3369 (delete-file tmpfile))))
3370
3371 ;; Use inline file transfer.
3372 (rem-dec
3373 ;; Encode tmpfile.
3374 (unwind-protect
3375 (with-temp-buffer
3376 (set-buffer-multibyte nil)
3377 ;; Use encoding function or command.
3378 (with-tramp-progress-reporter
3379 v 3 (format-message
3380 "Encoding local file `%s' using `%s'"
3381 tmpfile loc-enc)
3382 (if (functionp loc-enc)
3383 ;; The following `let' is a workaround for
3384 ;; the base64.el that comes with pgnus-0.84.
3385 ;; If both of the following conditions are
3386 ;; satisfied, it tries to write to a local
3387 ;; file in default-directory, but at this
3388 ;; point, default-directory is remote.
3389 ;; (`call-process-region' can't write to
3390 ;; remote files, it seems.) The file in
3391 ;; question is a tmp file anyway.
3392 (let ((coding-system-for-read 'binary)
3393 (default-directory
3394 (tramp-compat-temporary-file-directory)))
3395 (insert-file-contents-literally tmpfile)
3396 (funcall loc-enc (point-min) (point-max)))
3397
3398 (unless (zerop (tramp-call-local-coding-command
3399 loc-enc tmpfile t))
3400 (tramp-error
3401 v 'file-error
3402 (concat "Cannot write to `%s', "
3403 "local encoding command `%s' failed")
3404 filename loc-enc))))
3405
3406 ;; Send buffer into remote decoding command which
3407 ;; writes to remote file. Because this happens on
3408 ;; the remote host, we cannot use the function.
3409 (with-tramp-progress-reporter
3410 v 3 (format-message
3411 "Decoding remote file `%s' using `%s'"
3412 filename rem-dec)
3413 (goto-char (point-max))
3414 (unless (bolp) (newline))
3415 (tramp-send-command
3416 v
3417 (format
3418 (concat rem-dec " <<'%s'\n%s%s")
3419 (tramp-shell-quote-argument localname)
3420 tramp-end-of-heredoc
3421 (buffer-string)
3422 tramp-end-of-heredoc))
3423 (tramp-barf-unless-okay
3424 v nil
3425 "Couldn't write region to `%s', decode using `%s' failed"
3426 filename rem-dec)
3427 ;; When `file-precious-flag' is set, the region is
3428 ;; written to a temporary file. Check that the
3429 ;; checksum is equal to that from the local tmpfile.
3430 (when file-precious-flag
3431 (erase-buffer)
3432 (and
3433 ;; cksum runs locally, if possible.
3434 (zerop (tramp-call-process v "cksum" tmpfile t))
3435 ;; cksum runs remotely.
3436 (tramp-send-command-and-check
3437 v
3438 (format
3439 "cksum <%s" (tramp-shell-quote-argument localname)))
3440 ;; ... they are different.
3441 (not
3442 (string-equal
3443 (buffer-string)
3444 (with-current-buffer (tramp-get-buffer v)
3445 (buffer-string))))
3446 (tramp-error
3447 v 'file-error
3448 (concat "Couldn't write region to `%s',"
3449 " decode using `%s' failed")
3450 filename rem-dec)))))
3451
3452 ;; Save exit.
3453 (delete-file tmpfile)))
3454
3455 ;; That's not expected.
3456 (t
3457 (tramp-error
3458 v 'file-error
3459 (concat "Method `%s' should specify both encoding and "
3460 "decoding command or an scp program")
3461 method))))
3462
3463 ;; Make `last-coding-system-used' have the right value.
3464 (when coding-system-used
3465 (set 'last-coding-system-used coding-system-used))))
3466
3467 (tramp-flush-file-property v (file-name-directory localname))
3468 (tramp-flush-file-property v localname)
3469
3470 ;; We must protect `last-coding-system-used', now we have set it
3471 ;; to its correct value.
3472 (let (last-coding-system-used (need-chown t))
3473 ;; Set file modification time.
3474 (when (or (eq visit t) (stringp visit))
3475 (let ((file-attr (file-attributes filename 'integer)))
3476 (set-visited-file-modtime
3477 ;; We must pass modtime explicitly, because FILENAME can
3478 ;; be different from (buffer-file-name), f.e. if
3479 ;; `file-precious-flag' is set.
3480 (nth 5 file-attr))
3481 (when (and (= (nth 2 file-attr) uid)
3482 (= (nth 3 file-attr) gid))
3483 (setq need-chown nil))))
3484
3485 ;; Set the ownership.
3486 (when need-chown
3487 (tramp-set-file-uid-gid filename uid gid))
3488 (when (or (eq visit t) (null visit) (stringp visit))
3489 (tramp-message v 0 "Wrote %s" filename))
3490 (run-hooks 'tramp-handle-write-region-hook)))))
3491
3492 (defvar tramp-vc-registered-file-names nil
3493 "List used to collect file names, which are checked during `vc-registered'.")
3494
3495 ;; VC backends check for the existence of various different special
3496 ;; files. This is very time consuming, because every single check
3497 ;; requires a remote command (the file cache must be invalidated).
3498 ;; Therefore, we apply a kind of optimization. We install the file
3499 ;; name handler `tramp-vc-file-name-handler', which does nothing but
3500 ;; remembers all file names for which `file-exists-p' or
3501 ;; `file-readable-p' has been applied. A first run of `vc-registered'
3502 ;; is performed. Afterwards, a script is applied for all collected
3503 ;; file names, using just one remote command. The result of this
3504 ;; script is used to fill the file cache with actual values. Now we
3505 ;; can reset the file name handlers, and we make a second run of
3506 ;; `vc-registered', which returns the expected result without sending
3507 ;; any other remote command.
3508 (defun tramp-sh-handle-vc-registered (file)
3509 "Like `vc-registered' for Tramp files."
3510 (with-temp-message ""
3511 (with-parsed-tramp-file-name file nil
3512 (with-tramp-progress-reporter
3513 v 3 (format-message "Checking `vc-registered' for %s" file)
3514
3515 ;; There could be new files, created by the vc backend. We
3516 ;; cannot reuse the old cache entries, therefore. In
3517 ;; `tramp-get-file-property', `remote-file-name-inhibit-cache'
3518 ;; could also be a timestamp as `current-time' returns. This
3519 ;; means invalidate all cache entries with an older timestamp.
3520 (let (tramp-vc-registered-file-names
3521 (remote-file-name-inhibit-cache (current-time))
3522 (file-name-handler-alist
3523 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
3524
3525 ;; Here we collect only file names, which need an operation.
3526 (ignore-errors (tramp-run-real-handler 'vc-registered (list file)))
3527 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
3528
3529 ;; Send just one command, in order to fill the cache.
3530 (when tramp-vc-registered-file-names
3531 (tramp-maybe-send-script
3532 v
3533 (format tramp-vc-registered-read-file-names
3534 (tramp-get-file-exists-command v)
3535 (format "%s -r" (tramp-get-test-command v)))
3536 "tramp_vc_registered_read_file_names")
3537
3538 (dolist
3539 (elt
3540 (ignore-errors
3541 ;; We cannot use `tramp-send-command-and-read',
3542 ;; because this does not cooperate well with
3543 ;; heredoc documents.
3544 (tramp-send-command
3545 v
3546 (format
3547 "tramp_vc_registered_read_file_names <<'%s'\n%s\n%s\n"
3548 tramp-end-of-heredoc
3549 (mapconcat 'tramp-shell-quote-argument
3550 tramp-vc-registered-file-names
3551 "\n")
3552 tramp-end-of-heredoc))
3553 (with-current-buffer (tramp-get-connection-buffer v)
3554 ;; Read the expression.
3555 (goto-char (point-min))
3556 (read (current-buffer)))))
3557
3558 (tramp-set-file-property
3559 v (car elt) (cadr elt) (cadr (cdr elt))))))
3560
3561 ;; Second run. Now all `file-exists-p' or `file-readable-p'
3562 ;; calls shall be answered from the file cache. We unset
3563 ;; `process-file-side-effects' and `remote-file-name-inhibit-cache'
3564 ;; in order to keep the cache.
3565 (let ((vc-handled-backends vc-handled-backends)
3566 remote-file-name-inhibit-cache process-file-side-effects)
3567 ;; Reduce `vc-handled-backends' in order to minimize process calls.
3568 (when (and (memq 'Bzr vc-handled-backends)
3569 (boundp 'vc-bzr-program)
3570 (not (with-tramp-connection-property v vc-bzr-program
3571 (tramp-find-executable
3572 v vc-bzr-program (tramp-get-remote-path v)))))
3573 (setq vc-handled-backends (remq 'Bzr vc-handled-backends)))
3574 (when (and (memq 'Git vc-handled-backends)
3575 (boundp 'vc-git-program)
3576 (not (with-tramp-connection-property v vc-git-program
3577 (tramp-find-executable
3578 v vc-git-program (tramp-get-remote-path v)))))
3579 (setq vc-handled-backends (remq 'Git vc-handled-backends)))
3580 (when (and (memq 'Hg vc-handled-backends)
3581 (boundp 'vc-hg-program)
3582 (not (with-tramp-connection-property v vc-hg-program
3583 (tramp-find-executable
3584 v vc-hg-program (tramp-get-remote-path v)))))
3585 (setq vc-handled-backends (remq 'Hg vc-handled-backends)))
3586 ;; Run.
3587 (ignore-errors
3588 (tramp-run-real-handler 'vc-registered (list file))))))))
3589
3590 ;;;###tramp-autoload
3591 (defun tramp-sh-file-name-handler (operation &rest args)
3592 "Invoke remote-shell Tramp file name handler.
3593 Fall back to normal file name handler if no Tramp handler exists."
3594 (when (and tramp-locked (not tramp-locker))
3595 (setq tramp-locked nil)
3596 (tramp-error
3597 (car-safe tramp-current-connection) 'file-error
3598 "Forbidden reentrant call of Tramp"))
3599 (let ((tl tramp-locked))
3600 (setq tramp-locked t)
3601 (unwind-protect
3602 (let ((tramp-locker t))
3603 (save-match-data
3604 (let ((fn (assoc operation tramp-sh-file-name-handler-alist)))
3605 (if fn
3606 (apply (cdr fn) args)
3607 (tramp-run-real-handler operation args)))))
3608 (setq tramp-locked tl))))
3609
3610 (defun tramp-vc-file-name-handler (operation &rest args)
3611 "Invoke special file name handler, which collects files to be handled."
3612 (save-match-data
3613 (let ((filename
3614 (tramp-replace-environment-variables
3615 (apply 'tramp-file-name-for-operation operation args)))
3616 (fn (assoc operation tramp-sh-file-name-handler-alist)))
3617 (with-parsed-tramp-file-name filename nil
3618 (cond
3619 ;; That's what we want: file names, for which checks are
3620 ;; applied. We assume that VC uses only `file-exists-p' and
3621 ;; `file-readable-p' checks; otherwise we must extend the
3622 ;; list. We do not perform any action, but return nil, in
3623 ;; order to keep `vc-registered' running.
3624 ((and fn (memq operation '(file-exists-p file-readable-p)))
3625 (add-to-list 'tramp-vc-registered-file-names localname 'append)
3626 nil)
3627 ;; `process-file' and `start-file-process' shall be ignored.
3628 ((and fn (eq operation 'process-file) 0))
3629 ((and fn (eq operation 'start-file-process) nil))
3630 ;; Tramp file name handlers like `expand-file-name'. They
3631 ;; must still work.
3632 (fn (save-match-data (apply (cdr fn) args)))
3633 ;; Default file name handlers, we don't care.
3634 (t (tramp-run-real-handler operation args)))))))
3635
3636 (defun tramp-sh-handle-file-notify-add-watch (file-name flags _callback)
3637 "Like `file-notify-add-watch' for Tramp files."
3638 (setq file-name (expand-file-name file-name))
3639 (with-parsed-tramp-file-name file-name nil
3640 (let ((default-directory (file-name-directory file-name))
3641 command events filter p sequence)
3642 (cond
3643 ;; gvfs-monitor-dir.
3644 ((setq command (tramp-get-remote-gvfs-monitor-dir v))
3645 (setq filter 'tramp-sh-gvfs-monitor-dir-process-filter
3646 events
3647 (cond
3648 ((and (memq 'change flags) (memq 'attribute-change flags))
3649 '(created changed changes-done-hint moved deleted
3650 attribute-changed))
3651 ((memq 'change flags)
3652 '(created changed changes-done-hint moved deleted))
3653 ((memq 'attribute-change flags) '(attribute-changed)))
3654 sequence `(,command ,localname)))
3655 ;; inotifywait.
3656 ((setq command (tramp-get-remote-inotifywait v))
3657 (setq filter 'tramp-sh-inotifywait-process-filter
3658 events
3659 (cond
3660 ((and (memq 'change flags) (memq 'attribute-change flags))
3661 (concat "create,modify,move,moved_from,moved_to,move_self,"
3662 "delete,delete_self,attrib,ignored"))
3663 ((memq 'change flags)
3664 (concat "create,modify,move,moved_from,moved_to,move_self,"
3665 "delete,delete_self,ignored"))
3666 ((memq 'attribute-change flags) "attrib,ignored"))
3667 sequence `(,command "-mq" "-e" ,events ,localname)))
3668 ;; None.
3669 (t (tramp-error
3670 v 'file-notify-error
3671 "No file notification program found on %s"
3672 (file-remote-p file-name))))
3673 ;; Start process.
3674 (setq p (apply
3675 'start-file-process
3676 (file-name-nondirectory command)
3677 (generate-new-buffer
3678 (format " *%s*" (file-name-nondirectory command)))
3679 sequence))
3680 ;; Return the process object as watch-descriptor.
3681 (if (not (processp p))
3682 (tramp-error
3683 v 'file-notify-error
3684 "`%s' failed to start on remote host"
3685 (mapconcat 'identity sequence " "))
3686 (tramp-message v 6 "Run `%s', %S" (mapconcat 'identity sequence " ") p)
3687 (tramp-set-connection-property p "vector" v)
3688 ;; Needed for `tramp-sh-gvfs-monitor-dir-process-filter'.
3689 (process-put p 'events events)
3690 (process-put p 'watch-name localname)
3691 (set-process-query-on-exit-flag p nil)
3692 (set-process-filter p filter)
3693 ;; There might be an error if the monitor is not supported.
3694 ;; Give the filter a chance to read the output.
3695 (tramp-accept-process-output p 1)
3696 (unless (memq (process-status p) '(run open))
3697 (tramp-error
3698 v 'file-notify-error "Monitoring not supported for `%s'" file-name))
3699 p))))
3700
3701 (defun tramp-sh-gvfs-monitor-dir-process-filter (proc string)
3702 "Read output from \"gvfs-monitor-dir\" and add corresponding \
3703 file-notify events."
3704 (let ((remote-prefix
3705 (with-current-buffer (process-buffer proc)
3706 (file-remote-p default-directory)))
3707 (rest-string (process-get proc 'rest-string)))
3708 (when rest-string
3709 (tramp-message proc 10 "Previous string:\n%s" rest-string))
3710 (tramp-message proc 6 "%S\n%s" proc string)
3711 (setq string (concat rest-string string)
3712 ;; Attribute change is returned in unused wording.
3713 string (replace-regexp-in-string
3714 "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))
3715 (when (string-match "Monitoring not supported" string)
3716 (delete-process proc))
3717
3718 (while (string-match
3719 (concat "^[\n\r]*"
3720 "Directory Monitor Event:[\n\r]+"
3721 "Child = \\([^\n\r]+\\)[\n\r]+"
3722 "\\(Other = \\([^\n\r]+\\)[\n\r]+\\)?"
3723 "Event = \\([^[:blank:]]+\\)[\n\r]+")
3724 string)
3725 (let* ((file (match-string 1 string))
3726 (file1 (match-string 3 string))
3727 (object
3728 (list
3729 proc
3730 (intern-soft
3731 (replace-regexp-in-string
3732 "_" "-" (downcase (match-string 4 string))))
3733 ;; File names are returned as absolute paths. We must
3734 ;; add the remote prefix.
3735 (concat remote-prefix file)
3736 (when file1 (concat remote-prefix file1)))))
3737 (setq string (replace-match "" nil nil string))
3738 ;; Remove watch when file or directory to be watched is deleted.
3739 (when (and (member (cadr object) '(moved deleted))
3740 (string-equal file (process-get proc 'watch-name)))
3741 (delete-process proc))
3742 ;; Usually, we would add an Emacs event now. Unfortunately,
3743 ;; `unread-command-events' does not accept several events at
3744 ;; once. Therefore, we apply the callback directly.
3745 (when (member (cadr object) (process-get proc 'events))
3746 (tramp-compat-funcall 'file-notify-callback object))))
3747
3748 ;; Save rest of the string.
3749 (when (zerop (length string)) (setq string nil))
3750 (when string (tramp-message proc 10 "Rest string:\n%s" string))
3751 (process-put proc 'rest-string string)))
3752
3753 (defun tramp-sh-inotifywait-process-filter (proc string)
3754 "Read output from \"inotifywait\" and add corresponding file-notify events."
3755 (tramp-message proc 6 "%S\n%s" proc string)
3756 (dolist (line (split-string string "[\n\r]+" 'omit))
3757 ;; Check, whether there is a problem.
3758 (unless
3759 (string-match
3760 (concat "^[^[:blank:]]+"
3761 "[[:blank:]]+\\([^[:blank:]]+\\)+"
3762 "\\([[:blank:]]+\\([^\n\r]+\\)\\)?")
3763 line)
3764 (tramp-error proc 'file-notify-error "%s" line))
3765
3766 (let ((object
3767 (list
3768 proc
3769 (mapcar
3770 (lambda (x)
3771 (intern-soft
3772 (replace-regexp-in-string "_" "-" (downcase x))))
3773 (split-string (match-string 1 line) "," 'omit))
3774 (match-string 3 line))))
3775 ;; Remove watch when file or directory to be watched is deleted.
3776 (when (equal (cadr object) 'ignored)
3777 (delete-process proc))
3778 ;; Usually, we would add an Emacs event now. Unfortunately,
3779 ;; `unread-command-events' does not accept several events at
3780 ;; once. Therefore, we apply the callback directly.
3781 (tramp-compat-funcall 'file-notify-callback object))))
3782
3783 ;;; Internal Functions:
3784
3785 (defun tramp-maybe-send-script (vec script name)
3786 "Define in remote shell function NAME implemented as SCRIPT.
3787 Only send the definition if it has not already been done."
3788 ;; We cannot let-bind (tramp-get-connection-process vec) because it
3789 ;; might be nil.
3790 (let ((scripts (tramp-get-connection-property
3791 (tramp-get-connection-process vec) "scripts" nil)))
3792 (unless (member name scripts)
3793 (with-tramp-progress-reporter
3794 vec 5 (format-message "Sending script `%s'" name)
3795 ;; In bash, leading TABs like in `tramp-vc-registered-read-file-names'
3796 ;; could result in unwanted command expansion. Avoid this.
3797 (setq script (replace-regexp-in-string
3798 (make-string 1 ?\t) (make-string 8 ? ) script))
3799 ;; The script could contain a call of Perl. This is masked with `%s'.
3800 (when (and (string-match "%s" script)
3801 (not (tramp-get-remote-perl vec)))
3802 (tramp-error vec 'file-error "No Perl available on remote host"))
3803 (tramp-barf-unless-okay
3804 vec
3805 (format "%s () {\n%s\n}"
3806 name (format script (tramp-get-remote-perl vec)))
3807 "Script %s sending failed" name)
3808 (tramp-set-connection-property
3809 (tramp-get-connection-process vec) "scripts" (cons name scripts))))))
3810
3811 (defun tramp-run-test (switch filename)
3812 "Run `test' on the remote system, given a SWITCH and a FILENAME.
3813 Returns the exit code of the `test' program."
3814 (with-parsed-tramp-file-name filename nil
3815 (tramp-send-command-and-check
3816 v
3817 (format
3818 "%s %s %s"
3819 (tramp-get-test-command v)
3820 switch
3821 (tramp-shell-quote-argument localname)))))
3822
3823 (defun tramp-run-test2 (format-string file1 file2)
3824 "Run `test'-like program on the remote system, given FILE1, FILE2.
3825 FORMAT-STRING contains the program name, switches, and place holders.
3826 Returns the exit code of the `test' program. Barfs if the methods,
3827 hosts, or files, disagree."
3828 (unless (tramp-equal-remote file1 file2)
3829 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
3830 (tramp-error
3831 v 'file-error
3832 "tramp-run-test2 only implemented for same method, user, host")))
3833 (with-parsed-tramp-file-name file1 v1
3834 (with-parsed-tramp-file-name file1 v2
3835 (tramp-send-command-and-check
3836 v1
3837 (format format-string
3838 (tramp-shell-quote-argument v1-localname)
3839 (tramp-shell-quote-argument v2-localname))))))
3840
3841 (defun tramp-find-executable
3842 (vec progname dirlist &optional ignore-tilde ignore-path)
3843 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
3844 First arg VEC specifies the connection, PROGNAME is the program
3845 to search for, and DIRLIST gives the list of directories to
3846 search. If IGNORE-TILDE is non-nil, directory names starting
3847 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
3848 only in DIRLIST.
3849
3850 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
3851
3852 This function expects to be in the right *tramp* buffer."
3853 (with-current-buffer (tramp-get-connection-buffer vec)
3854 (let (result)
3855 ;; Check whether the executable is in $PATH. "which(1)" does not
3856 ;; report always a correct error code; therefore we check the
3857 ;; number of words it returns. "SunOS 5.10" (and maybe "SunOS
3858 ;; 5.11") have problems with this command, we disable the call
3859 ;; therefore.
3860 (unless (or ignore-path
3861 (string-match
3862 (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
3863 (tramp-get-connection-property vec "uname" "")))
3864 (tramp-send-command vec (format "which \\%s | wc -w" progname))
3865 (goto-char (point-min))
3866 (if (looking-at "^\\s-*1$")
3867 (setq result (concat "\\" progname))))
3868 (unless result
3869 (when ignore-tilde
3870 ;; Remove all ~/foo directories from dirlist.
3871 (let (newdl d)
3872 (while dirlist
3873 (setq d (car dirlist))
3874 (setq dirlist (cdr dirlist))
3875 (unless (char-equal ?~ (aref d 0))
3876 (setq newdl (cons d newdl))))
3877 (setq dirlist (nreverse newdl))))
3878 (tramp-send-command
3879 vec
3880 (format (concat "while read d; "
3881 "do if test -x $d/%s && test -f $d/%s; "
3882 "then echo tramp_executable $d/%s; "
3883 "break; fi; done <<'%s'\n"
3884 "%s\n%s")
3885 progname progname progname
3886 tramp-end-of-heredoc
3887 (mapconcat 'identity dirlist "\n")
3888 tramp-end-of-heredoc))
3889 (goto-char (point-max))
3890 (when (search-backward "tramp_executable " nil t)
3891 (skip-chars-forward "^ ")
3892 (skip-chars-forward " ")
3893 (setq result (buffer-substring (point) (point-at-eol)))))
3894 result)))
3895
3896 (defun tramp-set-remote-path (vec)
3897 "Sets the remote environment PATH to existing directories.
3898 I.e., for each directory in `tramp-remote-path', it is tested
3899 whether it exists and if so, it is added to the environment
3900 variable PATH."
3901 (tramp-message vec 5 "Setting $PATH environment variable")
3902 (tramp-send-command
3903 vec (format "PATH=%s; export PATH"
3904 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
3905
3906 ;; ------------------------------------------------------------
3907 ;; -- Communication with external shell --
3908 ;; ------------------------------------------------------------
3909
3910 (defun tramp-find-file-exists-command (vec)
3911 "Find a command on the remote host for checking if a file exists.
3912 Here, we are looking for a command which has zero exit status if the
3913 file exists and nonzero exit status otherwise."
3914 (let ((existing "/")
3915 (nonexistent
3916 (tramp-shell-quote-argument "/ this file does not exist "))
3917 result)
3918 ;; The algorithm is as follows: we try a list of several commands.
3919 ;; For each command, we first run `$cmd /' -- this should return
3920 ;; true, as the root directory always exists. And then we run
3921 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
3922 ;; does not exist. This should return false. We use the first
3923 ;; command we find that seems to work.
3924 ;; The list of commands to try is as follows:
3925 ;; `ls -d' This works on most systems, but NetBSD 1.4
3926 ;; has a bug: `ls' always returns zero exit
3927 ;; status, even for files which don't exist.
3928 ;; `test -e' Some Bourne shells have a `test' builtin
3929 ;; which does not know the `-e' option.
3930 ;; `/bin/test -e' For those, the `test' binary on disk normally
3931 ;; provides the option. Alas, the binary
3932 ;; is sometimes `/bin/test' and sometimes it's
3933 ;; `/usr/bin/test'.
3934 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
3935 (unless (or
3936 (ignore-errors
3937 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
3938 (tramp-send-command-and-check
3939 vec (format "%s %s" result existing))
3940 (not (tramp-send-command-and-check
3941 vec (format "%s %s" result nonexistent)))))
3942 (ignore-errors
3943 (and (setq result "/bin/test -e")
3944 (tramp-send-command-and-check
3945 vec (format "%s %s" result existing))
3946 (not (tramp-send-command-and-check
3947 vec (format "%s %s" result nonexistent)))))
3948 (ignore-errors
3949 (and (setq result "/usr/bin/test -e")
3950 (tramp-send-command-and-check
3951 vec (format "%s %s" result existing))
3952 (not (tramp-send-command-and-check
3953 vec (format "%s %s" result nonexistent)))))
3954 (ignore-errors
3955 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
3956 (tramp-send-command-and-check
3957 vec (format "%s %s" result existing))
3958 (not (tramp-send-command-and-check
3959 vec (format "%s %s" result nonexistent))))))
3960 (tramp-error
3961 vec 'file-error "Couldn't find command to check if file exists"))
3962 result))
3963
3964 (defun tramp-open-shell (vec shell)
3965 "Opens shell SHELL."
3966 (with-tramp-progress-reporter
3967 vec 5 (format-message "Opening remote shell `%s'" shell)
3968 ;; Find arguments for this shell.
3969 (let ((alist tramp-sh-extra-args)
3970 item extra-args)
3971 (while (and alist (null extra-args))
3972 (setq item (pop alist))
3973 (when (string-match (car item) shell)
3974 (setq extra-args (cdr item))))
3975 ;; It is useful to set the prompt in the following command
3976 ;; because some people have a setting for $PS1 which /bin/sh
3977 ;; doesn't know about and thus /bin/sh will display a strange
3978 ;; prompt. For example, if $PS1 has "${CWD}" in the value, then
3979 ;; ksh will display the current working directory but /bin/sh
3980 ;; will display a dollar sign. The following command line sets
3981 ;; $PS1 to a sane value, and works under Bourne-ish shells as
3982 ;; well as csh-like shells. We also unset the variable $ENV
3983 ;; because that is read by some sh implementations (eg, bash
3984 ;; when called as sh) on startup; this way, we avoid the startup
3985 ;; file clobbering $PS1. $PROMPT_COMMAND is another way to set
3986 ;; the prompt in /bin/bash, it must be discarded as well.
3987 ;; $HISTFILE is set according to `tramp-histfile-override'.
3988 (tramp-send-command
3989 vec (format
3990 "exec env ENV='' %s PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s %s"
3991 (if (stringp tramp-histfile-override)
3992 (format "HISTFILE=%s"
3993 (tramp-shell-quote-argument tramp-histfile-override))
3994 (if tramp-histfile-override
3995 "HISTFILE='' HISTFILESIZE=0 HISTSIZE=0"
3996 ""))
3997 (tramp-shell-quote-argument tramp-end-of-output)
3998 shell (or extra-args ""))
3999 t))
4000 (tramp-set-connection-property
4001 (tramp-get-connection-process vec) "remote-shell" shell)))
4002
4003 (defun tramp-find-shell (vec)
4004 "Opens a shell on the remote host which groks tilde expansion."
4005 (with-current-buffer (tramp-get-buffer vec)
4006 (let ((default-shell (tramp-get-method-parameter vec 'tramp-remote-shell))
4007 shell)
4008 (setq shell
4009 (with-tramp-connection-property vec "remote-shell"
4010 ;; CCC: "root" does not exist always, see QNAP 459.
4011 ;; Which check could we apply instead?
4012 (tramp-send-command vec "echo ~root" t)
4013 (if (or (string-match "^~root$" (buffer-string))
4014 ;; The default shell (ksh93) of OpenSolaris and
4015 ;; Solaris is buggy. We've got reports for
4016 ;; "SunOS 5.10" and "SunOS 5.11" so far.
4017 (string-match (regexp-opt '("SunOS 5.10" "SunOS 5.11"))
4018 (tramp-get-connection-property
4019 vec "uname" "")))
4020
4021 (or (tramp-find-executable
4022 vec "bash" (tramp-get-remote-path vec) t t)
4023 (tramp-find-executable
4024 vec "ksh" (tramp-get-remote-path vec) t t)
4025 ;; Maybe it works at least for some other commands.
4026 (prog1
4027 default-shell
4028 (tramp-message
4029 vec 2
4030 (concat
4031 "Couldn't find a remote shell which groks tilde "
4032 "expansion, using `%s'")
4033 default-shell)))
4034
4035 default-shell)))
4036
4037 ;; Open a new shell if needed.
4038 (unless (string-equal shell default-shell)
4039 (tramp-message
4040 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
4041 (tramp-open-shell vec shell)))))
4042
4043 ;; Utility functions.
4044
4045 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
4046 "Wait for shell prompt and barf if none appears.
4047 Looks at process PROC to see if a shell prompt appears in TIMEOUT
4048 seconds. If not, it produces an error message with the given ERROR-ARGS."
4049 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4050 (condition-case nil
4051 (tramp-wait-for-regexp
4052 proc timeout
4053 (format
4054 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
4055 (error
4056 (delete-process proc)
4057 (apply 'tramp-error-with-buffer
4058 (tramp-get-connection-buffer vec) vec 'file-error error-args)))))
4059
4060 (defun tramp-open-connection-setup-interactive-shell (proc vec)
4061 "Set up an interactive shell.
4062 Mainly sets the prompt and the echo correctly. PROC is the shell
4063 process to set up. VEC specifies the connection."
4064 (let ((tramp-end-of-output tramp-initial-end-of-output)
4065 (case-fold-search t))
4066 (tramp-open-shell vec (tramp-get-method-parameter vec 'tramp-remote-shell))
4067
4068 ;; Disable tab and echo expansion.
4069 (tramp-message vec 5 "Setting up remote shell environment")
4070 (tramp-send-command
4071 vec "stty tab0 -inlcr -onlcr -echo kill '^U' erase '^H'" t)
4072 ;; Check whether the echo has really been disabled. Some
4073 ;; implementations, like busybox of embedded GNU/Linux, don't
4074 ;; support disabling.
4075 (tramp-send-command vec "echo foo" t)
4076 (with-current-buffer (process-buffer proc)
4077 (goto-char (point-min))
4078 (when (looking-at "echo foo")
4079 (tramp-set-connection-property proc "remote-echo" t)
4080 (tramp-message vec 5 "Remote echo still on. Ok.")
4081 ;; Make sure backspaces and their echo are enabled and no line
4082 ;; width magic interferes with them.
4083 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
4084
4085 (tramp-message vec 5 "Setting shell prompt")
4086 (tramp-send-command
4087 vec (format "PS1=%s PS2='' PS3='' PROMPT_COMMAND=''"
4088 (tramp-shell-quote-argument tramp-end-of-output)) t)
4089
4090 ;; Check whether the output of "uname -sr" has been changed. If
4091 ;; yes, this is a strong indication that we must expire all
4092 ;; connection properties. We start again with
4093 ;; `tramp-maybe-open-connection', it will be caught there.
4094 (tramp-message vec 5 "Checking system information")
4095 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
4096 (new-uname
4097 (tramp-set-connection-property
4098 vec "uname"
4099 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
4100 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
4101 (tramp-message
4102 vec 3
4103 "Connection reset, because remote host changed from `%s' to `%s'"
4104 old-uname new-uname)
4105 ;; We want to keep the password.
4106 (tramp-cleanup-connection vec t t)
4107 (throw 'uname-changed (tramp-maybe-open-connection vec))))
4108
4109 ;; Try to set up the coding system correctly.
4110 ;; CCC this can't be the right way to do it. Hm.
4111 (tramp-message vec 5 "Determining coding system")
4112 (with-current-buffer (process-buffer proc)
4113 (if (featurep 'mule)
4114 ;; Use MULE to select the right EOL convention for communicating
4115 ;; with the process.
4116 (let ((cs (or (and (memq 'utf-8 (coding-system-list))
4117 (string-match "utf-?8" (tramp-get-remote-locale vec))
4118 (cons 'utf-8 'utf-8))
4119 (process-coding-system proc)
4120 (cons 'undecided 'undecided)))
4121 cs-decode cs-encode)
4122 (when (symbolp cs) (setq cs (cons cs cs)))
4123 (setq cs-decode (or (car cs) 'undecided)
4124 cs-encode (or (cdr cs) 'undecided))
4125 (setq cs-encode
4126 (coding-system-change-eol-conversion
4127 cs-encode
4128 (if (string-match
4129 "^Darwin" (tramp-get-connection-property vec "uname" ""))
4130 'mac 'unix)))
4131 (tramp-send-command vec "echo foo ; echo bar" t)
4132 (goto-char (point-min))
4133 (when (search-forward "\r" nil t)
4134 (setq cs-decode (coding-system-change-eol-conversion
4135 cs-decode 'dos)))
4136 ;; Special setting for Mac OS X.
4137 (when (and (string-match
4138 "^Darwin" (tramp-get-connection-property vec "uname" ""))
4139 (memq 'utf-8-hfs (coding-system-list)))
4140 (setq cs-decode 'utf-8-hfs
4141 cs-encode 'utf-8-hfs))
4142 (set-buffer-process-coding-system cs-decode cs-encode)
4143 (tramp-message
4144 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
4145 ;; Look for ^M and do something useful if found.
4146 (when (search-forward "\r" nil t)
4147 ;; We have found a ^M but cannot frob the process coding system
4148 ;; because we're running on a non-MULE Emacs. Let's try
4149 ;; stty, instead.
4150 (tramp-send-command vec "stty -onlcr" t))))
4151
4152 (tramp-send-command vec "set +o vi +o emacs" t)
4153
4154 ;; Check whether the remote host suffers from buggy
4155 ;; `send-process-string'. This is known for FreeBSD (see comment in
4156 ;; `send_process', file process.c). I've tested sending 624 bytes
4157 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
4158 ;; this host type is detected locally. It cannot handle remote
4159 ;; hosts, though.
4160 (with-tramp-connection-property proc "chunksize"
4161 (cond
4162 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
4163 tramp-chunksize)
4164 (t
4165 (tramp-message
4166 vec 5 "Checking remote host type for `send-process-string' bug")
4167 (if (string-match
4168 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
4169 500 0))))
4170
4171 ;; Set remote PATH variable.
4172 (tramp-set-remote-path vec)
4173
4174 ;; Search for a good shell before searching for a command which
4175 ;; checks if a file exists. This is done because Tramp wants to use
4176 ;; "test foo; echo $?" to check if various conditions hold, and
4177 ;; there are buggy /bin/sh implementations which don't execute the
4178 ;; "echo $?" part if the "test" part has an error. In particular,
4179 ;; the OpenSolaris /bin/sh is a problem. There are also other
4180 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
4181 ;; in function declarations, or changing HISTFILE in place.
4182 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
4183 ;; detected.
4184 (tramp-find-shell vec)
4185
4186 ;; Disable unexpected output.
4187 (tramp-send-command vec "mesg n 2>/dev/null; biff n 2>/dev/null" t)
4188
4189 ;; IRIX64 bash expands "!" even when in single quotes. This
4190 ;; destroys our shell functions, we must disable it. See
4191 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
4192 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
4193 (tramp-send-command vec "set +H" t))
4194
4195 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
4196 (when (string-match "BSD\\|Darwin"
4197 (tramp-get-connection-property vec "uname" ""))
4198 (tramp-send-command vec "stty -oxtabs" t))
4199
4200 ;; Set utf8 encoding. Needed for Mac OS X, for example. This is
4201 ;; non-POSIX, so we must expect errors on some systems.
4202 (tramp-send-command vec "stty iutf8 2>/dev/null" t)
4203
4204 ;; Set `remote-tty' process property.
4205 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"" 'noerror)))
4206 (unless (zerop (length tty))
4207 (process-put proc 'remote-tty tty)))
4208
4209 ;; Dump stty settings in the traces.
4210 (when (>= tramp-verbose 9)
4211 (tramp-send-command vec "stty -a" t))
4212
4213 ;; Set the environment.
4214 (tramp-message vec 5 "Setting default environment")
4215
4216 (let ((env (append `(,(tramp-get-remote-locale vec))
4217 (copy-sequence tramp-remote-process-environment)))
4218 unset vars item)
4219 (while env
4220 (setq item (split-string (car env) "=" 'omit))
4221 (setcdr item (mapconcat 'identity (cdr item) "="))
4222 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
4223 (push (format "%s %s" (car item) (cdr item)) vars)
4224 (push (car item) unset))
4225 (setq env (cdr env)))
4226 (when vars
4227 (tramp-send-command
4228 vec
4229 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
4230 tramp-end-of-heredoc
4231 (mapconcat 'identity vars "\n")
4232 tramp-end-of-heredoc)
4233 t))
4234 (when unset
4235 (tramp-send-command
4236 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
4237
4238 ;; Old text from documentation of tramp-methods:
4239 ;; Using a uuencode/uudecode inline method is discouraged, please use one
4240 ;; of the base64 methods instead since base64 encoding is much more
4241 ;; reliable and the commands are more standardized between the different
4242 ;; Unix versions. But if you can't use base64 for some reason, please
4243 ;; note that the default uudecode command does not work well for some
4244 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
4245 ;; the following command for uudecode:
4246 ;;
4247 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
4248 ;;
4249 ;; For Irix, no solution is known yet.
4250
4251 (autoload 'uudecode-decode-region "uudecode")
4252
4253 (defconst tramp-local-coding-commands
4254 `((b64 base64-encode-region base64-decode-region)
4255 (uu tramp-uuencode-region uudecode-decode-region)
4256 (pack ,(format tramp-perl-pack "perl") ,(format tramp-perl-unpack "perl")))
4257 "List of local coding commands for inline transfer.
4258 Each item is a list that looks like this:
4259
4260 \(FORMAT ENCODING DECODING)
4261
4262 FORMAT is symbol describing the encoding/decoding format. It can be
4263 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4264
4265 ENCODING and DECODING can be strings, giving commands, or symbols,
4266 giving functions. If they are strings, then they can contain
4267 the \"%s\" format specifier. If that specifier is present, the input
4268 file name will be put into the command line at that spot. If the
4269 specifier is not present, the input should be read from standard
4270 input.
4271
4272 If they are functions, they will be called with two arguments, start
4273 and end of region, and are expected to replace the region contents
4274 with the encoded or decoded results, respectively.")
4275
4276 (defconst tramp-remote-coding-commands
4277 `((b64 "base64" "base64 -d -i")
4278 ;; "-i" is more robust with older base64 from GNU coreutils.
4279 ;; However, I don't know whether all base64 versions do supports
4280 ;; this option.
4281 (b64 "base64" "base64 -d")
4282 (b64 "openssl enc -base64" "openssl enc -d -base64")
4283 (b64 "mimencode -b" "mimencode -u -b")
4284 (b64 "mmencode -b" "mmencode -u -b")
4285 (b64 "recode data..base64" "recode base64..data")
4286 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
4287 (b64 tramp-perl-encode tramp-perl-decode)
4288 ;; This is painful slow, so we put it on the end.
4289 (b64 tramp-awk-encode tramp-awk-decode ,tramp-awk-coding-test)
4290 (uu "uuencode xxx" "uudecode -o /dev/stdout" "test -c /dev/stdout")
4291 (uu "uuencode xxx" "uudecode -o -")
4292 (uu "uuencode xxx" "uudecode -p")
4293 (uu "uuencode xxx" tramp-uudecode)
4294 (pack tramp-perl-pack tramp-perl-unpack))
4295 "List of remote coding commands for inline transfer.
4296 Each item is a list that looks like this:
4297
4298 \(FORMAT ENCODING DECODING [TEST])
4299
4300 FORMAT is a symbol describing the encoding/decoding format. It can be
4301 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
4302
4303 ENCODING and DECODING can be strings, giving commands, or symbols,
4304 giving variables. If they are strings, then they can contain
4305 the \"%s\" format specifier. If that specifier is present, the input
4306 file name will be put into the command line at that spot. If the
4307 specifier is not present, the input should be read from standard
4308 input.
4309
4310 If they are variables, this variable is a string containing a
4311 Perl or Shell implementation for this functionality. This
4312 program will be transferred to the remote host, and it is
4313 available as shell function with the same name. A \"%t\" format
4314 specifier in the variable value denotes a temporary file.
4315
4316 The optional TEST command can be used for further tests, whether
4317 ENCODING and DECODING are applicable.")
4318
4319 (defun tramp-find-inline-encoding (vec)
4320 "Find an inline transfer encoding that works.
4321 Goes through the list `tramp-local-coding-commands' and
4322 `tramp-remote-coding-commands'."
4323 (save-excursion
4324 (let ((local-commands tramp-local-coding-commands)
4325 (magic "xyzzy")
4326 (p (tramp-get-connection-process vec))
4327 loc-enc loc-dec rem-enc rem-dec rem-test litem ritem found)
4328 (while (and local-commands (not found))
4329 (setq litem (pop local-commands))
4330 (catch 'wont-work-local
4331 (let ((format (nth 0 litem))
4332 (remote-commands tramp-remote-coding-commands))
4333 (setq loc-enc (nth 1 litem))
4334 (setq loc-dec (nth 2 litem))
4335 ;; If the local encoder or decoder is a string, the
4336 ;; corresponding command has to work locally.
4337 (if (not (stringp loc-enc))
4338 (tramp-message
4339 vec 5 "Checking local encoding function `%s'" loc-enc)
4340 (tramp-message
4341 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
4342 (unless (zerop (tramp-call-local-coding-command
4343 loc-enc nil nil))
4344 (throw 'wont-work-local nil)))
4345 (if (not (stringp loc-dec))
4346 (tramp-message
4347 vec 5 "Checking local decoding function `%s'" loc-dec)
4348 (tramp-message
4349 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
4350 (unless (zerop (tramp-call-local-coding-command
4351 loc-dec nil nil))
4352 (throw 'wont-work-local nil)))
4353 ;; Search for remote coding commands with the same format
4354 (while (and remote-commands (not found))
4355 (setq ritem (pop remote-commands))
4356 (catch 'wont-work-remote
4357 (when (equal format (nth 0 ritem))
4358 (setq rem-enc (nth 1 ritem))
4359 (setq rem-dec (nth 2 ritem))
4360 (setq rem-test (nth 3 ritem))
4361 ;; Check the remote test command if exists.
4362 (when (stringp rem-test)
4363 (tramp-message
4364 vec 5 "Checking remote test command `%s'" rem-test)
4365 (unless (tramp-send-command-and-check vec rem-test t)
4366 (throw 'wont-work-remote nil)))
4367 ;; Check if remote perl exists when necessary.
4368 (when (and (symbolp rem-enc)
4369 (string-match "perl" (symbol-name rem-enc))
4370 (not (tramp-get-remote-perl vec)))
4371 (throw 'wont-work-remote nil))
4372 ;; Check if remote encoding and decoding commands can be
4373 ;; called remotely with null input and output. This makes
4374 ;; sure there are no syntax errors and the command is really
4375 ;; found. Note that we do not redirect stdout to /dev/null,
4376 ;; for two reasons: when checking the decoding command, we
4377 ;; actually check the output it gives. And also, when
4378 ;; redirecting "mimencode" output to /dev/null, then as root
4379 ;; it might change the permissions of /dev/null!
4380 (when (not (stringp rem-enc))
4381 (let ((name (symbol-name rem-enc)))
4382 (while (string-match (regexp-quote "-") name)
4383 (setq name (replace-match "_" nil t name)))
4384 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
4385 (setq rem-enc name)))
4386 (tramp-message
4387 vec 5
4388 "Checking remote encoding command `%s' for sanity" rem-enc)
4389 (unless (tramp-send-command-and-check
4390 vec (format "%s </dev/null" rem-enc) t)
4391 (throw 'wont-work-remote nil))
4392
4393 (when (not (stringp rem-dec))
4394 (let ((name (symbol-name rem-dec))
4395 (value (symbol-value rem-dec))
4396 tmpfile)
4397 (while (string-match (regexp-quote "-") name)
4398 (setq name (replace-match "_" nil t name)))
4399 (when (string-match "\\(^\\|[^%]\\)%t" value)
4400 (setq tmpfile
4401 (make-temp-name
4402 (expand-file-name
4403 tramp-temp-name-prefix
4404 (tramp-get-remote-tmpdir vec)))
4405 value
4406 (format-spec
4407 value
4408 (format-spec-make
4409 ?t
4410 (file-remote-p tmpfile 'localname)))))
4411 (tramp-maybe-send-script vec value name)
4412 (setq rem-dec name)))
4413 (tramp-message
4414 vec 5
4415 "Checking remote decoding command `%s' for sanity" rem-dec)
4416 (unless (tramp-send-command-and-check
4417 vec
4418 (format "echo %s | %s | %s" magic rem-enc rem-dec)
4419 t)
4420 (throw 'wont-work-remote nil))
4421
4422 (with-current-buffer (tramp-get-buffer vec)
4423 (goto-char (point-min))
4424 (unless (looking-at (regexp-quote magic))
4425 (throw 'wont-work-remote nil)))
4426
4427 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
4428 (setq rem-enc (nth 1 ritem))
4429 (setq rem-dec (nth 2 ritem))
4430 (setq found t)))))))
4431
4432 (when found
4433 ;; Set connection properties. Since the commands are risky
4434 ;; (due to output direction), we cache them in the process cache.
4435 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
4436 (tramp-set-connection-property p "local-encoding" loc-enc)
4437 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
4438 (tramp-set-connection-property p "local-decoding" loc-dec)
4439 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
4440 (tramp-set-connection-property p "remote-encoding" rem-enc)
4441 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
4442 (tramp-set-connection-property p "remote-decoding" rem-dec)))))
4443
4444 (defun tramp-call-local-coding-command (cmd input output)
4445 "Call the local encoding or decoding command.
4446 If CMD contains \"%s\", provide input file INPUT there in command.
4447 Otherwise, INPUT is passed via standard input.
4448 INPUT can also be nil which means `/dev/null'.
4449 OUTPUT can be a string (which specifies a file name), or t (which
4450 means standard output and thus the current buffer), or nil (which
4451 means discard it)."
4452 (tramp-call-process
4453 nil tramp-encoding-shell
4454 (when (and input (not (string-match "%s" cmd))) input)
4455 (if (eq output t) t nil)
4456 nil
4457 tramp-encoding-command-switch
4458 (concat
4459 (if (string-match "%s" cmd) (format cmd input) cmd)
4460 (if (stringp output) (concat " >" output) ""))))
4461
4462 (defconst tramp-inline-compress-commands
4463 '(("gzip" "gzip -d")
4464 ("bzip2" "bzip2 -d")
4465 ("xz" "xz -d")
4466 ("compress" "compress -d"))
4467 "List of compress and decompress commands for inline transfer.
4468 Each item is a list that looks like this:
4469
4470 \(COMPRESS DECOMPRESS)
4471
4472 COMPRESS or DECOMPRESS are strings with the respective commands.")
4473
4474 (defun tramp-find-inline-compress (vec)
4475 "Find an inline transfer compress command that works.
4476 Goes through the list `tramp-inline-compress-commands'."
4477 (save-excursion
4478 (let ((commands tramp-inline-compress-commands)
4479 (magic "xyzzy")
4480 (p (tramp-get-connection-process vec))
4481 item compress decompress found)
4482 (while (and commands (not found))
4483 (catch 'next
4484 (setq item (pop commands)
4485 compress (nth 0 item)
4486 decompress (nth 1 item))
4487 (tramp-message
4488 vec 5
4489 "Checking local compress commands `%s', `%s' for sanity"
4490 compress decompress)
4491 (unless
4492 (zerop
4493 (tramp-call-local-coding-command
4494 (format
4495 ;; Windows shells need the program file name after
4496 ;; the pipe symbol be quoted if they use forward
4497 ;; slashes as directory separators.
4498 (if (memq system-type '(windows-nt))
4499 "echo %s | \"%s\" | \"%s\""
4500 "echo %s | %s | %s")
4501 magic compress decompress) nil nil))
4502 (throw 'next nil))
4503 (tramp-message
4504 vec 5
4505 "Checking remote compress commands `%s', `%s' for sanity"
4506 compress decompress)
4507 (unless (tramp-send-command-and-check
4508 vec (format "echo %s | %s | %s" magic compress decompress) t)
4509 (throw 'next nil))
4510 (setq found t)))
4511
4512 ;; Did we find something?
4513 (if found
4514 (progn
4515 ;; Set connection properties. Since the commands are
4516 ;; risky (due to output direction), we cache them in the
4517 ;; process cache.
4518 (tramp-message
4519 vec 5 "Using inline transfer compress command `%s'" compress)
4520 (tramp-set-connection-property p "inline-compress" compress)
4521 (tramp-message
4522 vec 5 "Using inline transfer decompress command `%s'" decompress)
4523 (tramp-set-connection-property p "inline-decompress" decompress))
4524
4525 (tramp-set-connection-property p "inline-compress" nil)
4526 (tramp-set-connection-property p "inline-decompress" nil)
4527 (tramp-message
4528 vec 2 "Couldn't find an inline transfer compress command")))))
4529
4530 (defun tramp-compute-multi-hops (vec)
4531 "Expands VEC according to `tramp-default-proxies-alist'.
4532 Gateway hops are already opened."
4533 (let ((target-alist `(,vec))
4534 (hops (or (tramp-file-name-hop vec) ""))
4535 (item vec)
4536 choices proxy)
4537
4538 ;; Ad-hoc proxy definitions.
4539 (dolist (proxy (reverse (split-string hops tramp-postfix-hop-regexp 'omit)))
4540 (let ((user (tramp-file-name-user item))
4541 (host (tramp-file-name-host item))
4542 (proxy (concat
4543 tramp-prefix-format proxy tramp-postfix-host-format)))
4544 (tramp-message
4545 vec 5 "Add proxy (\"%s\" \"%s\" \"%s\")"
4546 (and (stringp host) (regexp-quote host))
4547 (and (stringp user) (regexp-quote user))
4548 proxy)
4549 ;; Add the hop.
4550 (add-to-list
4551 'tramp-default-proxies-alist
4552 (list (and (stringp host) (regexp-quote host))
4553 (and (stringp user) (regexp-quote user))
4554 proxy))
4555 (setq item (tramp-dissect-file-name proxy))))
4556 ;; Save the new value.
4557 (when (and hops tramp-save-ad-hoc-proxies)
4558 (customize-save-variable
4559 'tramp-default-proxies-alist tramp-default-proxies-alist))
4560
4561 ;; Look for proxy hosts to be passed.
4562 (setq choices tramp-default-proxies-alist)
4563 (while choices
4564 (setq item (pop choices)
4565 proxy (eval (nth 2 item)))
4566 (when (and
4567 ;; Host.
4568 (string-match (or (eval (nth 0 item)) "")
4569 (or (tramp-file-name-host (car target-alist)) ""))
4570 ;; User.
4571 (string-match (or (eval (nth 1 item)) "")
4572 (or (tramp-file-name-user (car target-alist)) "")))
4573 (if (null proxy)
4574 ;; No more hops needed.
4575 (setq choices nil)
4576 ;; Replace placeholders.
4577 (setq proxy
4578 (format-spec
4579 proxy
4580 (format-spec-make
4581 ?u (or (tramp-file-name-user (car target-alist)) "")
4582 ?h (or (tramp-file-name-host (car target-alist)) ""))))
4583 (with-parsed-tramp-file-name proxy l
4584 ;; Add the hop.
4585 (push l target-alist)
4586 ;; Start next search.
4587 (setq choices tramp-default-proxies-alist)))))
4588
4589 ;; Handle gateways.
4590 (when (and (boundp 'tramp-gw-tunnel-method) (boundp 'tramp-gw-socks-method)
4591 (string-match
4592 (format
4593 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
4594 (tramp-file-name-method (car target-alist))))
4595 (let ((gw (pop target-alist))
4596 (hop (pop target-alist)))
4597 ;; Is the method prepared for gateways?
4598 (unless (tramp-file-name-port hop)
4599 (tramp-error
4600 vec 'file-error
4601 "Connection `%s' is not supported for gateway access." hop))
4602 ;; Open the gateway connection.
4603 (push
4604 (vector
4605 (tramp-file-name-method hop) (tramp-file-name-user hop)
4606 (tramp-gw-open-connection vec gw hop) nil nil)
4607 target-alist)
4608 ;; For the password prompt, we need the correct values.
4609 ;; Therefore, we must remember the gateway vector. But we
4610 ;; cannot do it as connection property, because it shouldn't
4611 ;; be persistent. And we have no started process yet either.
4612 (let ((tramp-verbose 0))
4613 (tramp-set-file-property (car target-alist) "" "gateway" hop))))
4614
4615 ;; Foreign and out-of-band methods are not supported for multi-hops.
4616 (when (cdr target-alist)
4617 (setq choices target-alist)
4618 (while (setq item (pop choices))
4619 (when (or (not (tramp-get-method-parameter item 'tramp-login-program))
4620 (tramp-get-method-parameter item 'tramp-copy-program))
4621 (tramp-error
4622 vec 'file-error
4623 "Method `%s' is not supported for multi-hops."
4624 (tramp-file-name-method item)))))
4625
4626 ;; In case the host name is not used for the remote shell
4627 ;; command, the user could be misguided by applying a random
4628 ;; host name.
4629 (let* ((v (car target-alist))
4630 (method (tramp-file-name-method v))
4631 (host (tramp-file-name-host v)))
4632 (unless
4633 (or
4634 ;; There are multi-hops.
4635 (cdr target-alist)
4636 ;; The host name is used for the remote shell command.
4637 (member '("%h") (tramp-get-method-parameter v 'tramp-login-args))
4638 ;; The host is local. We cannot use `tramp-local-host-p'
4639 ;; here, because it opens a connection as well.
4640 (string-match tramp-local-host-regexp host))
4641 (tramp-error
4642 v 'file-error
4643 "Host `%s' looks like a remote host, `%s' can only use the local host"
4644 host method)))
4645
4646 ;; Result.
4647 target-alist))
4648
4649 (defun tramp-ssh-controlmaster-options (vec)
4650 "Return the Control* arguments of the local ssh."
4651 (cond
4652 ;; No options to be computed.
4653 ((or (null tramp-use-ssh-controlmaster-options)
4654 (null (assoc "%c" (tramp-get-method-parameter vec 'tramp-login-args))))
4655 "")
4656
4657 ;; There is already a value to be used.
4658 ((stringp tramp-ssh-controlmaster-options) tramp-ssh-controlmaster-options)
4659
4660 ;; Determine the options.
4661 (t (setq tramp-ssh-controlmaster-options "")
4662 (let ((case-fold-search t))
4663 (ignore-errors
4664 (when (executable-find "ssh")
4665 (with-temp-buffer
4666 (tramp-call-process vec "ssh" nil t nil "-o" "ControlMaster")
4667 (goto-char (point-min))
4668 (when (search-forward-regexp "missing.+argument" nil t)
4669 (setq tramp-ssh-controlmaster-options "-o ControlMaster=auto")))
4670 (unless (zerop (length tramp-ssh-controlmaster-options))
4671 (with-temp-buffer
4672 ;; We use a non-existing IP address, in order to avoid
4673 ;; useless connections, and DNS timeouts.
4674 (tramp-call-process
4675 vec "ssh" nil t nil "-o" "ControlPath=%C" "0.0.0.1")
4676 (goto-char (point-min))
4677 (setq tramp-ssh-controlmaster-options
4678 (concat tramp-ssh-controlmaster-options
4679 (if (search-forward-regexp "unknown.+key" nil t)
4680 " -o ControlPath='tramp.%%r@%%h:%%p'"
4681 " -o ControlPath='tramp.%%C'"))))
4682 (with-temp-buffer
4683 (tramp-call-process vec "ssh" nil t nil "-o" "ControlPersist")
4684 (goto-char (point-min))
4685 (when (search-forward-regexp "missing.+argument" nil t)
4686 (setq tramp-ssh-controlmaster-options
4687 (concat tramp-ssh-controlmaster-options
4688 " -o ControlPersist=no"))))))))
4689 tramp-ssh-controlmaster-options)))
4690
4691 (defun tramp-maybe-open-connection (vec)
4692 "Maybe open a connection VEC.
4693 Does not do anything if a connection is already open, but re-opens the
4694 connection if a previous connection has died for some reason."
4695 (tramp-check-proper-method-and-host vec)
4696
4697 (let ((p (tramp-get-connection-process vec))
4698 (process-name (tramp-get-connection-property vec "process-name" nil))
4699 (process-environment (copy-sequence process-environment))
4700 (pos (with-current-buffer (tramp-get-connection-buffer vec) (point))))
4701
4702 ;; If Tramp opens the same connection within a short time frame,
4703 ;; there is a problem. We shall signal this.
4704 (unless (or (and p (processp p) (memq (process-status p) '(run open)))
4705 (not (equal (butlast (append vec nil) 2)
4706 (car tramp-current-connection)))
4707 (> (tramp-time-diff
4708 (current-time) (cdr tramp-current-connection))
4709 (or tramp-connection-min-time-diff 0)))
4710 (throw 'suppress 'suppress))
4711
4712 ;; If too much time has passed since last command was sent, look
4713 ;; whether process is still alive. If it isn't, kill it. When
4714 ;; using ssh, it can sometimes happen that the remote end has hung
4715 ;; up but the local ssh client doesn't recognize this until it
4716 ;; tries to send some data to the remote end. So that's why we
4717 ;; try to send a command from time to time, then look again
4718 ;; whether the process is really alive.
4719 (condition-case nil
4720 (when (and (> (tramp-time-diff
4721 (current-time)
4722 (tramp-get-connection-property
4723 p "last-cmd-time" '(0 0 0)))
4724 60)
4725 p (processp p) (memq (process-status p) '(run open)))
4726 (tramp-send-command vec "echo are you awake" t t)
4727 (unless (and (memq (process-status p) '(run open))
4728 (tramp-wait-for-output p 10))
4729 ;; The error will be caught locally.
4730 (tramp-error vec 'file-error "Awake did fail")))
4731 (file-error
4732 (tramp-cleanup-connection vec t)
4733 (setq p nil)))
4734
4735 ;; New connection must be opened.
4736 (condition-case err
4737 (unless (and p (processp p) (memq (process-status p) '(run open)))
4738
4739 ;; If `non-essential' is non-nil, don't reopen a new connection.
4740 ;; This variable has been introduced with Emacs 24.1.
4741 (when (and (boundp 'non-essential) (symbol-value 'non-essential))
4742 (throw 'non-essential 'non-essential))
4743
4744 (with-tramp-progress-reporter
4745 vec 3
4746 (if (zerop (length (tramp-file-name-user vec)))
4747 (format "Opening connection for %s using %s"
4748 (tramp-file-name-host vec)
4749 (tramp-file-name-method vec))
4750 (format "Opening connection for %s@%s using %s"
4751 (tramp-file-name-user vec)
4752 (tramp-file-name-host vec)
4753 (tramp-file-name-method vec)))
4754
4755 (catch 'uname-changed
4756 ;; Start new process.
4757 (when (and p (processp p))
4758 (delete-process p))
4759 (setenv "TERM" tramp-terminal-type)
4760 (setenv "LC_ALL" "en_US.utf8")
4761 (if (stringp tramp-histfile-override)
4762 (setenv "HISTFILE" tramp-histfile-override)
4763 (if tramp-histfile-override
4764 (progn
4765 (setenv "HISTFILE")
4766 (setenv "HISTFILESIZE" "0")
4767 (setenv "HISTSIZE" "0"))))
4768 (setenv "PROMPT_COMMAND")
4769 (setenv "PS1" tramp-initial-end-of-output)
4770 (let* ((target-alist (tramp-compute-multi-hops vec))
4771 ;; We will apply `tramp-ssh-controlmaster-options'
4772 ;; only for the first hop.
4773 (options (tramp-ssh-controlmaster-options vec))
4774 (process-connection-type tramp-process-connection-type)
4775 (process-adaptive-read-buffering nil)
4776 (coding-system-for-read nil)
4777 ;; This must be done in order to avoid our file
4778 ;; name handler.
4779 (p (let ((default-directory
4780 (tramp-compat-temporary-file-directory)))
4781 (apply
4782 'start-process
4783 (tramp-get-connection-name vec)
4784 (tramp-get-connection-buffer vec)
4785 (if tramp-encoding-command-interactive
4786 (list tramp-encoding-shell
4787 tramp-encoding-command-interactive)
4788 (list tramp-encoding-shell))))))
4789
4790 ;; Set sentinel and query flag.
4791 (tramp-set-connection-property p "vector" vec)
4792 (set-process-sentinel p 'tramp-process-sentinel)
4793 (set-process-query-on-exit-flag p nil)
4794 (setq tramp-current-connection
4795 (cons (butlast (append vec nil) 2) (current-time))
4796 tramp-current-host (system-name))
4797
4798 (tramp-message
4799 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
4800
4801 ;; Check whether process is alive.
4802 (tramp-barf-if-no-shell-prompt
4803 p 10
4804 "Couldn't find local shell prompt for %s" tramp-encoding-shell)
4805
4806 ;; Now do all the connections as specified.
4807 (while target-alist
4808 (let* ((hop (car target-alist))
4809 (l-method (tramp-file-name-method hop))
4810 (l-user (tramp-file-name-user hop))
4811 (l-host (tramp-file-name-host hop))
4812 (l-port nil)
4813 (login-program
4814 (tramp-get-method-parameter hop 'tramp-login-program))
4815 (login-args
4816 (tramp-get-method-parameter hop 'tramp-login-args))
4817 (login-env
4818 (tramp-get-method-parameter hop 'tramp-login-env))
4819 (async-args
4820 (tramp-get-method-parameter hop 'tramp-async-args))
4821 (connection-timeout
4822 (tramp-get-method-parameter
4823 hop 'tramp-connection-timeout))
4824 (gw-args
4825 (tramp-get-method-parameter hop 'tramp-gw-args))
4826 (gw (let ((tramp-verbose 0))
4827 (tramp-get-file-property hop "" "gateway" nil)))
4828 (g-method (and gw (tramp-file-name-method gw)))
4829 (g-user (and gw (tramp-file-name-user gw)))
4830 (g-host (and gw (tramp-file-name-real-host gw)))
4831 (command login-program)
4832 ;; We don't create the temporary file. In
4833 ;; fact, it is just a prefix for the
4834 ;; ControlPath option of ssh; the real
4835 ;; temporary file has another name, and it is
4836 ;; created and protected by ssh. It is also
4837 ;; removed by ssh when the connection is
4838 ;; closed. The temporary file name is cached
4839 ;; in the main connection process, therefore
4840 ;; we cannot use `tramp-get-connection-process'.
4841 (tmpfile
4842 (with-tramp-connection-property
4843 (get-process (tramp-buffer-name vec)) "temp-file"
4844 (make-temp-name
4845 (expand-file-name
4846 tramp-temp-name-prefix
4847 (tramp-compat-temporary-file-directory)))))
4848 spec r-shell)
4849
4850 ;; Add arguments for asynchronous processes.
4851 (when (and process-name async-args)
4852 (setq login-args (append async-args login-args)))
4853
4854 ;; Add gateway arguments if necessary.
4855 (when gw
4856 (tramp-set-connection-property p "gateway" t)
4857 (when gw-args
4858 (setq login-args (append gw-args login-args))))
4859
4860 ;; Check for port number. Until now, there's no
4861 ;; need for handling like method, user, host.
4862 (when (string-match tramp-host-with-port-regexp l-host)
4863 (setq l-port (match-string 2 l-host)
4864 l-host (match-string 1 l-host)))
4865
4866 ;; Check, whether there is a restricted shell.
4867 (dolist (elt tramp-restricted-shell-hosts-alist)
4868 (when (string-match elt tramp-current-host)
4869 (setq r-shell t)))
4870
4871 ;; Set variables for computing the prompt for
4872 ;; reading password. They can also be derived
4873 ;; from a gateway.
4874 (setq tramp-current-method (or g-method l-method)
4875 tramp-current-user (or g-user l-user)
4876 tramp-current-host (or g-host l-host))
4877
4878 ;; Add login environment.
4879 (when login-env
4880 (setq
4881 login-env
4882 (mapcar
4883 (lambda (x)
4884 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4885 (unless (member "" x) (mapconcat 'identity x " ")))
4886 login-env))
4887 (while login-env
4888 (setq command
4889 (format
4890 "%s=%s %s"
4891 (pop login-env)
4892 (tramp-shell-quote-argument (pop login-env))
4893 command)))
4894 (setq command (concat "env " command)))
4895
4896 ;; Replace `login-args' place holders.
4897 (setq
4898 l-host (or l-host "")
4899 l-user (or l-user "")
4900 l-port (or l-port "")
4901 spec (format-spec-make ?t tmpfile)
4902 options (format-spec options spec)
4903 spec (format-spec-make
4904 ?h l-host ?u l-user ?p l-port ?c options)
4905 command
4906 (concat
4907 ;; We do not want to see the trailing local
4908 ;; prompt in `start-file-process'.
4909 (unless r-shell "exec ")
4910 command " "
4911 (mapconcat
4912 (lambda (x)
4913 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4914 (unless (member "" x) (mapconcat 'identity x " ")))
4915 login-args " ")
4916 ;; Local shell could be a Windows COMSPEC. It
4917 ;; doesn't know the ";" syntax, but we must exit
4918 ;; always for `start-file-process'. It could
4919 ;; also be a restricted shell, which does not
4920 ;; allow "exec".
4921 (when r-shell " && exit || exit")))
4922
4923 ;; Send the command.
4924 (tramp-message vec 3 "Sending command `%s'" command)
4925 (tramp-send-command vec command t t)
4926 (tramp-process-actions
4927 p vec pos tramp-actions-before-shell
4928 (or connection-timeout tramp-connection-timeout))
4929 (tramp-message
4930 vec 3 "Found remote shell prompt on `%s'" l-host))
4931 ;; Next hop.
4932 (setq options ""
4933 target-alist (cdr target-alist)))
4934
4935 ;; Make initial shell settings.
4936 (tramp-open-connection-setup-interactive-shell p vec)))))
4937
4938 ;; When the user did interrupt, we must cleanup.
4939 (quit
4940 (tramp-cleanup-connection vec t)
4941 ;; Propagate the quit signal.
4942 (signal (car err) (cdr err))))))
4943
4944 (defun tramp-send-command (vec command &optional neveropen nooutput)
4945 "Send the COMMAND to connection VEC.
4946 Erases temporary buffer before sending the command. If optional
4947 arg NEVEROPEN is non-nil, never try to open the connection. This
4948 is meant to be used from `tramp-maybe-open-connection' only. The
4949 function waits for output unless NOOUTPUT is set."
4950 (unless neveropen (tramp-maybe-open-connection vec))
4951 (let ((p (tramp-get-connection-process vec)))
4952 (when (tramp-get-connection-property p "remote-echo" nil)
4953 ;; We mark the command string that it can be erased in the output buffer.
4954 (tramp-set-connection-property p "check-remote-echo" t)
4955 ;; If we put `tramp-echo-mark' after a trailing newline (which
4956 ;; is assumed to be unquoted) `tramp-send-string' doesn't see
4957 ;; that newline and adds `tramp-rsh-end-of-line' right after
4958 ;; `tramp-echo-mark', so the remote shell sees two consecutive
4959 ;; trailing line endings and sends two prompts after executing
4960 ;; the command, which confuses `tramp-wait-for-output'.
4961 (when (and (not (string= command ""))
4962 (string-equal (substring command -1) "\n"))
4963 (setq command (substring command 0 -1)))
4964 ;; No need to restore a trailing newline here since `tramp-send-string'
4965 ;; makes sure that the string ends in `tramp-rsh-end-of-line', anyway.
4966 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
4967 ;; Send the command.
4968 (tramp-message vec 6 "%s" command)
4969 (tramp-send-string vec command)
4970 (unless nooutput (tramp-wait-for-output p))))
4971
4972 (defun tramp-wait-for-output (proc &optional timeout)
4973 "Wait for output from remote command."
4974 (unless (buffer-live-p (process-buffer proc))
4975 (delete-process proc)
4976 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
4977 (with-current-buffer (process-buffer proc)
4978 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
4979 ;; be leading escape sequences, which must be ignored.
4980 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
4981 ;; Sometimes, the commands do not return a newline but a
4982 ;; null byte before the shell prompt, for example "git
4983 ;; ls-files -c -z ...".
4984 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
4985 (found (tramp-wait-for-regexp proc timeout regexp1)))
4986 (if found
4987 (let (buffer-read-only)
4988 ;; A simple-minded busybox has sent " ^H" sequences.
4989 ;; Delete them.
4990 (goto-char (point-min))
4991 (when (re-search-forward "^\\(.\b\\)+$" (point-at-eol) t)
4992 (forward-line 1)
4993 (delete-region (point-min) (point)))
4994 ;; Delete the prompt.
4995 (goto-char (point-max))
4996 (re-search-backward regexp nil t)
4997 (delete-region (point) (point-max)))
4998 (if timeout
4999 (tramp-error
5000 proc 'file-error
5001 "[[Remote prompt `%s' not found in %d secs]]"
5002 tramp-end-of-output timeout)
5003 (tramp-error
5004 proc 'file-error
5005 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
5006 ;; Return value is whether end-of-output sentinel was found.
5007 found)))
5008
5009 (defun tramp-send-command-and-check
5010 (vec command &optional subshell dont-suppress-err)
5011 "Run COMMAND and check its exit status.
5012 Sends `echo $?' along with the COMMAND for checking the exit status.
5013 If COMMAND is nil, just sends `echo $?'. Returns t if the exit
5014 status is 0, and nil otherwise.
5015
5016 If the optional argument SUBSHELL is non-nil, the command is
5017 executed in a subshell, ie surrounded by parentheses. If
5018 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
5019 (tramp-send-command
5020 vec
5021 (concat (if subshell "( " "")
5022 command
5023 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
5024 "echo tramp_exit_status $?"
5025 (if subshell " )" "")))
5026 (with-current-buffer (tramp-get-connection-buffer vec)
5027 (goto-char (point-max))
5028 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
5029 (tramp-error
5030 vec 'file-error "Couldn't find exit status of `%s'" command))
5031 (skip-chars-forward "^ ")
5032 (prog1
5033 (zerop (read (current-buffer)))
5034 (let (buffer-read-only)
5035 (delete-region (match-beginning 0) (point-max))))))
5036
5037 (defun tramp-barf-unless-okay (vec command fmt &rest args)
5038 "Run COMMAND, check exit status, throw error if exit status not okay.
5039 Similar to `tramp-send-command-and-check' but accepts two more arguments
5040 FMT and ARGS which are passed to `error'."
5041 (or (tramp-send-command-and-check vec command)
5042 (apply 'tramp-error vec 'file-error fmt args)))
5043
5044 (defun tramp-send-command-and-read (vec command &optional noerror marker)
5045 "Run COMMAND and return the output, which must be a Lisp expression.
5046 If MARKER is a regexp, read the output after that string.
5047 In case there is no valid Lisp expression and NOERROR is nil, it
5048 raises an error."
5049 (when (if noerror
5050 (tramp-send-command-and-check vec command)
5051 (tramp-barf-unless-okay
5052 vec command "`%s' returns with error" command))
5053 (with-current-buffer (tramp-get-connection-buffer vec)
5054 (goto-char (point-min))
5055 ;; Read the marker.
5056 (when (stringp marker)
5057 (condition-case nil
5058 (re-search-forward marker)
5059 (error (unless noerror
5060 (tramp-error
5061 vec 'file-error
5062 "`%s' does not return the marker `%s': `%s'"
5063 command marker (buffer-string))))))
5064 ;; Read the expression.
5065 (condition-case nil
5066 (prog1 (read (current-buffer))
5067 ;; Error handling.
5068 (when (re-search-forward "\\S-" (point-at-eol) t)
5069 (error nil)))
5070 (error (unless noerror
5071 (tramp-error
5072 vec 'file-error
5073 "`%s' does not return a valid Lisp expression: `%s'"
5074 command (buffer-string))))))))
5075
5076 (defun tramp-convert-file-attributes (vec attr)
5077 "Convert `file-attributes' ATTR generated by perl script, stat or ls.
5078 Convert file mode bits to string and set virtual device number.
5079 Return ATTR."
5080 (when attr
5081 ;; Remove color escape sequences from symlink.
5082 (when (stringp (car attr))
5083 (while (string-match tramp-color-escape-sequence-regexp (car attr))
5084 (setcar attr (replace-match "" nil nil (car attr)))))
5085 ;; Convert uid and gid. Use -1 as indication of unusable value.
5086 (when (and (numberp (nth 2 attr)) (< (nth 2 attr) 0))
5087 (setcar (nthcdr 2 attr) -1))
5088 (when (and (floatp (nth 2 attr))
5089 (<= (nth 2 attr) most-positive-fixnum))
5090 (setcar (nthcdr 2 attr) (round (nth 2 attr))))
5091 (when (and (numberp (nth 3 attr)) (< (nth 3 attr) 0))
5092 (setcar (nthcdr 3 attr) -1))
5093 (when (and (floatp (nth 3 attr))
5094 (<= (nth 3 attr) most-positive-fixnum))
5095 (setcar (nthcdr 3 attr) (round (nth 3 attr))))
5096 ;; Convert last access time.
5097 (unless (listp (nth 4 attr))
5098 (setcar (nthcdr 4 attr)
5099 (list (floor (nth 4 attr) 65536)
5100 (floor (mod (nth 4 attr) 65536)))))
5101 ;; Convert last modification time.
5102 (unless (listp (nth 5 attr))
5103 (setcar (nthcdr 5 attr)
5104 (list (floor (nth 5 attr) 65536)
5105 (floor (mod (nth 5 attr) 65536)))))
5106 ;; Convert last status change time.
5107 (unless (listp (nth 6 attr))
5108 (setcar (nthcdr 6 attr)
5109 (list (floor (nth 6 attr) 65536)
5110 (floor (mod (nth 6 attr) 65536)))))
5111 ;; Convert file size.
5112 (when (< (nth 7 attr) 0)
5113 (setcar (nthcdr 7 attr) -1))
5114 (when (and (floatp (nth 7 attr))
5115 (<= (nth 7 attr) most-positive-fixnum))
5116 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
5117 ;; Convert file mode bits to string.
5118 (unless (stringp (nth 8 attr))
5119 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
5120 (when (stringp (car attr))
5121 (aset (nth 8 attr) 0 ?l)))
5122 ;; Convert directory indication bit.
5123 (when (string-match "^d" (nth 8 attr))
5124 (setcar attr t))
5125 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
5126 (when (consp (car attr))
5127 (if (and (stringp (caar attr))
5128 (string-match ".+ -> .\\(.+\\)." (caar attr)))
5129 (setcar attr (match-string 1 (caar attr)))
5130 (setcar attr nil)))
5131 ;; Set file's gid change bit.
5132 (setcar (nthcdr 9 attr)
5133 (if (numberp (nth 3 attr))
5134 (not (= (nth 3 attr)
5135 (tramp-get-remote-gid vec 'integer)))
5136 (not (string-equal
5137 (nth 3 attr)
5138 (tramp-get-remote-gid vec 'string)))))
5139 ;; Convert inode.
5140 (unless (listp (nth 10 attr))
5141 (setcar (nthcdr 10 attr)
5142 (condition-case nil
5143 (cons (floor (nth 10 attr) 65536)
5144 (floor (mod (nth 10 attr) 65536)))
5145 ;; Inodes can be incredible huge. We must hide this.
5146 (error (tramp-get-inode vec)))))
5147 ;; Set virtual device number.
5148 (setcar (nthcdr 11 attr)
5149 (tramp-get-device vec))
5150 attr))
5151
5152 (defun tramp-shell-case-fold (string)
5153 "Converts STRING to shell glob pattern which ignores case."
5154 (mapconcat
5155 (lambda (c)
5156 (if (equal (downcase c) (upcase c))
5157 (vector c)
5158 (format "[%c%c]" (downcase c) (upcase c))))
5159 string
5160 ""))
5161
5162 (defun tramp-make-copy-program-file-name (vec)
5163 "Create a file name suitable for `scp', `pscp', or `nc' and workalikes."
5164 (let ((method (tramp-file-name-method vec))
5165 (user (tramp-file-name-user vec))
5166 (host (tramp-file-name-real-host vec))
5167 (localname (tramp-file-name-localname vec)))
5168 (when (string-match tramp-ipv6-regexp host)
5169 (setq host (format "[%s]" host)))
5170 (unless (string-match "ftp$" method)
5171 (setq localname (tramp-shell-quote-argument localname)))
5172 (cond
5173 ((tramp-get-method-parameter vec 'tramp-remote-copy-program)
5174 localname)
5175 ((not (zerop (length user)))
5176 (shell-quote-argument (format "%s@%s:%s" user host localname)))
5177 (t (shell-quote-argument (format "%s:%s" host localname))))))
5178
5179 (defun tramp-method-out-of-band-p (vec size)
5180 "Return t if this is an out-of-band method, nil otherwise."
5181 (and
5182 ;; It shall be an out-of-band method.
5183 (tramp-get-method-parameter vec 'tramp-copy-program)
5184 ;; There must be a size, otherwise the file doesn't exist.
5185 (numberp size)
5186 ;; Either the file size is large enough, or (in rare cases) there
5187 ;; does not exist a remote encoding.
5188 (or (null tramp-copy-size-limit)
5189 (> size tramp-copy-size-limit)
5190 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
5191
5192 ;; Variables local to connection.
5193
5194 (defun tramp-get-remote-path (vec)
5195 (with-tramp-connection-property
5196 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
5197 ;; cache the result for the session only. Otherwise, the result
5198 ;; is cached persistently.
5199 (if (memq 'tramp-own-remote-path tramp-remote-path)
5200 (tramp-get-connection-process vec)
5201 vec)
5202 "remote-path"
5203 (let* ((remote-path (copy-tree tramp-remote-path))
5204 (elt1 (memq 'tramp-default-remote-path remote-path))
5205 (elt2 (memq 'tramp-own-remote-path remote-path))
5206 (default-remote-path
5207 (when elt1
5208 (or
5209 (tramp-send-command-and-read
5210 vec "echo \\\"`getconf PATH 2>/dev/null`\\\"" 'noerror)
5211 ;; Default if "getconf" is not available.
5212 (progn
5213 (tramp-message
5214 vec 3
5215 "`getconf PATH' not successful, using default value \"%s\"."
5216 "/bin:/usr/bin")
5217 "/bin:/usr/bin"))))
5218 (own-remote-path
5219 ;; The login shell could return more than just the $PATH
5220 ;; string. So we use `tramp-end-of-heredoc' as marker.
5221 (when elt2
5222 (or
5223 (tramp-send-command-and-read
5224 vec
5225 (format
5226 "%s %s %s 'echo %s \\\"$PATH\\\"'"
5227 (tramp-get-method-parameter vec 'tramp-remote-shell)
5228 (mapconcat
5229 'identity
5230 (tramp-get-method-parameter vec 'tramp-remote-shell-login)
5231 " ")
5232 (mapconcat
5233 'identity
5234 (tramp-get-method-parameter vec 'tramp-remote-shell-args)
5235 " ")
5236 (tramp-shell-quote-argument tramp-end-of-heredoc))
5237 'noerror (regexp-quote tramp-end-of-heredoc))
5238 (progn
5239 (tramp-message
5240 vec 2 "Could not retrieve `tramp-own-remote-path'")
5241 nil)))))
5242
5243 ;; Replace place holder `tramp-default-remote-path'.
5244 (when elt1
5245 (setcdr elt1
5246 (append
5247 (split-string (or default-remote-path "") ":" 'omit)
5248 (cdr elt1)))
5249 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
5250
5251 ;; Replace place holder `tramp-own-remote-path'.
5252 (when elt2
5253 (setcdr elt2
5254 (append
5255 (split-string (or own-remote-path "") ":" 'omit)
5256 (cdr elt2)))
5257 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
5258
5259 ;; Remove double entries.
5260 (setq elt1 remote-path)
5261 (while (consp elt1)
5262 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
5263 (setcar elt2 nil))
5264 (setq elt1 (cdr elt1)))
5265
5266 ;; Remove non-existing directories.
5267 (delq
5268 nil
5269 (mapcar
5270 (lambda (x)
5271 (and
5272 (stringp x)
5273 (file-directory-p
5274 (tramp-make-tramp-file-name
5275 (tramp-file-name-method vec)
5276 (tramp-file-name-user vec)
5277 (tramp-file-name-host vec)
5278 x))
5279 x))
5280 remote-path)))))
5281
5282 (defun tramp-get-remote-locale (vec)
5283 (with-tramp-connection-property vec "locale"
5284 (tramp-send-command vec "locale -a")
5285 (let ((candidates '("en_US.utf8" "C.utf8" "en_US.UTF-8"))
5286 locale)
5287 (with-current-buffer (tramp-get-connection-buffer vec)
5288 (while candidates
5289 (goto-char (point-min))
5290 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
5291 (buffer-string))
5292 (setq locale (car candidates)
5293 candidates nil)
5294 (setq candidates (cdr candidates)))))
5295 ;; Return value.
5296 (format "LC_ALL=%s" (or locale "C")))))
5297
5298 (defun tramp-get-ls-command (vec)
5299 (with-tramp-connection-property vec "ls"
5300 (tramp-message vec 5 "Finding a suitable `ls' command")
5301 (or
5302 (catch 'ls-found
5303 (dolist (cmd '("ls" "gnuls" "gls"))
5304 (let ((dl (tramp-get-remote-path vec))
5305 result)
5306 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5307 ;; Check parameters. On busybox, "ls" output coloring is
5308 ;; enabled by default sometimes. So we try to disable it
5309 ;; when possible. $LS_COLORING is not supported there.
5310 ;; Some "ls" versions are sensible wrt the order of
5311 ;; arguments, they fail when "-al" is after the
5312 ;; "--color=never" argument (for example on FreeBSD).
5313 (when (tramp-send-command-and-check
5314 vec (format "%s -lnd /" result))
5315 (when (tramp-send-command-and-check
5316 vec (format
5317 "%s --color=never -al /dev/null" result))
5318 (setq result (concat result " --color=never")))
5319 (throw 'ls-found result))
5320 (setq dl (cdr dl))))))
5321 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
5322
5323 (defun tramp-get-ls-command-with-dired (vec)
5324 (save-match-data
5325 (with-tramp-connection-property vec "ls-dired"
5326 (tramp-message vec 5 "Checking, whether `ls --dired' works")
5327 ;; Some "ls" versions are sensible wrt the order of arguments,
5328 ;; they fail when "-al" is after the "--dired" argument (for
5329 ;; example on FreeBSD).
5330 (tramp-send-command-and-check
5331 vec (format "%s --dired -al /dev/null" (tramp-get-ls-command vec))))))
5332
5333 (defun tramp-get-ls-command-with-quoting-style (vec)
5334 (save-match-data
5335 (with-tramp-connection-property vec "ls-quoting-style"
5336 (tramp-message vec 5 "Checking, whether `ls --quoting-style=shell' works")
5337 (tramp-send-command-and-check
5338 vec (format "%s --quoting-style=shell -al /dev/null"
5339 (tramp-get-ls-command vec))))))
5340
5341 (defun tramp-get-ls-command-with-w-option (vec)
5342 (save-match-data
5343 (with-tramp-connection-property vec "ls-w-option"
5344 (tramp-message vec 5 "Checking, whether `ls -w' works")
5345 ;; Option "-w" is available on BSD systems. No argument is
5346 ;; given, because this could return wrong results in case "ls"
5347 ;; supports the "-w NUM" argument, as for busyboxes.
5348 (tramp-send-command-and-check
5349 vec (format "%s -alw" (tramp-get-ls-command vec))))))
5350
5351 (defun tramp-get-test-command (vec)
5352 (with-tramp-connection-property vec "test"
5353 (tramp-message vec 5 "Finding a suitable `test' command")
5354 (if (tramp-send-command-and-check vec "test 0")
5355 "test"
5356 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
5357
5358 (defun tramp-get-test-nt-command (vec)
5359 ;; Does `test A -nt B' work? Use abominable `find' construct if it
5360 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
5361 ;; for otherwise the shell crashes.
5362 (with-tramp-connection-property vec "test-nt"
5363 (or
5364 (progn
5365 (tramp-send-command
5366 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
5367 (with-current-buffer (tramp-get-buffer vec)
5368 (goto-char (point-min))
5369 (when (looking-at (regexp-quote tramp-end-of-output))
5370 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
5371 (progn
5372 (tramp-send-command
5373 vec
5374 (format
5375 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
5376 (tramp-get-test-command vec)))
5377 "tramp_test_nt %s %s"))))
5378
5379 (defun tramp-get-file-exists-command (vec)
5380 (with-tramp-connection-property vec "file-exists"
5381 (tramp-message vec 5 "Finding command to check if file exists")
5382 (tramp-find-file-exists-command vec)))
5383
5384 (defun tramp-get-remote-ln (vec)
5385 (with-tramp-connection-property vec "ln"
5386 (tramp-message vec 5 "Finding a suitable `ln' command")
5387 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
5388
5389 (defun tramp-get-remote-perl (vec)
5390 (with-tramp-connection-property vec "perl"
5391 (tramp-message vec 5 "Finding a suitable `perl' command")
5392 (let ((result
5393 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
5394 (tramp-find-executable
5395 vec "perl" (tramp-get-remote-path vec)))))
5396 ;; We must check also for some Perl modules.
5397 (when result
5398 (with-tramp-connection-property vec "perl-file-spec"
5399 (tramp-send-command-and-check
5400 vec (format "%s -e 'use File::Spec;'" result)))
5401 (with-tramp-connection-property vec "perl-cwd-realpath"
5402 (tramp-send-command-and-check
5403 vec (format "%s -e 'use Cwd \"realpath\";'" result))))
5404 result)))
5405
5406 (defun tramp-get-remote-stat (vec)
5407 (with-tramp-connection-property vec "stat"
5408 (tramp-message vec 5 "Finding a suitable `stat' command")
5409 (let ((result (tramp-find-executable
5410 vec "stat" (tramp-get-remote-path vec)))
5411 tmp)
5412 ;; Check whether stat(1) returns usable syntax. "%s" does not
5413 ;; work on older AIX systems.
5414 (when result
5415 (setq tmp
5416 (tramp-send-command-and-read
5417 vec (format "%s -c '(\"%%N\" %%s)' /" result) 'noerror))
5418 (unless (and (listp tmp) (stringp (car tmp))
5419 (string-match "^./.$" (car tmp))
5420 (integerp (cadr tmp)))
5421 (setq result nil)))
5422 result)))
5423
5424 (defun tramp-get-remote-readlink (vec)
5425 (with-tramp-connection-property vec "readlink"
5426 (tramp-message vec 5 "Finding a suitable `readlink' command")
5427 (let ((result (tramp-find-executable
5428 vec "readlink" (tramp-get-remote-path vec))))
5429 (when (and result
5430 (tramp-send-command-and-check
5431 vec (format "%s --canonicalize-missing /" result)))
5432 result))))
5433
5434 (defun tramp-get-remote-trash (vec)
5435 (with-tramp-connection-property vec "trash"
5436 (tramp-message vec 5 "Finding a suitable `trash' command")
5437 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
5438
5439 (defun tramp-get-remote-touch (vec)
5440 (with-tramp-connection-property vec "touch"
5441 (tramp-message vec 5 "Finding a suitable `touch' command")
5442 (let ((result (tramp-find-executable
5443 vec "touch" (tramp-get-remote-path vec)))
5444 (tmpfile
5445 (make-temp-name
5446 (expand-file-name
5447 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
5448 ;; Busyboxes do support the "-t" option only when they have been
5449 ;; built with the DESKTOP config option. Let's check it.
5450 (when result
5451 (tramp-set-connection-property
5452 vec "touch-t"
5453 (tramp-send-command-and-check
5454 vec
5455 (format
5456 "%s -t %s %s"
5457 result
5458 (format-time-string "%Y%m%d%H%M.%S")
5459 (file-remote-p tmpfile 'localname))))
5460 (delete-file tmpfile))
5461 result)))
5462
5463 (defun tramp-get-remote-gvfs-monitor-dir (vec)
5464 (with-tramp-connection-property vec "gvfs-monitor-dir"
5465 (tramp-message vec 5 "Finding a suitable `gvfs-monitor-dir' command")
5466 (tramp-find-executable
5467 vec "gvfs-monitor-dir" (tramp-get-remote-path vec) t t)))
5468
5469 (defun tramp-get-remote-inotifywait (vec)
5470 (with-tramp-connection-property vec "inotifywait"
5471 (tramp-message vec 5 "Finding a suitable `inotifywait' command")
5472 (tramp-find-executable vec "inotifywait" (tramp-get-remote-path vec) t t)))
5473
5474 (defun tramp-get-remote-id (vec)
5475 (with-tramp-connection-property vec "id"
5476 (tramp-message vec 5 "Finding POSIX `id' command")
5477 (catch 'id-found
5478 (dolist (cmd '("id" "gid"))
5479 (let ((dl (tramp-get-remote-path vec))
5480 result)
5481 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
5482 ;; Check POSIX parameter.
5483 (when (tramp-send-command-and-check vec (format "%s -u" result))
5484 (throw 'id-found result))
5485 (setq dl (cdr dl))))))))
5486
5487 (defun tramp-get-remote-uid-with-id (vec id-format)
5488 (tramp-send-command-and-read
5489 vec
5490 (format "%s -u%s %s"
5491 (tramp-get-remote-id vec)
5492 (if (equal id-format 'integer) "" "n")
5493 (if (equal id-format 'integer)
5494 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5495
5496 (defun tramp-get-remote-uid-with-perl (vec id-format)
5497 (tramp-send-command-and-read
5498 vec
5499 (format "%s -le '%s'"
5500 (tramp-get-remote-perl vec)
5501 (if (equal id-format 'integer)
5502 "print $>"
5503 "print \"\\\"\", scalar getpwuid($>), \"\\\"\""))))
5504
5505 (defun tramp-get-remote-python (vec)
5506 (with-tramp-connection-property vec "python"
5507 (tramp-message vec 5 "Finding a suitable `python' command")
5508 (or (tramp-find-executable vec "python" (tramp-get-remote-path vec))
5509 (tramp-find-executable vec "python2" (tramp-get-remote-path vec))
5510 (tramp-find-executable vec "python3" (tramp-get-remote-path vec)))))
5511
5512 (defun tramp-get-remote-uid-with-python (vec id-format)
5513 (tramp-send-command-and-read
5514 vec
5515 (format "%s -c \"%s\""
5516 (tramp-get-remote-python vec)
5517 (if (equal id-format 'integer)
5518 "import os; print (os.getuid())"
5519 "import os, pwd; print ('\\\"' + pwd.getpwuid(os.getuid())[0] + '\\\"')"))))
5520
5521 (defun tramp-get-remote-uid (vec id-format)
5522 (with-tramp-connection-property vec (format "uid-%s" id-format)
5523 (let ((res
5524 (ignore-errors
5525 (cond
5526 ((tramp-get-remote-id vec)
5527 (tramp-get-remote-uid-with-id vec id-format))
5528 ((tramp-get-remote-perl vec)
5529 (tramp-get-remote-uid-with-perl vec id-format))
5530 ((tramp-get-remote-python vec)
5531 (tramp-get-remote-uid-with-python vec id-format))))))
5532 ;; Ensure there is a valid result.
5533 (cond
5534 ((and (equal id-format 'integer) (not (integerp res))) -1)
5535 ((and (equal id-format 'string) (not (stringp res))) "UNKNOWN")
5536 (t res)))))
5537
5538 (defun tramp-get-remote-gid-with-id (vec id-format)
5539 (tramp-send-command-and-read
5540 vec
5541 (format "%s -g%s %s"
5542 (tramp-get-remote-id vec)
5543 (if (equal id-format 'integer) "" "n")
5544 (if (equal id-format 'integer)
5545 "" "| sed -e s/^/\\\"/ -e s/\\$/\\\"/"))))
5546
5547 (defun tramp-get-remote-gid-with-perl (vec id-format)
5548 (tramp-send-command-and-read
5549 vec
5550 (format "%s -le '%s'"
5551 (tramp-get-remote-perl vec)
5552 (if (equal id-format 'integer)
5553 "print ($)=~/(\\d+)/)"
5554 "print \"\\\"\", scalar getgrgid($)), \"\\\"\""))))
5555
5556 (defun tramp-get-remote-gid-with-python (vec id-format)
5557 (tramp-send-command-and-read
5558 vec
5559 (format "%s -c \"%s\""
5560 (tramp-get-remote-python vec)
5561 (if (equal id-format 'integer)
5562 "import os; print (os.getgid())"
5563 "import os, grp; print ('\\\"' + grp.getgrgid(os.getgid())[0] + '\\\"')"))))
5564
5565 (defun tramp-get-remote-gid (vec id-format)
5566 (with-tramp-connection-property vec (format "gid-%s" id-format)
5567 (let ((res
5568 (ignore-errors
5569 (cond
5570 ((tramp-get-remote-id vec)
5571 (tramp-get-remote-gid-with-id vec id-format))
5572 ((tramp-get-remote-perl vec)
5573 (tramp-get-remote-gid-with-perl vec id-format))
5574 ((tramp-get-remote-python vec)
5575 (tramp-get-remote-gid-with-python vec id-format))))))
5576 ;; Ensure there is a valid result.
5577 (cond
5578 ((and (equal id-format 'integer) (not (integerp res))) -1)
5579 ((and (equal id-format 'string) (not (stringp res))) "UNKNOWN")
5580 (t res)))))
5581
5582 ;; Some predefined connection properties.
5583 (defun tramp-get-inline-compress (vec prop size)
5584 "Return the compress command related to PROP.
5585 PROP is either `inline-compress' or `inline-decompress'. SIZE is
5586 the length of the file to be compressed.
5587
5588 If no corresponding command is found, nil is returned."
5589 (when (and (integerp tramp-inline-compress-start-size)
5590 (> size tramp-inline-compress-start-size))
5591 (with-tramp-connection-property (tramp-get-connection-process vec) prop
5592 (tramp-find-inline-compress vec)
5593 (tramp-get-connection-property
5594 (tramp-get-connection-process vec) prop nil))))
5595
5596 (defun tramp-get-inline-coding (vec prop size)
5597 "Return the coding command related to PROP.
5598 PROP is either `remote-encoding', `remote-decoding',
5599 `local-encoding' or `local-decoding'.
5600
5601 SIZE is the length of the file to be coded. Depending on SIZE,
5602 compression might be applied.
5603
5604 If no corresponding command is found, nil is returned.
5605 Otherwise, either a string is returned which contains a `%s' mark
5606 to be used for the respective input or output file; or a Lisp
5607 function cell is returned to be applied on a buffer."
5608 ;; We must catch the errors, because we want to return nil, when
5609 ;; no inline coding is found.
5610 (ignore-errors
5611 (let ((coding
5612 (with-tramp-connection-property
5613 (tramp-get-connection-process vec) prop
5614 (tramp-find-inline-encoding vec)
5615 (tramp-get-connection-property
5616 (tramp-get-connection-process vec) prop nil)))
5617 (prop1 (if (string-match "encoding" prop)
5618 "inline-compress" "inline-decompress"))
5619 compress)
5620 ;; The connection property might have been cached. So we must
5621 ;; send the script to the remote side - maybe.
5622 (when (and coding (symbolp coding) (string-match "remote" prop))
5623 (let ((name (symbol-name coding)))
5624 (while (string-match (regexp-quote "-") name)
5625 (setq name (replace-match "_" nil t name)))
5626 (tramp-maybe-send-script vec (symbol-value coding) name)
5627 (setq coding name)))
5628 (when coding
5629 ;; Check for the `compress' command.
5630 (setq compress (tramp-get-inline-compress vec prop1 size))
5631 ;; Return the value.
5632 (cond
5633 ((and compress (symbolp coding))
5634 (if (string-match "decompress" prop1)
5635 `(lambda (beg end)
5636 (,coding beg end)
5637 (let ((coding-system-for-write 'binary)
5638 (coding-system-for-read 'binary)
5639 (default-directory
5640 (tramp-compat-temporary-file-directory)))
5641 (apply
5642 'tramp-call-process-region ,vec (point-min) (point-max)
5643 (car (split-string ,compress)) t t nil
5644 (cdr (split-string ,compress)))))
5645 `(lambda (beg end)
5646 (let ((coding-system-for-write 'binary)
5647 (coding-system-for-read 'binary)
5648 (default-directory
5649 (tramp-compat-temporary-file-directory)))
5650 (apply
5651 'tramp-call-process-region ,vec beg end
5652 (car (split-string ,compress)) t t nil
5653 (cdr (split-string ,compress))))
5654 (,coding (point-min) (point-max)))))
5655 ((symbolp coding)
5656 coding)
5657 ((and compress (string-match "decoding" prop))
5658 (format
5659 ;; Windows shells need the program file name after
5660 ;; the pipe symbol be quoted if they use forward
5661 ;; slashes as directory separators.
5662 (cond
5663 ((and (string-match "local" prop)
5664 (memq system-type '(windows-nt)))
5665 "(%s | \"%s\")")
5666 ((string-match "local" prop) "(%s | %s)")
5667 (t "(%s | %s >%%s)"))
5668 coding compress))
5669 (compress
5670 (format
5671 ;; Windows shells need the program file name after
5672 ;; the pipe symbol be quoted if they use forward
5673 ;; slashes as directory separators.
5674 (if (and (string-match "local" prop)
5675 (memq system-type '(windows-nt)))
5676 "(%s <%%s | \"%s\")"
5677 "(%s <%%s | %s)")
5678 compress coding))
5679 ((string-match "decoding" prop)
5680 (cond
5681 ((string-match "local" prop) (format "%s" coding))
5682 (t (format "%s >%%s" coding))))
5683 (t
5684 (format "%s <%%s" coding)))))))
5685
5686 (add-hook 'tramp-unload-hook
5687 (lambda ()
5688 (unload-feature 'tramp-sh 'force)))
5689
5690 (provide 'tramp-sh)
5691
5692 ;;; TODO:
5693
5694 ;; * Don't use globbing for directories with many files, as this is
5695 ;; likely to produce long command lines, and some shells choke on
5696 ;; long command lines.
5697 ;; * Don't search for perl5 and perl. Instead, only search for perl and
5698 ;; then look if it's the right version (with `perl -v').
5699 ;; * When editing a remote CVS controlled file as a different user, VC
5700 ;; gets confused about the file locking status. Try to find out why
5701 ;; the workaround doesn't work.
5702 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
5703 ;; until the last but one hop via `start-file-process'. Apply it
5704 ;; also for ftp and smb.
5705 ;; * WIBNI if we had a command "trampclient"? If I was editing in
5706 ;; some shell with root privileges, it would be nice if I could
5707 ;; just call
5708 ;; trampclient filename.c
5709 ;; as an editor, and the _current_ shell would connect to an Emacs
5710 ;; server and would be used in an existing non-privileged Emacs
5711 ;; session for doing the editing in question.
5712 ;; That way, I need not tell Emacs my password again and be afraid
5713 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
5714 ;; once display a just typed password in the context of a keyboard
5715 ;; sequence prompt for a question immediately following in a shell
5716 ;; script run within Emacs -- nasty).
5717 ;; And if I have some ssh session running to a different computer,
5718 ;; having the possibility of passing a local file there to a local
5719 ;; Emacs session (in case I can arrange for a connection back) would
5720 ;; be nice.
5721 ;; Likely the corresponding Tramp server should not allow the
5722 ;; equivalent of the emacsclient -eval option in order to make this
5723 ;; reasonably unproblematic. And maybe trampclient should have some
5724 ;; way of passing credentials, like by using an SSL socket or
5725 ;; something. (David Kastrup)
5726 ;; * Reconnect directly to a compliant shell without first going
5727 ;; through the user's default shell. (Pete Forman)
5728 ;; * How can I interrupt the remote process with a signal
5729 ;; (interrupt-process seems not to work)? (Markus Triska)
5730 ;; * Avoid the local shell entirely for starting remote processes. If
5731 ;; so, I think even a signal, when delivered directly to the local
5732 ;; SSH instance, would correctly be propagated to the remote process
5733 ;; automatically; possibly SSH would have to be started with
5734 ;; "-t". (Markus Triska)
5735 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
5736 ;; isn't on the remote host. (Mark A. Hershberger)
5737 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
5738 ;; * Optimize out-of-band copying when both methods are scp-like (not
5739 ;; rsync).
5740 ;; * Keep a second connection open for out-of-band methods like scp or
5741 ;; rsync.
5742 ;; * Check, whether we could also use "getent passwd" and "getent
5743 ;; group" for user/group name completion.
5744
5745 ;;; tramp-sh.el ends here