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