* net/tramp.el (tramp-replace-environment-variables): Do not fail
[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,
b96e6899 4;; 2005, 2006, 2007, 2008, 2009 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;;
00d6fd04
MA
39;; This package only works for Emacs 21.1 and higher, and for XEmacs 21.4
40;; and higher. For XEmacs 21, you need the package `fsf-compat' for
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
9fa0d3aa 82(require 'format-spec) ; from Gnus 5.8, also in tar ball
5ec2cc41
KG
83;; As long as password.el is not part of (X)Emacs, it shouldn't
84;; be mandatory
85(if (featurep 'xemacs)
86 (load "password" 'noerror)
fd48cd18
GM
87 (or (require 'password-cache nil 'noerror)
88 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
5ec2cc41 89
fb7933a3
KG
90(require 'shell)
91(require 'advice)
92
bcb04d98
GM
93(eval-and-compile
94 (if (featurep 'xemacs)
95 (load "auth-source" 'noerror)
96 (require 'auth-source nil 'noerror)))
5615d63f 97
00d6fd04
MA
98;; Requiring 'tramp-cache results in an endless loop.
99(autoload 'tramp-get-file-property "tramp-cache")
100(autoload 'tramp-set-file-property "tramp-cache")
101(autoload 'tramp-flush-file-property "tramp-cache")
102(autoload 'tramp-flush-directory-property "tramp-cache")
00d6fd04
MA
103(autoload 'tramp-get-connection-property "tramp-cache")
104(autoload 'tramp-set-connection-property "tramp-cache")
105(autoload 'tramp-flush-connection-property "tramp-cache")
106(autoload 'tramp-parse-connection-properties "tramp-cache")
107(add-hook 'tramp-unload-hook
aa485f7c
MA
108 (lambda ()
109 (when (featurep 'tramp-cache)
110 (unload-feature 'tramp-cache 'force))))
00d6fd04 111
16674e4f
KG
112(autoload 'tramp-uuencode-region "tramp-uu"
113 "Implementation of `uuencode' in Lisp.")
a69c01a0 114(add-hook 'tramp-unload-hook
aa485f7c
MA
115 (lambda ()
116 (when (featurep 'tramp-uu)
117 (unload-feature 'tramp-uu 'force))))
16674e4f 118
00d6fd04 119(autoload 'uudecode-decode-region "uudecode")
16674e4f 120
0664ff72
MA
121;; The following Tramp packages must be loaded after tramp.el, because
122;; they require it as well.
00d6fd04 123(eval-after-load "tramp"
9c13938d
MA
124 '(dolist
125 (feature
126 (list
127
0664ff72 128 ;; Tramp interactive commands.
9c13938d
MA
129 'tramp-cmds
130
131 ;; Load foreign FTP method.
132 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
133
134 ;; tramp-smb uses "smbclient" from Samba. Not available
135 ;; under Cygwin and Windows, because they don't offer
136 ;; "smbclient". And even not necessary there, because Emacs
137 ;; supports UNC file names like "//host/share/localname".
138 (unless (memq system-type '(cygwin windows-nt)) 'tramp-smb)
139
140 ;; Load foreign FISH method.
141 'tramp-fish
00d6fd04 142
70c11b0b 143 ;; tramp-gvfs needs D-Bus messages. Available since Emacs 23
8e754ea2
MA
144 ;; on some system types. We don't call `dbus-ping', because
145 ;; this would load dbus.el.
70c11b0b 146 (when (and (featurep 'dbusbind)
2ac33804
MA
147 (condition-case nil
148 (funcall 'dbus-get-unique-name :session)
149 (error nil))
70c11b0b
MA
150 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
151 'tramp-gvfs)
152
9c13938d 153 ;; Load gateways. It needs `make-network-process' from Emacs 22.
03db0efc
MA
154 (when (functionp 'make-network-process) 'tramp-gw)
155
156 ;; tramp-imap needs both epa (from Emacs 23.1) and imap-hash
157 ;; (from Emacs 23.2).
158 (when (and (locate-library "epa") (locate-library "imap-hash"))
159 'tramp-imap)))
9c13938d
MA
160
161 (when feature
70c11b0b
MA
162 ;; We have used just some basic tests, whether a package shall
163 ;; be added. There might still be other errors during loading,
164 ;; which we will catch here.
165 (catch 'tramp-loading
166 (require feature)
167 (add-hook 'tramp-unload-hook
168 `(lambda ()
169 (when (featurep (quote ,feature))
170 (unload-feature (quote ,feature) 'force)))))
171 (unless (featurep feature)
172 (message "Loading %s failed, ignoring this package" feature)))))
fb7933a3
KG
173
174;;; User Customizable Internal Variables:
175
176(defgroup tramp nil
177 "Edit remote files with a combination of rsh and rcp or similar programs."
589d30dd 178 :group 'files
bf247b6e 179 :version "22.1")
fb7933a3 180
2e271195
MA
181;; Maybe we need once a real Tramp mode, with key bindings etc.
182;;;###autoload
183(defcustom tramp-mode t
184 "*Whether Tramp is enabled.
185If it is set to nil, all remote file names are used literally."
186 :group 'tramp
187 :type 'boolean)
188
00d6fd04 189(defcustom tramp-verbose 3
263c02ef 190 "*Verbosity level for Tramp messages.
00d6fd04
MA
191Any level x includes messages for all levels 1 .. x-1. The levels are
192
193 0 silent (no tramp messages at all)
194 1 errors
195 2 warnings
196 3 connection to remote hosts (default level)
197 4 activities
198 5 internal
199 6 sent and received strings
200 7 file caching
201 8 connection properties
20210 traces (huge)."
fb7933a3
KG
203 :group 'tramp
204 :type 'integer)
205
263c02ef 206;; Emacs case.
38c65fca
KG
207(eval-and-compile
208 (when (boundp 'backup-directory-alist)
209 (defcustom tramp-backup-directory-alist nil
210 "Alist of filename patterns and backup directory names.
211Each element looks like (REGEXP . DIRECTORY), with the same meaning like
212in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
213is a local file name, the backup directory is prepended with Tramp file
00d6fd04 214name prefix \(method, user, host\) of file.
38c65fca
KG
215
216\(setq tramp-backup-directory-alist backup-directory-alist\)
217
218gives the same backup policy for Tramp files on their hosts like the
219policy for local files."
220 :group 'tramp
221 :type '(repeat (cons (regexp :tag "Regexp matching filename")
222 (directory :tag "Backup directory name"))))))
223
224;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
225;; the package "backup-dir" might not be loaded yet.
226(eval-and-compile
227 (when (featurep 'xemacs)
228 (defcustom tramp-bkup-backup-directory-info nil
229 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
230It has the same meaning like `bkup-backup-directory-info' from package
231`backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
232file name, the backup directory is prepended with Tramp file name prefix
00d6fd04 233\(method, user, host\) of file.
38c65fca
KG
234
235\(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
236
237gives the same backup policy for Tramp files on their hosts like the
238policy for local files."
bf247b6e 239 :type '(repeat
38c65fca
KG
240 (list (regexp :tag "File regexp")
241 (string :tag "Backup Dir")
242 (set :inline t
243 (const ok-create)
244 (const full-path)
245 (const prepend-name)
246 (const search-upward))))
247 :group 'tramp)))
248
fb7933a3
KG
249(defcustom tramp-auto-save-directory nil
250 "*Put auto-save files in this directory, if set.
251The idea is to use a local directory so that auto-saving is faster."
252 :group 'tramp
00d6fd04 253 :type '(choice (const nil) string))
fb7933a3 254
16674e4f
KG
255(defcustom tramp-encoding-shell
256 (if (memq system-type '(windows-nt))
257 (getenv "COMSPEC")
258 "/bin/sh")
259 "*Use this program for encoding and decoding commands on the local host.
260This shell is used to execute the encoding and decoding command on the
261local host, so if you want to use `~' in those commands, you should
262choose a shell here which groks tilde expansion. `/bin/sh' normally
263does not understand tilde expansion.
264
265For encoding and deocding, commands like the following are executed:
266
267 /bin/sh -c COMMAND < INPUT > OUTPUT
268
269This variable can be used to change the \"/bin/sh\" part. See the
00d6fd04 270variable `tramp-encoding-command-switch' for the \"-c\" part.
fb7933a3
KG
271
272Note that this variable is not used for remote commands. There are
273mechanisms in tramp.el which automatically determine the right shell to
274use for the remote host."
275 :group 'tramp
276 :type '(file :must-match t))
277
16674e4f
KG
278(defcustom tramp-encoding-command-switch
279 (if (string-match "cmd\\.exe" tramp-encoding-shell)
280 "/c"
281 "-c")
282 "*Use this switch together with `tramp-encoding-shell' for local commands.
283See the variable `tramp-encoding-shell' for more information."
284 :group 'tramp
285 :type 'string)
286
00d6fd04
MA
287(defcustom tramp-copy-size-limit 10240
288 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
16674e4f 289 :group 'tramp
00d6fd04 290 :type 'integer)
90dc758d 291
00d6fd04
MA
292(defcustom tramp-terminal-type "dumb"
293 "*Value of TERM environment variable for logging in to remote host.
294Because Tramp wants to parse the output of the remote shell, it is easily
295confused by ANSI color escape sequences and suchlike. Often, shell init
296files conditionalize this setup based on the TERM environment variable."
90dc758d 297 :group 'tramp
00d6fd04 298 :type 'string)
90dc758d 299
00d6fd04
MA
300(defvar tramp-methods
301 `(("rcp" (tramp-login-program "rsh")
302 (tramp-login-args (("%h") ("-l" "%u")))
303 (tramp-remote-sh "/bin/sh")
304 (tramp-copy-program "rcp")
263c02ef 305 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 306 (tramp-copy-keep-date t)
263c02ef 307 (tramp-copy-recursive t)
00d6fd04
MA
308 (tramp-password-end-of-line nil))
309 ("scp" (tramp-login-program "ssh")
2296b54d 310 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
311 ("-e" "none")))
312 (tramp-remote-sh "/bin/sh")
313 (tramp-copy-program "scp")
263c02ef
MA
314 (tramp-copy-args (("-P" "%p") ("-p" "%k")
315 ("-q") ("-r")))
00d6fd04 316 (tramp-copy-keep-date t)
263c02ef 317 (tramp-copy-recursive t)
00d6fd04
MA
318 (tramp-password-end-of-line nil)
319 (tramp-gw-args (("-o"
320 "GlobalKnownHostsFile=/dev/null")
321 ("-o" "UserKnownHostsFile=/dev/null")
322 ("-o" "StrictHostKeyChecking=no")))
323 (tramp-default-port 22))
324 ("scp1" (tramp-login-program "ssh")
2296b54d 325 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
326 ("-1" "-e" "none")))
327 (tramp-remote-sh "/bin/sh")
328 (tramp-copy-program "scp")
329 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
263c02ef 330 ("-q") ("-r")))
00d6fd04 331 (tramp-copy-keep-date t)
263c02ef 332 (tramp-copy-recursive t)
00d6fd04
MA
333 (tramp-password-end-of-line nil)
334 (tramp-gw-args (("-o"
335 "GlobalKnownHostsFile=/dev/null")
336 ("-o" "UserKnownHostsFile=/dev/null")
337 ("-o" "StrictHostKeyChecking=no")))
338 (tramp-default-port 22))
339 ("scp2" (tramp-login-program "ssh")
2296b54d 340 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
341 ("-2" "-e" "none")))
342 (tramp-remote-sh "/bin/sh")
343 (tramp-copy-program "scp")
344 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
263c02ef 345 ("-q") ("-r")))
00d6fd04 346 (tramp-copy-keep-date t)
263c02ef 347 (tramp-copy-recursive t)
00d6fd04
MA
348 (tramp-password-end-of-line nil)
349 (tramp-gw-args (("-o"
350 "GlobalKnownHostsFile=/dev/null")
351 ("-o" "UserKnownHostsFile=/dev/null")
352 ("-o" "StrictHostKeyChecking=no")))
353 (tramp-default-port 22))
354 ("scp1_old"
355 (tramp-login-program "ssh1")
356 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
357 ("-e" "none")))
358 (tramp-remote-sh "/bin/sh")
359 (tramp-copy-program "scp1")
263c02ef 360 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 361 (tramp-copy-keep-date t)
263c02ef 362 (tramp-copy-recursive t)
00d6fd04
MA
363 (tramp-password-end-of-line nil))
364 ("scp2_old"
365 (tramp-login-program "ssh2")
366 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
367 ("-e" "none")))
368 (tramp-remote-sh "/bin/sh")
369 (tramp-copy-program "scp2")
263c02ef 370 (tramp-copy-args (("-p" "%k") ("-r")))
00d6fd04 371 (tramp-copy-keep-date t)
263c02ef 372 (tramp-copy-recursive t)
00d6fd04
MA
373 (tramp-password-end-of-line nil))
374 ("sftp" (tramp-login-program "ssh")
375 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
376 ("-e" "none")))
377 (tramp-remote-sh "/bin/sh")
378 (tramp-copy-program "sftp")
379 (tramp-copy-args nil)
380 (tramp-copy-keep-date nil)
381 (tramp-password-end-of-line nil))
382 ("rsync" (tramp-login-program "ssh")
383 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
384 ("-e" "none")))
385 (tramp-remote-sh "/bin/sh")
386 (tramp-copy-program "rsync")
263c02ef 387 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
00d6fd04 388 (tramp-copy-keep-date t)
263c02ef 389 (tramp-copy-recursive t)
00d6fd04 390 (tramp-password-end-of-line nil))
263c02ef
MA
391 ("rsyncc"
392 (tramp-login-program "ssh")
946a5aeb
MA
393 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
394 ("-o" "ControlPath=%t.%%r@%%h:%%p")
395 ("-o" "ControlMaster=yes")
396 ("-e" "none")))
397 (tramp-remote-sh "/bin/sh")
398 (tramp-copy-program "rsync")
263c02ef 399 (tramp-copy-args (("-t" "%k") ("-r")))
946a5aeb
MA
400 (tramp-copy-env (("RSYNC_RSH")
401 (,(concat
402 "ssh"
403 " -o ControlPath=%t.%%r@%%h:%%p"
404 " -o ControlMaster=auto"))))
405 (tramp-copy-keep-date t)
263c02ef 406 (tramp-copy-recursive t)
946a5aeb 407 (tramp-password-end-of-line nil))
00d6fd04
MA
408 ("remcp" (tramp-login-program "remsh")
409 (tramp-login-args (("%h") ("-l" "%u")))
410 (tramp-remote-sh "/bin/sh")
411 (tramp-copy-program "rcp")
412 (tramp-copy-args (("-p" "%k")))
413 (tramp-copy-keep-date t)
414 (tramp-password-end-of-line nil))
415 ("rsh" (tramp-login-program "rsh")
416 (tramp-login-args (("%h") ("-l" "%u")))
417 (tramp-remote-sh "/bin/sh")
418 (tramp-copy-program nil)
419 (tramp-copy-args nil)
420 (tramp-copy-keep-date nil)
421 (tramp-password-end-of-line nil))
422 ("ssh" (tramp-login-program "ssh")
2296b54d 423 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
424 ("-e" "none")))
425 (tramp-remote-sh "/bin/sh")
426 (tramp-copy-program nil)
427 (tramp-copy-args nil)
428 (tramp-copy-keep-date nil)
429 (tramp-password-end-of-line nil)
430 (tramp-gw-args (("-o"
431 "GlobalKnownHostsFile=/dev/null")
432 ("-o" "UserKnownHostsFile=/dev/null")
433 ("-o" "StrictHostKeyChecking=no")))
434 (tramp-default-port 22))
435 ("ssh1" (tramp-login-program "ssh")
2296b54d 436 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
437 ("-1" "-e" "none")))
438 (tramp-remote-sh "/bin/sh")
439 (tramp-copy-program nil)
440 (tramp-copy-args nil)
441 (tramp-copy-keep-date nil)
442 (tramp-password-end-of-line nil)
443 (tramp-gw-args (("-o"
444 "GlobalKnownHostsFile=/dev/null")
445 ("-o" "UserKnownHostsFile=/dev/null")
446 ("-o" "StrictHostKeyChecking=no")))
447 (tramp-default-port 22))
448 ("ssh2" (tramp-login-program "ssh")
2296b54d 449 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
450 ("-2" "-e" "none")))
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 (tramp-gw-args (("-o"
457 "GlobalKnownHostsFile=/dev/null")
458 ("-o" "UserKnownHostsFile=/dev/null")
459 ("-o" "StrictHostKeyChecking=no")))
460 (tramp-default-port 22))
461 ("ssh1_old"
462 (tramp-login-program "ssh1")
463 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
464 ("-e" "none")))
465 (tramp-remote-sh "/bin/sh")
466 (tramp-copy-program nil)
467 (tramp-copy-args nil)
468 (tramp-copy-keep-date nil)
469 (tramp-password-end-of-line nil))
470 ("ssh2_old"
471 (tramp-login-program "ssh2")
472 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
473 ("-e" "none")))
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 ("remsh" (tramp-login-program "remsh")
480 (tramp-login-args (("%h") ("-l" "%u")))
481 (tramp-remote-sh "/bin/sh")
482 (tramp-copy-program nil)
483 (tramp-copy-args nil)
484 (tramp-copy-keep-date nil)
485 (tramp-password-end-of-line nil))
486 ("telnet"
487 (tramp-login-program "telnet")
488 (tramp-login-args (("%h") ("%p")))
489 (tramp-remote-sh "/bin/sh")
490 (tramp-copy-program nil)
491 (tramp-copy-args nil)
492 (tramp-copy-keep-date nil)
493 (tramp-password-end-of-line nil)
494 (tramp-default-port 23))
495 ("su" (tramp-login-program "su")
496 (tramp-login-args (("-") ("%u")))
497 (tramp-remote-sh "/bin/sh")
498 (tramp-copy-program nil)
499 (tramp-copy-args nil)
500 (tramp-copy-keep-date nil)
501 (tramp-password-end-of-line nil))
502 ("sudo" (tramp-login-program "sudo")
503 (tramp-login-args (("-u" "%u")
42bc9b6d 504 ("-s") ("-H") ("-p" "Password:")))
00d6fd04
MA
505 (tramp-remote-sh "/bin/sh")
506 (tramp-copy-program nil)
507 (tramp-copy-args nil)
508 (tramp-copy-keep-date nil)
509 (tramp-password-end-of-line nil))
510 ("scpc" (tramp-login-program "ssh")
2296b54d 511 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
512 ("-o" "ControlPath=%t.%%r@%%h:%%p")
513 ("-o" "ControlMaster=yes")
514 ("-e" "none")))
515 (tramp-remote-sh "/bin/sh")
516 (tramp-copy-program "scp")
517 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
518 ("-o" "ControlPath=%t.%%r@%%h:%%p")
519 ("-o" "ControlMaster=auto")))
520 (tramp-copy-keep-date t)
521 (tramp-password-end-of-line nil)
522 (tramp-gw-args (("-o"
523 "GlobalKnownHostsFile=/dev/null")
524 ("-o" "UserKnownHostsFile=/dev/null")
525 ("-o" "StrictHostKeyChecking=no")))
526 (tramp-default-port 22))
527 ("scpx" (tramp-login-program "ssh")
2296b54d 528 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
529 ("-e" "none" "-t" "-t" "/bin/sh")))
530 (tramp-remote-sh "/bin/sh")
531 (tramp-copy-program "scp")
532 (tramp-copy-args (("-p" "%k")))
533 (tramp-copy-keep-date t)
534 (tramp-password-end-of-line nil)
535 (tramp-gw-args (("-o"
536 "GlobalKnownHostsFile=/dev/null")
537 ("-o" "UserKnownHostsFile=/dev/null")
538 ("-o" "StrictHostKeyChecking=no")))
539 (tramp-default-port 22))
540 ("sshx" (tramp-login-program "ssh")
2296b54d 541 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
00d6fd04
MA
542 ("-e" "none" "-t" "-t" "/bin/sh")))
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 (tramp-gw-args (("-o"
549 "GlobalKnownHostsFile=/dev/null")
550 ("-o" "UserKnownHostsFile=/dev/null")
551 ("-o" "StrictHostKeyChecking=no")))
552 (tramp-default-port 22))
553 ("krlogin"
554 (tramp-login-program "krlogin")
555 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
556 (tramp-remote-sh "/bin/sh")
557 (tramp-copy-program nil)
558 (tramp-copy-args nil)
559 (tramp-copy-keep-date nil)
560 (tramp-password-end-of-line nil))
561 ("plink" (tramp-login-program "plink")
562 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
563 ("-ssh")))
564 (tramp-remote-sh "/bin/sh")
565 (tramp-copy-program nil)
566 (tramp-copy-args nil)
567 (tramp-copy-keep-date nil)
568 (tramp-password-end-of-line "xy") ;see docstring for "xy"
569 (tramp-default-port 22))
570 ("plink1"
571 (tramp-login-program "plink")
572 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
573 ("-1" "-ssh")))
574 (tramp-remote-sh "/bin/sh")
575 (tramp-copy-program nil)
576 (tramp-copy-args nil)
577 (tramp-copy-keep-date nil)
578 (tramp-password-end-of-line "xy") ;see docstring for "xy"
579 (tramp-default-port 22))
580 ("plinkx"
581 (tramp-login-program "plink")
42bc9b6d
MA
582 ;; ("%h") must be a single element, see
583 ;; `tramp-compute-multi-hops'.
584 (tramp-login-args (("-load") ("%h") ("-t")
ce3f516f
MA
585 (,(format
586 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=$ '"
587 tramp-terminal-type))
00d6fd04
MA
588 ("/bin/sh")))
589 (tramp-remote-sh "/bin/sh")
590 (tramp-copy-program nil)
591 (tramp-copy-args nil)
592 (tramp-copy-keep-date nil)
593 (tramp-password-end-of-line nil))
594 ("pscp" (tramp-login-program "plink")
595 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
596 ("-ssh")))
597 (tramp-remote-sh "/bin/sh")
598 (tramp-copy-program "pscp")
60f2c210 599 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
00d6fd04
MA
600 (tramp-copy-keep-date t)
601 (tramp-password-end-of-line "xy") ;see docstring for "xy"
602 (tramp-default-port 22))
603 ("psftp" (tramp-login-program "plink")
604 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
605 ("-ssh")))
606 (tramp-remote-sh "/bin/sh")
607 (tramp-copy-program "pscp")
60f2c210 608 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
00d6fd04
MA
609 (tramp-copy-keep-date t)
610 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
611 ("fcp" (tramp-login-program "fsh")
612 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
613 (tramp-remote-sh "/bin/sh -i")
614 (tramp-copy-program "fcp")
615 (tramp-copy-args (("-p" "%k")))
616 (tramp-copy-keep-date t)
617 (tramp-password-end-of-line nil)))
fb7933a3
KG
618 "*Alist of methods for remote files.
619This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
620Each NAME stands for a remote access method. Each PARAM is a
621pair of the form (KEY VALUE). The following KEYs are defined:
fb7933a3
KG
622 * `tramp-remote-sh'
623 This specifies the Bourne shell to use on the remote host. This
624 MUST be a Bourne-like shell. It is normally not necessary to set
a4aeb9a4 625 this to any value other than \"/bin/sh\": Tramp wants to use a shell
fb7933a3
KG
626 which groks tilde expansion, but it can search for it. Also note
627 that \"/bin/sh\" exists on all Unixen, this might not be true for
628 the value that you decide to use. You Have Been Warned.
b25a52cc
KG
629 * `tramp-login-program'
630 This specifies the name of the program to use for logging in to the
00d6fd04
MA
631 remote host. This may be the name of rsh or a workalike program,
632 or the name of telnet or a workalike, or the name of su or a workalike.
b25a52cc 633 * `tramp-login-args'
fb7933a3 634 This specifies the list of arguments to pass to the above
00d6fd04 635 mentioned program. Please note that this is a list of list of arguments,
fb7933a3 636 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
00d6fd04
MA
637 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
638 There are some patterns: \"%h\" in this list is replaced by the host
639 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
640 port number, and \"%%\" can be used to obtain a literal percent character.
641 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
642 expansion (i.e. no host or no user specified), this list is not used as
643 argument. By this, arguments like (\"-l\" \"%u\") are optional.
644 \"%t\" is replaced by the temporary file name produced with
645 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
646 parameter of a program, if exists.
b25a52cc
KG
647 * `tramp-copy-program'
648 This specifies the name of the program to use for remotely copying
649 the file; this might be the absolute filename of rcp or the name of
650 a workalike program.
651 * `tramp-copy-args'
fb7933a3 652 This specifies the list of parameters to pass to the above mentioned
b25a52cc 653 program, the hints for `tramp-login-args' also apply here.
00d6fd04
MA
654 * `tramp-copy-keep-date'
655 This specifies whether the copying program when the preserves the
656 timestamp of the original file.
657 * `tramp-default-port'
658 The default port of a method is needed in case of gateway connections.
659 Additionally, it is used as indication which method is prepared for
660 passing gateways.
661 * `tramp-gw-args'
662 As the attribute name says, additional arguments are specified here
663 when a method is applied via a gateway.
90f8dc03
KG
664 * `tramp-password-end-of-line'
665 This specifies the string to use for terminating the line after
666 submitting the password. If this method parameter is nil, then the
667 value of the normal variable `tramp-default-password-end-of-line'
668 is used. This parameter is necessary because the \"plink\" program
669 requires any two characters after sending the password. These do
670 not have to be newline or carriage return characters. Other login
671 programs are happy with just one character, the newline character.
672 We use \"xy\" as the value for methods using \"plink\".
b25a52cc
KG
673
674What does all this mean? Well, you should specify `tramp-login-program'
675for all methods; this program is used to log in to the remote site. Then,
676there are two ways to actually transfer the files between the local and the
677remote side. One way is using an additional rcp-like program. If you want
678to do this, set `tramp-copy-program' in the method.
fb7933a3
KG
679
680Another possibility for file transfer is inline transfer, i.e. the
b25a52cc 681file is passed through the same buffer used by `tramp-login-program'. In
fb7933a3 682this case, the file contents need to be protected since the
b25a52cc 683`tramp-login-program' might use escape codes or the connection might not
fb7933a3 684be eight-bit clean. Therefore, file contents are encoded for transit.
00d6fd04
MA
685See the variables `tramp-local-coding-commands' and
686`tramp-remote-coding-commands' for details.
fb7933a3 687
16674e4f 688So, to summarize: if the method is an out-of-band method, then you
b25a52cc 689must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
00d6fd04
MA
690inline method, then these two parameters should be nil. Methods which
691are fit for gateways must have `tramp-default-port' at least.
fb7933a3
KG
692
693Notes:
694
00d6fd04
MA
695When using `su' or `sudo' the phrase `open connection to a remote
696host' sounds strange, but it is used nevertheless, for consistency.
697No connection is opened to a remote host, but `su' or `sudo' is
698started on the local host. You should specify a remote host
699`localhost' or the name of the local host. Another host name is
700useful only in combination with `tramp-default-proxies-alist'.")
fb7933a3 701
b25a52cc 702(defcustom tramp-default-method
83e20b5c
MA
703 ;; An external copy method seems to be preferred, because it is much
704 ;; more performant for large files, and it hasn't too serious delays
705 ;; for small files. But it must be ensured that there aren't
706 ;; permanent password queries. Either a password agent like
263c02ef
MA
707 ;; "ssh-agent" or "Pageant" shall run, or the optional
708 ;; password-cache.el or auth-sources.el packages shall be active for
709 ;; password caching. "scpc" would be another good choice because of
710 ;; the "ControlMaster" option, but this is a more modern alternative
711 ;; in OpenSSH 4, which cannot be taken as default.
00d6fd04
MA
712 (cond
713 ;; PuTTY is installed.
714 ((executable-find "pscp")
715 (if (or (fboundp 'password-read)
263c02ef 716 (fboundp 'auth-source-user-or-password)
00d6fd04 717 ;; Pageant is running.
70c11b0b 718 (tramp-compat-process-running-p "Pageant"))
00d6fd04
MA
719 "pscp"
720 "plink"))
721 ;; There is an ssh installation.
722 ((executable-find "scp")
723 (if (or (fboundp 'password-read)
263c02ef 724 (fboundp 'auth-source-user-or-password)
00d6fd04
MA
725 ;; ssh-agent is running.
726 (getenv "SSH_AUTH_SOCK")
727 (getenv "SSH_AGENT_PID"))
728 "scp"
729 "ssh"))
730 ;; Fallback.
731 (t "ftp"))
fb7933a3 732 "*Default method to use for transferring files.
c62c9d08 733See `tramp-methods' for possibilities.
4007ba5b 734Also see `tramp-default-method-alist'."
c62c9d08
KG
735 :group 'tramp
736 :type 'string)
737
505edaeb 738(defcustom tramp-default-method-alist
4007ba5b 739 '(("\\`localhost\\'" "\\`root\\'" "su"))
00d6fd04 740 "*Default method to use for specific host/user pairs.
c62c9d08
KG
741This is an alist of items (HOST USER METHOD). The first matching item
742specifies the method to use for a file name which does not specify a
743method. HOST and USER are regular expressions or nil, which is
744interpreted as a regular expression which always matches. If no entry
745matches, the variable `tramp-default-method' takes effect.
746
747If the file name does not specify the user, lookup is done using the
748empty string for the user name.
749
750See `tramp-methods' for a list of possibilities for METHOD."
751 :group 'tramp
752 :type '(repeat (list (regexp :tag "Host regexp")
753 (regexp :tag "User regexp")
754 (string :tag "Method"))))
755
00d6fd04
MA
756(defcustom tramp-default-user
757 nil
758 "*Default user to use for transferring files.
759It is nil by default; otherwise settings in configuration files like
760\"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
761
762This variable is regarded as obsolete, and will be removed soon."
763 :group 'tramp
764 :type '(choice (const nil) string))
765
766(defcustom tramp-default-user-alist
767 `(("\\`su\\(do\\)?\\'" nil "root")
768 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
769 nil ,(user-login-name)))
770 "*Default user to use for specific method/host pairs.
771This is an alist of items (METHOD HOST USER). The first matching item
772specifies the user to use for a file name which does not specify a
773user. METHOD and USER are regular expressions or nil, which is
774interpreted as a regular expression which always matches. If no entry
775matches, the variable `tramp-default-user' takes effect.
776
777If the file name does not specify the method, lookup is done using the
778empty string for the method name."
779 :group 'tramp
780 :type '(repeat (list (regexp :tag "Method regexp")
781 (regexp :tag "Host regexp")
782 (string :tag "User"))))
783
784(defcustom tramp-default-host
785 (system-name)
786 "*Default host to use for transferring files.
787Useful for su and sudo methods mostly."
788 :group 'tramp
789 :type 'string)
790
791(defcustom tramp-default-proxies-alist nil
792 "*Route to be followed for specific host/user pairs.
793This is an alist of items (HOST USER PROXY). The first matching
794item specifies the proxy to be passed for a file name located on
795a remote target matching USER@HOST. HOST and USER are regular
70c11b0b
MA
796expressions. PROXY must be a Tramp filename without a localname
797part. Method and user name on PROXY are optional, which is
798interpreted with the default values. PROXY can contain the
799patterns %h and %u, which are replaced by the strings matching
800HOST or USER, respectively.
801
802HOST, USER or PROXY could also be Lisp forms, which will be
803evaluated. The result must be a string or nil, which is
804interpreted as a regular expression which always matches."
00d6fd04 805 :group 'tramp
70c11b0b
MA
806 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
807 (choice :tag "User regexp" regexp sexp)
808 (choice :tag "Proxy remote name" string (const nil)))))
00d6fd04 809
b96e6899
MA
810(defconst tramp-local-host-regexp
811 (concat
812 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
813 "*Host names which are regarded as local host.")
814
16674e4f 815(defconst tramp-completion-function-alist-rsh
00d6fd04
MA
816 '((tramp-parse-rhosts "/etc/hosts.equiv")
817 (tramp-parse-rhosts "~/.rhosts"))
b25a52cc 818 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
16674e4f 819
16674e4f 820(defconst tramp-completion-function-alist-ssh
00d6fd04
MA
821 '((tramp-parse-rhosts "/etc/hosts.equiv")
822 (tramp-parse-rhosts "/etc/shosts.equiv")
823 (tramp-parse-shosts "/etc/ssh_known_hosts")
824 (tramp-parse-sconfig "/etc/ssh_config")
825 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
826 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
827 (tramp-parse-rhosts "~/.rhosts")
828 (tramp-parse-rhosts "~/.shosts")
829 (tramp-parse-shosts "~/.ssh/known_hosts")
830 (tramp-parse-sconfig "~/.ssh/config")
831 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
832 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
b25a52cc 833 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
16674e4f 834
16674e4f 835(defconst tramp-completion-function-alist-telnet
00d6fd04 836 '((tramp-parse-hosts "/etc/hosts"))
b25a52cc 837 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
16674e4f 838
16674e4f 839(defconst tramp-completion-function-alist-su
00d6fd04 840 '((tramp-parse-passwd "/etc/passwd"))
b25a52cc 841 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
292ffc15 842
00d6fd04
MA
843(defconst tramp-completion-function-alist-putty
844 '((tramp-parse-putty
845 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
846 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
847
5ec2cc41 848(defvar tramp-completion-function-alist nil
16674e4f
KG
849 "*Alist of methods for remote files.
850This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
851Each NAME stands for a remote access method. Each PAIR is of the form
852\(FUNCTION FILE). FUNCTION is responsible to extract user names and host
853names from FILE for completion. The following predefined FUNCTIONs exists:
854
5ec2cc41
KG
855 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
856 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
857 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
858 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
859 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
860 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
861 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
862 * `tramp-parse-netrc' for \"~/.netrc\" like files.
00d6fd04 863 * `tramp-parse-putty' for PuTTY registry keys.
5ec2cc41
KG
864
865FUNCTION can also be a customer defined function. For more details see
866the info pages.")
867
868(eval-after-load "tramp"
869 '(progn
870 (tramp-set-completion-function
871 "rcp" tramp-completion-function-alist-rsh)
872 (tramp-set-completion-function
873 "scp" tramp-completion-function-alist-ssh)
874 (tramp-set-completion-function
875 "scp1" tramp-completion-function-alist-ssh)
876 (tramp-set-completion-function
877 "scp2" tramp-completion-function-alist-ssh)
878 (tramp-set-completion-function
879 "scp1_old" tramp-completion-function-alist-ssh)
880 (tramp-set-completion-function
881 "scp2_old" tramp-completion-function-alist-ssh)
882 (tramp-set-completion-function
70c11b0b 883 "rsync" tramp-completion-function-alist-ssh)
946a5aeb
MA
884 (tramp-set-completion-function
885 "rsyncc" tramp-completion-function-alist-ssh)
5ec2cc41
KG
886 (tramp-set-completion-function
887 "remcp" tramp-completion-function-alist-rsh)
888 (tramp-set-completion-function
889 "rsh" tramp-completion-function-alist-rsh)
890 (tramp-set-completion-function
891 "ssh" tramp-completion-function-alist-ssh)
892 (tramp-set-completion-function
893 "ssh1" tramp-completion-function-alist-ssh)
894 (tramp-set-completion-function
895 "ssh2" tramp-completion-function-alist-ssh)
896 (tramp-set-completion-function
897 "ssh1_old" tramp-completion-function-alist-ssh)
898 (tramp-set-completion-function
899 "ssh2_old" tramp-completion-function-alist-ssh)
900 (tramp-set-completion-function
901 "remsh" tramp-completion-function-alist-rsh)
902 (tramp-set-completion-function
903 "telnet" tramp-completion-function-alist-telnet)
904 (tramp-set-completion-function
905 "su" tramp-completion-function-alist-su)
906 (tramp-set-completion-function
907 "sudo" tramp-completion-function-alist-su)
bf247b6e 908 (tramp-set-completion-function
5ec2cc41
KG
909 "scpx" tramp-completion-function-alist-ssh)
910 (tramp-set-completion-function
911 "sshx" tramp-completion-function-alist-ssh)
912 (tramp-set-completion-function
913 "krlogin" tramp-completion-function-alist-rsh)
914 (tramp-set-completion-function
915 "plink" tramp-completion-function-alist-ssh)
916 (tramp-set-completion-function
917 "plink1" tramp-completion-function-alist-ssh)
00d6fd04
MA
918 (tramp-set-completion-function
919 "plinkx" tramp-completion-function-alist-putty)
5ec2cc41
KG
920 (tramp-set-completion-function
921 "pscp" tramp-completion-function-alist-ssh)
922 (tramp-set-completion-function
923 "fcp" tramp-completion-function-alist-ssh)))
16674e4f 924
674da028
MA
925(defconst tramp-echo-mark-marker "_echo"
926 "String marker to surround echoed commands.")
927
00d6fd04
MA
928(defconst tramp-echo-mark "_echo\b\b\b\b\b"
929 "String mark to be transmitted around shell commands.
930Used to separate their echo from the output they produce. This
931will only be used if we cannot disable remote echo via stty.
932This string must have no effect on the remote shell except for
933producing some echo which can later be detected by
674da028
MA
934`tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
935followed by an equal number of backspaces to erase them will
936usually suffice.")
00d6fd04
MA
937
938(defconst tramp-echoed-echo-mark-regexp "_echo\\(\b\\( \b\\)?\\)\\{5\\}"
939 "Regexp which matches `tramp-echo-mark' as it gets echoed by
940the remote shell.")
941
fb7933a3
KG
942(defcustom tramp-rsh-end-of-line "\n"
943 "*String used for end of line in rsh connections.
944I don't think this ever needs to be changed, so please tell me about it
16674e4f 945if you need to change this.
90f8dc03
KG
946Also see the method parameter `tramp-password-end-of-line' and the normal
947variable `tramp-default-password-end-of-line'."
16674e4f
KG
948 :group 'tramp
949 :type 'string)
950
90f8dc03
KG
951(defcustom tramp-default-password-end-of-line
952 tramp-rsh-end-of-line
16674e4f 953 "*String used for end of line after sending a password.
90f8dc03
KG
954This variable provides the default value for the method parameter
955`tramp-password-end-of-line', see `tramp-methods' for more details.
956
16674e4f
KG
957It seems that people using plink under Windows need to send
958\"\\r\\n\" (carriage-return, then newline) after a password, but just
959\"\\n\" after all other lines. This variable can be used for the
960password, see `tramp-rsh-end-of-line' for the other cases.
961
962The default value is to use the same value as `tramp-rsh-end-of-line'."
fb7933a3
KG
963 :group 'tramp
964 :type 'string)
965
00d6fd04
MA
966;; "getconf PATH" yields:
967;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
968;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
0664ff72 969;; GNU/Linux (Debian, Suse): /bin:/usr/bin
00d6fd04 970;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
fb7933a3 971(defcustom tramp-remote-path
00d6fd04
MA
972 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
973 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
fb7933a3
KG
974 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
975 "*List of directories to search for executables on remote host.
00d6fd04
MA
976For every remote host, this variable will be set buffer local,
977keeping the list of existing directories on that host.
fb7933a3
KG
978
979You can use `~' in this list, but when searching for a shell which groks
00d6fd04
MA
980tilde expansion, all directory names starting with `~' will be ignored.
981
982`Default Directories' represent the list of directories given by
983the command \"getconf PATH\". It is recommended to use this
984entry on top of this list, because these are the default
70c11b0b
MA
985directories for POSIX compatible commands.
986
987`Private Directories' are the settings of the $PATH environment,
988as given in your `~/.profile'."
00d6fd04
MA
989 :group 'tramp
990 :type '(repeat (choice
991 (const :tag "Default Directories" tramp-default-remote-path)
70c11b0b 992 (const :tag "Private Directories" tramp-own-remote-path)
00d6fd04
MA
993 (string :tag "Directory"))))
994
00d6fd04 995(defcustom tramp-remote-process-environment
a0a5183a 996 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
00d6fd04 997 ,(concat "TERM=" tramp-terminal-type)
97c696d5
MA
998 "EMACS=t" ;; Deprecated.
999 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
00d6fd04
MA
1000 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1001 "autocorrect=" "correct=")
1002
1003 "*List of environment variables to be set on the remote host.
1004
1005Each element should be a string of the form ENVVARNAME=VALUE. An
1006entry ENVVARNAME= diables the corresponding environment variable,
1007which might have been set in the init files like ~/.profile.
1008
1009Special handling is applied to the PATH environment, which should
1010not be set here. Instead of, it should be set via `tramp-remote-path'."
fb7933a3
KG
1011 :group 'tramp
1012 :type '(repeat string))
1013
1014(defcustom tramp-login-prompt-regexp
bc103d00 1015 ".*ogin\\( .*\\)?: *"
fb7933a3 1016 "*Regexp matching login-like prompts.
bc103d00
MA
1017The regexp should match at end of buffer.
1018
1019Sometimes the prompt is reported to look like \"login as:\"."
fb7933a3
KG
1020 :group 'tramp
1021 :type 'regexp)
1022
821e6e36 1023(defcustom tramp-shell-prompt-pattern
aa485f7c
MA
1024 ;; Allow a prompt to start right after a ^M since it indeed would be
1025 ;; displayed at the beginning of the line (and Zsh uses it).
1026 "\\(?:^\\|\r\\)[^#$%>\n]*[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
821e6e36
KG
1027 "Regexp to match prompts from remote shell.
1028Normally, Tramp expects you to configure `shell-prompt-pattern'
1029correctly, but sometimes it happens that you are connecting to a
1030remote host which sends a different kind of shell prompt. Therefore,
1031Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1032and also things matched by this variable. The default value of this
b25a52cc 1033variable is similar to the default value of `shell-prompt-pattern',
821e6e36
KG
1034which should work well in many cases."
1035 :group 'tramp
1036 :type 'regexp)
1037
fb7933a3 1038(defcustom tramp-password-prompt-regexp
00d6fd04 1039 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
fb7933a3 1040 "*Regexp matching password-like prompts.
ac474af1 1041The regexp should match at end of buffer.
fb7933a3
KG
1042
1043The `sudo' program appears to insert a `^@' character into the prompt."
1044 :group 'tramp
1045 :type 'regexp)
1046
1047(defcustom tramp-wrong-passwd-regexp
b1d06e75
KG
1048 (concat "^.*"
1049 ;; These strings should be on the last line
a4aeb9a4 1050 (regexp-opt '("Permission denied"
b1d06e75
KG
1051 "Login incorrect"
1052 "Login Incorrect"
1053 "Connection refused"
27e813fe 1054 "Connection closed"
b1d06e75
KG
1055 "Sorry, try again."
1056 "Name or service not known"
00d6fd04 1057 "Host key verification failed."
70c11b0b 1058 "No supported authentication methods left to try!") t)
b1d06e75
KG
1059 ".*"
1060 "\\|"
1061 "^.*\\("
1062 ;; Here comes a list of regexes, separated by \\|
1063 "Received signal [0-9]+"
1064 "\\).*")
fb7933a3 1065 "*Regexp matching a `login failed' message.
ac474af1
KG
1066The regexp should match at end of buffer."
1067 :group 'tramp
1068 :type 'regexp)
1069
1070(defcustom tramp-yesno-prompt-regexp
3cdaec13
KG
1071 (concat
1072 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1073 "\\s-*")
1074 "Regular expression matching all yes/no queries which need to be confirmed.
ac474af1 1075The confirmation should be done with yes or no.
3cdaec13
KG
1076The regexp should match at end of buffer.
1077See also `tramp-yn-prompt-regexp'."
fb7933a3
KG
1078 :group 'tramp
1079 :type 'regexp)
1080
3cdaec13 1081(defcustom tramp-yn-prompt-regexp
658052a2
MA
1082 (concat
1083 (regexp-opt '("Store key in cache? (y/n)"
1084 "Update cached key? (y/n, Return cancels connection)") t)
1085 "\\s-*")
3cdaec13
KG
1086 "Regular expression matching all y/n queries which need to be confirmed.
1087The confirmation should be done with y or n.
1088The regexp should match at end of buffer.
1089See also `tramp-yesno-prompt-regexp'."
1090 :group 'tramp
1091 :type 'regexp)
487f4fb7
KG
1092
1093(defcustom tramp-terminal-prompt-regexp
1094 (concat "\\("
1095 "TERM = (.*)"
1096 "\\|"
1097 "Terminal type\\? \\[.*\\]"
1098 "\\)\\s-*")
1099 "Regular expression matching all terminal setting prompts.
1100The regexp should match at end of buffer.
1101The answer will be provided by `tramp-action-terminal', which see."
1102 :group 'tramp
1103 :type 'regexp)
3cdaec13 1104
01917a18
MA
1105(defcustom tramp-operation-not-permitted-regexp
1106 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1107 (regexp-opt '("Operation not permitted") t))
1108 "Regular expression matching keep-date problems in (s)cp operations.
1109Copying has been performed successfully already, so this message can
1110be ignored safely."
1111 :group 'tramp
1112 :type 'regexp)
1113
6b2633cc
LH
1114(defcustom tramp-copy-failed-regexp
1115 (concat "\\(.+: "
1116 (regexp-opt '("Permission denied"
1117 "not a regular file"
1118 "is a directory"
1119 "No such file or directory") t)
1120 "\\)\\s-*")
1121 "Regular expression matching copy problems in (s)cp operations."
1122 :group 'tramp
1123 :type 'regexp)
1124
19a87064 1125(defcustom tramp-process-alive-regexp
38c65fca 1126 ""
19a87064 1127 "Regular expression indicating a process has finished.
38c65fca
KG
1128In fact this expression is empty by intention, it will be used only to
1129check regularly the status of the associated process.
07dfe738 1130The answer will be provided by `tramp-action-process-alive',
00d6fd04 1131`tramp-action-out-of-band', which see."
38c65fca
KG
1132 :group 'tramp
1133 :type 'regexp)
1134
fb7933a3
KG
1135(defcustom tramp-temp-name-prefix "tramp."
1136 "*Prefix to use for temporary files.
1137If this is a relative file name (such as \"tramp.\"), it is considered
1138relative to the directory name returned by the function
9e6ab520 1139`tramp-compat-temporary-file-directory' (which see). It may also be an
fb7933a3
KG
1140absolute file name; don't forget to include a prefix for the filename
1141part, though."
1142 :group 'tramp
1143 :type 'string)
1144
2296b54d
MA
1145(defconst tramp-temp-buffer-name " *tramp temp*"
1146 "Buffer name for a temporary buffer.
1147It shall be used in combination with `generate-new-buffer-name'.")
1148
4007ba5b 1149(defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
c62c9d08
KG
1150 "*Alist specifying extra arguments to pass to the remote shell.
1151Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1152matching the shell file name and ARGS is a string specifying the
1153arguments.
1154
1155This variable is only used when Tramp needs to start up another shell
1156for tilde expansion. The extra arguments should typically prevent the
1157shell from reading its init file."
1158 :group 'tramp
90f8dc03
KG
1159 ;; This might be the wrong way to test whether the widget type
1160 ;; `alist' is available. Who knows the right way to test it?
1161 :type (if (get 'alist 'widget-type)
1162 '(alist :key-type string :value-type string)
1163 '(repeat (cons string string))))
c62c9d08 1164
00d6fd04
MA
1165;; XEmacs is distributed with few Lisp packages. Further packages are
1166;; installed using EFS. If we use a unified filename format, then
1167;; Tramp is required in addition to EFS. (But why can't Tramp just
1168;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1169;; just like before.) Another reason for using a separate filename
1170;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1171;; Tramp only knows how to deal with `file-name-handler-alist', not
1172;; the other places.
1173
1174;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1175;;;###autoload
1176(defcustom tramp-syntax
1177 (if (featurep 'xemacs) 'sep 'ftp)
1178 "Tramp filename syntax to be used.
1179
1180It can have the following values:
1181
1182 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1183 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1184 'url -- URL-like syntax."
16674e4f 1185 :group 'tramp
00d6fd04
MA
1186 :type (if (featurep 'xemacs)
1187 '(choice (const :tag "EFS" ftp)
1188 (const :tag "XEmacs" sep)
1189 (const :tag "URL" url))
1190 '(choice (const :tag "Ange-FTP" ftp)
1191 (const :tag "URL" url))))
1192
1193(defconst tramp-prefix-format
1194 (cond ((equal tramp-syntax 'ftp) "/")
1195 ((equal tramp-syntax 'sep) "/[")
1196 ((equal tramp-syntax 'url) "/")
1197 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4 1198 "*String matching the very beginning of Tramp file names.
00d6fd04 1199Used in `tramp-make-tramp-file-name'.")
16674e4f 1200
00d6fd04 1201(defconst tramp-prefix-regexp
16674e4f 1202 (concat "^" (regexp-quote tramp-prefix-format))
a4aeb9a4 1203 "*Regexp matching the very beginning of Tramp file names.
00d6fd04 1204Should always start with \"^\". Derived from `tramp-prefix-format'.")
16674e4f 1205
00d6fd04 1206(defconst tramp-method-regexp
16674e4f 1207 "[a-zA-Z_0-9-]+"
00d6fd04 1208 "*Regexp matching methods identifiers.")
16674e4f 1209
00d6fd04
MA
1210(defconst tramp-postfix-method-format
1211 (cond ((equal tramp-syntax 'ftp) ":")
1212 ((equal tramp-syntax 'sep) "/")
1213 ((equal tramp-syntax 'url) "://")
1214 (t (error "Wrong `tramp-syntax' defined")))
16674e4f 1215 "*String matching delimeter between method and user or host names.
00d6fd04 1216Used in `tramp-make-tramp-file-name'.")
16674e4f 1217
00d6fd04
MA
1218(defconst tramp-postfix-method-regexp
1219 (regexp-quote tramp-postfix-method-format)
16674e4f 1220 "*Regexp matching delimeter between method and user or host names.
00d6fd04 1221Derived from `tramp-postfix-method-format'.")
16674e4f 1222
00d6fd04
MA
1223(defconst tramp-user-regexp
1224 "[^:/ \t]+"
1225 "*Regexp matching user names.")
16674e4f 1226
b96e6899
MA
1227(defconst tramp-prefix-domain-format "%"
1228 "*String matching delimeter between user and domain names.")
1229
1230(defconst tramp-prefix-domain-regexp
1231 (regexp-quote tramp-prefix-domain-format)
1232 "*Regexp matching delimeter between user and domain names.
1233Derived from `tramp-prefix-domain-format'.")
1234
1235(defconst tramp-domain-regexp
70c11b0b 1236 "[-a-zA-Z0-9_.]+"
b96e6899
MA
1237 "*Regexp matching domain names.")
1238
1239(defconst tramp-user-with-domain-regexp
1240 (concat "\\(" tramp-user-regexp "\\)"
1241 tramp-prefix-domain-regexp
1242 "\\(" tramp-domain-regexp "\\)")
1243 "*Regexp matching user names with domain names.")
1244
00d6fd04 1245(defconst tramp-postfix-user-format
16674e4f
KG
1246 "@"
1247 "*String matching delimeter between user and host names.
00d6fd04 1248Used in `tramp-make-tramp-file-name'.")
16674e4f 1249
00d6fd04 1250(defconst tramp-postfix-user-regexp
16674e4f
KG
1251 (regexp-quote tramp-postfix-user-format)
1252 "*Regexp matching delimeter between user and host names.
00d6fd04
MA
1253Derived from `tramp-postfix-user-format'.")
1254
1255(defconst tramp-host-regexp
1256 "[a-zA-Z0-9_.-]+"
1257 "*Regexp matching host names.")
1258
b96e6899
MA
1259(defconst tramp-prefix-ipv6-format
1260 (cond ((equal tramp-syntax 'ftp) "[")
1261 ((equal tramp-syntax 'sep) "")
1262 ((equal tramp-syntax 'url) "[")
1263 (t (error "Wrong `tramp-syntax' defined")))
1264 "*String matching left hand side of IPv6 addresses.
1265Used in `tramp-make-tramp-file-name'.")
1266
1267(defconst tramp-prefix-ipv6-regexp
1268 (regexp-quote tramp-prefix-ipv6-format)
1269 "*Regexp matching left hand side of IPv6 addresses.
1270Derived from `tramp-prefix-ipv6-format'.")
1271
e0b6e3b9
MA
1272;; The following regexp is a bit sloppy. But it shall serve our
1273;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1274;; "::ffff:192.168.0.1".
b96e6899 1275(defconst tramp-ipv6-regexp
e0b6e3b9 1276 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
b96e6899
MA
1277 "*Regexp matching IPv6 addresses.")
1278
1279(defconst tramp-postfix-ipv6-format
1280 (cond ((equal tramp-syntax 'ftp) "]")
1281 ((equal tramp-syntax 'sep) "")
1282 ((equal tramp-syntax 'url) "]")
1283 (t (error "Wrong `tramp-syntax' defined")))
1284 "*String matching right hand side of IPv6 addresses.
1285Used in `tramp-make-tramp-file-name'.")
1286
1287(defconst tramp-postfix-ipv6-regexp
1288 (regexp-quote tramp-postfix-ipv6-format)
1289 "*Regexp matching right hand side of IPv6 addresses.
1290Derived from `tramp-postfix-ipv6-format'.")
1291
00d6fd04
MA
1292(defconst tramp-prefix-port-format
1293 (cond ((equal tramp-syntax 'ftp) "#")
1294 ((equal tramp-syntax 'sep) "#")
1295 ((equal tramp-syntax 'url) ":")
1296 (t (error "Wrong `tramp-syntax' defined")))
1297 "*String matching delimeter between host names and port numbers.")
1298
1299(defconst tramp-prefix-port-regexp
1300 (regexp-quote tramp-prefix-port-format)
1301 "*Regexp matching delimeter between host names and port numbers.
1302Derived from `tramp-prefix-port-format'.")
1303
1304(defconst tramp-port-regexp
1305 "[0-9]+"
1306 "*Regexp matching port numbers.")
1307
1308(defconst tramp-host-with-port-regexp
1309 (concat "\\(" tramp-host-regexp "\\)"
1310 tramp-prefix-port-regexp
1311 "\\(" tramp-port-regexp "\\)")
1312 "*Regexp matching host names with port numbers.")
1313
1314(defconst tramp-postfix-host-format
1315 (cond ((equal tramp-syntax 'ftp) ":")
1316 ((equal tramp-syntax 'sep) "]")
1317 ((equal tramp-syntax 'url) "")
1318 (t (error "Wrong `tramp-syntax' defined")))
7432277c 1319 "*String matching delimeter between host names and localnames.
00d6fd04 1320Used in `tramp-make-tramp-file-name'.")
16674e4f 1321
00d6fd04 1322(defconst tramp-postfix-host-regexp
16674e4f 1323 (regexp-quote tramp-postfix-host-format)
7432277c 1324 "*Regexp matching delimeter between host names and localnames.
00d6fd04 1325Derived from `tramp-postfix-host-format'.")
16674e4f 1326
00d6fd04 1327(defconst tramp-localname-regexp
16674e4f 1328 ".*$"
00d6fd04 1329 "*Regexp matching localnames.")
16674e4f
KG
1330
1331;; File name format.
505edaeb 1332
00d6fd04 1333(defconst tramp-file-name-structure
16674e4f
KG
1334 (list
1335 (concat
1336 tramp-prefix-regexp
00d6fd04
MA
1337 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1338 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
b96e6899
MA
1339 "\\(" "\\(" tramp-host-regexp
1340 "\\|"
1341 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1342 tramp-postfix-ipv6-regexp "\\)"
1343 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
00d6fd04
MA
1344 tramp-postfix-host-regexp
1345 "\\(" tramp-localname-regexp "\\)")
b96e6899 1346 2 4 5 8)
16674e4f 1347
fb7933a3 1348 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
a4aeb9a4 1349the Tramp file name structure.
fb7933a3 1350
a4aeb9a4 1351The first element REGEXP is a regular expression matching a Tramp file
fb7933a3
KG
1352name. The regex should contain parentheses around the method name,
1353the user name, the host name, and the file name parts.
1354
1355The second element METHOD is a number, saying which pair of
1356parentheses matches the method name. The third element USER is
1357similar, but for the user name. The fourth element HOST is similar,
1358but for the host name. The fifth element FILE is for the file name.
1359These numbers are passed directly to `match-string', which see. That
1360means the opening parentheses are counted to identify the pair.
1361
00d6fd04 1362See also `tramp-file-name-regexp'.")
fb7933a3
KG
1363
1364;;;###autoload
505edaeb 1365(defconst tramp-file-name-regexp-unified
b96e6899 1366 "\\`/\\([^[/:]+\\|[^/]+]\\):"
505edaeb
KG
1367 "Value for `tramp-file-name-regexp' for unified remoting.
1368Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
00d6fd04 1369Tramp. See `tramp-file-name-structure' for more explanations.")
505edaeb
KG
1370
1371;;;###autoload
1372(defconst tramp-file-name-regexp-separate
1373 "\\`/\\[.*\\]"
1374 "Value for `tramp-file-name-regexp' for separate remoting.
1375XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 1376See `tramp-file-name-structure' for more explanations.")
505edaeb
KG
1377
1378;;;###autoload
00d6fd04
MA
1379(defconst tramp-file-name-regexp-url
1380 "\\`/[^/:]+://"
1381 "Value for `tramp-file-name-regexp' for URL-like remoting.
1382See `tramp-file-name-structure' for more explanations.")
1383
1384;;;###autoload
1385(defconst tramp-file-name-regexp
1386 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1387 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1388 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1389 (t (error "Wrong `tramp-syntax' defined")))
94be87e8 1390 "*Regular expression matching file names handled by Tramp.
a4aeb9a4 1391This regexp should match Tramp file names but no other file names.
fb7933a3
KG
1392\(When tramp.el is loaded, this regular expression is prepended to
1393`file-name-handler-alist', and that is searched sequentially. Thus,
a4aeb9a4
MA
1394if the Tramp entry appears rather early in the `file-name-handler-alist'
1395and is a bit too general, then some files might be considered Tramp
00d6fd04 1396files which are not really Tramp files.
fb7933a3
KG
1397
1398Please note that the entry in `file-name-handler-alist' is made when
1399this file (tramp.el) is loaded. This means that this variable must be set
1400before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1401updated after changing this variable.
1402
00d6fd04 1403Also see `tramp-file-name-structure'.")
fb7933a3 1404
16674e4f 1405;;;###autoload
8a798e41 1406(defconst tramp-root-regexp
00d6fd04 1407 (if (memq system-type '(cygwin windows-nt))
aa485f7c
MA
1408 "\\`\\([a-zA-Z]:\\)?/"
1409 "\\`/")
8a798e41 1410 "Beginning of an incomplete Tramp file name.
aa485f7c 1411Usually, it is just \"\\\\`/\". On W32 systems, there might be a
57671b72 1412volume letter, which will be removed by `tramp-drop-volume-letter'.")
8a798e41
MA
1413
1414;;;###autoload
1415(defconst tramp-completion-file-name-regexp-unified
aa485f7c 1416 (concat tramp-root-regexp "[^/]*\\'")
16674e4f 1417 "Value for `tramp-completion-file-name-regexp' for unified remoting.
8a798e41
MA
1418GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1419See `tramp-file-name-structure' for more explanations.")
fb7933a3 1420
16674e4f
KG
1421;;;###autoload
1422(defconst tramp-completion-file-name-regexp-separate
aa485f7c 1423 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
16674e4f
KG
1424 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1425XEmacs uses a separate filename syntax for Tramp and EFS.
00d6fd04 1426See `tramp-file-name-structure' for more explanations.")
fb7933a3 1427
16674e4f 1428;;;###autoload
00d6fd04 1429(defconst tramp-completion-file-name-regexp-url
aa485f7c 1430 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
00d6fd04
MA
1431 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1432See `tramp-file-name-structure' for more explanations.")
1433
1434;;;###autoload
1435(defconst tramp-completion-file-name-regexp
1436 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1437 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1438 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1439 (t (error "Wrong `tramp-syntax' defined")))
a4aeb9a4
MA
1440 "*Regular expression matching file names handled by Tramp completion.
1441This regexp should match partial Tramp file names only.
16674e4f
KG
1442
1443Please note that the entry in `file-name-handler-alist' is made when
1444this file (tramp.el) is loaded. This means that this variable must be set
1445before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1446updated after changing this variable.
1447
00d6fd04 1448Also see `tramp-file-name-structure'.")
fb7933a3 1449
00d6fd04
MA
1450(defconst tramp-actions-before-shell
1451 '((tramp-login-prompt-regexp tramp-action-login)
1452 (tramp-password-prompt-regexp tramp-action-password)
1453 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
ac474af1 1454 (shell-prompt-pattern tramp-action-succeed)
821e6e36 1455 (tramp-shell-prompt-pattern tramp-action-succeed)
3cdaec13 1456 (tramp-yesno-prompt-regexp tramp-action-yesno)
487f4fb7 1457 (tramp-yn-prompt-regexp tramp-action-yn)
19a87064
MA
1458 (tramp-terminal-prompt-regexp tramp-action-terminal)
1459 (tramp-process-alive-regexp tramp-action-process-alive))
ac474af1
KG
1460 "List of pattern/action pairs.
1461Whenever a pattern matches, the corresponding action is performed.
1462Each item looks like (PATTERN ACTION).
1463
1464The PATTERN should be a symbol, a variable. The value of this
1465variable gives the regular expression to search for. Note that the
1466regexp must match at the end of the buffer, \"\\'\" is implicitly
1467appended to it.
1468
1469The ACTION should also be a symbol, but a function. When the
00d6fd04 1470corresponding PATTERN matches, the ACTION function is called.")
ac474af1 1471
00d6fd04 1472(defconst tramp-actions-copy-out-of-band
38c65fca
KG
1473 '((tramp-password-prompt-regexp tramp-action-password)
1474 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
00d6fd04 1475 (tramp-copy-failed-regexp tramp-action-permission-denied)
19a87064 1476 (tramp-process-alive-regexp tramp-action-out-of-band))
38c65fca
KG
1477 "List of pattern/action pairs.
1478This list is used for copying/renaming with out-of-band methods.
90f8dc03 1479
00d6fd04
MA
1480See `tramp-actions-before-shell' for more info.")
1481
1482;; Chunked sending kludge. We set this to 500 for black-listed constellations
7432277c 1483;; known to have a bug in `process-send-string'; some ssh connections appear
7177e2a3
MA
1484;; to drop bytes when data is sent too quickly. There is also a connection
1485;; buffer local variable, which is computed depending on remote host properties
1486;; when `tramp-chunksize' is zero or nil.
7432277c
KG
1487(defcustom tramp-chunksize
1488 (when (and (not (featurep 'xemacs))
1489 (memq system-type '(hpux)))
1490 500)
55880756
MA
1491;; Parentheses in docstring starting at beginning of line are escaped.
1492;; Fontification is messed up when
1493;; `open-paren-in-column-0-is-defun-start' set to t.
7432277c
KG
1494 "*If non-nil, chunksize for sending input to local process.
1495It is necessary only on systems which have a buggy `process-send-string'
1496implementation. The necessity, whether this variable must be set, can be
1497checked via the following code:
1498
1499 (with-temp-buffer
11948172
MA
1500 (let* ((user \"xxx\") (host \"yyy\")
1501 (init 0) (step 50)
1502 (sent init) (received init))
1503 (while (= sent received)
1504 (setq sent (+ sent step))
1505 (erase-buffer)
1506 (let ((proc (start-process (buffer-name) (current-buffer)
1507 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1508 (when (memq (process-status proc) '(run open))
1509 (process-send-string proc (make-string sent ?\\ ))
1510 (process-send-eof proc)
1511 (process-send-eof proc))
1512 (while (not (progn (goto-char (point-min))
1513 (re-search-forward \"\\\\w+\" (point-max) t)))
1514 (accept-process-output proc 1))
1515 (when (memq (process-status proc) '(run open))
1516 (setq received (string-to-number (match-string 0)))
1517 (delete-process proc)
1518 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1519 (sit-for 0))))
1520 (if (> sent (+ init step))
1521 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1522 (- sent step))
1523 (message \"Test does not work\")
1524 (display-buffer (current-buffer))
1525 (sit-for 30))))
1526
1527In the Emacs normally running Tramp, evaluate the above code
55880756 1528\(replace \"xxx\" and \"yyy\" by the remote user and host name,
11948172
MA
1529respectively). You can do this, for example, by pasting it into
1530the `*scratch*' buffer and then hitting C-j with the cursor after the
1531last closing parenthesis. Note that it works only if you have configured
1532\"ssh\" to run without password query, see ssh-agent(1).
1533
1534You will see the number of bytes sent successfully to the remote host.
1535If that number exceeds 1000, you can stop the execution by hitting
1536C-g, because your Emacs is likely clean.
1537
11948172
MA
1538When it is necessary to set `tramp-chunksize', you might consider to
1539use an out-of-the-band method (like \"scp\") instead of an internal one
55880756 1540\(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
11948172 1541performance.
c951aecb 1542
00d6fd04
MA
1543If your Emacs is buggy, the code stops and gives you an indication
1544about the value `tramp-chunksize' should be set. Maybe you could just
1545experiment a bit, e.g. changing the values of `init' and `step'
1546in the third line of the code.
1547
7432277c
KG
1548Please raise a bug report via \"M-x tramp-bug\" if your system needs
1549this variable to be set as well."
1550 :group 'tramp
b1a2b924 1551 :type '(choice (const nil) integer))
7432277c 1552
5ec2cc41
KG
1553;; Logging in to a remote host normally requires obtaining a pty. But
1554;; Emacs on MacOS X has process-connection-type set to nil by default,
1555;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1556;; for an override of the system default.
1557(defcustom tramp-process-connection-type t
1558 "Overrides `process-connection-type' for connections from Tramp.
1559Tramp binds process-connection-type to the value given here before
1560opening a connection to a remote host."
1561 :group 'tramp
1562 :type '(choice (const nil) (const t) (const pty)))
1563
b50dd0d2
MA
1564(defcustom tramp-completion-reread-directory-timeout 10
1565 "Defines seconds since last remote command before rereading a directory.
1566A remote directory might have changed its contents. In order to
1567make it visible during file name completion in the minibuffer,
1568Tramp flushes its cache and rereads the directory contents when
1569more than `tramp-completion-reread-directory-timeout' seconds
1570have been gone since last remote command execution. A value of 0
1571would require an immediate reread during filename completion, nil
1572means to use always cached values for the directory contents."
1573 :group 'tramp
1574 :type '(choice (const nil) integer))
1575
fb7933a3
KG
1576;;; Internal Variables:
1577
4007ba5b 1578(defvar tramp-end-of-output
a0a5183a 1579 (format
70c11b0b
MA
1580 "///%s$"
1581 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
1582 "String used to recognize end of output.
1583The '$' character at the end is quoted; the string cannot be
1584detected as prompt when being sent on echoing hosts, therefore.")
fb7933a3 1585
fb7933a3 1586(defvar tramp-current-method nil
00d6fd04 1587 "Connection method for this *tramp* buffer.")
fb7933a3
KG
1588
1589(defvar tramp-current-user nil
00d6fd04 1590 "Remote login name for this *tramp* buffer.")
fb7933a3
KG
1591
1592(defvar tramp-current-host nil
00d6fd04
MA
1593 "Remote host for this *tramp* buffer.")
1594
1595(defconst tramp-uudecode
1596 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
fabf2143 1597cat /tmp/tramp.$$
00d6fd04 1598rm -f /tmp/tramp.$$"
fabf2143 1599 "Shell function to implement `uudecode' to standard output.
c08e6004
MA
1600Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1601for this or `uudecode -p', but some systems don't, and for them
1602we have this shell function.")
fabf2143
KG
1603
1604;; Perl script to implement `file-attributes' in a Lisp `read'able
1605;; output. If you are hacking on this, note that you get *no* output
1606;; unless this spits out a complete line, including the '\n' at the
1607;; end.
8daea7fc 1608;; The device number is returned as "-1", because there will be a virtual
b946a456 1609;; device number set in `tramp-handle-file-attributes'.
00d6fd04
MA
1610(defconst tramp-perl-file-attributes
1611 "%s -e '
c82c5727 1612@stat = lstat($ARGV[0]);
680db9ac
MA
1613if (!@stat) {
1614 print \"nil\\n\";
1615 exit 0;
1616}
c82c5727
LH
1617if (($stat[2] & 0170000) == 0120000)
1618{
1619 $type = readlink($ARGV[0]);
1620 $type = \"\\\"$type\\\"\";
1621}
1622elsif (($stat[2] & 0170000) == 040000)
1623{
1624 $type = \"t\";
1625}
1626else
1627{
1628 $type = \"nil\"
1629};
1630$uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1631$gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1632printf(
d4443a0d 1633 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
c82c5727
LH
1634 $type,
1635 $stat[3],
1636 $uid,
1637 $gid,
1638 $stat[8] >> 16 & 0xffff,
1639 $stat[8] & 0xffff,
1640 $stat[9] >> 16 & 0xffff,
1641 $stat[9] & 0xffff,
1642 $stat[10] >> 16 & 0xffff,
1643 $stat[10] & 0xffff,
1644 $stat[7],
1645 $stat[2],
1646 $stat[1] >> 16 & 0xffff,
1647 $stat[1] & 0xffff
00d6fd04 1648);' \"$1\" \"$2\" \"$3\" 2>/dev/null"
fb7933a3 1649 "Perl script to produce output suitable for use with `file-attributes'
00d6fd04
MA
1650on the remote file system.
1651Escape sequence %s is replaced with name of Perl binary.
1652This string is passed to `format', so percent characters need to be doubled.")
fb7933a3 1653
00d6fd04
MA
1654(defconst tramp-perl-directory-files-and-attributes
1655 "%s -e '
8cb0a559
LH
1656chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1657opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
c82c5727
LH
1658@list = readdir(DIR);
1659closedir(DIR);
1660$n = scalar(@list);
1661printf(\"(\\n\");
1662for($i = 0; $i < $n; $i++)
1663{
1664 $filename = $list[$i];
1665 @stat = lstat($filename);
1666 if (($stat[2] & 0170000) == 0120000)
1667 {
1668 $type = readlink($filename);
1669 $type = \"\\\"$type\\\"\";
1670 }
1671 elsif (($stat[2] & 0170000) == 040000)
1672 {
1673 $type = \"t\";
1674 }
1675 else
1676 {
1677 $type = \"nil\"
1678 };
1679 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1680 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1681 printf(
b946a456 1682 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
c82c5727
LH
1683 $filename,
1684 $type,
1685 $stat[3],
1686 $uid,
1687 $gid,
1688 $stat[8] >> 16 & 0xffff,
1689 $stat[8] & 0xffff,
1690 $stat[9] >> 16 & 0xffff,
1691 $stat[9] & 0xffff,
1692 $stat[10] >> 16 & 0xffff,
1693 $stat[10] & 0xffff,
1694 $stat[7],
1695 $stat[2],
1696 $stat[1] >> 16 & 0xffff,
1697 $stat[1] & 0xffff,
1698 $stat[0] >> 16 & 0xffff,
1699 $stat[0] & 0xffff);
1700}
00d6fd04 1701printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
c82c5727 1702 "Perl script implementing `directory-files-attributes' as Lisp `read'able
00d6fd04
MA
1703output.
1704Escape sequence %s is replaced with name of Perl binary.
1705This string is passed to `format', so percent characters need to be doubled.")
c82c5727 1706
ac474af1
KG
1707;; ;; These two use uu encoding.
1708;; (defvar tramp-perl-encode "%s -e'\
1709;; print qq(begin 644 xxx\n);
1710;; my $s = q();
1711;; my $res = q();
1712;; while (read(STDIN, $s, 45)) {
1713;; print pack(q(u), $s);
1714;; }
1715;; print qq(`\n);
1716;; print qq(end\n);
1717;; '"
1718;; "Perl program to use for encoding a file.
1719;; Escape sequence %s is replaced with name of Perl binary.")
1720
1721;; (defvar tramp-perl-decode "%s -ne '
1722;; print unpack q(u), $_;
1723;; '"
1724;; "Perl program to use for decoding a file.
1725;; Escape sequence %s is replaced with name of Perl binary.")
1726
1727;; These two use base64 encoding.
00d6fd04
MA
1728(defconst tramp-perl-encode-with-module
1729 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
ac474af1 1730 "Perl program to use for encoding a file.
b1d06e75 1731Escape sequence %s is replaced with name of Perl binary.
89509ea0 1732This string is passed to `format', so percent characters need to be doubled.
b1d06e75
KG
1733This implementation requires the MIME::Base64 Perl module to be installed
1734on the remote host.")
1735
00d6fd04
MA
1736(defconst tramp-perl-decode-with-module
1737 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
b1d06e75
KG
1738 "Perl program to use for decoding a file.
1739Escape sequence %s is replaced with name of Perl binary.
89509ea0 1740This string is passed to `format', so percent characters need to be doubled.
b1d06e75
KG
1741This implementation requires the MIME::Base64 Perl module to be installed
1742on the remote host.")
1743
00d6fd04 1744(defconst tramp-perl-encode
b1d06e75
KG
1745 "%s -e '
1746# This script contributed by Juanma Barranquero <lektu@terra.es>.
46932a8d 1747# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
cbd12ed7 1748# Free Software Foundation, Inc.
b1d06e75
KG
1749use strict;
1750
fa32e96a 1751my %%trans = do {
b1d06e75
KG
1752 my $i = 0;
1753 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1754 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1755};
1756
36541701 1757binmode(\\*STDIN);
b1d06e75
KG
1758
1759# We read in chunks of 54 bytes, to generate output lines
1760# of 72 chars (plus end of line)
36541701 1761$/ = \\54;
b1d06e75
KG
1762
1763while (my $data = <STDIN>) {
1764 my $pad = q();
1765
1766 # Only for the last chunk, and only if did not fill the last three-byte packet
1767 if (eof) {
fa32e96a 1768 my $mod = length($data) %% 3;
b1d06e75
KG
1769 $pad = q(=) x (3 - $mod) if $mod;
1770 }
1771
1772 # Not the fastest method, but it is simple: unpack to binary string, split
1773 # by groups of 6 bits and convert back from binary to byte; then map into
1774 # the translation table
1775 print
1776 join q(),
1777 map($trans{$_},
1778 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1779 $pad,
36541701 1780 qq(\\n);
00d6fd04 1781}' 2>/dev/null"
b1d06e75 1782 "Perl program to use for encoding a file.
fa32e96a 1783Escape sequence %s is replaced with name of Perl binary.
ccf29586 1784This string is passed to `format', so percent characters need to be doubled.")
ac474af1 1785
00d6fd04 1786(defconst tramp-perl-decode
b1d06e75
KG
1787 "%s -e '
1788# This script contributed by Juanma Barranquero <lektu@terra.es>.
46932a8d 1789# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
cbd12ed7 1790# Free Software Foundation, Inc.
b1d06e75
KG
1791use strict;
1792
fa32e96a 1793my %%trans = do {
b1d06e75 1794 my $i = 0;
16674e4f 1795 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
b1d06e75
KG
1796 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1797};
1798
fa32e96a 1799my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
b1d06e75 1800
36541701 1801binmode(\\*STDOUT);
b1d06e75
KG
1802
1803# We are going to accumulate into $pending to accept any line length
1804# (we do not check they are <= 76 chars as the RFC says)
1805my $pending = q();
1806
1807while (my $data = <STDIN>) {
1808 chomp $data;
1809
1810 # If we find one or two =, we have reached the end and
1811 # any following data is to be discarded
1812 my $finished = $data =~ s/(==?).*/$1/;
1813 $pending .= $data;
1814
1815 my $len = length($pending);
16674e4f 1816 my $chunk = substr($pending, 0, $len & ~3);
414da5ab 1817 $pending = substr($pending, $len & ~3 + 1);
b1d06e75
KG
1818
1819 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1820 # split in 8-bit chunks and convert back to char.
1821 print join q(),
1822 map $bytes{$_},
1823 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1824
1825 last if $finished;
00d6fd04 1826}' 2>/dev/null"
ac474af1 1827 "Perl program to use for decoding a file.
fa32e96a 1828Escape sequence %s is replaced with name of Perl binary.
ccf29586 1829This string is passed to `format', so percent characters need to be doubled.")
fb7933a3 1830
946a5aeb
MA
1831(defconst tramp-vc-registered-read-file-names
1832 "echo \"(\"
1833for file in \"$@\"; do
1834 if %s $file; then
1835 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1836 else
1837 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1838 fi
1839 if %s $file; then
1840 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1841 else
1842 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1843 fi
1844done
1845echo \")\""
1846 "Script to check existence of VC related files.
1847It must be send formatted with two strings; the tests for file
1848existence, and file readability.")
1849
9ce8462a
MA
1850(defconst tramp-file-mode-type-map
1851 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1852 (1 . "p") ; fifo
1853 (2 . "c") ; character device
1854 (3 . "m") ; multiplexed character device (v7)
1855 (4 . "d") ; directory
1856 (5 . "?") ; Named special file (XENIX)
1857 (6 . "b") ; block device
1858 (7 . "?") ; multiplexed block device (v7)
1859 (8 . "-") ; regular file
1860 (9 . "n") ; network special file (HP-UX)
1861 (10 . "l") ; symlink
1862 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1863 (12 . "s") ; socket
1864 (13 . "D") ; door special (Solaris)
1865 (14 . "w")) ; whiteout (BSD)
fb7933a3
KG
1866 "A list of file types returned from the `stat' system call.
1867This is used to map a mode number to a permission string.")
1868
fb7933a3 1869;; New handlers should be added here. The following operations can be
c0fc6170
MA
1870;; handled using the normal primitives: file-name-sans-versions,
1871;; get-file-buffer.
fb7933a3 1872(defconst tramp-file-name-handler-alist
00d6fd04 1873 '((load . tramp-handle-load)
fb7933a3 1874 (make-symbolic-link . tramp-handle-make-symbolic-link)
c0fc6170 1875 (file-name-as-directory . tramp-handle-file-name-as-directory)
fb7933a3
KG
1876 (file-name-directory . tramp-handle-file-name-directory)
1877 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1878 (file-truename . tramp-handle-file-truename)
1879 (file-exists-p . tramp-handle-file-exists-p)
1880 (file-directory-p . tramp-handle-file-directory-p)
1881 (file-executable-p . tramp-handle-file-executable-p)
fb7933a3
KG
1882 (file-readable-p . tramp-handle-file-readable-p)
1883 (file-regular-p . tramp-handle-file-regular-p)
1884 (file-symlink-p . tramp-handle-file-symlink-p)
1885 (file-writable-p . tramp-handle-file-writable-p)
1886 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1887 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1888 (file-attributes . tramp-handle-file-attributes)
1889 (file-modes . tramp-handle-file-modes)
fb7933a3 1890 (directory-files . tramp-handle-directory-files)
c82c5727 1891 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
fb7933a3
KG
1892 (file-name-all-completions . tramp-handle-file-name-all-completions)
1893 (file-name-completion . tramp-handle-file-name-completion)
1894 (add-name-to-file . tramp-handle-add-name-to-file)
1895 (copy-file . tramp-handle-copy-file)
263c02ef 1896 (copy-directory . tramp-handle-copy-directory)
fb7933a3
KG
1897 (rename-file . tramp-handle-rename-file)
1898 (set-file-modes . tramp-handle-set-file-modes)
ce3f516f 1899 (set-file-times . tramp-handle-set-file-times)
fb7933a3
KG
1900 (make-directory . tramp-handle-make-directory)
1901 (delete-directory . tramp-handle-delete-directory)
1902 (delete-file . tramp-handle-delete-file)
1903 (directory-file-name . tramp-handle-directory-file-name)
00d6fd04
MA
1904 ;; `executable-find' is not official yet.
1905 (executable-find . tramp-handle-executable-find)
1906 (start-file-process . tramp-handle-start-file-process)
0457dd55 1907 (process-file . tramp-handle-process-file)
00d6fd04 1908 (shell-command . tramp-handle-shell-command)
fb7933a3
KG
1909 (insert-directory . tramp-handle-insert-directory)
1910 (expand-file-name . tramp-handle-expand-file-name)
00d6fd04 1911 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
fb7933a3 1912 (file-local-copy . tramp-handle-file-local-copy)
19a87064 1913 (file-remote-p . tramp-handle-file-remote-p)
fb7933a3 1914 (insert-file-contents . tramp-handle-insert-file-contents)
94be87e8
MA
1915 (insert-file-contents-literally
1916 . tramp-handle-insert-file-contents-literally)
fb7933a3 1917 (write-region . tramp-handle-write-region)
38c65fca 1918 (find-backup-file-name . tramp-handle-find-backup-file-name)
c1105d05 1919 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
fb7933a3 1920 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
5ec2cc41 1921 (dired-compress-file . tramp-handle-dired-compress-file)
fb7933a3
KG
1922 (dired-recursive-delete-directory
1923 . tramp-handle-dired-recursive-delete-directory)
70c11b0b 1924 (dired-uncache . tramp-handle-dired-uncache)
fb7933a3 1925 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
49096407
MA
1926 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
1927 (vc-registered . tramp-handle-vc-registered))
c1105d05 1928 "Alist of handler functions.
fb7933a3
KG
1929Operations not mentioned here will be handled by the normal Emacs functions.")
1930
a4aeb9a4 1931;; Handlers for partial Tramp file names. For Emacs just
41c8e348 1932;; `file-name-all-completions' is needed.
a01b1e22 1933;;;###autoload
16674e4f 1934(defconst tramp-completion-file-name-handler-alist
a01b1e22 1935 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
41c8e348 1936 (file-name-completion . tramp-completion-handle-file-name-completion))
16674e4f
KG
1937 "Alist of completion handler functions.
1938Used for file names matching `tramp-file-name-regexp'. Operations not
1939mentioned here will be handled by `tramp-file-name-handler-alist' or the
1940normal Emacs functions.")
1941
4007ba5b 1942;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
ea9d1443
KG
1943(defvar tramp-foreign-file-name-handler-alist
1944 ;; (identity . tramp-sh-file-name-handler) should always be the last
1945 ;; entry, since `identity' always matches.
1946 '((identity . tramp-sh-file-name-handler))
4007ba5b
KG
1947 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1948If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1949calling HANDLER.")
1950
0664ff72 1951;;; Internal functions which must come first:
fb7933a3 1952
00d6fd04
MA
1953(defsubst tramp-debug-message (vec fmt-string &rest args)
1954 "Append message to debug buffer.
1955Message is formatted with FMT-STRING as control string and the remaining
1956ARGS to actually emit the message (if applicable)."
1957 (when (get-buffer (tramp-buffer-name vec))
1958 (with-current-buffer (tramp-get-debug-buffer vec)
1959 (goto-char (point-max))
70c11b0b
MA
1960 ;; Headline.
1961 (when (bobp)
1962 (insert
1963 (format
1964 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1965 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1966 emacs-version tramp-version)))
00d6fd04
MA
1967 (unless (bolp)
1968 (insert "\n"))
70c11b0b 1969 ;; Timestamp.
736ac90f
MA
1970 (let ((now (current-time)))
1971 (insert (format-time-string "%T." now))
1972 (insert (format "%06d " (nth 2 now))))
70c11b0b 1973 ;; Calling function.
00d6fd04
MA
1974 (let ((btn 1) btf fn)
1975 (while (not fn)
1976 (setq btf (nth 1 (backtrace-frame btn)))
1977 (if (not btf)
1978 (setq fn "")
1979 (when (symbolp btf)
1980 (setq fn (symbol-name btf))
1981 (unless (and (string-match "^tramp" fn)
1982 (not (string-match
1983 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
1984 fn)))
1985 (setq fn nil)))
1986 (setq btn (1+ btn))))
1987 ;; The following code inserts filename and line number.
1988 ;; Should be deactivated by default, because it is time
1989 ;; consuming.
1990; (let ((ffn (find-function-noselect (intern fn))))
1991; (insert
1992; (format
1993; "%s:%d: "
1994; (file-name-nondirectory (buffer-file-name (car ffn)))
1995; (with-current-buffer (car ffn)
1996; (1+ (count-lines (point-min) (cdr ffn)))))))
1997 (insert (format "%s " fn)))
70c11b0b 1998 ;; The message.
00d6fd04
MA
1999 (insert (apply 'format fmt-string args)))))
2000
946a5aeb
MA
2001(defvar tramp-message-show-message t
2002 "Show Tramp message in the minibuffer.
2003This variable is used to disable messages from `tramp-error'.
2004The messages are visible anyway, because an error is raised.")
2005
00d6fd04 2006(defsubst tramp-message (vec-or-proc level fmt-string &rest args)
fb7933a3 2007 "Emit a message depending on verbosity level.
a4aeb9a4 2008VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
00d6fd04
MA
2009vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2010less than LEVEL. The message is emitted only if `tramp-verbose' is
2011greater than or equal to LEVEL.
2012
2013The message is also logged into the debug buffer when `tramp-verbose'
2014is greater than or equal 4.
2015
2016Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2017control string and the remaining ARGS to actually emit the message (if
2018applicable)."
2019 (condition-case nil
2020 (when (<= level tramp-verbose)
2021 ;; Match data must be preserved!
2022 (save-match-data
2023 ;; Display only when there is a minimum level.
946a5aeb 2024 (when (and tramp-message-show-message (<= level 3))
00d6fd04
MA
2025 (apply 'message
2026 (concat
2027 (cond
2028 ((= level 0) "")
2029 ((= level 1) "")
2030 ((= level 2) "Warning: ")
2031 (t "Tramp: "))
2032 fmt-string)
2033 args))
2034 ;; Log only when there is a minimum level.
2035 (when (>= tramp-verbose 4)
2036 (when (and vec-or-proc
2037 (processp vec-or-proc)
2038 (buffer-name (process-buffer vec-or-proc)))
2039 (with-current-buffer (process-buffer vec-or-proc)
2040 ;; Translate proc to vec.
2041 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2042 (when (and vec-or-proc (vectorp vec-or-proc))
2043 (apply 'tramp-debug-message
2044 vec-or-proc
2045 (concat (format "(%d) # " level) fmt-string)
2046 args)))))
2047 ;; Suppress all errors.
2048 (error nil)))
2049
2050(defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2051 "Emit an error.
2052VEC-OR-PROC identifies the connection to use, SIGNAL is the
2053signal identifier to be raised, remaining args passed to
2054`tramp-message'. Finally, signal SIGNAL is raised."
946a5aeb
MA
2055 (let (tramp-message-show-message)
2056 (tramp-message
2057 vec-or-proc 1 "%s"
2058 (error-message-string
2059 (list signal
2060 (get signal 'error-message)
2061 (apply 'format fmt-string args))))
2062 (signal signal (list (apply 'format fmt-string args)))))
00d6fd04
MA
2063
2064(defsubst tramp-error-with-buffer
2065 (buffer vec-or-proc signal fmt-string &rest args)
2066 "Emit an error, and show BUFFER.
2067If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2068an input event arrives. The other arguments are passed to `tramp-error'."
2069 (save-window-excursion
2070 (unwind-protect
2071 (apply 'tramp-error vec-or-proc signal fmt-string args)
2072 (when (and vec-or-proc (not (zerop tramp-verbose)))
2073 (let ((enable-recursive-minibuffers t))
2074 (pop-to-buffer
2075 (or (and (bufferp buffer) buffer)
2076 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2077 (tramp-get-buffer vec-or-proc)))
2078 (sit-for 30))))))
fb7933a3 2079
c62c9d08
KG
2080(defmacro with-parsed-tramp-file-name (filename var &rest body)
2081 "Parse a Tramp filename and make components available in the body.
2082
2083First arg FILENAME is evaluated and dissected into its components.
2084Second arg VAR is a symbol. It is used as a variable name to hold
2085the filename structure. It is also used as a prefix for the variables
2086holding the components. For example, if VAR is the symbol `foo', then
00d6fd04
MA
2087`foo' will be bound to the whole structure, `foo-method' will be bound to
2088the method component, and so on for `foo-user', `foo-host', `foo-localname'.
c62c9d08
KG
2089
2090Remaining args are Lisp expressions to be evaluated (inside an implicit
2091`progn').
2092
00d6fd04
MA
2093If VAR is nil, then we bind `v' to the structure and `method', `user',
2094`host', `localname' to the components."
c62c9d08 2095 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
c62c9d08
KG
2096 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2097 (tramp-file-name-method ,(or var 'v)))
2098 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2099 (tramp-file-name-user ,(or var 'v)))
2100 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2101 (tramp-file-name-host ,(or var 'v)))
7432277c
KG
2102 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2103 (tramp-file-name-localname ,(or var 'v))))
c62c9d08
KG
2104 ,@body))
2105
2106(put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
00d6fd04 2107(put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
9e6ab520 2108(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
c62c9d08 2109
00d6fd04
MA
2110(defmacro with-file-property (vec file property &rest body)
2111 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2112FILE must be a local file name on a connection identified via VEC."
2113 `(if (file-name-absolute-p ,file)
2114 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2115 (when (eq value 'undef)
2116 ;; We cannot pass @body as parameter to
2117 ;; `tramp-set-file-property' because it mangles our
2118 ;; debug messages.
2119 (setq value (progn ,@body))
2120 (tramp-set-file-property ,vec ,file ,property value))
2121 value)
2122 ,@body))
9ce8462a 2123
00d6fd04
MA
2124(put 'with-file-property 'lisp-indent-function 3)
2125(put 'with-file-property 'edebug-form-spec t)
9e6ab520 2126(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
00d6fd04
MA
2127
2128(defmacro with-connection-property (key property &rest body)
2129 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2130 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2131 (when (eq value 'undef)
2132 ;; We cannot pass ,@body as parameter to
2133 ;; `tramp-set-connection-property' because it mangles our debug
2134 ;; messages.
2135 (setq value (progn ,@body))
2136 (tramp-set-connection-property ,key ,property value))
2137 value))
9ce8462a 2138
00d6fd04
MA
2139(put 'with-connection-property 'lisp-indent-function 2)
2140(put 'with-connection-property 'edebug-form-spec t)
9e6ab520 2141(font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
00d6fd04 2142
628c97b2
GM
2143(eval-and-compile ; silence compiler
2144 (if (memq system-type '(cygwin windows-nt))
2145 (defun tramp-drop-volume-letter (name)
2146 "Cut off unnecessary drive letter from file NAME.
2147The function `tramp-handle-expand-file-name' calls `expand-file-name'
2148locally on a remote file name. When the local system is a W32 system
2149but the remote system is Unix, this introduces a superfluous drive
2150letter into the file name. This function removes it."
2151 (save-match-data
2152 (if (string-match tramp-root-regexp name)
2153 (replace-match "/" nil t name)
2154 name)))
2155
2156 (defalias 'tramp-drop-volume-letter 'identity)))
2157
9c13938d 2158(defsubst tramp-make-tramp-temp-file (vec)
a6e96327 2159 "Create a temporary file on the remote host identified by VEC.
9c13938d
MA
2160Return the local name of the temporary file."
2161 (let ((prefix
2162 (tramp-make-tramp-file-name
2163 (tramp-file-name-method vec)
2164 (tramp-file-name-user vec)
2165 (tramp-file-name-host vec)
113e2a84
MA
2166 (tramp-drop-volume-letter
2167 (expand-file-name
2168 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
9c13938d
MA
2169 result)
2170 (while (not result)
2171 ;; `make-temp-file' would be the natural choice for
2172 ;; implementation. But it calls `write-region' internally,
2173 ;; which also needs a temporary file - we would end in an
2174 ;; infinite loop.
2175 (setq result (make-temp-name prefix))
2176 (if (file-exists-p result)
2177 (setq result nil)
2178 ;; This creates the file by side effect.
2179 (set-file-times result)
2180 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2181
2182 ;; Return the local part.
2183 (with-parsed-tramp-file-name result nil localname)))
8a4438b6
MA
2184
2185
16674e4f
KG
2186;;; Config Manipulation Functions:
2187
2188(defun tramp-set-completion-function (method function-list)
2189 "Sets the list of completion functions for METHOD.
2190FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2191The FUNCTION is intended to parse FILE according its syntax.
2192It might be a predefined FUNCTION, or a user defined FUNCTION.
2193Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
8fc29035 2194`tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
8daea7fc
KG
2195and `tramp-parse-netrc'.
2196
16674e4f
KG
2197Example:
2198
2199 (tramp-set-completion-function
2200 \"ssh\"
8daea7fc
KG
2201 '((tramp-parse-sconfig \"/etc/ssh_config\")
2202 (tramp-parse-sconfig \"~/.ssh/config\")))"
16674e4f 2203
5ec2cc41
KG
2204 (let ((r function-list)
2205 (v function-list))
2206 (setq tramp-completion-function-alist
2207 (delete (assoc method tramp-completion-function-alist)
2208 tramp-completion-function-alist))
2209
2210 (while v
00d6fd04 2211 ;; Remove double entries.
5ec2cc41
KG
2212 (when (member (car v) (cdr v))
2213 (setcdr v (delete (car v) (cdr v))))
00d6fd04 2214 ;; Check for function and file or registry key.
5ec2cc41 2215 (unless (and (functionp (nth 0 (car v)))
00d6fd04
MA
2216 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2217 ;; Windows registry.
2218 (and (memq system-type '(cygwin windows-nt))
a4aeb9a4
MA
2219 (zerop
2220 (tramp-local-call-process
2221 "reg" nil nil nil "query" (nth 1 (car v)))))
00d6fd04
MA
2222 ;; Configuration file.
2223 (file-exists-p (nth 1 (car v)))))
5ec2cc41
KG
2224 (setq r (delete (car v) r)))
2225 (setq v (cdr v)))
2226
2227 (when r
4007ba5b 2228 (add-to-list 'tramp-completion-function-alist
5ec2cc41 2229 (cons method r)))))
16674e4f
KG
2230
2231(defun tramp-get-completion-function (method)
00d6fd04 2232 "Returns a list of completion functions for METHOD.
16674e4f 2233For definition of that list see `tramp-set-completion-function'."
00d6fd04
MA
2234 (cons
2235 ;; Hosts visited once shall be remembered.
2236 `(tramp-parse-connection-properties ,method)
2237 ;; The method related defaults.
2238 (cdr (assoc method tramp-completion-function-alist))))
16674e4f 2239
d037d501 2240
0664ff72 2241;;; Fontification of `read-file-name':
d037d501 2242
0664ff72 2243;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
d037d501
MA
2244(defvar tramp-rfn-eshadow-overlay)
2245(make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2246
2247(defun tramp-rfn-eshadow-setup-minibuffer ()
2248 "Set up a minibuffer for `file-name-shadow-mode'.
2249Adds another overlay hiding filename parts according to Tramp's
2250special handling of `substitute-in-file-name'."
9ce8462a 2251 (when (symbol-value 'minibuffer-completing-file-name)
d037d501 2252 (setq tramp-rfn-eshadow-overlay
9e6ab520
MA
2253 (funcall (symbol-function 'make-overlay)
2254 (funcall (symbol-function 'minibuffer-prompt-end))
2255 (funcall (symbol-function 'minibuffer-prompt-end))))
d037d501 2256 ;; Copy rfn-eshadow-overlay properties.
9e6ab520
MA
2257 (let ((props (funcall (symbol-function 'overlay-properties)
2258 (symbol-value 'rfn-eshadow-overlay))))
d037d501 2259 (while props
9e6ab520
MA
2260 (funcall (symbol-function 'overlay-put)
2261 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
d037d501
MA
2262
2263(when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2264 (add-hook 'rfn-eshadow-setup-minibuffer-hook
48846dc5
MA
2265 'tramp-rfn-eshadow-setup-minibuffer)
2266 (add-hook 'tramp-unload-hook
aa485f7c
MA
2267 (lambda ()
2268 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2269 'tramp-rfn-eshadow-setup-minibuffer))))
d037d501 2270
adcbca53
MA
2271(defconst tramp-rfn-eshadow-update-overlay-regexp
2272 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2273
d037d501
MA
2274(defun tramp-rfn-eshadow-update-overlay ()
2275 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2276This is intended to be used as a minibuffer `post-command-hook' for
2277`file-name-shadow-mode'; the minibuffer should have already
2278been set up by `rfn-eshadow-setup-minibuffer'."
2279 ;; In remote files name, there is a shadowing just for the local part.
9e6ab520
MA
2280 (let ((end (or (funcall (symbol-function 'overlay-end)
2281 (symbol-value 'rfn-eshadow-overlay))
2282 (funcall (symbol-function 'minibuffer-prompt-end)))))
2283 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
bd316474
KY
2284 (save-excursion
2285 (save-restriction
2286 (narrow-to-region
adcbca53
MA
2287 (1+ (or (string-match
2288 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2289 end))
2290 (point-max))
bd316474
KY
2291 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2292 (rfn-eshadow-update-overlay-hook nil))
dea31ca6 2293 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
bd316474 2294 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
d037d501
MA
2295
2296(when (boundp 'rfn-eshadow-update-overlay-hook)
2297 (add-hook 'rfn-eshadow-update-overlay-hook
2298 'tramp-rfn-eshadow-update-overlay))
2299
2300
fb7933a3
KG
2301;;; File Name Handler Functions:
2302
fb7933a3
KG
2303(defun tramp-handle-make-symbolic-link
2304 (filename linkname &optional ok-if-already-exists)
00d6fd04 2305 "Like `make-symbolic-link' for Tramp files.
cebb4ec6 2306If LINKNAME is a non-Tramp file, it is used verbatim as the target of
7432277c 2307the symlink. If LINKNAME is a Tramp file, only the localname component is
cebb4ec6
KG
2308used as the target of the symlink.
2309
7432277c
KG
2310If LINKNAME is a Tramp file and the localname component is relative, then
2311it is expanded first, before the localname component is taken. Note that
cebb4ec6
KG
2312this can give surprising results if the user/host for the source and
2313target of the symlink differ."
c62c9d08 2314 (with-parsed-tramp-file-name linkname l
00d6fd04 2315 (let ((ln (tramp-get-remote-ln l))
87bdd2c7
MA
2316 (cwd (tramp-run-real-handler
2317 'file-name-directory (list l-localname))))
c62c9d08 2318 (unless ln
00d6fd04
MA
2319 (tramp-error
2320 l 'file-error
2321 "Making a symbolic link. ln(1) does not exist on the remote host."))
c62c9d08
KG
2322
2323 ;; Do the 'confirm if exists' thing.
cebb4ec6 2324 (when (file-exists-p linkname)
c62c9d08
KG
2325 ;; What to do?
2326 (if (or (null ok-if-already-exists) ; not allowed to exist
2327 (and (numberp ok-if-already-exists)
2328 (not (yes-or-no-p
2329 (format
2330 "File %s already exists; make it a link anyway? "
7432277c 2331 l-localname)))))
00d6fd04
MA
2332 (tramp-error
2333 l 'file-already-exists "File %s already exists" l-localname)
cebb4ec6
KG
2334 (delete-file linkname)))
2335
7432277c 2336 ;; If FILENAME is a Tramp name, use just the localname component.
cebb4ec6 2337 (when (tramp-tramp-file-p filename)
1834b39f
MA
2338 (setq filename
2339 (tramp-file-name-localname
2340 (tramp-dissect-file-name (expand-file-name filename)))))
bf247b6e 2341
c62c9d08
KG
2342 ;; Right, they are on the same host, regardless of user, method, etc.
2343 ;; We now make the link on the remote machine. This will occur as the user
2344 ;; that FILENAME belongs to.
2345 (zerop
2346 (tramp-send-command-and-check
00d6fd04 2347 l (format "cd %s && %s -sf %s %s" cwd ln filename l-localname) t)))))
fb7933a3 2348
fb7933a3 2349(defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
00d6fd04
MA
2350 "Like `load' for Tramp files."
2351 (with-parsed-tramp-file-name (expand-file-name file) nil
c62c9d08
KG
2352 (unless nosuffix
2353 (cond ((file-exists-p (concat file ".elc"))
2354 (setq file (concat file ".elc")))
2355 ((file-exists-p (concat file ".el"))
2356 (setq file (concat file ".el")))))
2357 (when must-suffix
2358 ;; The first condition is always true for absolute file names.
2359 ;; Included for safety's sake.
2360 (unless (or (file-name-directory file)
2361 (string-match "\\.elc?\\'" file))
00d6fd04
MA
2362 (tramp-error
2363 v 'file-error
2364 "File `%s' does not include a `.el' or `.elc' suffix" file)))
c62c9d08
KG
2365 (unless noerror
2366 (when (not (file-exists-p file))
00d6fd04 2367 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
c62c9d08
KG
2368 (if (not (file-exists-p file))
2369 nil
00d6fd04 2370 (unless nomessage (tramp-message v 0 "Loading %s..." file))
c62c9d08
KG
2371 (let ((local-copy (file-local-copy file)))
2372 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
ce2cc728
MA
2373 (unwind-protect
2374 (load local-copy noerror t t)
2375 (delete-file local-copy)))
00d6fd04 2376 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
c62c9d08 2377 t)))
fb7933a3 2378
a4aeb9a4 2379;; Localname manipulation functions that grok Tramp localnames...
c0fc6170
MA
2380(defun tramp-handle-file-name-as-directory (file)
2381 "Like `file-name-as-directory' but aware of Tramp files."
2382 ;; `file-name-as-directory' would be sufficient except localname is
2383 ;; the empty string.
2384 (let ((v (tramp-dissect-file-name file t)))
2385 ;; Run the command on the localname portion only.
2386 (tramp-make-tramp-file-name
2387 (tramp-file-name-method v)
2388 (tramp-file-name-user v)
2389 (tramp-file-name-host v)
2390 (tramp-run-real-handler
2391 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2392
fb7933a3 2393(defun tramp-handle-file-name-directory (file)
00d6fd04 2394 "Like `file-name-directory' but aware of Tramp files."
9ce8462a
MA
2395 ;; Everything except the last filename thing is the directory. We
2396 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2397 ;; the remote file name parts. This is a problem when we are in
2398 ;; file name completion.
2399 (let ((v (tramp-dissect-file-name file t)))
a01b1e22
MA
2400 ;; Run the command on the localname portion only.
2401 (tramp-make-tramp-file-name
9ce8462a
MA
2402 (tramp-file-name-method v)
2403 (tramp-file-name-user v)
2404 (tramp-file-name-host v)
87bdd2c7
MA
2405 (tramp-run-real-handler
2406 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
fb7933a3
KG
2407
2408(defun tramp-handle-file-name-nondirectory (file)
00d6fd04 2409 "Like `file-name-nondirectory' but aware of Tramp files."
c62c9d08 2410 (with-parsed-tramp-file-name file nil
87bdd2c7 2411 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
fb7933a3
KG
2412
2413(defun tramp-handle-file-truename (filename &optional counter prev-dirs)
00d6fd04 2414 "Like `file-truename' for Tramp files."
48ddd622 2415 (with-parsed-tramp-file-name (expand-file-name filename) nil
00d6fd04 2416 (with-file-property v localname "file-truename"
aff67808 2417 (let* ((directory-sep-char ?/) ; for XEmacs
70c11b0b 2418 (steps (tramp-compat-split-string localname "/"))
87bdd2c7
MA
2419 (localnamedir (tramp-run-real-handler
2420 'file-name-as-directory (list localname)))
00d6fd04
MA
2421 (is-dir (string= localname localnamedir))
2422 (thisstep nil)
2423 (numchase 0)
2424 ;; Don't make the following value larger than necessary.
2425 ;; People expect an error message in a timely fashion when
2426 ;; something is wrong; otherwise they might think that Emacs
2427 ;; is hung. Of course, correctness has to come first.
2428 (numchase-limit 20)
2429 (result nil) ;result steps in reverse order
2430 symlink-target)
2431 (tramp-message v 4 "Finding true name for `%s'" filename)
2432 (while (and steps (< numchase numchase-limit))
2433 (setq thisstep (pop steps))
2434 (tramp-message
2435 v 5 "Check %s"
2436 (mapconcat 'identity
2437 (append '("") (reverse result) (list thisstep))
2438 "/"))
2439 (setq symlink-target
2440 (nth 0 (file-attributes
2441 (tramp-make-tramp-file-name
2442 method user host
2443 (mapconcat 'identity
2444 (append '("")
2445 (reverse result)
2446 (list thisstep))
2447 "/")))))
2448 (cond ((string= "." thisstep)
2449 (tramp-message v 5 "Ignoring step `.'"))
2450 ((string= ".." thisstep)
2451 (tramp-message v 5 "Processing step `..'")
2452 (pop result))
2453 ((stringp symlink-target)
2454 ;; It's a symlink, follow it.
2455 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2456 (setq numchase (1+ numchase))
2457 (when (file-name-absolute-p symlink-target)
2458 (setq result nil))
2459 ;; If the symlink was absolute, we'll get a string like
2460 ;; "/user@host:/some/target"; extract the
2461 ;; "/some/target" part from it.
2462 (when (tramp-tramp-file-p symlink-target)
2463 (unless (tramp-equal-remote filename symlink-target)
2464 (tramp-error
2465 v 'file-error
2466 "Symlink target `%s' on wrong host" symlink-target))
2467 (setq symlink-target localname))
2468 (setq steps
70c11b0b 2469 (append (tramp-compat-split-string symlink-target "/")
00d6fd04
MA
2470 steps)))
2471 (t
2472 ;; It's a file.
2473 (setq result (cons thisstep result)))))
2474 (when (>= numchase numchase-limit)
2475 (tramp-error
2476 v 'file-error
2477 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2478 (setq result (reverse result))
2479 ;; Combine list to form string.
2480 (setq result
2481 (if result
2482 (mapconcat 'identity (cons "" result) "/")
2483 "/"))
2484 (when (and is-dir (or (string= "" result)
2485 (not (string= (substring result -1) "/"))))
2486 (setq result (concat result "/")))
2487 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2488 (tramp-make-tramp-file-name method user host result)))))
fb7933a3
KG
2489
2490;; Basic functions.
2491
2492(defun tramp-handle-file-exists-p (filename)
00d6fd04 2493 "Like `file-exists-p' for Tramp files."
c62c9d08 2494 (with-parsed-tramp-file-name filename nil
00d6fd04 2495 (with-file-property v localname "file-exists-p"
fb7933a3 2496 (zerop (tramp-send-command-and-check
00d6fd04 2497 v
fb7933a3 2498 (format
00d6fd04
MA
2499 "%s %s"
2500 (tramp-get-file-exists-command v)
7432277c 2501 (tramp-shell-quote-argument localname)))))))
fb7933a3 2502
00d6fd04
MA
2503;; Inodes don't exist for some file systems. Therefore we must
2504;; generate virtual ones. Used in `find-buffer-visiting'. The method
2505;; applied might be not so efficient (Ange-FTP uses hashes). But
2506;; performance isn't the major issue given that file transfer will
2507;; take time.
2508(defvar tramp-inodes nil
2509 "Keeps virtual inodes numbers.")
2510
8daea7fc
KG
2511;; Devices must distinguish physical file systems. The device numbers
2512;; provided by "lstat" aren't unique, because we operate on different hosts.
2513;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2514;; EFS use device number "-1". In order to be different, we use device number
b946a456 2515;; (-1 . x), whereby "x" is unique for a given (method user host).
8daea7fc
KG
2516(defvar tramp-devices nil
2517 "Keeps virtual device numbers.")
2518
fb7933a3
KG
2519;; CCC: This should check for an error condition and signal failure
2520;; when something goes wrong.
2521;; Daniel Pittman <daniel@danann.net>
c951aecb 2522(defun tramp-handle-file-attributes (filename &optional id-format)
00d6fd04
MA
2523 "Like `file-attributes' for Tramp files."
2524 (unless id-format (setq id-format 'integer))
aa485f7c
MA
2525 ;; Don't modify `last-coding-system-used' by accident.
2526 (let ((last-coding-system-used last-coding-system-used))
2527 (with-parsed-tramp-file-name (expand-file-name filename) nil
2528 (with-file-property v localname (format "file-attributes-%s" id-format)
7f49fe46
MA
2529 (save-excursion
2530 (tramp-convert-file-attributes
2531 v
2532 (cond
2533 ((tramp-get-remote-stat v)
2534 (tramp-do-file-attributes-with-stat v localname id-format))
2535 ((tramp-get-remote-perl v)
2536 (tramp-do-file-attributes-with-perl v localname id-format))
2537 (t
2538 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2539
2540(defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
00d6fd04 2541 "Implement `file-attributes' for Tramp files using the ls(1) command."
fb7933a3
KG
2542 (let (symlinkp dirp
2543 res-inode res-filemodes res-numlinks
2544 res-uid res-gid res-size res-symlink-target)
00d6fd04 2545 (tramp-message vec 5 "file attributes with ls: %s" localname)
fb7933a3 2546 (tramp-send-command
00d6fd04 2547 vec
680db9ac
MA
2548 (format "(%s %s || %s -h %s) && %s %s %s"
2549 (tramp-get-file-exists-command vec)
2550 (tramp-shell-quote-argument localname)
2551 (tramp-get-test-command vec)
2552 (tramp-shell-quote-argument localname)
00d6fd04 2553 (tramp-get-ls-command vec)
c82c5727 2554 (if (eq id-format 'integer) "-ildn" "-ild")
7432277c 2555 (tramp-shell-quote-argument localname)))
fb7933a3 2556 ;; parse `ls -l' output ...
00d6fd04 2557 (with-current-buffer (tramp-get-buffer vec)
680db9ac
MA
2558 (when (> (buffer-size) 0)
2559 (goto-char (point-min))
2560 ;; ... inode
2561 (setq res-inode
2562 (condition-case err
2563 (read (current-buffer))
2564 (invalid-read-syntax
2565 (when (and (equal (cadr err)
2566 "Integer constant overflow in reader")
2567 (string-match
2568 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2569 (car (cddr err))))
2570 (let* ((big (read (substring (car (cddr err)) 0
2571 (match-beginning 1))))
2572 (small (read (match-string 1 (car (cddr err)))))
2573 (twiddle (/ small 65536)))
2574 (cons (+ big twiddle)
2575 (- small (* twiddle 65536))))))))
2576 ;; ... file mode flags
2577 (setq res-filemodes (symbol-name (read (current-buffer))))
2578 ;; ... number links
2579 (setq res-numlinks (read (current-buffer)))
2580 ;; ... uid and gid
2581 (setq res-uid (read (current-buffer)))
2582 (setq res-gid (read (current-buffer)))
2583 (if (eq id-format 'integer)
2584 (progn
2585 (unless (numberp res-uid) (setq res-uid -1))
2586 (unless (numberp res-gid) (setq res-gid -1)))
2587 (progn
2588 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2589 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2590 ;; ... size
2591 (setq res-size (read (current-buffer)))
2592 ;; From the file modes, figure out other stuff.
2593 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2594 (setq dirp (eq ?d (aref res-filemodes 0)))
2595 ;; if symlink, find out file name pointed to
2596 (when symlinkp
2597 (search-forward "-> ")
2598 (setq res-symlink-target
2599 (buffer-substring (point) (tramp-compat-line-end-position))))
2600 ;; return data gathered
2601 (list
2602 ;; 0. t for directory, string (name linked to) for symbolic
2603 ;; link, or nil.
2604 (or dirp res-symlink-target)
2605 ;; 1. Number of links to file.
2606 res-numlinks
2607 ;; 2. File uid.
2608 res-uid
2609 ;; 3. File gid.
2610 res-gid
2611 ;; 4. Last access time, as a list of two integers. First
2612 ;; integer has high-order 16 bits of time, second has low 16
2613 ;; bits.
2614 ;; 5. Last modification time, likewise.
2615 ;; 6. Last status change time, likewise.
2616 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2617 ;; 7. Size in bytes (-1, if number is out of range).
2618 res-size
2619 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2620 res-filemodes
2621 ;; 9. t if file's gid would change if file were deleted and
2622 ;; recreated. Will be set in `tramp-convert-file-attributes'
2623 t
2624 ;; 10. inode number.
2625 res-inode
2626 ;; 11. Device number. Will be replaced by a virtual device number.
2627 -1
2628 )))))
fb7933a3 2629
7f49fe46 2630(defun tramp-do-file-attributes-with-perl
00d6fd04
MA
2631 (vec localname &optional id-format)
2632 "Implement `file-attributes' for Tramp files using a Perl script."
2633 (tramp-message vec 5 "file attributes with perl: %s" localname)
2634 (tramp-maybe-send-script
2635 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2636 (tramp-send-command-and-read
2637 vec
2638 (format "tramp_perl_file_attributes %s %s"
2639 (tramp-shell-quote-argument localname) id-format)))
2640
7f49fe46 2641(defun tramp-do-file-attributes-with-stat
00d6fd04
MA
2642 (vec localname &optional id-format)
2643 "Implement `file-attributes' for Tramp files using stat(1) command."
2644 (tramp-message vec 5 "file attributes with stat: %s" localname)
2645 (tramp-send-command-and-read
2646 vec
2647 (format
680db9ac
MA
2648 "((%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s || echo nil)"
2649 (tramp-get-file-exists-command vec)
2650 (tramp-shell-quote-argument localname)
2651 (tramp-get-test-command vec)
2652 (tramp-shell-quote-argument localname)
00d6fd04
MA
2653 (tramp-get-remote-stat vec)
2654 (if (eq id-format 'integer) "%u" "\"%U\"")
2655 (if (eq id-format 'integer) "%g" "\"%G\"")
2656 (tramp-shell-quote-argument localname))))
8daea7fc 2657
fb7933a3 2658(defun tramp-handle-set-visited-file-modtime (&optional time-list)
00d6fd04 2659 "Like `set-visited-file-modtime' for Tramp files."
fb7933a3
KG
2660 (unless (buffer-file-name)
2661 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2662 (buffer-name)))
48ddd622
MA
2663 (if time-list
2664 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
11948172
MA
2665 (let ((f (buffer-file-name))
2666 coding-system-used)
48ddd622
MA
2667 (with-parsed-tramp-file-name f nil
2668 (let* ((attr (file-attributes f))
2669 ;; '(-1 65535) means file doesn't exists yet.
2670 (modtime (or (nth 5 attr) '(-1 65535))))
11948172
MA
2671 (when (boundp 'last-coding-system-used)
2672 (setq coding-system-used (symbol-value 'last-coding-system-used)))
48ddd622 2673 ;; We use '(0 0) as a don't-know value. See also
7f49fe46 2674 ;; `tramp-do-file-attributes-with-ls'.
48ddd622
MA
2675 (if (not (equal modtime '(0 0)))
2676 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
00d6fd04 2677 (progn
48ddd622 2678 (tramp-send-command
00d6fd04 2679 v
48ddd622 2680 (format "%s -ild %s"
00d6fd04 2681 (tramp-get-ls-command v)
48ddd622 2682 (tramp-shell-quote-argument localname)))
48ddd622
MA
2683 (setq attr (buffer-substring (point)
2684 (progn (end-of-line) (point)))))
00d6fd04
MA
2685 (tramp-set-file-property
2686 v localname "visited-file-modtime-ild" attr))
11948172
MA
2687 (when (boundp 'last-coding-system-used)
2688 (set 'last-coding-system-used coding-system-used))
d2a2c17f 2689 nil)))))
fb7933a3 2690
c62c9d08
KG
2691;; This function makes the same assumption as
2692;; `tramp-handle-set-visited-file-modtime'.
2693(defun tramp-handle-verify-visited-file-modtime (buf)
00d6fd04 2694 "Like `verify-visited-file-modtime' for Tramp files.
c08e6004
MA
2695At the time `verify-visited-file-modtime' calls this function, we
2696already know that the buffer is visiting a file and that
2697`visited-file-modtime' does not return 0. Do not call this
2698function directly, unless those two cases are already taken care
2699of."
c62c9d08 2700 (with-current-buffer buf
b15d0c4c
MA
2701 ;; There is no file visiting the buffer, or the buffer has no
2702 ;; recorded last modification time.
2703 (if (or (not (buffer-file-name))
2704 (eq (visited-file-modtime) 0))
d2a2c17f 2705 t
b15d0c4c
MA
2706 (let ((f (buffer-file-name)))
2707 (with-parsed-tramp-file-name f nil
bce04fee 2708 (tramp-flush-file-property v localname)
b15d0c4c
MA
2709 (let* ((attr (file-attributes f))
2710 (modtime (nth 5 attr))
2711 (mt (visited-file-modtime)))
bf247b6e 2712
70c11b0b
MA
2713 (cond
2714 ;; File exists, and has a known modtime.
b15d0c4c
MA
2715 ((and attr (not (equal modtime '(0 0))))
2716 (< (abs (tramp-time-diff
2717 modtime
2718 ;; For compatibility, deal with both the old
70c11b0b
MA
2719 ;; (HIGH . LOW) and the new (HIGH LOW) return
2720 ;; values of `visited-file-modtime'.
b15d0c4c
MA
2721 (if (atom (cdr mt))
2722 (list (car mt) (cdr mt))
2723 mt)))
2724 2))
70c11b0b 2725 ;; Modtime has the don't know value.
b15d0c4c 2726 (attr
00d6fd04
MA
2727 (tramp-send-command
2728 v
2729 (format "%s -ild %s"
2730 (tramp-get-ls-command v)
2731 (tramp-shell-quote-argument localname)))
2732 (with-current-buffer (tramp-get-buffer v)
b15d0c4c
MA
2733 (setq attr (buffer-substring
2734 (point) (progn (end-of-line) (point)))))
00d6fd04
MA
2735 (equal
2736 attr
2737 (tramp-get-file-property
2738 v localname "visited-file-modtime-ild" "")))
70c11b0b
MA
2739 ;; If file does not exist, say it is not modified if and
2740 ;; only if that agrees with the buffer's record.
b15d0c4c 2741 (t (equal mt '(-1 65535))))))))))
c62c9d08 2742
fb7933a3 2743(defun tramp-handle-set-file-modes (filename mode)
00d6fd04 2744 "Like `set-file-modes' for Tramp files."
c62c9d08 2745 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2746 (tramp-flush-file-property v localname)
2747 (unless (zerop (tramp-send-command-and-check
2748 v
2749 (format "chmod %s %s"
2750 (tramp-decimal-to-octal mode)
2751 (tramp-shell-quote-argument localname))))
2752 ;; FIXME: extract the proper text from chmod's stderr.
2753 (tramp-error
2754 v 'file-error "Error while changing file's mode %s" filename))))
fb7933a3 2755
ce3f516f
MA
2756(defun tramp-handle-set-file-times (filename &optional time)
2757 "Like `set-file-times' for Tramp files."
2758 (zerop
9e6ab520 2759 (if (file-remote-p filename)
ce3f516f 2760 (with-parsed-tramp-file-name filename nil
8d60099b 2761 (tramp-flush-file-property v localname)
ce3f516f
MA
2762 (let ((time (if (or (null time) (equal time '(0 0)))
2763 (current-time)
2764 time))
2765 (utc
2766 ;; With GNU Emacs, `format-time-string' has an
2767 ;; optional parameter UNIVERSAL. This is preferred,
2768 ;; because we could handle the case when the remote
2769 ;; host is located in a different time zone as the
2770 ;; local host.
2771 (and (functionp 'subr-arity)
2772 (subrp (symbol-function 'format-time-string))
2773 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2774 (symbol-function
2775 'format-time-string)))))))
2776 (tramp-send-command-and-check
2777 v (format "%s touch -t %s %s"
2778 (if utc "TZ=UTC; export TZ;" "")
2779 (if utc
2780 (format-time-string "%Y%m%d%H%M.%S" time t)
2781 (format-time-string "%Y%m%d%H%M.%S" time))
2782 (tramp-shell-quote-argument localname)))))
8d60099b 2783
ce3f516f
MA
2784 ;; We handle also the local part, because in older Emacsen,
2785 ;; without `set-file-times', this function is an alias for this.
2786 ;; We are local, so we don't need the UTC settings.
a4aeb9a4 2787 (tramp-local-call-process
ce3f516f
MA
2788 "touch" nil nil nil "-t"
2789 (format-time-string "%Y%m%d%H%M.%S" time)
2790 (tramp-shell-quote-argument filename)))))
2791
8d60099b
MA
2792(defun tramp-set-file-uid-gid (filename &optional uid gid)
2793 "Set the ownership for FILENAME.
2794If UID and GID are provided, these values are used; otherwise uid
2795and gid of the corresponding user is taken. Both parameters must be integers."
70c11b0b
MA
2796 ;; Modern Unices allow chown only for root. So we might need
2797 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2798 ;; working with su(do)? when it is needed, so it shall succeed in
2799 ;; the majority of cases.
aa485f7c
MA
2800 ;; Don't modify `last-coding-system-used' by accident.
2801 (let ((last-coding-system-used last-coding-system-used))
2802 (if (file-remote-p filename)
2803 (with-parsed-tramp-file-name filename nil
2804 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2805 ;; If we are root on the local host, we can do it directly.
2806 (tramp-set-file-uid-gid localname uid gid)
2807 (let ((uid (or (and (integerp uid) uid)
2808 (tramp-get-remote-uid v 'integer)))
2809 (gid (or (and (integerp gid) gid)
2810 (tramp-get-remote-gid v 'integer))))
2811 (tramp-send-command
2812 v (format
2813 "chown %d:%d %s" uid gid
2814 (tramp-shell-quote-argument localname))))))
2815
2816 ;; We handle also the local part, because there doesn't exist
2817 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2818 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2819 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2820 (tramp-local-call-process
2821 "chown" nil nil nil
2822 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
8d60099b 2823
fb7933a3
KG
2824;; Simple functions using the `test' command.
2825
2826(defun tramp-handle-file-executable-p (filename)
00d6fd04 2827 "Like `file-executable-p' for Tramp files."
c62c9d08 2828 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2829 (with-file-property v localname "file-executable-p"
2830 (zerop (tramp-run-test "-x" filename)))))
fb7933a3
KG
2831
2832(defun tramp-handle-file-readable-p (filename)
00d6fd04 2833 "Like `file-readable-p' for Tramp files."
c62c9d08 2834 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2835 (with-file-property v localname "file-readable-p"
2836 (zerop (tramp-run-test "-r" filename)))))
fb7933a3
KG
2837
2838;; When the remote shell is started, it looks for a shell which groks
2839;; tilde expansion. Here, we assume that all shells which grok tilde
2840;; expansion will also provide a `test' command which groks `-nt' (for
2841;; newer than). If this breaks, tell me about it and I'll try to do
2842;; something smarter about it.
2843(defun tramp-handle-file-newer-than-file-p (file1 file2)
00d6fd04 2844 "Like `file-newer-than-file-p' for Tramp files."
fb7933a3
KG
2845 (cond ((not (file-exists-p file1))
2846 nil)
2847 ((not (file-exists-p file2))
2848 t)
91879624 2849 ;; We are sure both files exist at this point.
fb7933a3
KG
2850 (t
2851 (save-excursion
91879624
KG
2852 ;; We try to get the mtime of both files. If they are not
2853 ;; equal to the "dont-know" value, then we subtract the times
2854 ;; and obtain the result.
2855 (let ((fa1 (file-attributes file1))
2856 (fa2 (file-attributes file2)))
2857 (if (and (not (equal (nth 5 fa1) '(0 0)))
2858 (not (equal (nth 5 fa2) '(0 0))))
01917a18 2859 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
91879624
KG
2860 ;; If one of them is the dont-know value, then we can
2861 ;; still try to run a shell command on the remote host.
2862 ;; However, this only works if both files are Tramp
2863 ;; files and both have the same method, same user, same
2864 ;; host.
00d6fd04
MA
2865 (unless (tramp-equal-remote file1 file2)
2866 (with-parsed-tramp-file-name
2867 (if (tramp-tramp-file-p file1) file1 file2) nil
2868 (tramp-error
2869 v 'file-error
2870 "Files %s and %s must have same method, user, host"
2871 file1 file2)))
2872 (with-parsed-tramp-file-name file1 nil
2873 (zerop (tramp-run-test2
2874 (tramp-get-test-nt-command v) file1 file2)))))))))
fb7933a3
KG
2875
2876;; Functions implemented using the basic functions above.
2877
2878(defun tramp-handle-file-modes (filename)
00d6fd04 2879 "Like `file-modes' for Tramp files."
5da24108
MA
2880 (let ((truename (or (file-truename filename) filename)))
2881 (when (file-exists-p truename)
2882 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
fb7933a3 2883
b86c1cd8
MA
2884(defun tramp-default-file-modes (filename)
2885 "Return file modes of FILENAME as integer.
2886If the file modes of FILENAME cannot be determined, return the
974647ac
MA
2887value of `default-file-modes', without execute permissions."
2888 (or (file-modes filename)
2889 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
b86c1cd8 2890
fb7933a3 2891(defun tramp-handle-file-directory-p (filename)
00d6fd04 2892 "Like `file-directory-p' for Tramp files."
fb7933a3
KG
2893 ;; Care must be taken that this function returns `t' for symlinks
2894 ;; pointing to directories. Surely the most obvious implementation
2895 ;; would be `test -d', but that returns false for such symlinks.
2896 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
2897 ;; I now think he's right. So we could be using `test -d', couldn't
2898 ;; we?
2899 ;;
2900 ;; Alternatives: `cd %s', `test -d %s'
c62c9d08 2901 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2902 (with-file-property v localname "file-directory-p"
2903 (zerop (tramp-run-test "-d" filename)))))
fb7933a3
KG
2904
2905(defun tramp-handle-file-regular-p (filename)
00d6fd04
MA
2906 "Like `file-regular-p' for Tramp files."
2907 (and (file-exists-p filename)
2908 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
fb7933a3
KG
2909
2910(defun tramp-handle-file-symlink-p (filename)
00d6fd04 2911 "Like `file-symlink-p' for Tramp files."
c62c9d08 2912 (with-parsed-tramp-file-name filename nil
c951aecb 2913 (let ((x (car (file-attributes filename))))
b25a52cc
KG
2914 (when (stringp x)
2915 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2916 ;; might do weird things.
2917 (if (file-name-absolute-p x)
00d6fd04 2918 (tramp-make-tramp-file-name method user host x)
b25a52cc 2919 x)))))
fb7933a3
KG
2920
2921(defun tramp-handle-file-writable-p (filename)
00d6fd04 2922 "Like `file-writable-p' for Tramp files."
c62c9d08 2923 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2924 (with-file-property v localname "file-writable-p"
2925 (if (file-exists-p filename)
2926 ;; Existing files must be writable.
2927 (zerop (tramp-run-test "-w" filename))
2928 ;; If file doesn't exist, check if directory is writable.
2929 (and (zerop (tramp-run-test
2930 "-d" (file-name-directory filename)))
2931 (zerop (tramp-run-test
2932 "-w" (file-name-directory filename))))))))
fb7933a3
KG
2933
2934(defun tramp-handle-file-ownership-preserved-p (filename)
00d6fd04 2935 "Like `file-ownership-preserved-p' for Tramp files."
c62c9d08 2936 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
2937 (with-file-property v localname "file-ownership-preserved-p"
2938 (let ((attributes (file-attributes filename)))
2939 ;; Return t if the file doesn't exist, since it's true that no
2940 ;; information would be lost by an (attempted) delete and create.
2941 (or (null attributes)
2942 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
fb7933a3
KG
2943
2944;; Other file name ops.
2945
fb7933a3 2946(defun tramp-handle-directory-file-name (directory)
00d6fd04 2947 "Like `directory-file-name' for Tramp files."
7432277c
KG
2948 ;; If localname component of filename is "/", leave it unchanged.
2949 ;; Otherwise, remove any trailing slash from localname component.
8daea7fc
KG
2950 ;; Method, host, etc, are unchanged. Does it make sense to try
2951 ;; to avoid parsing the filename?
c62c9d08 2952 (with-parsed-tramp-file-name directory nil
7432277c
KG
2953 (if (and (not (zerop (length localname)))
2954 (eq (aref localname (1- (length localname))) ?/)
2955 (not (string= localname "/")))
8daea7fc
KG
2956 (substring directory 0 -1)
2957 directory)))
fb7933a3
KG
2958
2959;; Directory listings.
2960
00d6fd04
MA
2961(defun tramp-handle-directory-files
2962 (directory &optional full match nosort files-only)
2963 "Like `directory-files' for Tramp files."
2964 ;; FILES-ONLY is valid for XEmacs only.
2965 (when (file-directory-p directory)
2966 (setq directory (expand-file-name directory))
2967 (let ((temp (nreverse (file-name-all-completions "" directory)))
2968 result item)
2969
2970 (while temp
2971 (setq item (directory-file-name (pop temp)))
2972 (when (and (or (null match) (string-match match item))
2973 (or (null files-only)
2974 ;; files only
2975 (and (equal files-only t) (file-regular-p item))
2976 ;; directories only
2977 (file-directory-p item)))
2978 (push (if full (expand-file-name item directory) item)
2979 result)))
c62c9d08
KG
2980 result)))
2981
c82c5727
LH
2982(defun tramp-handle-directory-files-and-attributes
2983 (directory &optional full match nosort id-format)
00d6fd04
MA
2984 "Like `directory-files-and-attributes' for Tramp files."
2985 (unless id-format (setq id-format 'integer))
2986 (when (file-directory-p directory)
2987 (setq directory (expand-file-name directory))
2988 (let* ((temp
9e6ab520 2989 (tramp-compat-copy-tree
00d6fd04
MA
2990 (with-parsed-tramp-file-name directory nil
2991 (with-file-property
2992 v localname
2993 (format "directory-files-and-attributes-%s" id-format)
2994 (save-excursion
2995 (mapcar
aa485f7c
MA
2996 (lambda (x)
2997 (cons (car x)
2998 (tramp-convert-file-attributes v (cdr x))))
7f49fe46
MA
2999 (cond
3000 ((tramp-get-remote-stat v)
3001 (tramp-do-directory-files-and-attributes-with-stat
3002 v localname id-format))
3003 ((tramp-get-remote-perl v)
3004 (tramp-do-directory-files-and-attributes-with-perl
3005 v localname id-format)))))))))
00d6fd04
MA
3006 result item)
3007
3008 (while temp
3009 (setq item (pop temp))
3010 (when (or (null match) (string-match match (car item)))
3011 (when full
3012 (setcar item (expand-file-name (car item) directory)))
3013 (push item result)))
3014
3015 (if nosort
3016 result
3017 (sort result (lambda (x y) (string< (car x) (car y))))))))
3018
7f49fe46 3019(defun tramp-do-directory-files-and-attributes-with-perl
00d6fd04
MA
3020 (vec localname &optional id-format)
3021 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3022 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3023 (tramp-maybe-send-script
3024 vec tramp-perl-directory-files-and-attributes
3025 "tramp_perl_directory_files_and_attributes")
3026 (let ((object
3027 (tramp-send-command-and-read
3028 vec
3029 (format "tramp_perl_directory_files_and_attributes %s %s"
3030 (tramp-shell-quote-argument localname) id-format))))
3031 (when (stringp object) (tramp-error vec 'file-error object))
3032 object))
3033
7f49fe46 3034(defun tramp-do-directory-files-and-attributes-with-stat
00d6fd04
MA
3035 (vec localname &optional id-format)
3036 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3037 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3038 (tramp-send-command-and-read
3039 vec
3040 (format
3041 (concat
70c11b0b
MA
3042 ;; We must care about filenames with spaces, or starting with
3043 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3044 ;; but it does not work on all remote systems. Therefore, we
3045 ;; quote the filenames via sed.
3046 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
d4443a0d 3047 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
00d6fd04
MA
3048 "echo \")\"")
3049 (tramp-shell-quote-argument localname)
3050 (tramp-get-ls-command vec)
3051 (tramp-get-remote-stat vec)
3052 (if (eq id-format 'integer) "%u" "\"%U\"")
3053 (if (eq id-format 'integer) "%g" "\"%G\""))))
c82c5727 3054
c62c9d08 3055;; This function should return "foo/" for directories and "bar" for
00d6fd04 3056;; files.
c62c9d08 3057(defun tramp-handle-file-name-all-completions (filename directory)
00d6fd04
MA
3058 "Like `file-name-all-completions' for Tramp files."
3059 (unless (save-match-data (string-match "/" filename))
9c13938d 3060 (with-parsed-tramp-file-name (expand-file-name directory) nil
b50dd0d2
MA
3061 ;; Flush the directory cache. There could be changed directory
3062 ;; contents.
3063 (when (and (integerp tramp-completion-reread-directory-timeout)
3064 (> (tramp-time-diff
3065 (current-time)
3066 (tramp-get-file-property
3067 v localname "last-completion" '(0 0 0)))
3068 tramp-completion-reread-directory-timeout))
3069 (tramp-flush-file-property v localname))
3070
00d6fd04
MA
3071 (all-completions
3072 filename
3073 (mapcar
3074 'list
3075 (with-file-property v localname "file-name-all-completions"
3076 (let (result)
3077 (tramp-barf-unless-okay
3078 v
3079 (format "cd %s" (tramp-shell-quote-argument localname))
3080 "tramp-handle-file-name-all-completions: Couldn't `cd %s'"
3081 (tramp-shell-quote-argument localname))
3082
3083 ;; Get a list of directories and files, including reliably
3084 ;; tagging the directories with a trailing '/'. Because I
3085 ;; rock. --daniel@danann.net
3086 (tramp-send-command
3087 v
65a099b6 3088 (format (concat "%s -a 2>/dev/null | while read f; do "
00d6fd04
MA
3089 "if %s -d \"$f\" 2>/dev/null; "
3090 "then echo \"$f/\"; else echo \"$f\"; fi; done")
3091 (tramp-get-ls-command v)
3092 (tramp-get-test-command v)))
3093
3094 ;; Now grab the output.
3095 (with-current-buffer (tramp-get-buffer v)
3096 (goto-char (point-max))
3097 (while (zerop (forward-line -1))
9e6ab520
MA
3098 (push (buffer-substring
3099 (point) (tramp-compat-line-end-position))
00d6fd04
MA
3100 result)))
3101
b50dd0d2
MA
3102 (tramp-set-file-property
3103 v localname "last-completion" (current-time))
00d6fd04 3104 result)))))))
fb7933a3
KG
3105
3106;; The following isn't needed for Emacs 20 but for 19.34?
e1e17cae
MA
3107(defun tramp-handle-file-name-completion
3108 (filename directory &optional predicate)
00d6fd04 3109 "Like `file-name-completion' for Tramp files."
fb7933a3
KG
3110 (unless (tramp-tramp-file-p directory)
3111 (error
3112 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3113 directory))
83e20b5c
MA
3114 (try-completion
3115 filename
3116 (mapcar 'list (file-name-all-completions filename directory))
3117 (when predicate
3118 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
fb7933a3
KG
3119
3120;; cp, mv and ln
3121
3122(defun tramp-handle-add-name-to-file
3123 (filename newname &optional ok-if-already-exists)
00d6fd04
MA
3124 "Like `add-name-to-file' for Tramp files."
3125 (unless (tramp-equal-remote filename newname)
3126 (with-parsed-tramp-file-name
3127 (if (tramp-tramp-file-p filename) filename newname) nil
3128 (tramp-error
3129 v 'file-error
3130 "add-name-to-file: %s"
3131 "only implemented for same method, same user, same host")))
c62c9d08
KG
3132 (with-parsed-tramp-file-name filename v1
3133 (with-parsed-tramp-file-name newname v2
00d6fd04 3134 (let ((ln (when v1 (tramp-get-remote-ln v1))))
c62c9d08
KG
3135 (when (and (not ok-if-already-exists)
3136 (file-exists-p newname)
3137 (not (numberp ok-if-already-exists))
3138 (y-or-n-p
3139 (format
3140 "File %s already exists; make it a new name anyway? "
3141 newname)))
00d6fd04
MA
3142 (tramp-error
3143 v2 'file-error
3144 "add-name-to-file: file %s already exists" newname))
3145 (tramp-flush-file-property v2 v2-localname)
c62c9d08 3146 (tramp-barf-unless-okay
00d6fd04 3147 v1
7432277c
KG
3148 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3149 (tramp-shell-quote-argument v2-localname))
c62c9d08
KG
3150 "error with add-name-to-file, see buffer `%s' for details"
3151 (buffer-name))))))
fb7933a3
KG
3152
3153(defun tramp-handle-copy-file
8d60099b 3154 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
00d6fd04 3155 "Like `copy-file' for Tramp files."
fb7933a3 3156 ;; Check if both files are local -- invoke normal copy-file.
9e6ab520 3157 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3158 (setq filename (expand-file-name filename))
3159 (setq newname (expand-file-name newname))
9e6ab520 3160 (cond
a4aeb9a4 3161 ;; At least one file a Tramp file?
9e6ab520
MA
3162 ((or (tramp-tramp-file-p filename)
3163 (tramp-tramp-file-p newname))
3164 (tramp-do-copy-or-rename-file
3165 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3166 ;; Compat section.
3167 (preserve-uid-gid
fb7933a3 3168 (tramp-run-real-handler
8d60099b 3169 'copy-file
9e6ab520
MA
3170 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3171 (t
3172 (tramp-run-real-handler
3173 'copy-file (list filename newname ok-if-already-exists keep-date)))))
fb7933a3 3174
263c02ef
MA
3175(defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3176 "Like `copy-directory' for Tramp files."
3177 (let ((t1 (tramp-tramp-file-p dirname))
3178 (t2 (tramp-tramp-file-p newname)))
3179 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3180 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3181 ;; When DIRNAME and NEWNAME are remote, they must have
3182 ;; the same method.
3183 (or (null t1) (null t2)
3184 (string-equal (file-remote-p dirname 'method)
3185 (file-remote-p newname 'method))))
3186 ;; scp or rsync DTRT.
3187 (progn
3188 (setq dirname (directory-file-name (expand-file-name dirname))
3189 newname (directory-file-name (expand-file-name newname)))
3190 (if (and (file-directory-p newname)
3191 (not (string-equal (file-name-nondirectory dirname)
3192 (file-name-nondirectory newname))))
3193 (setq newname
3194 (expand-file-name
3195 (file-name-nondirectory dirname) newname)))
3196 (if (not (file-directory-p (file-name-directory newname)))
3197 (make-directory (file-name-directory newname) parents))
3198 (tramp-do-copy-or-rename-file-out-of-band
3199 'copy dirname newname keep-date))
3200 ;; We must do it file-wise.
3201 (tramp-run-real-handler
3202 'copy-directory (list dirname newname keep-date parents))))))
3203
fb7933a3
KG
3204(defun tramp-handle-rename-file
3205 (filename newname &optional ok-if-already-exists)
00d6fd04 3206 "Like `rename-file' for Tramp files."
fb7933a3 3207 ;; Check if both files are local -- invoke normal rename-file.
a4aeb9a4 3208 ;; Otherwise, use Tramp from local system.
fb7933a3
KG
3209 (setq filename (expand-file-name filename))
3210 (setq newname (expand-file-name newname))
a4aeb9a4 3211 ;; At least one file a Tramp file?
fb7933a3
KG
3212 (if (or (tramp-tramp-file-p filename)
3213 (tramp-tramp-file-p newname))
3214 (tramp-do-copy-or-rename-file
8d60099b 3215 'rename filename newname ok-if-already-exists t t)
00d6fd04
MA
3216 (tramp-run-real-handler
3217 'rename-file (list filename newname ok-if-already-exists))))
fb7933a3
KG
3218
3219(defun tramp-do-copy-or-rename-file
8d60099b 3220 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3221 "Copy or rename a remote file.
3222OP must be `copy' or `rename' and indicates the operation to perform.
3223FILENAME specifies the file to copy or rename, NEWNAME is the name of
3224the new file (for copy) or the new name of the file (for rename).
3225OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3226KEEP-DATE means to make sure that NEWNAME has the same timestamp
8d60099b
MA
3227as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3228the uid and gid if both files are on the same host.
fb7933a3
KG
3229
3230This function is invoked by `tramp-handle-copy-file' and
3231`tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3232and `rename'. FILENAME and NEWNAME must be absolute file names."
3233 (unless (memq op '(copy rename))
3234 (error "Unknown operation `%s', must be `copy' or `rename'" op))
90dc758d 3235 (let ((t1 (tramp-tramp-file-p filename))
00d6fd04 3236 (t2 (tramp-tramp-file-p newname)))
5ec2cc41 3237
da1975d7
MA
3238 (when (and (not ok-if-already-exists) (file-exists-p newname))
3239 (with-parsed-tramp-file-name (if t1 filename newname) nil
3240 (tramp-error
3241 v 'file-already-exists "File %s already exists" newname)))
5ec2cc41 3242
905fb90e
MA
3243 (with-parsed-tramp-file-name (if t1 filename newname) nil
3244 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3245
00d6fd04
MA
3246 (prog1
3247 (cond
3248 ;; Both are Tramp files.
3249 ((and t1 t2)
3250 (with-parsed-tramp-file-name filename v1
3251 (with-parsed-tramp-file-name newname v2
3252 (cond
3253 ;; Shortcut: if method, host, user are the same for both
3254 ;; files, we invoke `cp' or `mv' on the remote host
3255 ;; directly.
3256 ((tramp-equal-remote filename newname)
3257 (tramp-do-copy-or-rename-file-directly
8d60099b
MA
3258 op filename newname
3259 ok-if-already-exists keep-date preserve-uid-gid))
3260
905fb90e 3261 ;; Try out-of-band operation.
7f49fe46
MA
3262 ((tramp-method-out-of-band-p
3263 v1 (nth 7 (file-attributes filename)))
00d6fd04
MA
3264 (tramp-do-copy-or-rename-file-out-of-band
3265 op filename newname keep-date))
8d60099b 3266
00d6fd04
MA
3267 ;; No shortcut was possible. So we copy the
3268 ;; file first. If the operation was `rename', we go
3269 ;; back and delete the original file (if the copy was
3270 ;; successful). The approach is simple-minded: we
3271 ;; create a new buffer, insert the contents of the
3272 ;; source file into it, then write out the buffer to
3273 ;; the target file. The advantage is that it doesn't
3274 ;; matter which filename handlers are used for the
3275 ;; source and target file.
3276 (t
3277 (tramp-do-copy-or-rename-file-via-buffer
3278 op filename newname keep-date))))))
3279
3280 ;; One file is a Tramp file, the other one is local.
3281 ((or t1 t2)
3282 (with-parsed-tramp-file-name (if t1 filename newname) nil
8d60099b
MA
3283 (cond
3284 ;; Fast track on local machine.
3285 ((tramp-local-host-p v)
3286 (tramp-do-copy-or-rename-file-directly
3287 op filename newname
3288 ok-if-already-exists keep-date preserve-uid-gid))
3289
3290 ;; If the Tramp file has an out-of-band method, the corresponding
3291 ;; copy-program can be invoked.
7f49fe46 3292 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
8d60099b
MA
3293 (tramp-do-copy-or-rename-file-out-of-band
3294 op filename newname keep-date))
3295
3296 ;; Use the inline method via a Tramp buffer.
3297 (t (tramp-do-copy-or-rename-file-via-buffer
3298 op filename newname keep-date)))))
00d6fd04
MA
3299
3300 (t
3301 ;; One of them must be a Tramp file.
3302 (error "Tramp implementation says this cannot happen")))
8d60099b 3303
484ea0b6
MA
3304 ;; In case of `rename', we must flush the cache of the source file.
3305 (when (and t1 (eq op 'rename))
3306 (with-parsed-tramp-file-name filename nil
3307 (tramp-flush-file-property v localname)))
3308
00d6fd04
MA
3309 ;; When newname did exist, we have wrong cached values.
3310 (when t2
3311 (with-parsed-tramp-file-name newname nil
905fb90e
MA
3312 (tramp-flush-file-property v localname)))
3313
3314 (with-parsed-tramp-file-name (if t1 filename newname) nil
3315 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
7432277c 3316
38c65fca 3317(defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
90dc758d
KG
3318 "Use an Emacs buffer to copy or rename a file.
3319First arg OP is either `copy' or `rename' and indicates the operation.
3320FILENAME is the source file, NEWNAME the target file.
3321KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
8a798e41
MA
3322 (with-temp-buffer
3323 ;; We must disable multibyte, because binary data shall not be
3324 ;; converted.
3325 (set-buffer-multibyte nil)
3326 (let ((coding-system-for-read 'binary)
3327 (jka-compr-inhibit t))
3328 (insert-file-contents-literally filename))
3329 ;; We don't want the target file to be compressed, so we let-bind
3330 ;; `jka-compr-inhibit' to t.
3331 (let ((coding-system-for-write 'binary)
3332 (jka-compr-inhibit t))
3333 (write-region (point-min) (point-max) newname)))
3334 ;; KEEP-DATE handling.
3335 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3336 ;; Set the mode.
b86c1cd8 3337 (set-file-modes newname (tramp-default-file-modes filename))
8a798e41
MA
3338 ;; If the operation was `rename', delete the original file.
3339 (unless (eq op 'copy) (delete-file filename)))
fb7933a3
KG
3340
3341(defun tramp-do-copy-or-rename-file-directly
8d60099b 3342 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
fb7933a3
KG
3343 "Invokes `cp' or `mv' on the remote system.
3344OP must be one of `copy' or `rename', indicating `cp' or `mv',
8d60099b
MA
3345respectively. FILENAME specifies the file to copy or rename,
3346NEWNAME is the name of the new file (for copy) or the new name of
3347the file (for rename). Both files must reside on the same host.
3348KEEP-DATE means to make sure that NEWNAME has the same timestamp
3349as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3350the uid and gid from FILENAME."
8a4438b6 3351 (let ((t1 (tramp-tramp-file-p filename))
4f4126e6
MA
3352 (t2 (tramp-tramp-file-p newname))
3353 (file-times (nth 5 (file-attributes filename)))
3354 (file-modes (tramp-default-file-modes filename)))
8a4438b6
MA
3355 (with-parsed-tramp-file-name (if t1 filename newname) nil
3356 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3357 ((eq op 'copy) "cp -f")
3358 ((eq op 'rename) "mv -f")
3359 (t (tramp-error
3360 v 'file-error
3361 "Unknown operation `%s', must be `copy' or `rename'"
3362 op))))
3363 (localname1
3364 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3365 (localname2
3366 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
258800f8 3367 (prefix (file-remote-p (if t1 filename newname))))
8d60099b 3368
8d60099b 3369 (cond
8a4438b6
MA
3370 ;; Both files are on a remote host, with same user.
3371 ((and t1 t2)
3372 (tramp-send-command
3373 v
3374 (format "%s %s %s" cmd
3375 (tramp-shell-quote-argument localname1)
3376 (tramp-shell-quote-argument localname2)))
3377 (with-current-buffer (tramp-get-buffer v)
3378 (goto-char (point-min))
3379 (unless
3380 (or
3381 (and keep-date
3382 ;; Mask cp -f error.
3383 (re-search-forward
3384 tramp-operation-not-permitted-regexp nil t))
3385 (zerop (tramp-send-command-and-check v nil)))
3386 (tramp-error-with-buffer
3387 nil v 'file-error
3388 "Copying directly failed, see buffer `%s' for details."
3389 (buffer-name)))))
3390
3391 ;; We are on the local host.
3392 ((or t1 t2)
8d60099b 3393 (cond
8a4438b6 3394 ;; We can do it directly.
87bdd2c7
MA
3395 ((let (file-name-handler-alist)
3396 (and (file-readable-p localname1)
3397 (file-writable-p (file-name-directory localname2))
3398 (or (file-directory-p localname2)
3399 (file-writable-p localname2))))
8d60099b 3400 (if (eq op 'copy)
9e6ab520
MA
3401 (tramp-compat-copy-file
3402 localname1 localname2 ok-if-already-exists
3403 keep-date preserve-uid-gid)
87bdd2c7
MA
3404 (tramp-run-real-handler
3405 'rename-file (list localname1 localname2 ok-if-already-exists))))
8a4438b6
MA
3406
3407 ;; We can do it directly with `tramp-send-command'
946a5aeb
MA
3408 ((and (file-readable-p (concat prefix localname1))
3409 (file-writable-p
3410 (file-name-directory (concat prefix localname2)))
3411 (or (file-directory-p (concat prefix localname2))
3412 (file-writable-p (concat prefix localname2))))
8a4438b6
MA
3413 (tramp-do-copy-or-rename-file-directly
3414 op (concat prefix localname1) (concat prefix localname2)
3415 ok-if-already-exists keep-date t)
3416 ;; We must change the ownership to the local user.
8d60099b 3417 (tramp-set-file-uid-gid
8a4438b6
MA
3418 (concat prefix localname2)
3419 (tramp-get-local-uid 'integer)
3420 (tramp-get-local-gid 'integer)))
8d60099b 3421
8a4438b6
MA
3422 ;; We need a temporary file in between.
3423 (t
2c418c5b
MA
3424 ;; Create the temporary file.
3425 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
917b89a6 3426 (unwind-protect
2c418c5b
MA
3427 (progn
3428 (cond
3429 (t1
917b89a6
MA
3430 (or
3431 (zerop
3432 (tramp-send-command-and-check
3433 v (format
3434 "%s %s %s" cmd
3435 (tramp-shell-quote-argument localname1)
3436 (tramp-shell-quote-argument tmpfile))))
3437 (tramp-error-with-buffer
3438 nil v 'file-error
3439 "Copying directly failed, see buffer `%s' for details."
3440 (tramp-get-buffer v)))
2c418c5b 3441 ;; We must change the ownership as remote user.
917b89a6
MA
3442 ;; Since this does not work reliable, we also
3443 ;; give read permissions.
3444 (set-file-modes
3445 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3446 (tramp-set-file-uid-gid
3447 (concat prefix tmpfile)
3448 (tramp-get-local-uid 'integer)
3449 (tramp-get-local-gid 'integer)))
3450 (t2
3451 (if (eq op 'copy)
3452 (tramp-compat-copy-file
5ab38c3c 3453 localname1 tmpfile t
2c418c5b
MA
3454 keep-date preserve-uid-gid)
3455 (tramp-run-real-handler
3456 'rename-file
5ab38c3c 3457 (list localname1 tmpfile t)))
2c418c5b 3458 ;; We must change the ownership as local user.
917b89a6
MA
3459 ;; Since this does not work reliable, we also
3460 ;; give read permissions.
3461 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
2c418c5b
MA
3462 (tramp-set-file-uid-gid
3463 tmpfile
3464 (tramp-get-remote-uid v 'integer)
3465 (tramp-get-remote-gid v 'integer))))
3466
3467 ;; Move the temporary file to its destination.
3468 (cond
3469 (t2
917b89a6
MA
3470 (or
3471 (zerop
3472 (tramp-send-command-and-check
3473 v (format
3474 "cp -f -p %s %s"
3475 (tramp-shell-quote-argument tmpfile)
3476 (tramp-shell-quote-argument localname2))))
3477 (tramp-error-with-buffer
3478 nil v 'file-error
3479 "Copying directly failed, see buffer `%s' for details."
3480 (tramp-get-buffer v))))
2c418c5b 3481 (t1
ce2cc728
MA
3482 (tramp-run-real-handler
3483 'rename-file
2c418c5b
MA
3484 (list tmpfile localname2 ok-if-already-exists)))))
3485
917b89a6
MA
3486 ;; Save exit.
3487 (condition-case nil
3488 (delete-file tmpfile)
3489 (error)))))))))
8d60099b
MA
3490
3491 ;; Set the time and mode. Mask possible errors.
8d60099b 3492 (condition-case nil
1f107aed 3493 (when keep-date
4f4126e6
MA
3494 (set-file-times newname file-times)
3495 (set-file-modes newname file-modes))
8d60099b
MA
3496 (error)))))
3497
5ec2cc41 3498(defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
7432277c 3499 "Invoke rcp program to copy.
905fb90e 3500The method used must be an out-of-band method."
38c65fca 3501 (let ((t1 (tramp-tramp-file-p filename))
5ec2cc41 3502 (t2 (tramp-tramp-file-p newname))
946a5aeb 3503 copy-program copy-args copy-env copy-keep-date port spec
00d6fd04
MA
3504 source target)
3505
3506 (with-parsed-tramp-file-name (if t1 filename newname) nil
905fb90e 3507 (if (and t1 t2)
00d6fd04 3508
905fb90e
MA
3509 ;; Both are Tramp files. We shall optimize it, when the
3510 ;; methods for filename and newname are the same.
3511 (let ((tmpfile (tramp-compat-make-temp-file localname)))
3512 (unwind-protect
3513 (progn
3514 (tramp-do-copy-or-rename-file-out-of-band
3515 op filename tmpfile keep-date)
3516 (tramp-do-copy-or-rename-file-out-of-band
3517 'rename tmpfile newname keep-date))
3518 ;; Save exit.
3519 (condition-case nil
3520 (delete-file tmpfile)
3521 (error))))
3522
3523 ;; Expand hops. Might be necessary for gateway methods.
3524 (setq v (car (tramp-compute-multi-hops v)))
3525 (aset v 3 localname)
3526
3527 ;; Check which ones of source and target are Tramp files.
3528 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
263c02ef
MA
3529 target (funcall
3530 (if (and (file-directory-p filename)
3531 (string-equal
3532 (file-name-nondirectory filename)
3533 (file-name-nondirectory newname)))
3534 'file-name-directory
3535 'identity)
3536 (if t2 (tramp-make-copy-program-file-name v) newname)))
905fb90e
MA
3537
3538 ;; Check for port number. Until now, there's no need for handling
3539 ;; like method, user, host.
3540 (setq host (tramp-file-name-real-host v)
3541 port (tramp-file-name-port v)
3542 port (or (and port (number-to-string port)) ""))
3543
3544 ;; Compose copy command.
3545 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3546 (?t . ,(tramp-get-connection-property
3547 (tramp-get-connection-process v) "temp-file" ""))
3548 (?k . ,(if keep-date " " "")))
3549 copy-program (tramp-get-method-parameter
3550 method 'tramp-copy-program)
3551 copy-keep-date (tramp-get-method-parameter
3552 method 'tramp-copy-keep-date)
3553 copy-args
3554 (delq
3555 nil
3556 (mapcar
aa485f7c
MA
3557 (lambda (x)
3558 (setq
3559 x
3560 ;; " " is indication for keep-date argument.
3561 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3562 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb
MA
3563 (tramp-get-method-parameter method 'tramp-copy-args)))
3564 copy-env
3565 (delq
3566 nil
3567 (mapcar
aa485f7c
MA
3568 (lambda (x)
3569 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3570 (unless (member "" x) (mapconcat 'identity x " ")))
946a5aeb 3571 (tramp-get-method-parameter method 'tramp-copy-env))))
905fb90e
MA
3572
3573 ;; Check for program.
3574 (when (and (fboundp 'executable-find)
3575 (not (let ((default-directory
3576 (tramp-compat-temporary-file-directory)))
3577 (executable-find copy-program))))
3578 (tramp-error
3579 v 'file-error "Cannot find copy program: %s" copy-program))
00d6fd04 3580
905fb90e
MA
3581 (unwind-protect
3582 (with-temp-buffer
3583 ;; The default directory must be remote.
3584 (let ((default-directory
946a5aeb
MA
3585 (file-name-directory (if t1 filename newname)))
3586 (process-environment (copy-sequence process-environment)))
905fb90e
MA
3587 ;; Set the transfer process properties.
3588 (tramp-set-connection-property
3589 v "process-name" (buffer-name (current-buffer)))
3590 (tramp-set-connection-property
3591 v "process-buffer" (current-buffer))
946a5aeb
MA
3592 (while copy-env
3593 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3594 (setenv (pop copy-env) (pop copy-env)))
905fb90e
MA
3595
3596 ;; Use an asynchronous process. By this, password can
3597 ;; be handled. The default directory must be local, in
3598 ;; order to apply the correct `copy-program'. We don't
3599 ;; set a timeout, because the copying of large files can
3600 ;; last longer than 60 secs.
3601 (let ((p (let ((default-directory
3602 (tramp-compat-temporary-file-directory)))
3603 (apply 'start-process
3604 (tramp-get-connection-property
3605 v "process-name" nil)
3606 (tramp-get-connection-property
3607 v "process-buffer" nil)
3608 copy-program
3609 (append copy-args (list source target))))))
3610 (tramp-message
3611 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3612 (tramp-set-process-query-on-exit-flag p nil)
3613 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
00d6fd04 3614
905fb90e
MA
3615 ;; Reset the transfer process properties.
3616 (tramp-set-connection-property v "process-name" nil)
3617 (tramp-set-connection-property v "process-buffer" nil))
00d6fd04 3618
905fb90e
MA
3619 ;; Handle KEEP-DATE argument.
3620 (when (and keep-date (not copy-keep-date))
3621 (set-file-times newname (nth 5 (file-attributes filename))))
01917a18 3622
905fb90e
MA
3623 ;; Set the mode.
3624 (unless (and keep-date copy-keep-date)
3625 (set-file-modes newname (tramp-default-file-modes filename))))
5ec2cc41 3626
905fb90e
MA
3627 ;; If the operation was `rename', delete the original file.
3628 (unless (eq op 'copy)
3629 (delete-file filename)))))
7432277c 3630
fb7933a3 3631(defun tramp-handle-make-directory (dir &optional parents)
00d6fd04 3632 "Like `make-directory' for Tramp files."
ac474af1 3633 (setq dir (expand-file-name dir))
c62c9d08 3634 (with-parsed-tramp-file-name dir nil
c15cdf02 3635 (tramp-flush-directory-property v (file-name-directory localname))
b1d06e75
KG
3636 (save-excursion
3637 (tramp-barf-unless-okay
00d6fd04 3638 v
9c13938d 3639 (format "%s %s"
b1d06e75 3640 (if parents "mkdir -p" "mkdir")
7432277c 3641 (tramp-shell-quote-argument localname))
b1d06e75 3642 "Couldn't make directory %s" dir))))
fb7933a3 3643
c15cdf02 3644(defun tramp-handle-delete-directory (directory &optional recursive)
00d6fd04 3645 "Like `delete-directory' for Tramp files."
ac474af1 3646 (setq directory (expand-file-name directory))
c62c9d08 3647 (with-parsed-tramp-file-name directory nil
00d6fd04
MA
3648 (tramp-flush-directory-property v localname)
3649 (unless (zerop (tramp-send-command-and-check
3650 v
c15cdf02
MA
3651 (format
3652 "%s %s"
3653 (if recursive "rm -rf" "rmdir")
3654 (tramp-shell-quote-argument localname))))
00d6fd04 3655 (tramp-error v 'file-error "Couldn't delete %s" directory))))
fb7933a3
KG
3656
3657(defun tramp-handle-delete-file (filename)
00d6fd04 3658 "Like `delete-file' for Tramp files."
ac474af1 3659 (setq filename (expand-file-name filename))
c62c9d08 3660 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3661 (tramp-flush-file-property v localname)
3662 (unless (zerop (tramp-send-command-and-check
3663 v
3664 (format "rm -f %s"
3665 (tramp-shell-quote-argument localname))))
3666 (tramp-error v 'file-error "Couldn't delete %s" filename))))
fb7933a3
KG
3667
3668;; Dired.
3669
3670;; CCC: This does not seem to be enough. Something dies when
a4aeb9a4 3671;; we try and delete two directories under Tramp :/
fb7933a3
KG
3672(defun tramp-handle-dired-recursive-delete-directory (filename)
3673 "Recursively delete the directory given.
00d6fd04 3674This is like `dired-recursive-delete-directory' for Tramp files."
c62c9d08 3675 (with-parsed-tramp-file-name filename nil
00d6fd04 3676 ;; Run a shell command 'rm -r <localname>'
260821d3 3677 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
00d6fd04
MA
3678 (unless (file-exists-p filename)
3679 (tramp-error v 'file-error "No such directory: %s" filename))
fb7933a3 3680 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
00d6fd04
MA
3681 (tramp-send-command
3682 v
9c13938d 3683 (format "rm -rf %s" (tramp-shell-quote-argument localname))
00d6fd04
MA
3684 ;; Don't read the output, do it explicitely.
3685 nil t)
fb7933a3
KG
3686 ;; Wait for the remote system to return to us...
3687 ;; This might take a while, allow it plenty of time.
00d6fd04 3688 (tramp-wait-for-output (tramp-get-connection-process v) 120)
fb7933a3 3689 ;; Make sure that it worked...
c15cdf02 3690 (tramp-flush-directory-property v localname)
07dfe738 3691 (and (file-exists-p filename)
00d6fd04
MA
3692 (tramp-error
3693 v 'file-error "Failed to recursively delete %s" filename))))
bf247b6e 3694
5ec2cc41 3695(defun tramp-handle-dired-compress-file (file &rest ok-flag)
00d6fd04 3696 "Like `dired-compress-file' for Tramp files."
5ec2cc41
KG
3697 ;; OK-FLAG is valid for XEmacs only, but not implemented.
3698 ;; Code stolen mainly from dired-aux.el.
3699 (with-parsed-tramp-file-name file nil
00d6fd04 3700 (tramp-flush-file-property v localname)
5ec2cc41
KG
3701 (save-excursion
3702 (let ((suffixes
3703 (if (not (featurep 'xemacs))
3704 ;; Emacs case
3705 (symbol-value 'dired-compress-file-suffixes)
3706 ;; XEmacs has `dired-compression-method-alist', which is
3707 ;; transformed into `dired-compress-file-suffixes' structure.
3708 (mapcar
aa485f7c
MA
3709 (lambda (x)
3710 (list (concat (regexp-quote (nth 1 x)) "\\'")
3711 nil
3712 (mapconcat 'identity (nth 3 x) " ")))
5ec2cc41
KG
3713 (symbol-value 'dired-compression-method-alist))))
3714 suffix)
3715 ;; See if any suffix rule matches this file name.
3716 (while suffixes
3717 (let (case-fold-search)
3718 (if (string-match (car (car suffixes)) localname)
3719 (setq suffix (car suffixes) suffixes nil))
3720 (setq suffixes (cdr suffixes))))
3721
3722 (cond ((file-symlink-p file)
3723 nil)
3724 ((and suffix (nth 2 suffix))
3725 ;; We found an uncompression rule.
00d6fd04 3726 (tramp-message v 0 "Uncompressing %s..." file)
5ec2cc41 3727 (when (zerop (tramp-send-command-and-check
00d6fd04
MA
3728 v (concat (nth 2 suffix) " " localname)))
3729 (tramp-message v 0 "Uncompressing %s...done" file)
38c65fca
KG
3730 ;; `dired-remove-file' is not defined in XEmacs
3731 (funcall (symbol-function 'dired-remove-file) file)
5ec2cc41
KG
3732 (string-match (car suffix) file)
3733 (concat (substring file 0 (match-beginning 0)))))
3734 (t
3735 ;; We don't recognize the file as compressed, so compress it.
3736 ;; Try gzip.
00d6fd04 3737 (tramp-message v 0 "Compressing %s..." file)
5ec2cc41 3738 (when (zerop (tramp-send-command-and-check
00d6fd04
MA
3739 v (concat "gzip -f " localname)))
3740 (tramp-message v 0 "Compressing %s...done" file)
38c65fca
KG
3741 ;; `dired-remove-file' is not defined in XEmacs
3742 (funcall (symbol-function 'dired-remove-file) file)
5ec2cc41
KG
3743 (cond ((file-exists-p (concat file ".gz"))
3744 (concat file ".gz"))
3745 ((file-exists-p (concat file ".z"))
3746 (concat file ".z"))
3747 (t nil)))))))))
fb7933a3 3748
70c11b0b
MA
3749(defun tramp-handle-dired-uncache (dir)
3750 "Like `dired-uncache' for Tramp files."
3751 (with-parsed-tramp-file-name dir nil
3752 (tramp-flush-file-property v localname)))
3753
fb7933a3
KG
3754;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
3755;; not sure at all that this is the right way to do it, but let's hope
3756;; it works for now, and wait for a guru to point out the Right Way to
3757;; achieve this.
3758;;(eval-when-compile
3759;; (unless (fboundp 'dired-insert-set-properties)
3760;; (fset 'dired-insert-set-properties 'ignore)))
3761;; Gerd suggests this:
3762(eval-when-compile (require 'dired))
3763;; Note that dired is required at run-time, too, when it is needed.
3764;; It is only needed on XEmacs for the function
3765;; `dired-insert-set-properties'.
3766
3767(defun tramp-handle-insert-directory
3768 (filename switches &optional wildcard full-directory-p)
00d6fd04
MA
3769 "Like `insert-directory' for Tramp files."
3770 (setq filename (expand-file-name filename))
3771 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
3772 (if (and (featurep 'ls-lisp)
3773 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
3774 (tramp-run-real-handler
3775 'insert-directory (list filename switches wildcard full-directory-p))
8e754ea2
MA
3776 (when (and (string-match "^--dired\\s-+" switches)
3777 (not (tramp-get-ls-command-with-dired v)))
00d6fd04
MA
3778 (setq switches (replace-match "" nil t switches)))
3779 (tramp-message
3780 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
c82c5727
LH
3781 switches filename (if wildcard "yes" "no")
3782 (if full-directory-p "yes" "no"))
3783 (when wildcard
87bdd2c7
MA
3784 (setq wildcard (tramp-run-real-handler
3785 'file-name-nondirectory (list localname)))
3786 (setq localname (tramp-run-real-handler
3787 'file-name-directory (list localname))))
c82c5727
LH
3788 (when (listp switches)
3789 (setq switches (mapconcat 'identity switches " ")))
3790 (unless full-directory-p
3791 (setq switches (concat "-d " switches)))
3792 (when wildcard
3793 (setq switches (concat switches " " wildcard)))
00d6fd04
MA
3794 ;; If `full-directory-p', we just say `ls -l FILENAME'.
3795 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
3796 (if full-directory-p
3797 (tramp-send-command
3798 v
3799 (format "%s %s %s"
3800 (tramp-get-ls-command v)
3801 switches
3802 (if wildcard
3803 localname
3804 (tramp-shell-quote-argument (concat localname ".")))))
3805 (tramp-barf-unless-okay
3806 v
3807 (format "cd %s" (tramp-shell-quote-argument
87bdd2c7
MA
3808 (tramp-run-real-handler
3809 'file-name-directory (list localname))))
00d6fd04 3810 "Couldn't `cd %s'"
87bdd2c7
MA
3811 (tramp-shell-quote-argument
3812 (tramp-run-real-handler 'file-name-directory (list localname))))
00d6fd04
MA
3813 (tramp-send-command
3814 v
3815 (format "%s %s %s"
3816 (tramp-get-ls-command v)
3817 switches
3818 (if (or wildcard
87bdd2c7
MA
3819 (zerop (length
3820 (tramp-run-real-handler
3821 'file-name-nondirectory (list localname)))))
00d6fd04
MA
3822 ""
3823 (tramp-shell-quote-argument
87bdd2c7
MA
3824 (tramp-run-real-handler
3825 'file-name-nondirectory (list localname)))))))
8e754ea2
MA
3826 (let ((beg (point)))
3827 ;; We cannot use `insert-buffer-substring' because the Tramp
3828 ;; buffer changes its contents before insertion due to calling
3829 ;; `expand-file' and alike.
3830 (insert
3831 (with-current-buffer (tramp-get-buffer v)
3832 (buffer-string)))
3833
3834 ;; Check for "--dired" output.
8e754ea2
MA
3835 (forward-line -2)
3836 (when (looking-at "//DIRED//")
7ba1d9c2 3837 (let ((end (tramp-compat-line-end-position))
8e754ea2
MA
3838 (linebeg (point)))
3839 ;; Now read the numeric positions of file names.
3840 (goto-char linebeg)
3841 (forward-word 1)
3842 (forward-char 3)
3843 (while (< (point) end)
3844 (let ((start (+ beg (read (current-buffer))))
3845 (end (+ beg (read (current-buffer)))))
7f49fe46 3846 (if (memq (char-after end) '(?\n ?\ ))
8e754ea2
MA
3847 ;; End is followed by \n or by " -> ".
3848 (put-text-property start end 'dired-filename t)))))
03db0efc 3849 ;; Remove trailing lines.
7ba1d9c2 3850 (goto-char (tramp-compat-line-beginning-position))
8e754ea2
MA
3851 (while (looking-at "//")
3852 (forward-line 1)
7ba1d9c2 3853 (delete-region (match-beginning 0) (point)))))
8e754ea2 3854 (goto-char (point-max)))))
fb7933a3 3855
fb7933a3 3856(defun tramp-handle-unhandled-file-name-directory (filename)
00d6fd04 3857 "Like `unhandled-file-name-directory' for Tramp files."
8a798e41
MA
3858 ;; With Emacs 23, we could simply return `nil'. But we must keep it
3859 ;; for backward compatibility.
ce3f516f 3860 (expand-file-name "~/"))
fb7933a3
KG
3861
3862;; Canonicalization of file names.
3863
fb7933a3 3864(defun tramp-handle-expand-file-name (name &optional dir)
00d6fd04 3865 "Like `expand-file-name' for Tramp files.
7432277c
KG
3866If the localname part of the given filename starts with \"/../\" then
3867the result will be a local, non-Tramp, filename."
fb7933a3
KG
3868 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
3869 (setq dir (or dir default-directory "/"))
3870 ;; Unless NAME is absolute, concat DIR and NAME.
3871 (unless (file-name-absolute-p name)
3872 (setq name (concat (file-name-as-directory dir) name)))
00d6fd04 3873 ;; If NAME is not a Tramp file, run the real handler.
fb7933a3 3874 (if (not (tramp-tramp-file-p name))
00d6fd04 3875 (tramp-run-real-handler 'expand-file-name (list name nil))
fb7933a3 3876 ;; Dissect NAME.
c62c9d08 3877 (with-parsed-tramp-file-name name nil
87bdd2c7 3878 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
7432277c 3879 (setq localname (concat "~/" localname)))
00d6fd04
MA
3880 ;; Tilde expansion if necessary. This needs a shell which
3881 ;; groks tilde expansion! The function `tramp-find-shell' is
3882 ;; supposed to find such a shell on the remote host. Please
3883 ;; tell me about it when this doesn't work on your system.
3884 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
3885 (let ((uname (match-string 1 localname))
3886 (fname (match-string 2 localname)))
3887 ;; We cannot simply apply "~/", because under sudo "~/" is
3888 ;; expanded to the local user home directory but to the
3889 ;; root home directory. On the other hand, using always
3890 ;; the default user name for tilde expansion is not
3891 ;; appropriate either, because ssh and companions might
3892 ;; use a user name from the config file.
3893 (when (and (string-equal uname "~")
3894 (string-match "\\`su\\(do\\)?\\'" method))
3895 (setq uname (concat uname user)))
3896 (setq uname
3897 (with-connection-property v uname
3898 (tramp-send-command v (format "cd %s; pwd" uname))
3899 (with-current-buffer (tramp-get-buffer v)
3900 (goto-char (point-min))
9e6ab520 3901 (buffer-substring (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
3902 (setq localname (concat uname fname))))
3903 ;; There might be a double slash, for example when "~/"
cb85dcd0 3904 ;; expands to "/". Remove this.
00d6fd04
MA
3905 (while (string-match "//" localname)
3906 (setq localname (replace-match "/" t t localname)))
3907 ;; No tilde characters in file name, do normal
a17632c1
MA
3908 ;; `expand-file-name' (this does "/./" and "/../"). We bind
3909 ;; `directory-sep-char' here for XEmacs on Windows, which would
3910 ;; otherwise use backslash. `default-directory' is bound,
3911 ;; because on Windows there would be problems with UNC shares or
3912 ;; Cygwin mounts.
aff67808
MA
3913 (let ((directory-sep-char ?/)
3914 (default-directory (tramp-compat-temporary-file-directory)))
3915 (tramp-make-tramp-file-name
3916 method user host
3917 (tramp-drop-volume-letter
87bdd2c7
MA
3918 (tramp-run-real-handler
3919 'expand-file-name (list localname))))))))
00d6fd04 3920
c23c3394
MA
3921(defun tramp-replace-environment-variables (filename)
3922 "Replace environment variables in FILENAME.
3923Return the string with the replaced variables."
2e271195 3924 (save-match-data
ec5145d6 3925 (let ((idx (string-match "$\\(\\w+\\)" filename)))
2e271195 3926 ;; `$' is coded as `$$'.
ec5145d6
MA
3927 (when (and idx
3928 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
3929 (getenv (match-string 1 filename)))
2e271195
MA
3930 (setq filename
3931 (replace-match
3932 (substitute-in-file-name (match-string 0 filename))
3933 t nil filename)))
3934 filename)))
c23c3394 3935
00d6fd04
MA
3936(defun tramp-handle-substitute-in-file-name (filename)
3937 "Like `substitute-in-file-name' for Tramp files.
3938\"//\" and \"/~\" substitute only in the local filename part.
3939If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
3940beginning of local filename are not substituted."
c23c3394
MA
3941 ;; First, we must replace environment variables.
3942 (setq filename (tramp-replace-environment-variables filename))
00d6fd04
MA
3943 (with-parsed-tramp-file-name filename nil
3944 (if (equal tramp-syntax 'url)
3945 ;; We need to check localname only. The other parts cannot contain
3946 ;; "//" or "/~".
3947 (if (and (> (length localname) 1)
3948 (or (string-match "//" localname)
3949 (string-match "/~" localname 1)))
3950 (tramp-run-real-handler 'substitute-in-file-name (list filename))
3951 (tramp-make-tramp-file-name
3952 (when method (substitute-in-file-name method))
3953 (when user (substitute-in-file-name user))
3954 (when host (substitute-in-file-name host))
87bdd2c7
MA
3955 (when localname
3956 (tramp-run-real-handler
3957 'substitute-in-file-name (list localname)))))
00d6fd04
MA
3958 ;; Ignore in LOCALNAME everything before "//" or "/~".
3959 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3960 (setq filename
b08104a0
MA
3961 (concat (file-remote-p filename)
3962 (replace-match "\\1" nil nil localname)))
00d6fd04
MA
3963 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3964 (when (string-match "~$" filename)
3965 (setq filename (concat filename "/"))))
3966 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
3967
3968;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
3969;; which calls corresponding functions (see minibuf.el).
3970(when (fboundp 'minibuffer-electric-separator)
9e6ab520 3971 (mapc
aa485f7c
MA
3972 (lambda (x)
3973 (eval
3974 `(defadvice ,x
3975 (around ,(intern (format "tramp-advice-%s" x)) activate)
3976 "Invoke `substitute-in-file-name' for Tramp files."
3977 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
3978 (tramp-tramp-file-p (buffer-substring)))
3979 ;; We don't need to handle `last-input-event', because
3980 ;; due to the key map we know it must be ?/ or ?~.
3981 (let ((s (concat (buffer-substring (point-min) (point))
3982 (string last-command-char))))
3983 (delete-region (point-min) (point))
3984 (insert (substitute-in-file-name s))
3985 (setq ad-return-value last-command-char))
3986 ad-do-it))))
00d6fd04
MA
3987
3988 '(minibuffer-electric-separator
3989 minibuffer-electric-tilde)))
3990
3991
0664ff72 3992;;; Remote commands:
fb7933a3 3993
00d6fd04
MA
3994(defun tramp-handle-executable-find (command)
3995 "Like `executable-find' for Tramp files."
3996 (with-parsed-tramp-file-name default-directory nil
f84638eb 3997 (tramp-find-executable v command (tramp-get-remote-path v) t)))
00d6fd04
MA
3998
3999;; We use BUFFER also as connection buffer during setup. Because of
4000;; this, its original contents must be saved, and restored once
4001;; connection has been setup.
4002(defun tramp-handle-start-file-process (name buffer program &rest args)
4003 "Like `start-file-process' for Tramp files."
4004 (with-parsed-tramp-file-name default-directory nil
9fb2cdc5
GM
4005 (unless (stringp program)
4006 (tramp-error
4007 v 'file-error "pty association is not supported for `%s'" name))
00d6fd04 4008 (unwind-protect
263c02ef
MA
4009 (let ((command (format "cd %s; exec %s"
4010 (tramp-shell-quote-argument localname)
4011 (mapconcat 'tramp-shell-quote-argument
4012 (cons program args) " ")))
4013 (name1 name)
38d63e6a 4014 (i 0))
2296b54d 4015 (unless buffer
6ce63faf 4016 ;; BUFFER can be nil. We use a temporary buffer.
2296b54d 4017 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
38d63e6a
MA
4018 (while (get-process name1)
4019 ;; NAME must be unique as process name.
4020 (setq i (1+ i)
4021 name1 (format "%s<%d>" name i)))
4022 (setq name name1)
00d6fd04
MA
4023 ;; Set the new process properties.
4024 (tramp-set-connection-property v "process-name" name)
2296b54d 4025 (tramp-set-connection-property v "process-buffer" buffer)
00d6fd04 4026 ;; Activate narrowing in order to save BUFFER contents.
11c71217
MA
4027 ;; Clear also the modification time; otherwise we might be
4028 ;; interrupted by `verify-visited-file-modtime'.
00d6fd04 4029 (with-current-buffer (tramp-get-connection-buffer v)
11c71217 4030 (clear-visited-file-modtime)
00d6fd04 4031 (narrow-to-region (point-max) (point-max)))
263c02ef 4032 ;; Send the command. `tramp-send-command' opens a new
00d6fd04 4033 ;; connection.
263c02ef 4034 (tramp-send-command v command nil t) ; nooutput
6ce63faf
MA
4035 ;; Set query flag for this process.
4036 (tramp-set-process-query-on-exit-flag
4037 (tramp-get-connection-process v) t)
00d6fd04
MA
4038 ;; Return process.
4039 (tramp-get-connection-process v))
4040 ;; Save exit.
ce3f516f 4041 (with-current-buffer (tramp-get-connection-buffer v)
6ce63faf
MA
4042 (if (string-match tramp-temp-buffer-name (buffer-name))
4043 (progn
4044 (set-process-buffer (tramp-get-connection-process v) nil)
4045 (kill-buffer (current-buffer)))
4046 (widen)
4047 (goto-char (point-max))))
00d6fd04
MA
4048 (tramp-set-connection-property v "process-name" nil)
4049 (tramp-set-connection-property v "process-buffer" nil))))
4050
4051(defun tramp-handle-process-file
4052 (program &optional infile destination display &rest args)
4053 "Like `process-file' for Tramp files."
4054 ;; The implementation is not complete yet.
4055 (when (and (numberp destination) (zerop destination))
4056 (error "Implementation does not handle immediate return"))
4057
4058 (with-parsed-tramp-file-name default-directory nil
a6e96327 4059 (let (command input tmpinput stderr tmpstderr outbuf ret)
00d6fd04
MA
4060 ;; Compute command.
4061 (setq command (mapconcat 'tramp-shell-quote-argument
4062 (cons program args) " "))
4063 ;; Determine input.
4064 (if (null infile)
4065 (setq input "/dev/null")
4066 (setq infile (expand-file-name infile))
4067 (if (tramp-equal-remote default-directory infile)
4068 ;; INFILE is on the same remote host.
4069 (setq input (with-parsed-tramp-file-name infile nil localname))
4070 ;; INFILE must be copied to remote host.
a6e96327
MA
4071 (setq input (tramp-make-tramp-temp-file v)
4072 tmpinput (tramp-make-tramp-file-name method user host input))
4073 (copy-file infile tmpinput t)))
00d6fd04
MA
4074 (when input (setq command (format "%s <%s" command input)))
4075
4076 ;; Determine output.
4077 (cond
bede3e9f 4078 ;; Just a buffer.
00d6fd04
MA
4079 ((bufferp destination)
4080 (setq outbuf destination))
bede3e9f 4081 ;; A buffer name.
00d6fd04
MA
4082 ((stringp destination)
4083 (setq outbuf (get-buffer-create destination)))
4084 ;; (REAL-DESTINATION ERROR-DESTINATION)
4085 ((consp destination)
bede3e9f 4086 ;; output.
00d6fd04
MA
4087 (cond
4088 ((bufferp (car destination))
4089 (setq outbuf (car destination)))
4090 ((stringp (car destination))
0664ff72
MA
4091 (setq outbuf (get-buffer-create (car destination))))
4092 ((car destination)
4093 (setq outbuf (current-buffer))))
bede3e9f 4094 ;; stderr.
00d6fd04
MA
4095 (cond
4096 ((stringp (cadr destination))
4097 (setcar (cdr destination) (expand-file-name (cadr destination)))
4098 (if (tramp-equal-remote default-directory (cadr destination))
4099 ;; stderr is on the same remote host.
4100 (setq stderr (with-parsed-tramp-file-name
4101 (cadr destination) nil localname))
4102 ;; stderr must be copied to remote host. The temporary
4103 ;; file must be deleted after execution.
a6e96327
MA
4104 (setq stderr (tramp-make-tramp-temp-file v)
4105 tmpstderr (tramp-make-tramp-file-name
4106 method user host stderr))))
bede3e9f 4107 ;; stderr to be discarded.
00d6fd04
MA
4108 ((null (cadr destination))
4109 (setq stderr "/dev/null"))))
4110 ;; 't
4111 (destination
4112 (setq outbuf (current-buffer))))
4113 (when stderr (setq command (format "%s 2>%s" command stderr)))
4114
00d6fd04
MA
4115 ;; Goto working directory.
4116 (tramp-send-command
4117 v (format "cd %s" (tramp-shell-quote-argument localname)))
4118 ;; Send the command. It might not return in time, so we protect it.
4119 (condition-case nil
4120 (unwind-protect
4121 (tramp-send-command v command)
4122 ;; We should show the output anyway.
4123 (when outbuf
27e813fe
MA
4124 (let ((output-string
4125 (with-current-buffer (tramp-get-connection-buffer v)
4126 (buffer-substring (point-min) (point-max)))))
4127 (with-current-buffer outbuf
4128 (insert output-string)))
00d6fd04 4129 (when display (display-buffer outbuf))))
260821d3
MA
4130 ;; When the user did interrupt, we should do it also. We use
4131 ;; return code -1 as marker.
4132 (quit
4133 (kill-buffer (tramp-get-connection-buffer v))
4134 (setq ret -1))
4135 ;; Handle errors.
00d6fd04
MA
4136 (error
4137 (kill-buffer (tramp-get-connection-buffer v))
4138 (setq ret 1)))
a6e96327
MA
4139
4140 ;; Check return code.
4141 (unless ret (setq ret (tramp-send-command-and-check v nil)))
4142 ;; Provide error file.
4143 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
263c02ef 4144
260821d3
MA
4145 ;; Cleanup. We remove all file cache values for the connection,
4146 ;; because the remote process could have changed them.
a6e96327 4147 (when tmpinput (delete-file tmpinput))
946a5aeb
MA
4148
4149 ;; `process-file-side-effects' has been introduced with GNU
4150 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4151 ;; by `program'. If it doesn't exist, we assume its default
4152 ;; value 't'.
4153 (unless (and (boundp 'process-file-side-effects)
4154 (not (symbol-value 'process-file-side-effects)))
4155 (tramp-flush-directory-property v ""))
4156
00d6fd04 4157 ;; Return exit status.
260821d3
MA
4158 (if (equal ret -1)
4159 (keyboard-quit)
4160 ret))))
00d6fd04 4161
a4aeb9a4
MA
4162(defun tramp-local-call-process
4163 (program &optional infile destination display &rest args)
4164 "Calls `call-process' on the local host.
4165This is needed because for some Emacs flavors Tramp has
4166defadviced `call-process' to behave like `process-file'. The
4167Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4168 (let ((default-directory
4169 (if (file-remote-p default-directory)
4170 (tramp-compat-temporary-file-directory)
4171 default-directory)))
4172 (if (executable-find program)
4173 (apply 'call-process program infile destination display args)
4174 1)))
4175
00d6fd04
MA
4176(defun tramp-handle-call-process-region
4177 (start end program &optional delete buffer display &rest args)
4178 "Like `call-process-region' for Tramp files."
258800f8 4179 (let ((tmpfile (tramp-compat-make-temp-file "")))
00d6fd04
MA
4180 (write-region start end tmpfile)
4181 (when delete (delete-region start end))
4182 (unwind-protect
4183 (apply 'call-process program tmpfile buffer display args)
4184 (delete-file tmpfile))))
4185
4186(defun tramp-handle-shell-command
4187 (command &optional output-buffer error-buffer)
4188 "Like `shell-command' for Tramp files."
ce3f516f 4189 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
b8bfcf96
MA
4190 ;; We cannot use `shell-file-name' and `shell-command-switch',
4191 ;; they are variables of the local host.
4192 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
5d2ebd96 4193 current-buffer-p
ce3f516f 4194 (output-buffer
27e813fe
MA
4195 (cond
4196 ((bufferp output-buffer) output-buffer)
4197 ((stringp output-buffer) (get-buffer-create output-buffer))
5d2ebd96
AS
4198 (output-buffer
4199 (setq current-buffer-p t)
4200 (current-buffer))
42bc9b6d 4201 (t (get-buffer-create
27e813fe
MA
4202 (if asynchronous
4203 "*Async Shell Command*"
4204 "*Shell Command Output*")))))
4205 (error-buffer
4206 (cond
4207 ((bufferp error-buffer) error-buffer)
4208 ((stringp error-buffer) (get-buffer-create error-buffer))))
ce3f516f 4209 (buffer
27e813fe 4210 (if (and (not asynchronous) error-buffer)
ce3f516f
MA
4211 (with-parsed-tramp-file-name default-directory nil
4212 (list output-buffer (tramp-make-tramp-temp-file v)))
42bc9b6d 4213 output-buffer))
cfb5c0db 4214 (p (get-buffer-process output-buffer)))
42bc9b6d
MA
4215
4216 ;; Check whether there is another process running. Tramp does not
4217 ;; support 2 (asynchronous) processes in parallel.
cfb5c0db 4218 (when p
42bc9b6d 4219 (if (yes-or-no-p "A command is running. Kill it? ")
699a11fb
GM
4220 (condition-case nil
4221 (kill-process p)
4222 (error nil))
42bc9b6d
MA
4223 (error "Shell command in progress")))
4224
f34db316
AS
4225 (if current-buffer-p
4226 (progn
4227 (barf-if-buffer-read-only)
4228 (push-mark nil t))
5d2ebd96
AS
4229 (with-current-buffer output-buffer
4230 (setq buffer-read-only nil)
4231 (erase-buffer)))
42bc9b6d 4232
5d2ebd96 4233 (if (and (not current-buffer-p) (integerp asynchronous))
42bc9b6d
MA
4234 (prog1
4235 ;; Run the process.
3412f35d 4236 (apply 'start-file-process "*Async Shell*" buffer args)
42bc9b6d 4237 ;; Display output.
cfb5c0db
MA
4238 (pop-to-buffer output-buffer)
4239 (setq mode-line-process '(":%s"))
4240 (require 'shell) (shell-mode))
42bc9b6d
MA
4241
4242 (prog1
4243 ;; Run the process.
4244 (apply 'process-file (car args) nil buffer nil (cdr args))
4245 ;; Insert error messages if they were separated.
4246 (when (listp buffer)
4247 (with-current-buffer error-buffer
4248 (insert-file-contents (cadr buffer)))
4249 (delete-file (cadr buffer)))
f34db316
AS
4250 (if current-buffer-p
4251 ;; This is like exchange-point-and-mark, but doesn't
4252 ;; activate the mark. It is cleaner to avoid activation,
4253 ;; even though the command loop would deactivate the mark
4254 ;; because we inserted text.
4255 (goto-char (prog1 (mark t)
4256 (set-marker (mark-marker) (point)
4257 (current-buffer))))
4258 ;; There's some output, display it.
4259 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4260 (if (functionp 'display-message-or-buffer)
4261 (funcall (symbol-function 'display-message-or-buffer)
4262 output-buffer)
4263 (pop-to-buffer output-buffer))))))))
00d6fd04
MA
4264
4265;; File Editing.
4266
4267(defvar tramp-handle-file-local-copy-hook nil
4268 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4269
fb7933a3 4270(defun tramp-handle-file-local-copy (filename)
00d6fd04 4271 "Like `file-local-copy' for Tramp files."
0f205eee 4272
c62c9d08 4273 (with-parsed-tramp-file-name filename nil
2988341a
MA
4274 (unless (file-exists-p filename)
4275 (tramp-error
4276 v 'file-error
4277 "Cannot make local copy of non-existing file `%s'" filename))
4278
0f205eee 4279 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
00d6fd04 4280 (loc-dec (tramp-get-local-coding v "local-decoding"))
258800f8 4281 (tmpfile (tramp-compat-make-temp-file filename)))
5ec2cc41 4282
2988341a
MA
4283 (condition-case err
4284 (cond
4285 ;; `copy-file' handles direct copy and out-of-band methods.
4286 ((or (tramp-local-host-p v)
7f49fe46
MA
4287 (tramp-method-out-of-band-p
4288 v (nth 7 (file-attributes filename))))
2988341a
MA
4289 (copy-file filename tmpfile t t))
4290
4291 ;; Use inline encoding for file transfer.
4292 (rem-enc
4293 (save-excursion
4294 (tramp-message v 5 "Encoding remote file %s..." filename)
4295 (tramp-barf-unless-okay
4296 v
4297 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4298 "Encoding remote file failed")
4299 (tramp-message v 5 "Encoding remote file %s...done" filename)
4300
4301 (if (and (symbolp loc-dec) (fboundp loc-dec))
4302 ;; If local decoding is a function, we call it. We
4303 ;; must disable multibyte, because
4304 ;; `uudecode-decode-region' doesn't handle it
4305 ;; correctly.
0f205eee
MA
4306 (with-temp-buffer
4307 (set-buffer-multibyte nil)
4308 (insert-buffer-substring (tramp-get-buffer v))
4309 (tramp-message
4310 v 5 "Decoding remote file %s with function %s..."
4311 filename loc-dec)
4312 (funcall loc-dec (point-min) (point-max))
aa485f7c
MA
4313 ;; Unset `file-name-handler-alist'. Otherwise,
4314 ;; epa-file gets confused.
4315 (let (file-name-handler-alist
4316 (coding-system-for-write 'binary))
2988341a
MA
4317 (write-region (point-min) (point-max) tmpfile)))
4318
4319 ;; If tramp-decoding-function is not defined for this
4320 ;; method, we invoke tramp-decoding-command instead.
4321 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
aa485f7c
MA
4322 ;; Unset `file-name-handler-alist'. Otherwise,
4323 ;; epa-file gets confused.
4324 (let (file-name-handler-alist
4325 (coding-system-for-write 'binary))
2988341a
MA
4326 (write-region (point-min) (point-max) tmpfile2))
4327 (tramp-message
4328 v 5 "Decoding remote file %s with command %s..."
4329 filename loc-dec)
4330 (unwind-protect
4331 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4332 (delete-file tmpfile2))))
4333
4334 (tramp-message v 5 "Decoding remote file %s...done" filename)
4335 ;; Set proper permissions.
b86c1cd8 4336 (set-file-modes tmpfile (tramp-default-file-modes filename))
2988341a
MA
4337 ;; Set local user ownership.
4338 (tramp-set-file-uid-gid tmpfile)))
4339
4340 ;; Oops, I don't know what to do.
4341 (t (tramp-error
4342 v 'file-error "Wrong method specification for `%s'" method)))
4343
4344 ;; Error handling.
4345 ((error quit)
4346 (delete-file tmpfile)
4347 (signal (car err) (cdr err))))
0f205eee 4348
00d6fd04 4349 (run-hooks 'tramp-handle-file-local-copy-hook)
94be87e8 4350 tmpfile)))
fb7933a3 4351
bce04fee 4352(defun tramp-handle-file-remote-p (filename &optional identification connected)
00d6fd04 4353 "Like `file-remote-p' for Tramp files."
15cc764c
KG
4354 (when (tramp-tramp-file-p filename)
4355 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4356 (and (or (not connected)
4357 (let ((p (tramp-get-connection-process v)))
4358 (and p (processp p) (memq (process-status p) '(run open)))))
ce3f516f
MA
4359 (cond
4360 ((eq identification 'method) method)
4361 ((eq identification 'user) user)
4362 ((eq identification 'host) host)
8d60099b 4363 ((eq identification 'localname) localname)
ce3f516f 4364 (t (tramp-make-tramp-file-name method user host "")))))))
fb7933a3 4365
eb562962
MA
4366(defun tramp-find-file-name-coding-system-alist (filename tmpname)
4367 "Like `find-operation-coding-system' for Tramp filenames.
4368Tramp's `insert-file-contents' and `write-region' work over
4369temporary file names. If `file-coding-system-alist' contains an
4370expression, which matches more than the file name suffix, the
4371coding system might not be determined. This function repairs it."
4372 (let (result)
4373 (dolist (elt file-coding-system-alist result)
4374 (when (and (consp elt) (string-match (car elt) filename))
4375 ;; We found a matching entry in `file-coding-system-alist'.
4376 ;; So we add a similar entry, but with the temporary file name
4377 ;; as regexp.
4378 (add-to-list
4379 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4380
fb7933a3
KG
4381(defun tramp-handle-insert-file-contents
4382 (filename &optional visit beg end replace)
00d6fd04 4383 "Like `insert-file-contents' for Tramp files."
fb7933a3
KG
4384 (barf-if-buffer-read-only)
4385 (setq filename (expand-file-name filename))
736ac90f 4386 (let (coding-system-used result local-copy remote-copy)
2ac33804
MA
4387 (with-parsed-tramp-file-name filename nil
4388 (unwind-protect
70c11b0b
MA
4389 (if (not (file-exists-p filename))
4390 ;; We don't raise a Tramp error, because it might be
4391 ;; suppressed, like in `find-file-noselect-1'.
4392 (signal 'file-error
4393 (list "File not found on remote host" filename))
4394
4395 (if (and (tramp-local-host-p v)
4396 (let (file-name-handler-alist)
4397 (file-readable-p localname)))
4398 ;; Short track: if we are on the local host, we can
4399 ;; run directly.
4400 (setq result
4401 (tramp-run-real-handler
4402 'insert-file-contents
4403 (list localname visit beg end replace)))
4404
736ac90f
MA
4405 ;; When we shall insert only a part of the file, we copy
4406 ;; this part.
4407 (when (or beg end)
4408 (setq remote-copy (tramp-make-tramp-temp-file v))
4409 (tramp-send-command
4410 v
4411 (cond
4412 ((and beg end)
4413 (format "tail -c +%d %s | head -c +%d >%s"
4414 (1+ beg) (tramp-shell-quote-argument localname)
4415 (- end beg) remote-copy))
4416 (beg
4417 (format "tail -c +%d %s >%s"
4418 (1+ beg) (tramp-shell-quote-argument localname)
4419 remote-copy))
4420 (end
4421 (format "head -c +%d %s >%s"
4422 (1+ end) (tramp-shell-quote-argument localname)
4423 remote-copy)))))
4424
70c11b0b
MA
4425 ;; `insert-file-contents-literally' takes care to avoid
4426 ;; calling jka-compr. By let-binding
4427 ;; `inhibit-file-name-operation', we propagate that care
4428 ;; to the `file-local-copy' operation.
4429 (setq local-copy
4430 (let ((inhibit-file-name-operation
4431 (when (eq inhibit-file-name-operation
4432 'insert-file-contents)
4433 'file-local-copy)))
736ac90f
MA
4434 (file-local-copy
4435 (if (stringp remote-copy)
4436 (tramp-make-tramp-file-name
4437 method user host remote-copy)
4438 filename))))
70c11b0b
MA
4439 (tramp-message
4440 v 4 "Inserting local temp file `%s'..." local-copy)
4441
4442 ;; We must ensure that `file-coding-system-alist'
4443 ;; matches `local-copy'.
4444 (let ((file-coding-system-alist
4445 (tramp-find-file-name-coding-system-alist
4446 filename local-copy)))
4447 (setq result
4448 (insert-file-contents
736ac90f 4449 local-copy nil nil nil replace))
70c11b0b
MA
4450 ;; Now `last-coding-system-used' has right value.
4451 ;; Remember it.
4452 (when (boundp 'last-coding-system-used)
4453 (setq coding-system-used
4454 (symbol-value 'last-coding-system-used))))
8d60099b 4455
70c11b0b
MA
4456 (tramp-message
4457 v 4 "Inserting local temp file `%s'...done" local-copy)
4458 (when (boundp 'last-coding-system-used)
2ac33804 4459 (set 'last-coding-system-used coding-system-used))))
70c11b0b 4460
2ac33804
MA
4461 ;; Save exit.
4462 (progn
4463 (when visit
4464 (setq buffer-file-name filename)
4465 (setq buffer-read-only (not (file-writable-p filename)))
4466 (set-visited-file-modtime)
4467 (set-buffer-modified-p nil))
4468 (when (stringp local-copy)
4469 (delete-file local-copy))
4470 (when (stringp remote-copy)
4471 (delete-file
4472 (tramp-make-tramp-file-name method user host remote-copy))))))
70c11b0b
MA
4473
4474 ;; Result.
4475 (list (expand-file-name filename)
4476 (cadr result))))
fb7933a3 4477
94be87e8
MA
4478;; This is needed for XEmacs only. Code stolen from files.el.
4479(defun tramp-handle-insert-file-contents-literally
4480 (filename &optional visit beg end replace)
4481 "Like `insert-file-contents-literally' for Tramp files."
4482 (let ((format-alist nil)
4483 (after-insert-file-functions nil)
4484 (coding-system-for-read 'no-conversion)
4485 (coding-system-for-write 'no-conversion)
4486 (find-buffer-file-type-function
4487 (if (fboundp 'find-buffer-file-type)
4488 (symbol-function 'find-buffer-file-type)
4489 nil))
4490 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4491 (inhibit-file-name-operation 'insert-file-contents))
4492 (unwind-protect
4493 (progn
4494 (fset 'find-buffer-file-type (lambda (filename) t))
4495 (insert-file-contents filename visit beg end replace))
70c11b0b 4496 ;; Save exit.
94be87e8
MA
4497 (if find-buffer-file-type-function
4498 (fset 'find-buffer-file-type find-buffer-file-type-function)
4499 (fmakunbound 'find-buffer-file-type)))))
4500
38c65fca 4501(defun tramp-handle-find-backup-file-name (filename)
00d6fd04 4502 "Like `find-backup-file-name' for Tramp files."
07dfe738
KG
4503 (with-parsed-tramp-file-name filename nil
4504 ;; We set both variables. It doesn't matter whether it is
4505 ;; Emacs or XEmacs
4506 (let ((backup-directory-alist
4507 ;; Emacs case
4508 (when (boundp 'backup-directory-alist)
b86c1cd8 4509 (if (symbol-value 'tramp-backup-directory-alist)
07dfe738 4510 (mapcar
aa485f7c
MA
4511 (lambda (x)
4512 (cons
4513 (car x)
4514 (if (and (stringp (cdr x))
4515 (file-name-absolute-p (cdr x))
4516 (not (tramp-file-name-p (cdr x))))
4517 (tramp-make-tramp-file-name method user host (cdr x))
4518 (cdr x))))
07dfe738
KG
4519 (symbol-value 'tramp-backup-directory-alist))
4520 (symbol-value 'backup-directory-alist))))
4521
4522 (bkup-backup-directory-info
4523 ;; XEmacs case
4524 (when (boundp 'bkup-backup-directory-info)
b86c1cd8 4525 (if (symbol-value 'tramp-bkup-backup-directory-info)
07dfe738 4526 (mapcar
aa485f7c
MA
4527 (lambda (x)
4528 (nconc
4529 (list (car x))
4530 (list
4531 (if (and (stringp (car (cdr x)))
4532 (file-name-absolute-p (car (cdr x)))
4533 (not (tramp-file-name-p (car (cdr x)))))
4534 (tramp-make-tramp-file-name
4535 method user host (car (cdr x)))
4536 (car (cdr x))))
4537 (cdr (cdr x))))
07dfe738
KG
4538 (symbol-value 'tramp-bkup-backup-directory-info))
4539 (symbol-value 'bkup-backup-directory-info)))))
4540
4541 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
38c65fca 4542
c1105d05 4543(defun tramp-handle-make-auto-save-file-name ()
00d6fd04 4544 "Like `make-auto-save-file-name' for Tramp files.
c1105d05 4545Returns a file name in `tramp-auto-save-directory' for autosaving this file."
00d6fd04
MA
4546 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4547 (buffer-file-name
4548 (tramp-subst-strs-in-string
4549 '(("_" . "|")
4550 ("/" . "_a")
4551 (":" . "_b")
4552 ("|" . "__")
4553 ("[" . "_l")
4554 ("]" . "_r"))
4555 (buffer-file-name))))
1a762140
MA
4556 ;; File name must be unique. This is ensured with Emacs 22 (see
4557 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4558 ;; all other cases we must do it ourselves.
4559 (when (boundp 'auto-save-file-name-transforms)
9e6ab520 4560 (mapc
aa485f7c
MA
4561 (lambda (x)
4562 (when (and (string-match (car x) buffer-file-name)
4563 (not (car (cddr x))))
4564 (setq tramp-auto-save-directory
4565 (or tramp-auto-save-directory
4566 (tramp-compat-temporary-file-directory)))))
1a762140
MA
4567 (symbol-value 'auto-save-file-name-transforms)))
4568 ;; Create directory.
4569 (when tramp-auto-save-directory
00d6fd04
MA
4570 (setq buffer-file-name
4571 (expand-file-name buffer-file-name tramp-auto-save-directory))
1a762140
MA
4572 (unless (file-exists-p tramp-auto-save-directory)
4573 (make-directory tramp-auto-save-directory t)))
00d6fd04
MA
4574 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4575 ;; it is not a magic file name operation (since Emacs 22).
4576 ;; We must deactivate it temporarily.
4577 (if (not (ad-is-active 'make-auto-save-file-name))
4578 (tramp-run-real-handler 'make-auto-save-file-name nil)
4579 ;; else
4580 (ad-deactivate 'make-auto-save-file-name)
4581 (prog1
4582 (tramp-run-real-handler 'make-auto-save-file-name nil)
4583 (ad-activate 'make-auto-save-file-name)))))
4584
4585(defvar tramp-handle-write-region-hook nil
4586 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4587
4588;; CCC grok APPEND, LOCKNAME
fb7933a3
KG
4589(defun tramp-handle-write-region
4590 (start end filename &optional append visit lockname confirm)
00d6fd04 4591 "Like `write-region' for Tramp files."
fb7933a3 4592 (setq filename (expand-file-name filename))
c62c9d08 4593 (with-parsed-tramp-file-name filename nil
00d6fd04
MA
4594 (unless (null append)
4595 (tramp-error
4596 v 'file-error "Cannot append to file using Tramp (`%s')" filename))
4597 ;; Following part commented out because we don't know what to do about
4598 ;; file locking, and it does not appear to be a problem to ignore it.
4599 ;; Ange-ftp ignores it, too.
4600 ;; (when (and lockname (stringp lockname))
4601 ;; (setq lockname (expand-file-name lockname)))
4602 ;; (unless (or (eq lockname nil)
4603 ;; (string= lockname filename))
4604 ;; (error
4605 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
8d60099b 4606
94be87e8 4607 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
00d6fd04
MA
4608 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4609 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4610 (tramp-error v 'file-error "File not overwritten")))
8d60099b 4611
a4aeb9a4 4612 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
9c13938d 4613 (tramp-get-remote-uid v 'integer)))
a4aeb9a4 4614 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
9c13938d
MA
4615 (tramp-get-remote-gid v 'integer))))
4616
4617 (if (and (tramp-local-host-p v)
93c3eb7c 4618 ;; `file-writable-p' calls `file-expand-file-name'. We
87bdd2c7
MA
4619 ;; cannot use `tramp-run-real-handler' therefore.
4620 (let (file-name-handler-alist)
82f3844e
MA
4621 (and
4622 (file-writable-p (file-name-directory localname))
4623 (or (file-directory-p localname)
4624 (file-writable-p localname)))))
9c13938d 4625 ;; Short track: if we are on the local host, we can run directly.
93c3eb7c
MA
4626 (progn
4627 (tramp-run-real-handler
4628 'write-region
4629 (list start end localname append 'no-message lockname confirm))
3e2fa353 4630 (tramp-flush-file-property v localname))
9c13938d
MA
4631
4632 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4633 (loc-enc (tramp-get-local-coding v "local-encoding"))
b86c1cd8 4634 (modes (save-excursion (tramp-default-file-modes filename)))
9c13938d
MA
4635 ;; We use this to save the value of
4636 ;; `last-coding-system-used' after writing the tmp file.
4637 ;; At the end of the function, we set
4638 ;; `last-coding-system-used' to this saved value. This
4639 ;; way, any intermediary coding systems used while
4640 ;; talking to the remote shell or suchlike won't hose
4641 ;; this variable. This approach was snarfed from
4642 ;; ange-ftp.el.
4643 coding-system-used
4644 ;; Write region into a tmp file. This isn't really
4645 ;; needed if we use an encoding function, but currently
4646 ;; we use it always because this makes the logic
4647 ;; simpler.
4648 (tmpfile (tramp-compat-make-temp-file filename)))
4649
4650 ;; We say `no-message' here because we don't want the
4651 ;; visited file modtime data to be clobbered from the temp
4652 ;; file. We call `set-visited-file-modtime' ourselves later
eb562962
MA
4653 ;; on. We must ensure that `file-coding-system-alist'
4654 ;; matches `tmpfile'.
4655 (let ((file-coding-system-alist
4656 (tramp-find-file-name-coding-system-alist filename tmpfile)))
ce2cc728
MA
4657 (condition-case err
4658 (tramp-run-real-handler
4659 'write-region
4660 (list start end tmpfile append 'no-message lockname confirm))
2988341a
MA
4661 ((error quit)
4662 (delete-file tmpfile)
4663 (signal (car err) (cdr err))))
ce2cc728 4664
eb562962
MA
4665 ;; Now, `last-coding-system-used' has the right value. Remember it.
4666 (when (boundp 'last-coding-system-used)
4667 (setq coding-system-used
4668 (symbol-value 'last-coding-system-used))))
4669
9c13938d
MA
4670 ;; The permissions of the temporary file should be set. If
4671 ;; filename does not exist (eq modes nil) it has been
4672 ;; renamed to the backup file. This case `save-buffer'
4673 ;; handles permissions.
4674 (when modes (set-file-modes tmpfile modes))
4675
4676 ;; This is a bit lengthy due to the different methods
4677 ;; possible for file transfer. First, we check whether the
4678 ;; method uses an rcp program. If so, we call it.
4679 ;; Otherwise, both encoding and decoding command must be
4680 ;; specified. However, if the method _also_ specifies an
4681 ;; encoding function, then that is used for encoding the
4682 ;; contents of the tmp file.
4683 (cond
4684 ;; `rename-file' handles direct copy and out-of-band methods.
4685 ((or (tramp-local-host-p v)
7f49fe46
MA
4686 (tramp-method-out-of-band-p
4687 v (- (or end (point-max)) (or start (point-min)))))
ce2cc728
MA
4688 (condition-case err
4689 (rename-file tmpfile filename t)
2988341a
MA
4690 ((error quit)
4691 (delete-file tmpfile)
4692 (signal (car err) (cdr err)))))
9c13938d 4693
1d7e9a01 4694 ;; Use inline file transfer.
9c13938d 4695 (rem-dec
1d7e9a01 4696 ;; Encode tmpfile.
9c13938d
MA
4697 (tramp-message v 5 "Encoding region...")
4698 (unwind-protect
4699 (with-temp-buffer
4700 ;; Use encoding function or command.
4701 (if (and (symbolp loc-enc) (fboundp loc-enc))
4702 (progn
4703 (tramp-message
4704 v 5 "Encoding region using function `%s'..."
4705 (symbol-name loc-enc))
4706 (let ((coding-system-for-read 'binary))
4707 (insert-file-contents-literally tmpfile))
70c11b0b
MA
4708 ;; The following `let' is a workaround for the
4709 ;; base64.el that comes with pgnus-0.84. If
4710 ;; both of the following conditions are
4711 ;; satisfied, it tries to write to a local
4712 ;; file in default-directory, but at this
4713 ;; point, default-directory is remote.
4714 ;; (`call-process-region' can't write to
4715 ;; remote files, it seems.) The file in
4716 ;; question is a tmp file anyway.
9c13938d
MA
4717 (let ((default-directory
4718 (tramp-compat-temporary-file-directory)))
4719 (funcall loc-enc (point-min) (point-max))))
8d60099b 4720
9c13938d
MA
4721 (tramp-message
4722 v 5 "Encoding region using command `%s'..." loc-enc)
4723 (unless (equal 0 (tramp-call-local-coding-command
4724 loc-enc tmpfile t))
4725 (tramp-error
4726 v 'file-error
4727 "Cannot write to `%s', local encoding command `%s' failed"
4728 filename loc-enc)))
4729
4730 ;; Send buffer into remote decoding command which
4731 ;; writes to remote file. Because this happens on
4732 ;; the remote host, we cannot use the function.
4733 (goto-char (point-max))
4734 (unless (bolp) (newline))
8d60099b 4735 (tramp-message
9c13938d
MA
4736 v 5 "Decoding region into remote file %s..." filename)
4737 (tramp-send-command
4738 v
4739 (format
4740 "%s >%s <<'EOF'\n%sEOF"
4741 rem-dec
4742 (tramp-shell-quote-argument localname)
4743 (buffer-string)))
4744 (tramp-barf-unless-okay
4745 v nil
4746 "Couldn't write region to `%s', decode using `%s' failed"
4747 filename rem-dec)
4748 ;; When `file-precious-flag' is set, the region is
4749 ;; written to a temporary file. Check that the
4750 ;; checksum is equal to that from the local tmpfile.
4751 (when file-precious-flag
4752 (erase-buffer)
4753 (and
a4aeb9a4
MA
4754 ;; cksum runs locally, if possible.
4755 (zerop (tramp-local-call-process "cksum" tmpfile t))
4756 ;; cksum runs remotely.
9c13938d
MA
4757 (zerop
4758 (tramp-send-command-and-check
4759 v
4760 (format
4761 "cksum <%s" (tramp-shell-quote-argument localname))))
a4aeb9a4 4762 ;; ... they are different.
9c13938d
MA
4763 (not
4764 (string-equal
4765 (buffer-string)
4766 (with-current-buffer (tramp-get-buffer v)
4767 (buffer-string))))
4768 (tramp-error
4769 v 'file-error
4770 (concat "Couldn't write region to `%s',"
4771 " decode using `%s' failed")
4772 filename rem-dec)))
4773 (tramp-message
4774 v 5 "Decoding region into remote file %s...done" filename)
4775 (tramp-flush-file-property v localname))
8d60099b 4776
9c13938d
MA
4777 ;; Save exit.
4778 (delete-file tmpfile)))
8d60099b 4779
9c13938d
MA
4780 ;; That's not expected.
4781 (t
4782 (tramp-error
4783 v 'file-error
4784 (concat "Method `%s' should specify both encoding and "
4785 "decoding command or an rcp program")
4786 method)))
258800f8 4787
9c13938d
MA
4788 ;; Make `last-coding-system-used' have the right value.
4789 (when coding-system-used
4790 (set 'last-coding-system-used coding-system-used))))
0f205eee 4791
57671b72
MA
4792 ;; We must protect `last-coding-system-used', now we have set it
4793 ;; to its correct value.
4794 (let (last-coding-system-used)
4795 ;; Set file modification time.
4796 (when (or (eq visit t) (stringp visit))
4797 (set-visited-file-modtime
4798 ;; We must pass modtime explicitely, because filename can
4799 ;; be different from (buffer-file-name), f.e. if
4800 ;; `file-precious-flag' is set.
4801 (nth 5 (file-attributes filename))))
4802
4803 ;; Set the ownership.
4804 (tramp-set-file-uid-gid filename uid gid)
4805 (when (or (eq visit t) (null visit) (stringp visit))
4806 (tramp-message v 0 "Wrote %s" filename))
4807 (run-hooks 'tramp-handle-write-region-hook)))))
fb7933a3 4808
946a5aeb
MA
4809(defvar tramp-vc-registered-file-names nil
4810 "List used to collect file names, which are checked during `vc-registered'.")
4811
4812;; VC backends check for the existence of various different special
4813;; files. This is very time consuming, because every single check
4814;; requires a remote command (the file cache must be invalidated).
4815;; Therefore, we apply a kind of optimization. We install the file
4816;; name handler `tramp-vc-file-name-handler', which does nothing but
4817;; remembers all file names for which `file-exists-p' or
4818;; `file-readable-p' has been applied. A first run of `vc-registered'
4819;; is performed. Afterwards, a script is applied for all collected
4820;; file names, using just one remote command. The result of this
4821;; script is used to fill the file cache with actual values. Now we
4822;; can reset the file name handlers, and we make a second run of
4823;; `vc-registered', which returns the expected result without sending
4824;; any other remote command.
49096407
MA
4825(defun tramp-handle-vc-registered (file)
4826 "Like `vc-registered' for Tramp files."
946a5aeb 4827 (with-parsed-tramp-file-name file nil
7f49fe46
MA
4828
4829 ;; There could be new files, created by the vc backend. We cannot
4830 ;; reuse the old cache entries, therefore.
946a5aeb
MA
4831 (let (tramp-vc-registered-file-names
4832 (tramp-cache-inhibit-cache (current-time))
4833 (file-name-handler-alist
4834 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
4835
4836 ;; Here we collect only file names, which need an operation.
4837 (tramp-run-real-handler 'vc-registered (list file))
4838 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
4839
4840 ;; Send just one command, in order to fill the cache.
7f49fe46
MA
4841 (when tramp-vc-registered-file-names
4842 (tramp-maybe-send-script
4843 v
4844 (format tramp-vc-registered-read-file-names
4845 (tramp-get-file-exists-command v)
4846 (format "%s -r" (tramp-get-test-command v)))
4847 "tramp_vc_registered_read_file_names")
4848
4849 (dolist
4850 (elt
4851 (tramp-send-command-and-read
4852 v
4853 (format
4854 "tramp_vc_registered_read_file_names %s"
4855 (mapconcat 'tramp-shell-quote-argument
4856 tramp-vc-registered-file-names
4857 " "))))
946a5aeb 4858
7f49fe46 4859 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
946a5aeb 4860
7f49fe46
MA
4861 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
4862 ;; shall be answered from the file cache.
4863 ;; We unset `process-file-side-effects' in order to keep the cache
4864 ;; when `process-file' calls appear.
946a5aeb
MA
4865 (let (process-file-side-effects)
4866 (tramp-run-real-handler 'vc-registered (list file)))))
49096407 4867
a01b1e22
MA
4868;;;###autoload
4869(progn (defun tramp-run-real-handler (operation args)
fb7933a3 4870 "Invoke normal file name handler for OPERATION.
c62c9d08
KG
4871First arg specifies the OPERATION, second arg is a list of arguments to
4872pass to the OPERATION."
4007ba5b
KG
4873 (let* ((inhibit-file-name-handlers
4874 `(tramp-file-name-handler
946a5aeb 4875 tramp-vc-file-name-handler
4007ba5b
KG
4876 tramp-completion-file-name-handler
4877 cygwin-mount-name-hook-function
4878 cygwin-mount-map-drive-hook-function
4879 .
4880 ,(and (eq inhibit-file-name-operation operation)
4881 inhibit-file-name-handlers)))
4882 (inhibit-file-name-operation operation))
a01b1e22 4883 (apply operation args))))
16674e4f 4884
a01b1e22
MA
4885;;;###autoload
4886(progn (defun tramp-completion-run-real-handler (operation args)
16674e4f
KG
4887 "Invoke `tramp-file-name-handler' for OPERATION.
4888First arg specifies the OPERATION, second arg is a list of arguments to
4889pass to the OPERATION."
4007ba5b
KG
4890 (let* ((inhibit-file-name-handlers
4891 `(tramp-completion-file-name-handler
4892 cygwin-mount-name-hook-function
4893 cygwin-mount-map-drive-hook-function
4894 .
4895 ,(and (eq inhibit-file-name-operation operation)
4896 inhibit-file-name-handlers)))
4897 (inhibit-file-name-operation operation))
a01b1e22 4898 (apply operation args))))
fb7933a3 4899
4007ba5b
KG
4900;; We handle here all file primitives. Most of them have the file
4901;; name as first parameter; nevertheless we check for them explicitly
04bf5b65 4902;; in order to be signaled if a new primitive appears. This
4007ba5b
KG
4903;; scenario is needed because there isn't a way to decide by
4904;; syntactical means whether a foreign method must be called. It would
19a87064 4905;; ease the life if `file-name-handler-alist' would support a decision
4007ba5b
KG
4906;; function as well but regexp only.
4907(defun tramp-file-name-for-operation (operation &rest args)
4908 "Return file name related to OPERATION file primitive.
4909ARGS are the arguments OPERATION has been called with."
4910 (cond
4911 ; FILE resp DIRECTORY
4912 ((member operation
4913 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
4914 'delete-file 'diff-latest-backup-file 'directory-file-name
4915 'directory-files 'directory-files-and-attributes
4916 'dired-compress-file 'dired-uncache
4917 'file-accessible-directory-p 'file-attributes
4918 'file-directory-p 'file-executable-p 'file-exists-p
19a87064
MA
4919 'file-local-copy 'file-remote-p 'file-modes
4920 'file-name-as-directory 'file-name-directory
4921 'file-name-nondirectory 'file-name-sans-versions
4922 'file-ownership-preserved-p 'file-readable-p
4923 'file-regular-p 'file-symlink-p 'file-truename
4924 'file-writable-p 'find-backup-file-name 'find-file-noselect
4925 'get-file-buffer 'insert-directory 'insert-file-contents
4926 'load 'make-directory 'make-directory-internal
4927 'set-file-modes 'substitute-in-file-name
4928 'unhandled-file-name-directory 'vc-registered
ce3f516f
MA
4929 ; Emacs 22 only
4930 'set-file-times
4007ba5b
KG
4931 ; XEmacs only
4932 'abbreviate-file-name 'create-file-buffer
4933 'dired-file-modtime 'dired-make-compressed-filename
4934 'dired-recursive-delete-directory 'dired-set-file-modtime
4935 'dired-shell-unhandle-file-name 'dired-uucode-file
5615d63f 4936 'insert-file-contents-literally 'make-temp-name 'recover-file
4007ba5b 4937 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
8daea7fc
KG
4938 (if (file-name-absolute-p (nth 0 args))
4939 (nth 0 args)
4940 (expand-file-name (nth 0 args))))
4007ba5b
KG
4941 ; FILE DIRECTORY resp FILE1 FILE2
4942 ((member operation
4943 (list 'add-name-to-file 'copy-file 'expand-file-name
4944 'file-name-all-completions 'file-name-completion
4945 'file-newer-than-file-p 'make-symbolic-link 'rename-file
263c02ef
MA
4946 ; Emacs 23 only
4947 'copy-directory
4007ba5b
KG
4948 ; XEmacs only
4949 'dired-make-relative-symlink
4950 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
4951 (save-match-data
4952 (cond
4953 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
4954 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
4955 (t (buffer-file-name (current-buffer))))))
4956 ; START END FILE
4957 ((eq operation 'write-region)
4958 (nth 2 args))
4959 ; BUF
4960 ((member operation
00d6fd04 4961 (list 'set-visited-file-modtime 'verify-visited-file-modtime
b50dd0d2 4962 ; since Emacs 22 only
00d6fd04
MA
4963 'make-auto-save-file-name
4964 ; XEmacs only
4007ba5b
KG
4965 'backup-buffer))
4966 (buffer-file-name
4967 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
4968 ; COMMAND
4969 ((member operation
00d6fd04
MA
4970 (list ; not in Emacs 23
4971 'dired-call-process
01917a18 4972 ; Emacs only
b71c9e75 4973 'shell-command
00d6fd04 4974 ; since Emacs 22 only
0457dd55 4975 'process-file
00d6fd04
MA
4976 ; since Emacs 23 only
4977 'start-file-process
4007ba5b 4978 ; XEmacs only
00d6fd04
MA
4979 'dired-print-file 'dired-shell-call-process
4980 ; nowhere yet
4981 'executable-find 'start-process 'call-process))
4007ba5b
KG
4982 default-directory)
4983 ; unknown file primitive
4984 (t (error "unknown file I/O primitive: %s" operation))))
4985
4986(defun tramp-find-foreign-file-name-handler (filename)
4987 "Return foreign file name handler if exists."
9ce8462a
MA
4988 (when (and (stringp filename) (tramp-tramp-file-p filename))
4989 (let ((v (tramp-dissect-file-name filename t))
4990 (handler tramp-foreign-file-name-handler-alist)
4991 elt res)
4992 ;; When we are not fully sure that filename completion is safe,
4993 ;; we should not return a handler.
4994 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1834b39f
MA
4995 (and (tramp-file-name-host v)
4996 (not (member (tramp-file-name-host v)
4997 (mapcar 'car tramp-methods))))
9ce8462a
MA
4998 (not (tramp-completion-mode-p)))
4999 (while handler
5000 (setq elt (car handler)
5001 handler (cdr handler))
5002 (when (funcall (car elt) filename)
5003 (setq handler nil
5004 res (cdr elt))))
5005 res))))
4007ba5b 5006
fb7933a3
KG
5007;; Main function.
5008;;;###autoload
5009(defun tramp-file-name-handler (operation &rest args)
ea9d1443 5010 "Invoke Tramp file name handler.
a4aeb9a4 5011Falls back to normal file name handler if no Tramp file name handler exists."
2e271195
MA
5012 (if tramp-mode
5013 (save-match-data
5014 (let* ((filename
5015 (tramp-replace-environment-variables
5016 (apply 'tramp-file-name-for-operation operation args)))
5017 (completion (tramp-completion-mode-p))
5018 (foreign (tramp-find-foreign-file-name-handler filename)))
5019 (with-parsed-tramp-file-name filename nil
5020 (cond
5021 ;; When we are in completion mode, some operations
5022 ;; shouldn't be handled by backend.
5023 ((and completion (zerop (length localname))
5024 (memq operation '(file-exists-p file-directory-p)))
5025 t)
5026 ((and completion (zerop (length localname))
5027 (memq operation '(file-name-as-directory)))
5028 filename)
5029 ;; Call the backend function.
5030 (foreign (apply foreign operation args))
5031 ;; Nothing to do for us.
5032 (t (tramp-run-real-handler operation args))))))
5033 ;; When `tramp-mode' is not enabled, we don't do anything.
5034 (tramp-run-real-handler operation args)))
fb7933a3 5035
07dfe738
KG
5036;; In Emacs, there is some concurrency due to timers. If a timer
5037;; interrupts Tramp and wishes to use the same connection buffer as
5038;; the "main" Emacs, then garbage might occur in the connection
5039;; buffer. Therefore, we need to make sure that a timer does not use
5040;; the same connection buffer as the "main" Emacs. We implement a
5041;; cheap global lock, instead of locking each connection buffer
5042;; separately. The global lock is based on two variables,
5043;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5044;; (with setq) to indicate a lock. But Tramp also calls itself during
5045;; processing of a single file operation, so we need to allow
5046;; recursive calls. That's where the `tramp-locker' variable comes in
5047;; -- it is let-bound to t during the execution of the current
5048;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5049;; then we should just proceed because we have been called
5050;; recursively. But if `tramp-locker' is nil, then we are a timer
5051;; interrupting the "main" Emacs, and then we signal an error.
5052
5053(defvar tramp-locked nil
5054 "If non-nil, then Tramp is currently busy.
5055Together with `tramp-locker', this implements a locking mechanism
5056preventing reentrant calls of Tramp.")
5057
5058(defvar tramp-locker nil
5059 "If non-nil, then a caller has locked Tramp.
5060Together with `tramp-locked', this implements a locking mechanism
5061preventing reentrant calls of Tramp.")
5062
ea9d1443
KG
5063(defun tramp-sh-file-name-handler (operation &rest args)
5064 "Invoke remote-shell Tramp file name handler.
5065Fall back to normal file name handler if no Tramp handler exists."
07dfe738 5066 (when (and tramp-locked (not tramp-locker))
11c71217 5067 (setq tramp-locked nil)
00d6fd04 5068 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
07dfe738
KG
5069 (let ((tl tramp-locked))
5070 (unwind-protect
5071 (progn
5072 (setq tramp-locked t)
5073 (let ((tramp-locker t))
5074 (save-match-data
5075 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5076 (if fn
5077 (apply (cdr fn) args)
5078 (tramp-run-real-handler operation args))))))
5079 (setq tramp-locked tl))))
ea9d1443 5080
946a5aeb
MA
5081(defun tramp-vc-file-name-handler (operation &rest args)
5082 "Invoke special file name handler, which collects files to be handled."
5083 (save-match-data
5084 (let ((filename
5085 (tramp-replace-environment-variables
5086 (apply 'tramp-file-name-for-operation operation args)))
5087 (fn (assoc operation tramp-file-name-handler-alist)))
5088 (with-parsed-tramp-file-name filename nil
5089 (cond
5090 ;; That's what we want: file names, for which checks are
5091 ;; applied. We assume, that VC uses only `file-exists-p' and
5092 ;; `file-readable-p' checks; otherwise we must extend the
5093 ;; list. We do not perform any action, but return nil, in
5094 ;; order to keep `vc-registered' running.
5095 ((and fn (memq operation '(file-exists-p file-readable-p)))
5096 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5097 nil)
5098 ;; Tramp file name handlers like `expand-file-name'. They
5099 ;; must still work.
5100 (fn
5101 (save-match-data (apply (cdr fn) args)))
5102 ;; Default file name handlers, we don't care.
5103 (t (tramp-run-real-handler operation args)))))))
5104
16674e4f 5105;;;###autoload
1ecc6145 5106(progn (defun tramp-completion-file-name-handler (operation &rest args)
a4aeb9a4
MA
5107 "Invoke Tramp file name completion handler.
5108Falls back to normal file name handler if no Tramp file name handler exists."
57671b72
MA
5109 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5110 ;; would otherwise use backslash.
aff67808
MA
5111 (let ((directory-sep-char ?/)
5112 (fn (assoc operation tramp-completion-file-name-handler-alist)))
aa485f7c
MA
5113 (if (and
5114 ;; When `tramp-mode' is not enabled, we don't do anything.
5115 fn tramp-mode
5116 ;; For other syntaxes than `sep', the regexp matches many common
5117 ;; situations where the user doesn't actually want to use Tramp.
5118 ;; So to avoid autoloading Tramp after typing just "/s", we
5119 ;; disable this part of the completion, unless the user implicitly
5120 ;; indicated his interest in using a fancier completion system.
5121 (or (eq tramp-syntax 'sep)
5122 (featurep 'tramp) ; If it's loaded, we may as well use it.
5123 (and (boundp 'partial-completion-mode) partial-completion-mode)
5124 ;; FIXME: These may have been loaded even if the user never
5125 ;; intended to use them.
5126 (featurep 'ido)
5127 (featurep 'icicles)))
aff67808
MA
5128 (save-match-data (apply (cdr fn) args))
5129 (tramp-completion-run-real-handler operation args)))))
a01b1e22 5130
b25a52cc 5131;;;###autoload
aa485f7c
MA
5132(progn (defun tramp-register-file-name-handlers ()
5133 "Add Tramp file name handlers to `file-name-handler-alist'."
5134 ;; Remove autoloaded handlers from file name handler alist. Useful,
00d6fd04
MA
5135 ;; if `tramp-syntax' has been changed.
5136 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
aa485f7c
MA
5137 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5138 (let ((a1 (rassq
5139 'tramp-completion-file-name-handler file-name-handler-alist)))
5140 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5141 ;; Add the handlers.
a01b1e22
MA
5142 (add-to-list 'file-name-handler-alist
5143 (cons tramp-file-name-regexp 'tramp-file-name-handler))
aa485f7c
MA
5144 (add-to-list 'file-name-handler-alist
5145 (cons tramp-completion-file-name-regexp
5146 'tramp-completion-file-name-handler))
5147 (put 'tramp-completion-file-name-handler 'safe-magic t)
5148 ;; If jka-compr or epa-file are already loaded, move them to the
5149 ;; front of `file-name-handler-alist'.
5150 (dolist (fnh '(epa-file-handler jka-compr-handler))
5151 (let ((entry (rassoc fnh file-name-handler-alist)))
5152 (when entry
5153 (setq file-name-handler-alist
5154 (cons entry (delete entry file-name-handler-alist))))))))
69cee873 5155
00d6fd04
MA
5156;; `tramp-file-name-handler' must be registered before evaluation of
5157;; site-start and init files, because there might exist remote files
5158;; already, f.e. files kept via recentf-mode.
aa485f7c
MA
5159;;;###autoload(tramp-register-file-name-handlers)
5160(tramp-register-file-name-handlers)
b25a52cc 5161
fb7933a3 5162;;;###autoload
8c04e197 5163(defun tramp-unload-file-name-handlers ()
a69c01a0
MA
5164 (setq file-name-handler-alist
5165 (delete (rassoc 'tramp-file-name-handler
5166 file-name-handler-alist)
5167 (delete (rassoc 'tramp-completion-file-name-handler
5168 file-name-handler-alist)
5169 file-name-handler-alist))))
5170
8c04e197 5171(add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
a69c01a0 5172
0664ff72 5173;;; File name handler functions for completion mode:
a6e96327
MA
5174
5175(defvar tramp-completion-mode nil
5176 "If non-nil, external packages signal that they are in file name completion.
5177
5178This is necessary, because Tramp uses a heuristic depending on last
5179input event. This fails when external packages use other characters
5180but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5181should never be set globally, the intention is to let-bind it.")
16674e4f
KG
5182
5183;; Necessary because `tramp-file-name-regexp-unified' and
00d6fd04
MA
5184;; `tramp-completion-file-name-regexp-unified' aren't different. If
5185;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5186;; to `tramp-file-name-handler'). Otherwise, it takes
5187;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5188;; risky, because completing a file might require loading other files,
5189;; like "~/.netrc", and for them it shouldn't be decided based on that
5190;; variable. On the other hand, those files shouldn't have partial
a4aeb9a4
MA
5191;; Tramp file name syntax. Maybe another variable should be introduced
5192;; overwriting this check in such cases. Or we change Tramp file name
00d6fd04 5193;; syntax in order to avoid ambiguities, like in XEmacs ...
6c4e47fa 5194(defun tramp-completion-mode-p ()
16674e4f 5195 "Checks whether method / user name / host name completion is active."
6c4e47fa 5196 (or
a6e96327
MA
5197 ;; Signal from outside.
5198 tramp-completion-mode
5199 ;; Emacs.
94be87e8 5200 (equal last-input-event 'tab)
6c4e47fa 5201 (and (natnump last-input-event)
94be87e8 5202 (or
a6e96327 5203 ;; ?\t has event-modifier 'control.
800a97b8 5204 (equal last-input-event ?\t)
94be87e8 5205 (and (not (event-modifiers last-input-event))
800a97b8
SM
5206 (or (equal last-input-event ?\?)
5207 (equal last-input-event ?\ )))))
a6e96327 5208 ;; XEmacs.
6c4e47fa
MA
5209 (and (featurep 'xemacs)
5210 ;; `last-input-event' might be nil.
5211 (not (null last-input-event))
5212 ;; `last-input-event' may have no character approximation.
5213 (funcall (symbol-function 'event-to-character) last-input-event)
94be87e8 5214 (or
a6e96327 5215 ;; ?\t has event-modifier 'control.
800a97b8 5216 (equal
94be87e8
MA
5217 (funcall (symbol-function 'event-to-character)
5218 last-input-event) ?\t)
5219 (and (not (event-modifiers last-input-event))
800a97b8 5220 (or (equal
94be87e8
MA
5221 (funcall (symbol-function 'event-to-character)
5222 last-input-event) ?\?)
800a97b8 5223 (equal
94be87e8
MA
5224 (funcall (symbol-function 'event-to-character)
5225 last-input-event) ?\ )))))))
16674e4f 5226
16674e4f
KG
5227;; Method, host name and user name completion.
5228;; `tramp-completion-dissect-file-name' returns a list of
5229;; tramp-file-name structures. For all of them we return possible completions.
a01b1e22 5230;;;###autoload
16674e4f 5231(defun tramp-completion-handle-file-name-all-completions (filename directory)
00d6fd04 5232 "Like `file-name-all-completions' for partial Tramp files."
16674e4f 5233
00d6fd04
MA
5234 (let* ((fullname (tramp-drop-volume-letter
5235 (expand-file-name filename directory)))
5236 ;; Possible completion structures.
5237 (v (tramp-completion-dissect-file-name fullname))
5238 result result1)
5239
5240 (while v
5241 (let* ((car (car v))
5242 (method (tramp-file-name-method car))
5243 (user (tramp-file-name-user car))
5244 (host (tramp-file-name-host car))
5245 (localname (tramp-file-name-localname car))
5246 (m (tramp-find-method method user host))
5247 (tramp-current-user user) ; see `tramp-parse-passwd'
5248 all-user-hosts)
5249
5250 (unless localname ;; Nothing to complete.
5251
5252 (if (or user host)
5253
5254 ;; Method dependent user / host combinations.
5255 (progn
9e6ab520 5256 (mapc
00d6fd04
MA
5257 (lambda (x)
5258 (setq all-user-hosts
5259 (append all-user-hosts
5260 (funcall (nth 0 x) (nth 1 x)))))
5261 (tramp-get-completion-function m))
5262
9e6ab520
MA
5263 (setq result
5264 (append result
5265 (mapcar
5266 (lambda (x)
5267 (tramp-get-completion-user-host
5268 method user host (nth 0 x) (nth 1 x)))
5269 (delq nil all-user-hosts)))))
00d6fd04
MA
5270
5271 ;; Possible methods.
5272 (setq result
5273 (append result (tramp-get-completion-methods m)))))
5274
5275 (setq v (cdr v))))
5276
5277 ;; Unify list, remove nil elements.
5278 (while result
5279 (let ((car (car result)))
5280 (when car
5281 (add-to-list
5282 'result1
5283 (substring car (length (tramp-drop-volume-letter directory)))))
5284 (setq result (cdr result))))
5285
5286 ;; Complete local parts.
5287 (append
5288 result1
5289 (condition-case nil
5290 (tramp-completion-run-real-handler
5291 'file-name-all-completions (list filename directory))
5292 (error nil)))))
16674e4f
KG
5293
5294;; Method, host name and user name completion for a file.
a01b1e22 5295;;;###autoload
e1e17cae
MA
5296(defun tramp-completion-handle-file-name-completion
5297 (filename directory &optional predicate)
00d6fd04 5298 "Like `file-name-completion' for Tramp files."
e1e17cae
MA
5299 (try-completion
5300 filename
5301 (mapcar 'list (file-name-all-completions filename directory))
83e20b5c
MA
5302 (when predicate
5303 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
16674e4f
KG
5304
5305;; I misuse a little bit the tramp-file-name structure in order to handle
5306;; completion possibilities for partial methods / user names / host names.
5307;; Return value is a list of tramp-file-name structures according to possible
00d6fd04 5308;; completions. If "localname" is non-nil it means there
16674e4f
KG
5309;; shouldn't be a completion anymore.
5310
5311;; Expected results:
5312
00d6fd04
MA
5313;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5314;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5315;; [nil "x" nil nil]
5316;; ["x" nil nil nil]
5317
5318;; "/x:" "/x:y" "/x:y:"
5319;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5320;; "/[x/" "/[x/y"
5321;; ["x" nil "" nil] ["x" nil "y" nil]
5322;; ["x" "" nil nil] ["x" "y" nil nil]
5323
5324;; "/x:y@" "/x:y@z" "/x:y@z:"
5325;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5326;; "/[x/y@" "/[x/y@z"
5327;; ["x" nil "y" nil] ["x" "y" "z" nil]
16674e4f
KG
5328(defun tramp-completion-dissect-file-name (name)
5329 "Returns a list of `tramp-file-name' structures.
5330They are collected by `tramp-completion-dissect-file-name1'."
5331
5332 (let* ((result)
4007ba5b 5333 (x-nil "\\|\\(\\)")
b96e6899
MA
5334 (tramp-completion-ipv6-regexp
5335 (format
5336 "[^%s]*"
5337 (if (zerop (length tramp-postfix-ipv6-format))
5338 tramp-postfix-host-format
5339 tramp-postfix-ipv6-format)))
4007ba5b
KG
5340 ;; "/method" "/[method"
5341 (tramp-completion-file-name-structure1
5342 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5343 1 nil nil nil))
5344 ;; "/user" "/[user"
5345 (tramp-completion-file-name-structure2
5346 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5347 nil 1 nil nil))
5348 ;; "/host" "/[host"
5349 (tramp-completion-file-name-structure3
5350 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5351 nil nil 1 nil))
b96e6899 5352 ;; "/[ipv6" "/[ipv6"
4007ba5b 5353 (tramp-completion-file-name-structure4
b96e6899
MA
5354 (list (concat tramp-prefix-regexp
5355 tramp-prefix-ipv6-regexp
5356 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5357 nil nil 1 nil))
5358 ;; "/user@host" "/[user@host"
5359 (tramp-completion-file-name-structure5
4007ba5b
KG
5360 (list (concat tramp-prefix-regexp
5361 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5362 "\\(" tramp-host-regexp x-nil "\\)$")
5363 nil 1 2 nil))
b96e6899
MA
5364 ;; "/user@[ipv6" "/[user@ipv6"
5365 (tramp-completion-file-name-structure6
5366 (list (concat tramp-prefix-regexp
5367 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5368 tramp-prefix-ipv6-regexp
5369 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5370 nil 1 2 nil))
00d6fd04 5371 ;; "/method:user" "/[method/user" "/method://user"
b96e6899 5372 (tramp-completion-file-name-structure7
4007ba5b 5373 (list (concat tramp-prefix-regexp
00d6fd04 5374 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5375 "\\(" tramp-user-regexp x-nil "\\)$")
5376 1 2 nil nil))
00d6fd04 5377 ;; "/method:host" "/[method/host" "/method://host"
b96e6899 5378 (tramp-completion-file-name-structure8
4007ba5b 5379 (list (concat tramp-prefix-regexp
00d6fd04 5380 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5381 "\\(" tramp-host-regexp x-nil "\\)$")
5382 1 nil 2 nil))
b96e6899
MA
5383 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5384 (tramp-completion-file-name-structure9
5385 (list (concat tramp-prefix-regexp
5386 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5387 tramp-prefix-ipv6-regexp
5388 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5389 1 nil 2 nil))
00d6fd04 5390 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
b96e6899 5391 (tramp-completion-file-name-structure10
4007ba5b 5392 (list (concat tramp-prefix-regexp
00d6fd04 5393 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4007ba5b
KG
5394 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5395 "\\(" tramp-host-regexp x-nil "\\)$")
00d6fd04 5396 1 2 3 nil))
b96e6899
MA
5397 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5398 (tramp-completion-file-name-structure11
5399 (list (concat tramp-prefix-regexp
5400 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5401 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5402 tramp-prefix-ipv6-regexp
5403 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5404 1 2 3 nil))
00d6fd04 5405 ;; "/method: "/method:/"
b96e6899 5406 (tramp-completion-file-name-structure12
00d6fd04
MA
5407 (list
5408 (if (equal tramp-syntax 'url)
5409 (concat tramp-prefix-regexp
5410 "\\(" tramp-method-regexp "\\)"
5411 "\\(" (substring tramp-postfix-method-regexp 0 1)
5412 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5413 "\\(" "\\)$")
5414 ;; Should not match if not URL syntax.
5415 (concat tramp-prefix-regexp "/$"))
5416 1 3 nil nil))
5417 ;; "/method: "/method:/"
b96e6899 5418 (tramp-completion-file-name-structure13
00d6fd04
MA
5419 (list
5420 (if (equal tramp-syntax 'url)
5421 (concat tramp-prefix-regexp
5422 "\\(" tramp-method-regexp "\\)"
5423 "\\(" (substring tramp-postfix-method-regexp 0 1)
5424 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5425 "\\(" "\\)$")
5426 ;; Should not match if not URL syntax.
5427 (concat tramp-prefix-regexp "/$"))
5428 1 nil 3 nil)))
4007ba5b 5429
9e6ab520 5430 (mapc (lambda (regexp)
16674e4f
KG
5431 (add-to-list 'result
5432 (tramp-completion-dissect-file-name1 regexp name)))
5433 (list
5434 tramp-completion-file-name-structure1
5435 tramp-completion-file-name-structure2
5436 tramp-completion-file-name-structure3
5437 tramp-completion-file-name-structure4
5438 tramp-completion-file-name-structure5
5439 tramp-completion-file-name-structure6
5440 tramp-completion-file-name-structure7
00d6fd04
MA
5441 tramp-completion-file-name-structure8
5442 tramp-completion-file-name-structure9
b96e6899
MA
5443 tramp-completion-file-name-structure10
5444 tramp-completion-file-name-structure11
5445 tramp-completion-file-name-structure12
5446 tramp-completion-file-name-structure13
16674e4f
KG
5447 tramp-file-name-structure))
5448
5449 (delq nil result)))
5450
5451(defun tramp-completion-dissect-file-name1 (structure name)
5452 "Returns a `tramp-file-name' structure matching STRUCTURE.
00d6fd04 5453The structure consists of remote method, remote user,
7432277c 5454remote host and localname (filename on remote host)."
fb7933a3 5455
00d6fd04
MA
5456 (save-match-data
5457 (when (string-match (nth 0 structure) name)
5458 (let ((method (and (nth 1 structure)
5459 (match-string (nth 1 structure) name)))
5460 (user (and (nth 2 structure)
5461 (match-string (nth 2 structure) name)))
5462 (host (and (nth 3 structure)
5463 (match-string (nth 3 structure) name)))
5464 (localname (and (nth 4 structure)
5465 (match-string (nth 4 structure) name))))
5466 (vector method user host localname)))))
16674e4f
KG
5467
5468;; This function returns all possible method completions, adding the
5469;; trailing method delimeter.
16674e4f
KG
5470(defun tramp-get-completion-methods (partial-method)
5471 "Returns all method completions for PARTIAL-METHOD."
4007ba5b
KG
5472 (mapcar
5473 (lambda (method)
5474 (and method
5475 (string-match (concat "^" (regexp-quote partial-method)) method)
00d6fd04
MA
5476 (tramp-completion-make-tramp-file-name method nil nil nil)))
5477 (mapcar 'car tramp-methods)))
16674e4f
KG
5478
5479;; Compares partial user and host names with possible completions.
5480(defun tramp-get-completion-user-host (method partial-user partial-host user host)
5481 "Returns the most expanded string for user and host name completion.
5482PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5483 (cond
5484
5485 ((and partial-user partial-host)
5486 (if (and host
5487 (string-match (concat "^" (regexp-quote partial-host)) host)
5488 (string-equal partial-user (or user partial-user)))
5489 (setq user partial-user)
5490 (setq user nil
5491 host nil)))
5492
5493 (partial-user
5494 (setq host nil)
5495 (unless
5496 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5497 (setq user nil)))
5498
5499 (partial-host
5500 (setq user nil)
5501 (unless
5502 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5503 (setq host nil)))
5504
5505 (t (setq user nil
5506 host nil)))
5507
292ffc15 5508 (unless (zerop (+ (length user) (length host)))
00d6fd04 5509 (tramp-completion-make-tramp-file-name method user host nil)))
16674e4f
KG
5510
5511(defun tramp-parse-rhosts (filename)
5512 "Return a list of (user host) tuples allowed to access.
292ffc15 5513Either user or host may be nil."
00d6fd04
MA
5514 ;; On Windows, there are problems in completion when
5515 ;; `default-directory' is remote.
9e6ab520 5516 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5517 res)
8daea7fc 5518 (when (file-readable-p filename)
16674e4f
KG
5519 (with-temp-buffer
5520 (insert-file-contents filename)
5521 (goto-char (point-min))
5522 (while (not (eobp))
292ffc15 5523 (push (tramp-parse-rhosts-group) res))))
16674e4f
KG
5524 res))
5525
16674e4f
KG
5526(defun tramp-parse-rhosts-group ()
5527 "Return a (user host) tuple allowed to access.
292ffc15 5528Either user or host may be nil."
16674e4f
KG
5529 (let ((result)
5530 (regexp
5531 (concat
5532 "^\\(" tramp-host-regexp "\\)"
5533 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 5534 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5535 (when (re-search-forward regexp nil t)
5536 (setq result (append (list (match-string 3) (match-string 1)))))
5537 (widen)
5538 (forward-line 1)
5539 result))
5540
5541(defun tramp-parse-shosts (filename)
5542 "Return a list of (user host) tuples allowed to access.
5543User is always nil."
00d6fd04
MA
5544 ;; On Windows, there are problems in completion when
5545 ;; `default-directory' is remote.
9e6ab520 5546 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5547 res)
8daea7fc 5548 (when (file-readable-p filename)
16674e4f
KG
5549 (with-temp-buffer
5550 (insert-file-contents filename)
5551 (goto-char (point-min))
5552 (while (not (eobp))
292ffc15 5553 (push (tramp-parse-shosts-group) res))))
16674e4f
KG
5554 res))
5555
5556(defun tramp-parse-shosts-group ()
5557 "Return a (user host) tuple allowed to access.
5558User is always nil."
16674e4f
KG
5559 (let ((result)
5560 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
9e6ab520 5561 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5562 (when (re-search-forward regexp nil t)
5563 (setq result (list nil (match-string 1))))
5564 (widen)
5565 (or
5566 (> (skip-chars-forward ",") 0)
5567 (forward-line 1))
5568 result))
5569
8daea7fc
KG
5570(defun tramp-parse-sconfig (filename)
5571 "Return a list of (user host) tuples allowed to access.
5572User is always nil."
00d6fd04
MA
5573 ;; On Windows, there are problems in completion when
5574 ;; `default-directory' is remote.
9e6ab520 5575 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5576 res)
8daea7fc
KG
5577 (when (file-readable-p filename)
5578 (with-temp-buffer
5579 (insert-file-contents filename)
5580 (goto-char (point-min))
5581 (while (not (eobp))
5582 (push (tramp-parse-sconfig-group) res))))
5583 res))
5584
5585(defun tramp-parse-sconfig-group ()
5586 "Return a (user host) tuple allowed to access.
5587User is always nil."
8daea7fc
KG
5588 (let ((result)
5589 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
9e6ab520 5590 (narrow-to-region (point) (tramp-compat-line-end-position))
8daea7fc
KG
5591 (when (re-search-forward regexp nil t)
5592 (setq result (list nil (match-string 1))))
5593 (widen)
5594 (or
5595 (> (skip-chars-forward ",") 0)
5596 (forward-line 1))
5597 result))
5598
5ec2cc41
KG
5599(defun tramp-parse-shostkeys (dirname)
5600 "Return a list of (user host) tuples allowed to access.
5601User is always nil."
00d6fd04
MA
5602 ;; On Windows, there are problems in completion when
5603 ;; `default-directory' is remote.
9e6ab520 5604 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
5605 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
5606 (files (when (file-directory-p dirname) (directory-files dirname)))
5607 result)
5ec2cc41
KG
5608 (while files
5609 (when (string-match regexp (car files))
5610 (push (list nil (match-string 1 (car files))) result))
5611 (setq files (cdr files)))
5612 result))
5613
5614(defun tramp-parse-sknownhosts (dirname)
5615 "Return a list of (user host) tuples allowed to access.
5616User is always nil."
00d6fd04
MA
5617 ;; On Windows, there are problems in completion when
5618 ;; `default-directory' is remote.
9e6ab520 5619 (let* ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
5620 (regexp (concat "^\\(" tramp-host-regexp
5621 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
5622 (files (when (file-directory-p dirname) (directory-files dirname)))
5623 result)
5ec2cc41
KG
5624 (while files
5625 (when (string-match regexp (car files))
5626 (push (list nil (match-string 1 (car files))) result))
5627 (setq files (cdr files)))
5628 result))
5629
16674e4f
KG
5630(defun tramp-parse-hosts (filename)
5631 "Return a list of (user host) tuples allowed to access.
5632User is always nil."
00d6fd04
MA
5633 ;; On Windows, there are problems in completion when
5634 ;; `default-directory' is remote.
9e6ab520 5635 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5636 res)
8daea7fc 5637 (when (file-readable-p filename)
16674e4f
KG
5638 (with-temp-buffer
5639 (insert-file-contents filename)
5640 (goto-char (point-min))
5641 (while (not (eobp))
292ffc15 5642 (push (tramp-parse-hosts-group) res))))
16674e4f
KG
5643 res))
5644
5645(defun tramp-parse-hosts-group ()
5646 "Return a (user host) tuple allowed to access.
5647User is always nil."
16674e4f 5648 (let ((result)
b96e6899
MA
5649 (regexp
5650 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
9e6ab520 5651 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f 5652 (when (re-search-forward regexp nil t)
b96e6899 5653 (setq result (list nil (match-string 1))))
16674e4f
KG
5654 (widen)
5655 (or
5656 (> (skip-chars-forward " \t") 0)
5657 (forward-line 1))
5658 result))
5659
8daea7fc
KG
5660;; For su-alike methods it would be desirable to return "root@localhost"
5661;; as default. Unfortunately, we have no information whether any user name
00d6fd04 5662;; has been typed already. So we use `tramp-current-user' as indication,
8daea7fc 5663;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
16674e4f
KG
5664(defun tramp-parse-passwd (filename)
5665 "Return a list of (user host) tuples allowed to access.
5666Host is always \"localhost\"."
00d6fd04
MA
5667 ;; On Windows, there are problems in completion when
5668 ;; `default-directory' is remote.
9e6ab520 5669 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5670 res)
8daea7fc 5671 (if (zerop (length tramp-current-user))
16674e4f 5672 '(("root" nil))
8daea7fc 5673 (when (file-readable-p filename)
16674e4f
KG
5674 (with-temp-buffer
5675 (insert-file-contents filename)
5676 (goto-char (point-min))
5677 (while (not (eobp))
292ffc15 5678 (push (tramp-parse-passwd-group) res))))
16674e4f
KG
5679 res)))
5680
5681(defun tramp-parse-passwd-group ()
5682 "Return a (user host) tuple allowed to access.
292ffc15 5683Host is always \"localhost\"."
16674e4f
KG
5684 (let ((result)
5685 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
9e6ab520 5686 (narrow-to-region (point) (tramp-compat-line-end-position))
16674e4f
KG
5687 (when (re-search-forward regexp nil t)
5688 (setq result (list (match-string 1) "localhost")))
5689 (widen)
5690 (forward-line 1)
5691 result))
5692
292ffc15
KG
5693(defun tramp-parse-netrc (filename)
5694 "Return a list of (user host) tuples allowed to access.
5695User may be nil."
00d6fd04
MA
5696 ;; On Windows, there are problems in completion when
5697 ;; `default-directory' is remote.
9e6ab520 5698 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04 5699 res)
8daea7fc 5700 (when (file-readable-p filename)
292ffc15
KG
5701 (with-temp-buffer
5702 (insert-file-contents filename)
5703 (goto-char (point-min))
5704 (while (not (eobp))
5705 (push (tramp-parse-netrc-group) res))))
5706 res))
5707
5708(defun tramp-parse-netrc-group ()
5709 "Return a (user host) tuple allowed to access.
5710User may be nil."
292ffc15
KG
5711 (let ((result)
5712 (regexp
5713 (concat
5714 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
5715 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
9e6ab520 5716 (narrow-to-region (point) (tramp-compat-line-end-position))
292ffc15
KG
5717 (when (re-search-forward regexp nil t)
5718 (setq result (list (match-string 3) (match-string 1))))
5719 (widen)
5720 (forward-line 1)
5721 result))
5722
00d6fd04
MA
5723(defun tramp-parse-putty (registry)
5724 "Return a list of (user host) tuples allowed to access.
5725User is always nil."
5726 ;; On Windows, there are problems in completion when
5727 ;; `default-directory' is remote.
9e6ab520 5728 (let ((default-directory (tramp-compat-temporary-file-directory))
00d6fd04
MA
5729 res)
5730 (with-temp-buffer
a4aeb9a4 5731 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
00d6fd04
MA
5732 (goto-char (point-min))
5733 (while (not (eobp))
5734 (push (tramp-parse-putty-group registry) res))))
5735 res))
5736
5737(defun tramp-parse-putty-group (registry)
5738 "Return a (user host) tuple allowed to access.
5739User is always nil."
5740 (let ((result)
5741 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
9e6ab520 5742 (narrow-to-region (point) (tramp-compat-line-end-position))
00d6fd04
MA
5743 (when (re-search-forward regexp nil t)
5744 (setq result (list nil (match-string 1))))
5745 (widen)
5746 (forward-line 1)
5747 result))
5748
fb7933a3
KG
5749;;; Internal Functions:
5750
00d6fd04
MA
5751(defun tramp-maybe-send-script (vec script name)
5752 "Define in remote shell function NAME implemented as SCRIPT.
5753Only send the definition if it has not already been done."
5754 (let* ((p (tramp-get-connection-process vec))
5755 (scripts (tramp-get-connection-property p "scripts" nil)))
1834b39f 5756 (unless (member name scripts)
00d6fd04
MA
5757 (tramp-message vec 5 "Sending script `%s'..." name)
5758 ;; The script could contain a call of Perl. This is masked with `%s'.
5759 (tramp-send-command-and-check
5760 vec
5761 (format "%s () {\n%s\n}" name
5762 (format script (tramp-get-remote-perl vec))))
5763 (tramp-set-connection-property p "scripts" (cons name scripts))
5764 (tramp-message vec 5 "Sending script `%s'...done." name))))
c82c5727 5765
fb7933a3 5766(defun tramp-set-auto-save ()
00d6fd04 5767 (when (and ;; ange-ftp has its own auto-save mechanism
7177e2a3
MA
5768 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
5769 'tramp-sh-file-name-handler)
fb7933a3
KG
5770 auto-save-default)
5771 (auto-save-mode 1)))
5772(add-hook 'find-file-hooks 'tramp-set-auto-save t)
a69c01a0 5773(add-hook 'tramp-unload-hook
aa485f7c
MA
5774 (lambda ()
5775 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
fb7933a3
KG
5776
5777(defun tramp-run-test (switch filename)
5778 "Run `test' on the remote system, given a SWITCH and a FILENAME.
5779Returns the exit code of the `test' program."
00d6fd04
MA
5780 (with-parsed-tramp-file-name filename nil
5781 (tramp-send-command-and-check
5782 v
5783 (format
5784 "%s %s %s"
5785 (tramp-get-test-command v)
5786 switch
5787 (tramp-shell-quote-argument localname)))))
5788
5789(defun tramp-run-test2 (format-string file1 file2)
5790 "Run `test'-like program on the remote system, given FILE1, FILE2.
5791FORMAT-STRING contains the program name, switches, and place holders.
5792Returns the exit code of the `test' program. Barfs if the methods,
fb7933a3 5793hosts, or files, disagree."
00d6fd04
MA
5794 (unless (tramp-equal-remote file1 file2)
5795 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
5796 (tramp-error
5797 v 'file-error
5798 "tramp-run-test2 only implemented for same method, user, host")))
5799 (with-parsed-tramp-file-name file1 v1
5800 (with-parsed-tramp-file-name file1 v2
fb7933a3 5801 (tramp-send-command-and-check
00d6fd04
MA
5802 v1
5803 (format format-string
5804 (tramp-shell-quote-argument v1-localname)
5805 (tramp-shell-quote-argument v2-localname))))))
fb7933a3 5806
00d6fd04
MA
5807(defun tramp-buffer-name (vec)
5808 "A name for the connection buffer VEC."
5809 ;; We must use `tramp-file-name-real-host', because for gateway
5810 ;; methods the default port will be expanded later on, which would
5811 ;; tamper the name.
5812 (let ((method (tramp-file-name-method vec))
5813 (user (tramp-file-name-user vec))
5814 (host (tramp-file-name-real-host vec)))
5815 (if (not (zerop (length user)))
5816 (format "*tramp/%s %s@%s*" method user host)
5817 (format "*tramp/%s %s*" method host))))
5818
5819(defun tramp-get-buffer (vec)
5820 "Get the connection buffer to be used for VEC."
5821 (or (get-buffer (tramp-buffer-name vec))
5822 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
5823 (setq buffer-undo-list t)
5824 (setq default-directory
5825 (tramp-make-tramp-file-name
5826 (tramp-file-name-method vec)
5827 (tramp-file-name-user vec)
5828 (tramp-file-name-host vec)
5829 "/"))
5830 (current-buffer))))
5831
5832(defun tramp-get-connection-buffer (vec)
5833 "Get the connection buffer to be used for VEC.
5834In case a second asynchronous communication has been started, it is different
5835from `tramp-get-buffer'."
5836 (or (tramp-get-connection-property vec "process-buffer" nil)
5837 (tramp-get-buffer vec)))
5838
5839(defun tramp-get-connection-process (vec)
5840 "Get the connection process to be used for VEC.
5841In case a second asynchronous communication has been started, it is different
5842from the default one."
5843 (get-process
5844 (or (tramp-get-connection-property vec "process-name" nil)
5845 (tramp-buffer-name vec))))
5846
5847(defun tramp-debug-buffer-name (vec)
5848 "A name for the debug buffer for VEC."
5849 ;; We must use `tramp-file-name-real-host', because for gateway
5850 ;; methods the default port will be expanded later on, which would
5851 ;; tamper the name.
5852 (let ((method (tramp-file-name-method vec))
5853 (user (tramp-file-name-user vec))
5854 (host (tramp-file-name-real-host vec)))
5855 (if (not (zerop (length user)))
5856 (format "*debug tramp/%s %s@%s*" method user host)
5857 (format "*debug tramp/%s %s*" method host))))
5858
5859(defun tramp-get-debug-buffer (vec)
5860 "Get the debug buffer for VEC."
01917a18 5861 (with-current-buffer
00d6fd04
MA
5862 (get-buffer-create (tramp-debug-buffer-name vec))
5863 (when (bobp)
5864 (setq buffer-undo-list t)
9ce8462a
MA
5865 ;; Activate outline-mode. This runs `text-mode-hook' and
5866 ;; `outline-mode-hook'. We must prevent that local processes
5867 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
5868 ;; ...
9e6ab520 5869 (let ((default-directory (tramp-compat-temporary-file-directory)))
00d6fd04 5870 (outline-mode))
9ce8462a 5871 (set (make-local-variable 'outline-regexp)
736ac90f 5872 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
9ce8462a
MA
5873; (set (make-local-variable 'outline-regexp)
5874; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
5875 (set (make-local-variable 'outline-level) 'tramp-outline-level))
01917a18 5876 (current-buffer)))
fb7933a3 5877
00d6fd04
MA
5878(defun tramp-outline-level ()
5879 "Return the depth to which a statement is nested in the outline.
5880Point must be at the beginning of a header line.
5881
5882The outline level is equal to the verbosity of the Tramp message."
5883 (1+ (string-to-number (match-string 1))))
fb7933a3 5884
00d6fd04
MA
5885(defun tramp-find-executable
5886 (vec progname dirlist &optional ignore-tilde ignore-path)
5887 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
5888First arg VEC specifies the connection, PROGNAME is the program
5889to search for, and DIRLIST gives the list of directories to
5890search. If IGNORE-TILDE is non-nil, directory names starting
5891with `~' will be ignored. If IGNORE-PATH is non-nil, searches
5892only in DIRLIST.
fb7933a3 5893
7432277c 5894Returns the absolute file name of PROGNAME, if found, and nil otherwise.
fb7933a3
KG
5895
5896This function expects to be in the right *tramp* buffer."
00d6fd04
MA
5897 (with-current-buffer (tramp-get-buffer vec)
5898 (let (result)
5899 ;; Check whether the executable is in $PATH. "which(1)" does not
5900 ;; report always a correct error code; therefore we check the
5901 ;; number of words it returns.
5902 (unless ignore-path
5903 (tramp-send-command vec (format "which \\%s | wc -w" progname))
5904 (goto-char (point-min))
5905 (if (looking-at "^1$")
5906 (setq result (concat "\\" progname))))
5907 (unless result
5908 (when ignore-tilde
5909 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
5910 ;; `remove' is in CL, and we want to avoid CL dependencies.
5911 (let (newdl d)
5912 (while dirlist
5913 (setq d (car dirlist))
5914 (setq dirlist (cdr dirlist))
5915 (unless (char-equal ?~ (aref d 0))
5916 (setq newdl (cons d newdl))))
5917 (setq dirlist (nreverse newdl))))
5918 (tramp-send-command
5919 vec
5920 (format (concat "while read d; "
5921 "do if test -x $d/%s -a -f $d/%s; "
5922 "then echo tramp_executable $d/%s; "
5923 "break; fi; done <<'EOF'\n"
5924 "%s\nEOF")
5925 progname progname progname (mapconcat 'identity dirlist "\n")))
5926 (goto-char (point-max))
5927 (when (search-backward "tramp_executable " nil t)
5928 (skip-chars-forward "^ ")
5929 (skip-chars-forward " ")
9e6ab520
MA
5930 (setq result (buffer-substring
5931 (point) (tramp-compat-line-end-position)))))
00d6fd04
MA
5932 result)))
5933
5934(defun tramp-set-remote-path (vec)
5935 "Sets the remote environment PATH to existing directories.
5936I.e., for each directory in `tramp-remote-path', it is tested
5937whether it exists and if so, it is added to the environment
5938variable PATH."
5939 (tramp-message vec 5 (format "Setting $PATH environment variable"))
f84638eb
MA
5940 (tramp-send-command
5941 vec (format "PATH=%s; export PATH"
5942 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
fb7933a3 5943
cfb5c0db
MA
5944;; ------------------------------------------------------------
5945;; -- Communication with external shell --
5946;; ------------------------------------------------------------
fb7933a3 5947
00d6fd04 5948(defun tramp-find-file-exists-command (vec)
fb7933a3
KG
5949 "Find a command on the remote host for checking if a file exists.
5950Here, we are looking for a command which has zero exit status if the
5951file exists and nonzero exit status otherwise."
00d6fd04 5952 (let ((existing "/")
fb7933a3 5953 (nonexisting
00d6fd04
MA
5954 (tramp-shell-quote-argument "/ this file does not exist "))
5955 result)
fb7933a3
KG
5956 ;; The algorithm is as follows: we try a list of several commands.
5957 ;; For each command, we first run `$cmd /' -- this should return
5958 ;; true, as the root directory always exists. And then we run
00d6fd04 5959 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
fb7933a3
KG
5960 ;; does not exist. This should return false. We use the first
5961 ;; command we find that seems to work.
5962 ;; The list of commands to try is as follows:
00d6fd04
MA
5963 ;; `ls -d' This works on most systems, but NetBSD 1.4
5964 ;; has a bug: `ls' always returns zero exit
5965 ;; status, even for files which don't exist.
5966 ;; `test -e' Some Bourne shells have a `test' builtin
5967 ;; which does not know the `-e' option.
5968 ;; `/bin/test -e' For those, the `test' binary on disk normally
5969 ;; provides the option. Alas, the binary
5970 ;; is sometimes `/bin/test' and sometimes it's
5971 ;; `/usr/bin/test'.
5972 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
fb7933a3 5973 (unless (or
00d6fd04
MA
5974 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
5975 (zerop (tramp-send-command-and-check
5976 vec (format "%s %s" result existing)))
5977 (not (zerop (tramp-send-command-and-check
5978 vec (format "%s %s" result nonexisting)))))
5979 (and (setq result "/bin/test -e")
5980 (zerop (tramp-send-command-and-check
5981 vec (format "%s %s" result existing)))
5982 (not (zerop (tramp-send-command-and-check
5983 vec (format "%s %s" result nonexisting)))))
5984 (and (setq result "/usr/bin/test -e")
5985 (zerop (tramp-send-command-and-check
5986 vec (format "%s %s" result existing)))
5987 (not (zerop (tramp-send-command-and-check
5988 vec (format "%s %s" result nonexisting)))))
5989 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
5990 (zerop (tramp-send-command-and-check
5991 vec (format "%s %s" result existing)))
5992 (not (zerop (tramp-send-command-and-check
5993 vec (format "%s %s" result nonexisting))))))
5994 (tramp-error
5995 vec 'file-error "Couldn't find command to check if file exists"))
5996 result))
bf247b6e 5997
fb7933a3 5998;; CCC test ksh or bash found for tilde expansion?
00d6fd04
MA
5999(defun tramp-find-shell (vec)
6000 "Opens a shell on the remote host which groks tilde expansion."
6001 (unless (tramp-get-connection-property vec "remote-shell" nil)
6002 (let (shell)
6003 (with-current-buffer (tramp-get-buffer vec)
7e780ff1 6004 (tramp-send-command vec "echo ~root" t)
00d6fd04
MA
6005 (cond
6006 ((string-match "^~root$" (buffer-string))
6007 (setq shell
f84638eb
MA
6008 (or (tramp-find-executable
6009 vec "bash" (tramp-get-remote-path vec) t)
6010 (tramp-find-executable
6011 vec "ksh" (tramp-get-remote-path vec) t)))
00d6fd04
MA
6012 (unless shell
6013 (tramp-error
6014 vec 'file-error
6015 "Couldn't find a shell which groks tilde expansion"))
6016 ;; Find arguments for this shell.
6017 (let ((alist tramp-sh-extra-args)
6018 item extra-args)
6019 (while (and alist (null extra-args))
6020 (setq item (pop alist))
6021 (when (string-match (car item) shell)
6022 (setq extra-args (cdr item))))
6023 (when extra-args (setq shell (concat shell " " extra-args))))
6024 (tramp-message
6025 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
a4aeb9a4
MA
6026 (let ((tramp-end-of-output "$ "))
6027 (tramp-send-command
b08104a0 6028 vec
70c11b0b
MA
6029 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6030 (shell-quote-argument tramp-end-of-output) shell)
b08104a0 6031 t))
a0a5183a 6032 ;; Setting prompts.
00d6fd04 6033 (tramp-message vec 5 "Setting remote shell prompt...")
70c11b0b
MA
6034 (tramp-send-command
6035 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
6036 (tramp-send-command vec "PS2=''" t)
6037 (tramp-send-command vec "PS3=''" t)
6038 (tramp-send-command vec "PROMPT_COMMAND=''" t)
00d6fd04 6039 (tramp-message vec 5 "Setting remote shell prompt...done"))
a0a5183a 6040
00d6fd04
MA
6041 (t (tramp-message
6042 vec 5 "Remote `%s' groks tilde expansion, good"
6043 (tramp-get-method-parameter
6044 (tramp-file-name-method vec) 'tramp-remote-sh))
6045 (tramp-set-connection-property
6046 vec "remote-shell"
6047 (tramp-get-method-parameter
6048 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
fb7933a3 6049
bf247b6e
KS
6050;; ------------------------------------------------------------
6051;; -- Functions for establishing connection --
6052;; ------------------------------------------------------------
fb7933a3 6053
ac474af1
KG
6054;; The following functions are actions to be taken when seeing certain
6055;; prompts from the remote host. See the variable
6056;; `tramp-actions-before-shell' for usage of these functions.
6057
00d6fd04 6058(defun tramp-action-login (proc vec)
ac474af1 6059 "Send the login name."
00d6fd04
MA
6060 (when (not (stringp tramp-current-user))
6061 (save-window-excursion
6062 (let ((enable-recursive-minibuffers t))
6063 (pop-to-buffer (tramp-get-connection-buffer vec))
6064 (setq tramp-current-user (read-string (match-string 0))))))
6065 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6066 (with-current-buffer (tramp-get-connection-buffer vec)
6067 (tramp-message vec 6 "\n%s" (buffer-string)))
6068 (tramp-send-string vec tramp-current-user))
6069
6070(defun tramp-action-password (proc vec)
ac474af1 6071 "Query the user for a password."
70c11b0b
MA
6072 (with-current-buffer (process-buffer proc)
6073 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6074 (tramp-message vec 3 "Sending %s" (match-string 1)))
00d6fd04
MA
6075 (tramp-enter-password proc))
6076
6077(defun tramp-action-succeed (proc vec)
ac474af1 6078 "Signal success in finding shell prompt."
ac474af1
KG
6079 (throw 'tramp-action 'ok))
6080
00d6fd04 6081(defun tramp-action-permission-denied (proc vec)
ac474af1 6082 "Signal permission denied."
00d6fd04 6083 (kill-process proc)
ac474af1
KG
6084 (throw 'tramp-action 'permission-denied))
6085
00d6fd04 6086(defun tramp-action-yesno (proc vec)
3cdaec13
KG
6087 "Ask the user for confirmation using `yes-or-no-p'.
6088Send \"yes\" to remote process on confirmation, abort otherwise.
6089See also `tramp-action-yn'."
ac474af1 6090 (save-window-excursion
00d6fd04
MA
6091 (let ((enable-recursive-minibuffers t))
6092 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6093 (unless (yes-or-no-p (match-string 0))
6094 (kill-process proc)
6095 (throw 'tramp-action 'permission-denied))
6096 (with-current-buffer (tramp-get-connection-buffer vec)
6097 (tramp-message vec 6 "\n%s" (buffer-string)))
6098 (tramp-send-string vec "yes"))))
6099
6100(defun tramp-action-yn (proc vec)
3cdaec13
KG
6101 "Ask the user for confirmation using `y-or-n-p'.
6102Send \"y\" to remote process on confirmation, abort otherwise.
6103See also `tramp-action-yesno'."
6104 (save-window-excursion
00d6fd04
MA
6105 (let ((enable-recursive-minibuffers t))
6106 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6107 (unless (y-or-n-p (match-string 0))
6108 (kill-process proc)
6109 (throw 'tramp-action 'permission-denied))
6110 (with-current-buffer (tramp-get-connection-buffer vec)
6111 (tramp-message vec 6 "\n%s" (buffer-string)))
6112 (tramp-send-string vec "y"))))
6113
6114(defun tramp-action-terminal (proc vec)
487f4fb7
KG
6115 "Tell the remote host which terminal type to use.
6116The terminal type can be configured with `tramp-terminal-type'."
00d6fd04 6117 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
7e780ff1
MA
6118 (with-current-buffer (tramp-get-connection-buffer vec)
6119 (tramp-message vec 6 "\n%s" (buffer-string)))
00d6fd04 6120 (tramp-send-string vec tramp-terminal-type))
487f4fb7 6121
00d6fd04 6122(defun tramp-action-process-alive (proc vec)
19a87064 6123 "Check whether a process has finished."
00d6fd04 6124 (unless (memq (process-status proc) '(run open))
19a87064
MA
6125 (throw 'tramp-action 'process-died)))
6126
00d6fd04 6127(defun tramp-action-out-of-band (proc vec)
38c65fca 6128 "Check whether an out-of-band copy has finished."
00d6fd04
MA
6129 (cond ((and (memq (process-status proc) '(stop exit))
6130 (zerop (process-exit-status proc)))
6131 (tramp-message vec 3 "Process has finished.")
38c65fca 6132 (throw 'tramp-action 'ok))
00d6fd04
MA
6133 ((or (and (memq (process-status proc) '(stop exit))
6134 (not (zerop (process-exit-status proc))))
6135 (memq (process-status proc) '(signal)))
01917a18
MA
6136 ;; `scp' could have copied correctly, but set modes could have failed.
6137 ;; This can be ignored.
00d6fd04
MA
6138 (with-current-buffer (process-buffer proc)
6139 (goto-char (point-min))
6140 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6141 (progn
6142 (tramp-message vec 5 "'set mode' error ignored.")
6143 (tramp-message vec 3 "Process has finished.")
6144 (throw 'tramp-action 'ok))
6145 (tramp-message vec 3 "Process has died.")
6146 (throw 'tramp-action 'process-died))))
38c65fca
KG
6147 (t nil)))
6148
ac474af1
KG
6149;; Functions for processing the actions.
6150
00d6fd04 6151(defun tramp-process-one-action (proc vec actions)
ac474af1 6152 "Wait for output from the shell and perform one action."
00d6fd04 6153 (let (found todo item pattern action)
e6466697 6154 (while (not found)
00d6fd04
MA
6155 ;; Reread output once all actions have been performed.
6156 ;; Obviously, the output was not complete.
6157 (tramp-accept-process-output proc 1)
e6466697
MA
6158 (setq todo actions)
6159 (while todo
e6466697 6160 (setq item (pop todo))
95d610cb 6161 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
e6466697 6162 (setq action (nth 1 item))
00d6fd04
MA
6163 (tramp-message
6164 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6165 (when (tramp-check-for-regexp proc pattern)
6166 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6167 (setq found (funcall action proc vec)))))
e6466697
MA
6168 found))
6169
00d6fd04 6170(defun tramp-process-actions (proc vec actions &optional timeout)
e6466697 6171 "Perform actions until success or TIMEOUT."
263c02ef 6172 ;; Enable auth-source and password-cache.
5c7043a2 6173 (tramp-set-connection-property proc "first-password-request" t)
ac474af1
KG
6174 (let (exit)
6175 (while (not exit)
00d6fd04 6176 (tramp-message proc 3 "Waiting for prompts from remote shell")
ac474af1
KG
6177 (setq exit
6178 (catch 'tramp-action
e6466697
MA
6179 (if timeout
6180 (with-timeout (timeout)
00d6fd04
MA
6181 (tramp-process-one-action proc vec actions))
6182 (tramp-process-one-action proc vec actions)))))
6183 (with-current-buffer (tramp-get-connection-buffer vec)
6184 (tramp-message vec 6 "\n%s" (buffer-string)))
ac474af1 6185 (unless (eq exit 'ok)
9c13938d 6186 (tramp-clear-passwd vec)
00d6fd04
MA
6187 (tramp-error-with-buffer
6188 nil vec 'file-error
6189 (cond
6190 ((eq exit 'permission-denied) "Permission denied")
6191 ((eq exit 'process-died) "Process died")
6192 (t "Login failed"))))))
fb7933a3
KG
6193
6194;; Utility functions.
6195
00d6fd04 6196(defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
d2a2c17f
MA
6197 "Like `accept-process-output' for Tramp processes.
6198This is needed in order to hide `last-coding-system-used', which is set
6199for process communication also."
00d6fd04
MA
6200 (with-current-buffer (process-buffer proc)
6201 (tramp-message proc 10 "%s %s" proc (process-status proc))
6202 (let (buffer-read-only last-coding-system-used)
6203 ;; Under Windows XP, accept-process-output doesn't return
6204 ;; sometimes. So we add an additional timeout.
6205 (with-timeout ((or timeout 1))
6206 (accept-process-output proc timeout timeout-msecs)))
6207 (tramp-message proc 10 "\n%s" (buffer-string))))
6208
6209(defun tramp-check-for-regexp (proc regexp)
6210 "Check whether REGEXP is contained in process buffer of PROC.
6211Erase echoed commands if exists."
6212 (with-current-buffer (process-buffer proc)
6213 (goto-char (point-min))
674da028 6214
00d6fd04
MA
6215 ;; Check whether we need to remove echo output.
6216 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6217 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6218 (let ((begin (match-beginning 0)))
6219 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6220 ;; Discard echo from remote output.
6221 (tramp-set-connection-property proc "check-remote-echo" nil)
6222 (tramp-message proc 5 "echo-mark found")
6223 (forward-line)
6224 (delete-region begin (point))
6225 (goto-char (point-min)))))
674da028 6226
70c11b0b
MA
6227 (when (not (tramp-get-connection-property proc "check-remote-echo" nil))
6228 ;; No echo to be handled, now we can look for the regexp.
674da028 6229 (goto-char (point-min))
00d6fd04 6230 (re-search-forward regexp nil t))))
d2a2c17f 6231
fb7933a3
KG
6232(defun tramp-wait-for-regexp (proc timeout regexp)
6233 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6234Expects the output of PROC to be sent to the current buffer. Returns
6235the string that matched, or nil. Waits indefinitely if TIMEOUT is
6236nil."
00d6fd04
MA
6237 (with-current-buffer (process-buffer proc)
6238 (let ((found (tramp-check-for-regexp proc regexp))
6239 (start-time (current-time)))
6240 (cond (timeout
6241 ;; Work around a bug in XEmacs 21, where the timeout
6242 ;; expires faster than it should. This degenerates
6243 ;; to polling for buggy XEmacsen, but oh, well.
6244 (while (and (not found)
6245 (< (tramp-time-diff (current-time) start-time)
6246 timeout))
6247 (with-timeout (timeout)
6248 (while (not found)
6249 (tramp-accept-process-output proc 1)
6250 (unless (memq (process-status proc) '(run open))
6251 (tramp-error-with-buffer
6252 nil proc 'file-error "Process has died"))
6253 (setq found (tramp-check-for-regexp proc regexp))))))
6254 (t
6255 (while (not found)
6256 (tramp-accept-process-output proc 1)
6257 (unless (memq (process-status proc) '(run open))
6258 (tramp-error-with-buffer
6259 nil proc 'file-error "Process has died"))
6260 (setq found (tramp-check-for-regexp proc regexp)))))
6261 (tramp-message proc 6 "\n%s" (buffer-string))
fb7933a3 6262 (when (not found)
00d6fd04
MA
6263 (if timeout
6264 (tramp-error
6265 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6266 regexp timeout)
6267 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6268 found)))
fb7933a3 6269
b25a52cc
KG
6270(defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6271 "Wait for shell prompt and barf if none appears.
6272Looks at process PROC to see if a shell prompt appears in TIMEOUT
6273seconds. If not, it produces an error message with the given ERROR-ARGS."
7e780ff1
MA
6274 (unless
6275 (tramp-wait-for-regexp
6276 proc timeout
6277 (format
6278 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
00d6fd04
MA
6279 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6280
7e780ff1
MA
6281;; We don't call `tramp-send-string' in order to hide the password
6282;; from the debug buffer, and because end-of-line handling of the
6283;; string.
6284(defun tramp-enter-password (proc)
00d6fd04
MA
6285 "Prompt for a password and send it to the remote end."
6286 (process-send-string
7e780ff1
MA
6287 proc (concat (tramp-read-passwd proc)
6288 (or (tramp-get-method-parameter
6289 tramp-current-method
6290 'tramp-password-end-of-line)
6291 tramp-default-password-end-of-line))))
00d6fd04
MA
6292
6293(defun tramp-open-connection-setup-interactive-shell (proc vec)
fb7933a3 6294 "Set up an interactive shell.
00d6fd04
MA
6295Mainly sets the prompt and the echo correctly. PROC is the shell
6296process to set up. VEC specifies the connection."
a4aeb9a4 6297 (let ((tramp-end-of-output "$ "))
8950769a
MA
6298 ;; It is useful to set the prompt in the following command because
6299 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6300 ;; about and thus /bin/sh will display a strange prompt. For
6301 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6302 ;; display the current working directory but /bin/sh will display
6303 ;; a dollar sign. The following command line sets $PS1 to a sane
6304 ;; value, and works under Bourne-ish shells as well as csh-like
6305 ;; shells. Daniel Pittman reports that the unusual positioning of
6306 ;; the single quotes makes it work under `rc', too. We also unset
6307 ;; the variable $ENV because that is read by some sh
6308 ;; implementations (eg, bash when called as sh) on startup; this
6309 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6310 ;; is another way to set the prompt in /bin/bash, it must be
6311 ;; discarded as well.
a4aeb9a4
MA
6312 (tramp-send-command
6313 vec
6314 (format
70c11b0b
MA
6315 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6316 (shell-quote-argument tramp-end-of-output)
a4aeb9a4
MA
6317 (tramp-get-method-parameter
6318 (tramp-file-name-method vec) 'tramp-remote-sh))
8950769a
MA
6319 t)
6320
6321 ;; Disable echo.
6322 (tramp-message vec 5 "Setting up remote shell environment")
6323 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6324 ;; Check whether the echo has really been disabled. Some
6325 ;; implementations, like busybox of embedded GNU/Linux, don't
6326 ;; support disabling.
6327 (tramp-send-command vec "echo foo" t)
6328 (with-current-buffer (process-buffer proc)
6329 (goto-char (point-min))
6330 (when (looking-at "echo foo")
6331 (tramp-set-connection-property proc "remote-echo" t)
6332 (tramp-message vec 5 "Remote echo still on. Ok.")
6333 ;; Make sure backspaces and their echo are enabled and no line
6334 ;; width magic interferes with them.
6335 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
e42c6bbc 6336
7e780ff1 6337 (tramp-message vec 5 "Setting shell prompt")
70c11b0b
MA
6338 (tramp-send-command
6339 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
9fa0d3aa
MA
6340 (tramp-send-command vec "PS2=''" t)
6341 (tramp-send-command vec "PS3=''" t)
6342 (tramp-send-command vec "PROMPT_COMMAND=''" t)
e42c6bbc 6343
fb7933a3
KG
6344 ;; Try to set up the coding system correctly.
6345 ;; CCC this can't be the right way to do it. Hm.
00d6fd04 6346 (tramp-message vec 5 "Determining coding system")
7e780ff1 6347 (tramp-send-command vec "echo foo ; echo bar" t)
00d6fd04 6348 (with-current-buffer (process-buffer proc)
fb7933a3
KG
6349 (goto-char (point-min))
6350 (if (featurep 'mule)
00d6fd04
MA
6351 ;; Use MULE to select the right EOL convention for communicating
6352 ;; with the process.
311dd93f 6353 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
00d6fd04
MA
6354 (cons 'undecided 'undecided)))
6355 cs-decode cs-encode)
6356 (when (symbolp cs) (setq cs (cons cs cs)))
6357 (setq cs-decode (car cs))
6358 (setq cs-encode (cdr cs))
6359 (unless cs-decode (setq cs-decode 'undecided))
6360 (unless cs-encode (setq cs-encode 'undecided))
6361 (setq cs-encode (tramp-coding-system-change-eol-conversion
6362 cs-encode 'unix))
6363 (when (search-forward "\r" nil t)
6364 (setq cs-decode (tramp-coding-system-change-eol-conversion
6365 cs-decode 'dos)))
311dd93f 6366 (funcall (symbol-function 'set-buffer-process-coding-system)
70c11b0b
MA
6367 cs-decode cs-encode)
6368 (tramp-message
6369 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
fb7933a3
KG
6370 ;; Look for ^M and do something useful if found.
6371 (when (search-forward "\r" nil t)
00d6fd04
MA
6372 ;; We have found a ^M but cannot frob the process coding system
6373 ;; because we're running on a non-MULE Emacs. Let's try
6374 ;; stty, instead.
7e780ff1
MA
6375 (tramp-send-command vec "stty -onlcr" t))))
6376 (tramp-send-command vec "set +o vi +o emacs" t)
e42c6bbc
MA
6377
6378 ;; Check whether the output of "uname -sr" has been changed. If
6379 ;; yes, this is a strong indication that we must expire all
d8ac123e
MA
6380 ;; connection properties. We start again with
6381 ;; `tramp-maybe-open-connection', it will be catched there.
e42c6bbc
MA
6382 (tramp-message vec 5 "Checking system information")
6383 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6384 (new-uname
6385 (tramp-set-connection-property
6386 vec "uname"
6387 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6388 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
d8ac123e
MA
6389 (with-current-buffer (tramp-get-debug-buffer vec)
6390 ;; Keep the debug buffer
2296b54d
MA
6391 (rename-buffer
6392 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
d8ac123e
MA
6393 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6394 (if (= (point-min) (point-max))
6395 (kill-buffer nil)
6396 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6397 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6398 (tramp-get-buffer vec)
6399 (tramp-message
6400 vec 3
6401 "Connection reset, because remote host changed from `%s' to `%s'"
6402 old-uname new-uname)
6403 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
e42c6bbc
MA
6404
6405 ;; Check whether the remote host suffers from buggy
6406 ;; `send-process-string'. This is known for FreeBSD (see comment in
6407 ;; `send_process', file process.c). I've tested sending 624 bytes
6408 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6409 ;; this host type is detected locally. It cannot handle remote
6410 ;; hosts, though.
00d6fd04
MA
6411 (with-connection-property proc "chunksize"
6412 (cond
6413 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6414 tramp-chunksize)
6415 (t
6416 (tramp-message
6417 vec 5 "Checking remote host type for `send-process-string' bug")
6418 (if (string-match
e42c6bbc 6419 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
00d6fd04 6420 500 0))))
e42c6bbc 6421
00d6fd04
MA
6422 ;; Set remote PATH variable.
6423 (tramp-set-remote-path vec)
e42c6bbc 6424
fb7933a3
KG
6425 ;; Search for a good shell before searching for a command which
6426 ;; checks if a file exists. This is done because Tramp wants to use
6427 ;; "test foo; echo $?" to check if various conditions hold, and
6428 ;; there are buggy /bin/sh implementations which don't execute the
6429 ;; "echo $?" part if the "test" part has an error. In particular,
6430 ;; the Solaris /bin/sh is a problem. I'm betting that all systems
6431 ;; with buggy /bin/sh implementations will have a working bash or
6432 ;; ksh. Whee...
00d6fd04 6433 (tramp-find-shell vec)
e42c6bbc 6434
00d6fd04 6435 ;; Disable unexpected output.
7e780ff1 6436 (tramp-send-command vec "mesg n; biff n" t)
e42c6bbc 6437
00d6fd04
MA
6438 ;; Set the environment.
6439 (tramp-message vec 5 "Setting default environment")
661aaece
MA
6440
6441 ;; On OpenSolaris, there is a bug when HISTFILE is changed in place
6442 ;; <http://bugs.opensolaris.org/view_bug.do?bug_id=6834184>. We
6443 ;; apply the workaround.
6444 (if (string-equal (tramp-get-connection-property vec "uname" "") "SunOS 5.11")
6445 (tramp-send-command vec "unset HISTFILE"))
6446
00d6fd04
MA
6447 (let ((env (copy-sequence tramp-remote-process-environment))
6448 unset item)
6449 (while env
70c11b0b 6450 (setq item (tramp-compat-split-string (car env) "="))
00d6fd04
MA
6451 (if (and (stringp (cadr item)) (not (string-equal (cadr item) "")))
6452 (tramp-send-command
7e780ff1 6453 vec (format "%s=%s; export %s" (car item) (cadr item) (car item)) t)
00d6fd04
MA
6454 (push (car item) unset))
6455 (setq env (cdr env)))
6456 (when unset
fb7933a3 6457 (tramp-send-command
7e780ff1 6458 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
fb7933a3 6459
ac474af1
KG
6460;; CCC: We should either implement a Perl version of base64 encoding
6461;; and decoding. Then we just use that in the last item. The other
6462;; alternative is to use the Perl version of UU encoding. But then
6463;; we need a Lisp version of uuencode.
16674e4f
KG
6464;;
6465;; Old text from documentation of tramp-methods:
6466;; Using a uuencode/uudecode inline method is discouraged, please use one
6467;; of the base64 methods instead since base64 encoding is much more
6468;; reliable and the commands are more standardized between the different
6469;; Unix versions. But if you can't use base64 for some reason, please
6470;; note that the default uudecode command does not work well for some
6471;; Unices, in particular AIX and Irix. For AIX, you might want to use
6472;; the following command for uudecode:
6473;;
6474;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6475;;
6476;; For Irix, no solution is known yet.
6477
00d6fd04
MA
6478(defconst tramp-local-coding-commands
6479 '((b64 base64-encode-region base64-decode-region)
6480 (uu tramp-uuencode-region uudecode-decode-region)
6481 (pack
6482 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6483 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6484 "List of local coding commands for inline transfer.
16674e4f
KG
6485Each item is a list that looks like this:
6486
00d6fd04 6487\(FORMAT ENCODING DECODING)
ac474af1 6488
00d6fd04
MA
6489FORMAT is symbol describing the encoding/decoding format. It can be
6490`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
ac474af1 6491
00d6fd04
MA
6492ENCODING and DECODING can be strings, giving commands, or symbols,
6493giving functions. If they are strings, then they can contain
16674e4f
KG
6494the \"%s\" format specifier. If that specifier is present, the input
6495filename will be put into the command line at that spot. If the
6496specifier is not present, the input should be read from standard
6497input.
ac474af1 6498
16674e4f
KG
6499If they are functions, they will be called with two arguments, start
6500and end of region, and are expected to replace the region contents
6501with the encoded or decoded results, respectively.")
ac474af1 6502
00d6fd04 6503(defconst tramp-remote-coding-commands
3dc847a3
MA
6504 '((b64 "base64" "base64 -d")
6505 (b64 "mimencode -b" "mimencode -u -b")
00d6fd04
MA
6506 (b64 "mmencode -b" "mmencode -u -b")
6507 (b64 "recode data..base64" "recode base64..data")
6508 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6509 (b64 tramp-perl-encode tramp-perl-decode)
6510 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6511 (uu "uuencode xxx" "uudecode -o -")
6512 (uu "uuencode xxx" "uudecode -p")
6513 (uu "uuencode xxx" tramp-uudecode)
6514 (pack
6515 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6516 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6517 "List of remote coding commands for inline transfer.
6518Each item is a list that looks like this:
6519
6520\(FORMAT ENCODING DECODING)
6521
6522FORMAT is symbol describing the encoding/decoding format. It can be
6523`b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6524
6525ENCODING and DECODING can be strings, giving commands, or symbols,
6526giving variables. If they are strings, then they can contain
6527the \"%s\" format specifier. If that specifier is present, the input
6528filename will be put into the command line at that spot. If the
6529specifier is not present, the input should be read from standard
6530input.
6531
6532If they are variables, this variable is a string containing a Perl
6533implementation for this functionality. This Perl program will be transferred
6534to the remote host, and it is avalible as shell function with the same name.")
6535
6536(defun tramp-find-inline-encoding (vec)
ac474af1 6537 "Find an inline transfer encoding that works.
00d6fd04
MA
6538Goes through the list `tramp-local-coding-commands' and
6539`tramp-remote-coding-commands'."
6540 (save-excursion
6541 (let ((local-commands tramp-local-coding-commands)
6542 (magic "xyzzy")
6543 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6544 (while (and local-commands (not found))
6545 (setq litem (pop local-commands))
6546 (catch 'wont-work-local
6547 (let ((format (nth 0 litem))
6548 (remote-commands tramp-remote-coding-commands))
6549 (setq loc-enc (nth 1 litem))
6550 (setq loc-dec (nth 2 litem))
6551 ;; If the local encoder or decoder is a string, the
6552 ;; corresponding command has to work locally.
6553 (if (not (stringp loc-enc))
6554 (tramp-message
6555 vec 5 "Checking local encoding function `%s'" loc-enc)
6556 (tramp-message
6557 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6558 (unless (zerop (tramp-call-local-coding-command
6559 loc-enc nil nil))
6560 (throw 'wont-work-local nil)))
6561 (if (not (stringp loc-dec))
6562 (tramp-message
6563 vec 5 "Checking local decoding function `%s'" loc-dec)
6564 (tramp-message
6565 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
6566 (unless (zerop (tramp-call-local-coding-command
6567 loc-dec nil nil))
6568 (throw 'wont-work-local nil)))
6569 ;; Search for remote coding commands with the same format
6570 (while (and remote-commands (not found))
6571 (setq ritem (pop remote-commands))
6572 (catch 'wont-work-remote
6573 (when (equal format (nth 0 ritem))
6574 (setq rem-enc (nth 1 ritem))
6575 (setq rem-dec (nth 2 ritem))
6576 ;; Check if remote encoding and decoding commands can be
6577 ;; called remotely with null input and output. This makes
6578 ;; sure there are no syntax errors and the command is really
6579 ;; found. Note that we do not redirect stdout to /dev/null,
6580 ;; for two reasons: when checking the decoding command, we
6581 ;; actually check the output it gives. And also, when
6582 ;; redirecting "mimencode" output to /dev/null, then as root
6583 ;; it might change the permissions of /dev/null!
6584 (when (not (stringp rem-enc))
6585 (let ((name (symbol-name rem-enc)))
6586 (while (string-match (regexp-quote "-") name)
6587 (setq name (replace-match "_" nil t name)))
6588 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
6589 (setq rem-enc name)))
6590 (tramp-message
6591 vec 5
6592 "Checking remote encoding command `%s' for sanity" rem-enc)
6593 (unless (zerop (tramp-send-command-and-check
6594 vec (format "%s </dev/null" rem-enc) t))
6595 (throw 'wont-work-remote nil))
6596
6597 (when (not (stringp rem-dec))
6598 (let ((name (symbol-name rem-dec)))
6599 (while (string-match (regexp-quote "-") name)
6600 (setq name (replace-match "_" nil t name)))
6601 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
6602 (setq rem-dec name)))
6603 (tramp-message
6604 vec 5
6605 "Checking remote decoding command `%s' for sanity" rem-dec)
6606 (unless (zerop (tramp-send-command-and-check
6607 vec
6608 (format "echo %s | %s | %s"
6609 magic rem-enc rem-dec) t))
6610 (throw 'wont-work-remote nil))
6611
6612 (with-current-buffer (tramp-get-buffer vec)
6613 (goto-char (point-min))
6614 (unless (looking-at (regexp-quote magic))
6615 (throw 'wont-work-remote nil)))
6616
6617 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
6618 (setq rem-enc (nth 1 ritem))
6619 (setq rem-dec (nth 2 ritem))
6620 (setq found t)))))))
6621
1d7e9a01 6622 ;; Did we find something?
00d6fd04 6623 (unless found
1d7e9a01 6624 (tramp-message vec 2 "Couldn't find an inline transfer encoding"))
00d6fd04
MA
6625
6626 ;; Set connection properties.
6627 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
6628 (tramp-set-connection-property vec "local-encoding" loc-enc)
6629 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
6630 (tramp-set-connection-property vec "local-decoding" loc-dec)
6631 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
6632 (tramp-set-connection-property vec "remote-encoding" rem-enc)
6633 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
6634 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
16674e4f
KG
6635
6636(defun tramp-call-local-coding-command (cmd input output)
6637 "Call the local encoding or decoding command.
6638If CMD contains \"%s\", provide input file INPUT there in command.
6639Otherwise, INPUT is passed via standard input.
6640INPUT can also be nil which means `/dev/null'.
6641OUTPUT can be a string (which specifies a filename), or t (which
6642means standard output and thus the current buffer), or nil (which
6643means discard it)."
a4aeb9a4
MA
6644 (tramp-local-call-process
6645 tramp-encoding-shell
6646 (when (and input (not (string-match "%s" cmd))) input)
6647 (if (eq output t) t nil)
6648 nil
6649 tramp-encoding-command-switch
6650 (concat
6651 (if (string-match "%s" cmd) (format cmd input) cmd)
6652 (if (stringp output) (concat "> " output) ""))))
00d6fd04
MA
6653
6654(defun tramp-compute-multi-hops (vec)
6655 "Expands VEC according to `tramp-default-proxies-alist'.
6656Gateway hops are already opened."
6657 (let ((target-alist `(,vec))
6658 (choices tramp-default-proxies-alist)
6659 item proxy)
6660
6661 ;; Look for proxy hosts to be passed.
6662 (while choices
6663 (setq item (pop choices)
70c11b0b 6664 proxy (eval (nth 2 item)))
00d6fd04
MA
6665 (when (and
6666 ;; host
70c11b0b 6667 (string-match (or (eval (nth 0 item)) "")
00d6fd04
MA
6668 (or (tramp-file-name-host (car target-alist)) ""))
6669 ;; user
70c11b0b 6670 (string-match (or (eval (nth 1 item)) "")
00d6fd04
MA
6671 (or (tramp-file-name-user (car target-alist)) "")))
6672 (if (null proxy)
6673 ;; No more hops needed.
6674 (setq choices nil)
6675 ;; Replace placeholders.
6676 (setq proxy
6677 (format-spec
6678 proxy
6679 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
6680 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
6681 (with-parsed-tramp-file-name proxy l
6682 ;; Add the hop.
6683 (add-to-list 'target-alist l)
6684 ;; Start next search.
6685 (setq choices tramp-default-proxies-alist)))))
6686
6687 ;; Handle gateways.
8a4438b6
MA
6688 (when (and (boundp 'tramp-gw-tunnel-method)
6689 (string-match (format
6690 "^\\(%s\\|%s\\)$"
6691 (symbol-value 'tramp-gw-tunnel-method)
6692 (symbol-value 'tramp-gw-socks-method))
6693 (tramp-file-name-method (car target-alist))))
00d6fd04
MA
6694 (let ((gw (pop target-alist))
6695 (hop (pop target-alist)))
6696 ;; Is the method prepared for gateways?
6697 (unless (tramp-get-method-parameter
6698 (tramp-file-name-method hop) 'tramp-default-port)
6699 (tramp-error
6700 vec 'file-error
6701 "Method `%s' is not supported for gateway access."
6702 (tramp-file-name-method hop)))
6703 ;; Add default port if needed.
6704 (unless
6705 (string-match
6706 tramp-host-with-port-regexp (tramp-file-name-host hop))
6707 (aset hop 2
6708 (concat
6709 (tramp-file-name-host hop) tramp-prefix-port-format
6710 (number-to-string
6711 (tramp-get-method-parameter
6712 (tramp-file-name-method hop) 'tramp-default-port)))))
6713 ;; Open the gateway connection.
6714 (add-to-list
6715 'target-alist
6716 (vector
6717 (tramp-file-name-method hop) (tramp-file-name-user hop)
9e6ab520 6718 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
00d6fd04
MA
6719 ;; For the password prompt, we need the correct values.
6720 ;; Therefore, we must remember the gateway vector. But we
6721 ;; cannot do it as connection property, because it shouldn't
6722 ;; be persistent. And we have no started process yet either.
6723 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
6724
6725 ;; Foreign and out-of-band methods are not supported for multi-hops.
6726 (when (cdr target-alist)
6727 (setq choices target-alist)
6728 (while choices
6729 (setq item (pop choices))
6730 (when
6731 (or
6732 (not
6733 (tramp-get-method-parameter
6734 (tramp-file-name-method item) 'tramp-login-program))
6735 (tramp-get-method-parameter
6736 (tramp-file-name-method item) 'tramp-copy-program))
6737 (tramp-error
6738 vec 'file-error
6739 "Method `%s' is not supported for multi-hops."
6740 (tramp-file-name-method item)))))
6741
2991e49f
MA
6742 ;; In case the host name is not used for the remote shell
6743 ;; command, the user could be misguided by applying a random
6744 ;; hostname.
6745 (let* ((v (car target-alist))
6746 (method (tramp-file-name-method v))
6747 (host (tramp-file-name-host v)))
6748 (unless
6749 (or
6750 ;; There are multi-hops.
6751 (cdr target-alist)
6752 ;; The host name is used for the remote shell command.
6753 (member
6754 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
6755 ;; The host is local. We cannot use `tramp-local-host-p'
6756 ;; here, because it opens a connection as well.
b96e6899 6757 (string-match tramp-local-host-regexp host))
2991e49f 6758 (tramp-error
42bc9b6d
MA
6759 v 'file-error
6760 "Host `%s' looks like a remote host, `%s' can only use the local host"
6761 host method)))
2991e49f 6762
00d6fd04
MA
6763 ;; Result.
6764 target-alist))
6765
6766(defun tramp-maybe-open-connection (vec)
6767 "Maybe open a connection VEC.
fb7933a3
KG
6768Does not do anything if a connection is already open, but re-opens the
6769connection if a previous connection has died for some reason."
d8ac123e
MA
6770 (catch 'uname-changed
6771 (let ((p (tramp-get-connection-process vec))
6772 (process-environment (copy-sequence process-environment)))
6773
6774 ;; If too much time has passed since last command was sent, look
6775 ;; whether process is still alive. If it isn't, kill it. When
6776 ;; using ssh, it can sometimes happen that the remote end has
6777 ;; hung up but the local ssh client doesn't recognize this until
6778 ;; it tries to send some data to the remote end. So that's why
6779 ;; we try to send a command from time to time, then look again
6780 ;; whether the process is really alive.
6781 (condition-case nil
6782 (when (and (> (tramp-time-diff
6783 (current-time)
6784 (tramp-get-connection-property
6785 p "last-cmd-time" '(0 0 0)))
6786 60)
6787 p (processp p) (memq (process-status p) '(run open)))
6788 (tramp-send-command vec "echo are you awake" t t)
6789 (unless (and (memq (process-status p) '(run open))
6790 (tramp-wait-for-output p 10))
6791 ;; The error will be catched locally.
6792 (tramp-error vec 'file-error "Awake did fail")))
6793 (file-error
6794 (tramp-flush-connection-property vec)
6795 (tramp-flush-connection-property p)
6796 (delete-process p)
6797 (setq p nil)))
6798
6799 ;; New connection must be opened.
6800 (unless (and p (processp p) (memq (process-status p) '(run open)))
6801
6802 ;; We call `tramp-get-buffer' in order to get a debug buffer for
6803 ;; messages from the beginning.
6804 (tramp-get-buffer vec)
6805 (if (zerop (length (tramp-file-name-user vec)))
6806 (tramp-message
6807 vec 3 "Opening connection for %s using %s..."
6808 (tramp-file-name-host vec)
6809 (tramp-file-name-method vec))
00d6fd04 6810 (tramp-message
d8ac123e
MA
6811 vec 3 "Opening connection for %s@%s using %s..."
6812 (tramp-file-name-user vec)
00d6fd04 6813 (tramp-file-name-host vec)
d8ac123e
MA
6814 (tramp-file-name-method vec)))
6815
6816 ;; Start new process.
6817 (when (and p (processp p))
6818 (delete-process p))
6819 (setenv "TERM" tramp-terminal-type)
6820 (setenv "LC_ALL" "C")
6821 (setenv "PROMPT_COMMAND")
6822 (setenv "PS1" "$ ")
6823 (let* ((target-alist (tramp-compute-multi-hops vec))
6824 (process-connection-type tramp-process-connection-type)
6825 (process-adaptive-read-buffering nil)
6826 (coding-system-for-read nil)
6827 ;; This must be done in order to avoid our file name handler.
6828 (p (let ((default-directory
6829 (tramp-compat-temporary-file-directory)))
6830 (start-process
6831 (or (tramp-get-connection-property vec "process-name" nil)
6832 (tramp-buffer-name vec))
6833 (tramp-get-connection-buffer vec)
70c11b0b 6834 tramp-encoding-shell))))
00d6fd04 6835
d8ac123e
MA
6836 (tramp-message
6837 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
6838
6839 ;; Check whether process is alive.
d8ac123e
MA
6840 (tramp-set-process-query-on-exit-flag p nil)
6841 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
6842 (tramp-barf-if-no-shell-prompt
6843 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
6844
6845 ;; Now do all the connections as specified.
6846 (while target-alist
6847 (let* ((hop (car target-alist))
6848 (l-method (tramp-file-name-method hop))
6849 (l-user (tramp-file-name-user hop))
6850 (l-host (tramp-file-name-host hop))
6851 (l-port nil)
6852 (login-program
6853 (tramp-get-method-parameter l-method 'tramp-login-program))
6854 (login-args
6855 (tramp-get-method-parameter l-method 'tramp-login-args))
6856 (gw-args
6857 (tramp-get-method-parameter l-method 'tramp-gw-args))
6858 (gw (tramp-get-file-property hop "" "gateway" nil))
6859 (g-method (and gw (tramp-file-name-method gw)))
6860 (g-user (and gw (tramp-file-name-user gw)))
6861 (g-host (and gw (tramp-file-name-host gw)))
6862 (command login-program)
6863 ;; We don't create the temporary file. In fact, it
6864 ;; is just a prefix for the ControlPath option of
6865 ;; ssh; the real temporary file has another name, and
6866 ;; it is created and protected by ssh. It is also
6867 ;; removed by ssh, when the connection is closed.
6868 (tmpfile
6869 (tramp-set-connection-property
6870 p "temp-file"
6871 (make-temp-name
6872 (expand-file-name
6873 tramp-temp-name-prefix
6874 (tramp-compat-temporary-file-directory)))))
6875 spec)
6876
6877 ;; Add gateway arguments if necessary.
6878 (when (and gw gw-args)
6879 (setq login-args (append login-args gw-args)))
6880
6881 ;; Check for port number. Until now, there's no need
6882 ;; for handling like method, user, host.
6883 (when (string-match tramp-host-with-port-regexp l-host)
6884 (setq l-port (match-string 2 l-host)
6885 l-host (match-string 1 l-host)))
6886
6887 ;; Set variables for computing the prompt for reading
2296b54d 6888 ;; password. They can also be derived from a gateway.
d8ac123e
MA
6889 (setq tramp-current-method (or g-method l-method)
6890 tramp-current-user (or g-user l-user)
6891 tramp-current-host (or g-host l-host))
6892
6893 ;; Replace login-args place holders.
6894 (setq
6895 l-host (or l-host "")
6896 l-user (or l-user "")
6897 l-port (or l-port "")
6898 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
6899 (?t . ,tmpfile))
6900 command
6901 (concat
6902 command " "
6903 (mapconcat
aa485f7c
MA
6904 (lambda (x)
6905 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
6906 (unless (member "" x) (mapconcat 'identity x " ")))
d8ac123e 6907 login-args " ")
d8ac123e
MA
6908 ;; Local shell could be a Windows COMSPEC. It doesn't
6909 ;; know the ";" syntax, but we must exit always for
70c11b0b
MA
6910 ;; `start-file-process'. "exec" does not work either.
6911 " && exit || exit"))
d8ac123e
MA
6912
6913 ;; Send the command.
6914 (tramp-message vec 3 "Sending command `%s'" command)
6915 (tramp-send-command vec command t t)
6916 (tramp-process-actions p vec tramp-actions-before-shell 60)
6917 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
6918 ;; Next hop.
6919 (setq target-alist (cdr target-alist)))
6920
6921 ;; Make initial shell settings.
6922 (tramp-open-connection-setup-interactive-shell p vec))))))
00d6fd04
MA
6923
6924(defun tramp-send-command (vec command &optional neveropen nooutput)
6925 "Send the COMMAND to connection VEC.
6926Erases temporary buffer before sending the command. If optional
6927arg NEVEROPEN is non-nil, never try to open the connection. This
6928is meant to be used from `tramp-maybe-open-connection' only. The
6929function waits for output unless NOOUTPUT is set."
6930 (unless neveropen (tramp-maybe-open-connection vec))
6931 (let ((p (tramp-get-connection-process vec)))
8950769a 6932 (when (tramp-get-connection-property p "remote-echo" nil)
00d6fd04
MA
6933 ;; We mark the command string that it can be erased in the output buffer.
6934 (tramp-set-connection-property p "check-remote-echo" t)
6935 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
6936 (tramp-message vec 6 "%s" command)
6937 (tramp-send-string vec command)
6938 (unless nooutput (tramp-wait-for-output p))))
6939
00d6fd04 6940(defun tramp-wait-for-output (proc &optional timeout)
fb7933a3 6941 "Wait for output from remote rsh command."
00d6fd04 6942 (with-current-buffer (process-buffer proc)
bede3e9f
MA
6943 (let* (;; Initially, `tramp-end-of-output' is "$ ". There might
6944 ;; be leading escape sequences, which must be ignored.
6945 (regexp (format "[^$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
6946 ;; Sometimes, the commands do not return a newline but a
6947 ;; null byte before the shell prompt, for example "git
6948 ;; ls-files -c -z ...".
6949 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
6950 (found (tramp-wait-for-regexp proc timeout regexp1)))
00d6fd04
MA
6951 (if found
6952 (let (buffer-read-only)
6953 (goto-char (point-max))
0664ff72 6954 (re-search-backward regexp nil t)
00d6fd04
MA
6955 (delete-region (point) (point-max)))
6956 (if timeout
6957 (tramp-error
6958 proc 'file-error
6959 "[[Remote prompt `%s' not found in %d secs]]"
6960 tramp-end-of-output timeout)
6961 (tramp-error
6962 proc 'file-error
6963 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
6964 ;; Return value is whether end-of-output sentinel was found.
6965 found)))
fb7933a3 6966
00d6fd04 6967(defun tramp-send-command-and-check (vec command &optional subshell)
fb7933a3 6968 "Run COMMAND and check its exit status.
fb7933a3
KG
6969Sends `echo $?' along with the COMMAND for checking the exit status. If
6970COMMAND is nil, just sends `echo $?'. Returns the exit status found.
6971
6972If the optional argument SUBSHELL is non-nil, the command is executed in
6973a subshell, ie surrounded by parentheses."
00d6fd04
MA
6974 (tramp-send-command
6975 vec
6976 (concat (if subshell "( " "")
6977 command
6978 (if command " 2>/dev/null; " "")
6979 "echo tramp_exit_status $?"
6980 (if subshell " )" " ")))
6981 (with-current-buffer (tramp-get-connection-buffer vec)
6982 (goto-char (point-max))
6983 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
6984 (tramp-error
6985 vec 'file-error "Couldn't find exit status of `%s'" command))
6986 (skip-chars-forward "^ ")
6987 (prog1
6988 (read (current-buffer))
6989 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
6990
6991(defun tramp-barf-unless-okay (vec command fmt &rest args)
fb7933a3
KG
6992 "Run COMMAND, check exit status, throw error if exit status not okay.
6993Similar to `tramp-send-command-and-check' but accepts two more arguments
6994FMT and ARGS which are passed to `error'."
00d6fd04
MA
6995 (unless (zerop (tramp-send-command-and-check vec command))
6996 (apply 'tramp-error vec 'file-error fmt args)))
6997
6998(defun tramp-send-command-and-read (vec command)
6999 "Run COMMAND and return the output, which must be a Lisp expression.
7000In case there is no valid Lisp expression, it raises an error"
7001 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7002 (with-current-buffer (tramp-get-connection-buffer vec)
7003 ;; Read the expression.
7004 (goto-char (point-min))
7005 (condition-case nil
7006 (prog1 (read (current-buffer))
7007 ;; Error handling.
9e6ab520 7008 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
9ce8462a 7009 (error nil)))
00d6fd04
MA
7010 (error (tramp-error
7011 vec 'file-error
7012 "`%s' does not return a valid Lisp expression: `%s'"
7013 command (buffer-string))))))
fb7933a3 7014
7432277c
KG
7015;; It seems that Tru64 Unix does not like it if long strings are sent
7016;; to it in one go. (This happens when sending the Perl
7017;; `file-attributes' implementation, for instance.) Therefore, we
27e813fe 7018;; have this function which sends the string in chunks.
00d6fd04
MA
7019(defun tramp-send-string (vec string)
7020 "Send the STRING via connection VEC.
7432277c
KG
7021
7022The STRING is expected to use Unix line-endings, but the lines sent to
7023the remote host use line-endings as defined in the variable
00d6fd04
MA
7024`tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7025 (let* ((p (tramp-get-connection-process vec))
7026 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7027 (unless p
7028 (tramp-error
7029 vec 'file-error "Can't send string to remote host -- not logged in"))
7030 (tramp-set-connection-property p "last-cmd-time" (current-time))
7031 (tramp-message vec 10 "%s" string)
7032 (with-current-buffer (tramp-get-connection-buffer vec)
7033 ;; Clean up the buffer. We cannot call `erase-buffer' because
7034 ;; narrowing might be in effect.
7035 (let (buffer-read-only) (delete-region (point-min) (point-max)))
27e813fe 7036 ;; Replace "\n" by `tramp-rsh-end-of-line'.
00d6fd04
MA
7037 (setq string
7038 (mapconcat 'identity
70c11b0b 7039 (tramp-compat-split-string string "\n")
00d6fd04
MA
7040 tramp-rsh-end-of-line))
7041 (unless (or (string= string "")
7042 (string-equal (substring string -1) tramp-rsh-end-of-line))
7043 (setq string (concat string tramp-rsh-end-of-line)))
27e813fe 7044 ;; Send the string.
00d6fd04
MA
7045 (if (and chunksize (not (zerop chunksize)))
7046 (let ((pos 0)
7047 (end (length string)))
7048 (while (< pos end)
7049 (tramp-message
7050 vec 10 "Sending chunk from %s to %s"
7051 pos (min (+ pos chunksize) end))
7052 (process-send-string
7053 p (substring string pos (min (+ pos chunksize) end)))
7054 (setq pos (+ pos chunksize))))
7055 (process-send-string p string)))))
fb7933a3
KG
7056
7057(defun tramp-mode-string-to-int (mode-string)
7058 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
f3c071dd
MA
7059 (let* (case-fold-search
7060 (mode-chars (string-to-vector mode-string))
fb7933a3
KG
7061 (owner-read (aref mode-chars 1))
7062 (owner-write (aref mode-chars 2))
7063 (owner-execute-or-setid (aref mode-chars 3))
7064 (group-read (aref mode-chars 4))
7065 (group-write (aref mode-chars 5))
7066 (group-execute-or-setid (aref mode-chars 6))
7067 (other-read (aref mode-chars 7))
7068 (other-write (aref mode-chars 8))
7069 (other-execute-or-sticky (aref mode-chars 9)))
7070 (save-match-data
7071 (logior
f3c071dd
MA
7072 (cond
7073 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7074 ((char-equal owner-read ?-) 0)
7075 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7076 (cond
7077 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7078 ((char-equal owner-write ?-) 0)
7079 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7080 (cond
7081 ((char-equal owner-execute-or-setid ?x)
7082 (tramp-octal-to-decimal "00100"))
7083 ((char-equal owner-execute-or-setid ?S)
7084 (tramp-octal-to-decimal "04000"))
7085 ((char-equal owner-execute-or-setid ?s)
7086 (tramp-octal-to-decimal "04100"))
7087 ((char-equal owner-execute-or-setid ?-) 0)
7088 (t (error "Fourth char `%c' must be one of `xsS-'"
7089 owner-execute-or-setid)))
7090 (cond
7091 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7092 ((char-equal group-read ?-) 0)
7093 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7094 (cond
7095 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7096 ((char-equal group-write ?-) 0)
7097 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7098 (cond
7099 ((char-equal group-execute-or-setid ?x)
7100 (tramp-octal-to-decimal "00010"))
7101 ((char-equal group-execute-or-setid ?S)
7102 (tramp-octal-to-decimal "02000"))
7103 ((char-equal group-execute-or-setid ?s)
7104 (tramp-octal-to-decimal "02010"))
7105 ((char-equal group-execute-or-setid ?-) 0)
7106 (t (error "Seventh char `%c' must be one of `xsS-'"
7107 group-execute-or-setid)))
7108 (cond
7109 ((char-equal other-read ?r)
7110 (tramp-octal-to-decimal "00004"))
7111 ((char-equal other-read ?-) 0)
7112 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7113 (cond
7114 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7115 ((char-equal other-write ?-) 0)
fb7933a3 7116 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
f3c071dd
MA
7117 (cond
7118 ((char-equal other-execute-or-sticky ?x)
7119 (tramp-octal-to-decimal "00001"))
7120 ((char-equal other-execute-or-sticky ?T)
7121 (tramp-octal-to-decimal "01000"))
7122 ((char-equal other-execute-or-sticky ?t)
7123 (tramp-octal-to-decimal "01001"))
7124 ((char-equal other-execute-or-sticky ?-) 0)
7125 (t (error "Tenth char `%c' must be one of `xtT-'"
7126 other-execute-or-sticky)))))))
fb7933a3 7127
00d6fd04
MA
7128(defun tramp-convert-file-attributes (vec attr)
7129 "Convert file-attributes ATTR generated by perl script, stat or ls.
c82c5727
LH
7130Convert file mode bits to string and set virtual device number.
7131Return ATTR."
680db9ac
MA
7132 (when attr
7133 ;; Convert last access time.
7134 (unless (listp (nth 4 attr))
7135 (setcar (nthcdr 4 attr)
7136 (list (floor (nth 4 attr) 65536)
7137 (floor (mod (nth 4 attr) 65536)))))
7138 ;; Convert last modification time.
7139 (unless (listp (nth 5 attr))
7140 (setcar (nthcdr 5 attr)
7141 (list (floor (nth 5 attr) 65536)
7142 (floor (mod (nth 5 attr) 65536)))))
7143 ;; Convert last status change time.
7144 (unless (listp (nth 6 attr))
7145 (setcar (nthcdr 6 attr)
7146 (list (floor (nth 6 attr) 65536)
7147 (floor (mod (nth 6 attr) 65536)))))
7148 ;; Convert file size.
7149 (when (< (nth 7 attr) 0)
7150 (setcar (nthcdr 7 attr) -1))
7151 (when (and (floatp (nth 7 attr))
7152 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7153 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7154 ;; Convert file mode bits to string.
7155 (unless (stringp (nth 8 attr))
7156 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7157 (when (stringp (car attr))
7158 (aset (nth 8 attr) 0 ?l)))
7159 ;; Convert directory indication bit.
7160 (when (string-match "^d" (nth 8 attr))
7161 (setcar attr t))
7162 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7163 (when (consp (car attr))
7164 (if (and (stringp (caar attr))
7165 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7166 (setcar attr (match-string 1 (caar attr)))
7167 (setcar attr nil)))
7168 ;; Set file's gid change bit.
7169 (setcar (nthcdr 9 attr)
7170 (if (numberp (nth 3 attr))
7171 (not (= (nth 3 attr)
7172 (tramp-get-remote-gid vec 'integer)))
7173 (not (string-equal
7174 (nth 3 attr)
7175 (tramp-get-remote-gid vec 'string)))))
7176 ;; Convert inode.
7177 (unless (listp (nth 10 attr))
7178 (setcar (nthcdr 10 attr)
7179 (condition-case nil
7180 (cons (floor (nth 10 attr) 65536)
7181 (floor (mod (nth 10 attr) 65536)))
7182 ;; Inodes can be incredible huge. We must hide this.
7183 (error (tramp-get-inode vec)))))
7184 ;; Set virtual device number.
7185 (setcar (nthcdr 11 attr)
7186 (tramp-get-device vec))
7187 attr))
c82c5727 7188
ce3f516f 7189(defun tramp-get-inode (vec)
00d6fd04
MA
7190 "Returns the virtual inode number.
7191If it doesn't exist, generate a new one."
ce3f516f
MA
7192 (let ((string (tramp-make-tramp-file-name
7193 (tramp-file-name-method vec)
7194 (tramp-file-name-user vec)
7195 (tramp-file-name-host vec)
7196 "")))
00d6fd04
MA
7197 (unless (assoc string tramp-inodes)
7198 (add-to-list 'tramp-inodes
7199 (list string (length tramp-inodes))))
7200 (nth 1 (assoc string tramp-inodes))))
7201
7202(defun tramp-get-device (vec)
c82c5727
LH
7203 "Returns the virtual device number.
7204If it doesn't exist, generate a new one."
00d6fd04
MA
7205 (let ((string (tramp-make-tramp-file-name
7206 (tramp-file-name-method vec)
7207 (tramp-file-name-user vec)
7208 (tramp-file-name-host vec)
7209 "")))
c82c5727
LH
7210 (unless (assoc string tramp-devices)
7211 (add-to-list 'tramp-devices
7212 (list string (length tramp-devices))))
b946a456 7213 (cons -1 (nth 1 (assoc string tramp-devices)))))
fb7933a3
KG
7214
7215(defun tramp-file-mode-from-int (mode)
7216 "Turn an integer representing a file mode into an ls(1)-like string."
7217 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7218 (user (logand (lsh mode -6) 7))
7219 (group (logand (lsh mode -3) 7))
7220 (other (logand (lsh mode -0) 7))
7221 (suid (> (logand (lsh mode -9) 4) 0))
7222 (sgid (> (logand (lsh mode -9) 2) 0))
7223 (sticky (> (logand (lsh mode -9) 1) 0)))
7224 (setq user (tramp-file-mode-permissions user suid "s"))
7225 (setq group (tramp-file-mode-permissions group sgid "s"))
7226 (setq other (tramp-file-mode-permissions other sticky "t"))
7227 (concat type user group other)))
7228
fb7933a3
KG
7229(defun tramp-file-mode-permissions (perm suid suid-text)
7230 "Convert a permission bitset into a string.
7231This is used internally by `tramp-file-mode-from-int'."
7232 (let ((r (> (logand perm 4) 0))
7233 (w (> (logand perm 2) 0))
7234 (x (> (logand perm 1) 0)))
7235 (concat (or (and r "r") "-")
7236 (or (and w "w") "-")
7237 (or (and suid x suid-text) ; suid, execute
7238 (and suid (upcase suid-text)) ; suid, !execute
7239 (and x "x") "-")))) ; !suid
7240
fb7933a3
KG
7241(defun tramp-decimal-to-octal (i)
7242 "Return a string consisting of the octal digits of I.
7243Not actually used. Use `(format \"%o\" i)' instead?"
7244 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7245 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7246 ((zerop i) "0")
7247 (t (concat (tramp-decimal-to-octal (/ i 8))
7248 (number-to-string (% i 8))))))
7249
fb7933a3
KG
7250;; Kudos to Gerd Moellmann for this suggestion.
7251(defun tramp-octal-to-decimal (ostr)
7252 "Given a string of octal digits, return a decimal number."
7253 (let ((x (or ostr "")))
7254 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7255 (unless (string-match "\\`[0-7]*\\'" x)
7256 (error "Non-octal junk in string `%s'" x))
7257 (string-to-number ostr 8)))
7258
7259(defun tramp-shell-case-fold (string)
7260 "Converts STRING to shell glob pattern which ignores case."
7261 (mapconcat
7262 (lambda (c)
7263 (if (equal (downcase c) (upcase c))
7264 (vector c)
7265 (format "[%c%c]" (downcase c) (upcase c))))
7266 string
7267 ""))
7268
7269
bf247b6e 7270;; ------------------------------------------------------------
a4aeb9a4 7271;; -- Tramp file names --
bf247b6e 7272;; ------------------------------------------------------------
fb7933a3
KG
7273;; Conversion functions between external representation and
7274;; internal data structure. Convenience functions for internal
7275;; data structure.
7276
00d6fd04
MA
7277(defun tramp-file-name-p (vec)
7278 "Check whether VEC is a Tramp object."
7279 (and (vectorp vec) (= 4 (length vec))))
7280
7281(defun tramp-file-name-method (vec)
7282 "Return method component of VEC."
7283 (and (tramp-file-name-p vec) (aref vec 0)))
7284
7285(defun tramp-file-name-user (vec)
7286 "Return user component of VEC."
7287 (and (tramp-file-name-p vec) (aref vec 1)))
7288
7289(defun tramp-file-name-host (vec)
7290 "Return host component of VEC."
7291 (and (tramp-file-name-p vec) (aref vec 2)))
7292
7293(defun tramp-file-name-localname (vec)
7294 "Return localname component of VEC."
7295 (and (tramp-file-name-p vec) (aref vec 3)))
7296
dea31ca6 7297;; The user part of a Tramp file name vector can be of kind
b96e6899 7298;; "user%domain". Sometimes, we must extract these parts.
dea31ca6
MA
7299(defun tramp-file-name-real-user (vec)
7300 "Return the user name of VEC without domain."
a17632c1
MA
7301 (save-match-data
7302 (let ((user (tramp-file-name-user vec)))
7303 (if (and (stringp user)
7304 (string-match tramp-user-with-domain-regexp user))
7305 (match-string 1 user)
7306 user))))
dea31ca6
MA
7307
7308(defun tramp-file-name-domain (vec)
7309 "Return the domain name of VEC."
a17632c1
MA
7310 (save-match-data
7311 (let ((user (tramp-file-name-user vec)))
7312 (and (stringp user)
7313 (string-match tramp-user-with-domain-regexp user)
7314 (match-string 2 user)))))
dea31ca6 7315
00d6fd04
MA
7316;; The host part of a Tramp file name vector can be of kind
7317;; "host#port". Sometimes, we must extract these parts.
8a4438b6 7318(defun tramp-file-name-real-host (vec)
00d6fd04 7319 "Return the host name of VEC without port."
a17632c1
MA
7320 (save-match-data
7321 (let ((host (tramp-file-name-host vec)))
7322 (if (and (stringp host)
7323 (string-match tramp-host-with-port-regexp host))
7324 (match-string 1 host)
7325 host))))
00d6fd04 7326
8a4438b6 7327(defun tramp-file-name-port (vec)
00d6fd04 7328 "Return the port number of VEC."
a17632c1
MA
7329 (save-match-data
7330 (let ((host (tramp-file-name-host vec)))
7331 (and (stringp host)
7332 (string-match tramp-host-with-port-regexp host)
7333 (string-to-number (match-string 2 host))))))
fb7933a3
KG
7334
7335(defun tramp-tramp-file-p (name)
a4aeb9a4 7336 "Return t if NAME is a Tramp file."
fb7933a3
KG
7337 (save-match-data
7338 (string-match tramp-file-name-regexp name)))
bf247b6e 7339
8a4438b6 7340(defun tramp-find-method (method user host)
00d6fd04
MA
7341 "Return the right method string to use.
7342This is METHOD, if non-nil. Otherwise, do a lookup in
7343`tramp-default-method-alist'."
7344 (or method
7345 (let ((choices tramp-default-method-alist)
7346 lmethod item)
7347 (while choices
7348 (setq item (pop choices))
7349 (when (and (string-match (or (nth 0 item) "") (or host ""))
7350 (string-match (or (nth 1 item) "") (or user "")))
7351 (setq lmethod (nth 2 item))
7352 (setq choices nil)))
7353 lmethod)
7354 tramp-default-method))
7355
8a4438b6 7356(defun tramp-find-user (method user host)
00d6fd04
MA
7357 "Return the right user string to use.
7358This is USER, if non-nil. Otherwise, do a lookup in
7359`tramp-default-user-alist'."
7360 (or user
7361 (let ((choices tramp-default-user-alist)
7362 luser item)
7363 (while choices
7364 (setq item (pop choices))
7365 (when (and (string-match (or (nth 0 item) "") (or method ""))
7366 (string-match (or (nth 1 item) "") (or host "")))
7367 (setq luser (nth 2 item))
7368 (setq choices nil)))
7369 luser)
7370 tramp-default-user))
7371
8a4438b6 7372(defun tramp-find-host (method user host)
00d6fd04
MA
7373 "Return the right host string to use.
7374This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7375 (or (and (> (length host) 0) host)
7376 tramp-default-host))
7377
9ce8462a 7378(defun tramp-dissect-file-name (name &optional nodefault)
00d6fd04 7379 "Return a `tramp-file-name' structure.
9ce8462a
MA
7380The structure consists of remote method, remote user, remote host
7381and localname (file name on remote host). If NODEFAULT is
7382non-nil, the file name parts are not expanded to their default
7383values."
4007ba5b 7384 (save-match-data
00d6fd04 7385 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
a4aeb9a4 7386 (unless match (error "Not a Tramp file name: %s" name))
00d6fd04
MA
7387 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7388 (user (match-string (nth 2 tramp-file-name-structure) name))
7389 (host (match-string (nth 3 tramp-file-name-structure) name))
7390 (localname (match-string (nth 4 tramp-file-name-structure) name)))
5d449a36
MA
7391 (when (member method '("multi" "multiu"))
7392 (error
7393 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7394 method))
b96e6899
MA
7395 (when host
7396 (when (string-match tramp-prefix-ipv6-regexp host)
7397 (setq host (replace-match "" nil t host)))
7398 (when (string-match tramp-postfix-ipv6-regexp host)
7399 (setq host (replace-match "" nil t host))))
9ce8462a
MA
7400 (if nodefault
7401 (vector method user host localname)
7402 (vector
7403 (tramp-find-method method user host)
7404 (tramp-find-user method user host)
7405 (tramp-find-host method user host)
7406 localname))))))
00d6fd04
MA
7407
7408(defun tramp-equal-remote (file1 file2)
7409 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7410The check depends on method, user and host name of the files. If
7411one of the components is missing, the default values are used.
7412The local file name parts of FILE1 and FILE2 are not taken into
7413account.
fb7933a3 7414
00d6fd04
MA
7415Example:
7416
7417 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7418
7419would yield `t'. On the other hand, the following check results in nil:
7420
7421 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
9e6ab520
MA
7422 (and (stringp (file-remote-p file1))
7423 (stringp (file-remote-p file2))
94be87e8 7424 (string-equal (file-remote-p file1) (file-remote-p file2))))
00d6fd04
MA
7425
7426(defun tramp-make-tramp-file-name (method user host localname)
7427 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7428 (concat tramp-prefix-format
7429 (when (not (zerop (length method)))
7430 (concat method tramp-postfix-method-format))
7431 (when (not (zerop (length user)))
7432 (concat user tramp-postfix-user-format))
b96e6899
MA
7433 (when host
7434 (if (string-match tramp-ipv6-regexp host)
7435 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7436 host))
7437 tramp-postfix-host-format
00d6fd04
MA
7438 (when localname localname)))
7439
7440(defun tramp-completion-make-tramp-file-name (method user host localname)
7441 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7442It must not be a complete Tramp file name, but as long as there are
7443necessary only. This function will be used in file name completion."
7444 (concat tramp-prefix-format
7445 (when (not (zerop (length method)))
7446 (concat method tramp-postfix-method-format))
7447 (when (not (zerop (length user)))
7448 (concat user tramp-postfix-user-format))
7449 (when (not (zerop (length host)))
b96e6899
MA
7450 (concat
7451 (if (string-match tramp-ipv6-regexp host)
7452 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7453 host)
7454 tramp-postfix-host-format))
00d6fd04
MA
7455 (when localname localname)))
7456
7457(defun tramp-make-copy-program-file-name (vec)
7458 "Create a file name suitable to be passed to `rcp' and workalikes."
7459 (let ((user (tramp-file-name-user vec))
0f205eee 7460 (host (tramp-file-name-real-host vec))
00d6fd04
MA
7461 (localname (tramp-shell-quote-argument
7462 (tramp-file-name-localname vec))))
7463 (if (not (zerop (length user)))
7464 (format "%s@%s:%s" user host localname)
7465 (format "%s:%s" host localname))))
7466
7f49fe46 7467(defun tramp-method-out-of-band-p (vec size)
38c65fca 7468 "Return t if this is an out-of-band method, nil otherwise."
7f49fe46
MA
7469 (and
7470 ;; It shall be an out-of-band method.
7471 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7472 ;; Either the file size is large enough, or (in rare cases) there
7473 ;; does not exist a remote encoding.
7474 (or (> size tramp-copy-size-limit)
7475 (null (tramp-get-remote-coding vec "remote-encoding")))))
fb7933a3 7476
0f205eee
MA
7477(defun tramp-local-host-p (vec)
7478 "Return t if this points to the local host, nil otherwise."
c992abdb
MA
7479 ;; We cannot use `tramp-file-name-real-host'. A port is an
7480 ;; indication for an ssh tunnel or alike.
7481 (let ((host (tramp-file-name-host vec)))
0f205eee
MA
7482 (and
7483 (stringp host)
b96e6899 7484 (string-match tramp-local-host-regexp host)
46bcd78c
MA
7485 ;; The method shall be applied to one of the shell file name
7486 ;; handler. `tramp-local-host-p' is also called for "smb" and
7487 ;; alike, where it must fail.
7488 (tramp-get-method-parameter
7489 (tramp-file-name-method vec) 'tramp-login-program)
a0a5183a
MA
7490 ;; The local temp directory must be writable for the other user.
7491 (file-writable-p
7492 (tramp-make-tramp-file-name
7493 (tramp-file-name-method vec)
7494 (tramp-file-name-user vec)
7495 host
93c3eb7c
MA
7496 (tramp-compat-temporary-file-directory)))
7497 ;; On some systems, chown runs only for root.
7498 (or (zerop (user-uid))
7499 (zerop (tramp-get-remote-uid vec 'integer))))))
0f205eee 7500
fb7933a3
KG
7501;; Variables local to connection.
7502
f84638eb 7503(defun tramp-get-remote-path (vec)
70c11b0b
MA
7504 (with-connection-property
7505 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
7506 ;; cache the result for the session only. Otherwise, the result
7507 ;; is cached persistently.
7508 (if (memq 'tramp-own-remote-path tramp-remote-path)
7509 (tramp-get-connection-process vec)
7510 vec)
7511 "remote-path"
9e6ab520 7512 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
70c11b0b
MA
7513 (elt1 (memq 'tramp-default-remote-path remote-path))
7514 (elt2 (memq 'tramp-own-remote-path remote-path))
f84638eb 7515 (default-remote-path
70c11b0b 7516 (when elt1
f84638eb 7517 (condition-case nil
70c11b0b
MA
7518 (tramp-send-command-and-read
7519 vec "echo \\\"`getconf PATH`\\\"")
f84638eb
MA
7520 ;; Default if "getconf" is not available.
7521 (error
7522 (tramp-message
7523 vec 3
7524 "`getconf PATH' not successful, using default value \"%s\"."
7525 "/bin:/usr/bin")
70c11b0b
MA
7526 "/bin:/usr/bin"))))
7527 (own-remote-path
7528 (when elt2
7529 (condition-case nil
7530 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
7531 ;; Default if "getconf" is not available.
7532 (error
7533 (tramp-message
7534 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
7535 nil)))))
7536
7537 ;; Replace place holder `tramp-default-remote-path'.
7538 (when elt1
7539 (setcdr elt1
f84638eb 7540 (append
70c11b0b
MA
7541 (tramp-compat-split-string default-remote-path ":")
7542 (cdr elt1)))
f84638eb
MA
7543 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
7544
70c11b0b
MA
7545 ;; Replace place holder `tramp-own-remote-path'.
7546 (when elt2
7547 (setcdr elt2
7548 (append
7549 (tramp-compat-split-string own-remote-path ":")
7550 (cdr elt2)))
7551 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
7552
7553 ;; Remove double entries.
7554 (setq elt1 remote-path)
7555 (while (consp elt1)
7556 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
7557 (setcar elt2 nil))
7558 (setq elt1 (cdr elt1)))
7559
f84638eb
MA
7560 ;; Remove non-existing directories.
7561 (delq
7562 nil
7563 (mapcar
7564 (lambda (x)
7565 (and
70c11b0b
MA
7566 (stringp x)
7567 (file-directory-p
7568 (tramp-make-tramp-file-name
7569 (tramp-file-name-method vec)
7570 (tramp-file-name-user vec)
7571 (tramp-file-name-host vec)
7572 x))
f84638eb
MA
7573 x))
7574 remote-path)))))
7575
a4aeb9a4
MA
7576(defun tramp-get-remote-tmpdir (vec)
7577 (with-connection-property vec "tmp-directory"
7578 (let ((dir (tramp-shell-quote-argument "/tmp")))
7579 (if (and (zerop
7580 (tramp-send-command-and-check
7581 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
7582 (zerop
7583 (tramp-send-command-and-check
7584 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
7585 dir
7586 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
7587
00d6fd04
MA
7588(defun tramp-get-ls-command (vec)
7589 (with-connection-property vec "ls"
946a5aeb
MA
7590 (tramp-message vec 5 "Finding a suitable `ls' command")
7591 (or
7592 (catch 'ls-found
7593 (dolist (cmd '("ls" "gnuls" "gls"))
7594 (let ((dl (tramp-get-remote-path vec))
7595 result)
7596 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
7597 ;; Check parameter.
7598 (when (zerop (tramp-send-command-and-check
7599 vec (format "%s -lnd /" result)))
7600 (throw 'ls-found result))
7601 (setq dl (cdr dl))))))
7602 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
00d6fd04 7603
8e754ea2
MA
7604(defun tramp-get-ls-command-with-dired (vec)
7605 (save-match-data
7606 (with-connection-property vec "ls-dired"
7607 (tramp-message vec 5 "Checking, whether `ls --dired' works")
7608 (zerop (tramp-send-command-and-check
7f49fe46 7609 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8e754ea2 7610
00d6fd04
MA
7611(defun tramp-get-test-command (vec)
7612 (with-connection-property vec "test"
946a5aeb
MA
7613 (tramp-message vec 5 "Finding a suitable `test' command")
7614 (if (zerop (tramp-send-command-and-check vec "test 0"))
7615 "test"
7616 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
00d6fd04
MA
7617
7618(defun tramp-get-test-nt-command (vec)
7619 ;; Does `test A -nt B' work? Use abominable `find' construct if it
7620 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
7621 ;; for otherwise the shell crashes.
7622 (with-connection-property vec "test-nt"
7623 (or
7624 (progn
7625 (tramp-send-command
7626 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
7627 (with-current-buffer (tramp-get-buffer vec)
7628 (goto-char (point-min))
a0a5183a 7629 (when (looking-at (regexp-quote tramp-end-of-output))
00d6fd04
MA
7630 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
7631 (progn
7632 (tramp-send-command
7633 vec
7634 (format
7635 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
7636 (tramp-get-test-command vec)))
7637 "tramp_test_nt %s %s"))))
7638
7639(defun tramp-get-file-exists-command (vec)
7640 (with-connection-property vec "file-exists"
946a5aeb
MA
7641 (tramp-message vec 5 "Finding command to check if file exists")
7642 (tramp-find-file-exists-command vec)))
00d6fd04
MA
7643
7644(defun tramp-get-remote-ln (vec)
7645 (with-connection-property vec "ln"
946a5aeb
MA
7646 (tramp-message vec 5 "Finding a suitable `ln' command")
7647 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
00d6fd04
MA
7648
7649(defun tramp-get-remote-perl (vec)
7650 (with-connection-property vec "perl"
946a5aeb
MA
7651 (tramp-message vec 5 "Finding a suitable `perl' command")
7652 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
7653 (tramp-find-executable vec "perl" (tramp-get-remote-path vec)))))
00d6fd04
MA
7654
7655(defun tramp-get-remote-stat (vec)
7656 (with-connection-property vec "stat"
946a5aeb
MA
7657 (tramp-message vec 5 "Finding a suitable `stat' command")
7658 (let ((result (tramp-find-executable
7659 vec "stat" (tramp-get-remote-path vec)))
7660 tmp)
7661 ;; Check whether stat(1) returns usable syntax. %s does not
7662 ;; work on older AIX systems.
7663 (when result
7664 (setq tmp
7665 ;; We don't want to display an error message.
7666 (with-temp-message (or (current-message) "")
7667 (condition-case nil
7668 (tramp-send-command-and-read
7669 vec (format "%s -c '(\"%%N\" %%s)' /" result))
7670 (error nil))))
7671 (unless (and (listp tmp) (stringp (car tmp))
7672 (string-match "^./.$" (car tmp))
7673 (integerp (cadr tmp)))
7674 (setq result nil)))
7675 result)))
fb7933a3 7676
00d6fd04
MA
7677(defun tramp-get-remote-id (vec)
7678 (with-connection-property vec "id"
946a5aeb
MA
7679 (tramp-message vec 5 "Finding POSIX `id' command")
7680 (or
7681 (catch 'id-found
7682 (let ((dl (tramp-get-remote-path vec))
7683 result)
7684 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
7685 ;; Check POSIX parameter.
7686 (when (zerop (tramp-send-command-and-check
7687 vec (format "%s -u" result)))
7688 (throw 'id-found result))
7689 (setq dl (cdr dl)))))
7690 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
00d6fd04
MA
7691
7692(defun tramp-get-remote-uid (vec id-format)
7693 (with-connection-property vec (format "uid-%s" id-format)
7694 (let ((res (tramp-send-command-and-read
7695 vec
7696 (format "%s -u%s %s"
7697 (tramp-get-remote-id vec)
7698 (if (equal id-format 'integer) "" "n")
7699 (if (equal id-format 'integer)
7700 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
7701 ;; The command might not always return a number.
7702 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
7703
7704(defun tramp-get-remote-gid (vec id-format)
7705 (with-connection-property vec (format "gid-%s" id-format)
7706 (let ((res (tramp-send-command-and-read
7707 vec
7708 (format "%s -g%s %s"
7709 (tramp-get-remote-id vec)
7710 (if (equal id-format 'integer) "" "n")
7711 (if (equal id-format 'integer)
7712 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
7713 ;; The command might not always return a number.
7714 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
fb7933a3 7715
8d60099b
MA
7716(defun tramp-get-local-uid (id-format)
7717 (if (equal id-format 'integer) (user-uid) (user-login-name)))
7718
7719(defun tramp-get-local-gid (id-format)
9e6ab520 7720 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8d60099b 7721
00d6fd04
MA
7722;; Some predefined connection properties.
7723(defun tramp-get-remote-coding (vec prop)
7724 ;; Local coding handles properties like remote coding. So we could
7725 ;; call it without pain.
7726 (let ((ret (tramp-get-local-coding vec prop)))
7727 ;; The connection property might have been cached. So we must send
7728 ;; the script - maybe.
1d7e9a01 7729 (when (and ret (symbolp ret))
00d6fd04
MA
7730 (let ((name (symbol-name ret)))
7731 (while (string-match (regexp-quote "-") name)
7732 (setq name (replace-match "_" nil t name)))
7733 (tramp-maybe-send-script vec (symbol-value ret) name)
7734 (setq ret name)))
7735 ;; Return the value.
7736 ret))
7737
7738(defun tramp-get-local-coding (vec prop)
bf0503cb 7739 (or
00d6fd04
MA
7740 (tramp-get-connection-property vec prop nil)
7741 (progn
7742 (tramp-find-inline-encoding vec)
7743 (tramp-get-connection-property vec prop nil))))
fb7933a3 7744
00d6fd04 7745(defun tramp-get-method-parameter (method param)
c951aecb 7746 "Return the method parameter PARAM.
00d6fd04
MA
7747If the `tramp-methods' entry does not exist, return NIL."
7748 (let ((entry (assoc param (assoc method tramp-methods))))
7749 (when entry (cadr entry))))
90f8dc03 7750
fb7933a3
KG
7751;; Auto saving to a special directory.
7752
00cec167 7753(defun tramp-exists-file-name-handler (operation &rest args)
00d6fd04
MA
7754 "Checks whether OPERATION runs a file name handler."
7755 ;; The file name handler is determined on base of either an
7756 ;; argument, `buffer-file-name', or `default-directory'.
7757 (condition-case nil
7758 (let* ((buffer-file-name "/")
7759 (default-directory "/")
7760 (fnha file-name-handler-alist)
7761 (check-file-name-operation operation)
7762 (file-name-handler-alist
7763 (list
7764 (cons "/"
aa485f7c
MA
7765 (lambda (operation &rest args)
7766 "Returns OPERATION if it is the one to be checked."
7767 (if (equal check-file-name-operation operation)
7768 operation
7769 (let ((file-name-handler-alist fnha))
7770 (apply operation args))))))))
00d6fd04
MA
7771 (equal (apply operation args) operation))
7772 (error nil)))
c1105d05
MA
7773
7774(unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
7775 (defadvice make-auto-save-file-name
7776 (around tramp-advice-make-auto-save-file-name () activate)
00d6fd04 7777 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
c1105d05 7778 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
7f49fe46
MA
7779 ;; We cannot call `tramp-handle-make-auto-save-file-name'
7780 ;; directly, because this would bypass the locking mechanism.
7781 (setq ad-return-value
7782 (tramp-file-name-handler 'make-auto-save-file-name))
a69c01a0
MA
7783 ad-do-it))
7784 (add-hook 'tramp-unload-hook
aa485f7c 7785 (lambda () (ad-unadvise 'make-auto-save-file-name))))
fb7933a3 7786
340b8d4f
MA
7787;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
7788;; permission 0666 minus umask. This is a security threat.
414da5ab
MA
7789
7790(defun tramp-set-auto-save-file-modes ()
7791 "Set permissions of autosaved remote files to the original permissions."
7792 (let ((bfn (buffer-file-name)))
7793 (when (and (stringp bfn)
7794 (tramp-tramp-file-p bfn)
b50dd0d2 7795 (buffer-modified-p)
414da5ab 7796 (stringp buffer-auto-save-file-name)
340b8d4f
MA
7797 (not (equal bfn buffer-auto-save-file-name)))
7798 (unless (file-exists-p buffer-auto-save-file-name)
7799 (write-region "" nil buffer-auto-save-file-name))
7800 ;; Permissions should be set always, because there might be an old
7801 ;; auto-saved file belonging to another original file. This could
7802 ;; be a security threat.
7177e2a3 7803 (set-file-modes buffer-auto-save-file-name
11948172 7804 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
414da5ab
MA
7805
7806(unless (or (> emacs-major-version 21)
7807 (and (featurep 'xemacs)
7808 (= emacs-major-version 21)
340b8d4f 7809 (> emacs-minor-version 4)))
a69c01a0
MA
7810 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
7811 (add-hook 'tramp-unload-hook
aa485f7c
MA
7812 (lambda ()
7813 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
414da5ab 7814
fb7933a3
KG
7815(defun tramp-subst-strs-in-string (alist string)
7816 "Replace all occurrences of the string FROM with TO in STRING.
7817ALIST is of the form ((FROM . TO) ...)."
7818 (save-match-data
7819 (while alist
7820 (let* ((pr (car alist))
7821 (from (car pr))
7822 (to (cdr pr)))
7823 (while (string-match (regexp-quote from) string)
7824 (setq string (replace-match to t t string)))
7825 (setq alist (cdr alist))))
7826 string))
7827
fb7933a3
KG
7828;; ------------------------------------------------------------
7829;; -- Compatibility functions section --
7830;; ------------------------------------------------------------
7831
00d6fd04 7832(defun tramp-read-passwd (proc &optional prompt)
fb7933a3 7833 "Read a password from user (compat function).
5615d63f 7834Consults the auth-source package.
5ec2cc41 7835Invokes `password-read' if available, `read-passwd' else."
00d6fd04
MA
7836 (let* ((key (tramp-make-tramp-file-name
7837 tramp-current-method tramp-current-user
7838 tramp-current-host ""))
7839 (pw-prompt
7840 (or prompt
7841 (with-current-buffer (process-buffer proc)
7842 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
7843 (format "%s for %s " (capitalize (match-string 1)) key)))))
5c7043a2
MA
7844 (prog1
7845 (or
7846 ;; See if auth-sources contains something useful, if it's bound.
7847 (and (boundp 'auth-sources)
7848 (tramp-get-connection-property proc "first-password-request" nil)
7849 ;; Try with Tramp's current method.
7850 (funcall (symbol-function 'auth-source-user-or-password)
7851 "password" tramp-current-host tramp-current-method))
7852 ;; Try the password cache.
cb85dcd0
MA
7853 (when (functionp 'password-read)
7854 (unless (tramp-get-connection-property
7855 proc "first-password-request" nil)
7856 (funcall (symbol-function 'password-cache-remove) key))
7857 (let ((password
7858 (funcall (symbol-function 'password-read) pw-prompt key)))
7859 (funcall (symbol-function 'password-cache-add) key password)
7860 password))
5c7043a2
MA
7861 ;; Else, get the password interactively.
7862 (read-passwd pw-prompt))
7863 (tramp-set-connection-property proc "first-password-request" nil))))
00d6fd04 7864
9c13938d
MA
7865(defun tramp-clear-passwd (vec)
7866 "Clear password cache for connection related to VEC."
00d6fd04 7867 (when (functionp 'password-cache-remove)
9c13938d
MA
7868 (funcall
7869 (symbol-function 'password-cache-remove)
7870 (tramp-make-tramp-file-name
7871 (tramp-file-name-method vec)
7872 (tramp-file-name-user vec)
7873 (tramp-file-name-host vec)
7874 ""))))
00d6fd04
MA
7875
7876;; Snarfed code from time-date.el and parse-time.el
7877
7878(defconst tramp-half-a-year '(241 17024)
7879"Evaluated by \"(days-to-time 183)\".")
7880
7881(defconst tramp-parse-time-months
7882 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
7883 ("apr" . 4) ("may" . 5) ("jun" . 6)
7884 ("jul" . 7) ("aug" . 8) ("sep" . 9)
7885 ("oct" . 10) ("nov" . 11) ("dec" . 12))
7886 "Alist mapping month names to integers.")
7887
7888(defun tramp-time-less-p (t1 t2)
7889 "Say whether time value T1 is less than time value T2."
7890 (unless t1 (setq t1 '(0 0)))
7891 (unless t2 (setq t2 '(0 0)))
7892 (or (< (car t1) (car t2))
7893 (and (= (car t1) (car t2))
7894 (< (nth 1 t1) (nth 1 t2)))))
7895
7896(defun tramp-time-subtract (t1 t2)
7897 "Subtract two time values.
7898Return the difference in the format of a time value."
7899 (unless t1 (setq t1 '(0 0)))
7900 (unless t2 (setq t2 '(0 0)))
7901 (let ((borrow (< (cadr t1) (cadr t2))))
7902 (list (- (car t1) (car t2) (if borrow 1 0))
7903 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
fb7933a3
KG
7904
7905(defun tramp-time-diff (t1 t2)
7906 "Return the difference between the two times, in seconds.
1a762140 7907T1 and T2 are time values (as returned by `current-time' for example)."
fb7933a3 7908 ;; Pacify byte-compiler with `symbol-function'.
ea9d1443
KG
7909 (cond ((and (fboundp 'subtract-time)
7910 (fboundp 'float-time))
7911 (funcall (symbol-function 'float-time)
7912 (funcall (symbol-function 'subtract-time) t1 t2)))
7913 ((and (fboundp 'subtract-time)
7914 (fboundp 'time-to-seconds))
7915 (funcall (symbol-function 'time-to-seconds)
7916 (funcall (symbol-function 'subtract-time) t1 t2)))
fb7933a3 7917 ((fboundp 'itimer-time-difference)
1a762140
MA
7918 (funcall (symbol-function 'itimer-time-difference)
7919 (if (< (length t1) 3) (append t1 '(0)) t1)
7920 (if (< (length t2) 3) (append t2 '(0)) t2)))
fb7933a3 7921 (t
00d6fd04 7922 (let ((time (tramp-time-subtract t1 t2)))
ea9d1443
KG
7923 (+ (* (car time) 65536.0)
7924 (cadr time)
7925 (/ (or (nth 2 time) 0) 1000000.0))))))
fb7933a3
KG
7926
7927(defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
7928 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
7929EOL-TYPE can be one of `dos', `unix', or `mac'."
7930 (cond ((fboundp 'coding-system-change-eol-conversion)
9e6ab520
MA
7931 (funcall (symbol-function 'coding-system-change-eol-conversion)
7932 coding-system eol-type))
fb7933a3 7933 ((fboundp 'subsidiary-coding-system)
9e6ab520
MA
7934 (funcall (symbol-function 'subsidiary-coding-system)
7935 coding-system
7936 (cond ((eq eol-type 'dos) 'crlf)
7937 ((eq eol-type 'unix) 'lf)
7938 ((eq eol-type 'mac) 'cr)
7939 (t
7940 (error "Unknown EOL-TYPE `%s', must be %s"
7941 eol-type
7942 "`dos', `unix', or `mac'")))))
fb7933a3
KG
7943 (t (error "Can't change EOL conversion -- is MULE missing?"))))
7944
19a87064
MA
7945(defun tramp-set-process-query-on-exit-flag (process flag)
7946 "Specify if query is needed for process when Emacs is exited.
7947If the second argument flag is non-nil, Emacs will query the user before
7948exiting if process is running."
7949 (if (fboundp 'set-process-query-on-exit-flag)
00d6fd04
MA
7950 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
7951 (funcall (symbol-function 'process-kill-without-query) process flag)))
19a87064 7952
19a87064 7953
bf247b6e
KS
7954;; ------------------------------------------------------------
7955;; -- Kludges section --
7956;; ------------------------------------------------------------
fb7933a3
KG
7957
7958;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
7959;; does not deal well with newline characters. Newline is replaced by
7960;; backslash newline. But if, say, the string `a backslash newline b'
7961;; is passed to a shell, the shell will expand this into "ab",
7962;; completely omitting the newline. This is not what was intended.
7963;; It does not appear to be possible to make the function
7964;; `shell-quote-argument' work with newlines without making it
7965;; dependent on the shell used. But within this package, we know that
7966;; we will always use a Bourne-like shell, so we use an approach which
7967;; groks newlines.
7968;;
7969;; The approach is simple: we call `shell-quote-argument', then
7970;; massage the newline part of the result.
7971;;
7972;; This function should produce a string which is grokked by a Unix
7973;; shell, even if the Emacs is running on Windows. Since this is the
7974;; kludges section, we bind `system-type' in such a way that
7975;; `shell-quote-arguments' behaves as if on Unix.
7976;;
7977;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
7978;; function to work with Bourne-like shells.
7979;;
7980;; CCC: This function should be rewritten so that
7981;; `shell-quote-argument' is not used. This way, we are safe from
7982;; changes in `shell-quote-argument'.
7983(defun tramp-shell-quote-argument (s)
7984 "Similar to `shell-quote-argument', but groks newlines.
7985Only works for Bourne-like shells."
7986 (let ((system-type 'not-windows))
7987 (save-match-data
7988 (let ((result (shell-quote-argument s))
7989 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
7990 (when (and (>= (length result) 2)
7991 (string= (substring result 0 2) "\\~"))
7992 (setq result (substring result 1)))
7993 (while (string-match nl result)
7994 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
7995 t t result)))
7996 result))))
7997
16674e4f
KG
7998;; We currently (sometimes) use "[" and "]" in the filename format.
7999;; This means that Emacs wants to expand wildcards if
fb7933a3
KG
8000;; `find-file-wildcards' is non-nil, and then barfs because no
8001;; expansion could be found. We detect this situation and do
8002;; something really awful: we have `file-expand-wildcards' return the
8003;; original filename if it can't expand anything. Let's just hope
8004;; that this doesn't break anything else.
16674e4f
KG
8005;; CCC: This check is now also really awful; we should search all
8006;; of the filename format, not just the prefix.
8007(when (string-match "\\[" tramp-prefix-format)
1834b39f
MA
8008 (defadvice file-expand-wildcards
8009 (around tramp-advice-file-expand-wildcards activate)
d2a2c17f
MA
8010 (let ((name (ad-get-arg 0)))
8011 (if (tramp-tramp-file-p name)
8012 ;; If it's a Tramp file, dissect it and look if wildcards
8013 ;; need to be expanded at all.
1834b39f
MA
8014 (if (string-match
8015 "[[*?]"
8016 (tramp-file-name-localname (tramp-dissect-file-name name)))
8017 (setq ad-return-value (or ad-do-it (list name)))
8018 (setq ad-return-value (list name)))
d2a2c17f 8019 ;; If it is not a Tramp file, just run the original function.
1834b39f 8020 (setq ad-return-value (or ad-do-it (list name))))))
a69c01a0 8021 (add-hook 'tramp-unload-hook
aa485f7c 8022 (lambda () (ad-unadvise 'file-expand-wildcards))))
fb7933a3 8023
a69c01a0
MA
8024;; Checklist for `tramp-unload-hook'
8025;; - Unload all `tramp-*' packages
8026;; - Reset `file-name-handler-alist'
8027;; - Cleanup hooks where Tramp functions are in
8028;; - Cleanup advised functions
8029;; - Cleanup autoloads
8030;;;###autoload
8031(defun tramp-unload-tramp ()
08b1eb21 8032 "Discard Tramp from loading remote files."
a69c01a0
MA
8033 (interactive)
8034 ;; When Tramp is not loaded yet, its autoloads are still active.
8c04e197 8035 (tramp-unload-file-name-handlers)
a69c01a0
MA
8036 ;; ange-ftp settings must be enabled.
8037 (when (functionp 'tramp-ftp-enable-ange-ftp)
8038 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
00d6fd04
MA
8039 ;; Maybe its not loaded yet.
8040 (condition-case nil
8041 (unload-feature 'tramp 'force)
a69c01a0
MA
8042 (error nil)))
8043
dea31ca6
MA
8044(when (and load-in-progress
8045 (string-match "Loading tramp..." (or (current-message) "")))
ccb4a481
MA
8046 (message "Loading tramp...done"))
8047
fb7933a3
KG
8048(provide 'tramp)
8049
fb7933a3
KG
8050;;; TODO:
8051
4007ba5b 8052;; * Handle nonlocal exits such as C-g.
00d6fd04
MA
8053;; * But it would probably be better to use with-local-quit at the
8054;; place where it's actually needed: around any potentially
8055;; indefinitely blocking piece of code. In this case it would be
8056;; within Tramp around one of its calls to accept-process-output (or
8057;; around one of the loops that calls accept-process-output)
d037d501 8058;; (Stefan Monnier).
fb7933a3 8059;; * Rewrite `tramp-shell-quote-argument' to abstain from using
b1d06e75 8060;; `shell-quote-argument'.
fb7933a3
KG
8061;; * In Emacs 21, `insert-directory' shows total number of bytes used
8062;; by the files in that directory. Add this here.
8063;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8064;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
fb7933a3 8065;; * Case-insensitive filename completion. (Norbert Goevert.)
fb7933a3
KG
8066;; * Don't use globbing for directories with many files, as this is
8067;; likely to produce long command lines, and some shells choke on
8068;; long command lines.
fb7933a3
KG
8069;; * `vc-directory' does not work. It never displays any files, even
8070;; if it does show files when run locally.
fb7933a3 8071;; * How to deal with MULE in `insert-file-contents' and `write-region'?
fb7933a3
KG
8072;; * Grok `append' parameter for `write-region'.
8073;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8074;; * abbreviate-file-name
8e754ea2 8075;; * Better error checking. At least whenever we see something
fb7933a3
KG
8076;; strange when doing zerop, we should kill the process and start
8077;; again. (Greg Stark)
fb7933a3
KG
8078;; * Provide a local cache of old versions of remote files for the rsync
8079;; transfer method to use. (Greg Stark)
8080;; * Remove unneeded parameters from methods.
fb7933a3
KG
8081;; * Make it work for different encodings, and for different file name
8082;; encodings, too. (Daniel Pittman)
fb7933a3 8083;; * Progress reports while copying files. (Michael Kifer)
fb7933a3
KG
8084;; * Don't search for perl5 and perl. Instead, only search for perl and
8085;; then look if it's the right version (with `perl -v').
8086;; * When editing a remote CVS controlled file as a different user, VC
8087;; gets confused about the file locking status. Try to find out why
8088;; the workaround doesn't work.
3cdaec13 8089;; * Username and hostname completion.
6c4e47fa 8090;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8daea7fc 8091;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
16674e4f 8092;; Code is nearly identical.
cfb5c0db
MA
8093;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8094;; until the last but one hop via `start-file-process'. Apply it
8095;; also for ftp and smb.
00d6fd04
MA
8096;; * WIBNI if we had a command "trampclient"? If I was editing in
8097;; some shell with root priviledges, it would be nice if I could
8098;; just call
8099;; trampclient filename.c
8100;; as an editor, and the _current_ shell would connect to an Emacs
8101;; server and would be used in an existing non-priviledged Emacs
8102;; session for doing the editing in question.
8103;; That way, I need not tell Emacs my password again and be afraid
8104;; that it makes it into core dumps or other ugly stuff (I had Emacs
8105;; once display a just typed password in the context of a keyboard
8106;; sequence prompt for a question immediately following in a shell
8107;; script run within Emacs -- nasty).
8108;; And if I have some ssh session running to a different computer,
8109;; having the possibility of passing a local file there to a local
8110;; Emacs session (in case I can arrange for a connection back) would
8111;; be nice.
a4aeb9a4 8112;; Likely the corresponding Tramp server should not allow the
00d6fd04
MA
8113;; equivalent of the emacsclient -eval option in order to make this
8114;; reasonably unproblematic. And maybe trampclient should have some
8115;; way of passing credentials, like by using an SSL socket or
8116;; something. (David Kastrup)
00d6fd04
MA
8117;; * Reconnect directly to a compliant shell without first going
8118;; through the user's default shell. (Pete Forman)
00d6fd04 8119;; * Make `tramp-default-user' obsolete.
adb67129
MA
8120;; * Tramp shall reconnect automatically to its ssh connection when it
8121;; detects that the process "has died". (David Reitter)
11c71217
MA
8122;; * How can I interrupt the remote process with a signal
8123;; (interrupt-process seems not to work)? (Markus Triska)
2296b54d
MA
8124;; * Avoid the local shell entirely for starting remote processes. If
8125;; so, I think even a signal, when delivered directly to the local
8126;; SSH instance, would correctly be propagated to the remote process
8127;; automatically; possibly SSH would have to be started with
8128;; "-t". (Markus Triska)
dea31ca6
MA
8129;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8130;; isn't on the remote host. (Mark A. Hershberger)
3e2fa353
MA
8131;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8132;; * Implement a general server-local-variable mechanism, as there are
8133;; probably other variables that need different values for different
8134;; servers too. The user could then configure a variable (such as
8135;; tramp-server-local-variable-alist) to define any such variables
8136;; that they need to, which would then be let bound as appropriate
8137;; in tramp functions. (Jason Rumney)
946a5aeb
MA
8138;; * Optimize out-of-band copying, when both methods are scp-like (not
8139;; rsync).
8140;; * Keep a second connection open for out-of-band methods like scp or
8141;; rsync.
263c02ef 8142;; * Support ptys in `tramp-handle-start-file-process'.
fb7933a3
KG
8143
8144;; Functions for file-name-handler-alist:
8145;; diff-latest-backup-file -- in diff.el
fb7933a3 8146
cdd44874 8147;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
fb7933a3 8148;;; tramp.el ends here
57671b72
MA
8149
8150;; Local Variables:
8151;; mode: Emacs-Lisp
8152;; coding: utf-8
8153;; End: