1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; (copyright statements below in code to be updated with the above notice)
8 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
9 ;; Michael Albinus <michael.albinus@gmx.de>
10 ;; Keywords: comm, processes
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
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.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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.
34 ;; For more detailed instructions, please see the info file.
39 ;; This package only works for Emacs 22.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.
43 ;; Also see the todo list at the bottom of this file.
45 ;; The current version of Tramp can be retrieved from the following URL:
46 ;; http://ftp.gnu.org/gnu/tramp/
48 ;; There's a mailing list for this, as well. Its name is:
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
53 ;; For the adventurous, the current development sources are available
54 ;; via CVS. You can find instructions about this at the following URL:
55 ;; http://savannah.gnu.org/projects/tramp/
56 ;; Click on "CVS" in the navigation bar near the top.
58 ;; Don't forget to put on your asbestos longjohns, first!
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..."))
69 ;; The Tramp version number and bug report address, as prepared by configure.
71 (add-hook 'tramp-unload-hook
73 (when (featurep 'trampver)
74 (unload-feature 'trampver 'force))))
76 (require 'tramp-compat)
77 (add-hook 'tramp-unload-hook
79 (when (featurep 'tramp-compat)
80 (unload-feature 'tramp-compat 'force))))
82 (require 'format-spec)
83 ;; As long as password.el is not part of (X)Emacs, it shouldn't
85 (if (featurep 'xemacs)
86 (load "password" 'noerror)
87 (or (require 'password-cache nil 'noerror)
88 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
94 (if (featurep 'xemacs)
95 (load "auth-source" 'noerror)
96 (require 'auth-source nil 'noerror)))
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")
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
109 (when (featurep 'tramp-cache)
110 (unload-feature 'tramp-cache 'force))))
112 (autoload 'tramp-uuencode-region "tramp-uu"
113 "Implementation of `uuencode' in Lisp.")
114 (add-hook 'tramp-unload-hook
116 (when (featurep 'tramp-uu)
117 (unload-feature 'tramp-uu 'force))))
119 (autoload 'uudecode-decode-region "uudecode")
121 ;; The following Tramp packages must be loaded after tramp.el, because
122 ;; they require it as well.
123 (eval-after-load "tramp"
128 ;; Tramp interactive commands.
131 ;; Load foreign FTP method.
132 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
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)
140 ;; Load foreign FISH method.
143 ;; tramp-gvfs needs D-Bus messages. Available since Emacs 23
144 ;; on some system types. We don't call `dbus-ping', because
145 ;; this would load dbus.el.
146 (when (and (featurep 'dbusbind)
148 (funcall 'dbus-get-unique-name :session)
150 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
153 ;; Load gateways. It needs `make-network-process' from Emacs 22.
154 (when (functionp 'make-network-process) 'tramp-gw)
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"))
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
167 (add-hook 'tramp-unload-hook
169 (when (featurep (quote ,feature))
170 (unload-feature (quote ,feature) 'force)))))
171 (unless (featurep feature)
172 (message "Loading %s failed, ignoring this package" feature)))))
174 ;;; User Customizable Internal Variables:
177 "Edit remote files with a combination of rsh and rcp or similar programs."
182 ;; Maybe we need once a real Tramp mode, with key bindings etc.
184 (defcustom tramp-mode t
185 "*Whether Tramp is enabled.
186 If it is set to nil, all remote file names are used literally."
190 (defcustom tramp-verbose 3
191 "*Verbosity level for Tramp messages.
192 Any level x includes messages for all levels 1 .. x-1. The levels are
194 0 silent (no tramp messages at all)
197 3 connection to remote hosts (default level)
200 6 sent and received strings
202 8 connection properties
209 (when (boundp 'backup-directory-alist)
210 (defcustom tramp-backup-directory-alist nil
211 "Alist of filename patterns and backup directory names.
212 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
213 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
214 is a local file name, the backup directory is prepended with Tramp file
215 name prefix \(method, user, host\) of file.
217 \(setq tramp-backup-directory-alist backup-directory-alist\)
219 gives the same backup policy for Tramp files on their hosts like the
220 policy for local files."
222 :type '(repeat (cons (regexp :tag "Regexp matching filename")
223 (directory :tag "Backup directory name"))))))
225 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
226 ;; the package "backup-dir" might not be loaded yet.
228 (when (featurep 'xemacs)
229 (defcustom tramp-bkup-backup-directory-info nil
230 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
231 It has the same meaning like `bkup-backup-directory-info' from package
232 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
233 file name, the backup directory is prepended with Tramp file name prefix
234 \(method, user, host\) of file.
236 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
238 gives the same backup policy for Tramp files on their hosts like the
239 policy for local files."
241 (list (regexp :tag "File regexp")
242 (string :tag "Backup Dir")
247 (const search-upward))))
250 (defcustom tramp-auto-save-directory nil
251 "*Put auto-save files in this directory, if set.
252 The idea is to use a local directory so that auto-saving is faster."
254 :type '(choice (const nil) string))
256 (defcustom tramp-encoding-shell
257 (if (memq system-type '(windows-nt))
260 "*Use this program for encoding and decoding commands on the local host.
261 This shell is used to execute the encoding and decoding command on the
262 local host, so if you want to use `~' in those commands, you should
263 choose a shell here which groks tilde expansion. `/bin/sh' normally
264 does not understand tilde expansion.
266 For encoding and deocding, commands like the following are executed:
268 /bin/sh -c COMMAND < INPUT > OUTPUT
270 This variable can be used to change the \"/bin/sh\" part. See the
271 variable `tramp-encoding-command-switch' for the \"-c\" part.
273 Note that this variable is not used for remote commands. There are
274 mechanisms in tramp.el which automatically determine the right shell to
275 use for the remote host."
277 :type '(file :must-match t))
279 (defcustom tramp-encoding-command-switch
280 (if (string-match "cmd\\.exe" tramp-encoding-shell)
283 "*Use this switch together with `tramp-encoding-shell' for local commands.
284 See the variable `tramp-encoding-shell' for more information."
288 (defcustom tramp-copy-size-limit 10240
289 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
293 (defcustom tramp-terminal-type "dumb"
294 "*Value of TERM environment variable for logging in to remote host.
295 Because Tramp wants to parse the output of the remote shell, it is easily
296 confused by ANSI color escape sequences and suchlike. Often, shell init
297 files conditionalize this setup based on the TERM environment variable."
301 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
302 ;; root users. It uses the `$' character for other users. In order
303 ;; to guarantee a proper prompt, we use "#$" for the prompt.
305 (defvar tramp-end-of-output
308 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
309 "String used to recognize end of output.
310 The '$' character at the end is quoted; the string cannot be
311 detected as prompt when being sent on echoing hosts, therefore.")
313 (defconst tramp-initial-end-of-output "#$ "
314 "Prompt when establishing a connection.")
316 (defvar tramp-methods
317 `(("rcp" (tramp-login-program "rsh")
318 (tramp-login-args (("%h") ("-l" "%u")))
319 (tramp-remote-sh "/bin/sh")
320 (tramp-copy-program "rcp")
321 (tramp-copy-args (("-p" "%k") ("-r")))
322 (tramp-copy-keep-date t)
323 (tramp-copy-recursive t)
324 (tramp-password-end-of-line nil))
325 ("scp" (tramp-login-program "ssh")
326 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
328 (tramp-remote-sh "/bin/sh")
329 (tramp-copy-program "scp")
330 (tramp-copy-args (("-P" "%p") ("-p" "%k")
332 (tramp-copy-keep-date t)
333 (tramp-copy-recursive t)
334 (tramp-password-end-of-line nil)
335 (tramp-gw-args (("-o"
336 "GlobalKnownHostsFile=/dev/null")
337 ("-o" "UserKnownHostsFile=/dev/null")
338 ("-o" "StrictHostKeyChecking=no")))
339 (tramp-default-port 22))
340 ("scp1" (tramp-login-program "ssh")
341 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
343 (tramp-remote-sh "/bin/sh")
344 (tramp-copy-program "scp")
345 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
347 (tramp-copy-keep-date t)
348 (tramp-copy-recursive t)
349 (tramp-password-end-of-line nil)
350 (tramp-gw-args (("-o"
351 "GlobalKnownHostsFile=/dev/null")
352 ("-o" "UserKnownHostsFile=/dev/null")
353 ("-o" "StrictHostKeyChecking=no")))
354 (tramp-default-port 22))
355 ("scp2" (tramp-login-program "ssh")
356 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
358 (tramp-remote-sh "/bin/sh")
359 (tramp-copy-program "scp")
360 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
362 (tramp-copy-keep-date t)
363 (tramp-copy-recursive t)
364 (tramp-password-end-of-line nil)
365 (tramp-gw-args (("-o"
366 "GlobalKnownHostsFile=/dev/null")
367 ("-o" "UserKnownHostsFile=/dev/null")
368 ("-o" "StrictHostKeyChecking=no")))
369 (tramp-default-port 22))
371 (tramp-login-program "ssh1")
372 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
374 (tramp-remote-sh "/bin/sh")
375 (tramp-copy-program "scp1")
376 (tramp-copy-args (("-p" "%k") ("-r")))
377 (tramp-copy-keep-date t)
378 (tramp-copy-recursive t)
379 (tramp-password-end-of-line nil))
381 (tramp-login-program "ssh2")
382 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
384 (tramp-remote-sh "/bin/sh")
385 (tramp-copy-program "scp2")
386 (tramp-copy-args (("-p" "%k") ("-r")))
387 (tramp-copy-keep-date t)
388 (tramp-copy-recursive t)
389 (tramp-password-end-of-line nil))
390 ("sftp" (tramp-login-program "ssh")
391 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
393 (tramp-remote-sh "/bin/sh")
394 (tramp-copy-program "sftp")
395 (tramp-copy-args nil)
396 (tramp-copy-keep-date nil)
397 (tramp-password-end-of-line nil))
398 ("rsync" (tramp-login-program "ssh")
399 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
401 (tramp-remote-sh "/bin/sh")
402 (tramp-copy-program "rsync")
403 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
404 (tramp-copy-keep-date t)
405 (tramp-copy-keep-tmpfile t)
406 (tramp-copy-recursive t)
407 (tramp-password-end-of-line nil))
409 (tramp-login-program "ssh")
410 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
411 ("-o" "ControlPath=%t.%%r@%%h:%%p")
412 ("-o" "ControlMaster=yes")
414 (tramp-remote-sh "/bin/sh")
415 (tramp-copy-program "rsync")
416 (tramp-copy-args (("-t" "%k") ("-r")))
417 (tramp-copy-env (("RSYNC_RSH")
420 " -o ControlPath=%t.%%r@%%h:%%p"
421 " -o ControlMaster=auto"))))
422 (tramp-copy-keep-date t)
423 (tramp-copy-keep-tmpfile t)
424 (tramp-copy-recursive t)
425 (tramp-password-end-of-line nil))
426 ("remcp" (tramp-login-program "remsh")
427 (tramp-login-args (("%h") ("-l" "%u")))
428 (tramp-remote-sh "/bin/sh")
429 (tramp-copy-program "rcp")
430 (tramp-copy-args (("-p" "%k")))
431 (tramp-copy-keep-date t)
432 (tramp-password-end-of-line nil))
433 ("rsh" (tramp-login-program "rsh")
434 (tramp-login-args (("%h") ("-l" "%u")))
435 (tramp-remote-sh "/bin/sh")
436 (tramp-copy-program nil)
437 (tramp-copy-args nil)
438 (tramp-copy-keep-date nil)
439 (tramp-password-end-of-line nil))
440 ("ssh" (tramp-login-program "ssh")
441 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
443 (tramp-remote-sh "/bin/sh")
444 (tramp-copy-program nil)
445 (tramp-copy-args nil)
446 (tramp-copy-keep-date nil)
447 (tramp-password-end-of-line nil)
448 (tramp-gw-args (("-o"
449 "GlobalKnownHostsFile=/dev/null")
450 ("-o" "UserKnownHostsFile=/dev/null")
451 ("-o" "StrictHostKeyChecking=no")))
452 (tramp-default-port 22))
453 ("ssh1" (tramp-login-program "ssh")
454 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
456 (tramp-remote-sh "/bin/sh")
457 (tramp-copy-program nil)
458 (tramp-copy-args nil)
459 (tramp-copy-keep-date nil)
460 (tramp-password-end-of-line nil)
461 (tramp-gw-args (("-o"
462 "GlobalKnownHostsFile=/dev/null")
463 ("-o" "UserKnownHostsFile=/dev/null")
464 ("-o" "StrictHostKeyChecking=no")))
465 (tramp-default-port 22))
466 ("ssh2" (tramp-login-program "ssh")
467 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
469 (tramp-remote-sh "/bin/sh")
470 (tramp-copy-program nil)
471 (tramp-copy-args nil)
472 (tramp-copy-keep-date nil)
473 (tramp-password-end-of-line nil)
474 (tramp-gw-args (("-o"
475 "GlobalKnownHostsFile=/dev/null")
476 ("-o" "UserKnownHostsFile=/dev/null")
477 ("-o" "StrictHostKeyChecking=no")))
478 (tramp-default-port 22))
480 (tramp-login-program "ssh1")
481 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
483 (tramp-remote-sh "/bin/sh")
484 (tramp-copy-program nil)
485 (tramp-copy-args nil)
486 (tramp-copy-keep-date nil)
487 (tramp-password-end-of-line nil))
489 (tramp-login-program "ssh2")
490 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
492 (tramp-remote-sh "/bin/sh")
493 (tramp-copy-program nil)
494 (tramp-copy-args nil)
495 (tramp-copy-keep-date nil)
496 (tramp-password-end-of-line nil))
497 ("remsh" (tramp-login-program "remsh")
498 (tramp-login-args (("%h") ("-l" "%u")))
499 (tramp-remote-sh "/bin/sh")
500 (tramp-copy-program nil)
501 (tramp-copy-args nil)
502 (tramp-copy-keep-date nil)
503 (tramp-password-end-of-line nil))
505 (tramp-login-program "telnet")
506 (tramp-login-args (("%h") ("%p")))
507 (tramp-remote-sh "/bin/sh")
508 (tramp-copy-program nil)
509 (tramp-copy-args nil)
510 (tramp-copy-keep-date nil)
511 (tramp-password-end-of-line nil)
512 (tramp-default-port 23))
513 ("su" (tramp-login-program "su")
514 (tramp-login-args (("-") ("%u")))
515 (tramp-remote-sh "/bin/sh")
516 (tramp-copy-program nil)
517 (tramp-copy-args nil)
518 (tramp-copy-keep-date nil)
519 (tramp-password-end-of-line nil))
520 ("sudo" (tramp-login-program "sudo")
521 (tramp-login-args (("-u" "%u")
522 ("-s") ("-H") ("-p" "Password:")))
523 (tramp-remote-sh "/bin/sh")
524 (tramp-copy-program nil)
525 (tramp-copy-args nil)
526 (tramp-copy-keep-date nil)
527 (tramp-password-end-of-line nil))
528 ("scpc" (tramp-login-program "ssh")
529 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
530 ("-o" "ControlPath=%t.%%r@%%h:%%p")
531 ("-o" "ControlMaster=yes")
533 (tramp-remote-sh "/bin/sh")
534 (tramp-copy-program "scp")
535 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
536 ("-o" "ControlPath=%t.%%r@%%h:%%p")
537 ("-o" "ControlMaster=auto")))
538 (tramp-copy-keep-date t)
539 (tramp-password-end-of-line nil)
540 (tramp-gw-args (("-o"
541 "GlobalKnownHostsFile=/dev/null")
542 ("-o" "UserKnownHostsFile=/dev/null")
543 ("-o" "StrictHostKeyChecking=no")))
544 (tramp-default-port 22))
545 ("scpx" (tramp-login-program "ssh")
546 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
547 ("-e" "none" "-t" "-t" "/bin/sh")))
548 (tramp-remote-sh "/bin/sh")
549 (tramp-copy-program "scp")
550 (tramp-copy-args (("-p" "%k")))
551 (tramp-copy-keep-date t)
552 (tramp-password-end-of-line nil)
553 (tramp-gw-args (("-o"
554 "GlobalKnownHostsFile=/dev/null")
555 ("-o" "UserKnownHostsFile=/dev/null")
556 ("-o" "StrictHostKeyChecking=no")))
557 (tramp-default-port 22))
558 ("sshx" (tramp-login-program "ssh")
559 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
560 ("-e" "none" "-t" "-t" "/bin/sh")))
561 (tramp-remote-sh "/bin/sh")
562 (tramp-copy-program nil)
563 (tramp-copy-args nil)
564 (tramp-copy-keep-date nil)
565 (tramp-password-end-of-line nil)
566 (tramp-gw-args (("-o"
567 "GlobalKnownHostsFile=/dev/null")
568 ("-o" "UserKnownHostsFile=/dev/null")
569 ("-o" "StrictHostKeyChecking=no")))
570 (tramp-default-port 22))
572 (tramp-login-program "krlogin")
573 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
574 (tramp-remote-sh "/bin/sh")
575 (tramp-copy-program nil)
576 (tramp-copy-args nil)
577 (tramp-copy-keep-date nil)
578 (tramp-password-end-of-line nil))
579 ("plink" (tramp-login-program "plink")
580 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
582 (tramp-remote-sh "/bin/sh")
583 (tramp-copy-program nil)
584 (tramp-copy-args nil)
585 (tramp-copy-keep-date nil)
586 (tramp-password-end-of-line "xy") ;see docstring for "xy"
587 (tramp-default-port 22))
589 (tramp-login-program "plink")
590 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
592 (tramp-remote-sh "/bin/sh")
593 (tramp-copy-program nil)
594 (tramp-copy-args nil)
595 (tramp-copy-keep-date nil)
596 (tramp-password-end-of-line "xy") ;see docstring for "xy"
597 (tramp-default-port 22))
599 (tramp-login-program "plink")
600 ;; ("%h") must be a single element, see
601 ;; `tramp-compute-multi-hops'.
602 (tramp-login-args (("-load") ("%h") ("-t")
604 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
606 tramp-initial-end-of-output))
608 (tramp-remote-sh "/bin/sh")
609 (tramp-copy-program nil)
610 (tramp-copy-args nil)
611 (tramp-copy-keep-date nil)
612 (tramp-password-end-of-line nil))
613 ("pscp" (tramp-login-program "plink")
614 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
616 (tramp-remote-sh "/bin/sh")
617 (tramp-copy-program "pscp")
618 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
619 (tramp-copy-keep-date t)
620 (tramp-password-end-of-line "xy") ;see docstring for "xy"
621 (tramp-default-port 22))
622 ("psftp" (tramp-login-program "plink")
623 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
625 (tramp-remote-sh "/bin/sh")
626 (tramp-copy-program "pscp")
627 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
628 (tramp-copy-keep-date t)
629 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
630 ("fcp" (tramp-login-program "fsh")
631 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
632 (tramp-remote-sh "/bin/sh -i")
633 (tramp-copy-program "fcp")
634 (tramp-copy-args (("-p" "%k")))
635 (tramp-copy-keep-date t)
636 (tramp-password-end-of-line nil)))
637 "*Alist of methods for remote files.
638 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
639 Each NAME stands for a remote access method. Each PARAM is a
640 pair of the form (KEY VALUE). The following KEYs are defined:
642 This specifies the Bourne shell to use on the remote host. This
643 MUST be a Bourne-like shell. It is normally not necessary to set
644 this to any value other than \"/bin/sh\": Tramp wants to use a shell
645 which groks tilde expansion, but it can search for it. Also note
646 that \"/bin/sh\" exists on all Unixen, this might not be true for
647 the value that you decide to use. You Have Been Warned.
648 * `tramp-login-program'
649 This specifies the name of the program to use for logging in to the
650 remote host. This may be the name of rsh or a workalike program,
651 or the name of telnet or a workalike, or the name of su or a workalike.
653 This specifies the list of arguments to pass to the above
654 mentioned program. Please note that this is a list of list of arguments,
655 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
656 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
657 There are some patterns: \"%h\" in this list is replaced by the host
658 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
659 port number, and \"%%\" can be used to obtain a literal percent character.
660 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
661 expansion (i.e. no host or no user specified), this list is not used as
662 argument. By this, arguments like (\"-l\" \"%u\") are optional.
663 \"%t\" is replaced by the temporary file name produced with
664 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
665 parameter of a program, if exists.
666 * `tramp-copy-program'
667 This specifies the name of the program to use for remotely copying
668 the file; this might be the absolute filename of rcp or the name of
671 This specifies the list of parameters to pass to the above mentioned
672 program, the hints for `tramp-login-args' also apply here.
673 * `tramp-copy-keep-date'
674 This specifies whether the copying program when the preserves the
675 timestamp of the original file.
676 * `tramp-copy-keep-tmpfile'
677 This specifies whether a temporary local file shall be kept
678 for optimization reasons (useful for \"rsync\" methods).
679 * `tramp-copy-recursive'
680 Whether the operation copies directories recursively.
681 * `tramp-default-port'
682 The default port of a method is needed in case of gateway connections.
683 Additionally, it is used as indication which method is prepared for
686 As the attribute name says, additional arguments are specified here
687 when a method is applied via a gateway.
688 * `tramp-password-end-of-line'
689 This specifies the string to use for terminating the line after
690 submitting the password. If this method parameter is nil, then the
691 value of the normal variable `tramp-default-password-end-of-line'
692 is used. This parameter is necessary because the \"plink\" program
693 requires any two characters after sending the password. These do
694 not have to be newline or carriage return characters. Other login
695 programs are happy with just one character, the newline character.
696 We use \"xy\" as the value for methods using \"plink\".
698 What does all this mean? Well, you should specify `tramp-login-program'
699 for all methods; this program is used to log in to the remote site. Then,
700 there are two ways to actually transfer the files between the local and the
701 remote side. One way is using an additional rcp-like program. If you want
702 to do this, set `tramp-copy-program' in the method.
704 Another possibility for file transfer is inline transfer, i.e. the
705 file is passed through the same buffer used by `tramp-login-program'. In
706 this case, the file contents need to be protected since the
707 `tramp-login-program' might use escape codes or the connection might not
708 be eight-bit clean. Therefore, file contents are encoded for transit.
709 See the variables `tramp-local-coding-commands' and
710 `tramp-remote-coding-commands' for details.
712 So, to summarize: if the method is an out-of-band method, then you
713 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
714 inline method, then these two parameters should be nil. Methods which
715 are fit for gateways must have `tramp-default-port' at least.
719 When using `su' or `sudo' the phrase `open connection to a remote
720 host' sounds strange, but it is used nevertheless, for consistency.
721 No connection is opened to a remote host, but `su' or `sudo' is
722 started on the local host. You should specify a remote host
723 `localhost' or the name of the local host. Another host name is
724 useful only in combination with `tramp-default-proxies-alist'.")
726 (defcustom tramp-default-method
727 ;; An external copy method seems to be preferred, because it is much
728 ;; more performant for large files, and it hasn't too serious delays
729 ;; for small files. But it must be ensured that there aren't
730 ;; permanent password queries. Either a password agent like
731 ;; "ssh-agent" or "Pageant" shall run, or the optional
732 ;; password-cache.el or auth-sources.el packages shall be active for
733 ;; password caching. "scpc" would be another good choice because of
734 ;; the "ControlMaster" option, but this is a more modern alternative
735 ;; in OpenSSH 4, which cannot be taken as default.
737 ;; PuTTY is installed.
738 ((executable-find "pscp")
739 (if (or (fboundp 'password-read)
740 (fboundp 'auth-source-user-or-password)
741 ;; Pageant is running.
742 (tramp-compat-process-running-p "Pageant"))
745 ;; There is an ssh installation.
746 ((executable-find "scp")
747 (if (or (fboundp 'password-read)
748 (fboundp 'auth-source-user-or-password)
749 ;; ssh-agent is running.
750 (getenv "SSH_AUTH_SOCK")
751 (getenv "SSH_AGENT_PID"))
756 "*Default method to use for transferring files.
757 See `tramp-methods' for possibilities.
758 Also see `tramp-default-method-alist'."
762 (defcustom tramp-default-method-alist
763 '(("\\`localhost\\'" "\\`root\\'" "su"))
764 "*Default method to use for specific host/user pairs.
765 This is an alist of items (HOST USER METHOD). The first matching item
766 specifies the method to use for a file name which does not specify a
767 method. HOST and USER are regular expressions or nil, which is
768 interpreted as a regular expression which always matches. If no entry
769 matches, the variable `tramp-default-method' takes effect.
771 If the file name does not specify the user, lookup is done using the
772 empty string for the user name.
774 See `tramp-methods' for a list of possibilities for METHOD."
776 :type '(repeat (list (regexp :tag "Host regexp")
777 (regexp :tag "User regexp")
778 (string :tag "Method"))))
780 (defcustom tramp-default-user
782 "*Default user to use for transferring files.
783 It is nil by default; otherwise settings in configuration files like
784 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
786 This variable is regarded as obsolete, and will be removed soon."
788 :type '(choice (const nil) string))
790 (defcustom tramp-default-user-alist
791 `(("\\`su\\(do\\)?\\'" nil "root")
792 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
793 nil ,(user-login-name)))
794 "*Default user to use for specific method/host pairs.
795 This is an alist of items (METHOD HOST USER). The first matching item
796 specifies the user to use for a file name which does not specify a
797 user. METHOD and USER are regular expressions or nil, which is
798 interpreted as a regular expression which always matches. If no entry
799 matches, the variable `tramp-default-user' takes effect.
801 If the file name does not specify the method, lookup is done using the
802 empty string for the method name."
804 :type '(repeat (list (regexp :tag "Method regexp")
805 (regexp :tag "Host regexp")
806 (string :tag "User"))))
808 (defcustom tramp-default-host
810 "*Default host to use for transferring files.
811 Useful for su and sudo methods mostly."
815 (defcustom tramp-default-proxies-alist nil
816 "*Route to be followed for specific host/user pairs.
817 This is an alist of items (HOST USER PROXY). The first matching
818 item specifies the proxy to be passed for a file name located on
819 a remote target matching USER@HOST. HOST and USER are regular
820 expressions. PROXY must be a Tramp filename without a localname
821 part. Method and user name on PROXY are optional, which is
822 interpreted with the default values. PROXY can contain the
823 patterns %h and %u, which are replaced by the strings matching
824 HOST or USER, respectively.
826 HOST, USER or PROXY could also be Lisp forms, which will be
827 evaluated. The result must be a string or nil, which is
828 interpreted as a regular expression which always matches."
830 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
831 (choice :tag "User regexp" regexp sexp)
832 (choice :tag "Proxy remote name" string (const nil)))))
834 (defconst tramp-local-host-regexp
836 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
837 "*Host names which are regarded as local host.")
839 (defconst tramp-completion-function-alist-rsh
840 '((tramp-parse-rhosts "/etc/hosts.equiv")
841 (tramp-parse-rhosts "~/.rhosts"))
842 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
844 (defconst tramp-completion-function-alist-ssh
845 '((tramp-parse-rhosts "/etc/hosts.equiv")
846 (tramp-parse-rhosts "/etc/shosts.equiv")
847 (tramp-parse-shosts "/etc/ssh_known_hosts")
848 (tramp-parse-sconfig "/etc/ssh_config")
849 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
850 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
851 (tramp-parse-rhosts "~/.rhosts")
852 (tramp-parse-rhosts "~/.shosts")
853 (tramp-parse-shosts "~/.ssh/known_hosts")
854 (tramp-parse-sconfig "~/.ssh/config")
855 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
856 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
857 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
859 (defconst tramp-completion-function-alist-telnet
860 '((tramp-parse-hosts "/etc/hosts"))
861 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
863 (defconst tramp-completion-function-alist-su
864 '((tramp-parse-passwd "/etc/passwd"))
865 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
867 (defconst tramp-completion-function-alist-putty
869 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
870 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
872 (defvar tramp-completion-function-alist nil
873 "*Alist of methods for remote files.
874 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
875 Each NAME stands for a remote access method. Each PAIR is of the form
876 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
877 names from FILE for completion. The following predefined FUNCTIONs exists:
879 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
880 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
881 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
882 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
883 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
884 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
885 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
886 * `tramp-parse-netrc' for \"~/.netrc\" like files.
887 * `tramp-parse-putty' for PuTTY registry keys.
889 FUNCTION can also be a customer defined function. For more details see
892 (eval-after-load "tramp"
894 (tramp-set-completion-function
895 "rcp" tramp-completion-function-alist-rsh)
896 (tramp-set-completion-function
897 "scp" tramp-completion-function-alist-ssh)
898 (tramp-set-completion-function
899 "scp1" tramp-completion-function-alist-ssh)
900 (tramp-set-completion-function
901 "scp2" tramp-completion-function-alist-ssh)
902 (tramp-set-completion-function
903 "scp1_old" tramp-completion-function-alist-ssh)
904 (tramp-set-completion-function
905 "scp2_old" tramp-completion-function-alist-ssh)
906 (tramp-set-completion-function
907 "rsync" tramp-completion-function-alist-ssh)
908 (tramp-set-completion-function
909 "rsyncc" tramp-completion-function-alist-ssh)
910 (tramp-set-completion-function
911 "remcp" tramp-completion-function-alist-rsh)
912 (tramp-set-completion-function
913 "rsh" tramp-completion-function-alist-rsh)
914 (tramp-set-completion-function
915 "ssh" tramp-completion-function-alist-ssh)
916 (tramp-set-completion-function
917 "ssh1" tramp-completion-function-alist-ssh)
918 (tramp-set-completion-function
919 "ssh2" tramp-completion-function-alist-ssh)
920 (tramp-set-completion-function
921 "ssh1_old" tramp-completion-function-alist-ssh)
922 (tramp-set-completion-function
923 "ssh2_old" tramp-completion-function-alist-ssh)
924 (tramp-set-completion-function
925 "remsh" tramp-completion-function-alist-rsh)
926 (tramp-set-completion-function
927 "telnet" tramp-completion-function-alist-telnet)
928 (tramp-set-completion-function
929 "su" tramp-completion-function-alist-su)
930 (tramp-set-completion-function
931 "sudo" tramp-completion-function-alist-su)
932 (tramp-set-completion-function
933 "scpx" tramp-completion-function-alist-ssh)
934 (tramp-set-completion-function
935 "sshx" tramp-completion-function-alist-ssh)
936 (tramp-set-completion-function
937 "krlogin" tramp-completion-function-alist-rsh)
938 (tramp-set-completion-function
939 "plink" tramp-completion-function-alist-ssh)
940 (tramp-set-completion-function
941 "plink1" tramp-completion-function-alist-ssh)
942 (tramp-set-completion-function
943 "plinkx" tramp-completion-function-alist-putty)
944 (tramp-set-completion-function
945 "pscp" tramp-completion-function-alist-ssh)
946 (tramp-set-completion-function
947 "fcp" tramp-completion-function-alist-ssh)))
949 (defconst tramp-echo-mark-marker "_echo"
950 "String marker to surround echoed commands.")
952 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
953 "String length of `tramp-echo-mark-marker'.")
955 (defconst tramp-echo-mark
956 (concat tramp-echo-mark-marker
957 (make-string tramp-echo-mark-marker-length ?\b))
958 "String mark to be transmitted around shell commands.
959 Used to separate their echo from the output they produce. This
960 will only be used if we cannot disable remote echo via stty.
961 This string must have no effect on the remote shell except for
962 producing some echo which can later be detected by
963 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
964 followed by an equal number of backspaces to erase them will
967 (defconst tramp-echoed-echo-mark-regexp
968 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
969 tramp-echo-mark-marker tramp-echo-mark-marker-length)
970 "Regexp which matches `tramp-echo-mark' as it gets echoed by
973 (defcustom tramp-rsh-end-of-line "\n"
974 "*String used for end of line in rsh connections.
975 I don't think this ever needs to be changed, so please tell me about it
976 if you need to change this.
977 Also see the method parameter `tramp-password-end-of-line' and the normal
978 variable `tramp-default-password-end-of-line'."
982 (defcustom tramp-default-password-end-of-line
983 tramp-rsh-end-of-line
984 "*String used for end of line after sending a password.
985 This variable provides the default value for the method parameter
986 `tramp-password-end-of-line', see `tramp-methods' for more details.
988 It seems that people using plink under Windows need to send
989 \"\\r\\n\" (carriage-return, then newline) after a password, but just
990 \"\\n\" after all other lines. This variable can be used for the
991 password, see `tramp-rsh-end-of-line' for the other cases.
993 The default value is to use the same value as `tramp-rsh-end-of-line'."
997 ;; "getconf PATH" yields:
998 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
999 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
1000 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1001 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1002 (defcustom tramp-remote-path
1003 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1004 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1005 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1006 "*List of directories to search for executables on remote host.
1007 For every remote host, this variable will be set buffer local,
1008 keeping the list of existing directories on that host.
1010 You can use `~' in this list, but when searching for a shell which groks
1011 tilde expansion, all directory names starting with `~' will be ignored.
1013 `Default Directories' represent the list of directories given by
1014 the command \"getconf PATH\". It is recommended to use this
1015 entry on top of this list, because these are the default
1016 directories for POSIX compatible commands.
1018 `Private Directories' are the settings of the $PATH environment,
1019 as given in your `~/.profile'."
1021 :type '(repeat (choice
1022 (const :tag "Default Directories" tramp-default-remote-path)
1023 (const :tag "Private Directories" tramp-own-remote-path)
1024 (string :tag "Directory"))))
1026 (defcustom tramp-remote-process-environment
1027 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1028 ,(format "TERM=%s" tramp-terminal-type)
1029 "EMACS=t" ;; Deprecated.
1030 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
1031 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1032 "autocorrect=" "correct=")
1034 "*List of environment variables to be set on the remote host.
1036 Each element should be a string of the form ENVVARNAME=VALUE. An
1037 entry ENVVARNAME= diables the corresponding environment variable,
1038 which might have been set in the init files like ~/.profile.
1040 Special handling is applied to the PATH environment, which should
1041 not be set here. Instead of, it should be set via `tramp-remote-path'."
1043 :type '(repeat string))
1045 (defcustom tramp-login-prompt-regexp
1046 ".*ogin\\( .*\\)?: *"
1047 "*Regexp matching login-like prompts.
1048 The regexp should match at end of buffer.
1050 Sometimes the prompt is reported to look like \"login as:\"."
1054 (defcustom tramp-shell-prompt-pattern
1055 ;; Allow a prompt to start right after a ^M since it indeed would be
1056 ;; displayed at the beginning of the line (and Zsh uses it).
1057 "\\(?:^\\|\r\\)[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
1058 "Regexp to match prompts from remote shell.
1059 Normally, Tramp expects you to configure `shell-prompt-pattern'
1060 correctly, but sometimes it happens that you are connecting to a
1061 remote host which sends a different kind of shell prompt. Therefore,
1062 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1063 and also things matched by this variable. The default value of this
1064 variable is similar to the default value of `shell-prompt-pattern',
1065 which should work well in many cases.
1067 This regexp must match both `tramp-initial-end-of-output' and
1068 `tramp-end-of-output'."
1072 (defcustom tramp-password-prompt-regexp
1073 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1074 "*Regexp matching password-like prompts.
1075 The regexp should match at end of buffer.
1077 The `sudo' program appears to insert a `^@' character into the prompt."
1081 (defcustom tramp-wrong-passwd-regexp
1083 ;; These strings should be on the last line
1084 (regexp-opt '("Permission denied"
1087 "Connection refused"
1089 "Timeout, server not responding."
1091 "Name or service not known"
1092 "Host key verification failed."
1093 "No supported authentication methods left to try!") t)
1097 ;; Here comes a list of regexes, separated by \\|
1098 "Received signal [0-9]+"
1100 "*Regexp matching a `login failed' message.
1101 The regexp should match at end of buffer."
1105 (defcustom tramp-yesno-prompt-regexp
1107 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1109 "Regular expression matching all yes/no queries which need to be confirmed.
1110 The confirmation should be done with yes or no.
1111 The regexp should match at end of buffer.
1112 See also `tramp-yn-prompt-regexp'."
1116 (defcustom tramp-yn-prompt-regexp
1118 (regexp-opt '("Store key in cache? (y/n)"
1119 "Update cached key? (y/n, Return cancels connection)") t)
1121 "Regular expression matching all y/n queries which need to be confirmed.
1122 The confirmation should be done with y or n.
1123 The regexp should match at end of buffer.
1124 See also `tramp-yesno-prompt-regexp'."
1128 (defcustom tramp-terminal-prompt-regexp
1132 "Terminal type\\? \\[.*\\]"
1134 "Regular expression matching all terminal setting prompts.
1135 The regexp should match at end of buffer.
1136 The answer will be provided by `tramp-action-terminal', which see."
1140 (defcustom tramp-operation-not-permitted-regexp
1141 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1142 (regexp-opt '("Operation not permitted") t))
1143 "Regular expression matching keep-date problems in (s)cp operations.
1144 Copying has been performed successfully already, so this message can
1149 (defcustom tramp-copy-failed-regexp
1151 (regexp-opt '("Permission denied"
1152 "not a regular file"
1154 "No such file or directory") t)
1156 "Regular expression matching copy problems in (s)cp operations."
1160 (defcustom tramp-process-alive-regexp
1162 "Regular expression indicating a process has finished.
1163 In fact this expression is empty by intention, it will be used only to
1164 check regularly the status of the associated process.
1165 The answer will be provided by `tramp-action-process-alive',
1166 `tramp-action-out-of-band', which see."
1170 (defcustom tramp-temp-name-prefix "tramp."
1171 "*Prefix to use for temporary files.
1172 If this is a relative file name (such as \"tramp.\"), it is considered
1173 relative to the directory name returned by the function
1174 `tramp-compat-temporary-file-directory' (which see). It may also be an
1175 absolute file name; don't forget to include a prefix for the filename
1180 (defconst tramp-temp-buffer-name " *tramp temp*"
1181 "Buffer name for a temporary buffer.
1182 It shall be used in combination with `generate-new-buffer-name'.")
1184 (defvar tramp-temp-buffer-file-name nil
1185 "File name of a persistent local temporary file.
1186 Useful for \"rsync\" like methods.")
1187 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1189 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1190 "*Alist specifying extra arguments to pass to the remote shell.
1191 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1192 matching the shell file name and ARGS is a string specifying the
1195 This variable is only used when Tramp needs to start up another shell
1196 for tilde expansion. The extra arguments should typically prevent the
1197 shell from reading its init file."
1199 ;; This might be the wrong way to test whether the widget type
1200 ;; `alist' is available. Who knows the right way to test it?
1201 :type (if (get 'alist 'widget-type)
1202 '(alist :key-type string :value-type string)
1203 '(repeat (cons string string))))
1205 ;; XEmacs is distributed with few Lisp packages. Further packages are
1206 ;; installed using EFS. If we use a unified filename format, then
1207 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1208 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1209 ;; just like before.) Another reason for using a separate filename
1210 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1211 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1212 ;; the other places.
1214 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1216 (defcustom tramp-syntax
1217 (if (featurep 'xemacs) 'sep 'ftp)
1218 "Tramp filename syntax to be used.
1220 It can have the following values:
1222 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1223 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1224 'url -- URL-like syntax."
1226 :type (if (featurep 'xemacs)
1227 '(choice (const :tag "EFS" ftp)
1228 (const :tag "XEmacs" sep)
1229 (const :tag "URL" url))
1230 '(choice (const :tag "Ange-FTP" ftp)
1231 (const :tag "URL" url))))
1233 (defconst tramp-prefix-format
1234 (cond ((equal tramp-syntax 'ftp) "/")
1235 ((equal tramp-syntax 'sep) "/[")
1236 ((equal tramp-syntax 'url) "/")
1237 (t (error "Wrong `tramp-syntax' defined")))
1238 "*String matching the very beginning of Tramp file names.
1239 Used in `tramp-make-tramp-file-name'.")
1241 (defconst tramp-prefix-regexp
1242 (concat "^" (regexp-quote tramp-prefix-format))
1243 "*Regexp matching the very beginning of Tramp file names.
1244 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1246 (defconst tramp-method-regexp
1248 "*Regexp matching methods identifiers.")
1250 (defconst tramp-postfix-method-format
1251 (cond ((equal tramp-syntax 'ftp) ":")
1252 ((equal tramp-syntax 'sep) "/")
1253 ((equal tramp-syntax 'url) "://")
1254 (t (error "Wrong `tramp-syntax' defined")))
1255 "*String matching delimeter between method and user or host names.
1256 Used in `tramp-make-tramp-file-name'.")
1258 (defconst tramp-postfix-method-regexp
1259 (regexp-quote tramp-postfix-method-format)
1260 "*Regexp matching delimeter between method and user or host names.
1261 Derived from `tramp-postfix-method-format'.")
1263 (defconst tramp-user-regexp
1265 "*Regexp matching user names.")
1267 (defconst tramp-prefix-domain-format "%"
1268 "*String matching delimeter between user and domain names.")
1270 (defconst tramp-prefix-domain-regexp
1271 (regexp-quote tramp-prefix-domain-format)
1272 "*Regexp matching delimeter between user and domain names.
1273 Derived from `tramp-prefix-domain-format'.")
1275 (defconst tramp-domain-regexp
1277 "*Regexp matching domain names.")
1279 (defconst tramp-user-with-domain-regexp
1280 (concat "\\(" tramp-user-regexp "\\)"
1281 tramp-prefix-domain-regexp
1282 "\\(" tramp-domain-regexp "\\)")
1283 "*Regexp matching user names with domain names.")
1285 (defconst tramp-postfix-user-format
1287 "*String matching delimeter between user and host names.
1288 Used in `tramp-make-tramp-file-name'.")
1290 (defconst tramp-postfix-user-regexp
1291 (regexp-quote tramp-postfix-user-format)
1292 "*Regexp matching delimeter between user and host names.
1293 Derived from `tramp-postfix-user-format'.")
1295 (defconst tramp-host-regexp
1297 "*Regexp matching host names.")
1299 (defconst tramp-prefix-ipv6-format
1300 (cond ((equal tramp-syntax 'ftp) "[")
1301 ((equal tramp-syntax 'sep) "")
1302 ((equal tramp-syntax 'url) "[")
1303 (t (error "Wrong `tramp-syntax' defined")))
1304 "*String matching left hand side of IPv6 addresses.
1305 Used in `tramp-make-tramp-file-name'.")
1307 (defconst tramp-prefix-ipv6-regexp
1308 (regexp-quote tramp-prefix-ipv6-format)
1309 "*Regexp matching left hand side of IPv6 addresses.
1310 Derived from `tramp-prefix-ipv6-format'.")
1312 ;; The following regexp is a bit sloppy. But it shall serve our
1313 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1314 ;; "::ffff:192.168.0.1".
1315 (defconst tramp-ipv6-regexp
1316 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1317 "*Regexp matching IPv6 addresses.")
1319 (defconst tramp-postfix-ipv6-format
1320 (cond ((equal tramp-syntax 'ftp) "]")
1321 ((equal tramp-syntax 'sep) "")
1322 ((equal tramp-syntax 'url) "]")
1323 (t (error "Wrong `tramp-syntax' defined")))
1324 "*String matching right hand side of IPv6 addresses.
1325 Used in `tramp-make-tramp-file-name'.")
1327 (defconst tramp-postfix-ipv6-regexp
1328 (regexp-quote tramp-postfix-ipv6-format)
1329 "*Regexp matching right hand side of IPv6 addresses.
1330 Derived from `tramp-postfix-ipv6-format'.")
1332 (defconst tramp-prefix-port-format
1333 (cond ((equal tramp-syntax 'ftp) "#")
1334 ((equal tramp-syntax 'sep) "#")
1335 ((equal tramp-syntax 'url) ":")
1336 (t (error "Wrong `tramp-syntax' defined")))
1337 "*String matching delimeter between host names and port numbers.")
1339 (defconst tramp-prefix-port-regexp
1340 (regexp-quote tramp-prefix-port-format)
1341 "*Regexp matching delimeter between host names and port numbers.
1342 Derived from `tramp-prefix-port-format'.")
1344 (defconst tramp-port-regexp
1346 "*Regexp matching port numbers.")
1348 (defconst tramp-host-with-port-regexp
1349 (concat "\\(" tramp-host-regexp "\\)"
1350 tramp-prefix-port-regexp
1351 "\\(" tramp-port-regexp "\\)")
1352 "*Regexp matching host names with port numbers.")
1354 (defconst tramp-postfix-host-format
1355 (cond ((equal tramp-syntax 'ftp) ":")
1356 ((equal tramp-syntax 'sep) "]")
1357 ((equal tramp-syntax 'url) "")
1358 (t (error "Wrong `tramp-syntax' defined")))
1359 "*String matching delimeter between host names and localnames.
1360 Used in `tramp-make-tramp-file-name'.")
1362 (defconst tramp-postfix-host-regexp
1363 (regexp-quote tramp-postfix-host-format)
1364 "*Regexp matching delimeter between host names and localnames.
1365 Derived from `tramp-postfix-host-format'.")
1367 (defconst tramp-localname-regexp
1369 "*Regexp matching localnames.")
1371 ;; File name format.
1373 (defconst tramp-file-name-structure
1377 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1378 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1379 "\\(" "\\(" tramp-host-regexp
1381 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1382 tramp-postfix-ipv6-regexp "\\)"
1383 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1384 tramp-postfix-host-regexp
1385 "\\(" tramp-localname-regexp "\\)")
1388 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1389 the Tramp file name structure.
1391 The first element REGEXP is a regular expression matching a Tramp file
1392 name. The regex should contain parentheses around the method name,
1393 the user name, the host name, and the file name parts.
1395 The second element METHOD is a number, saying which pair of
1396 parentheses matches the method name. The third element USER is
1397 similar, but for the user name. The fourth element HOST is similar,
1398 but for the host name. The fifth element FILE is for the file name.
1399 These numbers are passed directly to `match-string', which see. That
1400 means the opening parentheses are counted to identify the pair.
1402 See also `tramp-file-name-regexp'.")
1405 (defconst tramp-file-name-regexp-unified
1406 "\\`/\\([^[/:]+\\|[^/]+]\\):"
1407 "Value for `tramp-file-name-regexp' for unified remoting.
1408 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1409 Tramp. See `tramp-file-name-structure' for more explanations.")
1412 (defconst tramp-file-name-regexp-separate
1414 "Value for `tramp-file-name-regexp' for separate remoting.
1415 XEmacs uses a separate filename syntax for Tramp and EFS.
1416 See `tramp-file-name-structure' for more explanations.")
1419 (defconst tramp-file-name-regexp-url
1421 "Value for `tramp-file-name-regexp' for URL-like remoting.
1422 See `tramp-file-name-structure' for more explanations.")
1425 (defconst tramp-file-name-regexp
1426 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1427 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1428 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1429 (t (error "Wrong `tramp-syntax' defined")))
1430 "*Regular expression matching file names handled by Tramp.
1431 This regexp should match Tramp file names but no other file names.
1432 When tramp.el is loaded, this regular expression is prepended to
1433 `file-name-handler-alist', and that is searched sequentially. Thus,
1434 if the Tramp entry appears rather early in the `file-name-handler-alist'
1435 and is a bit too general, then some files might be considered Tramp
1436 files which are not really Tramp files.
1438 Please note that the entry in `file-name-handler-alist' is made when
1439 this file \(tramp.el\) is loaded. This means that this variable must be set
1440 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1441 updated after changing this variable.
1443 Also see `tramp-file-name-structure'.")
1446 (defconst tramp-root-regexp
1447 (if (memq system-type '(cygwin windows-nt))
1448 "\\`\\([a-zA-Z]:\\)?/"
1450 "Beginning of an incomplete Tramp file name.
1451 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1452 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1455 (defconst tramp-completion-file-name-regexp-unified
1456 (concat tramp-root-regexp "[^/]*\\'")
1457 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1458 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1459 See `tramp-file-name-structure' for more explanations.")
1462 (defconst tramp-completion-file-name-regexp-separate
1463 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1464 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1465 XEmacs uses a separate filename syntax for Tramp and EFS.
1466 See `tramp-file-name-structure' for more explanations.")
1469 (defconst tramp-completion-file-name-regexp-url
1470 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1471 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1472 See `tramp-file-name-structure' for more explanations.")
1475 (defconst tramp-completion-file-name-regexp
1476 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1477 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1478 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1479 (t (error "Wrong `tramp-syntax' defined")))
1480 "*Regular expression matching file names handled by Tramp completion.
1481 This regexp should match partial Tramp file names only.
1483 Please note that the entry in `file-name-handler-alist' is made when
1484 this file (tramp.el) is loaded. This means that this variable must be set
1485 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1486 updated after changing this variable.
1488 Also see `tramp-file-name-structure'.")
1490 (defconst tramp-actions-before-shell
1491 '((tramp-login-prompt-regexp tramp-action-login)
1492 (tramp-password-prompt-regexp tramp-action-password)
1493 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1494 (shell-prompt-pattern tramp-action-succeed)
1495 (tramp-shell-prompt-pattern tramp-action-succeed)
1496 (tramp-yesno-prompt-regexp tramp-action-yesno)
1497 (tramp-yn-prompt-regexp tramp-action-yn)
1498 (tramp-terminal-prompt-regexp tramp-action-terminal)
1499 (tramp-process-alive-regexp tramp-action-process-alive))
1500 "List of pattern/action pairs.
1501 Whenever a pattern matches, the corresponding action is performed.
1502 Each item looks like (PATTERN ACTION).
1504 The PATTERN should be a symbol, a variable. The value of this
1505 variable gives the regular expression to search for. Note that the
1506 regexp must match at the end of the buffer, \"\\'\" is implicitly
1509 The ACTION should also be a symbol, but a function. When the
1510 corresponding PATTERN matches, the ACTION function is called.")
1512 (defconst tramp-actions-copy-out-of-band
1513 '((tramp-password-prompt-regexp tramp-action-password)
1514 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1515 (tramp-copy-failed-regexp tramp-action-permission-denied)
1516 (tramp-process-alive-regexp tramp-action-out-of-band))
1517 "List of pattern/action pairs.
1518 This list is used for copying/renaming with out-of-band methods.
1520 See `tramp-actions-before-shell' for more info.")
1522 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1523 ;; known to have a bug in `process-send-string'; some ssh connections appear
1524 ;; to drop bytes when data is sent too quickly. There is also a connection
1525 ;; buffer local variable, which is computed depending on remote host properties
1526 ;; when `tramp-chunksize' is zero or nil.
1527 (defcustom tramp-chunksize
1528 (when (and (not (featurep 'xemacs))
1529 (memq system-type '(hpux)))
1531 ;; Parentheses in docstring starting at beginning of line are escaped.
1532 ;; Fontification is messed up when
1533 ;; `open-paren-in-column-0-is-defun-start' set to t.
1534 "*If non-nil, chunksize for sending input to local process.
1535 It is necessary only on systems which have a buggy `process-send-string'
1536 implementation. The necessity, whether this variable must be set, can be
1537 checked via the following code:
1540 (let* ((user \"xxx\") (host \"yyy\")
1542 (sent init) (received init))
1543 (while (= sent received)
1544 (setq sent (+ sent step))
1546 (let ((proc (start-process (buffer-name) (current-buffer)
1547 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1548 (when (memq (process-status proc) '(run open))
1549 (process-send-string proc (make-string sent ?\\ ))
1550 (process-send-eof proc)
1551 (process-send-eof proc))
1552 (while (not (progn (goto-char (point-min))
1553 (re-search-forward \"\\\\w+\" (point-max) t)))
1554 (accept-process-output proc 1))
1555 (when (memq (process-status proc) '(run open))
1556 (setq received (string-to-number (match-string 0)))
1557 (delete-process proc)
1558 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1560 (if (> sent (+ init step))
1561 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1563 (message \"Test does not work\")
1564 (display-buffer (current-buffer))
1567 In the Emacs normally running Tramp, evaluate the above code
1568 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1569 respectively\). You can do this, for example, by pasting it into
1570 the `*scratch*' buffer and then hitting C-j with the cursor after the
1571 last closing parenthesis. Note that it works only if you have configured
1572 \"ssh\" to run without password query, see ssh-agent\(1\).
1574 You will see the number of bytes sent successfully to the remote host.
1575 If that number exceeds 1000, you can stop the execution by hitting
1576 C-g, because your Emacs is likely clean.
1578 When it is necessary to set `tramp-chunksize', you might consider to
1579 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1580 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
1583 If your Emacs is buggy, the code stops and gives you an indication
1584 about the value `tramp-chunksize' should be set. Maybe you could just
1585 experiment a bit, e.g. changing the values of `init' and `step'
1586 in the third line of the code.
1588 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1589 this variable to be set as well."
1591 :type '(choice (const nil) integer))
1593 ;; Logging in to a remote host normally requires obtaining a pty. But
1594 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1595 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1596 ;; for an override of the system default.
1597 (defcustom tramp-process-connection-type t
1598 "Overrides `process-connection-type' for connections from Tramp.
1599 Tramp binds process-connection-type to the value given here before
1600 opening a connection to a remote host."
1602 :type '(choice (const nil) (const t) (const pty)))
1604 (defcustom tramp-completion-reread-directory-timeout 10
1605 "Defines seconds since last remote command before rereading a directory.
1606 A remote directory might have changed its contents. In order to
1607 make it visible during file name completion in the minibuffer,
1608 Tramp flushes its cache and rereads the directory contents when
1609 more than `tramp-completion-reread-directory-timeout' seconds
1610 have been gone since last remote command execution. A value of 0
1611 would require an immediate reread during filename completion, nil
1612 means to use always cached values for the directory contents."
1614 :type '(choice (const nil) integer))
1616 ;;; Internal Variables:
1618 (defvar tramp-current-method nil
1619 "Connection method for this *tramp* buffer.")
1621 (defvar tramp-current-user nil
1622 "Remote login name for this *tramp* buffer.")
1624 (defvar tramp-current-host nil
1625 "Remote host for this *tramp* buffer.")
1627 (defconst tramp-uudecode
1628 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1630 rm -f /tmp/tramp.$$"
1631 "Shell function to implement `uudecode' to standard output.
1632 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1633 for this or `uudecode -p', but some systems don't, and for them
1634 we have this shell function.")
1636 (defconst tramp-perl-file-truename
1639 use Cwd \"realpath\";
1642 my ($volume, @dirs) = @_;
1643 my $real = realpath(File::Spec->catpath(
1644 $volume, File::Spec->catdir(@dirs), \"\"));
1646 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1647 return ($vol, File::Spec->splitdir($dir));
1650 my $last = pop(@dirs);
1651 ($volume, @dirs) = recursive($volume, @dirs);
1653 return ($volume, @dirs);
1657 $result = realpath($ARGV[0]);
1659 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1660 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1662 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1665 if ($ARGV[0] =~ /\\/$/) {
1666 $result = $result . \"/\";
1669 print \"\\\"$result\\\"\\n\";
1670 ' \"$1\" 2>/dev/null"
1671 "Perl script to produce output suitable for use with `file-truename'
1672 on the remote file system.
1673 Escape sequence %s is replaced with name of Perl binary.
1674 This string is passed to `format', so percent characters need to be doubled.")
1676 (defconst tramp-perl-file-name-all-completions
1686 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1687 @files = readdir(d); closedir(d);
1688 foreach $f (@files) {
1689 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1690 if (-d \"$ARGV[0]/$f\") {
1699 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1700 "Perl script to produce output suitable for use with
1701 `file-name-all-completions' on the remote file system. Escape
1702 sequence %s is replaced with name of Perl binary. This string is
1703 passed to `format', so percent characters need to be doubled.")
1705 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1706 ;; output. If you are hacking on this, note that you get *no* output
1707 ;; unless this spits out a complete line, including the '\n' at the
1709 ;; The device number is returned as "-1", because there will be a virtual
1710 ;; device number set in `tramp-handle-file-attributes'.
1711 (defconst tramp-perl-file-attributes
1713 @stat = lstat($ARGV[0]);
1718 if (($stat[2] & 0170000) == 0120000)
1720 $type = readlink($ARGV[0]);
1721 $type = \"\\\"$type\\\"\";
1723 elsif (($stat[2] & 0170000) == 040000)
1731 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1732 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1734 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1739 $stat[8] >> 16 & 0xffff,
1741 $stat[9] >> 16 & 0xffff,
1743 $stat[10] >> 16 & 0xffff,
1747 $stat[1] >> 16 & 0xffff,
1749 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1750 "Perl script to produce output suitable for use with `file-attributes'
1751 on the remote file system.
1752 Escape sequence %s is replaced with name of Perl binary.
1753 This string is passed to `format', so percent characters need to be doubled.")
1755 (defconst tramp-perl-directory-files-and-attributes
1757 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1758 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1759 @list = readdir(DIR);
1763 for($i = 0; $i < $n; $i++)
1765 $filename = $list[$i];
1766 @stat = lstat($filename);
1767 if (($stat[2] & 0170000) == 0120000)
1769 $type = readlink($filename);
1770 $type = \"\\\"$type\\\"\";
1772 elsif (($stat[2] & 0170000) == 040000)
1780 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1781 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1783 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1789 $stat[8] >> 16 & 0xffff,
1791 $stat[9] >> 16 & 0xffff,
1793 $stat[10] >> 16 & 0xffff,
1797 $stat[1] >> 16 & 0xffff,
1799 $stat[0] >> 16 & 0xffff,
1802 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1803 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1805 Escape sequence %s is replaced with name of Perl binary.
1806 This string is passed to `format', so percent characters need to be doubled.")
1808 ;; ;; These two use uu encoding.
1809 ;; (defvar tramp-perl-encode "%s -e'\
1810 ;; print qq(begin 644 xxx\n);
1813 ;; while (read(STDIN, $s, 45)) {
1814 ;; print pack(q(u), $s);
1819 ;; "Perl program to use for encoding a file.
1820 ;; Escape sequence %s is replaced with name of Perl binary.")
1822 ;; (defvar tramp-perl-decode "%s -ne '
1823 ;; print unpack q(u), $_;
1825 ;; "Perl program to use for decoding a file.
1826 ;; Escape sequence %s is replaced with name of Perl binary.")
1828 ;; These two use base64 encoding.
1829 (defconst tramp-perl-encode-with-module
1830 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1831 "Perl program to use for encoding a file.
1832 Escape sequence %s is replaced with name of Perl binary.
1833 This string is passed to `format', so percent characters need to be doubled.
1834 This implementation requires the MIME::Base64 Perl module to be installed
1835 on the remote host.")
1837 (defconst tramp-perl-decode-with-module
1838 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1839 "Perl program to use for decoding a file.
1840 Escape sequence %s is replaced with name of Perl binary.
1841 This string is passed to `format', so percent characters need to be doubled.
1842 This implementation requires the MIME::Base64 Perl module to be installed
1843 on the remote host.")
1845 (defconst tramp-perl-encode
1847 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1848 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1849 # Free Software Foundation, Inc.
1854 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1855 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1860 # We read in chunks of 54 bytes, to generate output lines
1861 # of 72 chars (plus end of line)
1864 while (my $data = <STDIN>) {
1867 # Only for the last chunk, and only if did not fill the last three-byte packet
1869 my $mod = length($data) %% 3;
1870 $pad = q(=) x (3 - $mod) if $mod;
1873 # Not the fastest method, but it is simple: unpack to binary string, split
1874 # by groups of 6 bits and convert back from binary to byte; then map into
1875 # the translation table
1879 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1883 "Perl program to use for encoding a file.
1884 Escape sequence %s is replaced with name of Perl binary.
1885 This string is passed to `format', so percent characters need to be doubled.")
1887 (defconst tramp-perl-decode
1889 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1890 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1891 # Free Software Foundation, Inc.
1896 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1897 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1900 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1904 # We are going to accumulate into $pending to accept any line length
1905 # (we do not check they are <= 76 chars as the RFC says)
1908 while (my $data = <STDIN>) {
1911 # If we find one or two =, we have reached the end and
1912 # any following data is to be discarded
1913 my $finished = $data =~ s/(==?).*/$1/;
1916 my $len = length($pending);
1917 my $chunk = substr($pending, 0, $len & ~3);
1918 $pending = substr($pending, $len & ~3 + 1);
1920 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1921 # split in 8-bit chunks and convert back to char.
1924 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1928 "Perl program to use for decoding a file.
1929 Escape sequence %s is replaced with name of Perl binary.
1930 This string is passed to `format', so percent characters need to be doubled.")
1932 (defconst tramp-vc-registered-read-file-names
1934 for file in \"$@\"; do
1936 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1938 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1941 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1943 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1947 "Script to check existence of VC related files.
1948 It must be send formatted with two strings; the tests for file
1949 existence, and file readability.")
1951 (defconst tramp-file-mode-type-map
1952 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1954 (2 . "c") ; character device
1955 (3 . "m") ; multiplexed character device (v7)
1956 (4 . "d") ; directory
1957 (5 . "?") ; Named special file (XENIX)
1958 (6 . "b") ; block device
1959 (7 . "?") ; multiplexed block device (v7)
1960 (8 . "-") ; regular file
1961 (9 . "n") ; network special file (HP-UX)
1962 (10 . "l") ; symlink
1963 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1965 (13 . "D") ; door special (Solaris)
1966 (14 . "w")) ; whiteout (BSD)
1967 "A list of file types returned from the `stat' system call.
1968 This is used to map a mode number to a permission string.")
1970 ;; New handlers should be added here. The following operations can be
1971 ;; handled using the normal primitives: file-name-sans-versions,
1973 (defconst tramp-file-name-handler-alist
1974 '((load . tramp-handle-load)
1975 (make-symbolic-link . tramp-handle-make-symbolic-link)
1976 (file-name-as-directory . tramp-handle-file-name-as-directory)
1977 (file-name-directory . tramp-handle-file-name-directory)
1978 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1979 (file-truename . tramp-handle-file-truename)
1980 (file-exists-p . tramp-handle-file-exists-p)
1981 (file-directory-p . tramp-handle-file-directory-p)
1982 (file-executable-p . tramp-handle-file-executable-p)
1983 (file-readable-p . tramp-handle-file-readable-p)
1984 (file-regular-p . tramp-handle-file-regular-p)
1985 (file-symlink-p . tramp-handle-file-symlink-p)
1986 (file-writable-p . tramp-handle-file-writable-p)
1987 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1988 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1989 (file-attributes . tramp-handle-file-attributes)
1990 (file-modes . tramp-handle-file-modes)
1991 (directory-files . tramp-handle-directory-files)
1992 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1993 (file-name-all-completions . tramp-handle-file-name-all-completions)
1994 (file-name-completion . tramp-handle-file-name-completion)
1995 (add-name-to-file . tramp-handle-add-name-to-file)
1996 (copy-file . tramp-handle-copy-file)
1997 (copy-directory . tramp-handle-copy-directory)
1998 (rename-file . tramp-handle-rename-file)
1999 (set-file-modes . tramp-handle-set-file-modes)
2000 (set-file-times . tramp-handle-set-file-times)
2001 (make-directory . tramp-handle-make-directory)
2002 (delete-directory . tramp-handle-delete-directory)
2003 (delete-file . tramp-handle-delete-file)
2004 (directory-file-name . tramp-handle-directory-file-name)
2005 ;; `executable-find' is not official yet.
2006 (executable-find . tramp-handle-executable-find)
2007 (start-file-process . tramp-handle-start-file-process)
2008 (process-file . tramp-handle-process-file)
2009 (shell-command . tramp-handle-shell-command)
2010 (insert-directory . tramp-handle-insert-directory)
2011 (expand-file-name . tramp-handle-expand-file-name)
2012 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2013 (file-local-copy . tramp-handle-file-local-copy)
2014 (file-remote-p . tramp-handle-file-remote-p)
2015 (insert-file-contents . tramp-handle-insert-file-contents)
2016 (insert-file-contents-literally
2017 . tramp-handle-insert-file-contents-literally)
2018 (write-region . tramp-handle-write-region)
2019 (find-backup-file-name . tramp-handle-find-backup-file-name)
2020 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2021 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2022 (dired-compress-file . tramp-handle-dired-compress-file)
2023 (dired-recursive-delete-directory
2024 . tramp-handle-dired-recursive-delete-directory)
2025 (dired-uncache . tramp-handle-dired-uncache)
2026 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2027 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2028 (vc-registered . tramp-handle-vc-registered))
2029 "Alist of handler functions.
2030 Operations not mentioned here will be handled by the normal Emacs functions.")
2032 ;; Handlers for partial Tramp file names. For Emacs just
2033 ;; `file-name-all-completions' is needed.
2035 (defconst tramp-completion-file-name-handler-alist
2036 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2037 (file-name-completion . tramp-completion-handle-file-name-completion))
2038 "Alist of completion handler functions.
2039 Used for file names matching `tramp-file-name-regexp'. Operations not
2040 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2041 normal Emacs functions.")
2043 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2044 (defvar tramp-foreign-file-name-handler-alist
2045 ;; (identity . tramp-sh-file-name-handler) should always be the last
2046 ;; entry, because `identity' always matches.
2047 '((identity . tramp-sh-file-name-handler))
2048 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2049 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2052 ;;; Internal functions which must come first:
2054 (defsubst tramp-debug-message (vec fmt-string &rest args)
2055 "Append message to debug buffer.
2056 Message is formatted with FMT-STRING as control string and the remaining
2057 ARGS to actually emit the message (if applicable)."
2058 (when (get-buffer (tramp-buffer-name vec))
2059 (with-current-buffer (tramp-get-debug-buffer vec)
2060 (goto-char (point-max))
2065 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2066 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2067 emacs-version tramp-version)))
2071 (let ((now (current-time)))
2072 (insert (format-time-string "%T." now))
2073 (insert (format "%06d " (nth 2 now))))
2074 ;; Calling function.
2075 (let ((btn 1) btf fn)
2077 (setq btf (nth 1 (backtrace-frame btn)))
2081 (setq fn (symbol-name btf))
2082 (unless (and (string-match "^tramp" fn)
2084 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
2087 (setq btn (1+ btn))))
2088 ;; The following code inserts filename and line number.
2089 ;; Should be deactivated by default, because it is time
2091 ; (let ((ffn (find-function-noselect (intern fn))))
2095 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2096 ; (with-current-buffer (car ffn)
2097 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2098 (insert (format "%s " fn)))
2100 (insert (apply 'format fmt-string args)))))
2102 (defvar tramp-message-show-message t
2103 "Show Tramp message in the minibuffer.
2104 This variable is used to disable messages from `tramp-error'.
2105 The messages are visible anyway, because an error is raised.")
2107 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2108 "Emit a message depending on verbosity level.
2109 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2110 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2111 less than LEVEL. The message is emitted only if `tramp-verbose' is
2112 greater than or equal to LEVEL.
2114 The message is also logged into the debug buffer when `tramp-verbose'
2115 is greater than or equal 4.
2117 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2118 control string and the remaining ARGS to actually emit the message (if
2121 (when (<= level tramp-verbose)
2122 ;; Match data must be preserved!
2124 ;; Display only when there is a minimum level.
2125 (when (and tramp-message-show-message (<= level 3))
2131 ((= level 2) "Warning: ")
2135 ;; Log only when there is a minimum level.
2136 (when (>= tramp-verbose 4)
2137 (when (and vec-or-proc
2138 (processp vec-or-proc)
2139 (buffer-name (process-buffer vec-or-proc)))
2140 (with-current-buffer (process-buffer vec-or-proc)
2141 ;; Translate proc to vec.
2142 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2143 (when (and vec-or-proc (vectorp vec-or-proc))
2144 (apply 'tramp-debug-message
2146 (concat (format "(%d) # " level) fmt-string)
2148 ;; Suppress all errors.
2151 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2153 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2154 signal identifier to be raised, remaining args passed to
2155 `tramp-message'. Finally, signal SIGNAL is raised."
2156 (let (tramp-message-show-message)
2159 (error-message-string
2161 (get signal 'error-message)
2162 (apply 'format fmt-string args))))
2163 (signal signal (list (apply 'format fmt-string args)))))
2165 (defsubst tramp-error-with-buffer
2166 (buffer vec-or-proc signal fmt-string &rest args)
2167 "Emit an error, and show BUFFER.
2168 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2169 an input event arrives. The other arguments are passed to `tramp-error'."
2170 (save-window-excursion
2172 (apply 'tramp-error vec-or-proc signal fmt-string args)
2173 (when (and vec-or-proc (not (zerop tramp-verbose)))
2174 (let ((enable-recursive-minibuffers t))
2176 (or (and (bufferp buffer) buffer)
2177 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2178 (tramp-get-buffer vec-or-proc)))
2181 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2182 "Parse a Tramp filename and make components available in the body.
2184 First arg FILENAME is evaluated and dissected into its components.
2185 Second arg VAR is a symbol. It is used as a variable name to hold
2186 the filename structure. It is also used as a prefix for the variables
2187 holding the components. For example, if VAR is the symbol `foo', then
2188 `foo' will be bound to the whole structure, `foo-method' will be bound to
2189 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2191 Remaining args are Lisp expressions to be evaluated (inside an implicit
2194 If VAR is nil, then we bind `v' to the structure and `method', `user',
2195 `host', `localname' to the components."
2196 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2197 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2198 (tramp-file-name-method ,(or var 'v)))
2199 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2200 (tramp-file-name-user ,(or var 'v)))
2201 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2202 (tramp-file-name-host ,(or var 'v)))
2203 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2204 (tramp-file-name-localname ,(or var 'v))))
2207 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2208 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2209 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2211 (defmacro with-file-property (vec file property &rest body)
2212 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2213 FILE must be a local file name on a connection identified via VEC."
2214 `(if (file-name-absolute-p ,file)
2215 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2216 (when (eq value 'undef)
2217 ;; We cannot pass @body as parameter to
2218 ;; `tramp-set-file-property' because it mangles our
2220 (setq value (progn ,@body))
2221 (tramp-set-file-property ,vec ,file ,property value))
2225 (put 'with-file-property 'lisp-indent-function 3)
2226 (put 'with-file-property 'edebug-form-spec t)
2227 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2229 (defmacro with-connection-property (key property &rest body)
2230 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2231 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2232 (when (eq value 'undef)
2233 ;; We cannot pass ,@body as parameter to
2234 ;; `tramp-set-connection-property' because it mangles our debug
2236 (setq value (progn ,@body))
2237 (tramp-set-connection-property ,key ,property value))
2240 (put 'with-connection-property 'lisp-indent-function 2)
2241 (put 'with-connection-property 'edebug-form-spec t)
2242 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2244 (eval-and-compile ; silence compiler
2245 (if (memq system-type '(cygwin windows-nt))
2246 (defun tramp-drop-volume-letter (name)
2247 "Cut off unnecessary drive letter from file NAME.
2248 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2249 locally on a remote file name. When the local system is a W32 system
2250 but the remote system is Unix, this introduces a superfluous drive
2251 letter into the file name. This function removes it."
2253 (if (string-match tramp-root-regexp name)
2254 (replace-match "/" nil t name)
2257 (defalias 'tramp-drop-volume-letter 'identity)))
2259 (defsubst tramp-make-tramp-temp-file (vec)
2260 "Create a temporary file on the remote host identified by VEC.
2261 Return the local name of the temporary file."
2263 (tramp-make-tramp-file-name
2264 (tramp-file-name-method vec)
2265 (tramp-file-name-user vec)
2266 (tramp-file-name-host vec)
2267 (tramp-drop-volume-letter
2269 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2272 ;; `make-temp-file' would be the natural choice for
2273 ;; implementation. But it calls `write-region' internally,
2274 ;; which also needs a temporary file - we would end in an
2276 (setq result (make-temp-name prefix))
2277 (if (file-exists-p result)
2279 ;; This creates the file by side effect.
2280 (set-file-times result)
2281 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2283 ;; Return the local part.
2284 (with-parsed-tramp-file-name result nil localname)))
2287 ;;; Config Manipulation Functions:
2289 (defun tramp-set-completion-function (method function-list)
2290 "Sets the list of completion functions for METHOD.
2291 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2292 The FUNCTION is intended to parse FILE according its syntax.
2293 It might be a predefined FUNCTION, or a user defined FUNCTION.
2294 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2295 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2296 and `tramp-parse-netrc'.
2300 (tramp-set-completion-function
2302 '((tramp-parse-sconfig \"/etc/ssh_config\")
2303 (tramp-parse-sconfig \"~/.ssh/config\")))"
2305 (let ((r function-list)
2307 (setq tramp-completion-function-alist
2308 (delete (assoc method tramp-completion-function-alist)
2309 tramp-completion-function-alist))
2312 ;; Remove double entries.
2313 (when (member (car v) (cdr v))
2314 (setcdr v (delete (car v) (cdr v))))
2315 ;; Check for function and file or registry key.
2316 (unless (and (functionp (nth 0 (car v)))
2317 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2318 ;; Windows registry.
2319 (and (memq system-type '(cygwin windows-nt))
2321 (tramp-local-call-process
2322 "reg" nil nil nil "query" (nth 1 (car v)))))
2323 ;; Configuration file.
2324 (file-exists-p (nth 1 (car v)))))
2325 (setq r (delete (car v) r)))
2329 (add-to-list 'tramp-completion-function-alist
2332 (defun tramp-get-completion-function (method)
2333 "Returns a list of completion functions for METHOD.
2334 For definition of that list see `tramp-set-completion-function'."
2336 ;; Hosts visited once shall be remembered.
2337 `(tramp-parse-connection-properties ,method)
2338 ;; The method related defaults.
2339 (cdr (assoc method tramp-completion-function-alist))))
2342 ;;; Fontification of `read-file-name':
2344 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2345 (defvar tramp-rfn-eshadow-overlay)
2346 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2348 (defun tramp-rfn-eshadow-setup-minibuffer ()
2349 "Set up a minibuffer for `file-name-shadow-mode'.
2350 Adds another overlay hiding filename parts according to Tramp's
2351 special handling of `substitute-in-file-name'."
2352 (when (symbol-value 'minibuffer-completing-file-name)
2353 (setq tramp-rfn-eshadow-overlay
2354 (funcall (symbol-function 'make-overlay)
2355 (funcall (symbol-function 'minibuffer-prompt-end))
2356 (funcall (symbol-function 'minibuffer-prompt-end))))
2357 ;; Copy rfn-eshadow-overlay properties.
2358 (let ((props (funcall (symbol-function 'overlay-properties)
2359 (symbol-value 'rfn-eshadow-overlay))))
2361 (funcall (symbol-function 'overlay-put)
2362 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2364 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2365 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2366 'tramp-rfn-eshadow-setup-minibuffer)
2367 (add-hook 'tramp-unload-hook
2369 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2370 'tramp-rfn-eshadow-setup-minibuffer))))
2372 (defconst tramp-rfn-eshadow-update-overlay-regexp
2373 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2375 (defun tramp-rfn-eshadow-update-overlay ()
2376 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2377 This is intended to be used as a minibuffer `post-command-hook' for
2378 `file-name-shadow-mode'; the minibuffer should have already
2379 been set up by `rfn-eshadow-setup-minibuffer'."
2380 ;; In remote files name, there is a shadowing just for the local part.
2381 (let ((end (or (funcall (symbol-function 'overlay-end)
2382 (symbol-value 'rfn-eshadow-overlay))
2383 (funcall (symbol-function 'minibuffer-prompt-end)))))
2384 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
2388 (1+ (or (string-match
2389 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2392 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2393 (rfn-eshadow-update-overlay-hook nil))
2394 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
2395 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
2397 (when (boundp 'rfn-eshadow-update-overlay-hook)
2398 (add-hook 'rfn-eshadow-update-overlay-hook
2399 'tramp-rfn-eshadow-update-overlay)
2400 (add-hook 'tramp-unload-hook
2402 (remove-hook 'rfn-eshadow-update-overlay-hook
2403 'tramp-rfn-eshadow-update-overlay))))
2406 ;;; Integration of eshell.el:
2409 (defvar eshell-path-env))
2411 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2412 ;; when `default-directory' points to another host.
2413 (defun tramp-eshell-directory-change ()
2414 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2415 (setq eshell-path-env
2416 (if (file-remote-p default-directory)
2417 (with-parsed-tramp-file-name default-directory nil
2420 (tramp-get-remote-path v)
2424 (eval-after-load "esh-util"
2426 (tramp-eshell-directory-change)
2427 (add-hook 'eshell-directory-change-hook
2428 'tramp-eshell-directory-change)
2429 (add-hook 'tramp-unload-hook
2431 (remove-hook 'eshell-directory-change-hook
2432 'tramp-eshell-directory-change)))))
2435 ;;; File Name Handler Functions:
2437 (defun tramp-handle-make-symbolic-link
2438 (filename linkname &optional ok-if-already-exists)
2439 "Like `make-symbolic-link' for Tramp files.
2440 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2441 the symlink. If LINKNAME is a Tramp file, only the localname component is
2442 used as the target of the symlink.
2444 If LINKNAME is a Tramp file and the localname component is relative, then
2445 it is expanded first, before the localname component is taken. Note that
2446 this can give surprising results if the user/host for the source and
2447 target of the symlink differ."
2448 (with-parsed-tramp-file-name linkname l
2449 (let ((ln (tramp-get-remote-ln l))
2450 (cwd (tramp-run-real-handler
2451 'file-name-directory (list l-localname))))
2455 "Making a symbolic link. ln(1) does not exist on the remote host."))
2457 ;; Do the 'confirm if exists' thing.
2458 (when (file-exists-p linkname)
2460 (if (or (null ok-if-already-exists) ; not allowed to exist
2461 (and (numberp ok-if-already-exists)
2464 "File %s already exists; make it a link anyway? "
2467 l 'file-already-exists "File %s already exists" l-localname)
2468 (delete-file linkname)))
2470 ;; If FILENAME is a Tramp name, use just the localname component.
2471 (when (tramp-tramp-file-p filename)
2473 (tramp-file-name-localname
2474 (tramp-dissect-file-name (expand-file-name filename)))))
2476 ;; Right, they are on the same host, regardless of user, method, etc.
2477 ;; We now make the link on the remote machine. This will occur as the user
2478 ;; that FILENAME belongs to.
2480 (tramp-send-command-and-check
2483 "cd %s && %s -sf %s %s"
2484 (tramp-shell-quote-argument cwd)
2486 (tramp-shell-quote-argument filename)
2487 (tramp-shell-quote-argument l-localname))
2490 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2491 "Like `load' for Tramp files."
2492 (with-parsed-tramp-file-name (expand-file-name file) nil
2494 (cond ((file-exists-p (concat file ".elc"))
2495 (setq file (concat file ".elc")))
2496 ((file-exists-p (concat file ".el"))
2497 (setq file (concat file ".el")))))
2499 ;; The first condition is always true for absolute file names.
2500 ;; Included for safety's sake.
2501 (unless (or (file-name-directory file)
2502 (string-match "\\.elc?\\'" file))
2505 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2507 (when (not (file-exists-p file))
2508 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2509 (if (not (file-exists-p file))
2511 (unless nomessage (tramp-message v 0 "Loading %s..." file))
2512 (let ((local-copy (file-local-copy file)))
2513 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2515 (load local-copy noerror t t)
2516 (delete-file local-copy)))
2517 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
2520 ;; Localname manipulation functions that grok Tramp localnames...
2521 (defun tramp-handle-file-name-as-directory (file)
2522 "Like `file-name-as-directory' but aware of Tramp files."
2523 ;; `file-name-as-directory' would be sufficient except localname is
2524 ;; the empty string.
2525 (let ((v (tramp-dissect-file-name file t)))
2526 ;; Run the command on the localname portion only.
2527 (tramp-make-tramp-file-name
2528 (tramp-file-name-method v)
2529 (tramp-file-name-user v)
2530 (tramp-file-name-host v)
2531 (tramp-run-real-handler
2532 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2534 (defun tramp-handle-file-name-directory (file)
2535 "Like `file-name-directory' but aware of Tramp files."
2536 ;; Everything except the last filename thing is the directory. We
2537 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2538 ;; the remote file name parts. This is a problem when we are in
2539 ;; file name completion.
2540 (let ((v (tramp-dissect-file-name file t)))
2541 ;; Run the command on the localname portion only.
2542 (tramp-make-tramp-file-name
2543 (tramp-file-name-method v)
2544 (tramp-file-name-user v)
2545 (tramp-file-name-host v)
2546 (tramp-run-real-handler
2547 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2549 (defun tramp-handle-file-name-nondirectory (file)
2550 "Like `file-name-nondirectory' but aware of Tramp files."
2551 (with-parsed-tramp-file-name file nil
2552 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2554 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2555 "Like `file-truename' for Tramp files."
2556 (with-parsed-tramp-file-name (expand-file-name filename) nil
2557 (with-file-property v localname "file-truename"
2558 (let ((result nil)) ; result steps in reverse order
2559 (tramp-message v 4 "Finding true name for `%s'" filename)
2561 ;; Use GNU readlink --canonicalize-missing where available.
2562 ((tramp-get-remote-readlink v)
2564 (tramp-send-command-and-read
2566 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2567 (tramp-get-remote-readlink v)
2568 (tramp-shell-quote-argument localname)))))
2570 ;; Use Perl implementation.
2571 ((and (tramp-get-remote-perl v)
2572 (tramp-get-connection-property v "perl-file-spec" nil)
2573 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2574 (tramp-maybe-send-script
2575 v tramp-perl-file-truename "tramp_perl_file_truename")
2577 (tramp-send-command-and-read
2579 (format "tramp_perl_file_truename %s"
2580 (tramp-shell-quote-argument localname)))))
2582 ;; Do it yourself. We bind `directory-sep-char' here for
2583 ;; XEmacs on Windows, which would otherwise use backslash.
2584 (t (let* ((directory-sep-char ?/)
2585 (steps (tramp-compat-split-string localname "/"))
2586 (localnamedir (tramp-run-real-handler
2587 'file-name-as-directory (list localname)))
2588 (is-dir (string= localname localnamedir))
2591 ;; Don't make the following value larger than
2592 ;; necessary. People expect an error message in a
2593 ;; timely fashion when something is wrong;
2594 ;; otherwise they might think that Emacs is hung.
2595 ;; Of course, correctness has to come first.
2598 (while (and steps (< numchase numchase-limit))
2599 (setq thisstep (pop steps))
2602 (mapconcat 'identity
2603 (append '("") (reverse result) (list thisstep))
2605 (setq symlink-target
2606 (nth 0 (file-attributes
2607 (tramp-make-tramp-file-name
2609 (mapconcat 'identity
2614 (cond ((string= "." thisstep)
2615 (tramp-message v 5 "Ignoring step `.'"))
2616 ((string= ".." thisstep)
2617 (tramp-message v 5 "Processing step `..'")
2619 ((stringp symlink-target)
2620 ;; It's a symlink, follow it.
2621 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2622 (setq numchase (1+ numchase))
2623 (when (file-name-absolute-p symlink-target)
2625 ;; If the symlink was absolute, we'll get a string like
2626 ;; "/user@host:/some/target"; extract the
2627 ;; "/some/target" part from it.
2628 (when (tramp-tramp-file-p symlink-target)
2629 (unless (tramp-equal-remote filename symlink-target)
2632 "Symlink target `%s' on wrong host" symlink-target))
2633 (setq symlink-target localname))
2635 (append (tramp-compat-split-string
2640 (setq result (cons thisstep result)))))
2641 (when (>= numchase numchase-limit)
2644 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2645 (setq result (reverse result))
2646 ;; Combine list to form string.
2649 (mapconcat 'identity (cons "" result) "/")
2651 (when (and is-dir (or (string= "" result)
2652 (not (string= (substring result -1) "/"))))
2653 (setq result (concat result "/"))))))
2655 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2656 (tramp-make-tramp-file-name method user host result)))))
2660 (defun tramp-handle-file-exists-p (filename)
2661 "Like `file-exists-p' for Tramp files."
2662 (with-parsed-tramp-file-name filename nil
2663 (with-file-property v localname "file-exists-p"
2664 (or (not (null (tramp-get-file-property
2665 v localname "file-attributes-integer" nil)))
2666 (not (null (tramp-get-file-property
2667 v localname "file-attributes-string" nil)))
2668 (zerop (tramp-send-command-and-check
2672 (tramp-get-file-exists-command v)
2673 (tramp-shell-quote-argument localname))))))))
2675 ;; Inodes don't exist for some file systems. Therefore we must
2676 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2677 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2678 ;; performance isn't the major issue given that file transfer will
2680 (defvar tramp-inodes nil
2681 "Keeps virtual inodes numbers.")
2683 ;; Devices must distinguish physical file systems. The device numbers
2684 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2685 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2686 ;; EFS use device number "-1". In order to be different, we use device number
2687 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2688 (defvar tramp-devices nil
2689 "Keeps virtual device numbers.")
2691 ;; CCC: This should check for an error condition and signal failure
2692 ;; when something goes wrong.
2693 ;; Daniel Pittman <daniel@danann.net>
2694 (defun tramp-handle-file-attributes (filename &optional id-format)
2695 "Like `file-attributes' for Tramp files."
2696 (unless id-format (setq id-format 'integer))
2697 ;; Don't modify `last-coding-system-used' by accident.
2698 (let ((last-coding-system-used last-coding-system-used))
2699 (with-parsed-tramp-file-name (expand-file-name filename) nil
2700 (with-file-property v localname (format "file-attributes-%s" id-format)
2702 (tramp-convert-file-attributes
2705 ((tramp-get-remote-stat v)
2706 (tramp-do-file-attributes-with-stat v localname id-format))
2707 ((tramp-get-remote-perl v)
2708 (tramp-do-file-attributes-with-perl v localname id-format))
2710 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2712 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2713 "Implement `file-attributes' for Tramp files using the ls(1) command."
2715 res-inode res-filemodes res-numlinks
2716 res-uid res-gid res-size res-symlink-target)
2717 (tramp-message vec 5 "file attributes with ls: %s" localname)
2720 (format "(%s %s || %s -h %s) && %s %s %s"
2721 (tramp-get-file-exists-command vec)
2722 (tramp-shell-quote-argument localname)
2723 (tramp-get-test-command vec)
2724 (tramp-shell-quote-argument localname)
2725 (tramp-get-ls-command vec)
2726 (if (eq id-format 'integer) "-ildn" "-ild")
2727 (tramp-shell-quote-argument localname)))
2728 ;; parse `ls -l' output ...
2729 (with-current-buffer (tramp-get-buffer vec)
2730 (when (> (buffer-size) 0)
2731 (goto-char (point-min))
2735 (read (current-buffer))
2736 (invalid-read-syntax
2737 (when (and (equal (cadr err)
2738 "Integer constant overflow in reader")
2740 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2742 (let* ((big (read (substring (car (cddr err)) 0
2743 (match-beginning 1))))
2744 (small (read (match-string 1 (car (cddr err)))))
2745 (twiddle (/ small 65536)))
2746 (cons (+ big twiddle)
2747 (- small (* twiddle 65536))))))))
2748 ;; ... file mode flags
2749 (setq res-filemodes (symbol-name (read (current-buffer))))
2751 (setq res-numlinks (read (current-buffer)))
2753 (setq res-uid (read (current-buffer)))
2754 (setq res-gid (read (current-buffer)))
2755 (if (eq id-format 'integer)
2757 (unless (numberp res-uid) (setq res-uid -1))
2758 (unless (numberp res-gid) (setq res-gid -1)))
2760 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2761 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2763 (setq res-size (read (current-buffer)))
2764 ;; From the file modes, figure out other stuff.
2765 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2766 (setq dirp (eq ?d (aref res-filemodes 0)))
2767 ;; if symlink, find out file name pointed to
2769 (search-forward "-> ")
2770 (setq res-symlink-target
2771 (buffer-substring (point) (tramp-compat-line-end-position))))
2772 ;; return data gathered
2774 ;; 0. t for directory, string (name linked to) for symbolic
2776 (or dirp res-symlink-target)
2777 ;; 1. Number of links to file.
2783 ;; 4. Last access time, as a list of two integers. First
2784 ;; integer has high-order 16 bits of time, second has low 16
2786 ;; 5. Last modification time, likewise.
2787 ;; 6. Last status change time, likewise.
2788 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2789 ;; 7. Size in bytes (-1, if number is out of range).
2791 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2793 ;; 9. t if file's gid would change if file were deleted and
2794 ;; recreated. Will be set in `tramp-convert-file-attributes'
2796 ;; 10. inode number.
2798 ;; 11. Device number. Will be replaced by a virtual device number.
2802 (defun tramp-do-file-attributes-with-perl
2803 (vec localname &optional id-format)
2804 "Implement `file-attributes' for Tramp files using a Perl script."
2805 (tramp-message vec 5 "file attributes with perl: %s" localname)
2806 (tramp-maybe-send-script
2807 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2808 (tramp-send-command-and-read
2810 (format "tramp_perl_file_attributes %s %s"
2811 (tramp-shell-quote-argument localname) id-format)))
2813 (defun tramp-do-file-attributes-with-stat
2814 (vec localname &optional id-format)
2815 "Implement `file-attributes' for Tramp files using stat(1) command."
2816 (tramp-message vec 5 "file attributes with stat: %s" localname)
2817 (tramp-send-command-and-read
2820 "((%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s || echo nil)"
2821 (tramp-get-file-exists-command vec)
2822 (tramp-shell-quote-argument localname)
2823 (tramp-get-test-command vec)
2824 (tramp-shell-quote-argument localname)
2825 (tramp-get-remote-stat vec)
2826 (if (eq id-format 'integer) "%u" "\"%U\"")
2827 (if (eq id-format 'integer) "%g" "\"%G\"")
2828 (tramp-shell-quote-argument localname))))
2830 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2831 "Like `set-visited-file-modtime' for Tramp files."
2832 (unless (buffer-file-name)
2833 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2836 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2837 (let ((f (buffer-file-name))
2839 (with-parsed-tramp-file-name f nil
2840 (let* ((attr (file-attributes f))
2841 ;; '(-1 65535) means file doesn't exists yet.
2842 (modtime (or (nth 5 attr) '(-1 65535))))
2843 (when (boundp 'last-coding-system-used)
2844 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2845 ;; We use '(0 0) as a don't-know value. See also
2846 ;; `tramp-do-file-attributes-with-ls'.
2847 (if (not (equal modtime '(0 0)))
2848 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2852 (format "%s -ild %s"
2853 (tramp-get-ls-command v)
2854 (tramp-shell-quote-argument localname)))
2855 (setq attr (buffer-substring (point)
2856 (progn (end-of-line) (point)))))
2857 (tramp-set-file-property
2858 v localname "visited-file-modtime-ild" attr))
2859 (when (boundp 'last-coding-system-used)
2860 (set 'last-coding-system-used coding-system-used))
2863 ;; This function makes the same assumption as
2864 ;; `tramp-handle-set-visited-file-modtime'.
2865 (defun tramp-handle-verify-visited-file-modtime (buf)
2866 "Like `verify-visited-file-modtime' for Tramp files.
2867 At the time `verify-visited-file-modtime' calls this function, we
2868 already know that the buffer is visiting a file and that
2869 `visited-file-modtime' does not return 0. Do not call this
2870 function directly, unless those two cases are already taken care
2872 (with-current-buffer buf
2873 ;; There is no file visiting the buffer, or the buffer has no
2874 ;; recorded last modification time.
2875 (if (or (not (buffer-file-name))
2876 (eq (visited-file-modtime) 0))
2878 (let ((f (buffer-file-name)))
2879 (with-parsed-tramp-file-name f nil
2880 (tramp-flush-file-property v localname)
2881 (let* ((attr (file-attributes f))
2882 (modtime (nth 5 attr))
2883 (mt (visited-file-modtime)))
2886 ;; File exists, and has a known modtime.
2887 ((and attr (not (equal modtime '(0 0))))
2888 (< (abs (tramp-time-diff
2890 ;; For compatibility, deal with both the old
2891 ;; (HIGH . LOW) and the new (HIGH LOW) return
2892 ;; values of `visited-file-modtime'.
2894 (list (car mt) (cdr mt))
2897 ;; Modtime has the don't know value.
2901 (format "%s -ild %s"
2902 (tramp-get-ls-command v)
2903 (tramp-shell-quote-argument localname)))
2904 (with-current-buffer (tramp-get-buffer v)
2905 (setq attr (buffer-substring
2906 (point) (progn (end-of-line) (point)))))
2909 (tramp-get-file-property
2910 v localname "visited-file-modtime-ild" "")))
2911 ;; If file does not exist, say it is not modified if and
2912 ;; only if that agrees with the buffer's record.
2913 (t (equal mt '(-1 65535))))))))))
2915 (defun tramp-handle-set-file-modes (filename mode)
2916 "Like `set-file-modes' for Tramp files."
2917 (with-parsed-tramp-file-name filename nil
2918 (tramp-flush-file-property v localname)
2919 (unless (zerop (tramp-send-command-and-check
2921 (format "chmod %s %s"
2922 (tramp-decimal-to-octal mode)
2923 (tramp-shell-quote-argument localname))))
2924 ;; FIXME: extract the proper text from chmod's stderr.
2926 v 'file-error "Error while changing file's mode %s" filename))))
2928 (defun tramp-handle-set-file-times (filename &optional time)
2929 "Like `set-file-times' for Tramp files."
2931 (if (file-remote-p filename)
2932 (with-parsed-tramp-file-name filename nil
2933 (tramp-flush-file-property v localname)
2934 (let ((time (if (or (null time) (equal time '(0 0)))
2938 ;; With GNU Emacs, `format-time-string' has an
2939 ;; optional parameter UNIVERSAL. This is preferred,
2940 ;; because we could handle the case when the remote
2941 ;; host is located in a different time zone as the
2943 (and (functionp 'subr-arity)
2944 (subrp (symbol-function 'format-time-string))
2945 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2947 'format-time-string)))))))
2948 (tramp-send-command-and-check
2949 v (format "%s touch -t %s %s"
2950 (if utc "TZ=UTC; export TZ;" "")
2952 (format-time-string "%Y%m%d%H%M.%S" time t)
2953 (format-time-string "%Y%m%d%H%M.%S" time))
2954 (tramp-shell-quote-argument localname)))))
2956 ;; We handle also the local part, because in older Emacsen,
2957 ;; without `set-file-times', this function is an alias for this.
2958 ;; We are local, so we don't need the UTC settings.
2959 (tramp-local-call-process
2960 "touch" nil nil nil "-t"
2961 (format-time-string "%Y%m%d%H%M.%S" time)
2962 (tramp-shell-quote-argument filename)))))
2964 (defun tramp-set-file-uid-gid (filename &optional uid gid)
2965 "Set the ownership for FILENAME.
2966 If UID and GID are provided, these values are used; otherwise uid
2967 and gid of the corresponding user is taken. Both parameters must be integers."
2968 ;; Modern Unices allow chown only for root. So we might need
2969 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2970 ;; working with su(do)? when it is needed, so it shall succeed in
2971 ;; the majority of cases.
2972 ;; Don't modify `last-coding-system-used' by accident.
2973 (let ((last-coding-system-used last-coding-system-used))
2974 (if (file-remote-p filename)
2975 (with-parsed-tramp-file-name filename nil
2976 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2977 ;; If we are root on the local host, we can do it directly.
2978 (tramp-set-file-uid-gid localname uid gid)
2979 (let ((uid (or (and (integerp uid) uid)
2980 (tramp-get-remote-uid v 'integer)))
2981 (gid (or (and (integerp gid) gid)
2982 (tramp-get-remote-gid v 'integer))))
2985 "chown %d:%d %s" uid gid
2986 (tramp-shell-quote-argument localname))))))
2988 ;; We handle also the local part, because there doesn't exist
2989 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2990 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2991 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2992 (tramp-local-call-process
2994 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
2996 ;; Simple functions using the `test' command.
2998 (defun tramp-handle-file-executable-p (filename)
2999 "Like `file-executable-p' for Tramp files."
3000 (with-parsed-tramp-file-name filename nil
3001 (with-file-property v localname "file-executable-p"
3002 ;; Examine `file-attributes' cache to see if request can be
3003 ;; satisfied without remote operation.
3004 (or (tramp-check-cached-permissions v ?x)
3005 (zerop (tramp-run-test "-x" filename))))))
3007 (defun tramp-handle-file-readable-p (filename)
3008 "Like `file-readable-p' for Tramp files."
3009 (with-parsed-tramp-file-name filename nil
3010 (with-file-property v localname "file-readable-p"
3011 ;; Examine `file-attributes' cache to see if request can be
3012 ;; satisfied without remote operation.
3013 (or (tramp-check-cached-permissions v ?r)
3014 (zerop (tramp-run-test "-r" filename))))))
3016 ;; When the remote shell is started, it looks for a shell which groks
3017 ;; tilde expansion. Here, we assume that all shells which grok tilde
3018 ;; expansion will also provide a `test' command which groks `-nt' (for
3019 ;; newer than). If this breaks, tell me about it and I'll try to do
3020 ;; something smarter about it.
3021 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3022 "Like `file-newer-than-file-p' for Tramp files."
3023 (cond ((not (file-exists-p file1))
3025 ((not (file-exists-p file2))
3027 ;; We are sure both files exist at this point.
3030 ;; We try to get the mtime of both files. If they are not
3031 ;; equal to the "dont-know" value, then we subtract the times
3032 ;; and obtain the result.
3033 (let ((fa1 (file-attributes file1))
3034 (fa2 (file-attributes file2)))
3035 (if (and (not (equal (nth 5 fa1) '(0 0)))
3036 (not (equal (nth 5 fa2) '(0 0))))
3037 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3038 ;; If one of them is the dont-know value, then we can
3039 ;; still try to run a shell command on the remote host.
3040 ;; However, this only works if both files are Tramp
3041 ;; files and both have the same method, same user, same
3043 (unless (tramp-equal-remote file1 file2)
3044 (with-parsed-tramp-file-name
3045 (if (tramp-tramp-file-p file1) file1 file2) nil
3048 "Files %s and %s must have same method, user, host"
3050 (with-parsed-tramp-file-name file1 nil
3051 (zerop (tramp-run-test2
3052 (tramp-get-test-nt-command v) file1 file2)))))))))
3054 ;; Functions implemented using the basic functions above.
3056 (defun tramp-handle-file-modes (filename)
3057 "Like `file-modes' for Tramp files."
3058 (let ((truename (or (file-truename filename) filename)))
3059 (when (file-exists-p truename)
3060 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3062 (defun tramp-default-file-modes (filename)
3063 "Return file modes of FILENAME as integer.
3064 If the file modes of FILENAME cannot be determined, return the
3065 value of `default-file-modes', without execute permissions."
3066 (or (file-modes filename)
3067 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3069 (defun tramp-handle-file-directory-p (filename)
3070 "Like `file-directory-p' for Tramp files."
3071 ;; Care must be taken that this function returns `t' for symlinks
3072 ;; pointing to directories. Surely the most obvious implementation
3073 ;; would be `test -d', but that returns false for such symlinks.
3074 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3075 ;; I now think he's right. So we could be using `test -d', couldn't
3078 ;; Alternatives: `cd %s', `test -d %s'
3079 (with-parsed-tramp-file-name filename nil
3080 (with-file-property v localname "file-directory-p"
3081 (zerop (tramp-run-test "-d" filename)))))
3083 (defun tramp-handle-file-regular-p (filename)
3084 "Like `file-regular-p' for Tramp files."
3085 (and (file-exists-p filename)
3086 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3088 (defun tramp-handle-file-symlink-p (filename)
3089 "Like `file-symlink-p' for Tramp files."
3090 (with-parsed-tramp-file-name filename nil
3091 (let ((x (car (file-attributes filename))))
3093 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3094 ;; might do weird things.
3095 (if (file-name-absolute-p x)
3096 (tramp-make-tramp-file-name method user host x)
3099 (defun tramp-handle-file-writable-p (filename)
3100 "Like `file-writable-p' for Tramp files."
3101 (with-parsed-tramp-file-name filename nil
3102 (with-file-property v localname "file-writable-p"
3103 (if (file-exists-p filename)
3104 ;; Examine `file-attributes' cache to see if request can be
3105 ;; satisfied without remote operation.
3106 (or (tramp-check-cached-permissions v ?w)
3107 (zerop (tramp-run-test "-w" filename)))
3108 ;; If file doesn't exist, check if directory is writable.
3109 (and (zerop (tramp-run-test
3110 "-d" (file-name-directory filename)))
3111 (zerop (tramp-run-test
3112 "-w" (file-name-directory filename))))))))
3114 (defun tramp-handle-file-ownership-preserved-p (filename)
3115 "Like `file-ownership-preserved-p' for Tramp files."
3116 (with-parsed-tramp-file-name filename nil
3117 (with-file-property v localname "file-ownership-preserved-p"
3118 (let ((attributes (file-attributes filename)))
3119 ;; Return t if the file doesn't exist, since it's true that no
3120 ;; information would be lost by an (attempted) delete and create.
3121 (or (null attributes)
3122 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3124 ;; Other file name ops.
3126 (defun tramp-handle-directory-file-name (directory)
3127 "Like `directory-file-name' for Tramp files."
3128 ;; If localname component of filename is "/", leave it unchanged.
3129 ;; Otherwise, remove any trailing slash from localname component.
3130 ;; Method, host, etc, are unchanged. Does it make sense to try
3131 ;; to avoid parsing the filename?
3132 (with-parsed-tramp-file-name directory nil
3133 (if (and (not (zerop (length localname)))
3134 (eq (aref localname (1- (length localname))) ?/)
3135 (not (string= localname "/")))
3136 (substring directory 0 -1)
3139 ;; Directory listings.
3141 (defun tramp-handle-directory-files
3142 (directory &optional full match nosort files-only)
3143 "Like `directory-files' for Tramp files."
3144 ;; FILES-ONLY is valid for XEmacs only.
3145 (when (file-directory-p directory)
3146 (setq directory (file-name-as-directory (expand-file-name directory)))
3147 (let ((temp (nreverse (file-name-all-completions "" directory)))
3151 (setq item (directory-file-name (pop temp)))
3152 (when (and (or (null match) (string-match match item))
3153 (or (null files-only)
3155 (and (equal files-only t) (file-regular-p item))
3156 ;; Directories only.
3157 (file-directory-p item)))
3158 (push (if full (concat directory item) item)
3160 (if nosort result (sort result 'string<)))))
3162 (defun tramp-handle-directory-files-and-attributes
3163 (directory &optional full match nosort id-format)
3164 "Like `directory-files-and-attributes' for Tramp files."
3165 (unless id-format (setq id-format 'integer))
3166 (when (file-directory-p directory)
3167 (setq directory (expand-file-name directory))
3170 (with-parsed-tramp-file-name directory nil
3173 (format "directory-files-and-attributes-%s" id-format)
3178 (tramp-convert-file-attributes v (cdr x))))
3180 ((tramp-get-remote-stat v)
3181 (tramp-do-directory-files-and-attributes-with-stat
3182 v localname id-format))
3183 ((tramp-get-remote-perl v)
3184 (tramp-do-directory-files-and-attributes-with-perl
3185 v localname id-format)))))))))
3189 (setq item (pop temp))
3190 (when (or (null match) (string-match match (car item)))
3192 (setcar item (expand-file-name (car item) directory)))
3193 (push item result)))
3197 (sort result (lambda (x y) (string< (car x) (car y))))))))
3199 (defun tramp-do-directory-files-and-attributes-with-perl
3200 (vec localname &optional id-format)
3201 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3202 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3203 (tramp-maybe-send-script
3204 vec tramp-perl-directory-files-and-attributes
3205 "tramp_perl_directory_files_and_attributes")
3207 (tramp-send-command-and-read
3209 (format "tramp_perl_directory_files_and_attributes %s %s"
3210 (tramp-shell-quote-argument localname) id-format))))
3211 (when (stringp object) (tramp-error vec 'file-error object))
3214 (defun tramp-do-directory-files-and-attributes-with-stat
3215 (vec localname &optional id-format)
3216 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3217 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3218 (tramp-send-command-and-read
3222 ;; We must care about filenames with spaces, or starting with
3223 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3224 ;; but it does not work on all remote systems. Therefore, we
3225 ;; quote the filenames via sed.
3226 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3227 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3229 (tramp-shell-quote-argument localname)
3230 (tramp-get-ls-command vec)
3231 (tramp-get-remote-stat vec)
3232 (if (eq id-format 'integer) "%u" "\"%U\"")
3233 (if (eq id-format 'integer) "%g" "\"%G\""))))
3235 ;; This function should return "foo/" for directories and "bar" for
3237 (defun tramp-handle-file-name-all-completions (filename directory)
3238 "Like `file-name-all-completions' for Tramp files."
3239 (unless (save-match-data (string-match "/" filename))
3240 (with-parsed-tramp-file-name (expand-file-name directory) nil
3249 ;; Ignore if expired
3250 (or (not (integerp tramp-completion-reread-directory-timeout))
3251 (<= (tramp-time-diff
3253 (tramp-get-file-property
3254 v localname "last-completion" '(0 0 0)))
3255 tramp-completion-reread-directory-timeout))
3257 ;; Try cache entries for filename, filename with last
3258 ;; character removed, filename with last two characters
3259 ;; removed, ..., and finally the empty string - all
3260 ;; concatenated to the local directory name
3262 ;; This is inefficient for very long filenames, pity
3263 ;; `reduce' is not available...
3270 (tramp-get-file-property
3272 (concat localname (substring filename 0 x))
3273 "file-name-all-completions"
3275 (when cache-hit (list cache-hit))))
3276 (tramp-compat-number-sequence (length filename) 0 -1)))))
3278 ;; Cache expired or no matching cache entry found so we need
3279 ;; to perform a remote operation
3281 ;; Get a list of directories and files, including reliably
3282 ;; tagging the directories with a trailing '/'. Because I
3283 ;; rock. --daniel@danann.net
3285 ;; Changed to perform `cd' in the same remote op and only
3286 ;; get entries starting with `filename'. Capture any `cd'
3287 ;; error messages. Ensure any `cd' and `echo' aliases are
3291 (if (tramp-get-remote-perl v)
3293 (tramp-maybe-send-script
3294 v tramp-perl-file-name-all-completions
3295 "tramp_perl_file_name_all_completions")
3296 (format "tramp_perl_file_name_all_completions %s %s %d"
3297 (tramp-shell-quote-argument localname)
3298 (tramp-shell-quote-argument filename)
3300 ;; `read-file-name-completion-ignore-case'
3301 ;; is introduced with Emacs 22.1.
3303 'read-file-name-completion-ignore-case)
3304 'read-file-name-completion-ignore-case
3305 'completion-ignore-case))
3309 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3310 ;; `ls' with wildcard might fail with `Argument
3311 ;; list too long' error in some corner cases; if
3312 ;; `ls' fails after `cd' succeeded, chances are
3313 ;; that's the case, so let's retry without
3314 ;; wildcard. This will return "too many" entries
3315 ;; but that isn't harmful.
3316 " || %s -a 2>/dev/null)"
3317 " | while read f; do"
3318 " if %s -d \"$f\" 2>/dev/null;"
3319 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3320 " && \\echo ok) || \\echo fail")
3321 (tramp-shell-quote-argument localname)
3322 (tramp-get-ls-command v)
3323 ;; When `filename' is empty, just `ls' without
3324 ;; filename argument is more efficient than `ls *'
3325 ;; for very large directories and might avoid the
3326 ;; `Argument list too long' error.
3328 ;; With and only with wildcard, we need to add
3329 ;; `-d' to prevent `ls' from descending into
3331 (if (zerop (length filename))
3333 (concat (tramp-shell-quote-argument filename) "* -d"))
3334 (tramp-get-ls-command v)
3335 (tramp-get-test-command v))))
3337 ;; Now grab the output.
3338 (with-current-buffer (tramp-get-buffer v)
3339 (goto-char (point-max))
3341 ;; Check result code, found in last line of output
3343 (if (looking-at "^fail$")
3345 ;; Grab error message from line before last line
3346 ;; (it was put there by `cd 2>&1')
3350 "tramp-handle-file-name-all-completions: %s"
3352 (point) (tramp-compat-line-end-position))))
3353 ;; For peace of mind, if buffer doesn't end in `fail'
3354 ;; then it should end in `ok'. If neither are in the
3355 ;; buffer something went seriously wrong on the remote
3357 (unless (looking-at "^ok$")
3361 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3362 (tramp-shell-quote-argument localname) (buffer-string))))
3364 (while (zerop (forward-line -1))
3365 (push (buffer-substring
3366 (point) (tramp-compat-line-end-position))
3369 ;; Because the remote op went through OK we know the
3370 ;; directory we `cd'-ed to exists
3371 (tramp-set-file-property
3372 v localname "file-exists-p" t)
3374 ;; Because the remote op went through OK we know every
3375 ;; file listed by `ls' exists.
3376 (mapc (lambda (entry)
3377 (tramp-set-file-property
3378 v (concat localname entry) "file-exists-p" t))
3381 (tramp-set-file-property
3382 v localname "last-completion" (current-time))
3384 ;; Store result in the cache
3385 (tramp-set-file-property
3386 v (concat localname filename)
3387 "file-name-all-completions"
3390 (defun tramp-handle-file-name-completion
3391 (filename directory &optional predicate)
3392 "Like `file-name-completion' for Tramp files."
3393 (unless (tramp-tramp-file-p directory)
3395 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3399 (mapcar 'list (file-name-all-completions filename directory))
3401 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3405 (defun tramp-handle-add-name-to-file
3406 (filename newname &optional ok-if-already-exists)
3407 "Like `add-name-to-file' for Tramp files."
3408 (unless (tramp-equal-remote filename newname)
3409 (with-parsed-tramp-file-name
3410 (if (tramp-tramp-file-p filename) filename newname) nil
3413 "add-name-to-file: %s"
3414 "only implemented for same method, same user, same host")))
3415 (with-parsed-tramp-file-name filename v1
3416 (with-parsed-tramp-file-name newname v2
3417 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3418 (when (and (not ok-if-already-exists)
3419 (file-exists-p newname)
3420 (not (numberp ok-if-already-exists))
3423 "File %s already exists; make it a new name anyway? "
3427 "add-name-to-file: file %s already exists" newname))
3428 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3429 (tramp-flush-file-property v2 v2-localname)
3430 (tramp-barf-unless-okay
3432 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3433 (tramp-shell-quote-argument v2-localname))
3434 "error with add-name-to-file, see buffer `%s' for details"
3437 (defun tramp-handle-copy-file
3438 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3439 "Like `copy-file' for Tramp files."
3440 ;; Check if both files are local -- invoke normal copy-file.
3441 ;; Otherwise, use Tramp from local system.
3442 (setq filename (expand-file-name filename))
3443 (setq newname (expand-file-name newname))
3445 ;; At least one file a Tramp file?
3446 ((or (tramp-tramp-file-p filename)
3447 (tramp-tramp-file-p newname))
3448 (tramp-do-copy-or-rename-file
3449 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3452 (tramp-run-real-handler
3454 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3456 (tramp-run-real-handler
3457 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3459 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3460 "Like `copy-directory' for Tramp files."
3461 (let ((t1 (tramp-tramp-file-p dirname))
3462 (t2 (tramp-tramp-file-p newname)))
3463 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3464 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3465 ;; When DIRNAME and NEWNAME are remote, they must have
3467 (or (null t1) (null t2)
3469 (tramp-file-name-method (tramp-dissect-file-name dirname))
3470 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3471 ;; scp or rsync DTRT.
3473 (setq dirname (directory-file-name (expand-file-name dirname))
3474 newname (directory-file-name (expand-file-name newname)))
3475 (if (and (file-directory-p newname)
3476 (not (string-equal (file-name-nondirectory dirname)
3477 (file-name-nondirectory newname))))
3480 (file-name-nondirectory dirname) newname)))
3481 (if (not (file-directory-p (file-name-directory newname)))
3482 (make-directory (file-name-directory newname) parents))
3483 (tramp-do-copy-or-rename-file-out-of-band
3484 'copy dirname newname keep-date))
3485 ;; We must do it file-wise.
3486 (tramp-run-real-handler
3487 'copy-directory (list dirname newname keep-date parents)))
3489 ;; When newname did exist, we have wrong cached values.
3491 (with-parsed-tramp-file-name newname nil
3492 (tramp-flush-file-property v (file-name-directory localname))
3493 (tramp-flush-file-property v localname))))))
3495 (defun tramp-handle-rename-file
3496 (filename newname &optional ok-if-already-exists)
3497 "Like `rename-file' for Tramp files."
3498 ;; Check if both files are local -- invoke normal rename-file.
3499 ;; Otherwise, use Tramp from local system.
3500 (setq filename (expand-file-name filename))
3501 (setq newname (expand-file-name newname))
3502 ;; At least one file a Tramp file?
3503 (if (or (tramp-tramp-file-p filename)
3504 (tramp-tramp-file-p newname))
3505 (tramp-do-copy-or-rename-file
3506 'rename filename newname ok-if-already-exists t t)
3507 (tramp-run-real-handler
3508 'rename-file (list filename newname ok-if-already-exists))))
3510 (defun tramp-do-copy-or-rename-file
3511 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3512 "Copy or rename a remote file.
3513 OP must be `copy' or `rename' and indicates the operation to perform.
3514 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3515 the new file (for copy) or the new name of the file (for rename).
3516 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3517 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3518 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3519 the uid and gid if both files are on the same host.
3521 This function is invoked by `tramp-handle-copy-file' and
3522 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3523 and `rename'. FILENAME and NEWNAME must be absolute file names."
3524 (unless (memq op '(copy rename))
3525 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3526 (let ((t1 (tramp-tramp-file-p filename))
3527 (t2 (tramp-tramp-file-p newname))
3530 (when (and (not ok-if-already-exists) (file-exists-p newname))
3531 (with-parsed-tramp-file-name (if t1 filename newname) nil
3533 v 'file-already-exists "File %s already exists" newname)))
3535 (with-parsed-tramp-file-name (if t1 filename newname) nil
3536 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3538 ;; We start a pulsing progress reporter. Introduced in Emacs 24.1.
3539 (when (> (nth 7 (file-attributes filename)) tramp-copy-size-limit)
3542 'make-progress-reporter
3543 (format "Transferring %s to %s..." filename newname))
3544 tm (run-at-time 0 0.1 'progress-reporter-update pr))
3549 ;; Both are Tramp files.
3551 (with-parsed-tramp-file-name filename v1
3552 (with-parsed-tramp-file-name newname v2
3554 ;; Shortcut: if method, host, user are the same for both
3555 ;; files, we invoke `cp' or `mv' on the remote host
3557 ((tramp-equal-remote filename newname)
3558 (tramp-do-copy-or-rename-file-directly
3560 ok-if-already-exists keep-date preserve-uid-gid))
3562 ;; Try out-of-band operation.
3563 ((tramp-method-out-of-band-p
3564 v1 (nth 7 (file-attributes filename)))
3565 (tramp-do-copy-or-rename-file-out-of-band
3566 op filename newname keep-date))
3568 ;; No shortcut was possible. So we copy the
3569 ;; file first. If the operation was `rename', we go
3570 ;; back and delete the original file (if the copy was
3571 ;; successful). The approach is simple-minded: we
3572 ;; create a new buffer, insert the contents of the
3573 ;; source file into it, then write out the buffer to
3574 ;; the target file. The advantage is that it doesn't
3575 ;; matter which filename handlers are used for the
3576 ;; source and target file.
3578 (tramp-do-copy-or-rename-file-via-buffer
3579 op filename newname keep-date))))))
3581 ;; One file is a Tramp file, the other one is local.
3583 (with-parsed-tramp-file-name (if t1 filename newname) nil
3585 ;; Fast track on local machine.
3586 ((tramp-local-host-p v)
3587 (tramp-do-copy-or-rename-file-directly
3589 ok-if-already-exists keep-date preserve-uid-gid))
3591 ;; If the Tramp file has an out-of-band method, the corresponding
3592 ;; copy-program can be invoked.
3593 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3594 (tramp-do-copy-or-rename-file-out-of-band
3595 op filename newname keep-date))
3597 ;; Use the inline method via a Tramp buffer.
3598 (t (tramp-do-copy-or-rename-file-via-buffer
3599 op filename newname keep-date)))))
3602 ;; One of them must be a Tramp file.
3603 (error "Tramp implementation says this cannot happen")))
3605 ;; In case of `rename', we must flush the cache of the source file.
3606 (when (and t1 (eq op 'rename))
3607 (with-parsed-tramp-file-name filename nil
3608 (tramp-flush-file-property v (file-name-directory localname))
3609 (tramp-flush-file-property v localname)))
3611 ;; When newname did exist, we have wrong cached values.
3613 (with-parsed-tramp-file-name newname nil
3614 (tramp-flush-file-property v (file-name-directory localname))
3615 (tramp-flush-file-property v localname)))
3617 ;; Stop progress reporter.
3618 (if tm (cancel-timer tm))
3619 (with-parsed-tramp-file-name (if t1 filename newname) nil
3620 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
3622 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3623 "Use an Emacs buffer to copy or rename a file.
3624 First arg OP is either `copy' or `rename' and indicates the operation.
3625 FILENAME is the source file, NEWNAME the target file.
3626 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3628 ;; We must disable multibyte, because binary data shall not be
3630 (set-buffer-multibyte nil)
3631 (let ((coding-system-for-read 'binary)
3632 (jka-compr-inhibit t))
3633 (insert-file-contents-literally filename))
3634 ;; We don't want the target file to be compressed, so we let-bind
3635 ;; `jka-compr-inhibit' to t.
3636 (let ((coding-system-for-write 'binary)
3637 (jka-compr-inhibit t))
3638 (write-region (point-min) (point-max) newname)))
3639 ;; KEEP-DATE handling.
3640 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3642 (set-file-modes newname (tramp-default-file-modes filename))
3643 ;; If the operation was `rename', delete the original file.
3644 (unless (eq op 'copy) (delete-file filename)))
3646 (defun tramp-do-copy-or-rename-file-directly
3647 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3648 "Invokes `cp' or `mv' on the remote system.
3649 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3650 respectively. FILENAME specifies the file to copy or rename,
3651 NEWNAME is the name of the new file (for copy) or the new name of
3652 the file (for rename). Both files must reside on the same host.
3653 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3654 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3655 the uid and gid from FILENAME."
3656 (let ((t1 (tramp-tramp-file-p filename))
3657 (t2 (tramp-tramp-file-p newname))
3658 (file-times (nth 5 (file-attributes filename)))
3659 (file-modes (tramp-default-file-modes filename)))
3660 (with-parsed-tramp-file-name (if t1 filename newname) nil
3661 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3662 ((eq op 'copy) "cp -f")
3663 ((eq op 'rename) "mv -f")
3666 "Unknown operation `%s', must be `copy' or `rename'"
3670 (tramp-file-name-handler 'file-remote-p filename 'localname)
3674 (tramp-file-name-handler 'file-remote-p newname 'localname)
3676 (prefix (file-remote-p (if t1 filename newname)))
3680 ;; Both files are on a remote host, with same user.
3683 (tramp-send-command-and-check
3685 (format "%s %s %s" cmd
3686 (tramp-shell-quote-argument localname1)
3687 (tramp-shell-quote-argument localname2))))
3688 (with-current-buffer (tramp-get-buffer v)
3689 (goto-char (point-min))
3693 ;; Mask cp -f error.
3695 tramp-operation-not-permitted-regexp nil t))
3697 (tramp-error-with-buffer
3699 "Copying directly failed, see buffer `%s' for details."
3702 ;; We are on the local host.
3705 ;; We can do it directly.
3706 ((let (file-name-handler-alist)
3707 (and (file-readable-p localname1)
3708 (file-writable-p (file-name-directory localname2))
3709 (or (file-directory-p localname2)
3710 (file-writable-p localname2))))
3712 (tramp-compat-copy-file
3713 localname1 localname2 ok-if-already-exists
3714 keep-date preserve-uid-gid)
3715 (tramp-run-real-handler
3716 'rename-file (list localname1 localname2 ok-if-already-exists))))
3718 ;; We can do it directly with `tramp-send-command'
3719 ((and (file-readable-p (concat prefix localname1))
3721 (file-name-directory (concat prefix localname2)))
3722 (or (file-directory-p (concat prefix localname2))
3723 (file-writable-p (concat prefix localname2))))
3724 (tramp-do-copy-or-rename-file-directly
3725 op (concat prefix localname1) (concat prefix localname2)
3726 ok-if-already-exists keep-date t)
3727 ;; We must change the ownership to the local user.
3728 (tramp-set-file-uid-gid
3729 (concat prefix localname2)
3730 (tramp-get-local-uid 'integer)
3731 (tramp-get-local-gid 'integer)))
3733 ;; We need a temporary file in between.
3735 ;; Create the temporary file.
3736 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3743 (tramp-send-command-and-check
3746 (tramp-shell-quote-argument localname1)
3747 (tramp-shell-quote-argument tmpfile))))
3748 (tramp-error-with-buffer
3750 "Copying directly failed, see buffer `%s' for details."
3751 (tramp-get-buffer v)))
3752 ;; We must change the ownership as remote user.
3753 ;; Since this does not work reliable, we also
3754 ;; give read permissions.
3756 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3757 (tramp-set-file-uid-gid
3758 (concat prefix tmpfile)
3759 (tramp-get-local-uid 'integer)
3760 (tramp-get-local-gid 'integer)))
3763 (tramp-compat-copy-file
3764 localname1 tmpfile t
3765 keep-date preserve-uid-gid)
3766 (tramp-run-real-handler
3768 (list localname1 tmpfile t)))
3769 ;; We must change the ownership as local user.
3770 ;; Since this does not work reliable, we also
3771 ;; give read permissions.
3772 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3773 (tramp-set-file-uid-gid
3775 (tramp-get-remote-uid v 'integer)
3776 (tramp-get-remote-gid v 'integer))))
3778 ;; Move the temporary file to its destination.
3783 (tramp-send-command-and-check
3786 (tramp-shell-quote-argument tmpfile)
3787 (tramp-shell-quote-argument localname2))))
3788 (tramp-error-with-buffer
3790 "Copying directly failed, see buffer `%s' for details."
3791 (tramp-get-buffer v))))
3793 (tramp-run-real-handler
3795 (list tmpfile localname2 ok-if-already-exists)))))
3799 (delete-file tmpfile)
3802 ;; Set the time and mode. Mask possible errors.
3805 (set-file-times newname file-times)
3806 (set-file-modes newname file-modes))
3809 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3810 "Invoke rcp program to copy.
3811 The method used must be an out-of-band method."
3812 (let ((t1 (tramp-tramp-file-p filename))
3813 (t2 (tramp-tramp-file-p newname))
3814 copy-program copy-args copy-env copy-keep-date port spec
3817 (with-parsed-tramp-file-name (if t1 filename newname) nil
3820 ;; Both are Tramp files. We shall optimize it, when the
3821 ;; methods for filename and newname are the same.
3822 (let* ((dir-flag (file-directory-p filename))
3823 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3827 (file-name-nondirectory newname) tmpfile)))
3830 (tramp-do-copy-or-rename-file-out-of-band
3831 op filename tmpfile keep-date)
3832 (tramp-do-copy-or-rename-file-out-of-band
3833 'rename tmpfile newname keep-date))
3837 (tramp-compat-delete-directory
3838 (expand-file-name ".." tmpfile) 'recursive)
3839 (delete-file tmpfile))
3842 ;; Expand hops. Might be necessary for gateway methods.
3843 (setq v (car (tramp-compute-multi-hops v)))
3844 (aset v 3 localname)
3846 ;; Check which ones of source and target are Tramp files.
3847 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3849 (if (and (file-directory-p filename)
3851 (file-name-nondirectory filename)
3852 (file-name-nondirectory newname)))
3853 'file-name-directory
3855 (if t2 (tramp-make-copy-program-file-name v) newname)))
3857 ;; Check for port number. Until now, there's no need for handling
3858 ;; like method, user, host.
3859 (setq host (tramp-file-name-real-host v)
3860 port (tramp-file-name-port v)
3861 port (or (and port (number-to-string port)) ""))
3863 ;; Compose copy command.
3864 (setq spec (format-spec-make
3865 ?h host ?u user ?p port
3866 ?t (tramp-get-connection-property
3867 (tramp-get-connection-process v) "temp-file" "")
3868 ?k (if keep-date " " ""))
3869 copy-program (tramp-get-method-parameter
3870 method 'tramp-copy-program)
3871 copy-keep-date (tramp-get-method-parameter
3872 method 'tramp-copy-keep-date)
3880 ;; " " is indication for keep-date argument.
3881 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3882 (unless (member "" x) (mapconcat 'identity x " ")))
3883 (tramp-get-method-parameter method 'tramp-copy-args)))
3889 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3890 (unless (member "" x) (mapconcat 'identity x " ")))
3891 (tramp-get-method-parameter method 'tramp-copy-env))))
3893 ;; Check for program.
3894 (when (and (fboundp 'executable-find)
3895 (not (let ((default-directory
3896 (tramp-compat-temporary-file-directory)))
3897 (executable-find copy-program))))
3899 v 'file-error "Cannot find copy program: %s" copy-program))
3901 ;; Set variables for computing the prompt for reading
3903 (setq tramp-current-method (tramp-file-name-method v)
3904 tramp-current-user (tramp-file-name-user v)
3905 tramp-current-host (tramp-file-name-host v))
3909 ;; The default directory must be remote.
3910 (let ((default-directory
3911 (file-name-directory (if t1 filename newname)))
3912 (process-environment (copy-sequence process-environment)))
3913 ;; Set the transfer process properties.
3914 (tramp-set-connection-property
3915 v "process-name" (buffer-name (current-buffer)))
3916 (tramp-set-connection-property
3917 v "process-buffer" (current-buffer))
3919 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3920 (setenv (pop copy-env) (pop copy-env)))
3922 ;; Use an asynchronous process. By this, password can
3923 ;; be handled. The default directory must be local, in
3924 ;; order to apply the correct `copy-program'. We don't
3925 ;; set a timeout, because the copying of large files can
3926 ;; last longer than 60 secs.
3927 (let ((p (let ((default-directory
3928 (tramp-compat-temporary-file-directory)))
3929 (apply 'start-process
3930 (tramp-get-connection-property
3931 v "process-name" nil)
3932 (tramp-get-connection-property
3933 v "process-buffer" nil)
3935 (append copy-args (list source target))))))
3937 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3938 (tramp-set-process-query-on-exit-flag p nil)
3939 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
3941 ;; Reset the transfer process properties.
3942 (tramp-set-connection-property v "process-name" nil)
3943 (tramp-set-connection-property v "process-buffer" nil))
3945 ;; Handle KEEP-DATE argument.
3946 (when (and keep-date (not copy-keep-date))
3947 (set-file-times newname (nth 5 (file-attributes filename))))
3950 (unless (and keep-date copy-keep-date)
3952 (set-file-modes newname (tramp-default-file-modes filename)))))
3954 ;; If the operation was `rename', delete the original file.
3955 (unless (eq op 'copy)
3956 (if (file-regular-p filename)
3957 (delete-file filename)
3958 (tramp-compat-delete-directory filename 'recursive))))))
3960 (defun tramp-handle-make-directory (dir &optional parents)
3961 "Like `make-directory' for Tramp files."
3962 (setq dir (expand-file-name dir))
3963 (with-parsed-tramp-file-name dir nil
3964 (tramp-flush-directory-property v (file-name-directory localname))
3966 (tramp-barf-unless-okay
3969 (if parents "mkdir -p" "mkdir")
3970 (tramp-shell-quote-argument localname))
3971 "Couldn't make directory %s" dir))))
3973 (defun tramp-handle-delete-directory (directory &optional recursive)
3974 "Like `delete-directory' for Tramp files."
3975 (setq directory (expand-file-name directory))
3976 (with-parsed-tramp-file-name directory nil
3977 (tramp-flush-file-property v (file-name-directory localname))
3978 (tramp-flush-directory-property v localname)
3979 (unless (zerop (tramp-send-command-and-check
3983 (if recursive "rm -rf" "rmdir")
3984 (tramp-shell-quote-argument localname))))
3985 (tramp-error v 'file-error "Couldn't delete %s" directory))))
3987 (defun tramp-handle-delete-file (filename)
3988 "Like `delete-file' for Tramp files."
3989 (setq filename (expand-file-name filename))
3990 (with-parsed-tramp-file-name filename nil
3991 (tramp-flush-file-property v (file-name-directory localname))
3992 (tramp-flush-file-property v localname)
3993 (unless (zerop (tramp-send-command-and-check
3996 (tramp-shell-quote-argument localname))))
3997 (tramp-error v 'file-error "Couldn't delete %s" filename))))
4001 ;; CCC: This does not seem to be enough. Something dies when
4002 ;; we try and delete two directories under Tramp :/
4003 (defun tramp-handle-dired-recursive-delete-directory (filename)
4004 "Recursively delete the directory given.
4005 This is like `dired-recursive-delete-directory' for Tramp files."
4006 (with-parsed-tramp-file-name filename nil
4007 ;; Run a shell command 'rm -r <localname>'
4008 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
4009 (unless (file-exists-p filename)
4010 (tramp-error v 'file-error "No such directory: %s" filename))
4011 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
4014 (format "rm -rf %s" (tramp-shell-quote-argument localname))
4015 ;; Don't read the output, do it explicitely.
4017 ;; Wait for the remote system to return to us...
4018 ;; This might take a while, allow it plenty of time.
4019 (tramp-wait-for-output (tramp-get-connection-process v) 120)
4020 ;; Make sure that it worked...
4021 (tramp-flush-file-property v (file-name-directory localname))
4022 (tramp-flush-directory-property v localname)
4023 (and (file-exists-p filename)
4025 v 'file-error "Failed to recursively delete %s" filename))))
4027 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4028 "Like `dired-compress-file' for Tramp files."
4029 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4030 ;; Code stolen mainly from dired-aux.el.
4031 (with-parsed-tramp-file-name file nil
4032 (tramp-flush-file-property v localname)
4035 (if (not (featurep 'xemacs))
4037 (symbol-value 'dired-compress-file-suffixes)
4038 ;; XEmacs has `dired-compression-method-alist', which is
4039 ;; transformed into `dired-compress-file-suffixes' structure.
4042 (list (concat (regexp-quote (nth 1 x)) "\\'")
4044 (mapconcat 'identity (nth 3 x) " ")))
4045 (symbol-value 'dired-compression-method-alist))))
4047 ;; See if any suffix rule matches this file name.
4049 (let (case-fold-search)
4050 (if (string-match (car (car suffixes)) localname)
4051 (setq suffix (car suffixes) suffixes nil))
4052 (setq suffixes (cdr suffixes))))
4054 (cond ((file-symlink-p file)
4056 ((and suffix (nth 2 suffix))
4057 ;; We found an uncompression rule.
4058 (tramp-message v 0 "Uncompressing %s..." file)
4059 (when (zerop (tramp-send-command-and-check
4060 v (concat (nth 2 suffix) " "
4061 (tramp-shell-quote-argument localname))))
4062 (tramp-message v 0 "Uncompressing %s...done" file)
4063 ;; `dired-remove-file' is not defined in XEmacs
4064 (funcall (symbol-function 'dired-remove-file) file)
4065 (string-match (car suffix) file)
4066 (concat (substring file 0 (match-beginning 0)))))
4068 ;; We don't recognize the file as compressed, so compress it.
4070 (tramp-message v 0 "Compressing %s..." file)
4071 (when (zerop (tramp-send-command-and-check
4072 v (concat "gzip -f "
4073 (tramp-shell-quote-argument localname))))
4074 (tramp-message v 0 "Compressing %s...done" file)
4075 ;; `dired-remove-file' is not defined in XEmacs
4076 (funcall (symbol-function 'dired-remove-file) file)
4077 (cond ((file-exists-p (concat file ".gz"))
4078 (concat file ".gz"))
4079 ((file-exists-p (concat file ".z"))
4083 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4084 "Like `dired-uncache' for Tramp files."
4085 ;; DIR-P is valid for XEmacs only.
4086 (with-parsed-tramp-file-name
4087 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4088 (tramp-flush-file-property v localname)))
4090 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4091 ;; not sure at all that this is the right way to do it, but let's hope
4092 ;; it works for now, and wait for a guru to point out the Right Way to
4094 ;;(eval-when-compile
4095 ;; (unless (fboundp 'dired-insert-set-properties)
4096 ;; (fset 'dired-insert-set-properties 'ignore)))
4097 ;; Gerd suggests this:
4098 (eval-when-compile (require 'dired))
4099 ;; Note that dired is required at run-time, too, when it is needed.
4100 ;; It is only needed on XEmacs for the function
4101 ;; `dired-insert-set-properties'.
4103 (defun tramp-handle-insert-directory
4104 (filename switches &optional wildcard full-directory-p)
4105 "Like `insert-directory' for Tramp files."
4106 (setq filename (expand-file-name filename))
4107 (with-parsed-tramp-file-name filename nil
4108 (if (and (featurep 'ls-lisp)
4109 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4110 (tramp-run-real-handler
4111 'insert-directory (list filename switches wildcard full-directory-p))
4112 (when (stringp switches)
4113 (setq switches (split-string switches)))
4114 (when (and (member "--dired" switches)
4115 (not (tramp-get-ls-command-with-dired v)))
4116 (setq switches (delete "--dired" switches)))
4118 (setq wildcard (tramp-run-real-handler
4119 'file-name-nondirectory (list localname)))
4120 (setq localname (tramp-run-real-handler
4121 'file-name-directory (list localname))))
4122 (unless full-directory-p
4123 (setq switches (add-to-list 'switches "-d" 'append)))
4124 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4126 (setq switches (concat switches " " wildcard)))
4128 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4129 switches filename (if wildcard "yes" "no")
4130 (if full-directory-p "yes" "no"))
4131 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4132 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4133 (if full-directory-p
4136 (format "%s %s %s 2>/dev/null"
4137 (tramp-get-ls-command v)
4141 (tramp-shell-quote-argument (concat localname ".")))))
4142 (tramp-barf-unless-okay
4144 (format "cd %s" (tramp-shell-quote-argument
4145 (tramp-run-real-handler
4146 'file-name-directory (list localname))))
4148 (tramp-shell-quote-argument
4149 (tramp-run-real-handler 'file-name-directory (list localname))))
4153 (tramp-get-ls-command v)
4157 (tramp-run-real-handler
4158 'file-name-nondirectory (list localname)))))
4160 (tramp-shell-quote-argument
4161 (tramp-run-real-handler
4162 'file-name-nondirectory (list localname)))))))
4163 (let ((beg (point)))
4164 ;; We cannot use `insert-buffer-substring' because the Tramp
4165 ;; buffer changes its contents before insertion due to calling
4166 ;; `expand-file' and alike.
4168 (with-current-buffer (tramp-get-buffer v)
4171 ;; Check for "--dired" output.
4173 (when (looking-at "//SUBDIRED//")
4175 (when (looking-at "//DIRED//")
4176 (let ((end (tramp-compat-line-end-position))
4178 ;; Now read the numeric positions of file names.
4182 (while (< (point) end)
4183 (let ((start (+ beg (read (current-buffer))))
4184 (end (+ beg (read (current-buffer)))))
4185 (if (memq (char-after end) '(?\n ?\ ))
4186 ;; End is followed by \n or by " -> ".
4187 (put-text-property start end 'dired-filename t))))))
4188 ;; Remove trailing lines.
4189 (goto-char (tramp-compat-line-beginning-position))
4190 (while (looking-at "//")
4192 (delete-region (match-beginning 0) (point)))
4194 ;; The inserted file could be from somewhere else.
4195 (when (and (not wildcard) (not full-directory-p))
4196 (goto-char (point-max))
4197 (when (file-symlink-p filename)
4198 (goto-char (search-backward "->" beg 'noerror)))
4200 (if (zerop (length (file-name-nondirectory filename)))
4202 (file-name-nondirectory filename))
4204 (replace-match (file-relative-name filename) t))
4206 (goto-char (point-max))))))
4208 (defun tramp-handle-unhandled-file-name-directory (filename)
4209 "Like `unhandled-file-name-directory' for Tramp files."
4210 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4211 ;; for backward compatibility.
4212 (expand-file-name "~/"))
4214 ;; Canonicalization of file names.
4216 (defun tramp-handle-expand-file-name (name &optional dir)
4217 "Like `expand-file-name' for Tramp files.
4218 If the localname part of the given filename starts with \"/../\" then
4219 the result will be a local, non-Tramp, filename."
4220 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4221 (setq dir (or dir default-directory "/"))
4222 ;; Unless NAME is absolute, concat DIR and NAME.
4223 (unless (file-name-absolute-p name)
4224 (setq name (concat (file-name-as-directory dir) name)))
4225 ;; If NAME is not a Tramp file, run the real handler.
4226 (if (not (tramp-tramp-file-p name))
4227 (tramp-run-real-handler 'expand-file-name (list name nil))
4229 (with-parsed-tramp-file-name name nil
4230 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4231 (setq localname (concat "~/" localname)))
4232 ;; Tilde expansion if necessary. This needs a shell which
4233 ;; groks tilde expansion! The function `tramp-find-shell' is
4234 ;; supposed to find such a shell on the remote host. Please
4235 ;; tell me about it when this doesn't work on your system.
4236 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4237 (let ((uname (match-string 1 localname))
4238 (fname (match-string 2 localname)))
4239 ;; We cannot simply apply "~/", because under sudo "~/" is
4240 ;; expanded to the local user home directory but to the
4241 ;; root home directory. On the other hand, using always
4242 ;; the default user name for tilde expansion is not
4243 ;; appropriate either, because ssh and companions might
4244 ;; use a user name from the config file.
4245 (when (and (string-equal uname "~")
4246 (string-match "\\`su\\(do\\)?\\'" method))
4247 (setq uname (concat uname user)))
4249 (with-connection-property v uname
4251 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4252 (with-current-buffer (tramp-get-buffer v)
4253 (goto-char (point-min))
4255 (point) (tramp-compat-line-end-position)))))
4256 (setq localname (concat uname fname))))
4257 ;; There might be a double slash, for example when "~/"
4258 ;; expands to "/". Remove this.
4259 (while (string-match "//" localname)
4260 (setq localname (replace-match "/" t t localname)))
4261 ;; No tilde characters in file name, do normal
4262 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4263 ;; `directory-sep-char' here for XEmacs on Windows, which would
4264 ;; otherwise use backslash. `default-directory' is bound,
4265 ;; because on Windows there would be problems with UNC shares or
4267 (let ((directory-sep-char ?/)
4268 (default-directory (tramp-compat-temporary-file-directory)))
4269 (tramp-make-tramp-file-name
4271 (tramp-drop-volume-letter
4272 (tramp-run-real-handler
4273 'expand-file-name (list localname))))))))
4275 (defun tramp-replace-environment-variables (filename)
4276 "Replace environment variables in FILENAME.
4277 Return the string with the replaced variables."
4279 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4280 ;; `$' is coded as `$$'.
4282 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4283 (getenv (match-string 1 filename)))
4286 (substitute-in-file-name (match-string 0 filename))
4290 (defun tramp-handle-substitute-in-file-name (filename)
4291 "Like `substitute-in-file-name' for Tramp files.
4292 \"//\" and \"/~\" substitute only in the local filename part.
4293 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4294 beginning of local filename are not substituted."
4295 ;; First, we must replace environment variables.
4296 (setq filename (tramp-replace-environment-variables filename))
4297 (with-parsed-tramp-file-name filename nil
4298 (if (equal tramp-syntax 'url)
4299 ;; We need to check localname only. The other parts cannot contain
4301 (if (and (> (length localname) 1)
4302 (or (string-match "//" localname)
4303 (string-match "/~" localname 1)))
4304 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4305 (tramp-make-tramp-file-name
4306 (when method (substitute-in-file-name method))
4307 (when user (substitute-in-file-name user))
4308 (when host (substitute-in-file-name host))
4310 (tramp-run-real-handler
4311 'substitute-in-file-name (list localname)))))
4312 ;; Ignore in LOCALNAME everything before "//" or "/~".
4313 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4315 (concat (file-remote-p filename)
4316 (replace-match "\\1" nil nil localname)))
4317 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4318 (when (string-match "~$" filename)
4319 (setq filename (concat filename "/"))))
4320 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4322 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4323 ;; which calls corresponding functions (see minibuf.el).
4324 (when (fboundp 'minibuffer-electric-separator)
4329 (around ,(intern (format "tramp-advice-%s" x)) activate)
4330 "Invoke `substitute-in-file-name' for Tramp files."
4331 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4332 (tramp-tramp-file-p (buffer-substring)))
4333 ;; We don't need to handle `last-input-event', because
4334 ;; due to the key map we know it must be ?/ or ?~.
4335 (let ((s (concat (buffer-substring (point-min) (point))
4336 (string last-command-char))))
4337 (delete-region (point-min) (point))
4338 (insert (substitute-in-file-name s))
4339 (setq ad-return-value last-command-char))
4345 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4346 (ad-activate ',x)))))
4348 '(minibuffer-electric-separator
4349 minibuffer-electric-tilde)))
4352 ;;; Remote commands:
4354 (defun tramp-handle-executable-find (command)
4355 "Like `executable-find' for Tramp files."
4356 (with-parsed-tramp-file-name default-directory nil
4357 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4359 ;; We use BUFFER also as connection buffer during setup. Because of
4360 ;; this, its original contents must be saved, and restored once
4361 ;; connection has been setup.
4362 (defun tramp-handle-start-file-process (name buffer program &rest args)
4363 "Like `start-file-process' for Tramp files."
4364 (with-parsed-tramp-file-name default-directory nil
4365 (unless (stringp program)
4367 v 'file-error "pty association is not supported for `%s'" name))
4369 (let ((command (format "cd %s; exec %s"
4370 (tramp-shell-quote-argument localname)
4371 (mapconcat 'tramp-shell-quote-argument
4372 (cons program args) " ")))
4376 ;; BUFFER can be nil. We use a temporary buffer.
4377 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4378 (while (get-process name1)
4379 ;; NAME must be unique as process name.
4381 name1 (format "%s<%d>" name i)))
4383 ;; Set the new process properties.
4384 (tramp-set-connection-property v "process-name" name)
4385 (tramp-set-connection-property v "process-buffer" buffer)
4386 ;; Activate narrowing in order to save BUFFER contents.
4387 ;; Clear also the modification time; otherwise we might be
4388 ;; interrupted by `verify-visited-file-modtime'.
4389 (with-current-buffer (tramp-get-connection-buffer v)
4390 (clear-visited-file-modtime)
4391 (narrow-to-region (point-max) (point-max)))
4392 ;; Send the command. `tramp-send-command' opens a new
4394 (tramp-send-command v command nil t) ; nooutput
4395 ;; Set query flag for this process.
4396 (tramp-set-process-query-on-exit-flag
4397 (tramp-get-connection-process v) t)
4399 (tramp-get-connection-process v))
4401 (with-current-buffer (tramp-get-connection-buffer v)
4402 (if (string-match tramp-temp-buffer-name (buffer-name))
4404 (set-process-buffer (tramp-get-connection-process v) nil)
4405 (kill-buffer (current-buffer)))
4407 (goto-char (point-max))))
4408 (tramp-set-connection-property v "process-name" nil)
4409 (tramp-set-connection-property v "process-buffer" nil))))
4411 (defun tramp-handle-process-file
4412 (program &optional infile destination display &rest args)
4413 "Like `process-file' for Tramp files."
4414 ;; The implementation is not complete yet.
4415 (when (and (numberp destination) (zerop destination))
4416 (error "Implementation does not handle immediate return"))
4418 (with-parsed-tramp-file-name default-directory nil
4419 (let (command input tmpinput stderr tmpstderr outbuf ret)
4421 (setq command (mapconcat 'tramp-shell-quote-argument
4422 (cons program args) " "))
4425 (setq input "/dev/null")
4426 (setq infile (expand-file-name infile))
4427 (if (tramp-equal-remote default-directory infile)
4428 ;; INFILE is on the same remote host.
4429 (setq input (with-parsed-tramp-file-name infile nil localname))
4430 ;; INFILE must be copied to remote host.
4431 (setq input (tramp-make-tramp-temp-file v)
4432 tmpinput (tramp-make-tramp-file-name method user host input))
4433 (copy-file infile tmpinput t)))
4434 (when input (setq command (format "%s <%s" command input)))
4436 ;; Determine output.
4439 ((bufferp destination)
4440 (setq outbuf destination))
4442 ((stringp destination)
4443 (setq outbuf (get-buffer-create destination)))
4444 ;; (REAL-DESTINATION ERROR-DESTINATION)
4445 ((consp destination)
4448 ((bufferp (car destination))
4449 (setq outbuf (car destination)))
4450 ((stringp (car destination))
4451 (setq outbuf (get-buffer-create (car destination))))
4453 (setq outbuf (current-buffer))))
4456 ((stringp (cadr destination))
4457 (setcar (cdr destination) (expand-file-name (cadr destination)))
4458 (if (tramp-equal-remote default-directory (cadr destination))
4459 ;; stderr is on the same remote host.
4460 (setq stderr (with-parsed-tramp-file-name
4461 (cadr destination) nil localname))
4462 ;; stderr must be copied to remote host. The temporary
4463 ;; file must be deleted after execution.
4464 (setq stderr (tramp-make-tramp-temp-file v)
4465 tmpstderr (tramp-make-tramp-file-name
4466 method user host stderr))))
4467 ;; stderr to be discarded.
4468 ((null (cadr destination))
4469 (setq stderr "/dev/null"))))
4472 (setq outbuf (current-buffer))))
4473 (when stderr (setq command (format "%s 2>%s" command stderr)))
4475 ;; Send the command. It might not return in time, so we protect it.
4479 (tramp-send-command-and-check
4480 v (format "\\cd %s; %s"
4481 (tramp-shell-quote-argument localname)
4484 ;; We should show the output anyway.
4486 (with-current-buffer outbuf
4488 (with-current-buffer (tramp-get-connection-buffer v)
4490 (when display (display-buffer outbuf))))
4491 ;; When the user did interrupt, we should do it also. We use
4492 ;; return code -1 as marker.
4494 (kill-buffer (tramp-get-connection-buffer v))
4498 (kill-buffer (tramp-get-connection-buffer v))
4501 ;; Provide error file.
4502 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4504 ;; Cleanup. We remove all file cache values for the connection,
4505 ;; because the remote process could have changed them.
4506 (when tmpinput (delete-file tmpinput))
4508 ;; `process-file-side-effects' has been introduced with GNU
4509 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4510 ;; by `program'. If it doesn't exist, we assume its default
4512 (unless (and (boundp 'process-file-side-effects)
4513 (not (symbol-value 'process-file-side-effects)))
4514 (tramp-flush-directory-property v ""))
4516 ;; Return exit status.
4521 (defun tramp-local-call-process
4522 (program &optional infile destination display &rest args)
4523 "Calls `call-process' on the local host.
4524 This is needed because for some Emacs flavors Tramp has
4525 defadviced `call-process' to behave like `process-file'. The
4526 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4527 (let ((default-directory
4528 (if (file-remote-p default-directory)
4529 (tramp-compat-temporary-file-directory)
4530 default-directory)))
4531 (if (executable-find program)
4532 (apply 'call-process program infile destination display args)
4535 (defun tramp-handle-call-process-region
4536 (start end program &optional delete buffer display &rest args)
4537 "Like `call-process-region' for Tramp files."
4538 (let ((tmpfile (tramp-compat-make-temp-file "")))
4539 (write-region start end tmpfile)
4540 (when delete (delete-region start end))
4542 (apply 'call-process program tmpfile buffer display args)
4543 (delete-file tmpfile))))
4545 (defun tramp-handle-shell-command
4546 (command &optional output-buffer error-buffer)
4547 "Like `shell-command' for Tramp files."
4548 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4549 ;; We cannot use `shell-file-name' and `shell-command-switch',
4550 ;; they are variables of the local host.
4551 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
4555 ((bufferp output-buffer) output-buffer)
4556 ((stringp output-buffer) (get-buffer-create output-buffer))
4558 (setq current-buffer-p t)
4560 (t (get-buffer-create
4562 "*Async Shell Command*"
4563 "*Shell Command Output*")))))
4566 ((bufferp error-buffer) error-buffer)
4567 ((stringp error-buffer) (get-buffer-create error-buffer))))
4569 (if (and (not asynchronous) error-buffer)
4570 (with-parsed-tramp-file-name default-directory nil
4571 (list output-buffer (tramp-make-tramp-temp-file v)))
4573 (p (get-buffer-process output-buffer)))
4575 ;; Check whether there is another process running. Tramp does not
4576 ;; support 2 (asynchronous) processes in parallel.
4578 (if (yes-or-no-p "A command is running. Kill it? ")
4582 (error "Shell command in progress")))
4584 (if current-buffer-p
4586 (barf-if-buffer-read-only)
4588 (with-current-buffer output-buffer
4589 (setq buffer-read-only nil)
4592 (if (and (not current-buffer-p) (integerp asynchronous))
4595 (apply 'start-file-process "*Async Shell*" buffer args)
4597 (pop-to-buffer output-buffer)
4598 (setq mode-line-process '(":%s"))
4599 (require 'shell) (shell-mode))
4603 (apply 'process-file (car args) nil buffer nil (cdr args))
4604 ;; Insert error messages if they were separated.
4605 (when (listp buffer)
4606 (with-current-buffer error-buffer
4607 (insert-file-contents (cadr buffer)))
4608 (delete-file (cadr buffer)))
4609 (if current-buffer-p
4610 ;; This is like exchange-point-and-mark, but doesn't
4611 ;; activate the mark. It is cleaner to avoid activation,
4612 ;; even though the command loop would deactivate the mark
4613 ;; because we inserted text.
4614 (goto-char (prog1 (mark t)
4615 (set-marker (mark-marker) (point)
4617 ;; There's some output, display it.
4618 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4619 (if (functionp 'display-message-or-buffer)
4620 (funcall (symbol-function 'display-message-or-buffer)
4622 (pop-to-buffer output-buffer))))))))
4626 (defvar tramp-handle-file-local-copy-hook nil
4627 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4629 (defun tramp-handle-file-local-copy (filename)
4630 "Like `file-local-copy' for Tramp files."
4632 (with-parsed-tramp-file-name filename nil
4633 (unless (file-exists-p filename)
4636 "Cannot make local copy of non-existing file `%s'" filename))
4638 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
4639 (loc-dec (tramp-get-local-coding v "local-decoding"))
4640 (tmpfile (tramp-compat-make-temp-file filename)))
4644 ;; `copy-file' handles direct copy and out-of-band methods.
4645 ((or (tramp-local-host-p v)
4646 (tramp-method-out-of-band-p
4647 v (nth 7 (file-attributes filename))))
4648 (copy-file filename tmpfile t t))
4650 ;; Use inline encoding for file transfer.
4653 (tramp-message v 5 "Encoding remote file %s..." filename)
4654 (tramp-barf-unless-okay
4656 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4657 "Encoding remote file failed")
4658 (tramp-message v 5 "Encoding remote file %s...done" filename)
4660 (if (and (symbolp loc-dec) (fboundp loc-dec))
4661 ;; If local decoding is a function, we call it. We
4662 ;; must disable multibyte, because
4663 ;; `uudecode-decode-region' doesn't handle it
4666 (set-buffer-multibyte nil)
4667 (insert-buffer-substring (tramp-get-buffer v))
4669 v 5 "Decoding remote file %s with function %s..."
4671 (funcall loc-dec (point-min) (point-max))
4672 ;; Unset `file-name-handler-alist'. Otherwise,
4673 ;; epa-file gets confused.
4674 (let (file-name-handler-alist
4675 (coding-system-for-write 'binary))
4676 (write-region (point-min) (point-max) tmpfile)))
4678 ;; If tramp-decoding-function is not defined for this
4679 ;; method, we invoke tramp-decoding-command instead.
4680 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4681 ;; Unset `file-name-handler-alist'. Otherwise,
4682 ;; epa-file gets confused.
4683 (let (file-name-handler-alist
4684 (coding-system-for-write 'binary))
4685 (write-region (point-min) (point-max) tmpfile2))
4687 v 5 "Decoding remote file %s with command %s..."
4690 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4691 (delete-file tmpfile2))))
4693 (tramp-message v 5 "Decoding remote file %s...done" filename)
4694 ;; Set proper permissions.
4695 (set-file-modes tmpfile (tramp-default-file-modes filename))
4696 ;; Set local user ownership.
4697 (tramp-set-file-uid-gid tmpfile)))
4699 ;; Oops, I don't know what to do.
4701 v 'file-error "Wrong method specification for `%s'" method)))
4705 (delete-file tmpfile)
4706 (signal (car err) (cdr err))))
4708 (run-hooks 'tramp-handle-file-local-copy-hook)
4711 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4712 "Like `file-remote-p' for Tramp files."
4713 (let ((tramp-verbose 3))
4714 (when (tramp-tramp-file-p filename)
4715 (let* ((v (tramp-dissect-file-name filename))
4716 (p (tramp-get-connection-process v))
4717 (c (and p (processp p) (memq (process-status p) '(run open)))))
4718 ;; We expand the file name only, if there is already a connection.
4719 (with-parsed-tramp-file-name
4720 (if c (expand-file-name filename) filename) nil
4721 (and (or (not connected) c)
4723 ((eq identification 'method) method)
4724 ((eq identification 'user) user)
4725 ((eq identification 'host) host)
4726 ((eq identification 'localname) localname)
4727 (t (tramp-make-tramp-file-name method user host "")))))))))
4729 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4730 "Like `find-operation-coding-system' for Tramp filenames.
4731 Tramp's `insert-file-contents' and `write-region' work over
4732 temporary file names. If `file-coding-system-alist' contains an
4733 expression, which matches more than the file name suffix, the
4734 coding system might not be determined. This function repairs it."
4736 (dolist (elt file-coding-system-alist result)
4737 (when (and (consp elt) (string-match (car elt) filename))
4738 ;; We found a matching entry in `file-coding-system-alist'.
4739 ;; So we add a similar entry, but with the temporary file name
4742 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4744 (defun tramp-handle-insert-file-contents
4745 (filename &optional visit beg end replace)
4746 "Like `insert-file-contents' for Tramp files."
4747 (barf-if-buffer-read-only)
4748 (setq filename (expand-file-name filename))
4749 (let (coding-system-used result local-copy remote-copy)
4750 (with-parsed-tramp-file-name filename nil
4752 (if (not (file-exists-p filename))
4753 ;; We don't raise a Tramp error, because it might be
4754 ;; suppressed, like in `find-file-noselect-1'.
4756 (list "File not found on remote host" filename))
4758 (if (and (tramp-local-host-p v)
4759 (let (file-name-handler-alist)
4760 (file-readable-p localname)))
4761 ;; Short track: if we are on the local host, we can
4764 (tramp-run-real-handler
4765 'insert-file-contents
4766 (list localname visit beg end replace)))
4768 ;; When we shall insert only a part of the file, we copy
4771 (setq remote-copy (tramp-make-tramp-temp-file v))
4776 (format "tail -c +%d %s | head -c +%d >%s"
4777 (1+ beg) (tramp-shell-quote-argument localname)
4778 (- end beg) remote-copy))
4780 (format "tail -c +%d %s >%s"
4781 (1+ beg) (tramp-shell-quote-argument localname)
4784 (format "head -c +%d %s >%s"
4785 (1+ end) (tramp-shell-quote-argument localname)
4788 ;; `insert-file-contents-literally' takes care to avoid
4789 ;; calling jka-compr. By let-binding
4790 ;; `inhibit-file-name-operation', we propagate that care
4791 ;; to the `file-local-copy' operation.
4793 (let ((inhibit-file-name-operation
4794 (when (eq inhibit-file-name-operation
4795 'insert-file-contents)
4798 ((stringp remote-copy)
4800 (tramp-make-tramp-file-name
4801 method user host remote-copy)))
4802 ((stringp tramp-temp-buffer-file-name)
4803 (copy-file filename tramp-temp-buffer-file-name 'ok)
4804 tramp-temp-buffer-file-name)
4805 (t (file-local-copy filename)))))
4807 ;; When the file is not readable for the owner, it
4808 ;; cannot be inserted, even it is redable for the group
4809 ;; or for everybody.
4810 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4812 (when (and (null remote-copy)
4813 (tramp-get-method-parameter
4814 method 'tramp-copy-keep-tmpfile))
4815 ;; We keep the local file for performance reasons,
4816 ;; useful for "rsync".
4817 (setq tramp-temp-buffer-file-name local-copy)
4818 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4821 v 4 "Inserting local temp file `%s'..." local-copy)
4823 ;; We must ensure that `file-coding-system-alist'
4824 ;; matches `local-copy'.
4825 (let ((file-coding-system-alist
4826 (tramp-find-file-name-coding-system-alist
4827 filename local-copy)))
4829 (insert-file-contents
4830 local-copy nil nil nil replace))
4831 ;; Now `last-coding-system-used' has right value.
4833 (when (boundp 'last-coding-system-used)
4834 (setq coding-system-used
4835 (symbol-value 'last-coding-system-used))))
4838 v 4 "Inserting local temp file `%s'...done" local-copy)
4839 (when (boundp 'last-coding-system-used)
4840 (set 'last-coding-system-used coding-system-used))))
4845 (setq buffer-file-name filename)
4846 (setq buffer-read-only (not (file-writable-p filename)))
4847 (set-visited-file-modtime)
4848 (set-buffer-modified-p nil))
4849 (when (and (stringp local-copy)
4850 (or remote-copy (null tramp-temp-buffer-file-name)))
4851 (delete-file local-copy))
4852 (when (stringp remote-copy)
4854 (tramp-make-tramp-file-name method user host remote-copy))))))
4857 (list (expand-file-name filename)
4860 ;; This is needed for XEmacs only. Code stolen from files.el.
4861 (defun tramp-handle-insert-file-contents-literally
4862 (filename &optional visit beg end replace)
4863 "Like `insert-file-contents-literally' for Tramp files."
4864 (let ((format-alist nil)
4865 (after-insert-file-functions nil)
4866 (coding-system-for-read 'no-conversion)
4867 (coding-system-for-write 'no-conversion)
4868 (find-buffer-file-type-function
4869 (if (fboundp 'find-buffer-file-type)
4870 (symbol-function 'find-buffer-file-type)
4872 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4873 (inhibit-file-name-operation 'insert-file-contents))
4876 (fset 'find-buffer-file-type (lambda (filename) t))
4877 (insert-file-contents filename visit beg end replace))
4879 (if find-buffer-file-type-function
4880 (fset 'find-buffer-file-type find-buffer-file-type-function)
4881 (fmakunbound 'find-buffer-file-type)))))
4883 (defun tramp-handle-find-backup-file-name (filename)
4884 "Like `find-backup-file-name' for Tramp files."
4885 (with-parsed-tramp-file-name filename nil
4886 ;; We set both variables. It doesn't matter whether it is
4888 (let ((backup-directory-alist
4890 (when (boundp 'backup-directory-alist)
4891 (if (symbol-value 'tramp-backup-directory-alist)
4896 (if (and (stringp (cdr x))
4897 (file-name-absolute-p (cdr x))
4898 (not (tramp-file-name-p (cdr x))))
4899 (tramp-make-tramp-file-name method user host (cdr x))
4901 (symbol-value 'tramp-backup-directory-alist))
4902 (symbol-value 'backup-directory-alist))))
4904 (bkup-backup-directory-info
4906 (when (boundp 'bkup-backup-directory-info)
4907 (if (symbol-value 'tramp-bkup-backup-directory-info)
4913 (if (and (stringp (car (cdr x)))
4914 (file-name-absolute-p (car (cdr x)))
4915 (not (tramp-file-name-p (car (cdr x)))))
4916 (tramp-make-tramp-file-name
4917 method user host (car (cdr x)))
4920 (symbol-value 'tramp-bkup-backup-directory-info))
4921 (symbol-value 'bkup-backup-directory-info)))))
4923 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
4925 (defun tramp-handle-make-auto-save-file-name ()
4926 "Like `make-auto-save-file-name' for Tramp files.
4927 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
4928 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4930 (tramp-subst-strs-in-string
4937 (buffer-file-name))))
4938 ;; File name must be unique. This is ensured with Emacs 22 (see
4939 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4940 ;; all other cases we must do it ourselves.
4941 (when (boundp 'auto-save-file-name-transforms)
4944 (when (and (string-match (car x) buffer-file-name)
4945 (not (car (cddr x))))
4946 (setq tramp-auto-save-directory
4947 (or tramp-auto-save-directory
4948 (tramp-compat-temporary-file-directory)))))
4949 (symbol-value 'auto-save-file-name-transforms)))
4950 ;; Create directory.
4951 (when tramp-auto-save-directory
4952 (setq buffer-file-name
4953 (expand-file-name buffer-file-name tramp-auto-save-directory))
4954 (unless (file-exists-p tramp-auto-save-directory)
4955 (make-directory tramp-auto-save-directory t)))
4956 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4957 ;; it is not a magic file name operation (since Emacs 22).
4958 ;; We must deactivate it temporarily.
4959 (if (not (ad-is-active 'make-auto-save-file-name))
4960 (tramp-run-real-handler 'make-auto-save-file-name nil)
4962 (ad-deactivate 'make-auto-save-file-name)
4964 (tramp-run-real-handler 'make-auto-save-file-name nil)
4965 (ad-activate 'make-auto-save-file-name)))))
4967 (defvar tramp-handle-write-region-hook nil
4968 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4970 ;; CCC grok LOCKNAME
4971 (defun tramp-handle-write-region
4972 (start end filename &optional append visit lockname confirm)
4973 "Like `write-region' for Tramp files."
4974 (setq filename (expand-file-name filename))
4975 (with-parsed-tramp-file-name filename nil
4976 ;; Following part commented out because we don't know what to do about
4977 ;; file locking, and it does not appear to be a problem to ignore it.
4978 ;; Ange-ftp ignores it, too.
4979 ;; (when (and lockname (stringp lockname))
4980 ;; (setq lockname (expand-file-name lockname)))
4981 ;; (unless (or (eq lockname nil)
4982 ;; (string= lockname filename))
4984 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
4986 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
4987 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4988 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4989 (tramp-error v 'file-error "File not overwritten")))
4991 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
4992 (tramp-get-remote-uid v 'integer)))
4993 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
4994 (tramp-get-remote-gid v 'integer))))
4996 (if (and (tramp-local-host-p v)
4997 ;; `file-writable-p' calls `file-expand-file-name'. We
4998 ;; cannot use `tramp-run-real-handler' therefore.
4999 (let (file-name-handler-alist)
5001 (file-writable-p (file-name-directory localname))
5002 (or (file-directory-p localname)
5003 (file-writable-p localname)))))
5004 ;; Short track: if we are on the local host, we can run directly.
5005 (tramp-run-real-handler
5007 (list start end localname append 'no-message lockname confirm))
5009 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
5010 (loc-enc (tramp-get-local-coding v "local-encoding"))
5011 (modes (save-excursion (tramp-default-file-modes filename)))
5012 ;; We use this to save the value of
5013 ;; `last-coding-system-used' after writing the tmp file.
5014 ;; At the end of the function, we set
5015 ;; `last-coding-system-used' to this saved value. This
5016 ;; way, any intermediary coding systems used while
5017 ;; talking to the remote shell or suchlike won't hose
5018 ;; this variable. This approach was snarfed from
5021 ;; Write region into a tmp file. This isn't really
5022 ;; needed if we use an encoding function, but currently
5023 ;; we use it always because this makes the logic
5025 (tmpfile (or tramp-temp-buffer-file-name
5026 (tramp-compat-make-temp-file filename))))
5028 ;; If `append' is non-nil, we copy the file locally, and let
5029 ;; the native `write-region' implementation do the job.
5030 (when append (copy-file filename tmpfile 'ok))
5032 ;; We say `no-message' here because we don't want the
5033 ;; visited file modtime data to be clobbered from the temp
5034 ;; file. We call `set-visited-file-modtime' ourselves later
5035 ;; on. We must ensure that `file-coding-system-alist'
5036 ;; matches `tmpfile'.
5037 (let ((file-coding-system-alist
5038 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5040 (tramp-run-real-handler
5042 (list start end tmpfile append 'no-message lockname confirm))
5044 (setq tramp-temp-buffer-file-name nil)
5045 (delete-file tmpfile)
5046 (signal (car err) (cdr err))))
5048 ;; Now, `last-coding-system-used' has the right value. Remember it.
5049 (when (boundp 'last-coding-system-used)
5050 (setq coding-system-used
5051 (symbol-value 'last-coding-system-used))))
5053 ;; The permissions of the temporary file should be set. If
5054 ;; filename does not exist (eq modes nil) it has been
5055 ;; renamed to the backup file. This case `save-buffer'
5056 ;; handles permissions.
5057 ;; Ensure, that it is still readable.
5060 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
5062 ;; This is a bit lengthy due to the different methods
5063 ;; possible for file transfer. First, we check whether the
5064 ;; method uses an rcp program. If so, we call it.
5065 ;; Otherwise, both encoding and decoding command must be
5066 ;; specified. However, if the method _also_ specifies an
5067 ;; encoding function, then that is used for encoding the
5068 ;; contents of the tmp file.
5070 ;; `copy-file' handles direct copy and out-of-band methods.
5071 ((or (tramp-local-host-p v)
5072 (tramp-method-out-of-band-p
5073 v (nth 7 (file-attributes tmpfile))))
5074 (if (and (not (stringp start))
5075 (= (or end (point-max)) (point-max))
5076 (= (or start (point-min)) (point-min))
5077 (tramp-get-method-parameter
5078 method 'tramp-copy-keep-tmpfile))
5080 (setq tramp-temp-buffer-file-name tmpfile)
5082 ;; We keep the local file for performance
5083 ;; reasons, useful for "rsync".
5084 (copy-file tmpfile filename t)
5086 (setq tramp-temp-buffer-file-name nil)
5087 (delete-file tmpfile)
5088 (signal (car err) (cdr err)))))
5089 (setq tramp-temp-buffer-file-name nil)
5090 ;; Don't rename, in order to keep context in SELinux.
5092 (copy-file tmpfile filename t)
5093 (delete-file tmpfile))))
5095 ;; Use inline file transfer.
5098 (tramp-message v 5 "Encoding region...")
5101 ;; Use encoding function or command.
5102 (if (and (symbolp loc-enc) (fboundp loc-enc))
5105 v 5 "Encoding region using function `%s'..."
5106 (symbol-name loc-enc))
5107 (let ((coding-system-for-read 'binary))
5108 (insert-file-contents-literally tmpfile))
5109 ;; The following `let' is a workaround for the
5110 ;; base64.el that comes with pgnus-0.84. If
5111 ;; both of the following conditions are
5112 ;; satisfied, it tries to write to a local
5113 ;; file in default-directory, but at this
5114 ;; point, default-directory is remote.
5115 ;; (`call-process-region' can't write to
5116 ;; remote files, it seems.) The file in
5117 ;; question is a tmp file anyway.
5118 (let ((default-directory
5119 (tramp-compat-temporary-file-directory)))
5120 (funcall loc-enc (point-min) (point-max))))
5123 v 5 "Encoding region using command `%s'..." loc-enc)
5124 (unless (equal 0 (tramp-call-local-coding-command
5128 "Cannot write to `%s', local encoding command `%s' failed"
5131 ;; Send buffer into remote decoding command which
5132 ;; writes to remote file. Because this happens on
5133 ;; the remote host, we cannot use the function.
5134 (goto-char (point-max))
5135 (unless (bolp) (newline))
5137 v 5 "Decoding region into remote file %s..." filename)
5141 "%s >%s <<'EOF'\n%sEOF"
5143 (tramp-shell-quote-argument localname)
5145 (tramp-barf-unless-okay
5147 "Couldn't write region to `%s', decode using `%s' failed"
5149 ;; When `file-precious-flag' is set, the region is
5150 ;; written to a temporary file. Check that the
5151 ;; checksum is equal to that from the local tmpfile.
5152 (when file-precious-flag
5155 ;; cksum runs locally, if possible.
5156 (zerop (tramp-local-call-process "cksum" tmpfile t))
5157 ;; cksum runs remotely.
5159 (tramp-send-command-and-check
5162 "cksum <%s" (tramp-shell-quote-argument localname))))
5163 ;; ... they are different.
5167 (with-current-buffer (tramp-get-buffer v)
5171 (concat "Couldn't write region to `%s',"
5172 " decode using `%s' failed")
5175 v 5 "Decoding region into remote file %s...done" filename))
5178 (delete-file tmpfile)))
5180 ;; That's not expected.
5184 (concat "Method `%s' should specify both encoding and "
5185 "decoding command or an rcp program")
5188 ;; Make `last-coding-system-used' have the right value.
5189 (when coding-system-used
5190 (set 'last-coding-system-used coding-system-used))))
5192 (tramp-flush-file-property v (file-name-directory localname))
5193 (tramp-flush-file-property v localname)
5195 ;; We must protect `last-coding-system-used', now we have set it
5196 ;; to its correct value.
5197 (let (last-coding-system-used (need-chown t))
5198 ;; Set file modification time.
5199 (when (or (eq visit t) (stringp visit))
5200 (let ((file-attr (file-attributes filename)))
5201 (set-visited-file-modtime
5202 ;; We must pass modtime explicitely, because filename can
5203 ;; be different from (buffer-file-name), f.e. if
5204 ;; `file-precious-flag' is set.
5206 (when (and (eq (nth 2 file-attr) uid)
5207 (eq (nth 3 file-attr) gid))
5208 (setq need-chown nil))))
5210 ;; Set the ownership.
5212 (tramp-set-file-uid-gid filename uid gid))
5213 (when (or (eq visit t) (null visit) (stringp visit))
5214 (tramp-message v 0 "Wrote %s" filename))
5215 (run-hooks 'tramp-handle-write-region-hook)))))
5217 (defvar tramp-vc-registered-file-names nil
5218 "List used to collect file names, which are checked during `vc-registered'.")
5220 ;; VC backends check for the existence of various different special
5221 ;; files. This is very time consuming, because every single check
5222 ;; requires a remote command (the file cache must be invalidated).
5223 ;; Therefore, we apply a kind of optimization. We install the file
5224 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5225 ;; remembers all file names for which `file-exists-p' or
5226 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5227 ;; is performed. Afterwards, a script is applied for all collected
5228 ;; file names, using just one remote command. The result of this
5229 ;; script is used to fill the file cache with actual values. Now we
5230 ;; can reset the file name handlers, and we make a second run of
5231 ;; `vc-registered', which returns the expected result without sending
5232 ;; any other remote command.
5233 (defun tramp-handle-vc-registered (file)
5234 "Like `vc-registered' for Tramp files."
5235 (with-parsed-tramp-file-name file nil
5237 ;; There could be new files, created by the vc backend. We cannot
5238 ;; reuse the old cache entries, therefore.
5239 (let (tramp-vc-registered-file-names
5240 (tramp-cache-inhibit-cache (current-time))
5241 (file-name-handler-alist
5242 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5244 ;; Here we collect only file names, which need an operation.
5245 (tramp-run-real-handler 'vc-registered (list file))
5246 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5248 ;; Send just one command, in order to fill the cache.
5249 (when tramp-vc-registered-file-names
5250 (tramp-maybe-send-script
5252 (format tramp-vc-registered-read-file-names
5253 (tramp-get-file-exists-command v)
5254 (format "%s -r" (tramp-get-test-command v)))
5255 "tramp_vc_registered_read_file_names")
5259 (tramp-send-command-and-read
5262 "tramp_vc_registered_read_file_names %s"
5263 (mapconcat 'tramp-shell-quote-argument
5264 tramp-vc-registered-file-names
5267 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
5269 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
5270 ;; shall be answered from the file cache.
5271 ;; We unset `process-file-side-effects' in order to keep the cache
5272 ;; when `process-file' calls appear.
5273 (let (process-file-side-effects)
5274 (tramp-run-real-handler 'vc-registered (list file)))))
5277 (progn (defun tramp-run-real-handler (operation args)
5278 "Invoke normal file name handler for OPERATION.
5279 First arg specifies the OPERATION, second arg is a list of arguments to
5280 pass to the OPERATION."
5281 (let* ((inhibit-file-name-handlers
5282 `(tramp-file-name-handler
5283 tramp-vc-file-name-handler
5284 tramp-completion-file-name-handler
5285 cygwin-mount-name-hook-function
5286 cygwin-mount-map-drive-hook-function
5288 ,(and (eq inhibit-file-name-operation operation)
5289 inhibit-file-name-handlers)))
5290 (inhibit-file-name-operation operation))
5291 (apply operation args))))
5294 (progn (defun tramp-completion-run-real-handler (operation args)
5295 "Invoke `tramp-file-name-handler' for OPERATION.
5296 First arg specifies the OPERATION, second arg is a list of arguments to
5297 pass to the OPERATION."
5298 (let* ((inhibit-file-name-handlers
5299 `(tramp-completion-file-name-handler
5300 cygwin-mount-name-hook-function
5301 cygwin-mount-map-drive-hook-function
5303 ,(and (eq inhibit-file-name-operation operation)
5304 inhibit-file-name-handlers)))
5305 (inhibit-file-name-operation operation))
5306 (apply operation args))))
5308 ;; We handle here all file primitives. Most of them have the file
5309 ;; name as first parameter; nevertheless we check for them explicitly
5310 ;; in order to be signaled if a new primitive appears. This
5311 ;; scenario is needed because there isn't a way to decide by
5312 ;; syntactical means whether a foreign method must be called. It would
5313 ;; ease the life if `file-name-handler-alist' would support a decision
5314 ;; function as well but regexp only.
5315 (defun tramp-file-name-for-operation (operation &rest args)
5316 "Return file name related to OPERATION file primitive.
5317 ARGS are the arguments OPERATION has been called with."
5319 ;; FILE resp DIRECTORY.
5321 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5322 'delete-file 'diff-latest-backup-file 'directory-file-name
5323 'directory-files 'directory-files-and-attributes
5324 'dired-compress-file 'dired-uncache
5325 'file-accessible-directory-p 'file-attributes
5326 'file-directory-p 'file-executable-p 'file-exists-p
5327 'file-local-copy 'file-remote-p 'file-modes
5328 'file-name-as-directory 'file-name-directory
5329 'file-name-nondirectory 'file-name-sans-versions
5330 'file-ownership-preserved-p 'file-readable-p
5331 'file-regular-p 'file-symlink-p 'file-truename
5332 'file-writable-p 'find-backup-file-name 'find-file-noselect
5333 'get-file-buffer 'insert-directory 'insert-file-contents
5334 'load 'make-directory 'make-directory-internal
5335 'set-file-modes 'substitute-in-file-name
5336 'unhandled-file-name-directory 'vc-registered
5340 'abbreviate-file-name 'create-file-buffer
5341 'dired-file-modtime 'dired-make-compressed-filename
5342 'dired-recursive-delete-directory 'dired-set-file-modtime
5343 'dired-shell-unhandle-file-name 'dired-uucode-file
5344 'insert-file-contents-literally 'make-temp-name 'recover-file
5345 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5346 (if (file-name-absolute-p (nth 0 args))
5348 (expand-file-name (nth 0 args))))
5349 ;; FILE DIRECTORY resp FILE1 FILE2.
5351 (list 'add-name-to-file 'copy-file 'expand-file-name
5352 'file-name-all-completions 'file-name-completion
5353 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5357 'dired-make-relative-symlink
5358 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5361 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5362 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5363 (t (buffer-file-name (current-buffer))))))
5365 ((eq operation 'write-region)
5369 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5371 'make-auto-save-file-name
5375 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5378 (list ;; not in Emacs 23+.
5387 'dired-print-file 'dired-shell-call-process
5389 'executable-find 'start-process 'call-process))
5391 ;; Unknown file primitive.
5392 (t (error "unknown file I/O primitive: %s" operation))))
5394 (defun tramp-find-foreign-file-name-handler (filename)
5395 "Return foreign file name handler if exists."
5396 (when (tramp-tramp-file-p filename)
5397 (let ((v (tramp-dissect-file-name filename t))
5398 (handler tramp-foreign-file-name-handler-alist)
5400 ;; When we are not fully sure that filename completion is safe,
5401 ;; we should not return a handler.
5402 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5403 (and (tramp-file-name-host v)
5404 (not (member (tramp-file-name-host v)
5405 (mapcar 'car tramp-methods))))
5406 (not (tramp-completion-mode-p)))
5408 (setq elt (car handler)
5409 handler (cdr handler))
5410 (when (funcall (car elt) filename)
5417 (defun tramp-file-name-handler (operation &rest args)
5418 "Invoke Tramp file name handler.
5419 Falls back to normal file name handler if no Tramp file name handler exists."
5423 (tramp-replace-environment-variables
5424 (apply 'tramp-file-name-for-operation operation args)))
5425 (completion (tramp-completion-mode-p))
5426 (foreign (tramp-find-foreign-file-name-handler filename)))
5427 (with-parsed-tramp-file-name filename nil
5429 ;; When we are in completion mode, some operations
5430 ;; shouldn't be handled by backend.
5431 ((and completion (zerop (length localname))
5432 (memq operation '(file-exists-p file-directory-p)))
5434 ((and completion (zerop (length localname))
5435 (memq operation '(file-name-as-directory)))
5437 ;; Call the backend function.
5438 (foreign (apply foreign operation args))
5439 ;; Nothing to do for us.
5440 (t (tramp-run-real-handler operation args))))))
5441 ;; When `tramp-mode' is not enabled, we don't do anything.
5442 (tramp-run-real-handler operation args)))
5444 ;; In Emacs, there is some concurrency due to timers. If a timer
5445 ;; interrupts Tramp and wishes to use the same connection buffer as
5446 ;; the "main" Emacs, then garbage might occur in the connection
5447 ;; buffer. Therefore, we need to make sure that a timer does not use
5448 ;; the same connection buffer as the "main" Emacs. We implement a
5449 ;; cheap global lock, instead of locking each connection buffer
5450 ;; separately. The global lock is based on two variables,
5451 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5452 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5453 ;; processing of a single file operation, so we need to allow
5454 ;; recursive calls. That's where the `tramp-locker' variable comes in
5455 ;; -- it is let-bound to t during the execution of the current
5456 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5457 ;; then we should just proceed because we have been called
5458 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5459 ;; interrupting the "main" Emacs, and then we signal an error.
5461 (defvar tramp-locked nil
5462 "If non-nil, then Tramp is currently busy.
5463 Together with `tramp-locker', this implements a locking mechanism
5464 preventing reentrant calls of Tramp.")
5466 (defvar tramp-locker nil
5467 "If non-nil, then a caller has locked Tramp.
5468 Together with `tramp-locked', this implements a locking mechanism
5469 preventing reentrant calls of Tramp.")
5471 (defun tramp-sh-file-name-handler (operation &rest args)
5472 "Invoke remote-shell Tramp file name handler.
5473 Fall back to normal file name handler if no Tramp handler exists."
5474 (when (and tramp-locked (not tramp-locker))
5475 (setq tramp-locked nil)
5476 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5477 (let ((tl tramp-locked))
5480 (setq tramp-locked t)
5481 (let ((tramp-locker t))
5483 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5485 (apply (cdr fn) args)
5486 (tramp-run-real-handler operation args))))))
5487 (setq tramp-locked tl))))
5489 (defun tramp-vc-file-name-handler (operation &rest args)
5490 "Invoke special file name handler, which collects files to be handled."
5493 (tramp-replace-environment-variables
5494 (apply 'tramp-file-name-for-operation operation args)))
5495 (fn (assoc operation tramp-file-name-handler-alist)))
5496 (with-parsed-tramp-file-name filename nil
5498 ;; That's what we want: file names, for which checks are
5499 ;; applied. We assume, that VC uses only `file-exists-p' and
5500 ;; `file-readable-p' checks; otherwise we must extend the
5501 ;; list. We do not perform any action, but return nil, in
5502 ;; order to keep `vc-registered' running.
5503 ((and fn (memq operation '(file-exists-p file-readable-p)))
5504 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5506 ;; Tramp file name handlers like `expand-file-name'. They
5509 (save-match-data (apply (cdr fn) args)))
5510 ;; Default file name handlers, we don't care.
5511 (t (tramp-run-real-handler operation args)))))))
5514 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5515 "Invoke Tramp file name completion handler.
5516 Falls back to normal file name handler if no Tramp file name handler exists."
5517 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5518 ;; would otherwise use backslash.
5519 (let ((directory-sep-char ?/)
5520 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5522 ;; When `tramp-mode' is not enabled, we don't do anything.
5524 ;; For other syntaxes than `sep', the regexp matches many common
5525 ;; situations where the user doesn't actually want to use Tramp.
5526 ;; So to avoid autoloading Tramp after typing just "/s", we
5527 ;; disable this part of the completion, unless the user implicitly
5528 ;; indicated his interest in using a fancier completion system.
5529 (or (eq tramp-syntax 'sep)
5530 (featurep 'tramp) ;; If it's loaded, we may as well use
5531 ;; it. `partial-completion-mode' does not exist in
5532 ;; XEmacs. It is obsoleted with Emacs 24.1.
5533 (and (boundp 'partial-completion-mode) partial-completion-mode)
5534 ;; FIXME: These may have been loaded even if the user never
5535 ;; intended to use them.
5537 (featurep 'icicles)))
5538 (save-match-data (apply (cdr fn) args))
5539 (tramp-completion-run-real-handler operation args)))))
5542 (progn (defun tramp-register-file-name-handlers ()
5543 "Add Tramp file name handlers to `file-name-handler-alist'."
5544 ;; Remove autoloaded handlers from file name handler alist. Useful,
5545 ;; if `tramp-syntax' has been changed.
5546 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5547 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5549 'tramp-completion-file-name-handler file-name-handler-alist)))
5550 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5551 ;; Add the handlers.
5552 (add-to-list 'file-name-handler-alist
5553 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5554 (put 'tramp-file-name-handler 'safe-magic t)
5555 (add-to-list 'file-name-handler-alist
5556 (cons tramp-completion-file-name-regexp
5557 'tramp-completion-file-name-handler))
5558 (put 'tramp-completion-file-name-handler 'safe-magic t)
5559 ;; If jka-compr or epa-file are already loaded, move them to the
5560 ;; front of `file-name-handler-alist'.
5561 (dolist (fnh '(epa-file-handler jka-compr-handler))
5562 (let ((entry (rassoc fnh file-name-handler-alist)))
5564 (setq file-name-handler-alist
5565 (cons entry (delete entry file-name-handler-alist))))))))
5567 ;; `tramp-file-name-handler' must be registered before evaluation of
5568 ;; site-start and init files, because there might exist remote files
5569 ;; already, f.e. files kept via recentf-mode.
5570 ;;;###autoload(tramp-register-file-name-handlers)
5571 (tramp-register-file-name-handlers)
5574 (defun tramp-unload-file-name-handlers ()
5575 (setq file-name-handler-alist
5576 (delete (rassoc 'tramp-file-name-handler
5577 file-name-handler-alist)
5578 (delete (rassoc 'tramp-completion-file-name-handler
5579 file-name-handler-alist)
5580 file-name-handler-alist))))
5582 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5584 ;;; File name handler functions for completion mode:
5586 (defvar tramp-completion-mode nil
5587 "If non-nil, external packages signal that they are in file name completion.
5589 This is necessary, because Tramp uses a heuristic depending on last
5590 input event. This fails when external packages use other characters
5591 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5592 should never be set globally, the intention is to let-bind it.")
5594 ;; Necessary because `tramp-file-name-regexp-unified' and
5595 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5596 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5597 ;; to `tramp-file-name-handler'). Otherwise, it takes
5598 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5599 ;; risky, because completing a file might require loading other files,
5600 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5601 ;; variable. On the other hand, those files shouldn't have partial
5602 ;; Tramp file name syntax. Maybe another variable should be introduced
5603 ;; overwriting this check in such cases. Or we change Tramp file name
5604 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5605 (defun tramp-completion-mode-p ()
5606 "Checks whether method / user name / host name completion is active."
5608 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5609 (and (boundp 'non-essential) (symbol-value 'non-essential))
5610 tramp-completion-mode
5612 (equal last-input-event 'tab)
5613 (and (natnump last-input-event)
5615 ;; ?\t has event-modifier 'control.
5616 (equal last-input-event ?\t)
5617 (and (not (event-modifiers last-input-event))
5618 (or (equal last-input-event ?\?)
5619 (equal last-input-event ?\ )))))
5621 (and (featurep 'xemacs)
5622 ;; `last-input-event' might be nil.
5623 (not (null last-input-event))
5624 ;; `last-input-event' may have no character approximation.
5625 (funcall (symbol-function 'event-to-character) last-input-event)
5627 ;; ?\t has event-modifier 'control.
5629 (funcall (symbol-function 'event-to-character)
5630 last-input-event) ?\t)
5631 (and (not (event-modifiers last-input-event))
5633 (funcall (symbol-function 'event-to-character)
5634 last-input-event) ?\?)
5636 (funcall (symbol-function 'event-to-character)
5637 last-input-event) ?\ )))))))
5639 ;; Method, host name and user name completion.
5640 ;; `tramp-completion-dissect-file-name' returns a list of
5641 ;; tramp-file-name structures. For all of them we return possible completions.
5643 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5644 "Like `file-name-all-completions' for partial Tramp files."
5646 (let* ((fullname (tramp-drop-volume-letter
5647 (expand-file-name filename directory)))
5648 ;; Possible completion structures.
5649 (v (tramp-completion-dissect-file-name fullname))
5653 (let* ((car (car v))
5654 (method (tramp-file-name-method car))
5655 (user (tramp-file-name-user car))
5656 (host (tramp-file-name-host car))
5657 (localname (tramp-file-name-localname car))
5658 (m (tramp-find-method method user host))
5659 (tramp-current-user user) ; see `tramp-parse-passwd'
5662 (unless localname ;; Nothing to complete.
5666 ;; Method dependent user / host combinations.
5670 (setq all-user-hosts
5671 (append all-user-hosts
5672 (funcall (nth 0 x) (nth 1 x)))))
5673 (tramp-get-completion-function m))
5679 (tramp-get-completion-user-host
5680 method user host (nth 0 x) (nth 1 x)))
5681 (delq nil all-user-hosts)))))
5683 ;; Possible methods.
5685 (append result (tramp-get-completion-methods m)))))
5689 ;; Unify list, remove nil elements.
5691 (let ((car (car result)))
5695 (substring car (length (tramp-drop-volume-letter directory)))))
5696 (setq result (cdr result))))
5698 ;; Complete local parts.
5702 (tramp-completion-run-real-handler
5703 'file-name-all-completions (list filename directory))
5706 ;; Method, host name and user name completion for a file.
5708 (defun tramp-completion-handle-file-name-completion
5709 (filename directory &optional predicate)
5710 "Like `file-name-completion' for Tramp files."
5713 (mapcar 'list (file-name-all-completions filename directory))
5715 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5717 ;; I misuse a little bit the tramp-file-name structure in order to handle
5718 ;; completion possibilities for partial methods / user names / host names.
5719 ;; Return value is a list of tramp-file-name structures according to possible
5720 ;; completions. If "localname" is non-nil it means there
5721 ;; shouldn't be a completion anymore.
5723 ;; Expected results:
5725 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5726 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5727 ;; [nil "x" nil nil]
5728 ;; ["x" nil nil nil]
5730 ;; "/x:" "/x:y" "/x:y:"
5731 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5733 ;; ["x" nil "" nil] ["x" nil "y" nil]
5734 ;; ["x" "" nil nil] ["x" "y" nil nil]
5736 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5737 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5738 ;; "/[x/y@" "/[x/y@z"
5739 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5740 (defun tramp-completion-dissect-file-name (name)
5741 "Returns a list of `tramp-file-name' structures.
5742 They are collected by `tramp-completion-dissect-file-name1'."
5746 (tramp-completion-ipv6-regexp
5749 (if (zerop (length tramp-postfix-ipv6-format))
5750 tramp-postfix-host-format
5751 tramp-postfix-ipv6-format)))
5752 ;; "/method" "/[method"
5753 (tramp-completion-file-name-structure1
5754 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5757 (tramp-completion-file-name-structure2
5758 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5761 (tramp-completion-file-name-structure3
5762 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5764 ;; "/[ipv6" "/[ipv6"
5765 (tramp-completion-file-name-structure4
5766 (list (concat tramp-prefix-regexp
5767 tramp-prefix-ipv6-regexp
5768 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5770 ;; "/user@host" "/[user@host"
5771 (tramp-completion-file-name-structure5
5772 (list (concat tramp-prefix-regexp
5773 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5774 "\\(" tramp-host-regexp x-nil "\\)$")
5776 ;; "/user@[ipv6" "/[user@ipv6"
5777 (tramp-completion-file-name-structure6
5778 (list (concat tramp-prefix-regexp
5779 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5780 tramp-prefix-ipv6-regexp
5781 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5783 ;; "/method:user" "/[method/user" "/method://user"
5784 (tramp-completion-file-name-structure7
5785 (list (concat tramp-prefix-regexp
5786 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5787 "\\(" tramp-user-regexp x-nil "\\)$")
5789 ;; "/method:host" "/[method/host" "/method://host"
5790 (tramp-completion-file-name-structure8
5791 (list (concat tramp-prefix-regexp
5792 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5793 "\\(" tramp-host-regexp x-nil "\\)$")
5795 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5796 (tramp-completion-file-name-structure9
5797 (list (concat tramp-prefix-regexp
5798 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5799 tramp-prefix-ipv6-regexp
5800 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5802 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5803 (tramp-completion-file-name-structure10
5804 (list (concat tramp-prefix-regexp
5805 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5806 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5807 "\\(" tramp-host-regexp x-nil "\\)$")
5809 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5810 (tramp-completion-file-name-structure11
5811 (list (concat tramp-prefix-regexp
5812 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5813 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5814 tramp-prefix-ipv6-regexp
5815 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5817 ;; "/method: "/method:/"
5818 (tramp-completion-file-name-structure12
5820 (if (equal tramp-syntax 'url)
5821 (concat tramp-prefix-regexp
5822 "\\(" tramp-method-regexp "\\)"
5823 "\\(" (substring tramp-postfix-method-regexp 0 1)
5824 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5826 ;; Should not match if not URL syntax.
5827 (concat tramp-prefix-regexp "/$"))
5829 ;; "/method: "/method:/"
5830 (tramp-completion-file-name-structure13
5832 (if (equal tramp-syntax 'url)
5833 (concat tramp-prefix-regexp
5834 "\\(" tramp-method-regexp "\\)"
5835 "\\(" (substring tramp-postfix-method-regexp 0 1)
5836 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5838 ;; Should not match if not URL syntax.
5839 (concat tramp-prefix-regexp "/$"))
5842 (mapc (lambda (regexp)
5843 (add-to-list 'result
5844 (tramp-completion-dissect-file-name1 regexp name)))
5846 tramp-completion-file-name-structure1
5847 tramp-completion-file-name-structure2
5848 tramp-completion-file-name-structure3
5849 tramp-completion-file-name-structure4
5850 tramp-completion-file-name-structure5
5851 tramp-completion-file-name-structure6
5852 tramp-completion-file-name-structure7
5853 tramp-completion-file-name-structure8
5854 tramp-completion-file-name-structure9
5855 tramp-completion-file-name-structure10
5856 tramp-completion-file-name-structure11
5857 tramp-completion-file-name-structure12
5858 tramp-completion-file-name-structure13
5859 tramp-file-name-structure))
5863 (defun tramp-completion-dissect-file-name1 (structure name)
5864 "Returns a `tramp-file-name' structure matching STRUCTURE.
5865 The structure consists of remote method, remote user,
5866 remote host and localname (filename on remote host)."
5869 (when (string-match (nth 0 structure) name)
5870 (let ((method (and (nth 1 structure)
5871 (match-string (nth 1 structure) name)))
5872 (user (and (nth 2 structure)
5873 (match-string (nth 2 structure) name)))
5874 (host (and (nth 3 structure)
5875 (match-string (nth 3 structure) name)))
5876 (localname (and (nth 4 structure)
5877 (match-string (nth 4 structure) name))))
5878 (vector method user host localname)))))
5880 ;; This function returns all possible method completions, adding the
5881 ;; trailing method delimeter.
5882 (defun tramp-get-completion-methods (partial-method)
5883 "Returns all method completions for PARTIAL-METHOD."
5887 (string-match (concat "^" (regexp-quote partial-method)) method)
5888 (tramp-completion-make-tramp-file-name method nil nil nil)))
5889 (mapcar 'car tramp-methods)))
5891 ;; Compares partial user and host names with possible completions.
5892 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
5893 "Returns the most expanded string for user and host name completion.
5894 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5897 ((and partial-user partial-host)
5899 (string-match (concat "^" (regexp-quote partial-host)) host)
5900 (string-equal partial-user (or user partial-user)))
5901 (setq user partial-user)
5908 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5914 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5920 (unless (zerop (+ (length user) (length host)))
5921 (tramp-completion-make-tramp-file-name method user host nil)))
5923 (defun tramp-parse-rhosts (filename)
5924 "Return a list of (user host) tuples allowed to access.
5925 Either user or host may be nil."
5926 ;; On Windows, there are problems in completion when
5927 ;; `default-directory' is remote.
5928 (let ((default-directory (tramp-compat-temporary-file-directory))
5930 (when (file-readable-p filename)
5932 (insert-file-contents filename)
5933 (goto-char (point-min))
5935 (push (tramp-parse-rhosts-group) res))))
5938 (defun tramp-parse-rhosts-group ()
5939 "Return a (user host) tuple allowed to access.
5940 Either user or host may be nil."
5944 "^\\(" tramp-host-regexp "\\)"
5945 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5946 (narrow-to-region (point) (tramp-compat-line-end-position))
5947 (when (re-search-forward regexp nil t)
5948 (setq result (append (list (match-string 3) (match-string 1)))))
5953 (defun tramp-parse-shosts (filename)
5954 "Return a list of (user host) tuples allowed to access.
5955 User is always nil."
5956 ;; On Windows, there are problems in completion when
5957 ;; `default-directory' is remote.
5958 (let ((default-directory (tramp-compat-temporary-file-directory))
5960 (when (file-readable-p filename)
5962 (insert-file-contents filename)
5963 (goto-char (point-min))
5965 (push (tramp-parse-shosts-group) res))))
5968 (defun tramp-parse-shosts-group ()
5969 "Return a (user host) tuple allowed to access.
5970 User is always nil."
5972 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
5973 (narrow-to-region (point) (tramp-compat-line-end-position))
5974 (when (re-search-forward regexp nil t)
5975 (setq result (list nil (match-string 1))))
5978 (> (skip-chars-forward ",") 0)
5982 (defun tramp-parse-sconfig (filename)
5983 "Return a list of (user host) tuples allowed to access.
5984 User is always nil."
5985 ;; On Windows, there are problems in completion when
5986 ;; `default-directory' is remote.
5987 (let ((default-directory (tramp-compat-temporary-file-directory))
5989 (when (file-readable-p filename)
5991 (insert-file-contents filename)
5992 (goto-char (point-min))
5994 (push (tramp-parse-sconfig-group) res))))
5997 (defun tramp-parse-sconfig-group ()
5998 "Return a (user host) tuple allowed to access.
5999 User is always nil."
6001 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
6002 (narrow-to-region (point) (tramp-compat-line-end-position))
6003 (when (re-search-forward regexp nil t)
6004 (setq result (list nil (match-string 1))))
6007 (> (skip-chars-forward ",") 0)
6011 (defun tramp-parse-shostkeys (dirname)
6012 "Return a list of (user host) tuples allowed to access.
6013 User is always nil."
6014 ;; On Windows, there are problems in completion when
6015 ;; `default-directory' is remote.
6016 (let* ((default-directory (tramp-compat-temporary-file-directory))
6017 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6018 (files (when (file-directory-p dirname) (directory-files dirname)))
6021 (when (string-match regexp (car files))
6022 (push (list nil (match-string 1 (car files))) result))
6023 (setq files (cdr files)))
6026 (defun tramp-parse-sknownhosts (dirname)
6027 "Return a list of (user host) tuples allowed to access.
6028 User is always nil."
6029 ;; On Windows, there are problems in completion when
6030 ;; `default-directory' is remote.
6031 (let* ((default-directory (tramp-compat-temporary-file-directory))
6032 (regexp (concat "^\\(" tramp-host-regexp
6033 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6034 (files (when (file-directory-p dirname) (directory-files dirname)))
6037 (when (string-match regexp (car files))
6038 (push (list nil (match-string 1 (car files))) result))
6039 (setq files (cdr files)))
6042 (defun tramp-parse-hosts (filename)
6043 "Return a list of (user host) tuples allowed to access.
6044 User is always nil."
6045 ;; On Windows, there are problems in completion when
6046 ;; `default-directory' is remote.
6047 (let ((default-directory (tramp-compat-temporary-file-directory))
6049 (when (file-readable-p filename)
6051 (insert-file-contents filename)
6052 (goto-char (point-min))
6054 (push (tramp-parse-hosts-group) res))))
6057 (defun tramp-parse-hosts-group ()
6058 "Return a (user host) tuple allowed to access.
6059 User is always nil."
6062 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6063 (narrow-to-region (point) (tramp-compat-line-end-position))
6064 (when (re-search-forward regexp nil t)
6065 (setq result (list nil (match-string 1))))
6068 (> (skip-chars-forward " \t") 0)
6072 ;; For su-alike methods it would be desirable to return "root@localhost"
6073 ;; as default. Unfortunately, we have no information whether any user name
6074 ;; has been typed already. So we use `tramp-current-user' as indication,
6075 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6076 (defun tramp-parse-passwd (filename)
6077 "Return a list of (user host) tuples allowed to access.
6078 Host is always \"localhost\"."
6079 ;; On Windows, there are problems in completion when
6080 ;; `default-directory' is remote.
6081 (let ((default-directory (tramp-compat-temporary-file-directory))
6083 (if (zerop (length tramp-current-user))
6085 (when (file-readable-p filename)
6087 (insert-file-contents filename)
6088 (goto-char (point-min))
6090 (push (tramp-parse-passwd-group) res))))
6093 (defun tramp-parse-passwd-group ()
6094 "Return a (user host) tuple allowed to access.
6095 Host is always \"localhost\"."
6097 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6098 (narrow-to-region (point) (tramp-compat-line-end-position))
6099 (when (re-search-forward regexp nil t)
6100 (setq result (list (match-string 1) "localhost")))
6105 (defun tramp-parse-netrc (filename)
6106 "Return a list of (user host) tuples allowed to access.
6108 ;; On Windows, there are problems in completion when
6109 ;; `default-directory' is remote.
6110 (let ((default-directory (tramp-compat-temporary-file-directory))
6112 (when (file-readable-p filename)
6114 (insert-file-contents filename)
6115 (goto-char (point-min))
6117 (push (tramp-parse-netrc-group) res))))
6120 (defun tramp-parse-netrc-group ()
6121 "Return a (user host) tuple allowed to access.
6126 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6127 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6128 (narrow-to-region (point) (tramp-compat-line-end-position))
6129 (when (re-search-forward regexp nil t)
6130 (setq result (list (match-string 3) (match-string 1))))
6135 (defun tramp-parse-putty (registry)
6136 "Return a list of (user host) tuples allowed to access.
6137 User is always nil."
6138 ;; On Windows, there are problems in completion when
6139 ;; `default-directory' is remote.
6140 (let ((default-directory (tramp-compat-temporary-file-directory))
6143 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6144 (goto-char (point-min))
6146 (push (tramp-parse-putty-group registry) res))))
6149 (defun tramp-parse-putty-group (registry)
6150 "Return a (user host) tuple allowed to access.
6151 User is always nil."
6153 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6154 (narrow-to-region (point) (tramp-compat-line-end-position))
6155 (when (re-search-forward regexp nil t)
6156 (setq result (list nil (match-string 1))))
6161 ;;; Internal Functions:
6163 (defun tramp-maybe-send-script (vec script name)
6164 "Define in remote shell function NAME implemented as SCRIPT.
6165 Only send the definition if it has not already been done."
6166 (let* ((p (tramp-get-connection-process vec))
6167 (scripts (tramp-get-connection-property p "scripts" nil)))
6168 (unless (member name scripts)
6169 (tramp-message vec 5 "Sending script `%s'..." name)
6170 ;; The script could contain a call of Perl. This is masked with `%s'.
6171 (tramp-send-command-and-check
6173 (format "%s () {\n%s\n}" name
6174 (format script (tramp-get-remote-perl vec))))
6175 (tramp-set-connection-property p "scripts" (cons name scripts))
6176 (tramp-message vec 5 "Sending script `%s'...done." name))))
6178 (defun tramp-set-auto-save ()
6179 (when (and ;; ange-ftp has its own auto-save mechanism
6180 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6181 'tramp-sh-file-name-handler)
6183 (auto-save-mode 1)))
6184 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6185 (add-hook 'tramp-unload-hook
6187 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6189 (defun tramp-run-test (switch filename)
6190 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6191 Returns the exit code of the `test' program."
6192 (with-parsed-tramp-file-name filename nil
6193 (tramp-send-command-and-check
6197 (tramp-get-test-command v)
6199 (tramp-shell-quote-argument localname)))))
6201 (defun tramp-run-test2 (format-string file1 file2)
6202 "Run `test'-like program on the remote system, given FILE1, FILE2.
6203 FORMAT-STRING contains the program name, switches, and place holders.
6204 Returns the exit code of the `test' program. Barfs if the methods,
6205 hosts, or files, disagree."
6206 (unless (tramp-equal-remote file1 file2)
6207 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6210 "tramp-run-test2 only implemented for same method, user, host")))
6211 (with-parsed-tramp-file-name file1 v1
6212 (with-parsed-tramp-file-name file1 v2
6213 (tramp-send-command-and-check
6215 (format format-string
6216 (tramp-shell-quote-argument v1-localname)
6217 (tramp-shell-quote-argument v2-localname))))))
6219 (defun tramp-buffer-name (vec)
6220 "A name for the connection buffer VEC."
6221 ;; We must use `tramp-file-name-real-host', because for gateway
6222 ;; methods the default port will be expanded later on, which would
6224 (let ((method (tramp-file-name-method vec))
6225 (user (tramp-file-name-user vec))
6226 (host (tramp-file-name-real-host vec)))
6227 (if (not (zerop (length user)))
6228 (format "*tramp/%s %s@%s*" method user host)
6229 (format "*tramp/%s %s*" method host))))
6231 (defun tramp-delete-temp-file-function ()
6232 "Remove temporary files related to current buffer."
6233 (when (stringp tramp-temp-buffer-file-name)
6235 (delete-file tramp-temp-buffer-file-name)
6238 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6239 (add-hook 'tramp-cache-unload-hook
6241 (remove-hook 'kill-buffer-hook
6242 'tramp-delete-temp-file-function)))
6244 (defun tramp-get-buffer (vec)
6245 "Get the connection buffer to be used for VEC."
6246 (or (get-buffer (tramp-buffer-name vec))
6247 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6248 (setq buffer-undo-list t)
6249 (setq default-directory
6250 (tramp-make-tramp-file-name
6251 (tramp-file-name-method vec)
6252 (tramp-file-name-user vec)
6253 (tramp-file-name-host vec)
6257 (defun tramp-get-connection-buffer (vec)
6258 "Get the connection buffer to be used for VEC.
6259 In case a second asynchronous communication has been started, it is different
6260 from `tramp-get-buffer'."
6261 (or (tramp-get-connection-property vec "process-buffer" nil)
6262 (tramp-get-buffer vec)))
6264 (defun tramp-get-connection-process (vec)
6265 "Get the connection process to be used for VEC.
6266 In case a second asynchronous communication has been started, it is different
6267 from the default one."
6269 (or (tramp-get-connection-property vec "process-name" nil)
6270 (tramp-buffer-name vec))))
6272 (defun tramp-debug-buffer-name (vec)
6273 "A name for the debug buffer for VEC."
6274 ;; We must use `tramp-file-name-real-host', because for gateway
6275 ;; methods the default port will be expanded later on, which would
6277 (let ((method (tramp-file-name-method vec))
6278 (user (tramp-file-name-user vec))
6279 (host (tramp-file-name-real-host vec)))
6280 (if (not (zerop (length user)))
6281 (format "*debug tramp/%s %s@%s*" method user host)
6282 (format "*debug tramp/%s %s*" method host))))
6284 (defconst tramp-debug-outline-regexp
6285 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6287 (defun tramp-get-debug-buffer (vec)
6288 "Get the debug buffer for VEC."
6289 (with-current-buffer
6290 (get-buffer-create (tramp-debug-buffer-name vec))
6292 (setq buffer-undo-list t)
6293 ;; Activate `outline-mode'. This runs `text-mode-hook' and
6294 ;; `outline-mode-hook'. We must prevent that local processes
6295 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6296 ;; Furthermore, `outline-regexp' must have the correct value
6297 ;; already, because it is used by `font-lock-compile-keywords'.
6298 (let ((default-directory (tramp-compat-temporary-file-directory))
6299 (outline-regexp tramp-debug-outline-regexp))
6301 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
6302 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6305 (defun tramp-outline-level ()
6306 "Return the depth to which a statement is nested in the outline.
6307 Point must be at the beginning of a header line.
6309 The outline level is equal to the verbosity of the Tramp message."
6310 (1+ (string-to-number (match-string 1))))
6312 (defun tramp-find-executable
6313 (vec progname dirlist &optional ignore-tilde ignore-path)
6314 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6315 First arg VEC specifies the connection, PROGNAME is the program
6316 to search for, and DIRLIST gives the list of directories to
6317 search. If IGNORE-TILDE is non-nil, directory names starting
6318 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6321 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6323 This function expects to be in the right *tramp* buffer."
6324 (with-current-buffer (tramp-get-connection-buffer vec)
6326 ;; Check whether the executable is in $PATH. "which(1)" does not
6327 ;; report always a correct error code; therefore we check the
6328 ;; number of words it returns.
6330 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6331 (goto-char (point-min))
6332 (if (looking-at "^\\s-*1$")
6333 (setq result (concat "\\" progname))))
6336 ;; Remove all ~/foo directories from dirlist. In XEmacs,
6337 ;; `remove' is in CL, and we want to avoid CL dependencies.
6340 (setq d (car dirlist))
6341 (setq dirlist (cdr dirlist))
6342 (unless (char-equal ?~ (aref d 0))
6343 (setq newdl (cons d newdl))))
6344 (setq dirlist (nreverse newdl))))
6347 (format (concat "while read d; "
6348 "do if test -x $d/%s -a -f $d/%s; "
6349 "then echo tramp_executable $d/%s; "
6350 "break; fi; done <<'EOF'\n"
6352 progname progname progname (mapconcat 'identity dirlist "\n")))
6353 (goto-char (point-max))
6354 (when (search-backward "tramp_executable " nil t)
6355 (skip-chars-forward "^ ")
6356 (skip-chars-forward " ")
6357 (setq result (buffer-substring
6358 (point) (tramp-compat-line-end-position)))))
6361 (defun tramp-set-remote-path (vec)
6362 "Sets the remote environment PATH to existing directories.
6363 I.e., for each directory in `tramp-remote-path', it is tested
6364 whether it exists and if so, it is added to the environment
6366 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6368 vec (format "PATH=%s; export PATH"
6369 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6371 ;; ------------------------------------------------------------
6372 ;; -- Communication with external shell --
6373 ;; ------------------------------------------------------------
6375 (defun tramp-find-file-exists-command (vec)
6376 "Find a command on the remote host for checking if a file exists.
6377 Here, we are looking for a command which has zero exit status if the
6378 file exists and nonzero exit status otherwise."
6379 (let ((existing "/")
6381 (tramp-shell-quote-argument "/ this file does not exist "))
6383 ;; The algorithm is as follows: we try a list of several commands.
6384 ;; For each command, we first run `$cmd /' -- this should return
6385 ;; true, as the root directory always exists. And then we run
6386 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6387 ;; does not exist. This should return false. We use the first
6388 ;; command we find that seems to work.
6389 ;; The list of commands to try is as follows:
6390 ;; `ls -d' This works on most systems, but NetBSD 1.4
6391 ;; has a bug: `ls' always returns zero exit
6392 ;; status, even for files which don't exist.
6393 ;; `test -e' Some Bourne shells have a `test' builtin
6394 ;; which does not know the `-e' option.
6395 ;; `/bin/test -e' For those, the `test' binary on disk normally
6396 ;; provides the option. Alas, the binary
6397 ;; is sometimes `/bin/test' and sometimes it's
6399 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6401 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6402 (zerop (tramp-send-command-and-check
6403 vec (format "%s %s" result existing)))
6404 (not (zerop (tramp-send-command-and-check
6405 vec (format "%s %s" result nonexisting)))))
6406 (and (setq result "/bin/test -e")
6407 (zerop (tramp-send-command-and-check
6408 vec (format "%s %s" result existing)))
6409 (not (zerop (tramp-send-command-and-check
6410 vec (format "%s %s" result nonexisting)))))
6411 (and (setq result "/usr/bin/test -e")
6412 (zerop (tramp-send-command-and-check
6413 vec (format "%s %s" result existing)))
6414 (not (zerop (tramp-send-command-and-check
6415 vec (format "%s %s" result nonexisting)))))
6416 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6417 (zerop (tramp-send-command-and-check
6418 vec (format "%s %s" result existing)))
6419 (not (zerop (tramp-send-command-and-check
6420 vec (format "%s %s" result nonexisting))))))
6422 vec 'file-error "Couldn't find command to check if file exists"))
6425 ;; CCC test ksh or bash found for tilde expansion?
6426 (defun tramp-find-shell (vec)
6427 "Opens a shell on the remote host which groks tilde expansion."
6428 (unless (tramp-get-connection-property vec "remote-shell" nil)
6430 (with-current-buffer (tramp-get-buffer vec)
6431 (tramp-send-command vec "echo ~root" t)
6433 ((or (string-match "^~root$" (buffer-string))
6434 ;; The default shell (ksh93) of OpenSolaris is buggy.
6435 (string-equal (tramp-get-connection-property vec "uname" "")
6438 (or (tramp-find-executable
6439 vec "bash" (tramp-get-remote-path vec) t t)
6440 (tramp-find-executable
6441 vec "ksh" (tramp-get-remote-path vec) t t)))
6445 "Couldn't find a shell which groks tilde expansion"))
6446 ;; Find arguments for this shell.
6447 (let ((alist tramp-sh-extra-args)
6449 (while (and alist (null extra-args))
6450 (setq item (pop alist))
6451 (when (string-match (car item) shell)
6452 (setq extra-args (cdr item))))
6453 (when extra-args (setq shell (concat shell " " extra-args))))
6455 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
6456 (let ((tramp-end-of-output tramp-initial-end-of-output))
6459 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6460 (shell-quote-argument tramp-end-of-output) shell)
6463 (tramp-message vec 5 "Setting remote shell prompt...")
6465 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6466 (tramp-send-command vec "PS2=''" t)
6467 (tramp-send-command vec "PS3=''" t)
6468 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6469 (tramp-message vec 5 "Setting remote shell prompt...done"))
6472 vec 5 "Remote `%s' groks tilde expansion, good"
6473 (tramp-get-method-parameter
6474 (tramp-file-name-method vec) 'tramp-remote-sh))
6475 (tramp-set-connection-property
6477 (tramp-get-method-parameter
6478 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
6480 ;; ------------------------------------------------------------
6481 ;; -- Functions for establishing connection --
6482 ;; ------------------------------------------------------------
6484 ;; The following functions are actions to be taken when seeing certain
6485 ;; prompts from the remote host. See the variable
6486 ;; `tramp-actions-before-shell' for usage of these functions.
6488 (defun tramp-action-login (proc vec)
6489 "Send the login name."
6490 (when (not (stringp tramp-current-user))
6491 (save-window-excursion
6492 (let ((enable-recursive-minibuffers t))
6493 (pop-to-buffer (tramp-get-connection-buffer vec))
6494 (setq tramp-current-user (read-string (match-string 0))))))
6495 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6496 (with-current-buffer (tramp-get-connection-buffer vec)
6497 (tramp-message vec 6 "\n%s" (buffer-string)))
6498 (tramp-send-string vec tramp-current-user))
6500 (defun tramp-action-password (proc vec)
6501 "Query the user for a password."
6502 (with-current-buffer (process-buffer proc)
6503 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6504 (tramp-message vec 3 "Sending %s" (match-string 1)))
6505 (tramp-enter-password proc))
6507 (defun tramp-action-succeed (proc vec)
6508 "Signal success in finding shell prompt."
6509 (throw 'tramp-action 'ok))
6511 (defun tramp-action-permission-denied (proc vec)
6512 "Signal permission denied."
6514 (throw 'tramp-action 'permission-denied))
6516 (defun tramp-action-yesno (proc vec)
6517 "Ask the user for confirmation using `yes-or-no-p'.
6518 Send \"yes\" to remote process on confirmation, abort otherwise.
6519 See also `tramp-action-yn'."
6520 (save-window-excursion
6521 (let ((enable-recursive-minibuffers t))
6522 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6523 (unless (yes-or-no-p (match-string 0))
6525 (throw 'tramp-action 'permission-denied))
6526 (with-current-buffer (tramp-get-connection-buffer vec)
6527 (tramp-message vec 6 "\n%s" (buffer-string)))
6528 (tramp-send-string vec "yes"))))
6530 (defun tramp-action-yn (proc vec)
6531 "Ask the user for confirmation using `y-or-n-p'.
6532 Send \"y\" to remote process on confirmation, abort otherwise.
6533 See also `tramp-action-yesno'."
6534 (save-window-excursion
6535 (let ((enable-recursive-minibuffers t))
6536 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6537 (unless (y-or-n-p (match-string 0))
6539 (throw 'tramp-action 'permission-denied))
6540 (with-current-buffer (tramp-get-connection-buffer vec)
6541 (tramp-message vec 6 "\n%s" (buffer-string)))
6542 (tramp-send-string vec "y"))))
6544 (defun tramp-action-terminal (proc vec)
6545 "Tell the remote host which terminal type to use.
6546 The terminal type can be configured with `tramp-terminal-type'."
6547 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6548 (with-current-buffer (tramp-get-connection-buffer vec)
6549 (tramp-message vec 6 "\n%s" (buffer-string)))
6550 (tramp-send-string vec tramp-terminal-type))
6552 (defun tramp-action-process-alive (proc vec)
6553 "Check whether a process has finished."
6554 (unless (memq (process-status proc) '(run open))
6555 (throw 'tramp-action 'process-died)))
6557 (defun tramp-action-out-of-band (proc vec)
6558 "Check whether an out-of-band copy has finished."
6559 (cond ((and (memq (process-status proc) '(stop exit))
6560 (zerop (process-exit-status proc)))
6561 (tramp-message vec 3 "Process has finished.")
6562 (throw 'tramp-action 'ok))
6563 ((or (and (memq (process-status proc) '(stop exit))
6564 (not (zerop (process-exit-status proc))))
6565 (memq (process-status proc) '(signal)))
6566 ;; `scp' could have copied correctly, but set modes could have failed.
6567 ;; This can be ignored.
6568 (with-current-buffer (process-buffer proc)
6569 (goto-char (point-min))
6570 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6572 (tramp-message vec 5 "'set mode' error ignored.")
6573 (tramp-message vec 3 "Process has finished.")
6574 (throw 'tramp-action 'ok))
6575 (tramp-message vec 3 "Process has died.")
6576 (throw 'tramp-action 'process-died))))
6579 ;; Functions for processing the actions.
6581 (defun tramp-process-one-action (proc vec actions)
6582 "Wait for output from the shell and perform one action."
6583 (let (found todo item pattern action)
6585 ;; Reread output once all actions have been performed.
6586 ;; Obviously, the output was not complete.
6587 (tramp-accept-process-output proc 1)
6590 (setq item (pop todo))
6591 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6592 (setq action (nth 1 item))
6594 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6595 (when (tramp-check-for-regexp proc pattern)
6596 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6597 (setq found (funcall action proc vec)))))
6600 (defun tramp-process-actions (proc vec actions &optional timeout)
6601 "Perform actions until success or TIMEOUT."
6602 ;; Enable auth-source and password-cache.
6603 (tramp-set-connection-property vec "first-password-request" t)
6606 (tramp-message proc 3 "Waiting for prompts from remote shell")
6608 (catch 'tramp-action
6610 (with-timeout (timeout)
6611 (tramp-process-one-action proc vec actions))
6612 (tramp-process-one-action proc vec actions)))))
6613 (with-current-buffer (tramp-get-connection-buffer vec)
6614 (tramp-message vec 6 "\n%s" (buffer-string)))
6615 (unless (eq exit 'ok)
6616 (tramp-clear-passwd vec)
6617 (tramp-error-with-buffer
6620 ((eq exit 'permission-denied) "Permission denied")
6621 ((eq exit 'process-died) "Process died")
6622 (t "Login failed"))))))
6624 ;; Utility functions.
6626 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6627 "Like `accept-process-output' for Tramp processes.
6628 This is needed in order to hide `last-coding-system-used', which is set
6629 for process communication also."
6630 (with-current-buffer (process-buffer proc)
6631 (tramp-message proc 10 "%s %s" proc (process-status proc))
6632 (let (buffer-read-only last-coding-system-used)
6633 ;; Under Windows XP, accept-process-output doesn't return
6634 ;; sometimes. So we add an additional timeout.
6635 (with-timeout ((or timeout 1))
6636 (accept-process-output proc timeout timeout-msecs)))
6637 (tramp-message proc 10 "\n%s" (buffer-string))))
6639 (defun tramp-check-for-regexp (proc regexp)
6640 "Check whether REGEXP is contained in process buffer of PROC.
6641 Erase echoed commands if exists."
6642 (with-current-buffer (process-buffer proc)
6643 (goto-char (point-min))
6645 ;; Check whether we need to remove echo output.
6646 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6647 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6648 (let ((begin (match-beginning 0)))
6649 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6650 ;; Discard echo from remote output.
6651 (tramp-set-connection-property proc "check-remote-echo" nil)
6652 (tramp-message proc 5 "echo-mark found")
6654 (delete-region begin (point))
6655 (goto-char (point-min)))))
6657 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6658 ;; Sometimes, the echo string is suppressed on the remote side.
6660 (substring-no-properties
6661 tramp-echo-mark-marker
6662 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6663 (buffer-substring-no-properties
6664 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6665 ;; No echo to be handled, now we can look for the regexp.
6666 (goto-char (point-min))
6667 (re-search-forward regexp nil t))))
6669 (defun tramp-wait-for-regexp (proc timeout regexp)
6670 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6671 Expects the output of PROC to be sent to the current buffer. Returns
6672 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6674 (with-current-buffer (process-buffer proc)
6675 (let ((found (tramp-check-for-regexp proc regexp))
6676 (start-time (current-time)))
6678 ;; Work around a bug in XEmacs 21, where the timeout
6679 ;; expires faster than it should. This degenerates
6680 ;; to polling for buggy XEmacsen, but oh, well.
6681 (while (and (not found)
6682 (< (tramp-time-diff (current-time) start-time)
6684 (with-timeout (timeout)
6686 (tramp-accept-process-output proc 1)
6687 (unless (memq (process-status proc) '(run open))
6688 (tramp-error-with-buffer
6689 nil proc 'file-error "Process has died"))
6690 (setq found (tramp-check-for-regexp proc regexp))))))
6693 (tramp-accept-process-output proc 1)
6694 (unless (memq (process-status proc) '(run open))
6695 (tramp-error-with-buffer
6696 nil proc 'file-error "Process has died"))
6697 (setq found (tramp-check-for-regexp proc regexp)))))
6698 (tramp-message proc 6 "\n%s" (buffer-string))
6702 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6704 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6707 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6708 "Wait for shell prompt and barf if none appears.
6709 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6710 seconds. If not, it produces an error message with the given ERROR-ARGS."
6712 (tramp-wait-for-regexp
6715 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6716 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6718 ;; We don't call `tramp-send-string' in order to hide the password
6719 ;; from the debug buffer, and because end-of-line handling of the
6721 (defun tramp-enter-password (proc)
6722 "Prompt for a password and send it to the remote end."
6723 (process-send-string
6724 proc (concat (tramp-read-passwd proc)
6725 (or (tramp-get-method-parameter
6726 tramp-current-method
6727 'tramp-password-end-of-line)
6728 tramp-default-password-end-of-line))))
6730 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6731 "Set up an interactive shell.
6732 Mainly sets the prompt and the echo correctly. PROC is the shell
6733 process to set up. VEC specifies the connection."
6734 (let ((tramp-end-of-output tramp-initial-end-of-output))
6735 ;; It is useful to set the prompt in the following command because
6736 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6737 ;; about and thus /bin/sh will display a strange prompt. For
6738 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6739 ;; display the current working directory but /bin/sh will display
6740 ;; a dollar sign. The following command line sets $PS1 to a sane
6741 ;; value, and works under Bourne-ish shells as well as csh-like
6742 ;; shells. Daniel Pittman reports that the unusual positioning of
6743 ;; the single quotes makes it work under `rc', too. We also unset
6744 ;; the variable $ENV because that is read by some sh
6745 ;; implementations (eg, bash when called as sh) on startup; this
6746 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6747 ;; is another way to set the prompt in /bin/bash, it must be
6748 ;; discarded as well.
6752 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6753 (shell-quote-argument tramp-end-of-output)
6754 (tramp-get-method-parameter
6755 (tramp-file-name-method vec) 'tramp-remote-sh))
6759 (tramp-message vec 5 "Setting up remote shell environment")
6760 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6761 ;; Check whether the echo has really been disabled. Some
6762 ;; implementations, like busybox of embedded GNU/Linux, don't
6763 ;; support disabling.
6764 (tramp-send-command vec "echo foo" t)
6765 (with-current-buffer (process-buffer proc)
6766 (goto-char (point-min))
6767 (when (looking-at "echo foo")
6768 (tramp-set-connection-property proc "remote-echo" t)
6769 (tramp-message vec 5 "Remote echo still on. Ok.")
6770 ;; Make sure backspaces and their echo are enabled and no line
6771 ;; width magic interferes with them.
6772 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6774 (tramp-message vec 5 "Setting shell prompt")
6776 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6777 (tramp-send-command vec "PS2=''" t)
6778 (tramp-send-command vec "PS3=''" t)
6779 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6781 ;; Try to set up the coding system correctly.
6782 ;; CCC this can't be the right way to do it. Hm.
6783 (tramp-message vec 5 "Determining coding system")
6784 (tramp-send-command vec "echo foo ; echo bar" t)
6785 (with-current-buffer (process-buffer proc)
6786 (goto-char (point-min))
6787 (if (featurep 'mule)
6788 ;; Use MULE to select the right EOL convention for communicating
6789 ;; with the process.
6790 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
6791 (cons 'undecided 'undecided)))
6792 cs-decode cs-encode)
6793 (when (symbolp cs) (setq cs (cons cs cs)))
6794 (setq cs-decode (car cs))
6795 (setq cs-encode (cdr cs))
6796 (unless cs-decode (setq cs-decode 'undecided))
6797 (unless cs-encode (setq cs-encode 'undecided))
6798 (setq cs-encode (tramp-coding-system-change-eol-conversion
6800 (when (search-forward "\r" nil t)
6801 (setq cs-decode (tramp-coding-system-change-eol-conversion
6803 (funcall (symbol-function 'set-buffer-process-coding-system)
6804 cs-decode cs-encode)
6806 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6807 ;; Look for ^M and do something useful if found.
6808 (when (search-forward "\r" nil t)
6809 ;; We have found a ^M but cannot frob the process coding system
6810 ;; because we're running on a non-MULE Emacs. Let's try
6812 (tramp-send-command vec "stty -onlcr" t))))
6813 ;; Dump stty settings in the traces.
6814 (when (>= tramp-verbose 10)
6815 (tramp-send-command vec "stty -a" t))
6816 (tramp-send-command vec "set +o vi +o emacs" t)
6818 ;; Check whether the output of "uname -sr" has been changed. If
6819 ;; yes, this is a strong indication that we must expire all
6820 ;; connection properties. We start again with
6821 ;; `tramp-maybe-open-connection', it will be catched there.
6822 (tramp-message vec 5 "Checking system information")
6823 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6825 (tramp-set-connection-property
6827 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6828 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
6829 (with-current-buffer (tramp-get-debug-buffer vec)
6830 ;; Keep the debug buffer
6832 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
6833 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6834 (if (= (point-min) (point-max))
6836 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6837 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6838 (tramp-get-buffer vec)
6841 "Connection reset, because remote host changed from `%s' to `%s'"
6842 old-uname new-uname)
6843 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
6845 ;; Check whether the remote host suffers from buggy
6846 ;; `send-process-string'. This is known for FreeBSD (see comment in
6847 ;; `send_process', file process.c). I've tested sending 624 bytes
6848 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6849 ;; this host type is detected locally. It cannot handle remote
6851 (with-connection-property proc "chunksize"
6853 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6857 vec 5 "Checking remote host type for `send-process-string' bug")
6859 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
6862 ;; Set remote PATH variable.
6863 (tramp-set-remote-path vec)
6865 ;; Search for a good shell before searching for a command which
6866 ;; checks if a file exists. This is done because Tramp wants to use
6867 ;; "test foo; echo $?" to check if various conditions hold, and
6868 ;; there are buggy /bin/sh implementations which don't execute the
6869 ;; "echo $?" part if the "test" part has an error. In particular,
6870 ;; the OpenSolaris /bin/sh is a problem. There are also other
6871 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
6872 ;; in in function declarations, or changing HISTFILE in place.
6873 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
6875 (tramp-find-shell vec)
6877 ;; Disable unexpected output.
6878 (tramp-send-command vec "mesg n; biff n" t)
6880 ;; Set the environment.
6881 (tramp-message vec 5 "Setting default environment")
6883 (let ((env (copy-sequence tramp-remote-process-environment))
6886 (setq item (tramp-compat-split-string (car env) "="))
6887 (setcdr item (mapconcat 'identity (cdr item) "="))
6888 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
6890 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
6891 (push (car item) unset))
6892 (setq env (cdr env)))
6895 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
6897 ;; CCC: We should either implement a Perl version of base64 encoding
6898 ;; and decoding. Then we just use that in the last item. The other
6899 ;; alternative is to use the Perl version of UU encoding. But then
6900 ;; we need a Lisp version of uuencode.
6902 ;; Old text from documentation of tramp-methods:
6903 ;; Using a uuencode/uudecode inline method is discouraged, please use one
6904 ;; of the base64 methods instead since base64 encoding is much more
6905 ;; reliable and the commands are more standardized between the different
6906 ;; Unix versions. But if you can't use base64 for some reason, please
6907 ;; note that the default uudecode command does not work well for some
6908 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
6909 ;; the following command for uudecode:
6911 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6913 ;; For Irix, no solution is known yet.
6915 (defconst tramp-local-coding-commands
6916 '((b64 base64-encode-region base64-decode-region)
6917 (uu tramp-uuencode-region uudecode-decode-region)
6919 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6920 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6921 "List of local coding commands for inline transfer.
6922 Each item is a list that looks like this:
6924 \(FORMAT ENCODING DECODING\)
6926 FORMAT is symbol describing the encoding/decoding format. It can be
6927 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6929 ENCODING and DECODING can be strings, giving commands, or symbols,
6930 giving functions. If they are strings, then they can contain
6931 the \"%s\" format specifier. If that specifier is present, the input
6932 filename will be put into the command line at that spot. If the
6933 specifier is not present, the input should be read from standard
6936 If they are functions, they will be called with two arguments, start
6937 and end of region, and are expected to replace the region contents
6938 with the encoded or decoded results, respectively.")
6940 (defconst tramp-remote-coding-commands
6941 '((b64 "base64" "base64 -d")
6942 (b64 "mimencode -b" "mimencode -u -b")
6943 (b64 "mmencode -b" "mmencode -u -b")
6944 (b64 "recode data..base64" "recode base64..data")
6945 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6946 (b64 tramp-perl-encode tramp-perl-decode)
6947 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6948 (uu "uuencode xxx" "uudecode -o -")
6949 (uu "uuencode xxx" "uudecode -p")
6950 (uu "uuencode xxx" tramp-uudecode)
6952 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6953 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6954 "List of remote coding commands for inline transfer.
6955 Each item is a list that looks like this:
6957 \(FORMAT ENCODING DECODING\)
6959 FORMAT is symbol describing the encoding/decoding format. It can be
6960 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6962 ENCODING and DECODING can be strings, giving commands, or symbols,
6963 giving variables. If they are strings, then they can contain
6964 the \"%s\" format specifier. If that specifier is present, the input
6965 filename will be put into the command line at that spot. If the
6966 specifier is not present, the input should be read from standard
6969 If they are variables, this variable is a string containing a Perl
6970 implementation for this functionality. This Perl program will be transferred
6971 to the remote host, and it is available as shell function with the same name.")
6973 (defun tramp-find-inline-encoding (vec)
6974 "Find an inline transfer encoding that works.
6975 Goes through the list `tramp-local-coding-commands' and
6976 `tramp-remote-coding-commands'."
6978 (let ((local-commands tramp-local-coding-commands)
6980 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6981 (while (and local-commands (not found))
6982 (setq litem (pop local-commands))
6983 (catch 'wont-work-local
6984 (let ((format (nth 0 litem))
6985 (remote-commands tramp-remote-coding-commands))
6986 (setq loc-enc (nth 1 litem))
6987 (setq loc-dec (nth 2 litem))
6988 ;; If the local encoder or decoder is a string, the
6989 ;; corresponding command has to work locally.
6990 (if (not (stringp loc-enc))
6992 vec 5 "Checking local encoding function `%s'" loc-enc)
6994 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6995 (unless (zerop (tramp-call-local-coding-command
6997 (throw 'wont-work-local nil)))
6998 (if (not (stringp loc-dec))
7000 vec 5 "Checking local decoding function `%s'" loc-dec)
7002 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7003 (unless (zerop (tramp-call-local-coding-command
7005 (throw 'wont-work-local nil)))
7006 ;; Search for remote coding commands with the same format
7007 (while (and remote-commands (not found))
7008 (setq ritem (pop remote-commands))
7009 (catch 'wont-work-remote
7010 (when (equal format (nth 0 ritem))
7011 (setq rem-enc (nth 1 ritem))
7012 (setq rem-dec (nth 2 ritem))
7013 ;; Check if remote encoding and decoding commands can be
7014 ;; called remotely with null input and output. This makes
7015 ;; sure there are no syntax errors and the command is really
7016 ;; found. Note that we do not redirect stdout to /dev/null,
7017 ;; for two reasons: when checking the decoding command, we
7018 ;; actually check the output it gives. And also, when
7019 ;; redirecting "mimencode" output to /dev/null, then as root
7020 ;; it might change the permissions of /dev/null!
7021 (when (not (stringp rem-enc))
7022 (let ((name (symbol-name rem-enc)))
7023 (while (string-match (regexp-quote "-") name)
7024 (setq name (replace-match "_" nil t name)))
7025 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7026 (setq rem-enc name)))
7029 "Checking remote encoding command `%s' for sanity" rem-enc)
7030 (unless (zerop (tramp-send-command-and-check
7031 vec (format "%s </dev/null" rem-enc) t))
7032 (throw 'wont-work-remote nil))
7034 (when (not (stringp rem-dec))
7035 (let ((name (symbol-name rem-dec)))
7036 (while (string-match (regexp-quote "-") name)
7037 (setq name (replace-match "_" nil t name)))
7038 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7039 (setq rem-dec name)))
7042 "Checking remote decoding command `%s' for sanity" rem-dec)
7043 (unless (zerop (tramp-send-command-and-check
7045 (format "echo %s | %s | %s"
7046 magic rem-enc rem-dec)
7048 (throw 'wont-work-remote nil))
7050 (with-current-buffer (tramp-get-buffer vec)
7051 (goto-char (point-min))
7052 (unless (looking-at (regexp-quote magic))
7053 (throw 'wont-work-remote nil)))
7055 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7056 (setq rem-enc (nth 1 ritem))
7057 (setq rem-dec (nth 2 ritem))
7058 (setq found t)))))))
7060 ;; Did we find something?
7063 vec 'file-error "Couldn't find an inline transfer encoding"))
7065 ;; Set connection properties.
7066 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7067 (tramp-set-connection-property vec "local-encoding" loc-enc)
7068 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7069 (tramp-set-connection-property vec "local-decoding" loc-dec)
7070 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7071 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7072 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7073 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7075 (defun tramp-call-local-coding-command (cmd input output)
7076 "Call the local encoding or decoding command.
7077 If CMD contains \"%s\", provide input file INPUT there in command.
7078 Otherwise, INPUT is passed via standard input.
7079 INPUT can also be nil which means `/dev/null'.
7080 OUTPUT can be a string (which specifies a filename), or t (which
7081 means standard output and thus the current buffer), or nil (which
7083 (tramp-local-call-process
7084 tramp-encoding-shell
7085 (when (and input (not (string-match "%s" cmd))) input)
7086 (if (eq output t) t nil)
7088 tramp-encoding-command-switch
7090 (if (string-match "%s" cmd) (format cmd input) cmd)
7091 (if (stringp output) (concat "> " output) ""))))
7093 (defun tramp-compute-multi-hops (vec)
7094 "Expands VEC according to `tramp-default-proxies-alist'.
7095 Gateway hops are already opened."
7096 (let ((target-alist `(,vec))
7097 (choices tramp-default-proxies-alist)
7100 ;; Look for proxy hosts to be passed.
7102 (setq item (pop choices)
7103 proxy (eval (nth 2 item)))
7106 (string-match (or (eval (nth 0 item)) "")
7107 (or (tramp-file-name-host (car target-alist)) ""))
7109 (string-match (or (eval (nth 1 item)) "")
7110 (or (tramp-file-name-user (car target-alist)) "")))
7112 ;; No more hops needed.
7114 ;; Replace placeholders.
7119 ?u (or (tramp-file-name-user (car target-alist)) "")
7120 ?h (or (tramp-file-name-host (car target-alist)) ""))))
7121 (with-parsed-tramp-file-name proxy l
7123 (add-to-list 'target-alist l)
7124 ;; Start next search.
7125 (setq choices tramp-default-proxies-alist)))))
7128 (when (and (boundp 'tramp-gw-tunnel-method)
7129 (string-match (format
7131 (symbol-value 'tramp-gw-tunnel-method)
7132 (symbol-value 'tramp-gw-socks-method))
7133 (tramp-file-name-method (car target-alist))))
7134 (let ((gw (pop target-alist))
7135 (hop (pop target-alist)))
7136 ;; Is the method prepared for gateways?
7137 (unless (tramp-get-method-parameter
7138 (tramp-file-name-method hop) 'tramp-default-port)
7141 "Method `%s' is not supported for gateway access."
7142 (tramp-file-name-method hop)))
7143 ;; Add default port if needed.
7146 tramp-host-with-port-regexp (tramp-file-name-host hop))
7149 (tramp-file-name-host hop) tramp-prefix-port-format
7151 (tramp-get-method-parameter
7152 (tramp-file-name-method hop) 'tramp-default-port)))))
7153 ;; Open the gateway connection.
7157 (tramp-file-name-method hop) (tramp-file-name-user hop)
7158 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
7159 ;; For the password prompt, we need the correct values.
7160 ;; Therefore, we must remember the gateway vector. But we
7161 ;; cannot do it as connection property, because it shouldn't
7162 ;; be persistent. And we have no started process yet either.
7163 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7165 ;; Foreign and out-of-band methods are not supported for multi-hops.
7166 (when (cdr target-alist)
7167 (setq choices target-alist)
7169 (setq item (pop choices))
7173 (tramp-get-method-parameter
7174 (tramp-file-name-method item) 'tramp-login-program))
7175 (tramp-get-method-parameter
7176 (tramp-file-name-method item) 'tramp-copy-program))
7179 "Method `%s' is not supported for multi-hops."
7180 (tramp-file-name-method item)))))
7182 ;; In case the host name is not used for the remote shell
7183 ;; command, the user could be misguided by applying a random
7185 (let* ((v (car target-alist))
7186 (method (tramp-file-name-method v))
7187 (host (tramp-file-name-host v)))
7190 ;; There are multi-hops.
7192 ;; The host name is used for the remote shell command.
7194 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7195 ;; The host is local. We cannot use `tramp-local-host-p'
7196 ;; here, because it opens a connection as well.
7197 (string-match tramp-local-host-regexp host))
7200 "Host `%s' looks like a remote host, `%s' can only use the local host"
7206 (defun tramp-maybe-open-connection (vec)
7207 "Maybe open a connection VEC.
7208 Does not do anything if a connection is already open, but re-opens the
7209 connection if a previous connection has died for some reason."
7210 (catch 'uname-changed
7211 (let ((p (tramp-get-connection-process vec))
7212 (process-environment (copy-sequence process-environment)))
7214 ;; If too much time has passed since last command was sent, look
7215 ;; whether process is still alive. If it isn't, kill it. When
7216 ;; using ssh, it can sometimes happen that the remote end has
7217 ;; hung up but the local ssh client doesn't recognize this until
7218 ;; it tries to send some data to the remote end. So that's why
7219 ;; we try to send a command from time to time, then look again
7220 ;; whether the process is really alive.
7222 (when (and (> (tramp-time-diff
7224 (tramp-get-connection-property
7225 p "last-cmd-time" '(0 0 0)))
7227 p (processp p) (memq (process-status p) '(run open)))
7228 (tramp-send-command vec "echo are you awake" t t)
7229 (unless (and (memq (process-status p) '(run open))
7230 (tramp-wait-for-output p 10))
7231 ;; The error will be catched locally.
7232 (tramp-error vec 'file-error "Awake did fail")))
7234 (tramp-flush-connection-property vec)
7235 (tramp-flush-connection-property p)
7239 ;; New connection must be opened.
7240 (unless (and p (processp p) (memq (process-status p) '(run open)))
7242 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7243 ;; messages from the beginning.
7244 (tramp-get-buffer vec)
7245 (if (zerop (length (tramp-file-name-user vec)))
7247 vec 3 "Opening connection for %s using %s..."
7248 (tramp-file-name-host vec)
7249 (tramp-file-name-method vec))
7251 vec 3 "Opening connection for %s@%s using %s..."
7252 (tramp-file-name-user vec)
7253 (tramp-file-name-host vec)
7254 (tramp-file-name-method vec)))
7256 ;; Start new process.
7257 (when (and p (processp p))
7259 (setenv "TERM" tramp-terminal-type)
7260 (setenv "LC_ALL" "C")
7261 (setenv "PROMPT_COMMAND")
7262 (setenv "PS1" tramp-initial-end-of-output)
7263 (let* ((target-alist (tramp-compute-multi-hops vec))
7264 (process-connection-type tramp-process-connection-type)
7265 (process-adaptive-read-buffering nil)
7266 (coding-system-for-read nil)
7267 ;; This must be done in order to avoid our file name handler.
7268 (p (let ((default-directory
7269 (tramp-compat-temporary-file-directory)))
7271 (or (tramp-get-connection-property vec "process-name" nil)
7272 (tramp-buffer-name vec))
7273 (tramp-get-connection-buffer vec)
7274 tramp-encoding-shell))))
7277 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7279 ;; Check whether process is alive.
7280 (tramp-set-process-query-on-exit-flag p nil)
7281 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
7282 (tramp-barf-if-no-shell-prompt
7283 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7285 ;; Now do all the connections as specified.
7287 (let* ((hop (car target-alist))
7288 (l-method (tramp-file-name-method hop))
7289 (l-user (tramp-file-name-user hop))
7290 (l-host (tramp-file-name-host hop))
7293 (tramp-get-method-parameter l-method 'tramp-login-program))
7295 (tramp-get-method-parameter l-method 'tramp-login-args))
7297 (tramp-get-method-parameter l-method 'tramp-gw-args))
7298 (gw (tramp-get-file-property hop "" "gateway" nil))
7299 (g-method (and gw (tramp-file-name-method gw)))
7300 (g-user (and gw (tramp-file-name-user gw)))
7301 (g-host (and gw (tramp-file-name-host gw)))
7302 (command login-program)
7303 ;; We don't create the temporary file. In fact, it
7304 ;; is just a prefix for the ControlPath option of
7305 ;; ssh; the real temporary file has another name, and
7306 ;; it is created and protected by ssh. It is also
7307 ;; removed by ssh, when the connection is closed.
7309 (tramp-set-connection-property
7313 tramp-temp-name-prefix
7314 (tramp-compat-temporary-file-directory)))))
7317 ;; Add gateway arguments if necessary.
7318 (when (and gw gw-args)
7319 (setq login-args (append login-args gw-args)))
7321 ;; Check for port number. Until now, there's no need
7322 ;; for handling like method, user, host.
7323 (when (string-match tramp-host-with-port-regexp l-host)
7324 (setq l-port (match-string 2 l-host)
7325 l-host (match-string 1 l-host)))
7327 ;; Set variables for computing the prompt for reading
7328 ;; password. They can also be derived from a gateway.
7329 (setq tramp-current-method (or g-method l-method)
7330 tramp-current-user (or g-user l-user)
7331 tramp-current-host (or g-host l-host))
7333 ;; Replace login-args place holders.
7335 l-host (or l-host "")
7336 l-user (or l-user "")
7337 l-port (or l-port "")
7338 spec (format-spec-make ?h l-host ?u l-user ?p l-port ?t tmpfile)
7341 ;; We do not want to see the trailing local prompt in
7342 ;; `start-file-process'.
7343 (unless (memq system-type '(windows-nt)) "exec ")
7347 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7348 (unless (member "" x) (mapconcat 'identity x " ")))
7350 ;; Local shell could be a Windows COMSPEC. It doesn't
7351 ;; know the ";" syntax, but we must exit always for
7352 ;; `start-file-process'. "exec" does not work either.
7353 (if (memq system-type '(windows-nt)) " && exit || exit")))
7355 ;; Send the command.
7356 (tramp-message vec 3 "Sending command `%s'" command)
7357 (tramp-send-command vec command t t)
7358 (tramp-process-actions p vec tramp-actions-before-shell 60)
7359 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
7361 (setq target-alist (cdr target-alist)))
7363 ;; Make initial shell settings.
7364 (tramp-open-connection-setup-interactive-shell p vec))))))
7366 (defun tramp-send-command (vec command &optional neveropen nooutput)
7367 "Send the COMMAND to connection VEC.
7368 Erases temporary buffer before sending the command. If optional
7369 arg NEVEROPEN is non-nil, never try to open the connection. This
7370 is meant to be used from `tramp-maybe-open-connection' only. The
7371 function waits for output unless NOOUTPUT is set."
7372 (unless neveropen (tramp-maybe-open-connection vec))
7373 (let ((p (tramp-get-connection-process vec)))
7374 (when (tramp-get-connection-property p "remote-echo" nil)
7375 ;; We mark the command string that it can be erased in the output buffer.
7376 (tramp-set-connection-property p "check-remote-echo" t)
7377 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7378 (tramp-message vec 6 "%s" command)
7379 (tramp-send-string vec command)
7380 (unless nooutput (tramp-wait-for-output p))))
7382 (defun tramp-wait-for-output (proc &optional timeout)
7383 "Wait for output from remote command."
7384 (unless (buffer-live-p (process-buffer proc))
7385 (delete-process proc)
7386 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7387 (with-current-buffer (process-buffer proc)
7388 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7389 ;; be leading escape sequences, which must be ignored.
7390 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7391 ;; Sometimes, the commands do not return a newline but a
7392 ;; null byte before the shell prompt, for example "git
7393 ;; ls-files -c -z ...".
7394 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7395 (found (tramp-wait-for-regexp proc timeout regexp1)))
7397 (let (buffer-read-only)
7398 ;; A simple-minded busybox has sent " ^H" sequences.
7400 (goto-char (point-min))
7401 (when (re-search-forward
7402 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7404 (delete-region (point-min) (point)))
7405 ;; Delete the prompt.
7406 (goto-char (point-max))
7407 (re-search-backward regexp nil t)
7408 (delete-region (point) (point-max)))
7412 "[[Remote prompt `%s' not found in %d secs]]"
7413 tramp-end-of-output timeout)
7416 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7417 ;; Return value is whether end-of-output sentinel was found.
7420 (defun tramp-send-command-and-check
7421 (vec command &optional subshell dont-suppress-err)
7422 "Run COMMAND and check its exit status.
7423 Sends `echo $?' along with the COMMAND for checking the exit status. If
7424 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7426 If the optional argument SUBSHELL is non-nil, the command is
7427 executed in a subshell, ie surrounded by parentheses. If
7428 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7431 (concat (if subshell "( " "")
7433 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7434 "echo tramp_exit_status $?"
7435 (if subshell " )" "")))
7436 (with-current-buffer (tramp-get-connection-buffer vec)
7437 (goto-char (point-max))
7438 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7440 vec 'file-error "Couldn't find exit status of `%s'" command))
7441 (skip-chars-forward "^ ")
7443 (read (current-buffer))
7444 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7446 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7447 "Run COMMAND, check exit status, throw error if exit status not okay.
7448 Similar to `tramp-send-command-and-check' but accepts two more arguments
7449 FMT and ARGS which are passed to `error'."
7450 (unless (zerop (tramp-send-command-and-check vec command))
7451 (apply 'tramp-error vec 'file-error fmt args)))
7453 (defun tramp-send-command-and-read (vec command)
7454 "Run COMMAND and return the output, which must be a Lisp expression.
7455 In case there is no valid Lisp expression, it raises an error"
7456 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7457 (with-current-buffer (tramp-get-connection-buffer vec)
7458 ;; Read the expression.
7459 (goto-char (point-min))
7461 (prog1 (read (current-buffer))
7463 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7467 "`%s' does not return a valid Lisp expression: `%s'"
7468 command (buffer-string))))))
7470 ;; It seems that Tru64 Unix does not like it if long strings are sent
7471 ;; to it in one go. (This happens when sending the Perl
7472 ;; `file-attributes' implementation, for instance.) Therefore, we
7473 ;; have this function which sends the string in chunks.
7474 (defun tramp-send-string (vec string)
7475 "Send the STRING via connection VEC.
7477 The STRING is expected to use Unix line-endings, but the lines sent to
7478 the remote host use line-endings as defined in the variable
7479 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7480 (let* ((p (tramp-get-connection-process vec))
7481 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7484 vec 'file-error "Can't send string to remote host -- not logged in"))
7485 (tramp-set-connection-property p "last-cmd-time" (current-time))
7486 (tramp-message vec 10 "%s" string)
7487 (with-current-buffer (tramp-get-connection-buffer vec)
7488 ;; Clean up the buffer. We cannot call `erase-buffer' because
7489 ;; narrowing might be in effect.
7490 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7491 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7493 (mapconcat 'identity
7494 (tramp-compat-split-string string "\n")
7495 tramp-rsh-end-of-line))
7496 (unless (or (string= string "")
7497 (string-equal (substring string -1) tramp-rsh-end-of-line))
7498 (setq string (concat string tramp-rsh-end-of-line)))
7500 (if (and chunksize (not (zerop chunksize)))
7502 (end (length string)))
7505 vec 10 "Sending chunk from %s to %s"
7506 pos (min (+ pos chunksize) end))
7507 (process-send-string
7508 p (substring string pos (min (+ pos chunksize) end)))
7509 (setq pos (+ pos chunksize))))
7510 (process-send-string p string)))))
7512 (defun tramp-mode-string-to-int (mode-string)
7513 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7514 (let* (case-fold-search
7515 (mode-chars (string-to-vector mode-string))
7516 (owner-read (aref mode-chars 1))
7517 (owner-write (aref mode-chars 2))
7518 (owner-execute-or-setid (aref mode-chars 3))
7519 (group-read (aref mode-chars 4))
7520 (group-write (aref mode-chars 5))
7521 (group-execute-or-setid (aref mode-chars 6))
7522 (other-read (aref mode-chars 7))
7523 (other-write (aref mode-chars 8))
7524 (other-execute-or-sticky (aref mode-chars 9)))
7528 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7529 ((char-equal owner-read ?-) 0)
7530 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7532 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7533 ((char-equal owner-write ?-) 0)
7534 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7536 ((char-equal owner-execute-or-setid ?x)
7537 (tramp-octal-to-decimal "00100"))
7538 ((char-equal owner-execute-or-setid ?S)
7539 (tramp-octal-to-decimal "04000"))
7540 ((char-equal owner-execute-or-setid ?s)
7541 (tramp-octal-to-decimal "04100"))
7542 ((char-equal owner-execute-or-setid ?-) 0)
7543 (t (error "Fourth char `%c' must be one of `xsS-'"
7544 owner-execute-or-setid)))
7546 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7547 ((char-equal group-read ?-) 0)
7548 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7550 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7551 ((char-equal group-write ?-) 0)
7552 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7554 ((char-equal group-execute-or-setid ?x)
7555 (tramp-octal-to-decimal "00010"))
7556 ((char-equal group-execute-or-setid ?S)
7557 (tramp-octal-to-decimal "02000"))
7558 ((char-equal group-execute-or-setid ?s)
7559 (tramp-octal-to-decimal "02010"))
7560 ((char-equal group-execute-or-setid ?-) 0)
7561 (t (error "Seventh char `%c' must be one of `xsS-'"
7562 group-execute-or-setid)))
7564 ((char-equal other-read ?r)
7565 (tramp-octal-to-decimal "00004"))
7566 ((char-equal other-read ?-) 0)
7567 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7569 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7570 ((char-equal other-write ?-) 0)
7571 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7573 ((char-equal other-execute-or-sticky ?x)
7574 (tramp-octal-to-decimal "00001"))
7575 ((char-equal other-execute-or-sticky ?T)
7576 (tramp-octal-to-decimal "01000"))
7577 ((char-equal other-execute-or-sticky ?t)
7578 (tramp-octal-to-decimal "01001"))
7579 ((char-equal other-execute-or-sticky ?-) 0)
7580 (t (error "Tenth char `%c' must be one of `xtT-'"
7581 other-execute-or-sticky)))))))
7583 (defun tramp-convert-file-attributes (vec attr)
7584 "Convert file-attributes ATTR generated by perl script, stat or ls.
7585 Convert file mode bits to string and set virtual device number.
7588 ;; Convert last access time.
7589 (unless (listp (nth 4 attr))
7590 (setcar (nthcdr 4 attr)
7591 (list (floor (nth 4 attr) 65536)
7592 (floor (mod (nth 4 attr) 65536)))))
7593 ;; Convert last modification time.
7594 (unless (listp (nth 5 attr))
7595 (setcar (nthcdr 5 attr)
7596 (list (floor (nth 5 attr) 65536)
7597 (floor (mod (nth 5 attr) 65536)))))
7598 ;; Convert last status change time.
7599 (unless (listp (nth 6 attr))
7600 (setcar (nthcdr 6 attr)
7601 (list (floor (nth 6 attr) 65536)
7602 (floor (mod (nth 6 attr) 65536)))))
7603 ;; Convert file size.
7604 (when (< (nth 7 attr) 0)
7605 (setcar (nthcdr 7 attr) -1))
7606 (when (and (floatp (nth 7 attr))
7607 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7608 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7609 ;; Convert file mode bits to string.
7610 (unless (stringp (nth 8 attr))
7611 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7612 (when (stringp (car attr))
7613 (aset (nth 8 attr) 0 ?l)))
7614 ;; Convert directory indication bit.
7615 (when (string-match "^d" (nth 8 attr))
7617 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7618 (when (consp (car attr))
7619 (if (and (stringp (caar attr))
7620 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7621 (setcar attr (match-string 1 (caar attr)))
7623 ;; Set file's gid change bit.
7624 (setcar (nthcdr 9 attr)
7625 (if (numberp (nth 3 attr))
7626 (not (= (nth 3 attr)
7627 (tramp-get-remote-gid vec 'integer)))
7630 (tramp-get-remote-gid vec 'string)))))
7632 (unless (listp (nth 10 attr))
7633 (setcar (nthcdr 10 attr)
7635 (cons (floor (nth 10 attr) 65536)
7636 (floor (mod (nth 10 attr) 65536)))
7637 ;; Inodes can be incredible huge. We must hide this.
7638 (error (tramp-get-inode vec)))))
7639 ;; Set virtual device number.
7640 (setcar (nthcdr 11 attr)
7641 (tramp-get-device vec))
7644 (defun tramp-check-cached-permissions (vec access)
7645 "Check `file-attributes' caches for VEC.
7646 Return t if according to the cache access type ACCESS is known to
7652 ((eq ?x access) 3))))
7653 (dolist (suffix '("string" "integer") result)
7659 (tramp-get-file-property
7660 vec (tramp-file-name-localname vec)
7661 (concat "file-attributes-" suffix) nil))
7663 (tramp-get-connection-property
7664 vec (concat "uid-" suffix) nil))
7666 (tramp-get-connection-property
7667 vec (concat "gid-" suffix) nil)))
7672 (eq t (car file-attr))
7673 (null (car file-attr)))
7675 ;; World accessible.
7676 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7677 ;; User accessible and owned by user.
7679 (eq access (aref (nth 8 file-attr) offset))
7680 (equal remote-uid (nth 2 file-attr)))
7681 ;; Group accessible and owned by user's
7684 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7685 (equal remote-gid (nth 3 file-attr)))))))))))
7687 (defun tramp-get-inode (vec)
7688 "Returns the virtual inode number.
7689 If it doesn't exist, generate a new one."
7690 (let ((string (tramp-make-tramp-file-name
7691 (tramp-file-name-method vec)
7692 (tramp-file-name-user vec)
7693 (tramp-file-name-host vec)
7695 (unless (assoc string tramp-inodes)
7696 (add-to-list 'tramp-inodes
7697 (list string (length tramp-inodes))))
7698 (nth 1 (assoc string tramp-inodes))))
7700 (defun tramp-get-device (vec)
7701 "Returns the virtual device number.
7702 If it doesn't exist, generate a new one."
7703 (let ((string (tramp-make-tramp-file-name
7704 (tramp-file-name-method vec)
7705 (tramp-file-name-user vec)
7706 (tramp-file-name-host vec)
7708 (unless (assoc string tramp-devices)
7709 (add-to-list 'tramp-devices
7710 (list string (length tramp-devices))))
7711 (cons -1 (nth 1 (assoc string tramp-devices)))))
7713 (defun tramp-file-mode-from-int (mode)
7714 "Turn an integer representing a file mode into an ls(1)-like string."
7715 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7716 (user (logand (lsh mode -6) 7))
7717 (group (logand (lsh mode -3) 7))
7718 (other (logand (lsh mode -0) 7))
7719 (suid (> (logand (lsh mode -9) 4) 0))
7720 (sgid (> (logand (lsh mode -9) 2) 0))
7721 (sticky (> (logand (lsh mode -9) 1) 0)))
7722 (setq user (tramp-file-mode-permissions user suid "s"))
7723 (setq group (tramp-file-mode-permissions group sgid "s"))
7724 (setq other (tramp-file-mode-permissions other sticky "t"))
7725 (concat type user group other)))
7727 (defun tramp-file-mode-permissions (perm suid suid-text)
7728 "Convert a permission bitset into a string.
7729 This is used internally by `tramp-file-mode-from-int'."
7730 (let ((r (> (logand perm 4) 0))
7731 (w (> (logand perm 2) 0))
7732 (x (> (logand perm 1) 0)))
7733 (concat (or (and r "r") "-")
7734 (or (and w "w") "-")
7735 (or (and suid x suid-text) ; suid, execute
7736 (and suid (upcase suid-text)) ; suid, !execute
7737 (and x "x") "-")))) ; !suid
7739 (defun tramp-decimal-to-octal (i)
7740 "Return a string consisting of the octal digits of I.
7741 Not actually used. Use `(format \"%o\" i)' instead?"
7742 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7743 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7745 (t (concat (tramp-decimal-to-octal (/ i 8))
7746 (number-to-string (% i 8))))))
7748 ;; Kudos to Gerd Moellmann for this suggestion.
7749 (defun tramp-octal-to-decimal (ostr)
7750 "Given a string of octal digits, return a decimal number."
7751 (let ((x (or ostr "")))
7752 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7753 (unless (string-match "\\`[0-7]*\\'" x)
7754 (error "Non-octal junk in string `%s'" x))
7755 (string-to-number ostr 8)))
7757 (defun tramp-shell-case-fold (string)
7758 "Converts STRING to shell glob pattern which ignores case."
7761 (if (equal (downcase c) (upcase c))
7763 (format "[%c%c]" (downcase c) (upcase c))))
7768 ;; ------------------------------------------------------------
7769 ;; -- Tramp file names --
7770 ;; ------------------------------------------------------------
7771 ;; Conversion functions between external representation and
7772 ;; internal data structure. Convenience functions for internal
7775 (defun tramp-file-name-p (vec)
7776 "Check whether VEC is a Tramp object."
7777 (and (vectorp vec) (= 4 (length vec))))
7779 (defun tramp-file-name-method (vec)
7780 "Return method component of VEC."
7781 (and (tramp-file-name-p vec) (aref vec 0)))
7783 (defun tramp-file-name-user (vec)
7784 "Return user component of VEC."
7785 (and (tramp-file-name-p vec) (aref vec 1)))
7787 (defun tramp-file-name-host (vec)
7788 "Return host component of VEC."
7789 (and (tramp-file-name-p vec) (aref vec 2)))
7791 (defun tramp-file-name-localname (vec)
7792 "Return localname component of VEC."
7793 (and (tramp-file-name-p vec) (aref vec 3)))
7795 ;; The user part of a Tramp file name vector can be of kind
7796 ;; "user%domain". Sometimes, we must extract these parts.
7797 (defun tramp-file-name-real-user (vec)
7798 "Return the user name of VEC without domain."
7800 (let ((user (tramp-file-name-user vec)))
7801 (if (and (stringp user)
7802 (string-match tramp-user-with-domain-regexp user))
7803 (match-string 1 user)
7806 (defun tramp-file-name-domain (vec)
7807 "Return the domain name of VEC."
7809 (let ((user (tramp-file-name-user vec)))
7811 (string-match tramp-user-with-domain-regexp user)
7812 (match-string 2 user)))))
7814 ;; The host part of a Tramp file name vector can be of kind
7815 ;; "host#port". Sometimes, we must extract these parts.
7816 (defun tramp-file-name-real-host (vec)
7817 "Return the host name of VEC without port."
7819 (let ((host (tramp-file-name-host vec)))
7820 (if (and (stringp host)
7821 (string-match tramp-host-with-port-regexp host))
7822 (match-string 1 host)
7825 (defun tramp-file-name-port (vec)
7826 "Return the port number of VEC."
7828 (let ((host (tramp-file-name-host vec)))
7830 (string-match tramp-host-with-port-regexp host)
7831 (string-to-number (match-string 2 host))))))
7833 (defun tramp-tramp-file-p (name)
7834 "Return t if NAME is a string with Tramp file name syntax."
7836 (and (stringp name) (string-match tramp-file-name-regexp name))))
7838 (defun tramp-find-method (method user host)
7839 "Return the right method string to use.
7840 This is METHOD, if non-nil. Otherwise, do a lookup in
7841 `tramp-default-method-alist'."
7843 (let ((choices tramp-default-method-alist)
7846 (setq item (pop choices))
7847 (when (and (string-match (or (nth 0 item) "") (or host ""))
7848 (string-match (or (nth 1 item) "") (or user "")))
7849 (setq lmethod (nth 2 item))
7850 (setq choices nil)))
7852 tramp-default-method))
7854 (defun tramp-find-user (method user host)
7855 "Return the right user string to use.
7856 This is USER, if non-nil. Otherwise, do a lookup in
7857 `tramp-default-user-alist'."
7859 (let ((choices tramp-default-user-alist)
7862 (setq item (pop choices))
7863 (when (and (string-match (or (nth 0 item) "") (or method ""))
7864 (string-match (or (nth 1 item) "") (or host "")))
7865 (setq luser (nth 2 item))
7866 (setq choices nil)))
7868 tramp-default-user))
7870 (defun tramp-find-host (method user host)
7871 "Return the right host string to use.
7872 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7873 (or (and (> (length host) 0) host)
7874 tramp-default-host))
7876 (defun tramp-dissect-file-name (name &optional nodefault)
7877 "Return a `tramp-file-name' structure.
7878 The structure consists of remote method, remote user, remote host
7879 and localname (file name on remote host). If NODEFAULT is
7880 non-nil, the file name parts are not expanded to their default
7883 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
7884 (unless match (error "Not a Tramp file name: %s" name))
7885 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7886 (user (match-string (nth 2 tramp-file-name-structure) name))
7887 (host (match-string (nth 3 tramp-file-name-structure) name))
7888 (localname (match-string (nth 4 tramp-file-name-structure) name)))
7889 (when (member method '("multi" "multiu"))
7891 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7894 (when (string-match tramp-prefix-ipv6-regexp host)
7895 (setq host (replace-match "" nil t host)))
7896 (when (string-match tramp-postfix-ipv6-regexp host)
7897 (setq host (replace-match "" nil t host))))
7899 (vector method user host localname)
7901 (tramp-find-method method user host)
7902 (tramp-find-user method user host)
7903 (tramp-find-host method user host)
7906 (defun tramp-equal-remote (file1 file2)
7907 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7908 The check depends on method, user and host name of the files. If
7909 one of the components is missing, the default values are used.
7910 The local file name parts of FILE1 and FILE2 are not taken into
7915 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7917 would yield `t'. On the other hand, the following check results in nil:
7919 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
7920 (and (stringp (file-remote-p file1))
7921 (stringp (file-remote-p file2))
7922 (string-equal (file-remote-p file1) (file-remote-p file2))))
7924 (defun tramp-make-tramp-file-name (method user host localname)
7925 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7926 (concat tramp-prefix-format
7927 (when (not (zerop (length method)))
7928 (concat method tramp-postfix-method-format))
7929 (when (not (zerop (length user)))
7930 (concat user tramp-postfix-user-format))
7932 (if (string-match tramp-ipv6-regexp host)
7933 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7935 tramp-postfix-host-format
7936 (when localname localname)))
7938 (defun tramp-completion-make-tramp-file-name (method user host localname)
7939 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7940 It must not be a complete Tramp file name, but as long as there are
7941 necessary only. This function will be used in file name completion."
7942 (concat tramp-prefix-format
7943 (when (not (zerop (length method)))
7944 (concat method tramp-postfix-method-format))
7945 (when (not (zerop (length user)))
7946 (concat user tramp-postfix-user-format))
7947 (when (not (zerop (length host)))
7949 (if (string-match tramp-ipv6-regexp host)
7950 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7952 tramp-postfix-host-format))
7953 (when localname localname)))
7955 (defun tramp-make-copy-program-file-name (vec)
7956 "Create a file name suitable to be passed to `rcp' and workalikes."
7957 (let ((user (tramp-file-name-user vec))
7958 (host (tramp-file-name-real-host vec))
7959 (localname (tramp-shell-quote-argument
7960 (tramp-file-name-localname vec))))
7961 (if (not (zerop (length user)))
7962 (format "%s@%s:%s" user host localname)
7963 (format "%s:%s" host localname))))
7965 (defun tramp-method-out-of-band-p (vec size)
7966 "Return t if this is an out-of-band method, nil otherwise."
7968 ;; It shall be an out-of-band method.
7969 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7970 ;; Either the file size is large enough, or (in rare cases) there
7971 ;; does not exist a remote encoding.
7972 (or (> size tramp-copy-size-limit)
7973 (null (tramp-get-remote-coding vec "remote-encoding")))))
7975 (defun tramp-local-host-p (vec)
7976 "Return t if this points to the local host, nil otherwise."
7977 ;; We cannot use `tramp-file-name-real-host'. A port is an
7978 ;; indication for an ssh tunnel or alike.
7979 (let ((host (tramp-file-name-host vec)))
7982 (string-match tramp-local-host-regexp host)
7983 ;; The method shall be applied to one of the shell file name
7984 ;; handler. `tramp-local-host-p' is also called for "smb" and
7985 ;; alike, where it must fail.
7986 (tramp-get-method-parameter
7987 (tramp-file-name-method vec) 'tramp-login-program)
7988 ;; The local temp directory must be writable for the other user.
7990 (tramp-make-tramp-file-name
7991 (tramp-file-name-method vec)
7992 (tramp-file-name-user vec)
7994 (tramp-compat-temporary-file-directory)))
7995 ;; On some systems, chown runs only for root.
7996 (or (zerop (user-uid))
7997 (zerop (tramp-get-remote-uid vec 'integer))))))
7999 ;; Variables local to connection.
8001 (defun tramp-get-remote-path (vec)
8002 (with-connection-property
8003 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8004 ;; cache the result for the session only. Otherwise, the result
8005 ;; is cached persistently.
8006 (if (memq 'tramp-own-remote-path tramp-remote-path)
8007 (tramp-get-connection-process vec)
8010 (let* ((remote-path (copy-tree tramp-remote-path))
8011 (elt1 (memq 'tramp-default-remote-path remote-path))
8012 (elt2 (memq 'tramp-own-remote-path remote-path))
8013 (default-remote-path
8016 (tramp-send-command-and-read
8017 vec "echo \\\"`getconf PATH`\\\"")
8018 ;; Default if "getconf" is not available.
8022 "`getconf PATH' not successful, using default value \"%s\"."
8028 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8029 ;; Default if "getconf" is not available.
8032 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8035 ;; Replace place holder `tramp-default-remote-path'.
8039 (tramp-compat-split-string default-remote-path ":")
8041 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8043 ;; Replace place holder `tramp-own-remote-path'.
8047 (tramp-compat-split-string own-remote-path ":")
8049 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8051 ;; Remove double entries.
8052 (setq elt1 remote-path)
8054 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8056 (setq elt1 (cdr elt1)))
8058 ;; Remove non-existing directories.
8066 (tramp-make-tramp-file-name
8067 (tramp-file-name-method vec)
8068 (tramp-file-name-user vec)
8069 (tramp-file-name-host vec)
8074 (defun tramp-get-remote-tmpdir (vec)
8075 (with-connection-property vec "tmp-directory"
8076 (let ((dir (tramp-shell-quote-argument "/tmp")))
8078 (tramp-send-command-and-check
8079 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8081 (tramp-send-command-and-check
8082 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8084 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8086 (defun tramp-get-ls-command (vec)
8087 (with-connection-property vec "ls"
8088 (tramp-message vec 5 "Finding a suitable `ls' command")
8091 (dolist (cmd '("ls" "gnuls" "gls"))
8092 (let ((dl (tramp-get-remote-path vec))
8094 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8095 ;; Check parameters. On busybox, "ls" output coloring is
8096 ;; enabled by default sometimes. So we try to disable it
8097 ;; when possible. $LS_COLORING is not supported there.
8098 (when (zerop (tramp-send-command-and-check
8099 vec (format "%s -lnd /" result)))
8100 (when (zerop (tramp-send-command-and-check
8101 vec (format "%s --color=never /" result)))
8102 (setq result (concat result " --color=never")))
8103 (throw 'ls-found result))
8104 (setq dl (cdr dl))))))
8105 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8107 (defun tramp-get-ls-command-with-dired (vec)
8109 (with-connection-property vec "ls-dired"
8110 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8111 (zerop (tramp-send-command-and-check
8112 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8114 (defun tramp-get-test-command (vec)
8115 (with-connection-property vec "test"
8116 (tramp-message vec 5 "Finding a suitable `test' command")
8117 (if (zerop (tramp-send-command-and-check vec "test 0"))
8119 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8121 (defun tramp-get-test-nt-command (vec)
8122 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8123 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8124 ;; for otherwise the shell crashes.
8125 (with-connection-property vec "test-nt"
8129 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8130 (with-current-buffer (tramp-get-buffer vec)
8131 (goto-char (point-min))
8132 (when (looking-at (regexp-quote tramp-end-of-output))
8133 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8138 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8139 (tramp-get-test-command vec)))
8140 "tramp_test_nt %s %s"))))
8142 (defun tramp-get-file-exists-command (vec)
8143 (with-connection-property vec "file-exists"
8144 (tramp-message vec 5 "Finding command to check if file exists")
8145 (tramp-find-file-exists-command vec)))
8147 (defun tramp-get-remote-ln (vec)
8148 (with-connection-property vec "ln"
8149 (tramp-message vec 5 "Finding a suitable `ln' command")
8150 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8152 (defun tramp-get-remote-perl (vec)
8153 (with-connection-property vec "perl"
8154 (tramp-message vec 5 "Finding a suitable `perl' command")
8156 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8157 (tramp-find-executable
8158 vec "perl" (tramp-get-remote-path vec)))))
8159 ;; We must check also for some Perl modules.
8161 (with-connection-property vec "perl-file-spec"
8163 (tramp-send-command-and-check
8164 vec (format "%s -e 'use File::Spec;'" result))))
8165 (with-connection-property vec "perl-cwd-realpath"
8167 (tramp-send-command-and-check
8168 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8171 (defun tramp-get-remote-stat (vec)
8172 (with-connection-property vec "stat"
8173 (tramp-message vec 5 "Finding a suitable `stat' command")
8174 (let ((result (tramp-find-executable
8175 vec "stat" (tramp-get-remote-path vec)))
8177 ;; Check whether stat(1) returns usable syntax. %s does not
8178 ;; work on older AIX systems.
8181 ;; We don't want to display an error message.
8182 (with-temp-message (or (current-message) "")
8184 (tramp-send-command-and-read
8185 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8187 (unless (and (listp tmp) (stringp (car tmp))
8188 (string-match "^./.$" (car tmp))
8189 (integerp (cadr tmp)))
8193 (defun tramp-get-remote-readlink (vec)
8194 (with-connection-property vec "readlink"
8195 (tramp-message vec 5 "Finding a suitable `readlink' command")
8196 (let ((result (tramp-find-executable
8197 vec "readlink" (tramp-get-remote-path vec))))
8199 ;; We don't want to display an error message.
8200 (with-temp-message (or (current-message) "")
8203 (tramp-send-command-and-check
8204 vec (format "%s --canonicalize-missing /" result)))
8208 (defun tramp-get-remote-id (vec)
8209 (with-connection-property vec "id"
8210 (tramp-message vec 5 "Finding POSIX `id' command")
8213 (let ((dl (tramp-get-remote-path vec))
8215 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8216 ;; Check POSIX parameter.
8217 (when (zerop (tramp-send-command-and-check
8218 vec (format "%s -u" result)))
8219 (throw 'id-found result))
8220 (setq dl (cdr dl)))))
8221 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8223 (defun tramp-get-remote-uid (vec id-format)
8224 (with-connection-property vec (format "uid-%s" id-format)
8225 (let ((res (tramp-send-command-and-read
8227 (format "%s -u%s %s"
8228 (tramp-get-remote-id vec)
8229 (if (equal id-format 'integer) "" "n")
8230 (if (equal id-format 'integer)
8231 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8232 ;; The command might not always return a number.
8233 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8235 (defun tramp-get-remote-gid (vec id-format)
8236 (with-connection-property vec (format "gid-%s" id-format)
8237 (let ((res (tramp-send-command-and-read
8239 (format "%s -g%s %s"
8240 (tramp-get-remote-id vec)
8241 (if (equal id-format 'integer) "" "n")
8242 (if (equal id-format 'integer)
8243 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8244 ;; The command might not always return a number.
8245 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8247 (defun tramp-get-local-uid (id-format)
8248 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8250 (defun tramp-get-local-gid (id-format)
8251 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8253 ;; Some predefined connection properties.
8254 (defun tramp-get-remote-coding (vec prop)
8255 ;; Local coding handles properties like remote coding. So we could
8256 ;; call it without pain.
8257 (let ((ret (tramp-get-local-coding vec prop)))
8258 ;; The connection property might have been cached. So we must send
8259 ;; the script - maybe.
8260 (when (and ret (symbolp ret))
8261 (let ((name (symbol-name ret)))
8262 (while (string-match (regexp-quote "-") name)
8263 (setq name (replace-match "_" nil t name)))
8264 (tramp-maybe-send-script vec (symbol-value ret) name)
8266 ;; Return the value.
8269 (defun tramp-get-local-coding (vec prop)
8271 (tramp-get-connection-property vec prop nil)
8273 (tramp-find-inline-encoding vec)
8274 (tramp-get-connection-property vec prop nil))))
8276 (defun tramp-get-method-parameter (method param)
8277 "Return the method parameter PARAM.
8278 If the `tramp-methods' entry does not exist, return NIL."
8279 (let ((entry (assoc param (assoc method tramp-methods))))
8280 (when entry (cadr entry))))
8282 ;; Auto saving to a special directory.
8284 (defun tramp-exists-file-name-handler (operation &rest args)
8285 "Checks whether OPERATION runs a file name handler."
8286 ;; The file name handler is determined on base of either an
8287 ;; argument, `buffer-file-name', or `default-directory'.
8289 (let* ((buffer-file-name "/")
8290 (default-directory "/")
8291 (fnha file-name-handler-alist)
8292 (check-file-name-operation operation)
8293 (file-name-handler-alist
8296 (lambda (operation &rest args)
8297 "Returns OPERATION if it is the one to be checked."
8298 (if (equal check-file-name-operation operation)
8300 (let ((file-name-handler-alist fnha))
8301 (apply operation args))))))))
8302 (equal (apply operation args) operation))
8305 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8306 (defadvice make-auto-save-file-name
8307 (around tramp-advice-make-auto-save-file-name () activate)
8308 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8309 (if (tramp-tramp-file-p (buffer-file-name))
8310 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8311 ;; directly, because this would bypass the locking mechanism.
8312 (setq ad-return-value
8313 (tramp-file-name-handler 'make-auto-save-file-name))
8319 'make-auto-save-file-name
8320 'around 'tramp-advice-make-auto-save-file-name)
8321 (ad-activate 'make-auto-save-file-name))))
8323 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8324 ;; umask. This is a security threat.
8326 (defun tramp-set-auto-save-file-modes ()
8327 "Set permissions of autosaved remote files to the original permissions."
8328 (let ((bfn (buffer-file-name)))
8329 (when (and (tramp-tramp-file-p bfn)
8331 (stringp buffer-auto-save-file-name)
8332 (not (equal bfn buffer-auto-save-file-name)))
8333 (unless (file-exists-p buffer-auto-save-file-name)
8334 (write-region "" nil buffer-auto-save-file-name))
8335 ;; Permissions should be set always, because there might be an old
8336 ;; auto-saved file belonging to another original file. This could
8337 ;; be a security threat.
8338 (set-file-modes buffer-auto-save-file-name
8339 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8341 (unless (and (featurep 'xemacs)
8342 (= emacs-major-version 21)
8343 (> emacs-minor-version 4))
8344 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8345 (add-hook 'tramp-unload-hook
8347 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8349 (defun tramp-subst-strs-in-string (alist string)
8350 "Replace all occurrences of the string FROM with TO in STRING.
8351 ALIST is of the form ((FROM . TO) ...)."
8354 (let* ((pr (car alist))
8357 (while (string-match (regexp-quote from) string)
8358 (setq string (replace-match to t t string)))
8359 (setq alist (cdr alist))))
8362 ;; ------------------------------------------------------------
8363 ;; -- Compatibility functions section --
8364 ;; ------------------------------------------------------------
8366 (defun tramp-read-passwd (proc &optional prompt)
8367 "Read a password from user (compat function).
8368 Consults the auth-source package.
8369 Invokes `password-read' if available, `read-passwd' else."
8370 (let* ((key (tramp-make-tramp-file-name
8371 tramp-current-method tramp-current-user
8372 tramp-current-host ""))
8375 (with-current-buffer (process-buffer proc)
8376 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8377 (format "%s for %s " (capitalize (match-string 1)) key)))))
8378 (with-parsed-tramp-file-name key nil
8381 ;; See if auth-sources contains something useful, if it's bound.
8382 (and (boundp 'auth-sources)
8383 (tramp-get-connection-property v "first-password-request" nil)
8384 ;; Try with Tramp's current method.
8385 (funcall (symbol-function 'auth-source-user-or-password)
8386 "password" tramp-current-host tramp-current-method))
8387 ;; Try the password cache.
8388 (when (functionp 'password-read)
8389 (unless (tramp-get-connection-property
8390 v "first-password-request" nil)
8391 (funcall (symbol-function 'password-cache-remove) key))
8393 (funcall (symbol-function 'password-read) pw-prompt key)))
8394 (funcall (symbol-function 'password-cache-add) key password)
8396 ;; Else, get the password interactively.
8397 (read-passwd pw-prompt))
8398 (tramp-set-connection-property v "first-password-request" nil)))))
8400 (defun tramp-clear-passwd (vec)
8401 "Clear password cache for connection related to VEC."
8402 (when (functionp 'password-cache-remove)
8404 (symbol-function 'password-cache-remove)
8405 (tramp-make-tramp-file-name
8406 (tramp-file-name-method vec)
8407 (tramp-file-name-user vec)
8408 (tramp-file-name-host vec)
8411 ;; Snarfed code from time-date.el and parse-time.el
8413 (defconst tramp-half-a-year '(241 17024)
8414 "Evaluated by \"(days-to-time 183)\".")
8416 (defconst tramp-parse-time-months
8417 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8418 ("apr" . 4) ("may" . 5) ("jun" . 6)
8419 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8420 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8421 "Alist mapping month names to integers.")
8423 (defun tramp-time-less-p (t1 t2)
8424 "Say whether time value T1 is less than time value T2."
8425 (unless t1 (setq t1 '(0 0)))
8426 (unless t2 (setq t2 '(0 0)))
8427 (or (< (car t1) (car t2))
8428 (and (= (car t1) (car t2))
8429 (< (nth 1 t1) (nth 1 t2)))))
8431 (defun tramp-time-subtract (t1 t2)
8432 "Subtract two time values.
8433 Return the difference in the format of a time value."
8434 (unless t1 (setq t1 '(0 0)))
8435 (unless t2 (setq t2 '(0 0)))
8436 (let ((borrow (< (cadr t1) (cadr t2))))
8437 (list (- (car t1) (car t2) (if borrow 1 0))
8438 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8440 (defun tramp-time-diff (t1 t2)
8441 "Return the difference between the two times, in seconds.
8442 T1 and T2 are time values (as returned by `current-time' for example)."
8443 ;; Pacify byte-compiler with `symbol-function'.
8444 (cond ((and (fboundp 'subtract-time)
8445 (fboundp 'float-time))
8446 (funcall (symbol-function 'float-time)
8447 (funcall (symbol-function 'subtract-time) t1 t2)))
8448 ((and (fboundp 'subtract-time)
8449 (fboundp 'time-to-seconds))
8450 (funcall (symbol-function 'time-to-seconds)
8451 (funcall (symbol-function 'subtract-time) t1 t2)))
8452 ((fboundp 'itimer-time-difference)
8453 (funcall (symbol-function 'itimer-time-difference)
8454 (if (< (length t1) 3) (append t1 '(0)) t1)
8455 (if (< (length t2) 3) (append t2 '(0)) t2)))
8457 (let ((time (tramp-time-subtract t1 t2)))
8458 (+ (* (car time) 65536.0)
8460 (/ (or (nth 2 time) 0) 1000000.0))))))
8462 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8463 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8464 EOL-TYPE can be one of `dos', `unix', or `mac'."
8465 (cond ((fboundp 'coding-system-change-eol-conversion)
8466 (funcall (symbol-function 'coding-system-change-eol-conversion)
8467 coding-system eol-type))
8468 ((fboundp 'subsidiary-coding-system)
8469 (funcall (symbol-function 'subsidiary-coding-system)
8471 (cond ((eq eol-type 'dos) 'crlf)
8472 ((eq eol-type 'unix) 'lf)
8473 ((eq eol-type 'mac) 'cr)
8475 (error "Unknown EOL-TYPE `%s', must be %s"
8477 "`dos', `unix', or `mac'")))))
8478 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8480 (defun tramp-set-process-query-on-exit-flag (process flag)
8481 "Specify if query is needed for process when Emacs is exited.
8482 If the second argument flag is non-nil, Emacs will query the user before
8483 exiting if process is running."
8484 (if (fboundp 'set-process-query-on-exit-flag)
8485 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
8486 (funcall (symbol-function 'process-kill-without-query) process flag)))
8489 ;; ------------------------------------------------------------
8490 ;; -- Kludges section --
8491 ;; ------------------------------------------------------------
8493 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8494 ;; does not deal well with newline characters. Newline is replaced by
8495 ;; backslash newline. But if, say, the string `a backslash newline b'
8496 ;; is passed to a shell, the shell will expand this into "ab",
8497 ;; completely omitting the newline. This is not what was intended.
8498 ;; It does not appear to be possible to make the function
8499 ;; `shell-quote-argument' work with newlines without making it
8500 ;; dependent on the shell used. But within this package, we know that
8501 ;; we will always use a Bourne-like shell, so we use an approach which
8504 ;; The approach is simple: we call `shell-quote-argument', then
8505 ;; massage the newline part of the result.
8507 ;; This function should produce a string which is grokked by a Unix
8508 ;; shell, even if the Emacs is running on Windows. Since this is the
8509 ;; kludges section, we bind `system-type' in such a way that
8510 ;; `shell-quote-arguments' behaves as if on Unix.
8512 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8513 ;; function to work with Bourne-like shells.
8515 ;; CCC: This function should be rewritten so that
8516 ;; `shell-quote-argument' is not used. This way, we are safe from
8517 ;; changes in `shell-quote-argument'.
8518 (defun tramp-shell-quote-argument (s)
8519 "Similar to `shell-quote-argument', but groks newlines.
8520 Only works for Bourne-like shells."
8521 (let ((system-type 'not-windows))
8523 (let ((result (shell-quote-argument s))
8524 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8525 (when (and (>= (length result) 2)
8526 (string= (substring result 0 2) "\\~"))
8527 (setq result (substring result 1)))
8528 (while (string-match nl result)
8529 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8533 ;; Checklist for `tramp-unload-hook'
8534 ;; - Unload all `tramp-*' packages
8535 ;; - Reset `file-name-handler-alist'
8536 ;; - Cleanup hooks where Tramp functions are in
8537 ;; - Cleanup advised functions
8538 ;; - Cleanup autoloads
8540 (defun tramp-unload-tramp ()
8541 "Discard Tramp from loading remote files."
8543 ;; When Tramp is not loaded yet, its autoloads are still active.
8544 (tramp-unload-file-name-handlers)
8545 ;; ange-ftp settings must be enabled.
8546 (when (functionp 'tramp-ftp-enable-ange-ftp)
8547 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
8548 ;; Maybe its not loaded yet.
8550 (unload-feature 'tramp 'force)
8553 (when (and load-in-progress
8554 (string-match "Loading tramp..." (or (current-message) "")))
8555 (message "Loading tramp...done"))
8561 ;; * Handle nonlocal exits such as C-g.
8562 ;; * But it would probably be better to use with-local-quit at the
8563 ;; place where it's actually needed: around any potentially
8564 ;; indefinitely blocking piece of code. In this case it would be
8565 ;; within Tramp around one of its calls to accept-process-output (or
8566 ;; around one of the loops that calls accept-process-output)
8567 ;; (Stefan Monnier).
8568 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8569 ;; `shell-quote-argument'.
8570 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8571 ;; by the files in that directory. Add this here.
8572 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8573 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8574 ;; * Case-insensitive filename completion. (Norbert Goevert.)
8575 ;; * Don't use globbing for directories with many files, as this is
8576 ;; likely to produce long command lines, and some shells choke on
8577 ;; long command lines.
8578 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8579 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8580 ;; * abbreviate-file-name
8581 ;; * Better error checking. At least whenever we see something
8582 ;; strange when doing zerop, we should kill the process and start
8583 ;; again. (Greg Stark)
8584 ;; * Remove unneeded parameters from methods.
8585 ;; * Make it work for different encodings, and for different file name
8586 ;; encodings, too. (Daniel Pittman)
8587 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8588 ;; then look if it's the right version (with `perl -v').
8589 ;; * When editing a remote CVS controlled file as a different user, VC
8590 ;; gets confused about the file locking status. Try to find out why
8591 ;; the workaround doesn't work.
8592 ;; * Username and hostname completion.
8593 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8594 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8595 ;; Code is nearly identical.
8596 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8597 ;; until the last but one hop via `start-file-process'. Apply it
8598 ;; also for ftp and smb.
8599 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8600 ;; some shell with root priviledges, it would be nice if I could
8602 ;; trampclient filename.c
8603 ;; as an editor, and the _current_ shell would connect to an Emacs
8604 ;; server and would be used in an existing non-priviledged Emacs
8605 ;; session for doing the editing in question.
8606 ;; That way, I need not tell Emacs my password again and be afraid
8607 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8608 ;; once display a just typed password in the context of a keyboard
8609 ;; sequence prompt for a question immediately following in a shell
8610 ;; script run within Emacs -- nasty).
8611 ;; And if I have some ssh session running to a different computer,
8612 ;; having the possibility of passing a local file there to a local
8613 ;; Emacs session (in case I can arrange for a connection back) would
8615 ;; Likely the corresponding Tramp server should not allow the
8616 ;; equivalent of the emacsclient -eval option in order to make this
8617 ;; reasonably unproblematic. And maybe trampclient should have some
8618 ;; way of passing credentials, like by using an SSL socket or
8619 ;; something. (David Kastrup)
8620 ;; * Reconnect directly to a compliant shell without first going
8621 ;; through the user's default shell. (Pete Forman)
8622 ;; * Make `tramp-default-user' obsolete.
8623 ;; * How can I interrupt the remote process with a signal
8624 ;; (interrupt-process seems not to work)? (Markus Triska)
8625 ;; * Avoid the local shell entirely for starting remote processes. If
8626 ;; so, I think even a signal, when delivered directly to the local
8627 ;; SSH instance, would correctly be propagated to the remote process
8628 ;; automatically; possibly SSH would have to be started with
8629 ;; "-t". (Markus Triska)
8630 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8631 ;; isn't on the remote host. (Mark A. Hershberger)
8632 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8633 ;; * Implement a general server-local-variable mechanism, as there are
8634 ;; probably other variables that need different values for different
8635 ;; servers too. The user could then configure a variable (such as
8636 ;; tramp-server-local-variable-alist) to define any such variables
8637 ;; that they need to, which would then be let bound as appropriate
8638 ;; in tramp functions. (Jason Rumney)
8639 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8641 ;; * Keep a second connection open for out-of-band methods like scp or
8643 ;; * Support ptys in `tramp-handle-start-file-process'. (Bug#4604)
8644 ;; * IMHO, it's a drawback that currently Tramp doesn't support
8645 ;; Unicode in Dired file names by default. Is it possible to
8646 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8647 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
8648 ;; expects only English messages? (Juri Linkov)
8649 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8650 ;; * Do not handle files with drive letter as remote. (Bug#5447)
8651 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
8652 ;; * Try telnet+curl as new method. It might be useful for busybox,
8653 ;; without built-in uuencode/uudecode.
8654 ;; * Let `shell-dynamic-complete-*' and `comint-dynamic-complete' work
8656 ;; * Use secrets.el for password handling.
8657 ;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
8659 ;; Functions for file-name-handler-alist:
8660 ;; diff-latest-backup-file -- in diff.el
8662 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8663 ;;; tramp.el ends here