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