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