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