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