* frame.h (FRAME_SAMPLE_VISIBILITY): Undo previous change.
[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)
2173 (when (and vec-or-proc (not (zerop tramp-verbose)))
2174 (let ((enable-recursive-minibuffers t))
2175 (pop-to-buffer
2176 (or (and (bufferp buffer) buffer)
2177 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2178 (tramp-get-buffer vec-or-proc)))
2179 (sit-for 30))))))
fb7933a3 2180
c62c9d08
KG
2181(defmacro with-parsed-tramp-file-name (filename var &rest body)
2182 "Parse a Tramp filename and make components available in the body.
2183
2184First arg FILENAME is evaluated and dissected into its components.
2185Second arg VAR is a symbol. It is used as a variable name to hold
2186the filename structure. It is also used as a prefix for the variables
2187holding the components. For example, if VAR is the symbol `foo', then
00d6fd04
MA
2188`foo' will be bound to the whole structure, `foo-method' will be bound to
2189the method component, and so on for `foo-user', `foo-host', `foo-localname'.
c62c9d08
KG
2190
2191Remaining args are Lisp expressions to be evaluated (inside an implicit
2192`progn').
2193
00d6fd04
MA
2194If VAR is nil, then we bind `v' to the structure and `method', `user',
2195`host', `localname' to the components."
c62c9d08 2196 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
c62c9d08
KG
2197 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2198 (tramp-file-name-method ,(or var 'v)))
2199 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2200 (tramp-file-name-user ,(or var 'v)))
2201 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2202 (tramp-file-name-host ,(or var 'v)))
7432277c
KG
2203 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2204 (tramp-file-name-localname ,(or var 'v))))
c62c9d08
KG
2205 ,@body))
2206
2207(put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
00d6fd04 2208(put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
9e6ab520 2209(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
c62c9d08 2210
00d6fd04
MA
2211(defmacro with-file-property (vec file property &rest body)
2212 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2213FILE must be a local file name on a connection identified via VEC."
2214 `(if (file-name-absolute-p ,file)
2215 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2216 (when (eq value 'undef)
2217 ;; We cannot pass @body as parameter to
2218 ;; `tramp-set-file-property' because it mangles our
2219 ;; debug messages.
2220 (setq value (progn ,@body))
2221 (tramp-set-file-property ,vec ,file ,property value))
2222 value)
2223 ,@body))
9ce8462a 2224
00d6fd04
MA
2225(put 'with-file-property 'lisp-indent-function 3)
2226(put 'with-file-property 'edebug-form-spec t)
9e6ab520 2227(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
00d6fd04
MA
2228
2229(defmacro with-connection-property (key property &rest body)
2230 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2231 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2232 (when (eq value 'undef)
2233 ;; We cannot pass ,@body as parameter to
2234 ;; `tramp-set-connection-property' because it mangles our debug
2235 ;; messages.
2236 (setq value (progn ,@body))
2237 (tramp-set-connection-property ,key ,property value))
2238 value))
9ce8462a 2239
00d6fd04
MA
2240(put 'with-connection-property 'lisp-indent-function 2)
2241(put 'with-connection-property 'edebug-form-spec t)
9e6ab520 2242(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
00d6fd04 2243
628c97b2
GM
2244(eval-and-compile ; silence compiler
2245 (if (memq system-type '(cygwin windows-nt))
2246 (defun tramp-drop-volume-letter (name)
2247 "Cut off unnecessary drive letter from file NAME.
2248The function `tramp-handle-expand-file-name' calls `expand-file-name'
2249locally on a remote file name. When the local system is a W32 system
2250but the remote system is Unix, this introduces a superfluous drive
2251letter into the file name. This function removes it."
2252 (save-match-data
2253 (if (string-match tramp-root-regexp name)
2254 (replace-match "/" nil t name)
2255 name)))
2256
2257 (defalias 'tramp-drop-volume-letter 'identity)))
2258
9c13938d 2259(defsubst tramp-make-tramp-temp-file (vec)
a6e96327 2260 "Create a temporary file on the remote host identified by VEC.
9c13938d
MA
2261Return the local name of the temporary file."
2262 (let ((prefix
2263 (tramp-make-tramp-file-name
2264 (tramp-file-name-method vec)
2265 (tramp-file-name-user vec)
2266 (tramp-file-name-host vec)
113e2a84
MA
2267 (tramp-drop-volume-letter
2268 (expand-file-name
2269 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
9c13938d
MA
2270 result)
2271 (while (not result)
2272 ;; `make-temp-file' would be the natural choice for
2273 ;; implementation. But it calls `write-region' internally,
2274 ;; which also needs a temporary file - we would end in an
2275 ;; infinite loop.
2276 (setq result (make-temp-name prefix))
2277 (if (file-exists-p result)
2278 (setq result nil)
2279 ;; This creates the file by side effect.
2280 (set-file-times result)
2281 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2282
2283 ;; Return the local part.
2284 (with-parsed-tramp-file-name result nil localname)))
8a4438b6
MA
2285
2286
16674e4f
KG
2287;;; Config Manipulation Functions:
2288
2289(defun tramp-set-completion-function (method function-list)
2290 "Sets the list of completion functions for METHOD.
2291FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2292The FUNCTION is intended to parse FILE according its syntax.
2293It might be a predefined FUNCTION, or a user defined FUNCTION.
2294Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
8fc29035 2295`tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
8daea7fc
KG
2296and `tramp-parse-netrc'.
2297
16674e4f
KG
2298Example:
2299
2300 (tramp-set-completion-function
2301 \"ssh\"
8daea7fc
KG
2302 '((tramp-parse-sconfig \"/etc/ssh_config\")
2303 (tramp-parse-sconfig \"~/.ssh/config\")))"
16674e4f 2304
5ec2cc41
KG
2305 (let ((r function-list)
2306 (v function-list))
2307 (setq tramp-completion-function-alist
2308 (delete (assoc method tramp-completion-function-alist)
2309 tramp-completion-function-alist))
2310
2311 (while v
00d6fd04 2312 ;; Remove double entries.
5ec2cc41
KG
2313 (when (member (car v) (cdr v))
2314 (setcdr v (delete (car v) (cdr v))))
00d6fd04 2315 ;; Check for function and file or registry key.
5ec2cc41 2316 (unless (and (functionp (nth 0 (car v)))
00d6fd04
MA
2317 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2318 ;; Windows registry.
2319 (and (memq system-type '(cygwin windows-nt))
a4aeb9a4
MA
2320 (zerop
2321 (tramp-local-call-process
2322 "reg" nil nil nil "query" (nth 1 (car v)))))
00d6fd04
MA
2323 ;; Configuration file.
2324 (file-exists-p (nth 1 (car v)))))
5ec2cc41
KG
2325 (setq r (delete (car v) r)))
2326 (setq v (cdr v)))
2327
2328 (when r
4007ba5b 2329 (add-to-list 'tramp-completion-function-alist
5ec2cc41 2330 (cons method r)))))
16674e4f
KG
2331
2332(defun tramp-get-completion-function (method)
00d6fd04 2333 "Returns a list of completion functions for METHOD.
16674e4f 2334For definition of that list see `tramp-set-completion-function'."
00d6fd04
MA
2335 (cons
2336 ;; Hosts visited once shall be remembered.
2337 `(tramp-parse-connection-properties ,method)
2338 ;; The method related defaults.
2339 (cdr (assoc method tramp-completion-function-alist))))
16674e4f 2340
d037d501 2341
0664ff72 2342;;; Fontification of `read-file-name':
d037d501 2343
0664ff72 2344;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
d037d501
MA
2345(defvar tramp-rfn-eshadow-overlay)
2346(make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2347
2348(defun tramp-rfn-eshadow-setup-minibuffer ()
2349 "Set up a minibuffer for `file-name-shadow-mode'.
2350Adds another overlay hiding filename parts according to Tramp's
2351special handling of `substitute-in-file-name'."
9ce8462a 2352 (when (symbol-value 'minibuffer-completing-file-name)
d037d501 2353 (setq tramp-rfn-eshadow-overlay
9e6ab520
MA
2354 (funcall (symbol-function 'make-overlay)
2355 (funcall (symbol-function 'minibuffer-prompt-end))
2356 (funcall (symbol-function 'minibuffer-prompt-end))))
d037d501 2357 ;; Copy rfn-eshadow-overlay properties.
9e6ab520
MA
2358 (let ((props (funcall (symbol-function 'overlay-properties)
2359 (symbol-value 'rfn-eshadow-overlay))))
d037d501 2360 (while props
9e6ab520
MA
2361 (funcall (symbol-function 'overlay-put)
2362 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
d037d501
MA
2363
2364(when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2365 (add-hook 'rfn-eshadow-setup-minibuffer-hook
48846dc5
MA
2366 'tramp-rfn-eshadow-setup-minibuffer)
2367 (add-hook 'tramp-unload-hook
aa485f7c
MA
2368 (lambda ()
2369 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2370 'tramp-rfn-eshadow-setup-minibuffer))))
d037d501 2371
adcbca53
MA
2372(defconst tramp-rfn-eshadow-update-overlay-regexp
2373 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2374
d037d501
MA
2375(defun tramp-rfn-eshadow-update-overlay ()
2376 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2377This is intended to be used as a minibuffer `post-command-hook' for
2378`file-name-shadow-mode'; the minibuffer should have already
2379been set up by `rfn-eshadow-setup-minibuffer'."
2380 ;; In remote files name, there is a shadowing just for the local part.
9e6ab520
MA
2381 (let ((end (or (funcall (symbol-function 'overlay-end)
2382 (symbol-value 'rfn-eshadow-overlay))
2383 (funcall (symbol-function 'minibuffer-prompt-end)))))
2384 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
bd316474
KY
2385 (save-excursion
2386 (save-restriction
2387 (narrow-to-region
adcbca53
MA
2388 (1+ (or (string-match
2389 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2390 end))
2391 (point-max))
bd316474
KY
2392 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2393 (rfn-eshadow-update-overlay-hook nil))
dea31ca6 2394 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
bd316474 2395 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
d037d501
MA
2396
2397(when (boundp 'rfn-eshadow-update-overlay-hook)
2398 (add-hook 'rfn-eshadow-update-overlay-hook
b88f2d0a
MA
2399 'tramp-rfn-eshadow-update-overlay)
2400 (add-hook 'tramp-unload-hook
2401 (lambda ()
2402 (remove-hook 'rfn-eshadow-update-overlay-hook
2403 'tramp-rfn-eshadow-update-overlay))))
d037d501
MA
2404
2405
605a20a9
MA
2406;;; Integration of eshell.el:
2407
2408(eval-when-compile
2409 (defvar eshell-path-env))
2410
2411;; eshell.el keeps the path in `eshell-path-env'. We must change it
2412;; when `default-directory' points to another host.
2413(defun tramp-eshell-directory-change ()
2414 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2415 (setq eshell-path-env
2416 (if (file-remote-p default-directory)
2417 (with-parsed-tramp-file-name default-directory nil
2418 (mapconcat
2419 'identity
2420 (tramp-get-remote-path v)
2421 ":"))
2422 (getenv "PATH"))))
2423
2424(eval-after-load "esh-util"
2425 '(progn
2426 (tramp-eshell-directory-change)
2427 (add-hook 'eshell-directory-change-hook
2428 'tramp-eshell-directory-change)
2429 (add-hook 'tramp-unload-hook
2430 (lambda ()
2431 (remove-hook 'eshell-directory-change-hook
2432 'tramp-eshell-directory-change)))))
2433
2434
fb7933a3
KG
2435;;; File Name Handler Functions:
2436
fb7933a3
KG
2437(defun tramp-handle-make-symbolic-link
2438 (filename linkname &optional ok-if-already-exists)
00d6fd04 2439 "Like `make-symbolic-link' for Tramp files.
cebb4ec6 2440If LINKNAME is a non-Tramp file, it is used verbatim as the target of
7432277c 2441the symlink. If LINKNAME is a Tramp file, only the localname component is
cebb4ec6
KG
2442used as the target of the symlink.
2443
7432277c
KG
2444If LINKNAME is a Tramp file and the localname component is relative, then
2445it is expanded first, before the localname component is taken. Note that
cebb4ec6
KG
2446this can give surprising results if the user/host for the source and
2447target of the symlink differ."
c62c9d08 2448 (with-parsed-tramp-file-name linkname l
00d6fd04 2449 (let ((ln (tramp-get-remote-ln l))
87bdd2c7
MA
2450 (cwd (tramp-run-real-handler
2451 'file-name-directory (list l-localname))))
c62c9d08 2452 (unless ln
00d6fd04
MA
2453 (tramp-error
2454 l 'file-error
2455 "Making a symbolic link. ln(1) does not exist on the remote host."))
c62c9d08
KG
2456
2457 ;; Do the 'confirm if exists' thing.
cebb4ec6 2458 (when (file-exists-p linkname)
c62c9d08
KG
2459 ;; What to do?
2460 (if (or (null ok-if-already-exists) ; not allowed to exist
2461 (and (numberp ok-if-already-exists)
2462 (not (yes-or-no-p
2463 (format
2464 "File %s already exists; make it a link anyway? "
7432277c 2465 l-localname)))))
00d6fd04
MA
2466 (tramp-error
2467 l 'file-already-exists "File %s already exists" l-localname)
cebb4ec6
KG
2468 (delete-file linkname)))
2469
7432277c 2470 ;; If FILENAME is a Tramp name, use just the localname component.
cebb4ec6 2471 (when (tramp-tramp-file-p filename)
1834b39f
MA
2472 (setq filename
2473 (tramp-file-name-localname
2474 (tramp-dissect-file-name (expand-file-name filename)))))
bf247b6e 2475
c62c9d08
KG
2476 ;; Right, they are on the same host, regardless of user, method, etc.
2477 ;; We now make the link on the remote machine. This will occur as the user
2478 ;; that FILENAME belongs to.
2479 (zerop
2480 (tramp-send-command-and-check
b593f105
MA
2481 l
2482 (format
2483 "cd %s && %s -sf %s %s"
2484 (tramp-shell-quote-argument cwd)
2485 ln
2486 (tramp-shell-quote-argument filename)
2487 (tramp-shell-quote-argument l-localname))
2488 t)))))
fb7933a3 2489
fb7933a3 2490(defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
00d6fd04
MA
2491 "Like `load' for Tramp files."
2492 (with-parsed-tramp-file-name (expand-file-name file) nil
c62c9d08
KG
2493 (unless nosuffix
2494 (cond ((file-exists-p (concat file ".elc"))
2495 (setq file (concat file ".elc")))
2496 ((file-exists-p (concat file ".el"))
2497 (setq file (concat file ".el")))))
2498 (when must-suffix
2499 ;; The first condition is always true for absolute file names.
2500 ;; Included for safety's sake.
2501 (unless (or (file-name-directory file)
2502 (string-match "\\.elc?\\'" file))
00d6fd04
MA
2503 (tramp-error
2504 v 'file-error
2505 "File `%s' does not include a `.el' or `.elc' suffix" file)))
c62c9d08
KG
2506 (unless noerror
2507 (when (not (file-exists-p file))
00d6fd04 2508 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
c62c9d08
KG
2509 (if (not (file-exists-p file))
2510 nil
00d6fd04 2511 (unless nomessage (tramp-message v 0 "Loading %s..." file))
c62c9d08
KG
2512 (let ((local-copy (file-local-copy file)))
2513 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
ce2cc728
MA
2514 (unwind-protect
2515 (load local-copy noerror t t)
2516 (delete-file local-copy)))
00d6fd04 2517 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
c62c9d08 2518 t)))
fb7933a3 2519
a4aeb9a4 2520;; Localname manipulation functions that grok Tramp localnames...
c0fc6170
MA
2521(defun tramp-handle-file-name-as-directory (file)
2522 "Like `file-name-as-directory' but aware of Tramp files."
2523 ;; `file-name-as-directory' would be sufficient except localname is
2524 ;; the empty string.
2525 (let ((v (tramp-dissect-file-name file t)))
2526 ;; Run the command on the localname portion only.
2527 (tramp-make-tramp-file-name
2528 (tramp-file-name-method v)
2529 (tramp-file-name-user v)
2530 (tramp-file-name-host v)
2531 (tramp-run-real-handler
2532 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2533
fb7933a3 2534(defun tramp-handle-file-name-directory (file)
00d6fd04 2535 "Like `file-name-directory' but aware of Tramp files."
9ce8462a
MA
2536 ;; Everything except the last filename thing is the directory. We
2537 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2538 ;; the remote file name parts. This is a problem when we are in
2539 ;; file name completion.
2540 (let ((v (tramp-dissect-file-name file t)))
a01b1e22
MA
2541 ;; Run the command on the localname portion only.
2542 (tramp-make-tramp-file-name
9ce8462a
MA
2543 (tramp-file-name-method v)
2544 (tramp-file-name-user v)
2545 (tramp-file-name-host v)
87bdd2c7
MA
2546 (tramp-run-real-handler
2547 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
fb7933a3
KG
2548
2549(defun tramp-handle-file-name-nondirectory (file)
00d6fd04 2550 "Like `file-name-nondirectory' but aware of Tramp files."
c62c9d08 2551 (with-parsed-tramp-file-name file nil
87bdd2c7 2552 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
fb7933a3
KG
2553
2554(defun tramp-handle-file-truename (filename &optional counter prev-dirs)
00d6fd04 2555 "Like `file-truename' for Tramp files."
48ddd622 2556 (with-parsed-tramp-file-name (expand-file-name filename) nil
00d6fd04 2557 (with-file-property v localname "file-truename"
293c24f9 2558 (let ((result nil)) ; result steps in reverse order
00d6fd04 2559 (tramp-message v 4 "Finding true name for `%s'" filename)
293c24f9
MA
2560 (cond
2561 ;; Use GNU readlink --canonicalize-missing where available.
2562 ((tramp-get-remote-readlink v)
2563 (setq result
2564 (tramp-send-command-and-read
2565 v
2566 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2567 (tramp-get-remote-readlink v)
2568 (tramp-shell-quote-argument localname)))))
2569
2570 ;; Use Perl implementation.
2571 ((and (tramp-get-remote-perl v)
2572 (tramp-get-connection-property v "perl-file-spec" nil)
2573 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2574 (tramp-maybe-send-script
2575 v tramp-perl-file-truename "tramp_perl_file_truename")
2576 (setq result
2577 (tramp-send-command-and-read
2578 v
2579 (format "tramp_perl_file_truename %s"
2580 (tramp-shell-quote-argument localname)))))
2581
2582 ;; Do it yourself. We bind `directory-sep-char' here for
2583 ;; XEmacs on Windows, which would otherwise use backslash.
2584 (t (let* ((directory-sep-char ?/)
2585 (steps (tramp-compat-split-string localname "/"))
2586 (localnamedir (tramp-run-real-handler
2587 'file-name-as-directory (list localname)))
2588 (is-dir (string= localname localnamedir))
2589 (thisstep nil)
2590 (numchase 0)
2591 ;; Don't make the following value larger than
2592 ;; necessary. People expect an error message in a
2593 ;; timely fashion when something is wrong;
2594 ;; otherwise they might think that Emacs is hung.
2595 ;; Of course, correctness has to come first.
2596 (numchase-limit 20)
2597 symlink-target)
2598 (while (and steps (< numchase numchase-limit))
2599 (setq thisstep (pop steps))
2600 (tramp-message
2601 v 5 "Check %s"
2602 (mapconcat 'identity
2603 (append '("") (reverse result) (list thisstep))
2604 "/"))
2605 (setq symlink-target
2606 (nth 0 (file-attributes
2607 (tramp-make-tramp-file-name
2608 method user host
2609 (mapconcat 'identity
2610 (append '("")
2611 (reverse result)
2612 (list thisstep))
2613 "/")))))
2614 (cond ((string= "." thisstep)
2615 (tramp-message v 5 "Ignoring step `.'"))
2616 ((string= ".." thisstep)
2617 (tramp-message v 5 "Processing step `..'")
2618 (pop result))
2619 ((stringp symlink-target)
2620 ;; It's a symlink, follow it.
2621 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2622 (setq numchase (1+ numchase))
2623 (when (file-name-absolute-p symlink-target)
2624 (setq result nil))
2625 ;; If the symlink was absolute, we'll get a string like
2626 ;; "/user@host:/some/target"; extract the
2627 ;; "/some/target" part from it.
2628 (when (tramp-tramp-file-p symlink-target)
2629 (unless (tramp-equal-remote filename symlink-target)
2630 (tramp-error
2631 v 'file-error
2632 "Symlink target `%s' on wrong host" symlink-target))
2633 (setq symlink-target localname))
2634 (setq steps
2635 (append (tramp-compat-split-string
2636 symlink-target "/")
2637 steps)))
2638 (t
2639 ;; It's a file.
2640 (setq result (cons thisstep result)))))
2641 (when (>= numchase numchase-limit)
2642 (tramp-error
2643 v 'file-error
2644 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2645 (setq result (reverse result))
2646 ;; Combine list to form string.
2647 (setq result
2648 (if result
2649 (mapconcat 'identity (cons "" result) "/")
00d6fd04 2650 "/"))
293c24f9
MA
2651 (when (and is-dir (or (string= "" result)
2652 (not (string= (substring result -1) "/"))))
2653 (setq result (concat result "/"))))))
2654
2655 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2656 (tramp-make-tramp-file-name method user host result)))))
fb7933a3
KG
2657
2658;; Basic functions.
2659
2660(defun tramp-handle-file-exists-p (filename)
00d6fd04 2661 "Like `file-exists-p' for Tramp files."
c62c9d08 2662 (with-parsed-tramp-file-name filename nil
00d6fd04 2663 (with-file-property v localname "file-exists-p"
293c24f9
MA
2664 (or (not (null (tramp-get-file-property
2665 v localname "file-attributes-integer" nil)))
2666 (not (null (tramp-get-file-property
2667 v localname "file-attributes-string" nil)))
2668 (zerop (tramp-send-command-and-check
2669 v
2670 (format
2671 "%s %s"
2672 (tramp-get-file-exists-command v)
2673 (tramp-shell-quote-argument localname))))))))
fb7933a3 2674
00d6fd04
MA
2675;; Inodes don't exist for some file systems. Therefore we must
2676;; generate virtual ones. Used in `find-buffer-visiting'. The method
2677;; applied might be not so efficient (Ange-FTP uses hashes). But
2678;; performance isn't the major issue given that file transfer will
2679;; take time.
2680(defvar tramp-inodes nil
2681 "Keeps virtual inodes numbers.")
2682
8daea7fc
KG
2683;; Devices must distinguish physical file systems. The device numbers
2684;; provided by "lstat" aren't unique, because we operate on different hosts.
2685;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2686;; EFS use device number "-1". In order to be different, we use device number
b946a456 2687;; (-1 . x), whereby "x" is unique for a given (method user host).
8daea7fc
KG
2688(defvar tramp-devices nil
2689 "Keeps virtual device numbers.")
2690
fb7933a3
KG
2691;; CCC: This should check for an error condition and signal failure
2692;; when something goes wrong.
2693;; Daniel Pittman <daniel@danann.net>
c951aecb 2694(defun tramp-handle-file-attributes (filename &optional id-format)
00d6fd04
MA
2695 "Like `file-attributes' for Tramp files."
2696 (unless id-format (setq id-format 'integer))
aa485f7c
MA
2697 ;; Don't modify `last-coding-system-used' by accident.
2698 (let ((last-coding-system-used last-coding-system-used))
2699 (with-parsed-tramp-file-name (expand-file-name filename) nil
2700 (with-file-property v localname (format "file-attributes-%s" id-format)
7f49fe46
MA
2701 (save-excursion
2702 (tramp-convert-file-attributes
2703 v
2704 (cond
2705 ((tramp-get-remote-stat v)
2706 (tramp-do-file-attributes-with-stat v localname id-format))
2707 ((tramp-get-remote-perl v)
2708 (tramp-do-file-attributes-with-perl v localname id-format))
2709 (t
2710 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2711
2712(defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
00d6fd04 2713 "Implement `file-attributes' for Tramp files using the ls(1) command."
fb7933a3
KG
2714 (let (symlinkp dirp
2715 res-inode res-filemodes res-numlinks
2716 res-uid res-gid res-size res-symlink-target)
00d6fd04 2717 (tramp-message vec 5 "file attributes with ls: %s" localname)
fb7933a3 2718 (tramp-send-command
00d6fd04 2719 vec
680db9ac
MA
2720 (format "(%s %s || %s -h %s) && %s %s %s"
2721 (tramp-get-file-exists-command vec)
2722 (tramp-shell-quote-argument localname)
2723 (tramp-get-test-command vec)
2724 (tramp-shell-quote-argument localname)
00d6fd04 2725 (tramp-get-ls-command vec)
c82c5727 2726 (if (eq id-format 'integer) "-ildn" "-ild")
7432277c 2727 (tramp-shell-quote-argument localname)))
fb7933a3 2728 ;; parse `ls -l' output ...
00d6fd04 2729 (with-current-buffer (tramp-get-buffer vec)
680db9ac
MA
2730 (when (> (buffer-size) 0)
2731 (goto-char (point-min))
2732 ;; ... inode
2733 (setq res-inode
2734 (condition-case err
2735 (read (current-buffer))
2736 (invalid-read-syntax
2737 (when (and (equal (cadr err)
2738 "Integer constant overflow in reader")
2739 (string-match
2740 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2741 (car (cddr err))))
2742 (let* ((big (read (substring (car (cddr err)) 0
2743 (match-beginning 1))))
2744 (small (read (match-string 1 (car (cddr err)))))
2745 (twiddle (/ small 65536)))
2746 (cons (+ big twiddle)
2747 (- small (* twiddle 65536))))))))
2748 ;; ... file mode flags
2749 (setq res-filemodes (symbol-name (read (current-buffer))))
2750 ;; ... number links
2751 (setq res-numlinks (read (current-buffer)))
2752 ;; ... uid and gid
2753 (setq res-uid (read (current-buffer)))
2754 (setq res-gid (read (current-buffer)))
2755 (if (eq id-format 'integer)
2756 (progn
2757 (unless (numberp res-uid) (setq res-uid -1))
2758 (unless (numberp res-gid) (setq res-gid -1)))
2759 (progn
2760 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2761 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2762 ;; ... size
2763 (setq res-size (read (current-buffer)))
2764 ;; From the file modes, figure out other stuff.
2765 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2766 (setq dirp (eq ?d (aref res-filemodes 0)))
2767 ;; if symlink, find out file name pointed to
2768 (when symlinkp
2769 (search-forward "-> ")
2770 (setq res-symlink-target
2771 (buffer-substring (point) (tramp-compat-line-end-position))))
2772 ;; return data gathered
2773 (list
2774 ;; 0. t for directory, string (name linked to) for symbolic
2775 ;; link, or nil.
2776 (or dirp res-symlink-target)
2777 ;; 1. Number of links to file.
2778 res-numlinks
2779 ;; 2. File uid.
2780 res-uid
2781 ;; 3. File gid.
2782 res-gid
2783 ;; 4. Last access time, as a list of two integers. First
2784 ;; integer has high-order 16 bits of time, second has low 16
2785 ;; bits.
2786 ;; 5. Last modification time, likewise.
2787 ;; 6. Last status change time, likewise.
2788 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2789 ;; 7. Size in bytes (-1, if number is out of range).
2790 res-size
2791 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2792 res-filemodes
2793 ;; 9. t if file's gid would change if file were deleted and
2794 ;; recreated. Will be set in `tramp-convert-file-attributes'
2795 t
2796 ;; 10. inode number.
2797 res-inode
2798 ;; 11. Device number. Will be replaced by a virtual device number.
2799 -1
2800 )))))
fb7933a3 2801
7f49fe46 2802(defun tramp-do-file-attributes-with-perl
00d6fd04
MA
2803 (vec localname &optional id-format)
2804 "Implement `file-attributes' for Tramp files using a Perl script."
2805 (tramp-message vec 5 "file attributes with perl: %s" localname)
2806 (tramp-maybe-send-script
2807 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2808 (tramp-send-command-and-read
2809 vec
2810 (format "tramp_perl_file_attributes %s %s"
2811 (tramp-shell-quote-argument localname) id-format)))
2812
7f49fe46 2813(defun tramp-do-file-attributes-with-stat
00d6fd04
MA
2814 (vec localname &optional id-format)
2815 "Implement `file-attributes' for Tramp files using stat(1) command."
2816 (tramp-message vec 5 "file attributes with stat: %s" localname)
2817 (tramp-send-command-and-read
2818 vec
2819 (format
680db9ac
MA
2820 "((%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)"
2821 (tramp-get-file-exists-command vec)
2822 (tramp-shell-quote-argument localname)
2823 (tramp-get-test-command vec)
2824 (tramp-shell-quote-argument localname)
00d6fd04
MA
2825 (tramp-get-remote-stat vec)
2826 (if (eq id-format 'integer) "%u" "\"%U\"")
2827 (if (eq id-format 'integer) "%g" "\"%G\"")
2828 (tramp-shell-quote-argument localname))))
8daea7fc 2829
fb7933a3 2830(defun tramp-handle-set-visited-file-modtime (&optional time-list)
00d6fd04 2831 "Like `set-visited-file-modtime' for Tramp files."
fb7933a3
KG
2832 (unless (buffer-file-name)
2833 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2834 (buffer-name)))
48ddd622
MA
2835 (if time-list
2836 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
11948172
MA
2837 (let ((f (buffer-file-name))
2838 coding-system-used)
48ddd622
MA
2839 (with-parsed-tramp-file-name f nil
2840 (let* ((attr (file-attributes f))
2841 ;; '(-1 65535) means file doesn't exists yet.
2842 (modtime (or (nth 5 attr) '(-1 65535))))
11948172
MA
2843 (when (boundp 'last-coding-system-used)
2844 (setq coding-system-used (symbol-value 'last-coding-system-used)))
48ddd622 2845 ;; We use '(0 0) as a don't-know value. See also
7f49fe46 2846 ;; `tramp-do-file-attributes-with-ls'.
48ddd622
MA
2847 (if (not (equal modtime '(0 0)))
2848 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
00d6fd04 2849 (progn
48ddd622 2850 (tramp-send-command
00d6fd04 2851 v
48ddd622 2852 (format "%s -ild %s"
00d6fd04 2853 (tramp-get-ls-command v)
48ddd622 2854 (tramp-shell-quote-argument localname)))
48ddd622
MA
2855 (setq attr (buffer-substring (point)
2856 (progn (end-of-line) (point)))))
00d6fd04
MA
2857 (tramp-set-file-property
2858 v localname "visited-file-modtime-ild" attr))
11948172
MA
2859 (when (boundp 'last-coding-system-used)
2860 (set 'last-coding-system-used coding-system-used))
d2a2c17f 2861 nil)))))
fb7933a3 2862
c62c9d08
KG
2863;; This function makes the same assumption as
2864;; `tramp-handle-set-visited-file-modtime'.
2865(defun tramp-handle-verify-visited-file-modtime (buf)
00d6fd04 2866 "Like `verify-visited-file-modtime' for Tramp files.
c08e6004
MA
2867At the time `verify-visited-file-modtime' calls this function, we
2868already know that the buffer is visiting a file and that
2869`visited-file-modtime' does not return 0. Do not call this
2870function directly, unless those two cases are already taken care
2871of."
c62c9d08 2872 (with-current-buffer buf
b15d0c4c
MA
2873 ;; There is no file visiting the buffer, or the buffer has no
2874 ;; recorded last modification time.
2875 (if (or (not (buffer-file-name))
2876 (eq (visited-file-modtime) 0))
d2a2c17f 2877 t
b15d0c4c
MA
2878 (let ((f (buffer-file-name)))
2879 (with-parsed-tramp-file-name f nil
bce04fee 2880 (tramp-flush-file-property v localname)
b15d0c4c
MA
2881 (let* ((attr (file-attributes f))
2882 (modtime (nth 5 attr))
2883 (mt (visited-file-modtime)))
bf247b6e 2884
70c11b0b
MA
2885 (cond
2886 ;; File exists, and has a known modtime.
b15d0c4c
MA
2887 ((and attr (not (equal modtime '(0 0))))
2888 (< (abs (tramp-time-diff
2889 modtime
2890 ;; For compatibility, deal with both the old
70c11b0b
MA
2891 ;; (HIGH . LOW) and the new (HIGH LOW) return
2892 ;; values of `visited-file-modtime'.
b15d0c4c
MA
2893 (if (atom (cdr mt))
2894 (list (car mt) (cdr mt))
2895 mt)))
2896 2))
70c11b0b 2897 ;; Modtime has the don't know value.
b15d0c4c 2898 (attr
00d6fd04
MA
2899 (tramp-send-command
2900 v
2901 (format "%s -ild %s"
2902 (tramp-get-ls-command v)
2903 (tramp-shell-quote-argument localname)))
2904 (with-current-buffer (tramp-get-buffer v)
b15d0c4c
MA
2905 (setq attr (buffer-substring
2906 (point) (progn (end-of-line) (point)))))
00d6fd04
MA
2907 (equal
2908 attr
2909 (tramp-get-file-property
2910 v localname "visited-file-modtime-ild" "")))
70c11b0b
MA
2911 ;; If file does not exist, say it is not modified if and
2912 ;; only if that agrees with the buffer's record.
b15d0c4c 2913 (t (equal mt '(-1 65535))))))))))
c62c9d08 2914
fb7933a3 2915(defun tramp-handle-set-file-modes (filename mode)
00d6fd04 2916 "Like `set-file-modes' for Tramp files."
c62c9d08 2917 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2918 (tramp-flush-file-property v localname)
2919 (unless (zerop (tramp-send-command-and-check
2920 v
2921 (format "chmod %s %s"
2922 (tramp-decimal-to-octal mode)
2923 (tramp-shell-quote-argument localname))))
2924 ;; FIXME: extract the proper text from chmod's stderr.
2925 (tramp-error
2926 v 'file-error "Error while changing file's mode %s" filename))))
fb7933a3 2927
ce3f516f
MA
2928(defun tramp-handle-set-file-times (filename &optional time)
2929 "Like `set-file-times' for Tramp files."
2930 (zerop
9e6ab520 2931 (if (file-remote-p filename)
ce3f516f 2932 (with-parsed-tramp-file-name filename nil
8d60099b 2933 (tramp-flush-file-property v localname)
ce3f516f
MA
2934 (let ((time (if (or (null time) (equal time '(0 0)))
2935 (current-time)
2936 time))
2937 (utc
2938 ;; With GNU Emacs, `format-time-string' has an
2939 ;; optional parameter UNIVERSAL. This is preferred,
2940 ;; because we could handle the case when the remote
2941 ;; host is located in a different time zone as the
2942 ;; local host.
2943 (and (functionp 'subr-arity)
2944 (subrp (symbol-function 'format-time-string))
2945 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2946 (symbol-function
2947 'format-time-string)))))))
2948 (tramp-send-command-and-check
2949 v (format "%s touch -t %s %s"
2950 (if utc "TZ=UTC; export TZ;" "")
2951 (if utc
2952 (format-time-string "%Y%m%d%H%M.%S" time t)
2953 (format-time-string "%Y%m%d%H%M.%S" time))
2954 (tramp-shell-quote-argument localname)))))
8d60099b 2955
ce3f516f
MA
2956 ;; We handle also the local part, because in older Emacsen,
2957 ;; without `set-file-times', this function is an alias for this.
2958 ;; We are local, so we don't need the UTC settings.
a4aeb9a4 2959 (tramp-local-call-process
ce3f516f
MA
2960 "touch" nil nil nil "-t"
2961 (format-time-string "%Y%m%d%H%M.%S" time)
2962 (tramp-shell-quote-argument filename)))))
2963
8d60099b
MA
2964(defun tramp-set-file-uid-gid (filename &optional uid gid)
2965 "Set the ownership for FILENAME.
2966If UID and GID are provided, these values are used; otherwise uid
2967and gid of the corresponding user is taken. Both parameters must be integers."
70c11b0b
MA
2968 ;; Modern Unices allow chown only for root. So we might need
2969 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2970 ;; working with su(do)? when it is needed, so it shall succeed in
2971 ;; the majority of cases.
aa485f7c
MA
2972 ;; Don't modify `last-coding-system-used' by accident.
2973 (let ((last-coding-system-used last-coding-system-used))
2974 (if (file-remote-p filename)
2975 (with-parsed-tramp-file-name filename nil
2976 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2977 ;; If we are root on the local host, we can do it directly.
2978 (tramp-set-file-uid-gid localname uid gid)
2979 (let ((uid (or (and (integerp uid) uid)
2980 (tramp-get-remote-uid v 'integer)))
2981 (gid (or (and (integerp gid) gid)
2982 (tramp-get-remote-gid v 'integer))))
2983 (tramp-send-command
2984 v (format
2985 "chown %d:%d %s" uid gid
2986 (tramp-shell-quote-argument localname))))))
2987
2988 ;; We handle also the local part, because there doesn't exist
2989 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2990 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2991 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2992 (tramp-local-call-process
2993 "chown" nil nil nil
2994 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
8d60099b 2995
fb7933a3
KG
2996;; Simple functions using the `test' command.
2997
2998(defun tramp-handle-file-executable-p (filename)
00d6fd04 2999 "Like `file-executable-p' for Tramp files."
c62c9d08 3000 (with-parsed-tramp-file-name filename nil
00d6fd04 3001 (with-file-property v localname "file-executable-p"
293c24f9
MA
3002 ;; Examine `file-attributes' cache to see if request can be
3003 ;; satisfied without remote operation.
3004 (or (tramp-check-cached-permissions v ?x)
3005 (zerop (tramp-run-test "-x" filename))))))
fb7933a3
KG
3006
3007(defun tramp-handle-file-readable-p (filename)
00d6fd04 3008 "Like `file-readable-p' for Tramp files."
c62c9d08 3009 (with-parsed-tramp-file-name filename nil
00d6fd04 3010 (with-file-property v localname "file-readable-p"
293c24f9
MA
3011 ;; Examine `file-attributes' cache to see if request can be
3012 ;; satisfied without remote operation.
3013 (or (tramp-check-cached-permissions v ?r)
3014 (zerop (tramp-run-test "-r" filename))))))
fb7933a3
KG
3015
3016;; When the remote shell is started, it looks for a shell which groks
3017;; tilde expansion. Here, we assume that all shells which grok tilde
3018;; expansion will also provide a `test' command which groks `-nt' (for
3019;; newer than). If this breaks, tell me about it and I'll try to do
3020;; something smarter about it.
3021(defun tramp-handle-file-newer-than-file-p (file1 file2)
00d6fd04 3022 "Like `file-newer-than-file-p' for Tramp files."
fb7933a3
KG
3023 (cond ((not (file-exists-p file1))
3024 nil)
3025 ((not (file-exists-p file2))
3026 t)
91879624 3027 ;; We are sure both files exist at this point.
fb7933a3
KG
3028 (t
3029 (save-excursion
91879624
KG
3030 ;; We try to get the mtime of both files. If they are not
3031 ;; equal to the "dont-know" value, then we subtract the times
3032 ;; and obtain the result.
3033 (let ((fa1 (file-attributes file1))
3034 (fa2 (file-attributes file2)))
3035 (if (and (not (equal (nth 5 fa1) '(0 0)))
3036 (not (equal (nth 5 fa2) '(0 0))))
01917a18 3037 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
91879624
KG
3038 ;; If one of them is the dont-know value, then we can
3039 ;; still try to run a shell command on the remote host.
3040 ;; However, this only works if both files are Tramp
3041 ;; files and both have the same method, same user, same
3042 ;; host.
00d6fd04
MA
3043 (unless (tramp-equal-remote file1 file2)
3044 (with-parsed-tramp-file-name
3045 (if (tramp-tramp-file-p file1) file1 file2) nil
3046 (tramp-error
3047 v 'file-error
3048 "Files %s and %s must have same method, user, host"
3049 file1 file2)))
3050 (with-parsed-tramp-file-name file1 nil
3051 (zerop (tramp-run-test2
3052 (tramp-get-test-nt-command v) file1 file2)))))))))
fb7933a3
KG
3053
3054;; Functions implemented using the basic functions above.
3055
3056(defun tramp-handle-file-modes (filename)
00d6fd04 3057 "Like `file-modes' for Tramp files."
5da24108
MA
3058 (let ((truename (or (file-truename filename) filename)))
3059 (when (file-exists-p truename)
3060 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
fb7933a3 3061
b86c1cd8
MA
3062(defun tramp-default-file-modes (filename)
3063 "Return file modes of FILENAME as integer.
3064If the file modes of FILENAME cannot be determined, return the
974647ac
MA
3065value of `default-file-modes', without execute permissions."
3066 (or (file-modes filename)
3067 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
b86c1cd8 3068
fb7933a3 3069(defun tramp-handle-file-directory-p (filename)
00d6fd04 3070 "Like `file-directory-p' for Tramp files."
fb7933a3
KG
3071 ;; Care must be taken that this function returns `t' for symlinks
3072 ;; pointing to directories. Surely the most obvious implementation
3073 ;; would be `test -d', but that returns false for such symlinks.
3074 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3075 ;; I now think he's right. So we could be using `test -d', couldn't
3076 ;; we?
3077 ;;
3078 ;; Alternatives: `cd %s', `test -d %s'
c62c9d08 3079 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3080 (with-file-property v localname "file-directory-p"
3081 (zerop (tramp-run-test "-d" filename)))))
fb7933a3
KG
3082
3083(defun tramp-handle-file-regular-p (filename)
00d6fd04
MA
3084 "Like `file-regular-p' for Tramp files."
3085 (and (file-exists-p filename)
3086 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
fb7933a3
KG
3087
3088(defun tramp-handle-file-symlink-p (filename)
00d6fd04 3089 "Like `file-symlink-p' for Tramp files."
c62c9d08 3090 (with-parsed-tramp-file-name filename nil
c951aecb 3091 (let ((x (car (file-attributes filename))))
b25a52cc
KG
3092 (when (stringp x)
3093 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3094 ;; might do weird things.
3095 (if (file-name-absolute-p x)
00d6fd04 3096 (tramp-make-tramp-file-name method user host x)
b25a52cc 3097 x)))))
fb7933a3
KG
3098
3099(defun tramp-handle-file-writable-p (filename)
00d6fd04 3100 "Like `file-writable-p' for Tramp files."
c62c9d08 3101 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3102 (with-file-property v localname "file-writable-p"
3103 (if (file-exists-p filename)
293c24f9
MA
3104 ;; Examine `file-attributes' cache to see if request can be
3105 ;; satisfied without remote operation.
3106 (or (tramp-check-cached-permissions v ?w)
3107 (zerop (tramp-run-test "-w" filename)))
00d6fd04
MA
3108 ;; If file doesn't exist, check if directory is writable.
3109 (and (zerop (tramp-run-test
3110 "-d" (file-name-directory filename)))
3111 (zerop (tramp-run-test
3112 "-w" (file-name-directory filename))))))))
fb7933a3
KG
3113
3114(defun tramp-handle-file-ownership-preserved-p (filename)
00d6fd04 3115 "Like `file-ownership-preserved-p' for Tramp files."
c62c9d08 3116 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3117 (with-file-property v localname "file-ownership-preserved-p"
3118 (let ((attributes (file-attributes filename)))
3119 ;; Return t if the file doesn't exist, since it's true that no
3120 ;; information would be lost by an (attempted) delete and create.
3121 (or (null attributes)
3122 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
fb7933a3
KG
3123
3124;; Other file name ops.
3125
fb7933a3 3126(defun tramp-handle-directory-file-name (directory)
00d6fd04 3127 "Like `directory-file-name' for Tramp files."
7432277c
KG
3128 ;; If localname component of filename is "/", leave it unchanged.
3129 ;; Otherwise, remove any trailing slash from localname component.
8daea7fc
KG
3130 ;; Method, host, etc, are unchanged. Does it make sense to try
3131 ;; to avoid parsing the filename?
c62c9d08 3132 (with-parsed-tramp-file-name directory nil
7432277c
KG
3133 (if (and (not (zerop (length localname)))
3134 (eq (aref localname (1- (length localname))) ?/)
3135 (not (string= localname "/")))
8daea7fc
KG
3136 (substring directory 0 -1)
3137 directory)))
fb7933a3
KG
3138
3139;; Directory listings.
3140
00d6fd04
MA
3141(defun tramp-handle-directory-files
3142 (directory &optional full match nosort files-only)
3143 "Like `directory-files' for Tramp files."
3144 ;; FILES-ONLY is valid for XEmacs only.
3145 (when (file-directory-p directory)
73a37a69 3146 (setq directory (file-name-as-directory (expand-file-name directory)))
00d6fd04
MA
3147 (let ((temp (nreverse (file-name-all-completions "" directory)))
3148 result item)
3149
3150 (while temp
3151 (setq item (directory-file-name (pop temp)))
3152 (when (and (or (null match) (string-match match item))
3153 (or (null files-only)
73a37a69 3154 ;; Files only.
00d6fd04 3155 (and (equal files-only t) (file-regular-p item))
73a37a69 3156 ;; Directories only.
00d6fd04 3157 (file-directory-p item)))
73a37a69 3158 (push (if full (concat directory item) item)
00d6fd04 3159 result)))
73a37a69 3160 (if nosort result (sort result 'string<)))))
c62c9d08 3161
c82c5727
LH
3162(defun tramp-handle-directory-files-and-attributes
3163 (directory &optional full match nosort id-format)
00d6fd04
MA
3164 "Like `directory-files-and-attributes' for Tramp files."
3165 (unless id-format (setq id-format 'integer))
3166 (when (file-directory-p directory)
3167 (setq directory (expand-file-name directory))
3168 (let* ((temp
b533bc97 3169 (copy-tree
00d6fd04
MA
3170 (with-parsed-tramp-file-name directory nil
3171 (with-file-property
3172 v localname
3173 (format "directory-files-and-attributes-%s" id-format)
3174 (save-excursion
3175 (mapcar
aa485f7c
MA
3176 (lambda (x)
3177 (cons (car x)
3178 (tramp-convert-file-attributes v (cdr x))))
7f49fe46
MA
3179 (cond
3180 ((tramp-get-remote-stat v)
3181 (tramp-do-directory-files-and-attributes-with-stat
3182 v localname id-format))
3183 ((tramp-get-remote-perl v)
3184 (tramp-do-directory-files-and-attributes-with-perl
3185 v localname id-format)))))))))
00d6fd04
MA
3186 result item)
3187
3188 (while temp
3189 (setq item (pop temp))
3190 (when (or (null match) (string-match match (car item)))
3191 (when full
3192 (setcar item (expand-file-name (car item) directory)))
3193 (push item result)))
3194
3195 (if nosort
3196 result
3197 (sort result (lambda (x y) (string< (car x) (car y))))))))
3198
7f49fe46 3199(defun tramp-do-directory-files-and-attributes-with-perl
00d6fd04
MA
3200 (vec localname &optional id-format)
3201 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3202 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3203 (tramp-maybe-send-script
3204 vec tramp-perl-directory-files-and-attributes
3205 "tramp_perl_directory_files_and_attributes")
3206 (let ((object
3207 (tramp-send-command-and-read
3208 vec
3209 (format "tramp_perl_directory_files_and_attributes %s %s"
3210 (tramp-shell-quote-argument localname) id-format))))
3211 (when (stringp object) (tramp-error vec 'file-error object))
3212 object))
3213
7f49fe46 3214(defun tramp-do-directory-files-and-attributes-with-stat
00d6fd04
MA
3215 (vec localname &optional id-format)
3216 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3217 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3218 (tramp-send-command-and-read
3219 vec
3220 (format
3221 (concat
70c11b0b
MA
3222 ;; We must care about filenames with spaces, or starting with
3223 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3224 ;; but it does not work on all remote systems. Therefore, we
3225 ;; quote the filenames via sed.
3226 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
d4443a0d 3227 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
00d6fd04
MA
3228 "echo \")\"")
3229 (tramp-shell-quote-argument localname)
3230 (tramp-get-ls-command vec)
3231 (tramp-get-remote-stat vec)
3232 (if (eq id-format 'integer) "%u" "\"%U\"")
3233 (if (eq id-format 'integer) "%g" "\"%G\""))))
c82c5727 3234
c62c9d08 3235;; This function should return "foo/" for directories and "bar" for
00d6fd04 3236;; files.
c62c9d08 3237(defun tramp-handle-file-name-all-completions (filename directory)
00d6fd04
MA
3238 "Like `file-name-all-completions' for Tramp files."
3239 (unless (save-match-data (string-match "/" filename))
9c13938d 3240 (with-parsed-tramp-file-name (expand-file-name directory) nil
b50dd0d2 3241
00d6fd04
MA
3242 (all-completions
3243 filename
3244 (mapcar
3245 'list
293c24f9
MA
3246 (or
3247 ;; Try cache first
3248 (and
3249 ;; Ignore if expired
3250 (or (not (integerp tramp-completion-reread-directory-timeout))
3251 (<= (tramp-time-diff
3252 (current-time)
3253 (tramp-get-file-property
3254 v localname "last-completion" '(0 0 0)))
3255 tramp-completion-reread-directory-timeout))
3256
3257 ;; Try cache entries for filename, filename with last
3258 ;; character removed, filename with last two characters
3259 ;; removed, ..., and finally the empty string - all
3260 ;; concatenated to the local directory name
3261
3262 ;; This is inefficient for very long filenames, pity
3263 ;; `reduce' is not available...
3264 (car
3265 (apply
3266 'append
3267 (mapcar
3268 (lambda (x)
3269 (let ((cache-hit
3270 (tramp-get-file-property
3271 v
3272 (concat localname (substring filename 0 x))
3273 "file-name-all-completions"
3274 nil)))
3275 (when cache-hit (list cache-hit))))
3276 (tramp-compat-number-sequence (length filename) 0 -1)))))
3277
3278 ;; Cache expired or no matching cache entry found so we need
3279 ;; to perform a remote operation
3280 (let (result)
3281 ;; Get a list of directories and files, including reliably
3282 ;; tagging the directories with a trailing '/'. Because I
3283 ;; rock. --daniel@danann.net
3284
3285 ;; Changed to perform `cd' in the same remote op and only
3286 ;; get entries starting with `filename'. Capture any `cd'
3287 ;; error messages. Ensure any `cd' and `echo' aliases are
3288 ;; ignored.
3289 (tramp-send-command
3290 v
3291 (if (tramp-get-remote-perl v)
3292 (progn
3293 (tramp-maybe-send-script
3294 v tramp-perl-file-name-all-completions
3295 "tramp_perl_file_name_all_completions")
3296 (format "tramp_perl_file_name_all_completions %s %s %d"
3297 (tramp-shell-quote-argument localname)
3298 (tramp-shell-quote-argument filename)
3299 (if (symbol-value
b533bc97
MA
3300 ;; `read-file-name-completion-ignore-case'
3301 ;; is introduced with Emacs 22.1.
3302 (if (boundp
3303 'read-file-name-completion-ignore-case)
3304 'read-file-name-completion-ignore-case
3305 'completion-ignore-case))
293c24f9
MA
3306 1 0)))
3307
3308 (format (concat
3309 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3310 ;; `ls' with wildcard might fail with `Argument
3311 ;; list too long' error in some corner cases; if
3312 ;; `ls' fails after `cd' succeeded, chances are
3313 ;; that's the case, so let's retry without
3314 ;; wildcard. This will return "too many" entries
3315 ;; but that isn't harmful.
3316 " || %s -a 2>/dev/null)"
3317 " | while read f; do"
3318 " if %s -d \"$f\" 2>/dev/null;"
3319 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3320 " && \\echo ok) || \\echo fail")
3321 (tramp-shell-quote-argument localname)
3322 (tramp-get-ls-command v)
3323 ;; When `filename' is empty, just `ls' without
3324 ;; filename argument is more efficient than `ls *'
3325 ;; for very large directories and might avoid the
3326 ;; `Argument list too long' error.
3327 ;;
3328 ;; With and only with wildcard, we need to add
3329 ;; `-d' to prevent `ls' from descending into
3330 ;; sub-directories.
3331 (if (zerop (length filename))
3332 "."
3333 (concat (tramp-shell-quote-argument filename) "* -d"))
3334 (tramp-get-ls-command v)
3335 (tramp-get-test-command v))))
3336
3337 ;; Now grab the output.
3338 (with-current-buffer (tramp-get-buffer v)
3339 (goto-char (point-max))
3340
3341 ;; Check result code, found in last line of output
3342 (forward-line -1)
3343 (if (looking-at "^fail$")
3344 (progn
3345 ;; Grab error message from line before last line
3346 ;; (it was put there by `cd 2>&1')
3347 (forward-line -1)
3348 (tramp-error
3349 v 'file-error
3350 "tramp-handle-file-name-all-completions: %s"
3351 (buffer-substring
3352 (point) (tramp-compat-line-end-position))))
3353 ;; For peace of mind, if buffer doesn't end in `fail'
3354 ;; then it should end in `ok'. If neither are in the
3355 ;; buffer something went seriously wrong on the remote
3356 ;; side.
3357 (unless (looking-at "^ok$")
3358 (tramp-error
3359 v 'file-error
3360 "\
3361tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3362 (tramp-shell-quote-argument localname) (buffer-string))))
3363
3364 (while (zerop (forward-line -1))
3365 (push (buffer-substring
3366 (point) (tramp-compat-line-end-position))
3367 result)))
3368
3369 ;; Because the remote op went through OK we know the
3370 ;; directory we `cd'-ed to exists
3371 (tramp-set-file-property
3372 v localname "file-exists-p" t)
3373
3374 ;; Because the remote op went through OK we know every
3375 ;; file listed by `ls' exists.
3376 (mapc (lambda (entry)
3377 (tramp-set-file-property
3378 v (concat localname entry) "file-exists-p" t))
3379 result)
3380
3381 (tramp-set-file-property
3382 v localname "last-completion" (current-time))
3383
3384 ;; Store result in the cache
3385 (tramp-set-file-property
3386 v (concat localname filename)
3387 "file-name-all-completions"
3388 result))))))))
fb7933a3 3389
e1e17cae
MA
3390(defun tramp-handle-file-name-completion
3391 (filename directory &optional predicate)
00d6fd04 3392 "Like `file-name-completion' for Tramp files."
fb7933a3
KG
3393 (unless (tramp-tramp-file-p directory)
3394 (error
3395 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3396 directory))
83e20b5c
MA
3397 (try-completion
3398 filename
3399 (mapcar 'list (file-name-all-completions filename directory))
3400 (when predicate
3401 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
fb7933a3
KG
3402
3403;; cp, mv and ln
3404
3405(defun tramp-handle-add-name-to-file
3406 (filename newname &optional ok-if-already-exists)
00d6fd04
MA
3407 "Like `add-name-to-file' for Tramp files."
3408 (unless (tramp-equal-remote filename newname)
3409 (with-parsed-tramp-file-name
3410 (if (tramp-tramp-file-p filename) filename newname) nil
3411 (tramp-error
3412 v 'file-error
3413 "add-name-to-file: %s"
3414 "only implemented for same method, same user, same host")))
c62c9d08
KG
3415 (with-parsed-tramp-file-name filename v1
3416 (with-parsed-tramp-file-name newname v2
00d6fd04 3417 (let ((ln (when v1 (tramp-get-remote-ln v1))))
c62c9d08
KG
3418 (when (and (not ok-if-already-exists)
3419 (file-exists-p newname)
3420 (not (numberp ok-if-already-exists))
3421 (y-or-n-p
3422 (format
3423 "File %s already exists; make it a new name anyway? "
3424 newname)))
00d6fd04
MA
3425 (tramp-error
3426 v2 'file-error
3427 "add-name-to-file: file %s already exists" newname))
aac0b0f2 3428 (tramp-flush-file-property v2 (file-name-directory v2-localname))
00d6fd04 3429 (tramp-flush-file-property v2 v2-localname)
c62c9d08 3430 (tramp-barf-unless-okay
00d6fd04 3431 v1
7432277c
KG
3432 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3433 (tramp-shell-quote-argument v2-localname))
c62c9d08
KG
3434 "error with add-name-to-file, see buffer `%s' for details"
3435 (buffer-name))))))
fb7933a3
KG
3436
3437(defun tramp-handle-copy-file
8d60099b 3438 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
00d6fd04 3439 "Like `copy-file' for Tramp files."
fb7933a3 3440 ;; Check if both files are local -- invoke normal copy-file.
9e6ab520 3441 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3442 (setq filename (expand-file-name filename))
3443 (setq newname (expand-file-name newname))
9e6ab520 3444 (cond
a4aeb9a4 3445 ;; At least one file a Tramp file?
9e6ab520
MA
3446 ((or (tramp-tramp-file-p filename)
3447 (tramp-tramp-file-p newname))
3448 (tramp-do-copy-or-rename-file
3449 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3450 ;; Compat section.
3451 (preserve-uid-gid
fb7933a3 3452 (tramp-run-real-handler
8d60099b 3453 'copy-file
9e6ab520
MA
3454 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3455 (t
3456 (tramp-run-real-handler
3457 'copy-file (list filename newname ok-if-already-exists keep-date)))))
fb7933a3 3458
263c02ef
MA
3459(defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3460 "Like `copy-directory' for Tramp files."
3461 (let ((t1 (tramp-tramp-file-p dirname))
3462 (t2 (tramp-tramp-file-p newname)))
3463 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3464 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3465 ;; When DIRNAME and NEWNAME are remote, they must have
3466 ;; the same method.
3467 (or (null t1) (null t2)
b000a6e2
MA
3468 (string-equal
3469 (tramp-file-name-method (tramp-dissect-file-name dirname))
3470 (tramp-file-name-method (tramp-dissect-file-name newname)))))
263c02ef
MA
3471 ;; scp or rsync DTRT.
3472 (progn
3473 (setq dirname (directory-file-name (expand-file-name dirname))
3474 newname (directory-file-name (expand-file-name newname)))
3475 (if (and (file-directory-p newname)
3476 (not (string-equal (file-name-nondirectory dirname)
3477 (file-name-nondirectory newname))))
3478 (setq newname
3479 (expand-file-name
3480 (file-name-nondirectory dirname) newname)))
3481 (if (not (file-directory-p (file-name-directory newname)))
3482 (make-directory (file-name-directory newname) parents))
3483 (tramp-do-copy-or-rename-file-out-of-band
3484 'copy dirname newname keep-date))
3485 ;; We must do it file-wise.
3486 (tramp-run-real-handler
aac0b0f2
MA
3487 'copy-directory (list dirname newname keep-date parents)))
3488
3489 ;; When newname did exist, we have wrong cached values.
3490 (when t2
3491 (with-parsed-tramp-file-name newname nil
3492 (tramp-flush-file-property v (file-name-directory localname))
3493 (tramp-flush-file-property v localname))))))
263c02ef 3494
fb7933a3
KG
3495(defun tramp-handle-rename-file
3496 (filename newname &optional ok-if-already-exists)
00d6fd04 3497 "Like `rename-file' for Tramp files."
fb7933a3 3498 ;; Check if both files are local -- invoke normal rename-file.
a4aeb9a4 3499 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3500 (setq filename (expand-file-name filename))
3501 (setq newname (expand-file-name newname))
a4aeb9a4 3502 ;; At least one file a Tramp file?
fb7933a3
KG
3503 (if (or (tramp-tramp-file-p filename)
3504 (tramp-tramp-file-p newname))
3505 (tramp-do-copy-or-rename-file
8d60099b 3506 'rename filename newname ok-if-already-exists t t)
00d6fd04
MA
3507 (tramp-run-real-handler
3508 'rename-file (list filename newname ok-if-already-exists))))
fb7933a3
KG
3509
3510(defun tramp-do-copy-or-rename-file
8d60099b 3511 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3512 "Copy or rename a remote file.
3513OP must be `copy' or `rename' and indicates the operation to perform.
3514FILENAME specifies the file to copy or rename, NEWNAME is the name of
3515the new file (for copy) or the new name of the file (for rename).
3516OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3517KEEP-DATE means to make sure that NEWNAME has the same timestamp
8d60099b
MA
3518as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3519the uid and gid if both files are on the same host.
fb7933a3
KG
3520
3521This function is invoked by `tramp-handle-copy-file' and
3522`tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3523and `rename'. FILENAME and NEWNAME must be absolute file names."
3524 (unless (memq op '(copy rename))
3525 (error "Unknown operation `%s', must be `copy' or `rename'" op))
90dc758d 3526 (let ((t1 (tramp-tramp-file-p filename))
b6bbb65e
MA
3527 (t2 (tramp-tramp-file-p newname))
3528 pr tm)
5ec2cc41 3529
da1975d7
MA
3530 (when (and (not ok-if-already-exists) (file-exists-p newname))
3531 (with-parsed-tramp-file-name (if t1 filename newname) nil
3532 (tramp-error
3533 v 'file-already-exists "File %s already exists" newname)))
5ec2cc41 3534
905fb90e
MA
3535 (with-parsed-tramp-file-name (if t1 filename newname) nil
3536 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3537
b6bbb65e
MA
3538 ;; We start a pulsing progress reporter. Introduced in Emacs 24.1.
3539 (when (> (nth 7 (file-attributes filename)) tramp-copy-size-limit)
3540 (condition-case nil
3541 (setq pr (funcall
3542 'make-progress-reporter
3543 (format "Transferring %s to %s..." filename newname))
3544 tm (run-at-time 0 0.1 'progress-reporter-update pr))
3545 (error nil)))
3546
3547 (unwind-protect
00d6fd04
MA
3548 (cond
3549 ;; Both are Tramp files.
3550 ((and t1 t2)
3551 (with-parsed-tramp-file-name filename v1
3552 (with-parsed-tramp-file-name newname v2
3553 (cond
3554 ;; Shortcut: if method, host, user are the same for both
3555 ;; files, we invoke `cp' or `mv' on the remote host
3556 ;; directly.
3557 ((tramp-equal-remote filename newname)
3558 (tramp-do-copy-or-rename-file-directly
8d60099b
MA
3559 op filename newname
3560 ok-if-already-exists keep-date preserve-uid-gid))
3561
905fb90e 3562 ;; Try out-of-band operation.
7f49fe46
MA
3563 ((tramp-method-out-of-band-p
3564 v1 (nth 7 (file-attributes filename)))
00d6fd04
MA
3565 (tramp-do-copy-or-rename-file-out-of-band
3566 op filename newname keep-date))
8d60099b 3567
00d6fd04
MA
3568 ;; No shortcut was possible. So we copy the
3569 ;; file first. If the operation was `rename', we go
3570 ;; back and delete the original file (if the copy was
3571 ;; successful). The approach is simple-minded: we
3572 ;; create a new buffer, insert the contents of the
3573 ;; source file into it, then write out the buffer to
3574 ;; the target file. The advantage is that it doesn't
3575 ;; matter which filename handlers are used for the
3576 ;; source and target file.
3577 (t
3578 (tramp-do-copy-or-rename-file-via-buffer
3579 op filename newname keep-date))))))
3580
3581 ;; One file is a Tramp file, the other one is local.
3582 ((or t1 t2)
3583 (with-parsed-tramp-file-name (if t1 filename newname) nil
8d60099b
MA
3584 (cond
3585 ;; Fast track on local machine.
3586 ((tramp-local-host-p v)
3587 (tramp-do-copy-or-rename-file-directly
3588 op filename newname
3589 ok-if-already-exists keep-date preserve-uid-gid))
3590
3591 ;; If the Tramp file has an out-of-band method, the corresponding
3592 ;; copy-program can be invoked.
7f49fe46 3593 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
8d60099b
MA
3594 (tramp-do-copy-or-rename-file-out-of-band
3595 op filename newname keep-date))
3596
3597 ;; Use the inline method via a Tramp buffer.
3598 (t (tramp-do-copy-or-rename-file-via-buffer
3599 op filename newname keep-date)))))
00d6fd04
MA
3600
3601 (t
3602 ;; One of them must be a Tramp file.
3603 (error "Tramp implementation says this cannot happen")))
8d60099b 3604
484ea0b6
MA
3605 ;; In case of `rename', we must flush the cache of the source file.
3606 (when (and t1 (eq op 'rename))
3607 (with-parsed-tramp-file-name filename nil
aac0b0f2 3608 (tramp-flush-file-property v (file-name-directory localname))
484ea0b6
MA
3609 (tramp-flush-file-property v localname)))
3610
00d6fd04
MA
3611 ;; When newname did exist, we have wrong cached values.
3612 (when t2
3613 (with-parsed-tramp-file-name newname nil
aac0b0f2 3614 (tramp-flush-file-property v (file-name-directory localname))
905fb90e
MA
3615 (tramp-flush-file-property v localname)))
3616
b6bbb65e
MA
3617 ;; Stop progress reporter.
3618 (if tm (cancel-timer tm))
905fb90e
MA
3619 (with-parsed-tramp-file-name (if t1 filename newname) nil
3620 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
7432277c 3621
38c65fca 3622(defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
90dc758d
KG
3623 "Use an Emacs buffer to copy or rename a file.
3624First arg OP is either `copy' or `rename' and indicates the operation.
3625FILENAME is the source file, NEWNAME the target file.
3626KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
8a798e41
MA
3627 (with-temp-buffer
3628 ;; We must disable multibyte, because binary data shall not be
3629 ;; converted.
3630 (set-buffer-multibyte nil)
3631 (let ((coding-system-for-read 'binary)
3632 (jka-compr-inhibit t))
3633 (insert-file-contents-literally filename))
3634 ;; We don't want the target file to be compressed, so we let-bind
3635 ;; `jka-compr-inhibit' to t.
3636 (let ((coding-system-for-write 'binary)
3637 (jka-compr-inhibit t))
3638 (write-region (point-min) (point-max) newname)))
3639 ;; KEEP-DATE handling.
3640 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3641 ;; Set the mode.
b86c1cd8 3642 (set-file-modes newname (tramp-default-file-modes filename))
8a798e41
MA
3643 ;; If the operation was `rename', delete the original file.
3644 (unless (eq op 'copy) (delete-file filename)))
fb7933a3
KG
3645
3646(defun tramp-do-copy-or-rename-file-directly
8d60099b 3647 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3648 "Invokes `cp' or `mv' on the remote system.
3649OP must be one of `copy' or `rename', indicating `cp' or `mv',
8d60099b
MA
3650respectively. FILENAME specifies the file to copy or rename,
3651NEWNAME is the name of the new file (for copy) or the new name of
3652the file (for rename). Both files must reside on the same host.
3653KEEP-DATE means to make sure that NEWNAME has the same timestamp
3654as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3655the uid and gid from FILENAME."
8a4438b6 3656 (let ((t1 (tramp-tramp-file-p filename))
4f4126e6
MA
3657 (t2 (tramp-tramp-file-p newname))
3658 (file-times (nth 5 (file-attributes filename)))
3659 (file-modes (tramp-default-file-modes filename)))
8a4438b6
MA
3660 (with-parsed-tramp-file-name (if t1 filename newname) nil
3661 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3662 ((eq op 'copy) "cp -f")
3663 ((eq op 'rename) "mv -f")
3664 (t (tramp-error
3665 v 'file-error
3666 "Unknown operation `%s', must be `copy' or `rename'"
3667 op))))
3668 (localname1
b533bc97
MA
3669 (if t1
3670 (tramp-file-name-handler 'file-remote-p filename 'localname)
3671 filename))
8a4438b6 3672 (localname2
b533bc97
MA
3673 (if t2
3674 (tramp-file-name-handler 'file-remote-p newname 'localname)
3675 newname))
293c24f9
MA
3676 (prefix (file-remote-p (if t1 filename newname)))
3677 cmd-result)
8d60099b 3678
8d60099b 3679 (cond
8a4438b6
MA
3680 ;; Both files are on a remote host, with same user.
3681 ((and t1 t2)
293c24f9
MA
3682 (setq cmd-result
3683 (tramp-send-command-and-check
3684 v
3685 (format "%s %s %s" cmd
3686 (tramp-shell-quote-argument localname1)
3687 (tramp-shell-quote-argument localname2))))
8a4438b6
MA
3688 (with-current-buffer (tramp-get-buffer v)
3689 (goto-char (point-min))
3690 (unless
3691 (or
3692 (and keep-date
3693 ;; Mask cp -f error.
3694 (re-search-forward
3695 tramp-operation-not-permitted-regexp nil t))
293c24f9 3696 (zerop cmd-result))
8a4438b6
MA
3697 (tramp-error-with-buffer
3698 nil v 'file-error
3699 "Copying directly failed, see buffer `%s' for details."
3700 (buffer-name)))))
3701
3702 ;; We are on the local host.
3703 ((or t1 t2)
8d60099b 3704 (cond
8a4438b6 3705 ;; We can do it directly.
87bdd2c7
MA
3706 ((let (file-name-handler-alist)
3707 (and (file-readable-p localname1)
3708 (file-writable-p (file-name-directory localname2))
3709 (or (file-directory-p localname2)
3710 (file-writable-p localname2))))
8d60099b 3711 (if (eq op 'copy)
9e6ab520
MA
3712 (tramp-compat-copy-file
3713 localname1 localname2 ok-if-already-exists
3714 keep-date preserve-uid-gid)
87bdd2c7
MA
3715 (tramp-run-real-handler
3716 'rename-file (list localname1 localname2 ok-if-already-exists))))
8a4438b6
MA
3717
3718 ;; We can do it directly with `tramp-send-command'
946a5aeb
MA
3719 ((and (file-readable-p (concat prefix localname1))
3720 (file-writable-p
3721 (file-name-directory (concat prefix localname2)))
3722 (or (file-directory-p (concat prefix localname2))
3723 (file-writable-p (concat prefix localname2))))
8a4438b6
MA
3724 (tramp-do-copy-or-rename-file-directly
3725 op (concat prefix localname1) (concat prefix localname2)
3726 ok-if-already-exists keep-date t)
3727 ;; We must change the ownership to the local user.
8d60099b 3728 (tramp-set-file-uid-gid
8a4438b6
MA
3729 (concat prefix localname2)
3730 (tramp-get-local-uid 'integer)
3731 (tramp-get-local-gid 'integer)))
8d60099b 3732
8a4438b6
MA
3733 ;; We need a temporary file in between.
3734 (t
2c418c5b
MA
3735 ;; Create the temporary file.
3736 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
917b89a6 3737 (unwind-protect
2c418c5b
MA
3738 (progn
3739 (cond
3740 (t1
917b89a6
MA
3741 (or
3742 (zerop
3743 (tramp-send-command-and-check
3744 v (format
3745 "%s %s %s" cmd
3746 (tramp-shell-quote-argument localname1)
3747 (tramp-shell-quote-argument tmpfile))))
3748 (tramp-error-with-buffer
3749 nil v 'file-error
3750 "Copying directly failed, see buffer `%s' for details."
3751 (tramp-get-buffer v)))
2c418c5b 3752 ;; We must change the ownership as remote user.
917b89a6
MA
3753 ;; Since this does not work reliable, we also
3754 ;; give read permissions.
3755 (set-file-modes
3756 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3757 (tramp-set-file-uid-gid
3758 (concat prefix tmpfile)
3759 (tramp-get-local-uid 'integer)
3760 (tramp-get-local-gid 'integer)))
3761 (t2
3762 (if (eq op 'copy)
3763 (tramp-compat-copy-file
5ab38c3c 3764 localname1 tmpfile t
2c418c5b
MA
3765 keep-date preserve-uid-gid)
3766 (tramp-run-real-handler
3767 'rename-file
5ab38c3c 3768 (list localname1 tmpfile t)))
2c418c5b 3769 ;; We must change the ownership as local user.
917b89a6
MA
3770 ;; Since this does not work reliable, we also
3771 ;; give read permissions.
3772 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3773 (tramp-set-file-uid-gid
3774 tmpfile
3775 (tramp-get-remote-uid v 'integer)
3776 (tramp-get-remote-gid v 'integer))))
3777
3778 ;; Move the temporary file to its destination.
3779 (cond
3780 (t2
917b89a6
MA
3781 (or
3782 (zerop
3783 (tramp-send-command-and-check
3784 v (format
3785 "cp -f -p %s %s"
3786 (tramp-shell-quote-argument tmpfile)
3787 (tramp-shell-quote-argument localname2))))
3788 (tramp-error-with-buffer
3789 nil v 'file-error
3790 "Copying directly failed, see buffer `%s' for details."
3791 (tramp-get-buffer v))))
2c418c5b 3792 (t1
ce2cc728
MA
3793 (tramp-run-real-handler
3794 'rename-file
2c418c5b
MA
3795 (list tmpfile localname2 ok-if-already-exists)))))
3796
917b89a6
MA
3797 ;; Save exit.
3798 (condition-case nil
3799 (delete-file tmpfile)
3800 (error)))))))))
8d60099b
MA
3801
3802 ;; Set the time and mode. Mask possible errors.
8d60099b 3803 (condition-case nil
1f107aed 3804 (when keep-date
4f4126e6
MA
3805 (set-file-times newname file-times)
3806 (set-file-modes newname file-modes))
8d60099b
MA
3807 (error)))))
3808
5ec2cc41 3809(defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
7432277c 3810 "Invoke rcp program to copy.
905fb90e 3811The method used must be an out-of-band method."
38c65fca 3812 (let ((t1 (tramp-tramp-file-p filename))
5ec2cc41 3813 (t2 (tramp-tramp-file-p newname))
946a5aeb 3814 copy-program copy-args copy-env copy-keep-date port spec
00d6fd04
MA
3815 source target)
3816
3817 (with-parsed-tramp-file-name (if t1 filename newname) nil
905fb90e 3818 (if (and t1 t2)
00d6fd04 3819
905fb90e
MA
3820 ;; Both are Tramp files. We shall optimize it, when the
3821 ;; methods for filename and newname are the same.
9cf3544e
MA
3822 (let* ((dir-flag (file-directory-p filename))
3823 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3824 (if dir-flag
3825 (setq tmpfile
3826 (expand-file-name
3827 (file-name-nondirectory newname) tmpfile)))
905fb90e
MA
3828 (unwind-protect
3829 (progn
3830 (tramp-do-copy-or-rename-file-out-of-band
3831 op filename tmpfile keep-date)
3832 (tramp-do-copy-or-rename-file-out-of-band
3833 'rename tmpfile newname keep-date))
3834 ;; Save exit.
3835 (condition-case nil
9cf3544e 3836 (if dir-flag
b533bc97 3837 (tramp-compat-delete-directory
9cf3544e
MA
3838 (expand-file-name ".." tmpfile) 'recursive)
3839 (delete-file tmpfile))
905fb90e
MA
3840 (error))))
3841
3842 ;; Expand hops. Might be necessary for gateway methods.
3843 (setq v (car (tramp-compute-multi-hops v)))
3844 (aset v 3 localname)
3845
3846 ;; Check which ones of source and target are Tramp files.
3847 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
263c02ef
MA
3848 target (funcall
3849 (if (and (file-directory-p filename)
3850 (string-equal
3851 (file-name-nondirectory filename)
3852 (file-name-nondirectory newname)))
3853 'file-name-directory
3854 'identity)
3855 (if t2 (tramp-make-copy-program-file-name v) newname)))
905fb90e
MA
3856
3857 ;; Check for port number. Until now, there's no need for handling
3858 ;; like method, user, host.
3859 (setq host (tramp-file-name-real-host v)
3860 port (tramp-file-name-port v)
3861 port (or (and port (number-to-string port)) ""))
3862
3863 ;; Compose copy command.
b533bc97
MA
3864 (setq spec (format-spec-make
3865 ?h host ?u user ?p port
3866 ?t (tramp-get-connection-property
3867 (tramp-get-connection-process v) "temp-file" "")
3868 ?k (if keep-date " " ""))
905fb90e
MA
3869 copy-program (tramp-get-method-parameter
3870 method 'tramp-copy-program)
3871 copy-keep-date (tramp-get-method-parameter
3872 method 'tramp-copy-keep-date)
3873 copy-args
3874 (delq
3875 nil
3876 (mapcar
aa485f7c
MA
3877 (lambda (x)
3878 (setq
3879 x
3880 ;; " " is indication for keep-date argument.
3881 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3882 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb
MA
3883 (tramp-get-method-parameter method 'tramp-copy-args)))
3884 copy-env
3885 (delq
3886 nil
3887 (mapcar
aa485f7c
MA
3888 (lambda (x)
3889 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3890 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb 3891 (tramp-get-method-parameter method 'tramp-copy-env))))
905fb90e
MA
3892
3893 ;; Check for program.
3894 (when (and (fboundp 'executable-find)
3895 (not (let ((default-directory
3896 (tramp-compat-temporary-file-directory)))
3897 (executable-find copy-program))))
3898 (tramp-error
3899 v 'file-error "Cannot find copy program: %s" copy-program))
00d6fd04 3900
4265deab
MA
3901 ;; Set variables for computing the prompt for reading
3902 ;; password.
3903 (setq tramp-current-method (tramp-file-name-method v)
3904 tramp-current-user (tramp-file-name-user v)
3905 tramp-current-host (tramp-file-name-host v))
3906
905fb90e
MA
3907 (unwind-protect
3908 (with-temp-buffer
3909 ;; The default directory must be remote.
3910 (let ((default-directory
946a5aeb
MA
3911 (file-name-directory (if t1 filename newname)))
3912 (process-environment (copy-sequence process-environment)))
905fb90e
MA
3913 ;; Set the transfer process properties.
3914 (tramp-set-connection-property
3915 v "process-name" (buffer-name (current-buffer)))
3916 (tramp-set-connection-property
3917 v "process-buffer" (current-buffer))
946a5aeb
MA
3918 (while copy-env
3919 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3920 (setenv (pop copy-env) (pop copy-env)))
905fb90e
MA
3921
3922 ;; Use an asynchronous process. By this, password can
3923 ;; be handled. The default directory must be local, in
3924 ;; order to apply the correct `copy-program'. We don't
3925 ;; set a timeout, because the copying of large files can
3926 ;; last longer than 60 secs.
3927 (let ((p (let ((default-directory
3928 (tramp-compat-temporary-file-directory)))
3929 (apply 'start-process
3930 (tramp-get-connection-property
3931 v "process-name" nil)
3932 (tramp-get-connection-property
3933 v "process-buffer" nil)
3934 copy-program
3935 (append copy-args (list source target))))))
3936 (tramp-message
3937 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3938 (tramp-set-process-query-on-exit-flag p nil)
3939 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
00d6fd04 3940
905fb90e
MA
3941 ;; Reset the transfer process properties.
3942 (tramp-set-connection-property v "process-name" nil)
3943 (tramp-set-connection-property v "process-buffer" nil))
00d6fd04 3944
905fb90e
MA
3945 ;; Handle KEEP-DATE argument.
3946 (when (and keep-date (not copy-keep-date))
3947 (set-file-times newname (nth 5 (file-attributes filename))))
01917a18 3948
905fb90e
MA
3949 ;; Set the mode.
3950 (unless (and keep-date copy-keep-date)
459a5f4b
MA
3951 (ignore-errors
3952 (set-file-modes newname (tramp-default-file-modes filename)))))
5ec2cc41 3953
905fb90e
MA
3954 ;; If the operation was `rename', delete the original file.
3955 (unless (eq op 'copy)
aac0b0f2
MA
3956 (if (file-regular-p filename)
3957 (delete-file filename)
b533bc97 3958 (tramp-compat-delete-directory filename 'recursive))))))
7432277c 3959
fb7933a3 3960(defun tramp-handle-make-directory (dir &optional parents)
00d6fd04 3961 "Like `make-directory' for Tramp files."
ac474af1 3962 (setq dir (expand-file-name dir))
c62c9d08 3963 (with-parsed-tramp-file-name dir nil
c15cdf02 3964 (tramp-flush-directory-property v (file-name-directory localname))
b1d06e75
KG
3965 (save-excursion
3966 (tramp-barf-unless-okay
00d6fd04 3967 v
9c13938d 3968 (format "%s %s"
b1d06e75 3969 (if parents "mkdir -p" "mkdir")
7432277c 3970 (tramp-shell-quote-argument localname))
b1d06e75 3971 "Couldn't make directory %s" dir))))
fb7933a3 3972
c15cdf02 3973(defun tramp-handle-delete-directory (directory &optional recursive)
00d6fd04 3974 "Like `delete-directory' for Tramp files."
ac474af1 3975 (setq directory (expand-file-name directory))
c62c9d08 3976 (with-parsed-tramp-file-name directory nil
aac0b0f2 3977 (tramp-flush-file-property v (file-name-directory localname))
00d6fd04
MA
3978 (tramp-flush-directory-property v localname)
3979 (unless (zerop (tramp-send-command-and-check
3980 v
c15cdf02
MA
3981 (format
3982 "%s %s"
3983 (if recursive "rm -rf" "rmdir")
3984 (tramp-shell-quote-argument localname))))
00d6fd04 3985 (tramp-error v 'file-error "Couldn't delete %s" directory))))
fb7933a3
KG
3986
3987(defun tramp-handle-delete-file (filename)
00d6fd04 3988 "Like `delete-file' for Tramp files."
ac474af1 3989 (setq filename (expand-file-name filename))
c62c9d08 3990 (with-parsed-tramp-file-name filename nil
aac0b0f2 3991 (tramp-flush-file-property v (file-name-directory localname))
00d6fd04
MA
3992 (tramp-flush-file-property v localname)
3993 (unless (zerop (tramp-send-command-and-check
3994 v
3995 (format "rm -f %s"
3996 (tramp-shell-quote-argument localname))))
3997 (tramp-error v 'file-error "Couldn't delete %s" filename))))
fb7933a3
KG
3998
3999;; Dired.
4000
4001;; CCC: This does not seem to be enough. Something dies when
a4aeb9a4 4002;; we try and delete two directories under Tramp :/
fb7933a3
KG
4003(defun tramp-handle-dired-recursive-delete-directory (filename)
4004 "Recursively delete the directory given.
00d6fd04 4005This is like `dired-recursive-delete-directory' for Tramp files."
c62c9d08 4006 (with-parsed-tramp-file-name filename nil
00d6fd04 4007 ;; Run a shell command 'rm -r <localname>'
260821d3 4008 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
00d6fd04
MA
4009 (unless (file-exists-p filename)
4010 (tramp-error v 'file-error "No such directory: %s" filename))
fb7933a3 4011 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
00d6fd04
MA
4012 (tramp-send-command
4013 v
9c13938d 4014 (format "rm -rf %s" (tramp-shell-quote-argument localname))
00d6fd04
MA
4015 ;; Don't read the output, do it explicitely.
4016 nil t)
fb7933a3
KG
4017 ;; Wait for the remote system to return to us...
4018 ;; This might take a while, allow it plenty of time.
00d6fd04 4019 (tramp-wait-for-output (tramp-get-connection-process v) 120)
fb7933a3 4020 ;; Make sure that it worked...
aac0b0f2 4021 (tramp-flush-file-property v (file-name-directory localname))
c15cdf02 4022 (tramp-flush-directory-property v localname)
07dfe738 4023 (and (file-exists-p filename)
00d6fd04
MA
4024 (tramp-error
4025 v 'file-error "Failed to recursively delete %s" filename))))
bf247b6e 4026
5ec2cc41 4027(defun tramp-handle-dired-compress-file (file &rest ok-flag)
00d6fd04 4028 "Like `dired-compress-file' for Tramp files."
5ec2cc41
KG
4029 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4030 ;; Code stolen mainly from dired-aux.el.
4031 (with-parsed-tramp-file-name file nil
00d6fd04 4032 (tramp-flush-file-property v localname)
5ec2cc41
KG
4033 (save-excursion
4034 (let ((suffixes
4035 (if (not (featurep 'xemacs))
4036 ;; Emacs case
4037 (symbol-value 'dired-compress-file-suffixes)
4038 ;; XEmacs has `dired-compression-method-alist', which is
4039 ;; transformed into `dired-compress-file-suffixes' structure.
4040 (mapcar
aa485f7c
MA
4041 (lambda (x)
4042 (list (concat (regexp-quote (nth 1 x)) "\\'")
4043 nil
4044 (mapconcat 'identity (nth 3 x) " ")))
5ec2cc41
KG
4045 (symbol-value 'dired-compression-method-alist))))
4046 suffix)
4047 ;; See if any suffix rule matches this file name.
4048 (while suffixes
4049 (let (case-fold-search)
4050 (if (string-match (car (car suffixes)) localname)
4051 (setq suffix (car suffixes) suffixes nil))
4052 (setq suffixes (cdr suffixes))))
4053
4054 (cond ((file-symlink-p file)
4055 nil)
4056 ((and suffix (nth 2 suffix))
4057 ;; We found an uncompression rule.
00d6fd04 4058 (tramp-message v 0 "Uncompressing %s..." file)
5ec2cc41 4059 (when (zerop (tramp-send-command-and-check
b593f105
MA
4060 v (concat (nth 2 suffix) " "
4061 (tramp-shell-quote-argument localname))))
00d6fd04 4062 (tramp-message v 0 "Uncompressing %s...done" file)
38c65fca
KG
4063 ;; `dired-remove-file' is not defined in XEmacs
4064 (funcall (symbol-function 'dired-remove-file) file)
5ec2cc41
KG
4065 (string-match (car suffix) file)
4066 (concat (substring file 0 (match-beginning 0)))))
4067 (t
4068 ;; We don't recognize the file as compressed, so compress it.
4069 ;; Try gzip.
00d6fd04 4070 (tramp-message v 0 "Compressing %s..." file)
5ec2cc41 4071 (when (zerop (tramp-send-command-and-check
b593f105
MA
4072 v (concat "gzip -f "
4073 (tramp-shell-quote-argument localname))))
00d6fd04 4074 (tramp-message v 0 "Compressing %s...done" file)
38c65fca
KG
4075 ;; `dired-remove-file' is not defined in XEmacs
4076 (funcall (symbol-function 'dired-remove-file) file)
5ec2cc41
KG
4077 (cond ((file-exists-p (concat file ".gz"))
4078 (concat file ".gz"))
4079 ((file-exists-p (concat file ".z"))
4080 (concat file ".z"))
4081 (t nil)))))))))
fb7933a3 4082
d5b3979c 4083(defun tramp-handle-dired-uncache (dir &optional dir-p)
70c11b0b 4084 "Like `dired-uncache' for Tramp files."
d5b3979c
MA
4085 ;; DIR-P is valid for XEmacs only.
4086 (with-parsed-tramp-file-name
4087 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
70c11b0b
MA
4088 (tramp-flush-file-property v localname)))
4089
fb7933a3
KG
4090;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4091;; not sure at all that this is the right way to do it, but let's hope
4092;; it works for now, and wait for a guru to point out the Right Way to
4093;; achieve this.
4094;;(eval-when-compile
4095;; (unless (fboundp 'dired-insert-set-properties)
4096;; (fset 'dired-insert-set-properties 'ignore)))
4097;; Gerd suggests this:
4098(eval-when-compile (require 'dired))
4099;; Note that dired is required at run-time, too, when it is needed.
4100;; It is only needed on XEmacs for the function
4101;; `dired-insert-set-properties'.
4102
4103(defun tramp-handle-insert-directory
4104 (filename switches &optional wildcard full-directory-p)
00d6fd04
MA
4105 "Like `insert-directory' for Tramp files."
4106 (setq filename (expand-file-name filename))
4107 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4108 (if (and (featurep 'ls-lisp)
4109 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4110 (tramp-run-real-handler
4111 'insert-directory (list filename switches wildcard full-directory-p))
0c0b61f1
MA
4112 (when (stringp switches)
4113 (setq switches (split-string switches)))
4114 (when (and (member "--dired" switches)
8e754ea2 4115 (not (tramp-get-ls-command-with-dired v)))
0c0b61f1 4116 (setq switches (delete "--dired" switches)))
c82c5727 4117 (when wildcard
87bdd2c7
MA
4118 (setq wildcard (tramp-run-real-handler
4119 'file-name-nondirectory (list localname)))
4120 (setq localname (tramp-run-real-handler
4121 'file-name-directory (list localname))))
c82c5727 4122 (unless full-directory-p
0c0b61f1
MA
4123 (setq switches (add-to-list 'switches "-d" 'append)))
4124 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
c82c5727 4125 (when wildcard
0c0b61f1
MA
4126 (setq switches (concat switches " " wildcard)))
4127 (tramp-message
4128 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4129 switches filename (if wildcard "yes" "no")
4130 (if full-directory-p "yes" "no"))
00d6fd04
MA
4131 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4132 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4133 (if full-directory-p
4134 (tramp-send-command
4135 v
fe5facd3 4136 (format "%s %s %s 2>/dev/null"
00d6fd04
MA
4137 (tramp-get-ls-command v)
4138 switches
4139 (if wildcard
4140 localname
4141 (tramp-shell-quote-argument (concat localname ".")))))
4142 (tramp-barf-unless-okay
4143 v
4144 (format "cd %s" (tramp-shell-quote-argument
87bdd2c7
MA
4145 (tramp-run-real-handler
4146 'file-name-directory (list localname))))
00d6fd04 4147 "Couldn't `cd %s'"
87bdd2c7
MA
4148 (tramp-shell-quote-argument
4149 (tramp-run-real-handler 'file-name-directory (list localname))))
00d6fd04
MA
4150 (tramp-send-command
4151 v
4152 (format "%s %s %s"
4153 (tramp-get-ls-command v)
4154 switches
4155 (if (or wildcard
87bdd2c7
MA
4156 (zerop (length
4157 (tramp-run-real-handler
4158 'file-name-nondirectory (list localname)))))
00d6fd04
MA
4159 ""
4160 (tramp-shell-quote-argument
87bdd2c7
MA
4161 (tramp-run-real-handler
4162 'file-name-nondirectory (list localname)))))))
8e754ea2
MA
4163 (let ((beg (point)))
4164 ;; We cannot use `insert-buffer-substring' because the Tramp
4165 ;; buffer changes its contents before insertion due to calling
4166 ;; `expand-file' and alike.
4167 (insert
4168 (with-current-buffer (tramp-get-buffer v)
4169 (buffer-string)))
4170
4171 ;; Check for "--dired" output.
8e754ea2 4172 (forward-line -2)
7f4d4a97
MA
4173 (when (looking-at "//SUBDIRED//")
4174 (forward-line -1))
8e754ea2 4175 (when (looking-at "//DIRED//")
7ba1d9c2 4176 (let ((end (tramp-compat-line-end-position))
8e754ea2
MA
4177 (linebeg (point)))
4178 ;; Now read the numeric positions of file names.
4179 (goto-char linebeg)
4180 (forward-word 1)
4181 (forward-char 3)
4182 (while (< (point) end)
4183 (let ((start (+ beg (read (current-buffer))))
4184 (end (+ beg (read (current-buffer)))))
7f49fe46 4185 (if (memq (char-after end) '(?\n ?\ ))
8e754ea2 4186 ;; End is followed by \n or by " -> ".
fe5facd3
MA
4187 (put-text-property start end 'dired-filename t))))))
4188 ;; Remove trailing lines.
4189 (goto-char (tramp-compat-line-beginning-position))
4190 (while (looking-at "//")
4191 (forward-line 1)
4192 (delete-region (match-beginning 0) (point)))
0c0b61f1
MA
4193
4194 ;; The inserted file could be from somewhere else.
4195 (when (and (not wildcard) (not full-directory-p))
4196 (goto-char (point-max))
e5c70c41
MA
4197 (when (file-symlink-p filename)
4198 (goto-char (search-backward "->" beg 'noerror)))
0c0b61f1
MA
4199 (search-backward
4200 (if (zerop (length (file-name-nondirectory filename)))
4201 "."
4202 (file-name-nondirectory filename))
4203 beg 'noerror)
4204 (replace-match (file-relative-name filename) t))
4205
fe5facd3 4206 (goto-char (point-max))))))
fb7933a3 4207
fb7933a3 4208(defun tramp-handle-unhandled-file-name-directory (filename)
00d6fd04 4209 "Like `unhandled-file-name-directory' for Tramp files."
8a798e41
MA
4210 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4211 ;; for backward compatibility.
ce3f516f 4212 (expand-file-name "~/"))
fb7933a3
KG
4213
4214;; Canonicalization of file names.
4215
fb7933a3 4216(defun tramp-handle-expand-file-name (name &optional dir)
00d6fd04 4217 "Like `expand-file-name' for Tramp files.
7432277c
KG
4218If the localname part of the given filename starts with \"/../\" then
4219the result will be a local, non-Tramp, filename."
fb7933a3
KG
4220 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4221 (setq dir (or dir default-directory "/"))
4222 ;; Unless NAME is absolute, concat DIR and NAME.
4223 (unless (file-name-absolute-p name)
4224 (setq name (concat (file-name-as-directory dir) name)))
00d6fd04 4225 ;; If NAME is not a Tramp file, run the real handler.
fb7933a3 4226 (if (not (tramp-tramp-file-p name))
00d6fd04 4227 (tramp-run-real-handler 'expand-file-name (list name nil))
fb7933a3 4228 ;; Dissect NAME.
c62c9d08 4229 (with-parsed-tramp-file-name name nil
87bdd2c7 4230 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
7432277c 4231 (setq localname (concat "~/" localname)))
00d6fd04
MA
4232 ;; Tilde expansion if necessary. This needs a shell which
4233 ;; groks tilde expansion! The function `tramp-find-shell' is
4234 ;; supposed to find such a shell on the remote host. Please
4235 ;; tell me about it when this doesn't work on your system.
4236 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4237 (let ((uname (match-string 1 localname))
4238 (fname (match-string 2 localname)))
4239 ;; We cannot simply apply "~/", because under sudo "~/" is
4240 ;; expanded to the local user home directory but to the
4241 ;; root home directory. On the other hand, using always
4242 ;; the default user name for tilde expansion is not
4243 ;; appropriate either, because ssh and companions might
4244 ;; use a user name from the config file.
4245 (when (and (string-equal uname "~")
4246 (string-match "\\`su\\(do\\)?\\'" method))
4247 (setq uname (concat uname user)))
4248 (setq uname
b593f105
MA
4249 (with-connection-property v uname
4250 (tramp-send-command
4251 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4252 (with-current-buffer (tramp-get-buffer v)
4253 (goto-char (point-min))
4254 (buffer-substring
4255 (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
4256 (setq localname (concat uname fname))))
4257 ;; There might be a double slash, for example when "~/"
cb85dcd0 4258 ;; expands to "/". Remove this.
00d6fd04
MA
4259 (while (string-match "//" localname)
4260 (setq localname (replace-match "/" t t localname)))
4261 ;; No tilde characters in file name, do normal
a17632c1
MA
4262 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4263 ;; `directory-sep-char' here for XEmacs on Windows, which would
4264 ;; otherwise use backslash. `default-directory' is bound,
4265 ;; because on Windows there would be problems with UNC shares or
4266 ;; Cygwin mounts.
aff67808
MA
4267 (let ((directory-sep-char ?/)
4268 (default-directory (tramp-compat-temporary-file-directory)))
4269 (tramp-make-tramp-file-name
4270 method user host
4271 (tramp-drop-volume-letter
87bdd2c7
MA
4272 (tramp-run-real-handler
4273 'expand-file-name (list localname))))))))
00d6fd04 4274
c23c3394
MA
4275(defun tramp-replace-environment-variables (filename)
4276 "Replace environment variables in FILENAME.
4277Return the string with the replaced variables."
2e271195 4278 (save-match-data
ec5145d6 4279 (let ((idx (string-match "$\\(\\w+\\)" filename)))
2e271195 4280 ;; `$' is coded as `$$'.
ec5145d6
MA
4281 (when (and idx
4282 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4283 (getenv (match-string 1 filename)))
2e271195
MA
4284 (setq filename
4285 (replace-match
4286 (substitute-in-file-name (match-string 0 filename))
4287 t nil filename)))
4288 filename)))
c23c3394 4289
00d6fd04
MA
4290(defun tramp-handle-substitute-in-file-name (filename)
4291 "Like `substitute-in-file-name' for Tramp files.
4292\"//\" and \"/~\" substitute only in the local filename part.
4293If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4294beginning of local filename are not substituted."
c23c3394
MA
4295 ;; First, we must replace environment variables.
4296 (setq filename (tramp-replace-environment-variables filename))
00d6fd04
MA
4297 (with-parsed-tramp-file-name filename nil
4298 (if (equal tramp-syntax 'url)
4299 ;; We need to check localname only. The other parts cannot contain
4300 ;; "//" or "/~".
4301 (if (and (> (length localname) 1)
4302 (or (string-match "//" localname)
4303 (string-match "/~" localname 1)))
4304 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4305 (tramp-make-tramp-file-name
4306 (when method (substitute-in-file-name method))
4307 (when user (substitute-in-file-name user))
4308 (when host (substitute-in-file-name host))
87bdd2c7
MA
4309 (when localname
4310 (tramp-run-real-handler
4311 'substitute-in-file-name (list localname)))))
00d6fd04
MA
4312 ;; Ignore in LOCALNAME everything before "//" or "/~".
4313 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4314 (setq filename
b08104a0
MA
4315 (concat (file-remote-p filename)
4316 (replace-match "\\1" nil nil localname)))
00d6fd04
MA
4317 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4318 (when (string-match "~$" filename)
4319 (setq filename (concat filename "/"))))
4320 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4321
4322;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4323;; which calls corresponding functions (see minibuf.el).
4324(when (fboundp 'minibuffer-electric-separator)
9e6ab520 4325 (mapc
aa485f7c
MA
4326 (lambda (x)
4327 (eval
4328 `(defadvice ,x
4329 (around ,(intern (format "tramp-advice-%s" x)) activate)
4330 "Invoke `substitute-in-file-name' for Tramp files."
4331 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4332 (tramp-tramp-file-p (buffer-substring)))
4333 ;; We don't need to handle `last-input-event', because
4334 ;; due to the key map we know it must be ?/ or ?~.
4335 (let ((s (concat (buffer-substring (point-min) (point))
4336 (string last-command-char))))
4337 (delete-region (point-min) (point))
4338 (insert (substitute-in-file-name s))
4339 (setq ad-return-value last-command-char))
d7ec1df7
MA
4340 ad-do-it)))
4341 (eval
4342 `(add-hook
4343 'tramp-unload-hook
4344 (lambda ()
4345 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4346 (ad-activate ',x)))))
00d6fd04
MA
4347
4348 '(minibuffer-electric-separator
4349 minibuffer-electric-tilde)))
4350
4351
0664ff72 4352;;; Remote commands:
fb7933a3 4353
00d6fd04
MA
4354(defun tramp-handle-executable-find (command)
4355 "Like `executable-find' for Tramp files."
4356 (with-parsed-tramp-file-name default-directory nil
f84638eb 4357 (tramp-find-executable v command (tramp-get-remote-path v) t)))
00d6fd04
MA
4358
4359;; We use BUFFER also as connection buffer during setup. Because of
4360;; this, its original contents must be saved, and restored once
4361;; connection has been setup.
4362(defun tramp-handle-start-file-process (name buffer program &rest args)
4363 "Like `start-file-process' for Tramp files."
4364 (with-parsed-tramp-file-name default-directory nil
9fb2cdc5
GM
4365 (unless (stringp program)
4366 (tramp-error
4367 v 'file-error "pty association is not supported for `%s'" name))
00d6fd04 4368 (unwind-protect
263c02ef
MA
4369 (let ((command (format "cd %s; exec %s"
4370 (tramp-shell-quote-argument localname)
4371 (mapconcat 'tramp-shell-quote-argument
4372 (cons program args) " ")))
4373 (name1 name)
38d63e6a 4374 (i 0))
2296b54d 4375 (unless buffer
6ce63faf 4376 ;; BUFFER can be nil. We use a temporary buffer.
2296b54d 4377 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
38d63e6a
MA
4378 (while (get-process name1)
4379 ;; NAME must be unique as process name.
4380 (setq i (1+ i)
4381 name1 (format "%s<%d>" name i)))
4382 (setq name name1)
00d6fd04
MA
4383 ;; Set the new process properties.
4384 (tramp-set-connection-property v "process-name" name)
2296b54d 4385 (tramp-set-connection-property v "process-buffer" buffer)
00d6fd04 4386 ;; Activate narrowing in order to save BUFFER contents.
11c71217
MA
4387 ;; Clear also the modification time; otherwise we might be
4388 ;; interrupted by `verify-visited-file-modtime'.
00d6fd04 4389 (with-current-buffer (tramp-get-connection-buffer v)
11c71217 4390 (clear-visited-file-modtime)
00d6fd04 4391 (narrow-to-region (point-max) (point-max)))
263c02ef 4392 ;; Send the command. `tramp-send-command' opens a new
00d6fd04 4393 ;; connection.
263c02ef 4394 (tramp-send-command v command nil t) ; nooutput
6ce63faf
MA
4395 ;; Set query flag for this process.
4396 (tramp-set-process-query-on-exit-flag
4397 (tramp-get-connection-process v) t)
00d6fd04
MA
4398 ;; Return process.
4399 (tramp-get-connection-process v))
4400 ;; Save exit.
ce3f516f 4401 (with-current-buffer (tramp-get-connection-buffer v)
6ce63faf
MA
4402 (if (string-match tramp-temp-buffer-name (buffer-name))
4403 (progn
4404 (set-process-buffer (tramp-get-connection-process v) nil)
4405 (kill-buffer (current-buffer)))
4406 (widen)
4407 (goto-char (point-max))))
00d6fd04
MA
4408 (tramp-set-connection-property v "process-name" nil)
4409 (tramp-set-connection-property v "process-buffer" nil))))
4410
4411(defun tramp-handle-process-file
4412 (program &optional infile destination display &rest args)
4413 "Like `process-file' for Tramp files."
4414 ;; The implementation is not complete yet.
4415 (when (and (numberp destination) (zerop destination))
4416 (error "Implementation does not handle immediate return"))
4417
4418 (with-parsed-tramp-file-name default-directory nil
a6e96327 4419 (let (command input tmpinput stderr tmpstderr outbuf ret)
00d6fd04
MA
4420 ;; Compute command.
4421 (setq command (mapconcat 'tramp-shell-quote-argument
4422 (cons program args) " "))
4423 ;; Determine input.
4424 (if (null infile)
4425 (setq input "/dev/null")
4426 (setq infile (expand-file-name infile))
4427 (if (tramp-equal-remote default-directory infile)
4428 ;; INFILE is on the same remote host.
4429 (setq input (with-parsed-tramp-file-name infile nil localname))
4430 ;; INFILE must be copied to remote host.
a6e96327
MA
4431 (setq input (tramp-make-tramp-temp-file v)
4432 tmpinput (tramp-make-tramp-file-name method user host input))
4433 (copy-file infile tmpinput t)))
00d6fd04
MA
4434 (when input (setq command (format "%s <%s" command input)))
4435
4436 ;; Determine output.
4437 (cond
bede3e9f 4438 ;; Just a buffer.
00d6fd04
MA
4439 ((bufferp destination)
4440 (setq outbuf destination))
bede3e9f 4441 ;; A buffer name.
00d6fd04
MA
4442 ((stringp destination)
4443 (setq outbuf (get-buffer-create destination)))
4444 ;; (REAL-DESTINATION ERROR-DESTINATION)
4445 ((consp destination)
bede3e9f 4446 ;; output.
00d6fd04
MA
4447 (cond
4448 ((bufferp (car destination))
4449 (setq outbuf (car destination)))
4450 ((stringp (car destination))
0664ff72
MA
4451 (setq outbuf (get-buffer-create (car destination))))
4452 ((car destination)
4453 (setq outbuf (current-buffer))))
bede3e9f 4454 ;; stderr.
00d6fd04
MA
4455 (cond
4456 ((stringp (cadr destination))
4457 (setcar (cdr destination) (expand-file-name (cadr destination)))
4458 (if (tramp-equal-remote default-directory (cadr destination))
4459 ;; stderr is on the same remote host.
4460 (setq stderr (with-parsed-tramp-file-name
4461 (cadr destination) nil localname))
4462 ;; stderr must be copied to remote host. The temporary
4463 ;; file must be deleted after execution.
a6e96327
MA
4464 (setq stderr (tramp-make-tramp-temp-file v)
4465 tmpstderr (tramp-make-tramp-file-name
4466 method user host stderr))))
bede3e9f 4467 ;; stderr to be discarded.
00d6fd04
MA
4468 ((null (cadr destination))
4469 (setq stderr "/dev/null"))))
4470 ;; 't
4471 (destination
4472 (setq outbuf (current-buffer))))
4473 (when stderr (setq command (format "%s 2>%s" command stderr)))
4474
00d6fd04
MA
4475 ;; Send the command. It might not return in time, so we protect it.
4476 (condition-case nil
4477 (unwind-protect
293c24f9
MA
4478 (setq ret
4479 (tramp-send-command-and-check
4480 v (format "\\cd %s; %s"
4481 (tramp-shell-quote-argument localname)
b593f105
MA
4482 command)
4483 nil t))
00d6fd04
MA
4484 ;; We should show the output anyway.
4485 (when outbuf
293c24f9
MA
4486 (with-current-buffer outbuf
4487 (insert
4488 (with-current-buffer (tramp-get-connection-buffer v)
4489 (buffer-string))))
00d6fd04 4490 (when display (display-buffer outbuf))))
260821d3
MA
4491 ;; When the user did interrupt, we should do it also. We use
4492 ;; return code -1 as marker.
4493 (quit
4494 (kill-buffer (tramp-get-connection-buffer v))
4495 (setq ret -1))
4496 ;; Handle errors.
00d6fd04
MA
4497 (error
4498 (kill-buffer (tramp-get-connection-buffer v))
4499 (setq ret 1)))
a6e96327 4500
a6e96327
MA
4501 ;; Provide error file.
4502 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
263c02ef 4503
260821d3
MA
4504 ;; Cleanup. We remove all file cache values for the connection,
4505 ;; because the remote process could have changed them.
a6e96327 4506 (when tmpinput (delete-file tmpinput))
946a5aeb
MA
4507
4508 ;; `process-file-side-effects' has been introduced with GNU
4509 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4510 ;; by `program'. If it doesn't exist, we assume its default
4511 ;; value 't'.
4512 (unless (and (boundp 'process-file-side-effects)
4513 (not (symbol-value 'process-file-side-effects)))
4514 (tramp-flush-directory-property v ""))
4515
00d6fd04 4516 ;; Return exit status.
260821d3
MA
4517 (if (equal ret -1)
4518 (keyboard-quit)
4519 ret))))
00d6fd04 4520
a4aeb9a4
MA
4521(defun tramp-local-call-process
4522 (program &optional infile destination display &rest args)
4523 "Calls `call-process' on the local host.
4524This is needed because for some Emacs flavors Tramp has
4525defadviced `call-process' to behave like `process-file'. The
4526Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4527 (let ((default-directory
4528 (if (file-remote-p default-directory)
4529 (tramp-compat-temporary-file-directory)
4530 default-directory)))
4531 (if (executable-find program)
4532 (apply 'call-process program infile destination display args)
4533 1)))
4534
00d6fd04
MA
4535(defun tramp-handle-call-process-region
4536 (start end program &optional delete buffer display &rest args)
4537 "Like `call-process-region' for Tramp files."
258800f8 4538 (let ((tmpfile (tramp-compat-make-temp-file "")))
00d6fd04
MA
4539 (write-region start end tmpfile)
4540 (when delete (delete-region start end))
4541 (unwind-protect
4542 (apply 'call-process program tmpfile buffer display args)
4543 (delete-file tmpfile))))
4544
4545(defun tramp-handle-shell-command
4546 (command &optional output-buffer error-buffer)
4547 "Like `shell-command' for Tramp files."
ce3f516f 4548 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
b8bfcf96
MA
4549 ;; We cannot use `shell-file-name' and `shell-command-switch',
4550 ;; they are variables of the local host.
4551 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
5d2ebd96 4552 current-buffer-p
ce3f516f 4553 (output-buffer
27e813fe
MA
4554 (cond
4555 ((bufferp output-buffer) output-buffer)
4556 ((stringp output-buffer) (get-buffer-create output-buffer))
5d2ebd96
AS
4557 (output-buffer
4558 (setq current-buffer-p t)
4559 (current-buffer))
42bc9b6d 4560 (t (get-buffer-create
27e813fe
MA
4561 (if asynchronous
4562 "*Async Shell Command*"
4563 "*Shell Command Output*")))))
4564 (error-buffer
4565 (cond
4566 ((bufferp error-buffer) error-buffer)
4567 ((stringp error-buffer) (get-buffer-create error-buffer))))
ce3f516f 4568 (buffer
27e813fe 4569 (if (and (not asynchronous) error-buffer)
ce3f516f
MA
4570 (with-parsed-tramp-file-name default-directory nil
4571 (list output-buffer (tramp-make-tramp-temp-file v)))
42bc9b6d 4572 output-buffer))
cfb5c0db 4573 (p (get-buffer-process output-buffer)))
42bc9b6d
MA
4574
4575 ;; Check whether there is another process running. Tramp does not
4576 ;; support 2 (asynchronous) processes in parallel.
cfb5c0db 4577 (when p
42bc9b6d 4578 (if (yes-or-no-p "A command is running. Kill it? ")
699a11fb
GM
4579 (condition-case nil
4580 (kill-process p)
4581 (error nil))
42bc9b6d
MA
4582 (error "Shell command in progress")))
4583
f34db316
AS
4584 (if current-buffer-p
4585 (progn
4586 (barf-if-buffer-read-only)
4587 (push-mark nil t))
5d2ebd96
AS
4588 (with-current-buffer output-buffer
4589 (setq buffer-read-only nil)
4590 (erase-buffer)))
42bc9b6d 4591
5d2ebd96 4592 (if (and (not current-buffer-p) (integerp asynchronous))
42bc9b6d
MA
4593 (prog1
4594 ;; Run the process.
3412f35d 4595 (apply 'start-file-process "*Async Shell*" buffer args)
42bc9b6d 4596 ;; Display output.
cfb5c0db
MA
4597 (pop-to-buffer output-buffer)
4598 (setq mode-line-process '(":%s"))
4599 (require 'shell) (shell-mode))
42bc9b6d
MA
4600
4601 (prog1
4602 ;; Run the process.
4603 (apply 'process-file (car args) nil buffer nil (cdr args))
4604 ;; Insert error messages if they were separated.
4605 (when (listp buffer)
4606 (with-current-buffer error-buffer
4607 (insert-file-contents (cadr buffer)))
4608 (delete-file (cadr buffer)))
f34db316
AS
4609 (if current-buffer-p
4610 ;; This is like exchange-point-and-mark, but doesn't
4611 ;; activate the mark. It is cleaner to avoid activation,
4612 ;; even though the command loop would deactivate the mark
4613 ;; because we inserted text.
4614 (goto-char (prog1 (mark t)
4615 (set-marker (mark-marker) (point)
4616 (current-buffer))))
4617 ;; There's some output, display it.
4618 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4619 (if (functionp 'display-message-or-buffer)
4620 (funcall (symbol-function 'display-message-or-buffer)
4621 output-buffer)
4622 (pop-to-buffer output-buffer))))))))
00d6fd04
MA
4623
4624;; File Editing.
4625
4626(defvar tramp-handle-file-local-copy-hook nil
4627 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4628
fb7933a3 4629(defun tramp-handle-file-local-copy (filename)
00d6fd04 4630 "Like `file-local-copy' for Tramp files."
0f205eee 4631
c62c9d08 4632 (with-parsed-tramp-file-name filename nil
2988341a
MA
4633 (unless (file-exists-p filename)
4634 (tramp-error
4635 v 'file-error
4636 "Cannot make local copy of non-existing file `%s'" filename))
4637
0f205eee 4638 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
00d6fd04 4639 (loc-dec (tramp-get-local-coding v "local-decoding"))
258800f8 4640 (tmpfile (tramp-compat-make-temp-file filename)))
5ec2cc41 4641
2988341a
MA
4642 (condition-case err
4643 (cond
4644 ;; `copy-file' handles direct copy and out-of-band methods.
4645 ((or (tramp-local-host-p v)
7f49fe46
MA
4646 (tramp-method-out-of-band-p
4647 v (nth 7 (file-attributes filename))))
2988341a
MA
4648 (copy-file filename tmpfile t t))
4649
4650 ;; Use inline encoding for file transfer.
4651 (rem-enc
4652 (save-excursion
4653 (tramp-message v 5 "Encoding remote file %s..." filename)
4654 (tramp-barf-unless-okay
4655 v
4656 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4657 "Encoding remote file failed")
4658 (tramp-message v 5 "Encoding remote file %s...done" filename)
4659
4660 (if (and (symbolp loc-dec) (fboundp loc-dec))
4661 ;; If local decoding is a function, we call it. We
4662 ;; must disable multibyte, because
4663 ;; `uudecode-decode-region' doesn't handle it
4664 ;; correctly.
0f205eee
MA
4665 (with-temp-buffer
4666 (set-buffer-multibyte nil)
4667 (insert-buffer-substring (tramp-get-buffer v))
4668 (tramp-message
4669 v 5 "Decoding remote file %s with function %s..."
4670 filename loc-dec)
4671 (funcall loc-dec (point-min) (point-max))
aa485f7c
MA
4672 ;; Unset `file-name-handler-alist'. Otherwise,
4673 ;; epa-file gets confused.
4674 (let (file-name-handler-alist
4675 (coding-system-for-write 'binary))
2988341a
MA
4676 (write-region (point-min) (point-max) tmpfile)))
4677
4678 ;; If tramp-decoding-function is not defined for this
4679 ;; method, we invoke tramp-decoding-command instead.
4680 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
aa485f7c
MA
4681 ;; Unset `file-name-handler-alist'. Otherwise,
4682 ;; epa-file gets confused.
4683 (let (file-name-handler-alist
4684 (coding-system-for-write 'binary))
2988341a
MA
4685 (write-region (point-min) (point-max) tmpfile2))
4686 (tramp-message
4687 v 5 "Decoding remote file %s with command %s..."
4688 filename loc-dec)
4689 (unwind-protect
4690 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4691 (delete-file tmpfile2))))
4692
4693 (tramp-message v 5 "Decoding remote file %s...done" filename)
4694 ;; Set proper permissions.
b86c1cd8 4695 (set-file-modes tmpfile (tramp-default-file-modes filename))
2988341a
MA
4696 ;; Set local user ownership.
4697 (tramp-set-file-uid-gid tmpfile)))
4698
4699 ;; Oops, I don't know what to do.
4700 (t (tramp-error
4701 v 'file-error "Wrong method specification for `%s'" method)))
4702
4703 ;; Error handling.
4704 ((error quit)
4705 (delete-file tmpfile)
4706 (signal (car err) (cdr err))))
0f205eee 4707
00d6fd04 4708 (run-hooks 'tramp-handle-file-local-copy-hook)
94be87e8 4709 tmpfile)))
fb7933a3 4710
bce04fee 4711(defun tramp-handle-file-remote-p (filename &optional identification connected)
00d6fd04 4712 "Like `file-remote-p' for Tramp files."
d5b3979c
MA
4713 (let ((tramp-verbose 3))
4714 (when (tramp-tramp-file-p filename)
4715 (let* ((v (tramp-dissect-file-name filename))
4716 (p (tramp-get-connection-process v))
4717 (c (and p (processp p) (memq (process-status p) '(run open)))))
4718 ;; We expand the file name only, if there is already a connection.
4719 (with-parsed-tramp-file-name
4720 (if c (expand-file-name filename) filename) nil
4721 (and (or (not connected) c)
4722 (cond
4723 ((eq identification 'method) method)
4724 ((eq identification 'user) user)
4725 ((eq identification 'host) host)
4726 ((eq identification 'localname) localname)
4727 (t (tramp-make-tramp-file-name method user host "")))))))))
fb7933a3 4728
eb562962
MA
4729(defun tramp-find-file-name-coding-system-alist (filename tmpname)
4730 "Like `find-operation-coding-system' for Tramp filenames.
4731Tramp's `insert-file-contents' and `write-region' work over
4732temporary file names. If `file-coding-system-alist' contains an
4733expression, which matches more than the file name suffix, the
4734coding system might not be determined. This function repairs it."
4735 (let (result)
4736 (dolist (elt file-coding-system-alist result)
4737 (when (and (consp elt) (string-match (car elt) filename))
4738 ;; We found a matching entry in `file-coding-system-alist'.
4739 ;; So we add a similar entry, but with the temporary file name
4740 ;; as regexp.
4741 (add-to-list
4742 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4743
fb7933a3
KG
4744(defun tramp-handle-insert-file-contents
4745 (filename &optional visit beg end replace)
00d6fd04 4746 "Like `insert-file-contents' for Tramp files."
fb7933a3
KG
4747 (barf-if-buffer-read-only)
4748 (setq filename (expand-file-name filename))
736ac90f 4749 (let (coding-system-used result local-copy remote-copy)
2ac33804
MA
4750 (with-parsed-tramp-file-name filename nil
4751 (unwind-protect
70c11b0b
MA
4752 (if (not (file-exists-p filename))
4753 ;; We don't raise a Tramp error, because it might be
4754 ;; suppressed, like in `find-file-noselect-1'.
4755 (signal 'file-error
4756 (list "File not found on remote host" filename))
4757
4758 (if (and (tramp-local-host-p v)
4759 (let (file-name-handler-alist)
4760 (file-readable-p localname)))
4761 ;; Short track: if we are on the local host, we can
4762 ;; run directly.
4763 (setq result
4764 (tramp-run-real-handler
4765 'insert-file-contents
4766 (list localname visit beg end replace)))
4767
736ac90f
MA
4768 ;; When we shall insert only a part of the file, we copy
4769 ;; this part.
4770 (when (or beg end)
4771 (setq remote-copy (tramp-make-tramp-temp-file v))
4772 (tramp-send-command
4773 v
4774 (cond
4775 ((and beg end)
4776 (format "tail -c +%d %s | head -c +%d >%s"
4777 (1+ beg) (tramp-shell-quote-argument localname)
4778 (- end beg) remote-copy))
4779 (beg
4780 (format "tail -c +%d %s >%s"
4781 (1+ beg) (tramp-shell-quote-argument localname)
4782 remote-copy))
4783 (end
4784 (format "head -c +%d %s >%s"
4785 (1+ end) (tramp-shell-quote-argument localname)
4786 remote-copy)))))
4787
70c11b0b
MA
4788 ;; `insert-file-contents-literally' takes care to avoid
4789 ;; calling jka-compr. By let-binding
4790 ;; `inhibit-file-name-operation', we propagate that care
4791 ;; to the `file-local-copy' operation.
4792 (setq local-copy
4793 (let ((inhibit-file-name-operation
4794 (when (eq inhibit-file-name-operation
4795 'insert-file-contents)
4796 'file-local-copy)))
b88f2d0a
MA
4797 (cond
4798 ((stringp remote-copy)
4799 (file-local-copy
4800 (tramp-make-tramp-file-name
4801 method user host remote-copy)))
4802 ((stringp tramp-temp-buffer-file-name)
4803 (copy-file filename tramp-temp-buffer-file-name 'ok)
4804 tramp-temp-buffer-file-name)
4805 (t (file-local-copy filename)))))
4806
6e4f5731
MA
4807 ;; When the file is not readable for the owner, it
4808 ;; cannot be inserted, even it is redable for the group
4809 ;; or for everybody.
4810 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4811
b88f2d0a
MA
4812 (when (and (null remote-copy)
4813 (tramp-get-method-parameter
4814 method 'tramp-copy-keep-tmpfile))
4815 ;; We keep the local file for performance reasons,
4816 ;; useful for "rsync".
b88f2d0a
MA
4817 (setq tramp-temp-buffer-file-name local-copy)
4818 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4819
70c11b0b
MA
4820 (tramp-message
4821 v 4 "Inserting local temp file `%s'..." local-copy)
4822
4823 ;; We must ensure that `file-coding-system-alist'
4824 ;; matches `local-copy'.
4825 (let ((file-coding-system-alist
4826 (tramp-find-file-name-coding-system-alist
4827 filename local-copy)))
4828 (setq result
4829 (insert-file-contents
736ac90f 4830 local-copy nil nil nil replace))
70c11b0b
MA
4831 ;; Now `last-coding-system-used' has right value.
4832 ;; Remember it.
4833 (when (boundp 'last-coding-system-used)
4834 (setq coding-system-used
4835 (symbol-value 'last-coding-system-used))))
8d60099b 4836
70c11b0b
MA
4837 (tramp-message
4838 v 4 "Inserting local temp file `%s'...done" local-copy)
4839 (when (boundp 'last-coding-system-used)
2ac33804 4840 (set 'last-coding-system-used coding-system-used))))
70c11b0b 4841
2ac33804
MA
4842 ;; Save exit.
4843 (progn
4844 (when visit
4845 (setq buffer-file-name filename)
4846 (setq buffer-read-only (not (file-writable-p filename)))
4847 (set-visited-file-modtime)
4848 (set-buffer-modified-p nil))
b88f2d0a
MA
4849 (when (and (stringp local-copy)
4850 (or remote-copy (null tramp-temp-buffer-file-name)))
2ac33804
MA
4851 (delete-file local-copy))
4852 (when (stringp remote-copy)
4853 (delete-file
4854 (tramp-make-tramp-file-name method user host remote-copy))))))
70c11b0b
MA
4855
4856 ;; Result.
4857 (list (expand-file-name filename)
4858 (cadr result))))
fb7933a3 4859
94be87e8
MA
4860;; This is needed for XEmacs only. Code stolen from files.el.
4861(defun tramp-handle-insert-file-contents-literally
4862 (filename &optional visit beg end replace)
4863 "Like `insert-file-contents-literally' for Tramp files."
4864 (let ((format-alist nil)
4865 (after-insert-file-functions nil)
4866 (coding-system-for-read 'no-conversion)
4867 (coding-system-for-write 'no-conversion)
4868 (find-buffer-file-type-function
4869 (if (fboundp 'find-buffer-file-type)
4870 (symbol-function 'find-buffer-file-type)
4871 nil))
4872 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4873 (inhibit-file-name-operation 'insert-file-contents))
4874 (unwind-protect
4875 (progn
4876 (fset 'find-buffer-file-type (lambda (filename) t))
4877 (insert-file-contents filename visit beg end replace))
70c11b0b 4878 ;; Save exit.
94be87e8
MA
4879 (if find-buffer-file-type-function
4880 (fset 'find-buffer-file-type find-buffer-file-type-function)
4881 (fmakunbound 'find-buffer-file-type)))))
4882
38c65fca 4883(defun tramp-handle-find-backup-file-name (filename)
00d6fd04 4884 "Like `find-backup-file-name' for Tramp files."
07dfe738
KG
4885 (with-parsed-tramp-file-name filename nil
4886 ;; We set both variables. It doesn't matter whether it is
b533bc97 4887 ;; Emacs or XEmacs.
07dfe738 4888 (let ((backup-directory-alist
b533bc97 4889 ;; Emacs case.
07dfe738 4890 (when (boundp 'backup-directory-alist)
b86c1cd8 4891 (if (symbol-value 'tramp-backup-directory-alist)
07dfe738 4892 (mapcar
aa485f7c
MA
4893 (lambda (x)
4894 (cons
4895 (car x)
4896 (if (and (stringp (cdr x))
4897 (file-name-absolute-p (cdr x))
4898 (not (tramp-file-name-p (cdr x))))
4899 (tramp-make-tramp-file-name method user host (cdr x))
4900 (cdr x))))
07dfe738
KG
4901 (symbol-value 'tramp-backup-directory-alist))
4902 (symbol-value 'backup-directory-alist))))
4903
4904 (bkup-backup-directory-info
b533bc97 4905 ;; XEmacs case.
07dfe738 4906 (when (boundp 'bkup-backup-directory-info)
b86c1cd8 4907 (if (symbol-value 'tramp-bkup-backup-directory-info)
07dfe738 4908 (mapcar
aa485f7c
MA
4909 (lambda (x)
4910 (nconc
4911 (list (car x))
4912 (list
4913 (if (and (stringp (car (cdr x)))
4914 (file-name-absolute-p (car (cdr x)))
4915 (not (tramp-file-name-p (car (cdr x)))))
4916 (tramp-make-tramp-file-name
4917 method user host (car (cdr x)))
4918 (car (cdr x))))
4919 (cdr (cdr x))))
07dfe738
KG
4920 (symbol-value 'tramp-bkup-backup-directory-info))
4921 (symbol-value 'bkup-backup-directory-info)))))
4922
4923 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
38c65fca 4924
c1105d05 4925(defun tramp-handle-make-auto-save-file-name ()
00d6fd04 4926 "Like `make-auto-save-file-name' for Tramp files.
c1105d05 4927Returns a file name in `tramp-auto-save-directory' for autosaving this file."
00d6fd04
MA
4928 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4929 (buffer-file-name
4930 (tramp-subst-strs-in-string
4931 '(("_" . "|")
4932 ("/" . "_a")
4933 (":" . "_b")
4934 ("|" . "__")
4935 ("[" . "_l")
4936 ("]" . "_r"))
4937 (buffer-file-name))))
1a762140
MA
4938 ;; File name must be unique. This is ensured with Emacs 22 (see
4939 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4940 ;; all other cases we must do it ourselves.
4941 (when (boundp 'auto-save-file-name-transforms)
9e6ab520 4942 (mapc
aa485f7c
MA
4943 (lambda (x)
4944 (when (and (string-match (car x) buffer-file-name)
4945 (not (car (cddr x))))
4946 (setq tramp-auto-save-directory
4947 (or tramp-auto-save-directory
4948 (tramp-compat-temporary-file-directory)))))
1a762140
MA
4949 (symbol-value 'auto-save-file-name-transforms)))
4950 ;; Create directory.
4951 (when tramp-auto-save-directory
00d6fd04
MA
4952 (setq buffer-file-name
4953 (expand-file-name buffer-file-name tramp-auto-save-directory))
1a762140
MA
4954 (unless (file-exists-p tramp-auto-save-directory)
4955 (make-directory tramp-auto-save-directory t)))
00d6fd04
MA
4956 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4957 ;; it is not a magic file name operation (since Emacs 22).
4958 ;; We must deactivate it temporarily.
4959 (if (not (ad-is-active 'make-auto-save-file-name))
4960 (tramp-run-real-handler 'make-auto-save-file-name nil)
4961 ;; else
4962 (ad-deactivate 'make-auto-save-file-name)
4963 (prog1
4964 (tramp-run-real-handler 'make-auto-save-file-name nil)
4965 (ad-activate 'make-auto-save-file-name)))))
4966
4967(defvar tramp-handle-write-region-hook nil
4968 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4969
b88f2d0a 4970;; CCC grok LOCKNAME
fb7933a3
KG
4971(defun tramp-handle-write-region
4972 (start end filename &optional append visit lockname confirm)
00d6fd04 4973 "Like `write-region' for Tramp files."
fb7933a3 4974 (setq filename (expand-file-name filename))
c62c9d08 4975 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4976 ;; Following part commented out because we don't know what to do about
4977 ;; file locking, and it does not appear to be a problem to ignore it.
4978 ;; Ange-ftp ignores it, too.
4979 ;; (when (and lockname (stringp lockname))
4980 ;; (setq lockname (expand-file-name lockname)))
4981 ;; (unless (or (eq lockname nil)
4982 ;; (string= lockname filename))
4983 ;; (error
4984 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
8d60099b 4985
94be87e8 4986 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
00d6fd04
MA
4987 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4988 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4989 (tramp-error v 'file-error "File not overwritten")))
8d60099b 4990
a4aeb9a4 4991 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
9c13938d 4992 (tramp-get-remote-uid v 'integer)))
a4aeb9a4 4993 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
9c13938d
MA
4994 (tramp-get-remote-gid v 'integer))))
4995
4996 (if (and (tramp-local-host-p v)
93c3eb7c 4997 ;; `file-writable-p' calls `file-expand-file-name'. We
87bdd2c7
MA
4998 ;; cannot use `tramp-run-real-handler' therefore.
4999 (let (file-name-handler-alist)
82f3844e
MA
5000 (and
5001 (file-writable-p (file-name-directory localname))
5002 (or (file-directory-p localname)
5003 (file-writable-p localname)))))
9c13938d 5004 ;; Short track: if we are on the local host, we can run directly.
aac0b0f2
MA
5005 (tramp-run-real-handler
5006 'write-region
5007 (list start end localname append 'no-message lockname confirm))
9c13938d
MA
5008
5009 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
5010 (loc-enc (tramp-get-local-coding v "local-encoding"))
b86c1cd8 5011 (modes (save-excursion (tramp-default-file-modes filename)))
9c13938d
MA
5012 ;; We use this to save the value of
5013 ;; `last-coding-system-used' after writing the tmp file.
5014 ;; At the end of the function, we set
5015 ;; `last-coding-system-used' to this saved value. This
5016 ;; way, any intermediary coding systems used while
5017 ;; talking to the remote shell or suchlike won't hose
5018 ;; this variable. This approach was snarfed from
5019 ;; ange-ftp.el.
5020 coding-system-used
5021 ;; Write region into a tmp file. This isn't really
5022 ;; needed if we use an encoding function, but currently
5023 ;; we use it always because this makes the logic
293c24f9
MA
5024 ;; simpler.
5025 (tmpfile (or tramp-temp-buffer-file-name
5026 (tramp-compat-make-temp-file filename))))
5027
5028 ;; If `append' is non-nil, we copy the file locally, and let
5029 ;; the native `write-region' implementation do the job.
5030 (when append (copy-file filename tmpfile 'ok))
9c13938d
MA
5031
5032 ;; We say `no-message' here because we don't want the
5033 ;; visited file modtime data to be clobbered from the temp
5034 ;; file. We call `set-visited-file-modtime' ourselves later
eb562962
MA
5035 ;; on. We must ensure that `file-coding-system-alist'
5036 ;; matches `tmpfile'.
5037 (let ((file-coding-system-alist
5038 (tramp-find-file-name-coding-system-alist filename tmpfile)))
ce2cc728
MA
5039 (condition-case err
5040 (tramp-run-real-handler
5041 'write-region
5042 (list start end tmpfile append 'no-message lockname confirm))
2988341a 5043 ((error quit)
b88f2d0a 5044 (setq tramp-temp-buffer-file-name nil)
2988341a
MA
5045 (delete-file tmpfile)
5046 (signal (car err) (cdr err))))
ce2cc728 5047
eb562962
MA
5048 ;; Now, `last-coding-system-used' has the right value. Remember it.
5049 (when (boundp 'last-coding-system-used)
5050 (setq coding-system-used
5051 (symbol-value 'last-coding-system-used))))
5052
9c13938d
MA
5053 ;; The permissions of the temporary file should be set. If
5054 ;; filename does not exist (eq modes nil) it has been
5055 ;; renamed to the backup file. This case `save-buffer'
5056 ;; handles permissions.
459a5f4b
MA
5057 ;; Ensure, that it is still readable.
5058 (when modes
5059 (set-file-modes
5060 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
9c13938d
MA
5061
5062 ;; This is a bit lengthy due to the different methods
5063 ;; possible for file transfer. First, we check whether the
5064 ;; method uses an rcp program. If so, we call it.
5065 ;; Otherwise, both encoding and decoding command must be
5066 ;; specified. However, if the method _also_ specifies an
5067 ;; encoding function, then that is used for encoding the
5068 ;; contents of the tmp file.
5069 (cond
00cffdeb 5070 ;; `copy-file' handles direct copy and out-of-band methods.
9c13938d 5071 ((or (tramp-local-host-p v)
7f49fe46 5072 (tramp-method-out-of-band-p
00cffdeb
MA
5073 v (nth 7 (file-attributes tmpfile))))
5074 (if (and (not (stringp start))
5075 (= (or end (point-max)) (point-max))
191bb792
MA
5076 (= (or start (point-min)) (point-min))
5077 (tramp-get-method-parameter
5078 method 'tramp-copy-keep-tmpfile))
5079 (progn
5080 (setq tramp-temp-buffer-file-name tmpfile)
5081 (condition-case err
b88f2d0a
MA
5082 ;; We keep the local file for performance
5083 ;; reasons, useful for "rsync".
191bb792
MA
5084 (copy-file tmpfile filename t)
5085 ((error quit)
5086 (setq tramp-temp-buffer-file-name nil)
5087 (delete-file tmpfile)
5088 (signal (car err) (cdr err)))))
5089 (setq tramp-temp-buffer-file-name nil)
5090 ;; Don't rename, in order to keep context in SELinux.
5091 (unwind-protect
5092 (copy-file tmpfile filename t)
5093 (delete-file tmpfile))))
9c13938d 5094
1d7e9a01 5095 ;; Use inline file transfer.
9c13938d 5096 (rem-dec
1d7e9a01 5097 ;; Encode tmpfile.
9c13938d
MA
5098 (tramp-message v 5 "Encoding region...")
5099 (unwind-protect
5100 (with-temp-buffer
5101 ;; Use encoding function or command.
5102 (if (and (symbolp loc-enc) (fboundp loc-enc))
5103 (progn
5104 (tramp-message
5105 v 5 "Encoding region using function `%s'..."
5106 (symbol-name loc-enc))
5107 (let ((coding-system-for-read 'binary))
5108 (insert-file-contents-literally tmpfile))
70c11b0b
MA
5109 ;; The following `let' is a workaround for the
5110 ;; base64.el that comes with pgnus-0.84. If
5111 ;; both of the following conditions are
5112 ;; satisfied, it tries to write to a local
5113 ;; file in default-directory, but at this
5114 ;; point, default-directory is remote.
5115 ;; (`call-process-region' can't write to
5116 ;; remote files, it seems.) The file in
5117 ;; question is a tmp file anyway.
9c13938d
MA
5118 (let ((default-directory
5119 (tramp-compat-temporary-file-directory)))
5120 (funcall loc-enc (point-min) (point-max))))
8d60099b 5121
9c13938d
MA
5122 (tramp-message
5123 v 5 "Encoding region using command `%s'..." loc-enc)
5124 (unless (equal 0 (tramp-call-local-coding-command
5125 loc-enc tmpfile t))
5126 (tramp-error
5127 v 'file-error
5128 "Cannot write to `%s', local encoding command `%s' failed"
5129 filename loc-enc)))
5130
5131 ;; Send buffer into remote decoding command which
5132 ;; writes to remote file. Because this happens on
5133 ;; the remote host, we cannot use the function.
5134 (goto-char (point-max))
5135 (unless (bolp) (newline))
8d60099b 5136 (tramp-message
9c13938d
MA
5137 v 5 "Decoding region into remote file %s..." filename)
5138 (tramp-send-command
5139 v
5140 (format
5141 "%s >%s <<'EOF'\n%sEOF"
5142 rem-dec
5143 (tramp-shell-quote-argument localname)
5144 (buffer-string)))
5145 (tramp-barf-unless-okay
5146 v nil
5147 "Couldn't write region to `%s', decode using `%s' failed"
5148 filename rem-dec)
5149 ;; When `file-precious-flag' is set, the region is
5150 ;; written to a temporary file. Check that the
5151 ;; checksum is equal to that from the local tmpfile.
5152 (when file-precious-flag
5153 (erase-buffer)
5154 (and
a4aeb9a4
MA
5155 ;; cksum runs locally, if possible.
5156 (zerop (tramp-local-call-process "cksum" tmpfile t))
5157 ;; cksum runs remotely.
9c13938d
MA
5158 (zerop
5159 (tramp-send-command-and-check
5160 v
5161 (format
5162 "cksum <%s" (tramp-shell-quote-argument localname))))
a4aeb9a4 5163 ;; ... they are different.
9c13938d
MA
5164 (not
5165 (string-equal
5166 (buffer-string)
5167 (with-current-buffer (tramp-get-buffer v)
5168 (buffer-string))))
5169 (tramp-error
5170 v 'file-error
5171 (concat "Couldn't write region to `%s',"
5172 " decode using `%s' failed")
5173 filename rem-dec)))
5174 (tramp-message
aac0b0f2 5175 v 5 "Decoding region into remote file %s...done" filename))
8d60099b 5176
9c13938d
MA
5177 ;; Save exit.
5178 (delete-file tmpfile)))
8d60099b 5179
9c13938d
MA
5180 ;; That's not expected.
5181 (t
5182 (tramp-error
5183 v 'file-error
5184 (concat "Method `%s' should specify both encoding and "
5185 "decoding command or an rcp program")
5186 method)))
258800f8 5187
9c13938d
MA
5188 ;; Make `last-coding-system-used' have the right value.
5189 (when coding-system-used
5190 (set 'last-coding-system-used coding-system-used))))
0f205eee 5191
aac0b0f2
MA
5192 (tramp-flush-file-property v (file-name-directory localname))
5193 (tramp-flush-file-property v localname)
5194
57671b72
MA
5195 ;; We must protect `last-coding-system-used', now we have set it
5196 ;; to its correct value.
293c24f9 5197 (let (last-coding-system-used (need-chown t))
57671b72
MA
5198 ;; Set file modification time.
5199 (when (or (eq visit t) (stringp visit))
293c24f9
MA
5200 (let ((file-attr (file-attributes filename)))
5201 (set-visited-file-modtime
5202 ;; We must pass modtime explicitely, because filename can
5203 ;; be different from (buffer-file-name), f.e. if
5204 ;; `file-precious-flag' is set.
5205 (nth 5 file-attr))
5206 (when (and (eq (nth 2 file-attr) uid)
5207 (eq (nth 3 file-attr) gid))
5208 (setq need-chown nil))))
57671b72
MA
5209
5210 ;; Set the ownership.
293c24f9
MA
5211 (when need-chown
5212 (tramp-set-file-uid-gid filename uid gid))
57671b72
MA
5213 (when (or (eq visit t) (null visit) (stringp visit))
5214 (tramp-message v 0 "Wrote %s" filename))
5215 (run-hooks 'tramp-handle-write-region-hook)))))
fb7933a3 5216
946a5aeb
MA
5217(defvar tramp-vc-registered-file-names nil
5218 "List used to collect file names, which are checked during `vc-registered'.")
5219
5220;; VC backends check for the existence of various different special
5221;; files. This is very time consuming, because every single check
5222;; requires a remote command (the file cache must be invalidated).
5223;; Therefore, we apply a kind of optimization. We install the file
5224;; name handler `tramp-vc-file-name-handler', which does nothing but
5225;; remembers all file names for which `file-exists-p' or
5226;; `file-readable-p' has been applied. A first run of `vc-registered'
5227;; is performed. Afterwards, a script is applied for all collected
5228;; file names, using just one remote command. The result of this
5229;; script is used to fill the file cache with actual values. Now we
5230;; can reset the file name handlers, and we make a second run of
5231;; `vc-registered', which returns the expected result without sending
5232;; any other remote command.
49096407
MA
5233(defun tramp-handle-vc-registered (file)
5234 "Like `vc-registered' for Tramp files."
946a5aeb 5235 (with-parsed-tramp-file-name file nil
7f49fe46
MA
5236
5237 ;; There could be new files, created by the vc backend. We cannot
5238 ;; reuse the old cache entries, therefore.
946a5aeb
MA
5239 (let (tramp-vc-registered-file-names
5240 (tramp-cache-inhibit-cache (current-time))
5241 (file-name-handler-alist
5242 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5243
5244 ;; Here we collect only file names, which need an operation.
5245 (tramp-run-real-handler 'vc-registered (list file))
5246 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5247
5248 ;; Send just one command, in order to fill the cache.
7f49fe46
MA
5249 (when tramp-vc-registered-file-names
5250 (tramp-maybe-send-script
5251 v
5252 (format tramp-vc-registered-read-file-names
5253 (tramp-get-file-exists-command v)
5254 (format "%s -r" (tramp-get-test-command v)))
5255 "tramp_vc_registered_read_file_names")
5256
5257 (dolist
5258 (elt
5259 (tramp-send-command-and-read
5260 v
5261 (format
5262 "tramp_vc_registered_read_file_names %s"
5263 (mapconcat 'tramp-shell-quote-argument
5264 tramp-vc-registered-file-names
5265 " "))))
946a5aeb 5266
7f49fe46 5267 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
946a5aeb 5268
7f49fe46
MA
5269 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
5270 ;; shall be answered from the file cache.
5271 ;; We unset `process-file-side-effects' in order to keep the cache
5272 ;; when `process-file' calls appear.
946a5aeb
MA
5273 (let (process-file-side-effects)
5274 (tramp-run-real-handler 'vc-registered (list file)))))
49096407 5275
a01b1e22
MA
5276;;;###autoload
5277(progn (defun tramp-run-real-handler (operation args)
fb7933a3 5278 "Invoke normal file name handler for OPERATION.
c62c9d08
KG
5279First arg specifies the OPERATION, second arg is a list of arguments to
5280pass to the OPERATION."
4007ba5b
KG
5281 (let* ((inhibit-file-name-handlers
5282 `(tramp-file-name-handler
946a5aeb 5283 tramp-vc-file-name-handler
4007ba5b
KG
5284 tramp-completion-file-name-handler
5285 cygwin-mount-name-hook-function
5286 cygwin-mount-map-drive-hook-function
5287 .
5288 ,(and (eq inhibit-file-name-operation operation)
5289 inhibit-file-name-handlers)))
5290 (inhibit-file-name-operation operation))
a01b1e22 5291 (apply operation args))))
16674e4f 5292
a01b1e22
MA
5293;;;###autoload
5294(progn (defun tramp-completion-run-real-handler (operation args)
16674e4f
KG
5295 "Invoke `tramp-file-name-handler' for OPERATION.
5296First arg specifies the OPERATION, second arg is a list of arguments to
5297pass to the OPERATION."
4007ba5b
KG
5298 (let* ((inhibit-file-name-handlers
5299 `(tramp-completion-file-name-handler
5300 cygwin-mount-name-hook-function
5301 cygwin-mount-map-drive-hook-function
5302 .
5303 ,(and (eq inhibit-file-name-operation operation)
5304 inhibit-file-name-handlers)))
5305 (inhibit-file-name-operation operation))
a01b1e22 5306 (apply operation args))))
fb7933a3 5307
4007ba5b
KG
5308;; We handle here all file primitives. Most of them have the file
5309;; name as first parameter; nevertheless we check for them explicitly
04bf5b65 5310;; in order to be signaled if a new primitive appears. This
4007ba5b
KG
5311;; scenario is needed because there isn't a way to decide by
5312;; syntactical means whether a foreign method must be called. It would
19a87064 5313;; ease the life if `file-name-handler-alist' would support a decision
4007ba5b
KG
5314;; function as well but regexp only.
5315(defun tramp-file-name-for-operation (operation &rest args)
5316 "Return file name related to OPERATION file primitive.
5317ARGS are the arguments OPERATION has been called with."
5318 (cond
b533bc97 5319 ;; FILE resp DIRECTORY.
4007ba5b
KG
5320 ((member operation
5321 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5322 'delete-file 'diff-latest-backup-file 'directory-file-name
5323 'directory-files 'directory-files-and-attributes
5324 'dired-compress-file 'dired-uncache
5325 'file-accessible-directory-p 'file-attributes
5326 'file-directory-p 'file-executable-p 'file-exists-p
19a87064
MA
5327 'file-local-copy 'file-remote-p 'file-modes
5328 'file-name-as-directory 'file-name-directory
5329 'file-name-nondirectory 'file-name-sans-versions
5330 'file-ownership-preserved-p 'file-readable-p
5331 'file-regular-p 'file-symlink-p 'file-truename
5332 'file-writable-p 'find-backup-file-name 'find-file-noselect
5333 'get-file-buffer 'insert-directory 'insert-file-contents
5334 'load 'make-directory 'make-directory-internal
5335 'set-file-modes 'substitute-in-file-name
5336 'unhandled-file-name-directory 'vc-registered
b533bc97 5337 ;; Emacs 22+ only.
ce3f516f 5338 'set-file-times
b533bc97 5339 ;; XEmacs only.
4007ba5b
KG
5340 'abbreviate-file-name 'create-file-buffer
5341 'dired-file-modtime 'dired-make-compressed-filename
5342 'dired-recursive-delete-directory 'dired-set-file-modtime
5343 'dired-shell-unhandle-file-name 'dired-uucode-file
5615d63f 5344 'insert-file-contents-literally 'make-temp-name 'recover-file
4007ba5b 5345 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
8daea7fc
KG
5346 (if (file-name-absolute-p (nth 0 args))
5347 (nth 0 args)
5348 (expand-file-name (nth 0 args))))
b533bc97 5349 ;; FILE DIRECTORY resp FILE1 FILE2.
4007ba5b
KG
5350 ((member operation
5351 (list 'add-name-to-file 'copy-file 'expand-file-name
5352 'file-name-all-completions 'file-name-completion
5353 'file-newer-than-file-p 'make-symbolic-link 'rename-file
b533bc97 5354 ;; Emacs 23+ only.
263c02ef 5355 'copy-directory
b533bc97 5356 ;; XEmacs only.
4007ba5b
KG
5357 'dired-make-relative-symlink
5358 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5359 (save-match-data
5360 (cond
5361 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5362 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5363 (t (buffer-file-name (current-buffer))))))
b533bc97 5364 ;; START END FILE.
4007ba5b
KG
5365 ((eq operation 'write-region)
5366 (nth 2 args))
b533bc97 5367 ;; BUFFER.
4007ba5b 5368 ((member operation
00d6fd04 5369 (list 'set-visited-file-modtime 'verify-visited-file-modtime
b533bc97 5370 ;; Emacs 22+ only.
00d6fd04 5371 'make-auto-save-file-name
b533bc97 5372 ;; XEmacs only.
4007ba5b
KG
5373 'backup-buffer))
5374 (buffer-file-name
5375 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
b533bc97 5376 ;; COMMAND.
4007ba5b 5377 ((member operation
b533bc97 5378 (list ;; not in Emacs 23+.
00d6fd04 5379 'dired-call-process
b533bc97 5380 ;; Emacs only.
b71c9e75 5381 'shell-command
b533bc97 5382 ;; Emacs 22+ only.
0457dd55 5383 'process-file
b533bc97 5384 ;; Emacs 23+ only.
00d6fd04 5385 'start-file-process
b533bc97 5386 ;; XEmacs only.
00d6fd04 5387 'dired-print-file 'dired-shell-call-process
b533bc97 5388 ;; nowhere yet.
00d6fd04 5389 'executable-find 'start-process 'call-process))
4007ba5b 5390 default-directory)
b533bc97 5391 ;; Unknown file primitive.
4007ba5b
KG
5392 (t (error "unknown file I/O primitive: %s" operation))))
5393
5394(defun tramp-find-foreign-file-name-handler (filename)
5395 "Return foreign file name handler if exists."
b533bc97 5396 (when (tramp-tramp-file-p filename)
9ce8462a
MA
5397 (let ((v (tramp-dissect-file-name filename t))
5398 (handler tramp-foreign-file-name-handler-alist)
5399 elt res)
5400 ;; When we are not fully sure that filename completion is safe,
5401 ;; we should not return a handler.
5402 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1834b39f
MA
5403 (and (tramp-file-name-host v)
5404 (not (member (tramp-file-name-host v)
5405 (mapcar 'car tramp-methods))))
9ce8462a
MA
5406 (not (tramp-completion-mode-p)))
5407 (while handler
5408 (setq elt (car handler)
5409 handler (cdr handler))
5410 (when (funcall (car elt) filename)
5411 (setq handler nil
5412 res (cdr elt))))
5413 res))))
4007ba5b 5414
fb7933a3
KG
5415;; Main function.
5416;;;###autoload
5417(defun tramp-file-name-handler (operation &rest args)
ea9d1443 5418 "Invoke Tramp file name handler.
a4aeb9a4 5419Falls back to normal file name handler if no Tramp file name handler exists."
2e271195
MA
5420 (if tramp-mode
5421 (save-match-data
5422 (let* ((filename
5423 (tramp-replace-environment-variables
5424 (apply 'tramp-file-name-for-operation operation args)))
5425 (completion (tramp-completion-mode-p))
5426 (foreign (tramp-find-foreign-file-name-handler filename)))
5427 (with-parsed-tramp-file-name filename nil
5428 (cond
5429 ;; When we are in completion mode, some operations
5430 ;; shouldn't be handled by backend.
5431 ((and completion (zerop (length localname))
5432 (memq operation '(file-exists-p file-directory-p)))
5433 t)
5434 ((and completion (zerop (length localname))
5435 (memq operation '(file-name-as-directory)))
5436 filename)
5437 ;; Call the backend function.
5438 (foreign (apply foreign operation args))
5439 ;; Nothing to do for us.
5440 (t (tramp-run-real-handler operation args))))))
5441 ;; When `tramp-mode' is not enabled, we don't do anything.
5442 (tramp-run-real-handler operation args)))
fb7933a3 5443
07dfe738
KG
5444;; In Emacs, there is some concurrency due to timers. If a timer
5445;; interrupts Tramp and wishes to use the same connection buffer as
5446;; the "main" Emacs, then garbage might occur in the connection
5447;; buffer. Therefore, we need to make sure that a timer does not use
5448;; the same connection buffer as the "main" Emacs. We implement a
5449;; cheap global lock, instead of locking each connection buffer
5450;; separately. The global lock is based on two variables,
5451;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5452;; (with setq) to indicate a lock. But Tramp also calls itself during
5453;; processing of a single file operation, so we need to allow
5454;; recursive calls. That's where the `tramp-locker' variable comes in
5455;; -- it is let-bound to t during the execution of the current
5456;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5457;; then we should just proceed because we have been called
5458;; recursively. But if `tramp-locker' is nil, then we are a timer
5459;; interrupting the "main" Emacs, and then we signal an error.
5460
5461(defvar tramp-locked nil
5462 "If non-nil, then Tramp is currently busy.
5463Together with `tramp-locker', this implements a locking mechanism
5464preventing reentrant calls of Tramp.")
5465
5466(defvar tramp-locker nil
5467 "If non-nil, then a caller has locked Tramp.
5468Together with `tramp-locked', this implements a locking mechanism
5469preventing reentrant calls of Tramp.")
5470
ea9d1443
KG
5471(defun tramp-sh-file-name-handler (operation &rest args)
5472 "Invoke remote-shell Tramp file name handler.
5473Fall back to normal file name handler if no Tramp handler exists."
07dfe738 5474 (when (and tramp-locked (not tramp-locker))
11c71217 5475 (setq tramp-locked nil)
00d6fd04 5476 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
07dfe738
KG
5477 (let ((tl tramp-locked))
5478 (unwind-protect
5479 (progn
5480 (setq tramp-locked t)
5481 (let ((tramp-locker t))
5482 (save-match-data
5483 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5484 (if fn
5485 (apply (cdr fn) args)
5486 (tramp-run-real-handler operation args))))))
5487 (setq tramp-locked tl))))
ea9d1443 5488
946a5aeb
MA
5489(defun tramp-vc-file-name-handler (operation &rest args)
5490 "Invoke special file name handler, which collects files to be handled."
5491 (save-match-data
5492 (let ((filename
5493 (tramp-replace-environment-variables
5494 (apply 'tramp-file-name-for-operation operation args)))
5495 (fn (assoc operation tramp-file-name-handler-alist)))
5496 (with-parsed-tramp-file-name filename nil
5497 (cond
5498 ;; That's what we want: file names, for which checks are
5499 ;; applied. We assume, that VC uses only `file-exists-p' and
5500 ;; `file-readable-p' checks; otherwise we must extend the
5501 ;; list. We do not perform any action, but return nil, in
5502 ;; order to keep `vc-registered' running.
5503 ((and fn (memq operation '(file-exists-p file-readable-p)))
5504 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5505 nil)
5506 ;; Tramp file name handlers like `expand-file-name'. They
5507 ;; must still work.
5508 (fn
5509 (save-match-data (apply (cdr fn) args)))
5510 ;; Default file name handlers, we don't care.
5511 (t (tramp-run-real-handler operation args)))))))
5512
16674e4f 5513;;;###autoload
1ecc6145 5514(progn (defun tramp-completion-file-name-handler (operation &rest args)
a4aeb9a4
MA
5515 "Invoke Tramp file name completion handler.
5516Falls back to normal file name handler if no Tramp file name handler exists."
57671b72
MA
5517 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5518 ;; would otherwise use backslash.
aff67808
MA
5519 (let ((directory-sep-char ?/)
5520 (fn (assoc operation tramp-completion-file-name-handler-alist)))
aa485f7c
MA
5521 (if (and
5522 ;; When `tramp-mode' is not enabled, we don't do anything.
5523 fn tramp-mode
5524 ;; For other syntaxes than `sep', the regexp matches many common
5525 ;; situations where the user doesn't actually want to use Tramp.
5526 ;; So to avoid autoloading Tramp after typing just "/s", we
5527 ;; disable this part of the completion, unless the user implicitly
5528 ;; indicated his interest in using a fancier completion system.
5529 (or (eq tramp-syntax 'sep)
5f2b693f
MA
5530 (featurep 'tramp) ;; If it's loaded, we may as well use
5531 ;; it. `partial-completion-mode' does not exist in
5532 ;; XEmacs. It is obsoleted with Emacs 24.1.
aa485f7c
MA
5533 (and (boundp 'partial-completion-mode) partial-completion-mode)
5534 ;; FIXME: These may have been loaded even if the user never
5535 ;; intended to use them.
5536 (featurep 'ido)
5537 (featurep 'icicles)))
aff67808
MA
5538 (save-match-data (apply (cdr fn) args))
5539 (tramp-completion-run-real-handler operation args)))))
a01b1e22 5540
b25a52cc 5541;;;###autoload
aa485f7c
MA
5542(progn (defun tramp-register-file-name-handlers ()
5543 "Add Tramp file name handlers to `file-name-handler-alist'."
5544 ;; Remove autoloaded handlers from file name handler alist. Useful,
00d6fd04
MA
5545 ;; if `tramp-syntax' has been changed.
5546 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
aa485f7c
MA
5547 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5548 (let ((a1 (rassq
5549 'tramp-completion-file-name-handler file-name-handler-alist)))
5550 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5551 ;; Add the handlers.
a01b1e22
MA
5552 (add-to-list 'file-name-handler-alist
5553 (cons tramp-file-name-regexp 'tramp-file-name-handler))
0c0b61f1 5554 (put 'tramp-file-name-handler 'safe-magic t)
aa485f7c
MA
5555 (add-to-list 'file-name-handler-alist
5556 (cons tramp-completion-file-name-regexp
5557 'tramp-completion-file-name-handler))
5558 (put 'tramp-completion-file-name-handler 'safe-magic t)
5559 ;; If jka-compr or epa-file are already loaded, move them to the
5560 ;; front of `file-name-handler-alist'.
5561 (dolist (fnh '(epa-file-handler jka-compr-handler))
5562 (let ((entry (rassoc fnh file-name-handler-alist)))
5563 (when entry
5564 (setq file-name-handler-alist
5565 (cons entry (delete entry file-name-handler-alist))))))))
69cee873 5566
00d6fd04
MA
5567;; `tramp-file-name-handler' must be registered before evaluation of
5568;; site-start and init files, because there might exist remote files
5569;; already, f.e. files kept via recentf-mode.
aa485f7c
MA
5570;;;###autoload(tramp-register-file-name-handlers)
5571(tramp-register-file-name-handlers)
b25a52cc 5572
fb7933a3 5573;;;###autoload
8c04e197 5574(defun tramp-unload-file-name-handlers ()
a69c01a0
MA
5575 (setq file-name-handler-alist
5576 (delete (rassoc 'tramp-file-name-handler
5577 file-name-handler-alist)
5578 (delete (rassoc 'tramp-completion-file-name-handler
5579 file-name-handler-alist)
5580 file-name-handler-alist))))
5581
8c04e197 5582(add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
a69c01a0 5583
0664ff72 5584;;; File name handler functions for completion mode:
a6e96327
MA
5585
5586(defvar tramp-completion-mode nil
5587 "If non-nil, external packages signal that they are in file name completion.
5588
5589This is necessary, because Tramp uses a heuristic depending on last
5590input event. This fails when external packages use other characters
5591but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5592should never be set globally, the intention is to let-bind it.")
16674e4f
KG
5593
5594;; Necessary because `tramp-file-name-regexp-unified' and
00d6fd04
MA
5595;; `tramp-completion-file-name-regexp-unified' aren't different. If
5596;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5597;; to `tramp-file-name-handler'). Otherwise, it takes
5598;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5599;; risky, because completing a file might require loading other files,
5600;; like "~/.netrc", and for them it shouldn't be decided based on that
5601;; variable. On the other hand, those files shouldn't have partial
a4aeb9a4
MA
5602;; Tramp file name syntax. Maybe another variable should be introduced
5603;; overwriting this check in such cases. Or we change Tramp file name
00d6fd04 5604;; syntax in order to avoid ambiguities, like in XEmacs ...
6c4e47fa 5605(defun tramp-completion-mode-p ()
16674e4f 5606 "Checks whether method / user name / host name completion is active."
6c4e47fa 5607 (or
5f2b693f
MA
5608 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5609 (and (boundp 'non-essential) (symbol-value 'non-essential))
a6e96327
MA
5610 tramp-completion-mode
5611 ;; Emacs.
94be87e8 5612 (equal last-input-event 'tab)
6c4e47fa 5613 (and (natnump last-input-event)
94be87e8 5614 (or
a6e96327 5615 ;; ?\t has event-modifier 'control.
800a97b8 5616 (equal last-input-event ?\t)
94be87e8 5617 (and (not (event-modifiers last-input-event))
800a97b8
SM
5618 (or (equal last-input-event ?\?)
5619 (equal last-input-event ?\ )))))
a6e96327 5620 ;; XEmacs.
6c4e47fa
MA
5621 (and (featurep 'xemacs)
5622 ;; `last-input-event' might be nil.
5623 (not (null last-input-event))
5624 ;; `last-input-event' may have no character approximation.
5625 (funcall (symbol-function 'event-to-character) last-input-event)
94be87e8 5626 (or
a6e96327 5627 ;; ?\t has event-modifier 'control.
800a97b8 5628 (equal
94be87e8
MA
5629 (funcall (symbol-function 'event-to-character)
5630 last-input-event) ?\t)
5631 (and (not (event-modifiers last-input-event))
800a97b8 5632 (or (equal
94be87e8
MA
5633 (funcall (symbol-function 'event-to-character)
5634 last-input-event) ?\?)
800a97b8 5635 (equal
94be87e8
MA
5636 (funcall (symbol-function 'event-to-character)
5637 last-input-event) ?\ )))))))
16674e4f 5638
16674e4f
KG
5639;; Method, host name and user name completion.
5640;; `tramp-completion-dissect-file-name' returns a list of
5641;; tramp-file-name structures. For all of them we return possible completions.
a01b1e22 5642;;;###autoload
16674e4f 5643(defun tramp-completion-handle-file-name-all-completions (filename directory)
00d6fd04 5644 "Like `file-name-all-completions' for partial Tramp files."
16674e4f 5645
00d6fd04
MA
5646 (let* ((fullname (tramp-drop-volume-letter
5647 (expand-file-name filename directory)))
5648 ;; Possible completion structures.
5649 (v (tramp-completion-dissect-file-name fullname))
5650 result result1)
5651
5652 (while v
5653 (let* ((car (car v))
5654 (method (tramp-file-name-method car))
5655 (user (tramp-file-name-user car))
5656 (host (tramp-file-name-host car))
5657 (localname (tramp-file-name-localname car))
5658 (m (tramp-find-method method user host))
5659 (tramp-current-user user) ; see `tramp-parse-passwd'
5660 all-user-hosts)
5661
5662 (unless localname ;; Nothing to complete.
5663
5664 (if (or user host)
5665
5666 ;; Method dependent user / host combinations.
5667 (progn
9e6ab520 5668 (mapc
00d6fd04
MA
5669 (lambda (x)
5670 (setq all-user-hosts
5671 (append all-user-hosts
5672 (funcall (nth 0 x) (nth 1 x)))))
5673 (tramp-get-completion-function m))
5674
9e6ab520
MA
5675 (setq result
5676 (append result
5677 (mapcar
5678 (lambda (x)
5679 (tramp-get-completion-user-host
5680 method user host (nth 0 x) (nth 1 x)))
5681 (delq nil all-user-hosts)))))
00d6fd04
MA
5682
5683 ;; Possible methods.
5684 (setq result
5685 (append result (tramp-get-completion-methods m)))))
5686
5687 (setq v (cdr v))))
5688
5689 ;; Unify list, remove nil elements.
5690 (while result
5691 (let ((car (car result)))
5692 (when car
5693 (add-to-list
5694 'result1
5695 (substring car (length (tramp-drop-volume-letter directory)))))
5696 (setq result (cdr result))))
5697
5698 ;; Complete local parts.
5699 (append
5700 result1
5701 (condition-case nil
5702 (tramp-completion-run-real-handler
5703 'file-name-all-completions (list filename directory))
5704 (error nil)))))
16674e4f
KG
5705
5706;; Method, host name and user name completion for a file.
a01b1e22 5707;;;###autoload
e1e17cae
MA
5708(defun tramp-completion-handle-file-name-completion
5709 (filename directory &optional predicate)
00d6fd04 5710 "Like `file-name-completion' for Tramp files."
e1e17cae
MA
5711 (try-completion
5712 filename
5713 (mapcar 'list (file-name-all-completions filename directory))
83e20b5c
MA
5714 (when predicate
5715 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
16674e4f
KG
5716
5717;; I misuse a little bit the tramp-file-name structure in order to handle
5718;; completion possibilities for partial methods / user names / host names.
5719;; Return value is a list of tramp-file-name structures according to possible
00d6fd04 5720;; completions. If "localname" is non-nil it means there
16674e4f
KG
5721;; shouldn't be a completion anymore.
5722
5723;; Expected results:
5724
00d6fd04
MA
5725;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5726;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5727;; [nil "x" nil nil]
5728;; ["x" nil nil nil]
5729
5730;; "/x:" "/x:y" "/x:y:"
5731;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5732;; "/[x/" "/[x/y"
5733;; ["x" nil "" nil] ["x" nil "y" nil]
5734;; ["x" "" nil nil] ["x" "y" nil nil]
5735
5736;; "/x:y@" "/x:y@z" "/x:y@z:"
5737;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5738;; "/[x/y@" "/[x/y@z"
5739;; ["x" nil "y" nil] ["x" "y" "z" nil]
16674e4f
KG
5740(defun tramp-completion-dissect-file-name (name)
5741 "Returns a list of `tramp-file-name' structures.
5742They are collected by `tramp-completion-dissect-file-name1'."
5743
5744 (let* ((result)
4007ba5b 5745 (x-nil "\\|\\(\\)")
b96e6899
MA
5746 (tramp-completion-ipv6-regexp
5747 (format
5748 "[^%s]*"
5749 (if (zerop (length tramp-postfix-ipv6-format))
5750 tramp-postfix-host-format
5751 tramp-postfix-ipv6-format)))
4007ba5b
KG
5752 ;; "/method" "/[method"
5753 (tramp-completion-file-name-structure1
5754 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5755 1 nil nil nil))
5756 ;; "/user" "/[user"
5757 (tramp-completion-file-name-structure2
5758 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5759 nil 1 nil nil))
5760 ;; "/host" "/[host"
5761 (tramp-completion-file-name-structure3
5762 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5763 nil nil 1 nil))
b96e6899 5764 ;; "/[ipv6" "/[ipv6"
4007ba5b 5765 (tramp-completion-file-name-structure4
b96e6899
MA
5766 (list (concat tramp-prefix-regexp
5767 tramp-prefix-ipv6-regexp
5768 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5769 nil nil 1 nil))
5770 ;; "/user@host" "/[user@host"
5771 (tramp-completion-file-name-structure5
4007ba5b
KG
5772 (list (concat tramp-prefix-regexp
5773 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5774 "\\(" tramp-host-regexp x-nil "\\)$")
5775 nil 1 2 nil))
b96e6899
MA
5776 ;; "/user@[ipv6" "/[user@ipv6"
5777 (tramp-completion-file-name-structure6
5778 (list (concat tramp-prefix-regexp
5779 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5780 tramp-prefix-ipv6-regexp
5781 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5782 nil 1 2 nil))
00d6fd04 5783 ;; "/method:user" "/[method/user" "/method://user"
b96e6899 5784 (tramp-completion-file-name-structure7
4007ba5b 5785 (list (concat tramp-prefix-regexp
00d6fd04 5786 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5787 "\\(" tramp-user-regexp x-nil "\\)$")
5788 1 2 nil nil))
00d6fd04 5789 ;; "/method:host" "/[method/host" "/method://host"
b96e6899 5790 (tramp-completion-file-name-structure8
4007ba5b 5791 (list (concat tramp-prefix-regexp
00d6fd04 5792 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5793 "\\(" tramp-host-regexp x-nil "\\)$")
5794 1 nil 2 nil))
b96e6899
MA
5795 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5796 (tramp-completion-file-name-structure9
5797 (list (concat tramp-prefix-regexp
5798 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5799 tramp-prefix-ipv6-regexp
5800 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5801 1 nil 2 nil))
00d6fd04 5802 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
b96e6899 5803 (tramp-completion-file-name-structure10
4007ba5b 5804 (list (concat tramp-prefix-regexp
00d6fd04 5805 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5806 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5807 "\\(" tramp-host-regexp x-nil "\\)$")
00d6fd04 5808 1 2 3 nil))
b96e6899
MA
5809 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5810 (tramp-completion-file-name-structure11
5811 (list (concat tramp-prefix-regexp
5812 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5813 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5814 tramp-prefix-ipv6-regexp
5815 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5816 1 2 3 nil))
00d6fd04 5817 ;; "/method: "/method:/"
b96e6899 5818 (tramp-completion-file-name-structure12
00d6fd04
MA
5819 (list
5820 (if (equal tramp-syntax 'url)
5821 (concat tramp-prefix-regexp
5822 "\\(" tramp-method-regexp "\\)"
5823 "\\(" (substring tramp-postfix-method-regexp 0 1)
5824 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5825 "\\(" "\\)$")
5826 ;; Should not match if not URL syntax.
5827 (concat tramp-prefix-regexp "/$"))
5828 1 3 nil nil))
5829 ;; "/method: "/method:/"
b96e6899 5830 (tramp-completion-file-name-structure13
00d6fd04
MA
5831 (list
5832 (if (equal tramp-syntax 'url)
5833 (concat tramp-prefix-regexp
5834 "\\(" tramp-method-regexp "\\)"
5835 "\\(" (substring tramp-postfix-method-regexp 0 1)
5836 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5837 "\\(" "\\)$")
5838 ;; Should not match if not URL syntax.
5839 (concat tramp-prefix-regexp "/$"))
5840 1 nil 3 nil)))
4007ba5b 5841
9e6ab520 5842 (mapc (lambda (regexp)
16674e4f
KG
5843 (add-to-list 'result
5844 (tramp-completion-dissect-file-name1 regexp name)))
5845 (list
5846 tramp-completion-file-name-structure1
5847 tramp-completion-file-name-structure2
5848 tramp-completion-file-name-structure3
5849 tramp-completion-file-name-structure4
5850 tramp-completion-file-name-structure5
5851 tramp-completion-file-name-structure6
5852 tramp-completion-file-name-structure7
00d6fd04
MA
5853 tramp-completion-file-name-structure8
5854 tramp-completion-file-name-structure9
b96e6899
MA
5855 tramp-completion-file-name-structure10
5856 tramp-completion-file-name-structure11
5857 tramp-completion-file-name-structure12
5858 tramp-completion-file-name-structure13
16674e4f
KG
5859 tramp-file-name-structure))
5860
5861 (delq nil result)))
5862
5863(defun tramp-completion-dissect-file-name1 (structure name)
5864 "Returns a `tramp-file-name' structure matching STRUCTURE.
00d6fd04 5865The structure consists of remote method, remote user,
7432277c 5866remote host and localname (filename on remote host)."
fb7933a3 5867
00d6fd04
MA
5868 (save-match-data
5869 (when (string-match (nth 0 structure) name)
5870 (let ((method (and (nth 1 structure)
5871 (match-string (nth 1 structure) name)))
5872 (user (and (nth 2 structure)
5873 (match-string (nth 2 structure) name)))
5874 (host (and (nth 3 structure)
5875 (match-string (nth 3 structure) name)))
5876 (localname (and (nth 4 structure)
5877 (match-string (nth 4 structure) name))))
5878 (vector method user host localname)))))
16674e4f
KG
5879
5880;; This function returns all possible method completions, adding the
5881;; trailing method delimeter.
16674e4f
KG
5882(defun tramp-get-completion-methods (partial-method)
5883 "Returns all method completions for PARTIAL-METHOD."
4007ba5b
KG
5884 (mapcar
5885 (lambda (method)
5886 (and method
5887 (string-match (concat "^" (regexp-quote partial-method)) method)
00d6fd04
MA
5888 (tramp-completion-make-tramp-file-name method nil nil nil)))
5889 (mapcar 'car tramp-methods)))
16674e4f
KG
5890
5891;; Compares partial user and host names with possible completions.
5892(defun tramp-get-completion-user-host (method partial-user partial-host user host)
5893 "Returns the most expanded string for user and host name completion.
5894PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5895 (cond
5896
5897 ((and partial-user partial-host)
5898 (if (and host
5899 (string-match (concat "^" (regexp-quote partial-host)) host)
5900 (string-equal partial-user (or user partial-user)))
5901 (setq user partial-user)
5902 (setq user nil
5903 host nil)))
5904
5905 (partial-user
5906 (setq host nil)
5907 (unless
5908 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5909 (setq user nil)))
5910
5911 (partial-host
5912 (setq user nil)
5913 (unless
5914 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5915 (setq host nil)))
5916
5917 (t (setq user nil
5918 host nil)))
5919
292ffc15 5920 (unless (zerop (+ (length user) (length host)))
00d6fd04 5921 (tramp-completion-make-tramp-file-name method user host nil)))
16674e4f
KG
5922
5923(defun tramp-parse-rhosts (filename)
5924 "Return a list of (user host) tuples allowed to access.
292ffc15 5925Either user or host may be nil."
00d6fd04
MA
5926 ;; On Windows, there are problems in completion when
5927 ;; `default-directory' is remote.
9e6ab520 5928 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5929 res)
8daea7fc 5930 (when (file-readable-p filename)
16674e4f
KG
5931 (with-temp-buffer
5932 (insert-file-contents filename)
5933 (goto-char (point-min))
5934 (while (not (eobp))
292ffc15 5935 (push (tramp-parse-rhosts-group) res))))
16674e4f
KG
5936 res))
5937
16674e4f
KG
5938(defun tramp-parse-rhosts-group ()
5939 "Return a (user host) tuple allowed to access.
292ffc15 5940Either user or host may be nil."
16674e4f
KG
5941 (let ((result)
5942 (regexp
5943 (concat
5944 "^\\(" tramp-host-regexp "\\)"
5945 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 5946 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5947 (when (re-search-forward regexp nil t)
5948 (setq result (append (list (match-string 3) (match-string 1)))))
5949 (widen)
5950 (forward-line 1)
5951 result))
5952
5953(defun tramp-parse-shosts (filename)
5954 "Return a list of (user host) tuples allowed to access.
5955User is always nil."
00d6fd04
MA
5956 ;; On Windows, there are problems in completion when
5957 ;; `default-directory' is remote.
9e6ab520 5958 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5959 res)
8daea7fc 5960 (when (file-readable-p filename)
16674e4f
KG
5961 (with-temp-buffer
5962 (insert-file-contents filename)
5963 (goto-char (point-min))
5964 (while (not (eobp))
292ffc15 5965 (push (tramp-parse-shosts-group) res))))
16674e4f
KG
5966 res))
5967
5968(defun tramp-parse-shosts-group ()
5969 "Return a (user host) tuple allowed to access.
5970User is always nil."
16674e4f
KG
5971 (let ((result)
5972 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
9e6ab520 5973 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5974 (when (re-search-forward regexp nil t)
5975 (setq result (list nil (match-string 1))))
5976 (widen)
5977 (or
5978 (> (skip-chars-forward ",") 0)
5979 (forward-line 1))
5980 result))
5981
8daea7fc
KG
5982(defun tramp-parse-sconfig (filename)
5983 "Return a list of (user host) tuples allowed to access.
5984User is always nil."
00d6fd04
MA
5985 ;; On Windows, there are problems in completion when
5986 ;; `default-directory' is remote.
9e6ab520 5987 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5988 res)
8daea7fc
KG
5989 (when (file-readable-p filename)
5990 (with-temp-buffer
5991 (insert-file-contents filename)
5992 (goto-char (point-min))
5993 (while (not (eobp))
5994 (push (tramp-parse-sconfig-group) res))))
5995 res))
5996
5997(defun tramp-parse-sconfig-group ()
5998 "Return a (user host) tuple allowed to access.
5999User is always nil."
8daea7fc
KG
6000 (let ((result)
6001 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
9e6ab520 6002 (narrow-to-region (point) (tramp-compat-line-end-position))
8daea7fc
KG
6003 (when (re-search-forward regexp nil t)
6004 (setq result (list nil (match-string 1))))
6005 (widen)
6006 (or
6007 (> (skip-chars-forward ",") 0)
6008 (forward-line 1))
6009 result))
6010
5ec2cc41
KG
6011(defun tramp-parse-shostkeys (dirname)
6012 "Return a list of (user host) tuples allowed to access.
6013User is always nil."
00d6fd04
MA
6014 ;; On Windows, there are problems in completion when
6015 ;; `default-directory' is remote.
9e6ab520 6016 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6017 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6018 (files (when (file-directory-p dirname) (directory-files dirname)))
6019 result)
5ec2cc41
KG
6020 (while files
6021 (when (string-match regexp (car files))
6022 (push (list nil (match-string 1 (car files))) result))
6023 (setq files (cdr files)))
6024 result))
6025
6026(defun tramp-parse-sknownhosts (dirname)
6027 "Return a list of (user host) tuples allowed to access.
6028User is always nil."
00d6fd04
MA
6029 ;; On Windows, there are problems in completion when
6030 ;; `default-directory' is remote.
9e6ab520 6031 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6032 (regexp (concat "^\\(" tramp-host-regexp
6033 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6034 (files (when (file-directory-p dirname) (directory-files dirname)))
6035 result)
5ec2cc41
KG
6036 (while files
6037 (when (string-match regexp (car files))
6038 (push (list nil (match-string 1 (car files))) result))
6039 (setq files (cdr files)))
6040 result))
6041
16674e4f
KG
6042(defun tramp-parse-hosts (filename)
6043 "Return a list of (user host) tuples allowed to access.
6044User is always nil."
00d6fd04
MA
6045 ;; On Windows, there are problems in completion when
6046 ;; `default-directory' is remote.
9e6ab520 6047 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6048 res)
8daea7fc 6049 (when (file-readable-p filename)
16674e4f
KG
6050 (with-temp-buffer
6051 (insert-file-contents filename)
6052 (goto-char (point-min))
6053 (while (not (eobp))
292ffc15 6054 (push (tramp-parse-hosts-group) res))))
16674e4f
KG
6055 res))
6056
6057(defun tramp-parse-hosts-group ()
6058 "Return a (user host) tuple allowed to access.
6059User is always nil."
16674e4f 6060 (let ((result)
b96e6899
MA
6061 (regexp
6062 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
9e6ab520 6063 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f 6064 (when (re-search-forward regexp nil t)
b96e6899 6065 (setq result (list nil (match-string 1))))
16674e4f
KG
6066 (widen)
6067 (or
6068 (> (skip-chars-forward " \t") 0)
6069 (forward-line 1))
6070 result))
6071
8daea7fc
KG
6072;; For su-alike methods it would be desirable to return "root@localhost"
6073;; as default. Unfortunately, we have no information whether any user name
00d6fd04 6074;; has been typed already. So we use `tramp-current-user' as indication,
8daea7fc 6075;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
16674e4f
KG
6076(defun tramp-parse-passwd (filename)
6077 "Return a list of (user host) tuples allowed to access.
6078Host is always \"localhost\"."
00d6fd04
MA
6079 ;; On Windows, there are problems in completion when
6080 ;; `default-directory' is remote.
9e6ab520 6081 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6082 res)
8daea7fc 6083 (if (zerop (length tramp-current-user))
16674e4f 6084 '(("root" nil))
8daea7fc 6085 (when (file-readable-p filename)
16674e4f
KG
6086 (with-temp-buffer
6087 (insert-file-contents filename)
6088 (goto-char (point-min))
6089 (while (not (eobp))
292ffc15 6090 (push (tramp-parse-passwd-group) res))))
16674e4f
KG
6091 res)))
6092
6093(defun tramp-parse-passwd-group ()
6094 "Return a (user host) tuple allowed to access.
292ffc15 6095Host is always \"localhost\"."
16674e4f
KG
6096 (let ((result)
6097 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
9e6ab520 6098 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
6099 (when (re-search-forward regexp nil t)
6100 (setq result (list (match-string 1) "localhost")))
6101 (widen)
6102 (forward-line 1)
6103 result))
6104
292ffc15
KG
6105(defun tramp-parse-netrc (filename)
6106 "Return a list of (user host) tuples allowed to access.
6107User may be nil."
00d6fd04
MA
6108 ;; On Windows, there are problems in completion when
6109 ;; `default-directory' is remote.
9e6ab520 6110 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6111 res)
8daea7fc 6112 (when (file-readable-p filename)
292ffc15
KG
6113 (with-temp-buffer
6114 (insert-file-contents filename)
6115 (goto-char (point-min))
6116 (while (not (eobp))
6117 (push (tramp-parse-netrc-group) res))))
6118 res))
6119
6120(defun tramp-parse-netrc-group ()
6121 "Return a (user host) tuple allowed to access.
6122User may be nil."
292ffc15
KG
6123 (let ((result)
6124 (regexp
6125 (concat
6126 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6127 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 6128 (narrow-to-region (point) (tramp-compat-line-end-position))
292ffc15
KG
6129 (when (re-search-forward regexp nil t)
6130 (setq result (list (match-string 3) (match-string 1))))
6131 (widen)
6132 (forward-line 1)
6133 result))
6134
00d6fd04
MA
6135(defun tramp-parse-putty (registry)
6136 "Return a list of (user host) tuples allowed to access.
6137User is always nil."
6138 ;; On Windows, there are problems in completion when
6139 ;; `default-directory' is remote.
9e6ab520 6140 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6141 res)
6142 (with-temp-buffer
a4aeb9a4 6143 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
00d6fd04
MA
6144 (goto-char (point-min))
6145 (while (not (eobp))
6146 (push (tramp-parse-putty-group registry) res))))
6147 res))
6148
6149(defun tramp-parse-putty-group (registry)
6150 "Return a (user host) tuple allowed to access.
6151User is always nil."
6152 (let ((result)
6153 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
9e6ab520 6154 (narrow-to-region (point) (tramp-compat-line-end-position))
00d6fd04
MA
6155 (when (re-search-forward regexp nil t)
6156 (setq result (list nil (match-string 1))))
6157 (widen)
6158 (forward-line 1)
6159 result))
6160
fb7933a3
KG
6161;;; Internal Functions:
6162
00d6fd04
MA
6163(defun tramp-maybe-send-script (vec script name)
6164 "Define in remote shell function NAME implemented as SCRIPT.
6165Only send the definition if it has not already been done."
6166 (let* ((p (tramp-get-connection-process vec))
6167 (scripts (tramp-get-connection-property p "scripts" nil)))
1834b39f 6168 (unless (member name scripts)
00d6fd04
MA
6169 (tramp-message vec 5 "Sending script `%s'..." name)
6170 ;; The script could contain a call of Perl. This is masked with `%s'.
6171 (tramp-send-command-and-check
6172 vec
6173 (format "%s () {\n%s\n}" name
6174 (format script (tramp-get-remote-perl vec))))
6175 (tramp-set-connection-property p "scripts" (cons name scripts))
6176 (tramp-message vec 5 "Sending script `%s'...done." name))))
c82c5727 6177
fb7933a3 6178(defun tramp-set-auto-save ()
00d6fd04 6179 (when (and ;; ange-ftp has its own auto-save mechanism
7177e2a3
MA
6180 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6181 'tramp-sh-file-name-handler)
fb7933a3
KG
6182 auto-save-default)
6183 (auto-save-mode 1)))
6184(add-hook 'find-file-hooks 'tramp-set-auto-save t)
a69c01a0 6185(add-hook 'tramp-unload-hook
aa485f7c
MA
6186 (lambda ()
6187 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
fb7933a3
KG
6188
6189(defun tramp-run-test (switch filename)
6190 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6191Returns the exit code of the `test' program."
00d6fd04
MA
6192 (with-parsed-tramp-file-name filename nil
6193 (tramp-send-command-and-check
6194 v
6195 (format
6196 "%s %s %s"
6197 (tramp-get-test-command v)
6198 switch
6199 (tramp-shell-quote-argument localname)))))
6200
6201(defun tramp-run-test2 (format-string file1 file2)
6202 "Run `test'-like program on the remote system, given FILE1, FILE2.
6203FORMAT-STRING contains the program name, switches, and place holders.
6204Returns the exit code of the `test' program. Barfs if the methods,
fb7933a3 6205hosts, or files, disagree."
00d6fd04
MA
6206 (unless (tramp-equal-remote file1 file2)
6207 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6208 (tramp-error
6209 v 'file-error
6210 "tramp-run-test2 only implemented for same method, user, host")))
6211 (with-parsed-tramp-file-name file1 v1
6212 (with-parsed-tramp-file-name file1 v2
fb7933a3 6213 (tramp-send-command-and-check
00d6fd04
MA
6214 v1
6215 (format format-string
6216 (tramp-shell-quote-argument v1-localname)
6217 (tramp-shell-quote-argument v2-localname))))))
fb7933a3 6218
00d6fd04
MA
6219(defun tramp-buffer-name (vec)
6220 "A name for the connection buffer VEC."
6221 ;; We must use `tramp-file-name-real-host', because for gateway
6222 ;; methods the default port will be expanded later on, which would
6223 ;; tamper the name.
6224 (let ((method (tramp-file-name-method vec))
6225 (user (tramp-file-name-user vec))
6226 (host (tramp-file-name-real-host vec)))
6227 (if (not (zerop (length user)))
6228 (format "*tramp/%s %s@%s*" method user host)
6229 (format "*tramp/%s %s*" method host))))
6230
b88f2d0a
MA
6231(defun tramp-delete-temp-file-function ()
6232 "Remove temporary files related to current buffer."
6233 (when (stringp tramp-temp-buffer-file-name)
6234 (condition-case nil
6235 (delete-file tramp-temp-buffer-file-name)
6236 (error nil))))
6237
6238(add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6239(add-hook 'tramp-cache-unload-hook
6240 (lambda ()
6241 (remove-hook 'kill-buffer-hook
6242 'tramp-delete-temp-file-function)))
6243
00d6fd04
MA
6244(defun tramp-get-buffer (vec)
6245 "Get the connection buffer to be used for VEC."
6246 (or (get-buffer (tramp-buffer-name vec))
6247 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6248 (setq buffer-undo-list t)
6249 (setq default-directory
6250 (tramp-make-tramp-file-name
6251 (tramp-file-name-method vec)
6252 (tramp-file-name-user vec)
6253 (tramp-file-name-host vec)
6254 "/"))
6255 (current-buffer))))
6256
6257(defun tramp-get-connection-buffer (vec)
6258 "Get the connection buffer to be used for VEC.
6259In case a second asynchronous communication has been started, it is different
6260from `tramp-get-buffer'."
6261 (or (tramp-get-connection-property vec "process-buffer" nil)
6262 (tramp-get-buffer vec)))
6263
6264(defun tramp-get-connection-process (vec)
6265 "Get the connection process to be used for VEC.
6266In case a second asynchronous communication has been started, it is different
6267from the default one."
6268 (get-process
6269 (or (tramp-get-connection-property vec "process-name" nil)
6270 (tramp-buffer-name vec))))
6271
6272(defun tramp-debug-buffer-name (vec)
6273 "A name for the debug buffer for VEC."
6274 ;; We must use `tramp-file-name-real-host', because for gateway
6275 ;; methods the default port will be expanded later on, which would
6276 ;; tamper the name.
6277 (let ((method (tramp-file-name-method vec))
6278 (user (tramp-file-name-user vec))
6279 (host (tramp-file-name-real-host vec)))
6280 (if (not (zerop (length user)))
6281 (format "*debug tramp/%s %s@%s*" method user host)
6282 (format "*debug tramp/%s %s*" method host))))
6283
b533bc97
MA
6284(defconst tramp-debug-outline-regexp
6285 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6286
00d6fd04
MA
6287(defun tramp-get-debug-buffer (vec)
6288 "Get the debug buffer for VEC."
01917a18 6289 (with-current-buffer
00d6fd04
MA
6290 (get-buffer-create (tramp-debug-buffer-name vec))
6291 (when (bobp)
6292 (setq buffer-undo-list t)
b533bc97 6293 ;; Activate `outline-mode'. This runs `text-mode-hook' and
9ce8462a 6294 ;; `outline-mode-hook'. We must prevent that local processes
b533bc97
MA
6295 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6296 ;; Furthermore, `outline-regexp' must have the correct value
6297 ;; already, because it is used by `font-lock-compile-keywords'.
6298 (let ((default-directory (tramp-compat-temporary-file-directory))
6299 (outline-regexp tramp-debug-outline-regexp))
00d6fd04 6300 (outline-mode))
b533bc97 6301 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
9ce8462a 6302 (set (make-local-variable 'outline-level) 'tramp-outline-level))
01917a18 6303 (current-buffer)))
fb7933a3 6304
00d6fd04
MA
6305(defun tramp-outline-level ()
6306 "Return the depth to which a statement is nested in the outline.
6307Point must be at the beginning of a header line.
6308
6309The outline level is equal to the verbosity of the Tramp message."
6310 (1+ (string-to-number (match-string 1))))
fb7933a3 6311
00d6fd04
MA
6312(defun tramp-find-executable
6313 (vec progname dirlist &optional ignore-tilde ignore-path)
6314 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6315First arg VEC specifies the connection, PROGNAME is the program
6316to search for, and DIRLIST gives the list of directories to
6317search. If IGNORE-TILDE is non-nil, directory names starting
6318with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6319only in DIRLIST.
fb7933a3 6320
7432277c 6321Returns the absolute file name of PROGNAME, if found, and nil otherwise.
fb7933a3
KG
6322
6323This function expects to be in the right *tramp* buffer."
c0e17ff2 6324 (with-current-buffer (tramp-get-connection-buffer vec)
00d6fd04
MA
6325 (let (result)
6326 ;; Check whether the executable is in $PATH. "which(1)" does not
6327 ;; report always a correct error code; therefore we check the
6328 ;; number of words it returns.
6329 (unless ignore-path
6330 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6331 (goto-char (point-min))
c0e17ff2 6332 (if (looking-at "^\\s-*1$")
00d6fd04
MA
6333 (setq result (concat "\\" progname))))
6334 (unless result
6335 (when ignore-tilde
b533bc97 6336 ;; Remove all ~/foo directories from dirlist. In XEmacs,
00d6fd04
MA
6337 ;; `remove' is in CL, and we want to avoid CL dependencies.
6338 (let (newdl d)
6339 (while dirlist
6340 (setq d (car dirlist))
6341 (setq dirlist (cdr dirlist))
6342 (unless (char-equal ?~ (aref d 0))
6343 (setq newdl (cons d newdl))))
6344 (setq dirlist (nreverse newdl))))
6345 (tramp-send-command
6346 vec
6347 (format (concat "while read d; "
6348 "do if test -x $d/%s -a -f $d/%s; "
6349 "then echo tramp_executable $d/%s; "
6350 "break; fi; done <<'EOF'\n"
6351 "%s\nEOF")
6352 progname progname progname (mapconcat 'identity dirlist "\n")))
6353 (goto-char (point-max))
6354 (when (search-backward "tramp_executable " nil t)
6355 (skip-chars-forward "^ ")
6356 (skip-chars-forward " ")
9e6ab520
MA
6357 (setq result (buffer-substring
6358 (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
6359 result)))
6360
6361(defun tramp-set-remote-path (vec)
6362 "Sets the remote environment PATH to existing directories.
6363I.e., for each directory in `tramp-remote-path', it is tested
6364whether it exists and if so, it is added to the environment
6365variable PATH."
6366 (tramp-message vec 5 (format "Setting $PATH environment variable"))
f84638eb
MA
6367 (tramp-send-command
6368 vec (format "PATH=%s; export PATH"
6369 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
fb7933a3 6370
cfb5c0db
MA
6371;; ------------------------------------------------------------
6372;; -- Communication with external shell --
6373;; ------------------------------------------------------------
fb7933a3 6374
00d6fd04 6375(defun tramp-find-file-exists-command (vec)
fb7933a3
KG
6376 "Find a command on the remote host for checking if a file exists.
6377Here, we are looking for a command which has zero exit status if the
6378file exists and nonzero exit status otherwise."
00d6fd04 6379 (let ((existing "/")
fb7933a3 6380 (nonexisting
00d6fd04
MA
6381 (tramp-shell-quote-argument "/ this file does not exist "))
6382 result)
fb7933a3
KG
6383 ;; The algorithm is as follows: we try a list of several commands.
6384 ;; For each command, we first run `$cmd /' -- this should return
6385 ;; true, as the root directory always exists. And then we run
00d6fd04 6386 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
fb7933a3
KG
6387 ;; does not exist. This should return false. We use the first
6388 ;; command we find that seems to work.
6389 ;; The list of commands to try is as follows:
00d6fd04
MA
6390 ;; `ls -d' This works on most systems, but NetBSD 1.4
6391 ;; has a bug: `ls' always returns zero exit
6392 ;; status, even for files which don't exist.
6393 ;; `test -e' Some Bourne shells have a `test' builtin
6394 ;; which does not know the `-e' option.
6395 ;; `/bin/test -e' For those, the `test' binary on disk normally
6396 ;; provides the option. Alas, the binary
6397 ;; is sometimes `/bin/test' and sometimes it's
6398 ;; `/usr/bin/test'.
6399 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
fb7933a3 6400 (unless (or
00d6fd04
MA
6401 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6402 (zerop (tramp-send-command-and-check
6403 vec (format "%s %s" result existing)))
6404 (not (zerop (tramp-send-command-and-check
6405 vec (format "%s %s" result nonexisting)))))
6406 (and (setq result "/bin/test -e")
6407 (zerop (tramp-send-command-and-check
6408 vec (format "%s %s" result existing)))
6409 (not (zerop (tramp-send-command-and-check
6410 vec (format "%s %s" result nonexisting)))))
6411 (and (setq result "/usr/bin/test -e")
6412 (zerop (tramp-send-command-and-check
6413 vec (format "%s %s" result existing)))
6414 (not (zerop (tramp-send-command-and-check
6415 vec (format "%s %s" result nonexisting)))))
6416 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6417 (zerop (tramp-send-command-and-check
6418 vec (format "%s %s" result existing)))
6419 (not (zerop (tramp-send-command-and-check
6420 vec (format "%s %s" result nonexisting))))))
6421 (tramp-error
6422 vec 'file-error "Couldn't find command to check if file exists"))
6423 result))
bf247b6e 6424
fb7933a3 6425;; CCC test ksh or bash found for tilde expansion?
00d6fd04
MA
6426(defun tramp-find-shell (vec)
6427 "Opens a shell on the remote host which groks tilde expansion."
6428 (unless (tramp-get-connection-property vec "remote-shell" nil)
6429 (let (shell)
6430 (with-current-buffer (tramp-get-buffer vec)
7e780ff1 6431 (tramp-send-command vec "echo ~root" t)
00d6fd04 6432 (cond
c0e17ff2
MA
6433 ((or (string-match "^~root$" (buffer-string))
6434 ;; The default shell (ksh93) of OpenSolaris is buggy.
6435 (string-equal (tramp-get-connection-property vec "uname" "")
6436 "SunOS 5.11"))
00d6fd04 6437 (setq shell
f84638eb 6438 (or (tramp-find-executable
c0e17ff2 6439 vec "bash" (tramp-get-remote-path vec) t t)
f84638eb 6440 (tramp-find-executable
c0e17ff2 6441 vec "ksh" (tramp-get-remote-path vec) t t)))
00d6fd04
MA
6442 (unless shell
6443 (tramp-error
6444 vec 'file-error
6445 "Couldn't find a shell which groks tilde expansion"))
6446 ;; Find arguments for this shell.
6447 (let ((alist tramp-sh-extra-args)
6448 item extra-args)
6449 (while (and alist (null extra-args))
6450 (setq item (pop alist))
6451 (when (string-match (car item) shell)
6452 (setq extra-args (cdr item))))
6453 (when extra-args (setq shell (concat shell " " extra-args))))
6454 (tramp-message
6455 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
dab816a9 6456 (let ((tramp-end-of-output tramp-initial-end-of-output))
a4aeb9a4 6457 (tramp-send-command
b08104a0 6458 vec
70c11b0b
MA
6459 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6460 (shell-quote-argument tramp-end-of-output) shell)
b08104a0 6461 t))
a0a5183a 6462 ;; Setting prompts.
00d6fd04 6463 (tramp-message vec 5 "Setting remote shell prompt...")
70c11b0b
MA
6464 (tramp-send-command
6465 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
6466 (tramp-send-command vec "PS2=''" t)
6467 (tramp-send-command vec "PS3=''" t)
6468 (tramp-send-command vec "PROMPT_COMMAND=''" t)
00d6fd04 6469 (tramp-message vec 5 "Setting remote shell prompt...done"))
a0a5183a 6470
00d6fd04
MA
6471 (t (tramp-message
6472 vec 5 "Remote `%s' groks tilde expansion, good"
6473 (tramp-get-method-parameter
6474 (tramp-file-name-method vec) 'tramp-remote-sh))
6475 (tramp-set-connection-property
6476 vec "remote-shell"
6477 (tramp-get-method-parameter
6478 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
fb7933a3 6479
bf247b6e
KS
6480;; ------------------------------------------------------------
6481;; -- Functions for establishing connection --
6482;; ------------------------------------------------------------
fb7933a3 6483
ac474af1
KG
6484;; The following functions are actions to be taken when seeing certain
6485;; prompts from the remote host. See the variable
6486;; `tramp-actions-before-shell' for usage of these functions.
6487
00d6fd04 6488(defun tramp-action-login (proc vec)
ac474af1 6489 "Send the login name."
00d6fd04
MA
6490 (when (not (stringp tramp-current-user))
6491 (save-window-excursion
6492 (let ((enable-recursive-minibuffers t))
6493 (pop-to-buffer (tramp-get-connection-buffer vec))
6494 (setq tramp-current-user (read-string (match-string 0))))))
6495 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6496 (with-current-buffer (tramp-get-connection-buffer vec)
6497 (tramp-message vec 6 "\n%s" (buffer-string)))
6498 (tramp-send-string vec tramp-current-user))
6499
6500(defun tramp-action-password (proc vec)
ac474af1 6501 "Query the user for a password."
70c11b0b
MA
6502 (with-current-buffer (process-buffer proc)
6503 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6504 (tramp-message vec 3 "Sending %s" (match-string 1)))
00d6fd04
MA
6505 (tramp-enter-password proc))
6506
6507(defun tramp-action-succeed (proc vec)
ac474af1 6508 "Signal success in finding shell prompt."
ac474af1
KG
6509 (throw 'tramp-action 'ok))
6510
00d6fd04 6511(defun tramp-action-permission-denied (proc vec)
ac474af1 6512 "Signal permission denied."
00d6fd04 6513 (kill-process proc)
ac474af1
KG
6514 (throw 'tramp-action 'permission-denied))
6515
00d6fd04 6516(defun tramp-action-yesno (proc vec)
3cdaec13
KG
6517 "Ask the user for confirmation using `yes-or-no-p'.
6518Send \"yes\" to remote process on confirmation, abort otherwise.
6519See also `tramp-action-yn'."
ac474af1 6520 (save-window-excursion
00d6fd04
MA
6521 (let ((enable-recursive-minibuffers t))
6522 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6523 (unless (yes-or-no-p (match-string 0))
6524 (kill-process proc)
6525 (throw 'tramp-action 'permission-denied))
6526 (with-current-buffer (tramp-get-connection-buffer vec)
6527 (tramp-message vec 6 "\n%s" (buffer-string)))
6528 (tramp-send-string vec "yes"))))
6529
6530(defun tramp-action-yn (proc vec)
3cdaec13
KG
6531 "Ask the user for confirmation using `y-or-n-p'.
6532Send \"y\" to remote process on confirmation, abort otherwise.
6533See also `tramp-action-yesno'."
6534 (save-window-excursion
00d6fd04
MA
6535 (let ((enable-recursive-minibuffers t))
6536 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6537 (unless (y-or-n-p (match-string 0))
6538 (kill-process proc)
6539 (throw 'tramp-action 'permission-denied))
6540 (with-current-buffer (tramp-get-connection-buffer vec)
6541 (tramp-message vec 6 "\n%s" (buffer-string)))
6542 (tramp-send-string vec "y"))))
6543
6544(defun tramp-action-terminal (proc vec)
487f4fb7
KG
6545 "Tell the remote host which terminal type to use.
6546The terminal type can be configured with `tramp-terminal-type'."
00d6fd04 6547 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
7e780ff1
MA
6548 (with-current-buffer (tramp-get-connection-buffer vec)
6549 (tramp-message vec 6 "\n%s" (buffer-string)))
00d6fd04 6550 (tramp-send-string vec tramp-terminal-type))
487f4fb7 6551
00d6fd04 6552(defun tramp-action-process-alive (proc vec)
19a87064 6553 "Check whether a process has finished."
00d6fd04 6554 (unless (memq (process-status proc) '(run open))
19a87064
MA
6555 (throw 'tramp-action 'process-died)))
6556
00d6fd04 6557(defun tramp-action-out-of-band (proc vec)
38c65fca 6558 "Check whether an out-of-band copy has finished."
00d6fd04
MA
6559 (cond ((and (memq (process-status proc) '(stop exit))
6560 (zerop (process-exit-status proc)))
6561 (tramp-message vec 3 "Process has finished.")
38c65fca 6562 (throw 'tramp-action 'ok))
00d6fd04
MA
6563 ((or (and (memq (process-status proc) '(stop exit))
6564 (not (zerop (process-exit-status proc))))
6565 (memq (process-status proc) '(signal)))
01917a18
MA
6566 ;; `scp' could have copied correctly, but set modes could have failed.
6567 ;; This can be ignored.
00d6fd04
MA
6568 (with-current-buffer (process-buffer proc)
6569 (goto-char (point-min))
6570 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6571 (progn
6572 (tramp-message vec 5 "'set mode' error ignored.")
6573 (tramp-message vec 3 "Process has finished.")
6574 (throw 'tramp-action 'ok))
6575 (tramp-message vec 3 "Process has died.")
6576 (throw 'tramp-action 'process-died))))
38c65fca
KG
6577 (t nil)))
6578
ac474af1
KG
6579;; Functions for processing the actions.
6580
00d6fd04 6581(defun tramp-process-one-action (proc vec actions)
ac474af1 6582 "Wait for output from the shell and perform one action."
00d6fd04 6583 (let (found todo item pattern action)
e6466697 6584 (while (not found)
00d6fd04
MA
6585 ;; Reread output once all actions have been performed.
6586 ;; Obviously, the output was not complete.
6587 (tramp-accept-process-output proc 1)
e6466697
MA
6588 (setq todo actions)
6589 (while todo
e6466697 6590 (setq item (pop todo))
95d610cb 6591 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
e6466697 6592 (setq action (nth 1 item))
00d6fd04
MA
6593 (tramp-message
6594 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6595 (when (tramp-check-for-regexp proc pattern)
6596 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6597 (setq found (funcall action proc vec)))))
e6466697
MA
6598 found))
6599
00d6fd04 6600(defun tramp-process-actions (proc vec actions &optional timeout)
e6466697 6601 "Perform actions until success or TIMEOUT."
263c02ef 6602 ;; Enable auth-source and password-cache.
7540f029 6603 (tramp-set-connection-property vec "first-password-request" t)
ac474af1
KG
6604 (let (exit)
6605 (while (not exit)
00d6fd04 6606 (tramp-message proc 3 "Waiting for prompts from remote shell")
ac474af1
KG
6607 (setq exit
6608 (catch 'tramp-action
e6466697
MA
6609 (if timeout
6610 (with-timeout (timeout)
00d6fd04
MA
6611 (tramp-process-one-action proc vec actions))
6612 (tramp-process-one-action proc vec actions)))))
6613 (with-current-buffer (tramp-get-connection-buffer vec)
6614 (tramp-message vec 6 "\n%s" (buffer-string)))
ac474af1 6615 (unless (eq exit 'ok)
9c13938d 6616 (tramp-clear-passwd vec)
00d6fd04
MA
6617 (tramp-error-with-buffer
6618 nil vec 'file-error
6619 (cond
6620 ((eq exit 'permission-denied) "Permission denied")
6621 ((eq exit 'process-died) "Process died")
6622 (t "Login failed"))))))
fb7933a3
KG
6623
6624;; Utility functions.
6625
00d6fd04 6626(defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
d2a2c17f
MA
6627 "Like `accept-process-output' for Tramp processes.
6628This is needed in order to hide `last-coding-system-used', which is set
6629for process communication also."
00d6fd04
MA
6630 (with-current-buffer (process-buffer proc)
6631 (tramp-message proc 10 "%s %s" proc (process-status proc))
6632 (let (buffer-read-only last-coding-system-used)
6633 ;; Under Windows XP, accept-process-output doesn't return
6634 ;; sometimes. So we add an additional timeout.
6635 (with-timeout ((or timeout 1))
6636 (accept-process-output proc timeout timeout-msecs)))
6637 (tramp-message proc 10 "\n%s" (buffer-string))))
6638
6639(defun tramp-check-for-regexp (proc regexp)
6640 "Check whether REGEXP is contained in process buffer of PROC.
6641Erase echoed commands if exists."
6642 (with-current-buffer (process-buffer proc)
6643 (goto-char (point-min))
674da028 6644
00d6fd04
MA
6645 ;; Check whether we need to remove echo output.
6646 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6647 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6648 (let ((begin (match-beginning 0)))
6649 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6650 ;; Discard echo from remote output.
6651 (tramp-set-connection-property proc "check-remote-echo" nil)
6652 (tramp-message proc 5 "echo-mark found")
b533bc97 6653 (forward-line 1)
00d6fd04
MA
6654 (delete-region begin (point))
6655 (goto-char (point-min)))))
674da028 6656
68712eb6
MA
6657 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6658 ;; Sometimes, the echo string is suppressed on the remote side.
6659 (not (string-equal
6660 (substring-no-properties
6661 tramp-echo-mark-marker
6662 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6663 (buffer-substring-no-properties
6664 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
70c11b0b 6665 ;; No echo to be handled, now we can look for the regexp.
674da028 6666 (goto-char (point-min))
00d6fd04 6667 (re-search-forward regexp nil t))))
d2a2c17f 6668
fb7933a3
KG
6669(defun tramp-wait-for-regexp (proc timeout regexp)
6670 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6671Expects the output of PROC to be sent to the current buffer. Returns
6672the string that matched, or nil. Waits indefinitely if TIMEOUT is
6673nil."
00d6fd04
MA
6674 (with-current-buffer (process-buffer proc)
6675 (let ((found (tramp-check-for-regexp proc regexp))
6676 (start-time (current-time)))
6677 (cond (timeout
6678 ;; Work around a bug in XEmacs 21, where the timeout
6679 ;; expires faster than it should. This degenerates
6680 ;; to polling for buggy XEmacsen, but oh, well.
6681 (while (and (not found)
6682 (< (tramp-time-diff (current-time) start-time)
6683 timeout))
6684 (with-timeout (timeout)
6685 (while (not found)
6686 (tramp-accept-process-output proc 1)
6687 (unless (memq (process-status proc) '(run open))
6688 (tramp-error-with-buffer
6689 nil proc 'file-error "Process has died"))
6690 (setq found (tramp-check-for-regexp proc regexp))))))
6691 (t
6692 (while (not found)
6693 (tramp-accept-process-output proc 1)
6694 (unless (memq (process-status proc) '(run open))
6695 (tramp-error-with-buffer
6696 nil proc 'file-error "Process has died"))
6697 (setq found (tramp-check-for-regexp proc regexp)))))
6698 (tramp-message proc 6 "\n%s" (buffer-string))
fb7933a3 6699 (when (not found)
00d6fd04
MA
6700 (if timeout
6701 (tramp-error
6702 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6703 regexp timeout)
6704 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6705 found)))
fb7933a3 6706
b25a52cc
KG
6707(defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6708 "Wait for shell prompt and barf if none appears.
6709Looks at process PROC to see if a shell prompt appears in TIMEOUT
6710seconds. If not, it produces an error message with the given ERROR-ARGS."
7e780ff1
MA
6711 (unless
6712 (tramp-wait-for-regexp
6713 proc timeout
6714 (format
6715 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
00d6fd04
MA
6716 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6717
7e780ff1
MA
6718;; We don't call `tramp-send-string' in order to hide the password
6719;; from the debug buffer, and because end-of-line handling of the
6720;; string.
6721(defun tramp-enter-password (proc)
00d6fd04
MA
6722 "Prompt for a password and send it to the remote end."
6723 (process-send-string
7e780ff1
MA
6724 proc (concat (tramp-read-passwd proc)
6725 (or (tramp-get-method-parameter
6726 tramp-current-method
6727 'tramp-password-end-of-line)
6728 tramp-default-password-end-of-line))))
00d6fd04
MA
6729
6730(defun tramp-open-connection-setup-interactive-shell (proc vec)
fb7933a3 6731 "Set up an interactive shell.
00d6fd04
MA
6732Mainly sets the prompt and the echo correctly. PROC is the shell
6733process to set up. VEC specifies the connection."
dab816a9 6734 (let ((tramp-end-of-output tramp-initial-end-of-output))
8950769a
MA
6735 ;; It is useful to set the prompt in the following command because
6736 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6737 ;; about and thus /bin/sh will display a strange prompt. For
6738 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6739 ;; display the current working directory but /bin/sh will display
6740 ;; a dollar sign. The following command line sets $PS1 to a sane
6741 ;; value, and works under Bourne-ish shells as well as csh-like
6742 ;; shells. Daniel Pittman reports that the unusual positioning of
6743 ;; the single quotes makes it work under `rc', too. We also unset
6744 ;; the variable $ENV because that is read by some sh
6745 ;; implementations (eg, bash when called as sh) on startup; this
6746 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6747 ;; is another way to set the prompt in /bin/bash, it must be
6748 ;; discarded as well.
a4aeb9a4
MA
6749 (tramp-send-command
6750 vec
6751 (format
70c11b0b
MA
6752 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6753 (shell-quote-argument tramp-end-of-output)
a4aeb9a4
MA
6754 (tramp-get-method-parameter
6755 (tramp-file-name-method vec) 'tramp-remote-sh))
8950769a
MA
6756 t)
6757
6758 ;; Disable echo.
6759 (tramp-message vec 5 "Setting up remote shell environment")
6760 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6761 ;; Check whether the echo has really been disabled. Some
6762 ;; implementations, like busybox of embedded GNU/Linux, don't
6763 ;; support disabling.
6764 (tramp-send-command vec "echo foo" t)
6765 (with-current-buffer (process-buffer proc)
6766 (goto-char (point-min))
6767 (when (looking-at "echo foo")
6768 (tramp-set-connection-property proc "remote-echo" t)
6769 (tramp-message vec 5 "Remote echo still on. Ok.")
6770 ;; Make sure backspaces and their echo are enabled and no line
6771 ;; width magic interferes with them.
6772 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
e42c6bbc 6773
7e780ff1 6774 (tramp-message vec 5 "Setting shell prompt")
70c11b0b
MA
6775 (tramp-send-command
6776 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
6777 (tramp-send-command vec "PS2=''" t)
6778 (tramp-send-command vec "PS3=''" t)
6779 (tramp-send-command vec "PROMPT_COMMAND=''" t)
e42c6bbc 6780
fb7933a3
KG
6781 ;; Try to set up the coding system correctly.
6782 ;; CCC this can't be the right way to do it. Hm.
00d6fd04 6783 (tramp-message vec 5 "Determining coding system")
7e780ff1 6784 (tramp-send-command vec "echo foo ; echo bar" t)
00d6fd04 6785 (with-current-buffer (process-buffer proc)
fb7933a3
KG
6786 (goto-char (point-min))
6787 (if (featurep 'mule)
00d6fd04
MA
6788 ;; Use MULE to select the right EOL convention for communicating
6789 ;; with the process.
311dd93f 6790 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
00d6fd04
MA
6791 (cons 'undecided 'undecided)))
6792 cs-decode cs-encode)
6793 (when (symbolp cs) (setq cs (cons cs cs)))
6794 (setq cs-decode (car cs))
6795 (setq cs-encode (cdr cs))
6796 (unless cs-decode (setq cs-decode 'undecided))
6797 (unless cs-encode (setq cs-encode 'undecided))
6798 (setq cs-encode (tramp-coding-system-change-eol-conversion
6799 cs-encode 'unix))
6800 (when (search-forward "\r" nil t)
6801 (setq cs-decode (tramp-coding-system-change-eol-conversion
6802 cs-decode 'dos)))
311dd93f 6803 (funcall (symbol-function 'set-buffer-process-coding-system)
70c11b0b
MA
6804 cs-decode cs-encode)
6805 (tramp-message
6806 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
fb7933a3
KG
6807 ;; Look for ^M and do something useful if found.
6808 (when (search-forward "\r" nil t)
00d6fd04
MA
6809 ;; We have found a ^M but cannot frob the process coding system
6810 ;; because we're running on a non-MULE Emacs. Let's try
6811 ;; stty, instead.
7e780ff1 6812 (tramp-send-command vec "stty -onlcr" t))))
7e5686f0
MA
6813 ;; Dump stty settings in the traces.
6814 (when (>= tramp-verbose 10)
6815 (tramp-send-command vec "stty -a" t))
7e780ff1 6816 (tramp-send-command vec "set +o vi +o emacs" t)
e42c6bbc
MA
6817
6818 ;; Check whether the output of "uname -sr" has been changed. If
6819 ;; yes, this is a strong indication that we must expire all
d8ac123e
MA
6820 ;; connection properties. We start again with
6821 ;; `tramp-maybe-open-connection', it will be catched there.
e42c6bbc
MA
6822 (tramp-message vec 5 "Checking system information")
6823 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6824 (new-uname
6825 (tramp-set-connection-property
6826 vec "uname"
6827 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6828 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
d8ac123e
MA
6829 (with-current-buffer (tramp-get-debug-buffer vec)
6830 ;; Keep the debug buffer
2296b54d
MA
6831 (rename-buffer
6832 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
d8ac123e
MA
6833 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6834 (if (= (point-min) (point-max))
6835 (kill-buffer nil)
6836 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6837 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6838 (tramp-get-buffer vec)
6839 (tramp-message
6840 vec 3
6841 "Connection reset, because remote host changed from `%s' to `%s'"
6842 old-uname new-uname)
6843 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
e42c6bbc
MA
6844
6845 ;; Check whether the remote host suffers from buggy
6846 ;; `send-process-string'. This is known for FreeBSD (see comment in
6847 ;; `send_process', file process.c). I've tested sending 624 bytes
6848 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6849 ;; this host type is detected locally. It cannot handle remote
6850 ;; hosts, though.
00d6fd04
MA
6851 (with-connection-property proc "chunksize"
6852 (cond
6853 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6854 tramp-chunksize)
6855 (t
6856 (tramp-message
6857 vec 5 "Checking remote host type for `send-process-string' bug")
6858 (if (string-match
e42c6bbc 6859 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
00d6fd04 6860 500 0))))
e42c6bbc 6861
00d6fd04
MA
6862 ;; Set remote PATH variable.
6863 (tramp-set-remote-path vec)
e42c6bbc 6864
fb7933a3
KG
6865 ;; Search for a good shell before searching for a command which
6866 ;; checks if a file exists. This is done because Tramp wants to use
6867 ;; "test foo; echo $?" to check if various conditions hold, and
6868 ;; there are buggy /bin/sh implementations which don't execute the
6869 ;; "echo $?" part if the "test" part has an error. In particular,
c0e17ff2
MA
6870 ;; the OpenSolaris /bin/sh is a problem. There are also other
6871 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
6872 ;; in in function declarations, or changing HISTFILE in place.
6873 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
6874 ;; detected.
00d6fd04 6875 (tramp-find-shell vec)
e42c6bbc 6876
00d6fd04 6877 ;; Disable unexpected output.
7e780ff1 6878 (tramp-send-command vec "mesg n; biff n" t)
e42c6bbc 6879
00d6fd04
MA
6880 ;; Set the environment.
6881 (tramp-message vec 5 "Setting default environment")
661aaece 6882
00d6fd04
MA
6883 (let ((env (copy-sequence tramp-remote-process-environment))
6884 unset item)
6885 (while env
70c11b0b 6886 (setq item (tramp-compat-split-string (car env) "="))
7e5686f0
MA
6887 (setcdr item (mapconcat 'identity (cdr item) "="))
6888 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
00d6fd04 6889 (tramp-send-command
7e5686f0 6890 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
00d6fd04
MA
6891 (push (car item) unset))
6892 (setq env (cdr env)))
6893 (when unset
fb7933a3 6894 (tramp-send-command
7e780ff1 6895 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
fb7933a3 6896
ac474af1
KG
6897;; CCC: We should either implement a Perl version of base64 encoding
6898;; and decoding. Then we just use that in the last item. The other
6899;; alternative is to use the Perl version of UU encoding. But then
6900;; we need a Lisp version of uuencode.
16674e4f
KG
6901;;
6902;; Old text from documentation of tramp-methods:
6903;; Using a uuencode/uudecode inline method is discouraged, please use one
6904;; of the base64 methods instead since base64 encoding is much more
6905;; reliable and the commands are more standardized between the different
6906;; Unix versions. But if you can't use base64 for some reason, please
6907;; note that the default uudecode command does not work well for some
6908;; Unices, in particular AIX and Irix. For AIX, you might want to use
6909;; the following command for uudecode:
6910;;
6911;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6912;;
6913;; For Irix, no solution is known yet.
6914
00d6fd04
MA
6915(defconst tramp-local-coding-commands
6916 '((b64 base64-encode-region base64-decode-region)
6917 (uu tramp-uuencode-region uudecode-decode-region)
6918 (pack
6919 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6920 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6921 "List of local coding commands for inline transfer.
16674e4f
KG
6922Each item is a list that looks like this:
6923
b533bc97 6924\(FORMAT ENCODING DECODING\)
ac474af1 6925
00d6fd04
MA
6926FORMAT is symbol describing the encoding/decoding format. It can be
6927`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
ac474af1 6928
00d6fd04
MA
6929ENCODING and DECODING can be strings, giving commands, or symbols,
6930giving functions. If they are strings, then they can contain
16674e4f
KG
6931the \"%s\" format specifier. If that specifier is present, the input
6932filename will be put into the command line at that spot. If the
6933specifier is not present, the input should be read from standard
6934input.
ac474af1 6935
16674e4f
KG
6936If they are functions, they will be called with two arguments, start
6937and end of region, and are expected to replace the region contents
6938with the encoded or decoded results, respectively.")
ac474af1 6939
00d6fd04 6940(defconst tramp-remote-coding-commands
3dc847a3
MA
6941 '((b64 "base64" "base64 -d")
6942 (b64 "mimencode -b" "mimencode -u -b")
00d6fd04
MA
6943 (b64 "mmencode -b" "mmencode -u -b")
6944 (b64 "recode data..base64" "recode base64..data")
6945 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6946 (b64 tramp-perl-encode tramp-perl-decode)
6947 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6948 (uu "uuencode xxx" "uudecode -o -")
6949 (uu "uuencode xxx" "uudecode -p")
6950 (uu "uuencode xxx" tramp-uudecode)
6951 (pack
6952 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6953 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6954 "List of remote coding commands for inline transfer.
6955Each item is a list that looks like this:
6956
b533bc97 6957\(FORMAT ENCODING DECODING\)
00d6fd04
MA
6958
6959FORMAT is symbol describing the encoding/decoding format. It can be
6960`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6961
6962ENCODING and DECODING can be strings, giving commands, or symbols,
6963giving variables. If they are strings, then they can contain
6964the \"%s\" format specifier. If that specifier is present, the input
6965filename will be put into the command line at that spot. If the
6966specifier is not present, the input should be read from standard
6967input.
6968
6969If they are variables, this variable is a string containing a Perl
6970implementation for this functionality. This Perl program will be transferred
db9e401b 6971to the remote host, and it is available as shell function with the same name.")
00d6fd04
MA
6972
6973(defun tramp-find-inline-encoding (vec)
ac474af1 6974 "Find an inline transfer encoding that works.
00d6fd04
MA
6975Goes through the list `tramp-local-coding-commands' and
6976`tramp-remote-coding-commands'."
6977 (save-excursion
6978 (let ((local-commands tramp-local-coding-commands)
6979 (magic "xyzzy")
6980 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6981 (while (and local-commands (not found))
6982 (setq litem (pop local-commands))
6983 (catch 'wont-work-local
6984 (let ((format (nth 0 litem))
6985 (remote-commands tramp-remote-coding-commands))
6986 (setq loc-enc (nth 1 litem))
6987 (setq loc-dec (nth 2 litem))
6988 ;; If the local encoder or decoder is a string, the
6989 ;; corresponding command has to work locally.
6990 (if (not (stringp loc-enc))
6991 (tramp-message
6992 vec 5 "Checking local encoding function `%s'" loc-enc)
6993 (tramp-message
6994 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6995 (unless (zerop (tramp-call-local-coding-command
6996 loc-enc nil nil))
6997 (throw 'wont-work-local nil)))
6998 (if (not (stringp loc-dec))
6999 (tramp-message
7000 vec 5 "Checking local decoding function `%s'" loc-dec)
7001 (tramp-message
7002 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7003 (unless (zerop (tramp-call-local-coding-command
7004 loc-dec nil nil))
7005 (throw 'wont-work-local nil)))
7006 ;; Search for remote coding commands with the same format
7007 (while (and remote-commands (not found))
7008 (setq ritem (pop remote-commands))
7009 (catch 'wont-work-remote
7010 (when (equal format (nth 0 ritem))
7011 (setq rem-enc (nth 1 ritem))
7012 (setq rem-dec (nth 2 ritem))
7013 ;; Check if remote encoding and decoding commands can be
7014 ;; called remotely with null input and output. This makes
7015 ;; sure there are no syntax errors and the command is really
7016 ;; found. Note that we do not redirect stdout to /dev/null,
7017 ;; for two reasons: when checking the decoding command, we
7018 ;; actually check the output it gives. And also, when
7019 ;; redirecting "mimencode" output to /dev/null, then as root
7020 ;; it might change the permissions of /dev/null!
7021 (when (not (stringp rem-enc))
7022 (let ((name (symbol-name rem-enc)))
7023 (while (string-match (regexp-quote "-") name)
7024 (setq name (replace-match "_" nil t name)))
7025 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7026 (setq rem-enc name)))
7027 (tramp-message
7028 vec 5
7029 "Checking remote encoding command `%s' for sanity" rem-enc)
7030 (unless (zerop (tramp-send-command-and-check
7031 vec (format "%s </dev/null" rem-enc) t))
7032 (throw 'wont-work-remote nil))
7033
7034 (when (not (stringp rem-dec))
7035 (let ((name (symbol-name rem-dec)))
7036 (while (string-match (regexp-quote "-") name)
7037 (setq name (replace-match "_" nil t name)))
7038 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7039 (setq rem-dec name)))
7040 (tramp-message
7041 vec 5
7042 "Checking remote decoding command `%s' for sanity" rem-dec)
7043 (unless (zerop (tramp-send-command-and-check
7044 vec
7045 (format "echo %s | %s | %s"
b593f105
MA
7046 magic rem-enc rem-dec)
7047 t))
00d6fd04
MA
7048 (throw 'wont-work-remote nil))
7049
7050 (with-current-buffer (tramp-get-buffer vec)
7051 (goto-char (point-min))
7052 (unless (looking-at (regexp-quote magic))
7053 (throw 'wont-work-remote nil)))
7054
7055 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7056 (setq rem-enc (nth 1 ritem))
7057 (setq rem-dec (nth 2 ritem))
7058 (setq found t)))))))
7059
1d7e9a01 7060 ;; Did we find something?
00d6fd04 7061 (unless found
7e5686f0
MA
7062 (tramp-error
7063 vec 'file-error "Couldn't find an inline transfer encoding"))
00d6fd04
MA
7064
7065 ;; Set connection properties.
7066 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7067 (tramp-set-connection-property vec "local-encoding" loc-enc)
7068 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7069 (tramp-set-connection-property vec "local-decoding" loc-dec)
7070 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7071 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7072 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7073 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
16674e4f
KG
7074
7075(defun tramp-call-local-coding-command (cmd input output)
7076 "Call the local encoding or decoding command.
7077If CMD contains \"%s\", provide input file INPUT there in command.
7078Otherwise, INPUT is passed via standard input.
7079INPUT can also be nil which means `/dev/null'.
7080OUTPUT can be a string (which specifies a filename), or t (which
7081means standard output and thus the current buffer), or nil (which
7082means discard it)."
a4aeb9a4
MA
7083 (tramp-local-call-process
7084 tramp-encoding-shell
7085 (when (and input (not (string-match "%s" cmd))) input)
7086 (if (eq output t) t nil)
7087 nil
7088 tramp-encoding-command-switch
7089 (concat
7090 (if (string-match "%s" cmd) (format cmd input) cmd)
7091 (if (stringp output) (concat "> " output) ""))))
00d6fd04
MA
7092
7093(defun tramp-compute-multi-hops (vec)
7094 "Expands VEC according to `tramp-default-proxies-alist'.
7095Gateway hops are already opened."
7096 (let ((target-alist `(,vec))
7097 (choices tramp-default-proxies-alist)
7098 item proxy)
7099
7100 ;; Look for proxy hosts to be passed.
7101 (while choices
7102 (setq item (pop choices)
70c11b0b 7103 proxy (eval (nth 2 item)))
00d6fd04
MA
7104 (when (and
7105 ;; host
70c11b0b 7106 (string-match (or (eval (nth 0 item)) "")
00d6fd04
MA
7107 (or (tramp-file-name-host (car target-alist)) ""))
7108 ;; user
70c11b0b 7109 (string-match (or (eval (nth 1 item)) "")
00d6fd04
MA
7110 (or (tramp-file-name-user (car target-alist)) "")))
7111 (if (null proxy)
7112 ;; No more hops needed.
7113 (setq choices nil)
7114 ;; Replace placeholders.
7115 (setq proxy
7116 (format-spec
7117 proxy
b533bc97
MA
7118 (format-spec-make
7119 ?u (or (tramp-file-name-user (car target-alist)) "")
7120 ?h (or (tramp-file-name-host (car target-alist)) ""))))
00d6fd04
MA
7121 (with-parsed-tramp-file-name proxy l
7122 ;; Add the hop.
7123 (add-to-list 'target-alist l)
7124 ;; Start next search.
7125 (setq choices tramp-default-proxies-alist)))))
7126
7127 ;; Handle gateways.
8a4438b6
MA
7128 (when (and (boundp 'tramp-gw-tunnel-method)
7129 (string-match (format
7130 "^\\(%s\\|%s\\)$"
7131 (symbol-value 'tramp-gw-tunnel-method)
7132 (symbol-value 'tramp-gw-socks-method))
7133 (tramp-file-name-method (car target-alist))))
00d6fd04
MA
7134 (let ((gw (pop target-alist))
7135 (hop (pop target-alist)))
7136 ;; Is the method prepared for gateways?
7137 (unless (tramp-get-method-parameter
7138 (tramp-file-name-method hop) 'tramp-default-port)
7139 (tramp-error
7140 vec 'file-error
7141 "Method `%s' is not supported for gateway access."
7142 (tramp-file-name-method hop)))
7143 ;; Add default port if needed.
7144 (unless
7145 (string-match
7146 tramp-host-with-port-regexp (tramp-file-name-host hop))
7147 (aset hop 2
7148 (concat
7149 (tramp-file-name-host hop) tramp-prefix-port-format
7150 (number-to-string
7151 (tramp-get-method-parameter
7152 (tramp-file-name-method hop) 'tramp-default-port)))))
7153 ;; Open the gateway connection.
7154 (add-to-list
7155 'target-alist
7156 (vector
7157 (tramp-file-name-method hop) (tramp-file-name-user hop)
9e6ab520 7158 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
00d6fd04
MA
7159 ;; For the password prompt, we need the correct values.
7160 ;; Therefore, we must remember the gateway vector. But we
7161 ;; cannot do it as connection property, because it shouldn't
7162 ;; be persistent. And we have no started process yet either.
7163 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7164
7165 ;; Foreign and out-of-band methods are not supported for multi-hops.
7166 (when (cdr target-alist)
7167 (setq choices target-alist)
7168 (while choices
7169 (setq item (pop choices))
7170 (when
7171 (or
7172 (not
7173 (tramp-get-method-parameter
7174 (tramp-file-name-method item) 'tramp-login-program))
7175 (tramp-get-method-parameter
7176 (tramp-file-name-method item) 'tramp-copy-program))
7177 (tramp-error
7178 vec 'file-error
7179 "Method `%s' is not supported for multi-hops."
7180 (tramp-file-name-method item)))))
7181
2991e49f
MA
7182 ;; In case the host name is not used for the remote shell
7183 ;; command, the user could be misguided by applying a random
7184 ;; hostname.
7185 (let* ((v (car target-alist))
7186 (method (tramp-file-name-method v))
7187 (host (tramp-file-name-host v)))
7188 (unless
7189 (or
7190 ;; There are multi-hops.
7191 (cdr target-alist)
7192 ;; The host name is used for the remote shell command.
7193 (member
7194 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7195 ;; The host is local. We cannot use `tramp-local-host-p'
7196 ;; here, because it opens a connection as well.
b96e6899 7197 (string-match tramp-local-host-regexp host))
2991e49f 7198 (tramp-error
42bc9b6d
MA
7199 v 'file-error
7200 "Host `%s' looks like a remote host, `%s' can only use the local host"
7201 host method)))
2991e49f 7202
00d6fd04
MA
7203 ;; Result.
7204 target-alist))
7205
7206(defun tramp-maybe-open-connection (vec)
7207 "Maybe open a connection VEC.
fb7933a3
KG
7208Does not do anything if a connection is already open, but re-opens the
7209connection if a previous connection has died for some reason."
d8ac123e
MA
7210 (catch 'uname-changed
7211 (let ((p (tramp-get-connection-process vec))
7212 (process-environment (copy-sequence process-environment)))
7213
7214 ;; If too much time has passed since last command was sent, look
7215 ;; whether process is still alive. If it isn't, kill it. When
7216 ;; using ssh, it can sometimes happen that the remote end has
7217 ;; hung up but the local ssh client doesn't recognize this until
7218 ;; it tries to send some data to the remote end. So that's why
7219 ;; we try to send a command from time to time, then look again
7220 ;; whether the process is really alive.
7221 (condition-case nil
7222 (when (and (> (tramp-time-diff
7223 (current-time)
7224 (tramp-get-connection-property
7225 p "last-cmd-time" '(0 0 0)))
7226 60)
7227 p (processp p) (memq (process-status p) '(run open)))
7228 (tramp-send-command vec "echo are you awake" t t)
7229 (unless (and (memq (process-status p) '(run open))
7230 (tramp-wait-for-output p 10))
7231 ;; The error will be catched locally.
7232 (tramp-error vec 'file-error "Awake did fail")))
7233 (file-error
7234 (tramp-flush-connection-property vec)
7235 (tramp-flush-connection-property p)
7236 (delete-process p)
7237 (setq p nil)))
7238
7239 ;; New connection must be opened.
7240 (unless (and p (processp p) (memq (process-status p) '(run open)))
7241
7242 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7243 ;; messages from the beginning.
7244 (tramp-get-buffer vec)
7245 (if (zerop (length (tramp-file-name-user vec)))
7246 (tramp-message
7247 vec 3 "Opening connection for %s using %s..."
7248 (tramp-file-name-host vec)
7249 (tramp-file-name-method vec))
00d6fd04 7250 (tramp-message
d8ac123e
MA
7251 vec 3 "Opening connection for %s@%s using %s..."
7252 (tramp-file-name-user vec)
00d6fd04 7253 (tramp-file-name-host vec)
d8ac123e
MA
7254 (tramp-file-name-method vec)))
7255
7256 ;; Start new process.
7257 (when (and p (processp p))
7258 (delete-process p))
7259 (setenv "TERM" tramp-terminal-type)
7260 (setenv "LC_ALL" "C")
7261 (setenv "PROMPT_COMMAND")
dab816a9 7262 (setenv "PS1" tramp-initial-end-of-output)
d8ac123e
MA
7263 (let* ((target-alist (tramp-compute-multi-hops vec))
7264 (process-connection-type tramp-process-connection-type)
7265 (process-adaptive-read-buffering nil)
7266 (coding-system-for-read nil)
7267 ;; This must be done in order to avoid our file name handler.
7268 (p (let ((default-directory
7269 (tramp-compat-temporary-file-directory)))
7270 (start-process
7271 (or (tramp-get-connection-property vec "process-name" nil)
7272 (tramp-buffer-name vec))
7273 (tramp-get-connection-buffer vec)
70c11b0b 7274 tramp-encoding-shell))))
00d6fd04 7275
d8ac123e
MA
7276 (tramp-message
7277 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7278
7279 ;; Check whether process is alive.
d8ac123e
MA
7280 (tramp-set-process-query-on-exit-flag p nil)
7281 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
7282 (tramp-barf-if-no-shell-prompt
7283 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7284
7285 ;; Now do all the connections as specified.
7286 (while target-alist
7287 (let* ((hop (car target-alist))
7288 (l-method (tramp-file-name-method hop))
7289 (l-user (tramp-file-name-user hop))
7290 (l-host (tramp-file-name-host hop))
7291 (l-port nil)
7292 (login-program
7293 (tramp-get-method-parameter l-method 'tramp-login-program))
7294 (login-args
7295 (tramp-get-method-parameter l-method 'tramp-login-args))
7296 (gw-args
7297 (tramp-get-method-parameter l-method 'tramp-gw-args))
7298 (gw (tramp-get-file-property hop "" "gateway" nil))
7299 (g-method (and gw (tramp-file-name-method gw)))
7300 (g-user (and gw (tramp-file-name-user gw)))
7301 (g-host (and gw (tramp-file-name-host gw)))
7302 (command login-program)
7303 ;; We don't create the temporary file. In fact, it
7304 ;; is just a prefix for the ControlPath option of
7305 ;; ssh; the real temporary file has another name, and
7306 ;; it is created and protected by ssh. It is also
7307 ;; removed by ssh, when the connection is closed.
7308 (tmpfile
7309 (tramp-set-connection-property
7310 p "temp-file"
7311 (make-temp-name
7312 (expand-file-name
7313 tramp-temp-name-prefix
7314 (tramp-compat-temporary-file-directory)))))
7315 spec)
7316
7317 ;; Add gateway arguments if necessary.
7318 (when (and gw gw-args)
7319 (setq login-args (append login-args gw-args)))
7320
7321 ;; Check for port number. Until now, there's no need
7322 ;; for handling like method, user, host.
7323 (when (string-match tramp-host-with-port-regexp l-host)
7324 (setq l-port (match-string 2 l-host)
7325 l-host (match-string 1 l-host)))
7326
7327 ;; Set variables for computing the prompt for reading
2296b54d 7328 ;; password. They can also be derived from a gateway.
d8ac123e
MA
7329 (setq tramp-current-method (or g-method l-method)
7330 tramp-current-user (or g-user l-user)
7331 tramp-current-host (or g-host l-host))
7332
7333 ;; Replace login-args place holders.
7334 (setq
7335 l-host (or l-host "")
7336 l-user (or l-user "")
7337 l-port (or l-port "")
b533bc97 7338 spec (format-spec-make ?h l-host ?u l-user ?p l-port ?t tmpfile)
d8ac123e
MA
7339 command
7340 (concat
e2a421af
MA
7341 ;; We do not want to see the trailing local prompt in
7342 ;; `start-file-process'.
7343 (unless (memq system-type '(windows-nt)) "exec ")
d8ac123e
MA
7344 command " "
7345 (mapconcat
aa485f7c
MA
7346 (lambda (x)
7347 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7348 (unless (member "" x) (mapconcat 'identity x " ")))
d8ac123e 7349 login-args " ")
d8ac123e
MA
7350 ;; Local shell could be a Windows COMSPEC. It doesn't
7351 ;; know the ";" syntax, but we must exit always for
70c11b0b 7352 ;; `start-file-process'. "exec" does not work either.
e2a421af 7353 (if (memq system-type '(windows-nt)) " && exit || exit")))
d8ac123e
MA
7354
7355 ;; Send the command.
7356 (tramp-message vec 3 "Sending command `%s'" command)
7357 (tramp-send-command vec command t t)
7358 (tramp-process-actions p vec tramp-actions-before-shell 60)
7359 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
7360 ;; Next hop.
7361 (setq target-alist (cdr target-alist)))
7362
7363 ;; Make initial shell settings.
7364 (tramp-open-connection-setup-interactive-shell p vec))))))
00d6fd04
MA
7365
7366(defun tramp-send-command (vec command &optional neveropen nooutput)
7367 "Send the COMMAND to connection VEC.
7368Erases temporary buffer before sending the command. If optional
7369arg NEVEROPEN is non-nil, never try to open the connection. This
7370is meant to be used from `tramp-maybe-open-connection' only. The
7371function waits for output unless NOOUTPUT is set."
7372 (unless neveropen (tramp-maybe-open-connection vec))
7373 (let ((p (tramp-get-connection-process vec)))
8950769a 7374 (when (tramp-get-connection-property p "remote-echo" nil)
00d6fd04
MA
7375 ;; We mark the command string that it can be erased in the output buffer.
7376 (tramp-set-connection-property p "check-remote-echo" t)
7377 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7378 (tramp-message vec 6 "%s" command)
7379 (tramp-send-string vec command)
7380 (unless nooutput (tramp-wait-for-output p))))
7381
00d6fd04 7382(defun tramp-wait-for-output (proc &optional timeout)
7e5686f0
MA
7383 "Wait for output from remote command."
7384 (unless (buffer-live-p (process-buffer proc))
7385 (delete-process proc)
7386 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
00d6fd04 7387 (with-current-buffer (process-buffer proc)
dab816a9 7388 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
bede3e9f 7389 ;; be leading escape sequences, which must be ignored.
dab816a9 7390 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
bede3e9f
MA
7391 ;; Sometimes, the commands do not return a newline but a
7392 ;; null byte before the shell prompt, for example "git
7393 ;; ls-files -c -z ...".
7394 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7395 (found (tramp-wait-for-regexp proc timeout regexp1)))
00d6fd04
MA
7396 (if found
7397 (let (buffer-read-only)
7e5686f0
MA
7398 ;; A simple-minded busybox has sent " ^H" sequences.
7399 ;; Delete them.
7400 (goto-char (point-min))
7401 (when (re-search-forward
7402 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7403 (forward-line 1)
7404 (delete-region (point-min) (point)))
7405 ;; Delete the prompt.
00d6fd04 7406 (goto-char (point-max))
0664ff72 7407 (re-search-backward regexp nil t)
00d6fd04
MA
7408 (delete-region (point) (point-max)))
7409 (if timeout
7410 (tramp-error
7411 proc 'file-error
7412 "[[Remote prompt `%s' not found in %d secs]]"
7413 tramp-end-of-output timeout)
7414 (tramp-error
7415 proc 'file-error
7416 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7417 ;; Return value is whether end-of-output sentinel was found.
7418 found)))
fb7933a3 7419
b593f105
MA
7420(defun tramp-send-command-and-check
7421 (vec command &optional subshell dont-suppress-err)
fb7933a3 7422 "Run COMMAND and check its exit status.
fb7933a3
KG
7423Sends `echo $?' along with the COMMAND for checking the exit status. If
7424COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7425
b593f105
MA
7426If the optional argument SUBSHELL is non-nil, the command is
7427executed in a subshell, ie surrounded by parentheses. If
7428DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
00d6fd04
MA
7429 (tramp-send-command
7430 vec
7431 (concat (if subshell "( " "")
7432 command
b593f105 7433 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
00d6fd04 7434 "echo tramp_exit_status $?"
b593f105 7435 (if subshell " )" "")))
00d6fd04
MA
7436 (with-current-buffer (tramp-get-connection-buffer vec)
7437 (goto-char (point-max))
7438 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7439 (tramp-error
7440 vec 'file-error "Couldn't find exit status of `%s'" command))
7441 (skip-chars-forward "^ ")
7442 (prog1
7443 (read (current-buffer))
7444 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7445
7446(defun tramp-barf-unless-okay (vec command fmt &rest args)
fb7933a3
KG
7447 "Run COMMAND, check exit status, throw error if exit status not okay.
7448Similar to `tramp-send-command-and-check' but accepts two more arguments
7449FMT and ARGS which are passed to `error'."
00d6fd04
MA
7450 (unless (zerop (tramp-send-command-and-check vec command))
7451 (apply 'tramp-error vec 'file-error fmt args)))
7452
7453(defun tramp-send-command-and-read (vec command)
7454 "Run COMMAND and return the output, which must be a Lisp expression.
7455In case there is no valid Lisp expression, it raises an error"
7456 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7457 (with-current-buffer (tramp-get-connection-buffer vec)
7458 ;; Read the expression.
7459 (goto-char (point-min))
7460 (condition-case nil
7461 (prog1 (read (current-buffer))
7462 ;; Error handling.
9e6ab520 7463 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
9ce8462a 7464 (error nil)))
00d6fd04
MA
7465 (error (tramp-error
7466 vec 'file-error
7467 "`%s' does not return a valid Lisp expression: `%s'"
7468 command (buffer-string))))))
fb7933a3 7469
7432277c
KG
7470;; It seems that Tru64 Unix does not like it if long strings are sent
7471;; to it in one go. (This happens when sending the Perl
7472;; `file-attributes' implementation, for instance.) Therefore, we
27e813fe 7473;; have this function which sends the string in chunks.
00d6fd04
MA
7474(defun tramp-send-string (vec string)
7475 "Send the STRING via connection VEC.
7432277c
KG
7476
7477The STRING is expected to use Unix line-endings, but the lines sent to
7478the remote host use line-endings as defined in the variable
00d6fd04
MA
7479`tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7480 (let* ((p (tramp-get-connection-process vec))
7481 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7482 (unless p
7483 (tramp-error
7484 vec 'file-error "Can't send string to remote host -- not logged in"))
7485 (tramp-set-connection-property p "last-cmd-time" (current-time))
7486 (tramp-message vec 10 "%s" string)
7487 (with-current-buffer (tramp-get-connection-buffer vec)
7488 ;; Clean up the buffer. We cannot call `erase-buffer' because
7489 ;; narrowing might be in effect.
7490 (let (buffer-read-only) (delete-region (point-min) (point-max)))
27e813fe 7491 ;; Replace "\n" by `tramp-rsh-end-of-line'.
00d6fd04
MA
7492 (setq string
7493 (mapconcat 'identity
70c11b0b 7494 (tramp-compat-split-string string "\n")
00d6fd04
MA
7495 tramp-rsh-end-of-line))
7496 (unless (or (string= string "")
7497 (string-equal (substring string -1) tramp-rsh-end-of-line))
7498 (setq string (concat string tramp-rsh-end-of-line)))
27e813fe 7499 ;; Send the string.
00d6fd04
MA
7500 (if (and chunksize (not (zerop chunksize)))
7501 (let ((pos 0)
7502 (end (length string)))
7503 (while (< pos end)
7504 (tramp-message
7505 vec 10 "Sending chunk from %s to %s"
7506 pos (min (+ pos chunksize) end))
7507 (process-send-string
7508 p (substring string pos (min (+ pos chunksize) end)))
7509 (setq pos (+ pos chunksize))))
7510 (process-send-string p string)))))
fb7933a3
KG
7511
7512(defun tramp-mode-string-to-int (mode-string)
7513 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
f3c071dd
MA
7514 (let* (case-fold-search
7515 (mode-chars (string-to-vector mode-string))
fb7933a3
KG
7516 (owner-read (aref mode-chars 1))
7517 (owner-write (aref mode-chars 2))
7518 (owner-execute-or-setid (aref mode-chars 3))
7519 (group-read (aref mode-chars 4))
7520 (group-write (aref mode-chars 5))
7521 (group-execute-or-setid (aref mode-chars 6))
7522 (other-read (aref mode-chars 7))
7523 (other-write (aref mode-chars 8))
7524 (other-execute-or-sticky (aref mode-chars 9)))
7525 (save-match-data
7526 (logior
f3c071dd
MA
7527 (cond
7528 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7529 ((char-equal owner-read ?-) 0)
7530 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7531 (cond
7532 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7533 ((char-equal owner-write ?-) 0)
7534 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7535 (cond
7536 ((char-equal owner-execute-or-setid ?x)
7537 (tramp-octal-to-decimal "00100"))
7538 ((char-equal owner-execute-or-setid ?S)
7539 (tramp-octal-to-decimal "04000"))
7540 ((char-equal owner-execute-or-setid ?s)
7541 (tramp-octal-to-decimal "04100"))
7542 ((char-equal owner-execute-or-setid ?-) 0)
7543 (t (error "Fourth char `%c' must be one of `xsS-'"
7544 owner-execute-or-setid)))
7545 (cond
7546 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7547 ((char-equal group-read ?-) 0)
7548 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7549 (cond
7550 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7551 ((char-equal group-write ?-) 0)
7552 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7553 (cond
7554 ((char-equal group-execute-or-setid ?x)
7555 (tramp-octal-to-decimal "00010"))
7556 ((char-equal group-execute-or-setid ?S)
7557 (tramp-octal-to-decimal "02000"))
7558 ((char-equal group-execute-or-setid ?s)
7559 (tramp-octal-to-decimal "02010"))
7560 ((char-equal group-execute-or-setid ?-) 0)
7561 (t (error "Seventh char `%c' must be one of `xsS-'"
7562 group-execute-or-setid)))
7563 (cond
7564 ((char-equal other-read ?r)
7565 (tramp-octal-to-decimal "00004"))
7566 ((char-equal other-read ?-) 0)
7567 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7568 (cond
7569 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7570 ((char-equal other-write ?-) 0)
fb7933a3 7571 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
f3c071dd
MA
7572 (cond
7573 ((char-equal other-execute-or-sticky ?x)
7574 (tramp-octal-to-decimal "00001"))
7575 ((char-equal other-execute-or-sticky ?T)
7576 (tramp-octal-to-decimal "01000"))
7577 ((char-equal other-execute-or-sticky ?t)
7578 (tramp-octal-to-decimal "01001"))
7579 ((char-equal other-execute-or-sticky ?-) 0)
7580 (t (error "Tenth char `%c' must be one of `xtT-'"
7581 other-execute-or-sticky)))))))
fb7933a3 7582
00d6fd04
MA
7583(defun tramp-convert-file-attributes (vec attr)
7584 "Convert file-attributes ATTR generated by perl script, stat or ls.
c82c5727
LH
7585Convert file mode bits to string and set virtual device number.
7586Return ATTR."
680db9ac
MA
7587 (when attr
7588 ;; Convert last access time.
7589 (unless (listp (nth 4 attr))
7590 (setcar (nthcdr 4 attr)
7591 (list (floor (nth 4 attr) 65536)
7592 (floor (mod (nth 4 attr) 65536)))))
7593 ;; Convert last modification time.
7594 (unless (listp (nth 5 attr))
7595 (setcar (nthcdr 5 attr)
7596 (list (floor (nth 5 attr) 65536)
7597 (floor (mod (nth 5 attr) 65536)))))
7598 ;; Convert last status change time.
7599 (unless (listp (nth 6 attr))
7600 (setcar (nthcdr 6 attr)
7601 (list (floor (nth 6 attr) 65536)
7602 (floor (mod (nth 6 attr) 65536)))))
7603 ;; Convert file size.
7604 (when (< (nth 7 attr) 0)
7605 (setcar (nthcdr 7 attr) -1))
7606 (when (and (floatp (nth 7 attr))
7607 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7608 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7609 ;; Convert file mode bits to string.
7610 (unless (stringp (nth 8 attr))
7611 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7612 (when (stringp (car attr))
7613 (aset (nth 8 attr) 0 ?l)))
7614 ;; Convert directory indication bit.
7615 (when (string-match "^d" (nth 8 attr))
7616 (setcar attr t))
7617 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7618 (when (consp (car attr))
7619 (if (and (stringp (caar attr))
7620 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7621 (setcar attr (match-string 1 (caar attr)))
7622 (setcar attr nil)))
7623 ;; Set file's gid change bit.
7624 (setcar (nthcdr 9 attr)
7625 (if (numberp (nth 3 attr))
7626 (not (= (nth 3 attr)
7627 (tramp-get-remote-gid vec 'integer)))
7628 (not (string-equal
7629 (nth 3 attr)
7630 (tramp-get-remote-gid vec 'string)))))
7631 ;; Convert inode.
7632 (unless (listp (nth 10 attr))
7633 (setcar (nthcdr 10 attr)
7634 (condition-case nil
7635 (cons (floor (nth 10 attr) 65536)
7636 (floor (mod (nth 10 attr) 65536)))
7637 ;; Inodes can be incredible huge. We must hide this.
7638 (error (tramp-get-inode vec)))))
7639 ;; Set virtual device number.
7640 (setcar (nthcdr 11 attr)
7641 (tramp-get-device vec))
7642 attr))
c82c5727 7643
293c24f9
MA
7644(defun tramp-check-cached-permissions (vec access)
7645 "Check `file-attributes' caches for VEC.
7646Return t if according to the cache access type ACCESS is known to
7647be granted."
7648 (let ((result nil)
7649 (offset (cond
7650 ((eq ?r access) 1)
7651 ((eq ?w access) 2)
7652 ((eq ?x access) 3))))
7653 (dolist (suffix '("string" "integer") result)
7654 (setq
7655 result
7656 (or
7657 result
7658 (let ((file-attr
7659 (tramp-get-file-property
7660 vec (tramp-file-name-localname vec)
7661 (concat "file-attributes-" suffix) nil))
7662 (remote-uid
7663 (tramp-get-connection-property
7664 vec (concat "uid-" suffix) nil))
7665 (remote-gid
7666 (tramp-get-connection-property
7667 vec (concat "gid-" suffix) nil)))
7668 (and
7669 file-attr
7670 (or
7671 ;; Not a symlink
7672 (eq t (car file-attr))
7673 (null (car file-attr)))
7674 (or
7675 ;; World accessible.
7676 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7677 ;; User accessible and owned by user.
7678 (and
7679 (eq access (aref (nth 8 file-attr) offset))
7680 (equal remote-uid (nth 2 file-attr)))
7681 ;; Group accessible and owned by user's
7682 ;; principal group.
7683 (and
7684 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7685 (equal remote-gid (nth 3 file-attr)))))))))))
7686
ce3f516f 7687(defun tramp-get-inode (vec)
00d6fd04
MA
7688 "Returns the virtual inode number.
7689If it doesn't exist, generate a new one."
ce3f516f
MA
7690 (let ((string (tramp-make-tramp-file-name
7691 (tramp-file-name-method vec)
7692 (tramp-file-name-user vec)
7693 (tramp-file-name-host vec)
7694 "")))
00d6fd04
MA
7695 (unless (assoc string tramp-inodes)
7696 (add-to-list 'tramp-inodes
7697 (list string (length tramp-inodes))))
7698 (nth 1 (assoc string tramp-inodes))))
7699
7700(defun tramp-get-device (vec)
c82c5727
LH
7701 "Returns the virtual device number.
7702If it doesn't exist, generate a new one."
00d6fd04
MA
7703 (let ((string (tramp-make-tramp-file-name
7704 (tramp-file-name-method vec)
7705 (tramp-file-name-user vec)
7706 (tramp-file-name-host vec)
7707 "")))
c82c5727
LH
7708 (unless (assoc string tramp-devices)
7709 (add-to-list 'tramp-devices
7710 (list string (length tramp-devices))))
b946a456 7711 (cons -1 (nth 1 (assoc string tramp-devices)))))
fb7933a3
KG
7712
7713(defun tramp-file-mode-from-int (mode)
7714 "Turn an integer representing a file mode into an ls(1)-like string."
7715 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7716 (user (logand (lsh mode -6) 7))
7717 (group (logand (lsh mode -3) 7))
7718 (other (logand (lsh mode -0) 7))
7719 (suid (> (logand (lsh mode -9) 4) 0))
7720 (sgid (> (logand (lsh mode -9) 2) 0))
7721 (sticky (> (logand (lsh mode -9) 1) 0)))
7722 (setq user (tramp-file-mode-permissions user suid "s"))
7723 (setq group (tramp-file-mode-permissions group sgid "s"))
7724 (setq other (tramp-file-mode-permissions other sticky "t"))
7725 (concat type user group other)))
7726
fb7933a3
KG
7727(defun tramp-file-mode-permissions (perm suid suid-text)
7728 "Convert a permission bitset into a string.
7729This is used internally by `tramp-file-mode-from-int'."
7730 (let ((r (> (logand perm 4) 0))
7731 (w (> (logand perm 2) 0))
7732 (x (> (logand perm 1) 0)))
7733 (concat (or (and r "r") "-")
7734 (or (and w "w") "-")
7735 (or (and suid x suid-text) ; suid, execute
7736 (and suid (upcase suid-text)) ; suid, !execute
7737 (and x "x") "-")))) ; !suid
7738
fb7933a3
KG
7739(defun tramp-decimal-to-octal (i)
7740 "Return a string consisting of the octal digits of I.
7741Not actually used. Use `(format \"%o\" i)' instead?"
7742 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7743 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7744 ((zerop i) "0")
7745 (t (concat (tramp-decimal-to-octal (/ i 8))
7746 (number-to-string (% i 8))))))
7747
fb7933a3
KG
7748;; Kudos to Gerd Moellmann for this suggestion.
7749(defun tramp-octal-to-decimal (ostr)
7750 "Given a string of octal digits, return a decimal number."
7751 (let ((x (or ostr "")))
7752 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7753 (unless (string-match "\\`[0-7]*\\'" x)
7754 (error "Non-octal junk in string `%s'" x))
7755 (string-to-number ostr 8)))
7756
7757(defun tramp-shell-case-fold (string)
7758 "Converts STRING to shell glob pattern which ignores case."
7759 (mapconcat
7760 (lambda (c)
7761 (if (equal (downcase c) (upcase c))
7762 (vector c)
7763 (format "[%c%c]" (downcase c) (upcase c))))
7764 string
7765 ""))
7766
7767
bf247b6e 7768;; ------------------------------------------------------------
a4aeb9a4 7769;; -- Tramp file names --
bf247b6e 7770;; ------------------------------------------------------------
fb7933a3
KG
7771;; Conversion functions between external representation and
7772;; internal data structure. Convenience functions for internal
7773;; data structure.
7774
00d6fd04
MA
7775(defun tramp-file-name-p (vec)
7776 "Check whether VEC is a Tramp object."
7777 (and (vectorp vec) (= 4 (length vec))))
7778
7779(defun tramp-file-name-method (vec)
7780 "Return method component of VEC."
7781 (and (tramp-file-name-p vec) (aref vec 0)))
7782
7783(defun tramp-file-name-user (vec)
7784 "Return user component of VEC."
7785 (and (tramp-file-name-p vec) (aref vec 1)))
7786
7787(defun tramp-file-name-host (vec)
7788 "Return host component of VEC."
7789 (and (tramp-file-name-p vec) (aref vec 2)))
7790
7791(defun tramp-file-name-localname (vec)
7792 "Return localname component of VEC."
7793 (and (tramp-file-name-p vec) (aref vec 3)))
7794
dea31ca6 7795;; The user part of a Tramp file name vector can be of kind
b96e6899 7796;; "user%domain". Sometimes, we must extract these parts.
dea31ca6
MA
7797(defun tramp-file-name-real-user (vec)
7798 "Return the user name of VEC without domain."
a17632c1
MA
7799 (save-match-data
7800 (let ((user (tramp-file-name-user vec)))
7801 (if (and (stringp user)
7802 (string-match tramp-user-with-domain-regexp user))
7803 (match-string 1 user)
7804 user))))
dea31ca6
MA
7805
7806(defun tramp-file-name-domain (vec)
7807 "Return the domain name of VEC."
a17632c1
MA
7808 (save-match-data
7809 (let ((user (tramp-file-name-user vec)))
7810 (and (stringp user)
7811 (string-match tramp-user-with-domain-regexp user)
7812 (match-string 2 user)))))
dea31ca6 7813
00d6fd04
MA
7814;; The host part of a Tramp file name vector can be of kind
7815;; "host#port". Sometimes, we must extract these parts.
8a4438b6 7816(defun tramp-file-name-real-host (vec)
00d6fd04 7817 "Return the host name of VEC without port."
a17632c1
MA
7818 (save-match-data
7819 (let ((host (tramp-file-name-host vec)))
7820 (if (and (stringp host)
7821 (string-match tramp-host-with-port-regexp host))
7822 (match-string 1 host)
7823 host))))
00d6fd04 7824
8a4438b6 7825(defun tramp-file-name-port (vec)
00d6fd04 7826 "Return the port number of VEC."
a17632c1
MA
7827 (save-match-data
7828 (let ((host (tramp-file-name-host vec)))
7829 (and (stringp host)
7830 (string-match tramp-host-with-port-regexp host)
7831 (string-to-number (match-string 2 host))))))
fb7933a3
KG
7832
7833(defun tramp-tramp-file-p (name)
a09dc9bf 7834 "Return t if NAME is a string with Tramp file name syntax."
fb7933a3 7835 (save-match-data
a09dc9bf 7836 (and (stringp name) (string-match tramp-file-name-regexp name))))
bf247b6e 7837
8a4438b6 7838(defun tramp-find-method (method user host)
00d6fd04
MA
7839 "Return the right method string to use.
7840This is METHOD, if non-nil. Otherwise, do a lookup in
7841`tramp-default-method-alist'."
7842 (or method
7843 (let ((choices tramp-default-method-alist)
7844 lmethod item)
7845 (while choices
7846 (setq item (pop choices))
7847 (when (and (string-match (or (nth 0 item) "") (or host ""))
7848 (string-match (or (nth 1 item) "") (or user "")))
7849 (setq lmethod (nth 2 item))
7850 (setq choices nil)))
7851 lmethod)
7852 tramp-default-method))
7853
8a4438b6 7854(defun tramp-find-user (method user host)
00d6fd04
MA
7855 "Return the right user string to use.
7856This is USER, if non-nil. Otherwise, do a lookup in
7857`tramp-default-user-alist'."
7858 (or user
7859 (let ((choices tramp-default-user-alist)
7860 luser item)
7861 (while choices
7862 (setq item (pop choices))
7863 (when (and (string-match (or (nth 0 item) "") (or method ""))
7864 (string-match (or (nth 1 item) "") (or host "")))
7865 (setq luser (nth 2 item))
7866 (setq choices nil)))
7867 luser)
7868 tramp-default-user))
7869
8a4438b6 7870(defun tramp-find-host (method user host)
00d6fd04
MA
7871 "Return the right host string to use.
7872This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7873 (or (and (> (length host) 0) host)
7874 tramp-default-host))
7875
9ce8462a 7876(defun tramp-dissect-file-name (name &optional nodefault)
00d6fd04 7877 "Return a `tramp-file-name' structure.
9ce8462a
MA
7878The structure consists of remote method, remote user, remote host
7879and localname (file name on remote host). If NODEFAULT is
7880non-nil, the file name parts are not expanded to their default
7881values."
4007ba5b 7882 (save-match-data
00d6fd04 7883 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
a4aeb9a4 7884 (unless match (error "Not a Tramp file name: %s" name))
00d6fd04
MA
7885 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7886 (user (match-string (nth 2 tramp-file-name-structure) name))
7887 (host (match-string (nth 3 tramp-file-name-structure) name))
7888 (localname (match-string (nth 4 tramp-file-name-structure) name)))
5d449a36
MA
7889 (when (member method '("multi" "multiu"))
7890 (error
7891 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7892 method))
b96e6899
MA
7893 (when host
7894 (when (string-match tramp-prefix-ipv6-regexp host)
7895 (setq host (replace-match "" nil t host)))
7896 (when (string-match tramp-postfix-ipv6-regexp host)
7897 (setq host (replace-match "" nil t host))))
9ce8462a
MA
7898 (if nodefault
7899 (vector method user host localname)
7900 (vector
7901 (tramp-find-method method user host)
7902 (tramp-find-user method user host)
7903 (tramp-find-host method user host)
7904 localname))))))
00d6fd04
MA
7905
7906(defun tramp-equal-remote (file1 file2)
7907 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7908The check depends on method, user and host name of the files. If
7909one of the components is missing, the default values are used.
7910The local file name parts of FILE1 and FILE2 are not taken into
7911account.
fb7933a3 7912
00d6fd04
MA
7913Example:
7914
7915 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7916
7917would yield `t'. On the other hand, the following check results in nil:
7918
7919 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
9e6ab520
MA
7920 (and (stringp (file-remote-p file1))
7921 (stringp (file-remote-p file2))
94be87e8 7922 (string-equal (file-remote-p file1) (file-remote-p file2))))
00d6fd04
MA
7923
7924(defun tramp-make-tramp-file-name (method user host localname)
7925 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7926 (concat tramp-prefix-format
7927 (when (not (zerop (length method)))
7928 (concat method tramp-postfix-method-format))
7929 (when (not (zerop (length user)))
7930 (concat user tramp-postfix-user-format))
b96e6899
MA
7931 (when host
7932 (if (string-match tramp-ipv6-regexp host)
7933 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7934 host))
7935 tramp-postfix-host-format
00d6fd04
MA
7936 (when localname localname)))
7937
7938(defun tramp-completion-make-tramp-file-name (method user host localname)
7939 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7940It must not be a complete Tramp file name, but as long as there are
7941necessary only. This function will be used in file name completion."
7942 (concat tramp-prefix-format
7943 (when (not (zerop (length method)))
7944 (concat method tramp-postfix-method-format))
7945 (when (not (zerop (length user)))
7946 (concat user tramp-postfix-user-format))
7947 (when (not (zerop (length host)))
b96e6899
MA
7948 (concat
7949 (if (string-match tramp-ipv6-regexp host)
7950 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7951 host)
7952 tramp-postfix-host-format))
00d6fd04
MA
7953 (when localname localname)))
7954
7955(defun tramp-make-copy-program-file-name (vec)
7956 "Create a file name suitable to be passed to `rcp' and workalikes."
7957 (let ((user (tramp-file-name-user vec))
0f205eee 7958 (host (tramp-file-name-real-host vec))
00d6fd04
MA
7959 (localname (tramp-shell-quote-argument
7960 (tramp-file-name-localname vec))))
7961 (if (not (zerop (length user)))
7962 (format "%s@%s:%s" user host localname)
7963 (format "%s:%s" host localname))))
7964
7f49fe46 7965(defun tramp-method-out-of-band-p (vec size)
38c65fca 7966 "Return t if this is an out-of-band method, nil otherwise."
7f49fe46
MA
7967 (and
7968 ;; It shall be an out-of-band method.
7969 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7970 ;; Either the file size is large enough, or (in rare cases) there
7971 ;; does not exist a remote encoding.
7972 (or (> size tramp-copy-size-limit)
7973 (null (tramp-get-remote-coding vec "remote-encoding")))))
fb7933a3 7974
0f205eee
MA
7975(defun tramp-local-host-p (vec)
7976 "Return t if this points to the local host, nil otherwise."
c992abdb
MA
7977 ;; We cannot use `tramp-file-name-real-host'. A port is an
7978 ;; indication for an ssh tunnel or alike.
7979 (let ((host (tramp-file-name-host vec)))
0f205eee
MA
7980 (and
7981 (stringp host)
b96e6899 7982 (string-match tramp-local-host-regexp host)
46bcd78c
MA
7983 ;; The method shall be applied to one of the shell file name
7984 ;; handler. `tramp-local-host-p' is also called for "smb" and
7985 ;; alike, where it must fail.
7986 (tramp-get-method-parameter
7987 (tramp-file-name-method vec) 'tramp-login-program)
a0a5183a
MA
7988 ;; The local temp directory must be writable for the other user.
7989 (file-writable-p
7990 (tramp-make-tramp-file-name
7991 (tramp-file-name-method vec)
7992 (tramp-file-name-user vec)
7993 host
93c3eb7c
MA
7994 (tramp-compat-temporary-file-directory)))
7995 ;; On some systems, chown runs only for root.
7996 (or (zerop (user-uid))
7997 (zerop (tramp-get-remote-uid vec 'integer))))))
0f205eee 7998
fb7933a3
KG
7999;; Variables local to connection.
8000
f84638eb 8001(defun tramp-get-remote-path (vec)
70c11b0b
MA
8002 (with-connection-property
8003 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8004 ;; cache the result for the session only. Otherwise, the result
8005 ;; is cached persistently.
8006 (if (memq 'tramp-own-remote-path tramp-remote-path)
8007 (tramp-get-connection-process vec)
8008 vec)
8009 "remote-path"
b533bc97 8010 (let* ((remote-path (copy-tree tramp-remote-path))
70c11b0b
MA
8011 (elt1 (memq 'tramp-default-remote-path remote-path))
8012 (elt2 (memq 'tramp-own-remote-path remote-path))
f84638eb 8013 (default-remote-path
70c11b0b 8014 (when elt1
f84638eb 8015 (condition-case nil
70c11b0b
MA
8016 (tramp-send-command-and-read
8017 vec "echo \\\"`getconf PATH`\\\"")
f84638eb
MA
8018 ;; Default if "getconf" is not available.
8019 (error
8020 (tramp-message
8021 vec 3
8022 "`getconf PATH' not successful, using default value \"%s\"."
8023 "/bin:/usr/bin")
70c11b0b
MA
8024 "/bin:/usr/bin"))))
8025 (own-remote-path
8026 (when elt2
8027 (condition-case nil
8028 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8029 ;; Default if "getconf" is not available.
8030 (error
8031 (tramp-message
8032 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8033 nil)))))
8034
8035 ;; Replace place holder `tramp-default-remote-path'.
8036 (when elt1
8037 (setcdr elt1
f84638eb 8038 (append
70c11b0b
MA
8039 (tramp-compat-split-string default-remote-path ":")
8040 (cdr elt1)))
f84638eb
MA
8041 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8042
70c11b0b
MA
8043 ;; Replace place holder `tramp-own-remote-path'.
8044 (when elt2
8045 (setcdr elt2
8046 (append
8047 (tramp-compat-split-string own-remote-path ":")
8048 (cdr elt2)))
8049 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8050
8051 ;; Remove double entries.
8052 (setq elt1 remote-path)
8053 (while (consp elt1)
8054 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8055 (setcar elt2 nil))
8056 (setq elt1 (cdr elt1)))
8057
f84638eb
MA
8058 ;; Remove non-existing directories.
8059 (delq
8060 nil
8061 (mapcar
8062 (lambda (x)
8063 (and
70c11b0b
MA
8064 (stringp x)
8065 (file-directory-p
8066 (tramp-make-tramp-file-name
8067 (tramp-file-name-method vec)
8068 (tramp-file-name-user vec)
8069 (tramp-file-name-host vec)
8070 x))
f84638eb
MA
8071 x))
8072 remote-path)))))
8073
a4aeb9a4
MA
8074(defun tramp-get-remote-tmpdir (vec)
8075 (with-connection-property vec "tmp-directory"
8076 (let ((dir (tramp-shell-quote-argument "/tmp")))
8077 (if (and (zerop
8078 (tramp-send-command-and-check
8079 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8080 (zerop
8081 (tramp-send-command-and-check
8082 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8083 dir
8084 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8085
00d6fd04
MA
8086(defun tramp-get-ls-command (vec)
8087 (with-connection-property vec "ls"
946a5aeb
MA
8088 (tramp-message vec 5 "Finding a suitable `ls' command")
8089 (or
8090 (catch 'ls-found
8091 (dolist (cmd '("ls" "gnuls" "gls"))
8092 (let ((dl (tramp-get-remote-path vec))
8093 result)
8094 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
7e5686f0
MA
8095 ;; Check parameters. On busybox, "ls" output coloring is
8096 ;; enabled by default sometimes. So we try to disable it
8097 ;; when possible. $LS_COLORING is not supported there.
946a5aeb
MA
8098 (when (zerop (tramp-send-command-and-check
8099 vec (format "%s -lnd /" result)))
7e5686f0
MA
8100 (when (zerop (tramp-send-command-and-check
8101 vec (format "%s --color=never /" result)))
8102 (setq result (concat result " --color=never")))
946a5aeb
MA
8103 (throw 'ls-found result))
8104 (setq dl (cdr dl))))))
8105 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
00d6fd04 8106
8e754ea2
MA
8107(defun tramp-get-ls-command-with-dired (vec)
8108 (save-match-data
8109 (with-connection-property vec "ls-dired"
8110 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8111 (zerop (tramp-send-command-and-check
7f49fe46 8112 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8e754ea2 8113
00d6fd04
MA
8114(defun tramp-get-test-command (vec)
8115 (with-connection-property vec "test"
946a5aeb
MA
8116 (tramp-message vec 5 "Finding a suitable `test' command")
8117 (if (zerop (tramp-send-command-and-check vec "test 0"))
8118 "test"
8119 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
00d6fd04
MA
8120
8121(defun tramp-get-test-nt-command (vec)
8122 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8123 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8124 ;; for otherwise the shell crashes.
8125 (with-connection-property vec "test-nt"
8126 (or
8127 (progn
8128 (tramp-send-command
8129 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8130 (with-current-buffer (tramp-get-buffer vec)
8131 (goto-char (point-min))
a0a5183a 8132 (when (looking-at (regexp-quote tramp-end-of-output))
00d6fd04
MA
8133 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8134 (progn
8135 (tramp-send-command
8136 vec
8137 (format
8138 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8139 (tramp-get-test-command vec)))
8140 "tramp_test_nt %s %s"))))
8141
8142(defun tramp-get-file-exists-command (vec)
8143 (with-connection-property vec "file-exists"
946a5aeb
MA
8144 (tramp-message vec 5 "Finding command to check if file exists")
8145 (tramp-find-file-exists-command vec)))
00d6fd04
MA
8146
8147(defun tramp-get-remote-ln (vec)
8148 (with-connection-property vec "ln"
946a5aeb
MA
8149 (tramp-message vec 5 "Finding a suitable `ln' command")
8150 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
00d6fd04
MA
8151
8152(defun tramp-get-remote-perl (vec)
8153 (with-connection-property vec "perl"
946a5aeb 8154 (tramp-message vec 5 "Finding a suitable `perl' command")
293c24f9
MA
8155 (let ((result
8156 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8157 (tramp-find-executable
8158 vec "perl" (tramp-get-remote-path vec)))))
8159 ;; We must check also for some Perl modules.
8160 (when result
8161 (with-connection-property vec "perl-file-spec"
8162 (zerop
8163 (tramp-send-command-and-check
8164 vec (format "%s -e 'use File::Spec;'" result))))
8165 (with-connection-property vec "perl-cwd-realpath"
8166 (zerop
8167 (tramp-send-command-and-check
8168 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8169 result)))
00d6fd04
MA
8170
8171(defun tramp-get-remote-stat (vec)
8172 (with-connection-property vec "stat"
946a5aeb
MA
8173 (tramp-message vec 5 "Finding a suitable `stat' command")
8174 (let ((result (tramp-find-executable
8175 vec "stat" (tramp-get-remote-path vec)))
8176 tmp)
8177 ;; Check whether stat(1) returns usable syntax. %s does not
8178 ;; work on older AIX systems.
8179 (when result
8180 (setq tmp
8181 ;; We don't want to display an error message.
8182 (with-temp-message (or (current-message) "")
8183 (condition-case nil
8184 (tramp-send-command-and-read
8185 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8186 (error nil))))
8187 (unless (and (listp tmp) (stringp (car tmp))
8188 (string-match "^./.$" (car tmp))
8189 (integerp (cadr tmp)))
8190 (setq result nil)))
8191 result)))
fb7933a3 8192
293c24f9
MA
8193(defun tramp-get-remote-readlink (vec)
8194 (with-connection-property vec "readlink"
8195 (tramp-message vec 5 "Finding a suitable `readlink' command")
8196 (let ((result (tramp-find-executable
8197 vec "readlink" (tramp-get-remote-path vec))))
8198 (when (and result
8199 ;; We don't want to display an error message.
8200 (with-temp-message (or (current-message) "")
8201 (condition-case nil
8202 (zerop
8203 (tramp-send-command-and-check
8204 vec (format "%s --canonicalize-missing /" result)))
8205 (error nil))))
8206 result))))
8207
00d6fd04
MA
8208(defun tramp-get-remote-id (vec)
8209 (with-connection-property vec "id"
946a5aeb
MA
8210 (tramp-message vec 5 "Finding POSIX `id' command")
8211 (or
8212 (catch 'id-found
8213 (let ((dl (tramp-get-remote-path vec))
8214 result)
8215 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8216 ;; Check POSIX parameter.
8217 (when (zerop (tramp-send-command-and-check
8218 vec (format "%s -u" result)))
8219 (throw 'id-found result))
8220 (setq dl (cdr dl)))))
8221 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
00d6fd04
MA
8222
8223(defun tramp-get-remote-uid (vec id-format)
8224 (with-connection-property vec (format "uid-%s" id-format)
8225 (let ((res (tramp-send-command-and-read
8226 vec
8227 (format "%s -u%s %s"
8228 (tramp-get-remote-id vec)
8229 (if (equal id-format 'integer) "" "n")
8230 (if (equal id-format 'integer)
8231 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8232 ;; The command might not always return a number.
8233 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8234
8235(defun tramp-get-remote-gid (vec id-format)
8236 (with-connection-property vec (format "gid-%s" id-format)
8237 (let ((res (tramp-send-command-and-read
8238 vec
8239 (format "%s -g%s %s"
8240 (tramp-get-remote-id vec)
8241 (if (equal id-format 'integer) "" "n")
8242 (if (equal id-format 'integer)
8243 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8244 ;; The command might not always return a number.
8245 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
fb7933a3 8246
8d60099b
MA
8247(defun tramp-get-local-uid (id-format)
8248 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8249
8250(defun tramp-get-local-gid (id-format)
9e6ab520 8251 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8d60099b 8252
00d6fd04
MA
8253;; Some predefined connection properties.
8254(defun tramp-get-remote-coding (vec prop)
8255 ;; Local coding handles properties like remote coding. So we could
8256 ;; call it without pain.
8257 (let ((ret (tramp-get-local-coding vec prop)))
8258 ;; The connection property might have been cached. So we must send
8259 ;; the script - maybe.
1d7e9a01 8260 (when (and ret (symbolp ret))
00d6fd04
MA
8261 (let ((name (symbol-name ret)))
8262 (while (string-match (regexp-quote "-") name)
8263 (setq name (replace-match "_" nil t name)))
8264 (tramp-maybe-send-script vec (symbol-value ret) name)
8265 (setq ret name)))
8266 ;; Return the value.
8267 ret))
8268
8269(defun tramp-get-local-coding (vec prop)
bf0503cb 8270 (or
00d6fd04
MA
8271 (tramp-get-connection-property vec prop nil)
8272 (progn
8273 (tramp-find-inline-encoding vec)
8274 (tramp-get-connection-property vec prop nil))))
fb7933a3 8275
00d6fd04 8276(defun tramp-get-method-parameter (method param)
c951aecb 8277 "Return the method parameter PARAM.
00d6fd04
MA
8278If the `tramp-methods' entry does not exist, return NIL."
8279 (let ((entry (assoc param (assoc method tramp-methods))))
8280 (when entry (cadr entry))))
90f8dc03 8281
fb7933a3
KG
8282;; Auto saving to a special directory.
8283
00cec167 8284(defun tramp-exists-file-name-handler (operation &rest args)
00d6fd04
MA
8285 "Checks whether OPERATION runs a file name handler."
8286 ;; The file name handler is determined on base of either an
8287 ;; argument, `buffer-file-name', or `default-directory'.
8288 (condition-case nil
8289 (let* ((buffer-file-name "/")
8290 (default-directory "/")
8291 (fnha file-name-handler-alist)
8292 (check-file-name-operation operation)
8293 (file-name-handler-alist
8294 (list
8295 (cons "/"
aa485f7c
MA
8296 (lambda (operation &rest args)
8297 "Returns OPERATION if it is the one to be checked."
8298 (if (equal check-file-name-operation operation)
8299 operation
8300 (let ((file-name-handler-alist fnha))
8301 (apply operation args))))))))
00d6fd04
MA
8302 (equal (apply operation args) operation))
8303 (error nil)))
c1105d05
MA
8304
8305(unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8306 (defadvice make-auto-save-file-name
8307 (around tramp-advice-make-auto-save-file-name () activate)
00d6fd04 8308 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
b533bc97 8309 (if (tramp-tramp-file-p (buffer-file-name))
7f49fe46
MA
8310 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8311 ;; directly, because this would bypass the locking mechanism.
8312 (setq ad-return-value
8313 (tramp-file-name-handler 'make-auto-save-file-name))
a69c01a0 8314 ad-do-it))
191bb792
MA
8315 (add-hook
8316 'tramp-unload-hook
8317 (lambda ()
8318 (ad-remove-advice
8319 'make-auto-save-file-name
d7ec1df7
MA
8320 'around 'tramp-advice-make-auto-save-file-name)
8321 (ad-activate 'make-auto-save-file-name))))
fb7933a3 8322
b533bc97
MA
8323;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8324;; umask. This is a security threat.
414da5ab
MA
8325
8326(defun tramp-set-auto-save-file-modes ()
8327 "Set permissions of autosaved remote files to the original permissions."
8328 (let ((bfn (buffer-file-name)))
b533bc97 8329 (when (and (tramp-tramp-file-p bfn)
b50dd0d2 8330 (buffer-modified-p)
414da5ab 8331 (stringp buffer-auto-save-file-name)
340b8d4f
MA
8332 (not (equal bfn buffer-auto-save-file-name)))
8333 (unless (file-exists-p buffer-auto-save-file-name)
8334 (write-region "" nil buffer-auto-save-file-name))
8335 ;; Permissions should be set always, because there might be an old
8336 ;; auto-saved file belonging to another original file. This could
8337 ;; be a security threat.
7177e2a3 8338 (set-file-modes buffer-auto-save-file-name
11948172 8339 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
414da5ab 8340
b533bc97
MA
8341(unless (and (featurep 'xemacs)
8342 (= emacs-major-version 21)
8343 (> emacs-minor-version 4))
a69c01a0
MA
8344 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8345 (add-hook 'tramp-unload-hook
aa485f7c
MA
8346 (lambda ()
8347 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
414da5ab 8348
fb7933a3
KG
8349(defun tramp-subst-strs-in-string (alist string)
8350 "Replace all occurrences of the string FROM with TO in STRING.
8351ALIST is of the form ((FROM . TO) ...)."
8352 (save-match-data
8353 (while alist
8354 (let* ((pr (car alist))
8355 (from (car pr))
8356 (to (cdr pr)))
8357 (while (string-match (regexp-quote from) string)
8358 (setq string (replace-match to t t string)))
8359 (setq alist (cdr alist))))
8360 string))
8361
fb7933a3
KG
8362;; ------------------------------------------------------------
8363;; -- Compatibility functions section --
8364;; ------------------------------------------------------------
8365
00d6fd04 8366(defun tramp-read-passwd (proc &optional prompt)
fb7933a3 8367 "Read a password from user (compat function).
5615d63f 8368Consults the auth-source package.
5ec2cc41 8369Invokes `password-read' if available, `read-passwd' else."
00d6fd04
MA
8370 (let* ((key (tramp-make-tramp-file-name
8371 tramp-current-method tramp-current-user
8372 tramp-current-host ""))
8373 (pw-prompt
8374 (or prompt
8375 (with-current-buffer (process-buffer proc)
8376 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8377 (format "%s for %s " (capitalize (match-string 1)) key)))))
7540f029
MA
8378 (with-parsed-tramp-file-name key nil
8379 (prog1
8380 (or
8381 ;; See if auth-sources contains something useful, if it's bound.
8382 (and (boundp 'auth-sources)
8383 (tramp-get-connection-property v "first-password-request" nil)
8384 ;; Try with Tramp's current method.
8385 (funcall (symbol-function 'auth-source-user-or-password)
8386 "password" tramp-current-host tramp-current-method))
8387 ;; Try the password cache.
8388 (when (functionp 'password-read)
8389 (unless (tramp-get-connection-property
8390 v "first-password-request" nil)
8391 (funcall (symbol-function 'password-cache-remove) key))
8392 (let ((password
8393 (funcall (symbol-function 'password-read) pw-prompt key)))
8394 (funcall (symbol-function 'password-cache-add) key password)
8395 password))
8396 ;; Else, get the password interactively.
8397 (read-passwd pw-prompt))
8398 (tramp-set-connection-property v "first-password-request" nil)))))
00d6fd04 8399
9c13938d
MA
8400(defun tramp-clear-passwd (vec)
8401 "Clear password cache for connection related to VEC."
00d6fd04 8402 (when (functionp 'password-cache-remove)
9c13938d
MA
8403 (funcall
8404 (symbol-function 'password-cache-remove)
8405 (tramp-make-tramp-file-name
8406 (tramp-file-name-method vec)
8407 (tramp-file-name-user vec)
8408 (tramp-file-name-host vec)
8409 ""))))
00d6fd04
MA
8410
8411;; Snarfed code from time-date.el and parse-time.el
8412
8413(defconst tramp-half-a-year '(241 17024)
8414"Evaluated by \"(days-to-time 183)\".")
8415
8416(defconst tramp-parse-time-months
8417 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8418 ("apr" . 4) ("may" . 5) ("jun" . 6)
8419 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8420 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8421 "Alist mapping month names to integers.")
8422
8423(defun tramp-time-less-p (t1 t2)
8424 "Say whether time value T1 is less than time value T2."
8425 (unless t1 (setq t1 '(0 0)))
8426 (unless t2 (setq t2 '(0 0)))
8427 (or (< (car t1) (car t2))
8428 (and (= (car t1) (car t2))
8429 (< (nth 1 t1) (nth 1 t2)))))
8430
8431(defun tramp-time-subtract (t1 t2)
8432 "Subtract two time values.
8433Return the difference in the format of a time value."
8434 (unless t1 (setq t1 '(0 0)))
8435 (unless t2 (setq t2 '(0 0)))
8436 (let ((borrow (< (cadr t1) (cadr t2))))
8437 (list (- (car t1) (car t2) (if borrow 1 0))
8438 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
fb7933a3
KG
8439
8440(defun tramp-time-diff (t1 t2)
8441 "Return the difference between the two times, in seconds.
1a762140 8442T1 and T2 are time values (as returned by `current-time' for example)."
fb7933a3 8443 ;; Pacify byte-compiler with `symbol-function'.
ea9d1443
KG
8444 (cond ((and (fboundp 'subtract-time)
8445 (fboundp 'float-time))
8446 (funcall (symbol-function 'float-time)
8447 (funcall (symbol-function 'subtract-time) t1 t2)))
8448 ((and (fboundp 'subtract-time)
8449 (fboundp 'time-to-seconds))
8450 (funcall (symbol-function 'time-to-seconds)
8451 (funcall (symbol-function 'subtract-time) t1 t2)))
fb7933a3 8452 ((fboundp 'itimer-time-difference)
1a762140
MA
8453 (funcall (symbol-function 'itimer-time-difference)
8454 (if (< (length t1) 3) (append t1 '(0)) t1)
8455 (if (< (length t2) 3) (append t2 '(0)) t2)))
fb7933a3 8456 (t
00d6fd04 8457 (let ((time (tramp-time-subtract t1 t2)))
ea9d1443
KG
8458 (+ (* (car time) 65536.0)
8459 (cadr time)
8460 (/ (or (nth 2 time) 0) 1000000.0))))))
fb7933a3
KG
8461
8462(defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8463 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8464EOL-TYPE can be one of `dos', `unix', or `mac'."
8465 (cond ((fboundp 'coding-system-change-eol-conversion)
9e6ab520
MA
8466 (funcall (symbol-function 'coding-system-change-eol-conversion)
8467 coding-system eol-type))
fb7933a3 8468 ((fboundp 'subsidiary-coding-system)
9e6ab520
MA
8469 (funcall (symbol-function 'subsidiary-coding-system)
8470 coding-system
8471 (cond ((eq eol-type 'dos) 'crlf)
8472 ((eq eol-type 'unix) 'lf)
8473 ((eq eol-type 'mac) 'cr)
8474 (t
8475 (error "Unknown EOL-TYPE `%s', must be %s"
8476 eol-type
8477 "`dos', `unix', or `mac'")))))
fb7933a3
KG
8478 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8479
19a87064
MA
8480(defun tramp-set-process-query-on-exit-flag (process flag)
8481 "Specify if query is needed for process when Emacs is exited.
8482If the second argument flag is non-nil, Emacs will query the user before
8483exiting if process is running."
8484 (if (fboundp 'set-process-query-on-exit-flag)
00d6fd04
MA
8485 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
8486 (funcall (symbol-function 'process-kill-without-query) process flag)))
19a87064 8487
19a87064 8488
bf247b6e
KS
8489;; ------------------------------------------------------------
8490;; -- Kludges section --
8491;; ------------------------------------------------------------
fb7933a3
KG
8492
8493;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8494;; does not deal well with newline characters. Newline is replaced by
8495;; backslash newline. But if, say, the string `a backslash newline b'
8496;; is passed to a shell, the shell will expand this into "ab",
8497;; completely omitting the newline. This is not what was intended.
8498;; It does not appear to be possible to make the function
8499;; `shell-quote-argument' work with newlines without making it
8500;; dependent on the shell used. But within this package, we know that
8501;; we will always use a Bourne-like shell, so we use an approach which
8502;; groks newlines.
8503;;
8504;; The approach is simple: we call `shell-quote-argument', then
8505;; massage the newline part of the result.
8506;;
8507;; This function should produce a string which is grokked by a Unix
8508;; shell, even if the Emacs is running on Windows. Since this is the
8509;; kludges section, we bind `system-type' in such a way that
8510;; `shell-quote-arguments' behaves as if on Unix.
8511;;
8512;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8513;; function to work with Bourne-like shells.
8514;;
8515;; CCC: This function should be rewritten so that
8516;; `shell-quote-argument' is not used. This way, we are safe from
8517;; changes in `shell-quote-argument'.
8518(defun tramp-shell-quote-argument (s)
8519 "Similar to `shell-quote-argument', but groks newlines.
8520Only works for Bourne-like shells."
8521 (let ((system-type 'not-windows))
8522 (save-match-data
8523 (let ((result (shell-quote-argument s))
8524 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8525 (when (and (>= (length result) 2)
8526 (string= (substring result 0 2) "\\~"))
8527 (setq result (substring result 1)))
8528 (while (string-match nl result)
8529 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8530 t t result)))
8531 result))))
8532
a69c01a0
MA
8533;; Checklist for `tramp-unload-hook'
8534;; - Unload all `tramp-*' packages
8535;; - Reset `file-name-handler-alist'
8536;; - Cleanup hooks where Tramp functions are in
8537;; - Cleanup advised functions
8538;; - Cleanup autoloads
8539;;;###autoload
8540(defun tramp-unload-tramp ()
08b1eb21 8541 "Discard Tramp from loading remote files."
a69c01a0
MA
8542 (interactive)
8543 ;; When Tramp is not loaded yet, its autoloads are still active.
8c04e197 8544 (tramp-unload-file-name-handlers)
a69c01a0
MA
8545 ;; ange-ftp settings must be enabled.
8546 (when (functionp 'tramp-ftp-enable-ange-ftp)
8547 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
00d6fd04
MA
8548 ;; Maybe its not loaded yet.
8549 (condition-case nil
8550 (unload-feature 'tramp 'force)
a69c01a0
MA
8551 (error nil)))
8552
dea31ca6
MA
8553(when (and load-in-progress
8554 (string-match "Loading tramp..." (or (current-message) "")))
ccb4a481
MA
8555 (message "Loading tramp...done"))
8556
fb7933a3
KG
8557(provide 'tramp)
8558
fb7933a3
KG
8559;;; TODO:
8560
4007ba5b 8561;; * Handle nonlocal exits such as C-g.
00d6fd04
MA
8562;; * But it would probably be better to use with-local-quit at the
8563;; place where it's actually needed: around any potentially
8564;; indefinitely blocking piece of code. In this case it would be
8565;; within Tramp around one of its calls to accept-process-output (or
8566;; around one of the loops that calls accept-process-output)
d037d501 8567;; (Stefan Monnier).
fb7933a3 8568;; * Rewrite `tramp-shell-quote-argument' to abstain from using
b1d06e75 8569;; `shell-quote-argument'.
fb7933a3
KG
8570;; * In Emacs 21, `insert-directory' shows total number of bytes used
8571;; by the files in that directory. Add this here.
8572;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8573;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
fb7933a3 8574;; * Case-insensitive filename completion. (Norbert Goevert.)
fb7933a3
KG
8575;; * Don't use globbing for directories with many files, as this is
8576;; likely to produce long command lines, and some shells choke on
8577;; long command lines.
fb7933a3 8578;; * How to deal with MULE in `insert-file-contents' and `write-region'?
fb7933a3
KG
8579;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8580;; * abbreviate-file-name
8e754ea2 8581;; * Better error checking. At least whenever we see something
fb7933a3
KG
8582;; strange when doing zerop, we should kill the process and start
8583;; again. (Greg Stark)
fb7933a3 8584;; * Remove unneeded parameters from methods.
fb7933a3
KG
8585;; * Make it work for different encodings, and for different file name
8586;; encodings, too. (Daniel Pittman)
fb7933a3
KG
8587;; * Don't search for perl5 and perl. Instead, only search for perl and
8588;; then look if it's the right version (with `perl -v').
8589;; * When editing a remote CVS controlled file as a different user, VC
8590;; gets confused about the file locking status. Try to find out why
8591;; the workaround doesn't work.
3cdaec13 8592;; * Username and hostname completion.
6c4e47fa 8593;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8daea7fc 8594;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
16674e4f 8595;; Code is nearly identical.
cfb5c0db
MA
8596;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8597;; until the last but one hop via `start-file-process'. Apply it
8598;; also for ftp and smb.
00d6fd04
MA
8599;; * WIBNI if we had a command "trampclient"? If I was editing in
8600;; some shell with root priviledges, it would be nice if I could
8601;; just call
8602;; trampclient filename.c
8603;; as an editor, and the _current_ shell would connect to an Emacs
8604;; server and would be used in an existing non-priviledged Emacs
8605;; session for doing the editing in question.
8606;; That way, I need not tell Emacs my password again and be afraid
8607;; that it makes it into core dumps or other ugly stuff (I had Emacs
8608;; once display a just typed password in the context of a keyboard
8609;; sequence prompt for a question immediately following in a shell
8610;; script run within Emacs -- nasty).
8611;; And if I have some ssh session running to a different computer,
8612;; having the possibility of passing a local file there to a local
8613;; Emacs session (in case I can arrange for a connection back) would
8614;; be nice.
a4aeb9a4 8615;; Likely the corresponding Tramp server should not allow the
00d6fd04
MA
8616;; equivalent of the emacsclient -eval option in order to make this
8617;; reasonably unproblematic. And maybe trampclient should have some
8618;; way of passing credentials, like by using an SSL socket or
6e4f5731 8619;; something. (David Kastrup)
00d6fd04 8620;; * Reconnect directly to a compliant shell without first going
6e4f5731 8621;; through the user's default shell. (Pete Forman)
00d6fd04 8622;; * Make `tramp-default-user' obsolete.
11c71217 8623;; * How can I interrupt the remote process with a signal
6e4f5731 8624;; (interrupt-process seems not to work)? (Markus Triska)
2296b54d
MA
8625;; * Avoid the local shell entirely for starting remote processes. If
8626;; so, I think even a signal, when delivered directly to the local
8627;; SSH instance, would correctly be propagated to the remote process
8628;; automatically; possibly SSH would have to be started with
6e4f5731 8629;; "-t". (Markus Triska)
dea31ca6 8630;; * It makes me wonder if tramp couldn't fall back to ssh when scp
6e4f5731
MA
8631;; isn't on the remote host. (Mark A. Hershberger)
8632;; * Use lsh instead of ssh. (Alfred M. Szmidt)
3e2fa353
MA
8633;; * Implement a general server-local-variable mechanism, as there are
8634;; probably other variables that need different values for different
8635;; servers too. The user could then configure a variable (such as
8636;; tramp-server-local-variable-alist) to define any such variables
8637;; that they need to, which would then be let bound as appropriate
6e4f5731 8638;; in tramp functions. (Jason Rumney)
946a5aeb
MA
8639;; * Optimize out-of-band copying, when both methods are scp-like (not
8640;; rsync).
8641;; * Keep a second connection open for out-of-band methods like scp or
8642;; rsync.
7540f029 8643;; * Support ptys in `tramp-handle-start-file-process'. (Bug#4604)
7e5686f0
MA
8644;; * IMHO, it's a drawback that currently Tramp doesn't support
8645;; Unicode in Dired file names by default. Is it possible to
8646;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8647;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
6e4f5731 8648;; expects only English messages? (Juri Linkov)
7e5686f0
MA
8649;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8650;; * Do not handle files with drive letter as remote. (Bug#5447)
b533bc97 8651;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
7e5686f0
MA
8652;; * Try telnet+curl as new method. It might be useful for busybox,
8653;; without built-in uuencode/uudecode.
7540f029
MA
8654;; * Let `shell-dynamic-complete-*' and `comint-dynamic-complete' work
8655;; on remote hosts.
8656;; * Use secrets.el for password handling.
5f2b693f 8657;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
fb7933a3
KG
8658
8659;; Functions for file-name-handler-alist:
8660;; diff-latest-backup-file -- in diff.el
fb7933a3 8661
cdd44874 8662;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
fb7933a3 8663;;; tramp.el ends here
57671b72
MA
8664
8665;; Local Variables:
8666;; mode: Emacs-Lisp
8667;; coding: utf-8
8668;; End: