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