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