Add SELinux support.
[bpt/emacs.git] / lisp / net / tramp.el
CommitLineData
b1a2b924 1;;; tramp.el --- Transparent Remote Access, Multiple Protocol
fb7933a3 2
5fd6d89f 3;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
114f9c96 4;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
fb7933a3 5
cbd12ed7
GM
6;; (copyright statements below in code to be updated with the above notice)
7
cdd44874 8;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
d2a2c17f 9;; Michael Albinus <michael.albinus@gmx.de>
fb7933a3
KG
10;; Keywords: comm, processes
11
12;; This file is part of GNU Emacs.
13
874a927a 14;; GNU Emacs is free software: you can redistribute it and/or modify
fb7933a3 15;; it under the terms of the GNU General Public License as published by
874a927a
GM
16;; the Free Software Foundation, either version 3 of the License, or
17;; (at your option) any later version.
fb7933a3
KG
18
19;; GNU Emacs is distributed in the hope that it will be useful,
20;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22;; GNU General Public License for more details.
23
24;; You should have received a copy of the GNU General Public License
874a927a 25;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
fb7933a3
KG
26
27;;; Commentary:
28
29;; This package provides remote file editing, similar to ange-ftp.
30;; The difference is that ange-ftp uses FTP to transfer files between
31;; the local and the remote host, whereas tramp.el uses a combination
32;; of rsh and rcp or other work-alike programs, such as ssh/scp.
33;;
b1a2b924 34;; For more detailed instructions, please see the info file.
fb7933a3
KG
35;;
36;; Notes:
37;; -----
bf247b6e 38;;
b533bc97 39;; This package only works for Emacs 22.1 and higher, and for XEmacs 21.4
00d6fd04 40;; and higher. For XEmacs 21, you need the package `fsf-compat' for
7f4d4a97 41;; the `with-timeout' macro.
fb7933a3 42;;
fb7933a3
KG
43;; Also see the todo list at the bottom of this file.
44;;
b1a2b924 45;; The current version of Tramp can be retrieved from the following URL:
340b8d4f 46;; http://ftp.gnu.org/gnu/tramp/
fb7933a3
KG
47;;
48;; There's a mailing list for this, as well. Its name is:
340b8d4f
MA
49;; tramp-devel@gnu.org
50;; You can use the Web to subscribe, under the following URL:
51;; http://lists.gnu.org/mailman/listinfo/tramp-devel
fb7933a3
KG
52;;
53;; For the adventurous, the current development sources are available
54;; via CVS. You can find instructions about this at the following URL:
c62c9d08 55;; http://savannah.gnu.org/projects/tramp/
fb7933a3
KG
56;; Click on "CVS" in the navigation bar near the top.
57;;
58;; Don't forget to put on your asbestos longjohns, first!
59
60;;; Code:
61
ccb4a481
MA
62;; Since Emacs 23.1, loading messages have been disabled during
63;; autoload. However, loading Tramp takes a while, and it could
64;; happen while typing a filename in the minibuffer. Therefore, Tramp
65;; shall inform about.
66(when (and load-in-progress (null (current-message)))
67 (message "Loading tramp..."))
68
b1a2b924
KG
69;; The Tramp version number and bug report address, as prepared by configure.
70(require 'trampver)
a69c01a0 71(add-hook 'tramp-unload-hook
aa485f7c
MA
72 (lambda ()
73 (when (featurep 'trampver)
74 (unload-feature 'trampver 'force))))
a69c01a0 75
9e6ab520 76(require 'tramp-compat)
94be87e8 77(add-hook 'tramp-unload-hook
aa485f7c
MA
78 (lambda ()
79 (when (featurep 'tramp-compat)
80 (unload-feature 'tramp-compat 'force))))
fb7933a3 81
b533bc97 82(require 'format-spec)
5ec2cc41
KG
83;; As long as password.el is not part of (X)Emacs, it shouldn't
84;; be mandatory
85(if (featurep 'xemacs)
86 (load "password" 'noerror)
fd48cd18
GM
87 (or (require 'password-cache nil 'noerror)
88 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
5ec2cc41 89
fb7933a3
KG
90(require 'shell)
91(require 'advice)
92
bcb04d98
GM
93(eval-and-compile
94 (if (featurep 'xemacs)
95 (load "auth-source" 'noerror)
96 (require 'auth-source nil 'noerror)))
5615d63f 97
00d6fd04
MA
98;; Requiring 'tramp-cache results in an endless loop.
99(autoload 'tramp-get-file-property "tramp-cache")
100(autoload 'tramp-set-file-property "tramp-cache")
101(autoload 'tramp-flush-file-property "tramp-cache")
102(autoload 'tramp-flush-directory-property "tramp-cache")
00d6fd04
MA
103(autoload 'tramp-get-connection-property "tramp-cache")
104(autoload 'tramp-set-connection-property "tramp-cache")
105(autoload 'tramp-flush-connection-property "tramp-cache")
106(autoload 'tramp-parse-connection-properties "tramp-cache")
107(add-hook 'tramp-unload-hook
aa485f7c
MA
108 (lambda ()
109 (when (featurep 'tramp-cache)
110 (unload-feature 'tramp-cache 'force))))
00d6fd04 111
16674e4f
KG
112(autoload 'tramp-uuencode-region "tramp-uu"
113 "Implementation of `uuencode' in Lisp.")
a69c01a0 114(add-hook 'tramp-unload-hook
aa485f7c
MA
115 (lambda ()
116 (when (featurep 'tramp-uu)
117 (unload-feature 'tramp-uu 'force))))
16674e4f 118
00d6fd04 119(autoload 'uudecode-decode-region "uudecode")
16674e4f 120
0664ff72
MA
121;; The following Tramp packages must be loaded after tramp.el, because
122;; they require it as well.
00d6fd04 123(eval-after-load "tramp"
9c13938d
MA
124 '(dolist
125 (feature
126 (list
127
0664ff72 128 ;; Tramp interactive commands.
9c13938d
MA
129 'tramp-cmds
130
131 ;; Load foreign FTP method.
132 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
133
134 ;; tramp-smb uses "smbclient" from Samba. Not available
135 ;; under Cygwin and Windows, because they don't offer
136 ;; "smbclient". And even not necessary there, because Emacs
137 ;; supports UNC file names like "//host/share/localname".
138 (unless (memq system-type '(cygwin windows-nt)) 'tramp-smb)
139
140 ;; Load foreign FISH method.
141 'tramp-fish
00d6fd04 142
70c11b0b 143 ;; tramp-gvfs needs D-Bus messages. Available since Emacs 23
8e754ea2
MA
144 ;; on some system types. We don't call `dbus-ping', because
145 ;; this would load dbus.el.
70c11b0b 146 (when (and (featurep 'dbusbind)
2ac33804
MA
147 (condition-case nil
148 (funcall 'dbus-get-unique-name :session)
149 (error nil))
70c11b0b
MA
150 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
151 'tramp-gvfs)
152
9c13938d 153 ;; Load gateways. It needs `make-network-process' from Emacs 22.
03db0efc
MA
154 (when (functionp 'make-network-process) 'tramp-gw)
155
156 ;; tramp-imap needs both epa (from Emacs 23.1) and imap-hash
157 ;; (from Emacs 23.2).
158 (when (and (locate-library "epa") (locate-library "imap-hash"))
159 'tramp-imap)))
9c13938d
MA
160
161 (when feature
70c11b0b
MA
162 ;; We have used just some basic tests, whether a package shall
163 ;; be added. There might still be other errors during loading,
164 ;; which we will catch here.
165 (catch 'tramp-loading
166 (require feature)
167 (add-hook 'tramp-unload-hook
168 `(lambda ()
169 (when (featurep (quote ,feature))
170 (unload-feature (quote ,feature) 'force)))))
171 (unless (featurep feature)
172 (message "Loading %s failed, ignoring this package" feature)))))
fb7933a3
KG
173
174;;; User Customizable Internal Variables:
175
176(defgroup tramp nil
177 "Edit remote files with a combination of rsh and rcp or similar programs."
589d30dd 178 :group 'files
26f4b8ab 179 :group 'comm
bf247b6e 180 :version "22.1")
fb7933a3 181
2e271195
MA
182;; Maybe we need once a real Tramp mode, with key bindings etc.
183;;;###autoload
184(defcustom tramp-mode t
185 "*Whether Tramp is enabled.
186If it is set to nil, all remote file names are used literally."
187 :group 'tramp
188 :type 'boolean)
189
00d6fd04 190(defcustom tramp-verbose 3
263c02ef 191 "*Verbosity level for Tramp messages.
00d6fd04
MA
192Any level x includes messages for all levels 1 .. x-1. The levels are
193
194 0 silent (no tramp messages at all)
195 1 errors
196 2 warnings
197 3 connection to remote hosts (default level)
198 4 activities
199 5 internal
200 6 sent and received strings
201 7 file caching
202 8 connection properties
20310 traces (huge)."
fb7933a3
KG
204 :group 'tramp
205 :type 'integer)
206
263c02ef 207;; Emacs case.
38c65fca
KG
208(eval-and-compile
209 (when (boundp 'backup-directory-alist)
210 (defcustom tramp-backup-directory-alist nil
211 "Alist of filename patterns and backup directory names.
212Each element looks like (REGEXP . DIRECTORY), with the same meaning like
213in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
214is a local file name, the backup directory is prepended with Tramp file
00d6fd04 215name prefix \(method, user, host\) of file.
38c65fca
KG
216
217\(setq tramp-backup-directory-alist backup-directory-alist\)
218
219gives the same backup policy for Tramp files on their hosts like the
220policy for local files."
221 :group 'tramp
222 :type '(repeat (cons (regexp :tag "Regexp matching filename")
223 (directory :tag "Backup directory name"))))))
224
225;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
226;; the package "backup-dir" might not be loaded yet.
227(eval-and-compile
228 (when (featurep 'xemacs)
229 (defcustom tramp-bkup-backup-directory-info nil
230 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
231It has the same meaning like `bkup-backup-directory-info' from package
232`backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
233file name, the backup directory is prepended with Tramp file name prefix
00d6fd04 234\(method, user, host\) of file.
38c65fca
KG
235
236\(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
237
238gives the same backup policy for Tramp files on their hosts like the
239policy for local files."
bf247b6e 240 :type '(repeat
38c65fca
KG
241 (list (regexp :tag "File regexp")
242 (string :tag "Backup Dir")
243 (set :inline t
244 (const ok-create)
245 (const full-path)
246 (const prepend-name)
247 (const search-upward))))
248 :group 'tramp)))
249
fb7933a3
KG
250(defcustom tramp-auto-save-directory nil
251 "*Put auto-save files in this directory, if set.
252The idea is to use a local directory so that auto-saving is faster."
253 :group 'tramp
00d6fd04 254 :type '(choice (const nil) string))
fb7933a3 255
16674e4f
KG
256(defcustom tramp-encoding-shell
257 (if (memq system-type '(windows-nt))
258 (getenv "COMSPEC")
259 "/bin/sh")
260 "*Use this program for encoding and decoding commands on the local host.
261This shell is used to execute the encoding and decoding command on the
262local host, so if you want to use `~' in those commands, you should
263choose a shell here which groks tilde expansion. `/bin/sh' normally
264does not understand tilde expansion.
265
266For encoding and deocding, commands like the following are executed:
267
268 /bin/sh -c COMMAND < INPUT > OUTPUT
269
270This variable can be used to change the \"/bin/sh\" part. See the
00d6fd04 271variable `tramp-encoding-command-switch' for the \"-c\" part.
fb7933a3
KG
272
273Note that this variable is not used for remote commands. There are
274mechanisms in tramp.el which automatically determine the right shell to
275use for the remote host."
276 :group 'tramp
277 :type '(file :must-match t))
278
16674e4f
KG
279(defcustom tramp-encoding-command-switch
280 (if (string-match "cmd\\.exe" tramp-encoding-shell)
281 "/c"
282 "-c")
283 "*Use this switch together with `tramp-encoding-shell' for local commands.
284See the variable `tramp-encoding-shell' for more information."
285 :group 'tramp
286 :type 'string)
287
00d6fd04
MA
288(defcustom tramp-copy-size-limit 10240
289 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
16674e4f 290 :group 'tramp
00d6fd04 291 :type 'integer)
90dc758d 292
00d6fd04
MA
293(defcustom tramp-terminal-type "dumb"
294 "*Value of TERM environment variable for logging in to remote host.
295Because Tramp wants to parse the output of the remote shell, it is easily
296confused by ANSI color escape sequences and suchlike. Often, shell init
297files conditionalize this setup based on the TERM environment variable."
90dc758d 298 :group 'tramp
00d6fd04 299 :type 'string)
90dc758d 300
dab816a9
MA
301;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
302;; root users. It uses the `$' character for other users. In order
303;; to guarantee a proper prompt, we use "#$" for the prompt.
304
305(defvar tramp-end-of-output
306 (format
307 "///%s#$"
308 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
309 "String used to recognize end of output.
310The '$' character at the end is quoted; the string cannot be
311detected as prompt when being sent on echoing hosts, therefore.")
312
313(defconst tramp-initial-end-of-output "#$ "
314 "Prompt when establishing a connection.")
315
00d6fd04
MA
316(defvar tramp-methods
317 `(("rcp" (tramp-login-program "rsh")
318 (tramp-login-args (("%h") ("-l" "%u")))
319 (tramp-remote-sh "/bin/sh")
320 (tramp-copy-program "rcp")
263c02ef 321 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 322 (tramp-copy-keep-date t)
263c02ef 323 (tramp-copy-recursive t)
00d6fd04
MA
324 (tramp-password-end-of-line nil))
325 ("scp" (tramp-login-program "ssh")
2296b54d 326 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
327 ("-e" "none")))
328 (tramp-remote-sh "/bin/sh")
329 (tramp-copy-program "scp")
263c02ef
MA
330 (tramp-copy-args (("-P" "%p") ("-p" "%k")
331 ("-q") ("-r")))
00d6fd04 332 (tramp-copy-keep-date t)
263c02ef 333 (tramp-copy-recursive t)
00d6fd04
MA
334 (tramp-password-end-of-line nil)
335 (tramp-gw-args (("-o"
336 "GlobalKnownHostsFile=/dev/null")
337 ("-o" "UserKnownHostsFile=/dev/null")
338 ("-o" "StrictHostKeyChecking=no")))
339 (tramp-default-port 22))
340 ("scp1" (tramp-login-program "ssh")
2296b54d 341 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
342 ("-1" "-e" "none")))
343 (tramp-remote-sh "/bin/sh")
344 (tramp-copy-program "scp")
345 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
263c02ef 346 ("-q") ("-r")))
00d6fd04 347 (tramp-copy-keep-date t)
263c02ef 348 (tramp-copy-recursive t)
00d6fd04
MA
349 (tramp-password-end-of-line nil)
350 (tramp-gw-args (("-o"
351 "GlobalKnownHostsFile=/dev/null")
352 ("-o" "UserKnownHostsFile=/dev/null")
353 ("-o" "StrictHostKeyChecking=no")))
354 (tramp-default-port 22))
355 ("scp2" (tramp-login-program "ssh")
2296b54d 356 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
357 ("-2" "-e" "none")))
358 (tramp-remote-sh "/bin/sh")
359 (tramp-copy-program "scp")
360 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
263c02ef 361 ("-q") ("-r")))
00d6fd04 362 (tramp-copy-keep-date t)
263c02ef 363 (tramp-copy-recursive t)
00d6fd04
MA
364 (tramp-password-end-of-line nil)
365 (tramp-gw-args (("-o"
366 "GlobalKnownHostsFile=/dev/null")
367 ("-o" "UserKnownHostsFile=/dev/null")
368 ("-o" "StrictHostKeyChecking=no")))
369 (tramp-default-port 22))
370 ("scp1_old"
371 (tramp-login-program "ssh1")
372 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
373 ("-e" "none")))
374 (tramp-remote-sh "/bin/sh")
375 (tramp-copy-program "scp1")
263c02ef 376 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 377 (tramp-copy-keep-date t)
263c02ef 378 (tramp-copy-recursive t)
00d6fd04
MA
379 (tramp-password-end-of-line nil))
380 ("scp2_old"
381 (tramp-login-program "ssh2")
382 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
383 ("-e" "none")))
384 (tramp-remote-sh "/bin/sh")
385 (tramp-copy-program "scp2")
263c02ef 386 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 387 (tramp-copy-keep-date t)
263c02ef 388 (tramp-copy-recursive t)
00d6fd04
MA
389 (tramp-password-end-of-line nil))
390 ("sftp" (tramp-login-program "ssh")
391 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
392 ("-e" "none")))
393 (tramp-remote-sh "/bin/sh")
394 (tramp-copy-program "sftp")
395 (tramp-copy-args nil)
396 (tramp-copy-keep-date nil)
397 (tramp-password-end-of-line nil))
398 ("rsync" (tramp-login-program "ssh")
399 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
400 ("-e" "none")))
401 (tramp-remote-sh "/bin/sh")
402 (tramp-copy-program "rsync")
263c02ef 403 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
00d6fd04 404 (tramp-copy-keep-date t)
b88f2d0a 405 (tramp-copy-keep-tmpfile t)
263c02ef 406 (tramp-copy-recursive t)
00d6fd04 407 (tramp-password-end-of-line nil))
263c02ef
MA
408 ("rsyncc"
409 (tramp-login-program "ssh")
946a5aeb
MA
410 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
411 ("-o" "ControlPath=%t.%%r@%%h:%%p")
412 ("-o" "ControlMaster=yes")
413 ("-e" "none")))
414 (tramp-remote-sh "/bin/sh")
415 (tramp-copy-program "rsync")
263c02ef 416 (tramp-copy-args (("-t" "%k") ("-r")))
946a5aeb
MA
417 (tramp-copy-env (("RSYNC_RSH")
418 (,(concat
419 "ssh"
420 " -o ControlPath=%t.%%r@%%h:%%p"
421 " -o ControlMaster=auto"))))
422 (tramp-copy-keep-date t)
b88f2d0a 423 (tramp-copy-keep-tmpfile t)
263c02ef 424 (tramp-copy-recursive t)
946a5aeb 425 (tramp-password-end-of-line nil))
00d6fd04
MA
426 ("remcp" (tramp-login-program "remsh")
427 (tramp-login-args (("%h") ("-l" "%u")))
428 (tramp-remote-sh "/bin/sh")
429 (tramp-copy-program "rcp")
430 (tramp-copy-args (("-p" "%k")))
431 (tramp-copy-keep-date t)
432 (tramp-password-end-of-line nil))
433 ("rsh" (tramp-login-program "rsh")
434 (tramp-login-args (("%h") ("-l" "%u")))
435 (tramp-remote-sh "/bin/sh")
436 (tramp-copy-program nil)
437 (tramp-copy-args nil)
438 (tramp-copy-keep-date nil)
439 (tramp-password-end-of-line nil))
440 ("ssh" (tramp-login-program "ssh")
2296b54d 441 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
442 ("-e" "none")))
443 (tramp-remote-sh "/bin/sh")
444 (tramp-copy-program nil)
445 (tramp-copy-args nil)
446 (tramp-copy-keep-date nil)
447 (tramp-password-end-of-line nil)
448 (tramp-gw-args (("-o"
449 "GlobalKnownHostsFile=/dev/null")
450 ("-o" "UserKnownHostsFile=/dev/null")
451 ("-o" "StrictHostKeyChecking=no")))
452 (tramp-default-port 22))
453 ("ssh1" (tramp-login-program "ssh")
2296b54d 454 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
455 ("-1" "-e" "none")))
456 (tramp-remote-sh "/bin/sh")
457 (tramp-copy-program nil)
458 (tramp-copy-args nil)
459 (tramp-copy-keep-date nil)
460 (tramp-password-end-of-line nil)
461 (tramp-gw-args (("-o"
462 "GlobalKnownHostsFile=/dev/null")
463 ("-o" "UserKnownHostsFile=/dev/null")
464 ("-o" "StrictHostKeyChecking=no")))
465 (tramp-default-port 22))
466 ("ssh2" (tramp-login-program "ssh")
2296b54d 467 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
468 ("-2" "-e" "none")))
469 (tramp-remote-sh "/bin/sh")
470 (tramp-copy-program nil)
471 (tramp-copy-args nil)
472 (tramp-copy-keep-date nil)
473 (tramp-password-end-of-line nil)
474 (tramp-gw-args (("-o"
475 "GlobalKnownHostsFile=/dev/null")
476 ("-o" "UserKnownHostsFile=/dev/null")
477 ("-o" "StrictHostKeyChecking=no")))
478 (tramp-default-port 22))
479 ("ssh1_old"
480 (tramp-login-program "ssh1")
481 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
482 ("-e" "none")))
483 (tramp-remote-sh "/bin/sh")
484 (tramp-copy-program nil)
485 (tramp-copy-args nil)
486 (tramp-copy-keep-date nil)
487 (tramp-password-end-of-line nil))
488 ("ssh2_old"
489 (tramp-login-program "ssh2")
490 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
491 ("-e" "none")))
492 (tramp-remote-sh "/bin/sh")
493 (tramp-copy-program nil)
494 (tramp-copy-args nil)
495 (tramp-copy-keep-date nil)
496 (tramp-password-end-of-line nil))
497 ("remsh" (tramp-login-program "remsh")
498 (tramp-login-args (("%h") ("-l" "%u")))
499 (tramp-remote-sh "/bin/sh")
500 (tramp-copy-program nil)
501 (tramp-copy-args nil)
502 (tramp-copy-keep-date nil)
503 (tramp-password-end-of-line nil))
504 ("telnet"
505 (tramp-login-program "telnet")
506 (tramp-login-args (("%h") ("%p")))
507 (tramp-remote-sh "/bin/sh")
508 (tramp-copy-program nil)
509 (tramp-copy-args nil)
510 (tramp-copy-keep-date nil)
511 (tramp-password-end-of-line nil)
512 (tramp-default-port 23))
513 ("su" (tramp-login-program "su")
514 (tramp-login-args (("-") ("%u")))
515 (tramp-remote-sh "/bin/sh")
516 (tramp-copy-program nil)
517 (tramp-copy-args nil)
518 (tramp-copy-keep-date nil)
519 (tramp-password-end-of-line nil))
520 ("sudo" (tramp-login-program "sudo")
521 (tramp-login-args (("-u" "%u")
42bc9b6d 522 ("-s") ("-H") ("-p" "Password:")))
00d6fd04
MA
523 (tramp-remote-sh "/bin/sh")
524 (tramp-copy-program nil)
525 (tramp-copy-args nil)
526 (tramp-copy-keep-date nil)
527 (tramp-password-end-of-line nil))
528 ("scpc" (tramp-login-program "ssh")
2296b54d 529 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
530 ("-o" "ControlPath=%t.%%r@%%h:%%p")
531 ("-o" "ControlMaster=yes")
532 ("-e" "none")))
533 (tramp-remote-sh "/bin/sh")
534 (tramp-copy-program "scp")
535 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
536 ("-o" "ControlPath=%t.%%r@%%h:%%p")
537 ("-o" "ControlMaster=auto")))
538 (tramp-copy-keep-date t)
539 (tramp-password-end-of-line nil)
540 (tramp-gw-args (("-o"
541 "GlobalKnownHostsFile=/dev/null")
542 ("-o" "UserKnownHostsFile=/dev/null")
543 ("-o" "StrictHostKeyChecking=no")))
544 (tramp-default-port 22))
545 ("scpx" (tramp-login-program "ssh")
2296b54d 546 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
547 ("-e" "none" "-t" "-t" "/bin/sh")))
548 (tramp-remote-sh "/bin/sh")
549 (tramp-copy-program "scp")
550 (tramp-copy-args (("-p" "%k")))
551 (tramp-copy-keep-date t)
552 (tramp-password-end-of-line nil)
553 (tramp-gw-args (("-o"
554 "GlobalKnownHostsFile=/dev/null")
555 ("-o" "UserKnownHostsFile=/dev/null")
556 ("-o" "StrictHostKeyChecking=no")))
557 (tramp-default-port 22))
558 ("sshx" (tramp-login-program "ssh")
2296b54d 559 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
560 ("-e" "none" "-t" "-t" "/bin/sh")))
561 (tramp-remote-sh "/bin/sh")
562 (tramp-copy-program nil)
563 (tramp-copy-args nil)
564 (tramp-copy-keep-date nil)
565 (tramp-password-end-of-line nil)
566 (tramp-gw-args (("-o"
567 "GlobalKnownHostsFile=/dev/null")
568 ("-o" "UserKnownHostsFile=/dev/null")
569 ("-o" "StrictHostKeyChecking=no")))
570 (tramp-default-port 22))
571 ("krlogin"
572 (tramp-login-program "krlogin")
573 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
574 (tramp-remote-sh "/bin/sh")
575 (tramp-copy-program nil)
576 (tramp-copy-args nil)
577 (tramp-copy-keep-date nil)
578 (tramp-password-end-of-line nil))
579 ("plink" (tramp-login-program "plink")
580 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
581 ("-ssh")))
582 (tramp-remote-sh "/bin/sh")
583 (tramp-copy-program nil)
584 (tramp-copy-args nil)
585 (tramp-copy-keep-date nil)
586 (tramp-password-end-of-line "xy") ;see docstring for "xy"
587 (tramp-default-port 22))
588 ("plink1"
589 (tramp-login-program "plink")
590 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
591 ("-1" "-ssh")))
592 (tramp-remote-sh "/bin/sh")
593 (tramp-copy-program nil)
594 (tramp-copy-args nil)
595 (tramp-copy-keep-date nil)
596 (tramp-password-end-of-line "xy") ;see docstring for "xy"
597 (tramp-default-port 22))
598 ("plinkx"
599 (tramp-login-program "plink")
42bc9b6d
MA
600 ;; ("%h") must be a single element, see
601 ;; `tramp-compute-multi-hops'.
602 (tramp-login-args (("-load") ("%h") ("-t")
ce3f516f 603 (,(format
dab816a9
MA
604 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
605 tramp-terminal-type
606 tramp-initial-end-of-output))
00d6fd04
MA
607 ("/bin/sh")))
608 (tramp-remote-sh "/bin/sh")
609 (tramp-copy-program nil)
610 (tramp-copy-args nil)
611 (tramp-copy-keep-date nil)
612 (tramp-password-end-of-line nil))
613 ("pscp" (tramp-login-program "plink")
614 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
615 ("-ssh")))
616 (tramp-remote-sh "/bin/sh")
617 (tramp-copy-program "pscp")
60f2c210 618 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
00d6fd04
MA
619 (tramp-copy-keep-date t)
620 (tramp-password-end-of-line "xy") ;see docstring for "xy"
621 (tramp-default-port 22))
622 ("psftp" (tramp-login-program "plink")
623 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
624 ("-ssh")))
625 (tramp-remote-sh "/bin/sh")
626 (tramp-copy-program "pscp")
60f2c210 627 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
00d6fd04
MA
628 (tramp-copy-keep-date t)
629 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
630 ("fcp" (tramp-login-program "fsh")
631 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
632 (tramp-remote-sh "/bin/sh -i")
633 (tramp-copy-program "fcp")
634 (tramp-copy-args (("-p" "%k")))
635 (tramp-copy-keep-date t)
636 (tramp-password-end-of-line nil)))
fb7933a3
KG
637 "*Alist of methods for remote files.
638This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
639Each NAME stands for a remote access method. Each PARAM is a
640pair of the form (KEY VALUE). The following KEYs are defined:
fb7933a3
KG
641 * `tramp-remote-sh'
642 This specifies the Bourne shell to use on the remote host. This
643 MUST be a Bourne-like shell. It is normally not necessary to set
a4aeb9a4 644 this to any value other than \"/bin/sh\": Tramp wants to use a shell
fb7933a3
KG
645 which groks tilde expansion, but it can search for it. Also note
646 that \"/bin/sh\" exists on all Unixen, this might not be true for
647 the value that you decide to use. You Have Been Warned.
b25a52cc
KG
648 * `tramp-login-program'
649 This specifies the name of the program to use for logging in to the
00d6fd04
MA
650 remote host. This may be the name of rsh or a workalike program,
651 or the name of telnet or a workalike, or the name of su or a workalike.
b25a52cc 652 * `tramp-login-args'
fb7933a3 653 This specifies the list of arguments to pass to the above
00d6fd04 654 mentioned program. Please note that this is a list of list of arguments,
fb7933a3 655 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
00d6fd04
MA
656 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
657 There are some patterns: \"%h\" in this list is replaced by the host
658 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
659 port number, and \"%%\" can be used to obtain a literal percent character.
660 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
661 expansion (i.e. no host or no user specified), this list is not used as
662 argument. By this, arguments like (\"-l\" \"%u\") are optional.
663 \"%t\" is replaced by the temporary file name produced with
664 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
665 parameter of a program, if exists.
b25a52cc
KG
666 * `tramp-copy-program'
667 This specifies the name of the program to use for remotely copying
668 the file; this might be the absolute filename of rcp or the name of
669 a workalike program.
670 * `tramp-copy-args'
fb7933a3 671 This specifies the list of parameters to pass to the above mentioned
b25a52cc 672 program, the hints for `tramp-login-args' also apply here.
00d6fd04
MA
673 * `tramp-copy-keep-date'
674 This specifies whether the copying program when the preserves the
675 timestamp of the original file.
b88f2d0a
MA
676 * `tramp-copy-keep-tmpfile'
677 This specifies whether a temporary local file shall be kept
678 for optimization reasons (useful for \"rsync\" methods).
679 * `tramp-copy-recursive'
680 Whether the operation copies directories recursively.
00d6fd04
MA
681 * `tramp-default-port'
682 The default port of a method is needed in case of gateway connections.
683 Additionally, it is used as indication which method is prepared for
684 passing gateways.
685 * `tramp-gw-args'
686 As the attribute name says, additional arguments are specified here
687 when a method is applied via a gateway.
90f8dc03
KG
688 * `tramp-password-end-of-line'
689 This specifies the string to use for terminating the line after
690 submitting the password. If this method parameter is nil, then the
691 value of the normal variable `tramp-default-password-end-of-line'
692 is used. This parameter is necessary because the \"plink\" program
693 requires any two characters after sending the password. These do
694 not have to be newline or carriage return characters. Other login
695 programs are happy with just one character, the newline character.
696 We use \"xy\" as the value for methods using \"plink\".
b25a52cc
KG
697
698What does all this mean? Well, you should specify `tramp-login-program'
699for all methods; this program is used to log in to the remote site. Then,
700there are two ways to actually transfer the files between the local and the
701remote side. One way is using an additional rcp-like program. If you want
702to do this, set `tramp-copy-program' in the method.
fb7933a3
KG
703
704Another possibility for file transfer is inline transfer, i.e. the
b25a52cc 705file is passed through the same buffer used by `tramp-login-program'. In
fb7933a3 706this case, the file contents need to be protected since the
b25a52cc 707`tramp-login-program' might use escape codes or the connection might not
fb7933a3 708be eight-bit clean. Therefore, file contents are encoded for transit.
00d6fd04
MA
709See the variables `tramp-local-coding-commands' and
710`tramp-remote-coding-commands' for details.
fb7933a3 711
16674e4f 712So, to summarize: if the method is an out-of-band method, then you
b25a52cc 713must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
00d6fd04
MA
714inline method, then these two parameters should be nil. Methods which
715are fit for gateways must have `tramp-default-port' at least.
fb7933a3
KG
716
717Notes:
718
00d6fd04
MA
719When using `su' or `sudo' the phrase `open connection to a remote
720host' sounds strange, but it is used nevertheless, for consistency.
721No connection is opened to a remote host, but `su' or `sudo' is
722started on the local host. You should specify a remote host
723`localhost' or the name of the local host. Another host name is
724useful only in combination with `tramp-default-proxies-alist'.")
fb7933a3 725
b25a52cc 726(defcustom tramp-default-method
83e20b5c
MA
727 ;; An external copy method seems to be preferred, because it is much
728 ;; more performant for large files, and it hasn't too serious delays
729 ;; for small files. But it must be ensured that there aren't
730 ;; permanent password queries. Either a password agent like
263c02ef
MA
731 ;; "ssh-agent" or "Pageant" shall run, or the optional
732 ;; password-cache.el or auth-sources.el packages shall be active for
733 ;; password caching. "scpc" would be another good choice because of
734 ;; the "ControlMaster" option, but this is a more modern alternative
735 ;; in OpenSSH 4, which cannot be taken as default.
00d6fd04
MA
736 (cond
737 ;; PuTTY is installed.
738 ((executable-find "pscp")
739 (if (or (fboundp 'password-read)
263c02ef 740 (fboundp 'auth-source-user-or-password)
00d6fd04 741 ;; Pageant is running.
70c11b0b 742 (tramp-compat-process-running-p "Pageant"))
00d6fd04
MA
743 "pscp"
744 "plink"))
745 ;; There is an ssh installation.
746 ((executable-find "scp")
747 (if (or (fboundp 'password-read)
263c02ef 748 (fboundp 'auth-source-user-or-password)
00d6fd04
MA
749 ;; ssh-agent is running.
750 (getenv "SSH_AUTH_SOCK")
751 (getenv "SSH_AGENT_PID"))
752 "scp"
753 "ssh"))
754 ;; Fallback.
755 (t "ftp"))
fb7933a3 756 "*Default method to use for transferring files.
c62c9d08 757See `tramp-methods' for possibilities.
4007ba5b 758Also see `tramp-default-method-alist'."
c62c9d08
KG
759 :group 'tramp
760 :type 'string)
761
505edaeb 762(defcustom tramp-default-method-alist
4007ba5b 763 '(("\\`localhost\\'" "\\`root\\'" "su"))
00d6fd04 764 "*Default method to use for specific host/user pairs.
c62c9d08
KG
765This is an alist of items (HOST USER METHOD). The first matching item
766specifies the method to use for a file name which does not specify a
767method. HOST and USER are regular expressions or nil, which is
768interpreted as a regular expression which always matches. If no entry
769matches, the variable `tramp-default-method' takes effect.
770
771If the file name does not specify the user, lookup is done using the
772empty string for the user name.
773
774See `tramp-methods' for a list of possibilities for METHOD."
775 :group 'tramp
776 :type '(repeat (list (regexp :tag "Host regexp")
777 (regexp :tag "User regexp")
778 (string :tag "Method"))))
779
00d6fd04
MA
780(defcustom tramp-default-user
781 nil
782 "*Default user to use for transferring files.
783It is nil by default; otherwise settings in configuration files like
784\"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
785
786This variable is regarded as obsolete, and will be removed soon."
787 :group 'tramp
788 :type '(choice (const nil) string))
789
790(defcustom tramp-default-user-alist
791 `(("\\`su\\(do\\)?\\'" nil "root")
792 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
793 nil ,(user-login-name)))
794 "*Default user to use for specific method/host pairs.
795This is an alist of items (METHOD HOST USER). The first matching item
796specifies the user to use for a file name which does not specify a
797user. METHOD and USER are regular expressions or nil, which is
798interpreted as a regular expression which always matches. If no entry
799matches, the variable `tramp-default-user' takes effect.
800
801If the file name does not specify the method, lookup is done using the
802empty string for the method name."
803 :group 'tramp
804 :type '(repeat (list (regexp :tag "Method regexp")
805 (regexp :tag "Host regexp")
806 (string :tag "User"))))
807
808(defcustom tramp-default-host
809 (system-name)
810 "*Default host to use for transferring files.
811Useful for su and sudo methods mostly."
812 :group 'tramp
813 :type 'string)
814
815(defcustom tramp-default-proxies-alist nil
816 "*Route to be followed for specific host/user pairs.
817This is an alist of items (HOST USER PROXY). The first matching
818item specifies the proxy to be passed for a file name located on
819a remote target matching USER@HOST. HOST and USER are regular
70c11b0b
MA
820expressions. PROXY must be a Tramp filename without a localname
821part. Method and user name on PROXY are optional, which is
822interpreted with the default values. PROXY can contain the
823patterns %h and %u, which are replaced by the strings matching
824HOST or USER, respectively.
825
826HOST, USER or PROXY could also be Lisp forms, which will be
827evaluated. The result must be a string or nil, which is
828interpreted as a regular expression which always matches."
00d6fd04 829 :group 'tramp
70c11b0b
MA
830 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
831 (choice :tag "User regexp" regexp sexp)
832 (choice :tag "Proxy remote name" string (const nil)))))
00d6fd04 833
b96e6899
MA
834(defconst tramp-local-host-regexp
835 (concat
836 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
837 "*Host names which are regarded as local host.")
838
16674e4f 839(defconst tramp-completion-function-alist-rsh
00d6fd04
MA
840 '((tramp-parse-rhosts "/etc/hosts.equiv")
841 (tramp-parse-rhosts "~/.rhosts"))
b25a52cc 842 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
16674e4f 843
16674e4f 844(defconst tramp-completion-function-alist-ssh
00d6fd04
MA
845 '((tramp-parse-rhosts "/etc/hosts.equiv")
846 (tramp-parse-rhosts "/etc/shosts.equiv")
847 (tramp-parse-shosts "/etc/ssh_known_hosts")
848 (tramp-parse-sconfig "/etc/ssh_config")
849 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
850 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
851 (tramp-parse-rhosts "~/.rhosts")
852 (tramp-parse-rhosts "~/.shosts")
853 (tramp-parse-shosts "~/.ssh/known_hosts")
854 (tramp-parse-sconfig "~/.ssh/config")
855 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
856 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
b25a52cc 857 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
16674e4f 858
16674e4f 859(defconst tramp-completion-function-alist-telnet
00d6fd04 860 '((tramp-parse-hosts "/etc/hosts"))
b25a52cc 861 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
16674e4f 862
16674e4f 863(defconst tramp-completion-function-alist-su
00d6fd04 864 '((tramp-parse-passwd "/etc/passwd"))
b25a52cc 865 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
292ffc15 866
00d6fd04
MA
867(defconst tramp-completion-function-alist-putty
868 '((tramp-parse-putty
869 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
870 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
871
5ec2cc41 872(defvar tramp-completion-function-alist nil
16674e4f 873 "*Alist of methods for remote files.
b533bc97 874This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
16674e4f 875Each NAME stands for a remote access method. Each PAIR is of the form
b533bc97 876\(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
16674e4f
KG
877names from FILE for completion. The following predefined FUNCTIONs exists:
878
5ec2cc41
KG
879 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
880 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
881 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
882 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
883 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
884 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
885 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
886 * `tramp-parse-netrc' for \"~/.netrc\" like files.
00d6fd04 887 * `tramp-parse-putty' for PuTTY registry keys.
5ec2cc41
KG
888
889FUNCTION can also be a customer defined function. For more details see
890the info pages.")
891
892(eval-after-load "tramp"
893 '(progn
894 (tramp-set-completion-function
895 "rcp" tramp-completion-function-alist-rsh)
896 (tramp-set-completion-function
897 "scp" tramp-completion-function-alist-ssh)
898 (tramp-set-completion-function
899 "scp1" tramp-completion-function-alist-ssh)
900 (tramp-set-completion-function
901 "scp2" tramp-completion-function-alist-ssh)
902 (tramp-set-completion-function
903 "scp1_old" tramp-completion-function-alist-ssh)
904 (tramp-set-completion-function
905 "scp2_old" tramp-completion-function-alist-ssh)
906 (tramp-set-completion-function
70c11b0b 907 "rsync" tramp-completion-function-alist-ssh)
946a5aeb
MA
908 (tramp-set-completion-function
909 "rsyncc" tramp-completion-function-alist-ssh)
5ec2cc41
KG
910 (tramp-set-completion-function
911 "remcp" tramp-completion-function-alist-rsh)
912 (tramp-set-completion-function
913 "rsh" tramp-completion-function-alist-rsh)
914 (tramp-set-completion-function
915 "ssh" tramp-completion-function-alist-ssh)
916 (tramp-set-completion-function
917 "ssh1" tramp-completion-function-alist-ssh)
918 (tramp-set-completion-function
919 "ssh2" tramp-completion-function-alist-ssh)
920 (tramp-set-completion-function
921 "ssh1_old" tramp-completion-function-alist-ssh)
922 (tramp-set-completion-function
923 "ssh2_old" tramp-completion-function-alist-ssh)
924 (tramp-set-completion-function
925 "remsh" tramp-completion-function-alist-rsh)
926 (tramp-set-completion-function
927 "telnet" tramp-completion-function-alist-telnet)
928 (tramp-set-completion-function
929 "su" tramp-completion-function-alist-su)
930 (tramp-set-completion-function
931 "sudo" tramp-completion-function-alist-su)
bf247b6e 932 (tramp-set-completion-function
5ec2cc41
KG
933 "scpx" tramp-completion-function-alist-ssh)
934 (tramp-set-completion-function
935 "sshx" tramp-completion-function-alist-ssh)
936 (tramp-set-completion-function
937 "krlogin" tramp-completion-function-alist-rsh)
938 (tramp-set-completion-function
939 "plink" tramp-completion-function-alist-ssh)
940 (tramp-set-completion-function
941 "plink1" tramp-completion-function-alist-ssh)
00d6fd04
MA
942 (tramp-set-completion-function
943 "plinkx" tramp-completion-function-alist-putty)
5ec2cc41
KG
944 (tramp-set-completion-function
945 "pscp" tramp-completion-function-alist-ssh)
946 (tramp-set-completion-function
947 "fcp" tramp-completion-function-alist-ssh)))
16674e4f 948
674da028
MA
949(defconst tramp-echo-mark-marker "_echo"
950 "String marker to surround echoed commands.")
951
68712eb6
MA
952(defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
953 "String length of `tramp-echo-mark-marker'.")
954
955(defconst tramp-echo-mark
956 (concat tramp-echo-mark-marker
957 (make-string tramp-echo-mark-marker-length ?\b))
00d6fd04
MA
958 "String mark to be transmitted around shell commands.
959Used to separate their echo from the output they produce. This
960will only be used if we cannot disable remote echo via stty.
961This string must have no effect on the remote shell except for
962producing some echo which can later be detected by
674da028
MA
963`tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
964followed by an equal number of backspaces to erase them will
965usually suffice.")
00d6fd04 966
68712eb6
MA
967(defconst tramp-echoed-echo-mark-regexp
968 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
969 tramp-echo-mark-marker tramp-echo-mark-marker-length)
00d6fd04
MA
970 "Regexp which matches `tramp-echo-mark' as it gets echoed by
971the remote shell.")
972
fb7933a3
KG
973(defcustom tramp-rsh-end-of-line "\n"
974 "*String used for end of line in rsh connections.
975I don't think this ever needs to be changed, so please tell me about it
16674e4f 976if you need to change this.
90f8dc03
KG
977Also see the method parameter `tramp-password-end-of-line' and the normal
978variable `tramp-default-password-end-of-line'."
16674e4f
KG
979 :group 'tramp
980 :type 'string)
981
90f8dc03
KG
982(defcustom tramp-default-password-end-of-line
983 tramp-rsh-end-of-line
16674e4f 984 "*String used for end of line after sending a password.
90f8dc03
KG
985This variable provides the default value for the method parameter
986`tramp-password-end-of-line', see `tramp-methods' for more details.
987
16674e4f
KG
988It seems that people using plink under Windows need to send
989\"\\r\\n\" (carriage-return, then newline) after a password, but just
990\"\\n\" after all other lines. This variable can be used for the
991password, see `tramp-rsh-end-of-line' for the other cases.
992
993The default value is to use the same value as `tramp-rsh-end-of-line'."
fb7933a3
KG
994 :group 'tramp
995 :type 'string)
996
00d6fd04
MA
997;; "getconf PATH" yields:
998;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
999;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
0664ff72 1000;; GNU/Linux (Debian, Suse): /bin:/usr/bin
00d6fd04 1001;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
fb7933a3 1002(defcustom tramp-remote-path
00d6fd04
MA
1003 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1004 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
fb7933a3
KG
1005 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1006 "*List of directories to search for executables on remote host.
00d6fd04
MA
1007For every remote host, this variable will be set buffer local,
1008keeping the list of existing directories on that host.
fb7933a3
KG
1009
1010You can use `~' in this list, but when searching for a shell which groks
00d6fd04
MA
1011tilde expansion, all directory names starting with `~' will be ignored.
1012
1013`Default Directories' represent the list of directories given by
1014the command \"getconf PATH\". It is recommended to use this
1015entry on top of this list, because these are the default
70c11b0b
MA
1016directories for POSIX compatible commands.
1017
1018`Private Directories' are the settings of the $PATH environment,
1019as given in your `~/.profile'."
00d6fd04
MA
1020 :group 'tramp
1021 :type '(repeat (choice
1022 (const :tag "Default Directories" tramp-default-remote-path)
70c11b0b 1023 (const :tag "Private Directories" tramp-own-remote-path)
00d6fd04
MA
1024 (string :tag "Directory"))))
1025
00d6fd04 1026(defcustom tramp-remote-process-environment
a0a5183a 1027 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
b533bc97 1028 ,(format "TERM=%s" tramp-terminal-type)
97c696d5
MA
1029 "EMACS=t" ;; Deprecated.
1030 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
00d6fd04
MA
1031 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1032 "autocorrect=" "correct=")
1033
1034 "*List of environment variables to be set on the remote host.
1035
1036Each element should be a string of the form ENVVARNAME=VALUE. An
1037entry ENVVARNAME= diables the corresponding environment variable,
1038which might have been set in the init files like ~/.profile.
1039
1040Special handling is applied to the PATH environment, which should
1041not be set here. Instead of, it should be set via `tramp-remote-path'."
fb7933a3
KG
1042 :group 'tramp
1043 :type '(repeat string))
1044
1045(defcustom tramp-login-prompt-regexp
bc103d00 1046 ".*ogin\\( .*\\)?: *"
fb7933a3 1047 "*Regexp matching login-like prompts.
bc103d00
MA
1048The regexp should match at end of buffer.
1049
1050Sometimes the prompt is reported to look like \"login as:\"."
fb7933a3
KG
1051 :group 'tramp
1052 :type 'regexp)
1053
821e6e36 1054(defcustom tramp-shell-prompt-pattern
aa485f7c
MA
1055 ;; Allow a prompt to start right after a ^M since it indeed would be
1056 ;; displayed at the beginning of the line (and Zsh uses it).
dab816a9 1057 "\\(?:^\\|\r\\)[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
821e6e36
KG
1058 "Regexp to match prompts from remote shell.
1059Normally, Tramp expects you to configure `shell-prompt-pattern'
1060correctly, but sometimes it happens that you are connecting to a
1061remote host which sends a different kind of shell prompt. Therefore,
1062Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1063and also things matched by this variable. The default value of this
b25a52cc 1064variable is similar to the default value of `shell-prompt-pattern',
dab816a9
MA
1065which should work well in many cases.
1066
1067This regexp must match both `tramp-initial-end-of-output' and
1068`tramp-end-of-output'."
821e6e36
KG
1069 :group 'tramp
1070 :type 'regexp)
1071
fb7933a3 1072(defcustom tramp-password-prompt-regexp
00d6fd04 1073 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
fb7933a3 1074 "*Regexp matching password-like prompts.
ac474af1 1075The regexp should match at end of buffer.
fb7933a3
KG
1076
1077The `sudo' program appears to insert a `^@' character into the prompt."
1078 :group 'tramp
1079 :type 'regexp)
1080
1081(defcustom tramp-wrong-passwd-regexp
b1d06e75
KG
1082 (concat "^.*"
1083 ;; These strings should be on the last line
a4aeb9a4 1084 (regexp-opt '("Permission denied"
b1d06e75
KG
1085 "Login incorrect"
1086 "Login Incorrect"
1087 "Connection refused"
27e813fe 1088 "Connection closed"
7e5686f0 1089 "Timeout, server not responding."
b1d06e75
KG
1090 "Sorry, try again."
1091 "Name or service not known"
00d6fd04 1092 "Host key verification failed."
70c11b0b 1093 "No supported authentication methods left to try!") t)
b1d06e75
KG
1094 ".*"
1095 "\\|"
1096 "^.*\\("
1097 ;; Here comes a list of regexes, separated by \\|
1098 "Received signal [0-9]+"
1099 "\\).*")
fb7933a3 1100 "*Regexp matching a `login failed' message.
ac474af1
KG
1101The regexp should match at end of buffer."
1102 :group 'tramp
1103 :type 'regexp)
1104
1105(defcustom tramp-yesno-prompt-regexp
3cdaec13
KG
1106 (concat
1107 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1108 "\\s-*")
1109 "Regular expression matching all yes/no queries which need to be confirmed.
ac474af1 1110The confirmation should be done with yes or no.
3cdaec13
KG
1111The regexp should match at end of buffer.
1112See also `tramp-yn-prompt-regexp'."
fb7933a3
KG
1113 :group 'tramp
1114 :type 'regexp)
1115
3cdaec13 1116(defcustom tramp-yn-prompt-regexp
658052a2
MA
1117 (concat
1118 (regexp-opt '("Store key in cache? (y/n)"
1119 "Update cached key? (y/n, Return cancels connection)") t)
1120 "\\s-*")
3cdaec13
KG
1121 "Regular expression matching all y/n queries which need to be confirmed.
1122The confirmation should be done with y or n.
1123The regexp should match at end of buffer.
1124See also `tramp-yesno-prompt-regexp'."
1125 :group 'tramp
1126 :type 'regexp)
487f4fb7
KG
1127
1128(defcustom tramp-terminal-prompt-regexp
1129 (concat "\\("
1130 "TERM = (.*)"
1131 "\\|"
1132 "Terminal type\\? \\[.*\\]"
1133 "\\)\\s-*")
1134 "Regular expression matching all terminal setting prompts.
1135The regexp should match at end of buffer.
1136The answer will be provided by `tramp-action-terminal', which see."
1137 :group 'tramp
1138 :type 'regexp)
3cdaec13 1139
01917a18
MA
1140(defcustom tramp-operation-not-permitted-regexp
1141 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1142 (regexp-opt '("Operation not permitted") t))
1143 "Regular expression matching keep-date problems in (s)cp operations.
1144Copying has been performed successfully already, so this message can
1145be ignored safely."
1146 :group 'tramp
1147 :type 'regexp)
1148
6b2633cc
LH
1149(defcustom tramp-copy-failed-regexp
1150 (concat "\\(.+: "
1151 (regexp-opt '("Permission denied"
1152 "not a regular file"
1153 "is a directory"
1154 "No such file or directory") t)
1155 "\\)\\s-*")
1156 "Regular expression matching copy problems in (s)cp operations."
1157 :group 'tramp
1158 :type 'regexp)
1159
19a87064 1160(defcustom tramp-process-alive-regexp
38c65fca 1161 ""
19a87064 1162 "Regular expression indicating a process has finished.
38c65fca
KG
1163In fact this expression is empty by intention, it will be used only to
1164check regularly the status of the associated process.
07dfe738 1165The answer will be provided by `tramp-action-process-alive',
00d6fd04 1166`tramp-action-out-of-band', which see."
38c65fca
KG
1167 :group 'tramp
1168 :type 'regexp)
1169
fb7933a3
KG
1170(defcustom tramp-temp-name-prefix "tramp."
1171 "*Prefix to use for temporary files.
1172If this is a relative file name (such as \"tramp.\"), it is considered
1173relative to the directory name returned by the function
9e6ab520 1174`tramp-compat-temporary-file-directory' (which see). It may also be an
fb7933a3
KG
1175absolute file name; don't forget to include a prefix for the filename
1176part, though."
1177 :group 'tramp
1178 :type 'string)
1179
2296b54d
MA
1180(defconst tramp-temp-buffer-name " *tramp temp*"
1181 "Buffer name for a temporary buffer.
1182It shall be used in combination with `generate-new-buffer-name'.")
1183
b88f2d0a
MA
1184(defvar tramp-temp-buffer-file-name nil
1185 "File name of a persistent local temporary file.
1186Useful for \"rsync\" like methods.")
1187(make-variable-buffer-local 'tramp-temp-buffer-file-name)
1188
4007ba5b 1189(defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
c62c9d08
KG
1190 "*Alist specifying extra arguments to pass to the remote shell.
1191Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1192matching the shell file name and ARGS is a string specifying the
1193arguments.
1194
1195This variable is only used when Tramp needs to start up another shell
1196for tilde expansion. The extra arguments should typically prevent the
1197shell from reading its init file."
1198 :group 'tramp
90f8dc03
KG
1199 ;; This might be the wrong way to test whether the widget type
1200 ;; `alist' is available. Who knows the right way to test it?
1201 :type (if (get 'alist 'widget-type)
1202 '(alist :key-type string :value-type string)
1203 '(repeat (cons string string))))
c62c9d08 1204
00d6fd04
MA
1205;; XEmacs is distributed with few Lisp packages. Further packages are
1206;; installed using EFS. If we use a unified filename format, then
1207;; Tramp is required in addition to EFS. (But why can't Tramp just
1208;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1209;; just like before.) Another reason for using a separate filename
1210;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1211;; Tramp only knows how to deal with `file-name-handler-alist', not
1212;; the other places.
1213
1214;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1215;;;###autoload
1216(defcustom tramp-syntax
1217 (if (featurep 'xemacs) 'sep 'ftp)
1218 "Tramp filename syntax to be used.
1219
1220It can have the following values:
1221
1222 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1223 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1224 'url -- URL-like syntax."
16674e4f 1225 :group 'tramp
00d6fd04
MA
1226 :type (if (featurep 'xemacs)
1227 '(choice (const :tag "EFS" ftp)
1228 (const :tag "XEmacs" sep)
1229 (const :tag "URL" url))
1230 '(choice (const :tag "Ange-FTP" ftp)
1231 (const :tag "URL" url))))
1232
1233(defconst tramp-prefix-format
1234 (cond ((equal tramp-syntax 'ftp) "/")
1235 ((equal tramp-syntax 'sep) "/[")
1236 ((equal tramp-syntax 'url) "/")
1237 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4 1238 "*String matching the very beginning of Tramp file names.
00d6fd04 1239Used in `tramp-make-tramp-file-name'.")
16674e4f 1240
00d6fd04 1241(defconst tramp-prefix-regexp
16674e4f 1242 (concat "^" (regexp-quote tramp-prefix-format))
a4aeb9a4 1243 "*Regexp matching the very beginning of Tramp file names.
00d6fd04 1244Should always start with \"^\". Derived from `tramp-prefix-format'.")
16674e4f 1245
00d6fd04 1246(defconst tramp-method-regexp
16674e4f 1247 "[a-zA-Z_0-9-]+"
00d6fd04 1248 "*Regexp matching methods identifiers.")
16674e4f 1249
00d6fd04
MA
1250(defconst tramp-postfix-method-format
1251 (cond ((equal tramp-syntax 'ftp) ":")
1252 ((equal tramp-syntax 'sep) "/")
1253 ((equal tramp-syntax 'url) "://")
1254 (t (error "Wrong `tramp-syntax' defined")))
16674e4f 1255 "*String matching delimeter between method and user or host names.
00d6fd04 1256Used in `tramp-make-tramp-file-name'.")
16674e4f 1257
00d6fd04
MA
1258(defconst tramp-postfix-method-regexp
1259 (regexp-quote tramp-postfix-method-format)
16674e4f 1260 "*Regexp matching delimeter between method and user or host names.
00d6fd04 1261Derived from `tramp-postfix-method-format'.")
16674e4f 1262
00d6fd04
MA
1263(defconst tramp-user-regexp
1264 "[^:/ \t]+"
1265 "*Regexp matching user names.")
16674e4f 1266
b96e6899
MA
1267(defconst tramp-prefix-domain-format "%"
1268 "*String matching delimeter between user and domain names.")
1269
1270(defconst tramp-prefix-domain-regexp
1271 (regexp-quote tramp-prefix-domain-format)
1272 "*Regexp matching delimeter between user and domain names.
1273Derived from `tramp-prefix-domain-format'.")
1274
1275(defconst tramp-domain-regexp
70c11b0b 1276 "[-a-zA-Z0-9_.]+"
b96e6899
MA
1277 "*Regexp matching domain names.")
1278
1279(defconst tramp-user-with-domain-regexp
1280 (concat "\\(" tramp-user-regexp "\\)"
1281 tramp-prefix-domain-regexp
1282 "\\(" tramp-domain-regexp "\\)")
1283 "*Regexp matching user names with domain names.")
1284
00d6fd04 1285(defconst tramp-postfix-user-format
16674e4f
KG
1286 "@"
1287 "*String matching delimeter between user and host names.
00d6fd04 1288Used in `tramp-make-tramp-file-name'.")
16674e4f 1289
00d6fd04 1290(defconst tramp-postfix-user-regexp
16674e4f
KG
1291 (regexp-quote tramp-postfix-user-format)
1292 "*Regexp matching delimeter between user and host names.
00d6fd04
MA
1293Derived from `tramp-postfix-user-format'.")
1294
1295(defconst tramp-host-regexp
1296 "[a-zA-Z0-9_.-]+"
1297 "*Regexp matching host names.")
1298
b96e6899
MA
1299(defconst tramp-prefix-ipv6-format
1300 (cond ((equal tramp-syntax 'ftp) "[")
1301 ((equal tramp-syntax 'sep) "")
1302 ((equal tramp-syntax 'url) "[")
1303 (t (error "Wrong `tramp-syntax' defined")))
1304 "*String matching left hand side of IPv6 addresses.
1305Used in `tramp-make-tramp-file-name'.")
1306
1307(defconst tramp-prefix-ipv6-regexp
1308 (regexp-quote tramp-prefix-ipv6-format)
1309 "*Regexp matching left hand side of IPv6 addresses.
1310Derived from `tramp-prefix-ipv6-format'.")
1311
e0b6e3b9
MA
1312;; The following regexp is a bit sloppy. But it shall serve our
1313;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1314;; "::ffff:192.168.0.1".
b96e6899 1315(defconst tramp-ipv6-regexp
e0b6e3b9 1316 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
b96e6899
MA
1317 "*Regexp matching IPv6 addresses.")
1318
1319(defconst tramp-postfix-ipv6-format
1320 (cond ((equal tramp-syntax 'ftp) "]")
1321 ((equal tramp-syntax 'sep) "")
1322 ((equal tramp-syntax 'url) "]")
1323 (t (error "Wrong `tramp-syntax' defined")))
1324 "*String matching right hand side of IPv6 addresses.
1325Used in `tramp-make-tramp-file-name'.")
1326
1327(defconst tramp-postfix-ipv6-regexp
1328 (regexp-quote tramp-postfix-ipv6-format)
1329 "*Regexp matching right hand side of IPv6 addresses.
1330Derived from `tramp-postfix-ipv6-format'.")
1331
00d6fd04
MA
1332(defconst tramp-prefix-port-format
1333 (cond ((equal tramp-syntax 'ftp) "#")
1334 ((equal tramp-syntax 'sep) "#")
1335 ((equal tramp-syntax 'url) ":")
1336 (t (error "Wrong `tramp-syntax' defined")))
1337 "*String matching delimeter between host names and port numbers.")
1338
1339(defconst tramp-prefix-port-regexp
1340 (regexp-quote tramp-prefix-port-format)
1341 "*Regexp matching delimeter between host names and port numbers.
1342Derived from `tramp-prefix-port-format'.")
1343
1344(defconst tramp-port-regexp
1345 "[0-9]+"
1346 "*Regexp matching port numbers.")
1347
1348(defconst tramp-host-with-port-regexp
1349 (concat "\\(" tramp-host-regexp "\\)"
1350 tramp-prefix-port-regexp
1351 "\\(" tramp-port-regexp "\\)")
1352 "*Regexp matching host names with port numbers.")
1353
1354(defconst tramp-postfix-host-format
1355 (cond ((equal tramp-syntax 'ftp) ":")
1356 ((equal tramp-syntax 'sep) "]")
1357 ((equal tramp-syntax 'url) "")
1358 (t (error "Wrong `tramp-syntax' defined")))
7432277c 1359 "*String matching delimeter between host names and localnames.
00d6fd04 1360Used in `tramp-make-tramp-file-name'.")
16674e4f 1361
00d6fd04 1362(defconst tramp-postfix-host-regexp
16674e4f 1363 (regexp-quote tramp-postfix-host-format)
7432277c 1364 "*Regexp matching delimeter between host names and localnames.
00d6fd04 1365Derived from `tramp-postfix-host-format'.")
16674e4f 1366
00d6fd04 1367(defconst tramp-localname-regexp
16674e4f 1368 ".*$"
00d6fd04 1369 "*Regexp matching localnames.")
16674e4f
KG
1370
1371;; File name format.
505edaeb 1372
00d6fd04 1373(defconst tramp-file-name-structure
16674e4f
KG
1374 (list
1375 (concat
1376 tramp-prefix-regexp
00d6fd04
MA
1377 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1378 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
b96e6899
MA
1379 "\\(" "\\(" tramp-host-regexp
1380 "\\|"
1381 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1382 tramp-postfix-ipv6-regexp "\\)"
1383 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
00d6fd04
MA
1384 tramp-postfix-host-regexp
1385 "\\(" tramp-localname-regexp "\\)")
b96e6899 1386 2 4 5 8)
16674e4f 1387
fb7933a3 1388 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
a4aeb9a4 1389the Tramp file name structure.
fb7933a3 1390
a4aeb9a4 1391The first element REGEXP is a regular expression matching a Tramp file
fb7933a3
KG
1392name. The regex should contain parentheses around the method name,
1393the user name, the host name, and the file name parts.
1394
1395The second element METHOD is a number, saying which pair of
1396parentheses matches the method name. The third element USER is
1397similar, but for the user name. The fourth element HOST is similar,
1398but for the host name. The fifth element FILE is for the file name.
1399These numbers are passed directly to `match-string', which see. That
1400means the opening parentheses are counted to identify the pair.
1401
00d6fd04 1402See also `tramp-file-name-regexp'.")
fb7933a3
KG
1403
1404;;;###autoload
505edaeb 1405(defconst tramp-file-name-regexp-unified
b96e6899 1406 "\\`/\\([^[/:]+\\|[^/]+]\\):"
505edaeb
KG
1407 "Value for `tramp-file-name-regexp' for unified remoting.
1408Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
00d6fd04 1409Tramp. See `tramp-file-name-structure' for more explanations.")
505edaeb
KG
1410
1411;;;###autoload
1412(defconst tramp-file-name-regexp-separate
1413 "\\`/\\[.*\\]"
1414 "Value for `tramp-file-name-regexp' for separate remoting.
1415XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 1416See `tramp-file-name-structure' for more explanations.")
505edaeb
KG
1417
1418;;;###autoload
00d6fd04
MA
1419(defconst tramp-file-name-regexp-url
1420 "\\`/[^/:]+://"
1421 "Value for `tramp-file-name-regexp' for URL-like remoting.
1422See `tramp-file-name-structure' for more explanations.")
1423
1424;;;###autoload
1425(defconst tramp-file-name-regexp
1426 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1427 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1428 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1429 (t (error "Wrong `tramp-syntax' defined")))
94be87e8 1430 "*Regular expression matching file names handled by Tramp.
a4aeb9a4 1431This regexp should match Tramp file names but no other file names.
b533bc97 1432When tramp.el is loaded, this regular expression is prepended to
fb7933a3 1433`file-name-handler-alist', and that is searched sequentially. Thus,
a4aeb9a4
MA
1434if the Tramp entry appears rather early in the `file-name-handler-alist'
1435and is a bit too general, then some files might be considered Tramp
00d6fd04 1436files which are not really Tramp files.
fb7933a3
KG
1437
1438Please note that the entry in `file-name-handler-alist' is made when
b533bc97 1439this file \(tramp.el\) is loaded. This means that this variable must be set
fb7933a3
KG
1440before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1441updated after changing this variable.
1442
00d6fd04 1443Also see `tramp-file-name-structure'.")
fb7933a3 1444
16674e4f 1445;;;###autoload
8a798e41 1446(defconst tramp-root-regexp
00d6fd04 1447 (if (memq system-type '(cygwin windows-nt))
aa485f7c
MA
1448 "\\`\\([a-zA-Z]:\\)?/"
1449 "\\`/")
8a798e41 1450 "Beginning of an incomplete Tramp file name.
aa485f7c 1451Usually, it is just \"\\\\`/\". On W32 systems, there might be a
57671b72 1452volume letter, which will be removed by `tramp-drop-volume-letter'.")
8a798e41
MA
1453
1454;;;###autoload
1455(defconst tramp-completion-file-name-regexp-unified
aa485f7c 1456 (concat tramp-root-regexp "[^/]*\\'")
16674e4f 1457 "Value for `tramp-completion-file-name-regexp' for unified remoting.
8a798e41
MA
1458GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1459See `tramp-file-name-structure' for more explanations.")
fb7933a3 1460
16674e4f
KG
1461;;;###autoload
1462(defconst tramp-completion-file-name-regexp-separate
aa485f7c 1463 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
16674e4f
KG
1464 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1465XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 1466See `tramp-file-name-structure' for more explanations.")
fb7933a3 1467
16674e4f 1468;;;###autoload
00d6fd04 1469(defconst tramp-completion-file-name-regexp-url
aa485f7c 1470 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
00d6fd04
MA
1471 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1472See `tramp-file-name-structure' for more explanations.")
1473
1474;;;###autoload
1475(defconst tramp-completion-file-name-regexp
1476 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1477 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1478 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1479 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4
MA
1480 "*Regular expression matching file names handled by Tramp completion.
1481This regexp should match partial Tramp file names only.
16674e4f
KG
1482
1483Please note that the entry in `file-name-handler-alist' is made when
1484this file (tramp.el) is loaded. This means that this variable must be set
1485before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1486updated after changing this variable.
1487
00d6fd04 1488Also see `tramp-file-name-structure'.")
fb7933a3 1489
00d6fd04
MA
1490(defconst tramp-actions-before-shell
1491 '((tramp-login-prompt-regexp tramp-action-login)
1492 (tramp-password-prompt-regexp tramp-action-password)
1493 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
ac474af1 1494 (shell-prompt-pattern tramp-action-succeed)
821e6e36 1495 (tramp-shell-prompt-pattern tramp-action-succeed)
3cdaec13 1496 (tramp-yesno-prompt-regexp tramp-action-yesno)
487f4fb7 1497 (tramp-yn-prompt-regexp tramp-action-yn)
19a87064
MA
1498 (tramp-terminal-prompt-regexp tramp-action-terminal)
1499 (tramp-process-alive-regexp tramp-action-process-alive))
ac474af1
KG
1500 "List of pattern/action pairs.
1501Whenever a pattern matches, the corresponding action is performed.
1502Each item looks like (PATTERN ACTION).
1503
1504The PATTERN should be a symbol, a variable. The value of this
1505variable gives the regular expression to search for. Note that the
1506regexp must match at the end of the buffer, \"\\'\" is implicitly
1507appended to it.
1508
1509The ACTION should also be a symbol, but a function. When the
00d6fd04 1510corresponding PATTERN matches, the ACTION function is called.")
ac474af1 1511
00d6fd04 1512(defconst tramp-actions-copy-out-of-band
38c65fca
KG
1513 '((tramp-password-prompt-regexp tramp-action-password)
1514 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
00d6fd04 1515 (tramp-copy-failed-regexp tramp-action-permission-denied)
19a87064 1516 (tramp-process-alive-regexp tramp-action-out-of-band))
38c65fca
KG
1517 "List of pattern/action pairs.
1518This list is used for copying/renaming with out-of-band methods.
90f8dc03 1519
00d6fd04
MA
1520See `tramp-actions-before-shell' for more info.")
1521
1522;; Chunked sending kludge. We set this to 500 for black-listed constellations
7432277c 1523;; known to have a bug in `process-send-string'; some ssh connections appear
7177e2a3
MA
1524;; to drop bytes when data is sent too quickly. There is also a connection
1525;; buffer local variable, which is computed depending on remote host properties
1526;; when `tramp-chunksize' is zero or nil.
7432277c
KG
1527(defcustom tramp-chunksize
1528 (when (and (not (featurep 'xemacs))
1529 (memq system-type '(hpux)))
1530 500)
55880756
MA
1531;; Parentheses in docstring starting at beginning of line are escaped.
1532;; Fontification is messed up when
1533;; `open-paren-in-column-0-is-defun-start' set to t.
7432277c
KG
1534 "*If non-nil, chunksize for sending input to local process.
1535It is necessary only on systems which have a buggy `process-send-string'
1536implementation. The necessity, whether this variable must be set, can be
1537checked via the following code:
1538
1539 (with-temp-buffer
11948172
MA
1540 (let* ((user \"xxx\") (host \"yyy\")
1541 (init 0) (step 50)
1542 (sent init) (received init))
1543 (while (= sent received)
1544 (setq sent (+ sent step))
1545 (erase-buffer)
1546 (let ((proc (start-process (buffer-name) (current-buffer)
1547 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1548 (when (memq (process-status proc) '(run open))
1549 (process-send-string proc (make-string sent ?\\ ))
1550 (process-send-eof proc)
1551 (process-send-eof proc))
1552 (while (not (progn (goto-char (point-min))
1553 (re-search-forward \"\\\\w+\" (point-max) t)))
1554 (accept-process-output proc 1))
1555 (when (memq (process-status proc) '(run open))
1556 (setq received (string-to-number (match-string 0)))
1557 (delete-process proc)
1558 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1559 (sit-for 0))))
1560 (if (> sent (+ init step))
1561 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1562 (- sent step))
1563 (message \"Test does not work\")
1564 (display-buffer (current-buffer))
1565 (sit-for 30))))
1566
1567In the Emacs normally running Tramp, evaluate the above code
55880756 1568\(replace \"xxx\" and \"yyy\" by the remote user and host name,
b533bc97 1569respectively\). You can do this, for example, by pasting it into
11948172
MA
1570the `*scratch*' buffer and then hitting C-j with the cursor after the
1571last closing parenthesis. Note that it works only if you have configured
b533bc97 1572\"ssh\" to run without password query, see ssh-agent\(1\).
11948172
MA
1573
1574You will see the number of bytes sent successfully to the remote host.
1575If that number exceeds 1000, you can stop the execution by hitting
1576C-g, because your Emacs is likely clean.
1577
11948172 1578When it is necessary to set `tramp-chunksize', you might consider to
b533bc97
MA
1579use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1580\(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
11948172 1581performance.
c951aecb 1582
00d6fd04
MA
1583If your Emacs is buggy, the code stops and gives you an indication
1584about the value `tramp-chunksize' should be set. Maybe you could just
1585experiment a bit, e.g. changing the values of `init' and `step'
1586in the third line of the code.
1587
7432277c
KG
1588Please raise a bug report via \"M-x tramp-bug\" if your system needs
1589this variable to be set as well."
1590 :group 'tramp
b1a2b924 1591 :type '(choice (const nil) integer))
7432277c 1592
5ec2cc41
KG
1593;; Logging in to a remote host normally requires obtaining a pty. But
1594;; Emacs on MacOS X has process-connection-type set to nil by default,
1595;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1596;; for an override of the system default.
1597(defcustom tramp-process-connection-type t
1598 "Overrides `process-connection-type' for connections from Tramp.
1599Tramp binds process-connection-type to the value given here before
1600opening a connection to a remote host."
1601 :group 'tramp
1602 :type '(choice (const nil) (const t) (const pty)))
1603
b50dd0d2
MA
1604(defcustom tramp-completion-reread-directory-timeout 10
1605 "Defines seconds since last remote command before rereading a directory.
1606A remote directory might have changed its contents. In order to
1607make it visible during file name completion in the minibuffer,
1608Tramp flushes its cache and rereads the directory contents when
1609more than `tramp-completion-reread-directory-timeout' seconds
1610have been gone since last remote command execution. A value of 0
1611would require an immediate reread during filename completion, nil
1612means to use always cached values for the directory contents."
1613 :group 'tramp
1614 :type '(choice (const nil) integer))
1615
fb7933a3
KG
1616;;; Internal Variables:
1617
fb7933a3 1618(defvar tramp-current-method nil
00d6fd04 1619 "Connection method for this *tramp* buffer.")
fb7933a3
KG
1620
1621(defvar tramp-current-user nil
00d6fd04 1622 "Remote login name for this *tramp* buffer.")
fb7933a3
KG
1623
1624(defvar tramp-current-host nil
00d6fd04
MA
1625 "Remote host for this *tramp* buffer.")
1626
1627(defconst tramp-uudecode
1628 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
fabf2143 1629cat /tmp/tramp.$$
00d6fd04 1630rm -f /tmp/tramp.$$"
fabf2143 1631 "Shell function to implement `uudecode' to standard output.
c08e6004
MA
1632Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1633for this or `uudecode -p', but some systems don't, and for them
1634we have this shell function.")
fabf2143 1635
293c24f9
MA
1636(defconst tramp-perl-file-truename
1637 "%s -e '
1638use File::Spec;
1639use Cwd \"realpath\";
1640
1641sub recursive {
1642 my ($volume, @dirs) = @_;
1643 my $real = realpath(File::Spec->catpath(
1644 $volume, File::Spec->catdir(@dirs), \"\"));
1645 if ($real) {
1646 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1647 return ($vol, File::Spec->splitdir($dir));
1648 }
1649 else {
1650 my $last = pop(@dirs);
1651 ($volume, @dirs) = recursive($volume, @dirs);
1652 push(@dirs, $last);
1653 return ($volume, @dirs);
1654 }
1655}
1656
1657$result = realpath($ARGV[0]);
1658if (!$result) {
1659 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1660 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1661
1662 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1663}
1664
1665if ($ARGV[0] =~ /\\/$/) {
1666 $result = $result . \"/\";
1667}
1668
1669print \"\\\"$result\\\"\\n\";
1670' \"$1\" 2>/dev/null"
1671 "Perl script to produce output suitable for use with `file-truename'
1672on the remote file system.
1673Escape sequence %s is replaced with name of Perl binary.
1674This string is passed to `format', so percent characters need to be doubled.")
1675
1676(defconst tramp-perl-file-name-all-completions
1677 "%s -e 'sub case {
1678 my $str = shift;
1679 if ($ARGV[2]) {
1680 return lc($str);
1681 }
1682 else {
1683 return $str;
1684 }
1685}
1686opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1687@files = readdir(d); closedir(d);
1688foreach $f (@files) {
1689 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1690 if (-d \"$ARGV[0]/$f\") {
1691 print \"$f/\\n\";
1692 }
1693 else {
1694 print \"$f\\n\";
1695 }
1696 }
1697}
1698print \"ok\\n\"
1699' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1700 "Perl script to produce output suitable for use with
1701`file-name-all-completions' on the remote file system. Escape
1702sequence %s is replaced with name of Perl binary. This string is
1703passed to `format', so percent characters need to be doubled.")
1704
fabf2143
KG
1705;; Perl script to implement `file-attributes' in a Lisp `read'able
1706;; output. If you are hacking on this, note that you get *no* output
1707;; unless this spits out a complete line, including the '\n' at the
1708;; end.
8daea7fc 1709;; The device number is returned as "-1", because there will be a virtual
b946a456 1710;; device number set in `tramp-handle-file-attributes'.
00d6fd04
MA
1711(defconst tramp-perl-file-attributes
1712 "%s -e '
c82c5727 1713@stat = lstat($ARGV[0]);
680db9ac
MA
1714if (!@stat) {
1715 print \"nil\\n\";
1716 exit 0;
1717}
c82c5727
LH
1718if (($stat[2] & 0170000) == 0120000)
1719{
1720 $type = readlink($ARGV[0]);
1721 $type = \"\\\"$type\\\"\";
1722}
1723elsif (($stat[2] & 0170000) == 040000)
1724{
1725 $type = \"t\";
1726}
1727else
1728{
1729 $type = \"nil\"
1730};
1731$uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1732$gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1733printf(
d4443a0d 1734 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
c82c5727
LH
1735 $type,
1736 $stat[3],
1737 $uid,
1738 $gid,
1739 $stat[8] >> 16 & 0xffff,
1740 $stat[8] & 0xffff,
1741 $stat[9] >> 16 & 0xffff,
1742 $stat[9] & 0xffff,
1743 $stat[10] >> 16 & 0xffff,
1744 $stat[10] & 0xffff,
1745 $stat[7],
1746 $stat[2],
1747 $stat[1] >> 16 & 0xffff,
1748 $stat[1] & 0xffff
00d6fd04 1749);' \"$1\" \"$2\" \"$3\" 2>/dev/null"
fb7933a3 1750 "Perl script to produce output suitable for use with `file-attributes'
00d6fd04
MA
1751on the remote file system.
1752Escape sequence %s is replaced with name of Perl binary.
1753This string is passed to `format', so percent characters need to be doubled.")
fb7933a3 1754
00d6fd04
MA
1755(defconst tramp-perl-directory-files-and-attributes
1756 "%s -e '
8cb0a559
LH
1757chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1758opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
c82c5727
LH
1759@list = readdir(DIR);
1760closedir(DIR);
1761$n = scalar(@list);
1762printf(\"(\\n\");
1763for($i = 0; $i < $n; $i++)
1764{
1765 $filename = $list[$i];
1766 @stat = lstat($filename);
1767 if (($stat[2] & 0170000) == 0120000)
1768 {
1769 $type = readlink($filename);
1770 $type = \"\\\"$type\\\"\";
1771 }
1772 elsif (($stat[2] & 0170000) == 040000)
1773 {
1774 $type = \"t\";
1775 }
1776 else
1777 {
1778 $type = \"nil\"
1779 };
1780 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1781 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1782 printf(
b946a456 1783 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
c82c5727
LH
1784 $filename,
1785 $type,
1786 $stat[3],
1787 $uid,
1788 $gid,
1789 $stat[8] >> 16 & 0xffff,
1790 $stat[8] & 0xffff,
1791 $stat[9] >> 16 & 0xffff,
1792 $stat[9] & 0xffff,
1793 $stat[10] >> 16 & 0xffff,
1794 $stat[10] & 0xffff,
1795 $stat[7],
1796 $stat[2],
1797 $stat[1] >> 16 & 0xffff,
1798 $stat[1] & 0xffff,
1799 $stat[0] >> 16 & 0xffff,
1800 $stat[0] & 0xffff);
1801}
00d6fd04 1802printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
c82c5727 1803 "Perl script implementing `directory-files-attributes' as Lisp `read'able
00d6fd04
MA
1804output.
1805Escape sequence %s is replaced with name of Perl binary.
1806This string is passed to `format', so percent characters need to be doubled.")
c82c5727 1807
ac474af1
KG
1808;; ;; These two use uu encoding.
1809;; (defvar tramp-perl-encode "%s -e'\
1810;; print qq(begin 644 xxx\n);
1811;; my $s = q();
1812;; my $res = q();
1813;; while (read(STDIN, $s, 45)) {
1814;; print pack(q(u), $s);
1815;; }
1816;; print qq(`\n);
1817;; print qq(end\n);
1818;; '"
1819;; "Perl program to use for encoding a file.
1820;; Escape sequence %s is replaced with name of Perl binary.")
1821
1822;; (defvar tramp-perl-decode "%s -ne '
1823;; print unpack q(u), $_;
1824;; '"
1825;; "Perl program to use for decoding a file.
1826;; Escape sequence %s is replaced with name of Perl binary.")
1827
1828;; These two use base64 encoding.
00d6fd04
MA
1829(defconst tramp-perl-encode-with-module
1830 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
ac474af1 1831 "Perl program to use for encoding a file.
b1d06e75 1832Escape sequence %s is replaced with name of Perl binary.
89509ea0 1833This string is passed to `format', so percent characters need to be doubled.
b1d06e75
KG
1834This implementation requires the MIME::Base64 Perl module to be installed
1835on the remote host.")
1836
00d6fd04
MA
1837(defconst tramp-perl-decode-with-module
1838 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
b1d06e75
KG
1839 "Perl program to use for decoding a file.
1840Escape sequence %s is replaced with name of Perl binary.
89509ea0 1841This string is passed to `format', so percent characters need to be doubled.
b1d06e75
KG
1842This implementation requires the MIME::Base64 Perl module to be installed
1843on the remote host.")
1844
00d6fd04 1845(defconst tramp-perl-encode
b1d06e75
KG
1846 "%s -e '
1847# This script contributed by Juanma Barranquero <lektu@terra.es>.
114f9c96 1848# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
cbd12ed7 1849# Free Software Foundation, Inc.
b1d06e75
KG
1850use strict;
1851
fa32e96a 1852my %%trans = do {
b1d06e75
KG
1853 my $i = 0;
1854 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1855 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1856};
1857
36541701 1858binmode(\\*STDIN);
b1d06e75
KG
1859
1860# We read in chunks of 54 bytes, to generate output lines
1861# of 72 chars (plus end of line)
36541701 1862$/ = \\54;
b1d06e75
KG
1863
1864while (my $data = <STDIN>) {
1865 my $pad = q();
1866
1867 # Only for the last chunk, and only if did not fill the last three-byte packet
1868 if (eof) {
fa32e96a 1869 my $mod = length($data) %% 3;
b1d06e75
KG
1870 $pad = q(=) x (3 - $mod) if $mod;
1871 }
1872
1873 # Not the fastest method, but it is simple: unpack to binary string, split
1874 # by groups of 6 bits and convert back from binary to byte; then map into
1875 # the translation table
1876 print
1877 join q(),
1878 map($trans{$_},
1879 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1880 $pad,
36541701 1881 qq(\\n);
00d6fd04 1882}' 2>/dev/null"
b1d06e75 1883 "Perl program to use for encoding a file.
fa32e96a 1884Escape sequence %s is replaced with name of Perl binary.
ccf29586 1885This string is passed to `format', so percent characters need to be doubled.")
ac474af1 1886
00d6fd04 1887(defconst tramp-perl-decode
b1d06e75
KG
1888 "%s -e '
1889# This script contributed by Juanma Barranquero <lektu@terra.es>.
114f9c96 1890# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
cbd12ed7 1891# Free Software Foundation, Inc.
b1d06e75
KG
1892use strict;
1893
fa32e96a 1894my %%trans = do {
b1d06e75 1895 my $i = 0;
16674e4f 1896 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
b1d06e75
KG
1897 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1898};
1899
fa32e96a 1900my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
b1d06e75 1901
36541701 1902binmode(\\*STDOUT);
b1d06e75
KG
1903
1904# We are going to accumulate into $pending to accept any line length
1905# (we do not check they are <= 76 chars as the RFC says)
1906my $pending = q();
1907
1908while (my $data = <STDIN>) {
1909 chomp $data;
1910
1911 # If we find one or two =, we have reached the end and
1912 # any following data is to be discarded
1913 my $finished = $data =~ s/(==?).*/$1/;
1914 $pending .= $data;
1915
1916 my $len = length($pending);
16674e4f 1917 my $chunk = substr($pending, 0, $len & ~3);
414da5ab 1918 $pending = substr($pending, $len & ~3 + 1);
b1d06e75
KG
1919
1920 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1921 # split in 8-bit chunks and convert back to char.
1922 print join q(),
1923 map $bytes{$_},
1924 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1925
1926 last if $finished;
00d6fd04 1927}' 2>/dev/null"
ac474af1 1928 "Perl program to use for decoding a file.
fa32e96a 1929Escape sequence %s is replaced with name of Perl binary.
ccf29586 1930This string is passed to `format', so percent characters need to be doubled.")
fb7933a3 1931
946a5aeb
MA
1932(defconst tramp-vc-registered-read-file-names
1933 "echo \"(\"
1934for file in \"$@\"; do
1935 if %s $file; then
1936 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1937 else
1938 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1939 fi
1940 if %s $file; then
1941 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1942 else
1943 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1944 fi
1945done
1946echo \")\""
1947 "Script to check existence of VC related files.
1948It must be send formatted with two strings; the tests for file
1949existence, and file readability.")
1950
9ce8462a
MA
1951(defconst tramp-file-mode-type-map
1952 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1953 (1 . "p") ; fifo
1954 (2 . "c") ; character device
1955 (3 . "m") ; multiplexed character device (v7)
1956 (4 . "d") ; directory
1957 (5 . "?") ; Named special file (XENIX)
1958 (6 . "b") ; block device
1959 (7 . "?") ; multiplexed block device (v7)
1960 (8 . "-") ; regular file
1961 (9 . "n") ; network special file (HP-UX)
1962 (10 . "l") ; symlink
1963 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1964 (12 . "s") ; socket
1965 (13 . "D") ; door special (Solaris)
1966 (14 . "w")) ; whiteout (BSD)
fb7933a3
KG
1967 "A list of file types returned from the `stat' system call.
1968This is used to map a mode number to a permission string.")
1969
fb7933a3 1970;; New handlers should be added here. The following operations can be
c0fc6170
MA
1971;; handled using the normal primitives: file-name-sans-versions,
1972;; get-file-buffer.
fb7933a3 1973(defconst tramp-file-name-handler-alist
00d6fd04 1974 '((load . tramp-handle-load)
fb7933a3 1975 (make-symbolic-link . tramp-handle-make-symbolic-link)
c0fc6170 1976 (file-name-as-directory . tramp-handle-file-name-as-directory)
fb7933a3
KG
1977 (file-name-directory . tramp-handle-file-name-directory)
1978 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1979 (file-truename . tramp-handle-file-truename)
1980 (file-exists-p . tramp-handle-file-exists-p)
1981 (file-directory-p . tramp-handle-file-directory-p)
1982 (file-executable-p . tramp-handle-file-executable-p)
fb7933a3
KG
1983 (file-readable-p . tramp-handle-file-readable-p)
1984 (file-regular-p . tramp-handle-file-regular-p)
1985 (file-symlink-p . tramp-handle-file-symlink-p)
1986 (file-writable-p . tramp-handle-file-writable-p)
1987 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1988 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1989 (file-attributes . tramp-handle-file-attributes)
1990 (file-modes . tramp-handle-file-modes)
fb7933a3 1991 (directory-files . tramp-handle-directory-files)
c82c5727 1992 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
fb7933a3
KG
1993 (file-name-all-completions . tramp-handle-file-name-all-completions)
1994 (file-name-completion . tramp-handle-file-name-completion)
1995 (add-name-to-file . tramp-handle-add-name-to-file)
1996 (copy-file . tramp-handle-copy-file)
263c02ef 1997 (copy-directory . tramp-handle-copy-directory)
fb7933a3
KG
1998 (rename-file . tramp-handle-rename-file)
1999 (set-file-modes . tramp-handle-set-file-modes)
ce3f516f 2000 (set-file-times . tramp-handle-set-file-times)
fb7933a3
KG
2001 (make-directory . tramp-handle-make-directory)
2002 (delete-directory . tramp-handle-delete-directory)
2003 (delete-file . tramp-handle-delete-file)
2004 (directory-file-name . tramp-handle-directory-file-name)
00d6fd04
MA
2005 ;; `executable-find' is not official yet.
2006 (executable-find . tramp-handle-executable-find)
2007 (start-file-process . tramp-handle-start-file-process)
0457dd55 2008 (process-file . tramp-handle-process-file)
00d6fd04 2009 (shell-command . tramp-handle-shell-command)
fb7933a3
KG
2010 (insert-directory . tramp-handle-insert-directory)
2011 (expand-file-name . tramp-handle-expand-file-name)
00d6fd04 2012 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
fb7933a3 2013 (file-local-copy . tramp-handle-file-local-copy)
19a87064 2014 (file-remote-p . tramp-handle-file-remote-p)
fb7933a3 2015 (insert-file-contents . tramp-handle-insert-file-contents)
94be87e8
MA
2016 (insert-file-contents-literally
2017 . tramp-handle-insert-file-contents-literally)
fb7933a3 2018 (write-region . tramp-handle-write-region)
38c65fca 2019 (find-backup-file-name . tramp-handle-find-backup-file-name)
c1105d05 2020 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
fb7933a3 2021 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
5ec2cc41 2022 (dired-compress-file . tramp-handle-dired-compress-file)
fb7933a3
KG
2023 (dired-recursive-delete-directory
2024 . tramp-handle-dired-recursive-delete-directory)
70c11b0b 2025 (dired-uncache . tramp-handle-dired-uncache)
fb7933a3 2026 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
49096407
MA
2027 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2028 (vc-registered . tramp-handle-vc-registered))
c1105d05 2029 "Alist of handler functions.
fb7933a3
KG
2030Operations not mentioned here will be handled by the normal Emacs functions.")
2031
a4aeb9a4 2032;; Handlers for partial Tramp file names. For Emacs just
41c8e348 2033;; `file-name-all-completions' is needed.
a01b1e22 2034;;;###autoload
16674e4f 2035(defconst tramp-completion-file-name-handler-alist
a01b1e22 2036 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
41c8e348 2037 (file-name-completion . tramp-completion-handle-file-name-completion))
16674e4f
KG
2038 "Alist of completion handler functions.
2039Used for file names matching `tramp-file-name-regexp'. Operations not
2040mentioned here will be handled by `tramp-file-name-handler-alist' or the
2041normal Emacs functions.")
2042
4007ba5b 2043;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
ea9d1443
KG
2044(defvar tramp-foreign-file-name-handler-alist
2045 ;; (identity . tramp-sh-file-name-handler) should always be the last
b88f2d0a 2046 ;; entry, because `identity' always matches.
ea9d1443 2047 '((identity . tramp-sh-file-name-handler))
4007ba5b
KG
2048 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2049If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2050calling HANDLER.")
2051
0664ff72 2052;;; Internal functions which must come first:
fb7933a3 2053
00d6fd04
MA
2054(defsubst tramp-debug-message (vec fmt-string &rest args)
2055 "Append message to debug buffer.
2056Message is formatted with FMT-STRING as control string and the remaining
2057ARGS to actually emit the message (if applicable)."
2058 (when (get-buffer (tramp-buffer-name vec))
2059 (with-current-buffer (tramp-get-debug-buffer vec)
2060 (goto-char (point-max))
70c11b0b
MA
2061 ;; Headline.
2062 (when (bobp)
2063 (insert
2064 (format
2065 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2066 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2067 emacs-version tramp-version)))
00d6fd04
MA
2068 (unless (bolp)
2069 (insert "\n"))
70c11b0b 2070 ;; Timestamp.
736ac90f
MA
2071 (let ((now (current-time)))
2072 (insert (format-time-string "%T." now))
2073 (insert (format "%06d " (nth 2 now))))
70c11b0b 2074 ;; Calling function.
00d6fd04
MA
2075 (let ((btn 1) btf fn)
2076 (while (not fn)
2077 (setq btf (nth 1 (backtrace-frame btn)))
2078 (if (not btf)
2079 (setq fn "")
2080 (when (symbolp btf)
2081 (setq fn (symbol-name btf))
2082 (unless (and (string-match "^tramp" fn)
2083 (not (string-match
2084 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
2085 fn)))
2086 (setq fn nil)))
2087 (setq btn (1+ btn))))
2088 ;; The following code inserts filename and line number.
2089 ;; Should be deactivated by default, because it is time
2090 ;; consuming.
2091; (let ((ffn (find-function-noselect (intern fn))))
2092; (insert
2093; (format
2094; "%s:%d: "
2095; (file-name-nondirectory (buffer-file-name (car ffn)))
2096; (with-current-buffer (car ffn)
2097; (1+ (count-lines (point-min) (cdr ffn)))))))
2098 (insert (format "%s " fn)))
70c11b0b 2099 ;; The message.
00d6fd04
MA
2100 (insert (apply 'format fmt-string args)))))
2101
946a5aeb
MA
2102(defvar tramp-message-show-message t
2103 "Show Tramp message in the minibuffer.
2104This variable is used to disable messages from `tramp-error'.
2105The messages are visible anyway, because an error is raised.")
2106
00d6fd04 2107(defsubst tramp-message (vec-or-proc level fmt-string &rest args)
fb7933a3 2108 "Emit a message depending on verbosity level.
a4aeb9a4 2109VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
00d6fd04
MA
2110vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2111less than LEVEL. The message is emitted only if `tramp-verbose' is
2112greater than or equal to LEVEL.
2113
2114The message is also logged into the debug buffer when `tramp-verbose'
2115is greater than or equal 4.
2116
2117Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2118control string and the remaining ARGS to actually emit the message (if
2119applicable)."
2120 (condition-case nil
2121 (when (<= level tramp-verbose)
2122 ;; Match data must be preserved!
2123 (save-match-data
2124 ;; Display only when there is a minimum level.
946a5aeb 2125 (when (and tramp-message-show-message (<= level 3))
00d6fd04
MA
2126 (apply 'message
2127 (concat
2128 (cond
2129 ((= level 0) "")
2130 ((= level 1) "")
2131 ((= level 2) "Warning: ")
2132 (t "Tramp: "))
2133 fmt-string)
2134 args))
2135 ;; Log only when there is a minimum level.
2136 (when (>= tramp-verbose 4)
2137 (when (and vec-or-proc
2138 (processp vec-or-proc)
2139 (buffer-name (process-buffer vec-or-proc)))
2140 (with-current-buffer (process-buffer vec-or-proc)
2141 ;; Translate proc to vec.
2142 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2143 (when (and vec-or-proc (vectorp vec-or-proc))
2144 (apply 'tramp-debug-message
2145 vec-or-proc
2146 (concat (format "(%d) # " level) fmt-string)
2147 args)))))
2148 ;; Suppress all errors.
2149 (error nil)))
2150
2151(defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2152 "Emit an error.
2153VEC-OR-PROC identifies the connection to use, SIGNAL is the
2154signal identifier to be raised, remaining args passed to
2155`tramp-message'. Finally, signal SIGNAL is raised."
946a5aeb
MA
2156 (let (tramp-message-show-message)
2157 (tramp-message
2158 vec-or-proc 1 "%s"
2159 (error-message-string
2160 (list signal
2161 (get signal 'error-message)
2162 (apply 'format fmt-string args))))
2163 (signal signal (list (apply 'format fmt-string args)))))
00d6fd04
MA
2164
2165(defsubst tramp-error-with-buffer
2166 (buffer vec-or-proc signal fmt-string &rest args)
2167 "Emit an error, and show BUFFER.
2168If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2169an input event arrives. The other arguments are passed to `tramp-error'."
2170 (save-window-excursion
2171 (unwind-protect
2172 (apply 'tramp-error vec-or-proc signal fmt-string args)
4874f5e6
MA
2173 (when (and vec-or-proc
2174 (not (zerop tramp-verbose))
2175 (not (tramp-completion-mode-p)))
00d6fd04
MA
2176 (let ((enable-recursive-minibuffers t))
2177 (pop-to-buffer
2178 (or (and (bufferp buffer) buffer)
2179 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2180 (tramp-get-buffer vec-or-proc)))
2181 (sit-for 30))))))
fb7933a3 2182
c62c9d08
KG
2183(defmacro with-parsed-tramp-file-name (filename var &rest body)
2184 "Parse a Tramp filename and make components available in the body.
2185
2186First arg FILENAME is evaluated and dissected into its components.
2187Second arg VAR is a symbol. It is used as a variable name to hold
2188the filename structure. It is also used as a prefix for the variables
2189holding the components. For example, if VAR is the symbol `foo', then
00d6fd04
MA
2190`foo' will be bound to the whole structure, `foo-method' will be bound to
2191the method component, and so on for `foo-user', `foo-host', `foo-localname'.
c62c9d08
KG
2192
2193Remaining args are Lisp expressions to be evaluated (inside an implicit
2194`progn').
2195
00d6fd04
MA
2196If VAR is nil, then we bind `v' to the structure and `method', `user',
2197`host', `localname' to the components."
c62c9d08 2198 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
c62c9d08
KG
2199 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2200 (tramp-file-name-method ,(or var 'v)))
2201 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2202 (tramp-file-name-user ,(or var 'v)))
2203 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2204 (tramp-file-name-host ,(or var 'v)))
7432277c
KG
2205 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2206 (tramp-file-name-localname ,(or var 'v))))
c62c9d08
KG
2207 ,@body))
2208
2209(put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
00d6fd04 2210(put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
9e6ab520 2211(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
c62c9d08 2212
00d6fd04
MA
2213(defmacro with-file-property (vec file property &rest body)
2214 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2215FILE must be a local file name on a connection identified via VEC."
2216 `(if (file-name-absolute-p ,file)
2217 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2218 (when (eq value 'undef)
2219 ;; We cannot pass @body as parameter to
2220 ;; `tramp-set-file-property' because it mangles our
2221 ;; debug messages.
2222 (setq value (progn ,@body))
2223 (tramp-set-file-property ,vec ,file ,property value))
2224 value)
2225 ,@body))
9ce8462a 2226
00d6fd04
MA
2227(put 'with-file-property 'lisp-indent-function 3)
2228(put 'with-file-property 'edebug-form-spec t)
9e6ab520 2229(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
00d6fd04
MA
2230
2231(defmacro with-connection-property (key property &rest body)
2232 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2233 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2234 (when (eq value 'undef)
2235 ;; We cannot pass ,@body as parameter to
2236 ;; `tramp-set-connection-property' because it mangles our debug
2237 ;; messages.
2238 (setq value (progn ,@body))
2239 (tramp-set-connection-property ,key ,property value))
2240 value))
9ce8462a 2241
00d6fd04
MA
2242(put 'with-connection-property 'lisp-indent-function 2)
2243(put 'with-connection-property 'edebug-form-spec t)
9e6ab520 2244(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
00d6fd04 2245
628c97b2
GM
2246(eval-and-compile ; silence compiler
2247 (if (memq system-type '(cygwin windows-nt))
2248 (defun tramp-drop-volume-letter (name)
2249 "Cut off unnecessary drive letter from file NAME.
2250The function `tramp-handle-expand-file-name' calls `expand-file-name'
2251locally on a remote file name. When the local system is a W32 system
2252but the remote system is Unix, this introduces a superfluous drive
2253letter into the file name. This function removes it."
2254 (save-match-data
2255 (if (string-match tramp-root-regexp name)
2256 (replace-match "/" nil t name)
2257 name)))
2258
2259 (defalias 'tramp-drop-volume-letter 'identity)))
2260
9c13938d 2261(defsubst tramp-make-tramp-temp-file (vec)
a6e96327 2262 "Create a temporary file on the remote host identified by VEC.
9c13938d
MA
2263Return the local name of the temporary file."
2264 (let ((prefix
2265 (tramp-make-tramp-file-name
2266 (tramp-file-name-method vec)
2267 (tramp-file-name-user vec)
2268 (tramp-file-name-host vec)
113e2a84
MA
2269 (tramp-drop-volume-letter
2270 (expand-file-name
2271 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
9c13938d
MA
2272 result)
2273 (while (not result)
2274 ;; `make-temp-file' would be the natural choice for
2275 ;; implementation. But it calls `write-region' internally,
2276 ;; which also needs a temporary file - we would end in an
2277 ;; infinite loop.
2278 (setq result (make-temp-name prefix))
2279 (if (file-exists-p result)
2280 (setq result nil)
2281 ;; This creates the file by side effect.
2282 (set-file-times result)
2283 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2284
2285 ;; Return the local part.
2286 (with-parsed-tramp-file-name result nil localname)))
8a4438b6
MA
2287
2288
16674e4f
KG
2289;;; Config Manipulation Functions:
2290
2291(defun tramp-set-completion-function (method function-list)
2292 "Sets the list of completion functions for METHOD.
2293FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2294The FUNCTION is intended to parse FILE according its syntax.
2295It might be a predefined FUNCTION, or a user defined FUNCTION.
2296Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
8fc29035 2297`tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
8daea7fc
KG
2298and `tramp-parse-netrc'.
2299
16674e4f
KG
2300Example:
2301
2302 (tramp-set-completion-function
2303 \"ssh\"
8daea7fc
KG
2304 '((tramp-parse-sconfig \"/etc/ssh_config\")
2305 (tramp-parse-sconfig \"~/.ssh/config\")))"
16674e4f 2306
5ec2cc41
KG
2307 (let ((r function-list)
2308 (v function-list))
2309 (setq tramp-completion-function-alist
2310 (delete (assoc method tramp-completion-function-alist)
2311 tramp-completion-function-alist))
2312
2313 (while v
00d6fd04 2314 ;; Remove double entries.
5ec2cc41
KG
2315 (when (member (car v) (cdr v))
2316 (setcdr v (delete (car v) (cdr v))))
00d6fd04 2317 ;; Check for function and file or registry key.
5ec2cc41 2318 (unless (and (functionp (nth 0 (car v)))
00d6fd04
MA
2319 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2320 ;; Windows registry.
2321 (and (memq system-type '(cygwin windows-nt))
a4aeb9a4
MA
2322 (zerop
2323 (tramp-local-call-process
2324 "reg" nil nil nil "query" (nth 1 (car v)))))
00d6fd04
MA
2325 ;; Configuration file.
2326 (file-exists-p (nth 1 (car v)))))
5ec2cc41
KG
2327 (setq r (delete (car v) r)))
2328 (setq v (cdr v)))
2329
2330 (when r
4007ba5b 2331 (add-to-list 'tramp-completion-function-alist
5ec2cc41 2332 (cons method r)))))
16674e4f
KG
2333
2334(defun tramp-get-completion-function (method)
00d6fd04 2335 "Returns a list of completion functions for METHOD.
16674e4f 2336For definition of that list see `tramp-set-completion-function'."
00d6fd04
MA
2337 (cons
2338 ;; Hosts visited once shall be remembered.
2339 `(tramp-parse-connection-properties ,method)
2340 ;; The method related defaults.
2341 (cdr (assoc method tramp-completion-function-alist))))
16674e4f 2342
d037d501 2343
0664ff72 2344;;; Fontification of `read-file-name':
d037d501 2345
0664ff72 2346;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
d037d501
MA
2347(defvar tramp-rfn-eshadow-overlay)
2348(make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2349
2350(defun tramp-rfn-eshadow-setup-minibuffer ()
2351 "Set up a minibuffer for `file-name-shadow-mode'.
2352Adds another overlay hiding filename parts according to Tramp's
2353special handling of `substitute-in-file-name'."
9ce8462a 2354 (when (symbol-value 'minibuffer-completing-file-name)
d037d501 2355 (setq tramp-rfn-eshadow-overlay
9e6ab520
MA
2356 (funcall (symbol-function 'make-overlay)
2357 (funcall (symbol-function 'minibuffer-prompt-end))
2358 (funcall (symbol-function 'minibuffer-prompt-end))))
d037d501 2359 ;; Copy rfn-eshadow-overlay properties.
9e6ab520
MA
2360 (let ((props (funcall (symbol-function 'overlay-properties)
2361 (symbol-value 'rfn-eshadow-overlay))))
d037d501 2362 (while props
9e6ab520
MA
2363 (funcall (symbol-function 'overlay-put)
2364 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
d037d501
MA
2365
2366(when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2367 (add-hook 'rfn-eshadow-setup-minibuffer-hook
48846dc5
MA
2368 'tramp-rfn-eshadow-setup-minibuffer)
2369 (add-hook 'tramp-unload-hook
aa485f7c
MA
2370 (lambda ()
2371 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2372 'tramp-rfn-eshadow-setup-minibuffer))))
d037d501 2373
adcbca53
MA
2374(defconst tramp-rfn-eshadow-update-overlay-regexp
2375 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2376
d037d501
MA
2377(defun tramp-rfn-eshadow-update-overlay ()
2378 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2379This is intended to be used as a minibuffer `post-command-hook' for
2380`file-name-shadow-mode'; the minibuffer should have already
2381been set up by `rfn-eshadow-setup-minibuffer'."
2382 ;; In remote files name, there is a shadowing just for the local part.
9e6ab520
MA
2383 (let ((end (or (funcall (symbol-function 'overlay-end)
2384 (symbol-value 'rfn-eshadow-overlay))
2385 (funcall (symbol-function 'minibuffer-prompt-end)))))
2386 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
bd316474
KY
2387 (save-excursion
2388 (save-restriction
2389 (narrow-to-region
adcbca53
MA
2390 (1+ (or (string-match
2391 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2392 end))
2393 (point-max))
bd316474
KY
2394 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2395 (rfn-eshadow-update-overlay-hook nil))
dea31ca6 2396 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
bd316474 2397 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
d037d501
MA
2398
2399(when (boundp 'rfn-eshadow-update-overlay-hook)
2400 (add-hook 'rfn-eshadow-update-overlay-hook
b88f2d0a
MA
2401 'tramp-rfn-eshadow-update-overlay)
2402 (add-hook 'tramp-unload-hook
2403 (lambda ()
2404 (remove-hook 'rfn-eshadow-update-overlay-hook
2405 'tramp-rfn-eshadow-update-overlay))))
d037d501
MA
2406
2407
605a20a9
MA
2408;;; Integration of eshell.el:
2409
2410(eval-when-compile
2411 (defvar eshell-path-env))
2412
2413;; eshell.el keeps the path in `eshell-path-env'. We must change it
2414;; when `default-directory' points to another host.
2415(defun tramp-eshell-directory-change ()
2416 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2417 (setq eshell-path-env
2418 (if (file-remote-p default-directory)
2419 (with-parsed-tramp-file-name default-directory nil
2420 (mapconcat
2421 'identity
2422 (tramp-get-remote-path v)
2423 ":"))
2424 (getenv "PATH"))))
2425
2426(eval-after-load "esh-util"
2427 '(progn
2428 (tramp-eshell-directory-change)
2429 (add-hook 'eshell-directory-change-hook
2430 'tramp-eshell-directory-change)
2431 (add-hook 'tramp-unload-hook
2432 (lambda ()
2433 (remove-hook 'eshell-directory-change-hook
2434 'tramp-eshell-directory-change)))))
2435
2436
fb7933a3
KG
2437;;; File Name Handler Functions:
2438
fb7933a3
KG
2439(defun tramp-handle-make-symbolic-link
2440 (filename linkname &optional ok-if-already-exists)
00d6fd04 2441 "Like `make-symbolic-link' for Tramp files.
cebb4ec6 2442If LINKNAME is a non-Tramp file, it is used verbatim as the target of
7432277c 2443the symlink. If LINKNAME is a Tramp file, only the localname component is
cebb4ec6
KG
2444used as the target of the symlink.
2445
7432277c
KG
2446If LINKNAME is a Tramp file and the localname component is relative, then
2447it is expanded first, before the localname component is taken. Note that
cebb4ec6
KG
2448this can give surprising results if the user/host for the source and
2449target of the symlink differ."
c62c9d08 2450 (with-parsed-tramp-file-name linkname l
00d6fd04 2451 (let ((ln (tramp-get-remote-ln l))
87bdd2c7
MA
2452 (cwd (tramp-run-real-handler
2453 'file-name-directory (list l-localname))))
c62c9d08 2454 (unless ln
00d6fd04
MA
2455 (tramp-error
2456 l 'file-error
2457 "Making a symbolic link. ln(1) does not exist on the remote host."))
c62c9d08
KG
2458
2459 ;; Do the 'confirm if exists' thing.
cebb4ec6 2460 (when (file-exists-p linkname)
c62c9d08
KG
2461 ;; What to do?
2462 (if (or (null ok-if-already-exists) ; not allowed to exist
2463 (and (numberp ok-if-already-exists)
2464 (not (yes-or-no-p
2465 (format
2466 "File %s already exists; make it a link anyway? "
7432277c 2467 l-localname)))))
00d6fd04
MA
2468 (tramp-error
2469 l 'file-already-exists "File %s already exists" l-localname)
cebb4ec6
KG
2470 (delete-file linkname)))
2471
7432277c 2472 ;; If FILENAME is a Tramp name, use just the localname component.
cebb4ec6 2473 (when (tramp-tramp-file-p filename)
1834b39f
MA
2474 (setq filename
2475 (tramp-file-name-localname
2476 (tramp-dissect-file-name (expand-file-name filename)))))
bf247b6e 2477
c62c9d08
KG
2478 ;; Right, they are on the same host, regardless of user, method, etc.
2479 ;; We now make the link on the remote machine. This will occur as the user
2480 ;; that FILENAME belongs to.
2481 (zerop
2482 (tramp-send-command-and-check
b593f105
MA
2483 l
2484 (format
2485 "cd %s && %s -sf %s %s"
2486 (tramp-shell-quote-argument cwd)
2487 ln
2488 (tramp-shell-quote-argument filename)
2489 (tramp-shell-quote-argument l-localname))
2490 t)))))
fb7933a3 2491
fb7933a3 2492(defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
00d6fd04
MA
2493 "Like `load' for Tramp files."
2494 (with-parsed-tramp-file-name (expand-file-name file) nil
c62c9d08
KG
2495 (unless nosuffix
2496 (cond ((file-exists-p (concat file ".elc"))
2497 (setq file (concat file ".elc")))
2498 ((file-exists-p (concat file ".el"))
2499 (setq file (concat file ".el")))))
2500 (when must-suffix
2501 ;; The first condition is always true for absolute file names.
2502 ;; Included for safety's sake.
2503 (unless (or (file-name-directory file)
2504 (string-match "\\.elc?\\'" file))
00d6fd04
MA
2505 (tramp-error
2506 v 'file-error
2507 "File `%s' does not include a `.el' or `.elc' suffix" file)))
c62c9d08
KG
2508 (unless noerror
2509 (when (not (file-exists-p file))
00d6fd04 2510 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
c62c9d08
KG
2511 (if (not (file-exists-p file))
2512 nil
00d6fd04 2513 (unless nomessage (tramp-message v 0 "Loading %s..." file))
c62c9d08
KG
2514 (let ((local-copy (file-local-copy file)))
2515 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
ce2cc728
MA
2516 (unwind-protect
2517 (load local-copy noerror t t)
2518 (delete-file local-copy)))
00d6fd04 2519 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
c62c9d08 2520 t)))
fb7933a3 2521
a4aeb9a4 2522;; Localname manipulation functions that grok Tramp localnames...
c0fc6170
MA
2523(defun tramp-handle-file-name-as-directory (file)
2524 "Like `file-name-as-directory' but aware of Tramp files."
2525 ;; `file-name-as-directory' would be sufficient except localname is
2526 ;; the empty string.
2527 (let ((v (tramp-dissect-file-name file t)))
2528 ;; Run the command on the localname portion only.
2529 (tramp-make-tramp-file-name
2530 (tramp-file-name-method v)
2531 (tramp-file-name-user v)
2532 (tramp-file-name-host v)
2533 (tramp-run-real-handler
2534 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2535
fb7933a3 2536(defun tramp-handle-file-name-directory (file)
00d6fd04 2537 "Like `file-name-directory' but aware of Tramp files."
9ce8462a
MA
2538 ;; Everything except the last filename thing is the directory. We
2539 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2540 ;; the remote file name parts. This is a problem when we are in
2541 ;; file name completion.
2542 (let ((v (tramp-dissect-file-name file t)))
a01b1e22
MA
2543 ;; Run the command on the localname portion only.
2544 (tramp-make-tramp-file-name
9ce8462a
MA
2545 (tramp-file-name-method v)
2546 (tramp-file-name-user v)
2547 (tramp-file-name-host v)
87bdd2c7
MA
2548 (tramp-run-real-handler
2549 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
fb7933a3
KG
2550
2551(defun tramp-handle-file-name-nondirectory (file)
00d6fd04 2552 "Like `file-name-nondirectory' but aware of Tramp files."
c62c9d08 2553 (with-parsed-tramp-file-name file nil
87bdd2c7 2554 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
fb7933a3
KG
2555
2556(defun tramp-handle-file-truename (filename &optional counter prev-dirs)
00d6fd04 2557 "Like `file-truename' for Tramp files."
48ddd622 2558 (with-parsed-tramp-file-name (expand-file-name filename) nil
00d6fd04 2559 (with-file-property v localname "file-truename"
293c24f9 2560 (let ((result nil)) ; result steps in reverse order
00d6fd04 2561 (tramp-message v 4 "Finding true name for `%s'" filename)
293c24f9
MA
2562 (cond
2563 ;; Use GNU readlink --canonicalize-missing where available.
2564 ((tramp-get-remote-readlink v)
2565 (setq result
2566 (tramp-send-command-and-read
2567 v
2568 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2569 (tramp-get-remote-readlink v)
2570 (tramp-shell-quote-argument localname)))))
2571
2572 ;; Use Perl implementation.
2573 ((and (tramp-get-remote-perl v)
2574 (tramp-get-connection-property v "perl-file-spec" nil)
2575 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2576 (tramp-maybe-send-script
2577 v tramp-perl-file-truename "tramp_perl_file_truename")
2578 (setq result
2579 (tramp-send-command-and-read
2580 v
2581 (format "tramp_perl_file_truename %s"
2582 (tramp-shell-quote-argument localname)))))
2583
2584 ;; Do it yourself. We bind `directory-sep-char' here for
2585 ;; XEmacs on Windows, which would otherwise use backslash.
2586 (t (let* ((directory-sep-char ?/)
2587 (steps (tramp-compat-split-string localname "/"))
2588 (localnamedir (tramp-run-real-handler
2589 'file-name-as-directory (list localname)))
2590 (is-dir (string= localname localnamedir))
2591 (thisstep nil)
2592 (numchase 0)
2593 ;; Don't make the following value larger than
2594 ;; necessary. People expect an error message in a
2595 ;; timely fashion when something is wrong;
2596 ;; otherwise they might think that Emacs is hung.
2597 ;; Of course, correctness has to come first.
2598 (numchase-limit 20)
2599 symlink-target)
2600 (while (and steps (< numchase numchase-limit))
2601 (setq thisstep (pop steps))
2602 (tramp-message
2603 v 5 "Check %s"
2604 (mapconcat 'identity
2605 (append '("") (reverse result) (list thisstep))
2606 "/"))
2607 (setq symlink-target
2608 (nth 0 (file-attributes
2609 (tramp-make-tramp-file-name
2610 method user host
2611 (mapconcat 'identity
2612 (append '("")
2613 (reverse result)
2614 (list thisstep))
2615 "/")))))
2616 (cond ((string= "." thisstep)
2617 (tramp-message v 5 "Ignoring step `.'"))
2618 ((string= ".." thisstep)
2619 (tramp-message v 5 "Processing step `..'")
2620 (pop result))
2621 ((stringp symlink-target)
2622 ;; It's a symlink, follow it.
2623 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2624 (setq numchase (1+ numchase))
2625 (when (file-name-absolute-p symlink-target)
2626 (setq result nil))
2627 ;; If the symlink was absolute, we'll get a string like
2628 ;; "/user@host:/some/target"; extract the
2629 ;; "/some/target" part from it.
2630 (when (tramp-tramp-file-p symlink-target)
2631 (unless (tramp-equal-remote filename symlink-target)
2632 (tramp-error
2633 v 'file-error
2634 "Symlink target `%s' on wrong host" symlink-target))
2635 (setq symlink-target localname))
2636 (setq steps
2637 (append (tramp-compat-split-string
2638 symlink-target "/")
2639 steps)))
2640 (t
2641 ;; It's a file.
2642 (setq result (cons thisstep result)))))
2643 (when (>= numchase numchase-limit)
2644 (tramp-error
2645 v 'file-error
2646 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2647 (setq result (reverse result))
2648 ;; Combine list to form string.
2649 (setq result
2650 (if result
2651 (mapconcat 'identity (cons "" result) "/")
00d6fd04 2652 "/"))
293c24f9
MA
2653 (when (and is-dir (or (string= "" result)
2654 (not (string= (substring result -1) "/"))))
2655 (setq result (concat result "/"))))))
2656
2657 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2658 (tramp-make-tramp-file-name method user host result)))))
fb7933a3
KG
2659
2660;; Basic functions.
2661
2662(defun tramp-handle-file-exists-p (filename)
00d6fd04 2663 "Like `file-exists-p' for Tramp files."
c62c9d08 2664 (with-parsed-tramp-file-name filename nil
00d6fd04 2665 (with-file-property v localname "file-exists-p"
293c24f9
MA
2666 (or (not (null (tramp-get-file-property
2667 v localname "file-attributes-integer" nil)))
2668 (not (null (tramp-get-file-property
2669 v localname "file-attributes-string" nil)))
2670 (zerop (tramp-send-command-and-check
2671 v
2672 (format
2673 "%s %s"
2674 (tramp-get-file-exists-command v)
2675 (tramp-shell-quote-argument localname))))))))
fb7933a3 2676
00d6fd04
MA
2677;; Inodes don't exist for some file systems. Therefore we must
2678;; generate virtual ones. Used in `find-buffer-visiting'. The method
2679;; applied might be not so efficient (Ange-FTP uses hashes). But
2680;; performance isn't the major issue given that file transfer will
2681;; take time.
2682(defvar tramp-inodes nil
2683 "Keeps virtual inodes numbers.")
2684
8daea7fc
KG
2685;; Devices must distinguish physical file systems. The device numbers
2686;; provided by "lstat" aren't unique, because we operate on different hosts.
2687;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2688;; EFS use device number "-1". In order to be different, we use device number
b946a456 2689;; (-1 . x), whereby "x" is unique for a given (method user host).
8daea7fc
KG
2690(defvar tramp-devices nil
2691 "Keeps virtual device numbers.")
2692
fb7933a3
KG
2693;; CCC: This should check for an error condition and signal failure
2694;; when something goes wrong.
2695;; Daniel Pittman <daniel@danann.net>
c951aecb 2696(defun tramp-handle-file-attributes (filename &optional id-format)
00d6fd04
MA
2697 "Like `file-attributes' for Tramp files."
2698 (unless id-format (setq id-format 'integer))
aa485f7c
MA
2699 ;; Don't modify `last-coding-system-used' by accident.
2700 (let ((last-coding-system-used last-coding-system-used))
2701 (with-parsed-tramp-file-name (expand-file-name filename) nil
2702 (with-file-property v localname (format "file-attributes-%s" id-format)
7f49fe46
MA
2703 (save-excursion
2704 (tramp-convert-file-attributes
2705 v
2706 (cond
2707 ((tramp-get-remote-stat v)
2708 (tramp-do-file-attributes-with-stat v localname id-format))
2709 ((tramp-get-remote-perl v)
2710 (tramp-do-file-attributes-with-perl v localname id-format))
2711 (t
2712 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2713
2714(defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
00d6fd04 2715 "Implement `file-attributes' for Tramp files using the ls(1) command."
fb7933a3
KG
2716 (let (symlinkp dirp
2717 res-inode res-filemodes res-numlinks
2718 res-uid res-gid res-size res-symlink-target)
00d6fd04 2719 (tramp-message vec 5 "file attributes with ls: %s" localname)
fb7933a3 2720 (tramp-send-command
00d6fd04 2721 vec
680db9ac
MA
2722 (format "(%s %s || %s -h %s) && %s %s %s"
2723 (tramp-get-file-exists-command vec)
2724 (tramp-shell-quote-argument localname)
2725 (tramp-get-test-command vec)
2726 (tramp-shell-quote-argument localname)
00d6fd04 2727 (tramp-get-ls-command vec)
c82c5727 2728 (if (eq id-format 'integer) "-ildn" "-ild")
7432277c 2729 (tramp-shell-quote-argument localname)))
fb7933a3 2730 ;; parse `ls -l' output ...
00d6fd04 2731 (with-current-buffer (tramp-get-buffer vec)
680db9ac
MA
2732 (when (> (buffer-size) 0)
2733 (goto-char (point-min))
2734 ;; ... inode
2735 (setq res-inode
2736 (condition-case err
2737 (read (current-buffer))
2738 (invalid-read-syntax
2739 (when (and (equal (cadr err)
2740 "Integer constant overflow in reader")
2741 (string-match
2742 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2743 (car (cddr err))))
2744 (let* ((big (read (substring (car (cddr err)) 0
2745 (match-beginning 1))))
2746 (small (read (match-string 1 (car (cddr err)))))
2747 (twiddle (/ small 65536)))
2748 (cons (+ big twiddle)
2749 (- small (* twiddle 65536))))))))
2750 ;; ... file mode flags
2751 (setq res-filemodes (symbol-name (read (current-buffer))))
2752 ;; ... number links
2753 (setq res-numlinks (read (current-buffer)))
2754 ;; ... uid and gid
2755 (setq res-uid (read (current-buffer)))
2756 (setq res-gid (read (current-buffer)))
2757 (if (eq id-format 'integer)
2758 (progn
2759 (unless (numberp res-uid) (setq res-uid -1))
2760 (unless (numberp res-gid) (setq res-gid -1)))
2761 (progn
2762 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2763 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2764 ;; ... size
2765 (setq res-size (read (current-buffer)))
2766 ;; From the file modes, figure out other stuff.
2767 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2768 (setq dirp (eq ?d (aref res-filemodes 0)))
2769 ;; if symlink, find out file name pointed to
2770 (when symlinkp
2771 (search-forward "-> ")
2772 (setq res-symlink-target
2773 (buffer-substring (point) (tramp-compat-line-end-position))))
2774 ;; return data gathered
2775 (list
2776 ;; 0. t for directory, string (name linked to) for symbolic
2777 ;; link, or nil.
2778 (or dirp res-symlink-target)
2779 ;; 1. Number of links to file.
2780 res-numlinks
2781 ;; 2. File uid.
2782 res-uid
2783 ;; 3. File gid.
2784 res-gid
2785 ;; 4. Last access time, as a list of two integers. First
2786 ;; integer has high-order 16 bits of time, second has low 16
2787 ;; bits.
2788 ;; 5. Last modification time, likewise.
2789 ;; 6. Last status change time, likewise.
2790 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2791 ;; 7. Size in bytes (-1, if number is out of range).
2792 res-size
2793 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2794 res-filemodes
2795 ;; 9. t if file's gid would change if file were deleted and
2796 ;; recreated. Will be set in `tramp-convert-file-attributes'
2797 t
2798 ;; 10. inode number.
2799 res-inode
2800 ;; 11. Device number. Will be replaced by a virtual device number.
2801 -1
2802 )))))
fb7933a3 2803
7f49fe46 2804(defun tramp-do-file-attributes-with-perl
00d6fd04
MA
2805 (vec localname &optional id-format)
2806 "Implement `file-attributes' for Tramp files using a Perl script."
2807 (tramp-message vec 5 "file attributes with perl: %s" localname)
2808 (tramp-maybe-send-script
2809 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2810 (tramp-send-command-and-read
2811 vec
2812 (format "tramp_perl_file_attributes %s %s"
2813 (tramp-shell-quote-argument localname) id-format)))
2814
7f49fe46 2815(defun tramp-do-file-attributes-with-stat
00d6fd04
MA
2816 (vec localname &optional id-format)
2817 "Implement `file-attributes' for Tramp files using stat(1) command."
2818 (tramp-message vec 5 "file attributes with stat: %s" localname)
2819 (tramp-send-command-and-read
2820 vec
2821 (format
680db9ac
MA
2822 "((%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s || echo nil)"
2823 (tramp-get-file-exists-command vec)
2824 (tramp-shell-quote-argument localname)
2825 (tramp-get-test-command vec)
2826 (tramp-shell-quote-argument localname)
00d6fd04
MA
2827 (tramp-get-remote-stat vec)
2828 (if (eq id-format 'integer) "%u" "\"%U\"")
2829 (if (eq id-format 'integer) "%g" "\"%G\"")
2830 (tramp-shell-quote-argument localname))))
8daea7fc 2831
fb7933a3 2832(defun tramp-handle-set-visited-file-modtime (&optional time-list)
00d6fd04 2833 "Like `set-visited-file-modtime' for Tramp files."
fb7933a3
KG
2834 (unless (buffer-file-name)
2835 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2836 (buffer-name)))
48ddd622
MA
2837 (if time-list
2838 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
11948172
MA
2839 (let ((f (buffer-file-name))
2840 coding-system-used)
48ddd622
MA
2841 (with-parsed-tramp-file-name f nil
2842 (let* ((attr (file-attributes f))
2843 ;; '(-1 65535) means file doesn't exists yet.
2844 (modtime (or (nth 5 attr) '(-1 65535))))
11948172
MA
2845 (when (boundp 'last-coding-system-used)
2846 (setq coding-system-used (symbol-value 'last-coding-system-used)))
48ddd622 2847 ;; We use '(0 0) as a don't-know value. See also
7f49fe46 2848 ;; `tramp-do-file-attributes-with-ls'.
48ddd622
MA
2849 (if (not (equal modtime '(0 0)))
2850 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
00d6fd04 2851 (progn
48ddd622 2852 (tramp-send-command
00d6fd04 2853 v
48ddd622 2854 (format "%s -ild %s"
00d6fd04 2855 (tramp-get-ls-command v)
48ddd622 2856 (tramp-shell-quote-argument localname)))
48ddd622
MA
2857 (setq attr (buffer-substring (point)
2858 (progn (end-of-line) (point)))))
00d6fd04
MA
2859 (tramp-set-file-property
2860 v localname "visited-file-modtime-ild" attr))
11948172
MA
2861 (when (boundp 'last-coding-system-used)
2862 (set 'last-coding-system-used coding-system-used))
d2a2c17f 2863 nil)))))
fb7933a3 2864
c62c9d08
KG
2865;; This function makes the same assumption as
2866;; `tramp-handle-set-visited-file-modtime'.
2867(defun tramp-handle-verify-visited-file-modtime (buf)
00d6fd04 2868 "Like `verify-visited-file-modtime' for Tramp files.
c08e6004
MA
2869At the time `verify-visited-file-modtime' calls this function, we
2870already know that the buffer is visiting a file and that
2871`visited-file-modtime' does not return 0. Do not call this
2872function directly, unless those two cases are already taken care
2873of."
c62c9d08 2874 (with-current-buffer buf
b15d0c4c
MA
2875 ;; There is no file visiting the buffer, or the buffer has no
2876 ;; recorded last modification time.
2877 (if (or (not (buffer-file-name))
2878 (eq (visited-file-modtime) 0))
d2a2c17f 2879 t
b15d0c4c
MA
2880 (let ((f (buffer-file-name)))
2881 (with-parsed-tramp-file-name f nil
bce04fee 2882 (tramp-flush-file-property v localname)
b15d0c4c
MA
2883 (let* ((attr (file-attributes f))
2884 (modtime (nth 5 attr))
2885 (mt (visited-file-modtime)))
bf247b6e 2886
70c11b0b
MA
2887 (cond
2888 ;; File exists, and has a known modtime.
b15d0c4c
MA
2889 ((and attr (not (equal modtime '(0 0))))
2890 (< (abs (tramp-time-diff
2891 modtime
2892 ;; For compatibility, deal with both the old
70c11b0b
MA
2893 ;; (HIGH . LOW) and the new (HIGH LOW) return
2894 ;; values of `visited-file-modtime'.
b15d0c4c
MA
2895 (if (atom (cdr mt))
2896 (list (car mt) (cdr mt))
2897 mt)))
2898 2))
70c11b0b 2899 ;; Modtime has the don't know value.
b15d0c4c 2900 (attr
00d6fd04
MA
2901 (tramp-send-command
2902 v
2903 (format "%s -ild %s"
2904 (tramp-get-ls-command v)
2905 (tramp-shell-quote-argument localname)))
2906 (with-current-buffer (tramp-get-buffer v)
b15d0c4c
MA
2907 (setq attr (buffer-substring
2908 (point) (progn (end-of-line) (point)))))
00d6fd04
MA
2909 (equal
2910 attr
2911 (tramp-get-file-property
2912 v localname "visited-file-modtime-ild" "")))
70c11b0b
MA
2913 ;; If file does not exist, say it is not modified if and
2914 ;; only if that agrees with the buffer's record.
b15d0c4c 2915 (t (equal mt '(-1 65535))))))))))
c62c9d08 2916
fb7933a3 2917(defun tramp-handle-set-file-modes (filename mode)
00d6fd04 2918 "Like `set-file-modes' for Tramp files."
c62c9d08 2919 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2920 (tramp-flush-file-property v localname)
2921 (unless (zerop (tramp-send-command-and-check
2922 v
2923 (format "chmod %s %s"
2924 (tramp-decimal-to-octal mode)
2925 (tramp-shell-quote-argument localname))))
2926 ;; FIXME: extract the proper text from chmod's stderr.
2927 (tramp-error
2928 v 'file-error "Error while changing file's mode %s" filename))))
fb7933a3 2929
ce3f516f
MA
2930(defun tramp-handle-set-file-times (filename &optional time)
2931 "Like `set-file-times' for Tramp files."
2932 (zerop
9e6ab520 2933 (if (file-remote-p filename)
ce3f516f 2934 (with-parsed-tramp-file-name filename nil
8d60099b 2935 (tramp-flush-file-property v localname)
ce3f516f
MA
2936 (let ((time (if (or (null time) (equal time '(0 0)))
2937 (current-time)
2938 time))
2939 (utc
2940 ;; With GNU Emacs, `format-time-string' has an
2941 ;; optional parameter UNIVERSAL. This is preferred,
2942 ;; because we could handle the case when the remote
2943 ;; host is located in a different time zone as the
2944 ;; local host.
2945 (and (functionp 'subr-arity)
2946 (subrp (symbol-function 'format-time-string))
2947 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2948 (symbol-function
2949 'format-time-string)))))))
2950 (tramp-send-command-and-check
2951 v (format "%s touch -t %s %s"
2952 (if utc "TZ=UTC; export TZ;" "")
2953 (if utc
2954 (format-time-string "%Y%m%d%H%M.%S" time t)
2955 (format-time-string "%Y%m%d%H%M.%S" time))
2956 (tramp-shell-quote-argument localname)))))
8d60099b 2957
ce3f516f
MA
2958 ;; We handle also the local part, because in older Emacsen,
2959 ;; without `set-file-times', this function is an alias for this.
2960 ;; We are local, so we don't need the UTC settings.
a4aeb9a4 2961 (tramp-local-call-process
ce3f516f
MA
2962 "touch" nil nil nil "-t"
2963 (format-time-string "%Y%m%d%H%M.%S" time)
2964 (tramp-shell-quote-argument filename)))))
2965
8d60099b
MA
2966(defun tramp-set-file-uid-gid (filename &optional uid gid)
2967 "Set the ownership for FILENAME.
2968If UID and GID are provided, these values are used; otherwise uid
2969and gid of the corresponding user is taken. Both parameters must be integers."
70c11b0b
MA
2970 ;; Modern Unices allow chown only for root. So we might need
2971 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2972 ;; working with su(do)? when it is needed, so it shall succeed in
2973 ;; the majority of cases.
aa485f7c
MA
2974 ;; Don't modify `last-coding-system-used' by accident.
2975 (let ((last-coding-system-used last-coding-system-used))
2976 (if (file-remote-p filename)
2977 (with-parsed-tramp-file-name filename nil
2978 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2979 ;; If we are root on the local host, we can do it directly.
2980 (tramp-set-file-uid-gid localname uid gid)
2981 (let ((uid (or (and (integerp uid) uid)
2982 (tramp-get-remote-uid v 'integer)))
2983 (gid (or (and (integerp gid) gid)
2984 (tramp-get-remote-gid v 'integer))))
2985 (tramp-send-command
2986 v (format
2987 "chown %d:%d %s" uid gid
2988 (tramp-shell-quote-argument localname))))))
2989
2990 ;; We handle also the local part, because there doesn't exist
2991 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2992 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2993 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2994 (tramp-local-call-process
2995 "chown" nil nil nil
2996 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
8d60099b 2997
fb7933a3
KG
2998;; Simple functions using the `test' command.
2999
3000(defun tramp-handle-file-executable-p (filename)
00d6fd04 3001 "Like `file-executable-p' for Tramp files."
c62c9d08 3002 (with-parsed-tramp-file-name filename nil
00d6fd04 3003 (with-file-property v localname "file-executable-p"
293c24f9
MA
3004 ;; Examine `file-attributes' cache to see if request can be
3005 ;; satisfied without remote operation.
3006 (or (tramp-check-cached-permissions v ?x)
3007 (zerop (tramp-run-test "-x" filename))))))
fb7933a3
KG
3008
3009(defun tramp-handle-file-readable-p (filename)
00d6fd04 3010 "Like `file-readable-p' for Tramp files."
c62c9d08 3011 (with-parsed-tramp-file-name filename nil
00d6fd04 3012 (with-file-property v localname "file-readable-p"
293c24f9
MA
3013 ;; Examine `file-attributes' cache to see if request can be
3014 ;; satisfied without remote operation.
3015 (or (tramp-check-cached-permissions v ?r)
3016 (zerop (tramp-run-test "-r" filename))))))
fb7933a3
KG
3017
3018;; When the remote shell is started, it looks for a shell which groks
3019;; tilde expansion. Here, we assume that all shells which grok tilde
3020;; expansion will also provide a `test' command which groks `-nt' (for
3021;; newer than). If this breaks, tell me about it and I'll try to do
3022;; something smarter about it.
3023(defun tramp-handle-file-newer-than-file-p (file1 file2)
00d6fd04 3024 "Like `file-newer-than-file-p' for Tramp files."
fb7933a3
KG
3025 (cond ((not (file-exists-p file1))
3026 nil)
3027 ((not (file-exists-p file2))
3028 t)
91879624 3029 ;; We are sure both files exist at this point.
fb7933a3
KG
3030 (t
3031 (save-excursion
91879624
KG
3032 ;; We try to get the mtime of both files. If they are not
3033 ;; equal to the "dont-know" value, then we subtract the times
3034 ;; and obtain the result.
3035 (let ((fa1 (file-attributes file1))
3036 (fa2 (file-attributes file2)))
3037 (if (and (not (equal (nth 5 fa1) '(0 0)))
3038 (not (equal (nth 5 fa2) '(0 0))))
01917a18 3039 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
91879624
KG
3040 ;; If one of them is the dont-know value, then we can
3041 ;; still try to run a shell command on the remote host.
3042 ;; However, this only works if both files are Tramp
3043 ;; files and both have the same method, same user, same
3044 ;; host.
00d6fd04
MA
3045 (unless (tramp-equal-remote file1 file2)
3046 (with-parsed-tramp-file-name
3047 (if (tramp-tramp-file-p file1) file1 file2) nil
3048 (tramp-error
3049 v 'file-error
3050 "Files %s and %s must have same method, user, host"
3051 file1 file2)))
3052 (with-parsed-tramp-file-name file1 nil
3053 (zerop (tramp-run-test2
3054 (tramp-get-test-nt-command v) file1 file2)))))))))
fb7933a3
KG
3055
3056;; Functions implemented using the basic functions above.
3057
3058(defun tramp-handle-file-modes (filename)
00d6fd04 3059 "Like `file-modes' for Tramp files."
5da24108
MA
3060 (let ((truename (or (file-truename filename) filename)))
3061 (when (file-exists-p truename)
3062 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
fb7933a3 3063
b86c1cd8
MA
3064(defun tramp-default-file-modes (filename)
3065 "Return file modes of FILENAME as integer.
3066If the file modes of FILENAME cannot be determined, return the
974647ac
MA
3067value of `default-file-modes', without execute permissions."
3068 (or (file-modes filename)
3069 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
b86c1cd8 3070
fb7933a3 3071(defun tramp-handle-file-directory-p (filename)
00d6fd04 3072 "Like `file-directory-p' for Tramp files."
fb7933a3
KG
3073 ;; Care must be taken that this function returns `t' for symlinks
3074 ;; pointing to directories. Surely the most obvious implementation
3075 ;; would be `test -d', but that returns false for such symlinks.
3076 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3077 ;; I now think he's right. So we could be using `test -d', couldn't
3078 ;; we?
3079 ;;
3080 ;; Alternatives: `cd %s', `test -d %s'
c62c9d08 3081 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3082 (with-file-property v localname "file-directory-p"
3083 (zerop (tramp-run-test "-d" filename)))))
fb7933a3
KG
3084
3085(defun tramp-handle-file-regular-p (filename)
00d6fd04
MA
3086 "Like `file-regular-p' for Tramp files."
3087 (and (file-exists-p filename)
3088 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
fb7933a3
KG
3089
3090(defun tramp-handle-file-symlink-p (filename)
00d6fd04 3091 "Like `file-symlink-p' for Tramp files."
c62c9d08 3092 (with-parsed-tramp-file-name filename nil
c951aecb 3093 (let ((x (car (file-attributes filename))))
b25a52cc
KG
3094 (when (stringp x)
3095 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3096 ;; might do weird things.
3097 (if (file-name-absolute-p x)
00d6fd04 3098 (tramp-make-tramp-file-name method user host x)
b25a52cc 3099 x)))))
fb7933a3
KG
3100
3101(defun tramp-handle-file-writable-p (filename)
00d6fd04 3102 "Like `file-writable-p' for Tramp files."
c62c9d08 3103 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3104 (with-file-property v localname "file-writable-p"
3105 (if (file-exists-p filename)
293c24f9
MA
3106 ;; Examine `file-attributes' cache to see if request can be
3107 ;; satisfied without remote operation.
3108 (or (tramp-check-cached-permissions v ?w)
3109 (zerop (tramp-run-test "-w" filename)))
00d6fd04
MA
3110 ;; If file doesn't exist, check if directory is writable.
3111 (and (zerop (tramp-run-test
3112 "-d" (file-name-directory filename)))
3113 (zerop (tramp-run-test
3114 "-w" (file-name-directory filename))))))))
fb7933a3
KG
3115
3116(defun tramp-handle-file-ownership-preserved-p (filename)
00d6fd04 3117 "Like `file-ownership-preserved-p' for Tramp files."
c62c9d08 3118 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3119 (with-file-property v localname "file-ownership-preserved-p"
3120 (let ((attributes (file-attributes filename)))
3121 ;; Return t if the file doesn't exist, since it's true that no
3122 ;; information would be lost by an (attempted) delete and create.
3123 (or (null attributes)
3124 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
fb7933a3
KG
3125
3126;; Other file name ops.
3127
fb7933a3 3128(defun tramp-handle-directory-file-name (directory)
00d6fd04 3129 "Like `directory-file-name' for Tramp files."
7432277c
KG
3130 ;; If localname component of filename is "/", leave it unchanged.
3131 ;; Otherwise, remove any trailing slash from localname component.
8daea7fc
KG
3132 ;; Method, host, etc, are unchanged. Does it make sense to try
3133 ;; to avoid parsing the filename?
c62c9d08 3134 (with-parsed-tramp-file-name directory nil
7432277c
KG
3135 (if (and (not (zerop (length localname)))
3136 (eq (aref localname (1- (length localname))) ?/)
3137 (not (string= localname "/")))
8daea7fc
KG
3138 (substring directory 0 -1)
3139 directory)))
fb7933a3
KG
3140
3141;; Directory listings.
3142
00d6fd04
MA
3143(defun tramp-handle-directory-files
3144 (directory &optional full match nosort files-only)
3145 "Like `directory-files' for Tramp files."
3146 ;; FILES-ONLY is valid for XEmacs only.
3147 (when (file-directory-p directory)
73a37a69 3148 (setq directory (file-name-as-directory (expand-file-name directory)))
00d6fd04
MA
3149 (let ((temp (nreverse (file-name-all-completions "" directory)))
3150 result item)
3151
3152 (while temp
3153 (setq item (directory-file-name (pop temp)))
3154 (when (and (or (null match) (string-match match item))
3155 (or (null files-only)
73a37a69 3156 ;; Files only.
00d6fd04 3157 (and (equal files-only t) (file-regular-p item))
73a37a69 3158 ;; Directories only.
00d6fd04 3159 (file-directory-p item)))
73a37a69 3160 (push (if full (concat directory item) item)
00d6fd04 3161 result)))
73a37a69 3162 (if nosort result (sort result 'string<)))))
c62c9d08 3163
c82c5727
LH
3164(defun tramp-handle-directory-files-and-attributes
3165 (directory &optional full match nosort id-format)
00d6fd04
MA
3166 "Like `directory-files-and-attributes' for Tramp files."
3167 (unless id-format (setq id-format 'integer))
3168 (when (file-directory-p directory)
3169 (setq directory (expand-file-name directory))
3170 (let* ((temp
b533bc97 3171 (copy-tree
00d6fd04
MA
3172 (with-parsed-tramp-file-name directory nil
3173 (with-file-property
3174 v localname
3175 (format "directory-files-and-attributes-%s" id-format)
3176 (save-excursion
3177 (mapcar
aa485f7c
MA
3178 (lambda (x)
3179 (cons (car x)
3180 (tramp-convert-file-attributes v (cdr x))))
7f49fe46
MA
3181 (cond
3182 ((tramp-get-remote-stat v)
3183 (tramp-do-directory-files-and-attributes-with-stat
3184 v localname id-format))
3185 ((tramp-get-remote-perl v)
3186 (tramp-do-directory-files-and-attributes-with-perl
3187 v localname id-format)))))))))
00d6fd04
MA
3188 result item)
3189
3190 (while temp
3191 (setq item (pop temp))
3192 (when (or (null match) (string-match match (car item)))
3193 (when full
3194 (setcar item (expand-file-name (car item) directory)))
3195 (push item result)))
3196
3197 (if nosort
3198 result
3199 (sort result (lambda (x y) (string< (car x) (car y))))))))
3200
7f49fe46 3201(defun tramp-do-directory-files-and-attributes-with-perl
00d6fd04
MA
3202 (vec localname &optional id-format)
3203 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3204 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3205 (tramp-maybe-send-script
3206 vec tramp-perl-directory-files-and-attributes
3207 "tramp_perl_directory_files_and_attributes")
3208 (let ((object
3209 (tramp-send-command-and-read
3210 vec
3211 (format "tramp_perl_directory_files_and_attributes %s %s"
3212 (tramp-shell-quote-argument localname) id-format))))
3213 (when (stringp object) (tramp-error vec 'file-error object))
3214 object))
3215
7f49fe46 3216(defun tramp-do-directory-files-and-attributes-with-stat
00d6fd04
MA
3217 (vec localname &optional id-format)
3218 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3219 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3220 (tramp-send-command-and-read
3221 vec
3222 (format
3223 (concat
70c11b0b
MA
3224 ;; We must care about filenames with spaces, or starting with
3225 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3226 ;; but it does not work on all remote systems. Therefore, we
3227 ;; quote the filenames via sed.
3228 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
d4443a0d 3229 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
00d6fd04
MA
3230 "echo \")\"")
3231 (tramp-shell-quote-argument localname)
3232 (tramp-get-ls-command vec)
3233 (tramp-get-remote-stat vec)
3234 (if (eq id-format 'integer) "%u" "\"%U\"")
3235 (if (eq id-format 'integer) "%g" "\"%G\""))))
c82c5727 3236
c62c9d08 3237;; This function should return "foo/" for directories and "bar" for
00d6fd04 3238;; files.
c62c9d08 3239(defun tramp-handle-file-name-all-completions (filename directory)
00d6fd04
MA
3240 "Like `file-name-all-completions' for Tramp files."
3241 (unless (save-match-data (string-match "/" filename))
9c13938d 3242 (with-parsed-tramp-file-name (expand-file-name directory) nil
b50dd0d2 3243
00d6fd04
MA
3244 (all-completions
3245 filename
3246 (mapcar
3247 'list
293c24f9
MA
3248 (or
3249 ;; Try cache first
3250 (and
3251 ;; Ignore if expired
3252 (or (not (integerp tramp-completion-reread-directory-timeout))
3253 (<= (tramp-time-diff
3254 (current-time)
3255 (tramp-get-file-property
3256 v localname "last-completion" '(0 0 0)))
3257 tramp-completion-reread-directory-timeout))
3258
3259 ;; Try cache entries for filename, filename with last
3260 ;; character removed, filename with last two characters
3261 ;; removed, ..., and finally the empty string - all
3262 ;; concatenated to the local directory name
3263
3264 ;; This is inefficient for very long filenames, pity
3265 ;; `reduce' is not available...
3266 (car
3267 (apply
3268 'append
3269 (mapcar
3270 (lambda (x)
3271 (let ((cache-hit
3272 (tramp-get-file-property
3273 v
3274 (concat localname (substring filename 0 x))
3275 "file-name-all-completions"
3276 nil)))
3277 (when cache-hit (list cache-hit))))
3278 (tramp-compat-number-sequence (length filename) 0 -1)))))
3279
3280 ;; Cache expired or no matching cache entry found so we need
3281 ;; to perform a remote operation
3282 (let (result)
3283 ;; Get a list of directories and files, including reliably
3284 ;; tagging the directories with a trailing '/'. Because I
3285 ;; rock. --daniel@danann.net
3286
3287 ;; Changed to perform `cd' in the same remote op and only
3288 ;; get entries starting with `filename'. Capture any `cd'
3289 ;; error messages. Ensure any `cd' and `echo' aliases are
3290 ;; ignored.
3291 (tramp-send-command
3292 v
3293 (if (tramp-get-remote-perl v)
3294 (progn
3295 (tramp-maybe-send-script
3296 v tramp-perl-file-name-all-completions
3297 "tramp_perl_file_name_all_completions")
3298 (format "tramp_perl_file_name_all_completions %s %s %d"
3299 (tramp-shell-quote-argument localname)
3300 (tramp-shell-quote-argument filename)
3301 (if (symbol-value
b533bc97
MA
3302 ;; `read-file-name-completion-ignore-case'
3303 ;; is introduced with Emacs 22.1.
3304 (if (boundp
3305 'read-file-name-completion-ignore-case)
3306 'read-file-name-completion-ignore-case
3307 'completion-ignore-case))
293c24f9
MA
3308 1 0)))
3309
3310 (format (concat
3311 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3312 ;; `ls' with wildcard might fail with `Argument
3313 ;; list too long' error in some corner cases; if
3314 ;; `ls' fails after `cd' succeeded, chances are
3315 ;; that's the case, so let's retry without
3316 ;; wildcard. This will return "too many" entries
3317 ;; but that isn't harmful.
3318 " || %s -a 2>/dev/null)"
3319 " | while read f; do"
3320 " if %s -d \"$f\" 2>/dev/null;"
3321 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3322 " && \\echo ok) || \\echo fail")
3323 (tramp-shell-quote-argument localname)
3324 (tramp-get-ls-command v)
3325 ;; When `filename' is empty, just `ls' without
3326 ;; filename argument is more efficient than `ls *'
3327 ;; for very large directories and might avoid the
3328 ;; `Argument list too long' error.
3329 ;;
3330 ;; With and only with wildcard, we need to add
3331 ;; `-d' to prevent `ls' from descending into
3332 ;; sub-directories.
3333 (if (zerop (length filename))
3334 "."
3335 (concat (tramp-shell-quote-argument filename) "* -d"))
3336 (tramp-get-ls-command v)
3337 (tramp-get-test-command v))))
3338
3339 ;; Now grab the output.
3340 (with-current-buffer (tramp-get-buffer v)
3341 (goto-char (point-max))
3342
3343 ;; Check result code, found in last line of output
3344 (forward-line -1)
3345 (if (looking-at "^fail$")
3346 (progn
3347 ;; Grab error message from line before last line
3348 ;; (it was put there by `cd 2>&1')
3349 (forward-line -1)
3350 (tramp-error
3351 v 'file-error
3352 "tramp-handle-file-name-all-completions: %s"
3353 (buffer-substring
3354 (point) (tramp-compat-line-end-position))))
3355 ;; For peace of mind, if buffer doesn't end in `fail'
3356 ;; then it should end in `ok'. If neither are in the
3357 ;; buffer something went seriously wrong on the remote
3358 ;; side.
3359 (unless (looking-at "^ok$")
3360 (tramp-error
3361 v 'file-error
3362 "\
3363tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3364 (tramp-shell-quote-argument localname) (buffer-string))))
3365
3366 (while (zerop (forward-line -1))
3367 (push (buffer-substring
3368 (point) (tramp-compat-line-end-position))
3369 result)))
3370
3371 ;; Because the remote op went through OK we know the
3372 ;; directory we `cd'-ed to exists
3373 (tramp-set-file-property
3374 v localname "file-exists-p" t)
3375
3376 ;; Because the remote op went through OK we know every
3377 ;; file listed by `ls' exists.
3378 (mapc (lambda (entry)
3379 (tramp-set-file-property
3380 v (concat localname entry) "file-exists-p" t))
3381 result)
3382
3383 (tramp-set-file-property
3384 v localname "last-completion" (current-time))
3385
3386 ;; Store result in the cache
3387 (tramp-set-file-property
3388 v (concat localname filename)
3389 "file-name-all-completions"
3390 result))))))))
fb7933a3 3391
e1e17cae
MA
3392(defun tramp-handle-file-name-completion
3393 (filename directory &optional predicate)
00d6fd04 3394 "Like `file-name-completion' for Tramp files."
fb7933a3
KG
3395 (unless (tramp-tramp-file-p directory)
3396 (error
3397 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3398 directory))
83e20b5c
MA
3399 (try-completion
3400 filename
3401 (mapcar 'list (file-name-all-completions filename directory))
3402 (when predicate
3403 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
fb7933a3
KG
3404
3405;; cp, mv and ln
3406
3407(defun tramp-handle-add-name-to-file
3408 (filename newname &optional ok-if-already-exists)
00d6fd04
MA
3409 "Like `add-name-to-file' for Tramp files."
3410 (unless (tramp-equal-remote filename newname)
3411 (with-parsed-tramp-file-name
3412 (if (tramp-tramp-file-p filename) filename newname) nil
3413 (tramp-error
3414 v 'file-error
3415 "add-name-to-file: %s"
3416 "only implemented for same method, same user, same host")))
c62c9d08
KG
3417 (with-parsed-tramp-file-name filename v1
3418 (with-parsed-tramp-file-name newname v2
00d6fd04 3419 (let ((ln (when v1 (tramp-get-remote-ln v1))))
c62c9d08
KG
3420 (when (and (not ok-if-already-exists)
3421 (file-exists-p newname)
3422 (not (numberp ok-if-already-exists))
3423 (y-or-n-p
3424 (format
3425 "File %s already exists; make it a new name anyway? "
3426 newname)))
00d6fd04
MA
3427 (tramp-error
3428 v2 'file-error
3429 "add-name-to-file: file %s already exists" newname))
aac0b0f2 3430 (tramp-flush-file-property v2 (file-name-directory v2-localname))
00d6fd04 3431 (tramp-flush-file-property v2 v2-localname)
c62c9d08 3432 (tramp-barf-unless-okay
00d6fd04 3433 v1
7432277c
KG
3434 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3435 (tramp-shell-quote-argument v2-localname))
c62c9d08
KG
3436 "error with add-name-to-file, see buffer `%s' for details"
3437 (buffer-name))))))
fb7933a3
KG
3438
3439(defun tramp-handle-copy-file
8d60099b 3440 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
00d6fd04 3441 "Like `copy-file' for Tramp files."
fb7933a3 3442 ;; Check if both files are local -- invoke normal copy-file.
9e6ab520 3443 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3444 (setq filename (expand-file-name filename))
3445 (setq newname (expand-file-name newname))
9e6ab520 3446 (cond
a4aeb9a4 3447 ;; At least one file a Tramp file?
9e6ab520
MA
3448 ((or (tramp-tramp-file-p filename)
3449 (tramp-tramp-file-p newname))
3450 (tramp-do-copy-or-rename-file
3451 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3452 ;; Compat section.
3453 (preserve-uid-gid
fb7933a3 3454 (tramp-run-real-handler
8d60099b 3455 'copy-file
9e6ab520
MA
3456 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3457 (t
3458 (tramp-run-real-handler
3459 'copy-file (list filename newname ok-if-already-exists keep-date)))))
fb7933a3 3460
263c02ef
MA
3461(defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3462 "Like `copy-directory' for Tramp files."
3463 (let ((t1 (tramp-tramp-file-p dirname))
3464 (t2 (tramp-tramp-file-p newname)))
3465 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3466 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3467 ;; When DIRNAME and NEWNAME are remote, they must have
3468 ;; the same method.
3469 (or (null t1) (null t2)
b000a6e2
MA
3470 (string-equal
3471 (tramp-file-name-method (tramp-dissect-file-name dirname))
3472 (tramp-file-name-method (tramp-dissect-file-name newname)))))
263c02ef
MA
3473 ;; scp or rsync DTRT.
3474 (progn
3475 (setq dirname (directory-file-name (expand-file-name dirname))
3476 newname (directory-file-name (expand-file-name newname)))
3477 (if (and (file-directory-p newname)
3478 (not (string-equal (file-name-nondirectory dirname)
3479 (file-name-nondirectory newname))))
3480 (setq newname
3481 (expand-file-name
3482 (file-name-nondirectory dirname) newname)))
3483 (if (not (file-directory-p (file-name-directory newname)))
3484 (make-directory (file-name-directory newname) parents))
3485 (tramp-do-copy-or-rename-file-out-of-band
3486 'copy dirname newname keep-date))
3487 ;; We must do it file-wise.
3488 (tramp-run-real-handler
aac0b0f2
MA
3489 'copy-directory (list dirname newname keep-date parents)))
3490
3491 ;; When newname did exist, we have wrong cached values.
3492 (when t2
3493 (with-parsed-tramp-file-name newname nil
3494 (tramp-flush-file-property v (file-name-directory localname))
3495 (tramp-flush-file-property v localname))))))
263c02ef 3496
fb7933a3
KG
3497(defun tramp-handle-rename-file
3498 (filename newname &optional ok-if-already-exists)
00d6fd04 3499 "Like `rename-file' for Tramp files."
fb7933a3 3500 ;; Check if both files are local -- invoke normal rename-file.
a4aeb9a4 3501 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3502 (setq filename (expand-file-name filename))
3503 (setq newname (expand-file-name newname))
a4aeb9a4 3504 ;; At least one file a Tramp file?
fb7933a3
KG
3505 (if (or (tramp-tramp-file-p filename)
3506 (tramp-tramp-file-p newname))
3507 (tramp-do-copy-or-rename-file
8d60099b 3508 'rename filename newname ok-if-already-exists t t)
00d6fd04
MA
3509 (tramp-run-real-handler
3510 'rename-file (list filename newname ok-if-already-exists))))
fb7933a3
KG
3511
3512(defun tramp-do-copy-or-rename-file
8d60099b 3513 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3514 "Copy or rename a remote file.
3515OP must be `copy' or `rename' and indicates the operation to perform.
3516FILENAME specifies the file to copy or rename, NEWNAME is the name of
3517the new file (for copy) or the new name of the file (for rename).
3518OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3519KEEP-DATE means to make sure that NEWNAME has the same timestamp
8d60099b
MA
3520as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3521the uid and gid if both files are on the same host.
fb7933a3
KG
3522
3523This function is invoked by `tramp-handle-copy-file' and
3524`tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3525and `rename'. FILENAME and NEWNAME must be absolute file names."
3526 (unless (memq op '(copy rename))
3527 (error "Unknown operation `%s', must be `copy' or `rename'" op))
90dc758d 3528 (let ((t1 (tramp-tramp-file-p filename))
b6bbb65e
MA
3529 (t2 (tramp-tramp-file-p newname))
3530 pr tm)
5ec2cc41 3531
da1975d7
MA
3532 (when (and (not ok-if-already-exists) (file-exists-p newname))
3533 (with-parsed-tramp-file-name (if t1 filename newname) nil
3534 (tramp-error
3535 v 'file-already-exists "File %s already exists" newname)))
5ec2cc41 3536
905fb90e
MA
3537 (with-parsed-tramp-file-name (if t1 filename newname) nil
3538 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3539
b6bbb65e
MA
3540 ;; We start a pulsing progress reporter. Introduced in Emacs 24.1.
3541 (when (> (nth 7 (file-attributes filename)) tramp-copy-size-limit)
3542 (condition-case nil
3543 (setq pr (funcall
3544 'make-progress-reporter
3545 (format "Transferring %s to %s..." filename newname))
3546 tm (run-at-time 0 0.1 'progress-reporter-update pr))
3547 (error nil)))
3548
3549 (unwind-protect
00d6fd04
MA
3550 (cond
3551 ;; Both are Tramp files.
3552 ((and t1 t2)
3553 (with-parsed-tramp-file-name filename v1
3554 (with-parsed-tramp-file-name newname v2
3555 (cond
3556 ;; Shortcut: if method, host, user are the same for both
3557 ;; files, we invoke `cp' or `mv' on the remote host
3558 ;; directly.
3559 ((tramp-equal-remote filename newname)
3560 (tramp-do-copy-or-rename-file-directly
8d60099b
MA
3561 op filename newname
3562 ok-if-already-exists keep-date preserve-uid-gid))
3563
905fb90e 3564 ;; Try out-of-band operation.
7f49fe46
MA
3565 ((tramp-method-out-of-band-p
3566 v1 (nth 7 (file-attributes filename)))
00d6fd04
MA
3567 (tramp-do-copy-or-rename-file-out-of-band
3568 op filename newname keep-date))
8d60099b 3569
00d6fd04
MA
3570 ;; No shortcut was possible. So we copy the
3571 ;; file first. If the operation was `rename', we go
3572 ;; back and delete the original file (if the copy was
3573 ;; successful). The approach is simple-minded: we
3574 ;; create a new buffer, insert the contents of the
3575 ;; source file into it, then write out the buffer to
3576 ;; the target file. The advantage is that it doesn't
3577 ;; matter which filename handlers are used for the
3578 ;; source and target file.
3579 (t
3580 (tramp-do-copy-or-rename-file-via-buffer
3581 op filename newname keep-date))))))
3582
3583 ;; One file is a Tramp file, the other one is local.
3584 ((or t1 t2)
3585 (with-parsed-tramp-file-name (if t1 filename newname) nil
8d60099b
MA
3586 (cond
3587 ;; Fast track on local machine.
3588 ((tramp-local-host-p v)
3589 (tramp-do-copy-or-rename-file-directly
3590 op filename newname
3591 ok-if-already-exists keep-date preserve-uid-gid))
3592
3593 ;; If the Tramp file has an out-of-band method, the corresponding
3594 ;; copy-program can be invoked.
7f49fe46 3595 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
8d60099b
MA
3596 (tramp-do-copy-or-rename-file-out-of-band
3597 op filename newname keep-date))
3598
3599 ;; Use the inline method via a Tramp buffer.
3600 (t (tramp-do-copy-or-rename-file-via-buffer
3601 op filename newname keep-date)))))
00d6fd04
MA
3602
3603 (t
3604 ;; One of them must be a Tramp file.
3605 (error "Tramp implementation says this cannot happen")))
8d60099b 3606
484ea0b6
MA
3607 ;; In case of `rename', we must flush the cache of the source file.
3608 (when (and t1 (eq op 'rename))
3609 (with-parsed-tramp-file-name filename nil
aac0b0f2 3610 (tramp-flush-file-property v (file-name-directory localname))
484ea0b6
MA
3611 (tramp-flush-file-property v localname)))
3612
00d6fd04
MA
3613 ;; When newname did exist, we have wrong cached values.
3614 (when t2
3615 (with-parsed-tramp-file-name newname nil
aac0b0f2 3616 (tramp-flush-file-property v (file-name-directory localname))
905fb90e
MA
3617 (tramp-flush-file-property v localname)))
3618
b6bbb65e
MA
3619 ;; Stop progress reporter.
3620 (if tm (cancel-timer tm))
905fb90e
MA
3621 (with-parsed-tramp-file-name (if t1 filename newname) nil
3622 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
7432277c 3623
38c65fca 3624(defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
90dc758d
KG
3625 "Use an Emacs buffer to copy or rename a file.
3626First arg OP is either `copy' or `rename' and indicates the operation.
3627FILENAME is the source file, NEWNAME the target file.
3628KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
8a798e41
MA
3629 (with-temp-buffer
3630 ;; We must disable multibyte, because binary data shall not be
3631 ;; converted.
3632 (set-buffer-multibyte nil)
3633 (let ((coding-system-for-read 'binary)
3634 (jka-compr-inhibit t))
3635 (insert-file-contents-literally filename))
3636 ;; We don't want the target file to be compressed, so we let-bind
3637 ;; `jka-compr-inhibit' to t.
3638 (let ((coding-system-for-write 'binary)
3639 (jka-compr-inhibit t))
3640 (write-region (point-min) (point-max) newname)))
3641 ;; KEEP-DATE handling.
3642 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3643 ;; Set the mode.
b86c1cd8 3644 (set-file-modes newname (tramp-default-file-modes filename))
8a798e41
MA
3645 ;; If the operation was `rename', delete the original file.
3646 (unless (eq op 'copy) (delete-file filename)))
fb7933a3
KG
3647
3648(defun tramp-do-copy-or-rename-file-directly
8d60099b 3649 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3650 "Invokes `cp' or `mv' on the remote system.
3651OP must be one of `copy' or `rename', indicating `cp' or `mv',
8d60099b
MA
3652respectively. FILENAME specifies the file to copy or rename,
3653NEWNAME is the name of the new file (for copy) or the new name of
3654the file (for rename). Both files must reside on the same host.
3655KEEP-DATE means to make sure that NEWNAME has the same timestamp
3656as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3657the uid and gid from FILENAME."
8a4438b6 3658 (let ((t1 (tramp-tramp-file-p filename))
4f4126e6
MA
3659 (t2 (tramp-tramp-file-p newname))
3660 (file-times (nth 5 (file-attributes filename)))
3661 (file-modes (tramp-default-file-modes filename)))
8a4438b6
MA
3662 (with-parsed-tramp-file-name (if t1 filename newname) nil
3663 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3664 ((eq op 'copy) "cp -f")
3665 ((eq op 'rename) "mv -f")
3666 (t (tramp-error
3667 v 'file-error
3668 "Unknown operation `%s', must be `copy' or `rename'"
3669 op))))
3670 (localname1
b533bc97
MA
3671 (if t1
3672 (tramp-file-name-handler 'file-remote-p filename 'localname)
3673 filename))
8a4438b6 3674 (localname2
b533bc97
MA
3675 (if t2
3676 (tramp-file-name-handler 'file-remote-p newname 'localname)
3677 newname))
293c24f9
MA
3678 (prefix (file-remote-p (if t1 filename newname)))
3679 cmd-result)
8d60099b 3680
8d60099b 3681 (cond
8a4438b6
MA
3682 ;; Both files are on a remote host, with same user.
3683 ((and t1 t2)
293c24f9
MA
3684 (setq cmd-result
3685 (tramp-send-command-and-check
3686 v
3687 (format "%s %s %s" cmd
3688 (tramp-shell-quote-argument localname1)
3689 (tramp-shell-quote-argument localname2))))
8a4438b6
MA
3690 (with-current-buffer (tramp-get-buffer v)
3691 (goto-char (point-min))
3692 (unless
3693 (or
3694 (and keep-date
3695 ;; Mask cp -f error.
3696 (re-search-forward
3697 tramp-operation-not-permitted-regexp nil t))
293c24f9 3698 (zerop cmd-result))
8a4438b6
MA
3699 (tramp-error-with-buffer
3700 nil v 'file-error
3701 "Copying directly failed, see buffer `%s' for details."
3702 (buffer-name)))))
3703
3704 ;; We are on the local host.
3705 ((or t1 t2)
8d60099b 3706 (cond
8a4438b6 3707 ;; We can do it directly.
87bdd2c7
MA
3708 ((let (file-name-handler-alist)
3709 (and (file-readable-p localname1)
3710 (file-writable-p (file-name-directory localname2))
3711 (or (file-directory-p localname2)
3712 (file-writable-p localname2))))
8d60099b 3713 (if (eq op 'copy)
9e6ab520
MA
3714 (tramp-compat-copy-file
3715 localname1 localname2 ok-if-already-exists
3716 keep-date preserve-uid-gid)
87bdd2c7
MA
3717 (tramp-run-real-handler
3718 'rename-file (list localname1 localname2 ok-if-already-exists))))
8a4438b6
MA
3719
3720 ;; We can do it directly with `tramp-send-command'
946a5aeb
MA
3721 ((and (file-readable-p (concat prefix localname1))
3722 (file-writable-p
3723 (file-name-directory (concat prefix localname2)))
3724 (or (file-directory-p (concat prefix localname2))
3725 (file-writable-p (concat prefix localname2))))
8a4438b6
MA
3726 (tramp-do-copy-or-rename-file-directly
3727 op (concat prefix localname1) (concat prefix localname2)
3728 ok-if-already-exists keep-date t)
3729 ;; We must change the ownership to the local user.
8d60099b 3730 (tramp-set-file-uid-gid
8a4438b6
MA
3731 (concat prefix localname2)
3732 (tramp-get-local-uid 'integer)
3733 (tramp-get-local-gid 'integer)))
8d60099b 3734
8a4438b6
MA
3735 ;; We need a temporary file in between.
3736 (t
2c418c5b
MA
3737 ;; Create the temporary file.
3738 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
917b89a6 3739 (unwind-protect
2c418c5b
MA
3740 (progn
3741 (cond
3742 (t1
917b89a6
MA
3743 (or
3744 (zerop
3745 (tramp-send-command-and-check
3746 v (format
3747 "%s %s %s" cmd
3748 (tramp-shell-quote-argument localname1)
3749 (tramp-shell-quote-argument tmpfile))))
3750 (tramp-error-with-buffer
3751 nil v 'file-error
3752 "Copying directly failed, see buffer `%s' for details."
3753 (tramp-get-buffer v)))
2c418c5b 3754 ;; We must change the ownership as remote user.
917b89a6
MA
3755 ;; Since this does not work reliable, we also
3756 ;; give read permissions.
3757 (set-file-modes
3758 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3759 (tramp-set-file-uid-gid
3760 (concat prefix tmpfile)
3761 (tramp-get-local-uid 'integer)
3762 (tramp-get-local-gid 'integer)))
3763 (t2
3764 (if (eq op 'copy)
3765 (tramp-compat-copy-file
5ab38c3c 3766 localname1 tmpfile t
2c418c5b
MA
3767 keep-date preserve-uid-gid)
3768 (tramp-run-real-handler
3769 'rename-file
5ab38c3c 3770 (list localname1 tmpfile t)))
2c418c5b 3771 ;; We must change the ownership as local user.
917b89a6
MA
3772 ;; Since this does not work reliable, we also
3773 ;; give read permissions.
3774 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3775 (tramp-set-file-uid-gid
3776 tmpfile
3777 (tramp-get-remote-uid v 'integer)
3778 (tramp-get-remote-gid v 'integer))))
3779
3780 ;; Move the temporary file to its destination.
3781 (cond
3782 (t2
917b89a6
MA
3783 (or
3784 (zerop
3785 (tramp-send-command-and-check
3786 v (format
3787 "cp -f -p %s %s"
3788 (tramp-shell-quote-argument tmpfile)
3789 (tramp-shell-quote-argument localname2))))
3790 (tramp-error-with-buffer
3791 nil v 'file-error
3792 "Copying directly failed, see buffer `%s' for details."
3793 (tramp-get-buffer v))))
2c418c5b 3794 (t1
ce2cc728
MA
3795 (tramp-run-real-handler
3796 'rename-file
2c418c5b
MA
3797 (list tmpfile localname2 ok-if-already-exists)))))
3798
917b89a6
MA
3799 ;; Save exit.
3800 (condition-case nil
3801 (delete-file tmpfile)
3802 (error)))))))))
8d60099b
MA
3803
3804 ;; Set the time and mode. Mask possible errors.
8d60099b 3805 (condition-case nil
1f107aed 3806 (when keep-date
4f4126e6
MA
3807 (set-file-times newname file-times)
3808 (set-file-modes newname file-modes))
8d60099b
MA
3809 (error)))))
3810
5ec2cc41 3811(defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
7432277c 3812 "Invoke rcp program to copy.
905fb90e 3813The method used must be an out-of-band method."
38c65fca 3814 (let ((t1 (tramp-tramp-file-p filename))
5ec2cc41 3815 (t2 (tramp-tramp-file-p newname))
946a5aeb 3816 copy-program copy-args copy-env copy-keep-date port spec
00d6fd04
MA
3817 source target)
3818
3819 (with-parsed-tramp-file-name (if t1 filename newname) nil
905fb90e 3820 (if (and t1 t2)
00d6fd04 3821
905fb90e
MA
3822 ;; Both are Tramp files. We shall optimize it, when the
3823 ;; methods for filename and newname are the same.
9cf3544e
MA
3824 (let* ((dir-flag (file-directory-p filename))
3825 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3826 (if dir-flag
3827 (setq tmpfile
3828 (expand-file-name
3829 (file-name-nondirectory newname) tmpfile)))
905fb90e
MA
3830 (unwind-protect
3831 (progn
3832 (tramp-do-copy-or-rename-file-out-of-band
3833 op filename tmpfile keep-date)
3834 (tramp-do-copy-or-rename-file-out-of-band
3835 'rename tmpfile newname keep-date))
3836 ;; Save exit.
3837 (condition-case nil
9cf3544e 3838 (if dir-flag
b533bc97 3839 (tramp-compat-delete-directory
9cf3544e
MA
3840 (expand-file-name ".." tmpfile) 'recursive)
3841 (delete-file tmpfile))
905fb90e
MA
3842 (error))))
3843
3844 ;; Expand hops. Might be necessary for gateway methods.
3845 (setq v (car (tramp-compute-multi-hops v)))
3846 (aset v 3 localname)
3847
3848 ;; Check which ones of source and target are Tramp files.
3849 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
263c02ef
MA
3850 target (funcall
3851 (if (and (file-directory-p filename)
3852 (string-equal
3853 (file-name-nondirectory filename)
3854 (file-name-nondirectory newname)))
3855 'file-name-directory
3856 'identity)
3857 (if t2 (tramp-make-copy-program-file-name v) newname)))
905fb90e
MA
3858
3859 ;; Check for port number. Until now, there's no need for handling
3860 ;; like method, user, host.
3861 (setq host (tramp-file-name-real-host v)
3862 port (tramp-file-name-port v)
3863 port (or (and port (number-to-string port)) ""))
3864
3865 ;; Compose copy command.
b533bc97
MA
3866 (setq spec (format-spec-make
3867 ?h host ?u user ?p port
3868 ?t (tramp-get-connection-property
3869 (tramp-get-connection-process v) "temp-file" "")
3870 ?k (if keep-date " " ""))
905fb90e
MA
3871 copy-program (tramp-get-method-parameter
3872 method 'tramp-copy-program)
3873 copy-keep-date (tramp-get-method-parameter
3874 method 'tramp-copy-keep-date)
3875 copy-args
3876 (delq
3877 nil
3878 (mapcar
aa485f7c
MA
3879 (lambda (x)
3880 (setq
3881 x
3882 ;; " " is indication for keep-date argument.
3883 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3884 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb
MA
3885 (tramp-get-method-parameter method 'tramp-copy-args)))
3886 copy-env
3887 (delq
3888 nil
3889 (mapcar
aa485f7c
MA
3890 (lambda (x)
3891 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3892 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb 3893 (tramp-get-method-parameter method 'tramp-copy-env))))
905fb90e
MA
3894
3895 ;; Check for program.
3896 (when (and (fboundp 'executable-find)
3897 (not (let ((default-directory
3898 (tramp-compat-temporary-file-directory)))
3899 (executable-find copy-program))))
3900 (tramp-error
3901 v 'file-error "Cannot find copy program: %s" copy-program))
00d6fd04 3902
4265deab
MA
3903 ;; Set variables for computing the prompt for reading
3904 ;; password.
3905 (setq tramp-current-method (tramp-file-name-method v)
3906 tramp-current-user (tramp-file-name-user v)
3907 tramp-current-host (tramp-file-name-host v))
3908
905fb90e
MA
3909 (unwind-protect
3910 (with-temp-buffer
3911 ;; The default directory must be remote.
3912 (let ((default-directory
946a5aeb
MA
3913 (file-name-directory (if t1 filename newname)))
3914 (process-environment (copy-sequence process-environment)))
905fb90e
MA
3915 ;; Set the transfer process properties.
3916 (tramp-set-connection-property
3917 v "process-name" (buffer-name (current-buffer)))
3918 (tramp-set-connection-property
3919 v "process-buffer" (current-buffer))
946a5aeb
MA
3920 (while copy-env
3921 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3922 (setenv (pop copy-env) (pop copy-env)))
905fb90e
MA
3923
3924 ;; Use an asynchronous process. By this, password can
3925 ;; be handled. The default directory must be local, in
3926 ;; order to apply the correct `copy-program'. We don't
3927 ;; set a timeout, because the copying of large files can
3928 ;; last longer than 60 secs.
3929 (let ((p (let ((default-directory
3930 (tramp-compat-temporary-file-directory)))
3931 (apply 'start-process
3932 (tramp-get-connection-property
3933 v "process-name" nil)
3934 (tramp-get-connection-property
3935 v "process-buffer" nil)
3936 copy-program
3937 (append copy-args (list source target))))))
3938 (tramp-message
3939 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3940 (tramp-set-process-query-on-exit-flag p nil)
3941 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
00d6fd04 3942
905fb90e
MA
3943 ;; Reset the transfer process properties.
3944 (tramp-set-connection-property v "process-name" nil)
3945 (tramp-set-connection-property v "process-buffer" nil))
00d6fd04 3946
905fb90e
MA
3947 ;; Handle KEEP-DATE argument.
3948 (when (and keep-date (not copy-keep-date))
3949 (set-file-times newname (nth 5 (file-attributes filename))))
01917a18 3950
905fb90e
MA
3951 ;; Set the mode.
3952 (unless (and keep-date copy-keep-date)
459a5f4b
MA
3953 (ignore-errors
3954 (set-file-modes newname (tramp-default-file-modes filename)))))
5ec2cc41 3955
905fb90e
MA
3956 ;; If the operation was `rename', delete the original file.
3957 (unless (eq op 'copy)
aac0b0f2
MA
3958 (if (file-regular-p filename)
3959 (delete-file filename)
b533bc97 3960 (tramp-compat-delete-directory filename 'recursive))))))
7432277c 3961
fb7933a3 3962(defun tramp-handle-make-directory (dir &optional parents)
00d6fd04 3963 "Like `make-directory' for Tramp files."
ac474af1 3964 (setq dir (expand-file-name dir))
c62c9d08 3965 (with-parsed-tramp-file-name dir nil
c15cdf02 3966 (tramp-flush-directory-property v (file-name-directory localname))
b1d06e75
KG
3967 (save-excursion
3968 (tramp-barf-unless-okay
00d6fd04 3969 v
9c13938d 3970 (format "%s %s"
b1d06e75 3971 (if parents "mkdir -p" "mkdir")
7432277c 3972 (tramp-shell-quote-argument localname))
b1d06e75 3973 "Couldn't make directory %s" dir))))
fb7933a3 3974
c15cdf02 3975(defun tramp-handle-delete-directory (directory &optional recursive)
00d6fd04 3976 "Like `delete-directory' for Tramp files."
ac474af1 3977 (setq directory (expand-file-name directory))
c62c9d08 3978 (with-parsed-tramp-file-name directory nil
aac0b0f2 3979 (tramp-flush-file-property v (file-name-directory localname))
00d6fd04
MA
3980 (tramp-flush-directory-property v localname)
3981 (unless (zerop (tramp-send-command-and-check
3982 v
c15cdf02
MA
3983 (format
3984 "%s %s"
3985 (if recursive "rm -rf" "rmdir")
3986 (tramp-shell-quote-argument localname))))
00d6fd04 3987 (tramp-error v 'file-error "Couldn't delete %s" directory))))
fb7933a3
KG
3988
3989(defun tramp-handle-delete-file (filename)
00d6fd04 3990 "Like `delete-file' for Tramp files."
ac474af1 3991 (setq filename (expand-file-name filename))
c62c9d08 3992 (with-parsed-tramp-file-name filename nil
aac0b0f2 3993 (tramp-flush-file-property v (file-name-directory localname))
00d6fd04
MA
3994 (tramp-flush-file-property v localname)
3995 (unless (zerop (tramp-send-command-and-check
3996 v
3997 (format "rm -f %s"
3998 (tramp-shell-quote-argument localname))))
3999 (tramp-error v 'file-error "Couldn't delete %s" filename))))
fb7933a3
KG
4000
4001;; Dired.
4002
4003;; CCC: This does not seem to be enough. Something dies when
a4aeb9a4 4004;; we try and delete two directories under Tramp :/
fb7933a3
KG
4005(defun tramp-handle-dired-recursive-delete-directory (filename)
4006 "Recursively delete the directory given.
00d6fd04 4007This is like `dired-recursive-delete-directory' for Tramp files."
c62c9d08 4008 (with-parsed-tramp-file-name filename nil
00d6fd04 4009 ;; Run a shell command 'rm -r <localname>'
260821d3 4010 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
00d6fd04
MA
4011 (unless (file-exists-p filename)
4012 (tramp-error v 'file-error "No such directory: %s" filename))
fb7933a3 4013 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
00d6fd04
MA
4014 (tramp-send-command
4015 v
9c13938d 4016 (format "rm -rf %s" (tramp-shell-quote-argument localname))
00d6fd04
MA
4017 ;; Don't read the output, do it explicitely.
4018 nil t)
fb7933a3
KG
4019 ;; Wait for the remote system to return to us...
4020 ;; This might take a while, allow it plenty of time.
00d6fd04 4021 (tramp-wait-for-output (tramp-get-connection-process v) 120)
fb7933a3 4022 ;; Make sure that it worked...
aac0b0f2 4023 (tramp-flush-file-property v (file-name-directory localname))
c15cdf02 4024 (tramp-flush-directory-property v localname)
07dfe738 4025 (and (file-exists-p filename)
00d6fd04
MA
4026 (tramp-error
4027 v 'file-error "Failed to recursively delete %s" filename))))
bf247b6e 4028
5ec2cc41 4029(defun tramp-handle-dired-compress-file (file &rest ok-flag)
00d6fd04 4030 "Like `dired-compress-file' for Tramp files."
5ec2cc41
KG
4031 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4032 ;; Code stolen mainly from dired-aux.el.
4033 (with-parsed-tramp-file-name file nil
00d6fd04 4034 (tramp-flush-file-property v localname)
5ec2cc41
KG
4035 (save-excursion
4036 (let ((suffixes
4037 (if (not (featurep 'xemacs))
4038 ;; Emacs case
4039 (symbol-value 'dired-compress-file-suffixes)
4040 ;; XEmacs has `dired-compression-method-alist', which is
4041 ;; transformed into `dired-compress-file-suffixes' structure.
4042 (mapcar
aa485f7c
MA
4043 (lambda (x)
4044 (list (concat (regexp-quote (nth 1 x)) "\\'")
4045 nil
4046 (mapconcat 'identity (nth 3 x) " ")))
5ec2cc41
KG
4047 (symbol-value 'dired-compression-method-alist))))
4048 suffix)
4049 ;; See if any suffix rule matches this file name.
4050 (while suffixes
4051 (let (case-fold-search)
4052 (if (string-match (car (car suffixes)) localname)
4053 (setq suffix (car suffixes) suffixes nil))
4054 (setq suffixes (cdr suffixes))))
4055
4056 (cond ((file-symlink-p file)
4057 nil)
4058 ((and suffix (nth 2 suffix))
4059 ;; We found an uncompression rule.
00d6fd04 4060 (tramp-message v 0 "Uncompressing %s..." file)
5ec2cc41 4061 (when (zerop (tramp-send-command-and-check
b593f105
MA
4062 v (concat (nth 2 suffix) " "
4063 (tramp-shell-quote-argument localname))))
00d6fd04 4064 (tramp-message v 0 "Uncompressing %s...done" file)
38c65fca
KG
4065 ;; `dired-remove-file' is not defined in XEmacs
4066 (funcall (symbol-function 'dired-remove-file) file)
5ec2cc41
KG
4067 (string-match (car suffix) file)
4068 (concat (substring file 0 (match-beginning 0)))))
4069 (t
4070 ;; We don't recognize the file as compressed, so compress it.
4071 ;; Try gzip.
00d6fd04 4072 (tramp-message v 0 "Compressing %s..." file)
5ec2cc41 4073 (when (zerop (tramp-send-command-and-check
b593f105
MA
4074 v (concat "gzip -f "
4075 (tramp-shell-quote-argument localname))))
00d6fd04 4076 (tramp-message v 0 "Compressing %s...done" file)
38c65fca
KG
4077 ;; `dired-remove-file' is not defined in XEmacs
4078 (funcall (symbol-function 'dired-remove-file) file)
5ec2cc41
KG
4079 (cond ((file-exists-p (concat file ".gz"))
4080 (concat file ".gz"))
4081 ((file-exists-p (concat file ".z"))
4082 (concat file ".z"))
4083 (t nil)))))))))
fb7933a3 4084
d5b3979c 4085(defun tramp-handle-dired-uncache (dir &optional dir-p)
70c11b0b 4086 "Like `dired-uncache' for Tramp files."
d5b3979c
MA
4087 ;; DIR-P is valid for XEmacs only.
4088 (with-parsed-tramp-file-name
4089 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
70c11b0b
MA
4090 (tramp-flush-file-property v localname)))
4091
fb7933a3
KG
4092;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4093;; not sure at all that this is the right way to do it, but let's hope
4094;; it works for now, and wait for a guru to point out the Right Way to
4095;; achieve this.
4096;;(eval-when-compile
4097;; (unless (fboundp 'dired-insert-set-properties)
4098;; (fset 'dired-insert-set-properties 'ignore)))
4099;; Gerd suggests this:
4100(eval-when-compile (require 'dired))
4101;; Note that dired is required at run-time, too, when it is needed.
4102;; It is only needed on XEmacs for the function
4103;; `dired-insert-set-properties'.
4104
4105(defun tramp-handle-insert-directory
4106 (filename switches &optional wildcard full-directory-p)
00d6fd04
MA
4107 "Like `insert-directory' for Tramp files."
4108 (setq filename (expand-file-name filename))
4109 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4110 (if (and (featurep 'ls-lisp)
4111 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4112 (tramp-run-real-handler
4113 'insert-directory (list filename switches wildcard full-directory-p))
0c0b61f1
MA
4114 (when (stringp switches)
4115 (setq switches (split-string switches)))
4116 (when (and (member "--dired" switches)
8e754ea2 4117 (not (tramp-get-ls-command-with-dired v)))
0c0b61f1 4118 (setq switches (delete "--dired" switches)))
c82c5727 4119 (when wildcard
87bdd2c7
MA
4120 (setq wildcard (tramp-run-real-handler
4121 'file-name-nondirectory (list localname)))
4122 (setq localname (tramp-run-real-handler
4123 'file-name-directory (list localname))))
c82c5727 4124 (unless full-directory-p
0c0b61f1
MA
4125 (setq switches (add-to-list 'switches "-d" 'append)))
4126 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
c82c5727 4127 (when wildcard
0c0b61f1
MA
4128 (setq switches (concat switches " " wildcard)))
4129 (tramp-message
4130 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4131 switches filename (if wildcard "yes" "no")
4132 (if full-directory-p "yes" "no"))
00d6fd04
MA
4133 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4134 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4135 (if full-directory-p
4136 (tramp-send-command
4137 v
fe5facd3 4138 (format "%s %s %s 2>/dev/null"
00d6fd04
MA
4139 (tramp-get-ls-command v)
4140 switches
4141 (if wildcard
4142 localname
4143 (tramp-shell-quote-argument (concat localname ".")))))
4144 (tramp-barf-unless-okay
4145 v
4146 (format "cd %s" (tramp-shell-quote-argument
87bdd2c7
MA
4147 (tramp-run-real-handler
4148 'file-name-directory (list localname))))
00d6fd04 4149 "Couldn't `cd %s'"
87bdd2c7
MA
4150 (tramp-shell-quote-argument
4151 (tramp-run-real-handler 'file-name-directory (list localname))))
00d6fd04
MA
4152 (tramp-send-command
4153 v
4154 (format "%s %s %s"
4155 (tramp-get-ls-command v)
4156 switches
4157 (if (or wildcard
87bdd2c7
MA
4158 (zerop (length
4159 (tramp-run-real-handler
4160 'file-name-nondirectory (list localname)))))
00d6fd04
MA
4161 ""
4162 (tramp-shell-quote-argument
87bdd2c7
MA
4163 (tramp-run-real-handler
4164 'file-name-nondirectory (list localname)))))))
8e754ea2
MA
4165 (let ((beg (point)))
4166 ;; We cannot use `insert-buffer-substring' because the Tramp
4167 ;; buffer changes its contents before insertion due to calling
4168 ;; `expand-file' and alike.
4169 (insert
4170 (with-current-buffer (tramp-get-buffer v)
4171 (buffer-string)))
4172
4173 ;; Check for "--dired" output.
8e754ea2 4174 (forward-line -2)
7f4d4a97
MA
4175 (when (looking-at "//SUBDIRED//")
4176 (forward-line -1))
8e754ea2 4177 (when (looking-at "//DIRED//")
7ba1d9c2 4178 (let ((end (tramp-compat-line-end-position))
8e754ea2
MA
4179 (linebeg (point)))
4180 ;; Now read the numeric positions of file names.
4181 (goto-char linebeg)
4182 (forward-word 1)
4183 (forward-char 3)
4184 (while (< (point) end)
4185 (let ((start (+ beg (read (current-buffer))))
4186 (end (+ beg (read (current-buffer)))))
7f49fe46 4187 (if (memq (char-after end) '(?\n ?\ ))
8e754ea2 4188 ;; End is followed by \n or by " -> ".
fe5facd3
MA
4189 (put-text-property start end 'dired-filename t))))))
4190 ;; Remove trailing lines.
4191 (goto-char (tramp-compat-line-beginning-position))
4192 (while (looking-at "//")
4193 (forward-line 1)
4194 (delete-region (match-beginning 0) (point)))
0c0b61f1
MA
4195
4196 ;; The inserted file could be from somewhere else.
4197 (when (and (not wildcard) (not full-directory-p))
4198 (goto-char (point-max))
e5c70c41
MA
4199 (when (file-symlink-p filename)
4200 (goto-char (search-backward "->" beg 'noerror)))
0c0b61f1
MA
4201 (search-backward
4202 (if (zerop (length (file-name-nondirectory filename)))
4203 "."
4204 (file-name-nondirectory filename))
4205 beg 'noerror)
4206 (replace-match (file-relative-name filename) t))
4207
fe5facd3 4208 (goto-char (point-max))))))
fb7933a3 4209
fb7933a3 4210(defun tramp-handle-unhandled-file-name-directory (filename)
00d6fd04 4211 "Like `unhandled-file-name-directory' for Tramp files."
8a798e41
MA
4212 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4213 ;; for backward compatibility.
ce3f516f 4214 (expand-file-name "~/"))
fb7933a3
KG
4215
4216;; Canonicalization of file names.
4217
fb7933a3 4218(defun tramp-handle-expand-file-name (name &optional dir)
00d6fd04 4219 "Like `expand-file-name' for Tramp files.
7432277c
KG
4220If the localname part of the given filename starts with \"/../\" then
4221the result will be a local, non-Tramp, filename."
fb7933a3
KG
4222 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4223 (setq dir (or dir default-directory "/"))
4224 ;; Unless NAME is absolute, concat DIR and NAME.
4225 (unless (file-name-absolute-p name)
4226 (setq name (concat (file-name-as-directory dir) name)))
00d6fd04 4227 ;; If NAME is not a Tramp file, run the real handler.
fb7933a3 4228 (if (not (tramp-tramp-file-p name))
00d6fd04 4229 (tramp-run-real-handler 'expand-file-name (list name nil))
fb7933a3 4230 ;; Dissect NAME.
c62c9d08 4231 (with-parsed-tramp-file-name name nil
87bdd2c7 4232 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
7432277c 4233 (setq localname (concat "~/" localname)))
00d6fd04
MA
4234 ;; Tilde expansion if necessary. This needs a shell which
4235 ;; groks tilde expansion! The function `tramp-find-shell' is
4236 ;; supposed to find such a shell on the remote host. Please
4237 ;; tell me about it when this doesn't work on your system.
4238 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4239 (let ((uname (match-string 1 localname))
4240 (fname (match-string 2 localname)))
4241 ;; We cannot simply apply "~/", because under sudo "~/" is
4242 ;; expanded to the local user home directory but to the
4243 ;; root home directory. On the other hand, using always
4244 ;; the default user name for tilde expansion is not
4245 ;; appropriate either, because ssh and companions might
4246 ;; use a user name from the config file.
4247 (when (and (string-equal uname "~")
4248 (string-match "\\`su\\(do\\)?\\'" method))
4249 (setq uname (concat uname user)))
4250 (setq uname
b593f105
MA
4251 (with-connection-property v uname
4252 (tramp-send-command
4253 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4254 (with-current-buffer (tramp-get-buffer v)
4255 (goto-char (point-min))
4256 (buffer-substring
4257 (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
4258 (setq localname (concat uname fname))))
4259 ;; There might be a double slash, for example when "~/"
cb85dcd0 4260 ;; expands to "/". Remove this.
00d6fd04
MA
4261 (while (string-match "//" localname)
4262 (setq localname (replace-match "/" t t localname)))
4263 ;; No tilde characters in file name, do normal
a17632c1
MA
4264 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4265 ;; `directory-sep-char' here for XEmacs on Windows, which would
4266 ;; otherwise use backslash. `default-directory' is bound,
4267 ;; because on Windows there would be problems with UNC shares or
4268 ;; Cygwin mounts.
aff67808
MA
4269 (let ((directory-sep-char ?/)
4270 (default-directory (tramp-compat-temporary-file-directory)))
4271 (tramp-make-tramp-file-name
4272 method user host
4273 (tramp-drop-volume-letter
87bdd2c7
MA
4274 (tramp-run-real-handler
4275 'expand-file-name (list localname))))))))
00d6fd04 4276
c23c3394
MA
4277(defun tramp-replace-environment-variables (filename)
4278 "Replace environment variables in FILENAME.
4279Return the string with the replaced variables."
2e271195 4280 (save-match-data
ec5145d6 4281 (let ((idx (string-match "$\\(\\w+\\)" filename)))
2e271195 4282 ;; `$' is coded as `$$'.
ec5145d6
MA
4283 (when (and idx
4284 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4285 (getenv (match-string 1 filename)))
2e271195
MA
4286 (setq filename
4287 (replace-match
4288 (substitute-in-file-name (match-string 0 filename))
4289 t nil filename)))
4290 filename)))
c23c3394 4291
00d6fd04
MA
4292(defun tramp-handle-substitute-in-file-name (filename)
4293 "Like `substitute-in-file-name' for Tramp files.
4294\"//\" and \"/~\" substitute only in the local filename part.
4295If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4296beginning of local filename are not substituted."
c23c3394
MA
4297 ;; First, we must replace environment variables.
4298 (setq filename (tramp-replace-environment-variables filename))
00d6fd04
MA
4299 (with-parsed-tramp-file-name filename nil
4300 (if (equal tramp-syntax 'url)
4301 ;; We need to check localname only. The other parts cannot contain
4302 ;; "//" or "/~".
4303 (if (and (> (length localname) 1)
4304 (or (string-match "//" localname)
4305 (string-match "/~" localname 1)))
4306 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4307 (tramp-make-tramp-file-name
4308 (when method (substitute-in-file-name method))
4309 (when user (substitute-in-file-name user))
4310 (when host (substitute-in-file-name host))
87bdd2c7
MA
4311 (when localname
4312 (tramp-run-real-handler
4313 'substitute-in-file-name (list localname)))))
00d6fd04
MA
4314 ;; Ignore in LOCALNAME everything before "//" or "/~".
4315 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4316 (setq filename
b08104a0
MA
4317 (concat (file-remote-p filename)
4318 (replace-match "\\1" nil nil localname)))
00d6fd04
MA
4319 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4320 (when (string-match "~$" filename)
4321 (setq filename (concat filename "/"))))
4322 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4323
4324;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4325;; which calls corresponding functions (see minibuf.el).
4326(when (fboundp 'minibuffer-electric-separator)
9e6ab520 4327 (mapc
aa485f7c
MA
4328 (lambda (x)
4329 (eval
4330 `(defadvice ,x
4331 (around ,(intern (format "tramp-advice-%s" x)) activate)
4332 "Invoke `substitute-in-file-name' for Tramp files."
4333 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4334 (tramp-tramp-file-p (buffer-substring)))
4335 ;; We don't need to handle `last-input-event', because
4336 ;; due to the key map we know it must be ?/ or ?~.
4337 (let ((s (concat (buffer-substring (point-min) (point))
4338 (string last-command-char))))
4339 (delete-region (point-min) (point))
4340 (insert (substitute-in-file-name s))
4341 (setq ad-return-value last-command-char))
d7ec1df7
MA
4342 ad-do-it)))
4343 (eval
4344 `(add-hook
4345 'tramp-unload-hook
4346 (lambda ()
4347 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4348 (ad-activate ',x)))))
00d6fd04
MA
4349
4350 '(minibuffer-electric-separator
4351 minibuffer-electric-tilde)))
4352
4353
0664ff72 4354;;; Remote commands:
fb7933a3 4355
00d6fd04
MA
4356(defun tramp-handle-executable-find (command)
4357 "Like `executable-find' for Tramp files."
4358 (with-parsed-tramp-file-name default-directory nil
f84638eb 4359 (tramp-find-executable v command (tramp-get-remote-path v) t)))
00d6fd04
MA
4360
4361;; We use BUFFER also as connection buffer during setup. Because of
4362;; this, its original contents must be saved, and restored once
4363;; connection has been setup.
4364(defun tramp-handle-start-file-process (name buffer program &rest args)
4365 "Like `start-file-process' for Tramp files."
4366 (with-parsed-tramp-file-name default-directory nil
9fb2cdc5
GM
4367 (unless (stringp program)
4368 (tramp-error
4369 v 'file-error "pty association is not supported for `%s'" name))
00d6fd04 4370 (unwind-protect
263c02ef
MA
4371 (let ((command (format "cd %s; exec %s"
4372 (tramp-shell-quote-argument localname)
4373 (mapconcat 'tramp-shell-quote-argument
4374 (cons program args) " ")))
4375 (name1 name)
38d63e6a 4376 (i 0))
2296b54d 4377 (unless buffer
6ce63faf 4378 ;; BUFFER can be nil. We use a temporary buffer.
2296b54d 4379 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
38d63e6a
MA
4380 (while (get-process name1)
4381 ;; NAME must be unique as process name.
4382 (setq i (1+ i)
4383 name1 (format "%s<%d>" name i)))
4384 (setq name name1)
00d6fd04
MA
4385 ;; Set the new process properties.
4386 (tramp-set-connection-property v "process-name" name)
2296b54d 4387 (tramp-set-connection-property v "process-buffer" buffer)
00d6fd04 4388 ;; Activate narrowing in order to save BUFFER contents.
11c71217
MA
4389 ;; Clear also the modification time; otherwise we might be
4390 ;; interrupted by `verify-visited-file-modtime'.
00d6fd04 4391 (with-current-buffer (tramp-get-connection-buffer v)
11c71217 4392 (clear-visited-file-modtime)
00d6fd04 4393 (narrow-to-region (point-max) (point-max)))
263c02ef 4394 ;; Send the command. `tramp-send-command' opens a new
00d6fd04 4395 ;; connection.
263c02ef 4396 (tramp-send-command v command nil t) ; nooutput
6ce63faf
MA
4397 ;; Set query flag for this process.
4398 (tramp-set-process-query-on-exit-flag
4399 (tramp-get-connection-process v) t)
00d6fd04
MA
4400 ;; Return process.
4401 (tramp-get-connection-process v))
4402 ;; Save exit.
ce3f516f 4403 (with-current-buffer (tramp-get-connection-buffer v)
6ce63faf
MA
4404 (if (string-match tramp-temp-buffer-name (buffer-name))
4405 (progn
4406 (set-process-buffer (tramp-get-connection-process v) nil)
4407 (kill-buffer (current-buffer)))
4408 (widen)
4409 (goto-char (point-max))))
00d6fd04
MA
4410 (tramp-set-connection-property v "process-name" nil)
4411 (tramp-set-connection-property v "process-buffer" nil))))
4412
4413(defun tramp-handle-process-file
4414 (program &optional infile destination display &rest args)
4415 "Like `process-file' for Tramp files."
4416 ;; The implementation is not complete yet.
4417 (when (and (numberp destination) (zerop destination))
4418 (error "Implementation does not handle immediate return"))
4419
4420 (with-parsed-tramp-file-name default-directory nil
a6e96327 4421 (let (command input tmpinput stderr tmpstderr outbuf ret)
00d6fd04
MA
4422 ;; Compute command.
4423 (setq command (mapconcat 'tramp-shell-quote-argument
4424 (cons program args) " "))
4425 ;; Determine input.
4426 (if (null infile)
4427 (setq input "/dev/null")
4428 (setq infile (expand-file-name infile))
4429 (if (tramp-equal-remote default-directory infile)
4430 ;; INFILE is on the same remote host.
4431 (setq input (with-parsed-tramp-file-name infile nil localname))
4432 ;; INFILE must be copied to remote host.
a6e96327
MA
4433 (setq input (tramp-make-tramp-temp-file v)
4434 tmpinput (tramp-make-tramp-file-name method user host input))
4435 (copy-file infile tmpinput t)))
00d6fd04
MA
4436 (when input (setq command (format "%s <%s" command input)))
4437
4438 ;; Determine output.
4439 (cond
bede3e9f 4440 ;; Just a buffer.
00d6fd04
MA
4441 ((bufferp destination)
4442 (setq outbuf destination))
bede3e9f 4443 ;; A buffer name.
00d6fd04
MA
4444 ((stringp destination)
4445 (setq outbuf (get-buffer-create destination)))
4446 ;; (REAL-DESTINATION ERROR-DESTINATION)
4447 ((consp destination)
bede3e9f 4448 ;; output.
00d6fd04
MA
4449 (cond
4450 ((bufferp (car destination))
4451 (setq outbuf (car destination)))
4452 ((stringp (car destination))
0664ff72
MA
4453 (setq outbuf (get-buffer-create (car destination))))
4454 ((car destination)
4455 (setq outbuf (current-buffer))))
bede3e9f 4456 ;; stderr.
00d6fd04
MA
4457 (cond
4458 ((stringp (cadr destination))
4459 (setcar (cdr destination) (expand-file-name (cadr destination)))
4460 (if (tramp-equal-remote default-directory (cadr destination))
4461 ;; stderr is on the same remote host.
4462 (setq stderr (with-parsed-tramp-file-name
4463 (cadr destination) nil localname))
4464 ;; stderr must be copied to remote host. The temporary
4465 ;; file must be deleted after execution.
a6e96327
MA
4466 (setq stderr (tramp-make-tramp-temp-file v)
4467 tmpstderr (tramp-make-tramp-file-name
4468 method user host stderr))))
bede3e9f 4469 ;; stderr to be discarded.
00d6fd04
MA
4470 ((null (cadr destination))
4471 (setq stderr "/dev/null"))))
4472 ;; 't
4473 (destination
4474 (setq outbuf (current-buffer))))
4475 (when stderr (setq command (format "%s 2>%s" command stderr)))
4476
00d6fd04
MA
4477 ;; Send the command. It might not return in time, so we protect it.
4478 (condition-case nil
4479 (unwind-protect
293c24f9
MA
4480 (setq ret
4481 (tramp-send-command-and-check
4482 v (format "\\cd %s; %s"
4483 (tramp-shell-quote-argument localname)
b593f105
MA
4484 command)
4485 nil t))
00d6fd04
MA
4486 ;; We should show the output anyway.
4487 (when outbuf
293c24f9
MA
4488 (with-current-buffer outbuf
4489 (insert
4490 (with-current-buffer (tramp-get-connection-buffer v)
4491 (buffer-string))))
00d6fd04 4492 (when display (display-buffer outbuf))))
260821d3
MA
4493 ;; When the user did interrupt, we should do it also. We use
4494 ;; return code -1 as marker.
4495 (quit
4496 (kill-buffer (tramp-get-connection-buffer v))
4497 (setq ret -1))
4498 ;; Handle errors.
00d6fd04
MA
4499 (error
4500 (kill-buffer (tramp-get-connection-buffer v))
4501 (setq ret 1)))
a6e96327 4502
a6e96327
MA
4503 ;; Provide error file.
4504 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
263c02ef 4505
260821d3
MA
4506 ;; Cleanup. We remove all file cache values for the connection,
4507 ;; because the remote process could have changed them.
a6e96327 4508 (when tmpinput (delete-file tmpinput))
946a5aeb
MA
4509
4510 ;; `process-file-side-effects' has been introduced with GNU
4511 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4512 ;; by `program'. If it doesn't exist, we assume its default
4513 ;; value 't'.
4514 (unless (and (boundp 'process-file-side-effects)
4515 (not (symbol-value 'process-file-side-effects)))
4516 (tramp-flush-directory-property v ""))
4517
00d6fd04 4518 ;; Return exit status.
260821d3
MA
4519 (if (equal ret -1)
4520 (keyboard-quit)
4521 ret))))
00d6fd04 4522
a4aeb9a4
MA
4523(defun tramp-local-call-process
4524 (program &optional infile destination display &rest args)
4525 "Calls `call-process' on the local host.
4526This is needed because for some Emacs flavors Tramp has
4527defadviced `call-process' to behave like `process-file'. The
4528Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4529 (let ((default-directory
4530 (if (file-remote-p default-directory)
4531 (tramp-compat-temporary-file-directory)
4532 default-directory)))
4533 (if (executable-find program)
4534 (apply 'call-process program infile destination display args)
4535 1)))
4536
00d6fd04
MA
4537(defun tramp-handle-call-process-region
4538 (start end program &optional delete buffer display &rest args)
4539 "Like `call-process-region' for Tramp files."
258800f8 4540 (let ((tmpfile (tramp-compat-make-temp-file "")))
00d6fd04
MA
4541 (write-region start end tmpfile)
4542 (when delete (delete-region start end))
4543 (unwind-protect
4544 (apply 'call-process program tmpfile buffer display args)
4545 (delete-file tmpfile))))
4546
4547(defun tramp-handle-shell-command
4548 (command &optional output-buffer error-buffer)
4549 "Like `shell-command' for Tramp files."
ce3f516f 4550 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
b8bfcf96
MA
4551 ;; We cannot use `shell-file-name' and `shell-command-switch',
4552 ;; they are variables of the local host.
4553 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
5d2ebd96 4554 current-buffer-p
ce3f516f 4555 (output-buffer
27e813fe
MA
4556 (cond
4557 ((bufferp output-buffer) output-buffer)
4558 ((stringp output-buffer) (get-buffer-create output-buffer))
5d2ebd96
AS
4559 (output-buffer
4560 (setq current-buffer-p t)
4561 (current-buffer))
42bc9b6d 4562 (t (get-buffer-create
27e813fe
MA
4563 (if asynchronous
4564 "*Async Shell Command*"
4565 "*Shell Command Output*")))))
4566 (error-buffer
4567 (cond
4568 ((bufferp error-buffer) error-buffer)
4569 ((stringp error-buffer) (get-buffer-create error-buffer))))
ce3f516f 4570 (buffer
27e813fe 4571 (if (and (not asynchronous) error-buffer)
ce3f516f
MA
4572 (with-parsed-tramp-file-name default-directory nil
4573 (list output-buffer (tramp-make-tramp-temp-file v)))
42bc9b6d 4574 output-buffer))
cfb5c0db 4575 (p (get-buffer-process output-buffer)))
42bc9b6d
MA
4576
4577 ;; Check whether there is another process running. Tramp does not
4578 ;; support 2 (asynchronous) processes in parallel.
cfb5c0db 4579 (when p
42bc9b6d 4580 (if (yes-or-no-p "A command is running. Kill it? ")
699a11fb
GM
4581 (condition-case nil
4582 (kill-process p)
4583 (error nil))
42bc9b6d
MA
4584 (error "Shell command in progress")))
4585
f34db316
AS
4586 (if current-buffer-p
4587 (progn
4588 (barf-if-buffer-read-only)
4589 (push-mark nil t))
5d2ebd96
AS
4590 (with-current-buffer output-buffer
4591 (setq buffer-read-only nil)
4592 (erase-buffer)))
42bc9b6d 4593
5d2ebd96 4594 (if (and (not current-buffer-p) (integerp asynchronous))
42bc9b6d
MA
4595 (prog1
4596 ;; Run the process.
3412f35d 4597 (apply 'start-file-process "*Async Shell*" buffer args)
42bc9b6d 4598 ;; Display output.
cfb5c0db
MA
4599 (pop-to-buffer output-buffer)
4600 (setq mode-line-process '(":%s"))
4601 (require 'shell) (shell-mode))
42bc9b6d
MA
4602
4603 (prog1
4604 ;; Run the process.
4605 (apply 'process-file (car args) nil buffer nil (cdr args))
4606 ;; Insert error messages if they were separated.
4607 (when (listp buffer)
4608 (with-current-buffer error-buffer
4609 (insert-file-contents (cadr buffer)))
4610 (delete-file (cadr buffer)))
f34db316
AS
4611 (if current-buffer-p
4612 ;; This is like exchange-point-and-mark, but doesn't
4613 ;; activate the mark. It is cleaner to avoid activation,
4614 ;; even though the command loop would deactivate the mark
4615 ;; because we inserted text.
4616 (goto-char (prog1 (mark t)
4617 (set-marker (mark-marker) (point)
4618 (current-buffer))))
4619 ;; There's some output, display it.
4620 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4621 (if (functionp 'display-message-or-buffer)
4622 (funcall (symbol-function 'display-message-or-buffer)
4623 output-buffer)
4624 (pop-to-buffer output-buffer))))))))
00d6fd04
MA
4625
4626;; File Editing.
4627
4628(defvar tramp-handle-file-local-copy-hook nil
4629 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4630
fb7933a3 4631(defun tramp-handle-file-local-copy (filename)
00d6fd04 4632 "Like `file-local-copy' for Tramp files."
0f205eee 4633
c62c9d08 4634 (with-parsed-tramp-file-name filename nil
2988341a
MA
4635 (unless (file-exists-p filename)
4636 (tramp-error
4637 v 'file-error
4638 "Cannot make local copy of non-existing file `%s'" filename))
4639
0f205eee 4640 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
00d6fd04 4641 (loc-dec (tramp-get-local-coding v "local-decoding"))
258800f8 4642 (tmpfile (tramp-compat-make-temp-file filename)))
5ec2cc41 4643
2988341a
MA
4644 (condition-case err
4645 (cond
4646 ;; `copy-file' handles direct copy and out-of-band methods.
4647 ((or (tramp-local-host-p v)
7f49fe46
MA
4648 (tramp-method-out-of-band-p
4649 v (nth 7 (file-attributes filename))))
2988341a
MA
4650 (copy-file filename tmpfile t t))
4651
4652 ;; Use inline encoding for file transfer.
4653 (rem-enc
4654 (save-excursion
4655 (tramp-message v 5 "Encoding remote file %s..." filename)
4656 (tramp-barf-unless-okay
4657 v
4658 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4659 "Encoding remote file failed")
4660 (tramp-message v 5 "Encoding remote file %s...done" filename)
4661
4662 (if (and (symbolp loc-dec) (fboundp loc-dec))
4663 ;; If local decoding is a function, we call it. We
4664 ;; must disable multibyte, because
4665 ;; `uudecode-decode-region' doesn't handle it
4666 ;; correctly.
0f205eee
MA
4667 (with-temp-buffer
4668 (set-buffer-multibyte nil)
4669 (insert-buffer-substring (tramp-get-buffer v))
4670 (tramp-message
4671 v 5 "Decoding remote file %s with function %s..."
4672 filename loc-dec)
4673 (funcall loc-dec (point-min) (point-max))
aa485f7c
MA
4674 ;; Unset `file-name-handler-alist'. Otherwise,
4675 ;; epa-file gets confused.
4676 (let (file-name-handler-alist
4677 (coding-system-for-write 'binary))
2988341a
MA
4678 (write-region (point-min) (point-max) tmpfile)))
4679
4680 ;; If tramp-decoding-function is not defined for this
4681 ;; method, we invoke tramp-decoding-command instead.
4682 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
aa485f7c
MA
4683 ;; Unset `file-name-handler-alist'. Otherwise,
4684 ;; epa-file gets confused.
4685 (let (file-name-handler-alist
4686 (coding-system-for-write 'binary))
2988341a
MA
4687 (write-region (point-min) (point-max) tmpfile2))
4688 (tramp-message
4689 v 5 "Decoding remote file %s with command %s..."
4690 filename loc-dec)
4691 (unwind-protect
4692 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4693 (delete-file tmpfile2))))
4694
4695 (tramp-message v 5 "Decoding remote file %s...done" filename)
4696 ;; Set proper permissions.
b86c1cd8 4697 (set-file-modes tmpfile (tramp-default-file-modes filename))
2988341a
MA
4698 ;; Set local user ownership.
4699 (tramp-set-file-uid-gid tmpfile)))
4700
4701 ;; Oops, I don't know what to do.
4702 (t (tramp-error
4703 v 'file-error "Wrong method specification for `%s'" method)))
4704
4705 ;; Error handling.
4706 ((error quit)
4707 (delete-file tmpfile)
4708 (signal (car err) (cdr err))))
0f205eee 4709
00d6fd04 4710 (run-hooks 'tramp-handle-file-local-copy-hook)
94be87e8 4711 tmpfile)))
fb7933a3 4712
bce04fee 4713(defun tramp-handle-file-remote-p (filename &optional identification connected)
00d6fd04 4714 "Like `file-remote-p' for Tramp files."
d5b3979c
MA
4715 (let ((tramp-verbose 3))
4716 (when (tramp-tramp-file-p filename)
4717 (let* ((v (tramp-dissect-file-name filename))
4718 (p (tramp-get-connection-process v))
4719 (c (and p (processp p) (memq (process-status p) '(run open)))))
4720 ;; We expand the file name only, if there is already a connection.
4721 (with-parsed-tramp-file-name
4722 (if c (expand-file-name filename) filename) nil
4723 (and (or (not connected) c)
4724 (cond
4725 ((eq identification 'method) method)
4726 ((eq identification 'user) user)
4727 ((eq identification 'host) host)
4728 ((eq identification 'localname) localname)
4729 (t (tramp-make-tramp-file-name method user host "")))))))))
fb7933a3 4730
eb562962
MA
4731(defun tramp-find-file-name-coding-system-alist (filename tmpname)
4732 "Like `find-operation-coding-system' for Tramp filenames.
4733Tramp's `insert-file-contents' and `write-region' work over
4734temporary file names. If `file-coding-system-alist' contains an
4735expression, which matches more than the file name suffix, the
4736coding system might not be determined. This function repairs it."
4737 (let (result)
4738 (dolist (elt file-coding-system-alist result)
4739 (when (and (consp elt) (string-match (car elt) filename))
4740 ;; We found a matching entry in `file-coding-system-alist'.
4741 ;; So we add a similar entry, but with the temporary file name
4742 ;; as regexp.
4743 (add-to-list
4744 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4745
fb7933a3
KG
4746(defun tramp-handle-insert-file-contents
4747 (filename &optional visit beg end replace)
00d6fd04 4748 "Like `insert-file-contents' for Tramp files."
fb7933a3
KG
4749 (barf-if-buffer-read-only)
4750 (setq filename (expand-file-name filename))
736ac90f 4751 (let (coding-system-used result local-copy remote-copy)
2ac33804
MA
4752 (with-parsed-tramp-file-name filename nil
4753 (unwind-protect
70c11b0b
MA
4754 (if (not (file-exists-p filename))
4755 ;; We don't raise a Tramp error, because it might be
4756 ;; suppressed, like in `find-file-noselect-1'.
4757 (signal 'file-error
4758 (list "File not found on remote host" filename))
4759
4760 (if (and (tramp-local-host-p v)
4761 (let (file-name-handler-alist)
4762 (file-readable-p localname)))
4763 ;; Short track: if we are on the local host, we can
4764 ;; run directly.
4765 (setq result
4766 (tramp-run-real-handler
4767 'insert-file-contents
4768 (list localname visit beg end replace)))
4769
736ac90f
MA
4770 ;; When we shall insert only a part of the file, we copy
4771 ;; this part.
4772 (when (or beg end)
4773 (setq remote-copy (tramp-make-tramp-temp-file v))
4774 (tramp-send-command
4775 v
4776 (cond
4777 ((and beg end)
4778 (format "tail -c +%d %s | head -c +%d >%s"
4779 (1+ beg) (tramp-shell-quote-argument localname)
4780 (- end beg) remote-copy))
4781 (beg
4782 (format "tail -c +%d %s >%s"
4783 (1+ beg) (tramp-shell-quote-argument localname)
4784 remote-copy))
4785 (end
4786 (format "head -c +%d %s >%s"
4787 (1+ end) (tramp-shell-quote-argument localname)
4788 remote-copy)))))
4789
70c11b0b
MA
4790 ;; `insert-file-contents-literally' takes care to avoid
4791 ;; calling jka-compr. By let-binding
4792 ;; `inhibit-file-name-operation', we propagate that care
4793 ;; to the `file-local-copy' operation.
4794 (setq local-copy
4795 (let ((inhibit-file-name-operation
4796 (when (eq inhibit-file-name-operation
4797 'insert-file-contents)
4798 'file-local-copy)))
b88f2d0a
MA
4799 (cond
4800 ((stringp remote-copy)
4801 (file-local-copy
4802 (tramp-make-tramp-file-name
4803 method user host remote-copy)))
4804 ((stringp tramp-temp-buffer-file-name)
4805 (copy-file filename tramp-temp-buffer-file-name 'ok)
4806 tramp-temp-buffer-file-name)
4807 (t (file-local-copy filename)))))
4808
6e4f5731
MA
4809 ;; When the file is not readable for the owner, it
4810 ;; cannot be inserted, even it is redable for the group
4811 ;; or for everybody.
4812 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4813
b88f2d0a
MA
4814 (when (and (null remote-copy)
4815 (tramp-get-method-parameter
4816 method 'tramp-copy-keep-tmpfile))
4817 ;; We keep the local file for performance reasons,
4818 ;; useful for "rsync".
b88f2d0a
MA
4819 (setq tramp-temp-buffer-file-name local-copy)
4820 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4821
70c11b0b
MA
4822 (tramp-message
4823 v 4 "Inserting local temp file `%s'..." local-copy)
4824
4825 ;; We must ensure that `file-coding-system-alist'
4826 ;; matches `local-copy'.
4827 (let ((file-coding-system-alist
4828 (tramp-find-file-name-coding-system-alist
4829 filename local-copy)))
4830 (setq result
4831 (insert-file-contents
736ac90f 4832 local-copy nil nil nil replace))
70c11b0b
MA
4833 ;; Now `last-coding-system-used' has right value.
4834 ;; Remember it.
4835 (when (boundp 'last-coding-system-used)
4836 (setq coding-system-used
4837 (symbol-value 'last-coding-system-used))))
8d60099b 4838
70c11b0b
MA
4839 (tramp-message
4840 v 4 "Inserting local temp file `%s'...done" local-copy)
4841 (when (boundp 'last-coding-system-used)
2ac33804 4842 (set 'last-coding-system-used coding-system-used))))
70c11b0b 4843
2ac33804
MA
4844 ;; Save exit.
4845 (progn
4846 (when visit
4847 (setq buffer-file-name filename)
4848 (setq buffer-read-only (not (file-writable-p filename)))
4849 (set-visited-file-modtime)
4850 (set-buffer-modified-p nil))
b88f2d0a
MA
4851 (when (and (stringp local-copy)
4852 (or remote-copy (null tramp-temp-buffer-file-name)))
2ac33804
MA
4853 (delete-file local-copy))
4854 (when (stringp remote-copy)
4855 (delete-file
4856 (tramp-make-tramp-file-name method user host remote-copy))))))
70c11b0b
MA
4857
4858 ;; Result.
4859 (list (expand-file-name filename)
4860 (cadr result))))
fb7933a3 4861
94be87e8
MA
4862;; This is needed for XEmacs only. Code stolen from files.el.
4863(defun tramp-handle-insert-file-contents-literally
4864 (filename &optional visit beg end replace)
4865 "Like `insert-file-contents-literally' for Tramp files."
4866 (let ((format-alist nil)
4867 (after-insert-file-functions nil)
4868 (coding-system-for-read 'no-conversion)
4869 (coding-system-for-write 'no-conversion)
4870 (find-buffer-file-type-function
4871 (if (fboundp 'find-buffer-file-type)
4872 (symbol-function 'find-buffer-file-type)
4873 nil))
4874 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4875 (inhibit-file-name-operation 'insert-file-contents))
4876 (unwind-protect
4877 (progn
4878 (fset 'find-buffer-file-type (lambda (filename) t))
4879 (insert-file-contents filename visit beg end replace))
70c11b0b 4880 ;; Save exit.
94be87e8
MA
4881 (if find-buffer-file-type-function
4882 (fset 'find-buffer-file-type find-buffer-file-type-function)
4883 (fmakunbound 'find-buffer-file-type)))))
4884
38c65fca 4885(defun tramp-handle-find-backup-file-name (filename)
00d6fd04 4886 "Like `find-backup-file-name' for Tramp files."
07dfe738
KG
4887 (with-parsed-tramp-file-name filename nil
4888 ;; We set both variables. It doesn't matter whether it is
b533bc97 4889 ;; Emacs or XEmacs.
07dfe738 4890 (let ((backup-directory-alist
b533bc97 4891 ;; Emacs case.
07dfe738 4892 (when (boundp 'backup-directory-alist)
b86c1cd8 4893 (if (symbol-value 'tramp-backup-directory-alist)
07dfe738 4894 (mapcar
aa485f7c
MA
4895 (lambda (x)
4896 (cons
4897 (car x)
4898 (if (and (stringp (cdr x))
4899 (file-name-absolute-p (cdr x))
4900 (not (tramp-file-name-p (cdr x))))
4901 (tramp-make-tramp-file-name method user host (cdr x))
4902 (cdr x))))
07dfe738
KG
4903 (symbol-value 'tramp-backup-directory-alist))
4904 (symbol-value 'backup-directory-alist))))
4905
4906 (bkup-backup-directory-info
b533bc97 4907 ;; XEmacs case.
07dfe738 4908 (when (boundp 'bkup-backup-directory-info)
b86c1cd8 4909 (if (symbol-value 'tramp-bkup-backup-directory-info)
07dfe738 4910 (mapcar
aa485f7c
MA
4911 (lambda (x)
4912 (nconc
4913 (list (car x))
4914 (list
4915 (if (and (stringp (car (cdr x)))
4916 (file-name-absolute-p (car (cdr x)))
4917 (not (tramp-file-name-p (car (cdr x)))))
4918 (tramp-make-tramp-file-name
4919 method user host (car (cdr x)))
4920 (car (cdr x))))
4921 (cdr (cdr x))))
07dfe738
KG
4922 (symbol-value 'tramp-bkup-backup-directory-info))
4923 (symbol-value 'bkup-backup-directory-info)))))
4924
4925 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
38c65fca 4926
c1105d05 4927(defun tramp-handle-make-auto-save-file-name ()
00d6fd04 4928 "Like `make-auto-save-file-name' for Tramp files.
c1105d05 4929Returns a file name in `tramp-auto-save-directory' for autosaving this file."
00d6fd04
MA
4930 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4931 (buffer-file-name
4932 (tramp-subst-strs-in-string
4933 '(("_" . "|")
4934 ("/" . "_a")
4935 (":" . "_b")
4936 ("|" . "__")
4937 ("[" . "_l")
4938 ("]" . "_r"))
4939 (buffer-file-name))))
1a762140
MA
4940 ;; File name must be unique. This is ensured with Emacs 22 (see
4941 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4942 ;; all other cases we must do it ourselves.
4943 (when (boundp 'auto-save-file-name-transforms)
9e6ab520 4944 (mapc
aa485f7c
MA
4945 (lambda (x)
4946 (when (and (string-match (car x) buffer-file-name)
4947 (not (car (cddr x))))
4948 (setq tramp-auto-save-directory
4949 (or tramp-auto-save-directory
4950 (tramp-compat-temporary-file-directory)))))
1a762140
MA
4951 (symbol-value 'auto-save-file-name-transforms)))
4952 ;; Create directory.
4953 (when tramp-auto-save-directory
00d6fd04
MA
4954 (setq buffer-file-name
4955 (expand-file-name buffer-file-name tramp-auto-save-directory))
1a762140
MA
4956 (unless (file-exists-p tramp-auto-save-directory)
4957 (make-directory tramp-auto-save-directory t)))
00d6fd04
MA
4958 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4959 ;; it is not a magic file name operation (since Emacs 22).
4960 ;; We must deactivate it temporarily.
4961 (if (not (ad-is-active 'make-auto-save-file-name))
4962 (tramp-run-real-handler 'make-auto-save-file-name nil)
4963 ;; else
4964 (ad-deactivate 'make-auto-save-file-name)
4965 (prog1
4966 (tramp-run-real-handler 'make-auto-save-file-name nil)
4967 (ad-activate 'make-auto-save-file-name)))))
4968
4969(defvar tramp-handle-write-region-hook nil
4970 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4971
b88f2d0a 4972;; CCC grok LOCKNAME
fb7933a3
KG
4973(defun tramp-handle-write-region
4974 (start end filename &optional append visit lockname confirm)
00d6fd04 4975 "Like `write-region' for Tramp files."
fb7933a3 4976 (setq filename (expand-file-name filename))
c62c9d08 4977 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4978 ;; Following part commented out because we don't know what to do about
4979 ;; file locking, and it does not appear to be a problem to ignore it.
4980 ;; Ange-ftp ignores it, too.
4981 ;; (when (and lockname (stringp lockname))
4982 ;; (setq lockname (expand-file-name lockname)))
4983 ;; (unless (or (eq lockname nil)
4984 ;; (string= lockname filename))
4985 ;; (error
4986 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
8d60099b 4987
94be87e8 4988 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
00d6fd04
MA
4989 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4990 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4991 (tramp-error v 'file-error "File not overwritten")))
8d60099b 4992
a4aeb9a4 4993 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
9c13938d 4994 (tramp-get-remote-uid v 'integer)))
a4aeb9a4 4995 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
9c13938d
MA
4996 (tramp-get-remote-gid v 'integer))))
4997
4998 (if (and (tramp-local-host-p v)
93c3eb7c 4999 ;; `file-writable-p' calls `file-expand-file-name'. We
87bdd2c7
MA
5000 ;; cannot use `tramp-run-real-handler' therefore.
5001 (let (file-name-handler-alist)
82f3844e
MA
5002 (and
5003 (file-writable-p (file-name-directory localname))
5004 (or (file-directory-p localname)
5005 (file-writable-p localname)))))
9c13938d 5006 ;; Short track: if we are on the local host, we can run directly.
aac0b0f2
MA
5007 (tramp-run-real-handler
5008 'write-region
5009 (list start end localname append 'no-message lockname confirm))
9c13938d
MA
5010
5011 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
5012 (loc-enc (tramp-get-local-coding v "local-encoding"))
b86c1cd8 5013 (modes (save-excursion (tramp-default-file-modes filename)))
9c13938d
MA
5014 ;; We use this to save the value of
5015 ;; `last-coding-system-used' after writing the tmp file.
5016 ;; At the end of the function, we set
5017 ;; `last-coding-system-used' to this saved value. This
5018 ;; way, any intermediary coding systems used while
5019 ;; talking to the remote shell or suchlike won't hose
5020 ;; this variable. This approach was snarfed from
5021 ;; ange-ftp.el.
5022 coding-system-used
5023 ;; Write region into a tmp file. This isn't really
5024 ;; needed if we use an encoding function, but currently
5025 ;; we use it always because this makes the logic
293c24f9
MA
5026 ;; simpler.
5027 (tmpfile (or tramp-temp-buffer-file-name
5028 (tramp-compat-make-temp-file filename))))
5029
5030 ;; If `append' is non-nil, we copy the file locally, and let
5031 ;; the native `write-region' implementation do the job.
5032 (when append (copy-file filename tmpfile 'ok))
9c13938d
MA
5033
5034 ;; We say `no-message' here because we don't want the
5035 ;; visited file modtime data to be clobbered from the temp
5036 ;; file. We call `set-visited-file-modtime' ourselves later
eb562962
MA
5037 ;; on. We must ensure that `file-coding-system-alist'
5038 ;; matches `tmpfile'.
5039 (let ((file-coding-system-alist
5040 (tramp-find-file-name-coding-system-alist filename tmpfile)))
ce2cc728
MA
5041 (condition-case err
5042 (tramp-run-real-handler
5043 'write-region
5044 (list start end tmpfile append 'no-message lockname confirm))
2988341a 5045 ((error quit)
b88f2d0a 5046 (setq tramp-temp-buffer-file-name nil)
2988341a
MA
5047 (delete-file tmpfile)
5048 (signal (car err) (cdr err))))
ce2cc728 5049
eb562962
MA
5050 ;; Now, `last-coding-system-used' has the right value. Remember it.
5051 (when (boundp 'last-coding-system-used)
5052 (setq coding-system-used
5053 (symbol-value 'last-coding-system-used))))
5054
9c13938d
MA
5055 ;; The permissions of the temporary file should be set. If
5056 ;; filename does not exist (eq modes nil) it has been
5057 ;; renamed to the backup file. This case `save-buffer'
5058 ;; handles permissions.
459a5f4b
MA
5059 ;; Ensure, that it is still readable.
5060 (when modes
5061 (set-file-modes
5062 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
9c13938d
MA
5063
5064 ;; This is a bit lengthy due to the different methods
5065 ;; possible for file transfer. First, we check whether the
5066 ;; method uses an rcp program. If so, we call it.
5067 ;; Otherwise, both encoding and decoding command must be
5068 ;; specified. However, if the method _also_ specifies an
5069 ;; encoding function, then that is used for encoding the
5070 ;; contents of the tmp file.
5071 (cond
00cffdeb 5072 ;; `copy-file' handles direct copy and out-of-band methods.
9c13938d 5073 ((or (tramp-local-host-p v)
7f49fe46 5074 (tramp-method-out-of-band-p
00cffdeb
MA
5075 v (nth 7 (file-attributes tmpfile))))
5076 (if (and (not (stringp start))
5077 (= (or end (point-max)) (point-max))
191bb792
MA
5078 (= (or start (point-min)) (point-min))
5079 (tramp-get-method-parameter
5080 method 'tramp-copy-keep-tmpfile))
5081 (progn
5082 (setq tramp-temp-buffer-file-name tmpfile)
5083 (condition-case err
b88f2d0a
MA
5084 ;; We keep the local file for performance
5085 ;; reasons, useful for "rsync".
191bb792
MA
5086 (copy-file tmpfile filename t)
5087 ((error quit)
5088 (setq tramp-temp-buffer-file-name nil)
5089 (delete-file tmpfile)
5090 (signal (car err) (cdr err)))))
5091 (setq tramp-temp-buffer-file-name nil)
5092 ;; Don't rename, in order to keep context in SELinux.
5093 (unwind-protect
5094 (copy-file tmpfile filename t)
5095 (delete-file tmpfile))))
9c13938d 5096
1d7e9a01 5097 ;; Use inline file transfer.
9c13938d 5098 (rem-dec
1d7e9a01 5099 ;; Encode tmpfile.
9c13938d
MA
5100 (tramp-message v 5 "Encoding region...")
5101 (unwind-protect
5102 (with-temp-buffer
5103 ;; Use encoding function or command.
5104 (if (and (symbolp loc-enc) (fboundp loc-enc))
5105 (progn
5106 (tramp-message
5107 v 5 "Encoding region using function `%s'..."
5108 (symbol-name loc-enc))
5109 (let ((coding-system-for-read 'binary))
5110 (insert-file-contents-literally tmpfile))
70c11b0b
MA
5111 ;; The following `let' is a workaround for the
5112 ;; base64.el that comes with pgnus-0.84. If
5113 ;; both of the following conditions are
5114 ;; satisfied, it tries to write to a local
5115 ;; file in default-directory, but at this
5116 ;; point, default-directory is remote.
5117 ;; (`call-process-region' can't write to
5118 ;; remote files, it seems.) The file in
5119 ;; question is a tmp file anyway.
9c13938d
MA
5120 (let ((default-directory
5121 (tramp-compat-temporary-file-directory)))
5122 (funcall loc-enc (point-min) (point-max))))
8d60099b 5123
9c13938d
MA
5124 (tramp-message
5125 v 5 "Encoding region using command `%s'..." loc-enc)
5126 (unless (equal 0 (tramp-call-local-coding-command
5127 loc-enc tmpfile t))
5128 (tramp-error
5129 v 'file-error
5130 "Cannot write to `%s', local encoding command `%s' failed"
5131 filename loc-enc)))
5132
5133 ;; Send buffer into remote decoding command which
5134 ;; writes to remote file. Because this happens on
5135 ;; the remote host, we cannot use the function.
5136 (goto-char (point-max))
5137 (unless (bolp) (newline))
8d60099b 5138 (tramp-message
9c13938d
MA
5139 v 5 "Decoding region into remote file %s..." filename)
5140 (tramp-send-command
5141 v
5142 (format
5143 "%s >%s <<'EOF'\n%sEOF"
5144 rem-dec
5145 (tramp-shell-quote-argument localname)
5146 (buffer-string)))
5147 (tramp-barf-unless-okay
5148 v nil
5149 "Couldn't write region to `%s', decode using `%s' failed"
5150 filename rem-dec)
5151 ;; When `file-precious-flag' is set, the region is
5152 ;; written to a temporary file. Check that the
5153 ;; checksum is equal to that from the local tmpfile.
5154 (when file-precious-flag
5155 (erase-buffer)
5156 (and
a4aeb9a4
MA
5157 ;; cksum runs locally, if possible.
5158 (zerop (tramp-local-call-process "cksum" tmpfile t))
5159 ;; cksum runs remotely.
9c13938d
MA
5160 (zerop
5161 (tramp-send-command-and-check
5162 v
5163 (format
5164 "cksum <%s" (tramp-shell-quote-argument localname))))
a4aeb9a4 5165 ;; ... they are different.
9c13938d
MA
5166 (not
5167 (string-equal
5168 (buffer-string)
5169 (with-current-buffer (tramp-get-buffer v)
5170 (buffer-string))))
5171 (tramp-error
5172 v 'file-error
5173 (concat "Couldn't write region to `%s',"
5174 " decode using `%s' failed")
5175 filename rem-dec)))
5176 (tramp-message
aac0b0f2 5177 v 5 "Decoding region into remote file %s...done" filename))
8d60099b 5178
9c13938d
MA
5179 ;; Save exit.
5180 (delete-file tmpfile)))
8d60099b 5181
9c13938d
MA
5182 ;; That's not expected.
5183 (t
5184 (tramp-error
5185 v 'file-error
5186 (concat "Method `%s' should specify both encoding and "
5187 "decoding command or an rcp program")
5188 method)))
258800f8 5189
9c13938d
MA
5190 ;; Make `last-coding-system-used' have the right value.
5191 (when coding-system-used
5192 (set 'last-coding-system-used coding-system-used))))
0f205eee 5193
aac0b0f2
MA
5194 (tramp-flush-file-property v (file-name-directory localname))
5195 (tramp-flush-file-property v localname)
5196
57671b72
MA
5197 ;; We must protect `last-coding-system-used', now we have set it
5198 ;; to its correct value.
293c24f9 5199 (let (last-coding-system-used (need-chown t))
57671b72
MA
5200 ;; Set file modification time.
5201 (when (or (eq visit t) (stringp visit))
293c24f9
MA
5202 (let ((file-attr (file-attributes filename)))
5203 (set-visited-file-modtime
5204 ;; We must pass modtime explicitely, because filename can
5205 ;; be different from (buffer-file-name), f.e. if
5206 ;; `file-precious-flag' is set.
5207 (nth 5 file-attr))
5208 (when (and (eq (nth 2 file-attr) uid)
5209 (eq (nth 3 file-attr) gid))
5210 (setq need-chown nil))))
57671b72
MA
5211
5212 ;; Set the ownership.
293c24f9
MA
5213 (when need-chown
5214 (tramp-set-file-uid-gid filename uid gid))
57671b72
MA
5215 (when (or (eq visit t) (null visit) (stringp visit))
5216 (tramp-message v 0 "Wrote %s" filename))
5217 (run-hooks 'tramp-handle-write-region-hook)))))
fb7933a3 5218
946a5aeb
MA
5219(defvar tramp-vc-registered-file-names nil
5220 "List used to collect file names, which are checked during `vc-registered'.")
5221
5222;; VC backends check for the existence of various different special
5223;; files. This is very time consuming, because every single check
5224;; requires a remote command (the file cache must be invalidated).
5225;; Therefore, we apply a kind of optimization. We install the file
5226;; name handler `tramp-vc-file-name-handler', which does nothing but
5227;; remembers all file names for which `file-exists-p' or
5228;; `file-readable-p' has been applied. A first run of `vc-registered'
5229;; is performed. Afterwards, a script is applied for all collected
5230;; file names, using just one remote command. The result of this
5231;; script is used to fill the file cache with actual values. Now we
5232;; can reset the file name handlers, and we make a second run of
5233;; `vc-registered', which returns the expected result without sending
5234;; any other remote command.
49096407
MA
5235(defun tramp-handle-vc-registered (file)
5236 "Like `vc-registered' for Tramp files."
946a5aeb 5237 (with-parsed-tramp-file-name file nil
7f49fe46
MA
5238
5239 ;; There could be new files, created by the vc backend. We cannot
5240 ;; reuse the old cache entries, therefore.
946a5aeb
MA
5241 (let (tramp-vc-registered-file-names
5242 (tramp-cache-inhibit-cache (current-time))
5243 (file-name-handler-alist
5244 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5245
5246 ;; Here we collect only file names, which need an operation.
5247 (tramp-run-real-handler 'vc-registered (list file))
5248 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5249
5250 ;; Send just one command, in order to fill the cache.
7f49fe46
MA
5251 (when tramp-vc-registered-file-names
5252 (tramp-maybe-send-script
5253 v
5254 (format tramp-vc-registered-read-file-names
5255 (tramp-get-file-exists-command v)
5256 (format "%s -r" (tramp-get-test-command v)))
5257 "tramp_vc_registered_read_file_names")
5258
5259 (dolist
5260 (elt
5261 (tramp-send-command-and-read
5262 v
5263 (format
5264 "tramp_vc_registered_read_file_names %s"
5265 (mapconcat 'tramp-shell-quote-argument
5266 tramp-vc-registered-file-names
5267 " "))))
946a5aeb 5268
7f49fe46 5269 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
946a5aeb 5270
7f49fe46
MA
5271 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
5272 ;; shall be answered from the file cache.
5273 ;; We unset `process-file-side-effects' in order to keep the cache
5274 ;; when `process-file' calls appear.
946a5aeb
MA
5275 (let (process-file-side-effects)
5276 (tramp-run-real-handler 'vc-registered (list file)))))
49096407 5277
a01b1e22
MA
5278;;;###autoload
5279(progn (defun tramp-run-real-handler (operation args)
fb7933a3 5280 "Invoke normal file name handler for OPERATION.
c62c9d08
KG
5281First arg specifies the OPERATION, second arg is a list of arguments to
5282pass to the OPERATION."
4007ba5b
KG
5283 (let* ((inhibit-file-name-handlers
5284 `(tramp-file-name-handler
946a5aeb 5285 tramp-vc-file-name-handler
4007ba5b
KG
5286 tramp-completion-file-name-handler
5287 cygwin-mount-name-hook-function
5288 cygwin-mount-map-drive-hook-function
5289 .
5290 ,(and (eq inhibit-file-name-operation operation)
5291 inhibit-file-name-handlers)))
5292 (inhibit-file-name-operation operation))
a01b1e22 5293 (apply operation args))))
16674e4f 5294
a01b1e22
MA
5295;;;###autoload
5296(progn (defun tramp-completion-run-real-handler (operation args)
16674e4f
KG
5297 "Invoke `tramp-file-name-handler' for OPERATION.
5298First arg specifies the OPERATION, second arg is a list of arguments to
5299pass to the OPERATION."
4007ba5b
KG
5300 (let* ((inhibit-file-name-handlers
5301 `(tramp-completion-file-name-handler
5302 cygwin-mount-name-hook-function
5303 cygwin-mount-map-drive-hook-function
5304 .
5305 ,(and (eq inhibit-file-name-operation operation)
5306 inhibit-file-name-handlers)))
5307 (inhibit-file-name-operation operation))
a01b1e22 5308 (apply operation args))))
fb7933a3 5309
4007ba5b
KG
5310;; We handle here all file primitives. Most of them have the file
5311;; name as first parameter; nevertheless we check for them explicitly
04bf5b65 5312;; in order to be signaled if a new primitive appears. This
4007ba5b
KG
5313;; scenario is needed because there isn't a way to decide by
5314;; syntactical means whether a foreign method must be called. It would
19a87064 5315;; ease the life if `file-name-handler-alist' would support a decision
4007ba5b
KG
5316;; function as well but regexp only.
5317(defun tramp-file-name-for-operation (operation &rest args)
5318 "Return file name related to OPERATION file primitive.
5319ARGS are the arguments OPERATION has been called with."
5320 (cond
b533bc97 5321 ;; FILE resp DIRECTORY.
4007ba5b
KG
5322 ((member operation
5323 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5324 'delete-file 'diff-latest-backup-file 'directory-file-name
5325 'directory-files 'directory-files-and-attributes
5326 'dired-compress-file 'dired-uncache
5327 'file-accessible-directory-p 'file-attributes
5328 'file-directory-p 'file-executable-p 'file-exists-p
574c05e2 5329 'file-local-copy 'file-remote-p 'file-modes 'file-selinux-context
19a87064
MA
5330 'file-name-as-directory 'file-name-directory
5331 'file-name-nondirectory 'file-name-sans-versions
5332 'file-ownership-preserved-p 'file-readable-p
5333 'file-regular-p 'file-symlink-p 'file-truename
5334 'file-writable-p 'find-backup-file-name 'find-file-noselect
5335 'get-file-buffer 'insert-directory 'insert-file-contents
5336 'load 'make-directory 'make-directory-internal
5337 'set-file-modes 'substitute-in-file-name
5338 'unhandled-file-name-directory 'vc-registered
b533bc97 5339 ;; Emacs 22+ only.
ce3f516f 5340 'set-file-times
b533bc97 5341 ;; XEmacs only.
4007ba5b
KG
5342 'abbreviate-file-name 'create-file-buffer
5343 'dired-file-modtime 'dired-make-compressed-filename
5344 'dired-recursive-delete-directory 'dired-set-file-modtime
5345 'dired-shell-unhandle-file-name 'dired-uucode-file
5615d63f 5346 'insert-file-contents-literally 'make-temp-name 'recover-file
4007ba5b 5347 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
8daea7fc
KG
5348 (if (file-name-absolute-p (nth 0 args))
5349 (nth 0 args)
5350 (expand-file-name (nth 0 args))))
b533bc97 5351 ;; FILE DIRECTORY resp FILE1 FILE2.
4007ba5b
KG
5352 ((member operation
5353 (list 'add-name-to-file 'copy-file 'expand-file-name
5354 'file-name-all-completions 'file-name-completion
5355 'file-newer-than-file-p 'make-symbolic-link 'rename-file
b533bc97 5356 ;; Emacs 23+ only.
263c02ef 5357 'copy-directory
b533bc97 5358 ;; XEmacs only.
4007ba5b
KG
5359 'dired-make-relative-symlink
5360 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5361 (save-match-data
5362 (cond
5363 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5364 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5365 (t (buffer-file-name (current-buffer))))))
b533bc97 5366 ;; START END FILE.
4007ba5b
KG
5367 ((eq operation 'write-region)
5368 (nth 2 args))
b533bc97 5369 ;; BUFFER.
4007ba5b 5370 ((member operation
00d6fd04 5371 (list 'set-visited-file-modtime 'verify-visited-file-modtime
b533bc97 5372 ;; Emacs 22+ only.
00d6fd04 5373 'make-auto-save-file-name
b533bc97 5374 ;; XEmacs only.
4007ba5b
KG
5375 'backup-buffer))
5376 (buffer-file-name
5377 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
b533bc97 5378 ;; COMMAND.
4007ba5b 5379 ((member operation
b533bc97 5380 (list ;; not in Emacs 23+.
00d6fd04 5381 'dired-call-process
b533bc97 5382 ;; Emacs only.
b71c9e75 5383 'shell-command
b533bc97 5384 ;; Emacs 22+ only.
0457dd55 5385 'process-file
b533bc97 5386 ;; Emacs 23+ only.
00d6fd04 5387 'start-file-process
b533bc97 5388 ;; XEmacs only.
00d6fd04 5389 'dired-print-file 'dired-shell-call-process
b533bc97 5390 ;; nowhere yet.
00d6fd04 5391 'executable-find 'start-process 'call-process))
4007ba5b 5392 default-directory)
b533bc97 5393 ;; Unknown file primitive.
4007ba5b
KG
5394 (t (error "unknown file I/O primitive: %s" operation))))
5395
5396(defun tramp-find-foreign-file-name-handler (filename)
5397 "Return foreign file name handler if exists."
b533bc97 5398 (when (tramp-tramp-file-p filename)
9ce8462a
MA
5399 (let ((v (tramp-dissect-file-name filename t))
5400 (handler tramp-foreign-file-name-handler-alist)
5401 elt res)
5402 ;; When we are not fully sure that filename completion is safe,
5403 ;; we should not return a handler.
5404 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1834b39f
MA
5405 (and (tramp-file-name-host v)
5406 (not (member (tramp-file-name-host v)
5407 (mapcar 'car tramp-methods))))
9ce8462a
MA
5408 (not (tramp-completion-mode-p)))
5409 (while handler
5410 (setq elt (car handler)
5411 handler (cdr handler))
5412 (when (funcall (car elt) filename)
5413 (setq handler nil
5414 res (cdr elt))))
5415 res))))
4007ba5b 5416
fb7933a3
KG
5417;; Main function.
5418;;;###autoload
5419(defun tramp-file-name-handler (operation &rest args)
ea9d1443 5420 "Invoke Tramp file name handler.
a4aeb9a4 5421Falls back to normal file name handler if no Tramp file name handler exists."
2e271195
MA
5422 (if tramp-mode
5423 (save-match-data
5424 (let* ((filename
5425 (tramp-replace-environment-variables
5426 (apply 'tramp-file-name-for-operation operation args)))
5427 (completion (tramp-completion-mode-p))
5428 (foreign (tramp-find-foreign-file-name-handler filename)))
5429 (with-parsed-tramp-file-name filename nil
4874f5e6
MA
5430 ;; Call the backend function.
5431 (if foreign
5432 (condition-case err
5433 (apply foreign operation args)
5434 (error
5435 (cond
5436 ;; When we are in completion mode, some failed
5437 ;; operations shall return at least a default
5438 ;; value in order to give the user a chance to
5439 ;; correct the file name in the minibuffer.
5440 ((and completion (zerop (length localname))
5441 (memq operation '(file-exists-p file-directory-p)))
5442 t)
5443 ((and completion (zerop (length localname))
5444 (memq operation
5445 '(expand-file-name file-name-as-directory)))
5446 filename)
5447 ;; Propagate the error.
5448 (t (signal (car err) (cdr err))))))
5449 ;; Nothing to do for us.
5450 (tramp-run-real-handler operation args)))))
5451
2e271195
MA
5452 ;; When `tramp-mode' is not enabled, we don't do anything.
5453 (tramp-run-real-handler operation args)))
fb7933a3 5454
07dfe738
KG
5455;; In Emacs, there is some concurrency due to timers. If a timer
5456;; interrupts Tramp and wishes to use the same connection buffer as
5457;; the "main" Emacs, then garbage might occur in the connection
5458;; buffer. Therefore, we need to make sure that a timer does not use
5459;; the same connection buffer as the "main" Emacs. We implement a
5460;; cheap global lock, instead of locking each connection buffer
5461;; separately. The global lock is based on two variables,
5462;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5463;; (with setq) to indicate a lock. But Tramp also calls itself during
5464;; processing of a single file operation, so we need to allow
5465;; recursive calls. That's where the `tramp-locker' variable comes in
5466;; -- it is let-bound to t during the execution of the current
5467;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5468;; then we should just proceed because we have been called
5469;; recursively. But if `tramp-locker' is nil, then we are a timer
5470;; interrupting the "main" Emacs, and then we signal an error.
5471
5472(defvar tramp-locked nil
5473 "If non-nil, then Tramp is currently busy.
5474Together with `tramp-locker', this implements a locking mechanism
5475preventing reentrant calls of Tramp.")
5476
5477(defvar tramp-locker nil
5478 "If non-nil, then a caller has locked Tramp.
5479Together with `tramp-locked', this implements a locking mechanism
5480preventing reentrant calls of Tramp.")
5481
ea9d1443
KG
5482(defun tramp-sh-file-name-handler (operation &rest args)
5483 "Invoke remote-shell Tramp file name handler.
5484Fall back to normal file name handler if no Tramp handler exists."
07dfe738 5485 (when (and tramp-locked (not tramp-locker))
11c71217 5486 (setq tramp-locked nil)
00d6fd04 5487 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
07dfe738
KG
5488 (let ((tl tramp-locked))
5489 (unwind-protect
5490 (progn
5491 (setq tramp-locked t)
5492 (let ((tramp-locker t))
5493 (save-match-data
5494 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5495 (if fn
5496 (apply (cdr fn) args)
5497 (tramp-run-real-handler operation args))))))
5498 (setq tramp-locked tl))))
ea9d1443 5499
946a5aeb
MA
5500(defun tramp-vc-file-name-handler (operation &rest args)
5501 "Invoke special file name handler, which collects files to be handled."
5502 (save-match-data
5503 (let ((filename
5504 (tramp-replace-environment-variables
5505 (apply 'tramp-file-name-for-operation operation args)))
5506 (fn (assoc operation tramp-file-name-handler-alist)))
5507 (with-parsed-tramp-file-name filename nil
5508 (cond
5509 ;; That's what we want: file names, for which checks are
5510 ;; applied. We assume, that VC uses only `file-exists-p' and
5511 ;; `file-readable-p' checks; otherwise we must extend the
5512 ;; list. We do not perform any action, but return nil, in
5513 ;; order to keep `vc-registered' running.
5514 ((and fn (memq operation '(file-exists-p file-readable-p)))
5515 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5516 nil)
5517 ;; Tramp file name handlers like `expand-file-name'. They
5518 ;; must still work.
5519 (fn
5520 (save-match-data (apply (cdr fn) args)))
5521 ;; Default file name handlers, we don't care.
5522 (t (tramp-run-real-handler operation args)))))))
5523
16674e4f 5524;;;###autoload
1ecc6145 5525(progn (defun tramp-completion-file-name-handler (operation &rest args)
a4aeb9a4
MA
5526 "Invoke Tramp file name completion handler.
5527Falls back to normal file name handler if no Tramp file name handler exists."
57671b72
MA
5528 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5529 ;; would otherwise use backslash.
aff67808
MA
5530 (let ((directory-sep-char ?/)
5531 (fn (assoc operation tramp-completion-file-name-handler-alist)))
aa485f7c
MA
5532 (if (and
5533 ;; When `tramp-mode' is not enabled, we don't do anything.
5534 fn tramp-mode
5535 ;; For other syntaxes than `sep', the regexp matches many common
5536 ;; situations where the user doesn't actually want to use Tramp.
5537 ;; So to avoid autoloading Tramp after typing just "/s", we
5538 ;; disable this part of the completion, unless the user implicitly
5539 ;; indicated his interest in using a fancier completion system.
5540 (or (eq tramp-syntax 'sep)
5f2b693f
MA
5541 (featurep 'tramp) ;; If it's loaded, we may as well use
5542 ;; it. `partial-completion-mode' does not exist in
5543 ;; XEmacs. It is obsoleted with Emacs 24.1.
aa485f7c
MA
5544 (and (boundp 'partial-completion-mode) partial-completion-mode)
5545 ;; FIXME: These may have been loaded even if the user never
5546 ;; intended to use them.
5547 (featurep 'ido)
5548 (featurep 'icicles)))
aff67808
MA
5549 (save-match-data (apply (cdr fn) args))
5550 (tramp-completion-run-real-handler operation args)))))
a01b1e22 5551
b25a52cc 5552;;;###autoload
aa485f7c
MA
5553(progn (defun tramp-register-file-name-handlers ()
5554 "Add Tramp file name handlers to `file-name-handler-alist'."
5555 ;; Remove autoloaded handlers from file name handler alist. Useful,
00d6fd04
MA
5556 ;; if `tramp-syntax' has been changed.
5557 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
aa485f7c
MA
5558 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5559 (let ((a1 (rassq
5560 'tramp-completion-file-name-handler file-name-handler-alist)))
5561 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5562 ;; Add the handlers.
a01b1e22
MA
5563 (add-to-list 'file-name-handler-alist
5564 (cons tramp-file-name-regexp 'tramp-file-name-handler))
0c0b61f1 5565 (put 'tramp-file-name-handler 'safe-magic t)
aa485f7c
MA
5566 (add-to-list 'file-name-handler-alist
5567 (cons tramp-completion-file-name-regexp
5568 'tramp-completion-file-name-handler))
5569 (put 'tramp-completion-file-name-handler 'safe-magic t)
5570 ;; If jka-compr or epa-file are already loaded, move them to the
5571 ;; front of `file-name-handler-alist'.
5572 (dolist (fnh '(epa-file-handler jka-compr-handler))
5573 (let ((entry (rassoc fnh file-name-handler-alist)))
5574 (when entry
5575 (setq file-name-handler-alist
5576 (cons entry (delete entry file-name-handler-alist))))))))
69cee873 5577
00d6fd04
MA
5578;; `tramp-file-name-handler' must be registered before evaluation of
5579;; site-start and init files, because there might exist remote files
5580;; already, f.e. files kept via recentf-mode.
aa485f7c
MA
5581;;;###autoload(tramp-register-file-name-handlers)
5582(tramp-register-file-name-handlers)
b25a52cc 5583
fb7933a3 5584;;;###autoload
8c04e197 5585(defun tramp-unload-file-name-handlers ()
a69c01a0
MA
5586 (setq file-name-handler-alist
5587 (delete (rassoc 'tramp-file-name-handler
5588 file-name-handler-alist)
5589 (delete (rassoc 'tramp-completion-file-name-handler
5590 file-name-handler-alist)
5591 file-name-handler-alist))))
5592
8c04e197 5593(add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
a69c01a0 5594
0664ff72 5595;;; File name handler functions for completion mode:
a6e96327
MA
5596
5597(defvar tramp-completion-mode nil
5598 "If non-nil, external packages signal that they are in file name completion.
5599
5600This is necessary, because Tramp uses a heuristic depending on last
5601input event. This fails when external packages use other characters
5602but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5603should never be set globally, the intention is to let-bind it.")
16674e4f
KG
5604
5605;; Necessary because `tramp-file-name-regexp-unified' and
00d6fd04
MA
5606;; `tramp-completion-file-name-regexp-unified' aren't different. If
5607;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5608;; to `tramp-file-name-handler'). Otherwise, it takes
5609;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5610;; risky, because completing a file might require loading other files,
5611;; like "~/.netrc", and for them it shouldn't be decided based on that
5612;; variable. On the other hand, those files shouldn't have partial
a4aeb9a4
MA
5613;; Tramp file name syntax. Maybe another variable should be introduced
5614;; overwriting this check in such cases. Or we change Tramp file name
00d6fd04 5615;; syntax in order to avoid ambiguities, like in XEmacs ...
6c4e47fa 5616(defun tramp-completion-mode-p ()
16674e4f 5617 "Checks whether method / user name / host name completion is active."
6c4e47fa 5618 (or
5f2b693f
MA
5619 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5620 (and (boundp 'non-essential) (symbol-value 'non-essential))
a6e96327
MA
5621 tramp-completion-mode
5622 ;; Emacs.
94be87e8 5623 (equal last-input-event 'tab)
6c4e47fa 5624 (and (natnump last-input-event)
94be87e8 5625 (or
a6e96327 5626 ;; ?\t has event-modifier 'control.
800a97b8 5627 (equal last-input-event ?\t)
94be87e8 5628 (and (not (event-modifiers last-input-event))
800a97b8
SM
5629 (or (equal last-input-event ?\?)
5630 (equal last-input-event ?\ )))))
a6e96327 5631 ;; XEmacs.
6c4e47fa
MA
5632 (and (featurep 'xemacs)
5633 ;; `last-input-event' might be nil.
5634 (not (null last-input-event))
5635 ;; `last-input-event' may have no character approximation.
5636 (funcall (symbol-function 'event-to-character) last-input-event)
94be87e8 5637 (or
a6e96327 5638 ;; ?\t has event-modifier 'control.
800a97b8 5639 (equal
94be87e8
MA
5640 (funcall (symbol-function 'event-to-character)
5641 last-input-event) ?\t)
5642 (and (not (event-modifiers last-input-event))
800a97b8 5643 (or (equal
94be87e8
MA
5644 (funcall (symbol-function 'event-to-character)
5645 last-input-event) ?\?)
800a97b8 5646 (equal
94be87e8
MA
5647 (funcall (symbol-function 'event-to-character)
5648 last-input-event) ?\ )))))))
16674e4f 5649
16674e4f
KG
5650;; Method, host name and user name completion.
5651;; `tramp-completion-dissect-file-name' returns a list of
5652;; tramp-file-name structures. For all of them we return possible completions.
a01b1e22 5653;;;###autoload
16674e4f 5654(defun tramp-completion-handle-file-name-all-completions (filename directory)
00d6fd04 5655 "Like `file-name-all-completions' for partial Tramp files."
16674e4f 5656
00d6fd04
MA
5657 (let* ((fullname (tramp-drop-volume-letter
5658 (expand-file-name filename directory)))
5659 ;; Possible completion structures.
5660 (v (tramp-completion-dissect-file-name fullname))
5661 result result1)
5662
5663 (while v
5664 (let* ((car (car v))
5665 (method (tramp-file-name-method car))
5666 (user (tramp-file-name-user car))
5667 (host (tramp-file-name-host car))
5668 (localname (tramp-file-name-localname car))
5669 (m (tramp-find-method method user host))
5670 (tramp-current-user user) ; see `tramp-parse-passwd'
5671 all-user-hosts)
5672
5673 (unless localname ;; Nothing to complete.
5674
5675 (if (or user host)
5676
5677 ;; Method dependent user / host combinations.
5678 (progn
9e6ab520 5679 (mapc
00d6fd04
MA
5680 (lambda (x)
5681 (setq all-user-hosts
5682 (append all-user-hosts
5683 (funcall (nth 0 x) (nth 1 x)))))
5684 (tramp-get-completion-function m))
5685
9e6ab520
MA
5686 (setq result
5687 (append result
5688 (mapcar
5689 (lambda (x)
5690 (tramp-get-completion-user-host
5691 method user host (nth 0 x) (nth 1 x)))
5692 (delq nil all-user-hosts)))))
00d6fd04
MA
5693
5694 ;; Possible methods.
5695 (setq result
5696 (append result (tramp-get-completion-methods m)))))
5697
5698 (setq v (cdr v))))
5699
5700 ;; Unify list, remove nil elements.
5701 (while result
5702 (let ((car (car result)))
5703 (when car
5704 (add-to-list
5705 'result1
5706 (substring car (length (tramp-drop-volume-letter directory)))))
5707 (setq result (cdr result))))
5708
5709 ;; Complete local parts.
5710 (append
5711 result1
5712 (condition-case nil
5713 (tramp-completion-run-real-handler
5714 'file-name-all-completions (list filename directory))
5715 (error nil)))))
16674e4f
KG
5716
5717;; Method, host name and user name completion for a file.
a01b1e22 5718;;;###autoload
e1e17cae
MA
5719(defun tramp-completion-handle-file-name-completion
5720 (filename directory &optional predicate)
00d6fd04 5721 "Like `file-name-completion' for Tramp files."
e1e17cae
MA
5722 (try-completion
5723 filename
5724 (mapcar 'list (file-name-all-completions filename directory))
83e20b5c
MA
5725 (when predicate
5726 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
16674e4f
KG
5727
5728;; I misuse a little bit the tramp-file-name structure in order to handle
5729;; completion possibilities for partial methods / user names / host names.
5730;; Return value is a list of tramp-file-name structures according to possible
00d6fd04 5731;; completions. If "localname" is non-nil it means there
16674e4f
KG
5732;; shouldn't be a completion anymore.
5733
5734;; Expected results:
5735
00d6fd04
MA
5736;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5737;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5738;; [nil "x" nil nil]
5739;; ["x" nil nil nil]
5740
5741;; "/x:" "/x:y" "/x:y:"
5742;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5743;; "/[x/" "/[x/y"
5744;; ["x" nil "" nil] ["x" nil "y" nil]
5745;; ["x" "" nil nil] ["x" "y" nil nil]
5746
5747;; "/x:y@" "/x:y@z" "/x:y@z:"
5748;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5749;; "/[x/y@" "/[x/y@z"
5750;; ["x" nil "y" nil] ["x" "y" "z" nil]
16674e4f
KG
5751(defun tramp-completion-dissect-file-name (name)
5752 "Returns a list of `tramp-file-name' structures.
5753They are collected by `tramp-completion-dissect-file-name1'."
5754
5755 (let* ((result)
4007ba5b 5756 (x-nil "\\|\\(\\)")
b96e6899
MA
5757 (tramp-completion-ipv6-regexp
5758 (format
5759 "[^%s]*"
5760 (if (zerop (length tramp-postfix-ipv6-format))
5761 tramp-postfix-host-format
5762 tramp-postfix-ipv6-format)))
4007ba5b
KG
5763 ;; "/method" "/[method"
5764 (tramp-completion-file-name-structure1
5765 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5766 1 nil nil nil))
5767 ;; "/user" "/[user"
5768 (tramp-completion-file-name-structure2
5769 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5770 nil 1 nil nil))
5771 ;; "/host" "/[host"
5772 (tramp-completion-file-name-structure3
5773 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5774 nil nil 1 nil))
b96e6899 5775 ;; "/[ipv6" "/[ipv6"
4007ba5b 5776 (tramp-completion-file-name-structure4
b96e6899
MA
5777 (list (concat tramp-prefix-regexp
5778 tramp-prefix-ipv6-regexp
5779 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5780 nil nil 1 nil))
5781 ;; "/user@host" "/[user@host"
5782 (tramp-completion-file-name-structure5
4007ba5b
KG
5783 (list (concat tramp-prefix-regexp
5784 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5785 "\\(" tramp-host-regexp x-nil "\\)$")
5786 nil 1 2 nil))
b96e6899
MA
5787 ;; "/user@[ipv6" "/[user@ipv6"
5788 (tramp-completion-file-name-structure6
5789 (list (concat tramp-prefix-regexp
5790 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5791 tramp-prefix-ipv6-regexp
5792 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5793 nil 1 2 nil))
00d6fd04 5794 ;; "/method:user" "/[method/user" "/method://user"
b96e6899 5795 (tramp-completion-file-name-structure7
4007ba5b 5796 (list (concat tramp-prefix-regexp
00d6fd04 5797 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5798 "\\(" tramp-user-regexp x-nil "\\)$")
5799 1 2 nil nil))
00d6fd04 5800 ;; "/method:host" "/[method/host" "/method://host"
b96e6899 5801 (tramp-completion-file-name-structure8
4007ba5b 5802 (list (concat tramp-prefix-regexp
00d6fd04 5803 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5804 "\\(" tramp-host-regexp x-nil "\\)$")
5805 1 nil 2 nil))
b96e6899
MA
5806 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5807 (tramp-completion-file-name-structure9
5808 (list (concat tramp-prefix-regexp
5809 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5810 tramp-prefix-ipv6-regexp
5811 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5812 1 nil 2 nil))
00d6fd04 5813 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
b96e6899 5814 (tramp-completion-file-name-structure10
4007ba5b 5815 (list (concat tramp-prefix-regexp
00d6fd04 5816 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5817 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5818 "\\(" tramp-host-regexp x-nil "\\)$")
00d6fd04 5819 1 2 3 nil))
b96e6899
MA
5820 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5821 (tramp-completion-file-name-structure11
5822 (list (concat tramp-prefix-regexp
5823 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5824 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5825 tramp-prefix-ipv6-regexp
5826 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5827 1 2 3 nil))
00d6fd04 5828 ;; "/method: "/method:/"
b96e6899 5829 (tramp-completion-file-name-structure12
00d6fd04
MA
5830 (list
5831 (if (equal tramp-syntax 'url)
5832 (concat tramp-prefix-regexp
5833 "\\(" tramp-method-regexp "\\)"
5834 "\\(" (substring tramp-postfix-method-regexp 0 1)
5835 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5836 "\\(" "\\)$")
5837 ;; Should not match if not URL syntax.
5838 (concat tramp-prefix-regexp "/$"))
5839 1 3 nil nil))
5840 ;; "/method: "/method:/"
b96e6899 5841 (tramp-completion-file-name-structure13
00d6fd04
MA
5842 (list
5843 (if (equal tramp-syntax 'url)
5844 (concat tramp-prefix-regexp
5845 "\\(" tramp-method-regexp "\\)"
5846 "\\(" (substring tramp-postfix-method-regexp 0 1)
5847 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5848 "\\(" "\\)$")
5849 ;; Should not match if not URL syntax.
5850 (concat tramp-prefix-regexp "/$"))
5851 1 nil 3 nil)))
4007ba5b 5852
9e6ab520 5853 (mapc (lambda (regexp)
16674e4f
KG
5854 (add-to-list 'result
5855 (tramp-completion-dissect-file-name1 regexp name)))
5856 (list
5857 tramp-completion-file-name-structure1
5858 tramp-completion-file-name-structure2
5859 tramp-completion-file-name-structure3
5860 tramp-completion-file-name-structure4
5861 tramp-completion-file-name-structure5
5862 tramp-completion-file-name-structure6
5863 tramp-completion-file-name-structure7
00d6fd04
MA
5864 tramp-completion-file-name-structure8
5865 tramp-completion-file-name-structure9
b96e6899
MA
5866 tramp-completion-file-name-structure10
5867 tramp-completion-file-name-structure11
5868 tramp-completion-file-name-structure12
5869 tramp-completion-file-name-structure13
16674e4f
KG
5870 tramp-file-name-structure))
5871
5872 (delq nil result)))
5873
5874(defun tramp-completion-dissect-file-name1 (structure name)
5875 "Returns a `tramp-file-name' structure matching STRUCTURE.
00d6fd04 5876The structure consists of remote method, remote user,
7432277c 5877remote host and localname (filename on remote host)."
fb7933a3 5878
00d6fd04
MA
5879 (save-match-data
5880 (when (string-match (nth 0 structure) name)
5881 (let ((method (and (nth 1 structure)
5882 (match-string (nth 1 structure) name)))
5883 (user (and (nth 2 structure)
5884 (match-string (nth 2 structure) name)))
5885 (host (and (nth 3 structure)
5886 (match-string (nth 3 structure) name)))
5887 (localname (and (nth 4 structure)
5888 (match-string (nth 4 structure) name))))
5889 (vector method user host localname)))))
16674e4f
KG
5890
5891;; This function returns all possible method completions, adding the
5892;; trailing method delimeter.
16674e4f
KG
5893(defun tramp-get-completion-methods (partial-method)
5894 "Returns all method completions for PARTIAL-METHOD."
4007ba5b
KG
5895 (mapcar
5896 (lambda (method)
5897 (and method
5898 (string-match (concat "^" (regexp-quote partial-method)) method)
00d6fd04
MA
5899 (tramp-completion-make-tramp-file-name method nil nil nil)))
5900 (mapcar 'car tramp-methods)))
16674e4f
KG
5901
5902;; Compares partial user and host names with possible completions.
5903(defun tramp-get-completion-user-host (method partial-user partial-host user host)
5904 "Returns the most expanded string for user and host name completion.
5905PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5906 (cond
5907
5908 ((and partial-user partial-host)
5909 (if (and host
5910 (string-match (concat "^" (regexp-quote partial-host)) host)
5911 (string-equal partial-user (or user partial-user)))
5912 (setq user partial-user)
5913 (setq user nil
5914 host nil)))
5915
5916 (partial-user
5917 (setq host nil)
5918 (unless
5919 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5920 (setq user nil)))
5921
5922 (partial-host
5923 (setq user nil)
5924 (unless
5925 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5926 (setq host nil)))
5927
5928 (t (setq user nil
5929 host nil)))
5930
292ffc15 5931 (unless (zerop (+ (length user) (length host)))
00d6fd04 5932 (tramp-completion-make-tramp-file-name method user host nil)))
16674e4f
KG
5933
5934(defun tramp-parse-rhosts (filename)
5935 "Return a list of (user host) tuples allowed to access.
292ffc15 5936Either user or host may be nil."
00d6fd04
MA
5937 ;; On Windows, there are problems in completion when
5938 ;; `default-directory' is remote.
9e6ab520 5939 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5940 res)
8daea7fc 5941 (when (file-readable-p filename)
16674e4f
KG
5942 (with-temp-buffer
5943 (insert-file-contents filename)
5944 (goto-char (point-min))
5945 (while (not (eobp))
292ffc15 5946 (push (tramp-parse-rhosts-group) res))))
16674e4f
KG
5947 res))
5948
16674e4f
KG
5949(defun tramp-parse-rhosts-group ()
5950 "Return a (user host) tuple allowed to access.
292ffc15 5951Either user or host may be nil."
16674e4f
KG
5952 (let ((result)
5953 (regexp
5954 (concat
5955 "^\\(" tramp-host-regexp "\\)"
5956 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 5957 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5958 (when (re-search-forward regexp nil t)
5959 (setq result (append (list (match-string 3) (match-string 1)))))
5960 (widen)
5961 (forward-line 1)
5962 result))
5963
5964(defun tramp-parse-shosts (filename)
5965 "Return a list of (user host) tuples allowed to access.
5966User is always nil."
00d6fd04
MA
5967 ;; On Windows, there are problems in completion when
5968 ;; `default-directory' is remote.
9e6ab520 5969 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5970 res)
8daea7fc 5971 (when (file-readable-p filename)
16674e4f
KG
5972 (with-temp-buffer
5973 (insert-file-contents filename)
5974 (goto-char (point-min))
5975 (while (not (eobp))
292ffc15 5976 (push (tramp-parse-shosts-group) res))))
16674e4f
KG
5977 res))
5978
5979(defun tramp-parse-shosts-group ()
5980 "Return a (user host) tuple allowed to access.
5981User is always nil."
16674e4f
KG
5982 (let ((result)
5983 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
9e6ab520 5984 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5985 (when (re-search-forward regexp nil t)
5986 (setq result (list nil (match-string 1))))
5987 (widen)
5988 (or
5989 (> (skip-chars-forward ",") 0)
5990 (forward-line 1))
5991 result))
5992
8daea7fc
KG
5993(defun tramp-parse-sconfig (filename)
5994 "Return a list of (user host) tuples allowed to access.
5995User is always nil."
00d6fd04
MA
5996 ;; On Windows, there are problems in completion when
5997 ;; `default-directory' is remote.
9e6ab520 5998 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5999 res)
8daea7fc
KG
6000 (when (file-readable-p filename)
6001 (with-temp-buffer
6002 (insert-file-contents filename)
6003 (goto-char (point-min))
6004 (while (not (eobp))
6005 (push (tramp-parse-sconfig-group) res))))
6006 res))
6007
6008(defun tramp-parse-sconfig-group ()
6009 "Return a (user host) tuple allowed to access.
6010User is always nil."
8daea7fc
KG
6011 (let ((result)
6012 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
9e6ab520 6013 (narrow-to-region (point) (tramp-compat-line-end-position))
8daea7fc
KG
6014 (when (re-search-forward regexp nil t)
6015 (setq result (list nil (match-string 1))))
6016 (widen)
6017 (or
6018 (> (skip-chars-forward ",") 0)
6019 (forward-line 1))
6020 result))
6021
5ec2cc41
KG
6022(defun tramp-parse-shostkeys (dirname)
6023 "Return a list of (user host) tuples allowed to access.
6024User is always nil."
00d6fd04
MA
6025 ;; On Windows, there are problems in completion when
6026 ;; `default-directory' is remote.
9e6ab520 6027 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6028 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6029 (files (when (file-directory-p dirname) (directory-files dirname)))
6030 result)
5ec2cc41
KG
6031 (while files
6032 (when (string-match regexp (car files))
6033 (push (list nil (match-string 1 (car files))) result))
6034 (setq files (cdr files)))
6035 result))
6036
6037(defun tramp-parse-sknownhosts (dirname)
6038 "Return a list of (user host) tuples allowed to access.
6039User is always nil."
00d6fd04
MA
6040 ;; On Windows, there are problems in completion when
6041 ;; `default-directory' is remote.
9e6ab520 6042 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6043 (regexp (concat "^\\(" tramp-host-regexp
6044 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6045 (files (when (file-directory-p dirname) (directory-files dirname)))
6046 result)
5ec2cc41
KG
6047 (while files
6048 (when (string-match regexp (car files))
6049 (push (list nil (match-string 1 (car files))) result))
6050 (setq files (cdr files)))
6051 result))
6052
16674e4f
KG
6053(defun tramp-parse-hosts (filename)
6054 "Return a list of (user host) tuples allowed to access.
6055User is always nil."
00d6fd04
MA
6056 ;; On Windows, there are problems in completion when
6057 ;; `default-directory' is remote.
9e6ab520 6058 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6059 res)
8daea7fc 6060 (when (file-readable-p filename)
16674e4f
KG
6061 (with-temp-buffer
6062 (insert-file-contents filename)
6063 (goto-char (point-min))
6064 (while (not (eobp))
292ffc15 6065 (push (tramp-parse-hosts-group) res))))
16674e4f
KG
6066 res))
6067
6068(defun tramp-parse-hosts-group ()
6069 "Return a (user host) tuple allowed to access.
6070User is always nil."
16674e4f 6071 (let ((result)
b96e6899
MA
6072 (regexp
6073 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
9e6ab520 6074 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f 6075 (when (re-search-forward regexp nil t)
b96e6899 6076 (setq result (list nil (match-string 1))))
16674e4f
KG
6077 (widen)
6078 (or
6079 (> (skip-chars-forward " \t") 0)
6080 (forward-line 1))
6081 result))
6082
8daea7fc
KG
6083;; For su-alike methods it would be desirable to return "root@localhost"
6084;; as default. Unfortunately, we have no information whether any user name
00d6fd04 6085;; has been typed already. So we use `tramp-current-user' as indication,
8daea7fc 6086;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
16674e4f
KG
6087(defun tramp-parse-passwd (filename)
6088 "Return a list of (user host) tuples allowed to access.
6089Host is always \"localhost\"."
00d6fd04
MA
6090 ;; On Windows, there are problems in completion when
6091 ;; `default-directory' is remote.
9e6ab520 6092 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6093 res)
8daea7fc 6094 (if (zerop (length tramp-current-user))
16674e4f 6095 '(("root" nil))
8daea7fc 6096 (when (file-readable-p filename)
16674e4f
KG
6097 (with-temp-buffer
6098 (insert-file-contents filename)
6099 (goto-char (point-min))
6100 (while (not (eobp))
292ffc15 6101 (push (tramp-parse-passwd-group) res))))
16674e4f
KG
6102 res)))
6103
6104(defun tramp-parse-passwd-group ()
6105 "Return a (user host) tuple allowed to access.
292ffc15 6106Host is always \"localhost\"."
16674e4f
KG
6107 (let ((result)
6108 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
9e6ab520 6109 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
6110 (when (re-search-forward regexp nil t)
6111 (setq result (list (match-string 1) "localhost")))
6112 (widen)
6113 (forward-line 1)
6114 result))
6115
292ffc15
KG
6116(defun tramp-parse-netrc (filename)
6117 "Return a list of (user host) tuples allowed to access.
6118User may be nil."
00d6fd04
MA
6119 ;; On Windows, there are problems in completion when
6120 ;; `default-directory' is remote.
9e6ab520 6121 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6122 res)
8daea7fc 6123 (when (file-readable-p filename)
292ffc15
KG
6124 (with-temp-buffer
6125 (insert-file-contents filename)
6126 (goto-char (point-min))
6127 (while (not (eobp))
6128 (push (tramp-parse-netrc-group) res))))
6129 res))
6130
6131(defun tramp-parse-netrc-group ()
6132 "Return a (user host) tuple allowed to access.
6133User may be nil."
292ffc15
KG
6134 (let ((result)
6135 (regexp
6136 (concat
6137 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6138 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 6139 (narrow-to-region (point) (tramp-compat-line-end-position))
292ffc15
KG
6140 (when (re-search-forward regexp nil t)
6141 (setq result (list (match-string 3) (match-string 1))))
6142 (widen)
6143 (forward-line 1)
6144 result))
6145
00d6fd04
MA
6146(defun tramp-parse-putty (registry)
6147 "Return a list of (user host) tuples allowed to access.
6148User is always nil."
6149 ;; On Windows, there are problems in completion when
6150 ;; `default-directory' is remote.
9e6ab520 6151 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6152 res)
6153 (with-temp-buffer
a4aeb9a4 6154 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
00d6fd04
MA
6155 (goto-char (point-min))
6156 (while (not (eobp))
6157 (push (tramp-parse-putty-group registry) res))))
6158 res))
6159
6160(defun tramp-parse-putty-group (registry)
6161 "Return a (user host) tuple allowed to access.
6162User is always nil."
6163 (let ((result)
6164 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
9e6ab520 6165 (narrow-to-region (point) (tramp-compat-line-end-position))
00d6fd04
MA
6166 (when (re-search-forward regexp nil t)
6167 (setq result (list nil (match-string 1))))
6168 (widen)
6169 (forward-line 1)
6170 result))
6171
fb7933a3
KG
6172;;; Internal Functions:
6173
00d6fd04
MA
6174(defun tramp-maybe-send-script (vec script name)
6175 "Define in remote shell function NAME implemented as SCRIPT.
6176Only send the definition if it has not already been done."
6177 (let* ((p (tramp-get-connection-process vec))
6178 (scripts (tramp-get-connection-property p "scripts" nil)))
1834b39f 6179 (unless (member name scripts)
00d6fd04
MA
6180 (tramp-message vec 5 "Sending script `%s'..." name)
6181 ;; The script could contain a call of Perl. This is masked with `%s'.
6182 (tramp-send-command-and-check
6183 vec
6184 (format "%s () {\n%s\n}" name
6185 (format script (tramp-get-remote-perl vec))))
6186 (tramp-set-connection-property p "scripts" (cons name scripts))
6187 (tramp-message vec 5 "Sending script `%s'...done." name))))
c82c5727 6188
fb7933a3 6189(defun tramp-set-auto-save ()
00d6fd04 6190 (when (and ;; ange-ftp has its own auto-save mechanism
7177e2a3
MA
6191 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6192 'tramp-sh-file-name-handler)
fb7933a3
KG
6193 auto-save-default)
6194 (auto-save-mode 1)))
6195(add-hook 'find-file-hooks 'tramp-set-auto-save t)
a69c01a0 6196(add-hook 'tramp-unload-hook
aa485f7c
MA
6197 (lambda ()
6198 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
fb7933a3
KG
6199
6200(defun tramp-run-test (switch filename)
6201 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6202Returns the exit code of the `test' program."
00d6fd04
MA
6203 (with-parsed-tramp-file-name filename nil
6204 (tramp-send-command-and-check
6205 v
6206 (format
6207 "%s %s %s"
6208 (tramp-get-test-command v)
6209 switch
6210 (tramp-shell-quote-argument localname)))))
6211
6212(defun tramp-run-test2 (format-string file1 file2)
6213 "Run `test'-like program on the remote system, given FILE1, FILE2.
6214FORMAT-STRING contains the program name, switches, and place holders.
6215Returns the exit code of the `test' program. Barfs if the methods,
fb7933a3 6216hosts, or files, disagree."
00d6fd04
MA
6217 (unless (tramp-equal-remote file1 file2)
6218 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6219 (tramp-error
6220 v 'file-error
6221 "tramp-run-test2 only implemented for same method, user, host")))
6222 (with-parsed-tramp-file-name file1 v1
6223 (with-parsed-tramp-file-name file1 v2
fb7933a3 6224 (tramp-send-command-and-check
00d6fd04
MA
6225 v1
6226 (format format-string
6227 (tramp-shell-quote-argument v1-localname)
6228 (tramp-shell-quote-argument v2-localname))))))
fb7933a3 6229
00d6fd04
MA
6230(defun tramp-buffer-name (vec)
6231 "A name for the connection buffer VEC."
6232 ;; We must use `tramp-file-name-real-host', because for gateway
6233 ;; methods the default port will be expanded later on, which would
6234 ;; tamper the name.
6235 (let ((method (tramp-file-name-method vec))
6236 (user (tramp-file-name-user vec))
6237 (host (tramp-file-name-real-host vec)))
6238 (if (not (zerop (length user)))
6239 (format "*tramp/%s %s@%s*" method user host)
6240 (format "*tramp/%s %s*" method host))))
6241
b88f2d0a
MA
6242(defun tramp-delete-temp-file-function ()
6243 "Remove temporary files related to current buffer."
6244 (when (stringp tramp-temp-buffer-file-name)
6245 (condition-case nil
6246 (delete-file tramp-temp-buffer-file-name)
6247 (error nil))))
6248
6249(add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6250(add-hook 'tramp-cache-unload-hook
6251 (lambda ()
6252 (remove-hook 'kill-buffer-hook
6253 'tramp-delete-temp-file-function)))
6254
00d6fd04
MA
6255(defun tramp-get-buffer (vec)
6256 "Get the connection buffer to be used for VEC."
6257 (or (get-buffer (tramp-buffer-name vec))
6258 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6259 (setq buffer-undo-list t)
6260 (setq default-directory
6261 (tramp-make-tramp-file-name
6262 (tramp-file-name-method vec)
6263 (tramp-file-name-user vec)
6264 (tramp-file-name-host vec)
6265 "/"))
6266 (current-buffer))))
6267
6268(defun tramp-get-connection-buffer (vec)
6269 "Get the connection buffer to be used for VEC.
6270In case a second asynchronous communication has been started, it is different
6271from `tramp-get-buffer'."
6272 (or (tramp-get-connection-property vec "process-buffer" nil)
6273 (tramp-get-buffer vec)))
6274
6275(defun tramp-get-connection-process (vec)
6276 "Get the connection process to be used for VEC.
6277In case a second asynchronous communication has been started, it is different
6278from the default one."
6279 (get-process
6280 (or (tramp-get-connection-property vec "process-name" nil)
6281 (tramp-buffer-name vec))))
6282
6283(defun tramp-debug-buffer-name (vec)
6284 "A name for the debug buffer for VEC."
6285 ;; We must use `tramp-file-name-real-host', because for gateway
6286 ;; methods the default port will be expanded later on, which would
6287 ;; tamper the name.
6288 (let ((method (tramp-file-name-method vec))
6289 (user (tramp-file-name-user vec))
6290 (host (tramp-file-name-real-host vec)))
6291 (if (not (zerop (length user)))
6292 (format "*debug tramp/%s %s@%s*" method user host)
6293 (format "*debug tramp/%s %s*" method host))))
6294
b533bc97
MA
6295(defconst tramp-debug-outline-regexp
6296 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6297
00d6fd04
MA
6298(defun tramp-get-debug-buffer (vec)
6299 "Get the debug buffer for VEC."
01917a18 6300 (with-current-buffer
00d6fd04
MA
6301 (get-buffer-create (tramp-debug-buffer-name vec))
6302 (when (bobp)
6303 (setq buffer-undo-list t)
b533bc97 6304 ;; Activate `outline-mode'. This runs `text-mode-hook' and
9ce8462a 6305 ;; `outline-mode-hook'. We must prevent that local processes
b533bc97
MA
6306 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6307 ;; Furthermore, `outline-regexp' must have the correct value
6308 ;; already, because it is used by `font-lock-compile-keywords'.
6309 (let ((default-directory (tramp-compat-temporary-file-directory))
6310 (outline-regexp tramp-debug-outline-regexp))
00d6fd04 6311 (outline-mode))
b533bc97 6312 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
9ce8462a 6313 (set (make-local-variable 'outline-level) 'tramp-outline-level))
01917a18 6314 (current-buffer)))
fb7933a3 6315
00d6fd04
MA
6316(defun tramp-outline-level ()
6317 "Return the depth to which a statement is nested in the outline.
6318Point must be at the beginning of a header line.
6319
6320The outline level is equal to the verbosity of the Tramp message."
6321 (1+ (string-to-number (match-string 1))))
fb7933a3 6322
00d6fd04
MA
6323(defun tramp-find-executable
6324 (vec progname dirlist &optional ignore-tilde ignore-path)
6325 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6326First arg VEC specifies the connection, PROGNAME is the program
6327to search for, and DIRLIST gives the list of directories to
6328search. If IGNORE-TILDE is non-nil, directory names starting
6329with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6330only in DIRLIST.
fb7933a3 6331
7432277c 6332Returns the absolute file name of PROGNAME, if found, and nil otherwise.
fb7933a3
KG
6333
6334This function expects to be in the right *tramp* buffer."
c0e17ff2 6335 (with-current-buffer (tramp-get-connection-buffer vec)
00d6fd04
MA
6336 (let (result)
6337 ;; Check whether the executable is in $PATH. "which(1)" does not
6338 ;; report always a correct error code; therefore we check the
6339 ;; number of words it returns.
6340 (unless ignore-path
6341 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6342 (goto-char (point-min))
c0e17ff2 6343 (if (looking-at "^\\s-*1$")
00d6fd04
MA
6344 (setq result (concat "\\" progname))))
6345 (unless result
6346 (when ignore-tilde
b533bc97 6347 ;; Remove all ~/foo directories from dirlist. In XEmacs,
00d6fd04
MA
6348 ;; `remove' is in CL, and we want to avoid CL dependencies.
6349 (let (newdl d)
6350 (while dirlist
6351 (setq d (car dirlist))
6352 (setq dirlist (cdr dirlist))
6353 (unless (char-equal ?~ (aref d 0))
6354 (setq newdl (cons d newdl))))
6355 (setq dirlist (nreverse newdl))))
6356 (tramp-send-command
6357 vec
6358 (format (concat "while read d; "
6359 "do if test -x $d/%s -a -f $d/%s; "
6360 "then echo tramp_executable $d/%s; "
6361 "break; fi; done <<'EOF'\n"
6362 "%s\nEOF")
6363 progname progname progname (mapconcat 'identity dirlist "\n")))
6364 (goto-char (point-max))
6365 (when (search-backward "tramp_executable " nil t)
6366 (skip-chars-forward "^ ")
6367 (skip-chars-forward " ")
9e6ab520
MA
6368 (setq result (buffer-substring
6369 (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
6370 result)))
6371
6372(defun tramp-set-remote-path (vec)
6373 "Sets the remote environment PATH to existing directories.
6374I.e., for each directory in `tramp-remote-path', it is tested
6375whether it exists and if so, it is added to the environment
6376variable PATH."
6377 (tramp-message vec 5 (format "Setting $PATH environment variable"))
f84638eb
MA
6378 (tramp-send-command
6379 vec (format "PATH=%s; export PATH"
6380 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
fb7933a3 6381
cfb5c0db
MA
6382;; ------------------------------------------------------------
6383;; -- Communication with external shell --
6384;; ------------------------------------------------------------
fb7933a3 6385
00d6fd04 6386(defun tramp-find-file-exists-command (vec)
fb7933a3
KG
6387 "Find a command on the remote host for checking if a file exists.
6388Here, we are looking for a command which has zero exit status if the
6389file exists and nonzero exit status otherwise."
00d6fd04 6390 (let ((existing "/")
fb7933a3 6391 (nonexisting
00d6fd04
MA
6392 (tramp-shell-quote-argument "/ this file does not exist "))
6393 result)
fb7933a3
KG
6394 ;; The algorithm is as follows: we try a list of several commands.
6395 ;; For each command, we first run `$cmd /' -- this should return
6396 ;; true, as the root directory always exists. And then we run
00d6fd04 6397 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
fb7933a3
KG
6398 ;; does not exist. This should return false. We use the first
6399 ;; command we find that seems to work.
6400 ;; The list of commands to try is as follows:
00d6fd04
MA
6401 ;; `ls -d' This works on most systems, but NetBSD 1.4
6402 ;; has a bug: `ls' always returns zero exit
6403 ;; status, even for files which don't exist.
6404 ;; `test -e' Some Bourne shells have a `test' builtin
6405 ;; which does not know the `-e' option.
6406 ;; `/bin/test -e' For those, the `test' binary on disk normally
6407 ;; provides the option. Alas, the binary
6408 ;; is sometimes `/bin/test' and sometimes it's
6409 ;; `/usr/bin/test'.
6410 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
fb7933a3 6411 (unless (or
00d6fd04
MA
6412 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6413 (zerop (tramp-send-command-and-check
6414 vec (format "%s %s" result existing)))
6415 (not (zerop (tramp-send-command-and-check
6416 vec (format "%s %s" result nonexisting)))))
6417 (and (setq result "/bin/test -e")
6418 (zerop (tramp-send-command-and-check
6419 vec (format "%s %s" result existing)))
6420 (not (zerop (tramp-send-command-and-check
6421 vec (format "%s %s" result nonexisting)))))
6422 (and (setq result "/usr/bin/test -e")
6423 (zerop (tramp-send-command-and-check
6424 vec (format "%s %s" result existing)))
6425 (not (zerop (tramp-send-command-and-check
6426 vec (format "%s %s" result nonexisting)))))
6427 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6428 (zerop (tramp-send-command-and-check
6429 vec (format "%s %s" result existing)))
6430 (not (zerop (tramp-send-command-and-check
6431 vec (format "%s %s" result nonexisting))))))
6432 (tramp-error
6433 vec 'file-error "Couldn't find command to check if file exists"))
6434 result))
bf247b6e 6435
fb7933a3 6436;; CCC test ksh or bash found for tilde expansion?
00d6fd04
MA
6437(defun tramp-find-shell (vec)
6438 "Opens a shell on the remote host which groks tilde expansion."
6439 (unless (tramp-get-connection-property vec "remote-shell" nil)
6440 (let (shell)
6441 (with-current-buffer (tramp-get-buffer vec)
7e780ff1 6442 (tramp-send-command vec "echo ~root" t)
00d6fd04 6443 (cond
c0e17ff2
MA
6444 ((or (string-match "^~root$" (buffer-string))
6445 ;; The default shell (ksh93) of OpenSolaris is buggy.
6446 (string-equal (tramp-get-connection-property vec "uname" "")
6447 "SunOS 5.11"))
00d6fd04 6448 (setq shell
f84638eb 6449 (or (tramp-find-executable
c0e17ff2 6450 vec "bash" (tramp-get-remote-path vec) t t)
f84638eb 6451 (tramp-find-executable
c0e17ff2 6452 vec "ksh" (tramp-get-remote-path vec) t t)))
00d6fd04
MA
6453 (unless shell
6454 (tramp-error
6455 vec 'file-error
6456 "Couldn't find a shell which groks tilde expansion"))
6457 ;; Find arguments for this shell.
6458 (let ((alist tramp-sh-extra-args)
6459 item extra-args)
6460 (while (and alist (null extra-args))
6461 (setq item (pop alist))
6462 (when (string-match (car item) shell)
6463 (setq extra-args (cdr item))))
6464 (when extra-args (setq shell (concat shell " " extra-args))))
6465 (tramp-message
6466 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
dab816a9 6467 (let ((tramp-end-of-output tramp-initial-end-of-output))
a4aeb9a4 6468 (tramp-send-command
b08104a0 6469 vec
70c11b0b
MA
6470 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6471 (shell-quote-argument tramp-end-of-output) shell)
b08104a0 6472 t))
a0a5183a 6473 ;; Setting prompts.
00d6fd04 6474 (tramp-message vec 5 "Setting remote shell prompt...")
70c11b0b
MA
6475 (tramp-send-command
6476 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
6477 (tramp-send-command vec "PS2=''" t)
6478 (tramp-send-command vec "PS3=''" t)
6479 (tramp-send-command vec "PROMPT_COMMAND=''" t)
00d6fd04 6480 (tramp-message vec 5 "Setting remote shell prompt...done"))
a0a5183a 6481
00d6fd04
MA
6482 (t (tramp-message
6483 vec 5 "Remote `%s' groks tilde expansion, good"
6484 (tramp-get-method-parameter
6485 (tramp-file-name-method vec) 'tramp-remote-sh))
6486 (tramp-set-connection-property
6487 vec "remote-shell"
6488 (tramp-get-method-parameter
6489 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
fb7933a3 6490
bf247b6e
KS
6491;; ------------------------------------------------------------
6492;; -- Functions for establishing connection --
6493;; ------------------------------------------------------------
fb7933a3 6494
ac474af1
KG
6495;; The following functions are actions to be taken when seeing certain
6496;; prompts from the remote host. See the variable
6497;; `tramp-actions-before-shell' for usage of these functions.
6498
00d6fd04 6499(defun tramp-action-login (proc vec)
ac474af1 6500 "Send the login name."
00d6fd04
MA
6501 (when (not (stringp tramp-current-user))
6502 (save-window-excursion
6503 (let ((enable-recursive-minibuffers t))
6504 (pop-to-buffer (tramp-get-connection-buffer vec))
6505 (setq tramp-current-user (read-string (match-string 0))))))
6506 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6507 (with-current-buffer (tramp-get-connection-buffer vec)
6508 (tramp-message vec 6 "\n%s" (buffer-string)))
6509 (tramp-send-string vec tramp-current-user))
6510
6511(defun tramp-action-password (proc vec)
ac474af1 6512 "Query the user for a password."
70c11b0b
MA
6513 (with-current-buffer (process-buffer proc)
6514 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6515 (tramp-message vec 3 "Sending %s" (match-string 1)))
00d6fd04
MA
6516 (tramp-enter-password proc))
6517
6518(defun tramp-action-succeed (proc vec)
ac474af1 6519 "Signal success in finding shell prompt."
ac474af1
KG
6520 (throw 'tramp-action 'ok))
6521
00d6fd04 6522(defun tramp-action-permission-denied (proc vec)
ac474af1 6523 "Signal permission denied."
00d6fd04 6524 (kill-process proc)
ac474af1
KG
6525 (throw 'tramp-action 'permission-denied))
6526
00d6fd04 6527(defun tramp-action-yesno (proc vec)
3cdaec13
KG
6528 "Ask the user for confirmation using `yes-or-no-p'.
6529Send \"yes\" to remote process on confirmation, abort otherwise.
6530See also `tramp-action-yn'."
ac474af1 6531 (save-window-excursion
00d6fd04
MA
6532 (let ((enable-recursive-minibuffers t))
6533 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6534 (unless (yes-or-no-p (match-string 0))
6535 (kill-process proc)
6536 (throw 'tramp-action 'permission-denied))
6537 (with-current-buffer (tramp-get-connection-buffer vec)
6538 (tramp-message vec 6 "\n%s" (buffer-string)))
6539 (tramp-send-string vec "yes"))))
6540
6541(defun tramp-action-yn (proc vec)
3cdaec13
KG
6542 "Ask the user for confirmation using `y-or-n-p'.
6543Send \"y\" to remote process on confirmation, abort otherwise.
6544See also `tramp-action-yesno'."
6545 (save-window-excursion
00d6fd04
MA
6546 (let ((enable-recursive-minibuffers t))
6547 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6548 (unless (y-or-n-p (match-string 0))
6549 (kill-process proc)
6550 (throw 'tramp-action 'permission-denied))
6551 (with-current-buffer (tramp-get-connection-buffer vec)
6552 (tramp-message vec 6 "\n%s" (buffer-string)))
6553 (tramp-send-string vec "y"))))
6554
6555(defun tramp-action-terminal (proc vec)
487f4fb7
KG
6556 "Tell the remote host which terminal type to use.
6557The terminal type can be configured with `tramp-terminal-type'."
00d6fd04 6558 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
7e780ff1
MA
6559 (with-current-buffer (tramp-get-connection-buffer vec)
6560 (tramp-message vec 6 "\n%s" (buffer-string)))
00d6fd04 6561 (tramp-send-string vec tramp-terminal-type))
487f4fb7 6562
00d6fd04 6563(defun tramp-action-process-alive (proc vec)
19a87064 6564 "Check whether a process has finished."
00d6fd04 6565 (unless (memq (process-status proc) '(run open))
19a87064
MA
6566 (throw 'tramp-action 'process-died)))
6567
00d6fd04 6568(defun tramp-action-out-of-band (proc vec)
38c65fca 6569 "Check whether an out-of-band copy has finished."
00d6fd04
MA
6570 (cond ((and (memq (process-status proc) '(stop exit))
6571 (zerop (process-exit-status proc)))
6572 (tramp-message vec 3 "Process has finished.")
38c65fca 6573 (throw 'tramp-action 'ok))
00d6fd04
MA
6574 ((or (and (memq (process-status proc) '(stop exit))
6575 (not (zerop (process-exit-status proc))))
6576 (memq (process-status proc) '(signal)))
01917a18
MA
6577 ;; `scp' could have copied correctly, but set modes could have failed.
6578 ;; This can be ignored.
00d6fd04
MA
6579 (with-current-buffer (process-buffer proc)
6580 (goto-char (point-min))
6581 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6582 (progn
6583 (tramp-message vec 5 "'set mode' error ignored.")
6584 (tramp-message vec 3 "Process has finished.")
6585 (throw 'tramp-action 'ok))
6586 (tramp-message vec 3 "Process has died.")
6587 (throw 'tramp-action 'process-died))))
38c65fca
KG
6588 (t nil)))
6589
ac474af1
KG
6590;; Functions for processing the actions.
6591
00d6fd04 6592(defun tramp-process-one-action (proc vec actions)
ac474af1 6593 "Wait for output from the shell and perform one action."
00d6fd04 6594 (let (found todo item pattern action)
e6466697 6595 (while (not found)
00d6fd04
MA
6596 ;; Reread output once all actions have been performed.
6597 ;; Obviously, the output was not complete.
6598 (tramp-accept-process-output proc 1)
e6466697
MA
6599 (setq todo actions)
6600 (while todo
e6466697 6601 (setq item (pop todo))
95d610cb 6602 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
e6466697 6603 (setq action (nth 1 item))
00d6fd04
MA
6604 (tramp-message
6605 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6606 (when (tramp-check-for-regexp proc pattern)
6607 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6608 (setq found (funcall action proc vec)))))
e6466697
MA
6609 found))
6610
00d6fd04 6611(defun tramp-process-actions (proc vec actions &optional timeout)
e6466697 6612 "Perform actions until success or TIMEOUT."
263c02ef 6613 ;; Enable auth-source and password-cache.
7540f029 6614 (tramp-set-connection-property vec "first-password-request" t)
ac474af1
KG
6615 (let (exit)
6616 (while (not exit)
00d6fd04 6617 (tramp-message proc 3 "Waiting for prompts from remote shell")
ac474af1
KG
6618 (setq exit
6619 (catch 'tramp-action
e6466697
MA
6620 (if timeout
6621 (with-timeout (timeout)
00d6fd04
MA
6622 (tramp-process-one-action proc vec actions))
6623 (tramp-process-one-action proc vec actions)))))
6624 (with-current-buffer (tramp-get-connection-buffer vec)
6625 (tramp-message vec 6 "\n%s" (buffer-string)))
ac474af1 6626 (unless (eq exit 'ok)
9c13938d 6627 (tramp-clear-passwd vec)
00d6fd04
MA
6628 (tramp-error-with-buffer
6629 nil vec 'file-error
6630 (cond
6631 ((eq exit 'permission-denied) "Permission denied")
6632 ((eq exit 'process-died) "Process died")
6633 (t "Login failed"))))))
fb7933a3
KG
6634
6635;; Utility functions.
6636
00d6fd04 6637(defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
d2a2c17f
MA
6638 "Like `accept-process-output' for Tramp processes.
6639This is needed in order to hide `last-coding-system-used', which is set
6640for process communication also."
00d6fd04
MA
6641 (with-current-buffer (process-buffer proc)
6642 (tramp-message proc 10 "%s %s" proc (process-status proc))
6643 (let (buffer-read-only last-coding-system-used)
6644 ;; Under Windows XP, accept-process-output doesn't return
6645 ;; sometimes. So we add an additional timeout.
6646 (with-timeout ((or timeout 1))
6647 (accept-process-output proc timeout timeout-msecs)))
6648 (tramp-message proc 10 "\n%s" (buffer-string))))
6649
6650(defun tramp-check-for-regexp (proc regexp)
6651 "Check whether REGEXP is contained in process buffer of PROC.
6652Erase echoed commands if exists."
6653 (with-current-buffer (process-buffer proc)
6654 (goto-char (point-min))
674da028 6655
00d6fd04
MA
6656 ;; Check whether we need to remove echo output.
6657 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6658 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6659 (let ((begin (match-beginning 0)))
6660 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6661 ;; Discard echo from remote output.
6662 (tramp-set-connection-property proc "check-remote-echo" nil)
6663 (tramp-message proc 5 "echo-mark found")
b533bc97 6664 (forward-line 1)
00d6fd04
MA
6665 (delete-region begin (point))
6666 (goto-char (point-min)))))
674da028 6667
68712eb6
MA
6668 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6669 ;; Sometimes, the echo string is suppressed on the remote side.
6670 (not (string-equal
6671 (substring-no-properties
6672 tramp-echo-mark-marker
6673 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6674 (buffer-substring-no-properties
6675 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
70c11b0b 6676 ;; No echo to be handled, now we can look for the regexp.
674da028 6677 (goto-char (point-min))
00d6fd04 6678 (re-search-forward regexp nil t))))
d2a2c17f 6679
fb7933a3
KG
6680(defun tramp-wait-for-regexp (proc timeout regexp)
6681 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6682Expects the output of PROC to be sent to the current buffer. Returns
6683the string that matched, or nil. Waits indefinitely if TIMEOUT is
6684nil."
00d6fd04
MA
6685 (with-current-buffer (process-buffer proc)
6686 (let ((found (tramp-check-for-regexp proc regexp))
6687 (start-time (current-time)))
6688 (cond (timeout
6689 ;; Work around a bug in XEmacs 21, where the timeout
6690 ;; expires faster than it should. This degenerates
6691 ;; to polling for buggy XEmacsen, but oh, well.
6692 (while (and (not found)
6693 (< (tramp-time-diff (current-time) start-time)
6694 timeout))
6695 (with-timeout (timeout)
6696 (while (not found)
6697 (tramp-accept-process-output proc 1)
6698 (unless (memq (process-status proc) '(run open))
6699 (tramp-error-with-buffer
6700 nil proc 'file-error "Process has died"))
6701 (setq found (tramp-check-for-regexp proc regexp))))))
6702 (t
6703 (while (not found)
6704 (tramp-accept-process-output proc 1)
6705 (unless (memq (process-status proc) '(run open))
6706 (tramp-error-with-buffer
6707 nil proc 'file-error "Process has died"))
6708 (setq found (tramp-check-for-regexp proc regexp)))))
6709 (tramp-message proc 6 "\n%s" (buffer-string))
fb7933a3 6710 (when (not found)
00d6fd04
MA
6711 (if timeout
6712 (tramp-error
6713 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6714 regexp timeout)
6715 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6716 found)))
fb7933a3 6717
b25a52cc
KG
6718(defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6719 "Wait for shell prompt and barf if none appears.
6720Looks at process PROC to see if a shell prompt appears in TIMEOUT
6721seconds. If not, it produces an error message with the given ERROR-ARGS."
7e780ff1
MA
6722 (unless
6723 (tramp-wait-for-regexp
6724 proc timeout
6725 (format
6726 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
00d6fd04
MA
6727 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6728
7e780ff1
MA
6729;; We don't call `tramp-send-string' in order to hide the password
6730;; from the debug buffer, and because end-of-line handling of the
6731;; string.
6732(defun tramp-enter-password (proc)
00d6fd04
MA
6733 "Prompt for a password and send it to the remote end."
6734 (process-send-string
7e780ff1
MA
6735 proc (concat (tramp-read-passwd proc)
6736 (or (tramp-get-method-parameter
6737 tramp-current-method
6738 'tramp-password-end-of-line)
6739 tramp-default-password-end-of-line))))
00d6fd04
MA
6740
6741(defun tramp-open-connection-setup-interactive-shell (proc vec)
fb7933a3 6742 "Set up an interactive shell.
00d6fd04
MA
6743Mainly sets the prompt and the echo correctly. PROC is the shell
6744process to set up. VEC specifies the connection."
dab816a9 6745 (let ((tramp-end-of-output tramp-initial-end-of-output))
8950769a
MA
6746 ;; It is useful to set the prompt in the following command because
6747 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6748 ;; about and thus /bin/sh will display a strange prompt. For
6749 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6750 ;; display the current working directory but /bin/sh will display
6751 ;; a dollar sign. The following command line sets $PS1 to a sane
6752 ;; value, and works under Bourne-ish shells as well as csh-like
6753 ;; shells. Daniel Pittman reports that the unusual positioning of
6754 ;; the single quotes makes it work under `rc', too. We also unset
6755 ;; the variable $ENV because that is read by some sh
6756 ;; implementations (eg, bash when called as sh) on startup; this
6757 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6758 ;; is another way to set the prompt in /bin/bash, it must be
6759 ;; discarded as well.
a4aeb9a4
MA
6760 (tramp-send-command
6761 vec
6762 (format
70c11b0b
MA
6763 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6764 (shell-quote-argument tramp-end-of-output)
a4aeb9a4
MA
6765 (tramp-get-method-parameter
6766 (tramp-file-name-method vec) 'tramp-remote-sh))
8950769a
MA
6767 t)
6768
6769 ;; Disable echo.
6770 (tramp-message vec 5 "Setting up remote shell environment")
6771 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6772 ;; Check whether the echo has really been disabled. Some
6773 ;; implementations, like busybox of embedded GNU/Linux, don't
6774 ;; support disabling.
6775 (tramp-send-command vec "echo foo" t)
6776 (with-current-buffer (process-buffer proc)
6777 (goto-char (point-min))
6778 (when (looking-at "echo foo")
6779 (tramp-set-connection-property proc "remote-echo" t)
6780 (tramp-message vec 5 "Remote echo still on. Ok.")
6781 ;; Make sure backspaces and their echo are enabled and no line
6782 ;; width magic interferes with them.
6783 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
e42c6bbc 6784
7e780ff1 6785 (tramp-message vec 5 "Setting shell prompt")
70c11b0b
MA
6786 (tramp-send-command
6787 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
6788 (tramp-send-command vec "PS2=''" t)
6789 (tramp-send-command vec "PS3=''" t)
6790 (tramp-send-command vec "PROMPT_COMMAND=''" t)
e42c6bbc 6791
fb7933a3
KG
6792 ;; Try to set up the coding system correctly.
6793 ;; CCC this can't be the right way to do it. Hm.
00d6fd04 6794 (tramp-message vec 5 "Determining coding system")
7e780ff1 6795 (tramp-send-command vec "echo foo ; echo bar" t)
00d6fd04 6796 (with-current-buffer (process-buffer proc)
fb7933a3
KG
6797 (goto-char (point-min))
6798 (if (featurep 'mule)
00d6fd04
MA
6799 ;; Use MULE to select the right EOL convention for communicating
6800 ;; with the process.
311dd93f 6801 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
00d6fd04
MA
6802 (cons 'undecided 'undecided)))
6803 cs-decode cs-encode)
6804 (when (symbolp cs) (setq cs (cons cs cs)))
6805 (setq cs-decode (car cs))
6806 (setq cs-encode (cdr cs))
6807 (unless cs-decode (setq cs-decode 'undecided))
6808 (unless cs-encode (setq cs-encode 'undecided))
6809 (setq cs-encode (tramp-coding-system-change-eol-conversion
6810 cs-encode 'unix))
6811 (when (search-forward "\r" nil t)
6812 (setq cs-decode (tramp-coding-system-change-eol-conversion
6813 cs-decode 'dos)))
311dd93f 6814 (funcall (symbol-function 'set-buffer-process-coding-system)
70c11b0b
MA
6815 cs-decode cs-encode)
6816 (tramp-message
6817 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
fb7933a3
KG
6818 ;; Look for ^M and do something useful if found.
6819 (when (search-forward "\r" nil t)
00d6fd04
MA
6820 ;; We have found a ^M but cannot frob the process coding system
6821 ;; because we're running on a non-MULE Emacs. Let's try
6822 ;; stty, instead.
7e780ff1 6823 (tramp-send-command vec "stty -onlcr" t))))
7e5686f0
MA
6824 ;; Dump stty settings in the traces.
6825 (when (>= tramp-verbose 10)
6826 (tramp-send-command vec "stty -a" t))
7e780ff1 6827 (tramp-send-command vec "set +o vi +o emacs" t)
e42c6bbc
MA
6828
6829 ;; Check whether the output of "uname -sr" has been changed. If
6830 ;; yes, this is a strong indication that we must expire all
d8ac123e
MA
6831 ;; connection properties. We start again with
6832 ;; `tramp-maybe-open-connection', it will be catched there.
e42c6bbc
MA
6833 (tramp-message vec 5 "Checking system information")
6834 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6835 (new-uname
6836 (tramp-set-connection-property
6837 vec "uname"
6838 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6839 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
d8ac123e
MA
6840 (with-current-buffer (tramp-get-debug-buffer vec)
6841 ;; Keep the debug buffer
2296b54d
MA
6842 (rename-buffer
6843 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
d8ac123e
MA
6844 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6845 (if (= (point-min) (point-max))
6846 (kill-buffer nil)
6847 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6848 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6849 (tramp-get-buffer vec)
6850 (tramp-message
6851 vec 3
6852 "Connection reset, because remote host changed from `%s' to `%s'"
6853 old-uname new-uname)
6854 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
e42c6bbc
MA
6855
6856 ;; Check whether the remote host suffers from buggy
6857 ;; `send-process-string'. This is known for FreeBSD (see comment in
6858 ;; `send_process', file process.c). I've tested sending 624 bytes
6859 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6860 ;; this host type is detected locally. It cannot handle remote
6861 ;; hosts, though.
00d6fd04
MA
6862 (with-connection-property proc "chunksize"
6863 (cond
6864 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6865 tramp-chunksize)
6866 (t
6867 (tramp-message
6868 vec 5 "Checking remote host type for `send-process-string' bug")
6869 (if (string-match
e42c6bbc 6870 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
00d6fd04 6871 500 0))))
e42c6bbc 6872
00d6fd04
MA
6873 ;; Set remote PATH variable.
6874 (tramp-set-remote-path vec)
e42c6bbc 6875
fb7933a3
KG
6876 ;; Search for a good shell before searching for a command which
6877 ;; checks if a file exists. This is done because Tramp wants to use
6878 ;; "test foo; echo $?" to check if various conditions hold, and
6879 ;; there are buggy /bin/sh implementations which don't execute the
6880 ;; "echo $?" part if the "test" part has an error. In particular,
c0e17ff2
MA
6881 ;; the OpenSolaris /bin/sh is a problem. There are also other
6882 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
6883 ;; in in function declarations, or changing HISTFILE in place.
6884 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
6885 ;; detected.
00d6fd04 6886 (tramp-find-shell vec)
e42c6bbc 6887
00d6fd04 6888 ;; Disable unexpected output.
7e780ff1 6889 (tramp-send-command vec "mesg n; biff n" t)
e42c6bbc 6890
00d6fd04
MA
6891 ;; Set the environment.
6892 (tramp-message vec 5 "Setting default environment")
661aaece 6893
00d6fd04
MA
6894 (let ((env (copy-sequence tramp-remote-process-environment))
6895 unset item)
6896 (while env
70c11b0b 6897 (setq item (tramp-compat-split-string (car env) "="))
7e5686f0
MA
6898 (setcdr item (mapconcat 'identity (cdr item) "="))
6899 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
00d6fd04 6900 (tramp-send-command
7e5686f0 6901 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
00d6fd04
MA
6902 (push (car item) unset))
6903 (setq env (cdr env)))
6904 (when unset
fb7933a3 6905 (tramp-send-command
7e780ff1 6906 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
fb7933a3 6907
ac474af1
KG
6908;; CCC: We should either implement a Perl version of base64 encoding
6909;; and decoding. Then we just use that in the last item. The other
6910;; alternative is to use the Perl version of UU encoding. But then
6911;; we need a Lisp version of uuencode.
16674e4f
KG
6912;;
6913;; Old text from documentation of tramp-methods:
6914;; Using a uuencode/uudecode inline method is discouraged, please use one
6915;; of the base64 methods instead since base64 encoding is much more
6916;; reliable and the commands are more standardized between the different
6917;; Unix versions. But if you can't use base64 for some reason, please
6918;; note that the default uudecode command does not work well for some
6919;; Unices, in particular AIX and Irix. For AIX, you might want to use
6920;; the following command for uudecode:
6921;;
6922;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6923;;
6924;; For Irix, no solution is known yet.
6925
00d6fd04
MA
6926(defconst tramp-local-coding-commands
6927 '((b64 base64-encode-region base64-decode-region)
6928 (uu tramp-uuencode-region uudecode-decode-region)
6929 (pack
6930 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6931 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6932 "List of local coding commands for inline transfer.
16674e4f
KG
6933Each item is a list that looks like this:
6934
b533bc97 6935\(FORMAT ENCODING DECODING\)
ac474af1 6936
00d6fd04
MA
6937FORMAT is symbol describing the encoding/decoding format. It can be
6938`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
ac474af1 6939
00d6fd04
MA
6940ENCODING and DECODING can be strings, giving commands, or symbols,
6941giving functions. If they are strings, then they can contain
16674e4f
KG
6942the \"%s\" format specifier. If that specifier is present, the input
6943filename will be put into the command line at that spot. If the
6944specifier is not present, the input should be read from standard
6945input.
ac474af1 6946
16674e4f
KG
6947If they are functions, they will be called with two arguments, start
6948and end of region, and are expected to replace the region contents
6949with the encoded or decoded results, respectively.")
ac474af1 6950
00d6fd04 6951(defconst tramp-remote-coding-commands
3dc847a3
MA
6952 '((b64 "base64" "base64 -d")
6953 (b64 "mimencode -b" "mimencode -u -b")
00d6fd04
MA
6954 (b64 "mmencode -b" "mmencode -u -b")
6955 (b64 "recode data..base64" "recode base64..data")
6956 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6957 (b64 tramp-perl-encode tramp-perl-decode)
6958 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6959 (uu "uuencode xxx" "uudecode -o -")
6960 (uu "uuencode xxx" "uudecode -p")
6961 (uu "uuencode xxx" tramp-uudecode)
6962 (pack
6963 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6964 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6965 "List of remote coding commands for inline transfer.
6966Each item is a list that looks like this:
6967
b533bc97 6968\(FORMAT ENCODING DECODING\)
00d6fd04
MA
6969
6970FORMAT is symbol describing the encoding/decoding format. It can be
6971`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6972
6973ENCODING and DECODING can be strings, giving commands, or symbols,
6974giving variables. If they are strings, then they can contain
6975the \"%s\" format specifier. If that specifier is present, the input
6976filename will be put into the command line at that spot. If the
6977specifier is not present, the input should be read from standard
6978input.
6979
6980If they are variables, this variable is a string containing a Perl
6981implementation for this functionality. This Perl program will be transferred
db9e401b 6982to the remote host, and it is available as shell function with the same name.")
00d6fd04
MA
6983
6984(defun tramp-find-inline-encoding (vec)
ac474af1 6985 "Find an inline transfer encoding that works.
00d6fd04
MA
6986Goes through the list `tramp-local-coding-commands' and
6987`tramp-remote-coding-commands'."
6988 (save-excursion
6989 (let ((local-commands tramp-local-coding-commands)
6990 (magic "xyzzy")
6991 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6992 (while (and local-commands (not found))
6993 (setq litem (pop local-commands))
6994 (catch 'wont-work-local
6995 (let ((format (nth 0 litem))
6996 (remote-commands tramp-remote-coding-commands))
6997 (setq loc-enc (nth 1 litem))
6998 (setq loc-dec (nth 2 litem))
6999 ;; If the local encoder or decoder is a string, the
7000 ;; corresponding command has to work locally.
7001 (if (not (stringp loc-enc))
7002 (tramp-message
7003 vec 5 "Checking local encoding function `%s'" loc-enc)
7004 (tramp-message
7005 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
7006 (unless (zerop (tramp-call-local-coding-command
7007 loc-enc nil nil))
7008 (throw 'wont-work-local nil)))
7009 (if (not (stringp loc-dec))
7010 (tramp-message
7011 vec 5 "Checking local decoding function `%s'" loc-dec)
7012 (tramp-message
7013 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7014 (unless (zerop (tramp-call-local-coding-command
7015 loc-dec nil nil))
7016 (throw 'wont-work-local nil)))
7017 ;; Search for remote coding commands with the same format
7018 (while (and remote-commands (not found))
7019 (setq ritem (pop remote-commands))
7020 (catch 'wont-work-remote
7021 (when (equal format (nth 0 ritem))
7022 (setq rem-enc (nth 1 ritem))
7023 (setq rem-dec (nth 2 ritem))
7024 ;; Check if remote encoding and decoding commands can be
7025 ;; called remotely with null input and output. This makes
7026 ;; sure there are no syntax errors and the command is really
7027 ;; found. Note that we do not redirect stdout to /dev/null,
7028 ;; for two reasons: when checking the decoding command, we
7029 ;; actually check the output it gives. And also, when
7030 ;; redirecting "mimencode" output to /dev/null, then as root
7031 ;; it might change the permissions of /dev/null!
7032 (when (not (stringp rem-enc))
7033 (let ((name (symbol-name rem-enc)))
7034 (while (string-match (regexp-quote "-") name)
7035 (setq name (replace-match "_" nil t name)))
7036 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7037 (setq rem-enc name)))
7038 (tramp-message
7039 vec 5
7040 "Checking remote encoding command `%s' for sanity" rem-enc)
7041 (unless (zerop (tramp-send-command-and-check
7042 vec (format "%s </dev/null" rem-enc) t))
7043 (throw 'wont-work-remote nil))
7044
7045 (when (not (stringp rem-dec))
7046 (let ((name (symbol-name rem-dec)))
7047 (while (string-match (regexp-quote "-") name)
7048 (setq name (replace-match "_" nil t name)))
7049 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7050 (setq rem-dec name)))
7051 (tramp-message
7052 vec 5
7053 "Checking remote decoding command `%s' for sanity" rem-dec)
7054 (unless (zerop (tramp-send-command-and-check
7055 vec
7056 (format "echo %s | %s | %s"
b593f105
MA
7057 magic rem-enc rem-dec)
7058 t))
00d6fd04
MA
7059 (throw 'wont-work-remote nil))
7060
7061 (with-current-buffer (tramp-get-buffer vec)
7062 (goto-char (point-min))
7063 (unless (looking-at (regexp-quote magic))
7064 (throw 'wont-work-remote nil)))
7065
7066 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7067 (setq rem-enc (nth 1 ritem))
7068 (setq rem-dec (nth 2 ritem))
7069 (setq found t)))))))
7070
1d7e9a01 7071 ;; Did we find something?
00d6fd04 7072 (unless found
7e5686f0
MA
7073 (tramp-error
7074 vec 'file-error "Couldn't find an inline transfer encoding"))
00d6fd04
MA
7075
7076 ;; Set connection properties.
7077 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7078 (tramp-set-connection-property vec "local-encoding" loc-enc)
7079 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7080 (tramp-set-connection-property vec "local-decoding" loc-dec)
7081 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7082 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7083 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7084 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
16674e4f
KG
7085
7086(defun tramp-call-local-coding-command (cmd input output)
7087 "Call the local encoding or decoding command.
7088If CMD contains \"%s\", provide input file INPUT there in command.
7089Otherwise, INPUT is passed via standard input.
7090INPUT can also be nil which means `/dev/null'.
7091OUTPUT can be a string (which specifies a filename), or t (which
7092means standard output and thus the current buffer), or nil (which
7093means discard it)."
a4aeb9a4
MA
7094 (tramp-local-call-process
7095 tramp-encoding-shell
7096 (when (and input (not (string-match "%s" cmd))) input)
7097 (if (eq output t) t nil)
7098 nil
7099 tramp-encoding-command-switch
7100 (concat
7101 (if (string-match "%s" cmd) (format cmd input) cmd)
7102 (if (stringp output) (concat "> " output) ""))))
00d6fd04
MA
7103
7104(defun tramp-compute-multi-hops (vec)
7105 "Expands VEC according to `tramp-default-proxies-alist'.
7106Gateway hops are already opened."
7107 (let ((target-alist `(,vec))
7108 (choices tramp-default-proxies-alist)
7109 item proxy)
7110
7111 ;; Look for proxy hosts to be passed.
7112 (while choices
7113 (setq item (pop choices)
70c11b0b 7114 proxy (eval (nth 2 item)))
00d6fd04
MA
7115 (when (and
7116 ;; host
70c11b0b 7117 (string-match (or (eval (nth 0 item)) "")
00d6fd04
MA
7118 (or (tramp-file-name-host (car target-alist)) ""))
7119 ;; user
70c11b0b 7120 (string-match (or (eval (nth 1 item)) "")
00d6fd04
MA
7121 (or (tramp-file-name-user (car target-alist)) "")))
7122 (if (null proxy)
7123 ;; No more hops needed.
7124 (setq choices nil)
7125 ;; Replace placeholders.
7126 (setq proxy
7127 (format-spec
7128 proxy
b533bc97
MA
7129 (format-spec-make
7130 ?u (or (tramp-file-name-user (car target-alist)) "")
7131 ?h (or (tramp-file-name-host (car target-alist)) ""))))
00d6fd04
MA
7132 (with-parsed-tramp-file-name proxy l
7133 ;; Add the hop.
7134 (add-to-list 'target-alist l)
7135 ;; Start next search.
7136 (setq choices tramp-default-proxies-alist)))))
7137
7138 ;; Handle gateways.
8a4438b6
MA
7139 (when (and (boundp 'tramp-gw-tunnel-method)
7140 (string-match (format
7141 "^\\(%s\\|%s\\)$"
7142 (symbol-value 'tramp-gw-tunnel-method)
7143 (symbol-value 'tramp-gw-socks-method))
7144 (tramp-file-name-method (car target-alist))))
00d6fd04
MA
7145 (let ((gw (pop target-alist))
7146 (hop (pop target-alist)))
7147 ;; Is the method prepared for gateways?
7148 (unless (tramp-get-method-parameter
7149 (tramp-file-name-method hop) 'tramp-default-port)
7150 (tramp-error
7151 vec 'file-error
7152 "Method `%s' is not supported for gateway access."
7153 (tramp-file-name-method hop)))
7154 ;; Add default port if needed.
7155 (unless
7156 (string-match
7157 tramp-host-with-port-regexp (tramp-file-name-host hop))
7158 (aset hop 2
7159 (concat
7160 (tramp-file-name-host hop) tramp-prefix-port-format
7161 (number-to-string
7162 (tramp-get-method-parameter
7163 (tramp-file-name-method hop) 'tramp-default-port)))))
7164 ;; Open the gateway connection.
7165 (add-to-list
7166 'target-alist
7167 (vector
7168 (tramp-file-name-method hop) (tramp-file-name-user hop)
9e6ab520 7169 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
00d6fd04
MA
7170 ;; For the password prompt, we need the correct values.
7171 ;; Therefore, we must remember the gateway vector. But we
7172 ;; cannot do it as connection property, because it shouldn't
7173 ;; be persistent. And we have no started process yet either.
7174 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7175
7176 ;; Foreign and out-of-band methods are not supported for multi-hops.
7177 (when (cdr target-alist)
7178 (setq choices target-alist)
7179 (while choices
7180 (setq item (pop choices))
7181 (when
7182 (or
7183 (not
7184 (tramp-get-method-parameter
7185 (tramp-file-name-method item) 'tramp-login-program))
7186 (tramp-get-method-parameter
7187 (tramp-file-name-method item) 'tramp-copy-program))
7188 (tramp-error
7189 vec 'file-error
7190 "Method `%s' is not supported for multi-hops."
7191 (tramp-file-name-method item)))))
7192
2991e49f
MA
7193 ;; In case the host name is not used for the remote shell
7194 ;; command, the user could be misguided by applying a random
7195 ;; hostname.
7196 (let* ((v (car target-alist))
7197 (method (tramp-file-name-method v))
7198 (host (tramp-file-name-host v)))
7199 (unless
7200 (or
7201 ;; There are multi-hops.
7202 (cdr target-alist)
7203 ;; The host name is used for the remote shell command.
7204 (member
7205 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7206 ;; The host is local. We cannot use `tramp-local-host-p'
7207 ;; here, because it opens a connection as well.
b96e6899 7208 (string-match tramp-local-host-regexp host))
2991e49f 7209 (tramp-error
42bc9b6d
MA
7210 v 'file-error
7211 "Host `%s' looks like a remote host, `%s' can only use the local host"
7212 host method)))
2991e49f 7213
00d6fd04
MA
7214 ;; Result.
7215 target-alist))
7216
7217(defun tramp-maybe-open-connection (vec)
7218 "Maybe open a connection VEC.
fb7933a3
KG
7219Does not do anything if a connection is already open, but re-opens the
7220connection if a previous connection has died for some reason."
d8ac123e
MA
7221 (catch 'uname-changed
7222 (let ((p (tramp-get-connection-process vec))
7223 (process-environment (copy-sequence process-environment)))
7224
7225 ;; If too much time has passed since last command was sent, look
7226 ;; whether process is still alive. If it isn't, kill it. When
7227 ;; using ssh, it can sometimes happen that the remote end has
7228 ;; hung up but the local ssh client doesn't recognize this until
7229 ;; it tries to send some data to the remote end. So that's why
7230 ;; we try to send a command from time to time, then look again
7231 ;; whether the process is really alive.
7232 (condition-case nil
7233 (when (and (> (tramp-time-diff
7234 (current-time)
7235 (tramp-get-connection-property
7236 p "last-cmd-time" '(0 0 0)))
7237 60)
7238 p (processp p) (memq (process-status p) '(run open)))
7239 (tramp-send-command vec "echo are you awake" t t)
7240 (unless (and (memq (process-status p) '(run open))
7241 (tramp-wait-for-output p 10))
7242 ;; The error will be catched locally.
7243 (tramp-error vec 'file-error "Awake did fail")))
7244 (file-error
7245 (tramp-flush-connection-property vec)
7246 (tramp-flush-connection-property p)
7247 (delete-process p)
7248 (setq p nil)))
7249
7250 ;; New connection must be opened.
7251 (unless (and p (processp p) (memq (process-status p) '(run open)))
7252
7253 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7254 ;; messages from the beginning.
7255 (tramp-get-buffer vec)
7256 (if (zerop (length (tramp-file-name-user vec)))
7257 (tramp-message
7258 vec 3 "Opening connection for %s using %s..."
7259 (tramp-file-name-host vec)
7260 (tramp-file-name-method vec))
00d6fd04 7261 (tramp-message
d8ac123e
MA
7262 vec 3 "Opening connection for %s@%s using %s..."
7263 (tramp-file-name-user vec)
00d6fd04 7264 (tramp-file-name-host vec)
d8ac123e
MA
7265 (tramp-file-name-method vec)))
7266
7267 ;; Start new process.
7268 (when (and p (processp p))
7269 (delete-process p))
7270 (setenv "TERM" tramp-terminal-type)
7271 (setenv "LC_ALL" "C")
7272 (setenv "PROMPT_COMMAND")
dab816a9 7273 (setenv "PS1" tramp-initial-end-of-output)
d8ac123e
MA
7274 (let* ((target-alist (tramp-compute-multi-hops vec))
7275 (process-connection-type tramp-process-connection-type)
7276 (process-adaptive-read-buffering nil)
7277 (coding-system-for-read nil)
7278 ;; This must be done in order to avoid our file name handler.
7279 (p (let ((default-directory
7280 (tramp-compat-temporary-file-directory)))
7281 (start-process
7282 (or (tramp-get-connection-property vec "process-name" nil)
7283 (tramp-buffer-name vec))
7284 (tramp-get-connection-buffer vec)
70c11b0b 7285 tramp-encoding-shell))))
00d6fd04 7286
d8ac123e
MA
7287 (tramp-message
7288 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7289
7290 ;; Check whether process is alive.
d8ac123e
MA
7291 (tramp-set-process-query-on-exit-flag p nil)
7292 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
7293 (tramp-barf-if-no-shell-prompt
7294 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7295
7296 ;; Now do all the connections as specified.
7297 (while target-alist
7298 (let* ((hop (car target-alist))
7299 (l-method (tramp-file-name-method hop))
7300 (l-user (tramp-file-name-user hop))
7301 (l-host (tramp-file-name-host hop))
7302 (l-port nil)
7303 (login-program
7304 (tramp-get-method-parameter l-method 'tramp-login-program))
7305 (login-args
7306 (tramp-get-method-parameter l-method 'tramp-login-args))
7307 (gw-args
7308 (tramp-get-method-parameter l-method 'tramp-gw-args))
7309 (gw (tramp-get-file-property hop "" "gateway" nil))
7310 (g-method (and gw (tramp-file-name-method gw)))
7311 (g-user (and gw (tramp-file-name-user gw)))
7312 (g-host (and gw (tramp-file-name-host gw)))
7313 (command login-program)
7314 ;; We don't create the temporary file. In fact, it
7315 ;; is just a prefix for the ControlPath option of
7316 ;; ssh; the real temporary file has another name, and
7317 ;; it is created and protected by ssh. It is also
7318 ;; removed by ssh, when the connection is closed.
7319 (tmpfile
7320 (tramp-set-connection-property
7321 p "temp-file"
7322 (make-temp-name
7323 (expand-file-name
7324 tramp-temp-name-prefix
7325 (tramp-compat-temporary-file-directory)))))
7326 spec)
7327
7328 ;; Add gateway arguments if necessary.
7329 (when (and gw gw-args)
7330 (setq login-args (append login-args gw-args)))
7331
7332 ;; Check for port number. Until now, there's no need
7333 ;; for handling like method, user, host.
7334 (when (string-match tramp-host-with-port-regexp l-host)
7335 (setq l-port (match-string 2 l-host)
7336 l-host (match-string 1 l-host)))
7337
7338 ;; Set variables for computing the prompt for reading
2296b54d 7339 ;; password. They can also be derived from a gateway.
d8ac123e
MA
7340 (setq tramp-current-method (or g-method l-method)
7341 tramp-current-user (or g-user l-user)
7342 tramp-current-host (or g-host l-host))
7343
7344 ;; Replace login-args place holders.
7345 (setq
7346 l-host (or l-host "")
7347 l-user (or l-user "")
7348 l-port (or l-port "")
b533bc97 7349 spec (format-spec-make ?h l-host ?u l-user ?p l-port ?t tmpfile)
d8ac123e
MA
7350 command
7351 (concat
e2a421af
MA
7352 ;; We do not want to see the trailing local prompt in
7353 ;; `start-file-process'.
7354 (unless (memq system-type '(windows-nt)) "exec ")
d8ac123e
MA
7355 command " "
7356 (mapconcat
aa485f7c
MA
7357 (lambda (x)
7358 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7359 (unless (member "" x) (mapconcat 'identity x " ")))
d8ac123e 7360 login-args " ")
d8ac123e
MA
7361 ;; Local shell could be a Windows COMSPEC. It doesn't
7362 ;; know the ";" syntax, but we must exit always for
70c11b0b 7363 ;; `start-file-process'. "exec" does not work either.
e2a421af 7364 (if (memq system-type '(windows-nt)) " && exit || exit")))
d8ac123e
MA
7365
7366 ;; Send the command.
7367 (tramp-message vec 3 "Sending command `%s'" command)
7368 (tramp-send-command vec command t t)
7369 (tramp-process-actions p vec tramp-actions-before-shell 60)
7370 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
7371 ;; Next hop.
7372 (setq target-alist (cdr target-alist)))
7373
7374 ;; Make initial shell settings.
7375 (tramp-open-connection-setup-interactive-shell p vec))))))
00d6fd04
MA
7376
7377(defun tramp-send-command (vec command &optional neveropen nooutput)
7378 "Send the COMMAND to connection VEC.
7379Erases temporary buffer before sending the command. If optional
7380arg NEVEROPEN is non-nil, never try to open the connection. This
7381is meant to be used from `tramp-maybe-open-connection' only. The
7382function waits for output unless NOOUTPUT is set."
7383 (unless neveropen (tramp-maybe-open-connection vec))
7384 (let ((p (tramp-get-connection-process vec)))
8950769a 7385 (when (tramp-get-connection-property p "remote-echo" nil)
00d6fd04
MA
7386 ;; We mark the command string that it can be erased in the output buffer.
7387 (tramp-set-connection-property p "check-remote-echo" t)
7388 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7389 (tramp-message vec 6 "%s" command)
7390 (tramp-send-string vec command)
7391 (unless nooutput (tramp-wait-for-output p))))
7392
00d6fd04 7393(defun tramp-wait-for-output (proc &optional timeout)
7e5686f0
MA
7394 "Wait for output from remote command."
7395 (unless (buffer-live-p (process-buffer proc))
7396 (delete-process proc)
7397 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
00d6fd04 7398 (with-current-buffer (process-buffer proc)
dab816a9 7399 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
bede3e9f 7400 ;; be leading escape sequences, which must be ignored.
dab816a9 7401 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
bede3e9f
MA
7402 ;; Sometimes, the commands do not return a newline but a
7403 ;; null byte before the shell prompt, for example "git
7404 ;; ls-files -c -z ...".
7405 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7406 (found (tramp-wait-for-regexp proc timeout regexp1)))
00d6fd04
MA
7407 (if found
7408 (let (buffer-read-only)
7e5686f0
MA
7409 ;; A simple-minded busybox has sent " ^H" sequences.
7410 ;; Delete them.
7411 (goto-char (point-min))
7412 (when (re-search-forward
7413 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7414 (forward-line 1)
7415 (delete-region (point-min) (point)))
7416 ;; Delete the prompt.
00d6fd04 7417 (goto-char (point-max))
0664ff72 7418 (re-search-backward regexp nil t)
00d6fd04
MA
7419 (delete-region (point) (point-max)))
7420 (if timeout
7421 (tramp-error
7422 proc 'file-error
7423 "[[Remote prompt `%s' not found in %d secs]]"
7424 tramp-end-of-output timeout)
7425 (tramp-error
7426 proc 'file-error
7427 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7428 ;; Return value is whether end-of-output sentinel was found.
7429 found)))
fb7933a3 7430
b593f105
MA
7431(defun tramp-send-command-and-check
7432 (vec command &optional subshell dont-suppress-err)
fb7933a3 7433 "Run COMMAND and check its exit status.
fb7933a3
KG
7434Sends `echo $?' along with the COMMAND for checking the exit status. If
7435COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7436
b593f105
MA
7437If the optional argument SUBSHELL is non-nil, the command is
7438executed in a subshell, ie surrounded by parentheses. If
7439DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
00d6fd04
MA
7440 (tramp-send-command
7441 vec
7442 (concat (if subshell "( " "")
7443 command
b593f105 7444 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
00d6fd04 7445 "echo tramp_exit_status $?"
b593f105 7446 (if subshell " )" "")))
00d6fd04
MA
7447 (with-current-buffer (tramp-get-connection-buffer vec)
7448 (goto-char (point-max))
7449 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7450 (tramp-error
7451 vec 'file-error "Couldn't find exit status of `%s'" command))
7452 (skip-chars-forward "^ ")
7453 (prog1
7454 (read (current-buffer))
7455 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7456
7457(defun tramp-barf-unless-okay (vec command fmt &rest args)
fb7933a3
KG
7458 "Run COMMAND, check exit status, throw error if exit status not okay.
7459Similar to `tramp-send-command-and-check' but accepts two more arguments
7460FMT and ARGS which are passed to `error'."
00d6fd04
MA
7461 (unless (zerop (tramp-send-command-and-check vec command))
7462 (apply 'tramp-error vec 'file-error fmt args)))
7463
7464(defun tramp-send-command-and-read (vec command)
7465 "Run COMMAND and return the output, which must be a Lisp expression.
7466In case there is no valid Lisp expression, it raises an error"
7467 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7468 (with-current-buffer (tramp-get-connection-buffer vec)
7469 ;; Read the expression.
7470 (goto-char (point-min))
7471 (condition-case nil
7472 (prog1 (read (current-buffer))
7473 ;; Error handling.
9e6ab520 7474 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
9ce8462a 7475 (error nil)))
00d6fd04
MA
7476 (error (tramp-error
7477 vec 'file-error
7478 "`%s' does not return a valid Lisp expression: `%s'"
7479 command (buffer-string))))))
fb7933a3 7480
7432277c
KG
7481;; It seems that Tru64 Unix does not like it if long strings are sent
7482;; to it in one go. (This happens when sending the Perl
7483;; `file-attributes' implementation, for instance.) Therefore, we
27e813fe 7484;; have this function which sends the string in chunks.
00d6fd04
MA
7485(defun tramp-send-string (vec string)
7486 "Send the STRING via connection VEC.
7432277c
KG
7487
7488The STRING is expected to use Unix line-endings, but the lines sent to
7489the remote host use line-endings as defined in the variable
00d6fd04
MA
7490`tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7491 (let* ((p (tramp-get-connection-process vec))
7492 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7493 (unless p
7494 (tramp-error
7495 vec 'file-error "Can't send string to remote host -- not logged in"))
7496 (tramp-set-connection-property p "last-cmd-time" (current-time))
7497 (tramp-message vec 10 "%s" string)
7498 (with-current-buffer (tramp-get-connection-buffer vec)
7499 ;; Clean up the buffer. We cannot call `erase-buffer' because
7500 ;; narrowing might be in effect.
7501 (let (buffer-read-only) (delete-region (point-min) (point-max)))
27e813fe 7502 ;; Replace "\n" by `tramp-rsh-end-of-line'.
00d6fd04
MA
7503 (setq string
7504 (mapconcat 'identity
70c11b0b 7505 (tramp-compat-split-string string "\n")
00d6fd04
MA
7506 tramp-rsh-end-of-line))
7507 (unless (or (string= string "")
7508 (string-equal (substring string -1) tramp-rsh-end-of-line))
7509 (setq string (concat string tramp-rsh-end-of-line)))
27e813fe 7510 ;; Send the string.
00d6fd04
MA
7511 (if (and chunksize (not (zerop chunksize)))
7512 (let ((pos 0)
7513 (end (length string)))
7514 (while (< pos end)
7515 (tramp-message
7516 vec 10 "Sending chunk from %s to %s"
7517 pos (min (+ pos chunksize) end))
7518 (process-send-string
7519 p (substring string pos (min (+ pos chunksize) end)))
7520 (setq pos (+ pos chunksize))))
7521 (process-send-string p string)))))
fb7933a3
KG
7522
7523(defun tramp-mode-string-to-int (mode-string)
7524 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
f3c071dd
MA
7525 (let* (case-fold-search
7526 (mode-chars (string-to-vector mode-string))
fb7933a3
KG
7527 (owner-read (aref mode-chars 1))
7528 (owner-write (aref mode-chars 2))
7529 (owner-execute-or-setid (aref mode-chars 3))
7530 (group-read (aref mode-chars 4))
7531 (group-write (aref mode-chars 5))
7532 (group-execute-or-setid (aref mode-chars 6))
7533 (other-read (aref mode-chars 7))
7534 (other-write (aref mode-chars 8))
7535 (other-execute-or-sticky (aref mode-chars 9)))
7536 (save-match-data
7537 (logior
f3c071dd
MA
7538 (cond
7539 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7540 ((char-equal owner-read ?-) 0)
7541 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7542 (cond
7543 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7544 ((char-equal owner-write ?-) 0)
7545 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7546 (cond
7547 ((char-equal owner-execute-or-setid ?x)
7548 (tramp-octal-to-decimal "00100"))
7549 ((char-equal owner-execute-or-setid ?S)
7550 (tramp-octal-to-decimal "04000"))
7551 ((char-equal owner-execute-or-setid ?s)
7552 (tramp-octal-to-decimal "04100"))
7553 ((char-equal owner-execute-or-setid ?-) 0)
7554 (t (error "Fourth char `%c' must be one of `xsS-'"
7555 owner-execute-or-setid)))
7556 (cond
7557 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7558 ((char-equal group-read ?-) 0)
7559 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7560 (cond
7561 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7562 ((char-equal group-write ?-) 0)
7563 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7564 (cond
7565 ((char-equal group-execute-or-setid ?x)
7566 (tramp-octal-to-decimal "00010"))
7567 ((char-equal group-execute-or-setid ?S)
7568 (tramp-octal-to-decimal "02000"))
7569 ((char-equal group-execute-or-setid ?s)
7570 (tramp-octal-to-decimal "02010"))
7571 ((char-equal group-execute-or-setid ?-) 0)
7572 (t (error "Seventh char `%c' must be one of `xsS-'"
7573 group-execute-or-setid)))
7574 (cond
7575 ((char-equal other-read ?r)
7576 (tramp-octal-to-decimal "00004"))
7577 ((char-equal other-read ?-) 0)
7578 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7579 (cond
7580 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7581 ((char-equal other-write ?-) 0)
fb7933a3 7582 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
f3c071dd
MA
7583 (cond
7584 ((char-equal other-execute-or-sticky ?x)
7585 (tramp-octal-to-decimal "00001"))
7586 ((char-equal other-execute-or-sticky ?T)
7587 (tramp-octal-to-decimal "01000"))
7588 ((char-equal other-execute-or-sticky ?t)
7589 (tramp-octal-to-decimal "01001"))
7590 ((char-equal other-execute-or-sticky ?-) 0)
7591 (t (error "Tenth char `%c' must be one of `xtT-'"
7592 other-execute-or-sticky)))))))
fb7933a3 7593
00d6fd04
MA
7594(defun tramp-convert-file-attributes (vec attr)
7595 "Convert file-attributes ATTR generated by perl script, stat or ls.
c82c5727
LH
7596Convert file mode bits to string and set virtual device number.
7597Return ATTR."
680db9ac
MA
7598 (when attr
7599 ;; Convert last access time.
7600 (unless (listp (nth 4 attr))
7601 (setcar (nthcdr 4 attr)
7602 (list (floor (nth 4 attr) 65536)
7603 (floor (mod (nth 4 attr) 65536)))))
7604 ;; Convert last modification time.
7605 (unless (listp (nth 5 attr))
7606 (setcar (nthcdr 5 attr)
7607 (list (floor (nth 5 attr) 65536)
7608 (floor (mod (nth 5 attr) 65536)))))
7609 ;; Convert last status change time.
7610 (unless (listp (nth 6 attr))
7611 (setcar (nthcdr 6 attr)
7612 (list (floor (nth 6 attr) 65536)
7613 (floor (mod (nth 6 attr) 65536)))))
7614 ;; Convert file size.
7615 (when (< (nth 7 attr) 0)
7616 (setcar (nthcdr 7 attr) -1))
7617 (when (and (floatp (nth 7 attr))
7618 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7619 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7620 ;; Convert file mode bits to string.
7621 (unless (stringp (nth 8 attr))
7622 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7623 (when (stringp (car attr))
7624 (aset (nth 8 attr) 0 ?l)))
7625 ;; Convert directory indication bit.
7626 (when (string-match "^d" (nth 8 attr))
7627 (setcar attr t))
7628 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7629 (when (consp (car attr))
7630 (if (and (stringp (caar attr))
7631 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7632 (setcar attr (match-string 1 (caar attr)))
7633 (setcar attr nil)))
7634 ;; Set file's gid change bit.
7635 (setcar (nthcdr 9 attr)
7636 (if (numberp (nth 3 attr))
7637 (not (= (nth 3 attr)
7638 (tramp-get-remote-gid vec 'integer)))
7639 (not (string-equal
7640 (nth 3 attr)
7641 (tramp-get-remote-gid vec 'string)))))
7642 ;; Convert inode.
7643 (unless (listp (nth 10 attr))
7644 (setcar (nthcdr 10 attr)
7645 (condition-case nil
7646 (cons (floor (nth 10 attr) 65536)
7647 (floor (mod (nth 10 attr) 65536)))
7648 ;; Inodes can be incredible huge. We must hide this.
7649 (error (tramp-get-inode vec)))))
7650 ;; Set virtual device number.
7651 (setcar (nthcdr 11 attr)
7652 (tramp-get-device vec))
7653 attr))
c82c5727 7654
293c24f9
MA
7655(defun tramp-check-cached-permissions (vec access)
7656 "Check `file-attributes' caches for VEC.
7657Return t if according to the cache access type ACCESS is known to
7658be granted."
7659 (let ((result nil)
7660 (offset (cond
7661 ((eq ?r access) 1)
7662 ((eq ?w access) 2)
7663 ((eq ?x access) 3))))
7664 (dolist (suffix '("string" "integer") result)
7665 (setq
7666 result
7667 (or
7668 result
7669 (let ((file-attr
7670 (tramp-get-file-property
7671 vec (tramp-file-name-localname vec)
7672 (concat "file-attributes-" suffix) nil))
7673 (remote-uid
7674 (tramp-get-connection-property
7675 vec (concat "uid-" suffix) nil))
7676 (remote-gid
7677 (tramp-get-connection-property
7678 vec (concat "gid-" suffix) nil)))
7679 (and
7680 file-attr
7681 (or
7682 ;; Not a symlink
7683 (eq t (car file-attr))
7684 (null (car file-attr)))
7685 (or
7686 ;; World accessible.
7687 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7688 ;; User accessible and owned by user.
7689 (and
7690 (eq access (aref (nth 8 file-attr) offset))
7691 (equal remote-uid (nth 2 file-attr)))
7692 ;; Group accessible and owned by user's
7693 ;; principal group.
7694 (and
7695 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7696 (equal remote-gid (nth 3 file-attr)))))))))))
7697
ce3f516f 7698(defun tramp-get-inode (vec)
00d6fd04
MA
7699 "Returns the virtual inode number.
7700If it doesn't exist, generate a new one."
ce3f516f
MA
7701 (let ((string (tramp-make-tramp-file-name
7702 (tramp-file-name-method vec)
7703 (tramp-file-name-user vec)
7704 (tramp-file-name-host vec)
7705 "")))
00d6fd04
MA
7706 (unless (assoc string tramp-inodes)
7707 (add-to-list 'tramp-inodes
7708 (list string (length tramp-inodes))))
7709 (nth 1 (assoc string tramp-inodes))))
7710
7711(defun tramp-get-device (vec)
c82c5727
LH
7712 "Returns the virtual device number.
7713If it doesn't exist, generate a new one."
00d6fd04
MA
7714 (let ((string (tramp-make-tramp-file-name
7715 (tramp-file-name-method vec)
7716 (tramp-file-name-user vec)
7717 (tramp-file-name-host vec)
7718 "")))
c82c5727
LH
7719 (unless (assoc string tramp-devices)
7720 (add-to-list 'tramp-devices
7721 (list string (length tramp-devices))))
b946a456 7722 (cons -1 (nth 1 (assoc string tramp-devices)))))
fb7933a3
KG
7723
7724(defun tramp-file-mode-from-int (mode)
7725 "Turn an integer representing a file mode into an ls(1)-like string."
7726 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7727 (user (logand (lsh mode -6) 7))
7728 (group (logand (lsh mode -3) 7))
7729 (other (logand (lsh mode -0) 7))
7730 (suid (> (logand (lsh mode -9) 4) 0))
7731 (sgid (> (logand (lsh mode -9) 2) 0))
7732 (sticky (> (logand (lsh mode -9) 1) 0)))
7733 (setq user (tramp-file-mode-permissions user suid "s"))
7734 (setq group (tramp-file-mode-permissions group sgid "s"))
7735 (setq other (tramp-file-mode-permissions other sticky "t"))
7736 (concat type user group other)))
7737
fb7933a3
KG
7738(defun tramp-file-mode-permissions (perm suid suid-text)
7739 "Convert a permission bitset into a string.
7740This is used internally by `tramp-file-mode-from-int'."
7741 (let ((r (> (logand perm 4) 0))
7742 (w (> (logand perm 2) 0))
7743 (x (> (logand perm 1) 0)))
7744 (concat (or (and r "r") "-")
7745 (or (and w "w") "-")
7746 (or (and suid x suid-text) ; suid, execute
7747 (and suid (upcase suid-text)) ; suid, !execute
7748 (and x "x") "-")))) ; !suid
7749
fb7933a3
KG
7750(defun tramp-decimal-to-octal (i)
7751 "Return a string consisting of the octal digits of I.
7752Not actually used. Use `(format \"%o\" i)' instead?"
7753 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7754 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7755 ((zerop i) "0")
7756 (t (concat (tramp-decimal-to-octal (/ i 8))
7757 (number-to-string (% i 8))))))
7758
fb7933a3
KG
7759;; Kudos to Gerd Moellmann for this suggestion.
7760(defun tramp-octal-to-decimal (ostr)
7761 "Given a string of octal digits, return a decimal number."
7762 (let ((x (or ostr "")))
7763 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7764 (unless (string-match "\\`[0-7]*\\'" x)
7765 (error "Non-octal junk in string `%s'" x))
7766 (string-to-number ostr 8)))
7767
7768(defun tramp-shell-case-fold (string)
7769 "Converts STRING to shell glob pattern which ignores case."
7770 (mapconcat
7771 (lambda (c)
7772 (if (equal (downcase c) (upcase c))
7773 (vector c)
7774 (format "[%c%c]" (downcase c) (upcase c))))
7775 string
7776 ""))
7777
7778
bf247b6e 7779;; ------------------------------------------------------------
a4aeb9a4 7780;; -- Tramp file names --
bf247b6e 7781;; ------------------------------------------------------------
fb7933a3
KG
7782;; Conversion functions between external representation and
7783;; internal data structure. Convenience functions for internal
7784;; data structure.
7785
00d6fd04
MA
7786(defun tramp-file-name-p (vec)
7787 "Check whether VEC is a Tramp object."
7788 (and (vectorp vec) (= 4 (length vec))))
7789
7790(defun tramp-file-name-method (vec)
7791 "Return method component of VEC."
7792 (and (tramp-file-name-p vec) (aref vec 0)))
7793
7794(defun tramp-file-name-user (vec)
7795 "Return user component of VEC."
7796 (and (tramp-file-name-p vec) (aref vec 1)))
7797
7798(defun tramp-file-name-host (vec)
7799 "Return host component of VEC."
7800 (and (tramp-file-name-p vec) (aref vec 2)))
7801
7802(defun tramp-file-name-localname (vec)
7803 "Return localname component of VEC."
7804 (and (tramp-file-name-p vec) (aref vec 3)))
7805
dea31ca6 7806;; The user part of a Tramp file name vector can be of kind
b96e6899 7807;; "user%domain". Sometimes, we must extract these parts.
dea31ca6
MA
7808(defun tramp-file-name-real-user (vec)
7809 "Return the user name of VEC without domain."
a17632c1
MA
7810 (save-match-data
7811 (let ((user (tramp-file-name-user vec)))
7812 (if (and (stringp user)
7813 (string-match tramp-user-with-domain-regexp user))
7814 (match-string 1 user)
7815 user))))
dea31ca6
MA
7816
7817(defun tramp-file-name-domain (vec)
7818 "Return the domain name of VEC."
a17632c1
MA
7819 (save-match-data
7820 (let ((user (tramp-file-name-user vec)))
7821 (and (stringp user)
7822 (string-match tramp-user-with-domain-regexp user)
7823 (match-string 2 user)))))
dea31ca6 7824
00d6fd04
MA
7825;; The host part of a Tramp file name vector can be of kind
7826;; "host#port". Sometimes, we must extract these parts.
8a4438b6 7827(defun tramp-file-name-real-host (vec)
00d6fd04 7828 "Return the host name of VEC without port."
a17632c1
MA
7829 (save-match-data
7830 (let ((host (tramp-file-name-host vec)))
7831 (if (and (stringp host)
7832 (string-match tramp-host-with-port-regexp host))
7833 (match-string 1 host)
7834 host))))
00d6fd04 7835
8a4438b6 7836(defun tramp-file-name-port (vec)
00d6fd04 7837 "Return the port number of VEC."
a17632c1
MA
7838 (save-match-data
7839 (let ((host (tramp-file-name-host vec)))
7840 (and (stringp host)
7841 (string-match tramp-host-with-port-regexp host)
7842 (string-to-number (match-string 2 host))))))
fb7933a3
KG
7843
7844(defun tramp-tramp-file-p (name)
a09dc9bf 7845 "Return t if NAME is a string with Tramp file name syntax."
fb7933a3 7846 (save-match-data
a09dc9bf 7847 (and (stringp name) (string-match tramp-file-name-regexp name))))
bf247b6e 7848
8a4438b6 7849(defun tramp-find-method (method user host)
00d6fd04
MA
7850 "Return the right method string to use.
7851This is METHOD, if non-nil. Otherwise, do a lookup in
7852`tramp-default-method-alist'."
7853 (or method
7854 (let ((choices tramp-default-method-alist)
7855 lmethod item)
7856 (while choices
7857 (setq item (pop choices))
7858 (when (and (string-match (or (nth 0 item) "") (or host ""))
7859 (string-match (or (nth 1 item) "") (or user "")))
7860 (setq lmethod (nth 2 item))
7861 (setq choices nil)))
7862 lmethod)
7863 tramp-default-method))
7864
8a4438b6 7865(defun tramp-find-user (method user host)
00d6fd04
MA
7866 "Return the right user string to use.
7867This is USER, if non-nil. Otherwise, do a lookup in
7868`tramp-default-user-alist'."
7869 (or user
7870 (let ((choices tramp-default-user-alist)
7871 luser item)
7872 (while choices
7873 (setq item (pop choices))
7874 (when (and (string-match (or (nth 0 item) "") (or method ""))
7875 (string-match (or (nth 1 item) "") (or host "")))
7876 (setq luser (nth 2 item))
7877 (setq choices nil)))
7878 luser)
7879 tramp-default-user))
7880
8a4438b6 7881(defun tramp-find-host (method user host)
00d6fd04
MA
7882 "Return the right host string to use.
7883This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7884 (or (and (> (length host) 0) host)
7885 tramp-default-host))
7886
9ce8462a 7887(defun tramp-dissect-file-name (name &optional nodefault)
00d6fd04 7888 "Return a `tramp-file-name' structure.
9ce8462a
MA
7889The structure consists of remote method, remote user, remote host
7890and localname (file name on remote host). If NODEFAULT is
7891non-nil, the file name parts are not expanded to their default
7892values."
4007ba5b 7893 (save-match-data
00d6fd04 7894 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
a4aeb9a4 7895 (unless match (error "Not a Tramp file name: %s" name))
00d6fd04
MA
7896 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7897 (user (match-string (nth 2 tramp-file-name-structure) name))
7898 (host (match-string (nth 3 tramp-file-name-structure) name))
7899 (localname (match-string (nth 4 tramp-file-name-structure) name)))
5d449a36
MA
7900 (when (member method '("multi" "multiu"))
7901 (error
7902 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7903 method))
b96e6899
MA
7904 (when host
7905 (when (string-match tramp-prefix-ipv6-regexp host)
7906 (setq host (replace-match "" nil t host)))
7907 (when (string-match tramp-postfix-ipv6-regexp host)
7908 (setq host (replace-match "" nil t host))))
9ce8462a
MA
7909 (if nodefault
7910 (vector method user host localname)
7911 (vector
7912 (tramp-find-method method user host)
7913 (tramp-find-user method user host)
7914 (tramp-find-host method user host)
7915 localname))))))
00d6fd04
MA
7916
7917(defun tramp-equal-remote (file1 file2)
7918 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7919The check depends on method, user and host name of the files. If
7920one of the components is missing, the default values are used.
7921The local file name parts of FILE1 and FILE2 are not taken into
7922account.
fb7933a3 7923
00d6fd04
MA
7924Example:
7925
7926 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7927
7928would yield `t'. On the other hand, the following check results in nil:
7929
7930 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
9e6ab520
MA
7931 (and (stringp (file-remote-p file1))
7932 (stringp (file-remote-p file2))
94be87e8 7933 (string-equal (file-remote-p file1) (file-remote-p file2))))
00d6fd04
MA
7934
7935(defun tramp-make-tramp-file-name (method user host localname)
7936 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7937 (concat tramp-prefix-format
7938 (when (not (zerop (length method)))
7939 (concat method tramp-postfix-method-format))
7940 (when (not (zerop (length user)))
7941 (concat user tramp-postfix-user-format))
b96e6899
MA
7942 (when host
7943 (if (string-match tramp-ipv6-regexp host)
7944 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7945 host))
7946 tramp-postfix-host-format
00d6fd04
MA
7947 (when localname localname)))
7948
7949(defun tramp-completion-make-tramp-file-name (method user host localname)
7950 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7951It must not be a complete Tramp file name, but as long as there are
7952necessary only. This function will be used in file name completion."
7953 (concat tramp-prefix-format
7954 (when (not (zerop (length method)))
7955 (concat method tramp-postfix-method-format))
7956 (when (not (zerop (length user)))
7957 (concat user tramp-postfix-user-format))
7958 (when (not (zerop (length host)))
b96e6899
MA
7959 (concat
7960 (if (string-match tramp-ipv6-regexp host)
7961 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7962 host)
7963 tramp-postfix-host-format))
00d6fd04
MA
7964 (when localname localname)))
7965
7966(defun tramp-make-copy-program-file-name (vec)
7967 "Create a file name suitable to be passed to `rcp' and workalikes."
7968 (let ((user (tramp-file-name-user vec))
0f205eee 7969 (host (tramp-file-name-real-host vec))
00d6fd04
MA
7970 (localname (tramp-shell-quote-argument
7971 (tramp-file-name-localname vec))))
7972 (if (not (zerop (length user)))
7973 (format "%s@%s:%s" user host localname)
7974 (format "%s:%s" host localname))))
7975
7f49fe46 7976(defun tramp-method-out-of-band-p (vec size)
38c65fca 7977 "Return t if this is an out-of-band method, nil otherwise."
7f49fe46
MA
7978 (and
7979 ;; It shall be an out-of-band method.
7980 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7981 ;; Either the file size is large enough, or (in rare cases) there
7982 ;; does not exist a remote encoding.
7983 (or (> size tramp-copy-size-limit)
7984 (null (tramp-get-remote-coding vec "remote-encoding")))))
fb7933a3 7985
0f205eee
MA
7986(defun tramp-local-host-p (vec)
7987 "Return t if this points to the local host, nil otherwise."
c992abdb
MA
7988 ;; We cannot use `tramp-file-name-real-host'. A port is an
7989 ;; indication for an ssh tunnel or alike.
7990 (let ((host (tramp-file-name-host vec)))
0f205eee
MA
7991 (and
7992 (stringp host)
b96e6899 7993 (string-match tramp-local-host-regexp host)
46bcd78c
MA
7994 ;; The method shall be applied to one of the shell file name
7995 ;; handler. `tramp-local-host-p' is also called for "smb" and
7996 ;; alike, where it must fail.
7997 (tramp-get-method-parameter
7998 (tramp-file-name-method vec) 'tramp-login-program)
a0a5183a
MA
7999 ;; The local temp directory must be writable for the other user.
8000 (file-writable-p
8001 (tramp-make-tramp-file-name
8002 (tramp-file-name-method vec)
8003 (tramp-file-name-user vec)
8004 host
93c3eb7c
MA
8005 (tramp-compat-temporary-file-directory)))
8006 ;; On some systems, chown runs only for root.
8007 (or (zerop (user-uid))
8008 (zerop (tramp-get-remote-uid vec 'integer))))))
0f205eee 8009
fb7933a3
KG
8010;; Variables local to connection.
8011
f84638eb 8012(defun tramp-get-remote-path (vec)
70c11b0b
MA
8013 (with-connection-property
8014 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8015 ;; cache the result for the session only. Otherwise, the result
8016 ;; is cached persistently.
8017 (if (memq 'tramp-own-remote-path tramp-remote-path)
8018 (tramp-get-connection-process vec)
8019 vec)
8020 "remote-path"
b533bc97 8021 (let* ((remote-path (copy-tree tramp-remote-path))
70c11b0b
MA
8022 (elt1 (memq 'tramp-default-remote-path remote-path))
8023 (elt2 (memq 'tramp-own-remote-path remote-path))
f84638eb 8024 (default-remote-path
70c11b0b 8025 (when elt1
f84638eb 8026 (condition-case nil
70c11b0b
MA
8027 (tramp-send-command-and-read
8028 vec "echo \\\"`getconf PATH`\\\"")
f84638eb
MA
8029 ;; Default if "getconf" is not available.
8030 (error
8031 (tramp-message
8032 vec 3
8033 "`getconf PATH' not successful, using default value \"%s\"."
8034 "/bin:/usr/bin")
70c11b0b
MA
8035 "/bin:/usr/bin"))))
8036 (own-remote-path
8037 (when elt2
8038 (condition-case nil
8039 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8040 ;; Default if "getconf" is not available.
8041 (error
8042 (tramp-message
8043 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8044 nil)))))
8045
8046 ;; Replace place holder `tramp-default-remote-path'.
8047 (when elt1
8048 (setcdr elt1
f84638eb 8049 (append
70c11b0b
MA
8050 (tramp-compat-split-string default-remote-path ":")
8051 (cdr elt1)))
f84638eb
MA
8052 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8053
70c11b0b
MA
8054 ;; Replace place holder `tramp-own-remote-path'.
8055 (when elt2
8056 (setcdr elt2
8057 (append
8058 (tramp-compat-split-string own-remote-path ":")
8059 (cdr elt2)))
8060 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8061
8062 ;; Remove double entries.
8063 (setq elt1 remote-path)
8064 (while (consp elt1)
8065 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8066 (setcar elt2 nil))
8067 (setq elt1 (cdr elt1)))
8068
f84638eb
MA
8069 ;; Remove non-existing directories.
8070 (delq
8071 nil
8072 (mapcar
8073 (lambda (x)
8074 (and
70c11b0b
MA
8075 (stringp x)
8076 (file-directory-p
8077 (tramp-make-tramp-file-name
8078 (tramp-file-name-method vec)
8079 (tramp-file-name-user vec)
8080 (tramp-file-name-host vec)
8081 x))
f84638eb
MA
8082 x))
8083 remote-path)))))
8084
a4aeb9a4
MA
8085(defun tramp-get-remote-tmpdir (vec)
8086 (with-connection-property vec "tmp-directory"
8087 (let ((dir (tramp-shell-quote-argument "/tmp")))
8088 (if (and (zerop
8089 (tramp-send-command-and-check
8090 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8091 (zerop
8092 (tramp-send-command-and-check
8093 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8094 dir
8095 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8096
00d6fd04
MA
8097(defun tramp-get-ls-command (vec)
8098 (with-connection-property vec "ls"
946a5aeb
MA
8099 (tramp-message vec 5 "Finding a suitable `ls' command")
8100 (or
8101 (catch 'ls-found
8102 (dolist (cmd '("ls" "gnuls" "gls"))
8103 (let ((dl (tramp-get-remote-path vec))
8104 result)
8105 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
7e5686f0
MA
8106 ;; Check parameters. On busybox, "ls" output coloring is
8107 ;; enabled by default sometimes. So we try to disable it
8108 ;; when possible. $LS_COLORING is not supported there.
946a5aeb
MA
8109 (when (zerop (tramp-send-command-and-check
8110 vec (format "%s -lnd /" result)))
7e5686f0
MA
8111 (when (zerop (tramp-send-command-and-check
8112 vec (format "%s --color=never /" result)))
8113 (setq result (concat result " --color=never")))
946a5aeb
MA
8114 (throw 'ls-found result))
8115 (setq dl (cdr dl))))))
8116 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
00d6fd04 8117
8e754ea2
MA
8118(defun tramp-get-ls-command-with-dired (vec)
8119 (save-match-data
8120 (with-connection-property vec "ls-dired"
8121 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8122 (zerop (tramp-send-command-and-check
7f49fe46 8123 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8e754ea2 8124
00d6fd04
MA
8125(defun tramp-get-test-command (vec)
8126 (with-connection-property vec "test"
946a5aeb
MA
8127 (tramp-message vec 5 "Finding a suitable `test' command")
8128 (if (zerop (tramp-send-command-and-check vec "test 0"))
8129 "test"
8130 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
00d6fd04
MA
8131
8132(defun tramp-get-test-nt-command (vec)
8133 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8134 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8135 ;; for otherwise the shell crashes.
8136 (with-connection-property vec "test-nt"
8137 (or
8138 (progn
8139 (tramp-send-command
8140 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8141 (with-current-buffer (tramp-get-buffer vec)
8142 (goto-char (point-min))
a0a5183a 8143 (when (looking-at (regexp-quote tramp-end-of-output))
00d6fd04
MA
8144 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8145 (progn
8146 (tramp-send-command
8147 vec
8148 (format
8149 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8150 (tramp-get-test-command vec)))
8151 "tramp_test_nt %s %s"))))
8152
8153(defun tramp-get-file-exists-command (vec)
8154 (with-connection-property vec "file-exists"
946a5aeb
MA
8155 (tramp-message vec 5 "Finding command to check if file exists")
8156 (tramp-find-file-exists-command vec)))
00d6fd04
MA
8157
8158(defun tramp-get-remote-ln (vec)
8159 (with-connection-property vec "ln"
946a5aeb
MA
8160 (tramp-message vec 5 "Finding a suitable `ln' command")
8161 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
00d6fd04
MA
8162
8163(defun tramp-get-remote-perl (vec)
8164 (with-connection-property vec "perl"
946a5aeb 8165 (tramp-message vec 5 "Finding a suitable `perl' command")
293c24f9
MA
8166 (let ((result
8167 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8168 (tramp-find-executable
8169 vec "perl" (tramp-get-remote-path vec)))))
8170 ;; We must check also for some Perl modules.
8171 (when result
8172 (with-connection-property vec "perl-file-spec"
8173 (zerop
8174 (tramp-send-command-and-check
8175 vec (format "%s -e 'use File::Spec;'" result))))
8176 (with-connection-property vec "perl-cwd-realpath"
8177 (zerop
8178 (tramp-send-command-and-check
8179 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8180 result)))
00d6fd04
MA
8181
8182(defun tramp-get-remote-stat (vec)
8183 (with-connection-property vec "stat"
946a5aeb
MA
8184 (tramp-message vec 5 "Finding a suitable `stat' command")
8185 (let ((result (tramp-find-executable
8186 vec "stat" (tramp-get-remote-path vec)))
8187 tmp)
8188 ;; Check whether stat(1) returns usable syntax. %s does not
8189 ;; work on older AIX systems.
8190 (when result
8191 (setq tmp
8192 ;; We don't want to display an error message.
8193 (with-temp-message (or (current-message) "")
8194 (condition-case nil
8195 (tramp-send-command-and-read
8196 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8197 (error nil))))
8198 (unless (and (listp tmp) (stringp (car tmp))
8199 (string-match "^./.$" (car tmp))
8200 (integerp (cadr tmp)))
8201 (setq result nil)))
8202 result)))
fb7933a3 8203
293c24f9
MA
8204(defun tramp-get-remote-readlink (vec)
8205 (with-connection-property vec "readlink"
8206 (tramp-message vec 5 "Finding a suitable `readlink' command")
8207 (let ((result (tramp-find-executable
8208 vec "readlink" (tramp-get-remote-path vec))))
8209 (when (and result
8210 ;; We don't want to display an error message.
8211 (with-temp-message (or (current-message) "")
8212 (condition-case nil
8213 (zerop
8214 (tramp-send-command-and-check
8215 vec (format "%s --canonicalize-missing /" result)))
8216 (error nil))))
8217 result))))
8218
00d6fd04
MA
8219(defun tramp-get-remote-id (vec)
8220 (with-connection-property vec "id"
946a5aeb
MA
8221 (tramp-message vec 5 "Finding POSIX `id' command")
8222 (or
8223 (catch 'id-found
8224 (let ((dl (tramp-get-remote-path vec))
8225 result)
8226 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8227 ;; Check POSIX parameter.
8228 (when (zerop (tramp-send-command-and-check
8229 vec (format "%s -u" result)))
8230 (throw 'id-found result))
8231 (setq dl (cdr dl)))))
8232 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
00d6fd04
MA
8233
8234(defun tramp-get-remote-uid (vec id-format)
8235 (with-connection-property vec (format "uid-%s" id-format)
8236 (let ((res (tramp-send-command-and-read
8237 vec
8238 (format "%s -u%s %s"
8239 (tramp-get-remote-id vec)
8240 (if (equal id-format 'integer) "" "n")
8241 (if (equal id-format 'integer)
8242 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8243 ;; The command might not always return a number.
8244 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8245
8246(defun tramp-get-remote-gid (vec id-format)
8247 (with-connection-property vec (format "gid-%s" id-format)
8248 (let ((res (tramp-send-command-and-read
8249 vec
8250 (format "%s -g%s %s"
8251 (tramp-get-remote-id vec)
8252 (if (equal id-format 'integer) "" "n")
8253 (if (equal id-format 'integer)
8254 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8255 ;; The command might not always return a number.
8256 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
fb7933a3 8257
8d60099b
MA
8258(defun tramp-get-local-uid (id-format)
8259 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8260
8261(defun tramp-get-local-gid (id-format)
9e6ab520 8262 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8d60099b 8263
00d6fd04
MA
8264;; Some predefined connection properties.
8265(defun tramp-get-remote-coding (vec prop)
8266 ;; Local coding handles properties like remote coding. So we could
8267 ;; call it without pain.
8268 (let ((ret (tramp-get-local-coding vec prop)))
8269 ;; The connection property might have been cached. So we must send
8270 ;; the script - maybe.
1d7e9a01 8271 (when (and ret (symbolp ret))
00d6fd04
MA
8272 (let ((name (symbol-name ret)))
8273 (while (string-match (regexp-quote "-") name)
8274 (setq name (replace-match "_" nil t name)))
8275 (tramp-maybe-send-script vec (symbol-value ret) name)
8276 (setq ret name)))
8277 ;; Return the value.
8278 ret))
8279
8280(defun tramp-get-local-coding (vec prop)
bf0503cb 8281 (or
00d6fd04
MA
8282 (tramp-get-connection-property vec prop nil)
8283 (progn
8284 (tramp-find-inline-encoding vec)
8285 (tramp-get-connection-property vec prop nil))))
fb7933a3 8286
00d6fd04 8287(defun tramp-get-method-parameter (method param)
c951aecb 8288 "Return the method parameter PARAM.
00d6fd04
MA
8289If the `tramp-methods' entry does not exist, return NIL."
8290 (let ((entry (assoc param (assoc method tramp-methods))))
8291 (when entry (cadr entry))))
90f8dc03 8292
fb7933a3
KG
8293;; Auto saving to a special directory.
8294
00cec167 8295(defun tramp-exists-file-name-handler (operation &rest args)
00d6fd04
MA
8296 "Checks whether OPERATION runs a file name handler."
8297 ;; The file name handler is determined on base of either an
8298 ;; argument, `buffer-file-name', or `default-directory'.
8299 (condition-case nil
8300 (let* ((buffer-file-name "/")
8301 (default-directory "/")
8302 (fnha file-name-handler-alist)
8303 (check-file-name-operation operation)
8304 (file-name-handler-alist
8305 (list
8306 (cons "/"
aa485f7c
MA
8307 (lambda (operation &rest args)
8308 "Returns OPERATION if it is the one to be checked."
8309 (if (equal check-file-name-operation operation)
8310 operation
8311 (let ((file-name-handler-alist fnha))
8312 (apply operation args))))))))
00d6fd04
MA
8313 (equal (apply operation args) operation))
8314 (error nil)))
c1105d05
MA
8315
8316(unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8317 (defadvice make-auto-save-file-name
8318 (around tramp-advice-make-auto-save-file-name () activate)
00d6fd04 8319 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
b533bc97 8320 (if (tramp-tramp-file-p (buffer-file-name))
7f49fe46
MA
8321 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8322 ;; directly, because this would bypass the locking mechanism.
8323 (setq ad-return-value
8324 (tramp-file-name-handler 'make-auto-save-file-name))
a69c01a0 8325 ad-do-it))
191bb792
MA
8326 (add-hook
8327 'tramp-unload-hook
8328 (lambda ()
8329 (ad-remove-advice
8330 'make-auto-save-file-name
d7ec1df7
MA
8331 'around 'tramp-advice-make-auto-save-file-name)
8332 (ad-activate 'make-auto-save-file-name))))
fb7933a3 8333
b533bc97
MA
8334;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8335;; umask. This is a security threat.
414da5ab
MA
8336
8337(defun tramp-set-auto-save-file-modes ()
8338 "Set permissions of autosaved remote files to the original permissions."
8339 (let ((bfn (buffer-file-name)))
b533bc97 8340 (when (and (tramp-tramp-file-p bfn)
b50dd0d2 8341 (buffer-modified-p)
414da5ab 8342 (stringp buffer-auto-save-file-name)
340b8d4f
MA
8343 (not (equal bfn buffer-auto-save-file-name)))
8344 (unless (file-exists-p buffer-auto-save-file-name)
8345 (write-region "" nil buffer-auto-save-file-name))
8346 ;; Permissions should be set always, because there might be an old
8347 ;; auto-saved file belonging to another original file. This could
8348 ;; be a security threat.
7177e2a3 8349 (set-file-modes buffer-auto-save-file-name
11948172 8350 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
414da5ab 8351
b533bc97
MA
8352(unless (and (featurep 'xemacs)
8353 (= emacs-major-version 21)
8354 (> emacs-minor-version 4))
a69c01a0
MA
8355 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8356 (add-hook 'tramp-unload-hook
aa485f7c
MA
8357 (lambda ()
8358 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
414da5ab 8359
fb7933a3
KG
8360(defun tramp-subst-strs-in-string (alist string)
8361 "Replace all occurrences of the string FROM with TO in STRING.
8362ALIST is of the form ((FROM . TO) ...)."
8363 (save-match-data
8364 (while alist
8365 (let* ((pr (car alist))
8366 (from (car pr))
8367 (to (cdr pr)))
8368 (while (string-match (regexp-quote from) string)
8369 (setq string (replace-match to t t string)))
8370 (setq alist (cdr alist))))
8371 string))
8372
fb7933a3
KG
8373;; ------------------------------------------------------------
8374;; -- Compatibility functions section --
8375;; ------------------------------------------------------------
8376
00d6fd04 8377(defun tramp-read-passwd (proc &optional prompt)
fb7933a3 8378 "Read a password from user (compat function).
5615d63f 8379Consults the auth-source package.
5ec2cc41 8380Invokes `password-read' if available, `read-passwd' else."
00d6fd04
MA
8381 (let* ((key (tramp-make-tramp-file-name
8382 tramp-current-method tramp-current-user
8383 tramp-current-host ""))
8384 (pw-prompt
8385 (or prompt
8386 (with-current-buffer (process-buffer proc)
8387 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8388 (format "%s for %s " (capitalize (match-string 1)) key)))))
7540f029
MA
8389 (with-parsed-tramp-file-name key nil
8390 (prog1
8391 (or
8392 ;; See if auth-sources contains something useful, if it's bound.
8393 (and (boundp 'auth-sources)
8394 (tramp-get-connection-property v "first-password-request" nil)
8395 ;; Try with Tramp's current method.
8396 (funcall (symbol-function 'auth-source-user-or-password)
8397 "password" tramp-current-host tramp-current-method))
8398 ;; Try the password cache.
8399 (when (functionp 'password-read)
8400 (unless (tramp-get-connection-property
8401 v "first-password-request" nil)
8402 (funcall (symbol-function 'password-cache-remove) key))
8403 (let ((password
8404 (funcall (symbol-function 'password-read) pw-prompt key)))
8405 (funcall (symbol-function 'password-cache-add) key password)
8406 password))
8407 ;; Else, get the password interactively.
8408 (read-passwd pw-prompt))
8409 (tramp-set-connection-property v "first-password-request" nil)))))
00d6fd04 8410
9c13938d
MA
8411(defun tramp-clear-passwd (vec)
8412 "Clear password cache for connection related to VEC."
00d6fd04 8413 (when (functionp 'password-cache-remove)
9c13938d
MA
8414 (funcall
8415 (symbol-function 'password-cache-remove)
8416 (tramp-make-tramp-file-name
8417 (tramp-file-name-method vec)
8418 (tramp-file-name-user vec)
8419 (tramp-file-name-host vec)
8420 ""))))
00d6fd04
MA
8421
8422;; Snarfed code from time-date.el and parse-time.el
8423
8424(defconst tramp-half-a-year '(241 17024)
8425"Evaluated by \"(days-to-time 183)\".")
8426
8427(defconst tramp-parse-time-months
8428 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8429 ("apr" . 4) ("may" . 5) ("jun" . 6)
8430 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8431 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8432 "Alist mapping month names to integers.")
8433
8434(defun tramp-time-less-p (t1 t2)
8435 "Say whether time value T1 is less than time value T2."
8436 (unless t1 (setq t1 '(0 0)))
8437 (unless t2 (setq t2 '(0 0)))
8438 (or (< (car t1) (car t2))
8439 (and (= (car t1) (car t2))
8440 (< (nth 1 t1) (nth 1 t2)))))
8441
8442(defun tramp-time-subtract (t1 t2)
8443 "Subtract two time values.
8444Return the difference in the format of a time value."
8445 (unless t1 (setq t1 '(0 0)))
8446 (unless t2 (setq t2 '(0 0)))
8447 (let ((borrow (< (cadr t1) (cadr t2))))
8448 (list (- (car t1) (car t2) (if borrow 1 0))
8449 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
fb7933a3
KG
8450
8451(defun tramp-time-diff (t1 t2)
8452 "Return the difference between the two times, in seconds.
1a762140 8453T1 and T2 are time values (as returned by `current-time' for example)."
fb7933a3 8454 ;; Pacify byte-compiler with `symbol-function'.
ea9d1443
KG
8455 (cond ((and (fboundp 'subtract-time)
8456 (fboundp 'float-time))
8457 (funcall (symbol-function 'float-time)
8458 (funcall (symbol-function 'subtract-time) t1 t2)))
8459 ((and (fboundp 'subtract-time)
8460 (fboundp 'time-to-seconds))
8461 (funcall (symbol-function 'time-to-seconds)
8462 (funcall (symbol-function 'subtract-time) t1 t2)))
fb7933a3 8463 ((fboundp 'itimer-time-difference)
1a762140
MA
8464 (funcall (symbol-function 'itimer-time-difference)
8465 (if (< (length t1) 3) (append t1 '(0)) t1)
8466 (if (< (length t2) 3) (append t2 '(0)) t2)))
fb7933a3 8467 (t
00d6fd04 8468 (let ((time (tramp-time-subtract t1 t2)))
ea9d1443
KG
8469 (+ (* (car time) 65536.0)
8470 (cadr time)
8471 (/ (or (nth 2 time) 0) 1000000.0))))))
fb7933a3
KG
8472
8473(defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8474 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8475EOL-TYPE can be one of `dos', `unix', or `mac'."
8476 (cond ((fboundp 'coding-system-change-eol-conversion)
9e6ab520
MA
8477 (funcall (symbol-function 'coding-system-change-eol-conversion)
8478 coding-system eol-type))
fb7933a3 8479 ((fboundp 'subsidiary-coding-system)
9e6ab520
MA
8480 (funcall (symbol-function 'subsidiary-coding-system)
8481 coding-system
8482 (cond ((eq eol-type 'dos) 'crlf)
8483 ((eq eol-type 'unix) 'lf)
8484 ((eq eol-type 'mac) 'cr)
8485 (t
8486 (error "Unknown EOL-TYPE `%s', must be %s"
8487 eol-type
8488 "`dos', `unix', or `mac'")))))
fb7933a3
KG
8489 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8490
19a87064
MA
8491(defun tramp-set-process-query-on-exit-flag (process flag)
8492 "Specify if query is needed for process when Emacs is exited.
8493If the second argument flag is non-nil, Emacs will query the user before
8494exiting if process is running."
8495 (if (fboundp 'set-process-query-on-exit-flag)
00d6fd04
MA
8496 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
8497 (funcall (symbol-function 'process-kill-without-query) process flag)))
19a87064 8498
19a87064 8499
bf247b6e
KS
8500;; ------------------------------------------------------------
8501;; -- Kludges section --
8502;; ------------------------------------------------------------
fb7933a3
KG
8503
8504;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8505;; does not deal well with newline characters. Newline is replaced by
8506;; backslash newline. But if, say, the string `a backslash newline b'
8507;; is passed to a shell, the shell will expand this into "ab",
8508;; completely omitting the newline. This is not what was intended.
8509;; It does not appear to be possible to make the function
8510;; `shell-quote-argument' work with newlines without making it
8511;; dependent on the shell used. But within this package, we know that
8512;; we will always use a Bourne-like shell, so we use an approach which
8513;; groks newlines.
8514;;
8515;; The approach is simple: we call `shell-quote-argument', then
8516;; massage the newline part of the result.
8517;;
8518;; This function should produce a string which is grokked by a Unix
8519;; shell, even if the Emacs is running on Windows. Since this is the
8520;; kludges section, we bind `system-type' in such a way that
8521;; `shell-quote-arguments' behaves as if on Unix.
8522;;
8523;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8524;; function to work with Bourne-like shells.
8525;;
8526;; CCC: This function should be rewritten so that
8527;; `shell-quote-argument' is not used. This way, we are safe from
8528;; changes in `shell-quote-argument'.
8529(defun tramp-shell-quote-argument (s)
8530 "Similar to `shell-quote-argument', but groks newlines.
8531Only works for Bourne-like shells."
8532 (let ((system-type 'not-windows))
8533 (save-match-data
8534 (let ((result (shell-quote-argument s))
8535 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8536 (when (and (>= (length result) 2)
8537 (string= (substring result 0 2) "\\~"))
8538 (setq result (substring result 1)))
8539 (while (string-match nl result)
8540 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8541 t t result)))
8542 result))))
8543
a69c01a0
MA
8544;; Checklist for `tramp-unload-hook'
8545;; - Unload all `tramp-*' packages
8546;; - Reset `file-name-handler-alist'
8547;; - Cleanup hooks where Tramp functions are in
8548;; - Cleanup advised functions
8549;; - Cleanup autoloads
8550;;;###autoload
8551(defun tramp-unload-tramp ()
08b1eb21 8552 "Discard Tramp from loading remote files."
a69c01a0
MA
8553 (interactive)
8554 ;; When Tramp is not loaded yet, its autoloads are still active.
8c04e197 8555 (tramp-unload-file-name-handlers)
a69c01a0
MA
8556 ;; ange-ftp settings must be enabled.
8557 (when (functionp 'tramp-ftp-enable-ange-ftp)
8558 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
00d6fd04
MA
8559 ;; Maybe its not loaded yet.
8560 (condition-case nil
8561 (unload-feature 'tramp 'force)
a69c01a0
MA
8562 (error nil)))
8563
dea31ca6
MA
8564(when (and load-in-progress
8565 (string-match "Loading tramp..." (or (current-message) "")))
ccb4a481
MA
8566 (message "Loading tramp...done"))
8567
fb7933a3
KG
8568(provide 'tramp)
8569
fb7933a3
KG
8570;;; TODO:
8571
4007ba5b 8572;; * Handle nonlocal exits such as C-g.
00d6fd04
MA
8573;; * But it would probably be better to use with-local-quit at the
8574;; place where it's actually needed: around any potentially
8575;; indefinitely blocking piece of code. In this case it would be
8576;; within Tramp around one of its calls to accept-process-output (or
8577;; around one of the loops that calls accept-process-output)
d037d501 8578;; (Stefan Monnier).
fb7933a3 8579;; * Rewrite `tramp-shell-quote-argument' to abstain from using
b1d06e75 8580;; `shell-quote-argument'.
fb7933a3
KG
8581;; * In Emacs 21, `insert-directory' shows total number of bytes used
8582;; by the files in that directory. Add this here.
8583;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8584;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
fb7933a3 8585;; * Case-insensitive filename completion. (Norbert Goevert.)
fb7933a3
KG
8586;; * Don't use globbing for directories with many files, as this is
8587;; likely to produce long command lines, and some shells choke on
8588;; long command lines.
fb7933a3 8589;; * How to deal with MULE in `insert-file-contents' and `write-region'?
fb7933a3
KG
8590;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8591;; * abbreviate-file-name
8e754ea2 8592;; * Better error checking. At least whenever we see something
fb7933a3
KG
8593;; strange when doing zerop, we should kill the process and start
8594;; again. (Greg Stark)
fb7933a3 8595;; * Remove unneeded parameters from methods.
fb7933a3
KG
8596;; * Make it work for different encodings, and for different file name
8597;; encodings, too. (Daniel Pittman)
fb7933a3
KG
8598;; * Don't search for perl5 and perl. Instead, only search for perl and
8599;; then look if it's the right version (with `perl -v').
8600;; * When editing a remote CVS controlled file as a different user, VC
8601;; gets confused about the file locking status. Try to find out why
8602;; the workaround doesn't work.
3cdaec13 8603;; * Username and hostname completion.
6c4e47fa 8604;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8daea7fc 8605;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
16674e4f 8606;; Code is nearly identical.
cfb5c0db
MA
8607;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8608;; until the last but one hop via `start-file-process'. Apply it
8609;; also for ftp and smb.
00d6fd04
MA
8610;; * WIBNI if we had a command "trampclient"? If I was editing in
8611;; some shell with root priviledges, it would be nice if I could
8612;; just call
8613;; trampclient filename.c
8614;; as an editor, and the _current_ shell would connect to an Emacs
8615;; server and would be used in an existing non-priviledged Emacs
8616;; session for doing the editing in question.
8617;; That way, I need not tell Emacs my password again and be afraid
8618;; that it makes it into core dumps or other ugly stuff (I had Emacs
8619;; once display a just typed password in the context of a keyboard
8620;; sequence prompt for a question immediately following in a shell
8621;; script run within Emacs -- nasty).
8622;; And if I have some ssh session running to a different computer,
8623;; having the possibility of passing a local file there to a local
8624;; Emacs session (in case I can arrange for a connection back) would
8625;; be nice.
a4aeb9a4 8626;; Likely the corresponding Tramp server should not allow the
00d6fd04
MA
8627;; equivalent of the emacsclient -eval option in order to make this
8628;; reasonably unproblematic. And maybe trampclient should have some
8629;; way of passing credentials, like by using an SSL socket or
6e4f5731 8630;; something. (David Kastrup)
00d6fd04 8631;; * Reconnect directly to a compliant shell without first going
6e4f5731 8632;; through the user's default shell. (Pete Forman)
00d6fd04 8633;; * Make `tramp-default-user' obsolete.
11c71217 8634;; * How can I interrupt the remote process with a signal
6e4f5731 8635;; (interrupt-process seems not to work)? (Markus Triska)
2296b54d
MA
8636;; * Avoid the local shell entirely for starting remote processes. If
8637;; so, I think even a signal, when delivered directly to the local
8638;; SSH instance, would correctly be propagated to the remote process
8639;; automatically; possibly SSH would have to be started with
6e4f5731 8640;; "-t". (Markus Triska)
dea31ca6 8641;; * It makes me wonder if tramp couldn't fall back to ssh when scp
6e4f5731
MA
8642;; isn't on the remote host. (Mark A. Hershberger)
8643;; * Use lsh instead of ssh. (Alfred M. Szmidt)
3e2fa353
MA
8644;; * Implement a general server-local-variable mechanism, as there are
8645;; probably other variables that need different values for different
8646;; servers too. The user could then configure a variable (such as
8647;; tramp-server-local-variable-alist) to define any such variables
8648;; that they need to, which would then be let bound as appropriate
6e4f5731 8649;; in tramp functions. (Jason Rumney)
946a5aeb
MA
8650;; * Optimize out-of-band copying, when both methods are scp-like (not
8651;; rsync).
8652;; * Keep a second connection open for out-of-band methods like scp or
8653;; rsync.
7540f029 8654;; * Support ptys in `tramp-handle-start-file-process'. (Bug#4604)
7e5686f0
MA
8655;; * IMHO, it's a drawback that currently Tramp doesn't support
8656;; Unicode in Dired file names by default. Is it possible to
8657;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8658;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
6e4f5731 8659;; expects only English messages? (Juri Linkov)
7e5686f0
MA
8660;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8661;; * Do not handle files with drive letter as remote. (Bug#5447)
b533bc97 8662;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
7e5686f0
MA
8663;; * Try telnet+curl as new method. It might be useful for busybox,
8664;; without built-in uuencode/uudecode.
7540f029
MA
8665;; * Let `shell-dynamic-complete-*' and `comint-dynamic-complete' work
8666;; on remote hosts.
8667;; * Use secrets.el for password handling.
5f2b693f 8668;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
fb7933a3
KG
8669
8670;; Functions for file-name-handler-alist:
8671;; diff-latest-backup-file -- in diff.el
fb7933a3 8672
cdd44874 8673;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
fb7933a3 8674;;; tramp.el ends here
57671b72
MA
8675
8676;; Local Variables:
8677;; mode: Emacs-Lisp
8678;; coding: utf-8
8679;; End: