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