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