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