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