Tweak previous nxml doc 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;;
20b8ac83 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
20b8ac83 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 147 (condition-case nil
20b8ac83 148 (tramp-compat-funcall 'dbus-get-unique-name :session)
2ac33804 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
20b8ac83 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
20b8ac83 203 9 test commands
00d6fd04 20410 traces (huge)."
fb7933a3
KG
205 :group 'tramp
206 :type 'integer)
207
263c02ef 208;; Emacs case.
38c65fca
KG
209(eval-and-compile
210 (when (boundp 'backup-directory-alist)
211 (defcustom tramp-backup-directory-alist nil
212 "Alist of filename patterns and backup directory names.
213Each element looks like (REGEXP . DIRECTORY), with the same meaning like
214in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
215is a local file name, the backup directory is prepended with Tramp file
00d6fd04 216name prefix \(method, user, host\) of file.
38c65fca
KG
217
218\(setq tramp-backup-directory-alist backup-directory-alist\)
219
220gives the same backup policy for Tramp files on their hosts like the
221policy for local files."
222 :group 'tramp
223 :type '(repeat (cons (regexp :tag "Regexp matching filename")
224 (directory :tag "Backup directory name"))))))
225
226;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
227;; the package "backup-dir" might not be loaded yet.
228(eval-and-compile
229 (when (featurep 'xemacs)
230 (defcustom tramp-bkup-backup-directory-info nil
231 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
232It has the same meaning like `bkup-backup-directory-info' from package
233`backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
234file name, the backup directory is prepended with Tramp file name prefix
00d6fd04 235\(method, user, host\) of file.
38c65fca
KG
236
237\(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
238
239gives the same backup policy for Tramp files on their hosts like the
240policy for local files."
bf247b6e 241 :type '(repeat
38c65fca
KG
242 (list (regexp :tag "File regexp")
243 (string :tag "Backup Dir")
244 (set :inline t
245 (const ok-create)
246 (const full-path)
247 (const prepend-name)
248 (const search-upward))))
249 :group 'tramp)))
250
fb7933a3
KG
251(defcustom tramp-auto-save-directory nil
252 "*Put auto-save files in this directory, if set.
253The idea is to use a local directory so that auto-saving is faster."
254 :group 'tramp
00d6fd04 255 :type '(choice (const nil) string))
fb7933a3 256
16674e4f
KG
257(defcustom tramp-encoding-shell
258 (if (memq system-type '(windows-nt))
259 (getenv "COMSPEC")
260 "/bin/sh")
261 "*Use this program for encoding and decoding commands on the local host.
262This shell is used to execute the encoding and decoding command on the
263local host, so if you want to use `~' in those commands, you should
264choose a shell here which groks tilde expansion. `/bin/sh' normally
265does not understand tilde expansion.
266
267For encoding and deocding, commands like the following are executed:
268
269 /bin/sh -c COMMAND < INPUT > OUTPUT
270
271This variable can be used to change the \"/bin/sh\" part. See the
00d6fd04 272variable `tramp-encoding-command-switch' for the \"-c\" part.
fb7933a3
KG
273
274Note that this variable is not used for remote commands. There are
275mechanisms in tramp.el which automatically determine the right shell to
276use for the remote host."
277 :group 'tramp
278 :type '(file :must-match t))
279
16674e4f
KG
280(defcustom tramp-encoding-command-switch
281 (if (string-match "cmd\\.exe" tramp-encoding-shell)
282 "/c"
283 "-c")
284 "*Use this switch together with `tramp-encoding-shell' for local commands.
285See the variable `tramp-encoding-shell' for more information."
286 :group 'tramp
287 :type 'string)
288
20b8ac83
MA
289(defcustom tramp-inline-compress-start-size 4096
290 "*The minimum size of compressing where inline transfer.
291When inline transfer, compress transfered data of file
292whose size is this value or above (up to `tramp-copy-size-limit').
293If it is nil, no compression at all will be applied."
294 :group 'tramp
295 :type '(choice (const nil) integer))
296
00d6fd04 297(defcustom tramp-copy-size-limit 10240
20b8ac83
MA
298 "*The maximum file size where inline copying is preferred over an out-of-the-band copy.
299If it is nil, inline out-of-the-band copy will be used without a check."
16674e4f 300 :group 'tramp
20b8ac83 301 :type '(choice (const nil) integer))
90dc758d 302
00d6fd04
MA
303(defcustom tramp-terminal-type "dumb"
304 "*Value of TERM environment variable for logging in to remote host.
305Because Tramp wants to parse the output of the remote shell, it is easily
306confused by ANSI color escape sequences and suchlike. Often, shell init
307files conditionalize this setup based on the TERM environment variable."
90dc758d 308 :group 'tramp
00d6fd04 309 :type 'string)
90dc758d 310
dab816a9
MA
311;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
312;; root users. It uses the `$' character for other users. In order
313;; to guarantee a proper prompt, we use "#$" for the prompt.
314
315(defvar tramp-end-of-output
316 (format
317 "///%s#$"
318 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
319 "String used to recognize end of output.
320The '$' character at the end is quoted; the string cannot be
321detected as prompt when being sent on echoing hosts, therefore.")
322
323(defconst tramp-initial-end-of-output "#$ "
324 "Prompt when establishing a connection.")
325
00d6fd04
MA
326(defvar tramp-methods
327 `(("rcp" (tramp-login-program "rsh")
328 (tramp-login-args (("%h") ("-l" "%u")))
329 (tramp-remote-sh "/bin/sh")
330 (tramp-copy-program "rcp")
263c02ef 331 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 332 (tramp-copy-keep-date t)
263c02ef 333 (tramp-copy-recursive t)
00d6fd04
MA
334 (tramp-password-end-of-line nil))
335 ("scp" (tramp-login-program "ssh")
20b8ac83
MA
336 (tramp-login-args (("-l" "%u") ("-p" "%p")
337 ("-e" "none") ("%h")))
338 (tramp-async-args (("-q")))
00d6fd04
MA
339 (tramp-remote-sh "/bin/sh")
340 (tramp-copy-program "scp")
263c02ef
MA
341 (tramp-copy-args (("-P" "%p") ("-p" "%k")
342 ("-q") ("-r")))
00d6fd04 343 (tramp-copy-keep-date t)
263c02ef 344 (tramp-copy-recursive t)
00d6fd04
MA
345 (tramp-password-end-of-line nil)
346 (tramp-gw-args (("-o"
347 "GlobalKnownHostsFile=/dev/null")
348 ("-o" "UserKnownHostsFile=/dev/null")
349 ("-o" "StrictHostKeyChecking=no")))
350 (tramp-default-port 22))
351 ("scp1" (tramp-login-program "ssh")
20b8ac83
MA
352 (tramp-login-args (("-l" "%u") ("-p" "%p")
353 ("-1") ("-e" "none") ("%h")))
354 (tramp-async-args (("-q")))
00d6fd04
MA
355 (tramp-remote-sh "/bin/sh")
356 (tramp-copy-program "scp")
357 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
263c02ef 358 ("-q") ("-r")))
00d6fd04 359 (tramp-copy-keep-date t)
263c02ef 360 (tramp-copy-recursive t)
00d6fd04
MA
361 (tramp-password-end-of-line nil)
362 (tramp-gw-args (("-o"
363 "GlobalKnownHostsFile=/dev/null")
364 ("-o" "UserKnownHostsFile=/dev/null")
365 ("-o" "StrictHostKeyChecking=no")))
366 (tramp-default-port 22))
367 ("scp2" (tramp-login-program "ssh")
20b8ac83
MA
368 (tramp-login-args (("-l" "%u") ("-p" "%p")
369 ("-2") ("-e" "none") ("%h")))
370 (tramp-async-args (("-q")))
00d6fd04
MA
371 (tramp-remote-sh "/bin/sh")
372 (tramp-copy-program "scp")
373 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
263c02ef 374 ("-q") ("-r")))
00d6fd04 375 (tramp-copy-keep-date t)
263c02ef 376 (tramp-copy-recursive t)
00d6fd04
MA
377 (tramp-password-end-of-line nil)
378 (tramp-gw-args (("-o"
379 "GlobalKnownHostsFile=/dev/null")
380 ("-o" "UserKnownHostsFile=/dev/null")
381 ("-o" "StrictHostKeyChecking=no")))
382 (tramp-default-port 22))
383 ("scp1_old"
384 (tramp-login-program "ssh1")
385 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
386 ("-e" "none")))
387 (tramp-remote-sh "/bin/sh")
388 (tramp-copy-program "scp1")
263c02ef 389 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 390 (tramp-copy-keep-date t)
263c02ef 391 (tramp-copy-recursive t)
00d6fd04
MA
392 (tramp-password-end-of-line nil))
393 ("scp2_old"
394 (tramp-login-program "ssh2")
395 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
396 ("-e" "none")))
397 (tramp-remote-sh "/bin/sh")
398 (tramp-copy-program "scp2")
263c02ef 399 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 400 (tramp-copy-keep-date t)
263c02ef 401 (tramp-copy-recursive t)
00d6fd04
MA
402 (tramp-password-end-of-line nil))
403 ("sftp" (tramp-login-program "ssh")
20b8ac83
MA
404 (tramp-login-args (("-l" "%u") ("-p" "%p")
405 ("-e" "none") ("%h")))
406 (tramp-async-args (("-q")))
00d6fd04
MA
407 (tramp-remote-sh "/bin/sh")
408 (tramp-copy-program "sftp")
409 (tramp-copy-args nil)
410 (tramp-copy-keep-date nil)
411 (tramp-password-end-of-line nil))
412 ("rsync" (tramp-login-program "ssh")
20b8ac83
MA
413 (tramp-login-args (("-l" "%u") ("-p" "%p")
414 ("-e" "none") ("%h")))
415 (tramp-async-args (("-q")))
00d6fd04
MA
416 (tramp-remote-sh "/bin/sh")
417 (tramp-copy-program "rsync")
263c02ef 418 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
00d6fd04 419 (tramp-copy-keep-date t)
b88f2d0a 420 (tramp-copy-keep-tmpfile t)
263c02ef 421 (tramp-copy-recursive t)
00d6fd04 422 (tramp-password-end-of-line nil))
263c02ef
MA
423 ("rsyncc"
424 (tramp-login-program "ssh")
20b8ac83 425 (tramp-login-args (("-l" "%u") ("-p" "%p")
946a5aeb
MA
426 ("-o" "ControlPath=%t.%%r@%%h:%%p")
427 ("-o" "ControlMaster=yes")
20b8ac83
MA
428 ("-e" "none") ("%h")))
429 (tramp-async-args (("-q")))
946a5aeb
MA
430 (tramp-remote-sh "/bin/sh")
431 (tramp-copy-program "rsync")
263c02ef 432 (tramp-copy-args (("-t" "%k") ("-r")))
946a5aeb
MA
433 (tramp-copy-env (("RSYNC_RSH")
434 (,(concat
435 "ssh"
436 " -o ControlPath=%t.%%r@%%h:%%p"
437 " -o ControlMaster=auto"))))
438 (tramp-copy-keep-date t)
b88f2d0a 439 (tramp-copy-keep-tmpfile t)
263c02ef 440 (tramp-copy-recursive t)
946a5aeb 441 (tramp-password-end-of-line nil))
00d6fd04
MA
442 ("remcp" (tramp-login-program "remsh")
443 (tramp-login-args (("%h") ("-l" "%u")))
444 (tramp-remote-sh "/bin/sh")
445 (tramp-copy-program "rcp")
446 (tramp-copy-args (("-p" "%k")))
447 (tramp-copy-keep-date t)
448 (tramp-password-end-of-line nil))
449 ("rsh" (tramp-login-program "rsh")
450 (tramp-login-args (("%h") ("-l" "%u")))
451 (tramp-remote-sh "/bin/sh")
452 (tramp-copy-program nil)
453 (tramp-copy-args nil)
454 (tramp-copy-keep-date nil)
455 (tramp-password-end-of-line nil))
456 ("ssh" (tramp-login-program "ssh")
20b8ac83
MA
457 (tramp-login-args (("-l" "%u") ("-p" "%p")
458 ("-e" "none") ("%h")))
459 (tramp-async-args (("-q")))
00d6fd04
MA
460 (tramp-remote-sh "/bin/sh")
461 (tramp-copy-program nil)
462 (tramp-copy-args nil)
463 (tramp-copy-keep-date nil)
464 (tramp-password-end-of-line nil)
465 (tramp-gw-args (("-o"
466 "GlobalKnownHostsFile=/dev/null")
467 ("-o" "UserKnownHostsFile=/dev/null")
468 ("-o" "StrictHostKeyChecking=no")))
469 (tramp-default-port 22))
470 ("ssh1" (tramp-login-program "ssh")
20b8ac83
MA
471 (tramp-login-args (("-l" "%u") ("-p" "%p")
472 ("-1") ("-e" "none") ("%h")))
473 (tramp-async-args (("-q")))
00d6fd04
MA
474 (tramp-remote-sh "/bin/sh")
475 (tramp-copy-program nil)
476 (tramp-copy-args nil)
477 (tramp-copy-keep-date nil)
478 (tramp-password-end-of-line nil)
479 (tramp-gw-args (("-o"
480 "GlobalKnownHostsFile=/dev/null")
481 ("-o" "UserKnownHostsFile=/dev/null")
482 ("-o" "StrictHostKeyChecking=no")))
483 (tramp-default-port 22))
484 ("ssh2" (tramp-login-program "ssh")
20b8ac83
MA
485 (tramp-login-args (("-l" "%u") ("-p" "%p")
486 ("-2") ("-e" "none") ("%h")))
487 (tramp-async-args (("-q")))
00d6fd04
MA
488 (tramp-remote-sh "/bin/sh")
489 (tramp-copy-program nil)
490 (tramp-copy-args nil)
491 (tramp-copy-keep-date nil)
492 (tramp-password-end-of-line nil)
493 (tramp-gw-args (("-o"
494 "GlobalKnownHostsFile=/dev/null")
495 ("-o" "UserKnownHostsFile=/dev/null")
496 ("-o" "StrictHostKeyChecking=no")))
497 (tramp-default-port 22))
498 ("ssh1_old"
499 (tramp-login-program "ssh1")
500 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
501 ("-e" "none")))
20b8ac83 502 (tramp-async-args (("-q")))
00d6fd04
MA
503 (tramp-remote-sh "/bin/sh")
504 (tramp-copy-program nil)
505 (tramp-copy-args nil)
506 (tramp-copy-keep-date nil)
507 (tramp-password-end-of-line nil))
508 ("ssh2_old"
509 (tramp-login-program "ssh2")
510 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
511 ("-e" "none")))
512 (tramp-remote-sh "/bin/sh")
513 (tramp-copy-program nil)
514 (tramp-copy-args nil)
515 (tramp-copy-keep-date nil)
516 (tramp-password-end-of-line nil))
517 ("remsh" (tramp-login-program "remsh")
518 (tramp-login-args (("%h") ("-l" "%u")))
519 (tramp-remote-sh "/bin/sh")
520 (tramp-copy-program nil)
521 (tramp-copy-args nil)
522 (tramp-copy-keep-date nil)
523 (tramp-password-end-of-line nil))
524 ("telnet"
525 (tramp-login-program "telnet")
526 (tramp-login-args (("%h") ("%p")))
527 (tramp-remote-sh "/bin/sh")
528 (tramp-copy-program nil)
529 (tramp-copy-args nil)
530 (tramp-copy-keep-date nil)
531 (tramp-password-end-of-line nil)
532 (tramp-default-port 23))
533 ("su" (tramp-login-program "su")
534 (tramp-login-args (("-") ("%u")))
535 (tramp-remote-sh "/bin/sh")
536 (tramp-copy-program nil)
537 (tramp-copy-args nil)
538 (tramp-copy-keep-date nil)
539 (tramp-password-end-of-line nil))
540 ("sudo" (tramp-login-program "sudo")
541 (tramp-login-args (("-u" "%u")
42bc9b6d 542 ("-s") ("-H") ("-p" "Password:")))
00d6fd04
MA
543 (tramp-remote-sh "/bin/sh")
544 (tramp-copy-program nil)
545 (tramp-copy-args nil)
546 (tramp-copy-keep-date nil)
547 (tramp-password-end-of-line nil))
548 ("scpc" (tramp-login-program "ssh")
20b8ac83 549 (tramp-login-args (("-l" "%u") ("-p" "%p")
00d6fd04
MA
550 ("-o" "ControlPath=%t.%%r@%%h:%%p")
551 ("-o" "ControlMaster=yes")
20b8ac83
MA
552 ("-e" "none") ("%h")))
553 (tramp-async-args (("-q")))
00d6fd04
MA
554 (tramp-remote-sh "/bin/sh")
555 (tramp-copy-program "scp")
556 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
557 ("-o" "ControlPath=%t.%%r@%%h:%%p")
558 ("-o" "ControlMaster=auto")))
559 (tramp-copy-keep-date t)
560 (tramp-password-end-of-line nil)
561 (tramp-gw-args (("-o"
562 "GlobalKnownHostsFile=/dev/null")
563 ("-o" "UserKnownHostsFile=/dev/null")
564 ("-o" "StrictHostKeyChecking=no")))
565 (tramp-default-port 22))
566 ("scpx" (tramp-login-program "ssh")
20b8ac83
MA
567 (tramp-login-args (("-l" "%u") ("-p" "%p")
568 ("-e" "none") ("-t" "-t")
569 ("%h") ("/bin/sh")))
570 (tramp-async-args (("-q")))
00d6fd04
MA
571 (tramp-remote-sh "/bin/sh")
572 (tramp-copy-program "scp")
573 (tramp-copy-args (("-p" "%k")))
574 (tramp-copy-keep-date t)
575 (tramp-password-end-of-line nil)
576 (tramp-gw-args (("-o"
577 "GlobalKnownHostsFile=/dev/null")
578 ("-o" "UserKnownHostsFile=/dev/null")
579 ("-o" "StrictHostKeyChecking=no")))
580 (tramp-default-port 22))
581 ("sshx" (tramp-login-program "ssh")
20b8ac83
MA
582 (tramp-login-args (("-l" "%u") ("-p" "%p")
583 ("-e" "none") ("-t" "-t")
584 ("%h") ("/bin/sh")))
585 (tramp-async-args (("-q")))
00d6fd04
MA
586 (tramp-remote-sh "/bin/sh")
587 (tramp-copy-program nil)
588 (tramp-copy-args nil)
589 (tramp-copy-keep-date nil)
590 (tramp-password-end-of-line nil)
591 (tramp-gw-args (("-o"
592 "GlobalKnownHostsFile=/dev/null")
593 ("-o" "UserKnownHostsFile=/dev/null")
594 ("-o" "StrictHostKeyChecking=no")))
595 (tramp-default-port 22))
596 ("krlogin"
597 (tramp-login-program "krlogin")
598 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
599 (tramp-remote-sh "/bin/sh")
600 (tramp-copy-program nil)
601 (tramp-copy-args nil)
602 (tramp-copy-keep-date nil)
603 (tramp-password-end-of-line nil))
604 ("plink" (tramp-login-program "plink")
20b8ac83
MA
605 (tramp-login-args (("-l" "%u") ("-P" "%p")
606 ("-ssh") ("%h")))
00d6fd04
MA
607 (tramp-remote-sh "/bin/sh")
608 (tramp-copy-program nil)
609 (tramp-copy-args nil)
610 (tramp-copy-keep-date nil)
611 (tramp-password-end-of-line "xy") ;see docstring for "xy"
612 (tramp-default-port 22))
613 ("plink1"
614 (tramp-login-program "plink")
20b8ac83
MA
615 (tramp-login-args (("-l" "%u") ("-P" "%p")
616 ("-1" "-ssh") ("%h")))
00d6fd04
MA
617 (tramp-remote-sh "/bin/sh")
618 (tramp-copy-program nil)
619 (tramp-copy-args nil)
620 (tramp-copy-keep-date nil)
621 (tramp-password-end-of-line "xy") ;see docstring for "xy"
622 (tramp-default-port 22))
623 ("plinkx"
624 (tramp-login-program "plink")
42bc9b6d
MA
625 ;; ("%h") must be a single element, see
626 ;; `tramp-compute-multi-hops'.
627 (tramp-login-args (("-load") ("%h") ("-t")
ce3f516f 628 (,(format
dab816a9
MA
629 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
630 tramp-terminal-type
631 tramp-initial-end-of-output))
00d6fd04
MA
632 ("/bin/sh")))
633 (tramp-remote-sh "/bin/sh")
634 (tramp-copy-program nil)
635 (tramp-copy-args nil)
636 (tramp-copy-keep-date nil)
637 (tramp-password-end-of-line nil))
638 ("pscp" (tramp-login-program "plink")
20b8ac83
MA
639 (tramp-login-args (("-l" "%u") ("-P" "%p")
640 ("-ssh") ("%h")))
00d6fd04
MA
641 (tramp-remote-sh "/bin/sh")
642 (tramp-copy-program "pscp")
60f2c210 643 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
00d6fd04
MA
644 (tramp-copy-keep-date t)
645 (tramp-password-end-of-line "xy") ;see docstring for "xy"
646 (tramp-default-port 22))
647 ("psftp" (tramp-login-program "plink")
20b8ac83
MA
648 (tramp-login-args (("-l" "%u") ("-P" "%p")
649 ("-ssh") ("%h")))
00d6fd04
MA
650 (tramp-remote-sh "/bin/sh")
651 (tramp-copy-program "pscp")
60f2c210 652 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
00d6fd04
MA
653 (tramp-copy-keep-date t)
654 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
655 ("fcp" (tramp-login-program "fsh")
656 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
657 (tramp-remote-sh "/bin/sh -i")
658 (tramp-copy-program "fcp")
659 (tramp-copy-args (("-p" "%k")))
660 (tramp-copy-keep-date t)
661 (tramp-password-end-of-line nil)))
fb7933a3
KG
662 "*Alist of methods for remote files.
663This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
664Each NAME stands for a remote access method. Each PARAM is a
665pair of the form (KEY VALUE). The following KEYs are defined:
fb7933a3
KG
666 * `tramp-remote-sh'
667 This specifies the Bourne shell to use on the remote host. This
668 MUST be a Bourne-like shell. It is normally not necessary to set
a4aeb9a4 669 this to any value other than \"/bin/sh\": Tramp wants to use a shell
fb7933a3
KG
670 which groks tilde expansion, but it can search for it. Also note
671 that \"/bin/sh\" exists on all Unixen, this might not be true for
672 the value that you decide to use. You Have Been Warned.
b25a52cc
KG
673 * `tramp-login-program'
674 This specifies the name of the program to use for logging in to the
00d6fd04
MA
675 remote host. This may be the name of rsh or a workalike program,
676 or the name of telnet or a workalike, or the name of su or a workalike.
b25a52cc 677 * `tramp-login-args'
fb7933a3 678 This specifies the list of arguments to pass to the above
00d6fd04 679 mentioned program. Please note that this is a list of list of arguments,
fb7933a3 680 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
00d6fd04
MA
681 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
682 There are some patterns: \"%h\" in this list is replaced by the host
683 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
684 port number, and \"%%\" can be used to obtain a literal percent character.
685 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
686 expansion (i.e. no host or no user specified), this list is not used as
687 argument. By this, arguments like (\"-l\" \"%u\") are optional.
688 \"%t\" is replaced by the temporary file name produced with
689 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
690 parameter of a program, if exists.
20b8ac83
MA
691 * `tramp-async-args'
692 When an asynchronous process is started, we know already that
693 the connection works. Therefore, we can pass additional
694 parameters to suppress diagnostic messages, in order not to
695 tamper the process output.
b25a52cc
KG
696 * `tramp-copy-program'
697 This specifies the name of the program to use for remotely copying
698 the file; this might be the absolute filename of rcp or the name of
699 a workalike program.
700 * `tramp-copy-args'
fb7933a3 701 This specifies the list of parameters to pass to the above mentioned
b25a52cc 702 program, the hints for `tramp-login-args' also apply here.
00d6fd04
MA
703 * `tramp-copy-keep-date'
704 This specifies whether the copying program when the preserves the
705 timestamp of the original file.
b88f2d0a
MA
706 * `tramp-copy-keep-tmpfile'
707 This specifies whether a temporary local file shall be kept
708 for optimization reasons (useful for \"rsync\" methods).
709 * `tramp-copy-recursive'
710 Whether the operation copies directories recursively.
00d6fd04
MA
711 * `tramp-default-port'
712 The default port of a method is needed in case of gateway connections.
713 Additionally, it is used as indication which method is prepared for
714 passing gateways.
715 * `tramp-gw-args'
716 As the attribute name says, additional arguments are specified here
717 when a method is applied via a gateway.
90f8dc03
KG
718 * `tramp-password-end-of-line'
719 This specifies the string to use for terminating the line after
720 submitting the password. If this method parameter is nil, then the
721 value of the normal variable `tramp-default-password-end-of-line'
722 is used. This parameter is necessary because the \"plink\" program
723 requires any two characters after sending the password. These do
724 not have to be newline or carriage return characters. Other login
725 programs are happy with just one character, the newline character.
726 We use \"xy\" as the value for methods using \"plink\".
b25a52cc
KG
727
728What does all this mean? Well, you should specify `tramp-login-program'
729for all methods; this program is used to log in to the remote site. Then,
730there are two ways to actually transfer the files between the local and the
731remote side. One way is using an additional rcp-like program. If you want
732to do this, set `tramp-copy-program' in the method.
fb7933a3
KG
733
734Another possibility for file transfer is inline transfer, i.e. the
b25a52cc 735file is passed through the same buffer used by `tramp-login-program'. In
fb7933a3 736this case, the file contents need to be protected since the
b25a52cc 737`tramp-login-program' might use escape codes or the connection might not
fb7933a3 738be eight-bit clean. Therefore, file contents are encoded for transit.
00d6fd04
MA
739See the variables `tramp-local-coding-commands' and
740`tramp-remote-coding-commands' for details.
fb7933a3 741
16674e4f 742So, to summarize: if the method is an out-of-band method, then you
b25a52cc 743must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
00d6fd04
MA
744inline method, then these two parameters should be nil. Methods which
745are fit for gateways must have `tramp-default-port' at least.
fb7933a3
KG
746
747Notes:
748
00d6fd04
MA
749When using `su' or `sudo' the phrase `open connection to a remote
750host' sounds strange, but it is used nevertheless, for consistency.
751No connection is opened to a remote host, but `su' or `sudo' is
752started on the local host. You should specify a remote host
753`localhost' or the name of the local host. Another host name is
754useful only in combination with `tramp-default-proxies-alist'.")
fb7933a3 755
20b8ac83
MA
756(defun tramp-detect-ssh-controlmaster ()
757 "Call ssh to detect whether it supports the ControlMaster argument.
758This function may return nil when the argument is supported, but
759shouldn't return t when it isn't."
760 (ignore-errors
761 (with-temp-buffer
762 (call-process "ssh" nil t nil "-o" "ControlMaster")
763 (goto-char (point-min))
764 (search-forward-regexp "Missing ControlMaster argument" nil t))))
765
b25a52cc 766(defcustom tramp-default-method
83e20b5c
MA
767 ;; An external copy method seems to be preferred, because it is much
768 ;; more performant for large files, and it hasn't too serious delays
769 ;; for small files. But it must be ensured that there aren't
770 ;; permanent password queries. Either a password agent like
263c02ef
MA
771 ;; "ssh-agent" or "Pageant" shall run, or the optional
772 ;; password-cache.el or auth-sources.el packages shall be active for
20b8ac83
MA
773 ;; password caching. "scpc" is chosen if we detect that the user is
774 ;; running OpenSSH 4.0 or newer.
00d6fd04
MA
775 (cond
776 ;; PuTTY is installed.
777 ((executable-find "pscp")
778 (if (or (fboundp 'password-read)
263c02ef 779 (fboundp 'auth-source-user-or-password)
00d6fd04 780 ;; Pageant is running.
70c11b0b 781 (tramp-compat-process-running-p "Pageant"))
00d6fd04
MA
782 "pscp"
783 "plink"))
784 ;; There is an ssh installation.
785 ((executable-find "scp")
20b8ac83
MA
786 (cond
787 ((tramp-detect-ssh-controlmaster) "scpc")
788 ((or (fboundp 'password-read)
789 (fboundp 'auth-source-user-or-password)
790 ;; ssh-agent is running.
791 (getenv "SSH_AUTH_SOCK")
792 (getenv "SSH_AGENT_PID"))
793 "scp")
794 (t "ssh")))
00d6fd04
MA
795 ;; Fallback.
796 (t "ftp"))
fb7933a3 797 "*Default method to use for transferring files.
c62c9d08 798See `tramp-methods' for possibilities.
4007ba5b 799Also see `tramp-default-method-alist'."
c62c9d08
KG
800 :group 'tramp
801 :type 'string)
802
505edaeb 803(defcustom tramp-default-method-alist
4007ba5b 804 '(("\\`localhost\\'" "\\`root\\'" "su"))
00d6fd04 805 "*Default method to use for specific host/user pairs.
c62c9d08
KG
806This is an alist of items (HOST USER METHOD). The first matching item
807specifies the method to use for a file name which does not specify a
808method. HOST and USER are regular expressions or nil, which is
809interpreted as a regular expression which always matches. If no entry
810matches, the variable `tramp-default-method' takes effect.
811
812If the file name does not specify the user, lookup is done using the
813empty string for the user name.
814
815See `tramp-methods' for a list of possibilities for METHOD."
816 :group 'tramp
817 :type '(repeat (list (regexp :tag "Host regexp")
818 (regexp :tag "User regexp")
819 (string :tag "Method"))))
820
00d6fd04
MA
821(defcustom tramp-default-user
822 nil
823 "*Default user to use for transferring files.
824It is nil by default; otherwise settings in configuration files like
825\"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
826
827This variable is regarded as obsolete, and will be removed soon."
828 :group 'tramp
829 :type '(choice (const nil) string))
830
831(defcustom tramp-default-user-alist
832 `(("\\`su\\(do\\)?\\'" nil "root")
833 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
834 nil ,(user-login-name)))
835 "*Default user to use for specific method/host pairs.
836This is an alist of items (METHOD HOST USER). The first matching item
837specifies the user to use for a file name which does not specify a
838user. METHOD and USER are regular expressions or nil, which is
839interpreted as a regular expression which always matches. If no entry
840matches, the variable `tramp-default-user' takes effect.
841
842If the file name does not specify the method, lookup is done using the
843empty string for the method name."
844 :group 'tramp
845 :type '(repeat (list (regexp :tag "Method regexp")
846 (regexp :tag "Host regexp")
847 (string :tag "User"))))
848
849(defcustom tramp-default-host
850 (system-name)
851 "*Default host to use for transferring files.
852Useful for su and sudo methods mostly."
853 :group 'tramp
854 :type 'string)
855
856(defcustom tramp-default-proxies-alist nil
857 "*Route to be followed for specific host/user pairs.
858This is an alist of items (HOST USER PROXY). The first matching
859item specifies the proxy to be passed for a file name located on
860a remote target matching USER@HOST. HOST and USER are regular
70c11b0b
MA
861expressions. PROXY must be a Tramp filename without a localname
862part. Method and user name on PROXY are optional, which is
863interpreted with the default values. PROXY can contain the
864patterns %h and %u, which are replaced by the strings matching
865HOST or USER, respectively.
866
867HOST, USER or PROXY could also be Lisp forms, which will be
868evaluated. The result must be a string or nil, which is
869interpreted as a regular expression which always matches."
00d6fd04 870 :group 'tramp
70c11b0b
MA
871 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
872 (choice :tag "User regexp" regexp sexp)
873 (choice :tag "Proxy remote name" string (const nil)))))
00d6fd04 874
b96e6899
MA
875(defconst tramp-local-host-regexp
876 (concat
877 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
878 "*Host names which are regarded as local host.")
879
16674e4f 880(defconst tramp-completion-function-alist-rsh
00d6fd04
MA
881 '((tramp-parse-rhosts "/etc/hosts.equiv")
882 (tramp-parse-rhosts "~/.rhosts"))
b25a52cc 883 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
16674e4f 884
16674e4f 885(defconst tramp-completion-function-alist-ssh
00d6fd04
MA
886 '((tramp-parse-rhosts "/etc/hosts.equiv")
887 (tramp-parse-rhosts "/etc/shosts.equiv")
888 (tramp-parse-shosts "/etc/ssh_known_hosts")
889 (tramp-parse-sconfig "/etc/ssh_config")
890 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
891 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
892 (tramp-parse-rhosts "~/.rhosts")
893 (tramp-parse-rhosts "~/.shosts")
894 (tramp-parse-shosts "~/.ssh/known_hosts")
895 (tramp-parse-sconfig "~/.ssh/config")
896 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
897 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
b25a52cc 898 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
16674e4f 899
16674e4f 900(defconst tramp-completion-function-alist-telnet
00d6fd04 901 '((tramp-parse-hosts "/etc/hosts"))
b25a52cc 902 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
16674e4f 903
16674e4f 904(defconst tramp-completion-function-alist-su
00d6fd04 905 '((tramp-parse-passwd "/etc/passwd"))
b25a52cc 906 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
292ffc15 907
00d6fd04
MA
908(defconst tramp-completion-function-alist-putty
909 '((tramp-parse-putty
910 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
911 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
912
5ec2cc41 913(defvar tramp-completion-function-alist nil
16674e4f 914 "*Alist of methods for remote files.
20b8ac83 915This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
16674e4f 916Each NAME stands for a remote access method. Each PAIR is of the form
20b8ac83 917\(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
16674e4f
KG
918names from FILE for completion. The following predefined FUNCTIONs exists:
919
5ec2cc41
KG
920 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
921 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
922 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
923 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
924 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
925 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
926 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
927 * `tramp-parse-netrc' for \"~/.netrc\" like files.
00d6fd04 928 * `tramp-parse-putty' for PuTTY registry keys.
5ec2cc41
KG
929
930FUNCTION can also be a customer defined function. For more details see
931the info pages.")
932
933(eval-after-load "tramp"
934 '(progn
935 (tramp-set-completion-function
936 "rcp" tramp-completion-function-alist-rsh)
937 (tramp-set-completion-function
938 "scp" tramp-completion-function-alist-ssh)
939 (tramp-set-completion-function
940 "scp1" tramp-completion-function-alist-ssh)
941 (tramp-set-completion-function
942 "scp2" tramp-completion-function-alist-ssh)
943 (tramp-set-completion-function
944 "scp1_old" tramp-completion-function-alist-ssh)
945 (tramp-set-completion-function
946 "scp2_old" tramp-completion-function-alist-ssh)
947 (tramp-set-completion-function
70c11b0b 948 "rsync" tramp-completion-function-alist-ssh)
946a5aeb
MA
949 (tramp-set-completion-function
950 "rsyncc" tramp-completion-function-alist-ssh)
5ec2cc41
KG
951 (tramp-set-completion-function
952 "remcp" tramp-completion-function-alist-rsh)
953 (tramp-set-completion-function
954 "rsh" tramp-completion-function-alist-rsh)
955 (tramp-set-completion-function
956 "ssh" tramp-completion-function-alist-ssh)
957 (tramp-set-completion-function
958 "ssh1" tramp-completion-function-alist-ssh)
959 (tramp-set-completion-function
960 "ssh2" tramp-completion-function-alist-ssh)
961 (tramp-set-completion-function
962 "ssh1_old" tramp-completion-function-alist-ssh)
963 (tramp-set-completion-function
964 "ssh2_old" tramp-completion-function-alist-ssh)
965 (tramp-set-completion-function
966 "remsh" tramp-completion-function-alist-rsh)
967 (tramp-set-completion-function
968 "telnet" tramp-completion-function-alist-telnet)
969 (tramp-set-completion-function
970 "su" tramp-completion-function-alist-su)
971 (tramp-set-completion-function
972 "sudo" tramp-completion-function-alist-su)
bf247b6e 973 (tramp-set-completion-function
5ec2cc41
KG
974 "scpx" tramp-completion-function-alist-ssh)
975 (tramp-set-completion-function
976 "sshx" tramp-completion-function-alist-ssh)
977 (tramp-set-completion-function
978 "krlogin" tramp-completion-function-alist-rsh)
979 (tramp-set-completion-function
980 "plink" tramp-completion-function-alist-ssh)
981 (tramp-set-completion-function
982 "plink1" tramp-completion-function-alist-ssh)
00d6fd04
MA
983 (tramp-set-completion-function
984 "plinkx" tramp-completion-function-alist-putty)
5ec2cc41
KG
985 (tramp-set-completion-function
986 "pscp" tramp-completion-function-alist-ssh)
987 (tramp-set-completion-function
988 "fcp" tramp-completion-function-alist-ssh)))
16674e4f 989
674da028
MA
990(defconst tramp-echo-mark-marker "_echo"
991 "String marker to surround echoed commands.")
992
68712eb6
MA
993(defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
994 "String length of `tramp-echo-mark-marker'.")
995
996(defconst tramp-echo-mark
997 (concat tramp-echo-mark-marker
998 (make-string tramp-echo-mark-marker-length ?\b))
00d6fd04
MA
999 "String mark to be transmitted around shell commands.
1000Used to separate their echo from the output they produce. This
1001will only be used if we cannot disable remote echo via stty.
1002This string must have no effect on the remote shell except for
1003producing some echo which can later be detected by
674da028
MA
1004`tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
1005followed by an equal number of backspaces to erase them will
1006usually suffice.")
00d6fd04 1007
68712eb6
MA
1008(defconst tramp-echoed-echo-mark-regexp
1009 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
1010 tramp-echo-mark-marker tramp-echo-mark-marker-length)
00d6fd04
MA
1011 "Regexp which matches `tramp-echo-mark' as it gets echoed by
1012the remote shell.")
1013
fb7933a3
KG
1014(defcustom tramp-rsh-end-of-line "\n"
1015 "*String used for end of line in rsh connections.
1016I don't think this ever needs to be changed, so please tell me about it
16674e4f 1017if you need to change this.
90f8dc03
KG
1018Also see the method parameter `tramp-password-end-of-line' and the normal
1019variable `tramp-default-password-end-of-line'."
16674e4f
KG
1020 :group 'tramp
1021 :type 'string)
1022
90f8dc03
KG
1023(defcustom tramp-default-password-end-of-line
1024 tramp-rsh-end-of-line
16674e4f 1025 "*String used for end of line after sending a password.
90f8dc03
KG
1026This variable provides the default value for the method parameter
1027`tramp-password-end-of-line', see `tramp-methods' for more details.
1028
16674e4f
KG
1029It seems that people using plink under Windows need to send
1030\"\\r\\n\" (carriage-return, then newline) after a password, but just
1031\"\\n\" after all other lines. This variable can be used for the
1032password, see `tramp-rsh-end-of-line' for the other cases.
1033
1034The default value is to use the same value as `tramp-rsh-end-of-line'."
fb7933a3
KG
1035 :group 'tramp
1036 :type 'string)
1037
00d6fd04
MA
1038;; "getconf PATH" yields:
1039;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
1040;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
0664ff72 1041;; GNU/Linux (Debian, Suse): /bin:/usr/bin
00d6fd04 1042;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
20b8ac83 1043;; IRIX64: /usr/bin
fb7933a3 1044(defcustom tramp-remote-path
00d6fd04
MA
1045 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1046 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
fb7933a3
KG
1047 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1048 "*List of directories to search for executables on remote host.
00d6fd04
MA
1049For every remote host, this variable will be set buffer local,
1050keeping the list of existing directories on that host.
fb7933a3
KG
1051
1052You can use `~' in this list, but when searching for a shell which groks
00d6fd04
MA
1053tilde expansion, all directory names starting with `~' will be ignored.
1054
1055`Default Directories' represent the list of directories given by
1056the command \"getconf PATH\". It is recommended to use this
1057entry on top of this list, because these are the default
70c11b0b
MA
1058directories for POSIX compatible commands.
1059
1060`Private Directories' are the settings of the $PATH environment,
1061as given in your `~/.profile'."
00d6fd04
MA
1062 :group 'tramp
1063 :type '(repeat (choice
1064 (const :tag "Default Directories" tramp-default-remote-path)
70c11b0b 1065 (const :tag "Private Directories" tramp-own-remote-path)
00d6fd04
MA
1066 (string :tag "Directory"))))
1067
00d6fd04 1068(defcustom tramp-remote-process-environment
a0a5183a 1069 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
20b8ac83 1070 ,(format "TERM=%s" tramp-terminal-type)
97c696d5 1071 "EMACS=t" ;; Deprecated.
20b8ac83 1072 ,(format "INSIDE_EMACS='%s,tramp:%s'" emacs-version tramp-version)
00d6fd04
MA
1073 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1074 "autocorrect=" "correct=")
1075
1076 "*List of environment variables to be set on the remote host.
1077
1078Each element should be a string of the form ENVVARNAME=VALUE. An
1079entry ENVVARNAME= diables the corresponding environment variable,
1080which might have been set in the init files like ~/.profile.
1081
1082Special handling is applied to the PATH environment, which should
1083not be set here. Instead of, it should be set via `tramp-remote-path'."
fb7933a3
KG
1084 :group 'tramp
1085 :type '(repeat string))
1086
1087(defcustom tramp-login-prompt-regexp
bc103d00 1088 ".*ogin\\( .*\\)?: *"
fb7933a3 1089 "*Regexp matching login-like prompts.
bc103d00
MA
1090The regexp should match at end of buffer.
1091
1092Sometimes the prompt is reported to look like \"login as:\"."
fb7933a3
KG
1093 :group 'tramp
1094 :type 'regexp)
1095
821e6e36 1096(defcustom tramp-shell-prompt-pattern
aa485f7c 1097 ;; Allow a prompt to start right after a ^M since it indeed would be
20b8ac83
MA
1098 ;; displayed at the beginning of the line (and Zsh uses it). This
1099 ;; regexp works only for GNU Emacs.
1100 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
1101 "[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
821e6e36
KG
1102 "Regexp to match prompts from remote shell.
1103Normally, Tramp expects you to configure `shell-prompt-pattern'
1104correctly, but sometimes it happens that you are connecting to a
1105remote host which sends a different kind of shell prompt. Therefore,
1106Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1107and also things matched by this variable. The default value of this
b25a52cc 1108variable is similar to the default value of `shell-prompt-pattern',
dab816a9
MA
1109which should work well in many cases.
1110
1111This regexp must match both `tramp-initial-end-of-output' and
1112`tramp-end-of-output'."
821e6e36
KG
1113 :group 'tramp
1114 :type 'regexp)
1115
fb7933a3 1116(defcustom tramp-password-prompt-regexp
00d6fd04 1117 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
fb7933a3 1118 "*Regexp matching password-like prompts.
ac474af1 1119The regexp should match at end of buffer.
fb7933a3
KG
1120
1121The `sudo' program appears to insert a `^@' character into the prompt."
1122 :group 'tramp
1123 :type 'regexp)
1124
1125(defcustom tramp-wrong-passwd-regexp
b1d06e75
KG
1126 (concat "^.*"
1127 ;; These strings should be on the last line
a4aeb9a4 1128 (regexp-opt '("Permission denied"
b1d06e75
KG
1129 "Login incorrect"
1130 "Login Incorrect"
1131 "Connection refused"
27e813fe 1132 "Connection closed"
7e5686f0 1133 "Timeout, server not responding."
b1d06e75
KG
1134 "Sorry, try again."
1135 "Name or service not known"
00d6fd04 1136 "Host key verification failed."
70c11b0b 1137 "No supported authentication methods left to try!") t)
b1d06e75
KG
1138 ".*"
1139 "\\|"
1140 "^.*\\("
1141 ;; Here comes a list of regexes, separated by \\|
1142 "Received signal [0-9]+"
1143 "\\).*")
fb7933a3 1144 "*Regexp matching a `login failed' message.
ac474af1
KG
1145The regexp should match at end of buffer."
1146 :group 'tramp
1147 :type 'regexp)
1148
1149(defcustom tramp-yesno-prompt-regexp
3cdaec13
KG
1150 (concat
1151 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1152 "\\s-*")
1153 "Regular expression matching all yes/no queries which need to be confirmed.
ac474af1 1154The confirmation should be done with yes or no.
3cdaec13
KG
1155The regexp should match at end of buffer.
1156See also `tramp-yn-prompt-regexp'."
fb7933a3
KG
1157 :group 'tramp
1158 :type 'regexp)
1159
3cdaec13 1160(defcustom tramp-yn-prompt-regexp
658052a2
MA
1161 (concat
1162 (regexp-opt '("Store key in cache? (y/n)"
1163 "Update cached key? (y/n, Return cancels connection)") t)
1164 "\\s-*")
3cdaec13
KG
1165 "Regular expression matching all y/n queries which need to be confirmed.
1166The confirmation should be done with y or n.
1167The regexp should match at end of buffer.
1168See also `tramp-yesno-prompt-regexp'."
1169 :group 'tramp
1170 :type 'regexp)
487f4fb7
KG
1171
1172(defcustom tramp-terminal-prompt-regexp
1173 (concat "\\("
1174 "TERM = (.*)"
1175 "\\|"
1176 "Terminal type\\? \\[.*\\]"
1177 "\\)\\s-*")
1178 "Regular expression matching all terminal setting prompts.
1179The regexp should match at end of buffer.
1180The answer will be provided by `tramp-action-terminal', which see."
1181 :group 'tramp
1182 :type 'regexp)
3cdaec13 1183
01917a18
MA
1184(defcustom tramp-operation-not-permitted-regexp
1185 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1186 (regexp-opt '("Operation not permitted") t))
1187 "Regular expression matching keep-date problems in (s)cp operations.
1188Copying has been performed successfully already, so this message can
1189be ignored safely."
1190 :group 'tramp
1191 :type 'regexp)
1192
6b2633cc
LH
1193(defcustom tramp-copy-failed-regexp
1194 (concat "\\(.+: "
1195 (regexp-opt '("Permission denied"
1196 "not a regular file"
1197 "is a directory"
1198 "No such file or directory") t)
1199 "\\)\\s-*")
1200 "Regular expression matching copy problems in (s)cp operations."
1201 :group 'tramp
1202 :type 'regexp)
1203
19a87064 1204(defcustom tramp-process-alive-regexp
38c65fca 1205 ""
19a87064 1206 "Regular expression indicating a process has finished.
38c65fca
KG
1207In fact this expression is empty by intention, it will be used only to
1208check regularly the status of the associated process.
07dfe738 1209The answer will be provided by `tramp-action-process-alive',
00d6fd04 1210`tramp-action-out-of-band', which see."
38c65fca
KG
1211 :group 'tramp
1212 :type 'regexp)
1213
fb7933a3
KG
1214(defcustom tramp-temp-name-prefix "tramp."
1215 "*Prefix to use for temporary files.
1216If this is a relative file name (such as \"tramp.\"), it is considered
1217relative to the directory name returned by the function
9e6ab520 1218`tramp-compat-temporary-file-directory' (which see). It may also be an
fb7933a3
KG
1219absolute file name; don't forget to include a prefix for the filename
1220part, though."
1221 :group 'tramp
1222 :type 'string)
1223
2296b54d
MA
1224(defconst tramp-temp-buffer-name " *tramp temp*"
1225 "Buffer name for a temporary buffer.
1226It shall be used in combination with `generate-new-buffer-name'.")
1227
b88f2d0a
MA
1228(defvar tramp-temp-buffer-file-name nil
1229 "File name of a persistent local temporary file.
1230Useful for \"rsync\" like methods.")
1231(make-variable-buffer-local 'tramp-temp-buffer-file-name)
1232
4007ba5b 1233(defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
c62c9d08
KG
1234 "*Alist specifying extra arguments to pass to the remote shell.
1235Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1236matching the shell file name and ARGS is a string specifying the
1237arguments.
1238
1239This variable is only used when Tramp needs to start up another shell
1240for tilde expansion. The extra arguments should typically prevent the
1241shell from reading its init file."
1242 :group 'tramp
90f8dc03
KG
1243 ;; This might be the wrong way to test whether the widget type
1244 ;; `alist' is available. Who knows the right way to test it?
1245 :type (if (get 'alist 'widget-type)
1246 '(alist :key-type string :value-type string)
1247 '(repeat (cons string string))))
c62c9d08 1248
00d6fd04
MA
1249;; XEmacs is distributed with few Lisp packages. Further packages are
1250;; installed using EFS. If we use a unified filename format, then
1251;; Tramp is required in addition to EFS. (But why can't Tramp just
1252;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1253;; just like before.) Another reason for using a separate filename
1254;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1255;; Tramp only knows how to deal with `file-name-handler-alist', not
1256;; the other places.
1257
1258;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1259;;;###autoload
1260(defcustom tramp-syntax
1261 (if (featurep 'xemacs) 'sep 'ftp)
1262 "Tramp filename syntax to be used.
1263
1264It can have the following values:
1265
1266 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1267 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1268 'url -- URL-like syntax."
16674e4f 1269 :group 'tramp
00d6fd04
MA
1270 :type (if (featurep 'xemacs)
1271 '(choice (const :tag "EFS" ftp)
1272 (const :tag "XEmacs" sep)
1273 (const :tag "URL" url))
1274 '(choice (const :tag "Ange-FTP" ftp)
1275 (const :tag "URL" url))))
1276
1277(defconst tramp-prefix-format
1278 (cond ((equal tramp-syntax 'ftp) "/")
1279 ((equal tramp-syntax 'sep) "/[")
1280 ((equal tramp-syntax 'url) "/")
1281 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4 1282 "*String matching the very beginning of Tramp file names.
00d6fd04 1283Used in `tramp-make-tramp-file-name'.")
16674e4f 1284
00d6fd04 1285(defconst tramp-prefix-regexp
16674e4f 1286 (concat "^" (regexp-quote tramp-prefix-format))
a4aeb9a4 1287 "*Regexp matching the very beginning of Tramp file names.
00d6fd04 1288Should always start with \"^\". Derived from `tramp-prefix-format'.")
16674e4f 1289
00d6fd04 1290(defconst tramp-method-regexp
16674e4f 1291 "[a-zA-Z_0-9-]+"
00d6fd04 1292 "*Regexp matching methods identifiers.")
16674e4f 1293
00d6fd04
MA
1294(defconst tramp-postfix-method-format
1295 (cond ((equal tramp-syntax 'ftp) ":")
1296 ((equal tramp-syntax 'sep) "/")
1297 ((equal tramp-syntax 'url) "://")
1298 (t (error "Wrong `tramp-syntax' defined")))
16674e4f 1299 "*String matching delimeter between method and user or host names.
00d6fd04 1300Used in `tramp-make-tramp-file-name'.")
16674e4f 1301
00d6fd04
MA
1302(defconst tramp-postfix-method-regexp
1303 (regexp-quote tramp-postfix-method-format)
16674e4f 1304 "*Regexp matching delimeter between method and user or host names.
00d6fd04 1305Derived from `tramp-postfix-method-format'.")
16674e4f 1306
00d6fd04
MA
1307(defconst tramp-user-regexp
1308 "[^:/ \t]+"
1309 "*Regexp matching user names.")
16674e4f 1310
b96e6899
MA
1311(defconst tramp-prefix-domain-format "%"
1312 "*String matching delimeter between user and domain names.")
1313
1314(defconst tramp-prefix-domain-regexp
1315 (regexp-quote tramp-prefix-domain-format)
1316 "*Regexp matching delimeter between user and domain names.
1317Derived from `tramp-prefix-domain-format'.")
1318
1319(defconst tramp-domain-regexp
70c11b0b 1320 "[-a-zA-Z0-9_.]+"
b96e6899
MA
1321 "*Regexp matching domain names.")
1322
1323(defconst tramp-user-with-domain-regexp
1324 (concat "\\(" tramp-user-regexp "\\)"
1325 tramp-prefix-domain-regexp
1326 "\\(" tramp-domain-regexp "\\)")
1327 "*Regexp matching user names with domain names.")
1328
00d6fd04 1329(defconst tramp-postfix-user-format
16674e4f
KG
1330 "@"
1331 "*String matching delimeter between user and host names.
00d6fd04 1332Used in `tramp-make-tramp-file-name'.")
16674e4f 1333
00d6fd04 1334(defconst tramp-postfix-user-regexp
16674e4f
KG
1335 (regexp-quote tramp-postfix-user-format)
1336 "*Regexp matching delimeter between user and host names.
00d6fd04
MA
1337Derived from `tramp-postfix-user-format'.")
1338
1339(defconst tramp-host-regexp
1340 "[a-zA-Z0-9_.-]+"
1341 "*Regexp matching host names.")
1342
b96e6899
MA
1343(defconst tramp-prefix-ipv6-format
1344 (cond ((equal tramp-syntax 'ftp) "[")
1345 ((equal tramp-syntax 'sep) "")
1346 ((equal tramp-syntax 'url) "[")
1347 (t (error "Wrong `tramp-syntax' defined")))
1348 "*String matching left hand side of IPv6 addresses.
1349Used in `tramp-make-tramp-file-name'.")
1350
1351(defconst tramp-prefix-ipv6-regexp
1352 (regexp-quote tramp-prefix-ipv6-format)
1353 "*Regexp matching left hand side of IPv6 addresses.
1354Derived from `tramp-prefix-ipv6-format'.")
1355
e0b6e3b9
MA
1356;; The following regexp is a bit sloppy. But it shall serve our
1357;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1358;; "::ffff:192.168.0.1".
b96e6899 1359(defconst tramp-ipv6-regexp
e0b6e3b9 1360 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
b96e6899
MA
1361 "*Regexp matching IPv6 addresses.")
1362
1363(defconst tramp-postfix-ipv6-format
1364 (cond ((equal tramp-syntax 'ftp) "]")
1365 ((equal tramp-syntax 'sep) "")
1366 ((equal tramp-syntax 'url) "]")
1367 (t (error "Wrong `tramp-syntax' defined")))
1368 "*String matching right hand side of IPv6 addresses.
1369Used in `tramp-make-tramp-file-name'.")
1370
1371(defconst tramp-postfix-ipv6-regexp
1372 (regexp-quote tramp-postfix-ipv6-format)
1373 "*Regexp matching right hand side of IPv6 addresses.
1374Derived from `tramp-postfix-ipv6-format'.")
1375
00d6fd04
MA
1376(defconst tramp-prefix-port-format
1377 (cond ((equal tramp-syntax 'ftp) "#")
1378 ((equal tramp-syntax 'sep) "#")
1379 ((equal tramp-syntax 'url) ":")
1380 (t (error "Wrong `tramp-syntax' defined")))
1381 "*String matching delimeter between host names and port numbers.")
1382
1383(defconst tramp-prefix-port-regexp
1384 (regexp-quote tramp-prefix-port-format)
1385 "*Regexp matching delimeter between host names and port numbers.
1386Derived from `tramp-prefix-port-format'.")
1387
1388(defconst tramp-port-regexp
1389 "[0-9]+"
1390 "*Regexp matching port numbers.")
1391
1392(defconst tramp-host-with-port-regexp
1393 (concat "\\(" tramp-host-regexp "\\)"
1394 tramp-prefix-port-regexp
1395 "\\(" tramp-port-regexp "\\)")
1396 "*Regexp matching host names with port numbers.")
1397
1398(defconst tramp-postfix-host-format
1399 (cond ((equal tramp-syntax 'ftp) ":")
1400 ((equal tramp-syntax 'sep) "]")
1401 ((equal tramp-syntax 'url) "")
1402 (t (error "Wrong `tramp-syntax' defined")))
7432277c 1403 "*String matching delimeter between host names and localnames.
00d6fd04 1404Used in `tramp-make-tramp-file-name'.")
16674e4f 1405
00d6fd04 1406(defconst tramp-postfix-host-regexp
16674e4f 1407 (regexp-quote tramp-postfix-host-format)
7432277c 1408 "*Regexp matching delimeter between host names and localnames.
00d6fd04 1409Derived from `tramp-postfix-host-format'.")
16674e4f 1410
00d6fd04 1411(defconst tramp-localname-regexp
16674e4f 1412 ".*$"
00d6fd04 1413 "*Regexp matching localnames.")
16674e4f
KG
1414
1415;; File name format.
505edaeb 1416
00d6fd04 1417(defconst tramp-file-name-structure
16674e4f
KG
1418 (list
1419 (concat
1420 tramp-prefix-regexp
00d6fd04
MA
1421 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1422 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
b96e6899
MA
1423 "\\(" "\\(" tramp-host-regexp
1424 "\\|"
1425 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1426 tramp-postfix-ipv6-regexp "\\)"
1427 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
00d6fd04
MA
1428 tramp-postfix-host-regexp
1429 "\\(" tramp-localname-regexp "\\)")
b96e6899 1430 2 4 5 8)
16674e4f 1431
fb7933a3 1432 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
a4aeb9a4 1433the Tramp file name structure.
fb7933a3 1434
a4aeb9a4 1435The first element REGEXP is a regular expression matching a Tramp file
fb7933a3
KG
1436name. The regex should contain parentheses around the method name,
1437the user name, the host name, and the file name parts.
1438
1439The second element METHOD is a number, saying which pair of
1440parentheses matches the method name. The third element USER is
1441similar, but for the user name. The fourth element HOST is similar,
1442but for the host name. The fifth element FILE is for the file name.
1443These numbers are passed directly to `match-string', which see. That
1444means the opening parentheses are counted to identify the pair.
1445
00d6fd04 1446See also `tramp-file-name-regexp'.")
fb7933a3
KG
1447
1448;;;###autoload
505edaeb 1449(defconst tramp-file-name-regexp-unified
20b8ac83
MA
1450 (if (memq system-type '(cygwin windows-nt))
1451 "\\`/\\([^[/:]\\{2,\\}\\|[^/]\\{2,\\}]\\):"
1452 "\\`/\\([^[/:]+\\|[^/]+]\\):")
505edaeb
KG
1453 "Value for `tramp-file-name-regexp' for unified remoting.
1454Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
20b8ac83
MA
1455Tramp. See `tramp-file-name-structure' for more explanations.
1456
1457On W32 systems, the volume letter must be ignored.")
505edaeb
KG
1458
1459;;;###autoload
1460(defconst tramp-file-name-regexp-separate
1461 "\\`/\\[.*\\]"
1462 "Value for `tramp-file-name-regexp' for separate remoting.
1463XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 1464See `tramp-file-name-structure' for more explanations.")
505edaeb
KG
1465
1466;;;###autoload
00d6fd04
MA
1467(defconst tramp-file-name-regexp-url
1468 "\\`/[^/:]+://"
1469 "Value for `tramp-file-name-regexp' for URL-like remoting.
1470See `tramp-file-name-structure' for more explanations.")
1471
1472;;;###autoload
1473(defconst tramp-file-name-regexp
1474 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1475 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1476 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1477 (t (error "Wrong `tramp-syntax' defined")))
94be87e8 1478 "*Regular expression matching file names handled by Tramp.
a4aeb9a4 1479This regexp should match Tramp file names but no other file names.
20b8ac83 1480When tramp.el is loaded, this regular expression is prepended to
fb7933a3 1481`file-name-handler-alist', and that is searched sequentially. Thus,
a4aeb9a4
MA
1482if the Tramp entry appears rather early in the `file-name-handler-alist'
1483and is a bit too general, then some files might be considered Tramp
00d6fd04 1484files which are not really Tramp files.
fb7933a3
KG
1485
1486Please note that the entry in `file-name-handler-alist' is made when
20b8ac83 1487this file \(tramp.el\) is loaded. This means that this variable must be set
fb7933a3
KG
1488before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1489updated after changing this variable.
1490
00d6fd04 1491Also see `tramp-file-name-structure'.")
fb7933a3 1492
16674e4f 1493;;;###autoload
8a798e41 1494(defconst tramp-root-regexp
00d6fd04 1495 (if (memq system-type '(cygwin windows-nt))
aa485f7c
MA
1496 "\\`\\([a-zA-Z]:\\)?/"
1497 "\\`/")
8a798e41 1498 "Beginning of an incomplete Tramp file name.
aa485f7c 1499Usually, it is just \"\\\\`/\". On W32 systems, there might be a
57671b72 1500volume letter, which will be removed by `tramp-drop-volume-letter'.")
8a798e41
MA
1501
1502;;;###autoload
1503(defconst tramp-completion-file-name-regexp-unified
20b8ac83
MA
1504 (if (memq system-type '(cygwin windows-nt))
1505 (concat tramp-root-regexp "[^/]\\{2,\\}\\'")
1506 (concat tramp-root-regexp "[^/]*\\'"))
16674e4f 1507 "Value for `tramp-completion-file-name-regexp' for unified remoting.
8a798e41 1508GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
20b8ac83
MA
1509See `tramp-file-name-structure' for more explanations.
1510
1511On W32 systems, the volume letter must be ignored.")
fb7933a3 1512
16674e4f
KG
1513;;;###autoload
1514(defconst tramp-completion-file-name-regexp-separate
aa485f7c 1515 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
16674e4f
KG
1516 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1517XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 1518See `tramp-file-name-structure' for more explanations.")
fb7933a3 1519
16674e4f 1520;;;###autoload
00d6fd04 1521(defconst tramp-completion-file-name-regexp-url
aa485f7c 1522 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
00d6fd04
MA
1523 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1524See `tramp-file-name-structure' for more explanations.")
1525
1526;;;###autoload
1527(defconst tramp-completion-file-name-regexp
1528 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1529 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1530 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1531 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4
MA
1532 "*Regular expression matching file names handled by Tramp completion.
1533This regexp should match partial Tramp file names only.
16674e4f
KG
1534
1535Please note that the entry in `file-name-handler-alist' is made when
1536this file (tramp.el) is loaded. This means that this variable must be set
1537before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1538updated after changing this variable.
1539
00d6fd04 1540Also see `tramp-file-name-structure'.")
fb7933a3 1541
00d6fd04
MA
1542(defconst tramp-actions-before-shell
1543 '((tramp-login-prompt-regexp tramp-action-login)
1544 (tramp-password-prompt-regexp tramp-action-password)
1545 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
ac474af1 1546 (shell-prompt-pattern tramp-action-succeed)
821e6e36 1547 (tramp-shell-prompt-pattern tramp-action-succeed)
3cdaec13 1548 (tramp-yesno-prompt-regexp tramp-action-yesno)
487f4fb7 1549 (tramp-yn-prompt-regexp tramp-action-yn)
19a87064
MA
1550 (tramp-terminal-prompt-regexp tramp-action-terminal)
1551 (tramp-process-alive-regexp tramp-action-process-alive))
ac474af1
KG
1552 "List of pattern/action pairs.
1553Whenever a pattern matches, the corresponding action is performed.
1554Each item looks like (PATTERN ACTION).
1555
1556The PATTERN should be a symbol, a variable. The value of this
1557variable gives the regular expression to search for. Note that the
1558regexp must match at the end of the buffer, \"\\'\" is implicitly
1559appended to it.
1560
1561The ACTION should also be a symbol, but a function. When the
00d6fd04 1562corresponding PATTERN matches, the ACTION function is called.")
ac474af1 1563
00d6fd04 1564(defconst tramp-actions-copy-out-of-band
38c65fca
KG
1565 '((tramp-password-prompt-regexp tramp-action-password)
1566 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
00d6fd04 1567 (tramp-copy-failed-regexp tramp-action-permission-denied)
19a87064 1568 (tramp-process-alive-regexp tramp-action-out-of-band))
38c65fca
KG
1569 "List of pattern/action pairs.
1570This list is used for copying/renaming with out-of-band methods.
90f8dc03 1571
00d6fd04
MA
1572See `tramp-actions-before-shell' for more info.")
1573
1574;; Chunked sending kludge. We set this to 500 for black-listed constellations
7432277c 1575;; known to have a bug in `process-send-string'; some ssh connections appear
7177e2a3
MA
1576;; to drop bytes when data is sent too quickly. There is also a connection
1577;; buffer local variable, which is computed depending on remote host properties
1578;; when `tramp-chunksize' is zero or nil.
7432277c
KG
1579(defcustom tramp-chunksize
1580 (when (and (not (featurep 'xemacs))
1581 (memq system-type '(hpux)))
1582 500)
55880756
MA
1583;; Parentheses in docstring starting at beginning of line are escaped.
1584;; Fontification is messed up when
1585;; `open-paren-in-column-0-is-defun-start' set to t.
7432277c
KG
1586 "*If non-nil, chunksize for sending input to local process.
1587It is necessary only on systems which have a buggy `process-send-string'
1588implementation. The necessity, whether this variable must be set, can be
1589checked via the following code:
1590
1591 (with-temp-buffer
11948172
MA
1592 (let* ((user \"xxx\") (host \"yyy\")
1593 (init 0) (step 50)
1594 (sent init) (received init))
1595 (while (= sent received)
1596 (setq sent (+ sent step))
1597 (erase-buffer)
1598 (let ((proc (start-process (buffer-name) (current-buffer)
1599 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1600 (when (memq (process-status proc) '(run open))
1601 (process-send-string proc (make-string sent ?\\ ))
1602 (process-send-eof proc)
1603 (process-send-eof proc))
1604 (while (not (progn (goto-char (point-min))
1605 (re-search-forward \"\\\\w+\" (point-max) t)))
1606 (accept-process-output proc 1))
1607 (when (memq (process-status proc) '(run open))
1608 (setq received (string-to-number (match-string 0)))
1609 (delete-process proc)
1610 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1611 (sit-for 0))))
1612 (if (> sent (+ init step))
1613 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1614 (- sent step))
1615 (message \"Test does not work\")
1616 (display-buffer (current-buffer))
1617 (sit-for 30))))
1618
1619In the Emacs normally running Tramp, evaluate the above code
55880756 1620\(replace \"xxx\" and \"yyy\" by the remote user and host name,
20b8ac83 1621respectively\). You can do this, for example, by pasting it into
11948172
MA
1622the `*scratch*' buffer and then hitting C-j with the cursor after the
1623last closing parenthesis. Note that it works only if you have configured
20b8ac83 1624\"ssh\" to run without password query, see ssh-agent\(1\).
11948172
MA
1625
1626You will see the number of bytes sent successfully to the remote host.
1627If that number exceeds 1000, you can stop the execution by hitting
1628C-g, because your Emacs is likely clean.
1629
11948172 1630When it is necessary to set `tramp-chunksize', you might consider to
20b8ac83
MA
1631use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1632\(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
11948172 1633performance.
c951aecb 1634
00d6fd04
MA
1635If your Emacs is buggy, the code stops and gives you an indication
1636about the value `tramp-chunksize' should be set. Maybe you could just
1637experiment a bit, e.g. changing the values of `init' and `step'
1638in the third line of the code.
1639
7432277c
KG
1640Please raise a bug report via \"M-x tramp-bug\" if your system needs
1641this variable to be set as well."
1642 :group 'tramp
b1a2b924 1643 :type '(choice (const nil) integer))
7432277c 1644
5ec2cc41
KG
1645;; Logging in to a remote host normally requires obtaining a pty. But
1646;; Emacs on MacOS X has process-connection-type set to nil by default,
1647;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1648;; for an override of the system default.
1649(defcustom tramp-process-connection-type t
1650 "Overrides `process-connection-type' for connections from Tramp.
1651Tramp binds process-connection-type to the value given here before
1652opening a connection to a remote host."
1653 :group 'tramp
1654 :type '(choice (const nil) (const t) (const pty)))
1655
b50dd0d2
MA
1656(defcustom tramp-completion-reread-directory-timeout 10
1657 "Defines seconds since last remote command before rereading a directory.
1658A remote directory might have changed its contents. In order to
1659make it visible during file name completion in the minibuffer,
1660Tramp flushes its cache and rereads the directory contents when
1661more than `tramp-completion-reread-directory-timeout' seconds
1662have been gone since last remote command execution. A value of 0
1663would require an immediate reread during filename completion, nil
1664means to use always cached values for the directory contents."
1665 :group 'tramp
1666 :type '(choice (const nil) integer))
1667
fb7933a3
KG
1668;;; Internal Variables:
1669
fb7933a3 1670(defvar tramp-current-method nil
00d6fd04 1671 "Connection method for this *tramp* buffer.")
fb7933a3
KG
1672
1673(defvar tramp-current-user nil
00d6fd04 1674 "Remote login name for this *tramp* buffer.")
fb7933a3
KG
1675
1676(defvar tramp-current-host nil
00d6fd04
MA
1677 "Remote host for this *tramp* buffer.")
1678
1679(defconst tramp-uudecode
1680 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
fabf2143 1681cat /tmp/tramp.$$
00d6fd04 1682rm -f /tmp/tramp.$$"
fabf2143 1683 "Shell function to implement `uudecode' to standard output.
c08e6004
MA
1684Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1685for this or `uudecode -p', but some systems don't, and for them
1686we have this shell function.")
fabf2143 1687
293c24f9
MA
1688(defconst tramp-perl-file-truename
1689 "%s -e '
1690use File::Spec;
1691use Cwd \"realpath\";
1692
1693sub recursive {
1694 my ($volume, @dirs) = @_;
1695 my $real = realpath(File::Spec->catpath(
1696 $volume, File::Spec->catdir(@dirs), \"\"));
1697 if ($real) {
1698 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1699 return ($vol, File::Spec->splitdir($dir));
1700 }
1701 else {
1702 my $last = pop(@dirs);
1703 ($volume, @dirs) = recursive($volume, @dirs);
1704 push(@dirs, $last);
1705 return ($volume, @dirs);
1706 }
1707}
1708
1709$result = realpath($ARGV[0]);
1710if (!$result) {
1711 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1712 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1713
1714 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1715}
1716
1717if ($ARGV[0] =~ /\\/$/) {
1718 $result = $result . \"/\";
1719}
1720
1721print \"\\\"$result\\\"\\n\";
1722' \"$1\" 2>/dev/null"
1723 "Perl script to produce output suitable for use with `file-truename'
1724on the remote file system.
1725Escape sequence %s is replaced with name of Perl binary.
1726This string is passed to `format', so percent characters need to be doubled.")
1727
1728(defconst tramp-perl-file-name-all-completions
1729 "%s -e 'sub case {
1730 my $str = shift;
1731 if ($ARGV[2]) {
1732 return lc($str);
1733 }
1734 else {
1735 return $str;
1736 }
1737}
1738opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1739@files = readdir(d); closedir(d);
1740foreach $f (@files) {
1741 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1742 if (-d \"$ARGV[0]/$f\") {
1743 print \"$f/\\n\";
1744 }
1745 else {
1746 print \"$f\\n\";
1747 }
1748 }
1749}
1750print \"ok\\n\"
1751' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1752 "Perl script to produce output suitable for use with
1753`file-name-all-completions' on the remote file system. Escape
1754sequence %s is replaced with name of Perl binary. This string is
1755passed to `format', so percent characters need to be doubled.")
1756
fabf2143
KG
1757;; Perl script to implement `file-attributes' in a Lisp `read'able
1758;; output. If you are hacking on this, note that you get *no* output
1759;; unless this spits out a complete line, including the '\n' at the
1760;; end.
8daea7fc 1761;; The device number is returned as "-1", because there will be a virtual
b946a456 1762;; device number set in `tramp-handle-file-attributes'.
00d6fd04
MA
1763(defconst tramp-perl-file-attributes
1764 "%s -e '
c82c5727 1765@stat = lstat($ARGV[0]);
680db9ac
MA
1766if (!@stat) {
1767 print \"nil\\n\";
1768 exit 0;
1769}
c82c5727
LH
1770if (($stat[2] & 0170000) == 0120000)
1771{
1772 $type = readlink($ARGV[0]);
1773 $type = \"\\\"$type\\\"\";
1774}
1775elsif (($stat[2] & 0170000) == 040000)
1776{
1777 $type = \"t\";
1778}
1779else
1780{
1781 $type = \"nil\"
1782};
1783$uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1784$gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1785printf(
d4443a0d 1786 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
c82c5727
LH
1787 $type,
1788 $stat[3],
1789 $uid,
1790 $gid,
1791 $stat[8] >> 16 & 0xffff,
1792 $stat[8] & 0xffff,
1793 $stat[9] >> 16 & 0xffff,
1794 $stat[9] & 0xffff,
1795 $stat[10] >> 16 & 0xffff,
1796 $stat[10] & 0xffff,
1797 $stat[7],
1798 $stat[2],
1799 $stat[1] >> 16 & 0xffff,
1800 $stat[1] & 0xffff
20b8ac83 1801);' \"$1\" \"$2\" 2>/dev/null"
fb7933a3 1802 "Perl script to produce output suitable for use with `file-attributes'
00d6fd04
MA
1803on the remote file system.
1804Escape sequence %s is replaced with name of Perl binary.
1805This string is passed to `format', so percent characters need to be doubled.")
fb7933a3 1806
00d6fd04
MA
1807(defconst tramp-perl-directory-files-and-attributes
1808 "%s -e '
8cb0a559
LH
1809chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1810opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
c82c5727
LH
1811@list = readdir(DIR);
1812closedir(DIR);
1813$n = scalar(@list);
1814printf(\"(\\n\");
1815for($i = 0; $i < $n; $i++)
1816{
1817 $filename = $list[$i];
1818 @stat = lstat($filename);
1819 if (($stat[2] & 0170000) == 0120000)
1820 {
1821 $type = readlink($filename);
1822 $type = \"\\\"$type\\\"\";
1823 }
1824 elsif (($stat[2] & 0170000) == 040000)
1825 {
1826 $type = \"t\";
1827 }
1828 else
1829 {
1830 $type = \"nil\"
1831 };
1832 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1833 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1834 printf(
b946a456 1835 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
c82c5727
LH
1836 $filename,
1837 $type,
1838 $stat[3],
1839 $uid,
1840 $gid,
1841 $stat[8] >> 16 & 0xffff,
1842 $stat[8] & 0xffff,
1843 $stat[9] >> 16 & 0xffff,
1844 $stat[9] & 0xffff,
1845 $stat[10] >> 16 & 0xffff,
1846 $stat[10] & 0xffff,
1847 $stat[7],
1848 $stat[2],
1849 $stat[1] >> 16 & 0xffff,
1850 $stat[1] & 0xffff,
1851 $stat[0] >> 16 & 0xffff,
1852 $stat[0] & 0xffff);
1853}
20b8ac83 1854printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
c82c5727 1855 "Perl script implementing `directory-files-attributes' as Lisp `read'able
00d6fd04
MA
1856output.
1857Escape sequence %s is replaced with name of Perl binary.
1858This string is passed to `format', so percent characters need to be doubled.")
c82c5727 1859
ac474af1
KG
1860;; ;; These two use uu encoding.
1861;; (defvar tramp-perl-encode "%s -e'\
1862;; print qq(begin 644 xxx\n);
1863;; my $s = q();
1864;; my $res = q();
1865;; while (read(STDIN, $s, 45)) {
1866;; print pack(q(u), $s);
1867;; }
1868;; print qq(`\n);
1869;; print qq(end\n);
1870;; '"
1871;; "Perl program to use for encoding a file.
1872;; Escape sequence %s is replaced with name of Perl binary.")
1873
1874;; (defvar tramp-perl-decode "%s -ne '
1875;; print unpack q(u), $_;
1876;; '"
1877;; "Perl program to use for decoding a file.
1878;; Escape sequence %s is replaced with name of Perl binary.")
1879
1880;; These two use base64 encoding.
00d6fd04
MA
1881(defconst tramp-perl-encode-with-module
1882 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
ac474af1 1883 "Perl program to use for encoding a file.
b1d06e75 1884Escape sequence %s is replaced with name of Perl binary.
89509ea0 1885This string is passed to `format', so percent characters need to be doubled.
b1d06e75
KG
1886This implementation requires the MIME::Base64 Perl module to be installed
1887on the remote host.")
1888
00d6fd04
MA
1889(defconst tramp-perl-decode-with-module
1890 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
b1d06e75
KG
1891 "Perl program to use for decoding a file.
1892Escape sequence %s is replaced with name of Perl binary.
89509ea0 1893This string is passed to `format', so percent characters need to be doubled.
b1d06e75
KG
1894This implementation requires the MIME::Base64 Perl module to be installed
1895on the remote host.")
1896
00d6fd04 1897(defconst tramp-perl-encode
b1d06e75
KG
1898 "%s -e '
1899# This script contributed by Juanma Barranquero <lektu@terra.es>.
114f9c96 1900# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
cbd12ed7 1901# Free Software Foundation, Inc.
b1d06e75
KG
1902use strict;
1903
fa32e96a 1904my %%trans = do {
b1d06e75
KG
1905 my $i = 0;
1906 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1907 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1908};
1909
36541701 1910binmode(\\*STDIN);
b1d06e75
KG
1911
1912# We read in chunks of 54 bytes, to generate output lines
1913# of 72 chars (plus end of line)
36541701 1914$/ = \\54;
b1d06e75
KG
1915
1916while (my $data = <STDIN>) {
1917 my $pad = q();
1918
1919 # Only for the last chunk, and only if did not fill the last three-byte packet
1920 if (eof) {
fa32e96a 1921 my $mod = length($data) %% 3;
b1d06e75
KG
1922 $pad = q(=) x (3 - $mod) if $mod;
1923 }
1924
1925 # Not the fastest method, but it is simple: unpack to binary string, split
1926 # by groups of 6 bits and convert back from binary to byte; then map into
1927 # the translation table
1928 print
1929 join q(),
1930 map($trans{$_},
1931 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1932 $pad,
36541701 1933 qq(\\n);
00d6fd04 1934}' 2>/dev/null"
b1d06e75 1935 "Perl program to use for encoding a file.
fa32e96a 1936Escape sequence %s is replaced with name of Perl binary.
ccf29586 1937This string is passed to `format', so percent characters need to be doubled.")
ac474af1 1938
00d6fd04 1939(defconst tramp-perl-decode
b1d06e75
KG
1940 "%s -e '
1941# This script contributed by Juanma Barranquero <lektu@terra.es>.
114f9c96 1942# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
cbd12ed7 1943# Free Software Foundation, Inc.
b1d06e75
KG
1944use strict;
1945
fa32e96a 1946my %%trans = do {
b1d06e75 1947 my $i = 0;
16674e4f 1948 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
b1d06e75
KG
1949 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1950};
1951
fa32e96a 1952my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
b1d06e75 1953
36541701 1954binmode(\\*STDOUT);
b1d06e75
KG
1955
1956# We are going to accumulate into $pending to accept any line length
1957# (we do not check they are <= 76 chars as the RFC says)
1958my $pending = q();
1959
1960while (my $data = <STDIN>) {
1961 chomp $data;
1962
1963 # If we find one or two =, we have reached the end and
1964 # any following data is to be discarded
1965 my $finished = $data =~ s/(==?).*/$1/;
1966 $pending .= $data;
1967
1968 my $len = length($pending);
16674e4f 1969 my $chunk = substr($pending, 0, $len & ~3);
414da5ab 1970 $pending = substr($pending, $len & ~3 + 1);
b1d06e75
KG
1971
1972 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1973 # split in 8-bit chunks and convert back to char.
1974 print join q(),
1975 map $bytes{$_},
1976 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1977
1978 last if $finished;
00d6fd04 1979}' 2>/dev/null"
ac474af1 1980 "Perl program to use for decoding a file.
fa32e96a 1981Escape sequence %s is replaced with name of Perl binary.
ccf29586 1982This string is passed to `format', so percent characters need to be doubled.")
fb7933a3 1983
946a5aeb
MA
1984(defconst tramp-vc-registered-read-file-names
1985 "echo \"(\"
20b8ac83
MA
1986while read file; do
1987 if %s \"$file\"; then
946a5aeb
MA
1988 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1989 else
1990 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1991 fi
20b8ac83 1992 if %s \"$file\"; then
946a5aeb
MA
1993 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1994 else
1995 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1996 fi
1997done
1998echo \")\""
1999 "Script to check existence of VC related files.
2000It must be send formatted with two strings; the tests for file
20b8ac83
MA
2001existence, and file readability. Input shall be read via
2002here-document, otherwise the command could exceed maximum length
2003of command line.")
946a5aeb 2004
9ce8462a
MA
2005(defconst tramp-file-mode-type-map
2006 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
2007 (1 . "p") ; fifo
2008 (2 . "c") ; character device
2009 (3 . "m") ; multiplexed character device (v7)
2010 (4 . "d") ; directory
2011 (5 . "?") ; Named special file (XENIX)
2012 (6 . "b") ; block device
2013 (7 . "?") ; multiplexed block device (v7)
2014 (8 . "-") ; regular file
2015 (9 . "n") ; network special file (HP-UX)
2016 (10 . "l") ; symlink
2017 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
2018 (12 . "s") ; socket
2019 (13 . "D") ; door special (Solaris)
2020 (14 . "w")) ; whiteout (BSD)
fb7933a3
KG
2021 "A list of file types returned from the `stat' system call.
2022This is used to map a mode number to a permission string.")
2023
fb7933a3 2024;; New handlers should be added here. The following operations can be
c0fc6170
MA
2025;; handled using the normal primitives: file-name-sans-versions,
2026;; get-file-buffer.
fb7933a3 2027(defconst tramp-file-name-handler-alist
00d6fd04 2028 '((load . tramp-handle-load)
fb7933a3 2029 (make-symbolic-link . tramp-handle-make-symbolic-link)
c0fc6170 2030 (file-name-as-directory . tramp-handle-file-name-as-directory)
fb7933a3
KG
2031 (file-name-directory . tramp-handle-file-name-directory)
2032 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
2033 (file-truename . tramp-handle-file-truename)
2034 (file-exists-p . tramp-handle-file-exists-p)
2035 (file-directory-p . tramp-handle-file-directory-p)
2036 (file-executable-p . tramp-handle-file-executable-p)
fb7933a3
KG
2037 (file-readable-p . tramp-handle-file-readable-p)
2038 (file-regular-p . tramp-handle-file-regular-p)
2039 (file-symlink-p . tramp-handle-file-symlink-p)
2040 (file-writable-p . tramp-handle-file-writable-p)
2041 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
2042 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
2043 (file-attributes . tramp-handle-file-attributes)
2044 (file-modes . tramp-handle-file-modes)
fb7933a3 2045 (directory-files . tramp-handle-directory-files)
c82c5727 2046 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
fb7933a3
KG
2047 (file-name-all-completions . tramp-handle-file-name-all-completions)
2048 (file-name-completion . tramp-handle-file-name-completion)
2049 (add-name-to-file . tramp-handle-add-name-to-file)
2050 (copy-file . tramp-handle-copy-file)
263c02ef 2051 (copy-directory . tramp-handle-copy-directory)
fb7933a3
KG
2052 (rename-file . tramp-handle-rename-file)
2053 (set-file-modes . tramp-handle-set-file-modes)
ce3f516f 2054 (set-file-times . tramp-handle-set-file-times)
fb7933a3
KG
2055 (make-directory . tramp-handle-make-directory)
2056 (delete-directory . tramp-handle-delete-directory)
2057 (delete-file . tramp-handle-delete-file)
2058 (directory-file-name . tramp-handle-directory-file-name)
00d6fd04
MA
2059 ;; `executable-find' is not official yet.
2060 (executable-find . tramp-handle-executable-find)
2061 (start-file-process . tramp-handle-start-file-process)
0457dd55 2062 (process-file . tramp-handle-process-file)
00d6fd04 2063 (shell-command . tramp-handle-shell-command)
fb7933a3
KG
2064 (insert-directory . tramp-handle-insert-directory)
2065 (expand-file-name . tramp-handle-expand-file-name)
00d6fd04 2066 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
fb7933a3 2067 (file-local-copy . tramp-handle-file-local-copy)
19a87064 2068 (file-remote-p . tramp-handle-file-remote-p)
fb7933a3 2069 (insert-file-contents . tramp-handle-insert-file-contents)
94be87e8
MA
2070 (insert-file-contents-literally
2071 . tramp-handle-insert-file-contents-literally)
fb7933a3 2072 (write-region . tramp-handle-write-region)
38c65fca 2073 (find-backup-file-name . tramp-handle-find-backup-file-name)
c1105d05 2074 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
fb7933a3 2075 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
5ec2cc41 2076 (dired-compress-file . tramp-handle-dired-compress-file)
fb7933a3
KG
2077 (dired-recursive-delete-directory
2078 . tramp-handle-dired-recursive-delete-directory)
70c11b0b 2079 (dired-uncache . tramp-handle-dired-uncache)
fb7933a3 2080 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
49096407 2081 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
20b8ac83
MA
2082 (file-selinux-context . tramp-handle-file-selinux-context)
2083 (set-file-selinux-context . tramp-handle-set-file-selinux-context)
49096407 2084 (vc-registered . tramp-handle-vc-registered))
c1105d05 2085 "Alist of handler functions.
fb7933a3
KG
2086Operations not mentioned here will be handled by the normal Emacs functions.")
2087
a4aeb9a4 2088;; Handlers for partial Tramp file names. For Emacs just
41c8e348 2089;; `file-name-all-completions' is needed.
a01b1e22 2090;;;###autoload
16674e4f 2091(defconst tramp-completion-file-name-handler-alist
a01b1e22 2092 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
41c8e348 2093 (file-name-completion . tramp-completion-handle-file-name-completion))
16674e4f
KG
2094 "Alist of completion handler functions.
2095Used for file names matching `tramp-file-name-regexp'. Operations not
2096mentioned here will be handled by `tramp-file-name-handler-alist' or the
2097normal Emacs functions.")
2098
4007ba5b 2099;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
ea9d1443
KG
2100(defvar tramp-foreign-file-name-handler-alist
2101 ;; (identity . tramp-sh-file-name-handler) should always be the last
b88f2d0a 2102 ;; entry, because `identity' always matches.
ea9d1443 2103 '((identity . tramp-sh-file-name-handler))
4007ba5b
KG
2104 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2105If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2106calling HANDLER.")
2107
0664ff72 2108;;; Internal functions which must come first:
fb7933a3 2109
00d6fd04
MA
2110(defsubst tramp-debug-message (vec fmt-string &rest args)
2111 "Append message to debug buffer.
2112Message is formatted with FMT-STRING as control string and the remaining
2113ARGS to actually emit the message (if applicable)."
2114 (when (get-buffer (tramp-buffer-name vec))
2115 (with-current-buffer (tramp-get-debug-buffer vec)
2116 (goto-char (point-max))
70c11b0b
MA
2117 ;; Headline.
2118 (when (bobp)
2119 (insert
2120 (format
2121 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2122 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2123 emacs-version tramp-version)))
00d6fd04
MA
2124 (unless (bolp)
2125 (insert "\n"))
70c11b0b 2126 ;; Timestamp.
736ac90f
MA
2127 (let ((now (current-time)))
2128 (insert (format-time-string "%T." now))
2129 (insert (format "%06d " (nth 2 now))))
70c11b0b 2130 ;; Calling function.
00d6fd04
MA
2131 (let ((btn 1) btf fn)
2132 (while (not fn)
2133 (setq btf (nth 1 (backtrace-frame btn)))
2134 (if (not btf)
2135 (setq fn "")
2136 (when (symbolp btf)
2137 (setq fn (symbol-name btf))
2138 (unless (and (string-match "^tramp" fn)
2139 (not (string-match
20b8ac83 2140 "^tramp\\(-debug\\)?\\(-message\\|-error\\|-compat-funcall\\)$"
00d6fd04
MA
2141 fn)))
2142 (setq fn nil)))
2143 (setq btn (1+ btn))))
2144 ;; The following code inserts filename and line number.
2145 ;; Should be deactivated by default, because it is time
2146 ;; consuming.
2147; (let ((ffn (find-function-noselect (intern fn))))
2148; (insert
2149; (format
2150; "%s:%d: "
2151; (file-name-nondirectory (buffer-file-name (car ffn)))
2152; (with-current-buffer (car ffn)
2153; (1+ (count-lines (point-min) (cdr ffn)))))))
2154 (insert (format "%s " fn)))
70c11b0b 2155 ;; The message.
00d6fd04
MA
2156 (insert (apply 'format fmt-string args)))))
2157
946a5aeb
MA
2158(defvar tramp-message-show-message t
2159 "Show Tramp message in the minibuffer.
2160This variable is used to disable messages from `tramp-error'.
2161The messages are visible anyway, because an error is raised.")
2162
00d6fd04 2163(defsubst tramp-message (vec-or-proc level fmt-string &rest args)
fb7933a3 2164 "Emit a message depending on verbosity level.
a4aeb9a4 2165VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
00d6fd04
MA
2166vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2167less than LEVEL. The message is emitted only if `tramp-verbose' is
2168greater than or equal to LEVEL.
2169
2170The message is also logged into the debug buffer when `tramp-verbose'
2171is greater than or equal 4.
2172
2173Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2174control string and the remaining ARGS to actually emit the message (if
2175applicable)."
2176 (condition-case nil
2177 (when (<= level tramp-verbose)
2178 ;; Match data must be preserved!
2179 (save-match-data
2180 ;; Display only when there is a minimum level.
946a5aeb 2181 (when (and tramp-message-show-message (<= level 3))
00d6fd04
MA
2182 (apply 'message
2183 (concat
2184 (cond
2185 ((= level 0) "")
2186 ((= level 1) "")
2187 ((= level 2) "Warning: ")
2188 (t "Tramp: "))
2189 fmt-string)
2190 args))
2191 ;; Log only when there is a minimum level.
2192 (when (>= tramp-verbose 4)
2193 (when (and vec-or-proc
2194 (processp vec-or-proc)
2195 (buffer-name (process-buffer vec-or-proc)))
2196 (with-current-buffer (process-buffer vec-or-proc)
2197 ;; Translate proc to vec.
2198 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2199 (when (and vec-or-proc (vectorp vec-or-proc))
2200 (apply 'tramp-debug-message
2201 vec-or-proc
2202 (concat (format "(%d) # " level) fmt-string)
2203 args)))))
2204 ;; Suppress all errors.
2205 (error nil)))
2206
2207(defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2208 "Emit an error.
2209VEC-OR-PROC identifies the connection to use, SIGNAL is the
2210signal identifier to be raised, remaining args passed to
2211`tramp-message'. Finally, signal SIGNAL is raised."
946a5aeb
MA
2212 (let (tramp-message-show-message)
2213 (tramp-message
2214 vec-or-proc 1 "%s"
2215 (error-message-string
2216 (list signal
2217 (get signal 'error-message)
2218 (apply 'format fmt-string args))))
2219 (signal signal (list (apply 'format fmt-string args)))))
00d6fd04
MA
2220
2221(defsubst tramp-error-with-buffer
2222 (buffer vec-or-proc signal fmt-string &rest args)
2223 "Emit an error, and show BUFFER.
2224If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2225an input event arrives. The other arguments are passed to `tramp-error'."
2226 (save-window-excursion
2227 (unwind-protect
2228 (apply 'tramp-error vec-or-proc signal fmt-string args)
20b8ac83
MA
2229 (when (and vec-or-proc
2230 (not (zerop tramp-verbose))
2231 (not (tramp-completion-mode-p)))
00d6fd04
MA
2232 (let ((enable-recursive-minibuffers t))
2233 (pop-to-buffer
2234 (or (and (bufferp buffer) buffer)
2235 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2236 (tramp-get-buffer vec-or-proc)))
2237 (sit-for 30))))))
fb7933a3 2238
c62c9d08
KG
2239(defmacro with-parsed-tramp-file-name (filename var &rest body)
2240 "Parse a Tramp filename and make components available in the body.
2241
2242First arg FILENAME is evaluated and dissected into its components.
2243Second arg VAR is a symbol. It is used as a variable name to hold
2244the filename structure. It is also used as a prefix for the variables
2245holding the components. For example, if VAR is the symbol `foo', then
00d6fd04
MA
2246`foo' will be bound to the whole structure, `foo-method' will be bound to
2247the method component, and so on for `foo-user', `foo-host', `foo-localname'.
c62c9d08
KG
2248
2249Remaining args are Lisp expressions to be evaluated (inside an implicit
2250`progn').
2251
00d6fd04
MA
2252If VAR is nil, then we bind `v' to the structure and `method', `user',
2253`host', `localname' to the components."
c62c9d08 2254 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
c62c9d08
KG
2255 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2256 (tramp-file-name-method ,(or var 'v)))
2257 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2258 (tramp-file-name-user ,(or var 'v)))
2259 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2260 (tramp-file-name-host ,(or var 'v)))
7432277c
KG
2261 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2262 (tramp-file-name-localname ,(or var 'v))))
c62c9d08
KG
2263 ,@body))
2264
2265(put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
00d6fd04 2266(put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
9e6ab520 2267(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
c62c9d08 2268
00d6fd04
MA
2269(defmacro with-file-property (vec file property &rest body)
2270 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2271FILE must be a local file name on a connection identified via VEC."
2272 `(if (file-name-absolute-p ,file)
2273 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2274 (when (eq value 'undef)
2275 ;; We cannot pass @body as parameter to
2276 ;; `tramp-set-file-property' because it mangles our
2277 ;; debug messages.
2278 (setq value (progn ,@body))
2279 (tramp-set-file-property ,vec ,file ,property value))
2280 value)
2281 ,@body))
9ce8462a 2282
00d6fd04
MA
2283(put 'with-file-property 'lisp-indent-function 3)
2284(put 'with-file-property 'edebug-form-spec t)
9e6ab520 2285(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
00d6fd04
MA
2286
2287(defmacro with-connection-property (key property &rest body)
20b8ac83 2288 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
00d6fd04
MA
2289 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2290 (when (eq value 'undef)
2291 ;; We cannot pass ,@body as parameter to
2292 ;; `tramp-set-connection-property' because it mangles our debug
2293 ;; messages.
2294 (setq value (progn ,@body))
2295 (tramp-set-connection-property ,key ,property value))
2296 value))
9ce8462a 2297
00d6fd04
MA
2298(put 'with-connection-property 'lisp-indent-function 2)
2299(put 'with-connection-property 'edebug-form-spec t)
9e6ab520 2300(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
00d6fd04 2301
20b8ac83
MA
2302(defun tramp-progress-reporter-update (reporter &optional value)
2303 (let* ((parameters (cdr reporter))
2304 (message (aref parameters 3)))
2305 (when (string-match message (or (current-message) ""))
2306 (funcall 'progress-reporter-update reporter value))))
2307
2308(defmacro with-progress-reporter (vec level message &rest body)
2309 "Executes BODY, spinning a progress reporter with MESSAGE.
2310If LEVEL does not fit for visible messages, or if this is a
2311nested call of the macro, there are only traces without a visible
2312progress reporter."
2313 `(let (pr tm)
2314 (tramp-message ,vec ,level "%s..." ,message)
2315 ;; We start a pulsing progress reporter after 3 seconds. Feature
2316 ;; introduced in Emacs 24.1.
2317 (when (and tramp-message-show-message
2318 ;; Display only when there is a minimum level.
2319 (<= ,level (min tramp-verbose 3)))
2320 (condition-case nil
2321 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
2322 tm (when pr
2323 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))
2324 (error nil)))
2325 (unwind-protect
2326 ;; Execute the body. Unset `tramp-message-show-message' when
2327 ;; the timer object is created, in order to suppress
2328 ;; concurrent timers.
2329 (let ((tramp-message-show-message
2330 (and tramp-message-show-message (not tm))))
2331 ,@body)
2332 ;; Stop progress reporter.
2333 (if tm (tramp-compat-funcall 'cancel-timer tm))
2334 (tramp-message ,vec ,level "%s...done" ,message))))
2335
2336(put 'with-progress-reporter 'lisp-indent-function 3)
2337(put 'with-progress-reporter 'edebug-form-spec t)
2338(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
2339
2340(eval-and-compile ;; Silence compiler.
628c97b2
GM
2341 (if (memq system-type '(cygwin windows-nt))
2342 (defun tramp-drop-volume-letter (name)
2343 "Cut off unnecessary drive letter from file NAME.
2344The function `tramp-handle-expand-file-name' calls `expand-file-name'
2345locally on a remote file name. When the local system is a W32 system
2346but the remote system is Unix, this introduces a superfluous drive
2347letter into the file name. This function removes it."
2348 (save-match-data
2349 (if (string-match tramp-root-regexp name)
2350 (replace-match "/" nil t name)
2351 name)))
2352
2353 (defalias 'tramp-drop-volume-letter 'identity)))
2354
9c13938d 2355(defsubst tramp-make-tramp-temp-file (vec)
a6e96327 2356 "Create a temporary file on the remote host identified by VEC.
9c13938d
MA
2357Return the local name of the temporary file."
2358 (let ((prefix
2359 (tramp-make-tramp-file-name
2360 (tramp-file-name-method vec)
2361 (tramp-file-name-user vec)
2362 (tramp-file-name-host vec)
113e2a84
MA
2363 (tramp-drop-volume-letter
2364 (expand-file-name
2365 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
9c13938d
MA
2366 result)
2367 (while (not result)
2368 ;; `make-temp-file' would be the natural choice for
2369 ;; implementation. But it calls `write-region' internally,
2370 ;; which also needs a temporary file - we would end in an
2371 ;; infinite loop.
2372 (setq result (make-temp-name prefix))
2373 (if (file-exists-p result)
2374 (setq result nil)
2375 ;; This creates the file by side effect.
2376 (set-file-times result)
2377 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2378
2379 ;; Return the local part.
2380 (with-parsed-tramp-file-name result nil localname)))
8a4438b6
MA
2381
2382
16674e4f
KG
2383;;; Config Manipulation Functions:
2384
2385(defun tramp-set-completion-function (method function-list)
2386 "Sets the list of completion functions for METHOD.
2387FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2388The FUNCTION is intended to parse FILE according its syntax.
2389It might be a predefined FUNCTION, or a user defined FUNCTION.
2390Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
8fc29035 2391`tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
8daea7fc
KG
2392and `tramp-parse-netrc'.
2393
16674e4f
KG
2394Example:
2395
2396 (tramp-set-completion-function
2397 \"ssh\"
8daea7fc
KG
2398 '((tramp-parse-sconfig \"/etc/ssh_config\")
2399 (tramp-parse-sconfig \"~/.ssh/config\")))"
16674e4f 2400
5ec2cc41
KG
2401 (let ((r function-list)
2402 (v function-list))
2403 (setq tramp-completion-function-alist
2404 (delete (assoc method tramp-completion-function-alist)
2405 tramp-completion-function-alist))
2406
2407 (while v
00d6fd04 2408 ;; Remove double entries.
5ec2cc41
KG
2409 (when (member (car v) (cdr v))
2410 (setcdr v (delete (car v) (cdr v))))
00d6fd04 2411 ;; Check for function and file or registry key.
5ec2cc41 2412 (unless (and (functionp (nth 0 (car v)))
00d6fd04
MA
2413 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2414 ;; Windows registry.
2415 (and (memq system-type '(cygwin windows-nt))
a4aeb9a4
MA
2416 (zerop
2417 (tramp-local-call-process
2418 "reg" nil nil nil "query" (nth 1 (car v)))))
00d6fd04
MA
2419 ;; Configuration file.
2420 (file-exists-p (nth 1 (car v)))))
5ec2cc41
KG
2421 (setq r (delete (car v) r)))
2422 (setq v (cdr v)))
2423
2424 (when r
4007ba5b 2425 (add-to-list 'tramp-completion-function-alist
5ec2cc41 2426 (cons method r)))))
16674e4f
KG
2427
2428(defun tramp-get-completion-function (method)
00d6fd04 2429 "Returns a list of completion functions for METHOD.
16674e4f 2430For definition of that list see `tramp-set-completion-function'."
00d6fd04
MA
2431 (cons
2432 ;; Hosts visited once shall be remembered.
2433 `(tramp-parse-connection-properties ,method)
2434 ;; The method related defaults.
2435 (cdr (assoc method tramp-completion-function-alist))))
16674e4f 2436
d037d501 2437
0664ff72 2438;;; Fontification of `read-file-name':
d037d501 2439
0664ff72 2440;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
d037d501
MA
2441(defvar tramp-rfn-eshadow-overlay)
2442(make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2443
2444(defun tramp-rfn-eshadow-setup-minibuffer ()
2445 "Set up a minibuffer for `file-name-shadow-mode'.
2446Adds another overlay hiding filename parts according to Tramp's
2447special handling of `substitute-in-file-name'."
9ce8462a 2448 (when (symbol-value 'minibuffer-completing-file-name)
d037d501 2449 (setq tramp-rfn-eshadow-overlay
20b8ac83
MA
2450 (tramp-compat-funcall
2451 'make-overlay
2452 (tramp-compat-funcall 'minibuffer-prompt-end)
2453 (tramp-compat-funcall 'minibuffer-prompt-end)))
d037d501 2454 ;; Copy rfn-eshadow-overlay properties.
20b8ac83
MA
2455 (let ((props (tramp-compat-funcall
2456 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
d037d501 2457 (while props
20b8ac83
MA
2458 (tramp-compat-funcall
2459 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
d037d501
MA
2460
2461(when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2462 (add-hook 'rfn-eshadow-setup-minibuffer-hook
48846dc5
MA
2463 'tramp-rfn-eshadow-setup-minibuffer)
2464 (add-hook 'tramp-unload-hook
aa485f7c
MA
2465 (lambda ()
2466 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2467 'tramp-rfn-eshadow-setup-minibuffer))))
d037d501 2468
adcbca53
MA
2469(defconst tramp-rfn-eshadow-update-overlay-regexp
2470 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2471
d037d501
MA
2472(defun tramp-rfn-eshadow-update-overlay ()
2473 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2474This is intended to be used as a minibuffer `post-command-hook' for
2475`file-name-shadow-mode'; the minibuffer should have already
2476been set up by `rfn-eshadow-setup-minibuffer'."
2477 ;; In remote files name, there is a shadowing just for the local part.
20b8ac83
MA
2478 (let ((end (or (tramp-compat-funcall
2479 'overlay-end (symbol-value 'rfn-eshadow-overlay))
2480 (tramp-compat-funcall 'minibuffer-prompt-end))))
2481 (when
2482 (file-remote-p
2483 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
bd316474
KY
2484 (save-excursion
2485 (save-restriction
2486 (narrow-to-region
adcbca53
MA
2487 (1+ (or (string-match
2488 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2489 end))
2490 (point-max))
bd316474
KY
2491 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2492 (rfn-eshadow-update-overlay-hook nil))
20b8ac83
MA
2493 (tramp-compat-funcall
2494 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
2495 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
d037d501
MA
2496
2497(when (boundp 'rfn-eshadow-update-overlay-hook)
2498 (add-hook 'rfn-eshadow-update-overlay-hook
b88f2d0a
MA
2499 'tramp-rfn-eshadow-update-overlay)
2500 (add-hook 'tramp-unload-hook
2501 (lambda ()
2502 (remove-hook 'rfn-eshadow-update-overlay-hook
2503 'tramp-rfn-eshadow-update-overlay))))
d037d501
MA
2504
2505
605a20a9
MA
2506;;; Integration of eshell.el:
2507
2508(eval-when-compile
2509 (defvar eshell-path-env))
2510
2511;; eshell.el keeps the path in `eshell-path-env'. We must change it
2512;; when `default-directory' points to another host.
2513(defun tramp-eshell-directory-change ()
2514 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2515 (setq eshell-path-env
2516 (if (file-remote-p default-directory)
2517 (with-parsed-tramp-file-name default-directory nil
2518 (mapconcat
2519 'identity
2520 (tramp-get-remote-path v)
2521 ":"))
2522 (getenv "PATH"))))
2523
2524(eval-after-load "esh-util"
2525 '(progn
2526 (tramp-eshell-directory-change)
2527 (add-hook 'eshell-directory-change-hook
2528 'tramp-eshell-directory-change)
2529 (add-hook 'tramp-unload-hook
2530 (lambda ()
2531 (remove-hook 'eshell-directory-change-hook
2532 'tramp-eshell-directory-change)))))
2533
2534
fb7933a3
KG
2535;;; File Name Handler Functions:
2536
fb7933a3
KG
2537(defun tramp-handle-make-symbolic-link
2538 (filename linkname &optional ok-if-already-exists)
00d6fd04 2539 "Like `make-symbolic-link' for Tramp files.
cebb4ec6 2540If LINKNAME is a non-Tramp file, it is used verbatim as the target of
7432277c 2541the symlink. If LINKNAME is a Tramp file, only the localname component is
cebb4ec6
KG
2542used as the target of the symlink.
2543
7432277c
KG
2544If LINKNAME is a Tramp file and the localname component is relative, then
2545it is expanded first, before the localname component is taken. Note that
cebb4ec6
KG
2546this can give surprising results if the user/host for the source and
2547target of the symlink differ."
c62c9d08 2548 (with-parsed-tramp-file-name linkname l
00d6fd04 2549 (let ((ln (tramp-get-remote-ln l))
87bdd2c7
MA
2550 (cwd (tramp-run-real-handler
2551 'file-name-directory (list l-localname))))
c62c9d08 2552 (unless ln
00d6fd04
MA
2553 (tramp-error
2554 l 'file-error
20b8ac83 2555 "Making a symbolic link. ln(1) does not exist on the remote host."))
c62c9d08
KG
2556
2557 ;; Do the 'confirm if exists' thing.
cebb4ec6 2558 (when (file-exists-p linkname)
c62c9d08
KG
2559 ;; What to do?
2560 (if (or (null ok-if-already-exists) ; not allowed to exist
2561 (and (numberp ok-if-already-exists)
2562 (not (yes-or-no-p
2563 (format
2564 "File %s already exists; make it a link anyway? "
7432277c 2565 l-localname)))))
00d6fd04
MA
2566 (tramp-error
2567 l 'file-already-exists "File %s already exists" l-localname)
cebb4ec6
KG
2568 (delete-file linkname)))
2569
7432277c 2570 ;; If FILENAME is a Tramp name, use just the localname component.
cebb4ec6 2571 (when (tramp-tramp-file-p filename)
1834b39f
MA
2572 (setq filename
2573 (tramp-file-name-localname
2574 (tramp-dissect-file-name (expand-file-name filename)))))
bf247b6e 2575
20b8ac83
MA
2576 (tramp-flush-file-property l (file-name-directory l-localname))
2577 (tramp-flush-file-property l l-localname)
2578
c62c9d08
KG
2579 ;; Right, they are on the same host, regardless of user, method, etc.
2580 ;; We now make the link on the remote machine. This will occur as the user
2581 ;; that FILENAME belongs to.
2582 (zerop
2583 (tramp-send-command-and-check
b593f105
MA
2584 l
2585 (format
2586 "cd %s && %s -sf %s %s"
2587 (tramp-shell-quote-argument cwd)
2588 ln
2589 (tramp-shell-quote-argument filename)
2590 (tramp-shell-quote-argument l-localname))
2591 t)))))
fb7933a3 2592
fb7933a3 2593(defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
00d6fd04
MA
2594 "Like `load' for Tramp files."
2595 (with-parsed-tramp-file-name (expand-file-name file) nil
c62c9d08
KG
2596 (unless nosuffix
2597 (cond ((file-exists-p (concat file ".elc"))
2598 (setq file (concat file ".elc")))
2599 ((file-exists-p (concat file ".el"))
2600 (setq file (concat file ".el")))))
2601 (when must-suffix
2602 ;; The first condition is always true for absolute file names.
2603 ;; Included for safety's sake.
2604 (unless (or (file-name-directory file)
2605 (string-match "\\.elc?\\'" file))
00d6fd04
MA
2606 (tramp-error
2607 v 'file-error
2608 "File `%s' does not include a `.el' or `.elc' suffix" file)))
c62c9d08
KG
2609 (unless noerror
2610 (when (not (file-exists-p file))
00d6fd04 2611 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
c62c9d08
KG
2612 (if (not (file-exists-p file))
2613 nil
20b8ac83
MA
2614 (let ((tramp-message-show-message (not nomessage)))
2615 (with-progress-reporter v 0 (format "Loading %s" file)
2616 (let ((local-copy (file-local-copy file)))
2617 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2618 (unwind-protect
2619 (load local-copy noerror t t)
2620 (delete-file local-copy)))))
c62c9d08 2621 t)))
fb7933a3 2622
a4aeb9a4 2623;; Localname manipulation functions that grok Tramp localnames...
c0fc6170
MA
2624(defun tramp-handle-file-name-as-directory (file)
2625 "Like `file-name-as-directory' but aware of Tramp files."
2626 ;; `file-name-as-directory' would be sufficient except localname is
2627 ;; the empty string.
2628 (let ((v (tramp-dissect-file-name file t)))
2629 ;; Run the command on the localname portion only.
2630 (tramp-make-tramp-file-name
2631 (tramp-file-name-method v)
2632 (tramp-file-name-user v)
2633 (tramp-file-name-host v)
2634 (tramp-run-real-handler
2635 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2636
fb7933a3 2637(defun tramp-handle-file-name-directory (file)
00d6fd04 2638 "Like `file-name-directory' but aware of Tramp files."
9ce8462a
MA
2639 ;; Everything except the last filename thing is the directory. We
2640 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2641 ;; the remote file name parts. This is a problem when we are in
2642 ;; file name completion.
2643 (let ((v (tramp-dissect-file-name file t)))
a01b1e22
MA
2644 ;; Run the command on the localname portion only.
2645 (tramp-make-tramp-file-name
9ce8462a
MA
2646 (tramp-file-name-method v)
2647 (tramp-file-name-user v)
2648 (tramp-file-name-host v)
87bdd2c7
MA
2649 (tramp-run-real-handler
2650 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
fb7933a3
KG
2651
2652(defun tramp-handle-file-name-nondirectory (file)
00d6fd04 2653 "Like `file-name-nondirectory' but aware of Tramp files."
c62c9d08 2654 (with-parsed-tramp-file-name file nil
87bdd2c7 2655 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
fb7933a3
KG
2656
2657(defun tramp-handle-file-truename (filename &optional counter prev-dirs)
00d6fd04 2658 "Like `file-truename' for Tramp files."
48ddd622 2659 (with-parsed-tramp-file-name (expand-file-name filename) nil
00d6fd04 2660 (with-file-property v localname "file-truename"
293c24f9 2661 (let ((result nil)) ; result steps in reverse order
00d6fd04 2662 (tramp-message v 4 "Finding true name for `%s'" filename)
293c24f9
MA
2663 (cond
2664 ;; Use GNU readlink --canonicalize-missing where available.
2665 ((tramp-get-remote-readlink v)
2666 (setq result
2667 (tramp-send-command-and-read
2668 v
2669 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2670 (tramp-get-remote-readlink v)
2671 (tramp-shell-quote-argument localname)))))
2672
2673 ;; Use Perl implementation.
2674 ((and (tramp-get-remote-perl v)
2675 (tramp-get-connection-property v "perl-file-spec" nil)
2676 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2677 (tramp-maybe-send-script
2678 v tramp-perl-file-truename "tramp_perl_file_truename")
2679 (setq result
2680 (tramp-send-command-and-read
2681 v
2682 (format "tramp_perl_file_truename %s"
2683 (tramp-shell-quote-argument localname)))))
2684
2685 ;; Do it yourself. We bind `directory-sep-char' here for
2686 ;; XEmacs on Windows, which would otherwise use backslash.
2687 (t (let* ((directory-sep-char ?/)
2688 (steps (tramp-compat-split-string localname "/"))
2689 (localnamedir (tramp-run-real-handler
2690 'file-name-as-directory (list localname)))
2691 (is-dir (string= localname localnamedir))
2692 (thisstep nil)
2693 (numchase 0)
2694 ;; Don't make the following value larger than
2695 ;; necessary. People expect an error message in a
2696 ;; timely fashion when something is wrong;
2697 ;; otherwise they might think that Emacs is hung.
2698 ;; Of course, correctness has to come first.
2699 (numchase-limit 20)
2700 symlink-target)
2701 (while (and steps (< numchase numchase-limit))
2702 (setq thisstep (pop steps))
2703 (tramp-message
2704 v 5 "Check %s"
2705 (mapconcat 'identity
2706 (append '("") (reverse result) (list thisstep))
2707 "/"))
2708 (setq symlink-target
2709 (nth 0 (file-attributes
2710 (tramp-make-tramp-file-name
2711 method user host
2712 (mapconcat 'identity
2713 (append '("")
2714 (reverse result)
2715 (list thisstep))
2716 "/")))))
2717 (cond ((string= "." thisstep)
2718 (tramp-message v 5 "Ignoring step `.'"))
2719 ((string= ".." thisstep)
2720 (tramp-message v 5 "Processing step `..'")
2721 (pop result))
2722 ((stringp symlink-target)
2723 ;; It's a symlink, follow it.
2724 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2725 (setq numchase (1+ numchase))
2726 (when (file-name-absolute-p symlink-target)
2727 (setq result nil))
2728 ;; If the symlink was absolute, we'll get a string like
2729 ;; "/user@host:/some/target"; extract the
2730 ;; "/some/target" part from it.
2731 (when (tramp-tramp-file-p symlink-target)
2732 (unless (tramp-equal-remote filename symlink-target)
2733 (tramp-error
2734 v 'file-error
2735 "Symlink target `%s' on wrong host" symlink-target))
2736 (setq symlink-target localname))
2737 (setq steps
2738 (append (tramp-compat-split-string
2739 symlink-target "/")
2740 steps)))
2741 (t
2742 ;; It's a file.
2743 (setq result (cons thisstep result)))))
2744 (when (>= numchase numchase-limit)
2745 (tramp-error
2746 v 'file-error
2747 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2748 (setq result (reverse result))
2749 ;; Combine list to form string.
2750 (setq result
2751 (if result
2752 (mapconcat 'identity (cons "" result) "/")
00d6fd04 2753 "/"))
293c24f9
MA
2754 (when (and is-dir (or (string= "" result)
2755 (not (string= (substring result -1) "/"))))
2756 (setq result (concat result "/"))))))
2757
2758 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2759 (tramp-make-tramp-file-name method user host result)))))
fb7933a3
KG
2760
2761;; Basic functions.
2762
2763(defun tramp-handle-file-exists-p (filename)
00d6fd04 2764 "Like `file-exists-p' for Tramp files."
c62c9d08 2765 (with-parsed-tramp-file-name filename nil
00d6fd04 2766 (with-file-property v localname "file-exists-p"
293c24f9
MA
2767 (or (not (null (tramp-get-file-property
2768 v localname "file-attributes-integer" nil)))
2769 (not (null (tramp-get-file-property
2770 v localname "file-attributes-string" nil)))
2771 (zerop (tramp-send-command-and-check
2772 v
2773 (format
2774 "%s %s"
2775 (tramp-get-file-exists-command v)
2776 (tramp-shell-quote-argument localname))))))))
fb7933a3 2777
00d6fd04
MA
2778;; Inodes don't exist for some file systems. Therefore we must
2779;; generate virtual ones. Used in `find-buffer-visiting'. The method
2780;; applied might be not so efficient (Ange-FTP uses hashes). But
2781;; performance isn't the major issue given that file transfer will
2782;; take time.
2783(defvar tramp-inodes nil
2784 "Keeps virtual inodes numbers.")
2785
8daea7fc
KG
2786;; Devices must distinguish physical file systems. The device numbers
2787;; provided by "lstat" aren't unique, because we operate on different hosts.
2788;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2789;; EFS use device number "-1". In order to be different, we use device number
b946a456 2790;; (-1 . x), whereby "x" is unique for a given (method user host).
8daea7fc
KG
2791(defvar tramp-devices nil
2792 "Keeps virtual device numbers.")
2793
fb7933a3
KG
2794;; CCC: This should check for an error condition and signal failure
2795;; when something goes wrong.
2796;; Daniel Pittman <daniel@danann.net>
c951aecb 2797(defun tramp-handle-file-attributes (filename &optional id-format)
00d6fd04
MA
2798 "Like `file-attributes' for Tramp files."
2799 (unless id-format (setq id-format 'integer))
aa485f7c
MA
2800 ;; Don't modify `last-coding-system-used' by accident.
2801 (let ((last-coding-system-used last-coding-system-used))
2802 (with-parsed-tramp-file-name (expand-file-name filename) nil
2803 (with-file-property v localname (format "file-attributes-%s" id-format)
7f49fe46
MA
2804 (save-excursion
2805 (tramp-convert-file-attributes
2806 v
2807 (cond
2808 ((tramp-get-remote-stat v)
2809 (tramp-do-file-attributes-with-stat v localname id-format))
2810 ((tramp-get-remote-perl v)
2811 (tramp-do-file-attributes-with-perl v localname id-format))
2812 (t
2813 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2814
2815(defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
00d6fd04 2816 "Implement `file-attributes' for Tramp files using the ls(1) command."
fb7933a3
KG
2817 (let (symlinkp dirp
2818 res-inode res-filemodes res-numlinks
2819 res-uid res-gid res-size res-symlink-target)
00d6fd04 2820 (tramp-message vec 5 "file attributes with ls: %s" localname)
fb7933a3 2821 (tramp-send-command
00d6fd04 2822 vec
680db9ac
MA
2823 (format "(%s %s || %s -h %s) && %s %s %s"
2824 (tramp-get-file-exists-command vec)
2825 (tramp-shell-quote-argument localname)
2826 (tramp-get-test-command vec)
2827 (tramp-shell-quote-argument localname)
00d6fd04 2828 (tramp-get-ls-command vec)
c82c5727 2829 (if (eq id-format 'integer) "-ildn" "-ild")
7432277c 2830 (tramp-shell-quote-argument localname)))
fb7933a3 2831 ;; parse `ls -l' output ...
00d6fd04 2832 (with-current-buffer (tramp-get-buffer vec)
680db9ac
MA
2833 (when (> (buffer-size) 0)
2834 (goto-char (point-min))
2835 ;; ... inode
2836 (setq res-inode
2837 (condition-case err
2838 (read (current-buffer))
2839 (invalid-read-syntax
2840 (when (and (equal (cadr err)
2841 "Integer constant overflow in reader")
2842 (string-match
2843 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2844 (car (cddr err))))
2845 (let* ((big (read (substring (car (cddr err)) 0
2846 (match-beginning 1))))
2847 (small (read (match-string 1 (car (cddr err)))))
2848 (twiddle (/ small 65536)))
2849 (cons (+ big twiddle)
2850 (- small (* twiddle 65536))))))))
2851 ;; ... file mode flags
2852 (setq res-filemodes (symbol-name (read (current-buffer))))
2853 ;; ... number links
2854 (setq res-numlinks (read (current-buffer)))
2855 ;; ... uid and gid
2856 (setq res-uid (read (current-buffer)))
2857 (setq res-gid (read (current-buffer)))
2858 (if (eq id-format 'integer)
2859 (progn
2860 (unless (numberp res-uid) (setq res-uid -1))
2861 (unless (numberp res-gid) (setq res-gid -1)))
2862 (progn
2863 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2864 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2865 ;; ... size
2866 (setq res-size (read (current-buffer)))
2867 ;; From the file modes, figure out other stuff.
2868 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2869 (setq dirp (eq ?d (aref res-filemodes 0)))
2870 ;; if symlink, find out file name pointed to
2871 (when symlinkp
2872 (search-forward "-> ")
2873 (setq res-symlink-target
2874 (buffer-substring (point) (tramp-compat-line-end-position))))
2875 ;; return data gathered
2876 (list
2877 ;; 0. t for directory, string (name linked to) for symbolic
2878 ;; link, or nil.
2879 (or dirp res-symlink-target)
2880 ;; 1. Number of links to file.
2881 res-numlinks
2882 ;; 2. File uid.
2883 res-uid
2884 ;; 3. File gid.
2885 res-gid
2886 ;; 4. Last access time, as a list of two integers. First
2887 ;; integer has high-order 16 bits of time, second has low 16
2888 ;; bits.
2889 ;; 5. Last modification time, likewise.
2890 ;; 6. Last status change time, likewise.
2891 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2892 ;; 7. Size in bytes (-1, if number is out of range).
2893 res-size
2894 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2895 res-filemodes
2896 ;; 9. t if file's gid would change if file were deleted and
2897 ;; recreated. Will be set in `tramp-convert-file-attributes'
2898 t
2899 ;; 10. inode number.
2900 res-inode
2901 ;; 11. Device number. Will be replaced by a virtual device number.
2902 -1
2903 )))))
fb7933a3 2904
7f49fe46 2905(defun tramp-do-file-attributes-with-perl
00d6fd04
MA
2906 (vec localname &optional id-format)
2907 "Implement `file-attributes' for Tramp files using a Perl script."
2908 (tramp-message vec 5 "file attributes with perl: %s" localname)
2909 (tramp-maybe-send-script
2910 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2911 (tramp-send-command-and-read
2912 vec
2913 (format "tramp_perl_file_attributes %s %s"
2914 (tramp-shell-quote-argument localname) id-format)))
2915
7f49fe46 2916(defun tramp-do-file-attributes-with-stat
00d6fd04
MA
2917 (vec localname &optional id-format)
2918 "Implement `file-attributes' for Tramp files using stat(1) command."
2919 (tramp-message vec 5 "file attributes with stat: %s" localname)
2920 (tramp-send-command-and-read
2921 vec
2922 (format
20b8ac83
MA
2923 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
2924 ;; parse correctly the sequence "((". Therefore, we add a space.
bca0f839 2925 "( (%s %s || %s -h %s) && %s -c '( (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)' %s || echo nil)"
680db9ac
MA
2926 (tramp-get-file-exists-command vec)
2927 (tramp-shell-quote-argument localname)
2928 (tramp-get-test-command vec)
2929 (tramp-shell-quote-argument localname)
00d6fd04
MA
2930 (tramp-get-remote-stat vec)
2931 (if (eq id-format 'integer) "%u" "\"%U\"")
2932 (if (eq id-format 'integer) "%g" "\"%G\"")
2933 (tramp-shell-quote-argument localname))))
8daea7fc 2934
fb7933a3 2935(defun tramp-handle-set-visited-file-modtime (&optional time-list)
00d6fd04 2936 "Like `set-visited-file-modtime' for Tramp files."
fb7933a3
KG
2937 (unless (buffer-file-name)
2938 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2939 (buffer-name)))
48ddd622
MA
2940 (if time-list
2941 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
11948172
MA
2942 (let ((f (buffer-file-name))
2943 coding-system-used)
48ddd622
MA
2944 (with-parsed-tramp-file-name f nil
2945 (let* ((attr (file-attributes f))
2946 ;; '(-1 65535) means file doesn't exists yet.
2947 (modtime (or (nth 5 attr) '(-1 65535))))
11948172
MA
2948 (when (boundp 'last-coding-system-used)
2949 (setq coding-system-used (symbol-value 'last-coding-system-used)))
48ddd622 2950 ;; We use '(0 0) as a don't-know value. See also
7f49fe46 2951 ;; `tramp-do-file-attributes-with-ls'.
48ddd622
MA
2952 (if (not (equal modtime '(0 0)))
2953 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
00d6fd04 2954 (progn
48ddd622 2955 (tramp-send-command
00d6fd04 2956 v
48ddd622 2957 (format "%s -ild %s"
00d6fd04 2958 (tramp-get-ls-command v)
48ddd622 2959 (tramp-shell-quote-argument localname)))
48ddd622
MA
2960 (setq attr (buffer-substring (point)
2961 (progn (end-of-line) (point)))))
00d6fd04
MA
2962 (tramp-set-file-property
2963 v localname "visited-file-modtime-ild" attr))
11948172
MA
2964 (when (boundp 'last-coding-system-used)
2965 (set 'last-coding-system-used coding-system-used))
d2a2c17f 2966 nil)))))
fb7933a3 2967
c62c9d08
KG
2968;; This function makes the same assumption as
2969;; `tramp-handle-set-visited-file-modtime'.
2970(defun tramp-handle-verify-visited-file-modtime (buf)
00d6fd04 2971 "Like `verify-visited-file-modtime' for Tramp files.
c08e6004
MA
2972At the time `verify-visited-file-modtime' calls this function, we
2973already know that the buffer is visiting a file and that
2974`visited-file-modtime' does not return 0. Do not call this
2975function directly, unless those two cases are already taken care
2976of."
c62c9d08 2977 (with-current-buffer buf
20b8ac83
MA
2978 (let ((f (buffer-file-name)))
2979 ;; There is no file visiting the buffer, or the buffer has no
2980 ;; recorded last modification time, or there is no established
2981 ;; connection.
2982 (if (or (not f)
2983 (eq (visited-file-modtime) 0)
2984 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
2985 t
b15d0c4c 2986 (with-parsed-tramp-file-name f nil
bce04fee 2987 (tramp-flush-file-property v localname)
b15d0c4c
MA
2988 (let* ((attr (file-attributes f))
2989 (modtime (nth 5 attr))
2990 (mt (visited-file-modtime)))
bf247b6e 2991
70c11b0b
MA
2992 (cond
2993 ;; File exists, and has a known modtime.
b15d0c4c
MA
2994 ((and attr (not (equal modtime '(0 0))))
2995 (< (abs (tramp-time-diff
2996 modtime
2997 ;; For compatibility, deal with both the old
70c11b0b
MA
2998 ;; (HIGH . LOW) and the new (HIGH LOW) return
2999 ;; values of `visited-file-modtime'.
b15d0c4c
MA
3000 (if (atom (cdr mt))
3001 (list (car mt) (cdr mt))
3002 mt)))
3003 2))
70c11b0b 3004 ;; Modtime has the don't know value.
b15d0c4c 3005 (attr
00d6fd04
MA
3006 (tramp-send-command
3007 v
3008 (format "%s -ild %s"
3009 (tramp-get-ls-command v)
3010 (tramp-shell-quote-argument localname)))
3011 (with-current-buffer (tramp-get-buffer v)
b15d0c4c
MA
3012 (setq attr (buffer-substring
3013 (point) (progn (end-of-line) (point)))))
00d6fd04
MA
3014 (equal
3015 attr
3016 (tramp-get-file-property
3017 v localname "visited-file-modtime-ild" "")))
70c11b0b
MA
3018 ;; If file does not exist, say it is not modified if and
3019 ;; only if that agrees with the buffer's record.
b15d0c4c 3020 (t (equal mt '(-1 65535))))))))))
c62c9d08 3021
fb7933a3 3022(defun tramp-handle-set-file-modes (filename mode)
00d6fd04 3023 "Like `set-file-modes' for Tramp files."
c62c9d08 3024 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3025 (tramp-flush-file-property v localname)
3026 (unless (zerop (tramp-send-command-and-check
3027 v
3028 (format "chmod %s %s"
3029 (tramp-decimal-to-octal mode)
3030 (tramp-shell-quote-argument localname))))
3031 ;; FIXME: extract the proper text from chmod's stderr.
3032 (tramp-error
3033 v 'file-error "Error while changing file's mode %s" filename))))
fb7933a3 3034
ce3f516f
MA
3035(defun tramp-handle-set-file-times (filename &optional time)
3036 "Like `set-file-times' for Tramp files."
3037 (zerop
9e6ab520 3038 (if (file-remote-p filename)
ce3f516f 3039 (with-parsed-tramp-file-name filename nil
8d60099b 3040 (tramp-flush-file-property v localname)
ce3f516f
MA
3041 (let ((time (if (or (null time) (equal time '(0 0)))
3042 (current-time)
3043 time))
20b8ac83
MA
3044 ;; With GNU Emacs, `format-time-string' has an optional
3045 ;; parameter UNIVERSAL. This is preferred, because we
3046 ;; could handle the case when the remote host is
3047 ;; located in a different time zone as the local host.
3048 (utc (not (featurep 'xemacs))))
ce3f516f
MA
3049 (tramp-send-command-and-check
3050 v (format "%s touch -t %s %s"
3051 (if utc "TZ=UTC; export TZ;" "")
3052 (if utc
3053 (format-time-string "%Y%m%d%H%M.%S" time t)
3054 (format-time-string "%Y%m%d%H%M.%S" time))
3055 (tramp-shell-quote-argument localname)))))
8d60099b 3056
ce3f516f
MA
3057 ;; We handle also the local part, because in older Emacsen,
3058 ;; without `set-file-times', this function is an alias for this.
3059 ;; We are local, so we don't need the UTC settings.
a4aeb9a4 3060 (tramp-local-call-process
ce3f516f
MA
3061 "touch" nil nil nil "-t"
3062 (format-time-string "%Y%m%d%H%M.%S" time)
3063 (tramp-shell-quote-argument filename)))))
3064
8d60099b
MA
3065(defun tramp-set-file-uid-gid (filename &optional uid gid)
3066 "Set the ownership for FILENAME.
3067If UID and GID are provided, these values are used; otherwise uid
3068and gid of the corresponding user is taken. Both parameters must be integers."
70c11b0b
MA
3069 ;; Modern Unices allow chown only for root. So we might need
3070 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
3071 ;; working with su(do)? when it is needed, so it shall succeed in
3072 ;; the majority of cases.
aa485f7c
MA
3073 ;; Don't modify `last-coding-system-used' by accident.
3074 (let ((last-coding-system-used last-coding-system-used))
3075 (if (file-remote-p filename)
3076 (with-parsed-tramp-file-name filename nil
3077 (if (and (zerop (user-uid)) (tramp-local-host-p v))
3078 ;; If we are root on the local host, we can do it directly.
3079 (tramp-set-file-uid-gid localname uid gid)
3080 (let ((uid (or (and (integerp uid) uid)
3081 (tramp-get-remote-uid v 'integer)))
3082 (gid (or (and (integerp gid) gid)
3083 (tramp-get-remote-gid v 'integer))))
3084 (tramp-send-command
3085 v (format
3086 "chown %d:%d %s" uid gid
3087 (tramp-shell-quote-argument localname))))))
3088
3089 ;; We handle also the local part, because there doesn't exist
3090 ;; `set-file-uid-gid'. On W32 "chown" might not work.
3091 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
3092 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
3093 (tramp-local-call-process
3094 "chown" nil nil nil
3095 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
8d60099b 3096
20b8ac83
MA
3097(defun tramp-remote-selinux-p (vec)
3098 "Check, whether SELINUX is enabled on the remote host."
3099 (with-connection-property (tramp-get-connection-process vec) "selinux-p"
3100 (let ((result (tramp-find-executable
3101 vec "getenforce" (tramp-get-remote-path vec) t t)))
3102 (and result
3103 (string-equal
3104 (tramp-send-command-and-read
3105 vec (format "echo \\\"`%S`\\\"" result))
3106 "Enforcing")))))
3107
3108(defun tramp-handle-file-selinux-context (filename)
3109 "Like `file-selinux-context' for Tramp files."
3110 (with-parsed-tramp-file-name filename nil
3111 (with-file-property v localname "file-selinux-context"
3112 (let ((context '(nil nil nil nil))
3113 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
3114 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
3115 (when (and (tramp-remote-selinux-p v)
3116 (zerop (tramp-send-command-and-check
3117 v (format
3118 "%s -d -Z %s"
3119 (tramp-get-ls-command v)
3120 (tramp-shell-quote-argument localname)))))
3121 (with-current-buffer (tramp-get-connection-buffer v)
3122 (goto-char (point-min))
3123 (when (re-search-forward regexp (tramp-compat-line-end-position) t)
3124 (setq context (list (match-string 1) (match-string 2)
3125 (match-string 3) (match-string 4))))))
3126 ;; Return the context.
3127 context))))
3128
3129(defun tramp-handle-set-file-selinux-context (filename context)
3130 "Like `set-file-selinux-context' for Tramp files."
3131 (with-parsed-tramp-file-name filename nil
3132 (if (and (consp context)
3133 (tramp-remote-selinux-p v)
3134 (zerop (tramp-send-command-and-check
3135 v (format "chcon %s %s %s %s %s"
3136 (if (stringp (nth 0 context))
3137 (format "--user=%s" (nth 0 context)) "")
3138 (if (stringp (nth 1 context))
3139 (format "--role=%s" (nth 1 context)) "")
3140 (if (stringp (nth 2 context))
3141 (format "--type=%s" (nth 2 context)) "")
3142 (if (stringp (nth 3 context))
3143 (format "--range=%s" (nth 3 context)) "")
3144 (tramp-shell-quote-argument localname)))))
3145 (tramp-set-file-property v localname "file-selinux-context" context)
3146 (tramp-set-file-property v localname "file-selinux-context" 'undef)))
3147 ;; We always return nil.
3148 nil)
3149
fb7933a3
KG
3150;; Simple functions using the `test' command.
3151
3152(defun tramp-handle-file-executable-p (filename)
00d6fd04 3153 "Like `file-executable-p' for Tramp files."
c62c9d08 3154 (with-parsed-tramp-file-name filename nil
00d6fd04 3155 (with-file-property v localname "file-executable-p"
293c24f9
MA
3156 ;; Examine `file-attributes' cache to see if request can be
3157 ;; satisfied without remote operation.
3158 (or (tramp-check-cached-permissions v ?x)
3159 (zerop (tramp-run-test "-x" filename))))))
fb7933a3
KG
3160
3161(defun tramp-handle-file-readable-p (filename)
00d6fd04 3162 "Like `file-readable-p' for Tramp files."
c62c9d08 3163 (with-parsed-tramp-file-name filename nil
00d6fd04 3164 (with-file-property v localname "file-readable-p"
293c24f9
MA
3165 ;; Examine `file-attributes' cache to see if request can be
3166 ;; satisfied without remote operation.
3167 (or (tramp-check-cached-permissions v ?r)
3168 (zerop (tramp-run-test "-r" filename))))))
fb7933a3
KG
3169
3170;; When the remote shell is started, it looks for a shell which groks
3171;; tilde expansion. Here, we assume that all shells which grok tilde
3172;; expansion will also provide a `test' command which groks `-nt' (for
3173;; newer than). If this breaks, tell me about it and I'll try to do
3174;; something smarter about it.
3175(defun tramp-handle-file-newer-than-file-p (file1 file2)
00d6fd04 3176 "Like `file-newer-than-file-p' for Tramp files."
fb7933a3
KG
3177 (cond ((not (file-exists-p file1))
3178 nil)
3179 ((not (file-exists-p file2))
3180 t)
91879624 3181 ;; We are sure both files exist at this point.
fb7933a3
KG
3182 (t
3183 (save-excursion
91879624
KG
3184 ;; We try to get the mtime of both files. If they are not
3185 ;; equal to the "dont-know" value, then we subtract the times
3186 ;; and obtain the result.
3187 (let ((fa1 (file-attributes file1))
3188 (fa2 (file-attributes file2)))
3189 (if (and (not (equal (nth 5 fa1) '(0 0)))
3190 (not (equal (nth 5 fa2) '(0 0))))
01917a18 3191 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
91879624
KG
3192 ;; If one of them is the dont-know value, then we can
3193 ;; still try to run a shell command on the remote host.
3194 ;; However, this only works if both files are Tramp
3195 ;; files and both have the same method, same user, same
3196 ;; host.
00d6fd04
MA
3197 (unless (tramp-equal-remote file1 file2)
3198 (with-parsed-tramp-file-name
3199 (if (tramp-tramp-file-p file1) file1 file2) nil
3200 (tramp-error
3201 v 'file-error
3202 "Files %s and %s must have same method, user, host"
3203 file1 file2)))
3204 (with-parsed-tramp-file-name file1 nil
3205 (zerop (tramp-run-test2
3206 (tramp-get-test-nt-command v) file1 file2)))))))))
fb7933a3
KG
3207
3208;; Functions implemented using the basic functions above.
3209
3210(defun tramp-handle-file-modes (filename)
00d6fd04 3211 "Like `file-modes' for Tramp files."
5da24108
MA
3212 (let ((truename (or (file-truename filename) filename)))
3213 (when (file-exists-p truename)
3214 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
fb7933a3 3215
b86c1cd8
MA
3216(defun tramp-default-file-modes (filename)
3217 "Return file modes of FILENAME as integer.
3218If the file modes of FILENAME cannot be determined, return the
974647ac
MA
3219value of `default-file-modes', without execute permissions."
3220 (or (file-modes filename)
3221 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
b86c1cd8 3222
fb7933a3 3223(defun tramp-handle-file-directory-p (filename)
00d6fd04 3224 "Like `file-directory-p' for Tramp files."
fb7933a3
KG
3225 ;; Care must be taken that this function returns `t' for symlinks
3226 ;; pointing to directories. Surely the most obvious implementation
3227 ;; would be `test -d', but that returns false for such symlinks.
3228 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3229 ;; I now think he's right. So we could be using `test -d', couldn't
3230 ;; we?
3231 ;;
3232 ;; Alternatives: `cd %s', `test -d %s'
c62c9d08 3233 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3234 (with-file-property v localname "file-directory-p"
3235 (zerop (tramp-run-test "-d" filename)))))
fb7933a3
KG
3236
3237(defun tramp-handle-file-regular-p (filename)
00d6fd04
MA
3238 "Like `file-regular-p' for Tramp files."
3239 (and (file-exists-p filename)
3240 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
fb7933a3
KG
3241
3242(defun tramp-handle-file-symlink-p (filename)
00d6fd04 3243 "Like `file-symlink-p' for Tramp files."
c62c9d08 3244 (with-parsed-tramp-file-name filename nil
c951aecb 3245 (let ((x (car (file-attributes filename))))
b25a52cc
KG
3246 (when (stringp x)
3247 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3248 ;; might do weird things.
3249 (if (file-name-absolute-p x)
00d6fd04 3250 (tramp-make-tramp-file-name method user host x)
b25a52cc 3251 x)))))
fb7933a3
KG
3252
3253(defun tramp-handle-file-writable-p (filename)
00d6fd04 3254 "Like `file-writable-p' for Tramp files."
c62c9d08 3255 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3256 (with-file-property v localname "file-writable-p"
3257 (if (file-exists-p filename)
293c24f9
MA
3258 ;; Examine `file-attributes' cache to see if request can be
3259 ;; satisfied without remote operation.
3260 (or (tramp-check-cached-permissions v ?w)
3261 (zerop (tramp-run-test "-w" filename)))
00d6fd04
MA
3262 ;; If file doesn't exist, check if directory is writable.
3263 (and (zerop (tramp-run-test
3264 "-d" (file-name-directory filename)))
3265 (zerop (tramp-run-test
3266 "-w" (file-name-directory filename))))))))
fb7933a3
KG
3267
3268(defun tramp-handle-file-ownership-preserved-p (filename)
00d6fd04 3269 "Like `file-ownership-preserved-p' for Tramp files."
c62c9d08 3270 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3271 (with-file-property v localname "file-ownership-preserved-p"
3272 (let ((attributes (file-attributes filename)))
3273 ;; Return t if the file doesn't exist, since it's true that no
3274 ;; information would be lost by an (attempted) delete and create.
3275 (or (null attributes)
3276 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
fb7933a3
KG
3277
3278;; Other file name ops.
3279
fb7933a3 3280(defun tramp-handle-directory-file-name (directory)
00d6fd04 3281 "Like `directory-file-name' for Tramp files."
7432277c
KG
3282 ;; If localname component of filename is "/", leave it unchanged.
3283 ;; Otherwise, remove any trailing slash from localname component.
8daea7fc
KG
3284 ;; Method, host, etc, are unchanged. Does it make sense to try
3285 ;; to avoid parsing the filename?
c62c9d08 3286 (with-parsed-tramp-file-name directory nil
7432277c
KG
3287 (if (and (not (zerop (length localname)))
3288 (eq (aref localname (1- (length localname))) ?/)
3289 (not (string= localname "/")))
8daea7fc
KG
3290 (substring directory 0 -1)
3291 directory)))
fb7933a3
KG
3292
3293;; Directory listings.
3294
00d6fd04
MA
3295(defun tramp-handle-directory-files
3296 (directory &optional full match nosort files-only)
3297 "Like `directory-files' for Tramp files."
3298 ;; FILES-ONLY is valid for XEmacs only.
3299 (when (file-directory-p directory)
73a37a69 3300 (setq directory (file-name-as-directory (expand-file-name directory)))
00d6fd04
MA
3301 (let ((temp (nreverse (file-name-all-completions "" directory)))
3302 result item)
3303
3304 (while temp
3305 (setq item (directory-file-name (pop temp)))
3306 (when (and (or (null match) (string-match match item))
3307 (or (null files-only)
73a37a69 3308 ;; Files only.
00d6fd04 3309 (and (equal files-only t) (file-regular-p item))
73a37a69 3310 ;; Directories only.
00d6fd04 3311 (file-directory-p item)))
73a37a69 3312 (push (if full (concat directory item) item)
00d6fd04 3313 result)))
73a37a69 3314 (if nosort result (sort result 'string<)))))
c62c9d08 3315
c82c5727
LH
3316(defun tramp-handle-directory-files-and-attributes
3317 (directory &optional full match nosort id-format)
00d6fd04
MA
3318 "Like `directory-files-and-attributes' for Tramp files."
3319 (unless id-format (setq id-format 'integer))
3320 (when (file-directory-p directory)
3321 (setq directory (expand-file-name directory))
3322 (let* ((temp
20b8ac83 3323 (copy-tree
00d6fd04
MA
3324 (with-parsed-tramp-file-name directory nil
3325 (with-file-property
3326 v localname
3327 (format "directory-files-and-attributes-%s" id-format)
3328 (save-excursion
3329 (mapcar
aa485f7c
MA
3330 (lambda (x)
3331 (cons (car x)
3332 (tramp-convert-file-attributes v (cdr x))))
7f49fe46
MA
3333 (cond
3334 ((tramp-get-remote-stat v)
3335 (tramp-do-directory-files-and-attributes-with-stat
3336 v localname id-format))
3337 ((tramp-get-remote-perl v)
3338 (tramp-do-directory-files-and-attributes-with-perl
3339 v localname id-format)))))))))
00d6fd04
MA
3340 result item)
3341
3342 (while temp
3343 (setq item (pop temp))
3344 (when (or (null match) (string-match match (car item)))
3345 (when full
3346 (setcar item (expand-file-name (car item) directory)))
3347 (push item result)))
3348
3349 (if nosort
3350 result
3351 (sort result (lambda (x y) (string< (car x) (car y))))))))
3352
7f49fe46 3353(defun tramp-do-directory-files-and-attributes-with-perl
00d6fd04
MA
3354 (vec localname &optional id-format)
3355 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3356 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3357 (tramp-maybe-send-script
3358 vec tramp-perl-directory-files-and-attributes
3359 "tramp_perl_directory_files_and_attributes")
3360 (let ((object
3361 (tramp-send-command-and-read
3362 vec
3363 (format "tramp_perl_directory_files_and_attributes %s %s"
3364 (tramp-shell-quote-argument localname) id-format))))
3365 (when (stringp object) (tramp-error vec 'file-error object))
3366 object))
3367
7f49fe46 3368(defun tramp-do-directory-files-and-attributes-with-stat
00d6fd04
MA
3369 (vec localname &optional id-format)
3370 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3371 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3372 (tramp-send-command-and-read
3373 vec
3374 (format
3375 (concat
70c11b0b
MA
3376 ;; We must care about filenames with spaces, or starting with
3377 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3378 ;; but it does not work on all remote systems. Therefore, we
3379 ;; quote the filenames via sed.
3380 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
bca0f839 3381 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)'); "
00d6fd04
MA
3382 "echo \")\"")
3383 (tramp-shell-quote-argument localname)
3384 (tramp-get-ls-command vec)
3385 (tramp-get-remote-stat vec)
3386 (if (eq id-format 'integer) "%u" "\"%U\"")
3387 (if (eq id-format 'integer) "%g" "\"%G\""))))
c82c5727 3388
c62c9d08 3389;; This function should return "foo/" for directories and "bar" for
00d6fd04 3390;; files.
c62c9d08 3391(defun tramp-handle-file-name-all-completions (filename directory)
00d6fd04
MA
3392 "Like `file-name-all-completions' for Tramp files."
3393 (unless (save-match-data (string-match "/" filename))
9c13938d 3394 (with-parsed-tramp-file-name (expand-file-name directory) nil
b50dd0d2 3395
00d6fd04
MA
3396 (all-completions
3397 filename
3398 (mapcar
3399 'list
293c24f9
MA
3400 (or
3401 ;; Try cache first
3402 (and
3403 ;; Ignore if expired
3404 (or (not (integerp tramp-completion-reread-directory-timeout))
3405 (<= (tramp-time-diff
3406 (current-time)
3407 (tramp-get-file-property
3408 v localname "last-completion" '(0 0 0)))
3409 tramp-completion-reread-directory-timeout))
3410
3411 ;; Try cache entries for filename, filename with last
3412 ;; character removed, filename with last two characters
3413 ;; removed, ..., and finally the empty string - all
3414 ;; concatenated to the local directory name
3415
3416 ;; This is inefficient for very long filenames, pity
3417 ;; `reduce' is not available...
3418 (car
3419 (apply
3420 'append
3421 (mapcar
3422 (lambda (x)
3423 (let ((cache-hit
3424 (tramp-get-file-property
3425 v
3426 (concat localname (substring filename 0 x))
3427 "file-name-all-completions"
3428 nil)))
3429 (when cache-hit (list cache-hit))))
3430 (tramp-compat-number-sequence (length filename) 0 -1)))))
3431
3432 ;; Cache expired or no matching cache entry found so we need
3433 ;; to perform a remote operation
3434 (let (result)
3435 ;; Get a list of directories and files, including reliably
3436 ;; tagging the directories with a trailing '/'. Because I
3437 ;; rock. --daniel@danann.net
3438
3439 ;; Changed to perform `cd' in the same remote op and only
3440 ;; get entries starting with `filename'. Capture any `cd'
3441 ;; error messages. Ensure any `cd' and `echo' aliases are
3442 ;; ignored.
3443 (tramp-send-command
3444 v
3445 (if (tramp-get-remote-perl v)
3446 (progn
3447 (tramp-maybe-send-script
3448 v tramp-perl-file-name-all-completions
3449 "tramp_perl_file_name_all_completions")
3450 (format "tramp_perl_file_name_all_completions %s %s %d"
3451 (tramp-shell-quote-argument localname)
3452 (tramp-shell-quote-argument filename)
3453 (if (symbol-value
20b8ac83
MA
3454 ;; `read-file-name-completion-ignore-case'
3455 ;; is introduced with Emacs 22.1.
3456 (if (boundp
3457 'read-file-name-completion-ignore-case)
3458 'read-file-name-completion-ignore-case
3459 'completion-ignore-case))
293c24f9
MA
3460 1 0)))
3461
3462 (format (concat
3463 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3464 ;; `ls' with wildcard might fail with `Argument
3465 ;; list too long' error in some corner cases; if
3466 ;; `ls' fails after `cd' succeeded, chances are
3467 ;; that's the case, so let's retry without
3468 ;; wildcard. This will return "too many" entries
3469 ;; but that isn't harmful.
3470 " || %s -a 2>/dev/null)"
3471 " | while read f; do"
3472 " if %s -d \"$f\" 2>/dev/null;"
3473 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3474 " && \\echo ok) || \\echo fail")
3475 (tramp-shell-quote-argument localname)
3476 (tramp-get-ls-command v)
3477 ;; When `filename' is empty, just `ls' without
3478 ;; filename argument is more efficient than `ls *'
3479 ;; for very large directories and might avoid the
3480 ;; `Argument list too long' error.
3481 ;;
3482 ;; With and only with wildcard, we need to add
3483 ;; `-d' to prevent `ls' from descending into
3484 ;; sub-directories.
3485 (if (zerop (length filename))
3486 "."
3487 (concat (tramp-shell-quote-argument filename) "* -d"))
3488 (tramp-get-ls-command v)
3489 (tramp-get-test-command v))))
3490
3491 ;; Now grab the output.
3492 (with-current-buffer (tramp-get-buffer v)
3493 (goto-char (point-max))
3494
3495 ;; Check result code, found in last line of output
3496 (forward-line -1)
3497 (if (looking-at "^fail$")
3498 (progn
3499 ;; Grab error message from line before last line
3500 ;; (it was put there by `cd 2>&1')
3501 (forward-line -1)
3502 (tramp-error
3503 v 'file-error
3504 "tramp-handle-file-name-all-completions: %s"
3505 (buffer-substring
3506 (point) (tramp-compat-line-end-position))))
3507 ;; For peace of mind, if buffer doesn't end in `fail'
3508 ;; then it should end in `ok'. If neither are in the
3509 ;; buffer something went seriously wrong on the remote
3510 ;; side.
3511 (unless (looking-at "^ok$")
3512 (tramp-error
3513 v 'file-error
3514 "\
3515tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3516 (tramp-shell-quote-argument localname) (buffer-string))))
3517
3518 (while (zerop (forward-line -1))
3519 (push (buffer-substring
3520 (point) (tramp-compat-line-end-position))
3521 result)))
3522
3523 ;; Because the remote op went through OK we know the
3524 ;; directory we `cd'-ed to exists
3525 (tramp-set-file-property
3526 v localname "file-exists-p" t)
3527
3528 ;; Because the remote op went through OK we know every
3529 ;; file listed by `ls' exists.
3530 (mapc (lambda (entry)
3531 (tramp-set-file-property
3532 v (concat localname entry) "file-exists-p" t))
3533 result)
3534
3535 (tramp-set-file-property
3536 v localname "last-completion" (current-time))
3537
3538 ;; Store result in the cache
3539 (tramp-set-file-property
3540 v (concat localname filename)
3541 "file-name-all-completions"
3542 result))))))))
fb7933a3 3543
e1e17cae
MA
3544(defun tramp-handle-file-name-completion
3545 (filename directory &optional predicate)
00d6fd04 3546 "Like `file-name-completion' for Tramp files."
fb7933a3
KG
3547 (unless (tramp-tramp-file-p directory)
3548 (error
3549 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3550 directory))
83e20b5c
MA
3551 (try-completion
3552 filename
3553 (mapcar 'list (file-name-all-completions filename directory))
3554 (when predicate
3555 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
fb7933a3
KG
3556
3557;; cp, mv and ln
3558
3559(defun tramp-handle-add-name-to-file
3560 (filename newname &optional ok-if-already-exists)
00d6fd04
MA
3561 "Like `add-name-to-file' for Tramp files."
3562 (unless (tramp-equal-remote filename newname)
3563 (with-parsed-tramp-file-name
3564 (if (tramp-tramp-file-p filename) filename newname) nil
3565 (tramp-error
3566 v 'file-error
3567 "add-name-to-file: %s"
3568 "only implemented for same method, same user, same host")))
c62c9d08
KG
3569 (with-parsed-tramp-file-name filename v1
3570 (with-parsed-tramp-file-name newname v2
00d6fd04 3571 (let ((ln (when v1 (tramp-get-remote-ln v1))))
c62c9d08
KG
3572 (when (and (not ok-if-already-exists)
3573 (file-exists-p newname)
3574 (not (numberp ok-if-already-exists))
3575 (y-or-n-p
3576 (format
3577 "File %s already exists; make it a new name anyway? "
3578 newname)))
00d6fd04
MA
3579 (tramp-error
3580 v2 'file-error
3581 "add-name-to-file: file %s already exists" newname))
aac0b0f2 3582 (tramp-flush-file-property v2 (file-name-directory v2-localname))
00d6fd04 3583 (tramp-flush-file-property v2 v2-localname)
c62c9d08 3584 (tramp-barf-unless-okay
00d6fd04 3585 v1
7432277c
KG
3586 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3587 (tramp-shell-quote-argument v2-localname))
c62c9d08
KG
3588 "error with add-name-to-file, see buffer `%s' for details"
3589 (buffer-name))))))
fb7933a3
KG
3590
3591(defun tramp-handle-copy-file
20b8ac83
MA
3592 (filename newname &optional ok-if-already-exists keep-date
3593 preserve-uid-gid preserve-selinux-context)
00d6fd04 3594 "Like `copy-file' for Tramp files."
fb7933a3
KG
3595 (setq filename (expand-file-name filename))
3596 (setq newname (expand-file-name newname))
9e6ab520 3597 (cond
a4aeb9a4 3598 ;; At least one file a Tramp file?
9e6ab520
MA
3599 ((or (tramp-tramp-file-p filename)
3600 (tramp-tramp-file-p newname))
3601 (tramp-do-copy-or-rename-file
20b8ac83
MA
3602 'copy filename newname ok-if-already-exists keep-date
3603 preserve-uid-gid preserve-selinux-context))
9e6ab520 3604 ;; Compat section.
20b8ac83
MA
3605 (preserve-selinux-context
3606 (tramp-run-real-handler
3607 'copy-file
3608 (list filename newname ok-if-already-exists keep-date
3609 preserve-uid-gid preserve-selinux-context)))
9e6ab520 3610 (preserve-uid-gid
fb7933a3 3611 (tramp-run-real-handler
8d60099b 3612 'copy-file
9e6ab520
MA
3613 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3614 (t
3615 (tramp-run-real-handler
3616 'copy-file (list filename newname ok-if-already-exists keep-date)))))
fb7933a3 3617
263c02ef
MA
3618(defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3619 "Like `copy-directory' for Tramp files."
3620 (let ((t1 (tramp-tramp-file-p dirname))
3621 (t2 (tramp-tramp-file-p newname)))
3622 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3623 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3624 ;; When DIRNAME and NEWNAME are remote, they must have
3625 ;; the same method.
3626 (or (null t1) (null t2)
b000a6e2
MA
3627 (string-equal
3628 (tramp-file-name-method (tramp-dissect-file-name dirname))
3629 (tramp-file-name-method (tramp-dissect-file-name newname)))))
263c02ef
MA
3630 ;; scp or rsync DTRT.
3631 (progn
3632 (setq dirname (directory-file-name (expand-file-name dirname))
3633 newname (directory-file-name (expand-file-name newname)))
3634 (if (and (file-directory-p newname)
3635 (not (string-equal (file-name-nondirectory dirname)
3636 (file-name-nondirectory newname))))
3637 (setq newname
3638 (expand-file-name
3639 (file-name-nondirectory dirname) newname)))
3640 (if (not (file-directory-p (file-name-directory newname)))
3641 (make-directory (file-name-directory newname) parents))
3642 (tramp-do-copy-or-rename-file-out-of-band
3643 'copy dirname newname keep-date))
3644 ;; We must do it file-wise.
3645 (tramp-run-real-handler
aac0b0f2
MA
3646 'copy-directory (list dirname newname keep-date parents)))
3647
3648 ;; When newname did exist, we have wrong cached values.
3649 (when t2
3650 (with-parsed-tramp-file-name newname nil
3651 (tramp-flush-file-property v (file-name-directory localname))
3652 (tramp-flush-file-property v localname))))))
263c02ef 3653
fb7933a3
KG
3654(defun tramp-handle-rename-file
3655 (filename newname &optional ok-if-already-exists)
00d6fd04 3656 "Like `rename-file' for Tramp files."
fb7933a3 3657 ;; Check if both files are local -- invoke normal rename-file.
a4aeb9a4 3658 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3659 (setq filename (expand-file-name filename))
3660 (setq newname (expand-file-name newname))
a4aeb9a4 3661 ;; At least one file a Tramp file?
fb7933a3
KG
3662 (if (or (tramp-tramp-file-p filename)
3663 (tramp-tramp-file-p newname))
3664 (tramp-do-copy-or-rename-file
8d60099b 3665 'rename filename newname ok-if-already-exists t t)
00d6fd04
MA
3666 (tramp-run-real-handler
3667 'rename-file (list filename newname ok-if-already-exists))))
fb7933a3
KG
3668
3669(defun tramp-do-copy-or-rename-file
20b8ac83
MA
3670 (op filename newname &optional ok-if-already-exists keep-date
3671 preserve-uid-gid preserve-selinux-context)
fb7933a3
KG
3672 "Copy or rename a remote file.
3673OP must be `copy' or `rename' and indicates the operation to perform.
3674FILENAME specifies the file to copy or rename, NEWNAME is the name of
3675the new file (for copy) or the new name of the file (for rename).
3676OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3677KEEP-DATE means to make sure that NEWNAME has the same timestamp
8d60099b
MA
3678as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3679the uid and gid if both files are on the same host.
20b8ac83 3680PRESERVE-SELINUX-CONTEXT activates selinux commands.
fb7933a3
KG
3681
3682This function is invoked by `tramp-handle-copy-file' and
3683`tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3684and `rename'. FILENAME and NEWNAME must be absolute file names."
3685 (unless (memq op '(copy rename))
3686 (error "Unknown operation `%s', must be `copy' or `rename'" op))
90dc758d 3687 (let ((t1 (tramp-tramp-file-p filename))
20b8ac83
MA
3688 (t2 (tramp-tramp-file-p newname))
3689 (context (and preserve-selinux-context
3690 (apply 'file-selinux-context (list filename))))
3691 pr tm)
5ec2cc41 3692
20b8ac83
MA
3693 (with-parsed-tramp-file-name (if t1 filename newname) nil
3694 (when (and (not ok-if-already-exists) (file-exists-p newname))
da1975d7 3695 (tramp-error
20b8ac83 3696 v 'file-already-exists "File %s already exists" newname))
5ec2cc41 3697
20b8ac83
MA
3698 (with-progress-reporter
3699 v 0 (format "%s %s to %s"
3700 (if (eq op 'copy) "Copying" "Renaming")
3701 filename newname)
905fb90e 3702
00d6fd04
MA
3703 (cond
3704 ;; Both are Tramp files.
3705 ((and t1 t2)
3706 (with-parsed-tramp-file-name filename v1
3707 (with-parsed-tramp-file-name newname v2
3708 (cond
20b8ac83
MA
3709 ;; Shortcut: if method, host, user are the same for
3710 ;; both files, we invoke `cp' or `mv' on the remote
3711 ;; host directly.
00d6fd04
MA
3712 ((tramp-equal-remote filename newname)
3713 (tramp-do-copy-or-rename-file-directly
8d60099b
MA
3714 op filename newname
3715 ok-if-already-exists keep-date preserve-uid-gid))
3716
905fb90e 3717 ;; Try out-of-band operation.
7f49fe46
MA
3718 ((tramp-method-out-of-band-p
3719 v1 (nth 7 (file-attributes filename)))
00d6fd04
MA
3720 (tramp-do-copy-or-rename-file-out-of-band
3721 op filename newname keep-date))
8d60099b 3722
20b8ac83
MA
3723 ;; No shortcut was possible. So we copy the file
3724 ;; first. If the operation was `rename', we go back
3725 ;; and delete the original file (if the copy was
00d6fd04
MA
3726 ;; successful). The approach is simple-minded: we
3727 ;; create a new buffer, insert the contents of the
3728 ;; source file into it, then write out the buffer to
3729 ;; the target file. The advantage is that it doesn't
3730 ;; matter which filename handlers are used for the
3731 ;; source and target file.
3732 (t
3733 (tramp-do-copy-or-rename-file-via-buffer
3734 op filename newname keep-date))))))
3735
3736 ;; One file is a Tramp file, the other one is local.
3737 ((or t1 t2)
20b8ac83
MA
3738 (cond
3739 ;; Fast track on local machine.
3740 ((tramp-local-host-p v)
3741 (tramp-do-copy-or-rename-file-directly
3742 op filename newname
3743 ok-if-already-exists keep-date preserve-uid-gid))
3744
3745 ;; If the Tramp file has an out-of-band method, the
3746 ;; corresponding copy-program can be invoked.
3747 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3748 (tramp-do-copy-or-rename-file-out-of-band
3749 op filename newname keep-date))
3750
3751 ;; Use the inline method via a Tramp buffer.
3752 (t (tramp-do-copy-or-rename-file-via-buffer
3753 op filename newname keep-date))))
00d6fd04
MA
3754
3755 (t
3756 ;; One of them must be a Tramp file.
3757 (error "Tramp implementation says this cannot happen")))
8d60099b 3758
20b8ac83
MA
3759 ;; Handle `preserve-selinux-context'.
3760 (when context (apply 'set-file-selinux-context (list newname context)))
484ea0b6 3761
20b8ac83
MA
3762 ;; In case of `rename', we must flush the cache of the source file.
3763 (when (and t1 (eq op 'rename))
3764 (with-parsed-tramp-file-name filename v1
3765 (tramp-flush-file-property v1 (file-name-directory localname))
3766 (tramp-flush-file-property v1 localname)))
905fb90e 3767
20b8ac83
MA
3768 ;; When newname did exist, we have wrong cached values.
3769 (when t2
3770 (with-parsed-tramp-file-name newname v2
3771 (tramp-flush-file-property v2 (file-name-directory localname))
3772 (tramp-flush-file-property v2 localname)))))))
7432277c 3773
38c65fca 3774(defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
90dc758d
KG
3775 "Use an Emacs buffer to copy or rename a file.
3776First arg OP is either `copy' or `rename' and indicates the operation.
3777FILENAME is the source file, NEWNAME the target file.
3778KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
8a798e41
MA
3779 (with-temp-buffer
3780 ;; We must disable multibyte, because binary data shall not be
3781 ;; converted.
3782 (set-buffer-multibyte nil)
3783 (let ((coding-system-for-read 'binary)
3784 (jka-compr-inhibit t))
3785 (insert-file-contents-literally filename))
3786 ;; We don't want the target file to be compressed, so we let-bind
3787 ;; `jka-compr-inhibit' to t.
3788 (let ((coding-system-for-write 'binary)
3789 (jka-compr-inhibit t))
3790 (write-region (point-min) (point-max) newname)))
3791 ;; KEEP-DATE handling.
3792 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3793 ;; Set the mode.
b86c1cd8 3794 (set-file-modes newname (tramp-default-file-modes filename))
8a798e41
MA
3795 ;; If the operation was `rename', delete the original file.
3796 (unless (eq op 'copy) (delete-file filename)))
fb7933a3
KG
3797
3798(defun tramp-do-copy-or-rename-file-directly
8d60099b 3799 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3800 "Invokes `cp' or `mv' on the remote system.
3801OP must be one of `copy' or `rename', indicating `cp' or `mv',
8d60099b
MA
3802respectively. FILENAME specifies the file to copy or rename,
3803NEWNAME is the name of the new file (for copy) or the new name of
3804the file (for rename). Both files must reside on the same host.
3805KEEP-DATE means to make sure that NEWNAME has the same timestamp
3806as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3807the uid and gid from FILENAME."
8a4438b6 3808 (let ((t1 (tramp-tramp-file-p filename))
4f4126e6
MA
3809 (t2 (tramp-tramp-file-p newname))
3810 (file-times (nth 5 (file-attributes filename)))
3811 (file-modes (tramp-default-file-modes filename)))
8a4438b6
MA
3812 (with-parsed-tramp-file-name (if t1 filename newname) nil
3813 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3814 ((eq op 'copy) "cp -f")
3815 ((eq op 'rename) "mv -f")
3816 (t (tramp-error
3817 v 'file-error
3818 "Unknown operation `%s', must be `copy' or `rename'"
3819 op))))
3820 (localname1
20b8ac83
MA
3821 (if t1
3822 (tramp-file-name-handler 'file-remote-p filename 'localname)
3823 filename))
8a4438b6 3824 (localname2
20b8ac83
MA
3825 (if t2
3826 (tramp-file-name-handler 'file-remote-p newname 'localname)
3827 newname))
293c24f9
MA
3828 (prefix (file-remote-p (if t1 filename newname)))
3829 cmd-result)
8d60099b 3830
8d60099b 3831 (cond
8a4438b6
MA
3832 ;; Both files are on a remote host, with same user.
3833 ((and t1 t2)
293c24f9
MA
3834 (setq cmd-result
3835 (tramp-send-command-and-check
3836 v
3837 (format "%s %s %s" cmd
3838 (tramp-shell-quote-argument localname1)
3839 (tramp-shell-quote-argument localname2))))
8a4438b6
MA
3840 (with-current-buffer (tramp-get-buffer v)
3841 (goto-char (point-min))
3842 (unless
3843 (or
3844 (and keep-date
3845 ;; Mask cp -f error.
3846 (re-search-forward
3847 tramp-operation-not-permitted-regexp nil t))
293c24f9 3848 (zerop cmd-result))
8a4438b6
MA
3849 (tramp-error-with-buffer
3850 nil v 'file-error
3851 "Copying directly failed, see buffer `%s' for details."
3852 (buffer-name)))))
3853
3854 ;; We are on the local host.
3855 ((or t1 t2)
8d60099b 3856 (cond
8a4438b6 3857 ;; We can do it directly.
87bdd2c7
MA
3858 ((let (file-name-handler-alist)
3859 (and (file-readable-p localname1)
3860 (file-writable-p (file-name-directory localname2))
3861 (or (file-directory-p localname2)
3862 (file-writable-p localname2))))
8d60099b 3863 (if (eq op 'copy)
9e6ab520
MA
3864 (tramp-compat-copy-file
3865 localname1 localname2 ok-if-already-exists
3866 keep-date preserve-uid-gid)
87bdd2c7
MA
3867 (tramp-run-real-handler
3868 'rename-file (list localname1 localname2 ok-if-already-exists))))
8a4438b6
MA
3869
3870 ;; We can do it directly with `tramp-send-command'
946a5aeb
MA
3871 ((and (file-readable-p (concat prefix localname1))
3872 (file-writable-p
3873 (file-name-directory (concat prefix localname2)))
3874 (or (file-directory-p (concat prefix localname2))
3875 (file-writable-p (concat prefix localname2))))
8a4438b6
MA
3876 (tramp-do-copy-or-rename-file-directly
3877 op (concat prefix localname1) (concat prefix localname2)
3878 ok-if-already-exists keep-date t)
3879 ;; We must change the ownership to the local user.
8d60099b 3880 (tramp-set-file-uid-gid
8a4438b6
MA
3881 (concat prefix localname2)
3882 (tramp-get-local-uid 'integer)
3883 (tramp-get-local-gid 'integer)))
8d60099b 3884
8a4438b6
MA
3885 ;; We need a temporary file in between.
3886 (t
2c418c5b
MA
3887 ;; Create the temporary file.
3888 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
917b89a6 3889 (unwind-protect
2c418c5b
MA
3890 (progn
3891 (cond
3892 (t1
917b89a6
MA
3893 (or
3894 (zerop
3895 (tramp-send-command-and-check
3896 v (format
3897 "%s %s %s" cmd
3898 (tramp-shell-quote-argument localname1)
3899 (tramp-shell-quote-argument tmpfile))))
3900 (tramp-error-with-buffer
3901 nil v 'file-error
3902 "Copying directly failed, see buffer `%s' for details."
3903 (tramp-get-buffer v)))
2c418c5b 3904 ;; We must change the ownership as remote user.
917b89a6
MA
3905 ;; Since this does not work reliable, we also
3906 ;; give read permissions.
3907 (set-file-modes
3908 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3909 (tramp-set-file-uid-gid
3910 (concat prefix tmpfile)
3911 (tramp-get-local-uid 'integer)
3912 (tramp-get-local-gid 'integer)))
3913 (t2
3914 (if (eq op 'copy)
3915 (tramp-compat-copy-file
5ab38c3c 3916 localname1 tmpfile t
2c418c5b
MA
3917 keep-date preserve-uid-gid)
3918 (tramp-run-real-handler
3919 'rename-file
5ab38c3c 3920 (list localname1 tmpfile t)))
2c418c5b 3921 ;; We must change the ownership as local user.
917b89a6
MA
3922 ;; Since this does not work reliable, we also
3923 ;; give read permissions.
3924 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3925 (tramp-set-file-uid-gid
3926 tmpfile
3927 (tramp-get-remote-uid v 'integer)
3928 (tramp-get-remote-gid v 'integer))))
3929
3930 ;; Move the temporary file to its destination.
3931 (cond
3932 (t2
917b89a6
MA
3933 (or
3934 (zerop
3935 (tramp-send-command-and-check
3936 v (format
3937 "cp -f -p %s %s"
3938 (tramp-shell-quote-argument tmpfile)
3939 (tramp-shell-quote-argument localname2))))
3940 (tramp-error-with-buffer
3941 nil v 'file-error
3942 "Copying directly failed, see buffer `%s' for details."
3943 (tramp-get-buffer v))))
2c418c5b 3944 (t1
ce2cc728
MA
3945 (tramp-run-real-handler
3946 'rename-file
2c418c5b
MA
3947 (list tmpfile localname2 ok-if-already-exists)))))
3948
917b89a6
MA
3949 ;; Save exit.
3950 (condition-case nil
3951 (delete-file tmpfile)
3952 (error)))))))))
8d60099b
MA
3953
3954 ;; Set the time and mode. Mask possible errors.
8d60099b 3955 (condition-case nil
1f107aed 3956 (when keep-date
4f4126e6
MA
3957 (set-file-times newname file-times)
3958 (set-file-modes newname file-modes))
8d60099b
MA
3959 (error)))))
3960
5ec2cc41 3961(defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
7432277c 3962 "Invoke rcp program to copy.
905fb90e 3963The method used must be an out-of-band method."
38c65fca 3964 (let ((t1 (tramp-tramp-file-p filename))
5ec2cc41 3965 (t2 (tramp-tramp-file-p newname))
946a5aeb 3966 copy-program copy-args copy-env copy-keep-date port spec
00d6fd04
MA
3967 source target)
3968
3969 (with-parsed-tramp-file-name (if t1 filename newname) nil
905fb90e 3970 (if (and t1 t2)
00d6fd04 3971
905fb90e
MA
3972 ;; Both are Tramp files. We shall optimize it, when the
3973 ;; methods for filename and newname are the same.
9cf3544e
MA
3974 (let* ((dir-flag (file-directory-p filename))
3975 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3976 (if dir-flag
3977 (setq tmpfile
3978 (expand-file-name
3979 (file-name-nondirectory newname) tmpfile)))
905fb90e
MA
3980 (unwind-protect
3981 (progn
3982 (tramp-do-copy-or-rename-file-out-of-band
3983 op filename tmpfile keep-date)
3984 (tramp-do-copy-or-rename-file-out-of-band
3985 'rename tmpfile newname keep-date))
3986 ;; Save exit.
3987 (condition-case nil
9cf3544e 3988 (if dir-flag
20b8ac83 3989 (tramp-compat-delete-directory
9cf3544e
MA
3990 (expand-file-name ".." tmpfile) 'recursive)
3991 (delete-file tmpfile))
905fb90e
MA
3992 (error))))
3993
3994 ;; Expand hops. Might be necessary for gateway methods.
3995 (setq v (car (tramp-compute-multi-hops v)))
3996 (aset v 3 localname)
3997
3998 ;; Check which ones of source and target are Tramp files.
3999 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
263c02ef
MA
4000 target (funcall
4001 (if (and (file-directory-p filename)
4002 (string-equal
4003 (file-name-nondirectory filename)
4004 (file-name-nondirectory newname)))
4005 'file-name-directory
4006 'identity)
4007 (if t2 (tramp-make-copy-program-file-name v) newname)))
905fb90e
MA
4008
4009 ;; Check for port number. Until now, there's no need for handling
4010 ;; like method, user, host.
4011 (setq host (tramp-file-name-real-host v)
4012 port (tramp-file-name-port v)
4013 port (or (and port (number-to-string port)) ""))
4014
4015 ;; Compose copy command.
20b8ac83
MA
4016 (setq spec (format-spec-make
4017 ?h host ?u user ?p port
4018 ?t (tramp-get-connection-property
4019 (tramp-get-connection-process v) "temp-file" "")
4020 ?k (if keep-date " " ""))
905fb90e
MA
4021 copy-program (tramp-get-method-parameter
4022 method 'tramp-copy-program)
4023 copy-keep-date (tramp-get-method-parameter
4024 method 'tramp-copy-keep-date)
4025 copy-args
4026 (delq
4027 nil
4028 (mapcar
aa485f7c
MA
4029 (lambda (x)
4030 (setq
4031 x
4032 ;; " " is indication for keep-date argument.
4033 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
4034 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb
MA
4035 (tramp-get-method-parameter method 'tramp-copy-args)))
4036 copy-env
4037 (delq
4038 nil
4039 (mapcar
aa485f7c
MA
4040 (lambda (x)
4041 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4042 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb 4043 (tramp-get-method-parameter method 'tramp-copy-env))))
905fb90e
MA
4044
4045 ;; Check for program.
4046 (when (and (fboundp 'executable-find)
4047 (not (let ((default-directory
4048 (tramp-compat-temporary-file-directory)))
4049 (executable-find copy-program))))
4050 (tramp-error
4051 v 'file-error "Cannot find copy program: %s" copy-program))
00d6fd04 4052
4265deab
MA
4053 ;; Set variables for computing the prompt for reading
4054 ;; password.
4055 (setq tramp-current-method (tramp-file-name-method v)
4056 tramp-current-user (tramp-file-name-user v)
4057 tramp-current-host (tramp-file-name-host v))
4058
905fb90e
MA
4059 (unwind-protect
4060 (with-temp-buffer
4061 ;; The default directory must be remote.
4062 (let ((default-directory
946a5aeb
MA
4063 (file-name-directory (if t1 filename newname)))
4064 (process-environment (copy-sequence process-environment)))
905fb90e
MA
4065 ;; Set the transfer process properties.
4066 (tramp-set-connection-property
4067 v "process-name" (buffer-name (current-buffer)))
4068 (tramp-set-connection-property
4069 v "process-buffer" (current-buffer))
946a5aeb
MA
4070 (while copy-env
4071 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
4072 (setenv (pop copy-env) (pop copy-env)))
905fb90e
MA
4073
4074 ;; Use an asynchronous process. By this, password can
4075 ;; be handled. The default directory must be local, in
4076 ;; order to apply the correct `copy-program'. We don't
4077 ;; set a timeout, because the copying of large files can
4078 ;; last longer than 60 secs.
4079 (let ((p (let ((default-directory
4080 (tramp-compat-temporary-file-directory)))
4081 (apply 'start-process
4082 (tramp-get-connection-property
4083 v "process-name" nil)
4084 (tramp-get-connection-property
4085 v "process-buffer" nil)
4086 copy-program
4087 (append copy-args (list source target))))))
4088 (tramp-message
4089 v 6 "%s" (mapconcat 'identity (process-command p) " "))
4090 (tramp-set-process-query-on-exit-flag p nil)
4091 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
00d6fd04 4092
905fb90e
MA
4093 ;; Reset the transfer process properties.
4094 (tramp-set-connection-property v "process-name" nil)
4095 (tramp-set-connection-property v "process-buffer" nil))
00d6fd04 4096
905fb90e
MA
4097 ;; Handle KEEP-DATE argument.
4098 (when (and keep-date (not copy-keep-date))
4099 (set-file-times newname (nth 5 (file-attributes filename))))
01917a18 4100
905fb90e
MA
4101 ;; Set the mode.
4102 (unless (and keep-date copy-keep-date)
459a5f4b
MA
4103 (ignore-errors
4104 (set-file-modes newname (tramp-default-file-modes filename)))))
5ec2cc41 4105
905fb90e
MA
4106 ;; If the operation was `rename', delete the original file.
4107 (unless (eq op 'copy)
aac0b0f2
MA
4108 (if (file-regular-p filename)
4109 (delete-file filename)
20b8ac83 4110 (tramp-compat-delete-directory filename 'recursive))))))
7432277c 4111
fb7933a3 4112(defun tramp-handle-make-directory (dir &optional parents)
00d6fd04 4113 "Like `make-directory' for Tramp files."
ac474af1 4114 (setq dir (expand-file-name dir))
c62c9d08 4115 (with-parsed-tramp-file-name dir nil
c15cdf02 4116 (tramp-flush-directory-property v (file-name-directory localname))
b1d06e75
KG
4117 (save-excursion
4118 (tramp-barf-unless-okay
00d6fd04 4119 v
9c13938d 4120 (format "%s %s"
b1d06e75 4121 (if parents "mkdir -p" "mkdir")
7432277c 4122 (tramp-shell-quote-argument localname))
b1d06e75 4123 "Couldn't make directory %s" dir))))
fb7933a3 4124
c15cdf02 4125(defun tramp-handle-delete-directory (directory &optional recursive)
00d6fd04 4126 "Like `delete-directory' for Tramp files."
ac474af1 4127 (setq directory (expand-file-name directory))
c62c9d08 4128 (with-parsed-tramp-file-name directory nil
aac0b0f2 4129 (tramp-flush-file-property v (file-name-directory localname))
00d6fd04
MA
4130 (tramp-flush-directory-property v localname)
4131 (unless (zerop (tramp-send-command-and-check
4132 v
c15cdf02
MA
4133 (format
4134 "%s %s"
4135 (if recursive "rm -rf" "rmdir")
4136 (tramp-shell-quote-argument localname))))
00d6fd04 4137 (tramp-error v 'file-error "Couldn't delete %s" directory))))
fb7933a3 4138
20b8ac83 4139(defun tramp-handle-delete-file (filename &optional trash)
00d6fd04 4140 "Like `delete-file' for Tramp files."
ac474af1 4141 (setq filename (expand-file-name filename))
c62c9d08 4142 (with-parsed-tramp-file-name filename nil
aac0b0f2 4143 (tramp-flush-file-property v (file-name-directory localname))
00d6fd04 4144 (tramp-flush-file-property v localname)
20b8ac83
MA
4145 (unless
4146 (zerop
4147 (tramp-send-command-and-check
4148 v (format "%s %s"
4149 (or (and trash (tramp-get-remote-trash v)) "rm -f")
4150 (tramp-shell-quote-argument localname))))
00d6fd04 4151 (tramp-error v 'file-error "Couldn't delete %s" filename))))
fb7933a3
KG
4152
4153;; Dired.
4154
4155;; CCC: This does not seem to be enough. Something dies when
a4aeb9a4 4156;; we try and delete two directories under Tramp :/
fb7933a3
KG
4157(defun tramp-handle-dired-recursive-delete-directory (filename)
4158 "Recursively delete the directory given.
00d6fd04 4159This is like `dired-recursive-delete-directory' for Tramp files."
c62c9d08 4160 (with-parsed-tramp-file-name filename nil
00d6fd04 4161 ;; Run a shell command 'rm -r <localname>'
260821d3 4162 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
00d6fd04
MA
4163 (unless (file-exists-p filename)
4164 (tramp-error v 'file-error "No such directory: %s" filename))
fb7933a3 4165 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
00d6fd04
MA
4166 (tramp-send-command
4167 v
9c13938d 4168 (format "rm -rf %s" (tramp-shell-quote-argument localname))
00d6fd04
MA
4169 ;; Don't read the output, do it explicitely.
4170 nil t)
fb7933a3
KG
4171 ;; Wait for the remote system to return to us...
4172 ;; This might take a while, allow it plenty of time.
00d6fd04 4173 (tramp-wait-for-output (tramp-get-connection-process v) 120)
fb7933a3 4174 ;; Make sure that it worked...
aac0b0f2 4175 (tramp-flush-file-property v (file-name-directory localname))
c15cdf02 4176 (tramp-flush-directory-property v localname)
07dfe738 4177 (and (file-exists-p filename)
00d6fd04
MA
4178 (tramp-error
4179 v 'file-error "Failed to recursively delete %s" filename))))
bf247b6e 4180
5ec2cc41 4181(defun tramp-handle-dired-compress-file (file &rest ok-flag)
00d6fd04 4182 "Like `dired-compress-file' for Tramp files."
5ec2cc41
KG
4183 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4184 ;; Code stolen mainly from dired-aux.el.
4185 (with-parsed-tramp-file-name file nil
00d6fd04 4186 (tramp-flush-file-property v localname)
5ec2cc41
KG
4187 (save-excursion
4188 (let ((suffixes
4189 (if (not (featurep 'xemacs))
4190 ;; Emacs case
4191 (symbol-value 'dired-compress-file-suffixes)
4192 ;; XEmacs has `dired-compression-method-alist', which is
4193 ;; transformed into `dired-compress-file-suffixes' structure.
4194 (mapcar
aa485f7c
MA
4195 (lambda (x)
4196 (list (concat (regexp-quote (nth 1 x)) "\\'")
4197 nil
4198 (mapconcat 'identity (nth 3 x) " ")))
5ec2cc41
KG
4199 (symbol-value 'dired-compression-method-alist))))
4200 suffix)
4201 ;; See if any suffix rule matches this file name.
4202 (while suffixes
4203 (let (case-fold-search)
4204 (if (string-match (car (car suffixes)) localname)
4205 (setq suffix (car suffixes) suffixes nil))
4206 (setq suffixes (cdr suffixes))))
4207
4208 (cond ((file-symlink-p file)
4209 nil)
4210 ((and suffix (nth 2 suffix))
4211 ;; We found an uncompression rule.
20b8ac83
MA
4212 (with-progress-reporter v 0 (format "Uncompressing %s" file)
4213 (when (zerop
4214 (tramp-send-command-and-check
4215 v (concat (nth 2 suffix) " "
4216 (tramp-shell-quote-argument localname))))
4217 ;; `dired-remove-file' is not defined in XEmacs.
4218 (tramp-compat-funcall 'dired-remove-file file)
4219 (string-match (car suffix) file)
4220 (concat (substring file 0 (match-beginning 0))))))
5ec2cc41
KG
4221 (t
4222 ;; We don't recognize the file as compressed, so compress it.
4223 ;; Try gzip.
20b8ac83
MA
4224 (with-progress-reporter v 0 (format "Compressing %s" file)
4225 (when (zerop
4226 (tramp-send-command-and-check
4227 v (concat "gzip -f "
4228 (tramp-shell-quote-argument localname))))
4229 ;; `dired-remove-file' is not defined in XEmacs.
4230 (tramp-compat-funcall 'dired-remove-file file)
4231 (cond ((file-exists-p (concat file ".gz"))
4232 (concat file ".gz"))
4233 ((file-exists-p (concat file ".z"))
4234 (concat file ".z"))
4235 (t nil))))))))))
fb7933a3 4236
d5b3979c 4237(defun tramp-handle-dired-uncache (dir &optional dir-p)
70c11b0b 4238 "Like `dired-uncache' for Tramp files."
d5b3979c
MA
4239 ;; DIR-P is valid for XEmacs only.
4240 (with-parsed-tramp-file-name
4241 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
20b8ac83 4242 (tramp-flush-directory-property v localname)))
70c11b0b 4243
fb7933a3
KG
4244;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4245;; not sure at all that this is the right way to do it, but let's hope
4246;; it works for now, and wait for a guru to point out the Right Way to
4247;; achieve this.
4248;;(eval-when-compile
4249;; (unless (fboundp 'dired-insert-set-properties)
4250;; (fset 'dired-insert-set-properties 'ignore)))
4251;; Gerd suggests this:
4252(eval-when-compile (require 'dired))
4253;; Note that dired is required at run-time, too, when it is needed.
4254;; It is only needed on XEmacs for the function
4255;; `dired-insert-set-properties'.
4256
4257(defun tramp-handle-insert-directory
4258 (filename switches &optional wildcard full-directory-p)
00d6fd04
MA
4259 "Like `insert-directory' for Tramp files."
4260 (setq filename (expand-file-name filename))
4261 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4262 (if (and (featurep 'ls-lisp)
4263 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4264 (tramp-run-real-handler
4265 'insert-directory (list filename switches wildcard full-directory-p))
0c0b61f1
MA
4266 (when (stringp switches)
4267 (setq switches (split-string switches)))
4268 (when (and (member "--dired" switches)
8e754ea2 4269 (not (tramp-get-ls-command-with-dired v)))
0c0b61f1 4270 (setq switches (delete "--dired" switches)))
c82c5727 4271 (when wildcard
87bdd2c7
MA
4272 (setq wildcard (tramp-run-real-handler
4273 'file-name-nondirectory (list localname)))
4274 (setq localname (tramp-run-real-handler
4275 'file-name-directory (list localname))))
c82c5727 4276 (unless full-directory-p
0c0b61f1
MA
4277 (setq switches (add-to-list 'switches "-d" 'append)))
4278 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
c82c5727 4279 (when wildcard
0c0b61f1
MA
4280 (setq switches (concat switches " " wildcard)))
4281 (tramp-message
4282 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4283 switches filename (if wildcard "yes" "no")
4284 (if full-directory-p "yes" "no"))
00d6fd04
MA
4285 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4286 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4287 (if full-directory-p
4288 (tramp-send-command
4289 v
fe5facd3 4290 (format "%s %s %s 2>/dev/null"
00d6fd04
MA
4291 (tramp-get-ls-command v)
4292 switches
4293 (if wildcard
4294 localname
4295 (tramp-shell-quote-argument (concat localname ".")))))
4296 (tramp-barf-unless-okay
4297 v
4298 (format "cd %s" (tramp-shell-quote-argument
87bdd2c7
MA
4299 (tramp-run-real-handler
4300 'file-name-directory (list localname))))
00d6fd04 4301 "Couldn't `cd %s'"
87bdd2c7
MA
4302 (tramp-shell-quote-argument
4303 (tramp-run-real-handler 'file-name-directory (list localname))))
00d6fd04
MA
4304 (tramp-send-command
4305 v
4306 (format "%s %s %s"
4307 (tramp-get-ls-command v)
4308 switches
4309 (if (or wildcard
87bdd2c7
MA
4310 (zerop (length
4311 (tramp-run-real-handler
4312 'file-name-nondirectory (list localname)))))
00d6fd04
MA
4313 ""
4314 (tramp-shell-quote-argument
87bdd2c7
MA
4315 (tramp-run-real-handler
4316 'file-name-nondirectory (list localname)))))))
8e754ea2
MA
4317 (let ((beg (point)))
4318 ;; We cannot use `insert-buffer-substring' because the Tramp
4319 ;; buffer changes its contents before insertion due to calling
4320 ;; `expand-file' and alike.
4321 (insert
4322 (with-current-buffer (tramp-get-buffer v)
4323 (buffer-string)))
4324
4325 ;; Check for "--dired" output.
8e754ea2 4326 (forward-line -2)
7f4d4a97
MA
4327 (when (looking-at "//SUBDIRED//")
4328 (forward-line -1))
20b8ac83
MA
4329 (when (looking-at "//DIRED//\\s-+")
4330 (let ((databeg (match-end 0))
4331 (end (tramp-compat-line-end-position)))
8e754ea2 4332 ;; Now read the numeric positions of file names.
20b8ac83 4333 (goto-char databeg)
8e754ea2
MA
4334 (while (< (point) end)
4335 (let ((start (+ beg (read (current-buffer))))
4336 (end (+ beg (read (current-buffer)))))
7f49fe46 4337 (if (memq (char-after end) '(?\n ?\ ))
8e754ea2 4338 ;; End is followed by \n or by " -> ".
fe5facd3
MA
4339 (put-text-property start end 'dired-filename t))))))
4340 ;; Remove trailing lines.
4341 (goto-char (tramp-compat-line-beginning-position))
4342 (while (looking-at "//")
4343 (forward-line 1)
4344 (delete-region (match-beginning 0) (point)))
0c0b61f1
MA
4345
4346 ;; The inserted file could be from somewhere else.
4347 (when (and (not wildcard) (not full-directory-p))
4348 (goto-char (point-max))
e5c70c41
MA
4349 (when (file-symlink-p filename)
4350 (goto-char (search-backward "->" beg 'noerror)))
0c0b61f1
MA
4351 (search-backward
4352 (if (zerop (length (file-name-nondirectory filename)))
4353 "."
4354 (file-name-nondirectory filename))
4355 beg 'noerror)
4356 (replace-match (file-relative-name filename) t))
4357
fe5facd3 4358 (goto-char (point-max))))))
fb7933a3 4359
fb7933a3 4360(defun tramp-handle-unhandled-file-name-directory (filename)
00d6fd04 4361 "Like `unhandled-file-name-directory' for Tramp files."
8a798e41
MA
4362 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4363 ;; for backward compatibility.
ce3f516f 4364 (expand-file-name "~/"))
fb7933a3
KG
4365
4366;; Canonicalization of file names.
4367
fb7933a3 4368(defun tramp-handle-expand-file-name (name &optional dir)
00d6fd04 4369 "Like `expand-file-name' for Tramp files.
7432277c
KG
4370If the localname part of the given filename starts with \"/../\" then
4371the result will be a local, non-Tramp, filename."
fb7933a3
KG
4372 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4373 (setq dir (or dir default-directory "/"))
4374 ;; Unless NAME is absolute, concat DIR and NAME.
4375 (unless (file-name-absolute-p name)
4376 (setq name (concat (file-name-as-directory dir) name)))
00d6fd04 4377 ;; If NAME is not a Tramp file, run the real handler.
20b8ac83 4378 (if (not (tramp-connectable-p name))
00d6fd04 4379 (tramp-run-real-handler 'expand-file-name (list name nil))
fb7933a3 4380 ;; Dissect NAME.
c62c9d08 4381 (with-parsed-tramp-file-name name nil
87bdd2c7 4382 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
7432277c 4383 (setq localname (concat "~/" localname)))
00d6fd04
MA
4384 ;; Tilde expansion if necessary. This needs a shell which
4385 ;; groks tilde expansion! The function `tramp-find-shell' is
4386 ;; supposed to find such a shell on the remote host. Please
4387 ;; tell me about it when this doesn't work on your system.
4388 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4389 (let ((uname (match-string 1 localname))
4390 (fname (match-string 2 localname)))
4391 ;; We cannot simply apply "~/", because under sudo "~/" is
4392 ;; expanded to the local user home directory but to the
4393 ;; root home directory. On the other hand, using always
4394 ;; the default user name for tilde expansion is not
4395 ;; appropriate either, because ssh and companions might
4396 ;; use a user name from the config file.
4397 (when (and (string-equal uname "~")
4398 (string-match "\\`su\\(do\\)?\\'" method))
4399 (setq uname (concat uname user)))
4400 (setq uname
b593f105
MA
4401 (with-connection-property v uname
4402 (tramp-send-command
4403 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4404 (with-current-buffer (tramp-get-buffer v)
4405 (goto-char (point-min))
4406 (buffer-substring
4407 (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
4408 (setq localname (concat uname fname))))
4409 ;; There might be a double slash, for example when "~/"
cb85dcd0 4410 ;; expands to "/". Remove this.
00d6fd04
MA
4411 (while (string-match "//" localname)
4412 (setq localname (replace-match "/" t t localname)))
4413 ;; No tilde characters in file name, do normal
a17632c1
MA
4414 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4415 ;; `directory-sep-char' here for XEmacs on Windows, which would
4416 ;; otherwise use backslash. `default-directory' is bound,
4417 ;; because on Windows there would be problems with UNC shares or
4418 ;; Cygwin mounts.
aff67808
MA
4419 (let ((directory-sep-char ?/)
4420 (default-directory (tramp-compat-temporary-file-directory)))
4421 (tramp-make-tramp-file-name
4422 method user host
4423 (tramp-drop-volume-letter
87bdd2c7
MA
4424 (tramp-run-real-handler
4425 'expand-file-name (list localname))))))))
00d6fd04 4426
c23c3394
MA
4427(defun tramp-replace-environment-variables (filename)
4428 "Replace environment variables in FILENAME.
4429Return the string with the replaced variables."
2e271195 4430 (save-match-data
ec5145d6 4431 (let ((idx (string-match "$\\(\\w+\\)" filename)))
2e271195 4432 ;; `$' is coded as `$$'.
ec5145d6
MA
4433 (when (and idx
4434 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4435 (getenv (match-string 1 filename)))
2e271195
MA
4436 (setq filename
4437 (replace-match
4438 (substitute-in-file-name (match-string 0 filename))
4439 t nil filename)))
4440 filename)))
c23c3394 4441
00d6fd04
MA
4442(defun tramp-handle-substitute-in-file-name (filename)
4443 "Like `substitute-in-file-name' for Tramp files.
4444\"//\" and \"/~\" substitute only in the local filename part.
4445If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4446beginning of local filename are not substituted."
c23c3394
MA
4447 ;; First, we must replace environment variables.
4448 (setq filename (tramp-replace-environment-variables filename))
00d6fd04
MA
4449 (with-parsed-tramp-file-name filename nil
4450 (if (equal tramp-syntax 'url)
4451 ;; We need to check localname only. The other parts cannot contain
4452 ;; "//" or "/~".
4453 (if (and (> (length localname) 1)
4454 (or (string-match "//" localname)
4455 (string-match "/~" localname 1)))
4456 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4457 (tramp-make-tramp-file-name
4458 (when method (substitute-in-file-name method))
4459 (when user (substitute-in-file-name user))
4460 (when host (substitute-in-file-name host))
87bdd2c7
MA
4461 (when localname
4462 (tramp-run-real-handler
4463 'substitute-in-file-name (list localname)))))
00d6fd04
MA
4464 ;; Ignore in LOCALNAME everything before "//" or "/~".
4465 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4466 (setq filename
b08104a0
MA
4467 (concat (file-remote-p filename)
4468 (replace-match "\\1" nil nil localname)))
00d6fd04
MA
4469 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4470 (when (string-match "~$" filename)
4471 (setq filename (concat filename "/"))))
4472 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4473
4474;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4475;; which calls corresponding functions (see minibuf.el).
4476(when (fboundp 'minibuffer-electric-separator)
9e6ab520 4477 (mapc
aa485f7c
MA
4478 (lambda (x)
4479 (eval
4480 `(defadvice ,x
4481 (around ,(intern (format "tramp-advice-%s" x)) activate)
4482 "Invoke `substitute-in-file-name' for Tramp files."
4483 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4484 (tramp-tramp-file-p (buffer-substring)))
4485 ;; We don't need to handle `last-input-event', because
4486 ;; due to the key map we know it must be ?/ or ?~.
4487 (let ((s (concat (buffer-substring (point-min) (point))
4488 (string last-command-char))))
4489 (delete-region (point-min) (point))
4490 (insert (substitute-in-file-name s))
4491 (setq ad-return-value last-command-char))
d7ec1df7
MA
4492 ad-do-it)))
4493 (eval
4494 `(add-hook
4495 'tramp-unload-hook
4496 (lambda ()
4497 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4498 (ad-activate ',x)))))
00d6fd04
MA
4499
4500 '(minibuffer-electric-separator
4501 minibuffer-electric-tilde)))
4502
4503
0664ff72 4504;;; Remote commands:
fb7933a3 4505
00d6fd04
MA
4506(defun tramp-handle-executable-find (command)
4507 "Like `executable-find' for Tramp files."
4508 (with-parsed-tramp-file-name default-directory nil
f84638eb 4509 (tramp-find-executable v command (tramp-get-remote-path v) t)))
00d6fd04 4510
20b8ac83
MA
4511(defun tramp-process-sentinel (proc event)
4512 "Flush file caches."
4513 (unless (memq (process-status proc) '(run open))
4514 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4515 (when vec
4516 (tramp-message vec 5 "Sentinel called: `%s' `%s'" proc event)
4517 (tramp-flush-directory-property vec "")))))
4518
00d6fd04
MA
4519;; We use BUFFER also as connection buffer during setup. Because of
4520;; this, its original contents must be saved, and restored once
4521;; connection has been setup.
4522(defun tramp-handle-start-file-process (name buffer program &rest args)
4523 "Like `start-file-process' for Tramp files."
4524 (with-parsed-tramp-file-name default-directory nil
4525 (unwind-protect
20b8ac83
MA
4526 ;; When PROGRAM is nil, we just provide a tty.
4527 (let ((command
4528 (when (stringp program)
4529 (format "cd %s; exec %s"
4530 (tramp-shell-quote-argument localname)
4531 (mapconcat 'tramp-shell-quote-argument
4532 (cons program args) " "))))
4533 (tramp-process-connection-type
4534 (or (null program) tramp-process-connection-type))
263c02ef 4535 (name1 name)
38d63e6a 4536 (i 0))
2296b54d 4537 (unless buffer
6ce63faf 4538 ;; BUFFER can be nil. We use a temporary buffer.
2296b54d 4539 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
38d63e6a
MA
4540 (while (get-process name1)
4541 ;; NAME must be unique as process name.
4542 (setq i (1+ i)
4543 name1 (format "%s<%d>" name i)))
4544 (setq name name1)
00d6fd04
MA
4545 ;; Set the new process properties.
4546 (tramp-set-connection-property v "process-name" name)
2296b54d 4547 (tramp-set-connection-property v "process-buffer" buffer)
00d6fd04 4548 ;; Activate narrowing in order to save BUFFER contents.
11c71217
MA
4549 ;; Clear also the modification time; otherwise we might be
4550 ;; interrupted by `verify-visited-file-modtime'.
00d6fd04 4551 (with-current-buffer (tramp-get-connection-buffer v)
11c71217 4552 (clear-visited-file-modtime)
00d6fd04 4553 (narrow-to-region (point-max) (point-max)))
20b8ac83
MA
4554 (if command
4555 ;; Send the command.
4556 (tramp-send-command v command nil t) ; nooutput
4557 ;; Check, whether a pty is associated.
4558 (tramp-maybe-open-connection v)
4559 (unless (process-get (tramp-get-connection-process v) 'remote-tty)
4560 (tramp-error
4561 v 'file-error "pty association is not supported for `%s'" name)))
4562 (let ((p (tramp-get-connection-process v)))
4563 ;; Set sentinel and query flag for this process.
4564 (tramp-set-connection-property p "vector" v)
4565 (set-process-sentinel p 'tramp-process-sentinel)
4566 (tramp-set-process-query-on-exit-flag p t)
4567 ;; Return process.
4568 p))
00d6fd04 4569 ;; Save exit.
ce3f516f 4570 (with-current-buffer (tramp-get-connection-buffer v)
6ce63faf
MA
4571 (if (string-match tramp-temp-buffer-name (buffer-name))
4572 (progn
4573 (set-process-buffer (tramp-get-connection-process v) nil)
4574 (kill-buffer (current-buffer)))
4575 (widen)
4576 (goto-char (point-max))))
00d6fd04
MA
4577 (tramp-set-connection-property v "process-name" nil)
4578 (tramp-set-connection-property v "process-buffer" nil))))
4579
4580(defun tramp-handle-process-file
4581 (program &optional infile destination display &rest args)
4582 "Like `process-file' for Tramp files."
4583 ;; The implementation is not complete yet.
4584 (when (and (numberp destination) (zerop destination))
4585 (error "Implementation does not handle immediate return"))
4586
4587 (with-parsed-tramp-file-name default-directory nil
a6e96327 4588 (let (command input tmpinput stderr tmpstderr outbuf ret)
00d6fd04
MA
4589 ;; Compute command.
4590 (setq command (mapconcat 'tramp-shell-quote-argument
4591 (cons program args) " "))
4592 ;; Determine input.
4593 (if (null infile)
4594 (setq input "/dev/null")
4595 (setq infile (expand-file-name infile))
4596 (if (tramp-equal-remote default-directory infile)
4597 ;; INFILE is on the same remote host.
4598 (setq input (with-parsed-tramp-file-name infile nil localname))
4599 ;; INFILE must be copied to remote host.
a6e96327
MA
4600 (setq input (tramp-make-tramp-temp-file v)
4601 tmpinput (tramp-make-tramp-file-name method user host input))
4602 (copy-file infile tmpinput t)))
00d6fd04
MA
4603 (when input (setq command (format "%s <%s" command input)))
4604
4605 ;; Determine output.
4606 (cond
bede3e9f 4607 ;; Just a buffer.
00d6fd04
MA
4608 ((bufferp destination)
4609 (setq outbuf destination))
bede3e9f 4610 ;; A buffer name.
00d6fd04
MA
4611 ((stringp destination)
4612 (setq outbuf (get-buffer-create destination)))
4613 ;; (REAL-DESTINATION ERROR-DESTINATION)
4614 ((consp destination)
bede3e9f 4615 ;; output.
00d6fd04
MA
4616 (cond
4617 ((bufferp (car destination))
4618 (setq outbuf (car destination)))
4619 ((stringp (car destination))
0664ff72
MA
4620 (setq outbuf (get-buffer-create (car destination))))
4621 ((car destination)
4622 (setq outbuf (current-buffer))))
bede3e9f 4623 ;; stderr.
00d6fd04
MA
4624 (cond
4625 ((stringp (cadr destination))
4626 (setcar (cdr destination) (expand-file-name (cadr destination)))
4627 (if (tramp-equal-remote default-directory (cadr destination))
4628 ;; stderr is on the same remote host.
4629 (setq stderr (with-parsed-tramp-file-name
4630 (cadr destination) nil localname))
4631 ;; stderr must be copied to remote host. The temporary
4632 ;; file must be deleted after execution.
a6e96327
MA
4633 (setq stderr (tramp-make-tramp-temp-file v)
4634 tmpstderr (tramp-make-tramp-file-name
4635 method user host stderr))))
bede3e9f 4636 ;; stderr to be discarded.
00d6fd04
MA
4637 ((null (cadr destination))
4638 (setq stderr "/dev/null"))))
4639 ;; 't
4640 (destination
4641 (setq outbuf (current-buffer))))
4642 (when stderr (setq command (format "%s 2>%s" command stderr)))
4643
20b8ac83
MA
4644 ;; Send the command. It might not return in time, so we protect
4645 ;; it. Call it in a subshell, in order to preserve working
4646 ;; directory.
00d6fd04
MA
4647 (condition-case nil
4648 (unwind-protect
293c24f9
MA
4649 (setq ret
4650 (tramp-send-command-and-check
4651 v (format "\\cd %s; %s"
4652 (tramp-shell-quote-argument localname)
b593f105 4653 command)
20b8ac83 4654 t t))
00d6fd04
MA
4655 ;; We should show the output anyway.
4656 (when outbuf
293c24f9
MA
4657 (with-current-buffer outbuf
4658 (insert
4659 (with-current-buffer (tramp-get-connection-buffer v)
4660 (buffer-string))))
00d6fd04 4661 (when display (display-buffer outbuf))))
260821d3
MA
4662 ;; When the user did interrupt, we should do it also. We use
4663 ;; return code -1 as marker.
4664 (quit
4665 (kill-buffer (tramp-get-connection-buffer v))
4666 (setq ret -1))
4667 ;; Handle errors.
00d6fd04
MA
4668 (error
4669 (kill-buffer (tramp-get-connection-buffer v))
4670 (setq ret 1)))
a6e96327 4671
a6e96327
MA
4672 ;; Provide error file.
4673 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
263c02ef 4674
260821d3
MA
4675 ;; Cleanup. We remove all file cache values for the connection,
4676 ;; because the remote process could have changed them.
a6e96327 4677 (when tmpinput (delete-file tmpinput))
946a5aeb
MA
4678
4679 ;; `process-file-side-effects' has been introduced with GNU
4680 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4681 ;; by `program'. If it doesn't exist, we assume its default
4682 ;; value 't'.
4683 (unless (and (boundp 'process-file-side-effects)
4684 (not (symbol-value 'process-file-side-effects)))
4685 (tramp-flush-directory-property v ""))
4686
00d6fd04 4687 ;; Return exit status.
260821d3
MA
4688 (if (equal ret -1)
4689 (keyboard-quit)
4690 ret))))
00d6fd04 4691
a4aeb9a4
MA
4692(defun tramp-local-call-process
4693 (program &optional infile destination display &rest args)
4694 "Calls `call-process' on the local host.
4695This is needed because for some Emacs flavors Tramp has
4696defadviced `call-process' to behave like `process-file'. The
4697Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4698 (let ((default-directory
4699 (if (file-remote-p default-directory)
4700 (tramp-compat-temporary-file-directory)
4701 default-directory)))
4702 (if (executable-find program)
4703 (apply 'call-process program infile destination display args)
4704 1)))
4705
00d6fd04
MA
4706(defun tramp-handle-call-process-region
4707 (start end program &optional delete buffer display &rest args)
4708 "Like `call-process-region' for Tramp files."
258800f8 4709 (let ((tmpfile (tramp-compat-make-temp-file "")))
00d6fd04
MA
4710 (write-region start end tmpfile)
4711 (when delete (delete-region start end))
4712 (unwind-protect
4713 (apply 'call-process program tmpfile buffer display args)
4714 (delete-file tmpfile))))
4715
4716(defun tramp-handle-shell-command
4717 (command &optional output-buffer error-buffer)
4718 "Like `shell-command' for Tramp files."
ce3f516f 4719 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
b8bfcf96
MA
4720 ;; We cannot use `shell-file-name' and `shell-command-switch',
4721 ;; they are variables of the local host.
20b8ac83
MA
4722 (args (list
4723 (tramp-get-method-parameter
4724 (tramp-file-name-method
4725 (tramp-dissect-file-name default-directory))
4726 'tramp-remote-sh)
4727 "-c" (substring command 0 asynchronous)))
5d2ebd96 4728 current-buffer-p
ce3f516f 4729 (output-buffer
27e813fe
MA
4730 (cond
4731 ((bufferp output-buffer) output-buffer)
4732 ((stringp output-buffer) (get-buffer-create output-buffer))
5d2ebd96
AS
4733 (output-buffer
4734 (setq current-buffer-p t)
4735 (current-buffer))
42bc9b6d 4736 (t (get-buffer-create
27e813fe
MA
4737 (if asynchronous
4738 "*Async Shell Command*"
4739 "*Shell Command Output*")))))
4740 (error-buffer
4741 (cond
4742 ((bufferp error-buffer) error-buffer)
4743 ((stringp error-buffer) (get-buffer-create error-buffer))))
ce3f516f 4744 (buffer
27e813fe 4745 (if (and (not asynchronous) error-buffer)
ce3f516f
MA
4746 (with-parsed-tramp-file-name default-directory nil
4747 (list output-buffer (tramp-make-tramp-temp-file v)))
42bc9b6d 4748 output-buffer))
cfb5c0db 4749 (p (get-buffer-process output-buffer)))
42bc9b6d
MA
4750
4751 ;; Check whether there is another process running. Tramp does not
4752 ;; support 2 (asynchronous) processes in parallel.
cfb5c0db 4753 (when p
42bc9b6d 4754 (if (yes-or-no-p "A command is running. Kill it? ")
699a11fb
GM
4755 (condition-case nil
4756 (kill-process p)
4757 (error nil))
42bc9b6d
MA
4758 (error "Shell command in progress")))
4759
f34db316
AS
4760 (if current-buffer-p
4761 (progn
4762 (barf-if-buffer-read-only)
4763 (push-mark nil t))
5d2ebd96
AS
4764 (with-current-buffer output-buffer
4765 (setq buffer-read-only nil)
4766 (erase-buffer)))
42bc9b6d 4767
5d2ebd96 4768 (if (and (not current-buffer-p) (integerp asynchronous))
42bc9b6d
MA
4769 (prog1
4770 ;; Run the process.
3412f35d 4771 (apply 'start-file-process "*Async Shell*" buffer args)
42bc9b6d 4772 ;; Display output.
cfb5c0db
MA
4773 (pop-to-buffer output-buffer)
4774 (setq mode-line-process '(":%s"))
4775 (require 'shell) (shell-mode))
42bc9b6d
MA
4776
4777 (prog1
4778 ;; Run the process.
4779 (apply 'process-file (car args) nil buffer nil (cdr args))
4780 ;; Insert error messages if they were separated.
4781 (when (listp buffer)
4782 (with-current-buffer error-buffer
4783 (insert-file-contents (cadr buffer)))
4784 (delete-file (cadr buffer)))
f34db316
AS
4785 (if current-buffer-p
4786 ;; This is like exchange-point-and-mark, but doesn't
4787 ;; activate the mark. It is cleaner to avoid activation,
4788 ;; even though the command loop would deactivate the mark
4789 ;; because we inserted text.
4790 (goto-char (prog1 (mark t)
4791 (set-marker (mark-marker) (point)
4792 (current-buffer))))
4793 ;; There's some output, display it.
4794 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4795 (if (functionp 'display-message-or-buffer)
20b8ac83 4796 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
f34db316 4797 (pop-to-buffer output-buffer))))))))
00d6fd04
MA
4798
4799;; File Editing.
4800
4801(defvar tramp-handle-file-local-copy-hook nil
4802 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4803
fb7933a3 4804(defun tramp-handle-file-local-copy (filename)
00d6fd04 4805 "Like `file-local-copy' for Tramp files."
0f205eee 4806
c62c9d08 4807 (with-parsed-tramp-file-name filename nil
2988341a
MA
4808 (unless (file-exists-p filename)
4809 (tramp-error
4810 v 'file-error
4811 "Cannot make local copy of non-existing file `%s'" filename))
4812
20b8ac83
MA
4813 (let* ((size (nth 7 (file-attributes filename)))
4814 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
4815 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
4816 (tmpfile (tramp-compat-make-temp-file filename)))
5ec2cc41 4817
2988341a
MA
4818 (condition-case err
4819 (cond
4820 ;; `copy-file' handles direct copy and out-of-band methods.
4821 ((or (tramp-local-host-p v)
20b8ac83 4822 (tramp-method-out-of-band-p v size))
2988341a
MA
4823 (copy-file filename tmpfile t t))
4824
4825 ;; Use inline encoding for file transfer.
4826 (rem-enc
4827 (save-excursion
20b8ac83
MA
4828 (with-progress-reporter
4829 v 3 (format "Encoding remote file %s" filename)
4830 (tramp-barf-unless-okay
4831 v (format rem-enc (tramp-shell-quote-argument localname))
4832 "Encoding remote file failed"))
2988341a 4833
20b8ac83 4834 (if (functionp loc-dec)
2988341a
MA
4835 ;; If local decoding is a function, we call it. We
4836 ;; must disable multibyte, because
4837 ;; `uudecode-decode-region' doesn't handle it
4838 ;; correctly.
0f205eee
MA
4839 (with-temp-buffer
4840 (set-buffer-multibyte nil)
4841 (insert-buffer-substring (tramp-get-buffer v))
20b8ac83
MA
4842 (with-progress-reporter
4843 v 3 (format "Decoding remote file %s with function %s"
4844 filename loc-dec)
4845 (funcall loc-dec (point-min) (point-max))
4846 ;; Unset `file-name-handler-alist'. Otherwise,
4847 ;; epa-file gets confused.
4848 (let (file-name-handler-alist
4849 (coding-system-for-write 'binary))
4850 (write-region (point-min) (point-max) tmpfile))))
2988341a
MA
4851
4852 ;; If tramp-decoding-function is not defined for this
4853 ;; method, we invoke tramp-decoding-command instead.
4854 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
aa485f7c
MA
4855 ;; Unset `file-name-handler-alist'. Otherwise,
4856 ;; epa-file gets confused.
4857 (let (file-name-handler-alist
4858 (coding-system-for-write 'binary))
2988341a 4859 (write-region (point-min) (point-max) tmpfile2))
20b8ac83
MA
4860 (with-progress-reporter
4861 v 3 (format "Decoding remote file %s with command %s"
4862 filename loc-dec)
4863 (unwind-protect
4864 (tramp-call-local-coding-command
4865 loc-dec tmpfile2 tmpfile)
4866 (delete-file tmpfile2)))))
2988341a 4867
2988341a 4868 ;; Set proper permissions.
b86c1cd8 4869 (set-file-modes tmpfile (tramp-default-file-modes filename))
2988341a
MA
4870 ;; Set local user ownership.
4871 (tramp-set-file-uid-gid tmpfile)))
4872
4873 ;; Oops, I don't know what to do.
4874 (t (tramp-error
4875 v 'file-error "Wrong method specification for `%s'" method)))
4876
4877 ;; Error handling.
4878 ((error quit)
4879 (delete-file tmpfile)
4880 (signal (car err) (cdr err))))
0f205eee 4881
00d6fd04 4882 (run-hooks 'tramp-handle-file-local-copy-hook)
94be87e8 4883 tmpfile)))
fb7933a3 4884
bce04fee 4885(defun tramp-handle-file-remote-p (filename &optional identification connected)
00d6fd04 4886 "Like `file-remote-p' for Tramp files."
d5b3979c
MA
4887 (let ((tramp-verbose 3))
4888 (when (tramp-tramp-file-p filename)
4889 (let* ((v (tramp-dissect-file-name filename))
4890 (p (tramp-get-connection-process v))
4891 (c (and p (processp p) (memq (process-status p) '(run open)))))
4892 ;; We expand the file name only, if there is already a connection.
4893 (with-parsed-tramp-file-name
4894 (if c (expand-file-name filename) filename) nil
4895 (and (or (not connected) c)
4896 (cond
4897 ((eq identification 'method) method)
4898 ((eq identification 'user) user)
4899 ((eq identification 'host) host)
4900 ((eq identification 'localname) localname)
4901 (t (tramp-make-tramp-file-name method user host "")))))))))
fb7933a3 4902
eb562962
MA
4903(defun tramp-find-file-name-coding-system-alist (filename tmpname)
4904 "Like `find-operation-coding-system' for Tramp filenames.
4905Tramp's `insert-file-contents' and `write-region' work over
4906temporary file names. If `file-coding-system-alist' contains an
4907expression, which matches more than the file name suffix, the
4908coding system might not be determined. This function repairs it."
4909 (let (result)
4910 (dolist (elt file-coding-system-alist result)
4911 (when (and (consp elt) (string-match (car elt) filename))
4912 ;; We found a matching entry in `file-coding-system-alist'.
4913 ;; So we add a similar entry, but with the temporary file name
4914 ;; as regexp.
4915 (add-to-list
4916 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4917
fb7933a3
KG
4918(defun tramp-handle-insert-file-contents
4919 (filename &optional visit beg end replace)
00d6fd04 4920 "Like `insert-file-contents' for Tramp files."
fb7933a3
KG
4921 (barf-if-buffer-read-only)
4922 (setq filename (expand-file-name filename))
20b8ac83 4923 (let (result local-copy remote-copy)
2ac33804
MA
4924 (with-parsed-tramp-file-name filename nil
4925 (unwind-protect
70c11b0b
MA
4926 (if (not (file-exists-p filename))
4927 ;; We don't raise a Tramp error, because it might be
4928 ;; suppressed, like in `find-file-noselect-1'.
4929 (signal 'file-error
4930 (list "File not found on remote host" filename))
4931
4932 (if (and (tramp-local-host-p v)
4933 (let (file-name-handler-alist)
4934 (file-readable-p localname)))
4935 ;; Short track: if we are on the local host, we can
4936 ;; run directly.
4937 (setq result
4938 (tramp-run-real-handler
4939 'insert-file-contents
4940 (list localname visit beg end replace)))
4941
736ac90f
MA
4942 ;; When we shall insert only a part of the file, we copy
4943 ;; this part.
4944 (when (or beg end)
4945 (setq remote-copy (tramp-make-tramp-temp-file v))
4946 (tramp-send-command
4947 v
4948 (cond
4949 ((and beg end)
4950 (format "tail -c +%d %s | head -c +%d >%s"
4951 (1+ beg) (tramp-shell-quote-argument localname)
4952 (- end beg) remote-copy))
4953 (beg
4954 (format "tail -c +%d %s >%s"
4955 (1+ beg) (tramp-shell-quote-argument localname)
4956 remote-copy))
4957 (end
4958 (format "head -c +%d %s >%s"
4959 (1+ end) (tramp-shell-quote-argument localname)
4960 remote-copy)))))
4961
70c11b0b
MA
4962 ;; `insert-file-contents-literally' takes care to avoid
4963 ;; calling jka-compr. By let-binding
4964 ;; `inhibit-file-name-operation', we propagate that care
4965 ;; to the `file-local-copy' operation.
4966 (setq local-copy
4967 (let ((inhibit-file-name-operation
4968 (when (eq inhibit-file-name-operation
4969 'insert-file-contents)
4970 'file-local-copy)))
b88f2d0a
MA
4971 (cond
4972 ((stringp remote-copy)
4973 (file-local-copy
4974 (tramp-make-tramp-file-name
4975 method user host remote-copy)))
4976 ((stringp tramp-temp-buffer-file-name)
4977 (copy-file filename tramp-temp-buffer-file-name 'ok)
4978 tramp-temp-buffer-file-name)
4979 (t (file-local-copy filename)))))
4980
6e4f5731
MA
4981 ;; When the file is not readable for the owner, it
4982 ;; cannot be inserted, even it is redable for the group
4983 ;; or for everybody.
4984 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4985
b88f2d0a
MA
4986 (when (and (null remote-copy)
4987 (tramp-get-method-parameter
4988 method 'tramp-copy-keep-tmpfile))
4989 ;; We keep the local file for performance reasons,
4990 ;; useful for "rsync".
b88f2d0a
MA
4991 (setq tramp-temp-buffer-file-name local-copy)
4992 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4993
20b8ac83
MA
4994 (with-progress-reporter
4995 v 3 (format "Inserting local temp file `%s'" local-copy)
4996 ;; We must ensure that `file-coding-system-alist'
4997 ;; matches `local-copy'.
4998 (let ((file-coding-system-alist
4999 (tramp-find-file-name-coding-system-alist
5000 filename local-copy)))
5001 (setq result
5002 (insert-file-contents
5003 local-copy nil nil nil replace))))))
70c11b0b 5004
2ac33804
MA
5005 ;; Save exit.
5006 (progn
5007 (when visit
5008 (setq buffer-file-name filename)
5009 (setq buffer-read-only (not (file-writable-p filename)))
5010 (set-visited-file-modtime)
a057950d
MA
5011 (set-buffer-modified-p nil)
5012 ;; For root, preserve owner and group when editing files.
5013 (when (string-equal (file-remote-p filename 'user) "root")
6ce78fdc 5014 (set (make-local-variable 'backup-by-copying-when-mismatch) t)))
b88f2d0a
MA
5015 (when (and (stringp local-copy)
5016 (or remote-copy (null tramp-temp-buffer-file-name)))
2ac33804
MA
5017 (delete-file local-copy))
5018 (when (stringp remote-copy)
5019 (delete-file
5020 (tramp-make-tramp-file-name method user host remote-copy))))))
70c11b0b
MA
5021
5022 ;; Result.
5023 (list (expand-file-name filename)
5024 (cadr result))))
fb7933a3 5025
94be87e8
MA
5026;; This is needed for XEmacs only. Code stolen from files.el.
5027(defun tramp-handle-insert-file-contents-literally
5028 (filename &optional visit beg end replace)
5029 "Like `insert-file-contents-literally' for Tramp files."
5030 (let ((format-alist nil)
5031 (after-insert-file-functions nil)
5032 (coding-system-for-read 'no-conversion)
5033 (coding-system-for-write 'no-conversion)
5034 (find-buffer-file-type-function
5035 (if (fboundp 'find-buffer-file-type)
5036 (symbol-function 'find-buffer-file-type)
5037 nil))
5038 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
5039 (inhibit-file-name-operation 'insert-file-contents))
5040 (unwind-protect
5041 (progn
5042 (fset 'find-buffer-file-type (lambda (filename) t))
5043 (insert-file-contents filename visit beg end replace))
70c11b0b 5044 ;; Save exit.
94be87e8
MA
5045 (if find-buffer-file-type-function
5046 (fset 'find-buffer-file-type find-buffer-file-type-function)
5047 (fmakunbound 'find-buffer-file-type)))))
5048
38c65fca 5049(defun tramp-handle-find-backup-file-name (filename)
00d6fd04 5050 "Like `find-backup-file-name' for Tramp files."
07dfe738
KG
5051 (with-parsed-tramp-file-name filename nil
5052 ;; We set both variables. It doesn't matter whether it is
20b8ac83 5053 ;; Emacs or XEmacs.
07dfe738 5054 (let ((backup-directory-alist
20b8ac83 5055 ;; Emacs case.
07dfe738 5056 (when (boundp 'backup-directory-alist)
b86c1cd8 5057 (if (symbol-value 'tramp-backup-directory-alist)
07dfe738 5058 (mapcar
aa485f7c
MA
5059 (lambda (x)
5060 (cons
5061 (car x)
5062 (if (and (stringp (cdr x))
5063 (file-name-absolute-p (cdr x))
5064 (not (tramp-file-name-p (cdr x))))
5065 (tramp-make-tramp-file-name method user host (cdr x))
5066 (cdr x))))
07dfe738
KG
5067 (symbol-value 'tramp-backup-directory-alist))
5068 (symbol-value 'backup-directory-alist))))
5069
5070 (bkup-backup-directory-info
20b8ac83 5071 ;; XEmacs case.
07dfe738 5072 (when (boundp 'bkup-backup-directory-info)
b86c1cd8 5073 (if (symbol-value 'tramp-bkup-backup-directory-info)
07dfe738 5074 (mapcar
aa485f7c
MA
5075 (lambda (x)
5076 (nconc
5077 (list (car x))
5078 (list
5079 (if (and (stringp (car (cdr x)))
5080 (file-name-absolute-p (car (cdr x)))
5081 (not (tramp-file-name-p (car (cdr x)))))
5082 (tramp-make-tramp-file-name
5083 method user host (car (cdr x)))
5084 (car (cdr x))))
5085 (cdr (cdr x))))
07dfe738
KG
5086 (symbol-value 'tramp-bkup-backup-directory-info))
5087 (symbol-value 'bkup-backup-directory-info)))))
5088
5089 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
38c65fca 5090
c1105d05 5091(defun tramp-handle-make-auto-save-file-name ()
00d6fd04 5092 "Like `make-auto-save-file-name' for Tramp files.
c1105d05 5093Returns a file name in `tramp-auto-save-directory' for autosaving this file."
00d6fd04
MA
5094 (let ((tramp-auto-save-directory tramp-auto-save-directory)
5095 (buffer-file-name
5096 (tramp-subst-strs-in-string
5097 '(("_" . "|")
5098 ("/" . "_a")
5099 (":" . "_b")
5100 ("|" . "__")
5101 ("[" . "_l")
5102 ("]" . "_r"))
5103 (buffer-file-name))))
1a762140
MA
5104 ;; File name must be unique. This is ensured with Emacs 22 (see
5105 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
5106 ;; all other cases we must do it ourselves.
5107 (when (boundp 'auto-save-file-name-transforms)
9e6ab520 5108 (mapc
aa485f7c
MA
5109 (lambda (x)
5110 (when (and (string-match (car x) buffer-file-name)
5111 (not (car (cddr x))))
5112 (setq tramp-auto-save-directory
5113 (or tramp-auto-save-directory
5114 (tramp-compat-temporary-file-directory)))))
1a762140
MA
5115 (symbol-value 'auto-save-file-name-transforms)))
5116 ;; Create directory.
5117 (when tramp-auto-save-directory
00d6fd04
MA
5118 (setq buffer-file-name
5119 (expand-file-name buffer-file-name tramp-auto-save-directory))
1a762140
MA
5120 (unless (file-exists-p tramp-auto-save-directory)
5121 (make-directory tramp-auto-save-directory t)))
00d6fd04
MA
5122 ;; Run plain `make-auto-save-file-name'. There might be an advice when
5123 ;; it is not a magic file name operation (since Emacs 22).
5124 ;; We must deactivate it temporarily.
5125 (if (not (ad-is-active 'make-auto-save-file-name))
5126 (tramp-run-real-handler 'make-auto-save-file-name nil)
5127 ;; else
5128 (ad-deactivate 'make-auto-save-file-name)
5129 (prog1
5130 (tramp-run-real-handler 'make-auto-save-file-name nil)
5131 (ad-activate 'make-auto-save-file-name)))))
5132
5133(defvar tramp-handle-write-region-hook nil
5134 "Normal hook to be run at the end of `tramp-handle-write-region'.")
5135
b88f2d0a 5136;; CCC grok LOCKNAME
fb7933a3
KG
5137(defun tramp-handle-write-region
5138 (start end filename &optional append visit lockname confirm)
00d6fd04 5139 "Like `write-region' for Tramp files."
fb7933a3 5140 (setq filename (expand-file-name filename))
c62c9d08 5141 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
5142 ;; Following part commented out because we don't know what to do about
5143 ;; file locking, and it does not appear to be a problem to ignore it.
5144 ;; Ange-ftp ignores it, too.
5145 ;; (when (and lockname (stringp lockname))
5146 ;; (setq lockname (expand-file-name lockname)))
5147 ;; (unless (or (eq lockname nil)
5148 ;; (string= lockname filename))
5149 ;; (error
5150 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
8d60099b 5151
94be87e8 5152 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
00d6fd04
MA
5153 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
5154 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
5155 (tramp-error v 'file-error "File not overwritten")))
8d60099b 5156
a4aeb9a4 5157 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
9c13938d 5158 (tramp-get-remote-uid v 'integer)))
a4aeb9a4 5159 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
9c13938d
MA
5160 (tramp-get-remote-gid v 'integer))))
5161
5162 (if (and (tramp-local-host-p v)
93c3eb7c 5163 ;; `file-writable-p' calls `file-expand-file-name'. We
87bdd2c7
MA
5164 ;; cannot use `tramp-run-real-handler' therefore.
5165 (let (file-name-handler-alist)
82f3844e
MA
5166 (and
5167 (file-writable-p (file-name-directory localname))
5168 (or (file-directory-p localname)
5169 (file-writable-p localname)))))
9c13938d 5170 ;; Short track: if we are on the local host, we can run directly.
aac0b0f2
MA
5171 (tramp-run-real-handler
5172 'write-region
5173 (list start end localname append 'no-message lockname confirm))
9c13938d 5174
20b8ac83 5175 (let ((modes (save-excursion (tramp-default-file-modes filename)))
9c13938d 5176 ;; We use this to save the value of
20b8ac83
MA
5177 ;; `last-coding-system-used' after writing the tmp
5178 ;; file. At the end of the function, we set
9c13938d
MA
5179 ;; `last-coding-system-used' to this saved value. This
5180 ;; way, any intermediary coding systems used while
5181 ;; talking to the remote shell or suchlike won't hose
5182 ;; this variable. This approach was snarfed from
5183 ;; ange-ftp.el.
5184 coding-system-used
5185 ;; Write region into a tmp file. This isn't really
5186 ;; needed if we use an encoding function, but currently
5187 ;; we use it always because this makes the logic
293c24f9
MA
5188 ;; simpler.
5189 (tmpfile (or tramp-temp-buffer-file-name
5190 (tramp-compat-make-temp-file filename))))
5191
5192 ;; If `append' is non-nil, we copy the file locally, and let
5193 ;; the native `write-region' implementation do the job.
5194 (when append (copy-file filename tmpfile 'ok))
9c13938d
MA
5195
5196 ;; We say `no-message' here because we don't want the
5197 ;; visited file modtime data to be clobbered from the temp
5198 ;; file. We call `set-visited-file-modtime' ourselves later
eb562962
MA
5199 ;; on. We must ensure that `file-coding-system-alist'
5200 ;; matches `tmpfile'.
20b8ac83
MA
5201 (let (file-name-handler-alist
5202 (file-coding-system-alist
eb562962 5203 (tramp-find-file-name-coding-system-alist filename tmpfile)))
ce2cc728
MA
5204 (condition-case err
5205 (tramp-run-real-handler
5206 'write-region
5207 (list start end tmpfile append 'no-message lockname confirm))
2988341a 5208 ((error quit)
b88f2d0a 5209 (setq tramp-temp-buffer-file-name nil)
2988341a
MA
5210 (delete-file tmpfile)
5211 (signal (car err) (cdr err))))
ce2cc728 5212
eb562962
MA
5213 ;; Now, `last-coding-system-used' has the right value. Remember it.
5214 (when (boundp 'last-coding-system-used)
5215 (setq coding-system-used
5216 (symbol-value 'last-coding-system-used))))
5217
9c13938d
MA
5218 ;; The permissions of the temporary file should be set. If
5219 ;; filename does not exist (eq modes nil) it has been
5220 ;; renamed to the backup file. This case `save-buffer'
5221 ;; handles permissions.
459a5f4b
MA
5222 ;; Ensure, that it is still readable.
5223 (when modes
5224 (set-file-modes
5225 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
9c13938d
MA
5226
5227 ;; This is a bit lengthy due to the different methods
5228 ;; possible for file transfer. First, we check whether the
5229 ;; method uses an rcp program. If so, we call it.
5230 ;; Otherwise, both encoding and decoding command must be
5231 ;; specified. However, if the method _also_ specifies an
5232 ;; encoding function, then that is used for encoding the
5233 ;; contents of the tmp file.
20b8ac83
MA
5234 (let* ((size (nth 7 (file-attributes tmpfile)))
5235 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
5236 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
5237 (cond
5238 ;; `copy-file' handles direct copy and out-of-band methods.
5239 ((or (tramp-local-host-p v)
5240 (tramp-method-out-of-band-p v size))
5241 (if (and (not (stringp start))
5242 (= (or end (point-max)) (point-max))
5243 (= (or start (point-min)) (point-min))
5244 (tramp-get-method-parameter
5245 method 'tramp-copy-keep-tmpfile))
5246 (progn
5247 (setq tramp-temp-buffer-file-name tmpfile)
5248 (condition-case err
5249 ;; We keep the local file for performance
5250 ;; reasons, useful for "rsync".
5251 (copy-file tmpfile filename t)
5252 ((error quit)
5253 (setq tramp-temp-buffer-file-name nil)
5254 (delete-file tmpfile)
5255 (signal (car err) (cdr err)))))
5256 (setq tramp-temp-buffer-file-name nil)
5257 ;; Don't rename, in order to keep context in SELinux.
5258 (unwind-protect
5259 (copy-file tmpfile filename t)
5260 (delete-file tmpfile))))
5261
5262 ;; Use inline file transfer.
5263 (rem-dec
5264 ;; Encode tmpfile.
191bb792 5265 (unwind-protect
20b8ac83
MA
5266 (with-temp-buffer
5267 (set-buffer-multibyte nil)
5268 ;; Use encoding function or command.
5269 (if (functionp loc-enc)
5270 (with-progress-reporter
5271 v 3 (format "Encoding region using function `%s'"
5272 loc-enc)
5273 (let ((coding-system-for-read 'binary))
5274 (insert-file-contents-literally tmpfile))
5275 ;; The following `let' is a workaround for the
5276 ;; base64.el that comes with pgnus-0.84. If
5277 ;; both of the following conditions are
5278 ;; satisfied, it tries to write to a local
5279 ;; file in default-directory, but at this
5280 ;; point, default-directory is remote.
5281 ;; (`call-process-region' can't write to
5282 ;; remote files, it seems.) The file in
5283 ;; question is a tmp file anyway.
5284 (let ((default-directory
5285 (tramp-compat-temporary-file-directory)))
5286 (funcall loc-enc (point-min) (point-max))))
5287
5288 (with-progress-reporter
5289 v 3 (format "Encoding region using command `%s'"
5290 loc-enc)
5291 (unless (zerop (tramp-call-local-coding-command
5292 loc-enc tmpfile t))
5293 (tramp-error
5294 v 'file-error
5295 (concat "Cannot write to `%s', "
5296 "local encoding command `%s' failed")
5297 filename loc-enc))))
5298
5299 ;; Send buffer into remote decoding command which
5300 ;; writes to remote file. Because this happens on
5301 ;; the remote host, we cannot use the function.
5302 (with-progress-reporter
5303 v 3
5304 (format "Decoding region into remote file %s" filename)
5305 (goto-char (point-max))
5306 (unless (bolp) (newline))
5307 (tramp-send-command
9c13938d
MA
5308 v
5309 (format
20b8ac83
MA
5310 (concat rem-dec " <<'EOF'\n%sEOF")
5311 (tramp-shell-quote-argument localname)
5312 (buffer-string)))
5313 (tramp-barf-unless-okay
5314 v nil
5315 "Couldn't write region to `%s', decode using `%s' failed"
5316 filename rem-dec)
5317 ;; When `file-precious-flag' is set, the region is
5318 ;; written to a temporary file. Check that the
5319 ;; checksum is equal to that from the local tmpfile.
5320 (when file-precious-flag
5321 (erase-buffer)
5322 (and
5323 ;; cksum runs locally, if possible.
5324 (zerop (tramp-local-call-process "cksum" tmpfile t))
5325 ;; cksum runs remotely.
5326 (zerop
5327 (tramp-send-command-and-check
5328 v
5329 (format
5330 "cksum <%s"
5331 (tramp-shell-quote-argument localname))))
5332 ;; ... they are different.
5333 (not
5334 (string-equal
5335 (buffer-string)
5336 (with-current-buffer (tramp-get-buffer v)
5337 (buffer-string))))
5338 (tramp-error
5339 v 'file-error
5340 (concat "Couldn't write region to `%s',"
5341 " decode using `%s' failed")
5342 filename rem-dec)))))
8d60099b 5343
20b8ac83
MA
5344 ;; Save exit.
5345 (delete-file tmpfile)))
8d60099b 5346
20b8ac83
MA
5347 ;; That's not expected.
5348 (t
5349 (tramp-error
5350 v 'file-error
5351 (concat "Method `%s' should specify both encoding and "
5352 "decoding command or an rcp program")
5353 method))))
258800f8 5354
9c13938d
MA
5355 ;; Make `last-coding-system-used' have the right value.
5356 (when coding-system-used
5357 (set 'last-coding-system-used coding-system-used))))
0f205eee 5358
aac0b0f2
MA
5359 (tramp-flush-file-property v (file-name-directory localname))
5360 (tramp-flush-file-property v localname)
5361
57671b72
MA
5362 ;; We must protect `last-coding-system-used', now we have set it
5363 ;; to its correct value.
293c24f9 5364 (let (last-coding-system-used (need-chown t))
57671b72
MA
5365 ;; Set file modification time.
5366 (when (or (eq visit t) (stringp visit))
293c24f9
MA
5367 (let ((file-attr (file-attributes filename)))
5368 (set-visited-file-modtime
5369 ;; We must pass modtime explicitely, because filename can
5370 ;; be different from (buffer-file-name), f.e. if
5371 ;; `file-precious-flag' is set.
5372 (nth 5 file-attr))
5373 (when (and (eq (nth 2 file-attr) uid)
5374 (eq (nth 3 file-attr) gid))
5375 (setq need-chown nil))))
57671b72
MA
5376
5377 ;; Set the ownership.
293c24f9
MA
5378 (when need-chown
5379 (tramp-set-file-uid-gid filename uid gid))
57671b72
MA
5380 (when (or (eq visit t) (null visit) (stringp visit))
5381 (tramp-message v 0 "Wrote %s" filename))
5382 (run-hooks 'tramp-handle-write-region-hook)))))
fb7933a3 5383
946a5aeb
MA
5384(defvar tramp-vc-registered-file-names nil
5385 "List used to collect file names, which are checked during `vc-registered'.")
5386
5387;; VC backends check for the existence of various different special
5388;; files. This is very time consuming, because every single check
5389;; requires a remote command (the file cache must be invalidated).
5390;; Therefore, we apply a kind of optimization. We install the file
5391;; name handler `tramp-vc-file-name-handler', which does nothing but
5392;; remembers all file names for which `file-exists-p' or
5393;; `file-readable-p' has been applied. A first run of `vc-registered'
5394;; is performed. Afterwards, a script is applied for all collected
5395;; file names, using just one remote command. The result of this
5396;; script is used to fill the file cache with actual values. Now we
5397;; can reset the file name handlers, and we make a second run of
5398;; `vc-registered', which returns the expected result without sending
5399;; any other remote command.
49096407
MA
5400(defun tramp-handle-vc-registered (file)
5401 "Like `vc-registered' for Tramp files."
20b8ac83
MA
5402 (with-temp-message ""
5403 (with-parsed-tramp-file-name file nil
5404 (with-progress-reporter
5405 v 3 (format "Checking `vc-registered' for %s" file)
5406
5407 ;; There could be new files, created by the vc backend. We
5408 ;; cannot reuse the old cache entries, therefore.
5409 (let (tramp-vc-registered-file-names
5410 (tramp-cache-inhibit-cache (current-time))
5411 (file-name-handler-alist
5412 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5413
5414 ;; Here we collect only file names, which need an operation.
5415 (tramp-run-real-handler 'vc-registered (list file))
5416 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5417
5418 ;; Send just one command, in order to fill the cache.
5419 (when tramp-vc-registered-file-names
5420 (tramp-maybe-send-script
5421 v
5422 (format tramp-vc-registered-read-file-names
5423 (tramp-get-file-exists-command v)
5424 (format "%s -r" (tramp-get-test-command v)))
5425 "tramp_vc_registered_read_file_names")
5426
5427 (dolist
5428 (elt
5429 (tramp-send-command-and-read
5430 v
5431 (format
5432 "tramp_vc_registered_read_file_names <<'EOF'\n%s\nEOF\n"
5433 (mapconcat 'tramp-shell-quote-argument
5434 tramp-vc-registered-file-names
5435 "\n"))))
5436
5437 (tramp-set-file-property
5438 v (car elt) (cadr elt) (cadr (cdr elt))))))
5439
5440 ;; Second run. Now all `file-exists-p' or `file-readable-p'
5441 ;; calls shall be answered from the file cache. We unset
5442 ;; `process-file-side-effects' in order to keep the cache when
5443 ;; `process-file' calls appear.
5444 (let (process-file-side-effects)
5445 (tramp-run-real-handler 'vc-registered (list file)))))))
49096407 5446
a01b1e22
MA
5447;;;###autoload
5448(progn (defun tramp-run-real-handler (operation args)
fb7933a3 5449 "Invoke normal file name handler for OPERATION.
c62c9d08
KG
5450First arg specifies the OPERATION, second arg is a list of arguments to
5451pass to the OPERATION."
4007ba5b
KG
5452 (let* ((inhibit-file-name-handlers
5453 `(tramp-file-name-handler
946a5aeb 5454 tramp-vc-file-name-handler
4007ba5b
KG
5455 tramp-completion-file-name-handler
5456 cygwin-mount-name-hook-function
5457 cygwin-mount-map-drive-hook-function
5458 .
5459 ,(and (eq inhibit-file-name-operation operation)
5460 inhibit-file-name-handlers)))
5461 (inhibit-file-name-operation operation))
a01b1e22 5462 (apply operation args))))
16674e4f 5463
a01b1e22
MA
5464;;;###autoload
5465(progn (defun tramp-completion-run-real-handler (operation args)
16674e4f
KG
5466 "Invoke `tramp-file-name-handler' for OPERATION.
5467First arg specifies the OPERATION, second arg is a list of arguments to
5468pass to the OPERATION."
4007ba5b
KG
5469 (let* ((inhibit-file-name-handlers
5470 `(tramp-completion-file-name-handler
5471 cygwin-mount-name-hook-function
5472 cygwin-mount-map-drive-hook-function
5473 .
5474 ,(and (eq inhibit-file-name-operation operation)
5475 inhibit-file-name-handlers)))
5476 (inhibit-file-name-operation operation))
a01b1e22 5477 (apply operation args))))
fb7933a3 5478
4007ba5b
KG
5479;; We handle here all file primitives. Most of them have the file
5480;; name as first parameter; nevertheless we check for them explicitly
04bf5b65 5481;; in order to be signaled if a new primitive appears. This
4007ba5b
KG
5482;; scenario is needed because there isn't a way to decide by
5483;; syntactical means whether a foreign method must be called. It would
19a87064 5484;; ease the life if `file-name-handler-alist' would support a decision
4007ba5b
KG
5485;; function as well but regexp only.
5486(defun tramp-file-name-for-operation (operation &rest args)
5487 "Return file name related to OPERATION file primitive.
5488ARGS are the arguments OPERATION has been called with."
5489 (cond
20b8ac83 5490 ;; FILE resp DIRECTORY.
4007ba5b
KG
5491 ((member operation
5492 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5493 'delete-file 'diff-latest-backup-file 'directory-file-name
5494 'directory-files 'directory-files-and-attributes
5495 'dired-compress-file 'dired-uncache
5496 'file-accessible-directory-p 'file-attributes
5497 'file-directory-p 'file-executable-p 'file-exists-p
19a87064
MA
5498 'file-local-copy 'file-remote-p 'file-modes
5499 'file-name-as-directory 'file-name-directory
5500 'file-name-nondirectory 'file-name-sans-versions
5501 'file-ownership-preserved-p 'file-readable-p
5502 'file-regular-p 'file-symlink-p 'file-truename
5503 'file-writable-p 'find-backup-file-name 'find-file-noselect
5504 'get-file-buffer 'insert-directory 'insert-file-contents
5505 'load 'make-directory 'make-directory-internal
5506 'set-file-modes 'substitute-in-file-name
5507 'unhandled-file-name-directory 'vc-registered
20b8ac83 5508 ;; Emacs 22+ only.
ce3f516f 5509 'set-file-times
20b8ac83
MA
5510 ;; Emacs 24+ only.
5511 'file-selinux-context 'set-file-selinux-context
5512 ;; XEmacs only.
4007ba5b
KG
5513 'abbreviate-file-name 'create-file-buffer
5514 'dired-file-modtime 'dired-make-compressed-filename
5515 'dired-recursive-delete-directory 'dired-set-file-modtime
5516 'dired-shell-unhandle-file-name 'dired-uucode-file
5615d63f 5517 'insert-file-contents-literally 'make-temp-name 'recover-file
4007ba5b 5518 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
8daea7fc
KG
5519 (if (file-name-absolute-p (nth 0 args))
5520 (nth 0 args)
5521 (expand-file-name (nth 0 args))))
20b8ac83 5522 ;; FILE DIRECTORY resp FILE1 FILE2.
4007ba5b
KG
5523 ((member operation
5524 (list 'add-name-to-file 'copy-file 'expand-file-name
5525 'file-name-all-completions 'file-name-completion
5526 'file-newer-than-file-p 'make-symbolic-link 'rename-file
20b8ac83 5527 ;; Emacs 23+ only.
263c02ef 5528 'copy-directory
20b8ac83 5529 ;; XEmacs only.
4007ba5b
KG
5530 'dired-make-relative-symlink
5531 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5532 (save-match-data
5533 (cond
5534 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5535 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5536 (t (buffer-file-name (current-buffer))))))
20b8ac83 5537 ;; START END FILE.
4007ba5b
KG
5538 ((eq operation 'write-region)
5539 (nth 2 args))
20b8ac83 5540 ;; BUFFER.
4007ba5b 5541 ((member operation
00d6fd04 5542 (list 'set-visited-file-modtime 'verify-visited-file-modtime
20b8ac83 5543 ;; Emacs 22+ only.
00d6fd04 5544 'make-auto-save-file-name
20b8ac83 5545 ;; XEmacs only.
4007ba5b
KG
5546 'backup-buffer))
5547 (buffer-file-name
5548 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
20b8ac83 5549 ;; COMMAND.
4007ba5b 5550 ((member operation
20b8ac83 5551 (list ;; not in Emacs 23+.
00d6fd04 5552 'dired-call-process
20b8ac83 5553 ;; Emacs only.
b71c9e75 5554 'shell-command
20b8ac83 5555 ;; Emacs 22+ only.
0457dd55 5556 'process-file
20b8ac83 5557 ;; Emacs 23+ only.
00d6fd04 5558 'start-file-process
20b8ac83 5559 ;; XEmacs only.
00d6fd04 5560 'dired-print-file 'dired-shell-call-process
20b8ac83
MA
5561 ;; nowhere yet.
5562 'executable-find 'start-process
5563 'call-process 'call-process-region))
4007ba5b 5564 default-directory)
20b8ac83 5565 ;; Unknown file primitive.
4007ba5b
KG
5566 (t (error "unknown file I/O primitive: %s" operation))))
5567
5568(defun tramp-find-foreign-file-name-handler (filename)
5569 "Return foreign file name handler if exists."
20b8ac83 5570 (when (tramp-tramp-file-p filename)
9ce8462a
MA
5571 (let ((v (tramp-dissect-file-name filename t))
5572 (handler tramp-foreign-file-name-handler-alist)
5573 elt res)
5574 ;; When we are not fully sure that filename completion is safe,
5575 ;; we should not return a handler.
5576 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1834b39f
MA
5577 (and (tramp-file-name-host v)
5578 (not (member (tramp-file-name-host v)
5579 (mapcar 'car tramp-methods))))
9ce8462a
MA
5580 (not (tramp-completion-mode-p)))
5581 (while handler
5582 (setq elt (car handler)
5583 handler (cdr handler))
5584 (when (funcall (car elt) filename)
5585 (setq handler nil
5586 res (cdr elt))))
5587 res))))
4007ba5b 5588
fb7933a3
KG
5589;; Main function.
5590;;;###autoload
5591(defun tramp-file-name-handler (operation &rest args)
ea9d1443 5592 "Invoke Tramp file name handler.
a4aeb9a4 5593Falls back to normal file name handler if no Tramp file name handler exists."
2e271195
MA
5594 (if tramp-mode
5595 (save-match-data
5596 (let* ((filename
5597 (tramp-replace-environment-variables
5598 (apply 'tramp-file-name-for-operation operation args)))
5599 (completion (tramp-completion-mode-p))
5600 (foreign (tramp-find-foreign-file-name-handler filename)))
5601 (with-parsed-tramp-file-name filename nil
20b8ac83
MA
5602 ;; Call the backend function.
5603 (if foreign
5604 (condition-case err
5605 (apply foreign operation args)
5606
5607 ;; Trace that somebody has interrupted the
5608 ;; operation.
5609 (quit
5610 (let (tramp-message-show-message)
5611 (tramp-message
5612 v 1 "Interrupt received in operation %s"
5613 (append (list operation) args)))
5614 ;; Propagate the quit signal.
5615 (signal (car err) (cdr err)))
5616
5617 ;; When we are in completion mode, some failed
5618 ;; operations shall return at least a default value
5619 ;; in order to give the user a chance to correct the
5620 ;; file name in the minibuffer.
5621 (error
5622 (cond
5623 ((and completion (zerop (length localname))
5624 (memq operation '(file-exists-p file-directory-p)))
5625 t)
5626 ((and completion (zerop (length localname))
5627 (memq operation
5628 '(expand-file-name file-name-as-directory)))
5629 filename)
5630 ;; Propagate the error.
5631 (t (signal (car err) (cdr err))))))
5632
5633 ;; Nothing to do for us.
5634 (tramp-run-real-handler operation args)))))
5635
2e271195
MA
5636 ;; When `tramp-mode' is not enabled, we don't do anything.
5637 (tramp-run-real-handler operation args)))
fb7933a3 5638
07dfe738
KG
5639;; In Emacs, there is some concurrency due to timers. If a timer
5640;; interrupts Tramp and wishes to use the same connection buffer as
5641;; the "main" Emacs, then garbage might occur in the connection
5642;; buffer. Therefore, we need to make sure that a timer does not use
5643;; the same connection buffer as the "main" Emacs. We implement a
5644;; cheap global lock, instead of locking each connection buffer
5645;; separately. The global lock is based on two variables,
5646;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5647;; (with setq) to indicate a lock. But Tramp also calls itself during
5648;; processing of a single file operation, so we need to allow
5649;; recursive calls. That's where the `tramp-locker' variable comes in
5650;; -- it is let-bound to t during the execution of the current
5651;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5652;; then we should just proceed because we have been called
5653;; recursively. But if `tramp-locker' is nil, then we are a timer
5654;; interrupting the "main" Emacs, and then we signal an error.
5655
5656(defvar tramp-locked nil
5657 "If non-nil, then Tramp is currently busy.
5658Together with `tramp-locker', this implements a locking mechanism
5659preventing reentrant calls of Tramp.")
5660
5661(defvar tramp-locker nil
5662 "If non-nil, then a caller has locked Tramp.
5663Together with `tramp-locked', this implements a locking mechanism
5664preventing reentrant calls of Tramp.")
5665
ea9d1443
KG
5666(defun tramp-sh-file-name-handler (operation &rest args)
5667 "Invoke remote-shell Tramp file name handler.
5668Fall back to normal file name handler if no Tramp handler exists."
07dfe738 5669 (when (and tramp-locked (not tramp-locker))
11c71217 5670 (setq tramp-locked nil)
00d6fd04 5671 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
07dfe738
KG
5672 (let ((tl tramp-locked))
5673 (unwind-protect
5674 (progn
5675 (setq tramp-locked t)
5676 (let ((tramp-locker t))
5677 (save-match-data
5678 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5679 (if fn
5680 (apply (cdr fn) args)
5681 (tramp-run-real-handler operation args))))))
5682 (setq tramp-locked tl))))
ea9d1443 5683
946a5aeb
MA
5684(defun tramp-vc-file-name-handler (operation &rest args)
5685 "Invoke special file name handler, which collects files to be handled."
5686 (save-match-data
5687 (let ((filename
5688 (tramp-replace-environment-variables
5689 (apply 'tramp-file-name-for-operation operation args)))
5690 (fn (assoc operation tramp-file-name-handler-alist)))
5691 (with-parsed-tramp-file-name filename nil
5692 (cond
5693 ;; That's what we want: file names, for which checks are
5694 ;; applied. We assume, that VC uses only `file-exists-p' and
5695 ;; `file-readable-p' checks; otherwise we must extend the
5696 ;; list. We do not perform any action, but return nil, in
5697 ;; order to keep `vc-registered' running.
5698 ((and fn (memq operation '(file-exists-p file-readable-p)))
5699 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5700 nil)
5701 ;; Tramp file name handlers like `expand-file-name'. They
5702 ;; must still work.
5703 (fn
5704 (save-match-data (apply (cdr fn) args)))
5705 ;; Default file name handlers, we don't care.
5706 (t (tramp-run-real-handler operation args)))))))
5707
16674e4f 5708;;;###autoload
1ecc6145 5709(progn (defun tramp-completion-file-name-handler (operation &rest args)
a4aeb9a4
MA
5710 "Invoke Tramp file name completion handler.
5711Falls back to normal file name handler if no Tramp file name handler exists."
57671b72
MA
5712 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5713 ;; would otherwise use backslash.
aff67808
MA
5714 (let ((directory-sep-char ?/)
5715 (fn (assoc operation tramp-completion-file-name-handler-alist)))
aa485f7c
MA
5716 (if (and
5717 ;; When `tramp-mode' is not enabled, we don't do anything.
5718 fn tramp-mode
5719 ;; For other syntaxes than `sep', the regexp matches many common
5720 ;; situations where the user doesn't actually want to use Tramp.
5721 ;; So to avoid autoloading Tramp after typing just "/s", we
5722 ;; disable this part of the completion, unless the user implicitly
5723 ;; indicated his interest in using a fancier completion system.
5724 (or (eq tramp-syntax 'sep)
20b8ac83
MA
5725 (featurep 'tramp) ;; If it's loaded, we may as well use it.
5726 ;; `partial-completion-mode' does not exist in XEmacs.
5727 ;; It is obsoleted with Emacs 24.1.
5728 (and (boundp 'partial-completion-mode)
5729 (symbol-value 'partial-completion-mode))
aa485f7c
MA
5730 ;; FIXME: These may have been loaded even if the user never
5731 ;; intended to use them.
5732 (featurep 'ido)
5733 (featurep 'icicles)))
aff67808
MA
5734 (save-match-data (apply (cdr fn) args))
5735 (tramp-completion-run-real-handler operation args)))))
a01b1e22 5736
b25a52cc 5737;;;###autoload
aa485f7c
MA
5738(progn (defun tramp-register-file-name-handlers ()
5739 "Add Tramp file name handlers to `file-name-handler-alist'."
5740 ;; Remove autoloaded handlers from file name handler alist. Useful,
00d6fd04
MA
5741 ;; if `tramp-syntax' has been changed.
5742 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
aa485f7c
MA
5743 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5744 (let ((a1 (rassq
5745 'tramp-completion-file-name-handler file-name-handler-alist)))
5746 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5747 ;; Add the handlers.
a01b1e22
MA
5748 (add-to-list 'file-name-handler-alist
5749 (cons tramp-file-name-regexp 'tramp-file-name-handler))
0c0b61f1 5750 (put 'tramp-file-name-handler 'safe-magic t)
aa485f7c
MA
5751 (add-to-list 'file-name-handler-alist
5752 (cons tramp-completion-file-name-regexp
5753 'tramp-completion-file-name-handler))
5754 (put 'tramp-completion-file-name-handler 'safe-magic t)
5755 ;; If jka-compr or epa-file are already loaded, move them to the
5756 ;; front of `file-name-handler-alist'.
5757 (dolist (fnh '(epa-file-handler jka-compr-handler))
5758 (let ((entry (rassoc fnh file-name-handler-alist)))
5759 (when entry
5760 (setq file-name-handler-alist
5761 (cons entry (delete entry file-name-handler-alist))))))))
69cee873 5762
00d6fd04
MA
5763;; `tramp-file-name-handler' must be registered before evaluation of
5764;; site-start and init files, because there might exist remote files
5765;; already, f.e. files kept via recentf-mode.
aa485f7c
MA
5766;;;###autoload(tramp-register-file-name-handlers)
5767(tramp-register-file-name-handlers)
b25a52cc 5768
fb7933a3 5769;;;###autoload
8c04e197 5770(defun tramp-unload-file-name-handlers ()
a69c01a0
MA
5771 (setq file-name-handler-alist
5772 (delete (rassoc 'tramp-file-name-handler
5773 file-name-handler-alist)
5774 (delete (rassoc 'tramp-completion-file-name-handler
5775 file-name-handler-alist)
5776 file-name-handler-alist))))
5777
8c04e197 5778(add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
a69c01a0 5779
0664ff72 5780;;; File name handler functions for completion mode:
a6e96327
MA
5781
5782(defvar tramp-completion-mode nil
5783 "If non-nil, external packages signal that they are in file name completion.
5784
5785This is necessary, because Tramp uses a heuristic depending on last
5786input event. This fails when external packages use other characters
5787but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5788should never be set globally, the intention is to let-bind it.")
16674e4f
KG
5789
5790;; Necessary because `tramp-file-name-regexp-unified' and
00d6fd04
MA
5791;; `tramp-completion-file-name-regexp-unified' aren't different. If
5792;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5793;; to `tramp-file-name-handler'). Otherwise, it takes
5794;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5795;; risky, because completing a file might require loading other files,
5796;; like "~/.netrc", and for them it shouldn't be decided based on that
5797;; variable. On the other hand, those files shouldn't have partial
a4aeb9a4
MA
5798;; Tramp file name syntax. Maybe another variable should be introduced
5799;; overwriting this check in such cases. Or we change Tramp file name
00d6fd04 5800;; syntax in order to avoid ambiguities, like in XEmacs ...
6c4e47fa 5801(defun tramp-completion-mode-p ()
20b8ac83 5802 "Check, whether method / user name / host name completion is active."
6c4e47fa 5803 (or
20b8ac83
MA
5804 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5805 (and (boundp 'non-essential) (symbol-value 'non-essential))
a6e96327
MA
5806 tramp-completion-mode
5807 ;; Emacs.
94be87e8 5808 (equal last-input-event 'tab)
6c4e47fa 5809 (and (natnump last-input-event)
94be87e8 5810 (or
a6e96327 5811 ;; ?\t has event-modifier 'control.
800a97b8 5812 (equal last-input-event ?\t)
94be87e8 5813 (and (not (event-modifiers last-input-event))
800a97b8
SM
5814 (or (equal last-input-event ?\?)
5815 (equal last-input-event ?\ )))))
a6e96327 5816 ;; XEmacs.
6c4e47fa
MA
5817 (and (featurep 'xemacs)
5818 ;; `last-input-event' might be nil.
5819 (not (null last-input-event))
5820 ;; `last-input-event' may have no character approximation.
20b8ac83 5821 (tramp-compat-funcall 'event-to-character last-input-event)
94be87e8 5822 (or
a6e96327 5823 ;; ?\t has event-modifier 'control.
800a97b8 5824 (equal
20b8ac83 5825 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
94be87e8 5826 (and (not (event-modifiers last-input-event))
800a97b8 5827 (or (equal
20b8ac83
MA
5828 (tramp-compat-funcall 'event-to-character last-input-event)
5829 ?\?)
800a97b8 5830 (equal
20b8ac83
MA
5831 (tramp-compat-funcall 'event-to-character last-input-event)
5832 ?\ )))))))
5833
5834(defun tramp-connectable-p (filename)
5835 "Check, whether it is possible to connect the remote host w/o side-effects.
5836This is true, if either the remote host is already connected, or if we are
5837not in completion mode."
5838 (and (tramp-tramp-file-p filename)
5839 (with-parsed-tramp-file-name filename nil
5840 (or (get-buffer (tramp-buffer-name v))
5841 (not (tramp-completion-mode-p))))))
16674e4f 5842
16674e4f
KG
5843;; Method, host name and user name completion.
5844;; `tramp-completion-dissect-file-name' returns a list of
5845;; tramp-file-name structures. For all of them we return possible completions.
a01b1e22 5846;;;###autoload
16674e4f 5847(defun tramp-completion-handle-file-name-all-completions (filename directory)
00d6fd04 5848 "Like `file-name-all-completions' for partial Tramp files."
16674e4f 5849
00d6fd04
MA
5850 (let* ((fullname (tramp-drop-volume-letter
5851 (expand-file-name filename directory)))
5852 ;; Possible completion structures.
5853 (v (tramp-completion-dissect-file-name fullname))
5854 result result1)
5855
5856 (while v
5857 (let* ((car (car v))
5858 (method (tramp-file-name-method car))
5859 (user (tramp-file-name-user car))
5860 (host (tramp-file-name-host car))
5861 (localname (tramp-file-name-localname car))
5862 (m (tramp-find-method method user host))
5863 (tramp-current-user user) ; see `tramp-parse-passwd'
5864 all-user-hosts)
5865
5866 (unless localname ;; Nothing to complete.
5867
5868 (if (or user host)
5869
5870 ;; Method dependent user / host combinations.
5871 (progn
9e6ab520 5872 (mapc
00d6fd04
MA
5873 (lambda (x)
5874 (setq all-user-hosts
5875 (append all-user-hosts
5876 (funcall (nth 0 x) (nth 1 x)))))
5877 (tramp-get-completion-function m))
5878
9e6ab520
MA
5879 (setq result
5880 (append result
5881 (mapcar
5882 (lambda (x)
5883 (tramp-get-completion-user-host
5884 method user host (nth 0 x) (nth 1 x)))
5885 (delq nil all-user-hosts)))))
00d6fd04
MA
5886
5887 ;; Possible methods.
5888 (setq result
5889 (append result (tramp-get-completion-methods m)))))
5890
5891 (setq v (cdr v))))
5892
5893 ;; Unify list, remove nil elements.
5894 (while result
5895 (let ((car (car result)))
5896 (when car
5897 (add-to-list
5898 'result1
5899 (substring car (length (tramp-drop-volume-letter directory)))))
5900 (setq result (cdr result))))
5901
5902 ;; Complete local parts.
5903 (append
5904 result1
5905 (condition-case nil
20b8ac83
MA
5906 (apply (if (tramp-connectable-p fullname)
5907 'tramp-completion-run-real-handler
5908 'tramp-run-real-handler)
5909 'file-name-all-completions (list (list filename directory)))
00d6fd04 5910 (error nil)))))
16674e4f
KG
5911
5912;; Method, host name and user name completion for a file.
a01b1e22 5913;;;###autoload
e1e17cae
MA
5914(defun tramp-completion-handle-file-name-completion
5915 (filename directory &optional predicate)
00d6fd04 5916 "Like `file-name-completion' for Tramp files."
e1e17cae
MA
5917 (try-completion
5918 filename
5919 (mapcar 'list (file-name-all-completions filename directory))
20b8ac83
MA
5920 (when (and predicate
5921 (tramp-connectable-p (expand-file-name filename directory)))
83e20b5c 5922 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
16674e4f
KG
5923
5924;; I misuse a little bit the tramp-file-name structure in order to handle
5925;; completion possibilities for partial methods / user names / host names.
5926;; Return value is a list of tramp-file-name structures according to possible
00d6fd04 5927;; completions. If "localname" is non-nil it means there
16674e4f
KG
5928;; shouldn't be a completion anymore.
5929
5930;; Expected results:
5931
00d6fd04
MA
5932;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5933;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5934;; [nil "x" nil nil]
5935;; ["x" nil nil nil]
5936
5937;; "/x:" "/x:y" "/x:y:"
5938;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5939;; "/[x/" "/[x/y"
5940;; ["x" nil "" nil] ["x" nil "y" nil]
5941;; ["x" "" nil nil] ["x" "y" nil nil]
5942
5943;; "/x:y@" "/x:y@z" "/x:y@z:"
5944;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5945;; "/[x/y@" "/[x/y@z"
5946;; ["x" nil "y" nil] ["x" "y" "z" nil]
16674e4f
KG
5947(defun tramp-completion-dissect-file-name (name)
5948 "Returns a list of `tramp-file-name' structures.
5949They are collected by `tramp-completion-dissect-file-name1'."
5950
5951 (let* ((result)
4007ba5b 5952 (x-nil "\\|\\(\\)")
b96e6899
MA
5953 (tramp-completion-ipv6-regexp
5954 (format
5955 "[^%s]*"
5956 (if (zerop (length tramp-postfix-ipv6-format))
5957 tramp-postfix-host-format
5958 tramp-postfix-ipv6-format)))
4007ba5b
KG
5959 ;; "/method" "/[method"
5960 (tramp-completion-file-name-structure1
5961 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5962 1 nil nil nil))
5963 ;; "/user" "/[user"
5964 (tramp-completion-file-name-structure2
5965 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5966 nil 1 nil nil))
5967 ;; "/host" "/[host"
5968 (tramp-completion-file-name-structure3
5969 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5970 nil nil 1 nil))
b96e6899 5971 ;; "/[ipv6" "/[ipv6"
4007ba5b 5972 (tramp-completion-file-name-structure4
b96e6899
MA
5973 (list (concat tramp-prefix-regexp
5974 tramp-prefix-ipv6-regexp
5975 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5976 nil nil 1 nil))
5977 ;; "/user@host" "/[user@host"
5978 (tramp-completion-file-name-structure5
4007ba5b
KG
5979 (list (concat tramp-prefix-regexp
5980 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5981 "\\(" tramp-host-regexp x-nil "\\)$")
5982 nil 1 2 nil))
b96e6899
MA
5983 ;; "/user@[ipv6" "/[user@ipv6"
5984 (tramp-completion-file-name-structure6
5985 (list (concat tramp-prefix-regexp
5986 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5987 tramp-prefix-ipv6-regexp
5988 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5989 nil 1 2 nil))
00d6fd04 5990 ;; "/method:user" "/[method/user" "/method://user"
b96e6899 5991 (tramp-completion-file-name-structure7
4007ba5b 5992 (list (concat tramp-prefix-regexp
00d6fd04 5993 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5994 "\\(" tramp-user-regexp x-nil "\\)$")
5995 1 2 nil nil))
00d6fd04 5996 ;; "/method:host" "/[method/host" "/method://host"
b96e6899 5997 (tramp-completion-file-name-structure8
4007ba5b 5998 (list (concat tramp-prefix-regexp
00d6fd04 5999 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
6000 "\\(" tramp-host-regexp x-nil "\\)$")
6001 1 nil 2 nil))
b96e6899
MA
6002 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
6003 (tramp-completion-file-name-structure9
6004 (list (concat tramp-prefix-regexp
6005 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6006 tramp-prefix-ipv6-regexp
6007 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6008 1 nil 2 nil))
00d6fd04 6009 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
b96e6899 6010 (tramp-completion-file-name-structure10
4007ba5b 6011 (list (concat tramp-prefix-regexp
00d6fd04 6012 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
6013 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6014 "\\(" tramp-host-regexp x-nil "\\)$")
00d6fd04 6015 1 2 3 nil))
b96e6899
MA
6016 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
6017 (tramp-completion-file-name-structure11
6018 (list (concat tramp-prefix-regexp
6019 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6020 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6021 tramp-prefix-ipv6-regexp
6022 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6023 1 2 3 nil))
00d6fd04 6024 ;; "/method: "/method:/"
b96e6899 6025 (tramp-completion-file-name-structure12
00d6fd04
MA
6026 (list
6027 (if (equal tramp-syntax 'url)
6028 (concat tramp-prefix-regexp
6029 "\\(" tramp-method-regexp "\\)"
6030 "\\(" (substring tramp-postfix-method-regexp 0 1)
6031 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6032 "\\(" "\\)$")
6033 ;; Should not match if not URL syntax.
6034 (concat tramp-prefix-regexp "/$"))
6035 1 3 nil nil))
6036 ;; "/method: "/method:/"
b96e6899 6037 (tramp-completion-file-name-structure13
00d6fd04
MA
6038 (list
6039 (if (equal tramp-syntax 'url)
6040 (concat tramp-prefix-regexp
6041 "\\(" tramp-method-regexp "\\)"
6042 "\\(" (substring tramp-postfix-method-regexp 0 1)
6043 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6044 "\\(" "\\)$")
6045 ;; Should not match if not URL syntax.
6046 (concat tramp-prefix-regexp "/$"))
6047 1 nil 3 nil)))
4007ba5b 6048
9e6ab520 6049 (mapc (lambda (regexp)
16674e4f
KG
6050 (add-to-list 'result
6051 (tramp-completion-dissect-file-name1 regexp name)))
6052 (list
6053 tramp-completion-file-name-structure1
6054 tramp-completion-file-name-structure2
6055 tramp-completion-file-name-structure3
6056 tramp-completion-file-name-structure4
6057 tramp-completion-file-name-structure5
6058 tramp-completion-file-name-structure6
6059 tramp-completion-file-name-structure7
00d6fd04
MA
6060 tramp-completion-file-name-structure8
6061 tramp-completion-file-name-structure9
b96e6899
MA
6062 tramp-completion-file-name-structure10
6063 tramp-completion-file-name-structure11
6064 tramp-completion-file-name-structure12
6065 tramp-completion-file-name-structure13
16674e4f
KG
6066 tramp-file-name-structure))
6067
6068 (delq nil result)))
6069
6070(defun tramp-completion-dissect-file-name1 (structure name)
6071 "Returns a `tramp-file-name' structure matching STRUCTURE.
00d6fd04 6072The structure consists of remote method, remote user,
7432277c 6073remote host and localname (filename on remote host)."
fb7933a3 6074
00d6fd04
MA
6075 (save-match-data
6076 (when (string-match (nth 0 structure) name)
6077 (let ((method (and (nth 1 structure)
6078 (match-string (nth 1 structure) name)))
6079 (user (and (nth 2 structure)
6080 (match-string (nth 2 structure) name)))
6081 (host (and (nth 3 structure)
6082 (match-string (nth 3 structure) name)))
6083 (localname (and (nth 4 structure)
6084 (match-string (nth 4 structure) name))))
6085 (vector method user host localname)))))
16674e4f
KG
6086
6087;; This function returns all possible method completions, adding the
6088;; trailing method delimeter.
16674e4f
KG
6089(defun tramp-get-completion-methods (partial-method)
6090 "Returns all method completions for PARTIAL-METHOD."
4007ba5b
KG
6091 (mapcar
6092 (lambda (method)
6093 (and method
6094 (string-match (concat "^" (regexp-quote partial-method)) method)
00d6fd04
MA
6095 (tramp-completion-make-tramp-file-name method nil nil nil)))
6096 (mapcar 'car tramp-methods)))
16674e4f
KG
6097
6098;; Compares partial user and host names with possible completions.
6099(defun tramp-get-completion-user-host (method partial-user partial-host user host)
6100 "Returns the most expanded string for user and host name completion.
6101PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
6102 (cond
6103
6104 ((and partial-user partial-host)
6105 (if (and host
6106 (string-match (concat "^" (regexp-quote partial-host)) host)
6107 (string-equal partial-user (or user partial-user)))
6108 (setq user partial-user)
6109 (setq user nil
6110 host nil)))
6111
6112 (partial-user
6113 (setq host nil)
6114 (unless
6115 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
6116 (setq user nil)))
6117
6118 (partial-host
6119 (setq user nil)
6120 (unless
6121 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
6122 (setq host nil)))
6123
6124 (t (setq user nil
6125 host nil)))
6126
292ffc15 6127 (unless (zerop (+ (length user) (length host)))
00d6fd04 6128 (tramp-completion-make-tramp-file-name method user host nil)))
16674e4f
KG
6129
6130(defun tramp-parse-rhosts (filename)
6131 "Return a list of (user host) tuples allowed to access.
292ffc15 6132Either user or host may be nil."
00d6fd04
MA
6133 ;; On Windows, there are problems in completion when
6134 ;; `default-directory' is remote.
9e6ab520 6135 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6136 res)
8daea7fc 6137 (when (file-readable-p filename)
16674e4f
KG
6138 (with-temp-buffer
6139 (insert-file-contents filename)
6140 (goto-char (point-min))
6141 (while (not (eobp))
292ffc15 6142 (push (tramp-parse-rhosts-group) res))))
16674e4f
KG
6143 res))
6144
16674e4f
KG
6145(defun tramp-parse-rhosts-group ()
6146 "Return a (user host) tuple allowed to access.
292ffc15 6147Either user or host may be nil."
16674e4f
KG
6148 (let ((result)
6149 (regexp
6150 (concat
6151 "^\\(" tramp-host-regexp "\\)"
6152 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 6153 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
6154 (when (re-search-forward regexp nil t)
6155 (setq result (append (list (match-string 3) (match-string 1)))))
6156 (widen)
6157 (forward-line 1)
6158 result))
6159
6160(defun tramp-parse-shosts (filename)
6161 "Return a list of (user host) tuples allowed to access.
6162User is always nil."
00d6fd04
MA
6163 ;; On Windows, there are problems in completion when
6164 ;; `default-directory' is remote.
9e6ab520 6165 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6166 res)
8daea7fc 6167 (when (file-readable-p filename)
16674e4f
KG
6168 (with-temp-buffer
6169 (insert-file-contents filename)
6170 (goto-char (point-min))
6171 (while (not (eobp))
292ffc15 6172 (push (tramp-parse-shosts-group) res))))
16674e4f
KG
6173 res))
6174
6175(defun tramp-parse-shosts-group ()
6176 "Return a (user host) tuple allowed to access.
6177User is always nil."
16674e4f
KG
6178 (let ((result)
6179 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
9e6ab520 6180 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
6181 (when (re-search-forward regexp nil t)
6182 (setq result (list nil (match-string 1))))
6183 (widen)
6184 (or
6185 (> (skip-chars-forward ",") 0)
6186 (forward-line 1))
6187 result))
6188
8daea7fc
KG
6189(defun tramp-parse-sconfig (filename)
6190 "Return a list of (user host) tuples allowed to access.
6191User is always nil."
00d6fd04
MA
6192 ;; On Windows, there are problems in completion when
6193 ;; `default-directory' is remote.
9e6ab520 6194 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6195 res)
8daea7fc
KG
6196 (when (file-readable-p filename)
6197 (with-temp-buffer
6198 (insert-file-contents filename)
6199 (goto-char (point-min))
6200 (while (not (eobp))
6201 (push (tramp-parse-sconfig-group) res))))
6202 res))
6203
6204(defun tramp-parse-sconfig-group ()
6205 "Return a (user host) tuple allowed to access.
6206User is always nil."
8daea7fc
KG
6207 (let ((result)
6208 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
9e6ab520 6209 (narrow-to-region (point) (tramp-compat-line-end-position))
8daea7fc
KG
6210 (when (re-search-forward regexp nil t)
6211 (setq result (list nil (match-string 1))))
6212 (widen)
6213 (or
6214 (> (skip-chars-forward ",") 0)
6215 (forward-line 1))
6216 result))
6217
5ec2cc41
KG
6218(defun tramp-parse-shostkeys (dirname)
6219 "Return a list of (user host) tuples allowed to access.
6220User is always nil."
00d6fd04
MA
6221 ;; On Windows, there are problems in completion when
6222 ;; `default-directory' is remote.
9e6ab520 6223 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6224 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6225 (files (when (file-directory-p dirname) (directory-files dirname)))
6226 result)
5ec2cc41
KG
6227 (while files
6228 (when (string-match regexp (car files))
6229 (push (list nil (match-string 1 (car files))) result))
6230 (setq files (cdr files)))
6231 result))
6232
6233(defun tramp-parse-sknownhosts (dirname)
6234 "Return a list of (user host) tuples allowed to access.
6235User is always nil."
00d6fd04
MA
6236 ;; On Windows, there are problems in completion when
6237 ;; `default-directory' is remote.
9e6ab520 6238 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6239 (regexp (concat "^\\(" tramp-host-regexp
6240 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6241 (files (when (file-directory-p dirname) (directory-files dirname)))
6242 result)
5ec2cc41
KG
6243 (while files
6244 (when (string-match regexp (car files))
6245 (push (list nil (match-string 1 (car files))) result))
6246 (setq files (cdr files)))
6247 result))
6248
16674e4f
KG
6249(defun tramp-parse-hosts (filename)
6250 "Return a list of (user host) tuples allowed to access.
6251User is always nil."
00d6fd04
MA
6252 ;; On Windows, there are problems in completion when
6253 ;; `default-directory' is remote.
9e6ab520 6254 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6255 res)
8daea7fc 6256 (when (file-readable-p filename)
16674e4f
KG
6257 (with-temp-buffer
6258 (insert-file-contents filename)
6259 (goto-char (point-min))
6260 (while (not (eobp))
292ffc15 6261 (push (tramp-parse-hosts-group) res))))
16674e4f
KG
6262 res))
6263
6264(defun tramp-parse-hosts-group ()
6265 "Return a (user host) tuple allowed to access.
6266User is always nil."
16674e4f 6267 (let ((result)
b96e6899
MA
6268 (regexp
6269 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
9e6ab520 6270 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f 6271 (when (re-search-forward regexp nil t)
b96e6899 6272 (setq result (list nil (match-string 1))))
16674e4f
KG
6273 (widen)
6274 (or
6275 (> (skip-chars-forward " \t") 0)
6276 (forward-line 1))
6277 result))
6278
8daea7fc
KG
6279;; For su-alike methods it would be desirable to return "root@localhost"
6280;; as default. Unfortunately, we have no information whether any user name
00d6fd04 6281;; has been typed already. So we use `tramp-current-user' as indication,
8daea7fc 6282;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
16674e4f
KG
6283(defun tramp-parse-passwd (filename)
6284 "Return a list of (user host) tuples allowed to access.
6285Host is always \"localhost\"."
00d6fd04
MA
6286 ;; On Windows, there are problems in completion when
6287 ;; `default-directory' is remote.
9e6ab520 6288 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6289 res)
8daea7fc 6290 (if (zerop (length tramp-current-user))
16674e4f 6291 '(("root" nil))
8daea7fc 6292 (when (file-readable-p filename)
16674e4f
KG
6293 (with-temp-buffer
6294 (insert-file-contents filename)
6295 (goto-char (point-min))
6296 (while (not (eobp))
292ffc15 6297 (push (tramp-parse-passwd-group) res))))
16674e4f
KG
6298 res)))
6299
6300(defun tramp-parse-passwd-group ()
6301 "Return a (user host) tuple allowed to access.
292ffc15 6302Host is always \"localhost\"."
16674e4f
KG
6303 (let ((result)
6304 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
9e6ab520 6305 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
6306 (when (re-search-forward regexp nil t)
6307 (setq result (list (match-string 1) "localhost")))
6308 (widen)
6309 (forward-line 1)
6310 result))
6311
292ffc15
KG
6312(defun tramp-parse-netrc (filename)
6313 "Return a list of (user host) tuples allowed to access.
6314User may be nil."
00d6fd04
MA
6315 ;; On Windows, there are problems in completion when
6316 ;; `default-directory' is remote.
9e6ab520 6317 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 6318 res)
8daea7fc 6319 (when (file-readable-p filename)
292ffc15
KG
6320 (with-temp-buffer
6321 (insert-file-contents filename)
6322 (goto-char (point-min))
6323 (while (not (eobp))
6324 (push (tramp-parse-netrc-group) res))))
6325 res))
6326
6327(defun tramp-parse-netrc-group ()
6328 "Return a (user host) tuple allowed to access.
6329User may be nil."
292ffc15
KG
6330 (let ((result)
6331 (regexp
6332 (concat
6333 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6334 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 6335 (narrow-to-region (point) (tramp-compat-line-end-position))
292ffc15
KG
6336 (when (re-search-forward regexp nil t)
6337 (setq result (list (match-string 3) (match-string 1))))
6338 (widen)
6339 (forward-line 1)
6340 result))
6341
00d6fd04
MA
6342(defun tramp-parse-putty (registry)
6343 "Return a list of (user host) tuples allowed to access.
6344User is always nil."
6345 ;; On Windows, there are problems in completion when
6346 ;; `default-directory' is remote.
9e6ab520 6347 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
6348 res)
6349 (with-temp-buffer
a4aeb9a4 6350 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
00d6fd04
MA
6351 (goto-char (point-min))
6352 (while (not (eobp))
6353 (push (tramp-parse-putty-group registry) res))))
6354 res))
6355
6356(defun tramp-parse-putty-group (registry)
6357 "Return a (user host) tuple allowed to access.
6358User is always nil."
6359 (let ((result)
6360 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
9e6ab520 6361 (narrow-to-region (point) (tramp-compat-line-end-position))
00d6fd04
MA
6362 (when (re-search-forward regexp nil t)
6363 (setq result (list nil (match-string 1))))
6364 (widen)
6365 (forward-line 1)
6366 result))
6367
fb7933a3
KG
6368;;; Internal Functions:
6369
00d6fd04
MA
6370(defun tramp-maybe-send-script (vec script name)
6371 "Define in remote shell function NAME implemented as SCRIPT.
6372Only send the definition if it has not already been done."
6373 (let* ((p (tramp-get-connection-process vec))
6374 (scripts (tramp-get-connection-property p "scripts" nil)))
1834b39f 6375 (unless (member name scripts)
20b8ac83
MA
6376 (with-progress-reporter vec 5 (format "Sending script `%s'" name)
6377 ;; The script could contain a call of Perl. This is masked with `%s'.
6378 (tramp-send-command-and-check
6379 vec
6380 (format "%s () {\n%s\n}" name
6381 (format script (tramp-get-remote-perl vec))))
6382 (tramp-set-connection-property p "scripts" (cons name scripts))))))
c82c5727 6383
fb7933a3 6384(defun tramp-set-auto-save ()
00d6fd04 6385 (when (and ;; ange-ftp has its own auto-save mechanism
7177e2a3
MA
6386 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6387 'tramp-sh-file-name-handler)
fb7933a3
KG
6388 auto-save-default)
6389 (auto-save-mode 1)))
6390(add-hook 'find-file-hooks 'tramp-set-auto-save t)
a69c01a0 6391(add-hook 'tramp-unload-hook
aa485f7c
MA
6392 (lambda ()
6393 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
fb7933a3
KG
6394
6395(defun tramp-run-test (switch filename)
6396 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6397Returns the exit code of the `test' program."
00d6fd04
MA
6398 (with-parsed-tramp-file-name filename nil
6399 (tramp-send-command-and-check
6400 v
6401 (format
6402 "%s %s %s"
6403 (tramp-get-test-command v)
6404 switch
6405 (tramp-shell-quote-argument localname)))))
6406
6407(defun tramp-run-test2 (format-string file1 file2)
6408 "Run `test'-like program on the remote system, given FILE1, FILE2.
6409FORMAT-STRING contains the program name, switches, and place holders.
6410Returns the exit code of the `test' program. Barfs if the methods,
fb7933a3 6411hosts, or files, disagree."
00d6fd04
MA
6412 (unless (tramp-equal-remote file1 file2)
6413 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6414 (tramp-error
6415 v 'file-error
6416 "tramp-run-test2 only implemented for same method, user, host")))
6417 (with-parsed-tramp-file-name file1 v1
6418 (with-parsed-tramp-file-name file1 v2
fb7933a3 6419 (tramp-send-command-and-check
00d6fd04
MA
6420 v1
6421 (format format-string
6422 (tramp-shell-quote-argument v1-localname)
6423 (tramp-shell-quote-argument v2-localname))))))
fb7933a3 6424
00d6fd04
MA
6425(defun tramp-buffer-name (vec)
6426 "A name for the connection buffer VEC."
6427 ;; We must use `tramp-file-name-real-host', because for gateway
6428 ;; methods the default port will be expanded later on, which would
6429 ;; tamper the name.
6430 (let ((method (tramp-file-name-method vec))
6431 (user (tramp-file-name-user vec))
6432 (host (tramp-file-name-real-host vec)))
6433 (if (not (zerop (length user)))
6434 (format "*tramp/%s %s@%s*" method user host)
6435 (format "*tramp/%s %s*" method host))))
6436
b88f2d0a
MA
6437(defun tramp-delete-temp-file-function ()
6438 "Remove temporary files related to current buffer."
6439 (when (stringp tramp-temp-buffer-file-name)
6440 (condition-case nil
6441 (delete-file tramp-temp-buffer-file-name)
6442 (error nil))))
6443
6444(add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6445(add-hook 'tramp-cache-unload-hook
6446 (lambda ()
6447 (remove-hook 'kill-buffer-hook
6448 'tramp-delete-temp-file-function)))
6449
00d6fd04
MA
6450(defun tramp-get-buffer (vec)
6451 "Get the connection buffer to be used for VEC."
6452 (or (get-buffer (tramp-buffer-name vec))
6453 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6454 (setq buffer-undo-list t)
6455 (setq default-directory
6456 (tramp-make-tramp-file-name
6457 (tramp-file-name-method vec)
6458 (tramp-file-name-user vec)
6459 (tramp-file-name-host vec)
6460 "/"))
6461 (current-buffer))))
6462
6463(defun tramp-get-connection-buffer (vec)
6464 "Get the connection buffer to be used for VEC.
6465In case a second asynchronous communication has been started, it is different
6466from `tramp-get-buffer'."
6467 (or (tramp-get-connection-property vec "process-buffer" nil)
6468 (tramp-get-buffer vec)))
6469
6470(defun tramp-get-connection-process (vec)
6471 "Get the connection process to be used for VEC.
6472In case a second asynchronous communication has been started, it is different
6473from the default one."
6474 (get-process
6475 (or (tramp-get-connection-property vec "process-name" nil)
6476 (tramp-buffer-name vec))))
6477
6478(defun tramp-debug-buffer-name (vec)
6479 "A name for the debug buffer for VEC."
6480 ;; We must use `tramp-file-name-real-host', because for gateway
6481 ;; methods the default port will be expanded later on, which would
6482 ;; tamper the name.
6483 (let ((method (tramp-file-name-method vec))
6484 (user (tramp-file-name-user vec))
6485 (host (tramp-file-name-real-host vec)))
6486 (if (not (zerop (length user)))
6487 (format "*debug tramp/%s %s@%s*" method user host)
6488 (format "*debug tramp/%s %s*" method host))))
6489
20b8ac83
MA
6490(defconst tramp-debug-outline-regexp
6491 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6492
00d6fd04
MA
6493(defun tramp-get-debug-buffer (vec)
6494 "Get the debug buffer for VEC."
01917a18 6495 (with-current-buffer
00d6fd04
MA
6496 (get-buffer-create (tramp-debug-buffer-name vec))
6497 (when (bobp)
6498 (setq buffer-undo-list t)
20b8ac83 6499 ;; Activate `outline-mode'. This runs `text-mode-hook' and
9ce8462a 6500 ;; `outline-mode-hook'. We must prevent that local processes
20b8ac83
MA
6501 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6502 ;; Furthermore, `outline-regexp' must have the correct value
6503 ;; already, because it is used by `font-lock-compile-keywords'.
6504 (let ((default-directory (tramp-compat-temporary-file-directory))
6505 (outline-regexp tramp-debug-outline-regexp))
00d6fd04 6506 (outline-mode))
20b8ac83 6507 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
9ce8462a 6508 (set (make-local-variable 'outline-level) 'tramp-outline-level))
01917a18 6509 (current-buffer)))
fb7933a3 6510
00d6fd04
MA
6511(defun tramp-outline-level ()
6512 "Return the depth to which a statement is nested in the outline.
6513Point must be at the beginning of a header line.
6514
6515The outline level is equal to the verbosity of the Tramp message."
6516 (1+ (string-to-number (match-string 1))))
fb7933a3 6517
00d6fd04
MA
6518(defun tramp-find-executable
6519 (vec progname dirlist &optional ignore-tilde ignore-path)
6520 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6521First arg VEC specifies the connection, PROGNAME is the program
6522to search for, and DIRLIST gives the list of directories to
6523search. If IGNORE-TILDE is non-nil, directory names starting
6524with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6525only in DIRLIST.
fb7933a3 6526
7432277c 6527Returns the absolute file name of PROGNAME, if found, and nil otherwise.
fb7933a3
KG
6528
6529This function expects to be in the right *tramp* buffer."
c0e17ff2 6530 (with-current-buffer (tramp-get-connection-buffer vec)
00d6fd04
MA
6531 (let (result)
6532 ;; Check whether the executable is in $PATH. "which(1)" does not
6533 ;; report always a correct error code; therefore we check the
6534 ;; number of words it returns.
6535 (unless ignore-path
6536 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6537 (goto-char (point-min))
c0e17ff2 6538 (if (looking-at "^\\s-*1$")
00d6fd04
MA
6539 (setq result (concat "\\" progname))))
6540 (unless result
6541 (when ignore-tilde
20b8ac83 6542 ;; Remove all ~/foo directories from dirlist. In XEmacs,
00d6fd04
MA
6543 ;; `remove' is in CL, and we want to avoid CL dependencies.
6544 (let (newdl d)
6545 (while dirlist
6546 (setq d (car dirlist))
6547 (setq dirlist (cdr dirlist))
6548 (unless (char-equal ?~ (aref d 0))
6549 (setq newdl (cons d newdl))))
6550 (setq dirlist (nreverse newdl))))
6551 (tramp-send-command
6552 vec
6553 (format (concat "while read d; "
6554 "do if test -x $d/%s -a -f $d/%s; "
6555 "then echo tramp_executable $d/%s; "
6556 "break; fi; done <<'EOF'\n"
6557 "%s\nEOF")
6558 progname progname progname (mapconcat 'identity dirlist "\n")))
6559 (goto-char (point-max))
6560 (when (search-backward "tramp_executable " nil t)
6561 (skip-chars-forward "^ ")
6562 (skip-chars-forward " ")
9e6ab520
MA
6563 (setq result (buffer-substring
6564 (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
6565 result)))
6566
6567(defun tramp-set-remote-path (vec)
6568 "Sets the remote environment PATH to existing directories.
6569I.e., for each directory in `tramp-remote-path', it is tested
6570whether it exists and if so, it is added to the environment
6571variable PATH."
6572 (tramp-message vec 5 (format "Setting $PATH environment variable"))
f84638eb
MA
6573 (tramp-send-command
6574 vec (format "PATH=%s; export PATH"
6575 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
fb7933a3 6576
cfb5c0db
MA
6577;; ------------------------------------------------------------
6578;; -- Communication with external shell --
6579;; ------------------------------------------------------------
fb7933a3 6580
00d6fd04 6581(defun tramp-find-file-exists-command (vec)
fb7933a3
KG
6582 "Find a command on the remote host for checking if a file exists.
6583Here, we are looking for a command which has zero exit status if the
6584file exists and nonzero exit status otherwise."
00d6fd04 6585 (let ((existing "/")
fb7933a3 6586 (nonexisting
00d6fd04
MA
6587 (tramp-shell-quote-argument "/ this file does not exist "))
6588 result)
fb7933a3
KG
6589 ;; The algorithm is as follows: we try a list of several commands.
6590 ;; For each command, we first run `$cmd /' -- this should return
6591 ;; true, as the root directory always exists. And then we run
00d6fd04 6592 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
fb7933a3
KG
6593 ;; does not exist. This should return false. We use the first
6594 ;; command we find that seems to work.
6595 ;; The list of commands to try is as follows:
00d6fd04
MA
6596 ;; `ls -d' This works on most systems, but NetBSD 1.4
6597 ;; has a bug: `ls' always returns zero exit
6598 ;; status, even for files which don't exist.
6599 ;; `test -e' Some Bourne shells have a `test' builtin
6600 ;; which does not know the `-e' option.
6601 ;; `/bin/test -e' For those, the `test' binary on disk normally
6602 ;; provides the option. Alas, the binary
6603 ;; is sometimes `/bin/test' and sometimes it's
6604 ;; `/usr/bin/test'.
6605 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
fb7933a3 6606 (unless (or
00d6fd04
MA
6607 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6608 (zerop (tramp-send-command-and-check
6609 vec (format "%s %s" result existing)))
6610 (not (zerop (tramp-send-command-and-check
6611 vec (format "%s %s" result nonexisting)))))
6612 (and (setq result "/bin/test -e")
6613 (zerop (tramp-send-command-and-check
6614 vec (format "%s %s" result existing)))
6615 (not (zerop (tramp-send-command-and-check
6616 vec (format "%s %s" result nonexisting)))))
6617 (and (setq result "/usr/bin/test -e")
6618 (zerop (tramp-send-command-and-check
6619 vec (format "%s %s" result existing)))
6620 (not (zerop (tramp-send-command-and-check
6621 vec (format "%s %s" result nonexisting)))))
6622 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6623 (zerop (tramp-send-command-and-check
6624 vec (format "%s %s" result existing)))
6625 (not (zerop (tramp-send-command-and-check
6626 vec (format "%s %s" result nonexisting))))))
6627 (tramp-error
6628 vec 'file-error "Couldn't find command to check if file exists"))
6629 result))
bf247b6e 6630
20b8ac83
MA
6631(defun tramp-open-shell (vec shell)
6632 "Opens shell SHELL."
6633 (with-progress-reporter vec 5 (format "Opening remote shell `%s'" shell)
6634 ;; Find arguments for this shell.
6635 (let ((tramp-end-of-output tramp-initial-end-of-output)
6636 (alist tramp-sh-extra-args)
6637 item extra-args)
6638 (while (and alist (null extra-args))
6639 (setq item (pop alist))
6640 (when (string-match (car item) shell)
6641 (setq extra-args (cdr item))))
6642 (when extra-args (setq shell (concat shell " " extra-args)))
6643 (tramp-send-command
6644 vec (format "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6645 (shell-quote-argument tramp-end-of-output) shell)
6646 t))
6647 ;; Setting prompts.
6648 (tramp-send-command
6649 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6650 (tramp-send-command vec "PS2=''" t)
6651 (tramp-send-command vec "PS3=''" t)
6652 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
6653
00d6fd04
MA
6654(defun tramp-find-shell (vec)
6655 "Opens a shell on the remote host which groks tilde expansion."
6656 (unless (tramp-get-connection-property vec "remote-shell" nil)
6657 (let (shell)
6658 (with-current-buffer (tramp-get-buffer vec)
7e780ff1 6659 (tramp-send-command vec "echo ~root" t)
00d6fd04 6660 (cond
c0e17ff2
MA
6661 ((or (string-match "^~root$" (buffer-string))
6662 ;; The default shell (ksh93) of OpenSolaris is buggy.
6663 (string-equal (tramp-get-connection-property vec "uname" "")
6664 "SunOS 5.11"))
00d6fd04 6665 (setq shell
f84638eb 6666 (or (tramp-find-executable
c0e17ff2 6667 vec "bash" (tramp-get-remote-path vec) t t)
f84638eb 6668 (tramp-find-executable
c0e17ff2 6669 vec "ksh" (tramp-get-remote-path vec) t t)))
00d6fd04
MA
6670 (unless shell
6671 (tramp-error
6672 vec 'file-error
6673 "Couldn't find a shell which groks tilde expansion"))
00d6fd04 6674 (tramp-message
20b8ac83
MA
6675 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
6676 (tramp-open-shell vec shell))
a0a5183a 6677
00d6fd04
MA
6678 (t (tramp-message
6679 vec 5 "Remote `%s' groks tilde expansion, good"
20b8ac83
MA
6680 (tramp-set-connection-property
6681 vec "remote-shell"
6682 (tramp-get-method-parameter
6683 (tramp-file-name-method vec) 'tramp-remote-sh)))))))))
fb7933a3 6684
bf247b6e
KS
6685;; ------------------------------------------------------------
6686;; -- Functions for establishing connection --
6687;; ------------------------------------------------------------
fb7933a3 6688
ac474af1
KG
6689;; The following functions are actions to be taken when seeing certain
6690;; prompts from the remote host. See the variable
6691;; `tramp-actions-before-shell' for usage of these functions.
6692
00d6fd04 6693(defun tramp-action-login (proc vec)
ac474af1 6694 "Send the login name."
00d6fd04
MA
6695 (when (not (stringp tramp-current-user))
6696 (save-window-excursion
6697 (let ((enable-recursive-minibuffers t))
6698 (pop-to-buffer (tramp-get-connection-buffer vec))
6699 (setq tramp-current-user (read-string (match-string 0))))))
6700 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6701 (with-current-buffer (tramp-get-connection-buffer vec)
6702 (tramp-message vec 6 "\n%s" (buffer-string)))
6703 (tramp-send-string vec tramp-current-user))
6704
6705(defun tramp-action-password (proc vec)
ac474af1 6706 "Query the user for a password."
70c11b0b
MA
6707 (with-current-buffer (process-buffer proc)
6708 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
20b8ac83
MA
6709 (tramp-message vec 3 "Sending %s" (match-string 1))
6710 (tramp-enter-password proc)
6711 ;; Hide password prompt.
6712 (narrow-to-region (point-max) (point-max))))
00d6fd04
MA
6713
6714(defun tramp-action-succeed (proc vec)
ac474af1 6715 "Signal success in finding shell prompt."
ac474af1
KG
6716 (throw 'tramp-action 'ok))
6717
00d6fd04 6718(defun tramp-action-permission-denied (proc vec)
ac474af1 6719 "Signal permission denied."
00d6fd04 6720 (kill-process proc)
ac474af1
KG
6721 (throw 'tramp-action 'permission-denied))
6722
00d6fd04 6723(defun tramp-action-yesno (proc vec)
3cdaec13
KG
6724 "Ask the user for confirmation using `yes-or-no-p'.
6725Send \"yes\" to remote process on confirmation, abort otherwise.
6726See also `tramp-action-yn'."
ac474af1 6727 (save-window-excursion
00d6fd04
MA
6728 (let ((enable-recursive-minibuffers t))
6729 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6730 (unless (yes-or-no-p (match-string 0))
6731 (kill-process proc)
6732 (throw 'tramp-action 'permission-denied))
6733 (with-current-buffer (tramp-get-connection-buffer vec)
6734 (tramp-message vec 6 "\n%s" (buffer-string)))
6735 (tramp-send-string vec "yes"))))
6736
6737(defun tramp-action-yn (proc vec)
3cdaec13
KG
6738 "Ask the user for confirmation using `y-or-n-p'.
6739Send \"y\" to remote process on confirmation, abort otherwise.
6740See also `tramp-action-yesno'."
6741 (save-window-excursion
00d6fd04
MA
6742 (let ((enable-recursive-minibuffers t))
6743 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6744 (unless (y-or-n-p (match-string 0))
6745 (kill-process proc)
6746 (throw 'tramp-action 'permission-denied))
6747 (with-current-buffer (tramp-get-connection-buffer vec)
6748 (tramp-message vec 6 "\n%s" (buffer-string)))
6749 (tramp-send-string vec "y"))))
6750
6751(defun tramp-action-terminal (proc vec)
487f4fb7
KG
6752 "Tell the remote host which terminal type to use.
6753The terminal type can be configured with `tramp-terminal-type'."
00d6fd04 6754 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
7e780ff1
MA
6755 (with-current-buffer (tramp-get-connection-buffer vec)
6756 (tramp-message vec 6 "\n%s" (buffer-string)))
00d6fd04 6757 (tramp-send-string vec tramp-terminal-type))
487f4fb7 6758
00d6fd04 6759(defun tramp-action-process-alive (proc vec)
20b8ac83 6760 "Check, whether a process has finished."
00d6fd04 6761 (unless (memq (process-status proc) '(run open))
19a87064
MA
6762 (throw 'tramp-action 'process-died)))
6763
00d6fd04 6764(defun tramp-action-out-of-band (proc vec)
20b8ac83 6765 "Check, whether an out-of-band copy has finished."
00d6fd04
MA
6766 (cond ((and (memq (process-status proc) '(stop exit))
6767 (zerop (process-exit-status proc)))
6768 (tramp-message vec 3 "Process has finished.")
38c65fca 6769 (throw 'tramp-action 'ok))
00d6fd04
MA
6770 ((or (and (memq (process-status proc) '(stop exit))
6771 (not (zerop (process-exit-status proc))))
6772 (memq (process-status proc) '(signal)))
01917a18
MA
6773 ;; `scp' could have copied correctly, but set modes could have failed.
6774 ;; This can be ignored.
00d6fd04
MA
6775 (with-current-buffer (process-buffer proc)
6776 (goto-char (point-min))
6777 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6778 (progn
6779 (tramp-message vec 5 "'set mode' error ignored.")
6780 (tramp-message vec 3 "Process has finished.")
6781 (throw 'tramp-action 'ok))
6782 (tramp-message vec 3 "Process has died.")
6783 (throw 'tramp-action 'process-died))))
38c65fca
KG
6784 (t nil)))
6785
ac474af1
KG
6786;; Functions for processing the actions.
6787
00d6fd04 6788(defun tramp-process-one-action (proc vec actions)
ac474af1 6789 "Wait for output from the shell and perform one action."
00d6fd04 6790 (let (found todo item pattern action)
e6466697 6791 (while (not found)
00d6fd04
MA
6792 ;; Reread output once all actions have been performed.
6793 ;; Obviously, the output was not complete.
6794 (tramp-accept-process-output proc 1)
e6466697
MA
6795 (setq todo actions)
6796 (while todo
e6466697 6797 (setq item (pop todo))
95d610cb 6798 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
e6466697 6799 (setq action (nth 1 item))
00d6fd04
MA
6800 (tramp-message
6801 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6802 (when (tramp-check-for-regexp proc pattern)
6803 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6804 (setq found (funcall action proc vec)))))
e6466697
MA
6805 found))
6806
00d6fd04 6807(defun tramp-process-actions (proc vec actions &optional timeout)
e6466697 6808 "Perform actions until success or TIMEOUT."
20b8ac83
MA
6809 ;; Preserve message for `progress-reporter'.
6810 (with-temp-message ""
6811 ;; Enable auth-source and password-cache.
6812 (tramp-set-connection-property vec "first-password-request" t)
6813 (let (exit)
6814 (while (not exit)
6815 (tramp-message proc 3 "Waiting for prompts from remote shell")
6816 (setq exit
6817 (catch 'tramp-action
6818 (if timeout
6819 (with-timeout (timeout)
6820 (tramp-process-one-action proc vec actions))
6821 (tramp-process-one-action proc vec actions)))))
6822 (with-current-buffer (tramp-get-connection-buffer vec)
6823 (widen)
6824 (tramp-message vec 6 "\n%s" (buffer-string)))
6825 (unless (eq exit 'ok)
6826 (tramp-clear-passwd vec)
6827 (tramp-error-with-buffer
6828 nil vec 'file-error
6829 (cond
6830 ((eq exit 'permission-denied) "Permission denied")
6831 ((eq exit 'process-died) "Process died")
6832 (t "Login failed")))))))
fb7933a3
KG
6833
6834;; Utility functions.
6835
00d6fd04 6836(defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
d2a2c17f
MA
6837 "Like `accept-process-output' for Tramp processes.
6838This is needed in order to hide `last-coding-system-used', which is set
6839for process communication also."
00d6fd04
MA
6840 (with-current-buffer (process-buffer proc)
6841 (tramp-message proc 10 "%s %s" proc (process-status proc))
6842 (let (buffer-read-only last-coding-system-used)
6843 ;; Under Windows XP, accept-process-output doesn't return
6844 ;; sometimes. So we add an additional timeout.
6845 (with-timeout ((or timeout 1))
6846 (accept-process-output proc timeout timeout-msecs)))
6847 (tramp-message proc 10 "\n%s" (buffer-string))))
6848
6849(defun tramp-check-for-regexp (proc regexp)
20b8ac83 6850 "Check, whether REGEXP is contained in process buffer of PROC.
00d6fd04
MA
6851Erase echoed commands if exists."
6852 (with-current-buffer (process-buffer proc)
6853 (goto-char (point-min))
674da028 6854
00d6fd04
MA
6855 ;; Check whether we need to remove echo output.
6856 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6857 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6858 (let ((begin (match-beginning 0)))
6859 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6860 ;; Discard echo from remote output.
6861 (tramp-set-connection-property proc "check-remote-echo" nil)
6862 (tramp-message proc 5 "echo-mark found")
20b8ac83 6863 (forward-line 1)
00d6fd04
MA
6864 (delete-region begin (point))
6865 (goto-char (point-min)))))
674da028 6866
68712eb6
MA
6867 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6868 ;; Sometimes, the echo string is suppressed on the remote side.
6869 (not (string-equal
20b8ac83
MA
6870 (tramp-compat-funcall
6871 'substring-no-properties tramp-echo-mark-marker
68712eb6 6872 0 (min tramp-echo-mark-marker-length (1- (point-max))))
20b8ac83
MA
6873 (tramp-compat-funcall
6874 'buffer-substring-no-properties
68712eb6 6875 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
70c11b0b 6876 ;; No echo to be handled, now we can look for the regexp.
674da028 6877 (goto-char (point-min))
00d6fd04 6878 (re-search-forward regexp nil t))))
d2a2c17f 6879
fb7933a3
KG
6880(defun tramp-wait-for-regexp (proc timeout regexp)
6881 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6882Expects the output of PROC to be sent to the current buffer. Returns
6883the string that matched, or nil. Waits indefinitely if TIMEOUT is
6884nil."
00d6fd04
MA
6885 (with-current-buffer (process-buffer proc)
6886 (let ((found (tramp-check-for-regexp proc regexp))
6887 (start-time (current-time)))
6888 (cond (timeout
6889 ;; Work around a bug in XEmacs 21, where the timeout
6890 ;; expires faster than it should. This degenerates
6891 ;; to polling for buggy XEmacsen, but oh, well.
6892 (while (and (not found)
6893 (< (tramp-time-diff (current-time) start-time)
6894 timeout))
6895 (with-timeout (timeout)
6896 (while (not found)
6897 (tramp-accept-process-output proc 1)
6898 (unless (memq (process-status proc) '(run open))
6899 (tramp-error-with-buffer
6900 nil proc 'file-error "Process has died"))
6901 (setq found (tramp-check-for-regexp proc regexp))))))
6902 (t
6903 (while (not found)
6904 (tramp-accept-process-output proc 1)
6905 (unless (memq (process-status proc) '(run open))
6906 (tramp-error-with-buffer
6907 nil proc 'file-error "Process has died"))
6908 (setq found (tramp-check-for-regexp proc regexp)))))
6909 (tramp-message proc 6 "\n%s" (buffer-string))
fb7933a3 6910 (when (not found)
00d6fd04
MA
6911 (if timeout
6912 (tramp-error
6913 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6914 regexp timeout)
6915 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6916 found)))
fb7933a3 6917
b25a52cc
KG
6918(defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6919 "Wait for shell prompt and barf if none appears.
6920Looks at process PROC to see if a shell prompt appears in TIMEOUT
6921seconds. If not, it produces an error message with the given ERROR-ARGS."
7e780ff1
MA
6922 (unless
6923 (tramp-wait-for-regexp
6924 proc timeout
6925 (format
6926 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
00d6fd04
MA
6927 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6928
7e780ff1
MA
6929;; We don't call `tramp-send-string' in order to hide the password
6930;; from the debug buffer, and because end-of-line handling of the
6931;; string.
6932(defun tramp-enter-password (proc)
00d6fd04
MA
6933 "Prompt for a password and send it to the remote end."
6934 (process-send-string
7e780ff1
MA
6935 proc (concat (tramp-read-passwd proc)
6936 (or (tramp-get-method-parameter
6937 tramp-current-method
6938 'tramp-password-end-of-line)
6939 tramp-default-password-end-of-line))))
00d6fd04
MA
6940
6941(defun tramp-open-connection-setup-interactive-shell (proc vec)
fb7933a3 6942 "Set up an interactive shell.
00d6fd04
MA
6943Mainly sets the prompt and the echo correctly. PROC is the shell
6944process to set up. VEC specifies the connection."
dab816a9 6945 (let ((tramp-end-of-output tramp-initial-end-of-output))
8950769a
MA
6946 ;; It is useful to set the prompt in the following command because
6947 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6948 ;; about and thus /bin/sh will display a strange prompt. For
6949 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6950 ;; display the current working directory but /bin/sh will display
6951 ;; a dollar sign. The following command line sets $PS1 to a sane
6952 ;; value, and works under Bourne-ish shells as well as csh-like
6953 ;; shells. Daniel Pittman reports that the unusual positioning of
6954 ;; the single quotes makes it work under `rc', too. We also unset
6955 ;; the variable $ENV because that is read by some sh
6956 ;; implementations (eg, bash when called as sh) on startup; this
6957 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6958 ;; is another way to set the prompt in /bin/bash, it must be
6959 ;; discarded as well.
20b8ac83 6960 (tramp-open-shell
a4aeb9a4 6961 vec
20b8ac83 6962 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-remote-sh))
8950769a
MA
6963
6964 ;; Disable echo.
6965 (tramp-message vec 5 "Setting up remote shell environment")
6966 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6967 ;; Check whether the echo has really been disabled. Some
6968 ;; implementations, like busybox of embedded GNU/Linux, don't
6969 ;; support disabling.
6970 (tramp-send-command vec "echo foo" t)
6971 (with-current-buffer (process-buffer proc)
6972 (goto-char (point-min))
6973 (when (looking-at "echo foo")
6974 (tramp-set-connection-property proc "remote-echo" t)
6975 (tramp-message vec 5 "Remote echo still on. Ok.")
6976 ;; Make sure backspaces and their echo are enabled and no line
6977 ;; width magic interferes with them.
6978 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
e42c6bbc 6979
7e780ff1 6980 (tramp-message vec 5 "Setting shell prompt")
70c11b0b
MA
6981 (tramp-send-command
6982 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
6983 (tramp-send-command vec "PS2=''" t)
6984 (tramp-send-command vec "PS3=''" t)
6985 (tramp-send-command vec "PROMPT_COMMAND=''" t)
e42c6bbc 6986
fb7933a3
KG
6987 ;; Try to set up the coding system correctly.
6988 ;; CCC this can't be the right way to do it. Hm.
00d6fd04 6989 (tramp-message vec 5 "Determining coding system")
7e780ff1 6990 (tramp-send-command vec "echo foo ; echo bar" t)
00d6fd04 6991 (with-current-buffer (process-buffer proc)
fb7933a3
KG
6992 (goto-char (point-min))
6993 (if (featurep 'mule)
00d6fd04
MA
6994 ;; Use MULE to select the right EOL convention for communicating
6995 ;; with the process.
20b8ac83 6996 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
00d6fd04
MA
6997 (cons 'undecided 'undecided)))
6998 cs-decode cs-encode)
6999 (when (symbolp cs) (setq cs (cons cs cs)))
7000 (setq cs-decode (car cs))
7001 (setq cs-encode (cdr cs))
7002 (unless cs-decode (setq cs-decode 'undecided))
7003 (unless cs-encode (setq cs-encode 'undecided))
7004 (setq cs-encode (tramp-coding-system-change-eol-conversion
7005 cs-encode 'unix))
7006 (when (search-forward "\r" nil t)
7007 (setq cs-decode (tramp-coding-system-change-eol-conversion
7008 cs-decode 'dos)))
20b8ac83
MA
7009 (tramp-compat-funcall
7010 'set-buffer-process-coding-system cs-decode cs-encode)
70c11b0b
MA
7011 (tramp-message
7012 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
fb7933a3
KG
7013 ;; Look for ^M and do something useful if found.
7014 (when (search-forward "\r" nil t)
00d6fd04
MA
7015 ;; We have found a ^M but cannot frob the process coding system
7016 ;; because we're running on a non-MULE Emacs. Let's try
7017 ;; stty, instead.
7e780ff1 7018 (tramp-send-command vec "stty -onlcr" t))))
e499c64d 7019
7e780ff1 7020 (tramp-send-command vec "set +o vi +o emacs" t)
e42c6bbc
MA
7021
7022 ;; Check whether the output of "uname -sr" has been changed. If
7023 ;; yes, this is a strong indication that we must expire all
d8ac123e
MA
7024 ;; connection properties. We start again with
7025 ;; `tramp-maybe-open-connection', it will be catched there.
e42c6bbc
MA
7026 (tramp-message vec 5 "Checking system information")
7027 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
7028 (new-uname
7029 (tramp-set-connection-property
7030 vec "uname"
7031 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
7032 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
d8ac123e 7033 (with-current-buffer (tramp-get-debug-buffer vec)
20b8ac83 7034 ;; Keep the debug buffer.
2296b54d
MA
7035 (rename-buffer
7036 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
20b8ac83 7037 (tramp-compat-funcall 'tramp-cleanup-connection vec)
d8ac123e
MA
7038 (if (= (point-min) (point-max))
7039 (kill-buffer nil)
7040 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
7041 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
7042 (tramp-get-buffer vec)
7043 (tramp-message
7044 vec 3
7045 "Connection reset, because remote host changed from `%s' to `%s'"
7046 old-uname new-uname)
7047 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
e42c6bbc
MA
7048
7049 ;; Check whether the remote host suffers from buggy
7050 ;; `send-process-string'. This is known for FreeBSD (see comment in
7051 ;; `send_process', file process.c). I've tested sending 624 bytes
7052 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
7053 ;; this host type is detected locally. It cannot handle remote
7054 ;; hosts, though.
00d6fd04
MA
7055 (with-connection-property proc "chunksize"
7056 (cond
7057 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
7058 tramp-chunksize)
7059 (t
7060 (tramp-message
7061 vec 5 "Checking remote host type for `send-process-string' bug")
7062 (if (string-match
e42c6bbc 7063 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
00d6fd04 7064 500 0))))
e42c6bbc 7065
00d6fd04
MA
7066 ;; Set remote PATH variable.
7067 (tramp-set-remote-path vec)
e42c6bbc 7068
fb7933a3
KG
7069 ;; Search for a good shell before searching for a command which
7070 ;; checks if a file exists. This is done because Tramp wants to use
7071 ;; "test foo; echo $?" to check if various conditions hold, and
7072 ;; there are buggy /bin/sh implementations which don't execute the
7073 ;; "echo $?" part if the "test" part has an error. In particular,
c0e17ff2
MA
7074 ;; the OpenSolaris /bin/sh is a problem. There are also other
7075 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
20b8ac83 7076 ;; in function declarations, or changing HISTFILE in place.
c0e17ff2
MA
7077 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
7078 ;; detected.
00d6fd04 7079 (tramp-find-shell vec)
e42c6bbc 7080
00d6fd04 7081 ;; Disable unexpected output.
7e780ff1 7082 (tramp-send-command vec "mesg n; biff n" t)
e42c6bbc 7083
20b8ac83
MA
7084 ;; IRIX64 bash expands "!" even when in single quotes. This
7085 ;; destroys our shell functions, we must disable it. See
7086 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
7087 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
7088 (tramp-send-command vec "set +H" t))
7089
e499c64d
MA
7090 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
7091 (when (string-match "BSD\\|Darwin"
7092 (tramp-get-connection-property vec "uname" ""))
7093 (tramp-send-command vec "stty -oxtabs" t))
7094
20b8ac83
MA
7095 ;; Set `remote-tty' process property.
7096 (ignore-errors
7097 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"")))
7098 (unless (zerop (length tty)) (process-put proc 'remote-tty tty))))
7099
e499c64d
MA
7100 ;; Dump stty settings in the traces.
7101 (when (>= tramp-verbose 9)
7102 (tramp-send-command vec "stty -a" t))
7103
00d6fd04
MA
7104 ;; Set the environment.
7105 (tramp-message vec 5 "Setting default environment")
661aaece 7106
00d6fd04
MA
7107 (let ((env (copy-sequence tramp-remote-process-environment))
7108 unset item)
7109 (while env
70c11b0b 7110 (setq item (tramp-compat-split-string (car env) "="))
7e5686f0
MA
7111 (setcdr item (mapconcat 'identity (cdr item) "="))
7112 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
00d6fd04 7113 (tramp-send-command
7e5686f0 7114 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
00d6fd04
MA
7115 (push (car item) unset))
7116 (setq env (cdr env)))
7117 (when unset
fb7933a3 7118 (tramp-send-command
20b8ac83 7119 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
fb7933a3 7120
ac474af1
KG
7121;; CCC: We should either implement a Perl version of base64 encoding
7122;; and decoding. Then we just use that in the last item. The other
7123;; alternative is to use the Perl version of UU encoding. But then
7124;; we need a Lisp version of uuencode.
16674e4f
KG
7125;;
7126;; Old text from documentation of tramp-methods:
7127;; Using a uuencode/uudecode inline method is discouraged, please use one
7128;; of the base64 methods instead since base64 encoding is much more
7129;; reliable and the commands are more standardized between the different
7130;; Unix versions. But if you can't use base64 for some reason, please
7131;; note that the default uudecode command does not work well for some
7132;; Unices, in particular AIX and Irix. For AIX, you might want to use
7133;; the following command for uudecode:
7134;;
7135;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
7136;;
7137;; For Irix, no solution is known yet.
7138
00d6fd04
MA
7139(defconst tramp-local-coding-commands
7140 '((b64 base64-encode-region base64-decode-region)
7141 (uu tramp-uuencode-region uudecode-decode-region)
7142 (pack
7143 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7144 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7145 "List of local coding commands for inline transfer.
16674e4f
KG
7146Each item is a list that looks like this:
7147
20b8ac83 7148\(FORMAT ENCODING DECODING\)
ac474af1 7149
00d6fd04
MA
7150FORMAT is symbol describing the encoding/decoding format. It can be
7151`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
ac474af1 7152
00d6fd04
MA
7153ENCODING and DECODING can be strings, giving commands, or symbols,
7154giving functions. If they are strings, then they can contain
16674e4f
KG
7155the \"%s\" format specifier. If that specifier is present, the input
7156filename will be put into the command line at that spot. If the
7157specifier is not present, the input should be read from standard
7158input.
ac474af1 7159
16674e4f
KG
7160If they are functions, they will be called with two arguments, start
7161and end of region, and are expected to replace the region contents
7162with the encoded or decoded results, respectively.")
ac474af1 7163
00d6fd04 7164(defconst tramp-remote-coding-commands
cdf015b1
MA
7165 '((b64 "base64" "base64 -d -i")
7166 ;; "-i" is more robust with older base64 from GNU coreutils.
7167 ;; However, I don't know whether all base64 versions do supports
7168 ;; this option.
7169 (b64 "base64" "base64 -d")
3dc847a3 7170 (b64 "mimencode -b" "mimencode -u -b")
00d6fd04
MA
7171 (b64 "mmencode -b" "mmencode -u -b")
7172 (b64 "recode data..base64" "recode base64..data")
7173 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
7174 (b64 tramp-perl-encode tramp-perl-decode)
7175 (uu "uuencode xxx" "uudecode -o /dev/stdout")
7176 (uu "uuencode xxx" "uudecode -o -")
7177 (uu "uuencode xxx" "uudecode -p")
7178 (uu "uuencode xxx" tramp-uudecode)
7179 (pack
7180 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7181 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7182 "List of remote coding commands for inline transfer.
7183Each item is a list that looks like this:
7184
20b8ac83 7185\(FORMAT ENCODING DECODING\)
00d6fd04
MA
7186
7187FORMAT is symbol describing the encoding/decoding format. It can be
7188`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7189
7190ENCODING and DECODING can be strings, giving commands, or symbols,
7191giving variables. If they are strings, then they can contain
7192the \"%s\" format specifier. If that specifier is present, the input
7193filename will be put into the command line at that spot. If the
7194specifier is not present, the input should be read from standard
7195input.
7196
7197If they are variables, this variable is a string containing a Perl
7198implementation for this functionality. This Perl program will be transferred
db9e401b 7199to the remote host, and it is available as shell function with the same name.")
00d6fd04
MA
7200
7201(defun tramp-find-inline-encoding (vec)
ac474af1 7202 "Find an inline transfer encoding that works.
00d6fd04
MA
7203Goes through the list `tramp-local-coding-commands' and
7204`tramp-remote-coding-commands'."
7205 (save-excursion
7206 (let ((local-commands tramp-local-coding-commands)
7207 (magic "xyzzy")
7208 loc-enc loc-dec rem-enc rem-dec litem ritem found)
7209 (while (and local-commands (not found))
7210 (setq litem (pop local-commands))
7211 (catch 'wont-work-local
7212 (let ((format (nth 0 litem))
7213 (remote-commands tramp-remote-coding-commands))
7214 (setq loc-enc (nth 1 litem))
7215 (setq loc-dec (nth 2 litem))
7216 ;; If the local encoder or decoder is a string, the
7217 ;; corresponding command has to work locally.
7218 (if (not (stringp loc-enc))
7219 (tramp-message
7220 vec 5 "Checking local encoding function `%s'" loc-enc)
7221 (tramp-message
7222 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
7223 (unless (zerop (tramp-call-local-coding-command
7224 loc-enc nil nil))
7225 (throw 'wont-work-local nil)))
7226 (if (not (stringp loc-dec))
7227 (tramp-message
7228 vec 5 "Checking local decoding function `%s'" loc-dec)
7229 (tramp-message
7230 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7231 (unless (zerop (tramp-call-local-coding-command
7232 loc-dec nil nil))
7233 (throw 'wont-work-local nil)))
7234 ;; Search for remote coding commands with the same format
7235 (while (and remote-commands (not found))
7236 (setq ritem (pop remote-commands))
7237 (catch 'wont-work-remote
7238 (when (equal format (nth 0 ritem))
7239 (setq rem-enc (nth 1 ritem))
7240 (setq rem-dec (nth 2 ritem))
7241 ;; Check if remote encoding and decoding commands can be
7242 ;; called remotely with null input and output. This makes
7243 ;; sure there are no syntax errors and the command is really
7244 ;; found. Note that we do not redirect stdout to /dev/null,
7245 ;; for two reasons: when checking the decoding command, we
7246 ;; actually check the output it gives. And also, when
7247 ;; redirecting "mimencode" output to /dev/null, then as root
7248 ;; it might change the permissions of /dev/null!
7249 (when (not (stringp rem-enc))
7250 (let ((name (symbol-name rem-enc)))
7251 (while (string-match (regexp-quote "-") name)
7252 (setq name (replace-match "_" nil t name)))
7253 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7254 (setq rem-enc name)))
7255 (tramp-message
7256 vec 5
7257 "Checking remote encoding command `%s' for sanity" rem-enc)
7258 (unless (zerop (tramp-send-command-and-check
7259 vec (format "%s </dev/null" rem-enc) t))
7260 (throw 'wont-work-remote nil))
7261
7262 (when (not (stringp rem-dec))
7263 (let ((name (symbol-name rem-dec)))
7264 (while (string-match (regexp-quote "-") name)
7265 (setq name (replace-match "_" nil t name)))
7266 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7267 (setq rem-dec name)))
7268 (tramp-message
7269 vec 5
7270 "Checking remote decoding command `%s' for sanity" rem-dec)
7271 (unless (zerop (tramp-send-command-and-check
7272 vec
7273 (format "echo %s | %s | %s"
b593f105
MA
7274 magic rem-enc rem-dec)
7275 t))
00d6fd04
MA
7276 (throw 'wont-work-remote nil))
7277
7278 (with-current-buffer (tramp-get-buffer vec)
7279 (goto-char (point-min))
7280 (unless (looking-at (regexp-quote magic))
7281 (throw 'wont-work-remote nil)))
7282
7283 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7284 (setq rem-enc (nth 1 ritem))
7285 (setq rem-dec (nth 2 ritem))
7286 (setq found t)))))))
7287
1d7e9a01 7288 ;; Did we find something?
00d6fd04 7289 (unless found
7e5686f0
MA
7290 (tramp-error
7291 vec 'file-error "Couldn't find an inline transfer encoding"))
00d6fd04
MA
7292
7293 ;; Set connection properties.
7294 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7295 (tramp-set-connection-property vec "local-encoding" loc-enc)
7296 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7297 (tramp-set-connection-property vec "local-decoding" loc-dec)
7298 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7299 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7300 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7301 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
16674e4f
KG
7302
7303(defun tramp-call-local-coding-command (cmd input output)
7304 "Call the local encoding or decoding command.
7305If CMD contains \"%s\", provide input file INPUT there in command.
7306Otherwise, INPUT is passed via standard input.
7307INPUT can also be nil which means `/dev/null'.
7308OUTPUT can be a string (which specifies a filename), or t (which
7309means standard output and thus the current buffer), or nil (which
7310means discard it)."
a4aeb9a4
MA
7311 (tramp-local-call-process
7312 tramp-encoding-shell
7313 (when (and input (not (string-match "%s" cmd))) input)
7314 (if (eq output t) t nil)
7315 nil
7316 tramp-encoding-command-switch
7317 (concat
7318 (if (string-match "%s" cmd) (format cmd input) cmd)
7319 (if (stringp output) (concat "> " output) ""))))
00d6fd04 7320
20b8ac83
MA
7321(defconst tramp-inline-compress-commands
7322 '(("gzip" "gzip -d")
7323 ("bzip2" "bzip2 -d")
7324 ("compress" "compress -d"))
7325 "List of compress and decompress commands for inline transfer.
7326Each item is a list that looks like this:
7327
7328\(COMPRESS DECOMPRESS\)
7329
7330COMPRESS or DECOMPRESS are strings with the respective commands.")
7331
7332(defun tramp-find-inline-compress (vec)
7333 "Find an inline transfer compress command that works.
7334Goes through the list `tramp-inline-compress-commands'."
7335 (save-excursion
7336 (let ((commands tramp-inline-compress-commands)
7337 (magic "xyzzy")
7338 item compress decompress
7339 found)
7340 (while (and commands (not found))
7341 (catch 'next
7342 (setq item (pop commands)
7343 compress (nth 0 item)
7344 decompress (nth 1 item))
7345 (tramp-message
7346 vec 5
7347 "Checking local compress command `%s', `%s' for sanity"
7348 compress decompress)
7349 (unless (zerop (tramp-call-local-coding-command
7350 (format "echo %s | %s | %s"
7351 magic compress decompress) nil nil))
7352 (throw 'next nil))
7353 (tramp-message
7354 vec 5
7355 "Checking remote compress command `%s', `%s' for sanity"
7356 compress decompress)
7357 (unless (zerop (tramp-send-command-and-check
7358 vec (format "echo %s | %s | %s"
7359 magic compress decompress) t))
7360 (throw 'next nil))
7361 (setq found t)))
7362
7363 ;; Did we find something?
7364 (if found
7365 (progn
7366 ;; Set connection properties.
7367 (tramp-message
7368 vec 5 "Using inline transfer compress command `%s'" compress)
7369 (tramp-set-connection-property vec "inline-compress" compress)
7370 (tramp-message
7371 vec 5 "Using inline transfer decompress command `%s'" decompress)
7372 (tramp-set-connection-property vec "inline-decompress" decompress))
7373
7374 (tramp-set-connection-property vec "inline-compress" nil)
7375 (tramp-set-connection-property vec "inline-decompress" nil)
7376 (tramp-message
7377 vec 2 "Couldn't find an inline transfer compress command")))))
7378
00d6fd04
MA
7379(defun tramp-compute-multi-hops (vec)
7380 "Expands VEC according to `tramp-default-proxies-alist'.
7381Gateway hops are already opened."
7382 (let ((target-alist `(,vec))
7383 (choices tramp-default-proxies-alist)
7384 item proxy)
7385
7386 ;; Look for proxy hosts to be passed.
7387 (while choices
7388 (setq item (pop choices)
70c11b0b 7389 proxy (eval (nth 2 item)))
00d6fd04
MA
7390 (when (and
7391 ;; host
70c11b0b 7392 (string-match (or (eval (nth 0 item)) "")
00d6fd04
MA
7393 (or (tramp-file-name-host (car target-alist)) ""))
7394 ;; user
70c11b0b 7395 (string-match (or (eval (nth 1 item)) "")
00d6fd04
MA
7396 (or (tramp-file-name-user (car target-alist)) "")))
7397 (if (null proxy)
7398 ;; No more hops needed.
7399 (setq choices nil)
7400 ;; Replace placeholders.
7401 (setq proxy
7402 (format-spec
7403 proxy
20b8ac83
MA
7404 (format-spec-make
7405 ?u (or (tramp-file-name-user (car target-alist)) "")
7406 ?h (or (tramp-file-name-host (car target-alist)) ""))))
00d6fd04
MA
7407 (with-parsed-tramp-file-name proxy l
7408 ;; Add the hop.
7409 (add-to-list 'target-alist l)
7410 ;; Start next search.
7411 (setq choices tramp-default-proxies-alist)))))
7412
7413 ;; Handle gateways.
8a4438b6
MA
7414 (when (and (boundp 'tramp-gw-tunnel-method)
7415 (string-match (format
7416 "^\\(%s\\|%s\\)$"
7417 (symbol-value 'tramp-gw-tunnel-method)
7418 (symbol-value 'tramp-gw-socks-method))
7419 (tramp-file-name-method (car target-alist))))
00d6fd04
MA
7420 (let ((gw (pop target-alist))
7421 (hop (pop target-alist)))
7422 ;; Is the method prepared for gateways?
7423 (unless (tramp-get-method-parameter
7424 (tramp-file-name-method hop) 'tramp-default-port)
7425 (tramp-error
7426 vec 'file-error
7427 "Method `%s' is not supported for gateway access."
7428 (tramp-file-name-method hop)))
7429 ;; Add default port if needed.
7430 (unless
7431 (string-match
7432 tramp-host-with-port-regexp (tramp-file-name-host hop))
7433 (aset hop 2
7434 (concat
7435 (tramp-file-name-host hop) tramp-prefix-port-format
7436 (number-to-string
7437 (tramp-get-method-parameter
7438 (tramp-file-name-method hop) 'tramp-default-port)))))
7439 ;; Open the gateway connection.
7440 (add-to-list
7441 'target-alist
7442 (vector
7443 (tramp-file-name-method hop) (tramp-file-name-user hop)
20b8ac83 7444 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil))
00d6fd04
MA
7445 ;; For the password prompt, we need the correct values.
7446 ;; Therefore, we must remember the gateway vector. But we
7447 ;; cannot do it as connection property, because it shouldn't
7448 ;; be persistent. And we have no started process yet either.
7449 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7450
7451 ;; Foreign and out-of-band methods are not supported for multi-hops.
7452 (when (cdr target-alist)
7453 (setq choices target-alist)
7454 (while choices
7455 (setq item (pop choices))
7456 (when
7457 (or
7458 (not
7459 (tramp-get-method-parameter
7460 (tramp-file-name-method item) 'tramp-login-program))
7461 (tramp-get-method-parameter
7462 (tramp-file-name-method item) 'tramp-copy-program))
7463 (tramp-error
7464 vec 'file-error
7465 "Method `%s' is not supported for multi-hops."
7466 (tramp-file-name-method item)))))
7467
2991e49f
MA
7468 ;; In case the host name is not used for the remote shell
7469 ;; command, the user could be misguided by applying a random
7470 ;; hostname.
7471 (let* ((v (car target-alist))
7472 (method (tramp-file-name-method v))
7473 (host (tramp-file-name-host v)))
7474 (unless
7475 (or
7476 ;; There are multi-hops.
7477 (cdr target-alist)
7478 ;; The host name is used for the remote shell command.
7479 (member
7480 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7481 ;; The host is local. We cannot use `tramp-local-host-p'
7482 ;; here, because it opens a connection as well.
b96e6899 7483 (string-match tramp-local-host-regexp host))
2991e49f 7484 (tramp-error
42bc9b6d
MA
7485 v 'file-error
7486 "Host `%s' looks like a remote host, `%s' can only use the local host"
7487 host method)))
2991e49f 7488
00d6fd04
MA
7489 ;; Result.
7490 target-alist))
7491
7492(defun tramp-maybe-open-connection (vec)
7493 "Maybe open a connection VEC.
fb7933a3
KG
7494Does not do anything if a connection is already open, but re-opens the
7495connection if a previous connection has died for some reason."
d8ac123e
MA
7496 (catch 'uname-changed
7497 (let ((p (tramp-get-connection-process vec))
20b8ac83 7498 (process-name (tramp-get-connection-property vec "process-name" nil))
d8ac123e
MA
7499 (process-environment (copy-sequence process-environment)))
7500
7501 ;; If too much time has passed since last command was sent, look
7502 ;; whether process is still alive. If it isn't, kill it. When
7503 ;; using ssh, it can sometimes happen that the remote end has
7504 ;; hung up but the local ssh client doesn't recognize this until
7505 ;; it tries to send some data to the remote end. So that's why
7506 ;; we try to send a command from time to time, then look again
7507 ;; whether the process is really alive.
7508 (condition-case nil
7509 (when (and (> (tramp-time-diff
7510 (current-time)
7511 (tramp-get-connection-property
7512 p "last-cmd-time" '(0 0 0)))
7513 60)
7514 p (processp p) (memq (process-status p) '(run open)))
7515 (tramp-send-command vec "echo are you awake" t t)
7516 (unless (and (memq (process-status p) '(run open))
7517 (tramp-wait-for-output p 10))
7518 ;; The error will be catched locally.
7519 (tramp-error vec 'file-error "Awake did fail")))
7520 (file-error
7521 (tramp-flush-connection-property vec)
7522 (tramp-flush-connection-property p)
7523 (delete-process p)
7524 (setq p nil)))
7525
7526 ;; New connection must be opened.
7527 (unless (and p (processp p) (memq (process-status p) '(run open)))
7528
7529 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7530 ;; messages from the beginning.
7531 (tramp-get-buffer vec)
20b8ac83
MA
7532 (with-progress-reporter
7533 vec 3
7534 (if (zerop (length (tramp-file-name-user vec)))
7535 (format "Opening connection for %s using %s"
7536 (tramp-file-name-host vec)
7537 (tramp-file-name-method vec))
7538 (format "Opening connection for %s@%s using %s"
7539 (tramp-file-name-user vec)
7540 (tramp-file-name-host vec)
7541 (tramp-file-name-method vec)))
7542
7543 ;; Start new process.
7544 (when (and p (processp p))
7545 (delete-process p))
7546 (setenv "TERM" tramp-terminal-type)
7547 (setenv "LC_ALL" "C")
7548 (setenv "PROMPT_COMMAND")
7549 (setenv "PS1" tramp-initial-end-of-output)
7550 (let* ((target-alist (tramp-compute-multi-hops vec))
7551 (process-connection-type tramp-process-connection-type)
7552 (process-adaptive-read-buffering nil)
7553 (coding-system-for-read nil)
7554 ;; This must be done in order to avoid our file name handler.
7555 (p (let ((default-directory
7556 (tramp-compat-temporary-file-directory)))
7557 (start-process
7558 (or process-name (tramp-buffer-name vec))
7559 (tramp-get-connection-buffer vec)
7560 tramp-encoding-shell))))
d8ac123e 7561
20b8ac83
MA
7562 (tramp-message
7563 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7564
7565 ;; Check whether process is alive.
7566 (tramp-set-process-query-on-exit-flag p nil)
7567 (tramp-barf-if-no-shell-prompt
7568 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7569
7570 ;; Now do all the connections as specified.
7571 (while target-alist
7572 (let* ((hop (car target-alist))
7573 (l-method (tramp-file-name-method hop))
7574 (l-user (tramp-file-name-user hop))
7575 (l-host (tramp-file-name-host hop))
7576 (l-port nil)
7577 (login-program
7578 (tramp-get-method-parameter
7579 l-method 'tramp-login-program))
7580 (login-args
7581 (tramp-get-method-parameter l-method 'tramp-login-args))
7582 (async-args
7583 (tramp-get-method-parameter l-method 'tramp-async-args))
7584 (gw-args
7585 (tramp-get-method-parameter l-method 'tramp-gw-args))
7586 (gw (tramp-get-file-property hop "" "gateway" nil))
7587 (g-method (and gw (tramp-file-name-method gw)))
7588 (g-user (and gw (tramp-file-name-user gw)))
7589 (g-host (and gw (tramp-file-name-host gw)))
7590 (command login-program)
7591 ;; We don't create the temporary file. In fact,
7592 ;; it is just a prefix for the ControlPath option
7593 ;; of ssh; the real temporary file has another
7594 ;; name, and it is created and protected by ssh.
7595 ;; It is also removed by ssh, when the connection
7596 ;; is closed.
7597 (tmpfile
7598 (tramp-set-connection-property
7599 p "temp-file"
7600 (make-temp-name
7601 (expand-file-name
7602 tramp-temp-name-prefix
7603 (tramp-compat-temporary-file-directory)))))
7604 spec)
7605
7606 ;; Add arguments for asynchrononous processes.
7607 (when (and process-name async-args)
7608 (setq login-args (append async-args login-args)))
7609
7610 ;; Add gateway arguments if necessary.
7611 (when (and gw gw-args)
7612 (setq login-args (append gw-args login-args)))
7613
7614 ;; Check for port number. Until now, there's no need
7615 ;; for handling like method, user, host.
7616 (when (string-match tramp-host-with-port-regexp l-host)
d8ac123e
MA
7617 (setq l-port (match-string 2 l-host)
7618 l-host (match-string 1 l-host)))
7619
20b8ac83
MA
7620 ;; Set variables for computing the prompt for reading
7621 ;; password. They can also be derived from a gateway.
7622 (setq tramp-current-method (or g-method l-method)
7623 tramp-current-user (or g-user l-user)
7624 tramp-current-host (or g-host l-host))
7625
7626 ;; Replace login-args place holders.
7627 (setq
7628 l-host (or l-host "")
7629 l-user (or l-user "")
7630 l-port (or l-port "")
7631 spec (format-spec-make
7632 ?h l-host ?u l-user ?p l-port ?t tmpfile)
7633 command
7634 (concat
7635 ;; We do not want to see the trailing local prompt in
7636 ;; `start-file-process'.
7637 (unless (memq system-type '(windows-nt)) "exec ")
7638 command " "
7639 (mapconcat
7640 (lambda (x)
7641 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7642 (unless (member "" x) (mapconcat 'identity x " ")))
7643 login-args " ")
7644 ;; Local shell could be a Windows COMSPEC. It
7645 ;; doesn't know the ";" syntax, but we must exit
7646 ;; always for `start-file-process'. "exec" does not
7647 ;; work either.
7648 (if (memq system-type '(windows-nt)) " && exit || exit")))
7649
7650 ;; Send the command.
7651 (tramp-message vec 3 "Sending command `%s'" command)
7652 (tramp-send-command vec command t t)
7653 (tramp-process-actions p vec tramp-actions-before-shell 60)
7654 (tramp-message
7655 vec 3 "Found remote shell prompt on `%s'" l-host))
7656 ;; Next hop.
7657 (setq target-alist (cdr target-alist)))
d8ac123e 7658
20b8ac83
MA
7659 ;; Make initial shell settings.
7660 (tramp-open-connection-setup-interactive-shell p vec)))))))
00d6fd04
MA
7661
7662(defun tramp-send-command (vec command &optional neveropen nooutput)
7663 "Send the COMMAND to connection VEC.
7664Erases temporary buffer before sending the command. If optional
7665arg NEVEROPEN is non-nil, never try to open the connection. This
7666is meant to be used from `tramp-maybe-open-connection' only. The
7667function waits for output unless NOOUTPUT is set."
7668 (unless neveropen (tramp-maybe-open-connection vec))
7669 (let ((p (tramp-get-connection-process vec)))
8950769a 7670 (when (tramp-get-connection-property p "remote-echo" nil)
00d6fd04
MA
7671 ;; We mark the command string that it can be erased in the output buffer.
7672 (tramp-set-connection-property p "check-remote-echo" t)
7673 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7674 (tramp-message vec 6 "%s" command)
7675 (tramp-send-string vec command)
7676 (unless nooutput (tramp-wait-for-output p))))
7677
00d6fd04 7678(defun tramp-wait-for-output (proc &optional timeout)
7e5686f0
MA
7679 "Wait for output from remote command."
7680 (unless (buffer-live-p (process-buffer proc))
7681 (delete-process proc)
7682 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
00d6fd04 7683 (with-current-buffer (process-buffer proc)
dab816a9 7684 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
bede3e9f 7685 ;; be leading escape sequences, which must be ignored.
dab816a9 7686 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
bede3e9f
MA
7687 ;; Sometimes, the commands do not return a newline but a
7688 ;; null byte before the shell prompt, for example "git
7689 ;; ls-files -c -z ...".
7690 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7691 (found (tramp-wait-for-regexp proc timeout regexp1)))
00d6fd04
MA
7692 (if found
7693 (let (buffer-read-only)
7e5686f0
MA
7694 ;; A simple-minded busybox has sent " ^H" sequences.
7695 ;; Delete them.
7696 (goto-char (point-min))
7697 (when (re-search-forward
7698 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7699 (forward-line 1)
7700 (delete-region (point-min) (point)))
7701 ;; Delete the prompt.
00d6fd04 7702 (goto-char (point-max))
0664ff72 7703 (re-search-backward regexp nil t)
00d6fd04
MA
7704 (delete-region (point) (point-max)))
7705 (if timeout
7706 (tramp-error
7707 proc 'file-error
7708 "[[Remote prompt `%s' not found in %d secs]]"
7709 tramp-end-of-output timeout)
7710 (tramp-error
7711 proc 'file-error
7712 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7713 ;; Return value is whether end-of-output sentinel was found.
7714 found)))
fb7933a3 7715
b593f105
MA
7716(defun tramp-send-command-and-check
7717 (vec command &optional subshell dont-suppress-err)
fb7933a3 7718 "Run COMMAND and check its exit status.
fb7933a3
KG
7719Sends `echo $?' along with the COMMAND for checking the exit status. If
7720COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7721
b593f105
MA
7722If the optional argument SUBSHELL is non-nil, the command is
7723executed in a subshell, ie surrounded by parentheses. If
7724DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
00d6fd04
MA
7725 (tramp-send-command
7726 vec
7727 (concat (if subshell "( " "")
7728 command
b593f105 7729 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
00d6fd04 7730 "echo tramp_exit_status $?"
b593f105 7731 (if subshell " )" "")))
00d6fd04
MA
7732 (with-current-buffer (tramp-get-connection-buffer vec)
7733 (goto-char (point-max))
7734 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7735 (tramp-error
7736 vec 'file-error "Couldn't find exit status of `%s'" command))
7737 (skip-chars-forward "^ ")
7738 (prog1
7739 (read (current-buffer))
7740 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7741
7742(defun tramp-barf-unless-okay (vec command fmt &rest args)
fb7933a3
KG
7743 "Run COMMAND, check exit status, throw error if exit status not okay.
7744Similar to `tramp-send-command-and-check' but accepts two more arguments
7745FMT and ARGS which are passed to `error'."
00d6fd04
MA
7746 (unless (zerop (tramp-send-command-and-check vec command))
7747 (apply 'tramp-error vec 'file-error fmt args)))
7748
7749(defun tramp-send-command-and-read (vec command)
7750 "Run COMMAND and return the output, which must be a Lisp expression.
7751In case there is no valid Lisp expression, it raises an error"
7752 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7753 (with-current-buffer (tramp-get-connection-buffer vec)
7754 ;; Read the expression.
7755 (goto-char (point-min))
7756 (condition-case nil
7757 (prog1 (read (current-buffer))
7758 ;; Error handling.
9e6ab520 7759 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
9ce8462a 7760 (error nil)))
00d6fd04
MA
7761 (error (tramp-error
7762 vec 'file-error
7763 "`%s' does not return a valid Lisp expression: `%s'"
7764 command (buffer-string))))))
fb7933a3 7765
7432277c
KG
7766;; It seems that Tru64 Unix does not like it if long strings are sent
7767;; to it in one go. (This happens when sending the Perl
7768;; `file-attributes' implementation, for instance.) Therefore, we
27e813fe 7769;; have this function which sends the string in chunks.
00d6fd04
MA
7770(defun tramp-send-string (vec string)
7771 "Send the STRING via connection VEC.
7432277c
KG
7772
7773The STRING is expected to use Unix line-endings, but the lines sent to
7774the remote host use line-endings as defined in the variable
00d6fd04
MA
7775`tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7776 (let* ((p (tramp-get-connection-process vec))
7777 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7778 (unless p
7779 (tramp-error
7780 vec 'file-error "Can't send string to remote host -- not logged in"))
7781 (tramp-set-connection-property p "last-cmd-time" (current-time))
7782 (tramp-message vec 10 "%s" string)
7783 (with-current-buffer (tramp-get-connection-buffer vec)
7784 ;; Clean up the buffer. We cannot call `erase-buffer' because
7785 ;; narrowing might be in effect.
7786 (let (buffer-read-only) (delete-region (point-min) (point-max)))
27e813fe 7787 ;; Replace "\n" by `tramp-rsh-end-of-line'.
00d6fd04
MA
7788 (setq string
7789 (mapconcat 'identity
70c11b0b 7790 (tramp-compat-split-string string "\n")
00d6fd04
MA
7791 tramp-rsh-end-of-line))
7792 (unless (or (string= string "")
7793 (string-equal (substring string -1) tramp-rsh-end-of-line))
7794 (setq string (concat string tramp-rsh-end-of-line)))
27e813fe 7795 ;; Send the string.
00d6fd04
MA
7796 (if (and chunksize (not (zerop chunksize)))
7797 (let ((pos 0)
7798 (end (length string)))
7799 (while (< pos end)
7800 (tramp-message
7801 vec 10 "Sending chunk from %s to %s"
7802 pos (min (+ pos chunksize) end))
7803 (process-send-string
7804 p (substring string pos (min (+ pos chunksize) end)))
7805 (setq pos (+ pos chunksize))))
7806 (process-send-string p string)))))
fb7933a3
KG
7807
7808(defun tramp-mode-string-to-int (mode-string)
7809 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
f3c071dd
MA
7810 (let* (case-fold-search
7811 (mode-chars (string-to-vector mode-string))
fb7933a3
KG
7812 (owner-read (aref mode-chars 1))
7813 (owner-write (aref mode-chars 2))
7814 (owner-execute-or-setid (aref mode-chars 3))
7815 (group-read (aref mode-chars 4))
7816 (group-write (aref mode-chars 5))
7817 (group-execute-or-setid (aref mode-chars 6))
7818 (other-read (aref mode-chars 7))
7819 (other-write (aref mode-chars 8))
7820 (other-execute-or-sticky (aref mode-chars 9)))
7821 (save-match-data
7822 (logior
f3c071dd
MA
7823 (cond
7824 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7825 ((char-equal owner-read ?-) 0)
7826 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7827 (cond
7828 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7829 ((char-equal owner-write ?-) 0)
7830 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7831 (cond
7832 ((char-equal owner-execute-or-setid ?x)
7833 (tramp-octal-to-decimal "00100"))
7834 ((char-equal owner-execute-or-setid ?S)
7835 (tramp-octal-to-decimal "04000"))
7836 ((char-equal owner-execute-or-setid ?s)
7837 (tramp-octal-to-decimal "04100"))
7838 ((char-equal owner-execute-or-setid ?-) 0)
7839 (t (error "Fourth char `%c' must be one of `xsS-'"
7840 owner-execute-or-setid)))
7841 (cond
7842 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7843 ((char-equal group-read ?-) 0)
7844 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7845 (cond
7846 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7847 ((char-equal group-write ?-) 0)
7848 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7849 (cond
7850 ((char-equal group-execute-or-setid ?x)
7851 (tramp-octal-to-decimal "00010"))
7852 ((char-equal group-execute-or-setid ?S)
7853 (tramp-octal-to-decimal "02000"))
7854 ((char-equal group-execute-or-setid ?s)
7855 (tramp-octal-to-decimal "02010"))
7856 ((char-equal group-execute-or-setid ?-) 0)
7857 (t (error "Seventh char `%c' must be one of `xsS-'"
7858 group-execute-or-setid)))
7859 (cond
7860 ((char-equal other-read ?r)
7861 (tramp-octal-to-decimal "00004"))
7862 ((char-equal other-read ?-) 0)
7863 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7864 (cond
7865 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7866 ((char-equal other-write ?-) 0)
fb7933a3 7867 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
f3c071dd
MA
7868 (cond
7869 ((char-equal other-execute-or-sticky ?x)
7870 (tramp-octal-to-decimal "00001"))
7871 ((char-equal other-execute-or-sticky ?T)
7872 (tramp-octal-to-decimal "01000"))
7873 ((char-equal other-execute-or-sticky ?t)
7874 (tramp-octal-to-decimal "01001"))
7875 ((char-equal other-execute-or-sticky ?-) 0)
7876 (t (error "Tenth char `%c' must be one of `xtT-'"
7877 other-execute-or-sticky)))))))
fb7933a3 7878
00d6fd04
MA
7879(defun tramp-convert-file-attributes (vec attr)
7880 "Convert file-attributes ATTR generated by perl script, stat or ls.
c82c5727
LH
7881Convert file mode bits to string and set virtual device number.
7882Return ATTR."
680db9ac
MA
7883 (when attr
7884 ;; Convert last access time.
7885 (unless (listp (nth 4 attr))
7886 (setcar (nthcdr 4 attr)
7887 (list (floor (nth 4 attr) 65536)
7888 (floor (mod (nth 4 attr) 65536)))))
7889 ;; Convert last modification time.
7890 (unless (listp (nth 5 attr))
7891 (setcar (nthcdr 5 attr)
7892 (list (floor (nth 5 attr) 65536)
7893 (floor (mod (nth 5 attr) 65536)))))
7894 ;; Convert last status change time.
7895 (unless (listp (nth 6 attr))
7896 (setcar (nthcdr 6 attr)
7897 (list (floor (nth 6 attr) 65536)
7898 (floor (mod (nth 6 attr) 65536)))))
7899 ;; Convert file size.
7900 (when (< (nth 7 attr) 0)
7901 (setcar (nthcdr 7 attr) -1))
7902 (when (and (floatp (nth 7 attr))
7903 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7904 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7905 ;; Convert file mode bits to string.
7906 (unless (stringp (nth 8 attr))
7907 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7908 (when (stringp (car attr))
7909 (aset (nth 8 attr) 0 ?l)))
7910 ;; Convert directory indication bit.
7911 (when (string-match "^d" (nth 8 attr))
7912 (setcar attr t))
7913 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7914 (when (consp (car attr))
7915 (if (and (stringp (caar attr))
7916 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7917 (setcar attr (match-string 1 (caar attr)))
7918 (setcar attr nil)))
7919 ;; Set file's gid change bit.
7920 (setcar (nthcdr 9 attr)
7921 (if (numberp (nth 3 attr))
7922 (not (= (nth 3 attr)
7923 (tramp-get-remote-gid vec 'integer)))
7924 (not (string-equal
7925 (nth 3 attr)
7926 (tramp-get-remote-gid vec 'string)))))
7927 ;; Convert inode.
7928 (unless (listp (nth 10 attr))
7929 (setcar (nthcdr 10 attr)
7930 (condition-case nil
7931 (cons (floor (nth 10 attr) 65536)
7932 (floor (mod (nth 10 attr) 65536)))
7933 ;; Inodes can be incredible huge. We must hide this.
7934 (error (tramp-get-inode vec)))))
7935 ;; Set virtual device number.
7936 (setcar (nthcdr 11 attr)
7937 (tramp-get-device vec))
7938 attr))
c82c5727 7939
293c24f9
MA
7940(defun tramp-check-cached-permissions (vec access)
7941 "Check `file-attributes' caches for VEC.
7942Return t if according to the cache access type ACCESS is known to
7943be granted."
7944 (let ((result nil)
7945 (offset (cond
7946 ((eq ?r access) 1)
7947 ((eq ?w access) 2)
7948 ((eq ?x access) 3))))
7949 (dolist (suffix '("string" "integer") result)
7950 (setq
7951 result
7952 (or
7953 result
7954 (let ((file-attr
7955 (tramp-get-file-property
7956 vec (tramp-file-name-localname vec)
7957 (concat "file-attributes-" suffix) nil))
7958 (remote-uid
7959 (tramp-get-connection-property
7960 vec (concat "uid-" suffix) nil))
7961 (remote-gid
7962 (tramp-get-connection-property
7963 vec (concat "gid-" suffix) nil)))
7964 (and
7965 file-attr
7966 (or
7967 ;; Not a symlink
7968 (eq t (car file-attr))
7969 (null (car file-attr)))
7970 (or
7971 ;; World accessible.
7972 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7973 ;; User accessible and owned by user.
7974 (and
7975 (eq access (aref (nth 8 file-attr) offset))
7976 (equal remote-uid (nth 2 file-attr)))
7977 ;; Group accessible and owned by user's
7978 ;; principal group.
7979 (and
7980 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7981 (equal remote-gid (nth 3 file-attr)))))))))))
7982
ce3f516f 7983(defun tramp-get-inode (vec)
00d6fd04
MA
7984 "Returns the virtual inode number.
7985If it doesn't exist, generate a new one."
ce3f516f
MA
7986 (let ((string (tramp-make-tramp-file-name
7987 (tramp-file-name-method vec)
7988 (tramp-file-name-user vec)
7989 (tramp-file-name-host vec)
7990 "")))
00d6fd04
MA
7991 (unless (assoc string tramp-inodes)
7992 (add-to-list 'tramp-inodes
7993 (list string (length tramp-inodes))))
7994 (nth 1 (assoc string tramp-inodes))))
7995
7996(defun tramp-get-device (vec)
c82c5727
LH
7997 "Returns the virtual device number.
7998If it doesn't exist, generate a new one."
00d6fd04
MA
7999 (let ((string (tramp-make-tramp-file-name
8000 (tramp-file-name-method vec)
8001 (tramp-file-name-user vec)
8002 (tramp-file-name-host vec)
8003 "")))
c82c5727
LH
8004 (unless (assoc string tramp-devices)
8005 (add-to-list 'tramp-devices
8006 (list string (length tramp-devices))))
b946a456 8007 (cons -1 (nth 1 (assoc string tramp-devices)))))
fb7933a3
KG
8008
8009(defun tramp-file-mode-from-int (mode)
8010 "Turn an integer representing a file mode into an ls(1)-like string."
8011 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
8012 (user (logand (lsh mode -6) 7))
8013 (group (logand (lsh mode -3) 7))
8014 (other (logand (lsh mode -0) 7))
8015 (suid (> (logand (lsh mode -9) 4) 0))
8016 (sgid (> (logand (lsh mode -9) 2) 0))
8017 (sticky (> (logand (lsh mode -9) 1) 0)))
8018 (setq user (tramp-file-mode-permissions user suid "s"))
8019 (setq group (tramp-file-mode-permissions group sgid "s"))
8020 (setq other (tramp-file-mode-permissions other sticky "t"))
8021 (concat type user group other)))
8022
fb7933a3
KG
8023(defun tramp-file-mode-permissions (perm suid suid-text)
8024 "Convert a permission bitset into a string.
8025This is used internally by `tramp-file-mode-from-int'."
8026 (let ((r (> (logand perm 4) 0))
8027 (w (> (logand perm 2) 0))
8028 (x (> (logand perm 1) 0)))
8029 (concat (or (and r "r") "-")
8030 (or (and w "w") "-")
8031 (or (and suid x suid-text) ; suid, execute
8032 (and suid (upcase suid-text)) ; suid, !execute
8033 (and x "x") "-")))) ; !suid
8034
fb7933a3
KG
8035(defun tramp-decimal-to-octal (i)
8036 "Return a string consisting of the octal digits of I.
8037Not actually used. Use `(format \"%o\" i)' instead?"
8038 (cond ((< i 0) (error "Cannot convert negative number to octal"))
8039 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
8040 ((zerop i) "0")
8041 (t (concat (tramp-decimal-to-octal (/ i 8))
8042 (number-to-string (% i 8))))))
8043
fb7933a3
KG
8044;; Kudos to Gerd Moellmann for this suggestion.
8045(defun tramp-octal-to-decimal (ostr)
8046 "Given a string of octal digits, return a decimal number."
8047 (let ((x (or ostr "")))
8048 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
8049 (unless (string-match "\\`[0-7]*\\'" x)
8050 (error "Non-octal junk in string `%s'" x))
8051 (string-to-number ostr 8)))
8052
8053(defun tramp-shell-case-fold (string)
8054 "Converts STRING to shell glob pattern which ignores case."
8055 (mapconcat
8056 (lambda (c)
8057 (if (equal (downcase c) (upcase c))
8058 (vector c)
8059 (format "[%c%c]" (downcase c) (upcase c))))
8060 string
8061 ""))
8062
8063
bf247b6e 8064;; ------------------------------------------------------------
a4aeb9a4 8065;; -- Tramp file names --
bf247b6e 8066;; ------------------------------------------------------------
fb7933a3
KG
8067;; Conversion functions between external representation and
8068;; internal data structure. Convenience functions for internal
8069;; data structure.
8070
00d6fd04 8071(defun tramp-file-name-p (vec)
20b8ac83 8072 "Check, whether VEC is a Tramp object."
00d6fd04
MA
8073 (and (vectorp vec) (= 4 (length vec))))
8074
8075(defun tramp-file-name-method (vec)
8076 "Return method component of VEC."
8077 (and (tramp-file-name-p vec) (aref vec 0)))
8078
8079(defun tramp-file-name-user (vec)
8080 "Return user component of VEC."
8081 (and (tramp-file-name-p vec) (aref vec 1)))
8082
8083(defun tramp-file-name-host (vec)
8084 "Return host component of VEC."
8085 (and (tramp-file-name-p vec) (aref vec 2)))
8086
8087(defun tramp-file-name-localname (vec)
8088 "Return localname component of VEC."
8089 (and (tramp-file-name-p vec) (aref vec 3)))
8090
dea31ca6 8091;; The user part of a Tramp file name vector can be of kind
b96e6899 8092;; "user%domain". Sometimes, we must extract these parts.
dea31ca6
MA
8093(defun tramp-file-name-real-user (vec)
8094 "Return the user name of VEC without domain."
a17632c1
MA
8095 (save-match-data
8096 (let ((user (tramp-file-name-user vec)))
8097 (if (and (stringp user)
8098 (string-match tramp-user-with-domain-regexp user))
8099 (match-string 1 user)
8100 user))))
dea31ca6
MA
8101
8102(defun tramp-file-name-domain (vec)
8103 "Return the domain name of VEC."
a17632c1
MA
8104 (save-match-data
8105 (let ((user (tramp-file-name-user vec)))
8106 (and (stringp user)
8107 (string-match tramp-user-with-domain-regexp user)
8108 (match-string 2 user)))))
dea31ca6 8109
00d6fd04
MA
8110;; The host part of a Tramp file name vector can be of kind
8111;; "host#port". Sometimes, we must extract these parts.
8a4438b6 8112(defun tramp-file-name-real-host (vec)
00d6fd04 8113 "Return the host name of VEC without port."
a17632c1
MA
8114 (save-match-data
8115 (let ((host (tramp-file-name-host vec)))
8116 (if (and (stringp host)
8117 (string-match tramp-host-with-port-regexp host))
8118 (match-string 1 host)
8119 host))))
00d6fd04 8120
8a4438b6 8121(defun tramp-file-name-port (vec)
00d6fd04 8122 "Return the port number of VEC."
a17632c1
MA
8123 (save-match-data
8124 (let ((host (tramp-file-name-host vec)))
8125 (and (stringp host)
8126 (string-match tramp-host-with-port-regexp host)
8127 (string-to-number (match-string 2 host))))))
fb7933a3
KG
8128
8129(defun tramp-tramp-file-p (name)
a09dc9bf 8130 "Return t if NAME is a string with Tramp file name syntax."
fb7933a3 8131 (save-match-data
a09dc9bf 8132 (and (stringp name) (string-match tramp-file-name-regexp name))))
bf247b6e 8133
8a4438b6 8134(defun tramp-find-method (method user host)
00d6fd04
MA
8135 "Return the right method string to use.
8136This is METHOD, if non-nil. Otherwise, do a lookup in
8137`tramp-default-method-alist'."
8138 (or method
8139 (let ((choices tramp-default-method-alist)
8140 lmethod item)
8141 (while choices
8142 (setq item (pop choices))
8143 (when (and (string-match (or (nth 0 item) "") (or host ""))
8144 (string-match (or (nth 1 item) "") (or user "")))
8145 (setq lmethod (nth 2 item))
8146 (setq choices nil)))
8147 lmethod)
8148 tramp-default-method))
8149
8a4438b6 8150(defun tramp-find-user (method user host)
00d6fd04
MA
8151 "Return the right user string to use.
8152This is USER, if non-nil. Otherwise, do a lookup in
8153`tramp-default-user-alist'."
8154 (or user
8155 (let ((choices tramp-default-user-alist)
8156 luser item)
8157 (while choices
8158 (setq item (pop choices))
8159 (when (and (string-match (or (nth 0 item) "") (or method ""))
8160 (string-match (or (nth 1 item) "") (or host "")))
8161 (setq luser (nth 2 item))
8162 (setq choices nil)))
8163 luser)
8164 tramp-default-user))
8165
8a4438b6 8166(defun tramp-find-host (method user host)
00d6fd04
MA
8167 "Return the right host string to use.
8168This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
8169 (or (and (> (length host) 0) host)
8170 tramp-default-host))
8171
9ce8462a 8172(defun tramp-dissect-file-name (name &optional nodefault)
00d6fd04 8173 "Return a `tramp-file-name' structure.
9ce8462a
MA
8174The structure consists of remote method, remote user, remote host
8175and localname (file name on remote host). If NODEFAULT is
8176non-nil, the file name parts are not expanded to their default
8177values."
4007ba5b 8178 (save-match-data
00d6fd04 8179 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
a4aeb9a4 8180 (unless match (error "Not a Tramp file name: %s" name))
00d6fd04
MA
8181 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
8182 (user (match-string (nth 2 tramp-file-name-structure) name))
8183 (host (match-string (nth 3 tramp-file-name-structure) name))
8184 (localname (match-string (nth 4 tramp-file-name-structure) name)))
5d449a36
MA
8185 (when (member method '("multi" "multiu"))
8186 (error
8187 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
8188 method))
b96e6899
MA
8189 (when host
8190 (when (string-match tramp-prefix-ipv6-regexp host)
8191 (setq host (replace-match "" nil t host)))
8192 (when (string-match tramp-postfix-ipv6-regexp host)
8193 (setq host (replace-match "" nil t host))))
9ce8462a
MA
8194 (if nodefault
8195 (vector method user host localname)
8196 (vector
8197 (tramp-find-method method user host)
8198 (tramp-find-user method user host)
8199 (tramp-find-host method user host)
8200 localname))))))
00d6fd04
MA
8201
8202(defun tramp-equal-remote (file1 file2)
20b8ac83 8203 "Check, whether the remote parts of FILE1 and FILE2 are identical.
00d6fd04
MA
8204The check depends on method, user and host name of the files. If
8205one of the components is missing, the default values are used.
8206The local file name parts of FILE1 and FILE2 are not taken into
8207account.
fb7933a3 8208
00d6fd04
MA
8209Example:
8210
8211 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
8212
8213would yield `t'. On the other hand, the following check results in nil:
8214
8215 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
9e6ab520
MA
8216 (and (stringp (file-remote-p file1))
8217 (stringp (file-remote-p file2))
94be87e8 8218 (string-equal (file-remote-p file1) (file-remote-p file2))))
00d6fd04
MA
8219
8220(defun tramp-make-tramp-file-name (method user host localname)
8221 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
8222 (concat tramp-prefix-format
8223 (when (not (zerop (length method)))
8224 (concat method tramp-postfix-method-format))
8225 (when (not (zerop (length user)))
8226 (concat user tramp-postfix-user-format))
b96e6899
MA
8227 (when host
8228 (if (string-match tramp-ipv6-regexp host)
8229 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8230 host))
8231 tramp-postfix-host-format
00d6fd04
MA
8232 (when localname localname)))
8233
8234(defun tramp-completion-make-tramp-file-name (method user host localname)
8235 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
8236It must not be a complete Tramp file name, but as long as there are
8237necessary only. This function will be used in file name completion."
8238 (concat tramp-prefix-format
8239 (when (not (zerop (length method)))
8240 (concat method tramp-postfix-method-format))
8241 (when (not (zerop (length user)))
8242 (concat user tramp-postfix-user-format))
8243 (when (not (zerop (length host)))
b96e6899
MA
8244 (concat
8245 (if (string-match tramp-ipv6-regexp host)
8246 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8247 host)
8248 tramp-postfix-host-format))
00d6fd04
MA
8249 (when localname localname)))
8250
8251(defun tramp-make-copy-program-file-name (vec)
8252 "Create a file name suitable to be passed to `rcp' and workalikes."
8253 (let ((user (tramp-file-name-user vec))
0f205eee 8254 (host (tramp-file-name-real-host vec))
00d6fd04
MA
8255 (localname (tramp-shell-quote-argument
8256 (tramp-file-name-localname vec))))
8257 (if (not (zerop (length user)))
8258 (format "%s@%s:%s" user host localname)
8259 (format "%s:%s" host localname))))
8260
7f49fe46 8261(defun tramp-method-out-of-band-p (vec size)
38c65fca 8262 "Return t if this is an out-of-band method, nil otherwise."
7f49fe46
MA
8263 (and
8264 ;; It shall be an out-of-band method.
8265 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
8266 ;; Either the file size is large enough, or (in rare cases) there
8267 ;; does not exist a remote encoding.
20b8ac83
MA
8268 (or (null tramp-copy-size-limit)
8269 (> size tramp-copy-size-limit)
8270 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
fb7933a3 8271
0f205eee
MA
8272(defun tramp-local-host-p (vec)
8273 "Return t if this points to the local host, nil otherwise."
c992abdb
MA
8274 ;; We cannot use `tramp-file-name-real-host'. A port is an
8275 ;; indication for an ssh tunnel or alike.
8276 (let ((host (tramp-file-name-host vec)))
0f205eee
MA
8277 (and
8278 (stringp host)
b96e6899 8279 (string-match tramp-local-host-regexp host)
46bcd78c
MA
8280 ;; The method shall be applied to one of the shell file name
8281 ;; handler. `tramp-local-host-p' is also called for "smb" and
8282 ;; alike, where it must fail.
8283 (tramp-get-method-parameter
8284 (tramp-file-name-method vec) 'tramp-login-program)
a0a5183a
MA
8285 ;; The local temp directory must be writable for the other user.
8286 (file-writable-p
8287 (tramp-make-tramp-file-name
8288 (tramp-file-name-method vec)
8289 (tramp-file-name-user vec)
8290 host
93c3eb7c
MA
8291 (tramp-compat-temporary-file-directory)))
8292 ;; On some systems, chown runs only for root.
8293 (or (zerop (user-uid))
8294 (zerop (tramp-get-remote-uid vec 'integer))))))
0f205eee 8295
fb7933a3
KG
8296;; Variables local to connection.
8297
f84638eb 8298(defun tramp-get-remote-path (vec)
70c11b0b
MA
8299 (with-connection-property
8300 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8301 ;; cache the result for the session only. Otherwise, the result
8302 ;; is cached persistently.
8303 (if (memq 'tramp-own-remote-path tramp-remote-path)
8304 (tramp-get-connection-process vec)
8305 vec)
8306 "remote-path"
20b8ac83 8307 (let* ((remote-path (copy-tree tramp-remote-path))
70c11b0b
MA
8308 (elt1 (memq 'tramp-default-remote-path remote-path))
8309 (elt2 (memq 'tramp-own-remote-path remote-path))
f84638eb 8310 (default-remote-path
70c11b0b 8311 (when elt1
f84638eb 8312 (condition-case nil
70c11b0b
MA
8313 (tramp-send-command-and-read
8314 vec "echo \\\"`getconf PATH`\\\"")
f84638eb
MA
8315 ;; Default if "getconf" is not available.
8316 (error
8317 (tramp-message
8318 vec 3
8319 "`getconf PATH' not successful, using default value \"%s\"."
8320 "/bin:/usr/bin")
70c11b0b
MA
8321 "/bin:/usr/bin"))))
8322 (own-remote-path
8323 (when elt2
8324 (condition-case nil
8325 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8326 ;; Default if "getconf" is not available.
8327 (error
8328 (tramp-message
8329 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8330 nil)))))
8331
8332 ;; Replace place holder `tramp-default-remote-path'.
8333 (when elt1
8334 (setcdr elt1
f84638eb 8335 (append
70c11b0b
MA
8336 (tramp-compat-split-string default-remote-path ":")
8337 (cdr elt1)))
f84638eb
MA
8338 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8339
70c11b0b
MA
8340 ;; Replace place holder `tramp-own-remote-path'.
8341 (when elt2
8342 (setcdr elt2
8343 (append
8344 (tramp-compat-split-string own-remote-path ":")
8345 (cdr elt2)))
8346 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8347
8348 ;; Remove double entries.
8349 (setq elt1 remote-path)
8350 (while (consp elt1)
8351 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8352 (setcar elt2 nil))
8353 (setq elt1 (cdr elt1)))
8354
f84638eb
MA
8355 ;; Remove non-existing directories.
8356 (delq
8357 nil
8358 (mapcar
8359 (lambda (x)
8360 (and
70c11b0b
MA
8361 (stringp x)
8362 (file-directory-p
8363 (tramp-make-tramp-file-name
8364 (tramp-file-name-method vec)
8365 (tramp-file-name-user vec)
8366 (tramp-file-name-host vec)
8367 x))
f84638eb
MA
8368 x))
8369 remote-path)))))
8370
a4aeb9a4
MA
8371(defun tramp-get-remote-tmpdir (vec)
8372 (with-connection-property vec "tmp-directory"
8373 (let ((dir (tramp-shell-quote-argument "/tmp")))
8374 (if (and (zerop
8375 (tramp-send-command-and-check
8376 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8377 (zerop
8378 (tramp-send-command-and-check
8379 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8380 dir
8381 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8382
00d6fd04
MA
8383(defun tramp-get-ls-command (vec)
8384 (with-connection-property vec "ls"
946a5aeb
MA
8385 (tramp-message vec 5 "Finding a suitable `ls' command")
8386 (or
8387 (catch 'ls-found
8388 (dolist (cmd '("ls" "gnuls" "gls"))
8389 (let ((dl (tramp-get-remote-path vec))
8390 result)
8391 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
7e5686f0
MA
8392 ;; Check parameters. On busybox, "ls" output coloring is
8393 ;; enabled by default sometimes. So we try to disable it
8394 ;; when possible. $LS_COLORING is not supported there.
20b8ac83
MA
8395 ;; Some "ls" versions are sensible wrt the order of
8396 ;; arguments, they fail when "-al" is after the
8397 ;; "--color=never" argument (for example on FreeBSD).
946a5aeb
MA
8398 (when (zerop (tramp-send-command-and-check
8399 vec (format "%s -lnd /" result)))
7e5686f0 8400 (when (zerop (tramp-send-command-and-check
20b8ac83
MA
8401 vec (format
8402 "%s --color=never -al /dev/null" result)))
7e5686f0 8403 (setq result (concat result " --color=never")))
946a5aeb
MA
8404 (throw 'ls-found result))
8405 (setq dl (cdr dl))))))
8406 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
00d6fd04 8407
8e754ea2
MA
8408(defun tramp-get-ls-command-with-dired (vec)
8409 (save-match-data
8410 (with-connection-property vec "ls-dired"
8411 (tramp-message vec 5 "Checking, whether `ls --dired' works")
20b8ac83
MA
8412 ;; Some "ls" versions are sensible wrt the order of arguments,
8413 ;; they fail when "-al" is after the "--dired" argument (for
8414 ;; example on FreeBSD).
8e754ea2 8415 (zerop (tramp-send-command-and-check
20b8ac83
MA
8416 vec (format "%s --dired -al /dev/null"
8417 (tramp-get-ls-command vec)))))))
8e754ea2 8418
00d6fd04
MA
8419(defun tramp-get-test-command (vec)
8420 (with-connection-property vec "test"
946a5aeb
MA
8421 (tramp-message vec 5 "Finding a suitable `test' command")
8422 (if (zerop (tramp-send-command-and-check vec "test 0"))
8423 "test"
8424 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
00d6fd04
MA
8425
8426(defun tramp-get-test-nt-command (vec)
8427 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8428 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8429 ;; for otherwise the shell crashes.
8430 (with-connection-property vec "test-nt"
8431 (or
8432 (progn
8433 (tramp-send-command
8434 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8435 (with-current-buffer (tramp-get-buffer vec)
8436 (goto-char (point-min))
a0a5183a 8437 (when (looking-at (regexp-quote tramp-end-of-output))
00d6fd04
MA
8438 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8439 (progn
8440 (tramp-send-command
8441 vec
8442 (format
8443 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8444 (tramp-get-test-command vec)))
8445 "tramp_test_nt %s %s"))))
8446
8447(defun tramp-get-file-exists-command (vec)
8448 (with-connection-property vec "file-exists"
946a5aeb
MA
8449 (tramp-message vec 5 "Finding command to check if file exists")
8450 (tramp-find-file-exists-command vec)))
00d6fd04
MA
8451
8452(defun tramp-get-remote-ln (vec)
8453 (with-connection-property vec "ln"
946a5aeb
MA
8454 (tramp-message vec 5 "Finding a suitable `ln' command")
8455 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
00d6fd04
MA
8456
8457(defun tramp-get-remote-perl (vec)
8458 (with-connection-property vec "perl"
946a5aeb 8459 (tramp-message vec 5 "Finding a suitable `perl' command")
293c24f9
MA
8460 (let ((result
8461 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8462 (tramp-find-executable
8463 vec "perl" (tramp-get-remote-path vec)))))
8464 ;; We must check also for some Perl modules.
8465 (when result
8466 (with-connection-property vec "perl-file-spec"
8467 (zerop
8468 (tramp-send-command-and-check
8469 vec (format "%s -e 'use File::Spec;'" result))))
8470 (with-connection-property vec "perl-cwd-realpath"
8471 (zerop
8472 (tramp-send-command-and-check
8473 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8474 result)))
00d6fd04
MA
8475
8476(defun tramp-get-remote-stat (vec)
8477 (with-connection-property vec "stat"
946a5aeb
MA
8478 (tramp-message vec 5 "Finding a suitable `stat' command")
8479 (let ((result (tramp-find-executable
8480 vec "stat" (tramp-get-remote-path vec)))
8481 tmp)
8482 ;; Check whether stat(1) returns usable syntax. %s does not
8483 ;; work on older AIX systems.
8484 (when result
8485 (setq tmp
8486 ;; We don't want to display an error message.
8487 (with-temp-message (or (current-message) "")
8488 (condition-case nil
8489 (tramp-send-command-and-read
8490 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8491 (error nil))))
8492 (unless (and (listp tmp) (stringp (car tmp))
8493 (string-match "^./.$" (car tmp))
8494 (integerp (cadr tmp)))
8495 (setq result nil)))
8496 result)))
fb7933a3 8497
293c24f9
MA
8498(defun tramp-get-remote-readlink (vec)
8499 (with-connection-property vec "readlink"
8500 (tramp-message vec 5 "Finding a suitable `readlink' command")
8501 (let ((result (tramp-find-executable
8502 vec "readlink" (tramp-get-remote-path vec))))
8503 (when (and result
8504 ;; We don't want to display an error message.
8505 (with-temp-message (or (current-message) "")
8506 (condition-case nil
8507 (zerop
8508 (tramp-send-command-and-check
8509 vec (format "%s --canonicalize-missing /" result)))
8510 (error nil))))
8511 result))))
8512
20b8ac83
MA
8513(defun tramp-get-remote-trash (vec)
8514 (with-connection-property vec "trash"
8515 (tramp-message vec 5 "Finding a suitable `trash' command")
8516 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
8517
00d6fd04
MA
8518(defun tramp-get-remote-id (vec)
8519 (with-connection-property vec "id"
946a5aeb
MA
8520 (tramp-message vec 5 "Finding POSIX `id' command")
8521 (or
8522 (catch 'id-found
8523 (let ((dl (tramp-get-remote-path vec))
8524 result)
8525 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8526 ;; Check POSIX parameter.
8527 (when (zerop (tramp-send-command-and-check
8528 vec (format "%s -u" result)))
8529 (throw 'id-found result))
8530 (setq dl (cdr dl)))))
8531 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
00d6fd04
MA
8532
8533(defun tramp-get-remote-uid (vec id-format)
8534 (with-connection-property vec (format "uid-%s" id-format)
8535 (let ((res (tramp-send-command-and-read
8536 vec
8537 (format "%s -u%s %s"
8538 (tramp-get-remote-id vec)
8539 (if (equal id-format 'integer) "" "n")
8540 (if (equal id-format 'integer)
8541 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8542 ;; The command might not always return a number.
8543 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8544
8545(defun tramp-get-remote-gid (vec id-format)
8546 (with-connection-property vec (format "gid-%s" id-format)
8547 (let ((res (tramp-send-command-and-read
8548 vec
8549 (format "%s -g%s %s"
8550 (tramp-get-remote-id vec)
8551 (if (equal id-format 'integer) "" "n")
8552 (if (equal id-format 'integer)
8553 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8554 ;; The command might not always return a number.
8555 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
fb7933a3 8556
8d60099b
MA
8557(defun tramp-get-local-uid (id-format)
8558 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8559
8560(defun tramp-get-local-gid (id-format)
9e6ab520 8561 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8d60099b 8562
00d6fd04 8563;; Some predefined connection properties.
20b8ac83
MA
8564(defun tramp-get-inline-compress (vec prop size)
8565 "Return the compress command related to PROP.
8566PROP is either `inline-compress' or `inline-decompress'. SIZE is
8567the length of the file to be compressed.
8568
8569If no corresponding command is found, nil is returned."
8570 (when (and (integerp tramp-inline-compress-start-size)
8571 (> size tramp-inline-compress-start-size))
8572 (with-connection-property vec prop
8573 (tramp-find-inline-compress vec)
8574 (tramp-get-connection-property vec prop nil))))
8575
8576(defun tramp-get-inline-coding (vec prop size)
8577 "Return the coding command related to PROP.
8578PROP is either `remote-encoding', `remode-decoding',
8579`local-encoding' or `local-decoding'.
8580
8581SIZE is the length of the file to be coded. Depending on SIZE,
8582compression might be applied.
8583
8584If no corresponding command is found, nil is returned.
8585Otherwise, either a string is returned which contains a `%s' mark
8586to be used for the respective input or output file; or a Lisp
8587function cell is returned to be applied on a buffer."
efd49885
MA
8588 ;; We must catch the errors, because we want to return `nil', when
8589 ;; no inline coding is found.
8590 (ignore-errors
8591 (let ((coding
8592 (with-connection-property vec prop
8593 (tramp-find-inline-encoding vec)
8594 (tramp-get-connection-property vec prop nil)))
8595 (prop1 (if (string-match "encoding" prop)
8596 "inline-compress" "inline-decompress"))
8597 compress)
8598 ;; The connection property might have been cached. So we must
8599 ;; send the script to the remote side - maybe.
8600 (when (and coding (symbolp coding) (string-match "remote" prop))
8601 (let ((name (symbol-name coding)))
8602 (while (string-match (regexp-quote "-") name)
8603 (setq name (replace-match "_" nil t name)))
8604 (tramp-maybe-send-script vec (symbol-value coding) name)
8605 (setq coding name)))
8606 (when coding
8607 ;; Check for the `compress' command.
8608 (setq compress (tramp-get-inline-compress vec prop1 size))
8609 ;; Return the value.
8610 (cond
8611 ((and compress (symbolp coding))
8612 (if (string-match "decompress" prop1)
8613 `(lambda (beg end)
8614 (,coding beg end)
8615 (let ((coding-system-for-write 'binary)
8616 (coding-system-for-read 'binary))
8617 (apply
8618 'call-process-region (point-min) (point-max)
8619 (car (split-string ,compress)) t t nil
8620 (cdr (split-string ,compress)))))
20b8ac83 8621 `(lambda (beg end)
20b8ac83
MA
8622 (let ((coding-system-for-write 'binary)
8623 (coding-system-for-read 'binary))
8624 (apply
efd49885 8625 'call-process-region beg end
20b8ac83 8626 (car (split-string ,compress)) t t nil
efd49885
MA
8627 (cdr (split-string ,compress))))
8628 (,coding (point-min) (point-max)))))
8629 ((symbolp coding)
8630 coding)
8631 ((and compress (string-match "decoding" prop))
8632 (format "(%s | %s >%%s)" coding compress))
8633 (compress
8634 (format "(%s <%%s | %s)" compress coding))
8635 ((string-match "decoding" prop)
8636 (format "%s >%%s" coding))
8637 (t
8638 (format "%s <%%s" coding)))))))
fb7933a3 8639
00d6fd04 8640(defun tramp-get-method-parameter (method param)
c951aecb 8641 "Return the method parameter PARAM.
20b8ac83 8642If the `tramp-methods' entry does not exist, return nil."
00d6fd04
MA
8643 (let ((entry (assoc param (assoc method tramp-methods))))
8644 (when entry (cadr entry))))
90f8dc03 8645
fb7933a3
KG
8646;; Auto saving to a special directory.
8647
00cec167 8648(defun tramp-exists-file-name-handler (operation &rest args)
20b8ac83 8649 "Check, whether OPERATION runs a file name handler."
00d6fd04
MA
8650 ;; The file name handler is determined on base of either an
8651 ;; argument, `buffer-file-name', or `default-directory'.
8652 (condition-case nil
8653 (let* ((buffer-file-name "/")
8654 (default-directory "/")
8655 (fnha file-name-handler-alist)
8656 (check-file-name-operation operation)
8657 (file-name-handler-alist
8658 (list
8659 (cons "/"
aa485f7c
MA
8660 (lambda (operation &rest args)
8661 "Returns OPERATION if it is the one to be checked."
8662 (if (equal check-file-name-operation operation)
8663 operation
8664 (let ((file-name-handler-alist fnha))
8665 (apply operation args))))))))
00d6fd04
MA
8666 (equal (apply operation args) operation))
8667 (error nil)))
c1105d05
MA
8668
8669(unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8670 (defadvice make-auto-save-file-name
8671 (around tramp-advice-make-auto-save-file-name () activate)
00d6fd04 8672 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
20b8ac83 8673 (if (tramp-tramp-file-p (buffer-file-name))
7f49fe46
MA
8674 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8675 ;; directly, because this would bypass the locking mechanism.
8676 (setq ad-return-value
8677 (tramp-file-name-handler 'make-auto-save-file-name))
a69c01a0 8678 ad-do-it))
191bb792
MA
8679 (add-hook
8680 'tramp-unload-hook
8681 (lambda ()
8682 (ad-remove-advice
8683 'make-auto-save-file-name
d7ec1df7
MA
8684 'around 'tramp-advice-make-auto-save-file-name)
8685 (ad-activate 'make-auto-save-file-name))))
fb7933a3 8686
20b8ac83
MA
8687;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8688;; umask. This is a security threat.
414da5ab
MA
8689
8690(defun tramp-set-auto-save-file-modes ()
8691 "Set permissions of autosaved remote files to the original permissions."
8692 (let ((bfn (buffer-file-name)))
20b8ac83 8693 (when (and (tramp-tramp-file-p bfn)
b50dd0d2 8694 (buffer-modified-p)
414da5ab 8695 (stringp buffer-auto-save-file-name)
340b8d4f
MA
8696 (not (equal bfn buffer-auto-save-file-name)))
8697 (unless (file-exists-p buffer-auto-save-file-name)
8698 (write-region "" nil buffer-auto-save-file-name))
8699 ;; Permissions should be set always, because there might be an old
8700 ;; auto-saved file belonging to another original file. This could
8701 ;; be a security threat.
7177e2a3 8702 (set-file-modes buffer-auto-save-file-name
11948172 8703 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
414da5ab 8704
20b8ac83
MA
8705(unless (and (featurep 'xemacs)
8706 (= emacs-major-version 21)
8707 (> emacs-minor-version 4))
a69c01a0
MA
8708 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8709 (add-hook 'tramp-unload-hook
aa485f7c
MA
8710 (lambda ()
8711 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
414da5ab 8712
fb7933a3
KG
8713(defun tramp-subst-strs-in-string (alist string)
8714 "Replace all occurrences of the string FROM with TO in STRING.
8715ALIST is of the form ((FROM . TO) ...)."
8716 (save-match-data
8717 (while alist
8718 (let* ((pr (car alist))
8719 (from (car pr))
8720 (to (cdr pr)))
8721 (while (string-match (regexp-quote from) string)
8722 (setq string (replace-match to t t string)))
8723 (setq alist (cdr alist))))
8724 string))
8725
fb7933a3
KG
8726;; ------------------------------------------------------------
8727;; -- Compatibility functions section --
8728;; ------------------------------------------------------------
8729
00d6fd04 8730(defun tramp-read-passwd (proc &optional prompt)
fb7933a3 8731 "Read a password from user (compat function).
5615d63f 8732Consults the auth-source package.
5ec2cc41 8733Invokes `password-read' if available, `read-passwd' else."
00d6fd04
MA
8734 (let* ((key (tramp-make-tramp-file-name
8735 tramp-current-method tramp-current-user
8736 tramp-current-host ""))
8737 (pw-prompt
8738 (or prompt
8739 (with-current-buffer (process-buffer proc)
8740 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8741 (format "%s for %s " (capitalize (match-string 1)) key)))))
7540f029
MA
8742 (with-parsed-tramp-file-name key nil
8743 (prog1
8744 (or
8745 ;; See if auth-sources contains something useful, if it's bound.
8746 (and (boundp 'auth-sources)
8747 (tramp-get-connection-property v "first-password-request" nil)
8748 ;; Try with Tramp's current method.
20b8ac83
MA
8749 (tramp-compat-funcall
8750 'auth-source-user-or-password
8751 "password" tramp-current-host tramp-current-method))
7540f029
MA
8752 ;; Try the password cache.
8753 (when (functionp 'password-read)
8754 (unless (tramp-get-connection-property
8755 v "first-password-request" nil)
20b8ac83 8756 (tramp-compat-funcall 'password-cache-remove key))
7540f029 8757 (let ((password
20b8ac83
MA
8758 (tramp-compat-funcall 'password-read pw-prompt key)))
8759 (tramp-compat-funcall 'password-cache-add key password)
7540f029
MA
8760 password))
8761 ;; Else, get the password interactively.
8762 (read-passwd pw-prompt))
8763 (tramp-set-connection-property v "first-password-request" nil)))))
00d6fd04 8764
9c13938d
MA
8765(defun tramp-clear-passwd (vec)
8766 "Clear password cache for connection related to VEC."
20b8ac83
MA
8767 (tramp-compat-funcall
8768 'password-cache-remove
8769 (tramp-make-tramp-file-name
8770 (tramp-file-name-method vec)
8771 (tramp-file-name-user vec)
8772 (tramp-file-name-host vec)
8773 "")))
00d6fd04
MA
8774
8775;; Snarfed code from time-date.el and parse-time.el
8776
8777(defconst tramp-half-a-year '(241 17024)
8778"Evaluated by \"(days-to-time 183)\".")
8779
8780(defconst tramp-parse-time-months
8781 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8782 ("apr" . 4) ("may" . 5) ("jun" . 6)
8783 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8784 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8785 "Alist mapping month names to integers.")
8786
8787(defun tramp-time-less-p (t1 t2)
8788 "Say whether time value T1 is less than time value T2."
8789 (unless t1 (setq t1 '(0 0)))
8790 (unless t2 (setq t2 '(0 0)))
8791 (or (< (car t1) (car t2))
8792 (and (= (car t1) (car t2))
8793 (< (nth 1 t1) (nth 1 t2)))))
8794
8795(defun tramp-time-subtract (t1 t2)
8796 "Subtract two time values.
8797Return the difference in the format of a time value."
8798 (unless t1 (setq t1 '(0 0)))
8799 (unless t2 (setq t2 '(0 0)))
8800 (let ((borrow (< (cadr t1) (cadr t2))))
8801 (list (- (car t1) (car t2) (if borrow 1 0))
8802 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
fb7933a3
KG
8803
8804(defun tramp-time-diff (t1 t2)
8805 "Return the difference between the two times, in seconds.
1a762140 8806T1 and T2 are time values (as returned by `current-time' for example)."
fb7933a3 8807 ;; Pacify byte-compiler with `symbol-function'.
ea9d1443
KG
8808 (cond ((and (fboundp 'subtract-time)
8809 (fboundp 'float-time))
20b8ac83
MA
8810 (tramp-compat-funcall
8811 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
ea9d1443
KG
8812 ((and (fboundp 'subtract-time)
8813 (fboundp 'time-to-seconds))
20b8ac83
MA
8814 (tramp-compat-funcall
8815 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
fb7933a3 8816 ((fboundp 'itimer-time-difference)
20b8ac83
MA
8817 (tramp-compat-funcall
8818 'itimer-time-difference
8819 (if (< (length t1) 3) (append t1 '(0)) t1)
8820 (if (< (length t2) 3) (append t2 '(0)) t2)))
fb7933a3 8821 (t
00d6fd04 8822 (let ((time (tramp-time-subtract t1 t2)))
ea9d1443
KG
8823 (+ (* (car time) 65536.0)
8824 (cadr time)
8825 (/ (or (nth 2 time) 0) 1000000.0))))))
fb7933a3
KG
8826
8827(defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8828 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8829EOL-TYPE can be one of `dos', `unix', or `mac'."
8830 (cond ((fboundp 'coding-system-change-eol-conversion)
20b8ac83
MA
8831 (tramp-compat-funcall
8832 'coding-system-change-eol-conversion coding-system eol-type))
fb7933a3 8833 ((fboundp 'subsidiary-coding-system)
20b8ac83
MA
8834 (tramp-compat-funcall
8835 'subsidiary-coding-system coding-system
8836 (cond ((eq eol-type 'dos) 'crlf)
8837 ((eq eol-type 'unix) 'lf)
8838 ((eq eol-type 'mac) 'cr)
8839 (t
8840 (error "Unknown EOL-TYPE `%s', must be %s"
8841 eol-type
8842 "`dos', `unix', or `mac'")))))
fb7933a3
KG
8843 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8844
19a87064
MA
8845(defun tramp-set-process-query-on-exit-flag (process flag)
8846 "Specify if query is needed for process when Emacs is exited.
8847If the second argument flag is non-nil, Emacs will query the user before
8848exiting if process is running."
8849 (if (fboundp 'set-process-query-on-exit-flag)
20b8ac83
MA
8850 (tramp-compat-funcall 'set-process-query-on-exit-flag process flag)
8851 (tramp-compat-funcall 'process-kill-without-query process flag)))
19a87064 8852
19a87064 8853
bf247b6e
KS
8854;; ------------------------------------------------------------
8855;; -- Kludges section --
8856;; ------------------------------------------------------------
fb7933a3
KG
8857
8858;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8859;; does not deal well with newline characters. Newline is replaced by
8860;; backslash newline. But if, say, the string `a backslash newline b'
8861;; is passed to a shell, the shell will expand this into "ab",
8862;; completely omitting the newline. This is not what was intended.
8863;; It does not appear to be possible to make the function
8864;; `shell-quote-argument' work with newlines without making it
8865;; dependent on the shell used. But within this package, we know that
8866;; we will always use a Bourne-like shell, so we use an approach which
8867;; groks newlines.
8868;;
8869;; The approach is simple: we call `shell-quote-argument', then
8870;; massage the newline part of the result.
8871;;
8872;; This function should produce a string which is grokked by a Unix
8873;; shell, even if the Emacs is running on Windows. Since this is the
8874;; kludges section, we bind `system-type' in such a way that
8875;; `shell-quote-arguments' behaves as if on Unix.
8876;;
8877;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8878;; function to work with Bourne-like shells.
8879;;
8880;; CCC: This function should be rewritten so that
8881;; `shell-quote-argument' is not used. This way, we are safe from
8882;; changes in `shell-quote-argument'.
8883(defun tramp-shell-quote-argument (s)
8884 "Similar to `shell-quote-argument', but groks newlines.
8885Only works for Bourne-like shells."
8886 (let ((system-type 'not-windows))
8887 (save-match-data
8888 (let ((result (shell-quote-argument s))
8889 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8890 (when (and (>= (length result) 2)
8891 (string= (substring result 0 2) "\\~"))
8892 (setq result (substring result 1)))
8893 (while (string-match nl result)
8894 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8895 t t result)))
8896 result))))
8897
a69c01a0
MA
8898;; Checklist for `tramp-unload-hook'
8899;; - Unload all `tramp-*' packages
8900;; - Reset `file-name-handler-alist'
8901;; - Cleanup hooks where Tramp functions are in
8902;; - Cleanup advised functions
8903;; - Cleanup autoloads
8904;;;###autoload
8905(defun tramp-unload-tramp ()
08b1eb21 8906 "Discard Tramp from loading remote files."
a69c01a0
MA
8907 (interactive)
8908 ;; When Tramp is not loaded yet, its autoloads are still active.
8c04e197 8909 (tramp-unload-file-name-handlers)
a69c01a0 8910 ;; ange-ftp settings must be enabled.
20b8ac83 8911 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
00d6fd04
MA
8912 ;; Maybe its not loaded yet.
8913 (condition-case nil
8914 (unload-feature 'tramp 'force)
a69c01a0
MA
8915 (error nil)))
8916
dea31ca6
MA
8917(when (and load-in-progress
8918 (string-match "Loading tramp..." (or (current-message) "")))
ccb4a481
MA
8919 (message "Loading tramp...done"))
8920
fb7933a3
KG
8921(provide 'tramp)
8922
fb7933a3
KG
8923;;; TODO:
8924
4007ba5b 8925;; * Handle nonlocal exits such as C-g.
00d6fd04
MA
8926;; * But it would probably be better to use with-local-quit at the
8927;; place where it's actually needed: around any potentially
8928;; indefinitely blocking piece of code. In this case it would be
8929;; within Tramp around one of its calls to accept-process-output (or
8930;; around one of the loops that calls accept-process-output)
d037d501 8931;; (Stefan Monnier).
fb7933a3 8932;; * Rewrite `tramp-shell-quote-argument' to abstain from using
b1d06e75 8933;; `shell-quote-argument'.
fb7933a3
KG
8934;; * In Emacs 21, `insert-directory' shows total number of bytes used
8935;; by the files in that directory. Add this here.
8936;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8937;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
fb7933a3
KG
8938;; * Don't use globbing for directories with many files, as this is
8939;; likely to produce long command lines, and some shells choke on
8940;; long command lines.
fb7933a3 8941;; * How to deal with MULE in `insert-file-contents' and `write-region'?
fb7933a3 8942;; * abbreviate-file-name
8e754ea2 8943;; * Better error checking. At least whenever we see something
fb7933a3
KG
8944;; strange when doing zerop, we should kill the process and start
8945;; again. (Greg Stark)
fb7933a3 8946;; * Remove unneeded parameters from methods.
fb7933a3
KG
8947;; * Make it work for different encodings, and for different file name
8948;; encodings, too. (Daniel Pittman)
fb7933a3
KG
8949;; * Don't search for perl5 and perl. Instead, only search for perl and
8950;; then look if it's the right version (with `perl -v').
8951;; * When editing a remote CVS controlled file as a different user, VC
8952;; gets confused about the file locking status. Try to find out why
8953;; the workaround doesn't work.
3cdaec13 8954;; * Username and hostname completion.
6c4e47fa 8955;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8daea7fc 8956;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
16674e4f 8957;; Code is nearly identical.
cfb5c0db
MA
8958;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8959;; until the last but one hop via `start-file-process'. Apply it
8960;; also for ftp and smb.
00d6fd04
MA
8961;; * WIBNI if we had a command "trampclient"? If I was editing in
8962;; some shell with root priviledges, it would be nice if I could
8963;; just call
8964;; trampclient filename.c
8965;; as an editor, and the _current_ shell would connect to an Emacs
8966;; server and would be used in an existing non-priviledged Emacs
8967;; session for doing the editing in question.
8968;; That way, I need not tell Emacs my password again and be afraid
8969;; that it makes it into core dumps or other ugly stuff (I had Emacs
8970;; once display a just typed password in the context of a keyboard
8971;; sequence prompt for a question immediately following in a shell
8972;; script run within Emacs -- nasty).
8973;; And if I have some ssh session running to a different computer,
8974;; having the possibility of passing a local file there to a local
8975;; Emacs session (in case I can arrange for a connection back) would
8976;; be nice.
a4aeb9a4 8977;; Likely the corresponding Tramp server should not allow the
00d6fd04
MA
8978;; equivalent of the emacsclient -eval option in order to make this
8979;; reasonably unproblematic. And maybe trampclient should have some
8980;; way of passing credentials, like by using an SSL socket or
6e4f5731 8981;; something. (David Kastrup)
00d6fd04 8982;; * Reconnect directly to a compliant shell without first going
6e4f5731 8983;; through the user's default shell. (Pete Forman)
00d6fd04 8984;; * Make `tramp-default-user' obsolete.
11c71217 8985;; * How can I interrupt the remote process with a signal
6e4f5731 8986;; (interrupt-process seems not to work)? (Markus Triska)
2296b54d
MA
8987;; * Avoid the local shell entirely for starting remote processes. If
8988;; so, I think even a signal, when delivered directly to the local
8989;; SSH instance, would correctly be propagated to the remote process
8990;; automatically; possibly SSH would have to be started with
6e4f5731 8991;; "-t". (Markus Triska)
dea31ca6 8992;; * It makes me wonder if tramp couldn't fall back to ssh when scp
6e4f5731
MA
8993;; isn't on the remote host. (Mark A. Hershberger)
8994;; * Use lsh instead of ssh. (Alfred M. Szmidt)
3e2fa353
MA
8995;; * Implement a general server-local-variable mechanism, as there are
8996;; probably other variables that need different values for different
8997;; servers too. The user could then configure a variable (such as
8998;; tramp-server-local-variable-alist) to define any such variables
8999;; that they need to, which would then be let bound as appropriate
6e4f5731 9000;; in tramp functions. (Jason Rumney)
946a5aeb
MA
9001;; * Optimize out-of-band copying, when both methods are scp-like (not
9002;; rsync).
9003;; * Keep a second connection open for out-of-band methods like scp or
9004;; rsync.
7e5686f0
MA
9005;; * IMHO, it's a drawback that currently Tramp doesn't support
9006;; Unicode in Dired file names by default. Is it possible to
9007;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
9008;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
6e4f5731 9009;; expects only English messages? (Juri Linkov)
7e5686f0 9010;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
20b8ac83 9011;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
7e5686f0
MA
9012;; * Try telnet+curl as new method. It might be useful for busybox,
9013;; without built-in uuencode/uudecode.
20b8ac83
MA
9014;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
9015;; * I was wondering it it would be possible to use tramp even if I'm
9016;; actually using sshfs. But when I launch a command I would like
9017;; to get it executed on the remote machine where the files really
9018;; are. (Andrea Crotti)
9019;; * Run emerge on two remote files. Bug is described here:
9020;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
9021;; (Bug#6850)
fb7933a3
KG
9022
9023;; Functions for file-name-handler-alist:
9024;; diff-latest-backup-file -- in diff.el
fb7933a3 9025
cdd44874 9026;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
fb7933a3 9027;;; tramp.el ends here
57671b72
MA
9028
9029;; Local Variables:
9030;; mode: Emacs-Lisp
9031;; coding: utf-8
9032;; End: