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