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