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