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