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