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