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