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