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