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