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