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 (tramp-compat-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
210 (when (boundp 'backup-directory-alist)
211 (defcustom tramp-backup-directory-alist nil
212 "Alist of filename patterns and backup directory names.
213 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
214 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
215 is a local file name, the backup directory is prepended with Tramp file
216 name prefix \(method, user, host\) of file.
218 \(setq tramp-backup-directory-alist backup-directory-alist\)
220 gives the same backup policy for Tramp files on their hosts like the
221 policy for local files."
223 :type '(repeat (cons (regexp :tag "Regexp matching filename")
224 (directory :tag "Backup directory name"))))))
226 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
227 ;; the package "backup-dir" might not be loaded yet.
229 (when (featurep 'xemacs)
230 (defcustom tramp-bkup-backup-directory-info nil
231 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
232 It has the same meaning like `bkup-backup-directory-info' from package
233 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
234 file name, the backup directory is prepended with Tramp file name prefix
235 \(method, user, host\) of file.
237 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
239 gives the same backup policy for Tramp files on their hosts like the
240 policy for local files."
242 (list (regexp :tag "File regexp")
243 (string :tag "Backup Dir")
248 (const search-upward))))
251 (defcustom tramp-auto-save-directory nil
252 "*Put auto-save files in this directory, if set.
253 The idea is to use a local directory so that auto-saving is faster."
255 :type '(choice (const nil) string))
257 (defcustom tramp-encoding-shell
258 (if (memq system-type '(windows-nt))
261 "*Use this program for encoding and decoding commands on the local host.
262 This shell is used to execute the encoding and decoding command on the
263 local host, so if you want to use `~' in those commands, you should
264 choose a shell here which groks tilde expansion. `/bin/sh' normally
265 does not understand tilde expansion.
267 For encoding and deocding, commands like the following are executed:
269 /bin/sh -c COMMAND < INPUT > OUTPUT
271 This variable can be used to change the \"/bin/sh\" part. See the
272 variable `tramp-encoding-command-switch' for the \"-c\" part.
274 Note that this variable is not used for remote commands. There are
275 mechanisms in tramp.el which automatically determine the right shell to
276 use for the remote host."
278 :type '(file :must-match t))
280 (defcustom tramp-encoding-command-switch
281 (if (string-match "cmd\\.exe" tramp-encoding-shell)
284 "*Use this switch together with `tramp-encoding-shell' for local commands.
285 See the variable `tramp-encoding-shell' for more information."
289 (defcustom tramp-inline-compress-start-size 4096
290 "*The minimum size of compressing where inline transfer.
291 When inline transfer, compress transfered data of file
292 whose size is this value or above (up to `tramp-copy-size-limit').
293 If it is nil, no compression at all will be applied."
295 :type '(choice (const nil) integer))
297 (defcustom tramp-copy-size-limit 10240
298 "*The maximum file size where inline copying is preferred over an out-of-the-band copy.
299 If it is nil, inline out-of-the-band copy will be used without a check."
301 :type '(choice (const nil) integer))
303 (defcustom tramp-terminal-type "dumb"
304 "*Value of TERM environment variable for logging in to remote host.
305 Because Tramp wants to parse the output of the remote shell, it is easily
306 confused by ANSI color escape sequences and suchlike. Often, shell init
307 files conditionalize this setup based on the TERM environment variable."
311 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
312 ;; root users. It uses the `$' character for other users. In order
313 ;; to guarantee a proper prompt, we use "#$" for the prompt.
315 (defvar tramp-end-of-output
318 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
319 "String used to recognize end of output.
320 The '$' character at the end is quoted; the string cannot be
321 detected as prompt when being sent on echoing hosts, therefore.")
323 (defconst tramp-initial-end-of-output "#$ "
324 "Prompt when establishing a connection.")
326 (defvar tramp-methods
327 `(("rcp" (tramp-login-program "rsh")
328 (tramp-login-args (("%h") ("-l" "%u")))
329 (tramp-remote-sh "/bin/sh")
330 (tramp-copy-program "rcp")
331 (tramp-copy-args (("-p" "%k") ("-r")))
332 (tramp-copy-keep-date t)
333 (tramp-copy-recursive t)
334 (tramp-password-end-of-line nil))
335 ("scp" (tramp-login-program "ssh")
336 (tramp-login-args (("-l" "%u") ("-p" "%p")
337 ("-e" "none") ("%h")))
338 (tramp-async-args (("-q")))
339 (tramp-remote-sh "/bin/sh")
340 (tramp-copy-program "scp")
341 (tramp-copy-args (("-P" "%p") ("-p" "%k")
343 (tramp-copy-keep-date t)
344 (tramp-copy-recursive t)
345 (tramp-password-end-of-line nil)
346 (tramp-gw-args (("-o"
347 "GlobalKnownHostsFile=/dev/null")
348 ("-o" "UserKnownHostsFile=/dev/null")
349 ("-o" "StrictHostKeyChecking=no")))
350 (tramp-default-port 22))
351 ("scp1" (tramp-login-program "ssh")
352 (tramp-login-args (("-l" "%u") ("-p" "%p")
353 ("-1") ("-e" "none") ("%h")))
354 (tramp-async-args (("-q")))
355 (tramp-remote-sh "/bin/sh")
356 (tramp-copy-program "scp")
357 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
359 (tramp-copy-keep-date t)
360 (tramp-copy-recursive t)
361 (tramp-password-end-of-line nil)
362 (tramp-gw-args (("-o"
363 "GlobalKnownHostsFile=/dev/null")
364 ("-o" "UserKnownHostsFile=/dev/null")
365 ("-o" "StrictHostKeyChecking=no")))
366 (tramp-default-port 22))
367 ("scp2" (tramp-login-program "ssh")
368 (tramp-login-args (("-l" "%u") ("-p" "%p")
369 ("-2") ("-e" "none") ("%h")))
370 (tramp-async-args (("-q")))
371 (tramp-remote-sh "/bin/sh")
372 (tramp-copy-program "scp")
373 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
375 (tramp-copy-keep-date t)
376 (tramp-copy-recursive t)
377 (tramp-password-end-of-line nil)
378 (tramp-gw-args (("-o"
379 "GlobalKnownHostsFile=/dev/null")
380 ("-o" "UserKnownHostsFile=/dev/null")
381 ("-o" "StrictHostKeyChecking=no")))
382 (tramp-default-port 22))
384 (tramp-login-program "ssh1")
385 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
387 (tramp-remote-sh "/bin/sh")
388 (tramp-copy-program "scp1")
389 (tramp-copy-args (("-p" "%k") ("-r")))
390 (tramp-copy-keep-date t)
391 (tramp-copy-recursive t)
392 (tramp-password-end-of-line nil))
394 (tramp-login-program "ssh2")
395 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
397 (tramp-remote-sh "/bin/sh")
398 (tramp-copy-program "scp2")
399 (tramp-copy-args (("-p" "%k") ("-r")))
400 (tramp-copy-keep-date t)
401 (tramp-copy-recursive t)
402 (tramp-password-end-of-line nil))
403 ("sftp" (tramp-login-program "ssh")
404 (tramp-login-args (("-l" "%u") ("-p" "%p")
405 ("-e" "none") ("%h")))
406 (tramp-async-args (("-q")))
407 (tramp-remote-sh "/bin/sh")
408 (tramp-copy-program "sftp")
409 (tramp-copy-args nil)
410 (tramp-copy-keep-date nil)
411 (tramp-password-end-of-line nil))
412 ("rsync" (tramp-login-program "ssh")
413 (tramp-login-args (("-l" "%u") ("-p" "%p")
414 ("-e" "none") ("%h")))
415 (tramp-async-args (("-q")))
416 (tramp-remote-sh "/bin/sh")
417 (tramp-copy-program "rsync")
418 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
419 (tramp-copy-keep-date t)
420 (tramp-copy-keep-tmpfile t)
421 (tramp-copy-recursive t)
422 (tramp-password-end-of-line nil))
424 (tramp-login-program "ssh")
425 (tramp-login-args (("-l" "%u") ("-p" "%p")
426 ("-o" "ControlPath=%t.%%r@%%h:%%p")
427 ("-o" "ControlMaster=yes")
428 ("-e" "none") ("%h")))
429 (tramp-async-args (("-q")))
430 (tramp-remote-sh "/bin/sh")
431 (tramp-copy-program "rsync")
432 (tramp-copy-args (("-t" "%k") ("-r")))
433 (tramp-copy-env (("RSYNC_RSH")
436 " -o ControlPath=%t.%%r@%%h:%%p"
437 " -o ControlMaster=auto"))))
438 (tramp-copy-keep-date t)
439 (tramp-copy-keep-tmpfile t)
440 (tramp-copy-recursive t)
441 (tramp-password-end-of-line nil))
442 ("remcp" (tramp-login-program "remsh")
443 (tramp-login-args (("%h") ("-l" "%u")))
444 (tramp-remote-sh "/bin/sh")
445 (tramp-copy-program "rcp")
446 (tramp-copy-args (("-p" "%k")))
447 (tramp-copy-keep-date t)
448 (tramp-password-end-of-line nil))
449 ("rsh" (tramp-login-program "rsh")
450 (tramp-login-args (("%h") ("-l" "%u")))
451 (tramp-remote-sh "/bin/sh")
452 (tramp-copy-program nil)
453 (tramp-copy-args nil)
454 (tramp-copy-keep-date nil)
455 (tramp-password-end-of-line nil))
456 ("ssh" (tramp-login-program "ssh")
457 (tramp-login-args (("-l" "%u") ("-p" "%p")
458 ("-e" "none") ("%h")))
459 (tramp-async-args (("-q")))
460 (tramp-remote-sh "/bin/sh")
461 (tramp-copy-program nil)
462 (tramp-copy-args nil)
463 (tramp-copy-keep-date nil)
464 (tramp-password-end-of-line nil)
465 (tramp-gw-args (("-o"
466 "GlobalKnownHostsFile=/dev/null")
467 ("-o" "UserKnownHostsFile=/dev/null")
468 ("-o" "StrictHostKeyChecking=no")))
469 (tramp-default-port 22))
470 ("ssh1" (tramp-login-program "ssh")
471 (tramp-login-args (("-l" "%u") ("-p" "%p")
472 ("-1") ("-e" "none") ("%h")))
473 (tramp-async-args (("-q")))
474 (tramp-remote-sh "/bin/sh")
475 (tramp-copy-program nil)
476 (tramp-copy-args nil)
477 (tramp-copy-keep-date nil)
478 (tramp-password-end-of-line nil)
479 (tramp-gw-args (("-o"
480 "GlobalKnownHostsFile=/dev/null")
481 ("-o" "UserKnownHostsFile=/dev/null")
482 ("-o" "StrictHostKeyChecking=no")))
483 (tramp-default-port 22))
484 ("ssh2" (tramp-login-program "ssh")
485 (tramp-login-args (("-l" "%u") ("-p" "%p")
486 ("-2") ("-e" "none") ("%h")))
487 (tramp-async-args (("-q")))
488 (tramp-remote-sh "/bin/sh")
489 (tramp-copy-program nil)
490 (tramp-copy-args nil)
491 (tramp-copy-keep-date nil)
492 (tramp-password-end-of-line nil)
493 (tramp-gw-args (("-o"
494 "GlobalKnownHostsFile=/dev/null")
495 ("-o" "UserKnownHostsFile=/dev/null")
496 ("-o" "StrictHostKeyChecking=no")))
497 (tramp-default-port 22))
499 (tramp-login-program "ssh1")
500 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
502 (tramp-async-args (("-q")))
503 (tramp-remote-sh "/bin/sh")
504 (tramp-copy-program nil)
505 (tramp-copy-args nil)
506 (tramp-copy-keep-date nil)
507 (tramp-password-end-of-line nil))
509 (tramp-login-program "ssh2")
510 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
512 (tramp-remote-sh "/bin/sh")
513 (tramp-copy-program nil)
514 (tramp-copy-args nil)
515 (tramp-copy-keep-date nil)
516 (tramp-password-end-of-line nil))
517 ("remsh" (tramp-login-program "remsh")
518 (tramp-login-args (("%h") ("-l" "%u")))
519 (tramp-remote-sh "/bin/sh")
520 (tramp-copy-program nil)
521 (tramp-copy-args nil)
522 (tramp-copy-keep-date nil)
523 (tramp-password-end-of-line nil))
525 (tramp-login-program "telnet")
526 (tramp-login-args (("%h") ("%p")))
527 (tramp-remote-sh "/bin/sh")
528 (tramp-copy-program nil)
529 (tramp-copy-args nil)
530 (tramp-copy-keep-date nil)
531 (tramp-password-end-of-line nil)
532 (tramp-default-port 23))
533 ("su" (tramp-login-program "su")
534 (tramp-login-args (("-") ("%u")))
535 (tramp-remote-sh "/bin/sh")
536 (tramp-copy-program nil)
537 (tramp-copy-args nil)
538 (tramp-copy-keep-date nil)
539 (tramp-password-end-of-line nil))
540 ("sudo" (tramp-login-program "sudo")
541 (tramp-login-args (("-u" "%u")
542 ("-s") ("-H") ("-p" "Password:")))
543 (tramp-remote-sh "/bin/sh")
544 (tramp-copy-program nil)
545 (tramp-copy-args nil)
546 (tramp-copy-keep-date nil)
547 (tramp-password-end-of-line nil))
548 ("scpc" (tramp-login-program "ssh")
549 (tramp-login-args (("-l" "%u") ("-p" "%p")
550 ("-o" "ControlPath=%t.%%r@%%h:%%p")
551 ("-o" "ControlMaster=yes")
552 ("-e" "none") ("%h")))
553 (tramp-async-args (("-q")))
554 (tramp-remote-sh "/bin/sh")
555 (tramp-copy-program "scp")
556 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
557 ("-o" "ControlPath=%t.%%r@%%h:%%p")
558 ("-o" "ControlMaster=auto")))
559 (tramp-copy-keep-date t)
560 (tramp-password-end-of-line nil)
561 (tramp-gw-args (("-o"
562 "GlobalKnownHostsFile=/dev/null")
563 ("-o" "UserKnownHostsFile=/dev/null")
564 ("-o" "StrictHostKeyChecking=no")))
565 (tramp-default-port 22))
566 ("scpx" (tramp-login-program "ssh")
567 (tramp-login-args (("-l" "%u") ("-p" "%p")
568 ("-e" "none") ("-t" "-t")
570 (tramp-async-args (("-q")))
571 (tramp-remote-sh "/bin/sh")
572 (tramp-copy-program "scp")
573 (tramp-copy-args (("-p" "%k")))
574 (tramp-copy-keep-date t)
575 (tramp-password-end-of-line nil)
576 (tramp-gw-args (("-o"
577 "GlobalKnownHostsFile=/dev/null")
578 ("-o" "UserKnownHostsFile=/dev/null")
579 ("-o" "StrictHostKeyChecking=no")))
580 (tramp-default-port 22))
581 ("sshx" (tramp-login-program "ssh")
582 (tramp-login-args (("-l" "%u") ("-p" "%p")
583 ("-e" "none") ("-t" "-t")
585 (tramp-async-args (("-q")))
586 (tramp-remote-sh "/bin/sh")
587 (tramp-copy-program nil)
588 (tramp-copy-args nil)
589 (tramp-copy-keep-date nil)
590 (tramp-password-end-of-line nil)
591 (tramp-gw-args (("-o"
592 "GlobalKnownHostsFile=/dev/null")
593 ("-o" "UserKnownHostsFile=/dev/null")
594 ("-o" "StrictHostKeyChecking=no")))
595 (tramp-default-port 22))
597 (tramp-login-program "krlogin")
598 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
599 (tramp-remote-sh "/bin/sh")
600 (tramp-copy-program nil)
601 (tramp-copy-args nil)
602 (tramp-copy-keep-date nil)
603 (tramp-password-end-of-line nil))
604 ("plink" (tramp-login-program "plink")
605 (tramp-login-args (("-l" "%u") ("-P" "%p")
607 (tramp-remote-sh "/bin/sh")
608 (tramp-copy-program nil)
609 (tramp-copy-args nil)
610 (tramp-copy-keep-date nil)
611 (tramp-password-end-of-line "xy") ;see docstring for "xy"
612 (tramp-default-port 22))
614 (tramp-login-program "plink")
615 (tramp-login-args (("-l" "%u") ("-P" "%p")
616 ("-1" "-ssh") ("%h")))
617 (tramp-remote-sh "/bin/sh")
618 (tramp-copy-program nil)
619 (tramp-copy-args nil)
620 (tramp-copy-keep-date nil)
621 (tramp-password-end-of-line "xy") ;see docstring for "xy"
622 (tramp-default-port 22))
624 (tramp-login-program "plink")
625 ;; ("%h") must be a single element, see
626 ;; `tramp-compute-multi-hops'.
627 (tramp-login-args (("-load") ("%h") ("-t")
629 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
631 tramp-initial-end-of-output))
633 (tramp-remote-sh "/bin/sh")
634 (tramp-copy-program nil)
635 (tramp-copy-args nil)
636 (tramp-copy-keep-date nil)
637 (tramp-password-end-of-line nil))
638 ("pscp" (tramp-login-program "plink")
639 (tramp-login-args (("-l" "%u") ("-P" "%p")
641 (tramp-remote-sh "/bin/sh")
642 (tramp-copy-program "pscp")
643 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
644 (tramp-copy-keep-date t)
645 (tramp-password-end-of-line "xy") ;see docstring for "xy"
646 (tramp-default-port 22))
647 ("psftp" (tramp-login-program "plink")
648 (tramp-login-args (("-l" "%u") ("-P" "%p")
650 (tramp-remote-sh "/bin/sh")
651 (tramp-copy-program "pscp")
652 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
653 (tramp-copy-keep-date t)
654 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
655 ("fcp" (tramp-login-program "fsh")
656 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
657 (tramp-remote-sh "/bin/sh -i")
658 (tramp-copy-program "fcp")
659 (tramp-copy-args (("-p" "%k")))
660 (tramp-copy-keep-date t)
661 (tramp-password-end-of-line nil)))
662 "*Alist of methods for remote files.
663 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
664 Each NAME stands for a remote access method. Each PARAM is a
665 pair of the form (KEY VALUE). The following KEYs are defined:
667 This specifies the Bourne shell to use on the remote host. This
668 MUST be a Bourne-like shell. It is normally not necessary to set
669 this to any value other than \"/bin/sh\": Tramp wants to use a shell
670 which groks tilde expansion, but it can search for it. Also note
671 that \"/bin/sh\" exists on all Unixen, this might not be true for
672 the value that you decide to use. You Have Been Warned.
673 * `tramp-login-program'
674 This specifies the name of the program to use for logging in to the
675 remote host. This may be the name of rsh or a workalike program,
676 or the name of telnet or a workalike, or the name of su or a workalike.
678 This specifies the list of arguments to pass to the above
679 mentioned program. Please note that this is a list of list of arguments,
680 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
681 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
682 There are some patterns: \"%h\" in this list is replaced by the host
683 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
684 port number, and \"%%\" can be used to obtain a literal percent character.
685 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
686 expansion (i.e. no host or no user specified), this list is not used as
687 argument. By this, arguments like (\"-l\" \"%u\") are optional.
688 \"%t\" is replaced by the temporary file name produced with
689 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
690 parameter of a program, if exists.
692 When an asynchronous process is started, we know already that
693 the connection works. Therefore, we can pass additional
694 parameters to suppress diagnostic messages, in order not to
695 tamper the process output.
696 * `tramp-copy-program'
697 This specifies the name of the program to use for remotely copying
698 the file; this might be the absolute filename of rcp or the name of
701 This specifies the list of parameters to pass to the above mentioned
702 program, the hints for `tramp-login-args' also apply here.
703 * `tramp-copy-keep-date'
704 This specifies whether the copying program when the preserves the
705 timestamp of the original file.
706 * `tramp-copy-keep-tmpfile'
707 This specifies whether a temporary local file shall be kept
708 for optimization reasons (useful for \"rsync\" methods).
709 * `tramp-copy-recursive'
710 Whether the operation copies directories recursively.
711 * `tramp-default-port'
712 The default port of a method is needed in case of gateway connections.
713 Additionally, it is used as indication which method is prepared for
716 As the attribute name says, additional arguments are specified here
717 when a method is applied via a gateway.
718 * `tramp-password-end-of-line'
719 This specifies the string to use for terminating the line after
720 submitting the password. If this method parameter is nil, then the
721 value of the normal variable `tramp-default-password-end-of-line'
722 is used. This parameter is necessary because the \"plink\" program
723 requires any two characters after sending the password. These do
724 not have to be newline or carriage return characters. Other login
725 programs are happy with just one character, the newline character.
726 We use \"xy\" as the value for methods using \"plink\".
728 What does all this mean? Well, you should specify `tramp-login-program'
729 for all methods; this program is used to log in to the remote site. Then,
730 there are two ways to actually transfer the files between the local and the
731 remote side. One way is using an additional rcp-like program. If you want
732 to do this, set `tramp-copy-program' in the method.
734 Another possibility for file transfer is inline transfer, i.e. the
735 file is passed through the same buffer used by `tramp-login-program'. In
736 this case, the file contents need to be protected since the
737 `tramp-login-program' might use escape codes or the connection might not
738 be eight-bit clean. Therefore, file contents are encoded for transit.
739 See the variables `tramp-local-coding-commands' and
740 `tramp-remote-coding-commands' for details.
742 So, to summarize: if the method is an out-of-band method, then you
743 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
744 inline method, then these two parameters should be nil. Methods which
745 are fit for gateways must have `tramp-default-port' at least.
749 When using `su' or `sudo' the phrase `open connection to a remote
750 host' sounds strange, but it is used nevertheless, for consistency.
751 No connection is opened to a remote host, but `su' or `sudo' is
752 started on the local host. You should specify a remote host
753 `localhost' or the name of the local host. Another host name is
754 useful only in combination with `tramp-default-proxies-alist'.")
756 (defun tramp-detect-ssh-controlmaster ()
757 "Call ssh to detect whether it supports the ControlMaster argument.
758 This function may return nil when the argument is supported, but
759 shouldn't return t when it isn't."
762 (call-process "ssh" nil t nil "-o" "ControlMaster")
763 (goto-char (point-min))
764 (search-forward-regexp "Missing ControlMaster argument" nil t))))
766 (defcustom tramp-default-method
767 ;; An external copy method seems to be preferred, because it is much
768 ;; more performant for large files, and it hasn't too serious delays
769 ;; for small files. But it must be ensured that there aren't
770 ;; permanent password queries. Either a password agent like
771 ;; "ssh-agent" or "Pageant" shall run, or the optional
772 ;; password-cache.el or auth-sources.el packages shall be active for
773 ;; password caching. "scpc" is chosen if we detect that the user is
774 ;; running OpenSSH 4.0 or newer.
776 ;; PuTTY is installed.
777 ((executable-find "pscp")
778 (if (or (fboundp 'password-read)
779 (fboundp 'auth-source-user-or-password)
780 ;; Pageant is running.
781 (tramp-compat-process-running-p "Pageant"))
784 ;; There is an ssh installation.
785 ((executable-find "scp")
787 ((tramp-detect-ssh-controlmaster) "scpc")
788 ((or (fboundp 'password-read)
789 (fboundp 'auth-source-user-or-password)
790 ;; ssh-agent is running.
791 (getenv "SSH_AUTH_SOCK")
792 (getenv "SSH_AGENT_PID"))
797 "*Default method to use for transferring files.
798 See `tramp-methods' for possibilities.
799 Also see `tramp-default-method-alist'."
803 (defcustom tramp-default-method-alist
804 '(("\\`localhost\\'" "\\`root\\'" "su"))
805 "*Default method to use for specific host/user pairs.
806 This is an alist of items (HOST USER METHOD). The first matching item
807 specifies the method to use for a file name which does not specify a
808 method. HOST and USER are regular expressions or nil, which is
809 interpreted as a regular expression which always matches. If no entry
810 matches, the variable `tramp-default-method' takes effect.
812 If the file name does not specify the user, lookup is done using the
813 empty string for the user name.
815 See `tramp-methods' for a list of possibilities for METHOD."
817 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
818 (choice :tag "User regexp" regexp sexp)
819 (choice :tag "Method name" string (const nil)))))
821 (defcustom tramp-default-user
823 "*Default user to use for transferring files.
824 It is nil by default; otherwise settings in configuration files like
825 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
827 This variable is regarded as obsolete, and will be removed soon."
829 :type '(choice (const nil) string))
831 (defcustom tramp-default-user-alist
832 `(("\\`su\\(do\\)?\\'" nil "root")
833 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
834 nil ,(user-login-name)))
835 "*Default user to use for specific method/host pairs.
836 This is an alist of items (METHOD HOST USER). The first matching item
837 specifies the user to use for a file name which does not specify a
838 user. METHOD and USER are regular expressions or nil, which is
839 interpreted as a regular expression which always matches. If no entry
840 matches, the variable `tramp-default-user' takes effect.
842 If the file name does not specify the method, lookup is done using the
843 empty string for the method name."
845 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
846 (choice :tag " Host regexp" regexp sexp)
847 (choice :tag " User name" string (const nil)))))
849 (defcustom tramp-default-host
851 "*Default host to use for transferring files.
852 Useful for su and sudo methods mostly."
856 (defcustom tramp-default-proxies-alist nil
857 "*Route to be followed for specific host/user pairs.
858 This is an alist of items (HOST USER PROXY). The first matching
859 item specifies the proxy to be passed for a file name located on
860 a remote target matching USER@HOST. HOST and USER are regular
861 expressions. PROXY must be a Tramp filename without a localname
862 part. Method and user name on PROXY are optional, which is
863 interpreted with the default values. PROXY can contain the
864 patterns %h and %u, which are replaced by the strings matching
865 HOST or USER, respectively.
867 HOST, USER or PROXY could also be Lisp forms, which will be
868 evaluated. The result must be a string or nil, which is
869 interpreted as a regular expression which always matches."
871 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
872 (choice :tag "User regexp" regexp sexp)
873 (choice :tag " Proxy name" string (const nil)))))
875 (defconst tramp-local-host-regexp
877 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
878 "*Host names which are regarded as local host.")
880 (defconst tramp-completion-function-alist-rsh
881 '((tramp-parse-rhosts "/etc/hosts.equiv")
882 (tramp-parse-rhosts "~/.rhosts"))
883 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
885 (defconst tramp-completion-function-alist-ssh
886 '((tramp-parse-rhosts "/etc/hosts.equiv")
887 (tramp-parse-rhosts "/etc/shosts.equiv")
888 (tramp-parse-shosts "/etc/ssh_known_hosts")
889 (tramp-parse-sconfig "/etc/ssh_config")
890 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
891 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
892 (tramp-parse-rhosts "~/.rhosts")
893 (tramp-parse-rhosts "~/.shosts")
894 (tramp-parse-shosts "~/.ssh/known_hosts")
895 (tramp-parse-sconfig "~/.ssh/config")
896 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
897 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
898 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
900 (defconst tramp-completion-function-alist-telnet
901 '((tramp-parse-hosts "/etc/hosts"))
902 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
904 (defconst tramp-completion-function-alist-su
905 '((tramp-parse-passwd "/etc/passwd"))
906 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
908 (defconst tramp-completion-function-alist-putty
910 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
911 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
913 (defvar tramp-completion-function-alist nil
914 "*Alist of methods for remote files.
915 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
916 Each NAME stands for a remote access method. Each PAIR is of the form
917 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
918 names from FILE for completion. The following predefined FUNCTIONs exists:
920 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
921 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
922 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
923 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
924 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
925 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
926 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
927 * `tramp-parse-netrc' for \"~/.netrc\" like files.
928 * `tramp-parse-putty' for PuTTY registry keys.
930 FUNCTION can also be a customer defined function. For more details see
933 (eval-after-load "tramp"
935 (tramp-set-completion-function
936 "rcp" tramp-completion-function-alist-rsh)
937 (tramp-set-completion-function
938 "scp" tramp-completion-function-alist-ssh)
939 (tramp-set-completion-function
940 "scp1" tramp-completion-function-alist-ssh)
941 (tramp-set-completion-function
942 "scp2" tramp-completion-function-alist-ssh)
943 (tramp-set-completion-function
944 "scp1_old" tramp-completion-function-alist-ssh)
945 (tramp-set-completion-function
946 "scp2_old" tramp-completion-function-alist-ssh)
947 (tramp-set-completion-function
948 "rsync" tramp-completion-function-alist-ssh)
949 (tramp-set-completion-function
950 "rsyncc" tramp-completion-function-alist-ssh)
951 (tramp-set-completion-function
952 "remcp" tramp-completion-function-alist-rsh)
953 (tramp-set-completion-function
954 "rsh" tramp-completion-function-alist-rsh)
955 (tramp-set-completion-function
956 "ssh" tramp-completion-function-alist-ssh)
957 (tramp-set-completion-function
958 "ssh1" tramp-completion-function-alist-ssh)
959 (tramp-set-completion-function
960 "ssh2" tramp-completion-function-alist-ssh)
961 (tramp-set-completion-function
962 "ssh1_old" tramp-completion-function-alist-ssh)
963 (tramp-set-completion-function
964 "ssh2_old" tramp-completion-function-alist-ssh)
965 (tramp-set-completion-function
966 "remsh" tramp-completion-function-alist-rsh)
967 (tramp-set-completion-function
968 "telnet" tramp-completion-function-alist-telnet)
969 (tramp-set-completion-function
970 "su" tramp-completion-function-alist-su)
971 (tramp-set-completion-function
972 "sudo" tramp-completion-function-alist-su)
973 (tramp-set-completion-function
974 "scpx" tramp-completion-function-alist-ssh)
975 (tramp-set-completion-function
976 "sshx" tramp-completion-function-alist-ssh)
977 (tramp-set-completion-function
978 "krlogin" tramp-completion-function-alist-rsh)
979 (tramp-set-completion-function
980 "plink" tramp-completion-function-alist-ssh)
981 (tramp-set-completion-function
982 "plink1" tramp-completion-function-alist-ssh)
983 (tramp-set-completion-function
984 "plinkx" tramp-completion-function-alist-putty)
985 (tramp-set-completion-function
986 "pscp" tramp-completion-function-alist-ssh)
987 (tramp-set-completion-function
988 "fcp" tramp-completion-function-alist-ssh)))
990 (defconst tramp-echo-mark-marker "_echo"
991 "String marker to surround echoed commands.")
993 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
994 "String length of `tramp-echo-mark-marker'.")
996 (defconst tramp-echo-mark
997 (concat tramp-echo-mark-marker
998 (make-string tramp-echo-mark-marker-length ?\b))
999 "String mark to be transmitted around shell commands.
1000 Used to separate their echo from the output they produce. This
1001 will only be used if we cannot disable remote echo via stty.
1002 This string must have no effect on the remote shell except for
1003 producing some echo which can later be detected by
1004 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
1005 followed by an equal number of backspaces to erase them will
1008 (defconst tramp-echoed-echo-mark-regexp
1009 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
1010 tramp-echo-mark-marker tramp-echo-mark-marker-length)
1011 "Regexp which matches `tramp-echo-mark' as it gets echoed by
1014 (defcustom tramp-rsh-end-of-line "\n"
1015 "*String used for end of line in rsh connections.
1016 I don't think this ever needs to be changed, so please tell me about it
1017 if you need to change this.
1018 Also see the method parameter `tramp-password-end-of-line' and the normal
1019 variable `tramp-default-password-end-of-line'."
1023 (defcustom tramp-default-password-end-of-line
1024 tramp-rsh-end-of-line
1025 "*String used for end of line after sending a password.
1026 This variable provides the default value for the method parameter
1027 `tramp-password-end-of-line', see `tramp-methods' for more details.
1029 It seems that people using plink under Windows need to send
1030 \"\\r\\n\" (carriage-return, then newline) after a password, but just
1031 \"\\n\" after all other lines. This variable can be used for the
1032 password, see `tramp-rsh-end-of-line' for the other cases.
1034 The default value is to use the same value as `tramp-rsh-end-of-line'."
1038 ;; "getconf PATH" yields:
1039 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
1040 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
1041 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1042 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1044 (defcustom tramp-remote-path
1045 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1046 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1047 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1048 "*List of directories to search for executables on remote host.
1049 For every remote host, this variable will be set buffer local,
1050 keeping the list of existing directories on that host.
1052 You can use `~' in this list, but when searching for a shell which groks
1053 tilde expansion, all directory names starting with `~' will be ignored.
1055 `Default Directories' represent the list of directories given by
1056 the command \"getconf PATH\". It is recommended to use this
1057 entry on top of this list, because these are the default
1058 directories for POSIX compatible commands.
1060 `Private Directories' are the settings of the $PATH environment,
1061 as given in your `~/.profile'."
1063 :type '(repeat (choice
1064 (const :tag "Default Directories" tramp-default-remote-path)
1065 (const :tag "Private Directories" tramp-own-remote-path)
1066 (string :tag "Directory"))))
1068 (defcustom tramp-remote-process-environment
1069 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1070 ,(format "TERM=%s" tramp-terminal-type)
1071 "EMACS=t" ;; Deprecated.
1072 ,(format "INSIDE_EMACS='%s,tramp:%s'" emacs-version tramp-version)
1073 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1074 "autocorrect=" "correct=")
1076 "*List of environment variables to be set on the remote host.
1078 Each element should be a string of the form ENVVARNAME=VALUE. An
1079 entry ENVVARNAME= diables the corresponding environment variable,
1080 which might have been set in the init files like ~/.profile.
1082 Special handling is applied to the PATH environment, which should
1083 not be set here. Instead of, it should be set via `tramp-remote-path'."
1085 :type '(repeat string))
1087 (defcustom tramp-login-prompt-regexp
1088 ".*ogin\\( .*\\)?: *"
1089 "*Regexp matching login-like prompts.
1090 The regexp should match at end of buffer.
1092 Sometimes the prompt is reported to look like \"login as:\"."
1096 (defcustom tramp-shell-prompt-pattern
1097 ;; Allow a prompt to start right after a ^M since it indeed would be
1098 ;; displayed at the beginning of the line (and Zsh uses it). This
1099 ;; regexp works only for GNU Emacs.
1100 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
1101 "[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
1102 "Regexp to match prompts from remote shell.
1103 Normally, Tramp expects you to configure `shell-prompt-pattern'
1104 correctly, but sometimes it happens that you are connecting to a
1105 remote host which sends a different kind of shell prompt. Therefore,
1106 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1107 and also things matched by this variable. The default value of this
1108 variable is similar to the default value of `shell-prompt-pattern',
1109 which should work well in many cases.
1111 This regexp must match both `tramp-initial-end-of-output' and
1112 `tramp-end-of-output'."
1116 (defcustom tramp-password-prompt-regexp
1117 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1118 "*Regexp matching password-like prompts.
1119 The regexp should match at end of buffer.
1121 The `sudo' program appears to insert a `^@' character into the prompt."
1125 (defcustom tramp-wrong-passwd-regexp
1127 ;; These strings should be on the last line
1128 (regexp-opt '("Permission denied"
1131 "Connection refused"
1133 "Timeout, server not responding."
1135 "Name or service not known"
1136 "Host key verification failed."
1137 "No supported authentication methods left to try!") t)
1141 ;; Here comes a list of regexes, separated by \\|
1142 "Received signal [0-9]+"
1144 "*Regexp matching a `login failed' message.
1145 The regexp should match at end of buffer."
1149 (defcustom tramp-yesno-prompt-regexp
1151 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1153 "Regular expression matching all yes/no queries which need to be confirmed.
1154 The confirmation should be done with yes or no.
1155 The regexp should match at end of buffer.
1156 See also `tramp-yn-prompt-regexp'."
1160 (defcustom tramp-yn-prompt-regexp
1162 (regexp-opt '("Store key in cache? (y/n)"
1163 "Update cached key? (y/n, Return cancels connection)") t)
1165 "Regular expression matching all y/n queries which need to be confirmed.
1166 The confirmation should be done with y or n.
1167 The regexp should match at end of buffer.
1168 See also `tramp-yesno-prompt-regexp'."
1172 (defcustom tramp-terminal-prompt-regexp
1176 "Terminal type\\? \\[.*\\]"
1178 "Regular expression matching all terminal setting prompts.
1179 The regexp should match at end of buffer.
1180 The answer will be provided by `tramp-action-terminal', which see."
1184 (defcustom tramp-operation-not-permitted-regexp
1185 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1186 (regexp-opt '("Operation not permitted") t))
1187 "Regular expression matching keep-date problems in (s)cp operations.
1188 Copying has been performed successfully already, so this message can
1193 (defcustom tramp-copy-failed-regexp
1195 (regexp-opt '("Permission denied"
1196 "not a regular file"
1198 "No such file or directory") t)
1200 "Regular expression matching copy problems in (s)cp operations."
1204 (defcustom tramp-process-alive-regexp
1206 "Regular expression indicating a process has finished.
1207 In fact this expression is empty by intention, it will be used only to
1208 check regularly the status of the associated process.
1209 The answer will be provided by `tramp-action-process-alive',
1210 `tramp-action-out-of-band', which see."
1214 (defcustom tramp-temp-name-prefix "tramp."
1215 "*Prefix to use for temporary files.
1216 If this is a relative file name (such as \"tramp.\"), it is considered
1217 relative to the directory name returned by the function
1218 `tramp-compat-temporary-file-directory' (which see). It may also be an
1219 absolute file name; don't forget to include a prefix for the filename
1224 (defconst tramp-temp-buffer-name " *tramp temp*"
1225 "Buffer name for a temporary buffer.
1226 It shall be used in combination with `generate-new-buffer-name'.")
1228 (defvar tramp-temp-buffer-file-name nil
1229 "File name of a persistent local temporary file.
1230 Useful for \"rsync\" like methods.")
1231 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1233 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1234 "*Alist specifying extra arguments to pass to the remote shell.
1235 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1236 matching the shell file name and ARGS is a string specifying the
1239 This variable is only used when Tramp needs to start up another shell
1240 for tilde expansion. The extra arguments should typically prevent the
1241 shell from reading its init file."
1243 ;; This might be the wrong way to test whether the widget type
1244 ;; `alist' is available. Who knows the right way to test it?
1245 :type (if (get 'alist 'widget-type)
1246 '(alist :key-type string :value-type string)
1247 '(repeat (cons string string))))
1249 ;; XEmacs is distributed with few Lisp packages. Further packages are
1250 ;; installed using EFS. If we use a unified filename format, then
1251 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1252 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1253 ;; just like before.) Another reason for using a separate filename
1254 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1255 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1256 ;; the other places.
1258 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1260 (defcustom tramp-syntax
1261 (if (featurep 'xemacs) 'sep 'ftp)
1262 "Tramp filename syntax to be used.
1264 It can have the following values:
1266 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1267 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1268 'url -- URL-like syntax."
1270 :type (if (featurep 'xemacs)
1271 '(choice (const :tag "EFS" ftp)
1272 (const :tag "XEmacs" sep)
1273 (const :tag "URL" url))
1274 '(choice (const :tag "Ange-FTP" ftp)
1275 (const :tag "URL" url))))
1277 (defconst tramp-prefix-format
1278 (cond ((equal tramp-syntax 'ftp) "/")
1279 ((equal tramp-syntax 'sep) "/[")
1280 ((equal tramp-syntax 'url) "/")
1281 (t (error "Wrong `tramp-syntax' defined")))
1282 "*String matching the very beginning of Tramp file names.
1283 Used in `tramp-make-tramp-file-name'.")
1285 (defconst tramp-prefix-regexp
1286 (concat "^" (regexp-quote tramp-prefix-format))
1287 "*Regexp matching the very beginning of Tramp file names.
1288 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1290 (defconst tramp-method-regexp
1292 "*Regexp matching methods identifiers.")
1294 (defconst tramp-postfix-method-format
1295 (cond ((equal tramp-syntax 'ftp) ":")
1296 ((equal tramp-syntax 'sep) "/")
1297 ((equal tramp-syntax 'url) "://")
1298 (t (error "Wrong `tramp-syntax' defined")))
1299 "*String matching delimeter between method and user or host names.
1300 Used in `tramp-make-tramp-file-name'.")
1302 (defconst tramp-postfix-method-regexp
1303 (regexp-quote tramp-postfix-method-format)
1304 "*Regexp matching delimeter between method and user or host names.
1305 Derived from `tramp-postfix-method-format'.")
1307 (defconst tramp-user-regexp
1309 "*Regexp matching user names.")
1311 (defconst tramp-prefix-domain-format "%"
1312 "*String matching delimeter between user and domain names.")
1314 (defconst tramp-prefix-domain-regexp
1315 (regexp-quote tramp-prefix-domain-format)
1316 "*Regexp matching delimeter between user and domain names.
1317 Derived from `tramp-prefix-domain-format'.")
1319 (defconst tramp-domain-regexp
1321 "*Regexp matching domain names.")
1323 (defconst tramp-user-with-domain-regexp
1324 (concat "\\(" tramp-user-regexp "\\)"
1325 tramp-prefix-domain-regexp
1326 "\\(" tramp-domain-regexp "\\)")
1327 "*Regexp matching user names with domain names.")
1329 (defconst tramp-postfix-user-format
1331 "*String matching delimeter between user and host names.
1332 Used in `tramp-make-tramp-file-name'.")
1334 (defconst tramp-postfix-user-regexp
1335 (regexp-quote tramp-postfix-user-format)
1336 "*Regexp matching delimeter between user and host names.
1337 Derived from `tramp-postfix-user-format'.")
1339 (defconst tramp-host-regexp
1341 "*Regexp matching host names.")
1343 (defconst tramp-prefix-ipv6-format
1344 (cond ((equal tramp-syntax 'ftp) "[")
1345 ((equal tramp-syntax 'sep) "")
1346 ((equal tramp-syntax 'url) "[")
1347 (t (error "Wrong `tramp-syntax' defined")))
1348 "*String matching left hand side of IPv6 addresses.
1349 Used in `tramp-make-tramp-file-name'.")
1351 (defconst tramp-prefix-ipv6-regexp
1352 (regexp-quote tramp-prefix-ipv6-format)
1353 "*Regexp matching left hand side of IPv6 addresses.
1354 Derived from `tramp-prefix-ipv6-format'.")
1356 ;; The following regexp is a bit sloppy. But it shall serve our
1357 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1358 ;; "::ffff:192.168.0.1".
1359 (defconst tramp-ipv6-regexp
1360 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1361 "*Regexp matching IPv6 addresses.")
1363 (defconst tramp-postfix-ipv6-format
1364 (cond ((equal tramp-syntax 'ftp) "]")
1365 ((equal tramp-syntax 'sep) "")
1366 ((equal tramp-syntax 'url) "]")
1367 (t (error "Wrong `tramp-syntax' defined")))
1368 "*String matching right hand side of IPv6 addresses.
1369 Used in `tramp-make-tramp-file-name'.")
1371 (defconst tramp-postfix-ipv6-regexp
1372 (regexp-quote tramp-postfix-ipv6-format)
1373 "*Regexp matching right hand side of IPv6 addresses.
1374 Derived from `tramp-postfix-ipv6-format'.")
1376 (defconst tramp-prefix-port-format
1377 (cond ((equal tramp-syntax 'ftp) "#")
1378 ((equal tramp-syntax 'sep) "#")
1379 ((equal tramp-syntax 'url) ":")
1380 (t (error "Wrong `tramp-syntax' defined")))
1381 "*String matching delimeter between host names and port numbers.")
1383 (defconst tramp-prefix-port-regexp
1384 (regexp-quote tramp-prefix-port-format)
1385 "*Regexp matching delimeter between host names and port numbers.
1386 Derived from `tramp-prefix-port-format'.")
1388 (defconst tramp-port-regexp
1390 "*Regexp matching port numbers.")
1392 (defconst tramp-host-with-port-regexp
1393 (concat "\\(" tramp-host-regexp "\\)"
1394 tramp-prefix-port-regexp
1395 "\\(" tramp-port-regexp "\\)")
1396 "*Regexp matching host names with port numbers.")
1398 (defconst tramp-postfix-host-format
1399 (cond ((equal tramp-syntax 'ftp) ":")
1400 ((equal tramp-syntax 'sep) "]")
1401 ((equal tramp-syntax 'url) "")
1402 (t (error "Wrong `tramp-syntax' defined")))
1403 "*String matching delimeter between host names and localnames.
1404 Used in `tramp-make-tramp-file-name'.")
1406 (defconst tramp-postfix-host-regexp
1407 (regexp-quote tramp-postfix-host-format)
1408 "*Regexp matching delimeter between host names and localnames.
1409 Derived from `tramp-postfix-host-format'.")
1411 (defconst tramp-localname-regexp
1413 "*Regexp matching localnames.")
1415 ;; File name format.
1417 (defconst tramp-file-name-structure
1421 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1422 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1423 "\\(" "\\(" tramp-host-regexp
1425 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1426 tramp-postfix-ipv6-regexp "\\)"
1427 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1428 tramp-postfix-host-regexp
1429 "\\(" tramp-localname-regexp "\\)")
1432 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1433 the Tramp file name structure.
1435 The first element REGEXP is a regular expression matching a Tramp file
1436 name. The regex should contain parentheses around the method name,
1437 the user name, the host name, and the file name parts.
1439 The second element METHOD is a number, saying which pair of
1440 parentheses matches the method name. The third element USER is
1441 similar, but for the user name. The fourth element HOST is similar,
1442 but for the host name. The fifth element FILE is for the file name.
1443 These numbers are passed directly to `match-string', which see. That
1444 means the opening parentheses are counted to identify the pair.
1446 See also `tramp-file-name-regexp'.")
1449 (defconst tramp-file-name-regexp-unified
1450 (if (memq system-type '(cygwin windows-nt))
1451 "\\`/\\([^[/:]\\{2,\\}\\|[^/]\\{2,\\}]\\):"
1452 "\\`/\\([^[/:]+\\|[^/]+]\\):")
1453 "Value for `tramp-file-name-regexp' for unified remoting.
1454 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1455 Tramp. See `tramp-file-name-structure' for more explanations.
1457 On W32 systems, the volume letter must be ignored.")
1460 (defconst tramp-file-name-regexp-separate
1462 "Value for `tramp-file-name-regexp' for separate remoting.
1463 XEmacs uses a separate filename syntax for Tramp and EFS.
1464 See `tramp-file-name-structure' for more explanations.")
1467 (defconst tramp-file-name-regexp-url
1469 "Value for `tramp-file-name-regexp' for URL-like remoting.
1470 See `tramp-file-name-structure' for more explanations.")
1473 (defconst tramp-file-name-regexp
1474 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1475 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1476 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1477 (t (error "Wrong `tramp-syntax' defined")))
1478 "*Regular expression matching file names handled by Tramp.
1479 This regexp should match Tramp file names but no other file names.
1480 When tramp.el is loaded, this regular expression is prepended to
1481 `file-name-handler-alist', and that is searched sequentially. Thus,
1482 if the Tramp entry appears rather early in the `file-name-handler-alist'
1483 and is a bit too general, then some files might be considered Tramp
1484 files which are not really Tramp files.
1486 Please note that the entry in `file-name-handler-alist' is made when
1487 this file \(tramp.el\) is loaded. This means that this variable must be set
1488 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1489 updated after changing this variable.
1491 Also see `tramp-file-name-structure'.")
1494 (defconst tramp-root-regexp
1495 (if (memq system-type '(cygwin windows-nt))
1496 "\\`\\([a-zA-Z]:\\)?/"
1498 "Beginning of an incomplete Tramp file name.
1499 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1500 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1503 (defconst tramp-completion-file-name-regexp-unified
1504 (if (memq system-type '(cygwin windows-nt))
1505 (concat tramp-root-regexp "[^/]\\{2,\\}\\'")
1506 (concat tramp-root-regexp "[^/]*\\'"))
1507 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1508 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1509 See `tramp-file-name-structure' for more explanations.
1511 On W32 systems, the volume letter must be ignored.")
1514 (defconst tramp-completion-file-name-regexp-separate
1515 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1516 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1517 XEmacs uses a separate filename syntax for Tramp and EFS.
1518 See `tramp-file-name-structure' for more explanations.")
1521 (defconst tramp-completion-file-name-regexp-url
1522 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1523 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1524 See `tramp-file-name-structure' for more explanations.")
1527 (defconst tramp-completion-file-name-regexp
1528 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1529 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1530 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1531 (t (error "Wrong `tramp-syntax' defined")))
1532 "*Regular expression matching file names handled by Tramp completion.
1533 This regexp should match partial Tramp file names only.
1535 Please note that the entry in `file-name-handler-alist' is made when
1536 this file (tramp.el) is loaded. This means that this variable must be set
1537 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1538 updated after changing this variable.
1540 Also see `tramp-file-name-structure'.")
1542 (defconst tramp-actions-before-shell
1543 '((tramp-login-prompt-regexp tramp-action-login)
1544 (tramp-password-prompt-regexp tramp-action-password)
1545 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1546 (shell-prompt-pattern tramp-action-succeed)
1547 (tramp-shell-prompt-pattern tramp-action-succeed)
1548 (tramp-yesno-prompt-regexp tramp-action-yesno)
1549 (tramp-yn-prompt-regexp tramp-action-yn)
1550 (tramp-terminal-prompt-regexp tramp-action-terminal)
1551 (tramp-process-alive-regexp tramp-action-process-alive))
1552 "List of pattern/action pairs.
1553 Whenever a pattern matches, the corresponding action is performed.
1554 Each item looks like (PATTERN ACTION).
1556 The PATTERN should be a symbol, a variable. The value of this
1557 variable gives the regular expression to search for. Note that the
1558 regexp must match at the end of the buffer, \"\\'\" is implicitly
1561 The ACTION should also be a symbol, but a function. When the
1562 corresponding PATTERN matches, the ACTION function is called.")
1564 (defconst tramp-actions-copy-out-of-band
1565 '((tramp-password-prompt-regexp tramp-action-password)
1566 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1567 (tramp-copy-failed-regexp tramp-action-permission-denied)
1568 (tramp-process-alive-regexp tramp-action-out-of-band))
1569 "List of pattern/action pairs.
1570 This list is used for copying/renaming with out-of-band methods.
1572 See `tramp-actions-before-shell' for more info.")
1574 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1575 ;; known to have a bug in `process-send-string'; some ssh connections appear
1576 ;; to drop bytes when data is sent too quickly. There is also a connection
1577 ;; buffer local variable, which is computed depending on remote host properties
1578 ;; when `tramp-chunksize' is zero or nil.
1579 (defcustom tramp-chunksize
1580 (when (and (not (featurep 'xemacs))
1581 (memq system-type '(hpux)))
1583 ;; Parentheses in docstring starting at beginning of line are escaped.
1584 ;; Fontification is messed up when
1585 ;; `open-paren-in-column-0-is-defun-start' set to t.
1586 "*If non-nil, chunksize for sending input to local process.
1587 It is necessary only on systems which have a buggy `process-send-string'
1588 implementation. The necessity, whether this variable must be set, can be
1589 checked via the following code:
1592 (let* ((user \"xxx\") (host \"yyy\")
1594 (sent init) (received init))
1595 (while (= sent received)
1596 (setq sent (+ sent step))
1598 (let ((proc (start-process (buffer-name) (current-buffer)
1599 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1600 (when (memq (process-status proc) '(run open))
1601 (process-send-string proc (make-string sent ?\\ ))
1602 (process-send-eof proc)
1603 (process-send-eof proc))
1604 (while (not (progn (goto-char (point-min))
1605 (re-search-forward \"\\\\w+\" (point-max) t)))
1606 (accept-process-output proc 1))
1607 (when (memq (process-status proc) '(run open))
1608 (setq received (string-to-number (match-string 0)))
1609 (delete-process proc)
1610 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1612 (if (> sent (+ init step))
1613 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1615 (message \"Test does not work\")
1616 (display-buffer (current-buffer))
1619 In the Emacs normally running Tramp, evaluate the above code
1620 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1621 respectively\). You can do this, for example, by pasting it into
1622 the `*scratch*' buffer and then hitting C-j with the cursor after the
1623 last closing parenthesis. Note that it works only if you have configured
1624 \"ssh\" to run without password query, see ssh-agent\(1\).
1626 You will see the number of bytes sent successfully to the remote host.
1627 If that number exceeds 1000, you can stop the execution by hitting
1628 C-g, because your Emacs is likely clean.
1630 When it is necessary to set `tramp-chunksize', you might consider to
1631 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1632 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
1635 If your Emacs is buggy, the code stops and gives you an indication
1636 about the value `tramp-chunksize' should be set. Maybe you could just
1637 experiment a bit, e.g. changing the values of `init' and `step'
1638 in the third line of the code.
1640 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1641 this variable to be set as well."
1643 :type '(choice (const nil) integer))
1645 ;; Logging in to a remote host normally requires obtaining a pty. But
1646 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1647 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1648 ;; for an override of the system default.
1649 (defcustom tramp-process-connection-type t
1650 "Overrides `process-connection-type' for connections from Tramp.
1651 Tramp binds process-connection-type to the value given here before
1652 opening a connection to a remote host."
1654 :type '(choice (const nil) (const t) (const pty)))
1656 (defcustom tramp-completion-reread-directory-timeout 10
1657 "Defines seconds since last remote command before rereading a directory.
1658 A remote directory might have changed its contents. In order to
1659 make it visible during file name completion in the minibuffer,
1660 Tramp flushes its cache and rereads the directory contents when
1661 more than `tramp-completion-reread-directory-timeout' seconds
1662 have been gone since last remote command execution. A value of 0
1663 would require an immediate reread during filename completion, nil
1664 means to use always cached values for the directory contents."
1666 :type '(choice (const nil) integer))
1668 ;;; Internal Variables:
1670 (defvar tramp-current-method nil
1671 "Connection method for this *tramp* buffer.")
1673 (defvar tramp-current-user nil
1674 "Remote login name for this *tramp* buffer.")
1676 (defvar tramp-current-host nil
1677 "Remote host for this *tramp* buffer.")
1679 (defconst tramp-uudecode
1680 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1682 rm -f /tmp/tramp.$$"
1683 "Shell function to implement `uudecode' to standard output.
1684 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1685 for this or `uudecode -p', but some systems don't, and for them
1686 we have this shell function.")
1688 (defconst tramp-perl-file-truename
1691 use Cwd \"realpath\";
1694 my ($volume, @dirs) = @_;
1695 my $real = realpath(File::Spec->catpath(
1696 $volume, File::Spec->catdir(@dirs), \"\"));
1698 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1699 return ($vol, File::Spec->splitdir($dir));
1702 my $last = pop(@dirs);
1703 ($volume, @dirs) = recursive($volume, @dirs);
1705 return ($volume, @dirs);
1709 $result = realpath($ARGV[0]);
1711 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1712 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1714 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1717 if ($ARGV[0] =~ /\\/$/) {
1718 $result = $result . \"/\";
1721 print \"\\\"$result\\\"\\n\";
1722 ' \"$1\" 2>/dev/null"
1723 "Perl script to produce output suitable for use with `file-truename'
1724 on the remote file system.
1725 Escape sequence %s is replaced with name of Perl binary.
1726 This string is passed to `format', so percent characters need to be doubled.")
1728 (defconst tramp-perl-file-name-all-completions
1738 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1739 @files = readdir(d); closedir(d);
1740 foreach $f (@files) {
1741 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1742 if (-d \"$ARGV[0]/$f\") {
1751 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1752 "Perl script to produce output suitable for use with
1753 `file-name-all-completions' on the remote file system. Escape
1754 sequence %s is replaced with name of Perl binary. This string is
1755 passed to `format', so percent characters need to be doubled.")
1757 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1758 ;; output. If you are hacking on this, note that you get *no* output
1759 ;; unless this spits out a complete line, including the '\n' at the
1761 ;; The device number is returned as "-1", because there will be a virtual
1762 ;; device number set in `tramp-handle-file-attributes'.
1763 (defconst tramp-perl-file-attributes
1765 @stat = lstat($ARGV[0]);
1770 if (($stat[2] & 0170000) == 0120000)
1772 $type = readlink($ARGV[0]);
1773 $type = \"\\\"$type\\\"\";
1775 elsif (($stat[2] & 0170000) == 040000)
1783 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1784 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1786 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1791 $stat[8] >> 16 & 0xffff,
1793 $stat[9] >> 16 & 0xffff,
1795 $stat[10] >> 16 & 0xffff,
1799 $stat[1] >> 16 & 0xffff,
1801 );' \"$1\" \"$2\" 2>/dev/null"
1802 "Perl script to produce output suitable for use with `file-attributes'
1803 on the remote file system.
1804 Escape sequence %s is replaced with name of Perl binary.
1805 This string is passed to `format', so percent characters need to be doubled.")
1807 (defconst tramp-perl-directory-files-and-attributes
1809 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1810 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1811 @list = readdir(DIR);
1815 for($i = 0; $i < $n; $i++)
1817 $filename = $list[$i];
1818 @stat = lstat($filename);
1819 if (($stat[2] & 0170000) == 0120000)
1821 $type = readlink($filename);
1822 $type = \"\\\"$type\\\"\";
1824 elsif (($stat[2] & 0170000) == 040000)
1832 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1833 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1835 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1841 $stat[8] >> 16 & 0xffff,
1843 $stat[9] >> 16 & 0xffff,
1845 $stat[10] >> 16 & 0xffff,
1849 $stat[1] >> 16 & 0xffff,
1851 $stat[0] >> 16 & 0xffff,
1854 printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
1855 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1857 Escape sequence %s is replaced with name of Perl binary.
1858 This string is passed to `format', so percent characters need to be doubled.")
1860 ;; ;; These two use uu encoding.
1861 ;; (defvar tramp-perl-encode "%s -e'\
1862 ;; print qq(begin 644 xxx\n);
1865 ;; while (read(STDIN, $s, 45)) {
1866 ;; print pack(q(u), $s);
1871 ;; "Perl program to use for encoding a file.
1872 ;; Escape sequence %s is replaced with name of Perl binary.")
1874 ;; (defvar tramp-perl-decode "%s -ne '
1875 ;; print unpack q(u), $_;
1877 ;; "Perl program to use for decoding a file.
1878 ;; Escape sequence %s is replaced with name of Perl binary.")
1880 ;; These two use base64 encoding.
1881 (defconst tramp-perl-encode-with-module
1882 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
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.
1886 This implementation requires the MIME::Base64 Perl module to be installed
1887 on the remote host.")
1889 (defconst tramp-perl-decode-with-module
1890 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1891 "Perl program to use for decoding a file.
1892 Escape sequence %s is replaced with name of Perl binary.
1893 This string is passed to `format', so percent characters need to be doubled.
1894 This implementation requires the MIME::Base64 Perl module to be installed
1895 on the remote host.")
1897 (defconst tramp-perl-encode
1899 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1900 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1901 # Free Software Foundation, Inc.
1906 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1907 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1912 # We read in chunks of 54 bytes, to generate output lines
1913 # of 72 chars (plus end of line)
1916 while (my $data = <STDIN>) {
1919 # Only for the last chunk, and only if did not fill the last three-byte packet
1921 my $mod = length($data) %% 3;
1922 $pad = q(=) x (3 - $mod) if $mod;
1925 # Not the fastest method, but it is simple: unpack to binary string, split
1926 # by groups of 6 bits and convert back from binary to byte; then map into
1927 # the translation table
1931 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1935 "Perl program to use for encoding a file.
1936 Escape sequence %s is replaced with name of Perl binary.
1937 This string is passed to `format', so percent characters need to be doubled.")
1939 (defconst tramp-perl-decode
1941 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1942 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1943 # Free Software Foundation, Inc.
1948 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1949 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1952 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1956 # We are going to accumulate into $pending to accept any line length
1957 # (we do not check they are <= 76 chars as the RFC says)
1960 while (my $data = <STDIN>) {
1963 # If we find one or two =, we have reached the end and
1964 # any following data is to be discarded
1965 my $finished = $data =~ s/(==?).*/$1/;
1968 my $len = length($pending);
1969 my $chunk = substr($pending, 0, $len & ~3);
1970 $pending = substr($pending, $len & ~3 + 1);
1972 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1973 # split in 8-bit chunks and convert back to char.
1976 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1980 "Perl program to use for decoding a file.
1981 Escape sequence %s is replaced with name of Perl binary.
1982 This string is passed to `format', so percent characters need to be doubled.")
1984 (defconst tramp-vc-registered-read-file-names
1987 if %s \"$file\"; then
1988 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1990 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1992 if %s \"$file\"; then
1993 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1995 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1999 "Script to check existence of VC related files.
2000 It must be send formatted with two strings; the tests for file
2001 existence, and file readability. Input shall be read via
2002 here-document, otherwise the command could exceed maximum length
2005 (defconst tramp-file-mode-type-map
2006 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
2008 (2 . "c") ; character device
2009 (3 . "m") ; multiplexed character device (v7)
2010 (4 . "d") ; directory
2011 (5 . "?") ; Named special file (XENIX)
2012 (6 . "b") ; block device
2013 (7 . "?") ; multiplexed block device (v7)
2014 (8 . "-") ; regular file
2015 (9 . "n") ; network special file (HP-UX)
2016 (10 . "l") ; symlink
2017 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
2019 (13 . "D") ; door special (Solaris)
2020 (14 . "w")) ; whiteout (BSD)
2021 "A list of file types returned from the `stat' system call.
2022 This is used to map a mode number to a permission string.")
2024 ;; New handlers should be added here. The following operations can be
2025 ;; handled using the normal primitives: file-name-sans-versions,
2027 (defconst tramp-file-name-handler-alist
2028 '((load . tramp-handle-load)
2029 (make-symbolic-link . tramp-handle-make-symbolic-link)
2030 (file-name-as-directory . tramp-handle-file-name-as-directory)
2031 (file-name-directory . tramp-handle-file-name-directory)
2032 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
2033 (file-truename . tramp-handle-file-truename)
2034 (file-exists-p . tramp-handle-file-exists-p)
2035 (file-directory-p . tramp-handle-file-directory-p)
2036 (file-executable-p . tramp-handle-file-executable-p)
2037 (file-readable-p . tramp-handle-file-readable-p)
2038 (file-regular-p . tramp-handle-file-regular-p)
2039 (file-symlink-p . tramp-handle-file-symlink-p)
2040 (file-writable-p . tramp-handle-file-writable-p)
2041 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
2042 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
2043 (file-attributes . tramp-handle-file-attributes)
2044 (file-modes . tramp-handle-file-modes)
2045 (directory-files . tramp-handle-directory-files)
2046 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
2047 (file-name-all-completions . tramp-handle-file-name-all-completions)
2048 (file-name-completion . tramp-handle-file-name-completion)
2049 (add-name-to-file . tramp-handle-add-name-to-file)
2050 (copy-file . tramp-handle-copy-file)
2051 (copy-directory . tramp-handle-copy-directory)
2052 (rename-file . tramp-handle-rename-file)
2053 (set-file-modes . tramp-handle-set-file-modes)
2054 (set-file-times . tramp-handle-set-file-times)
2055 (make-directory . tramp-handle-make-directory)
2056 (delete-directory . tramp-handle-delete-directory)
2057 (delete-file . tramp-handle-delete-file)
2058 (directory-file-name . tramp-handle-directory-file-name)
2059 ;; `executable-find' is not official yet.
2060 (executable-find . tramp-handle-executable-find)
2061 (start-file-process . tramp-handle-start-file-process)
2062 (process-file . tramp-handle-process-file)
2063 (shell-command . tramp-handle-shell-command)
2064 (insert-directory . tramp-handle-insert-directory)
2065 (expand-file-name . tramp-handle-expand-file-name)
2066 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2067 (file-local-copy . tramp-handle-file-local-copy)
2068 (file-remote-p . tramp-handle-file-remote-p)
2069 (insert-file-contents . tramp-handle-insert-file-contents)
2070 (insert-file-contents-literally
2071 . tramp-handle-insert-file-contents-literally)
2072 (write-region . tramp-handle-write-region)
2073 (find-backup-file-name . tramp-handle-find-backup-file-name)
2074 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2075 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2076 (dired-compress-file . tramp-handle-dired-compress-file)
2077 (dired-recursive-delete-directory
2078 . tramp-handle-dired-recursive-delete-directory)
2079 (dired-uncache . tramp-handle-dired-uncache)
2080 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2081 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2082 (file-selinux-context . tramp-handle-file-selinux-context)
2083 (set-file-selinux-context . tramp-handle-set-file-selinux-context)
2084 (vc-registered . tramp-handle-vc-registered))
2085 "Alist of handler functions.
2086 Operations not mentioned here will be handled by the normal Emacs functions.")
2088 ;; Handlers for partial Tramp file names. For Emacs just
2089 ;; `file-name-all-completions' is needed.
2091 (defconst tramp-completion-file-name-handler-alist
2092 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2093 (file-name-completion . tramp-completion-handle-file-name-completion))
2094 "Alist of completion handler functions.
2095 Used for file names matching `tramp-file-name-regexp'. Operations not
2096 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2097 normal Emacs functions.")
2099 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2100 (defvar tramp-foreign-file-name-handler-alist
2101 ;; (identity . tramp-sh-file-name-handler) should always be the last
2102 ;; entry, because `identity' always matches.
2103 '((identity . tramp-sh-file-name-handler))
2104 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2105 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2108 ;;; Internal functions which must come first:
2110 (defsubst tramp-debug-message (vec fmt-string &rest args)
2111 "Append message to debug buffer.
2112 Message is formatted with FMT-STRING as control string and the remaining
2113 ARGS to actually emit the message (if applicable)."
2114 (when (get-buffer (tramp-buffer-name vec))
2115 (with-current-buffer (tramp-get-debug-buffer vec)
2116 (goto-char (point-max))
2121 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2122 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2123 emacs-version tramp-version)))
2127 (let ((now (current-time)))
2128 (insert (format-time-string "%T." now))
2129 (insert (format "%06d " (nth 2 now))))
2130 ;; Calling function.
2131 (let ((btn 1) btf fn)
2133 (setq btf (nth 1 (backtrace-frame btn)))
2137 (setq fn (symbol-name btf))
2138 (unless (and (string-match "^tramp" fn)
2140 "^tramp\\(-debug\\)?\\(-message\\|-error\\|-compat-funcall\\)$"
2143 (setq btn (1+ btn))))
2144 ;; The following code inserts filename and line number.
2145 ;; Should be deactivated by default, because it is time
2147 ; (let ((ffn (find-function-noselect (intern fn))))
2151 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2152 ; (with-current-buffer (car ffn)
2153 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2154 (insert (format "%s " fn)))
2156 (insert (apply 'format fmt-string args)))))
2158 (defvar tramp-message-show-message t
2159 "Show Tramp message in the minibuffer.
2160 This variable is used to disable messages from `tramp-error'.
2161 The messages are visible anyway, because an error is raised.")
2163 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2164 "Emit a message depending on verbosity level.
2165 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2166 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2167 less than LEVEL. The message is emitted only if `tramp-verbose' is
2168 greater than or equal to LEVEL.
2170 The message is also logged into the debug buffer when `tramp-verbose'
2171 is greater than or equal 4.
2173 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2174 control string and the remaining ARGS to actually emit the message (if
2177 (when (<= level tramp-verbose)
2178 ;; Match data must be preserved!
2180 ;; Display only when there is a minimum level.
2181 (when (and tramp-message-show-message (<= level 3))
2187 ((= level 2) "Warning: ")
2191 ;; Log only when there is a minimum level.
2192 (when (>= tramp-verbose 4)
2193 (when (and vec-or-proc
2194 (processp vec-or-proc)
2195 (buffer-name (process-buffer vec-or-proc)))
2196 (with-current-buffer (process-buffer vec-or-proc)
2197 ;; Translate proc to vec.
2198 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2199 (when (and vec-or-proc (vectorp vec-or-proc))
2200 (apply 'tramp-debug-message
2202 (concat (format "(%d) # " level) fmt-string)
2204 ;; Suppress all errors.
2207 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2209 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2210 signal identifier to be raised, remaining args passed to
2211 `tramp-message'. Finally, signal SIGNAL is raised."
2212 (let (tramp-message-show-message)
2215 (error-message-string
2217 (get signal 'error-message)
2218 (apply 'format fmt-string args))))
2219 (signal signal (list (apply 'format fmt-string args)))))
2221 (defsubst tramp-error-with-buffer
2222 (buffer vec-or-proc signal fmt-string &rest args)
2223 "Emit an error, and show BUFFER.
2224 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2225 an input event arrives. The other arguments are passed to `tramp-error'."
2226 (save-window-excursion
2228 (apply 'tramp-error vec-or-proc signal fmt-string args)
2229 (when (and vec-or-proc
2230 (not (zerop tramp-verbose))
2231 (not (tramp-completion-mode-p)))
2232 (let ((enable-recursive-minibuffers t))
2234 (or (and (bufferp buffer) buffer)
2235 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2236 (tramp-get-buffer vec-or-proc)))
2239 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2240 "Parse a Tramp filename and make components available in the body.
2242 First arg FILENAME is evaluated and dissected into its components.
2243 Second arg VAR is a symbol. It is used as a variable name to hold
2244 the filename structure. It is also used as a prefix for the variables
2245 holding the components. For example, if VAR is the symbol `foo', then
2246 `foo' will be bound to the whole structure, `foo-method' will be bound to
2247 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2249 Remaining args are Lisp expressions to be evaluated (inside an implicit
2252 If VAR is nil, then we bind `v' to the structure and `method', `user',
2253 `host', `localname' to the components."
2254 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2255 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2256 (tramp-file-name-method ,(or var 'v)))
2257 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2258 (tramp-file-name-user ,(or var 'v)))
2259 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2260 (tramp-file-name-host ,(or var 'v)))
2261 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2262 (tramp-file-name-localname ,(or var 'v))))
2265 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2266 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2267 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2269 (defmacro with-file-property (vec file property &rest body)
2270 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2271 FILE must be a local file name on a connection identified via VEC."
2272 `(if (file-name-absolute-p ,file)
2273 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2274 (when (eq value 'undef)
2275 ;; We cannot pass @body as parameter to
2276 ;; `tramp-set-file-property' because it mangles our
2278 (setq value (progn ,@body))
2279 (tramp-set-file-property ,vec ,file ,property value))
2283 (put 'with-file-property 'lisp-indent-function 3)
2284 (put 'with-file-property 'edebug-form-spec t)
2285 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2287 (defmacro with-connection-property (key property &rest body)
2288 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
2289 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2290 (when (eq value 'undef)
2291 ;; We cannot pass ,@body as parameter to
2292 ;; `tramp-set-connection-property' because it mangles our debug
2294 (setq value (progn ,@body))
2295 (tramp-set-connection-property ,key ,property value))
2298 (put 'with-connection-property 'lisp-indent-function 2)
2299 (put 'with-connection-property 'edebug-form-spec t)
2300 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2302 (defun tramp-progress-reporter-update (reporter &optional value)
2303 (let* ((parameters (cdr reporter))
2304 (message (aref parameters 3)))
2305 (when (string-match message (or (current-message) ""))
2306 (funcall 'progress-reporter-update reporter value))))
2308 (defmacro with-progress-reporter (vec level message &rest body)
2309 "Executes BODY, spinning a progress reporter with MESSAGE.
2310 If LEVEL does not fit for visible messages, or if this is a
2311 nested call of the macro, there are only traces without a visible
2314 (tramp-message ,vec ,level "%s..." ,message)
2315 ;; We start a pulsing progress reporter after 3 seconds. Feature
2316 ;; introduced in Emacs 24.1.
2317 (when (and tramp-message-show-message
2318 ;; Display only when there is a minimum level.
2319 (<= ,level (min tramp-verbose 3)))
2321 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
2323 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))
2326 ;; Execute the body. Unset `tramp-message-show-message' when
2327 ;; the timer object is created, in order to suppress
2328 ;; concurrent timers.
2329 (let ((tramp-message-show-message
2330 (and tramp-message-show-message (not tm))))
2332 ;; Stop progress reporter.
2333 (if tm (tramp-compat-funcall 'cancel-timer tm))
2334 (tramp-message ,vec ,level "%s...done" ,message))))
2336 (put 'with-progress-reporter 'lisp-indent-function 3)
2337 (put 'with-progress-reporter 'edebug-form-spec t)
2338 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
2340 (eval-and-compile ;; Silence compiler.
2341 (if (memq system-type '(cygwin windows-nt))
2342 (defun tramp-drop-volume-letter (name)
2343 "Cut off unnecessary drive letter from file NAME.
2344 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2345 locally on a remote file name. When the local system is a W32 system
2346 but the remote system is Unix, this introduces a superfluous drive
2347 letter into the file name. This function removes it."
2349 (if (string-match tramp-root-regexp name)
2350 (replace-match "/" nil t name)
2353 (defalias 'tramp-drop-volume-letter 'identity)))
2355 (defsubst tramp-make-tramp-temp-file (vec)
2356 "Create a temporary file on the remote host identified by VEC.
2357 Return the local name of the temporary file."
2359 (tramp-make-tramp-file-name
2360 (tramp-file-name-method vec)
2361 (tramp-file-name-user vec)
2362 (tramp-file-name-host vec)
2363 (tramp-drop-volume-letter
2365 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2368 ;; `make-temp-file' would be the natural choice for
2369 ;; implementation. But it calls `write-region' internally,
2370 ;; which also needs a temporary file - we would end in an
2372 (setq result (make-temp-name prefix))
2373 (if (file-exists-p result)
2375 ;; This creates the file by side effect.
2376 (set-file-times result)
2377 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2379 ;; Return the local part.
2380 (with-parsed-tramp-file-name result nil localname)))
2383 ;;; Config Manipulation Functions:
2385 (defun tramp-set-completion-function (method function-list)
2386 "Sets the list of completion functions for METHOD.
2387 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2388 The FUNCTION is intended to parse FILE according its syntax.
2389 It might be a predefined FUNCTION, or a user defined FUNCTION.
2390 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2391 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2392 and `tramp-parse-netrc'.
2396 (tramp-set-completion-function
2398 '((tramp-parse-sconfig \"/etc/ssh_config\")
2399 (tramp-parse-sconfig \"~/.ssh/config\")))"
2401 (let ((r function-list)
2403 (setq tramp-completion-function-alist
2404 (delete (assoc method tramp-completion-function-alist)
2405 tramp-completion-function-alist))
2408 ;; Remove double entries.
2409 (when (member (car v) (cdr v))
2410 (setcdr v (delete (car v) (cdr v))))
2411 ;; Check for function and file or registry key.
2412 (unless (and (functionp (nth 0 (car v)))
2413 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2414 ;; Windows registry.
2415 (and (memq system-type '(cygwin windows-nt))
2417 (tramp-local-call-process
2418 "reg" nil nil nil "query" (nth 1 (car v)))))
2419 ;; Configuration file.
2420 (file-exists-p (nth 1 (car v)))))
2421 (setq r (delete (car v) r)))
2425 (add-to-list 'tramp-completion-function-alist
2428 (defun tramp-get-completion-function (method)
2429 "Returns a list of completion functions for METHOD.
2430 For definition of that list see `tramp-set-completion-function'."
2432 ;; Hosts visited once shall be remembered.
2433 `(tramp-parse-connection-properties ,method)
2434 ;; The method related defaults.
2435 (cdr (assoc method tramp-completion-function-alist))))
2438 ;;; Fontification of `read-file-name':
2440 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2441 (defvar tramp-rfn-eshadow-overlay)
2442 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2444 (defun tramp-rfn-eshadow-setup-minibuffer ()
2445 "Set up a minibuffer for `file-name-shadow-mode'.
2446 Adds another overlay hiding filename parts according to Tramp's
2447 special handling of `substitute-in-file-name'."
2448 (when (symbol-value 'minibuffer-completing-file-name)
2449 (setq tramp-rfn-eshadow-overlay
2450 (tramp-compat-funcall
2452 (tramp-compat-funcall 'minibuffer-prompt-end)
2453 (tramp-compat-funcall 'minibuffer-prompt-end)))
2454 ;; Copy rfn-eshadow-overlay properties.
2455 (let ((props (tramp-compat-funcall
2456 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
2458 (tramp-compat-funcall
2459 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2461 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2462 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2463 'tramp-rfn-eshadow-setup-minibuffer)
2464 (add-hook 'tramp-unload-hook
2466 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2467 'tramp-rfn-eshadow-setup-minibuffer))))
2469 (defconst tramp-rfn-eshadow-update-overlay-regexp
2470 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2472 (defun tramp-rfn-eshadow-update-overlay ()
2473 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2474 This is intended to be used as a minibuffer `post-command-hook' for
2475 `file-name-shadow-mode'; the minibuffer should have already
2476 been set up by `rfn-eshadow-setup-minibuffer'."
2477 ;; In remote files name, there is a shadowing just for the local part.
2478 (let ((end (or (tramp-compat-funcall
2479 'overlay-end (symbol-value 'rfn-eshadow-overlay))
2480 (tramp-compat-funcall 'minibuffer-prompt-end))))
2483 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
2487 (1+ (or (string-match
2488 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2491 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2492 (rfn-eshadow-update-overlay-hook nil))
2493 (tramp-compat-funcall
2494 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
2495 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
2497 (when (boundp 'rfn-eshadow-update-overlay-hook)
2498 (add-hook 'rfn-eshadow-update-overlay-hook
2499 'tramp-rfn-eshadow-update-overlay)
2500 (add-hook 'tramp-unload-hook
2502 (remove-hook 'rfn-eshadow-update-overlay-hook
2503 'tramp-rfn-eshadow-update-overlay))))
2506 ;;; Integration of eshell.el:
2509 (defvar eshell-path-env))
2511 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2512 ;; when `default-directory' points to another host.
2513 (defun tramp-eshell-directory-change ()
2514 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2515 (setq eshell-path-env
2516 (if (file-remote-p default-directory)
2517 (with-parsed-tramp-file-name default-directory nil
2520 (tramp-get-remote-path v)
2524 (eval-after-load "esh-util"
2526 (tramp-eshell-directory-change)
2527 (add-hook 'eshell-directory-change-hook
2528 'tramp-eshell-directory-change)
2529 (add-hook 'tramp-unload-hook
2531 (remove-hook 'eshell-directory-change-hook
2532 'tramp-eshell-directory-change)))))
2535 ;;; File Name Handler Functions:
2537 (defun tramp-handle-make-symbolic-link
2538 (filename linkname &optional ok-if-already-exists)
2539 "Like `make-symbolic-link' for Tramp files.
2540 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2541 the symlink. If LINKNAME is a Tramp file, only the localname component is
2542 used as the target of the symlink.
2544 If LINKNAME is a Tramp file and the localname component is relative, then
2545 it is expanded first, before the localname component is taken. Note that
2546 this can give surprising results if the user/host for the source and
2547 target of the symlink differ."
2548 (with-parsed-tramp-file-name linkname l
2549 (let ((ln (tramp-get-remote-ln l))
2550 (cwd (tramp-run-real-handler
2551 'file-name-directory (list l-localname))))
2555 "Making a symbolic link. ln(1) does not exist on the remote host."))
2557 ;; Do the 'confirm if exists' thing.
2558 (when (file-exists-p linkname)
2560 (if (or (null ok-if-already-exists) ; not allowed to exist
2561 (and (numberp ok-if-already-exists)
2564 "File %s already exists; make it a link anyway? "
2567 l 'file-already-exists "File %s already exists" l-localname)
2568 (delete-file linkname)))
2570 ;; If FILENAME is a Tramp name, use just the localname component.
2571 (when (tramp-tramp-file-p filename)
2573 (tramp-file-name-localname
2574 (tramp-dissect-file-name (expand-file-name filename)))))
2576 (tramp-flush-file-property l (file-name-directory l-localname))
2577 (tramp-flush-file-property l l-localname)
2579 ;; Right, they are on the same host, regardless of user, method, etc.
2580 ;; We now make the link on the remote machine. This will occur as the user
2581 ;; that FILENAME belongs to.
2583 (tramp-send-command-and-check
2586 "cd %s && %s -sf %s %s"
2587 (tramp-shell-quote-argument cwd)
2589 (tramp-shell-quote-argument filename)
2590 (tramp-shell-quote-argument l-localname))
2593 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2594 "Like `load' for Tramp files."
2595 (with-parsed-tramp-file-name (expand-file-name file) nil
2597 (cond ((file-exists-p (concat file ".elc"))
2598 (setq file (concat file ".elc")))
2599 ((file-exists-p (concat file ".el"))
2600 (setq file (concat file ".el")))))
2602 ;; The first condition is always true for absolute file names.
2603 ;; Included for safety's sake.
2604 (unless (or (file-name-directory file)
2605 (string-match "\\.elc?\\'" file))
2608 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2610 (when (not (file-exists-p file))
2611 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2612 (if (not (file-exists-p file))
2614 (let ((tramp-message-show-message (not nomessage)))
2615 (with-progress-reporter v 0 (format "Loading %s" file)
2616 (let ((local-copy (file-local-copy file)))
2617 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2619 (load local-copy noerror t t)
2620 (delete-file local-copy)))))
2623 ;; Localname manipulation functions that grok Tramp localnames...
2624 (defun tramp-handle-file-name-as-directory (file)
2625 "Like `file-name-as-directory' but aware of Tramp files."
2626 ;; `file-name-as-directory' would be sufficient except localname is
2627 ;; the empty string.
2628 (let ((v (tramp-dissect-file-name file t)))
2629 ;; Run the command on the localname portion only.
2630 (tramp-make-tramp-file-name
2631 (tramp-file-name-method v)
2632 (tramp-file-name-user v)
2633 (tramp-file-name-host v)
2634 (tramp-run-real-handler
2635 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2637 (defun tramp-handle-file-name-directory (file)
2638 "Like `file-name-directory' but aware of Tramp files."
2639 ;; Everything except the last filename thing is the directory. We
2640 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2641 ;; the remote file name parts. This is a problem when we are in
2642 ;; file name completion.
2643 (let ((v (tramp-dissect-file-name file t)))
2644 ;; Run the command on the localname portion only.
2645 (tramp-make-tramp-file-name
2646 (tramp-file-name-method v)
2647 (tramp-file-name-user v)
2648 (tramp-file-name-host v)
2649 (tramp-run-real-handler
2650 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2652 (defun tramp-handle-file-name-nondirectory (file)
2653 "Like `file-name-nondirectory' but aware of Tramp files."
2654 (with-parsed-tramp-file-name file nil
2655 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2657 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2658 "Like `file-truename' for Tramp files."
2659 (with-parsed-tramp-file-name (expand-file-name filename) nil
2660 (with-file-property v localname "file-truename"
2661 (let ((result nil)) ; result steps in reverse order
2662 (tramp-message v 4 "Finding true name for `%s'" filename)
2664 ;; Use GNU readlink --canonicalize-missing where available.
2665 ((tramp-get-remote-readlink v)
2667 (tramp-send-command-and-read
2669 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2670 (tramp-get-remote-readlink v)
2671 (tramp-shell-quote-argument localname)))))
2673 ;; Use Perl implementation.
2674 ((and (tramp-get-remote-perl v)
2675 (tramp-get-connection-property v "perl-file-spec" nil)
2676 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2677 (tramp-maybe-send-script
2678 v tramp-perl-file-truename "tramp_perl_file_truename")
2680 (tramp-send-command-and-read
2682 (format "tramp_perl_file_truename %s"
2683 (tramp-shell-quote-argument localname)))))
2685 ;; Do it yourself. We bind `directory-sep-char' here for
2686 ;; XEmacs on Windows, which would otherwise use backslash.
2687 (t (let* ((directory-sep-char ?/)
2688 (steps (tramp-compat-split-string localname "/"))
2689 (localnamedir (tramp-run-real-handler
2690 'file-name-as-directory (list localname)))
2691 (is-dir (string= localname localnamedir))
2694 ;; Don't make the following value larger than
2695 ;; necessary. People expect an error message in a
2696 ;; timely fashion when something is wrong;
2697 ;; otherwise they might think that Emacs is hung.
2698 ;; Of course, correctness has to come first.
2701 (while (and steps (< numchase numchase-limit))
2702 (setq thisstep (pop steps))
2705 (mapconcat 'identity
2706 (append '("") (reverse result) (list thisstep))
2708 (setq symlink-target
2709 (nth 0 (file-attributes
2710 (tramp-make-tramp-file-name
2712 (mapconcat 'identity
2717 (cond ((string= "." thisstep)
2718 (tramp-message v 5 "Ignoring step `.'"))
2719 ((string= ".." thisstep)
2720 (tramp-message v 5 "Processing step `..'")
2722 ((stringp symlink-target)
2723 ;; It's a symlink, follow it.
2724 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2725 (setq numchase (1+ numchase))
2726 (when (file-name-absolute-p symlink-target)
2728 ;; If the symlink was absolute, we'll get a string like
2729 ;; "/user@host:/some/target"; extract the
2730 ;; "/some/target" part from it.
2731 (when (tramp-tramp-file-p symlink-target)
2732 (unless (tramp-equal-remote filename symlink-target)
2735 "Symlink target `%s' on wrong host" symlink-target))
2736 (setq symlink-target localname))
2738 (append (tramp-compat-split-string
2743 (setq result (cons thisstep result)))))
2744 (when (>= numchase numchase-limit)
2747 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2748 (setq result (reverse result))
2749 ;; Combine list to form string.
2752 (mapconcat 'identity (cons "" result) "/")
2754 (when (and is-dir (or (string= "" result)
2755 (not (string= (substring result -1) "/"))))
2756 (setq result (concat result "/"))))))
2758 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2759 (tramp-make-tramp-file-name method user host result)))))
2763 (defun tramp-handle-file-exists-p (filename)
2764 "Like `file-exists-p' for Tramp files."
2765 (with-parsed-tramp-file-name filename nil
2766 (with-file-property v localname "file-exists-p"
2767 (or (not (null (tramp-get-file-property
2768 v localname "file-attributes-integer" nil)))
2769 (not (null (tramp-get-file-property
2770 v localname "file-attributes-string" nil)))
2771 (zerop (tramp-send-command-and-check
2775 (tramp-get-file-exists-command v)
2776 (tramp-shell-quote-argument localname))))))))
2778 ;; Inodes don't exist for some file systems. Therefore we must
2779 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2780 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2781 ;; performance isn't the major issue given that file transfer will
2783 (defvar tramp-inodes nil
2784 "Keeps virtual inodes numbers.")
2786 ;; Devices must distinguish physical file systems. The device numbers
2787 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2788 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2789 ;; EFS use device number "-1". In order to be different, we use device number
2790 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2791 (defvar tramp-devices nil
2792 "Keeps virtual device numbers.")
2794 ;; CCC: This should check for an error condition and signal failure
2795 ;; when something goes wrong.
2796 ;; Daniel Pittman <daniel@danann.net>
2797 (defun tramp-handle-file-attributes (filename &optional id-format)
2798 "Like `file-attributes' for Tramp files."
2799 (unless id-format (setq id-format 'integer))
2800 ;; Don't modify `last-coding-system-used' by accident.
2801 (let ((last-coding-system-used last-coding-system-used))
2802 (with-parsed-tramp-file-name (expand-file-name filename) nil
2803 (with-file-property v localname (format "file-attributes-%s" id-format)
2805 (tramp-convert-file-attributes
2808 ((tramp-get-remote-stat v)
2809 (tramp-do-file-attributes-with-stat v localname id-format))
2810 ((tramp-get-remote-perl v)
2811 (tramp-do-file-attributes-with-perl v localname id-format))
2813 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2815 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2816 "Implement `file-attributes' for Tramp files using the ls(1) command."
2818 res-inode res-filemodes res-numlinks
2819 res-uid res-gid res-size res-symlink-target)
2820 (tramp-message vec 5 "file attributes with ls: %s" localname)
2823 (format "(%s %s || %s -h %s) && %s %s %s"
2824 (tramp-get-file-exists-command vec)
2825 (tramp-shell-quote-argument localname)
2826 (tramp-get-test-command vec)
2827 (tramp-shell-quote-argument localname)
2828 (tramp-get-ls-command vec)
2829 (if (eq id-format 'integer) "-ildn" "-ild")
2830 (tramp-shell-quote-argument localname)))
2831 ;; parse `ls -l' output ...
2832 (with-current-buffer (tramp-get-buffer vec)
2833 (when (> (buffer-size) 0)
2834 (goto-char (point-min))
2838 (read (current-buffer))
2839 (invalid-read-syntax
2840 (when (and (equal (cadr err)
2841 "Integer constant overflow in reader")
2843 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2845 (let* ((big (read (substring (car (cddr err)) 0
2846 (match-beginning 1))))
2847 (small (read (match-string 1 (car (cddr err)))))
2848 (twiddle (/ small 65536)))
2849 (cons (+ big twiddle)
2850 (- small (* twiddle 65536))))))))
2851 ;; ... file mode flags
2852 (setq res-filemodes (symbol-name (read (current-buffer))))
2854 (setq res-numlinks (read (current-buffer)))
2856 (setq res-uid (read (current-buffer)))
2857 (setq res-gid (read (current-buffer)))
2858 (if (eq id-format 'integer)
2860 (unless (numberp res-uid) (setq res-uid -1))
2861 (unless (numberp res-gid) (setq res-gid -1)))
2863 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2864 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2866 (setq res-size (read (current-buffer)))
2867 ;; From the file modes, figure out other stuff.
2868 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2869 (setq dirp (eq ?d (aref res-filemodes 0)))
2870 ;; if symlink, find out file name pointed to
2872 (search-forward "-> ")
2873 (setq res-symlink-target
2874 (buffer-substring (point) (tramp-compat-line-end-position))))
2875 ;; return data gathered
2877 ;; 0. t for directory, string (name linked to) for symbolic
2879 (or dirp res-symlink-target)
2880 ;; 1. Number of links to file.
2886 ;; 4. Last access time, as a list of two integers. First
2887 ;; integer has high-order 16 bits of time, second has low 16
2889 ;; 5. Last modification time, likewise.
2890 ;; 6. Last status change time, likewise.
2891 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2892 ;; 7. Size in bytes (-1, if number is out of range).
2894 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2896 ;; 9. t if file's gid would change if file were deleted and
2897 ;; recreated. Will be set in `tramp-convert-file-attributes'
2899 ;; 10. inode number.
2901 ;; 11. Device number. Will be replaced by a virtual device number.
2905 (defun tramp-do-file-attributes-with-perl
2906 (vec localname &optional id-format)
2907 "Implement `file-attributes' for Tramp files using a Perl script."
2908 (tramp-message vec 5 "file attributes with perl: %s" localname)
2909 (tramp-maybe-send-script
2910 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2911 (tramp-send-command-and-read
2913 (format "tramp_perl_file_attributes %s %s"
2914 (tramp-shell-quote-argument localname) id-format)))
2916 (defun tramp-do-file-attributes-with-stat
2917 (vec localname &optional id-format)
2918 "Implement `file-attributes' for Tramp files using stat(1) command."
2919 (tramp-message vec 5 "file attributes with stat: %s" localname)
2920 (tramp-send-command-and-read
2923 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
2924 ;; parse correctly the sequence "((". Therefore, we add a space.
2925 "( (%s %s || %s -h %s) && %s -c '( (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)' %s || echo nil)"
2926 (tramp-get-file-exists-command vec)
2927 (tramp-shell-quote-argument localname)
2928 (tramp-get-test-command vec)
2929 (tramp-shell-quote-argument localname)
2930 (tramp-get-remote-stat vec)
2931 (if (eq id-format 'integer) "%u" "\"%U\"")
2932 (if (eq id-format 'integer) "%g" "\"%G\"")
2933 (tramp-shell-quote-argument localname))))
2935 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2936 "Like `set-visited-file-modtime' for Tramp files."
2937 (unless (buffer-file-name)
2938 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2941 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2942 (let ((f (buffer-file-name))
2944 (with-parsed-tramp-file-name f nil
2945 (let* ((attr (file-attributes f))
2946 ;; '(-1 65535) means file doesn't exists yet.
2947 (modtime (or (nth 5 attr) '(-1 65535))))
2948 (when (boundp 'last-coding-system-used)
2949 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2950 ;; We use '(0 0) as a don't-know value. See also
2951 ;; `tramp-do-file-attributes-with-ls'.
2952 (if (not (equal modtime '(0 0)))
2953 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2957 (format "%s -ild %s"
2958 (tramp-get-ls-command v)
2959 (tramp-shell-quote-argument localname)))
2960 (setq attr (buffer-substring (point)
2961 (progn (end-of-line) (point)))))
2962 (tramp-set-file-property
2963 v localname "visited-file-modtime-ild" attr))
2964 (when (boundp 'last-coding-system-used)
2965 (set 'last-coding-system-used coding-system-used))
2968 ;; This function makes the same assumption as
2969 ;; `tramp-handle-set-visited-file-modtime'.
2970 (defun tramp-handle-verify-visited-file-modtime (buf)
2971 "Like `verify-visited-file-modtime' for Tramp files.
2972 At the time `verify-visited-file-modtime' calls this function, we
2973 already know that the buffer is visiting a file and that
2974 `visited-file-modtime' does not return 0. Do not call this
2975 function directly, unless those two cases are already taken care
2977 (with-current-buffer buf
2978 (let ((f (buffer-file-name)))
2979 ;; There is no file visiting the buffer, or the buffer has no
2980 ;; recorded last modification time, or there is no established
2983 (eq (visited-file-modtime) 0)
2984 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
2986 (with-parsed-tramp-file-name f nil
2987 (tramp-flush-file-property v localname)
2988 (let* ((attr (file-attributes f))
2989 (modtime (nth 5 attr))
2990 (mt (visited-file-modtime)))
2993 ;; File exists, and has a known modtime.
2994 ((and attr (not (equal modtime '(0 0))))
2995 (< (abs (tramp-time-diff
2997 ;; For compatibility, deal with both the old
2998 ;; (HIGH . LOW) and the new (HIGH LOW) return
2999 ;; values of `visited-file-modtime'.
3001 (list (car mt) (cdr mt))
3004 ;; Modtime has the don't know value.
3008 (format "%s -ild %s"
3009 (tramp-get-ls-command v)
3010 (tramp-shell-quote-argument localname)))
3011 (with-current-buffer (tramp-get-buffer v)
3012 (setq attr (buffer-substring
3013 (point) (progn (end-of-line) (point)))))
3016 (tramp-get-file-property
3017 v localname "visited-file-modtime-ild" "")))
3018 ;; If file does not exist, say it is not modified if and
3019 ;; only if that agrees with the buffer's record.
3020 (t (equal mt '(-1 65535))))))))))
3022 (defun tramp-handle-set-file-modes (filename mode)
3023 "Like `set-file-modes' for Tramp files."
3024 (with-parsed-tramp-file-name filename nil
3025 (tramp-flush-file-property v localname)
3026 (unless (zerop (tramp-send-command-and-check
3028 (format "chmod %s %s"
3029 (tramp-decimal-to-octal mode)
3030 (tramp-shell-quote-argument localname))))
3031 ;; FIXME: extract the proper text from chmod's stderr.
3033 v 'file-error "Error while changing file's mode %s" filename))))
3035 (defun tramp-handle-set-file-times (filename &optional time)
3036 "Like `set-file-times' for Tramp files."
3038 (if (file-remote-p filename)
3039 (with-parsed-tramp-file-name filename nil
3040 (tramp-flush-file-property v localname)
3041 (let ((time (if (or (null time) (equal time '(0 0)))
3044 ;; With GNU Emacs, `format-time-string' has an optional
3045 ;; parameter UNIVERSAL. This is preferred, because we
3046 ;; could handle the case when the remote host is
3047 ;; located in a different time zone as the local host.
3048 (utc (not (featurep 'xemacs))))
3049 (tramp-send-command-and-check
3050 v (format "%s touch -t %s %s"
3051 (if utc "TZ=UTC; export TZ;" "")
3053 (format-time-string "%Y%m%d%H%M.%S" time t)
3054 (format-time-string "%Y%m%d%H%M.%S" time))
3055 (tramp-shell-quote-argument localname)))))
3057 ;; We handle also the local part, because in older Emacsen,
3058 ;; without `set-file-times', this function is an alias for this.
3059 ;; We are local, so we don't need the UTC settings.
3060 (tramp-local-call-process
3061 "touch" nil nil nil "-t"
3062 (format-time-string "%Y%m%d%H%M.%S" time)
3063 (tramp-shell-quote-argument filename)))))
3065 (defun tramp-set-file-uid-gid (filename &optional uid gid)
3066 "Set the ownership for FILENAME.
3067 If UID and GID are provided, these values are used; otherwise uid
3068 and gid of the corresponding user is taken. Both parameters must be integers."
3069 ;; Modern Unices allow chown only for root. So we might need
3070 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
3071 ;; working with su(do)? when it is needed, so it shall succeed in
3072 ;; the majority of cases.
3073 ;; Don't modify `last-coding-system-used' by accident.
3074 (let ((last-coding-system-used last-coding-system-used))
3075 (if (file-remote-p filename)
3076 (with-parsed-tramp-file-name filename nil
3077 (if (and (zerop (user-uid)) (tramp-local-host-p v))
3078 ;; If we are root on the local host, we can do it directly.
3079 (tramp-set-file-uid-gid localname uid gid)
3080 (let ((uid (or (and (integerp uid) uid)
3081 (tramp-get-remote-uid v 'integer)))
3082 (gid (or (and (integerp gid) gid)
3083 (tramp-get-remote-gid v 'integer))))
3086 "chown %d:%d %s" uid gid
3087 (tramp-shell-quote-argument localname))))))
3089 ;; We handle also the local part, because there doesn't exist
3090 ;; `set-file-uid-gid'. On W32 "chown" might not work.
3091 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
3092 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
3093 (tramp-local-call-process
3095 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
3097 (defun tramp-remote-selinux-p (vec)
3098 "Check, whether SELINUX is enabled on the remote host."
3099 (with-connection-property (tramp-get-connection-process vec) "selinux-p"
3100 (let ((result (tramp-find-executable
3101 vec "getenforce" (tramp-get-remote-path vec) t t)))
3104 (tramp-send-command-and-read
3105 vec (format "echo \\\"`%S`\\\"" result))
3108 (defun tramp-handle-file-selinux-context (filename)
3109 "Like `file-selinux-context' for Tramp files."
3110 (with-parsed-tramp-file-name filename nil
3111 (with-file-property v localname "file-selinux-context"
3112 (let ((context '(nil nil nil nil))
3113 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
3114 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
3115 (when (and (tramp-remote-selinux-p v)
3116 (zerop (tramp-send-command-and-check
3119 (tramp-get-ls-command v)
3120 (tramp-shell-quote-argument localname)))))
3121 (with-current-buffer (tramp-get-connection-buffer v)
3122 (goto-char (point-min))
3123 (when (re-search-forward regexp (tramp-compat-line-end-position) t)
3124 (setq context (list (match-string 1) (match-string 2)
3125 (match-string 3) (match-string 4))))))
3126 ;; Return the context.
3129 (defun tramp-handle-set-file-selinux-context (filename context)
3130 "Like `set-file-selinux-context' for Tramp files."
3131 (with-parsed-tramp-file-name filename nil
3132 (if (and (consp context)
3133 (tramp-remote-selinux-p v)
3134 (zerop (tramp-send-command-and-check
3135 v (format "chcon %s %s %s %s %s"
3136 (if (stringp (nth 0 context))
3137 (format "--user=%s" (nth 0 context)) "")
3138 (if (stringp (nth 1 context))
3139 (format "--role=%s" (nth 1 context)) "")
3140 (if (stringp (nth 2 context))
3141 (format "--type=%s" (nth 2 context)) "")
3142 (if (stringp (nth 3 context))
3143 (format "--range=%s" (nth 3 context)) "")
3144 (tramp-shell-quote-argument localname)))))
3145 (tramp-set-file-property v localname "file-selinux-context" context)
3146 (tramp-set-file-property v localname "file-selinux-context" 'undef)))
3147 ;; We always return nil.
3150 ;; Simple functions using the `test' command.
3152 (defun tramp-handle-file-executable-p (filename)
3153 "Like `file-executable-p' for Tramp files."
3154 (with-parsed-tramp-file-name filename nil
3155 (with-file-property v localname "file-executable-p"
3156 ;; Examine `file-attributes' cache to see if request can be
3157 ;; satisfied without remote operation.
3158 (or (tramp-check-cached-permissions v ?x)
3159 (zerop (tramp-run-test "-x" filename))))))
3161 (defun tramp-handle-file-readable-p (filename)
3162 "Like `file-readable-p' for Tramp files."
3163 (with-parsed-tramp-file-name filename nil
3164 (with-file-property v localname "file-readable-p"
3165 ;; Examine `file-attributes' cache to see if request can be
3166 ;; satisfied without remote operation.
3167 (or (tramp-check-cached-permissions v ?r)
3168 (zerop (tramp-run-test "-r" filename))))))
3170 ;; When the remote shell is started, it looks for a shell which groks
3171 ;; tilde expansion. Here, we assume that all shells which grok tilde
3172 ;; expansion will also provide a `test' command which groks `-nt' (for
3173 ;; newer than). If this breaks, tell me about it and I'll try to do
3174 ;; something smarter about it.
3175 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3176 "Like `file-newer-than-file-p' for Tramp files."
3177 (cond ((not (file-exists-p file1))
3179 ((not (file-exists-p file2))
3181 ;; We are sure both files exist at this point.
3184 ;; We try to get the mtime of both files. If they are not
3185 ;; equal to the "dont-know" value, then we subtract the times
3186 ;; and obtain the result.
3187 (let ((fa1 (file-attributes file1))
3188 (fa2 (file-attributes file2)))
3189 (if (and (not (equal (nth 5 fa1) '(0 0)))
3190 (not (equal (nth 5 fa2) '(0 0))))
3191 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3192 ;; If one of them is the dont-know value, then we can
3193 ;; still try to run a shell command on the remote host.
3194 ;; However, this only works if both files are Tramp
3195 ;; files and both have the same method, same user, same
3197 (unless (tramp-equal-remote file1 file2)
3198 (with-parsed-tramp-file-name
3199 (if (tramp-tramp-file-p file1) file1 file2) nil
3202 "Files %s and %s must have same method, user, host"
3204 (with-parsed-tramp-file-name file1 nil
3205 (zerop (tramp-run-test2
3206 (tramp-get-test-nt-command v) file1 file2)))))))))
3208 ;; Functions implemented using the basic functions above.
3210 (defun tramp-handle-file-modes (filename)
3211 "Like `file-modes' for Tramp files."
3212 (let ((truename (or (file-truename filename) filename)))
3213 (when (file-exists-p truename)
3214 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3216 (defun tramp-default-file-modes (filename)
3217 "Return file modes of FILENAME as integer.
3218 If the file modes of FILENAME cannot be determined, return the
3219 value of `default-file-modes', without execute permissions."
3220 (or (file-modes filename)
3221 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3223 (defun tramp-handle-file-directory-p (filename)
3224 "Like `file-directory-p' for Tramp files."
3225 ;; Care must be taken that this function returns `t' for symlinks
3226 ;; pointing to directories. Surely the most obvious implementation
3227 ;; would be `test -d', but that returns false for such symlinks.
3228 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3229 ;; I now think he's right. So we could be using `test -d', couldn't
3232 ;; Alternatives: `cd %s', `test -d %s'
3233 (with-parsed-tramp-file-name filename nil
3234 (with-file-property v localname "file-directory-p"
3235 (zerop (tramp-run-test "-d" filename)))))
3237 (defun tramp-handle-file-regular-p (filename)
3238 "Like `file-regular-p' for Tramp files."
3239 (and (file-exists-p filename)
3240 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3242 (defun tramp-handle-file-symlink-p (filename)
3243 "Like `file-symlink-p' for Tramp files."
3244 (with-parsed-tramp-file-name filename nil
3245 (let ((x (car (file-attributes filename))))
3247 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3248 ;; might do weird things.
3249 (if (file-name-absolute-p x)
3250 (tramp-make-tramp-file-name method user host x)
3253 (defun tramp-handle-file-writable-p (filename)
3254 "Like `file-writable-p' for Tramp files."
3255 (with-parsed-tramp-file-name filename nil
3256 (with-file-property v localname "file-writable-p"
3257 (if (file-exists-p filename)
3258 ;; Examine `file-attributes' cache to see if request can be
3259 ;; satisfied without remote operation.
3260 (or (tramp-check-cached-permissions v ?w)
3261 (zerop (tramp-run-test "-w" filename)))
3262 ;; If file doesn't exist, check if directory is writable.
3263 (and (zerop (tramp-run-test
3264 "-d" (file-name-directory filename)))
3265 (zerop (tramp-run-test
3266 "-w" (file-name-directory filename))))))))
3268 (defun tramp-handle-file-ownership-preserved-p (filename)
3269 "Like `file-ownership-preserved-p' for Tramp files."
3270 (with-parsed-tramp-file-name filename nil
3271 (with-file-property v localname "file-ownership-preserved-p"
3272 (let ((attributes (file-attributes filename)))
3273 ;; Return t if the file doesn't exist, since it's true that no
3274 ;; information would be lost by an (attempted) delete and create.
3275 (or (null attributes)
3276 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3278 ;; Other file name ops.
3280 (defun tramp-handle-directory-file-name (directory)
3281 "Like `directory-file-name' for Tramp files."
3282 ;; If localname component of filename is "/", leave it unchanged.
3283 ;; Otherwise, remove any trailing slash from localname component.
3284 ;; Method, host, etc, are unchanged. Does it make sense to try
3285 ;; to avoid parsing the filename?
3286 (with-parsed-tramp-file-name directory nil
3287 (if (and (not (zerop (length localname)))
3288 (eq (aref localname (1- (length localname))) ?/)
3289 (not (string= localname "/")))
3290 (substring directory 0 -1)
3293 ;; Directory listings.
3295 (defun tramp-handle-directory-files
3296 (directory &optional full match nosort files-only)
3297 "Like `directory-files' for Tramp files."
3298 ;; FILES-ONLY is valid for XEmacs only.
3299 (when (file-directory-p directory)
3300 (setq directory (file-name-as-directory (expand-file-name directory)))
3301 (let ((temp (nreverse (file-name-all-completions "" directory)))
3305 (setq item (directory-file-name (pop temp)))
3306 (when (and (or (null match) (string-match match item))
3307 (or (null files-only)
3309 (and (equal files-only t) (file-regular-p item))
3310 ;; Directories only.
3311 (file-directory-p item)))
3312 (push (if full (concat directory item) item)
3314 (if nosort result (sort result 'string<)))))
3316 (defun tramp-handle-directory-files-and-attributes
3317 (directory &optional full match nosort id-format)
3318 "Like `directory-files-and-attributes' for Tramp files."
3319 (unless id-format (setq id-format 'integer))
3320 (when (file-directory-p directory)
3321 (setq directory (expand-file-name directory))
3324 (with-parsed-tramp-file-name directory nil
3327 (format "directory-files-and-attributes-%s" id-format)
3332 (tramp-convert-file-attributes v (cdr x))))
3334 ((tramp-get-remote-stat v)
3335 (tramp-do-directory-files-and-attributes-with-stat
3336 v localname id-format))
3337 ((tramp-get-remote-perl v)
3338 (tramp-do-directory-files-and-attributes-with-perl
3339 v localname id-format)))))))))
3343 (setq item (pop temp))
3344 (when (or (null match) (string-match match (car item)))
3346 (setcar item (expand-file-name (car item) directory)))
3347 (push item result)))
3351 (sort result (lambda (x y) (string< (car x) (car y))))))))
3353 (defun tramp-do-directory-files-and-attributes-with-perl
3354 (vec localname &optional id-format)
3355 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3356 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3357 (tramp-maybe-send-script
3358 vec tramp-perl-directory-files-and-attributes
3359 "tramp_perl_directory_files_and_attributes")
3361 (tramp-send-command-and-read
3363 (format "tramp_perl_directory_files_and_attributes %s %s"
3364 (tramp-shell-quote-argument localname) id-format))))
3365 (when (stringp object) (tramp-error vec 'file-error object))
3368 (defun tramp-do-directory-files-and-attributes-with-stat
3369 (vec localname &optional id-format)
3370 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3371 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3372 (tramp-send-command-and-read
3376 ;; We must care about filenames with spaces, or starting with
3377 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3378 ;; but it does not work on all remote systems. Therefore, we
3379 ;; quote the filenames via sed.
3380 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3381 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)'); "
3383 (tramp-shell-quote-argument localname)
3384 (tramp-get-ls-command vec)
3385 (tramp-get-remote-stat vec)
3386 (if (eq id-format 'integer) "%u" "\"%U\"")
3387 (if (eq id-format 'integer) "%g" "\"%G\""))))
3389 ;; This function should return "foo/" for directories and "bar" for
3391 (defun tramp-handle-file-name-all-completions (filename directory)
3392 "Like `file-name-all-completions' for Tramp files."
3393 (unless (save-match-data (string-match "/" filename))
3394 (with-parsed-tramp-file-name (expand-file-name directory) nil
3403 ;; Ignore if expired
3404 (or (not (integerp tramp-completion-reread-directory-timeout))
3405 (<= (tramp-time-diff
3407 (tramp-get-file-property
3408 v localname "last-completion" '(0 0 0)))
3409 tramp-completion-reread-directory-timeout))
3411 ;; Try cache entries for filename, filename with last
3412 ;; character removed, filename with last two characters
3413 ;; removed, ..., and finally the empty string - all
3414 ;; concatenated to the local directory name
3416 ;; This is inefficient for very long filenames, pity
3417 ;; `reduce' is not available...
3424 (tramp-get-file-property
3426 (concat localname (substring filename 0 x))
3427 "file-name-all-completions"
3429 (when cache-hit (list cache-hit))))
3430 (tramp-compat-number-sequence (length filename) 0 -1)))))
3432 ;; Cache expired or no matching cache entry found so we need
3433 ;; to perform a remote operation
3435 ;; Get a list of directories and files, including reliably
3436 ;; tagging the directories with a trailing '/'. Because I
3437 ;; rock. --daniel@danann.net
3439 ;; Changed to perform `cd' in the same remote op and only
3440 ;; get entries starting with `filename'. Capture any `cd'
3441 ;; error messages. Ensure any `cd' and `echo' aliases are
3445 (if (tramp-get-remote-perl v)
3447 (tramp-maybe-send-script
3448 v tramp-perl-file-name-all-completions
3449 "tramp_perl_file_name_all_completions")
3450 (format "tramp_perl_file_name_all_completions %s %s %d"
3451 (tramp-shell-quote-argument localname)
3452 (tramp-shell-quote-argument filename)
3454 ;; `read-file-name-completion-ignore-case'
3455 ;; is introduced with Emacs 22.1.
3457 'read-file-name-completion-ignore-case)
3458 'read-file-name-completion-ignore-case
3459 'completion-ignore-case))
3463 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3464 ;; `ls' with wildcard might fail with `Argument
3465 ;; list too long' error in some corner cases; if
3466 ;; `ls' fails after `cd' succeeded, chances are
3467 ;; that's the case, so let's retry without
3468 ;; wildcard. This will return "too many" entries
3469 ;; but that isn't harmful.
3470 " || %s -a 2>/dev/null)"
3471 " | while read f; do"
3472 " if %s -d \"$f\" 2>/dev/null;"
3473 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3474 " && \\echo ok) || \\echo fail")
3475 (tramp-shell-quote-argument localname)
3476 (tramp-get-ls-command v)
3477 ;; When `filename' is empty, just `ls' without
3478 ;; filename argument is more efficient than `ls *'
3479 ;; for very large directories and might avoid the
3480 ;; `Argument list too long' error.
3482 ;; With and only with wildcard, we need to add
3483 ;; `-d' to prevent `ls' from descending into
3485 (if (zerop (length filename))
3487 (concat (tramp-shell-quote-argument filename) "* -d"))
3488 (tramp-get-ls-command v)
3489 (tramp-get-test-command v))))
3491 ;; Now grab the output.
3492 (with-current-buffer (tramp-get-buffer v)
3493 (goto-char (point-max))
3495 ;; Check result code, found in last line of output
3497 (if (looking-at "^fail$")
3499 ;; Grab error message from line before last line
3500 ;; (it was put there by `cd 2>&1')
3504 "tramp-handle-file-name-all-completions: %s"
3506 (point) (tramp-compat-line-end-position))))
3507 ;; For peace of mind, if buffer doesn't end in `fail'
3508 ;; then it should end in `ok'. If neither are in the
3509 ;; buffer something went seriously wrong on the remote
3511 (unless (looking-at "^ok$")
3515 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3516 (tramp-shell-quote-argument localname) (buffer-string))))
3518 (while (zerop (forward-line -1))
3519 (push (buffer-substring
3520 (point) (tramp-compat-line-end-position))
3523 ;; Because the remote op went through OK we know the
3524 ;; directory we `cd'-ed to exists
3525 (tramp-set-file-property
3526 v localname "file-exists-p" t)
3528 ;; Because the remote op went through OK we know every
3529 ;; file listed by `ls' exists.
3530 (mapc (lambda (entry)
3531 (tramp-set-file-property
3532 v (concat localname entry) "file-exists-p" t))
3535 (tramp-set-file-property
3536 v localname "last-completion" (current-time))
3538 ;; Store result in the cache
3539 (tramp-set-file-property
3540 v (concat localname filename)
3541 "file-name-all-completions"
3544 (defun tramp-handle-file-name-completion
3545 (filename directory &optional predicate)
3546 "Like `file-name-completion' for Tramp files."
3547 (unless (tramp-tramp-file-p directory)
3549 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3553 (mapcar 'list (file-name-all-completions filename directory))
3555 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3559 (defun tramp-handle-add-name-to-file
3560 (filename newname &optional ok-if-already-exists)
3561 "Like `add-name-to-file' for Tramp files."
3562 (unless (tramp-equal-remote filename newname)
3563 (with-parsed-tramp-file-name
3564 (if (tramp-tramp-file-p filename) filename newname) nil
3567 "add-name-to-file: %s"
3568 "only implemented for same method, same user, same host")))
3569 (with-parsed-tramp-file-name filename v1
3570 (with-parsed-tramp-file-name newname v2
3571 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3572 (when (and (not ok-if-already-exists)
3573 (file-exists-p newname)
3574 (not (numberp ok-if-already-exists))
3577 "File %s already exists; make it a new name anyway? "
3581 "add-name-to-file: file %s already exists" newname))
3582 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3583 (tramp-flush-file-property v2 v2-localname)
3584 (tramp-barf-unless-okay
3586 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3587 (tramp-shell-quote-argument v2-localname))
3588 "error with add-name-to-file, see buffer `%s' for details"
3591 (defun tramp-handle-copy-file
3592 (filename newname &optional ok-if-already-exists keep-date
3593 preserve-uid-gid preserve-selinux-context)
3594 "Like `copy-file' for Tramp files."
3595 (setq filename (expand-file-name filename))
3596 (setq newname (expand-file-name newname))
3598 ;; At least one file a Tramp file?
3599 ((or (tramp-tramp-file-p filename)
3600 (tramp-tramp-file-p newname))
3601 (tramp-do-copy-or-rename-file
3602 'copy filename newname ok-if-already-exists keep-date
3603 preserve-uid-gid preserve-selinux-context))
3605 (preserve-selinux-context
3606 (tramp-run-real-handler
3608 (list filename newname ok-if-already-exists keep-date
3609 preserve-uid-gid preserve-selinux-context)))
3611 (tramp-run-real-handler
3613 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3615 (tramp-run-real-handler
3616 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3618 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3619 "Like `copy-directory' for Tramp files."
3620 (let ((t1 (tramp-tramp-file-p dirname))
3621 (t2 (tramp-tramp-file-p newname)))
3622 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3623 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3624 ;; When DIRNAME and NEWNAME are remote, they must have
3626 (or (null t1) (null t2)
3628 (tramp-file-name-method (tramp-dissect-file-name dirname))
3629 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3630 ;; scp or rsync DTRT.
3632 (setq dirname (directory-file-name (expand-file-name dirname))
3633 newname (directory-file-name (expand-file-name newname)))
3634 (if (and (file-directory-p newname)
3635 (not (string-equal (file-name-nondirectory dirname)
3636 (file-name-nondirectory newname))))
3639 (file-name-nondirectory dirname) newname)))
3640 (if (not (file-directory-p (file-name-directory newname)))
3641 (make-directory (file-name-directory newname) parents))
3642 (tramp-do-copy-or-rename-file-out-of-band
3643 'copy dirname newname keep-date))
3644 ;; We must do it file-wise.
3645 (tramp-run-real-handler
3646 'copy-directory (list dirname newname keep-date parents)))
3648 ;; When newname did exist, we have wrong cached values.
3650 (with-parsed-tramp-file-name newname nil
3651 (tramp-flush-file-property v (file-name-directory localname))
3652 (tramp-flush-file-property v localname))))))
3654 (defun tramp-handle-rename-file
3655 (filename newname &optional ok-if-already-exists)
3656 "Like `rename-file' for Tramp files."
3657 ;; Check if both files are local -- invoke normal rename-file.
3658 ;; Otherwise, use Tramp from local system.
3659 (setq filename (expand-file-name filename))
3660 (setq newname (expand-file-name newname))
3661 ;; At least one file a Tramp file?
3662 (if (or (tramp-tramp-file-p filename)
3663 (tramp-tramp-file-p newname))
3664 (tramp-do-copy-or-rename-file
3665 'rename filename newname ok-if-already-exists t t)
3666 (tramp-run-real-handler
3667 'rename-file (list filename newname ok-if-already-exists))))
3669 (defun tramp-do-copy-or-rename-file
3670 (op filename newname &optional ok-if-already-exists keep-date
3671 preserve-uid-gid preserve-selinux-context)
3672 "Copy or rename a remote file.
3673 OP must be `copy' or `rename' and indicates the operation to perform.
3674 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3675 the new file (for copy) or the new name of the file (for rename).
3676 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3677 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3678 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3679 the uid and gid if both files are on the same host.
3680 PRESERVE-SELINUX-CONTEXT activates selinux commands.
3682 This function is invoked by `tramp-handle-copy-file' and
3683 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3684 and `rename'. FILENAME and NEWNAME must be absolute file names."
3685 (unless (memq op '(copy rename))
3686 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3687 (let ((t1 (tramp-tramp-file-p filename))
3688 (t2 (tramp-tramp-file-p newname))
3689 (context (and preserve-selinux-context
3690 (apply 'file-selinux-context (list filename))))
3693 (with-parsed-tramp-file-name (if t1 filename newname) nil
3694 (when (and (not ok-if-already-exists) (file-exists-p newname))
3696 v 'file-already-exists "File %s already exists" newname))
3698 (with-progress-reporter
3699 v 0 (format "%s %s to %s"
3700 (if (eq op 'copy) "Copying" "Renaming")
3704 ;; Both are Tramp files.
3706 (with-parsed-tramp-file-name filename v1
3707 (with-parsed-tramp-file-name newname v2
3709 ;; Shortcut: if method, host, user are the same for
3710 ;; both files, we invoke `cp' or `mv' on the remote
3712 ((tramp-equal-remote filename newname)
3713 (tramp-do-copy-or-rename-file-directly
3715 ok-if-already-exists keep-date preserve-uid-gid))
3717 ;; Try out-of-band operation.
3718 ((tramp-method-out-of-band-p
3719 v1 (nth 7 (file-attributes filename)))
3720 (tramp-do-copy-or-rename-file-out-of-band
3721 op filename newname keep-date))
3723 ;; No shortcut was possible. So we copy the file
3724 ;; first. If the operation was `rename', we go back
3725 ;; and delete the original file (if the copy was
3726 ;; successful). The approach is simple-minded: we
3727 ;; create a new buffer, insert the contents of the
3728 ;; source file into it, then write out the buffer to
3729 ;; the target file. The advantage is that it doesn't
3730 ;; matter which filename handlers are used for the
3731 ;; source and target file.
3733 (tramp-do-copy-or-rename-file-via-buffer
3734 op filename newname keep-date))))))
3736 ;; One file is a Tramp file, the other one is local.
3739 ;; Fast track on local machine.
3740 ((tramp-local-host-p v)
3741 (tramp-do-copy-or-rename-file-directly
3743 ok-if-already-exists keep-date preserve-uid-gid))
3745 ;; If the Tramp file has an out-of-band method, the
3746 ;; corresponding copy-program can be invoked.
3747 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3748 (tramp-do-copy-or-rename-file-out-of-band
3749 op filename newname keep-date))
3751 ;; Use the inline method via a Tramp buffer.
3752 (t (tramp-do-copy-or-rename-file-via-buffer
3753 op filename newname keep-date))))
3756 ;; One of them must be a Tramp file.
3757 (error "Tramp implementation says this cannot happen")))
3759 ;; Handle `preserve-selinux-context'.
3760 (when context (apply 'set-file-selinux-context (list newname context)))
3762 ;; In case of `rename', we must flush the cache of the source file.
3763 (when (and t1 (eq op 'rename))
3764 (with-parsed-tramp-file-name filename v1
3765 (tramp-flush-file-property v1 (file-name-directory localname))
3766 (tramp-flush-file-property v1 localname)))
3768 ;; When newname did exist, we have wrong cached values.
3770 (with-parsed-tramp-file-name newname v2
3771 (tramp-flush-file-property v2 (file-name-directory localname))
3772 (tramp-flush-file-property v2 localname)))))))
3774 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3775 "Use an Emacs buffer to copy or rename a file.
3776 First arg OP is either `copy' or `rename' and indicates the operation.
3777 FILENAME is the source file, NEWNAME the target file.
3778 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3780 ;; We must disable multibyte, because binary data shall not be
3782 (set-buffer-multibyte nil)
3783 (let ((coding-system-for-read 'binary)
3784 (jka-compr-inhibit t))
3785 (insert-file-contents-literally filename))
3786 ;; We don't want the target file to be compressed, so we let-bind
3787 ;; `jka-compr-inhibit' to t.
3788 (let ((coding-system-for-write 'binary)
3789 (jka-compr-inhibit t))
3790 (write-region (point-min) (point-max) newname)))
3791 ;; KEEP-DATE handling.
3792 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3794 (set-file-modes newname (tramp-default-file-modes filename))
3795 ;; If the operation was `rename', delete the original file.
3796 (unless (eq op 'copy) (delete-file filename)))
3798 (defun tramp-do-copy-or-rename-file-directly
3799 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3800 "Invokes `cp' or `mv' on the remote system.
3801 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3802 respectively. FILENAME specifies the file to copy or rename,
3803 NEWNAME is the name of the new file (for copy) or the new name of
3804 the file (for rename). Both files must reside on the same host.
3805 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3806 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3807 the uid and gid from FILENAME."
3808 (let ((t1 (tramp-tramp-file-p filename))
3809 (t2 (tramp-tramp-file-p newname))
3810 (file-times (nth 5 (file-attributes filename)))
3811 (file-modes (tramp-default-file-modes filename)))
3812 (with-parsed-tramp-file-name (if t1 filename newname) nil
3813 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3814 ((eq op 'copy) "cp -f")
3815 ((eq op 'rename) "mv -f")
3818 "Unknown operation `%s', must be `copy' or `rename'"
3822 (tramp-file-name-handler 'file-remote-p filename 'localname)
3826 (tramp-file-name-handler 'file-remote-p newname 'localname)
3828 (prefix (file-remote-p (if t1 filename newname)))
3832 ;; Both files are on a remote host, with same user.
3835 (tramp-send-command-and-check
3837 (format "%s %s %s" cmd
3838 (tramp-shell-quote-argument localname1)
3839 (tramp-shell-quote-argument localname2))))
3840 (with-current-buffer (tramp-get-buffer v)
3841 (goto-char (point-min))
3845 ;; Mask cp -f error.
3847 tramp-operation-not-permitted-regexp nil t))
3849 (tramp-error-with-buffer
3851 "Copying directly failed, see buffer `%s' for details."
3854 ;; We are on the local host.
3857 ;; We can do it directly.
3858 ((let (file-name-handler-alist)
3859 (and (file-readable-p localname1)
3860 (file-writable-p (file-name-directory localname2))
3861 (or (file-directory-p localname2)
3862 (file-writable-p localname2))))
3864 (tramp-compat-copy-file
3865 localname1 localname2 ok-if-already-exists
3866 keep-date preserve-uid-gid)
3867 (tramp-run-real-handler
3868 'rename-file (list localname1 localname2 ok-if-already-exists))))
3870 ;; We can do it directly with `tramp-send-command'
3871 ((and (file-readable-p (concat prefix localname1))
3873 (file-name-directory (concat prefix localname2)))
3874 (or (file-directory-p (concat prefix localname2))
3875 (file-writable-p (concat prefix localname2))))
3876 (tramp-do-copy-or-rename-file-directly
3877 op (concat prefix localname1) (concat prefix localname2)
3878 ok-if-already-exists keep-date t)
3879 ;; We must change the ownership to the local user.
3880 (tramp-set-file-uid-gid
3881 (concat prefix localname2)
3882 (tramp-get-local-uid 'integer)
3883 (tramp-get-local-gid 'integer)))
3885 ;; We need a temporary file in between.
3887 ;; Create the temporary file.
3888 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3895 (tramp-send-command-and-check
3898 (tramp-shell-quote-argument localname1)
3899 (tramp-shell-quote-argument tmpfile))))
3900 (tramp-error-with-buffer
3902 "Copying directly failed, see buffer `%s' for details."
3903 (tramp-get-buffer v)))
3904 ;; We must change the ownership as remote user.
3905 ;; Since this does not work reliable, we also
3906 ;; give read permissions.
3908 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3909 (tramp-set-file-uid-gid
3910 (concat prefix tmpfile)
3911 (tramp-get-local-uid 'integer)
3912 (tramp-get-local-gid 'integer)))
3915 (tramp-compat-copy-file
3916 localname1 tmpfile t
3917 keep-date preserve-uid-gid)
3918 (tramp-run-real-handler
3920 (list localname1 tmpfile t)))
3921 ;; We must change the ownership as local user.
3922 ;; Since this does not work reliable, we also
3923 ;; give read permissions.
3924 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3925 (tramp-set-file-uid-gid
3927 (tramp-get-remote-uid v 'integer)
3928 (tramp-get-remote-gid v 'integer))))
3930 ;; Move the temporary file to its destination.
3935 (tramp-send-command-and-check
3938 (tramp-shell-quote-argument tmpfile)
3939 (tramp-shell-quote-argument localname2))))
3940 (tramp-error-with-buffer
3942 "Copying directly failed, see buffer `%s' for details."
3943 (tramp-get-buffer v))))
3945 (tramp-run-real-handler
3947 (list tmpfile localname2 ok-if-already-exists)))))
3951 (delete-file tmpfile)
3954 ;; Set the time and mode. Mask possible errors.
3957 (set-file-times newname file-times)
3958 (set-file-modes newname file-modes))
3961 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3962 "Invoke rcp program to copy.
3963 The method used must be an out-of-band method."
3964 (let ((t1 (tramp-tramp-file-p filename))
3965 (t2 (tramp-tramp-file-p newname))
3966 copy-program copy-args copy-env copy-keep-date port spec
3969 (with-parsed-tramp-file-name (if t1 filename newname) nil
3972 ;; Both are Tramp files. We shall optimize it, when the
3973 ;; methods for filename and newname are the same.
3974 (let* ((dir-flag (file-directory-p filename))
3975 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3979 (file-name-nondirectory newname) tmpfile)))
3982 (tramp-do-copy-or-rename-file-out-of-band
3983 op filename tmpfile keep-date)
3984 (tramp-do-copy-or-rename-file-out-of-band
3985 'rename tmpfile newname keep-date))
3989 (tramp-compat-delete-directory
3990 (expand-file-name ".." tmpfile) 'recursive)
3991 (delete-file tmpfile))
3994 ;; Expand hops. Might be necessary for gateway methods.
3995 (setq v (car (tramp-compute-multi-hops v)))
3996 (aset v 3 localname)
3998 ;; Check which ones of source and target are Tramp files.
3999 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
4001 (if (and (file-directory-p filename)
4003 (file-name-nondirectory filename)
4004 (file-name-nondirectory newname)))
4005 'file-name-directory
4007 (if t2 (tramp-make-copy-program-file-name v) newname)))
4009 ;; Check for port number. Until now, there's no need for handling
4010 ;; like method, user, host.
4011 (setq host (tramp-file-name-real-host v)
4012 port (tramp-file-name-port v)
4013 port (or (and port (number-to-string port)) ""))
4015 ;; Compose copy command.
4016 (setq spec (format-spec-make
4017 ?h host ?u user ?p port
4018 ?t (tramp-get-connection-property
4019 (tramp-get-connection-process v) "temp-file" "")
4020 ?k (if keep-date " " ""))
4021 copy-program (tramp-get-method-parameter
4022 method 'tramp-copy-program)
4023 copy-keep-date (tramp-get-method-parameter
4024 method 'tramp-copy-keep-date)
4032 ;; " " is indication for keep-date argument.
4033 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
4034 (unless (member "" x) (mapconcat 'identity x " ")))
4035 (tramp-get-method-parameter method 'tramp-copy-args)))
4041 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4042 (unless (member "" x) (mapconcat 'identity x " ")))
4043 (tramp-get-method-parameter method 'tramp-copy-env))))
4045 ;; Check for program.
4046 (when (and (fboundp 'executable-find)
4047 (not (let ((default-directory
4048 (tramp-compat-temporary-file-directory)))
4049 (executable-find copy-program))))
4051 v 'file-error "Cannot find copy program: %s" copy-program))
4053 ;; Set variables for computing the prompt for reading
4055 (setq tramp-current-method (tramp-file-name-method v)
4056 tramp-current-user (tramp-file-name-user v)
4057 tramp-current-host (tramp-file-name-host v))
4061 ;; The default directory must be remote.
4062 (let ((default-directory
4063 (file-name-directory (if t1 filename newname)))
4064 (process-environment (copy-sequence process-environment)))
4065 ;; Set the transfer process properties.
4066 (tramp-set-connection-property
4067 v "process-name" (buffer-name (current-buffer)))
4068 (tramp-set-connection-property
4069 v "process-buffer" (current-buffer))
4071 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
4072 (setenv (pop copy-env) (pop copy-env)))
4074 ;; Use an asynchronous process. By this, password can
4075 ;; be handled. The default directory must be local, in
4076 ;; order to apply the correct `copy-program'. We don't
4077 ;; set a timeout, because the copying of large files can
4078 ;; last longer than 60 secs.
4079 (let ((p (let ((default-directory
4080 (tramp-compat-temporary-file-directory)))
4081 (apply 'start-process
4082 (tramp-get-connection-property
4083 v "process-name" nil)
4084 (tramp-get-connection-property
4085 v "process-buffer" nil)
4087 (append copy-args (list source target))))))
4089 v 6 "%s" (mapconcat 'identity (process-command p) " "))
4090 (tramp-set-process-query-on-exit-flag p nil)
4091 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
4093 ;; Reset the transfer process properties.
4094 (tramp-set-connection-property v "process-name" nil)
4095 (tramp-set-connection-property v "process-buffer" nil))
4097 ;; Handle KEEP-DATE argument.
4098 (when (and keep-date (not copy-keep-date))
4099 (set-file-times newname (nth 5 (file-attributes filename))))
4102 (unless (and keep-date copy-keep-date)
4104 (set-file-modes newname (tramp-default-file-modes filename)))))
4106 ;; If the operation was `rename', delete the original file.
4107 (unless (eq op 'copy)
4108 (if (file-regular-p filename)
4109 (delete-file filename)
4110 (tramp-compat-delete-directory filename 'recursive))))))
4112 (defun tramp-handle-make-directory (dir &optional parents)
4113 "Like `make-directory' for Tramp files."
4114 (setq dir (expand-file-name dir))
4115 (with-parsed-tramp-file-name dir nil
4116 (tramp-flush-directory-property v (file-name-directory localname))
4118 (tramp-barf-unless-okay
4121 (if parents "mkdir -p" "mkdir")
4122 (tramp-shell-quote-argument localname))
4123 "Couldn't make directory %s" dir))))
4125 (defun tramp-handle-delete-directory (directory &optional recursive)
4126 "Like `delete-directory' for Tramp files."
4127 (setq directory (expand-file-name directory))
4128 (with-parsed-tramp-file-name directory nil
4129 (tramp-flush-file-property v (file-name-directory localname))
4130 (tramp-flush-directory-property v localname)
4131 (unless (zerop (tramp-send-command-and-check
4135 (if recursive "rm -rf" "rmdir")
4136 (tramp-shell-quote-argument localname))))
4137 (tramp-error v 'file-error "Couldn't delete %s" directory))))
4139 (defun tramp-handle-delete-file (filename &optional trash)
4140 "Like `delete-file' for Tramp files."
4141 (setq filename (expand-file-name filename))
4142 (with-parsed-tramp-file-name filename nil
4143 (tramp-flush-file-property v (file-name-directory localname))
4144 (tramp-flush-file-property v localname)
4147 (tramp-send-command-and-check
4149 (or (and trash (tramp-get-remote-trash v)) "rm -f")
4150 (tramp-shell-quote-argument localname))))
4151 (tramp-error v 'file-error "Couldn't delete %s" filename))))
4155 ;; CCC: This does not seem to be enough. Something dies when
4156 ;; we try and delete two directories under Tramp :/
4157 (defun tramp-handle-dired-recursive-delete-directory (filename)
4158 "Recursively delete the directory given.
4159 This is like `dired-recursive-delete-directory' for Tramp files."
4160 (with-parsed-tramp-file-name filename nil
4161 ;; Run a shell command 'rm -r <localname>'
4162 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
4163 (unless (file-exists-p filename)
4164 (tramp-error v 'file-error "No such directory: %s" filename))
4165 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
4168 (format "rm -rf %s" (tramp-shell-quote-argument localname))
4169 ;; Don't read the output, do it explicitely.
4171 ;; Wait for the remote system to return to us...
4172 ;; This might take a while, allow it plenty of time.
4173 (tramp-wait-for-output (tramp-get-connection-process v) 120)
4174 ;; Make sure that it worked...
4175 (tramp-flush-file-property v (file-name-directory localname))
4176 (tramp-flush-directory-property v localname)
4177 (and (file-exists-p filename)
4179 v 'file-error "Failed to recursively delete %s" filename))))
4181 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4182 "Like `dired-compress-file' for Tramp files."
4183 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4184 ;; Code stolen mainly from dired-aux.el.
4185 (with-parsed-tramp-file-name file nil
4186 (tramp-flush-file-property v localname)
4189 (if (not (featurep 'xemacs))
4191 (symbol-value 'dired-compress-file-suffixes)
4192 ;; XEmacs has `dired-compression-method-alist', which is
4193 ;; transformed into `dired-compress-file-suffixes' structure.
4196 (list (concat (regexp-quote (nth 1 x)) "\\'")
4198 (mapconcat 'identity (nth 3 x) " ")))
4199 (symbol-value 'dired-compression-method-alist))))
4201 ;; See if any suffix rule matches this file name.
4203 (let (case-fold-search)
4204 (if (string-match (car (car suffixes)) localname)
4205 (setq suffix (car suffixes) suffixes nil))
4206 (setq suffixes (cdr suffixes))))
4208 (cond ((file-symlink-p file)
4210 ((and suffix (nth 2 suffix))
4211 ;; We found an uncompression rule.
4212 (with-progress-reporter v 0 (format "Uncompressing %s" file)
4214 (tramp-send-command-and-check
4215 v (concat (nth 2 suffix) " "
4216 (tramp-shell-quote-argument localname))))
4217 ;; `dired-remove-file' is not defined in XEmacs.
4218 (tramp-compat-funcall 'dired-remove-file file)
4219 (string-match (car suffix) file)
4220 (concat (substring file 0 (match-beginning 0))))))
4222 ;; We don't recognize the file as compressed, so compress it.
4224 (with-progress-reporter v 0 (format "Compressing %s" file)
4226 (tramp-send-command-and-check
4227 v (concat "gzip -f "
4228 (tramp-shell-quote-argument localname))))
4229 ;; `dired-remove-file' is not defined in XEmacs.
4230 (tramp-compat-funcall 'dired-remove-file file)
4231 (cond ((file-exists-p (concat file ".gz"))
4232 (concat file ".gz"))
4233 ((file-exists-p (concat file ".z"))
4237 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4238 "Like `dired-uncache' for Tramp files."
4239 ;; DIR-P is valid for XEmacs only.
4240 (with-parsed-tramp-file-name
4241 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4242 (tramp-flush-directory-property v localname)))
4244 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4245 ;; not sure at all that this is the right way to do it, but let's hope
4246 ;; it works for now, and wait for a guru to point out the Right Way to
4248 ;;(eval-when-compile
4249 ;; (unless (fboundp 'dired-insert-set-properties)
4250 ;; (fset 'dired-insert-set-properties 'ignore)))
4251 ;; Gerd suggests this:
4252 (eval-when-compile (require 'dired))
4253 ;; Note that dired is required at run-time, too, when it is needed.
4254 ;; It is only needed on XEmacs for the function
4255 ;; `dired-insert-set-properties'.
4257 (defun tramp-handle-insert-directory
4258 (filename switches &optional wildcard full-directory-p)
4259 "Like `insert-directory' for Tramp files."
4260 (setq filename (expand-file-name filename))
4261 (with-parsed-tramp-file-name filename nil
4262 (if (and (featurep 'ls-lisp)
4263 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4264 (tramp-run-real-handler
4265 'insert-directory (list filename switches wildcard full-directory-p))
4266 (when (stringp switches)
4267 (setq switches (split-string switches)))
4268 (when (and (member "--dired" switches)
4269 (not (tramp-get-ls-command-with-dired v)))
4270 (setq switches (delete "--dired" switches)))
4272 (setq wildcard (tramp-run-real-handler
4273 'file-name-nondirectory (list localname)))
4274 (setq localname (tramp-run-real-handler
4275 'file-name-directory (list localname))))
4276 (unless full-directory-p
4277 (setq switches (add-to-list 'switches "-d" 'append)))
4278 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4280 (setq switches (concat switches " " wildcard)))
4282 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4283 switches filename (if wildcard "yes" "no")
4284 (if full-directory-p "yes" "no"))
4285 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4286 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4287 (if full-directory-p
4290 (format "%s %s %s 2>/dev/null"
4291 (tramp-get-ls-command v)
4295 (tramp-shell-quote-argument (concat localname ".")))))
4296 (tramp-barf-unless-okay
4298 (format "cd %s" (tramp-shell-quote-argument
4299 (tramp-run-real-handler
4300 'file-name-directory (list localname))))
4302 (tramp-shell-quote-argument
4303 (tramp-run-real-handler 'file-name-directory (list localname))))
4307 (tramp-get-ls-command v)
4311 (tramp-run-real-handler
4312 'file-name-nondirectory (list localname)))))
4314 (tramp-shell-quote-argument
4315 (tramp-run-real-handler
4316 'file-name-nondirectory (list localname)))))))
4317 (let ((beg (point)))
4318 ;; We cannot use `insert-buffer-substring' because the Tramp
4319 ;; buffer changes its contents before insertion due to calling
4320 ;; `expand-file' and alike.
4322 (with-current-buffer (tramp-get-buffer v)
4325 ;; Check for "--dired" output.
4327 (when (looking-at "//SUBDIRED//")
4329 (when (looking-at "//DIRED//\\s-+")
4330 (let ((databeg (match-end 0))
4331 (end (tramp-compat-line-end-position)))
4332 ;; Now read the numeric positions of file names.
4334 (while (< (point) end)
4335 (let ((start (+ beg (read (current-buffer))))
4336 (end (+ beg (read (current-buffer)))))
4337 (if (memq (char-after end) '(?\n ?\ ))
4338 ;; End is followed by \n or by " -> ".
4339 (put-text-property start end 'dired-filename t))))))
4340 ;; Remove trailing lines.
4341 (goto-char (tramp-compat-line-beginning-position))
4342 (while (looking-at "//")
4344 (delete-region (match-beginning 0) (point)))
4346 ;; The inserted file could be from somewhere else.
4347 (when (and (not wildcard) (not full-directory-p))
4348 (goto-char (point-max))
4349 (when (file-symlink-p filename)
4350 (goto-char (search-backward "->" beg 'noerror)))
4352 (if (zerop (length (file-name-nondirectory filename)))
4354 (file-name-nondirectory filename))
4356 (replace-match (file-relative-name filename) t))
4358 (goto-char (point-max))))))
4360 (defun tramp-handle-unhandled-file-name-directory (filename)
4361 "Like `unhandled-file-name-directory' for Tramp files."
4362 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4363 ;; for backward compatibility.
4364 (expand-file-name "~/"))
4366 ;; Canonicalization of file names.
4368 (defun tramp-handle-expand-file-name (name &optional dir)
4369 "Like `expand-file-name' for Tramp files.
4370 If the localname part of the given filename starts with \"/../\" then
4371 the result will be a local, non-Tramp, filename."
4372 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4373 (setq dir (or dir default-directory "/"))
4374 ;; Unless NAME is absolute, concat DIR and NAME.
4375 (unless (file-name-absolute-p name)
4376 (setq name (concat (file-name-as-directory dir) name)))
4377 ;; If NAME is not a Tramp file, run the real handler.
4378 (if (not (tramp-connectable-p name))
4379 (tramp-run-real-handler 'expand-file-name (list name nil))
4381 (with-parsed-tramp-file-name name nil
4382 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4383 (setq localname (concat "~/" localname)))
4384 ;; Tilde expansion if necessary. This needs a shell which
4385 ;; groks tilde expansion! The function `tramp-find-shell' is
4386 ;; supposed to find such a shell on the remote host. Please
4387 ;; tell me about it when this doesn't work on your system.
4388 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4389 (let ((uname (match-string 1 localname))
4390 (fname (match-string 2 localname)))
4391 ;; We cannot simply apply "~/", because under sudo "~/" is
4392 ;; expanded to the local user home directory but to the
4393 ;; root home directory. On the other hand, using always
4394 ;; the default user name for tilde expansion is not
4395 ;; appropriate either, because ssh and companions might
4396 ;; use a user name from the config file.
4397 (when (and (string-equal uname "~")
4398 (string-match "\\`su\\(do\\)?\\'" method))
4399 (setq uname (concat uname user)))
4401 (with-connection-property v uname
4403 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4404 (with-current-buffer (tramp-get-buffer v)
4405 (goto-char (point-min))
4407 (point) (tramp-compat-line-end-position)))))
4408 (setq localname (concat uname fname))))
4409 ;; There might be a double slash, for example when "~/"
4410 ;; expands to "/". Remove this.
4411 (while (string-match "//" localname)
4412 (setq localname (replace-match "/" t t localname)))
4413 ;; No tilde characters in file name, do normal
4414 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4415 ;; `directory-sep-char' here for XEmacs on Windows, which would
4416 ;; otherwise use backslash. `default-directory' is bound,
4417 ;; because on Windows there would be problems with UNC shares or
4419 (let ((directory-sep-char ?/)
4420 (default-directory (tramp-compat-temporary-file-directory)))
4421 (tramp-make-tramp-file-name
4423 (tramp-drop-volume-letter
4424 (tramp-run-real-handler
4425 'expand-file-name (list localname))))))))
4427 (defun tramp-replace-environment-variables (filename)
4428 "Replace environment variables in FILENAME.
4429 Return the string with the replaced variables."
4431 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4432 ;; `$' is coded as `$$'.
4434 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4435 (getenv (match-string 1 filename)))
4438 (substitute-in-file-name (match-string 0 filename))
4442 (defun tramp-handle-substitute-in-file-name (filename)
4443 "Like `substitute-in-file-name' for Tramp files.
4444 \"//\" and \"/~\" substitute only in the local filename part.
4445 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4446 beginning of local filename are not substituted."
4447 ;; First, we must replace environment variables.
4448 (setq filename (tramp-replace-environment-variables filename))
4449 (with-parsed-tramp-file-name filename nil
4450 (if (equal tramp-syntax 'url)
4451 ;; We need to check localname only. The other parts cannot contain
4453 (if (and (> (length localname) 1)
4454 (or (string-match "//" localname)
4455 (string-match "/~" localname 1)))
4456 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4457 (tramp-make-tramp-file-name
4458 (when method (substitute-in-file-name method))
4459 (when user (substitute-in-file-name user))
4460 (when host (substitute-in-file-name host))
4462 (tramp-run-real-handler
4463 'substitute-in-file-name (list localname)))))
4464 ;; Ignore in LOCALNAME everything before "//" or "/~".
4465 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4467 (concat (file-remote-p filename)
4468 (replace-match "\\1" nil nil localname)))
4469 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4470 (when (string-match "~$" filename)
4471 (setq filename (concat filename "/"))))
4472 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4474 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4475 ;; which calls corresponding functions (see minibuf.el).
4476 (when (fboundp 'minibuffer-electric-separator)
4481 (around ,(intern (format "tramp-advice-%s" x)) activate)
4482 "Invoke `substitute-in-file-name' for Tramp files."
4483 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4484 (tramp-tramp-file-p (buffer-substring)))
4485 ;; We don't need to handle `last-input-event', because
4486 ;; due to the key map we know it must be ?/ or ?~.
4487 (let ((s (concat (buffer-substring (point-min) (point))
4488 (string last-command-char))))
4489 (delete-region (point-min) (point))
4490 (insert (substitute-in-file-name s))
4491 (setq ad-return-value last-command-char))
4497 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4498 (ad-activate ',x)))))
4500 '(minibuffer-electric-separator
4501 minibuffer-electric-tilde)))
4504 ;;; Remote commands:
4506 (defun tramp-handle-executable-find (command)
4507 "Like `executable-find' for Tramp files."
4508 (with-parsed-tramp-file-name default-directory nil
4509 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4511 (defun tramp-process-sentinel (proc event)
4512 "Flush file caches."
4513 (unless (memq (process-status proc) '(run open))
4514 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4516 (tramp-message vec 5 "Sentinel called: `%s' `%s'" proc event)
4517 (tramp-flush-directory-property vec "")))))
4519 ;; We use BUFFER also as connection buffer during setup. Because of
4520 ;; this, its original contents must be saved, and restored once
4521 ;; connection has been setup.
4522 (defun tramp-handle-start-file-process (name buffer program &rest args)
4523 "Like `start-file-process' for Tramp files."
4524 (with-parsed-tramp-file-name default-directory nil
4526 ;; When PROGRAM is nil, we just provide a tty.
4528 (when (stringp program)
4529 (format "cd %s; exec %s"
4530 (tramp-shell-quote-argument localname)
4531 (mapconcat 'tramp-shell-quote-argument
4532 (cons program args) " "))))
4533 (tramp-process-connection-type
4534 (or (null program) tramp-process-connection-type))
4538 ;; BUFFER can be nil. We use a temporary buffer.
4539 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4540 (while (get-process name1)
4541 ;; NAME must be unique as process name.
4543 name1 (format "%s<%d>" name i)))
4545 ;; Set the new process properties.
4546 (tramp-set-connection-property v "process-name" name)
4547 (tramp-set-connection-property v "process-buffer" buffer)
4548 ;; Activate narrowing in order to save BUFFER contents.
4549 ;; Clear also the modification time; otherwise we might be
4550 ;; interrupted by `verify-visited-file-modtime'.
4551 (with-current-buffer (tramp-get-connection-buffer v)
4552 (clear-visited-file-modtime)
4553 (narrow-to-region (point-max) (point-max)))
4555 ;; Send the command.
4556 (tramp-send-command v command nil t) ; nooutput
4557 ;; Check, whether a pty is associated.
4558 (tramp-maybe-open-connection v)
4559 (unless (process-get (tramp-get-connection-process v) 'remote-tty)
4561 v 'file-error "pty association is not supported for `%s'" name)))
4562 (let ((p (tramp-get-connection-process v)))
4563 ;; Set sentinel and query flag for this process.
4564 (tramp-set-connection-property p "vector" v)
4565 (set-process-sentinel p 'tramp-process-sentinel)
4566 (tramp-set-process-query-on-exit-flag p t)
4570 (with-current-buffer (tramp-get-connection-buffer v)
4571 (if (string-match tramp-temp-buffer-name (buffer-name))
4573 (set-process-buffer (tramp-get-connection-process v) nil)
4574 (kill-buffer (current-buffer)))
4576 (goto-char (point-max))))
4577 (tramp-set-connection-property v "process-name" nil)
4578 (tramp-set-connection-property v "process-buffer" nil))))
4580 (defun tramp-handle-process-file
4581 (program &optional infile destination display &rest args)
4582 "Like `process-file' for Tramp files."
4583 ;; The implementation is not complete yet.
4584 (when (and (numberp destination) (zerop destination))
4585 (error "Implementation does not handle immediate return"))
4587 (with-parsed-tramp-file-name default-directory nil
4588 (let (command input tmpinput stderr tmpstderr outbuf ret)
4590 (setq command (mapconcat 'tramp-shell-quote-argument
4591 (cons program args) " "))
4594 (setq input "/dev/null")
4595 (setq infile (expand-file-name infile))
4596 (if (tramp-equal-remote default-directory infile)
4597 ;; INFILE is on the same remote host.
4598 (setq input (with-parsed-tramp-file-name infile nil localname))
4599 ;; INFILE must be copied to remote host.
4600 (setq input (tramp-make-tramp-temp-file v)
4601 tmpinput (tramp-make-tramp-file-name method user host input))
4602 (copy-file infile tmpinput t)))
4603 (when input (setq command (format "%s <%s" command input)))
4605 ;; Determine output.
4608 ((bufferp destination)
4609 (setq outbuf destination))
4611 ((stringp destination)
4612 (setq outbuf (get-buffer-create destination)))
4613 ;; (REAL-DESTINATION ERROR-DESTINATION)
4614 ((consp destination)
4617 ((bufferp (car destination))
4618 (setq outbuf (car destination)))
4619 ((stringp (car destination))
4620 (setq outbuf (get-buffer-create (car destination))))
4622 (setq outbuf (current-buffer))))
4625 ((stringp (cadr destination))
4626 (setcar (cdr destination) (expand-file-name (cadr destination)))
4627 (if (tramp-equal-remote default-directory (cadr destination))
4628 ;; stderr is on the same remote host.
4629 (setq stderr (with-parsed-tramp-file-name
4630 (cadr destination) nil localname))
4631 ;; stderr must be copied to remote host. The temporary
4632 ;; file must be deleted after execution.
4633 (setq stderr (tramp-make-tramp-temp-file v)
4634 tmpstderr (tramp-make-tramp-file-name
4635 method user host stderr))))
4636 ;; stderr to be discarded.
4637 ((null (cadr destination))
4638 (setq stderr "/dev/null"))))
4641 (setq outbuf (current-buffer))))
4642 (when stderr (setq command (format "%s 2>%s" command stderr)))
4644 ;; Send the command. It might not return in time, so we protect
4645 ;; it. Call it in a subshell, in order to preserve working
4650 (tramp-send-command-and-check
4651 v (format "\\cd %s; %s"
4652 (tramp-shell-quote-argument localname)
4655 ;; We should show the output anyway.
4657 (with-current-buffer outbuf
4659 (with-current-buffer (tramp-get-connection-buffer v)
4661 (when display (display-buffer outbuf))))
4662 ;; When the user did interrupt, we should do it also. We use
4663 ;; return code -1 as marker.
4665 (kill-buffer (tramp-get-connection-buffer v))
4669 (kill-buffer (tramp-get-connection-buffer v))
4672 ;; Provide error file.
4673 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4675 ;; Cleanup. We remove all file cache values for the connection,
4676 ;; because the remote process could have changed them.
4677 (when tmpinput (delete-file tmpinput))
4679 ;; `process-file-side-effects' has been introduced with GNU
4680 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4681 ;; by `program'. If it doesn't exist, we assume its default
4683 (unless (and (boundp 'process-file-side-effects)
4684 (not (symbol-value 'process-file-side-effects)))
4685 (tramp-flush-directory-property v ""))
4687 ;; Return exit status.
4692 (defun tramp-local-call-process
4693 (program &optional infile destination display &rest args)
4694 "Calls `call-process' on the local host.
4695 This is needed because for some Emacs flavors Tramp has
4696 defadviced `call-process' to behave like `process-file'. The
4697 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4698 (let ((default-directory
4699 (if (file-remote-p default-directory)
4700 (tramp-compat-temporary-file-directory)
4701 default-directory)))
4702 (if (executable-find program)
4703 (apply 'call-process program infile destination display args)
4706 (defun tramp-handle-call-process-region
4707 (start end program &optional delete buffer display &rest args)
4708 "Like `call-process-region' for Tramp files."
4709 (let ((tmpfile (tramp-compat-make-temp-file "")))
4710 (write-region start end tmpfile)
4711 (when delete (delete-region start end))
4713 (apply 'call-process program tmpfile buffer display args)
4714 (delete-file tmpfile))))
4716 (defun tramp-handle-shell-command
4717 (command &optional output-buffer error-buffer)
4718 "Like `shell-command' for Tramp files."
4719 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4720 ;; We cannot use `shell-file-name' and `shell-command-switch',
4721 ;; they are variables of the local host.
4723 (tramp-get-method-parameter
4724 (tramp-file-name-method
4725 (tramp-dissect-file-name default-directory))
4727 "-c" (substring command 0 asynchronous)))
4731 ((bufferp output-buffer) output-buffer)
4732 ((stringp output-buffer) (get-buffer-create output-buffer))
4734 (setq current-buffer-p t)
4736 (t (get-buffer-create
4738 "*Async Shell Command*"
4739 "*Shell Command Output*")))))
4742 ((bufferp error-buffer) error-buffer)
4743 ((stringp error-buffer) (get-buffer-create error-buffer))))
4745 (if (and (not asynchronous) error-buffer)
4746 (with-parsed-tramp-file-name default-directory nil
4747 (list output-buffer (tramp-make-tramp-temp-file v)))
4749 (p (get-buffer-process output-buffer)))
4751 ;; Check whether there is another process running. Tramp does not
4752 ;; support 2 (asynchronous) processes in parallel.
4754 (if (yes-or-no-p "A command is running. Kill it? ")
4758 (error "Shell command in progress")))
4760 (if current-buffer-p
4762 (barf-if-buffer-read-only)
4764 (with-current-buffer output-buffer
4765 (setq buffer-read-only nil)
4768 (if (and (not current-buffer-p) (integerp asynchronous))
4771 (apply 'start-file-process "*Async Shell*" buffer args)
4773 (pop-to-buffer output-buffer)
4774 (setq mode-line-process '(":%s"))
4775 (require 'shell) (shell-mode))
4779 (apply 'process-file (car args) nil buffer nil (cdr args))
4780 ;; Insert error messages if they were separated.
4781 (when (listp buffer)
4782 (with-current-buffer error-buffer
4783 (insert-file-contents (cadr buffer)))
4784 (delete-file (cadr buffer)))
4785 (if current-buffer-p
4786 ;; This is like exchange-point-and-mark, but doesn't
4787 ;; activate the mark. It is cleaner to avoid activation,
4788 ;; even though the command loop would deactivate the mark
4789 ;; because we inserted text.
4790 (goto-char (prog1 (mark t)
4791 (set-marker (mark-marker) (point)
4793 ;; There's some output, display it.
4794 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4795 (if (functionp 'display-message-or-buffer)
4796 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
4797 (pop-to-buffer output-buffer))))))))
4801 (defvar tramp-handle-file-local-copy-hook nil
4802 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4804 (defun tramp-handle-file-local-copy (filename)
4805 "Like `file-local-copy' for Tramp files."
4807 (with-parsed-tramp-file-name filename nil
4808 (unless (file-exists-p filename)
4811 "Cannot make local copy of non-existing file `%s'" filename))
4813 (let* ((size (nth 7 (file-attributes filename)))
4814 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
4815 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
4816 (tmpfile (tramp-compat-make-temp-file filename)))
4820 ;; `copy-file' handles direct copy and out-of-band methods.
4821 ((or (tramp-local-host-p v)
4822 (tramp-method-out-of-band-p v size))
4823 (copy-file filename tmpfile t t))
4825 ;; Use inline encoding for file transfer.
4828 (with-progress-reporter
4829 v 3 (format "Encoding remote file %s" filename)
4830 (tramp-barf-unless-okay
4831 v (format rem-enc (tramp-shell-quote-argument localname))
4832 "Encoding remote file failed"))
4834 (if (functionp loc-dec)
4835 ;; If local decoding is a function, we call it. We
4836 ;; must disable multibyte, because
4837 ;; `uudecode-decode-region' doesn't handle it
4840 (set-buffer-multibyte nil)
4841 (insert-buffer-substring (tramp-get-buffer v))
4842 (with-progress-reporter
4843 v 3 (format "Decoding remote file %s with function %s"
4845 (funcall loc-dec (point-min) (point-max))
4846 ;; Unset `file-name-handler-alist'. Otherwise,
4847 ;; epa-file gets confused.
4848 (let (file-name-handler-alist
4849 (coding-system-for-write 'binary))
4850 (write-region (point-min) (point-max) tmpfile))))
4852 ;; If tramp-decoding-function is not defined for this
4853 ;; method, we invoke tramp-decoding-command instead.
4854 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4855 ;; Unset `file-name-handler-alist'. Otherwise,
4856 ;; epa-file gets confused.
4857 (let (file-name-handler-alist
4858 (coding-system-for-write 'binary))
4859 (write-region (point-min) (point-max) tmpfile2))
4860 (with-progress-reporter
4861 v 3 (format "Decoding remote file %s with command %s"
4864 (tramp-call-local-coding-command
4865 loc-dec tmpfile2 tmpfile)
4866 (delete-file tmpfile2)))))
4868 ;; Set proper permissions.
4869 (set-file-modes tmpfile (tramp-default-file-modes filename))
4870 ;; Set local user ownership.
4871 (tramp-set-file-uid-gid tmpfile)))
4873 ;; Oops, I don't know what to do.
4875 v 'file-error "Wrong method specification for `%s'" method)))
4879 (delete-file tmpfile)
4880 (signal (car err) (cdr err))))
4882 (run-hooks 'tramp-handle-file-local-copy-hook)
4885 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4886 "Like `file-remote-p' for Tramp files."
4887 (let ((tramp-verbose 3))
4888 (when (tramp-tramp-file-p filename)
4889 (let* ((v (tramp-dissect-file-name filename))
4890 (p (tramp-get-connection-process v))
4891 (c (and p (processp p) (memq (process-status p) '(run open)))))
4892 ;; We expand the file name only, if there is already a connection.
4893 (with-parsed-tramp-file-name
4894 (if c (expand-file-name filename) filename) nil
4895 (and (or (not connected) c)
4897 ((eq identification 'method) method)
4898 ((eq identification 'user) user)
4899 ((eq identification 'host) host)
4900 ((eq identification 'localname) localname)
4901 (t (tramp-make-tramp-file-name method user host "")))))))))
4903 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4904 "Like `find-operation-coding-system' for Tramp filenames.
4905 Tramp's `insert-file-contents' and `write-region' work over
4906 temporary file names. If `file-coding-system-alist' contains an
4907 expression, which matches more than the file name suffix, the
4908 coding system might not be determined. This function repairs it."
4910 (dolist (elt file-coding-system-alist result)
4911 (when (and (consp elt) (string-match (car elt) filename))
4912 ;; We found a matching entry in `file-coding-system-alist'.
4913 ;; So we add a similar entry, but with the temporary file name
4916 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4918 (defun tramp-handle-insert-file-contents
4919 (filename &optional visit beg end replace)
4920 "Like `insert-file-contents' for Tramp files."
4921 (barf-if-buffer-read-only)
4922 (setq filename (expand-file-name filename))
4923 (let (result local-copy remote-copy)
4924 (with-parsed-tramp-file-name filename nil
4926 (if (not (file-exists-p filename))
4927 ;; We don't raise a Tramp error, because it might be
4928 ;; suppressed, like in `find-file-noselect-1'.
4930 (list "File not found on remote host" filename))
4932 (if (and (tramp-local-host-p v)
4933 (let (file-name-handler-alist)
4934 (file-readable-p localname)))
4935 ;; Short track: if we are on the local host, we can
4938 (tramp-run-real-handler
4939 'insert-file-contents
4940 (list localname visit beg end replace)))
4942 ;; When we shall insert only a part of the file, we copy
4945 (setq remote-copy (tramp-make-tramp-temp-file v))
4950 (format "tail -c +%d %s | head -c +%d >%s"
4951 (1+ beg) (tramp-shell-quote-argument localname)
4952 (- end beg) remote-copy))
4954 (format "tail -c +%d %s >%s"
4955 (1+ beg) (tramp-shell-quote-argument localname)
4958 (format "head -c +%d %s >%s"
4959 (1+ end) (tramp-shell-quote-argument localname)
4962 ;; `insert-file-contents-literally' takes care to avoid
4963 ;; calling jka-compr. By let-binding
4964 ;; `inhibit-file-name-operation', we propagate that care
4965 ;; to the `file-local-copy' operation.
4967 (let ((inhibit-file-name-operation
4968 (when (eq inhibit-file-name-operation
4969 'insert-file-contents)
4972 ((stringp remote-copy)
4974 (tramp-make-tramp-file-name
4975 method user host remote-copy)))
4976 ((stringp tramp-temp-buffer-file-name)
4977 (copy-file filename tramp-temp-buffer-file-name 'ok)
4978 tramp-temp-buffer-file-name)
4979 (t (file-local-copy filename)))))
4981 ;; When the file is not readable for the owner, it
4982 ;; cannot be inserted, even it is redable for the group
4983 ;; or for everybody.
4984 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4986 (when (and (null remote-copy)
4987 (tramp-get-method-parameter
4988 method 'tramp-copy-keep-tmpfile))
4989 ;; We keep the local file for performance reasons,
4990 ;; useful for "rsync".
4991 (setq tramp-temp-buffer-file-name local-copy)
4992 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4994 (with-progress-reporter
4995 v 3 (format "Inserting local temp file `%s'" local-copy)
4996 ;; We must ensure that `file-coding-system-alist'
4997 ;; matches `local-copy'.
4998 (let ((file-coding-system-alist
4999 (tramp-find-file-name-coding-system-alist
5000 filename local-copy)))
5002 (insert-file-contents
5003 local-copy nil nil nil replace))))))
5008 (setq buffer-file-name filename)
5009 (setq buffer-read-only (not (file-writable-p filename)))
5010 (set-visited-file-modtime)
5011 (set-buffer-modified-p nil)
5012 ;; For root, preserve owner and group when editing files.
5013 (when (string-equal (file-remote-p filename 'user) "root")
5014 (set (make-local-variable 'backup-by-copying-when-mismatch) t)))
5015 (when (and (stringp local-copy)
5016 (or remote-copy (null tramp-temp-buffer-file-name)))
5017 (delete-file local-copy))
5018 (when (stringp remote-copy)
5020 (tramp-make-tramp-file-name method user host remote-copy))))))
5023 (list (expand-file-name filename)
5026 ;; This is needed for XEmacs only. Code stolen from files.el.
5027 (defun tramp-handle-insert-file-contents-literally
5028 (filename &optional visit beg end replace)
5029 "Like `insert-file-contents-literally' for Tramp files."
5030 (let ((format-alist nil)
5031 (after-insert-file-functions nil)
5032 (coding-system-for-read 'no-conversion)
5033 (coding-system-for-write 'no-conversion)
5034 (find-buffer-file-type-function
5035 (if (fboundp 'find-buffer-file-type)
5036 (symbol-function 'find-buffer-file-type)
5038 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
5039 (inhibit-file-name-operation 'insert-file-contents))
5042 (fset 'find-buffer-file-type (lambda (filename) t))
5043 (insert-file-contents filename visit beg end replace))
5045 (if find-buffer-file-type-function
5046 (fset 'find-buffer-file-type find-buffer-file-type-function)
5047 (fmakunbound 'find-buffer-file-type)))))
5049 (defun tramp-handle-find-backup-file-name (filename)
5050 "Like `find-backup-file-name' for Tramp files."
5051 (with-parsed-tramp-file-name filename nil
5052 ;; We set both variables. It doesn't matter whether it is
5054 (let ((backup-directory-alist
5056 (when (boundp 'backup-directory-alist)
5057 (if (symbol-value 'tramp-backup-directory-alist)
5062 (if (and (stringp (cdr x))
5063 (file-name-absolute-p (cdr x))
5064 (not (tramp-file-name-p (cdr x))))
5065 (tramp-make-tramp-file-name method user host (cdr x))
5067 (symbol-value 'tramp-backup-directory-alist))
5068 (symbol-value 'backup-directory-alist))))
5070 (bkup-backup-directory-info
5072 (when (boundp 'bkup-backup-directory-info)
5073 (if (symbol-value 'tramp-bkup-backup-directory-info)
5079 (if (and (stringp (car (cdr x)))
5080 (file-name-absolute-p (car (cdr x)))
5081 (not (tramp-file-name-p (car (cdr x)))))
5082 (tramp-make-tramp-file-name
5083 method user host (car (cdr x)))
5086 (symbol-value 'tramp-bkup-backup-directory-info))
5087 (symbol-value 'bkup-backup-directory-info)))))
5089 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
5091 (defun tramp-handle-make-auto-save-file-name ()
5092 "Like `make-auto-save-file-name' for Tramp files.
5093 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
5094 (let ((tramp-auto-save-directory tramp-auto-save-directory)
5096 (tramp-subst-strs-in-string
5103 (buffer-file-name))))
5104 ;; File name must be unique. This is ensured with Emacs 22 (see
5105 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
5106 ;; all other cases we must do it ourselves.
5107 (when (boundp 'auto-save-file-name-transforms)
5110 (when (and (string-match (car x) buffer-file-name)
5111 (not (car (cddr x))))
5112 (setq tramp-auto-save-directory
5113 (or tramp-auto-save-directory
5114 (tramp-compat-temporary-file-directory)))))
5115 (symbol-value 'auto-save-file-name-transforms)))
5116 ;; Create directory.
5117 (when tramp-auto-save-directory
5118 (setq buffer-file-name
5119 (expand-file-name buffer-file-name tramp-auto-save-directory))
5120 (unless (file-exists-p tramp-auto-save-directory)
5121 (make-directory tramp-auto-save-directory t)))
5122 ;; Run plain `make-auto-save-file-name'. There might be an advice when
5123 ;; it is not a magic file name operation (since Emacs 22).
5124 ;; We must deactivate it temporarily.
5125 (if (not (ad-is-active 'make-auto-save-file-name))
5126 (tramp-run-real-handler 'make-auto-save-file-name nil)
5128 (ad-deactivate 'make-auto-save-file-name)
5130 (tramp-run-real-handler 'make-auto-save-file-name nil)
5131 (ad-activate 'make-auto-save-file-name)))))
5133 (defvar tramp-handle-write-region-hook nil
5134 "Normal hook to be run at the end of `tramp-handle-write-region'.")
5136 ;; CCC grok LOCKNAME
5137 (defun tramp-handle-write-region
5138 (start end filename &optional append visit lockname confirm)
5139 "Like `write-region' for Tramp files."
5140 (setq filename (expand-file-name filename))
5141 (with-parsed-tramp-file-name filename nil
5142 ;; Following part commented out because we don't know what to do about
5143 ;; file locking, and it does not appear to be a problem to ignore it.
5144 ;; Ange-ftp ignores it, too.
5145 ;; (when (and lockname (stringp lockname))
5146 ;; (setq lockname (expand-file-name lockname)))
5147 ;; (unless (or (eq lockname nil)
5148 ;; (string= lockname filename))
5150 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
5152 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
5153 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
5154 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
5155 (tramp-error v 'file-error "File not overwritten")))
5157 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
5158 (tramp-get-remote-uid v 'integer)))
5159 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
5160 (tramp-get-remote-gid v 'integer))))
5162 (if (and (tramp-local-host-p v)
5163 ;; `file-writable-p' calls `file-expand-file-name'. We
5164 ;; cannot use `tramp-run-real-handler' therefore.
5165 (let (file-name-handler-alist)
5167 (file-writable-p (file-name-directory localname))
5168 (or (file-directory-p localname)
5169 (file-writable-p localname)))))
5170 ;; Short track: if we are on the local host, we can run directly.
5171 (tramp-run-real-handler
5173 (list start end localname append 'no-message lockname confirm))
5175 (let ((modes (save-excursion (tramp-default-file-modes filename)))
5176 ;; We use this to save the value of
5177 ;; `last-coding-system-used' after writing the tmp
5178 ;; file. At the end of the function, we set
5179 ;; `last-coding-system-used' to this saved value. This
5180 ;; way, any intermediary coding systems used while
5181 ;; talking to the remote shell or suchlike won't hose
5182 ;; this variable. This approach was snarfed from
5185 ;; Write region into a tmp file. This isn't really
5186 ;; needed if we use an encoding function, but currently
5187 ;; we use it always because this makes the logic
5189 (tmpfile (or tramp-temp-buffer-file-name
5190 (tramp-compat-make-temp-file filename))))
5192 ;; If `append' is non-nil, we copy the file locally, and let
5193 ;; the native `write-region' implementation do the job.
5194 (when append (copy-file filename tmpfile 'ok))
5196 ;; We say `no-message' here because we don't want the
5197 ;; visited file modtime data to be clobbered from the temp
5198 ;; file. We call `set-visited-file-modtime' ourselves later
5199 ;; on. We must ensure that `file-coding-system-alist'
5200 ;; matches `tmpfile'.
5201 (let (file-name-handler-alist
5202 (file-coding-system-alist
5203 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5205 (tramp-run-real-handler
5207 (list start end tmpfile append 'no-message lockname confirm))
5209 (setq tramp-temp-buffer-file-name nil)
5210 (delete-file tmpfile)
5211 (signal (car err) (cdr err))))
5213 ;; Now, `last-coding-system-used' has the right value. Remember it.
5214 (when (boundp 'last-coding-system-used)
5215 (setq coding-system-used
5216 (symbol-value 'last-coding-system-used))))
5218 ;; The permissions of the temporary file should be set. If
5219 ;; filename does not exist (eq modes nil) it has been
5220 ;; renamed to the backup file. This case `save-buffer'
5221 ;; handles permissions.
5222 ;; Ensure, that it is still readable.
5225 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
5227 ;; This is a bit lengthy due to the different methods
5228 ;; possible for file transfer. First, we check whether the
5229 ;; method uses an rcp program. If so, we call it.
5230 ;; Otherwise, both encoding and decoding command must be
5231 ;; specified. However, if the method _also_ specifies an
5232 ;; encoding function, then that is used for encoding the
5233 ;; contents of the tmp file.
5234 (let* ((size (nth 7 (file-attributes tmpfile)))
5235 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
5236 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
5238 ;; `copy-file' handles direct copy and out-of-band methods.
5239 ((or (tramp-local-host-p v)
5240 (tramp-method-out-of-band-p v size))
5241 (if (and (not (stringp start))
5242 (= (or end (point-max)) (point-max))
5243 (= (or start (point-min)) (point-min))
5244 (tramp-get-method-parameter
5245 method 'tramp-copy-keep-tmpfile))
5247 (setq tramp-temp-buffer-file-name tmpfile)
5249 ;; We keep the local file for performance
5250 ;; reasons, useful for "rsync".
5251 (copy-file tmpfile filename t)
5253 (setq tramp-temp-buffer-file-name nil)
5254 (delete-file tmpfile)
5255 (signal (car err) (cdr err)))))
5256 (setq tramp-temp-buffer-file-name nil)
5257 ;; Don't rename, in order to keep context in SELinux.
5259 (copy-file tmpfile filename t)
5260 (delete-file tmpfile))))
5262 ;; Use inline file transfer.
5267 (set-buffer-multibyte nil)
5268 ;; Use encoding function or command.
5269 (if (functionp loc-enc)
5270 (with-progress-reporter
5271 v 3 (format "Encoding region using function `%s'"
5273 (let ((coding-system-for-read 'binary))
5274 (insert-file-contents-literally tmpfile))
5275 ;; The following `let' is a workaround for the
5276 ;; base64.el that comes with pgnus-0.84. If
5277 ;; both of the following conditions are
5278 ;; satisfied, it tries to write to a local
5279 ;; file in default-directory, but at this
5280 ;; point, default-directory is remote.
5281 ;; (`call-process-region' can't write to
5282 ;; remote files, it seems.) The file in
5283 ;; question is a tmp file anyway.
5284 (let ((default-directory
5285 (tramp-compat-temporary-file-directory)))
5286 (funcall loc-enc (point-min) (point-max))))
5288 (with-progress-reporter
5289 v 3 (format "Encoding region using command `%s'"
5291 (unless (zerop (tramp-call-local-coding-command
5295 (concat "Cannot write to `%s', "
5296 "local encoding command `%s' failed")
5297 filename loc-enc))))
5299 ;; Send buffer into remote decoding command which
5300 ;; writes to remote file. Because this happens on
5301 ;; the remote host, we cannot use the function.
5302 (with-progress-reporter
5304 (format "Decoding region into remote file %s" filename)
5305 (goto-char (point-max))
5306 (unless (bolp) (newline))
5310 (concat rem-dec " <<'EOF'\n%sEOF")
5311 (tramp-shell-quote-argument localname)
5313 (tramp-barf-unless-okay
5315 "Couldn't write region to `%s', decode using `%s' failed"
5317 ;; When `file-precious-flag' is set, the region is
5318 ;; written to a temporary file. Check that the
5319 ;; checksum is equal to that from the local tmpfile.
5320 (when file-precious-flag
5323 ;; cksum runs locally, if possible.
5324 (zerop (tramp-local-call-process "cksum" tmpfile t))
5325 ;; cksum runs remotely.
5327 (tramp-send-command-and-check
5331 (tramp-shell-quote-argument localname))))
5332 ;; ... they are different.
5336 (with-current-buffer (tramp-get-buffer v)
5340 (concat "Couldn't write region to `%s',"
5341 " decode using `%s' failed")
5342 filename rem-dec)))))
5345 (delete-file tmpfile)))
5347 ;; That's not expected.
5351 (concat "Method `%s' should specify both encoding and "
5352 "decoding command or an rcp program")
5355 ;; Make `last-coding-system-used' have the right value.
5356 (when coding-system-used
5357 (set 'last-coding-system-used coding-system-used))))
5359 (tramp-flush-file-property v (file-name-directory localname))
5360 (tramp-flush-file-property v localname)
5362 ;; We must protect `last-coding-system-used', now we have set it
5363 ;; to its correct value.
5364 (let (last-coding-system-used (need-chown t))
5365 ;; Set file modification time.
5366 (when (or (eq visit t) (stringp visit))
5367 (let ((file-attr (file-attributes filename)))
5368 (set-visited-file-modtime
5369 ;; We must pass modtime explicitely, because filename can
5370 ;; be different from (buffer-file-name), f.e. if
5371 ;; `file-precious-flag' is set.
5373 (when (and (eq (nth 2 file-attr) uid)
5374 (eq (nth 3 file-attr) gid))
5375 (setq need-chown nil))))
5377 ;; Set the ownership.
5379 (tramp-set-file-uid-gid filename uid gid))
5380 (when (or (eq visit t) (null visit) (stringp visit))
5381 (tramp-message v 0 "Wrote %s" filename))
5382 (run-hooks 'tramp-handle-write-region-hook)))))
5384 (defvar tramp-vc-registered-file-names nil
5385 "List used to collect file names, which are checked during `vc-registered'.")
5387 ;; VC backends check for the existence of various different special
5388 ;; files. This is very time consuming, because every single check
5389 ;; requires a remote command (the file cache must be invalidated).
5390 ;; Therefore, we apply a kind of optimization. We install the file
5391 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5392 ;; remembers all file names for which `file-exists-p' or
5393 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5394 ;; is performed. Afterwards, a script is applied for all collected
5395 ;; file names, using just one remote command. The result of this
5396 ;; script is used to fill the file cache with actual values. Now we
5397 ;; can reset the file name handlers, and we make a second run of
5398 ;; `vc-registered', which returns the expected result without sending
5399 ;; any other remote command.
5400 (defun tramp-handle-vc-registered (file)
5401 "Like `vc-registered' for Tramp files."
5402 (with-temp-message ""
5403 (with-parsed-tramp-file-name file nil
5404 (with-progress-reporter
5405 v 3 (format "Checking `vc-registered' for %s" file)
5407 ;; There could be new files, created by the vc backend. We
5408 ;; cannot reuse the old cache entries, therefore.
5409 (let (tramp-vc-registered-file-names
5410 (tramp-cache-inhibit-cache (current-time))
5411 (file-name-handler-alist
5412 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5414 ;; Here we collect only file names, which need an operation.
5415 (tramp-run-real-handler 'vc-registered (list file))
5416 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5418 ;; Send just one command, in order to fill the cache.
5419 (when tramp-vc-registered-file-names
5420 (tramp-maybe-send-script
5422 (format tramp-vc-registered-read-file-names
5423 (tramp-get-file-exists-command v)
5424 (format "%s -r" (tramp-get-test-command v)))
5425 "tramp_vc_registered_read_file_names")
5429 (tramp-send-command-and-read
5432 "tramp_vc_registered_read_file_names <<'EOF'\n%s\nEOF\n"
5433 (mapconcat 'tramp-shell-quote-argument
5434 tramp-vc-registered-file-names
5437 (tramp-set-file-property
5438 v (car elt) (cadr elt) (cadr (cdr elt))))))
5440 ;; Second run. Now all `file-exists-p' or `file-readable-p'
5441 ;; calls shall be answered from the file cache. We unset
5442 ;; `process-file-side-effects' in order to keep the cache when
5443 ;; `process-file' calls appear.
5444 (let (process-file-side-effects)
5445 (tramp-run-real-handler 'vc-registered (list file)))))))
5448 (progn (defun tramp-run-real-handler (operation args)
5449 "Invoke normal file name handler for OPERATION.
5450 First arg specifies the OPERATION, second arg is a list of arguments to
5451 pass to the OPERATION."
5452 (let* ((inhibit-file-name-handlers
5453 `(tramp-file-name-handler
5454 tramp-vc-file-name-handler
5455 tramp-completion-file-name-handler
5456 cygwin-mount-name-hook-function
5457 cygwin-mount-map-drive-hook-function
5459 ,(and (eq inhibit-file-name-operation operation)
5460 inhibit-file-name-handlers)))
5461 (inhibit-file-name-operation operation))
5462 (apply operation args))))
5465 (progn (defun tramp-completion-run-real-handler (operation args)
5466 "Invoke `tramp-file-name-handler' for OPERATION.
5467 First arg specifies the OPERATION, second arg is a list of arguments to
5468 pass to the OPERATION."
5469 (let* ((inhibit-file-name-handlers
5470 `(tramp-completion-file-name-handler
5471 cygwin-mount-name-hook-function
5472 cygwin-mount-map-drive-hook-function
5474 ,(and (eq inhibit-file-name-operation operation)
5475 inhibit-file-name-handlers)))
5476 (inhibit-file-name-operation operation))
5477 (apply operation args))))
5479 ;; We handle here all file primitives. Most of them have the file
5480 ;; name as first parameter; nevertheless we check for them explicitly
5481 ;; in order to be signaled if a new primitive appears. This
5482 ;; scenario is needed because there isn't a way to decide by
5483 ;; syntactical means whether a foreign method must be called. It would
5484 ;; ease the life if `file-name-handler-alist' would support a decision
5485 ;; function as well but regexp only.
5486 (defun tramp-file-name-for-operation (operation &rest args)
5487 "Return file name related to OPERATION file primitive.
5488 ARGS are the arguments OPERATION has been called with."
5490 ;; FILE resp DIRECTORY.
5492 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5493 'delete-file 'diff-latest-backup-file 'directory-file-name
5494 'directory-files 'directory-files-and-attributes
5495 'dired-compress-file 'dired-uncache
5496 'file-accessible-directory-p 'file-attributes
5497 'file-directory-p 'file-executable-p 'file-exists-p
5498 'file-local-copy 'file-remote-p 'file-modes
5499 'file-name-as-directory 'file-name-directory
5500 'file-name-nondirectory 'file-name-sans-versions
5501 'file-ownership-preserved-p 'file-readable-p
5502 'file-regular-p 'file-symlink-p 'file-truename
5503 'file-writable-p 'find-backup-file-name 'find-file-noselect
5504 'get-file-buffer 'insert-directory 'insert-file-contents
5505 'load 'make-directory 'make-directory-internal
5506 'set-file-modes 'substitute-in-file-name
5507 'unhandled-file-name-directory 'vc-registered
5511 'file-selinux-context 'set-file-selinux-context
5513 'abbreviate-file-name 'create-file-buffer
5514 'dired-file-modtime 'dired-make-compressed-filename
5515 'dired-recursive-delete-directory 'dired-set-file-modtime
5516 'dired-shell-unhandle-file-name 'dired-uucode-file
5517 'insert-file-contents-literally 'make-temp-name 'recover-file
5518 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5519 (if (file-name-absolute-p (nth 0 args))
5521 (expand-file-name (nth 0 args))))
5522 ;; FILE DIRECTORY resp FILE1 FILE2.
5524 (list 'add-name-to-file 'copy-file 'expand-file-name
5525 'file-name-all-completions 'file-name-completion
5526 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5530 'dired-make-relative-symlink
5531 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5534 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5535 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5536 (t (buffer-file-name (current-buffer))))))
5538 ((eq operation 'write-region)
5542 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5544 'make-auto-save-file-name
5548 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5551 (list ;; not in Emacs 23+.
5560 'dired-print-file 'dired-shell-call-process
5562 'executable-find 'start-process
5563 'call-process 'call-process-region))
5565 ;; Unknown file primitive.
5566 (t (error "unknown file I/O primitive: %s" operation))))
5568 (defun tramp-find-foreign-file-name-handler (filename)
5569 "Return foreign file name handler if exists."
5570 (when (tramp-tramp-file-p filename)
5571 (let ((v (tramp-dissect-file-name filename t))
5572 (handler tramp-foreign-file-name-handler-alist)
5574 ;; When we are not fully sure that filename completion is safe,
5575 ;; we should not return a handler.
5576 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5577 (and (tramp-file-name-host v)
5578 (not (member (tramp-file-name-host v)
5579 (mapcar 'car tramp-methods))))
5580 (not (tramp-completion-mode-p)))
5582 (setq elt (car handler)
5583 handler (cdr handler))
5584 (when (funcall (car elt) filename)
5591 (defun tramp-file-name-handler (operation &rest args)
5592 "Invoke Tramp file name handler.
5593 Falls back to normal file name handler if no Tramp file name handler exists."
5597 (tramp-replace-environment-variables
5598 (apply 'tramp-file-name-for-operation operation args)))
5599 (completion (tramp-completion-mode-p))
5600 (foreign (tramp-find-foreign-file-name-handler filename)))
5601 (with-parsed-tramp-file-name filename nil
5602 ;; Call the backend function.
5605 (apply foreign operation args)
5607 ;; Trace that somebody has interrupted the
5610 (let (tramp-message-show-message)
5612 v 1 "Interrupt received in operation %s"
5613 (append (list operation) args)))
5614 ;; Propagate the quit signal.
5615 (signal (car err) (cdr err)))
5617 ;; When we are in completion mode, some failed
5618 ;; operations shall return at least a default value
5619 ;; in order to give the user a chance to correct the
5620 ;; file name in the minibuffer.
5623 ((and completion (zerop (length localname))
5624 (memq operation '(file-exists-p file-directory-p)))
5626 ((and completion (zerop (length localname))
5628 '(expand-file-name file-name-as-directory)))
5630 ;; Propagate the error.
5631 (t (signal (car err) (cdr err))))))
5633 ;; Nothing to do for us.
5634 (tramp-run-real-handler operation args)))))
5636 ;; When `tramp-mode' is not enabled, we don't do anything.
5637 (tramp-run-real-handler operation args)))
5639 ;; In Emacs, there is some concurrency due to timers. If a timer
5640 ;; interrupts Tramp and wishes to use the same connection buffer as
5641 ;; the "main" Emacs, then garbage might occur in the connection
5642 ;; buffer. Therefore, we need to make sure that a timer does not use
5643 ;; the same connection buffer as the "main" Emacs. We implement a
5644 ;; cheap global lock, instead of locking each connection buffer
5645 ;; separately. The global lock is based on two variables,
5646 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5647 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5648 ;; processing of a single file operation, so we need to allow
5649 ;; recursive calls. That's where the `tramp-locker' variable comes in
5650 ;; -- it is let-bound to t during the execution of the current
5651 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5652 ;; then we should just proceed because we have been called
5653 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5654 ;; interrupting the "main" Emacs, and then we signal an error.
5656 (defvar tramp-locked nil
5657 "If non-nil, then Tramp is currently busy.
5658 Together with `tramp-locker', this implements a locking mechanism
5659 preventing reentrant calls of Tramp.")
5661 (defvar tramp-locker nil
5662 "If non-nil, then a caller has locked Tramp.
5663 Together with `tramp-locked', this implements a locking mechanism
5664 preventing reentrant calls of Tramp.")
5666 (defun tramp-sh-file-name-handler (operation &rest args)
5667 "Invoke remote-shell Tramp file name handler.
5668 Fall back to normal file name handler if no Tramp handler exists."
5669 (when (and tramp-locked (not tramp-locker))
5670 (setq tramp-locked nil)
5671 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5672 (let ((tl tramp-locked))
5675 (setq tramp-locked t)
5676 (let ((tramp-locker t))
5678 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5680 (apply (cdr fn) args)
5681 (tramp-run-real-handler operation args))))))
5682 (setq tramp-locked tl))))
5684 (defun tramp-vc-file-name-handler (operation &rest args)
5685 "Invoke special file name handler, which collects files to be handled."
5688 (tramp-replace-environment-variables
5689 (apply 'tramp-file-name-for-operation operation args)))
5690 (fn (assoc operation tramp-file-name-handler-alist)))
5691 (with-parsed-tramp-file-name filename nil
5693 ;; That's what we want: file names, for which checks are
5694 ;; applied. We assume, that VC uses only `file-exists-p' and
5695 ;; `file-readable-p' checks; otherwise we must extend the
5696 ;; list. We do not perform any action, but return nil, in
5697 ;; order to keep `vc-registered' running.
5698 ((and fn (memq operation '(file-exists-p file-readable-p)))
5699 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5701 ;; Tramp file name handlers like `expand-file-name'. They
5704 (save-match-data (apply (cdr fn) args)))
5705 ;; Default file name handlers, we don't care.
5706 (t (tramp-run-real-handler operation args)))))))
5709 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5710 "Invoke Tramp file name completion handler.
5711 Falls back to normal file name handler if no Tramp file name handler exists."
5712 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5713 ;; would otherwise use backslash.
5714 (let ((directory-sep-char ?/)
5715 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5717 ;; When `tramp-mode' is not enabled, we don't do anything.
5719 ;; For other syntaxes than `sep', the regexp matches many common
5720 ;; situations where the user doesn't actually want to use Tramp.
5721 ;; So to avoid autoloading Tramp after typing just "/s", we
5722 ;; disable this part of the completion, unless the user implicitly
5723 ;; indicated his interest in using a fancier completion system.
5724 (or (eq tramp-syntax 'sep)
5725 (featurep 'tramp) ;; If it's loaded, we may as well use it.
5726 ;; `partial-completion-mode' does not exist in XEmacs.
5727 ;; It is obsoleted with Emacs 24.1.
5728 (and (boundp 'partial-completion-mode)
5729 (symbol-value 'partial-completion-mode))
5730 ;; FIXME: These may have been loaded even if the user never
5731 ;; intended to use them.
5733 (featurep 'icicles)))
5734 (save-match-data (apply (cdr fn) args))
5735 (tramp-completion-run-real-handler operation args)))))
5738 (progn (defun tramp-register-file-name-handlers ()
5739 "Add Tramp file name handlers to `file-name-handler-alist'."
5740 ;; Remove autoloaded handlers from file name handler alist. Useful,
5741 ;; if `tramp-syntax' has been changed.
5742 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5743 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5745 'tramp-completion-file-name-handler file-name-handler-alist)))
5746 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5747 ;; Add the handlers.
5748 (add-to-list 'file-name-handler-alist
5749 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5750 (put 'tramp-file-name-handler 'safe-magic t)
5751 (add-to-list 'file-name-handler-alist
5752 (cons tramp-completion-file-name-regexp
5753 'tramp-completion-file-name-handler))
5754 (put 'tramp-completion-file-name-handler 'safe-magic t)
5755 ;; If jka-compr or epa-file are already loaded, move them to the
5756 ;; front of `file-name-handler-alist'.
5757 (dolist (fnh '(epa-file-handler jka-compr-handler))
5758 (let ((entry (rassoc fnh file-name-handler-alist)))
5760 (setq file-name-handler-alist
5761 (cons entry (delete entry file-name-handler-alist))))))))
5763 ;; `tramp-file-name-handler' must be registered before evaluation of
5764 ;; site-start and init files, because there might exist remote files
5765 ;; already, f.e. files kept via recentf-mode.
5766 ;;;###autoload(tramp-register-file-name-handlers)
5767 (tramp-register-file-name-handlers)
5770 (defun tramp-unload-file-name-handlers ()
5771 (setq file-name-handler-alist
5772 (delete (rassoc 'tramp-file-name-handler
5773 file-name-handler-alist)
5774 (delete (rassoc 'tramp-completion-file-name-handler
5775 file-name-handler-alist)
5776 file-name-handler-alist))))
5778 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5780 ;;; File name handler functions for completion mode:
5782 (defvar tramp-completion-mode nil
5783 "If non-nil, external packages signal that they are in file name completion.
5785 This is necessary, because Tramp uses a heuristic depending on last
5786 input event. This fails when external packages use other characters
5787 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5788 should never be set globally, the intention is to let-bind it.")
5790 ;; Necessary because `tramp-file-name-regexp-unified' and
5791 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5792 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5793 ;; to `tramp-file-name-handler'). Otherwise, it takes
5794 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5795 ;; risky, because completing a file might require loading other files,
5796 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5797 ;; variable. On the other hand, those files shouldn't have partial
5798 ;; Tramp file name syntax. Maybe another variable should be introduced
5799 ;; overwriting this check in such cases. Or we change Tramp file name
5800 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5801 (defun tramp-completion-mode-p ()
5802 "Check, whether method / user name / host name completion is active."
5804 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5805 (and (boundp 'non-essential) (symbol-value 'non-essential))
5806 tramp-completion-mode
5808 (equal last-input-event 'tab)
5809 (and (natnump last-input-event)
5811 ;; ?\t has event-modifier 'control.
5812 (equal last-input-event ?\t)
5813 (and (not (event-modifiers last-input-event))
5814 (or (equal last-input-event ?\?)
5815 (equal last-input-event ?\ )))))
5817 (and (featurep 'xemacs)
5818 ;; `last-input-event' might be nil.
5819 (not (null last-input-event))
5820 ;; `last-input-event' may have no character approximation.
5821 (tramp-compat-funcall 'event-to-character last-input-event)
5823 ;; ?\t has event-modifier 'control.
5825 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
5826 (and (not (event-modifiers last-input-event))
5828 (tramp-compat-funcall 'event-to-character last-input-event)
5831 (tramp-compat-funcall 'event-to-character last-input-event)
5834 (defun tramp-connectable-p (filename)
5835 "Check, whether it is possible to connect the remote host w/o side-effects.
5836 This is true, if either the remote host is already connected, or if we are
5837 not in completion mode."
5838 (and (tramp-tramp-file-p filename)
5839 (with-parsed-tramp-file-name filename nil
5840 (or (get-buffer (tramp-buffer-name v))
5841 (not (tramp-completion-mode-p))))))
5843 ;; Method, host name and user name completion.
5844 ;; `tramp-completion-dissect-file-name' returns a list of
5845 ;; tramp-file-name structures. For all of them we return possible completions.
5847 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5848 "Like `file-name-all-completions' for partial Tramp files."
5850 (let* ((fullname (tramp-drop-volume-letter
5851 (expand-file-name filename directory)))
5852 ;; Possible completion structures.
5853 (v (tramp-completion-dissect-file-name fullname))
5857 (let* ((car (car v))
5858 (method (tramp-file-name-method car))
5859 (user (tramp-file-name-user car))
5860 (host (tramp-file-name-host car))
5861 (localname (tramp-file-name-localname car))
5862 (m (tramp-find-method method user host))
5863 (tramp-current-user user) ; see `tramp-parse-passwd'
5866 (unless localname ;; Nothing to complete.
5870 ;; Method dependent user / host combinations.
5874 (setq all-user-hosts
5875 (append all-user-hosts
5876 (funcall (nth 0 x) (nth 1 x)))))
5877 (tramp-get-completion-function m))
5883 (tramp-get-completion-user-host
5884 method user host (nth 0 x) (nth 1 x)))
5885 (delq nil all-user-hosts)))))
5887 ;; Possible methods.
5889 (append result (tramp-get-completion-methods m)))))
5893 ;; Unify list, remove nil elements.
5895 (let ((car (car result)))
5899 (substring car (length (tramp-drop-volume-letter directory)))))
5900 (setq result (cdr result))))
5902 ;; Complete local parts.
5906 (apply (if (tramp-connectable-p fullname)
5907 'tramp-completion-run-real-handler
5908 'tramp-run-real-handler)
5909 'file-name-all-completions (list (list filename directory)))
5912 ;; Method, host name and user name completion for a file.
5914 (defun tramp-completion-handle-file-name-completion
5915 (filename directory &optional predicate)
5916 "Like `file-name-completion' for Tramp files."
5919 (mapcar 'list (file-name-all-completions filename directory))
5920 (when (and predicate
5921 (tramp-connectable-p (expand-file-name filename directory)))
5922 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5924 ;; I misuse a little bit the tramp-file-name structure in order to handle
5925 ;; completion possibilities for partial methods / user names / host names.
5926 ;; Return value is a list of tramp-file-name structures according to possible
5927 ;; completions. If "localname" is non-nil it means there
5928 ;; shouldn't be a completion anymore.
5930 ;; Expected results:
5932 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5933 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5934 ;; [nil "x" nil nil]
5935 ;; ["x" nil nil nil]
5937 ;; "/x:" "/x:y" "/x:y:"
5938 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5940 ;; ["x" nil "" nil] ["x" nil "y" nil]
5941 ;; ["x" "" nil nil] ["x" "y" nil nil]
5943 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5944 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5945 ;; "/[x/y@" "/[x/y@z"
5946 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5947 (defun tramp-completion-dissect-file-name (name)
5948 "Returns a list of `tramp-file-name' structures.
5949 They are collected by `tramp-completion-dissect-file-name1'."
5953 (tramp-completion-ipv6-regexp
5956 (if (zerop (length tramp-postfix-ipv6-format))
5957 tramp-postfix-host-format
5958 tramp-postfix-ipv6-format)))
5959 ;; "/method" "/[method"
5960 (tramp-completion-file-name-structure1
5961 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5964 (tramp-completion-file-name-structure2
5965 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5968 (tramp-completion-file-name-structure3
5969 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5971 ;; "/[ipv6" "/[ipv6"
5972 (tramp-completion-file-name-structure4
5973 (list (concat tramp-prefix-regexp
5974 tramp-prefix-ipv6-regexp
5975 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5977 ;; "/user@host" "/[user@host"
5978 (tramp-completion-file-name-structure5
5979 (list (concat tramp-prefix-regexp
5980 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5981 "\\(" tramp-host-regexp x-nil "\\)$")
5983 ;; "/user@[ipv6" "/[user@ipv6"
5984 (tramp-completion-file-name-structure6
5985 (list (concat tramp-prefix-regexp
5986 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5987 tramp-prefix-ipv6-regexp
5988 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5990 ;; "/method:user" "/[method/user" "/method://user"
5991 (tramp-completion-file-name-structure7
5992 (list (concat tramp-prefix-regexp
5993 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5994 "\\(" tramp-user-regexp x-nil "\\)$")
5996 ;; "/method:host" "/[method/host" "/method://host"
5997 (tramp-completion-file-name-structure8
5998 (list (concat tramp-prefix-regexp
5999 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6000 "\\(" tramp-host-regexp x-nil "\\)$")
6002 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
6003 (tramp-completion-file-name-structure9
6004 (list (concat tramp-prefix-regexp
6005 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6006 tramp-prefix-ipv6-regexp
6007 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6009 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
6010 (tramp-completion-file-name-structure10
6011 (list (concat tramp-prefix-regexp
6012 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6013 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6014 "\\(" tramp-host-regexp x-nil "\\)$")
6016 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
6017 (tramp-completion-file-name-structure11
6018 (list (concat tramp-prefix-regexp
6019 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6020 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6021 tramp-prefix-ipv6-regexp
6022 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6024 ;; "/method: "/method:/"
6025 (tramp-completion-file-name-structure12
6027 (if (equal tramp-syntax 'url)
6028 (concat tramp-prefix-regexp
6029 "\\(" tramp-method-regexp "\\)"
6030 "\\(" (substring tramp-postfix-method-regexp 0 1)
6031 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6033 ;; Should not match if not URL syntax.
6034 (concat tramp-prefix-regexp "/$"))
6036 ;; "/method: "/method:/"
6037 (tramp-completion-file-name-structure13
6039 (if (equal tramp-syntax 'url)
6040 (concat tramp-prefix-regexp
6041 "\\(" tramp-method-regexp "\\)"
6042 "\\(" (substring tramp-postfix-method-regexp 0 1)
6043 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6045 ;; Should not match if not URL syntax.
6046 (concat tramp-prefix-regexp "/$"))
6049 (mapc (lambda (regexp)
6050 (add-to-list 'result
6051 (tramp-completion-dissect-file-name1 regexp name)))
6053 tramp-completion-file-name-structure1
6054 tramp-completion-file-name-structure2
6055 tramp-completion-file-name-structure3
6056 tramp-completion-file-name-structure4
6057 tramp-completion-file-name-structure5
6058 tramp-completion-file-name-structure6
6059 tramp-completion-file-name-structure7
6060 tramp-completion-file-name-structure8
6061 tramp-completion-file-name-structure9
6062 tramp-completion-file-name-structure10
6063 tramp-completion-file-name-structure11
6064 tramp-completion-file-name-structure12
6065 tramp-completion-file-name-structure13
6066 tramp-file-name-structure))
6070 (defun tramp-completion-dissect-file-name1 (structure name)
6071 "Returns a `tramp-file-name' structure matching STRUCTURE.
6072 The structure consists of remote method, remote user,
6073 remote host and localname (filename on remote host)."
6076 (when (string-match (nth 0 structure) name)
6077 (let ((method (and (nth 1 structure)
6078 (match-string (nth 1 structure) name)))
6079 (user (and (nth 2 structure)
6080 (match-string (nth 2 structure) name)))
6081 (host (and (nth 3 structure)
6082 (match-string (nth 3 structure) name)))
6083 (localname (and (nth 4 structure)
6084 (match-string (nth 4 structure) name))))
6085 (vector method user host localname)))))
6087 ;; This function returns all possible method completions, adding the
6088 ;; trailing method delimeter.
6089 (defun tramp-get-completion-methods (partial-method)
6090 "Returns all method completions for PARTIAL-METHOD."
6094 (string-match (concat "^" (regexp-quote partial-method)) method)
6095 (tramp-completion-make-tramp-file-name method nil nil nil)))
6096 (mapcar 'car tramp-methods)))
6098 ;; Compares partial user and host names with possible completions.
6099 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
6100 "Returns the most expanded string for user and host name completion.
6101 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
6104 ((and partial-user partial-host)
6106 (string-match (concat "^" (regexp-quote partial-host)) host)
6107 (string-equal partial-user (or user partial-user)))
6108 (setq user partial-user)
6115 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
6121 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
6127 (unless (zerop (+ (length user) (length host)))
6128 (tramp-completion-make-tramp-file-name method user host nil)))
6130 (defun tramp-parse-rhosts (filename)
6131 "Return a list of (user host) tuples allowed to access.
6132 Either user or host may be nil."
6133 ;; On Windows, there are problems in completion when
6134 ;; `default-directory' is remote.
6135 (let ((default-directory (tramp-compat-temporary-file-directory))
6137 (when (file-readable-p filename)
6139 (insert-file-contents filename)
6140 (goto-char (point-min))
6142 (push (tramp-parse-rhosts-group) res))))
6145 (defun tramp-parse-rhosts-group ()
6146 "Return a (user host) tuple allowed to access.
6147 Either user or host may be nil."
6151 "^\\(" tramp-host-regexp "\\)"
6152 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6153 (narrow-to-region (point) (tramp-compat-line-end-position))
6154 (when (re-search-forward regexp nil t)
6155 (setq result (append (list (match-string 3) (match-string 1)))))
6160 (defun tramp-parse-shosts (filename)
6161 "Return a list of (user host) tuples allowed to access.
6162 User is always nil."
6163 ;; On Windows, there are problems in completion when
6164 ;; `default-directory' is remote.
6165 (let ((default-directory (tramp-compat-temporary-file-directory))
6167 (when (file-readable-p filename)
6169 (insert-file-contents filename)
6170 (goto-char (point-min))
6172 (push (tramp-parse-shosts-group) res))))
6175 (defun tramp-parse-shosts-group ()
6176 "Return a (user host) tuple allowed to access.
6177 User is always nil."
6179 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
6180 (narrow-to-region (point) (tramp-compat-line-end-position))
6181 (when (re-search-forward regexp nil t)
6182 (setq result (list nil (match-string 1))))
6185 (> (skip-chars-forward ",") 0)
6189 (defun tramp-parse-sconfig (filename)
6190 "Return a list of (user host) tuples allowed to access.
6191 User is always nil."
6192 ;; On Windows, there are problems in completion when
6193 ;; `default-directory' is remote.
6194 (let ((default-directory (tramp-compat-temporary-file-directory))
6196 (when (file-readable-p filename)
6198 (insert-file-contents filename)
6199 (goto-char (point-min))
6201 (push (tramp-parse-sconfig-group) res))))
6204 (defun tramp-parse-sconfig-group ()
6205 "Return a (user host) tuple allowed to access.
6206 User is always nil."
6208 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
6209 (narrow-to-region (point) (tramp-compat-line-end-position))
6210 (when (re-search-forward regexp nil t)
6211 (setq result (list nil (match-string 1))))
6214 (> (skip-chars-forward ",") 0)
6218 (defun tramp-parse-shostkeys (dirname)
6219 "Return a list of (user host) tuples allowed to access.
6220 User is always nil."
6221 ;; On Windows, there are problems in completion when
6222 ;; `default-directory' is remote.
6223 (let* ((default-directory (tramp-compat-temporary-file-directory))
6224 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6225 (files (when (file-directory-p dirname) (directory-files dirname)))
6228 (when (string-match regexp (car files))
6229 (push (list nil (match-string 1 (car files))) result))
6230 (setq files (cdr files)))
6233 (defun tramp-parse-sknownhosts (dirname)
6234 "Return a list of (user host) tuples allowed to access.
6235 User is always nil."
6236 ;; On Windows, there are problems in completion when
6237 ;; `default-directory' is remote.
6238 (let* ((default-directory (tramp-compat-temporary-file-directory))
6239 (regexp (concat "^\\(" tramp-host-regexp
6240 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6241 (files (when (file-directory-p dirname) (directory-files dirname)))
6244 (when (string-match regexp (car files))
6245 (push (list nil (match-string 1 (car files))) result))
6246 (setq files (cdr files)))
6249 (defun tramp-parse-hosts (filename)
6250 "Return a list of (user host) tuples allowed to access.
6251 User is always nil."
6252 ;; On Windows, there are problems in completion when
6253 ;; `default-directory' is remote.
6254 (let ((default-directory (tramp-compat-temporary-file-directory))
6256 (when (file-readable-p filename)
6258 (insert-file-contents filename)
6259 (goto-char (point-min))
6261 (push (tramp-parse-hosts-group) res))))
6264 (defun tramp-parse-hosts-group ()
6265 "Return a (user host) tuple allowed to access.
6266 User is always nil."
6269 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6270 (narrow-to-region (point) (tramp-compat-line-end-position))
6271 (when (re-search-forward regexp nil t)
6272 (setq result (list nil (match-string 1))))
6275 (> (skip-chars-forward " \t") 0)
6279 ;; For su-alike methods it would be desirable to return "root@localhost"
6280 ;; as default. Unfortunately, we have no information whether any user name
6281 ;; has been typed already. So we use `tramp-current-user' as indication,
6282 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6283 (defun tramp-parse-passwd (filename)
6284 "Return a list of (user host) tuples allowed to access.
6285 Host is always \"localhost\"."
6286 ;; On Windows, there are problems in completion when
6287 ;; `default-directory' is remote.
6288 (let ((default-directory (tramp-compat-temporary-file-directory))
6290 (if (zerop (length tramp-current-user))
6292 (when (file-readable-p filename)
6294 (insert-file-contents filename)
6295 (goto-char (point-min))
6297 (push (tramp-parse-passwd-group) res))))
6300 (defun tramp-parse-passwd-group ()
6301 "Return a (user host) tuple allowed to access.
6302 Host is always \"localhost\"."
6304 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6305 (narrow-to-region (point) (tramp-compat-line-end-position))
6306 (when (re-search-forward regexp nil t)
6307 (setq result (list (match-string 1) "localhost")))
6312 (defun tramp-parse-netrc (filename)
6313 "Return a list of (user host) tuples allowed to access.
6315 ;; On Windows, there are problems in completion when
6316 ;; `default-directory' is remote.
6317 (let ((default-directory (tramp-compat-temporary-file-directory))
6319 (when (file-readable-p filename)
6321 (insert-file-contents filename)
6322 (goto-char (point-min))
6324 (push (tramp-parse-netrc-group) res))))
6327 (defun tramp-parse-netrc-group ()
6328 "Return a (user host) tuple allowed to access.
6333 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6334 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6335 (narrow-to-region (point) (tramp-compat-line-end-position))
6336 (when (re-search-forward regexp nil t)
6337 (setq result (list (match-string 3) (match-string 1))))
6342 (defun tramp-parse-putty (registry)
6343 "Return a list of (user host) tuples allowed to access.
6344 User is always nil."
6345 ;; On Windows, there are problems in completion when
6346 ;; `default-directory' is remote.
6347 (let ((default-directory (tramp-compat-temporary-file-directory))
6350 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6351 (goto-char (point-min))
6353 (push (tramp-parse-putty-group registry) res))))
6356 (defun tramp-parse-putty-group (registry)
6357 "Return a (user host) tuple allowed to access.
6358 User is always nil."
6360 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6361 (narrow-to-region (point) (tramp-compat-line-end-position))
6362 (when (re-search-forward regexp nil t)
6363 (setq result (list nil (match-string 1))))
6368 ;;; Internal Functions:
6370 (defun tramp-maybe-send-script (vec script name)
6371 "Define in remote shell function NAME implemented as SCRIPT.
6372 Only send the definition if it has not already been done."
6373 (let* ((p (tramp-get-connection-process vec))
6374 (scripts (tramp-get-connection-property p "scripts" nil)))
6375 (unless (member name scripts)
6376 (with-progress-reporter vec 5 (format "Sending script `%s'" name)
6377 ;; The script could contain a call of Perl. This is masked with `%s'.
6378 (tramp-send-command-and-check
6380 (format "%s () {\n%s\n}" name
6381 (format script (tramp-get-remote-perl vec))))
6382 (tramp-set-connection-property p "scripts" (cons name scripts))))))
6384 (defun tramp-set-auto-save ()
6385 (when (and ;; ange-ftp has its own auto-save mechanism
6386 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6387 'tramp-sh-file-name-handler)
6389 (auto-save-mode 1)))
6390 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6391 (add-hook 'tramp-unload-hook
6393 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6395 (defun tramp-run-test (switch filename)
6396 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6397 Returns the exit code of the `test' program."
6398 (with-parsed-tramp-file-name filename nil
6399 (tramp-send-command-and-check
6403 (tramp-get-test-command v)
6405 (tramp-shell-quote-argument localname)))))
6407 (defun tramp-run-test2 (format-string file1 file2)
6408 "Run `test'-like program on the remote system, given FILE1, FILE2.
6409 FORMAT-STRING contains the program name, switches, and place holders.
6410 Returns the exit code of the `test' program. Barfs if the methods,
6411 hosts, or files, disagree."
6412 (unless (tramp-equal-remote file1 file2)
6413 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6416 "tramp-run-test2 only implemented for same method, user, host")))
6417 (with-parsed-tramp-file-name file1 v1
6418 (with-parsed-tramp-file-name file1 v2
6419 (tramp-send-command-and-check
6421 (format format-string
6422 (tramp-shell-quote-argument v1-localname)
6423 (tramp-shell-quote-argument v2-localname))))))
6425 (defun tramp-buffer-name (vec)
6426 "A name for the connection buffer VEC."
6427 ;; We must use `tramp-file-name-real-host', because for gateway
6428 ;; methods the default port will be expanded later on, which would
6430 (let ((method (tramp-file-name-method vec))
6431 (user (tramp-file-name-user vec))
6432 (host (tramp-file-name-real-host vec)))
6433 (if (not (zerop (length user)))
6434 (format "*tramp/%s %s@%s*" method user host)
6435 (format "*tramp/%s %s*" method host))))
6437 (defun tramp-delete-temp-file-function ()
6438 "Remove temporary files related to current buffer."
6439 (when (stringp tramp-temp-buffer-file-name)
6441 (delete-file tramp-temp-buffer-file-name)
6444 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6445 (add-hook 'tramp-cache-unload-hook
6447 (remove-hook 'kill-buffer-hook
6448 'tramp-delete-temp-file-function)))
6450 (defun tramp-get-buffer (vec)
6451 "Get the connection buffer to be used for VEC."
6452 (or (get-buffer (tramp-buffer-name vec))
6453 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6454 (setq buffer-undo-list t)
6455 (setq default-directory
6456 (tramp-make-tramp-file-name
6457 (tramp-file-name-method vec)
6458 (tramp-file-name-user vec)
6459 (tramp-file-name-host vec)
6463 (defun tramp-get-connection-buffer (vec)
6464 "Get the connection buffer to be used for VEC.
6465 In case a second asynchronous communication has been started, it is different
6466 from `tramp-get-buffer'."
6467 (or (tramp-get-connection-property vec "process-buffer" nil)
6468 (tramp-get-buffer vec)))
6470 (defun tramp-get-connection-process (vec)
6471 "Get the connection process to be used for VEC.
6472 In case a second asynchronous communication has been started, it is different
6473 from the default one."
6475 (or (tramp-get-connection-property vec "process-name" nil)
6476 (tramp-buffer-name vec))))
6478 (defun tramp-debug-buffer-name (vec)
6479 "A name for the debug buffer for VEC."
6480 ;; We must use `tramp-file-name-real-host', because for gateway
6481 ;; methods the default port will be expanded later on, which would
6483 (let ((method (tramp-file-name-method vec))
6484 (user (tramp-file-name-user vec))
6485 (host (tramp-file-name-real-host vec)))
6486 (if (not (zerop (length user)))
6487 (format "*debug tramp/%s %s@%s*" method user host)
6488 (format "*debug tramp/%s %s*" method host))))
6490 (defconst tramp-debug-outline-regexp
6491 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6493 (defun tramp-get-debug-buffer (vec)
6494 "Get the debug buffer for VEC."
6495 (with-current-buffer
6496 (get-buffer-create (tramp-debug-buffer-name vec))
6498 (setq buffer-undo-list t)
6499 ;; Activate `outline-mode'. This runs `text-mode-hook' and
6500 ;; `outline-mode-hook'. We must prevent that local processes
6501 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6502 ;; Furthermore, `outline-regexp' must have the correct value
6503 ;; already, because it is used by `font-lock-compile-keywords'.
6504 (let ((default-directory (tramp-compat-temporary-file-directory))
6505 (outline-regexp tramp-debug-outline-regexp))
6507 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
6508 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6511 (defun tramp-outline-level ()
6512 "Return the depth to which a statement is nested in the outline.
6513 Point must be at the beginning of a header line.
6515 The outline level is equal to the verbosity of the Tramp message."
6516 (1+ (string-to-number (match-string 1))))
6518 (defun tramp-find-executable
6519 (vec progname dirlist &optional ignore-tilde ignore-path)
6520 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6521 First arg VEC specifies the connection, PROGNAME is the program
6522 to search for, and DIRLIST gives the list of directories to
6523 search. If IGNORE-TILDE is non-nil, directory names starting
6524 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6527 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6529 This function expects to be in the right *tramp* buffer."
6530 (with-current-buffer (tramp-get-connection-buffer vec)
6532 ;; Check whether the executable is in $PATH. "which(1)" does not
6533 ;; report always a correct error code; therefore we check the
6534 ;; number of words it returns.
6536 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6537 (goto-char (point-min))
6538 (if (looking-at "^\\s-*1$")
6539 (setq result (concat "\\" progname))))
6542 ;; Remove all ~/foo directories from dirlist. In XEmacs,
6543 ;; `remove' is in CL, and we want to avoid CL dependencies.
6546 (setq d (car dirlist))
6547 (setq dirlist (cdr dirlist))
6548 (unless (char-equal ?~ (aref d 0))
6549 (setq newdl (cons d newdl))))
6550 (setq dirlist (nreverse newdl))))
6553 (format (concat "while read d; "
6554 "do if test -x $d/%s -a -f $d/%s; "
6555 "then echo tramp_executable $d/%s; "
6556 "break; fi; done <<'EOF'\n"
6558 progname progname progname (mapconcat 'identity dirlist "\n")))
6559 (goto-char (point-max))
6560 (when (search-backward "tramp_executable " nil t)
6561 (skip-chars-forward "^ ")
6562 (skip-chars-forward " ")
6563 (setq result (buffer-substring
6564 (point) (tramp-compat-line-end-position)))))
6567 (defun tramp-set-remote-path (vec)
6568 "Sets the remote environment PATH to existing directories.
6569 I.e., for each directory in `tramp-remote-path', it is tested
6570 whether it exists and if so, it is added to the environment
6572 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6574 vec (format "PATH=%s; export PATH"
6575 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6577 ;; ------------------------------------------------------------
6578 ;; -- Communication with external shell --
6579 ;; ------------------------------------------------------------
6581 (defun tramp-find-file-exists-command (vec)
6582 "Find a command on the remote host for checking if a file exists.
6583 Here, we are looking for a command which has zero exit status if the
6584 file exists and nonzero exit status otherwise."
6585 (let ((existing "/")
6587 (tramp-shell-quote-argument "/ this file does not exist "))
6589 ;; The algorithm is as follows: we try a list of several commands.
6590 ;; For each command, we first run `$cmd /' -- this should return
6591 ;; true, as the root directory always exists. And then we run
6592 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6593 ;; does not exist. This should return false. We use the first
6594 ;; command we find that seems to work.
6595 ;; The list of commands to try is as follows:
6596 ;; `ls -d' This works on most systems, but NetBSD 1.4
6597 ;; has a bug: `ls' always returns zero exit
6598 ;; status, even for files which don't exist.
6599 ;; `test -e' Some Bourne shells have a `test' builtin
6600 ;; which does not know the `-e' option.
6601 ;; `/bin/test -e' For those, the `test' binary on disk normally
6602 ;; provides the option. Alas, the binary
6603 ;; is sometimes `/bin/test' and sometimes it's
6605 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6607 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6608 (zerop (tramp-send-command-and-check
6609 vec (format "%s %s" result existing)))
6610 (not (zerop (tramp-send-command-and-check
6611 vec (format "%s %s" result nonexisting)))))
6612 (and (setq result "/bin/test -e")
6613 (zerop (tramp-send-command-and-check
6614 vec (format "%s %s" result existing)))
6615 (not (zerop (tramp-send-command-and-check
6616 vec (format "%s %s" result nonexisting)))))
6617 (and (setq result "/usr/bin/test -e")
6618 (zerop (tramp-send-command-and-check
6619 vec (format "%s %s" result existing)))
6620 (not (zerop (tramp-send-command-and-check
6621 vec (format "%s %s" result nonexisting)))))
6622 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6623 (zerop (tramp-send-command-and-check
6624 vec (format "%s %s" result existing)))
6625 (not (zerop (tramp-send-command-and-check
6626 vec (format "%s %s" result nonexisting))))))
6628 vec 'file-error "Couldn't find command to check if file exists"))
6631 (defun tramp-open-shell (vec shell)
6632 "Opens shell SHELL."
6633 (with-progress-reporter vec 5 (format "Opening remote shell `%s'" shell)
6634 ;; Find arguments for this shell.
6635 (let ((tramp-end-of-output tramp-initial-end-of-output)
6636 (alist tramp-sh-extra-args)
6638 (while (and alist (null extra-args))
6639 (setq item (pop alist))
6640 (when (string-match (car item) shell)
6641 (setq extra-args (cdr item))))
6642 (when extra-args (setq shell (concat shell " " extra-args)))
6644 vec (format "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6645 (shell-quote-argument tramp-end-of-output) shell)
6649 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6650 (tramp-send-command vec "PS2=''" t)
6651 (tramp-send-command vec "PS3=''" t)
6652 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
6654 (defun tramp-find-shell (vec)
6655 "Opens a shell on the remote host which groks tilde expansion."
6656 (unless (tramp-get-connection-property vec "remote-shell" nil)
6658 (with-current-buffer (tramp-get-buffer vec)
6659 (tramp-send-command vec "echo ~root" t)
6661 ((or (string-match "^~root$" (buffer-string))
6662 ;; The default shell (ksh93) of OpenSolaris is buggy.
6663 (string-equal (tramp-get-connection-property vec "uname" "")
6666 (or (tramp-find-executable
6667 vec "bash" (tramp-get-remote-path vec) t t)
6668 (tramp-find-executable
6669 vec "ksh" (tramp-get-remote-path vec) t t)))
6673 "Couldn't find a shell which groks tilde expansion"))
6675 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
6676 (tramp-open-shell vec shell))
6679 vec 5 "Remote `%s' groks tilde expansion, good"
6680 (tramp-set-connection-property
6682 (tramp-get-method-parameter
6683 (tramp-file-name-method vec) 'tramp-remote-sh)))))))))
6685 ;; ------------------------------------------------------------
6686 ;; -- Functions for establishing connection --
6687 ;; ------------------------------------------------------------
6689 ;; The following functions are actions to be taken when seeing certain
6690 ;; prompts from the remote host. See the variable
6691 ;; `tramp-actions-before-shell' for usage of these functions.
6693 (defun tramp-action-login (proc vec)
6694 "Send the login name."
6695 (when (not (stringp tramp-current-user))
6696 (save-window-excursion
6697 (let ((enable-recursive-minibuffers t))
6698 (pop-to-buffer (tramp-get-connection-buffer vec))
6699 (setq tramp-current-user (read-string (match-string 0))))))
6700 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6701 (with-current-buffer (tramp-get-connection-buffer vec)
6702 (tramp-message vec 6 "\n%s" (buffer-string)))
6703 (tramp-send-string vec tramp-current-user))
6705 (defun tramp-action-password (proc vec)
6706 "Query the user for a password."
6707 (with-current-buffer (process-buffer proc)
6708 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6709 (tramp-message vec 3 "Sending %s" (match-string 1))
6710 (tramp-enter-password proc)
6711 ;; Hide password prompt.
6712 (narrow-to-region (point-max) (point-max))))
6714 (defun tramp-action-succeed (proc vec)
6715 "Signal success in finding shell prompt."
6716 (throw 'tramp-action 'ok))
6718 (defun tramp-action-permission-denied (proc vec)
6719 "Signal permission denied."
6721 (throw 'tramp-action 'permission-denied))
6723 (defun tramp-action-yesno (proc vec)
6724 "Ask the user for confirmation using `yes-or-no-p'.
6725 Send \"yes\" to remote process on confirmation, abort otherwise.
6726 See also `tramp-action-yn'."
6727 (save-window-excursion
6728 (let ((enable-recursive-minibuffers t))
6729 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6730 (unless (yes-or-no-p (match-string 0))
6732 (throw 'tramp-action 'permission-denied))
6733 (with-current-buffer (tramp-get-connection-buffer vec)
6734 (tramp-message vec 6 "\n%s" (buffer-string)))
6735 (tramp-send-string vec "yes"))))
6737 (defun tramp-action-yn (proc vec)
6738 "Ask the user for confirmation using `y-or-n-p'.
6739 Send \"y\" to remote process on confirmation, abort otherwise.
6740 See also `tramp-action-yesno'."
6741 (save-window-excursion
6742 (let ((enable-recursive-minibuffers t))
6743 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6744 (unless (y-or-n-p (match-string 0))
6746 (throw 'tramp-action 'permission-denied))
6747 (with-current-buffer (tramp-get-connection-buffer vec)
6748 (tramp-message vec 6 "\n%s" (buffer-string)))
6749 (tramp-send-string vec "y"))))
6751 (defun tramp-action-terminal (proc vec)
6752 "Tell the remote host which terminal type to use.
6753 The terminal type can be configured with `tramp-terminal-type'."
6754 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6755 (with-current-buffer (tramp-get-connection-buffer vec)
6756 (tramp-message vec 6 "\n%s" (buffer-string)))
6757 (tramp-send-string vec tramp-terminal-type))
6759 (defun tramp-action-process-alive (proc vec)
6760 "Check, whether a process has finished."
6761 (unless (memq (process-status proc) '(run open))
6762 (throw 'tramp-action 'process-died)))
6764 (defun tramp-action-out-of-band (proc vec)
6765 "Check, whether an out-of-band copy has finished."
6766 (cond ((and (memq (process-status proc) '(stop exit))
6767 (zerop (process-exit-status proc)))
6768 (tramp-message vec 3 "Process has finished.")
6769 (throw 'tramp-action 'ok))
6770 ((or (and (memq (process-status proc) '(stop exit))
6771 (not (zerop (process-exit-status proc))))
6772 (memq (process-status proc) '(signal)))
6773 ;; `scp' could have copied correctly, but set modes could have failed.
6774 ;; This can be ignored.
6775 (with-current-buffer (process-buffer proc)
6776 (goto-char (point-min))
6777 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6779 (tramp-message vec 5 "'set mode' error ignored.")
6780 (tramp-message vec 3 "Process has finished.")
6781 (throw 'tramp-action 'ok))
6782 (tramp-message vec 3 "Process has died.")
6783 (throw 'tramp-action 'process-died))))
6786 ;; Functions for processing the actions.
6788 (defun tramp-process-one-action (proc vec actions)
6789 "Wait for output from the shell and perform one action."
6790 (let (found todo item pattern action)
6792 ;; Reread output once all actions have been performed.
6793 ;; Obviously, the output was not complete.
6794 (tramp-accept-process-output proc 1)
6797 (setq item (pop todo))
6798 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6799 (setq action (nth 1 item))
6801 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6802 (when (tramp-check-for-regexp proc pattern)
6803 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6804 (setq found (funcall action proc vec)))))
6807 (defun tramp-process-actions (proc vec actions &optional timeout)
6808 "Perform actions until success or TIMEOUT."
6809 ;; Preserve message for `progress-reporter'.
6810 (with-temp-message ""
6811 ;; Enable auth-source and password-cache.
6812 (tramp-set-connection-property vec "first-password-request" t)
6815 (tramp-message proc 3 "Waiting for prompts from remote shell")
6817 (catch 'tramp-action
6819 (with-timeout (timeout)
6820 (tramp-process-one-action proc vec actions))
6821 (tramp-process-one-action proc vec actions)))))
6822 (with-current-buffer (tramp-get-connection-buffer vec)
6824 (tramp-message vec 6 "\n%s" (buffer-string)))
6825 (unless (eq exit 'ok)
6826 (tramp-clear-passwd vec)
6827 (tramp-error-with-buffer
6830 ((eq exit 'permission-denied) "Permission denied")
6831 ((eq exit 'process-died) "Process died")
6832 (t "Login failed")))))))
6834 ;; Utility functions.
6836 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6837 "Like `accept-process-output' for Tramp processes.
6838 This is needed in order to hide `last-coding-system-used', which is set
6839 for process communication also."
6840 (with-current-buffer (process-buffer proc)
6841 (tramp-message proc 10 "%s %s" proc (process-status proc))
6842 (let (buffer-read-only last-coding-system-used)
6843 ;; Under Windows XP, accept-process-output doesn't return
6844 ;; sometimes. So we add an additional timeout.
6845 (with-timeout ((or timeout 1))
6846 (accept-process-output proc timeout timeout-msecs)))
6847 (tramp-message proc 10 "\n%s" (buffer-string))))
6849 (defun tramp-check-for-regexp (proc regexp)
6850 "Check, whether REGEXP is contained in process buffer of PROC.
6851 Erase echoed commands if exists."
6852 (with-current-buffer (process-buffer proc)
6853 (goto-char (point-min))
6855 ;; Check whether we need to remove echo output.
6856 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6857 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6858 (let ((begin (match-beginning 0)))
6859 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6860 ;; Discard echo from remote output.
6861 (tramp-set-connection-property proc "check-remote-echo" nil)
6862 (tramp-message proc 5 "echo-mark found")
6864 (delete-region begin (point))
6865 (goto-char (point-min)))))
6867 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6868 ;; Sometimes, the echo string is suppressed on the remote side.
6870 (tramp-compat-funcall
6871 'substring-no-properties tramp-echo-mark-marker
6872 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6873 (tramp-compat-funcall
6874 'buffer-substring-no-properties
6875 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6876 ;; No echo to be handled, now we can look for the regexp.
6877 (goto-char (point-min))
6878 (re-search-forward regexp nil t))))
6880 (defun tramp-wait-for-regexp (proc timeout regexp)
6881 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6882 Expects the output of PROC to be sent to the current buffer. Returns
6883 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6885 (with-current-buffer (process-buffer proc)
6886 (let ((found (tramp-check-for-regexp proc regexp))
6887 (start-time (current-time)))
6889 ;; Work around a bug in XEmacs 21, where the timeout
6890 ;; expires faster than it should. This degenerates
6891 ;; to polling for buggy XEmacsen, but oh, well.
6892 (while (and (not found)
6893 (< (tramp-time-diff (current-time) start-time)
6895 (with-timeout (timeout)
6897 (tramp-accept-process-output proc 1)
6898 (unless (memq (process-status proc) '(run open))
6899 (tramp-error-with-buffer
6900 nil proc 'file-error "Process has died"))
6901 (setq found (tramp-check-for-regexp proc regexp))))))
6904 (tramp-accept-process-output proc 1)
6905 (unless (memq (process-status proc) '(run open))
6906 (tramp-error-with-buffer
6907 nil proc 'file-error "Process has died"))
6908 (setq found (tramp-check-for-regexp proc regexp)))))
6909 (tramp-message proc 6 "\n%s" (buffer-string))
6913 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6915 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6918 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6919 "Wait for shell prompt and barf if none appears.
6920 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6921 seconds. If not, it produces an error message with the given ERROR-ARGS."
6923 (tramp-wait-for-regexp
6926 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6927 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6929 ;; We don't call `tramp-send-string' in order to hide the password
6930 ;; from the debug buffer, and because end-of-line handling of the
6932 (defun tramp-enter-password (proc)
6933 "Prompt for a password and send it to the remote end."
6934 (process-send-string
6935 proc (concat (tramp-read-passwd proc)
6936 (or (tramp-get-method-parameter
6937 tramp-current-method
6938 'tramp-password-end-of-line)
6939 tramp-default-password-end-of-line))))
6941 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6942 "Set up an interactive shell.
6943 Mainly sets the prompt and the echo correctly. PROC is the shell
6944 process to set up. VEC specifies the connection."
6945 (let ((tramp-end-of-output tramp-initial-end-of-output))
6946 ;; It is useful to set the prompt in the following command because
6947 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6948 ;; about and thus /bin/sh will display a strange prompt. For
6949 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6950 ;; display the current working directory but /bin/sh will display
6951 ;; a dollar sign. The following command line sets $PS1 to a sane
6952 ;; value, and works under Bourne-ish shells as well as csh-like
6953 ;; shells. Daniel Pittman reports that the unusual positioning of
6954 ;; the single quotes makes it work under `rc', too. We also unset
6955 ;; the variable $ENV because that is read by some sh
6956 ;; implementations (eg, bash when called as sh) on startup; this
6957 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6958 ;; is another way to set the prompt in /bin/bash, it must be
6959 ;; discarded as well.
6962 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-remote-sh))
6965 (tramp-message vec 5 "Setting up remote shell environment")
6966 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6967 ;; Check whether the echo has really been disabled. Some
6968 ;; implementations, like busybox of embedded GNU/Linux, don't
6969 ;; support disabling.
6970 (tramp-send-command vec "echo foo" t)
6971 (with-current-buffer (process-buffer proc)
6972 (goto-char (point-min))
6973 (when (looking-at "echo foo")
6974 (tramp-set-connection-property proc "remote-echo" t)
6975 (tramp-message vec 5 "Remote echo still on. Ok.")
6976 ;; Make sure backspaces and their echo are enabled and no line
6977 ;; width magic interferes with them.
6978 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6980 (tramp-message vec 5 "Setting shell prompt")
6982 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6983 (tramp-send-command vec "PS2=''" t)
6984 (tramp-send-command vec "PS3=''" t)
6985 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6987 ;; Try to set up the coding system correctly.
6988 ;; CCC this can't be the right way to do it. Hm.
6989 (tramp-message vec 5 "Determining coding system")
6990 (tramp-send-command vec "echo foo ; echo bar" t)
6991 (with-current-buffer (process-buffer proc)
6992 (goto-char (point-min))
6993 (if (featurep 'mule)
6994 ;; Use MULE to select the right EOL convention for communicating
6995 ;; with the process.
6996 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
6997 (cons 'undecided 'undecided)))
6998 cs-decode cs-encode)
6999 (when (symbolp cs) (setq cs (cons cs cs)))
7000 (setq cs-decode (car cs))
7001 (setq cs-encode (cdr cs))
7002 (unless cs-decode (setq cs-decode 'undecided))
7003 (unless cs-encode (setq cs-encode 'undecided))
7004 (setq cs-encode (tramp-coding-system-change-eol-conversion
7006 (when (search-forward "\r" nil t)
7007 (setq cs-decode (tramp-coding-system-change-eol-conversion
7009 (tramp-compat-funcall
7010 'set-buffer-process-coding-system cs-decode cs-encode)
7012 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
7013 ;; Look for ^M and do something useful if found.
7014 (when (search-forward "\r" nil t)
7015 ;; We have found a ^M but cannot frob the process coding system
7016 ;; because we're running on a non-MULE Emacs. Let's try
7018 (tramp-send-command vec "stty -onlcr" t))))
7020 (tramp-send-command vec "set +o vi +o emacs" t)
7022 ;; Check whether the output of "uname -sr" has been changed. If
7023 ;; yes, this is a strong indication that we must expire all
7024 ;; connection properties. We start again with
7025 ;; `tramp-maybe-open-connection', it will be catched there.
7026 (tramp-message vec 5 "Checking system information")
7027 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
7029 (tramp-set-connection-property
7031 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
7032 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
7033 (with-current-buffer (tramp-get-debug-buffer vec)
7034 ;; Keep the debug buffer.
7036 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
7037 (tramp-compat-funcall 'tramp-cleanup-connection vec)
7038 (if (= (point-min) (point-max))
7040 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
7041 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
7042 (tramp-get-buffer vec)
7045 "Connection reset, because remote host changed from `%s' to `%s'"
7046 old-uname new-uname)
7047 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
7049 ;; Check whether the remote host suffers from buggy
7050 ;; `send-process-string'. This is known for FreeBSD (see comment in
7051 ;; `send_process', file process.c). I've tested sending 624 bytes
7052 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
7053 ;; this host type is detected locally. It cannot handle remote
7055 (with-connection-property proc "chunksize"
7057 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
7061 vec 5 "Checking remote host type for `send-process-string' bug")
7063 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
7066 ;; Set remote PATH variable.
7067 (tramp-set-remote-path vec)
7069 ;; Search for a good shell before searching for a command which
7070 ;; checks if a file exists. This is done because Tramp wants to use
7071 ;; "test foo; echo $?" to check if various conditions hold, and
7072 ;; there are buggy /bin/sh implementations which don't execute the
7073 ;; "echo $?" part if the "test" part has an error. In particular,
7074 ;; the OpenSolaris /bin/sh is a problem. There are also other
7075 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
7076 ;; in function declarations, or changing HISTFILE in place.
7077 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
7079 (tramp-find-shell vec)
7081 ;; Disable unexpected output.
7082 (tramp-send-command vec "mesg n; biff n" t)
7084 ;; IRIX64 bash expands "!" even when in single quotes. This
7085 ;; destroys our shell functions, we must disable it. See
7086 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
7087 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
7088 (tramp-send-command vec "set +H" t))
7090 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
7091 (when (string-match "BSD\\|Darwin"
7092 (tramp-get-connection-property vec "uname" ""))
7093 (tramp-send-command vec "stty -oxtabs" t))
7095 ;; Set `remote-tty' process property.
7097 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"")))
7098 (unless (zerop (length tty)) (process-put proc 'remote-tty tty))))
7100 ;; Dump stty settings in the traces.
7101 (when (>= tramp-verbose 9)
7102 (tramp-send-command vec "stty -a" t))
7104 ;; Set the environment.
7105 (tramp-message vec 5 "Setting default environment")
7107 (let ((env (copy-sequence tramp-remote-process-environment))
7110 (setq item (tramp-compat-split-string (car env) "="))
7111 (setcdr item (mapconcat 'identity (cdr item) "="))
7112 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
7114 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
7115 (push (car item) unset))
7116 (setq env (cdr env)))
7119 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
7121 ;; CCC: We should either implement a Perl version of base64 encoding
7122 ;; and decoding. Then we just use that in the last item. The other
7123 ;; alternative is to use the Perl version of UU encoding. But then
7124 ;; we need a Lisp version of uuencode.
7126 ;; Old text from documentation of tramp-methods:
7127 ;; Using a uuencode/uudecode inline method is discouraged, please use one
7128 ;; of the base64 methods instead since base64 encoding is much more
7129 ;; reliable and the commands are more standardized between the different
7130 ;; Unix versions. But if you can't use base64 for some reason, please
7131 ;; note that the default uudecode command does not work well for some
7132 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
7133 ;; the following command for uudecode:
7135 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
7137 ;; For Irix, no solution is known yet.
7139 (defconst tramp-local-coding-commands
7140 '((b64 base64-encode-region base64-decode-region)
7141 (uu tramp-uuencode-region uudecode-decode-region)
7143 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7144 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7145 "List of local coding commands for inline transfer.
7146 Each item is a list that looks like this:
7148 \(FORMAT ENCODING DECODING\)
7150 FORMAT is symbol describing the encoding/decoding format. It can be
7151 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7153 ENCODING and DECODING can be strings, giving commands, or symbols,
7154 giving functions. If they are strings, then they can contain
7155 the \"%s\" format specifier. If that specifier is present, the input
7156 filename will be put into the command line at that spot. If the
7157 specifier is not present, the input should be read from standard
7160 If they are functions, they will be called with two arguments, start
7161 and end of region, and are expected to replace the region contents
7162 with the encoded or decoded results, respectively.")
7164 (defconst tramp-remote-coding-commands
7165 '((b64 "base64" "base64 -d -i")
7166 ;; "-i" is more robust with older base64 from GNU coreutils.
7167 ;; However, I don't know whether all base64 versions do supports
7169 (b64 "base64" "base64 -d")
7170 (b64 "mimencode -b" "mimencode -u -b")
7171 (b64 "mmencode -b" "mmencode -u -b")
7172 (b64 "recode data..base64" "recode base64..data")
7173 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
7174 (b64 tramp-perl-encode tramp-perl-decode)
7175 (uu "uuencode xxx" "uudecode -o /dev/stdout")
7176 (uu "uuencode xxx" "uudecode -o -")
7177 (uu "uuencode xxx" "uudecode -p")
7178 (uu "uuencode xxx" tramp-uudecode)
7180 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7181 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7182 "List of remote coding commands for inline transfer.
7183 Each item is a list that looks like this:
7185 \(FORMAT ENCODING DECODING\)
7187 FORMAT is symbol describing the encoding/decoding format. It can be
7188 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7190 ENCODING and DECODING can be strings, giving commands, or symbols,
7191 giving variables. If they are strings, then they can contain
7192 the \"%s\" format specifier. If that specifier is present, the input
7193 filename will be put into the command line at that spot. If the
7194 specifier is not present, the input should be read from standard
7197 If they are variables, this variable is a string containing a Perl
7198 implementation for this functionality. This Perl program will be transferred
7199 to the remote host, and it is available as shell function with the same name.")
7201 (defun tramp-find-inline-encoding (vec)
7202 "Find an inline transfer encoding that works.
7203 Goes through the list `tramp-local-coding-commands' and
7204 `tramp-remote-coding-commands'."
7206 (let ((local-commands tramp-local-coding-commands)
7208 loc-enc loc-dec rem-enc rem-dec litem ritem found)
7209 (while (and local-commands (not found))
7210 (setq litem (pop local-commands))
7211 (catch 'wont-work-local
7212 (let ((format (nth 0 litem))
7213 (remote-commands tramp-remote-coding-commands))
7214 (setq loc-enc (nth 1 litem))
7215 (setq loc-dec (nth 2 litem))
7216 ;; If the local encoder or decoder is a string, the
7217 ;; corresponding command has to work locally.
7218 (if (not (stringp loc-enc))
7220 vec 5 "Checking local encoding function `%s'" loc-enc)
7222 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
7223 (unless (zerop (tramp-call-local-coding-command
7225 (throw 'wont-work-local nil)))
7226 (if (not (stringp loc-dec))
7228 vec 5 "Checking local decoding function `%s'" loc-dec)
7230 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7231 (unless (zerop (tramp-call-local-coding-command
7233 (throw 'wont-work-local nil)))
7234 ;; Search for remote coding commands with the same format
7235 (while (and remote-commands (not found))
7236 (setq ritem (pop remote-commands))
7237 (catch 'wont-work-remote
7238 (when (equal format (nth 0 ritem))
7239 (setq rem-enc (nth 1 ritem))
7240 (setq rem-dec (nth 2 ritem))
7241 ;; Check if remote encoding and decoding commands can be
7242 ;; called remotely with null input and output. This makes
7243 ;; sure there are no syntax errors and the command is really
7244 ;; found. Note that we do not redirect stdout to /dev/null,
7245 ;; for two reasons: when checking the decoding command, we
7246 ;; actually check the output it gives. And also, when
7247 ;; redirecting "mimencode" output to /dev/null, then as root
7248 ;; it might change the permissions of /dev/null!
7249 (when (not (stringp rem-enc))
7250 (let ((name (symbol-name rem-enc)))
7251 (while (string-match (regexp-quote "-") name)
7252 (setq name (replace-match "_" nil t name)))
7253 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7254 (setq rem-enc name)))
7257 "Checking remote encoding command `%s' for sanity" rem-enc)
7258 (unless (zerop (tramp-send-command-and-check
7259 vec (format "%s </dev/null" rem-enc) t))
7260 (throw 'wont-work-remote nil))
7262 (when (not (stringp rem-dec))
7263 (let ((name (symbol-name rem-dec)))
7264 (while (string-match (regexp-quote "-") name)
7265 (setq name (replace-match "_" nil t name)))
7266 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7267 (setq rem-dec name)))
7270 "Checking remote decoding command `%s' for sanity" rem-dec)
7271 (unless (zerop (tramp-send-command-and-check
7273 (format "echo %s | %s | %s"
7274 magic rem-enc rem-dec)
7276 (throw 'wont-work-remote nil))
7278 (with-current-buffer (tramp-get-buffer vec)
7279 (goto-char (point-min))
7280 (unless (looking-at (regexp-quote magic))
7281 (throw 'wont-work-remote nil)))
7283 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7284 (setq rem-enc (nth 1 ritem))
7285 (setq rem-dec (nth 2 ritem))
7286 (setq found t)))))))
7288 ;; Did we find something?
7291 vec 'file-error "Couldn't find an inline transfer encoding"))
7293 ;; Set connection properties.
7294 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7295 (tramp-set-connection-property vec "local-encoding" loc-enc)
7296 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7297 (tramp-set-connection-property vec "local-decoding" loc-dec)
7298 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7299 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7300 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7301 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7303 (defun tramp-call-local-coding-command (cmd input output)
7304 "Call the local encoding or decoding command.
7305 If CMD contains \"%s\", provide input file INPUT there in command.
7306 Otherwise, INPUT is passed via standard input.
7307 INPUT can also be nil which means `/dev/null'.
7308 OUTPUT can be a string (which specifies a filename), or t (which
7309 means standard output and thus the current buffer), or nil (which
7311 (tramp-local-call-process
7312 tramp-encoding-shell
7313 (when (and input (not (string-match "%s" cmd))) input)
7314 (if (eq output t) t nil)
7316 tramp-encoding-command-switch
7318 (if (string-match "%s" cmd) (format cmd input) cmd)
7319 (if (stringp output) (concat "> " output) ""))))
7321 (defconst tramp-inline-compress-commands
7322 '(("gzip" "gzip -d")
7323 ("bzip2" "bzip2 -d")
7324 ("compress" "compress -d"))
7325 "List of compress and decompress commands for inline transfer.
7326 Each item is a list that looks like this:
7328 \(COMPRESS DECOMPRESS\)
7330 COMPRESS or DECOMPRESS are strings with the respective commands.")
7332 (defun tramp-find-inline-compress (vec)
7333 "Find an inline transfer compress command that works.
7334 Goes through the list `tramp-inline-compress-commands'."
7336 (let ((commands tramp-inline-compress-commands)
7338 item compress decompress
7340 (while (and commands (not found))
7342 (setq item (pop commands)
7343 compress (nth 0 item)
7344 decompress (nth 1 item))
7347 "Checking local compress command `%s', `%s' for sanity"
7348 compress decompress)
7349 (unless (zerop (tramp-call-local-coding-command
7350 (format "echo %s | %s | %s"
7351 magic compress decompress) nil nil))
7355 "Checking remote compress command `%s', `%s' for sanity"
7356 compress decompress)
7357 (unless (zerop (tramp-send-command-and-check
7358 vec (format "echo %s | %s | %s"
7359 magic compress decompress) t))
7363 ;; Did we find something?
7366 ;; Set connection properties.
7368 vec 5 "Using inline transfer compress command `%s'" compress)
7369 (tramp-set-connection-property vec "inline-compress" compress)
7371 vec 5 "Using inline transfer decompress command `%s'" decompress)
7372 (tramp-set-connection-property vec "inline-decompress" decompress))
7374 (tramp-set-connection-property vec "inline-compress" nil)
7375 (tramp-set-connection-property vec "inline-decompress" nil)
7377 vec 2 "Couldn't find an inline transfer compress command")))))
7379 (defun tramp-compute-multi-hops (vec)
7380 "Expands VEC according to `tramp-default-proxies-alist'.
7381 Gateway hops are already opened."
7382 (let ((target-alist `(,vec))
7383 (choices tramp-default-proxies-alist)
7386 ;; Look for proxy hosts to be passed.
7388 (setq item (pop choices)
7389 proxy (eval (nth 2 item)))
7392 (string-match (or (eval (nth 0 item)) "")
7393 (or (tramp-file-name-host (car target-alist)) ""))
7395 (string-match (or (eval (nth 1 item)) "")
7396 (or (tramp-file-name-user (car target-alist)) "")))
7398 ;; No more hops needed.
7400 ;; Replace placeholders.
7405 ?u (or (tramp-file-name-user (car target-alist)) "")
7406 ?h (or (tramp-file-name-host (car target-alist)) ""))))
7407 (with-parsed-tramp-file-name proxy l
7409 (add-to-list 'target-alist l)
7410 ;; Start next search.
7411 (setq choices tramp-default-proxies-alist)))))
7414 (when (and (boundp 'tramp-gw-tunnel-method)
7415 (string-match (format
7417 (symbol-value 'tramp-gw-tunnel-method)
7418 (symbol-value 'tramp-gw-socks-method))
7419 (tramp-file-name-method (car target-alist))))
7420 (let ((gw (pop target-alist))
7421 (hop (pop target-alist)))
7422 ;; Is the method prepared for gateways?
7423 (unless (tramp-get-method-parameter
7424 (tramp-file-name-method hop) 'tramp-default-port)
7427 "Method `%s' is not supported for gateway access."
7428 (tramp-file-name-method hop)))
7429 ;; Add default port if needed.
7432 tramp-host-with-port-regexp (tramp-file-name-host hop))
7435 (tramp-file-name-host hop) tramp-prefix-port-format
7437 (tramp-get-method-parameter
7438 (tramp-file-name-method hop) 'tramp-default-port)))))
7439 ;; Open the gateway connection.
7443 (tramp-file-name-method hop) (tramp-file-name-user hop)
7444 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil))
7445 ;; For the password prompt, we need the correct values.
7446 ;; Therefore, we must remember the gateway vector. But we
7447 ;; cannot do it as connection property, because it shouldn't
7448 ;; be persistent. And we have no started process yet either.
7449 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7451 ;; Foreign and out-of-band methods are not supported for multi-hops.
7452 (when (cdr target-alist)
7453 (setq choices target-alist)
7455 (setq item (pop choices))
7459 (tramp-get-method-parameter
7460 (tramp-file-name-method item) 'tramp-login-program))
7461 (tramp-get-method-parameter
7462 (tramp-file-name-method item) 'tramp-copy-program))
7465 "Method `%s' is not supported for multi-hops."
7466 (tramp-file-name-method item)))))
7468 ;; In case the host name is not used for the remote shell
7469 ;; command, the user could be misguided by applying a random
7471 (let* ((v (car target-alist))
7472 (method (tramp-file-name-method v))
7473 (host (tramp-file-name-host v)))
7476 ;; There are multi-hops.
7478 ;; The host name is used for the remote shell command.
7480 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7481 ;; The host is local. We cannot use `tramp-local-host-p'
7482 ;; here, because it opens a connection as well.
7483 (string-match tramp-local-host-regexp host))
7486 "Host `%s' looks like a remote host, `%s' can only use the local host"
7492 (defun tramp-maybe-open-connection (vec)
7493 "Maybe open a connection VEC.
7494 Does not do anything if a connection is already open, but re-opens the
7495 connection if a previous connection has died for some reason."
7496 (catch 'uname-changed
7497 (let ((p (tramp-get-connection-process vec))
7498 (process-name (tramp-get-connection-property vec "process-name" nil))
7499 (process-environment (copy-sequence process-environment)))
7501 ;; If too much time has passed since last command was sent, look
7502 ;; whether process is still alive. If it isn't, kill it. When
7503 ;; using ssh, it can sometimes happen that the remote end has
7504 ;; hung up but the local ssh client doesn't recognize this until
7505 ;; it tries to send some data to the remote end. So that's why
7506 ;; we try to send a command from time to time, then look again
7507 ;; whether the process is really alive.
7509 (when (and (> (tramp-time-diff
7511 (tramp-get-connection-property
7512 p "last-cmd-time" '(0 0 0)))
7514 p (processp p) (memq (process-status p) '(run open)))
7515 (tramp-send-command vec "echo are you awake" t t)
7516 (unless (and (memq (process-status p) '(run open))
7517 (tramp-wait-for-output p 10))
7518 ;; The error will be catched locally.
7519 (tramp-error vec 'file-error "Awake did fail")))
7521 (tramp-flush-connection-property vec)
7522 (tramp-flush-connection-property p)
7526 ;; New connection must be opened.
7527 (unless (and p (processp p) (memq (process-status p) '(run open)))
7529 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7530 ;; messages from the beginning.
7531 (tramp-get-buffer vec)
7532 (with-progress-reporter
7534 (if (zerop (length (tramp-file-name-user vec)))
7535 (format "Opening connection for %s using %s"
7536 (tramp-file-name-host vec)
7537 (tramp-file-name-method vec))
7538 (format "Opening connection for %s@%s using %s"
7539 (tramp-file-name-user vec)
7540 (tramp-file-name-host vec)
7541 (tramp-file-name-method vec)))
7543 ;; Start new process.
7544 (when (and p (processp p))
7546 (setenv "TERM" tramp-terminal-type)
7547 (setenv "LC_ALL" "C")
7548 (setenv "PROMPT_COMMAND")
7549 (setenv "PS1" tramp-initial-end-of-output)
7550 (let* ((target-alist (tramp-compute-multi-hops vec))
7551 (process-connection-type tramp-process-connection-type)
7552 (process-adaptive-read-buffering nil)
7553 (coding-system-for-read nil)
7554 ;; This must be done in order to avoid our file name handler.
7555 (p (let ((default-directory
7556 (tramp-compat-temporary-file-directory)))
7558 (or process-name (tramp-buffer-name vec))
7559 (tramp-get-connection-buffer vec)
7560 tramp-encoding-shell))))
7563 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7565 ;; Check whether process is alive.
7566 (tramp-set-process-query-on-exit-flag p nil)
7567 (tramp-barf-if-no-shell-prompt
7568 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7570 ;; Now do all the connections as specified.
7572 (let* ((hop (car target-alist))
7573 (l-method (tramp-file-name-method hop))
7574 (l-user (tramp-file-name-user hop))
7575 (l-host (tramp-file-name-host hop))
7578 (tramp-get-method-parameter
7579 l-method 'tramp-login-program))
7581 (tramp-get-method-parameter l-method 'tramp-login-args))
7583 (tramp-get-method-parameter l-method 'tramp-async-args))
7585 (tramp-get-method-parameter l-method 'tramp-gw-args))
7586 (gw (tramp-get-file-property hop "" "gateway" nil))
7587 (g-method (and gw (tramp-file-name-method gw)))
7588 (g-user (and gw (tramp-file-name-user gw)))
7589 (g-host (and gw (tramp-file-name-host gw)))
7590 (command login-program)
7591 ;; We don't create the temporary file. In fact,
7592 ;; it is just a prefix for the ControlPath option
7593 ;; of ssh; the real temporary file has another
7594 ;; name, and it is created and protected by ssh.
7595 ;; It is also removed by ssh, when the connection
7598 (tramp-set-connection-property
7602 tramp-temp-name-prefix
7603 (tramp-compat-temporary-file-directory)))))
7606 ;; Add arguments for asynchrononous processes.
7607 (when (and process-name async-args)
7608 (setq login-args (append async-args login-args)))
7610 ;; Add gateway arguments if necessary.
7611 (when (and gw gw-args)
7612 (setq login-args (append gw-args login-args)))
7614 ;; Check for port number. Until now, there's no need
7615 ;; for handling like method, user, host.
7616 (when (string-match tramp-host-with-port-regexp l-host)
7617 (setq l-port (match-string 2 l-host)
7618 l-host (match-string 1 l-host)))
7620 ;; Set variables for computing the prompt for reading
7621 ;; password. They can also be derived from a gateway.
7622 (setq tramp-current-method (or g-method l-method)
7623 tramp-current-user (or g-user l-user)
7624 tramp-current-host (or g-host l-host))
7626 ;; Replace login-args place holders.
7628 l-host (or l-host "")
7629 l-user (or l-user "")
7630 l-port (or l-port "")
7631 spec (format-spec-make
7632 ?h l-host ?u l-user ?p l-port ?t tmpfile)
7635 ;; We do not want to see the trailing local prompt in
7636 ;; `start-file-process'.
7637 (unless (memq system-type '(windows-nt)) "exec ")
7641 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7642 (unless (member "" x) (mapconcat 'identity x " ")))
7644 ;; Local shell could be a Windows COMSPEC. It
7645 ;; doesn't know the ";" syntax, but we must exit
7646 ;; always for `start-file-process'. "exec" does not
7648 (if (memq system-type '(windows-nt)) " && exit || exit")))
7650 ;; Send the command.
7651 (tramp-message vec 3 "Sending command `%s'" command)
7652 (tramp-send-command vec command t t)
7653 (tramp-process-actions p vec tramp-actions-before-shell 60)
7655 vec 3 "Found remote shell prompt on `%s'" l-host))
7657 (setq target-alist (cdr target-alist)))
7659 ;; Make initial shell settings.
7660 (tramp-open-connection-setup-interactive-shell p vec)))))))
7662 (defun tramp-send-command (vec command &optional neveropen nooutput)
7663 "Send the COMMAND to connection VEC.
7664 Erases temporary buffer before sending the command. If optional
7665 arg NEVEROPEN is non-nil, never try to open the connection. This
7666 is meant to be used from `tramp-maybe-open-connection' only. The
7667 function waits for output unless NOOUTPUT is set."
7668 (unless neveropen (tramp-maybe-open-connection vec))
7669 (let ((p (tramp-get-connection-process vec)))
7670 (when (tramp-get-connection-property p "remote-echo" nil)
7671 ;; We mark the command string that it can be erased in the output buffer.
7672 (tramp-set-connection-property p "check-remote-echo" t)
7673 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7674 (tramp-message vec 6 "%s" command)
7675 (tramp-send-string vec command)
7676 (unless nooutput (tramp-wait-for-output p))))
7678 (defun tramp-wait-for-output (proc &optional timeout)
7679 "Wait for output from remote command."
7680 (unless (buffer-live-p (process-buffer proc))
7681 (delete-process proc)
7682 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7683 (with-current-buffer (process-buffer proc)
7684 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7685 ;; be leading escape sequences, which must be ignored.
7686 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7687 ;; Sometimes, the commands do not return a newline but a
7688 ;; null byte before the shell prompt, for example "git
7689 ;; ls-files -c -z ...".
7690 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7691 (found (tramp-wait-for-regexp proc timeout regexp1)))
7693 (let (buffer-read-only)
7694 ;; A simple-minded busybox has sent " ^H" sequences.
7696 (goto-char (point-min))
7697 (when (re-search-forward
7698 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7700 (delete-region (point-min) (point)))
7701 ;; Delete the prompt.
7702 (goto-char (point-max))
7703 (re-search-backward regexp nil t)
7704 (delete-region (point) (point-max)))
7708 "[[Remote prompt `%s' not found in %d secs]]"
7709 tramp-end-of-output timeout)
7712 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7713 ;; Return value is whether end-of-output sentinel was found.
7716 (defun tramp-send-command-and-check
7717 (vec command &optional subshell dont-suppress-err)
7718 "Run COMMAND and check its exit status.
7719 Sends `echo $?' along with the COMMAND for checking the exit status. If
7720 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7722 If the optional argument SUBSHELL is non-nil, the command is
7723 executed in a subshell, ie surrounded by parentheses. If
7724 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7727 (concat (if subshell "( " "")
7729 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7730 "echo tramp_exit_status $?"
7731 (if subshell " )" "")))
7732 (with-current-buffer (tramp-get-connection-buffer vec)
7733 (goto-char (point-max))
7734 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7736 vec 'file-error "Couldn't find exit status of `%s'" command))
7737 (skip-chars-forward "^ ")
7739 (read (current-buffer))
7740 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7742 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7743 "Run COMMAND, check exit status, throw error if exit status not okay.
7744 Similar to `tramp-send-command-and-check' but accepts two more arguments
7745 FMT and ARGS which are passed to `error'."
7746 (unless (zerop (tramp-send-command-and-check vec command))
7747 (apply 'tramp-error vec 'file-error fmt args)))
7749 (defun tramp-send-command-and-read (vec command)
7750 "Run COMMAND and return the output, which must be a Lisp expression.
7751 In case there is no valid Lisp expression, it raises an error"
7752 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7753 (with-current-buffer (tramp-get-connection-buffer vec)
7754 ;; Read the expression.
7755 (goto-char (point-min))
7757 (prog1 (read (current-buffer))
7759 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7763 "`%s' does not return a valid Lisp expression: `%s'"
7764 command (buffer-string))))))
7766 ;; It seems that Tru64 Unix does not like it if long strings are sent
7767 ;; to it in one go. (This happens when sending the Perl
7768 ;; `file-attributes' implementation, for instance.) Therefore, we
7769 ;; have this function which sends the string in chunks.
7770 (defun tramp-send-string (vec string)
7771 "Send the STRING via connection VEC.
7773 The STRING is expected to use Unix line-endings, but the lines sent to
7774 the remote host use line-endings as defined in the variable
7775 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7776 (let* ((p (tramp-get-connection-process vec))
7777 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7780 vec 'file-error "Can't send string to remote host -- not logged in"))
7781 (tramp-set-connection-property p "last-cmd-time" (current-time))
7782 (tramp-message vec 10 "%s" string)
7783 (with-current-buffer (tramp-get-connection-buffer vec)
7784 ;; Clean up the buffer. We cannot call `erase-buffer' because
7785 ;; narrowing might be in effect.
7786 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7787 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7789 (mapconcat 'identity
7790 (tramp-compat-split-string string "\n")
7791 tramp-rsh-end-of-line))
7792 (unless (or (string= string "")
7793 (string-equal (substring string -1) tramp-rsh-end-of-line))
7794 (setq string (concat string tramp-rsh-end-of-line)))
7796 (if (and chunksize (not (zerop chunksize)))
7798 (end (length string)))
7801 vec 10 "Sending chunk from %s to %s"
7802 pos (min (+ pos chunksize) end))
7803 (process-send-string
7804 p (substring string pos (min (+ pos chunksize) end)))
7805 (setq pos (+ pos chunksize))))
7806 (process-send-string p string)))))
7808 (defun tramp-mode-string-to-int (mode-string)
7809 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7810 (let* (case-fold-search
7811 (mode-chars (string-to-vector mode-string))
7812 (owner-read (aref mode-chars 1))
7813 (owner-write (aref mode-chars 2))
7814 (owner-execute-or-setid (aref mode-chars 3))
7815 (group-read (aref mode-chars 4))
7816 (group-write (aref mode-chars 5))
7817 (group-execute-or-setid (aref mode-chars 6))
7818 (other-read (aref mode-chars 7))
7819 (other-write (aref mode-chars 8))
7820 (other-execute-or-sticky (aref mode-chars 9)))
7824 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7825 ((char-equal owner-read ?-) 0)
7826 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7828 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7829 ((char-equal owner-write ?-) 0)
7830 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7832 ((char-equal owner-execute-or-setid ?x)
7833 (tramp-octal-to-decimal "00100"))
7834 ((char-equal owner-execute-or-setid ?S)
7835 (tramp-octal-to-decimal "04000"))
7836 ((char-equal owner-execute-or-setid ?s)
7837 (tramp-octal-to-decimal "04100"))
7838 ((char-equal owner-execute-or-setid ?-) 0)
7839 (t (error "Fourth char `%c' must be one of `xsS-'"
7840 owner-execute-or-setid)))
7842 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7843 ((char-equal group-read ?-) 0)
7844 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7846 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7847 ((char-equal group-write ?-) 0)
7848 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7850 ((char-equal group-execute-or-setid ?x)
7851 (tramp-octal-to-decimal "00010"))
7852 ((char-equal group-execute-or-setid ?S)
7853 (tramp-octal-to-decimal "02000"))
7854 ((char-equal group-execute-or-setid ?s)
7855 (tramp-octal-to-decimal "02010"))
7856 ((char-equal group-execute-or-setid ?-) 0)
7857 (t (error "Seventh char `%c' must be one of `xsS-'"
7858 group-execute-or-setid)))
7860 ((char-equal other-read ?r)
7861 (tramp-octal-to-decimal "00004"))
7862 ((char-equal other-read ?-) 0)
7863 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7865 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7866 ((char-equal other-write ?-) 0)
7867 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7869 ((char-equal other-execute-or-sticky ?x)
7870 (tramp-octal-to-decimal "00001"))
7871 ((char-equal other-execute-or-sticky ?T)
7872 (tramp-octal-to-decimal "01000"))
7873 ((char-equal other-execute-or-sticky ?t)
7874 (tramp-octal-to-decimal "01001"))
7875 ((char-equal other-execute-or-sticky ?-) 0)
7876 (t (error "Tenth char `%c' must be one of `xtT-'"
7877 other-execute-or-sticky)))))))
7879 (defun tramp-convert-file-attributes (vec attr)
7880 "Convert file-attributes ATTR generated by perl script, stat or ls.
7881 Convert file mode bits to string and set virtual device number.
7884 ;; Convert last access time.
7885 (unless (listp (nth 4 attr))
7886 (setcar (nthcdr 4 attr)
7887 (list (floor (nth 4 attr) 65536)
7888 (floor (mod (nth 4 attr) 65536)))))
7889 ;; Convert last modification time.
7890 (unless (listp (nth 5 attr))
7891 (setcar (nthcdr 5 attr)
7892 (list (floor (nth 5 attr) 65536)
7893 (floor (mod (nth 5 attr) 65536)))))
7894 ;; Convert last status change time.
7895 (unless (listp (nth 6 attr))
7896 (setcar (nthcdr 6 attr)
7897 (list (floor (nth 6 attr) 65536)
7898 (floor (mod (nth 6 attr) 65536)))))
7899 ;; Convert file size.
7900 (when (< (nth 7 attr) 0)
7901 (setcar (nthcdr 7 attr) -1))
7902 (when (and (floatp (nth 7 attr))
7903 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7904 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7905 ;; Convert file mode bits to string.
7906 (unless (stringp (nth 8 attr))
7907 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7908 (when (stringp (car attr))
7909 (aset (nth 8 attr) 0 ?l)))
7910 ;; Convert directory indication bit.
7911 (when (string-match "^d" (nth 8 attr))
7913 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7914 (when (consp (car attr))
7915 (if (and (stringp (caar attr))
7916 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7917 (setcar attr (match-string 1 (caar attr)))
7919 ;; Set file's gid change bit.
7920 (setcar (nthcdr 9 attr)
7921 (if (numberp (nth 3 attr))
7922 (not (= (nth 3 attr)
7923 (tramp-get-remote-gid vec 'integer)))
7926 (tramp-get-remote-gid vec 'string)))))
7928 (unless (listp (nth 10 attr))
7929 (setcar (nthcdr 10 attr)
7931 (cons (floor (nth 10 attr) 65536)
7932 (floor (mod (nth 10 attr) 65536)))
7933 ;; Inodes can be incredible huge. We must hide this.
7934 (error (tramp-get-inode vec)))))
7935 ;; Set virtual device number.
7936 (setcar (nthcdr 11 attr)
7937 (tramp-get-device vec))
7940 (defun tramp-check-cached-permissions (vec access)
7941 "Check `file-attributes' caches for VEC.
7942 Return t if according to the cache access type ACCESS is known to
7948 ((eq ?x access) 3))))
7949 (dolist (suffix '("string" "integer") result)
7955 (tramp-get-file-property
7956 vec (tramp-file-name-localname vec)
7957 (concat "file-attributes-" suffix) nil))
7959 (tramp-get-connection-property
7960 vec (concat "uid-" suffix) nil))
7962 (tramp-get-connection-property
7963 vec (concat "gid-" suffix) nil)))
7968 (eq t (car file-attr))
7969 (null (car file-attr)))
7971 ;; World accessible.
7972 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7973 ;; User accessible and owned by user.
7975 (eq access (aref (nth 8 file-attr) offset))
7976 (equal remote-uid (nth 2 file-attr)))
7977 ;; Group accessible and owned by user's
7980 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7981 (equal remote-gid (nth 3 file-attr)))))))))))
7983 (defun tramp-get-inode (vec)
7984 "Returns the virtual inode number.
7985 If it doesn't exist, generate a new one."
7986 (let ((string (tramp-make-tramp-file-name
7987 (tramp-file-name-method vec)
7988 (tramp-file-name-user vec)
7989 (tramp-file-name-host vec)
7991 (unless (assoc string tramp-inodes)
7992 (add-to-list 'tramp-inodes
7993 (list string (length tramp-inodes))))
7994 (nth 1 (assoc string tramp-inodes))))
7996 (defun tramp-get-device (vec)
7997 "Returns the virtual device number.
7998 If it doesn't exist, generate a new one."
7999 (let ((string (tramp-make-tramp-file-name
8000 (tramp-file-name-method vec)
8001 (tramp-file-name-user vec)
8002 (tramp-file-name-host vec)
8004 (unless (assoc string tramp-devices)
8005 (add-to-list 'tramp-devices
8006 (list string (length tramp-devices))))
8007 (cons -1 (nth 1 (assoc string tramp-devices)))))
8009 (defun tramp-file-mode-from-int (mode)
8010 "Turn an integer representing a file mode into an ls(1)-like string."
8011 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
8012 (user (logand (lsh mode -6) 7))
8013 (group (logand (lsh mode -3) 7))
8014 (other (logand (lsh mode -0) 7))
8015 (suid (> (logand (lsh mode -9) 4) 0))
8016 (sgid (> (logand (lsh mode -9) 2) 0))
8017 (sticky (> (logand (lsh mode -9) 1) 0)))
8018 (setq user (tramp-file-mode-permissions user suid "s"))
8019 (setq group (tramp-file-mode-permissions group sgid "s"))
8020 (setq other (tramp-file-mode-permissions other sticky "t"))
8021 (concat type user group other)))
8023 (defun tramp-file-mode-permissions (perm suid suid-text)
8024 "Convert a permission bitset into a string.
8025 This is used internally by `tramp-file-mode-from-int'."
8026 (let ((r (> (logand perm 4) 0))
8027 (w (> (logand perm 2) 0))
8028 (x (> (logand perm 1) 0)))
8029 (concat (or (and r "r") "-")
8030 (or (and w "w") "-")
8031 (or (and suid x suid-text) ; suid, execute
8032 (and suid (upcase suid-text)) ; suid, !execute
8033 (and x "x") "-")))) ; !suid
8035 (defun tramp-decimal-to-octal (i)
8036 "Return a string consisting of the octal digits of I.
8037 Not actually used. Use `(format \"%o\" i)' instead?"
8038 (cond ((< i 0) (error "Cannot convert negative number to octal"))
8039 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
8041 (t (concat (tramp-decimal-to-octal (/ i 8))
8042 (number-to-string (% i 8))))))
8044 ;; Kudos to Gerd Moellmann for this suggestion.
8045 (defun tramp-octal-to-decimal (ostr)
8046 "Given a string of octal digits, return a decimal number."
8047 (let ((x (or ostr "")))
8048 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
8049 (unless (string-match "\\`[0-7]*\\'" x)
8050 (error "Non-octal junk in string `%s'" x))
8051 (string-to-number ostr 8)))
8053 (defun tramp-shell-case-fold (string)
8054 "Converts STRING to shell glob pattern which ignores case."
8057 (if (equal (downcase c) (upcase c))
8059 (format "[%c%c]" (downcase c) (upcase c))))
8064 ;; ------------------------------------------------------------
8065 ;; -- Tramp file names --
8066 ;; ------------------------------------------------------------
8067 ;; Conversion functions between external representation and
8068 ;; internal data structure. Convenience functions for internal
8071 (defun tramp-file-name-p (vec)
8072 "Check, whether VEC is a Tramp object."
8073 (and (vectorp vec) (= 4 (length vec))))
8075 (defun tramp-file-name-method (vec)
8076 "Return method component of VEC."
8077 (and (tramp-file-name-p vec) (aref vec 0)))
8079 (defun tramp-file-name-user (vec)
8080 "Return user component of VEC."
8081 (and (tramp-file-name-p vec) (aref vec 1)))
8083 (defun tramp-file-name-host (vec)
8084 "Return host component of VEC."
8085 (and (tramp-file-name-p vec) (aref vec 2)))
8087 (defun tramp-file-name-localname (vec)
8088 "Return localname component of VEC."
8089 (and (tramp-file-name-p vec) (aref vec 3)))
8091 ;; The user part of a Tramp file name vector can be of kind
8092 ;; "user%domain". Sometimes, we must extract these parts.
8093 (defun tramp-file-name-real-user (vec)
8094 "Return the user name of VEC without domain."
8096 (let ((user (tramp-file-name-user vec)))
8097 (if (and (stringp user)
8098 (string-match tramp-user-with-domain-regexp user))
8099 (match-string 1 user)
8102 (defun tramp-file-name-domain (vec)
8103 "Return the domain name of VEC."
8105 (let ((user (tramp-file-name-user vec)))
8107 (string-match tramp-user-with-domain-regexp user)
8108 (match-string 2 user)))))
8110 ;; The host part of a Tramp file name vector can be of kind
8111 ;; "host#port". Sometimes, we must extract these parts.
8112 (defun tramp-file-name-real-host (vec)
8113 "Return the host name of VEC without port."
8115 (let ((host (tramp-file-name-host vec)))
8116 (if (and (stringp host)
8117 (string-match tramp-host-with-port-regexp host))
8118 (match-string 1 host)
8121 (defun tramp-file-name-port (vec)
8122 "Return the port number of VEC."
8124 (let ((host (tramp-file-name-host vec)))
8126 (string-match tramp-host-with-port-regexp host)
8127 (string-to-number (match-string 2 host))))))
8129 (defun tramp-tramp-file-p (name)
8130 "Return t if NAME is a string with Tramp file name syntax."
8132 (and (stringp name) (string-match tramp-file-name-regexp name))))
8134 (defun tramp-find-method (method user host)
8135 "Return the right method string to use.
8136 This is METHOD, if non-nil. Otherwise, do a lookup in
8137 `tramp-default-method-alist'."
8139 (let ((choices tramp-default-method-alist)
8142 (setq item (pop choices))
8143 (when (and (string-match (or (nth 0 item) "") (or host ""))
8144 (string-match (or (nth 1 item) "") (or user "")))
8145 (setq lmethod (nth 2 item))
8146 (setq choices nil)))
8148 tramp-default-method))
8150 (defun tramp-find-user (method user host)
8151 "Return the right user string to use.
8152 This is USER, if non-nil. Otherwise, do a lookup in
8153 `tramp-default-user-alist'."
8155 (let ((choices tramp-default-user-alist)
8158 (setq item (pop choices))
8159 (when (and (string-match (or (nth 0 item) "") (or method ""))
8160 (string-match (or (nth 1 item) "") (or host "")))
8161 (setq luser (nth 2 item))
8162 (setq choices nil)))
8164 tramp-default-user))
8166 (defun tramp-find-host (method user host)
8167 "Return the right host string to use.
8168 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
8169 (or (and (> (length host) 0) host)
8170 tramp-default-host))
8172 (defun tramp-dissect-file-name (name &optional nodefault)
8173 "Return a `tramp-file-name' structure.
8174 The structure consists of remote method, remote user, remote host
8175 and localname (file name on remote host). If NODEFAULT is
8176 non-nil, the file name parts are not expanded to their default
8179 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
8180 (unless match (error "Not a Tramp file name: %s" name))
8181 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
8182 (user (match-string (nth 2 tramp-file-name-structure) name))
8183 (host (match-string (nth 3 tramp-file-name-structure) name))
8184 (localname (match-string (nth 4 tramp-file-name-structure) name)))
8185 (when (member method '("multi" "multiu"))
8187 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
8190 (when (string-match tramp-prefix-ipv6-regexp host)
8191 (setq host (replace-match "" nil t host)))
8192 (when (string-match tramp-postfix-ipv6-regexp host)
8193 (setq host (replace-match "" nil t host))))
8195 (vector method user host localname)
8197 (tramp-find-method method user host)
8198 (tramp-find-user method user host)
8199 (tramp-find-host method user host)
8202 (defun tramp-equal-remote (file1 file2)
8203 "Check, whether the remote parts of FILE1 and FILE2 are identical.
8204 The check depends on method, user and host name of the files. If
8205 one of the components is missing, the default values are used.
8206 The local file name parts of FILE1 and FILE2 are not taken into
8211 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
8213 would yield `t'. On the other hand, the following check results in nil:
8215 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
8216 (and (stringp (file-remote-p file1))
8217 (stringp (file-remote-p file2))
8218 (string-equal (file-remote-p file1) (file-remote-p file2))))
8220 (defun tramp-make-tramp-file-name (method user host localname)
8221 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
8222 (concat tramp-prefix-format
8223 (when (not (zerop (length method)))
8224 (concat method tramp-postfix-method-format))
8225 (when (not (zerop (length user)))
8226 (concat user tramp-postfix-user-format))
8228 (if (string-match tramp-ipv6-regexp host)
8229 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8231 tramp-postfix-host-format
8232 (when localname localname)))
8234 (defun tramp-completion-make-tramp-file-name (method user host localname)
8235 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
8236 It must not be a complete Tramp file name, but as long as there are
8237 necessary only. This function will be used in file name completion."
8238 (concat tramp-prefix-format
8239 (when (not (zerop (length method)))
8240 (concat method tramp-postfix-method-format))
8241 (when (not (zerop (length user)))
8242 (concat user tramp-postfix-user-format))
8243 (when (not (zerop (length host)))
8245 (if (string-match tramp-ipv6-regexp host)
8246 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8248 tramp-postfix-host-format))
8249 (when localname localname)))
8251 (defun tramp-make-copy-program-file-name (vec)
8252 "Create a file name suitable to be passed to `rcp' and workalikes."
8253 (let ((user (tramp-file-name-user vec))
8254 (host (tramp-file-name-real-host vec))
8255 (localname (tramp-shell-quote-argument
8256 (tramp-file-name-localname vec))))
8257 (if (not (zerop (length user)))
8258 (format "%s@%s:%s" user host localname)
8259 (format "%s:%s" host localname))))
8261 (defun tramp-method-out-of-band-p (vec size)
8262 "Return t if this is an out-of-band method, nil otherwise."
8264 ;; It shall be an out-of-band method.
8265 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
8266 ;; Either the file size is large enough, or (in rare cases) there
8267 ;; does not exist a remote encoding.
8268 (or (null tramp-copy-size-limit)
8269 (> size tramp-copy-size-limit)
8270 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
8272 (defun tramp-local-host-p (vec)
8273 "Return t if this points to the local host, nil otherwise."
8274 ;; We cannot use `tramp-file-name-real-host'. A port is an
8275 ;; indication for an ssh tunnel or alike.
8276 (let ((host (tramp-file-name-host vec)))
8279 (string-match tramp-local-host-regexp host)
8280 ;; The method shall be applied to one of the shell file name
8281 ;; handler. `tramp-local-host-p' is also called for "smb" and
8282 ;; alike, where it must fail.
8283 (tramp-get-method-parameter
8284 (tramp-file-name-method vec) 'tramp-login-program)
8285 ;; The local temp directory must be writable for the other user.
8287 (tramp-make-tramp-file-name
8288 (tramp-file-name-method vec)
8289 (tramp-file-name-user vec)
8291 (tramp-compat-temporary-file-directory)))
8292 ;; On some systems, chown runs only for root.
8293 (or (zerop (user-uid))
8294 (zerop (tramp-get-remote-uid vec 'integer))))))
8296 ;; Variables local to connection.
8298 (defun tramp-get-remote-path (vec)
8299 (with-connection-property
8300 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8301 ;; cache the result for the session only. Otherwise, the result
8302 ;; is cached persistently.
8303 (if (memq 'tramp-own-remote-path tramp-remote-path)
8304 (tramp-get-connection-process vec)
8307 (let* ((remote-path (copy-tree tramp-remote-path))
8308 (elt1 (memq 'tramp-default-remote-path remote-path))
8309 (elt2 (memq 'tramp-own-remote-path remote-path))
8310 (default-remote-path
8313 (tramp-send-command-and-read
8314 vec "echo \\\"`getconf PATH`\\\"")
8315 ;; Default if "getconf" is not available.
8319 "`getconf PATH' not successful, using default value \"%s\"."
8325 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8326 ;; Default if "getconf" is not available.
8329 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8332 ;; Replace place holder `tramp-default-remote-path'.
8336 (tramp-compat-split-string default-remote-path ":")
8338 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8340 ;; Replace place holder `tramp-own-remote-path'.
8344 (tramp-compat-split-string own-remote-path ":")
8346 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8348 ;; Remove double entries.
8349 (setq elt1 remote-path)
8351 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8353 (setq elt1 (cdr elt1)))
8355 ;; Remove non-existing directories.
8363 (tramp-make-tramp-file-name
8364 (tramp-file-name-method vec)
8365 (tramp-file-name-user vec)
8366 (tramp-file-name-host vec)
8371 (defun tramp-get-remote-tmpdir (vec)
8372 (with-connection-property vec "tmp-directory"
8373 (let ((dir (tramp-shell-quote-argument "/tmp")))
8375 (tramp-send-command-and-check
8376 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8378 (tramp-send-command-and-check
8379 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8381 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8383 (defun tramp-get-ls-command (vec)
8384 (with-connection-property vec "ls"
8385 (tramp-message vec 5 "Finding a suitable `ls' command")
8388 (dolist (cmd '("ls" "gnuls" "gls"))
8389 (let ((dl (tramp-get-remote-path vec))
8391 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8392 ;; Check parameters. On busybox, "ls" output coloring is
8393 ;; enabled by default sometimes. So we try to disable it
8394 ;; when possible. $LS_COLORING is not supported there.
8395 ;; Some "ls" versions are sensible wrt the order of
8396 ;; arguments, they fail when "-al" is after the
8397 ;; "--color=never" argument (for example on FreeBSD).
8398 (when (zerop (tramp-send-command-and-check
8399 vec (format "%s -lnd /" result)))
8400 (when (zerop (tramp-send-command-and-check
8402 "%s --color=never -al /dev/null" result)))
8403 (setq result (concat result " --color=never")))
8404 (throw 'ls-found result))
8405 (setq dl (cdr dl))))))
8406 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8408 (defun tramp-get-ls-command-with-dired (vec)
8410 (with-connection-property vec "ls-dired"
8411 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8412 ;; Some "ls" versions are sensible wrt the order of arguments,
8413 ;; they fail when "-al" is after the "--dired" argument (for
8414 ;; example on FreeBSD).
8415 (zerop (tramp-send-command-and-check
8416 vec (format "%s --dired -al /dev/null"
8417 (tramp-get-ls-command vec)))))))
8419 (defun tramp-get-test-command (vec)
8420 (with-connection-property vec "test"
8421 (tramp-message vec 5 "Finding a suitable `test' command")
8422 (if (zerop (tramp-send-command-and-check vec "test 0"))
8424 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8426 (defun tramp-get-test-nt-command (vec)
8427 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8428 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8429 ;; for otherwise the shell crashes.
8430 (with-connection-property vec "test-nt"
8434 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8435 (with-current-buffer (tramp-get-buffer vec)
8436 (goto-char (point-min))
8437 (when (looking-at (regexp-quote tramp-end-of-output))
8438 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8443 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8444 (tramp-get-test-command vec)))
8445 "tramp_test_nt %s %s"))))
8447 (defun tramp-get-file-exists-command (vec)
8448 (with-connection-property vec "file-exists"
8449 (tramp-message vec 5 "Finding command to check if file exists")
8450 (tramp-find-file-exists-command vec)))
8452 (defun tramp-get-remote-ln (vec)
8453 (with-connection-property vec "ln"
8454 (tramp-message vec 5 "Finding a suitable `ln' command")
8455 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8457 (defun tramp-get-remote-perl (vec)
8458 (with-connection-property vec "perl"
8459 (tramp-message vec 5 "Finding a suitable `perl' command")
8461 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8462 (tramp-find-executable
8463 vec "perl" (tramp-get-remote-path vec)))))
8464 ;; We must check also for some Perl modules.
8466 (with-connection-property vec "perl-file-spec"
8468 (tramp-send-command-and-check
8469 vec (format "%s -e 'use File::Spec;'" result))))
8470 (with-connection-property vec "perl-cwd-realpath"
8472 (tramp-send-command-and-check
8473 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8476 (defun tramp-get-remote-stat (vec)
8477 (with-connection-property vec "stat"
8478 (tramp-message vec 5 "Finding a suitable `stat' command")
8479 (let ((result (tramp-find-executable
8480 vec "stat" (tramp-get-remote-path vec)))
8482 ;; Check whether stat(1) returns usable syntax. %s does not
8483 ;; work on older AIX systems.
8486 ;; We don't want to display an error message.
8487 (with-temp-message (or (current-message) "")
8489 (tramp-send-command-and-read
8490 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8492 (unless (and (listp tmp) (stringp (car tmp))
8493 (string-match "^./.$" (car tmp))
8494 (integerp (cadr tmp)))
8498 (defun tramp-get-remote-readlink (vec)
8499 (with-connection-property vec "readlink"
8500 (tramp-message vec 5 "Finding a suitable `readlink' command")
8501 (let ((result (tramp-find-executable
8502 vec "readlink" (tramp-get-remote-path vec))))
8504 ;; We don't want to display an error message.
8505 (with-temp-message (or (current-message) "")
8508 (tramp-send-command-and-check
8509 vec (format "%s --canonicalize-missing /" result)))
8513 (defun tramp-get-remote-trash (vec)
8514 (with-connection-property vec "trash"
8515 (tramp-message vec 5 "Finding a suitable `trash' command")
8516 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
8518 (defun tramp-get-remote-id (vec)
8519 (with-connection-property vec "id"
8520 (tramp-message vec 5 "Finding POSIX `id' command")
8523 (let ((dl (tramp-get-remote-path vec))
8525 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8526 ;; Check POSIX parameter.
8527 (when (zerop (tramp-send-command-and-check
8528 vec (format "%s -u" result)))
8529 (throw 'id-found result))
8530 (setq dl (cdr dl)))))
8531 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8533 (defun tramp-get-remote-uid (vec id-format)
8534 (with-connection-property vec (format "uid-%s" id-format)
8535 (let ((res (tramp-send-command-and-read
8537 (format "%s -u%s %s"
8538 (tramp-get-remote-id vec)
8539 (if (equal id-format 'integer) "" "n")
8540 (if (equal id-format 'integer)
8541 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8542 ;; The command might not always return a number.
8543 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8545 (defun tramp-get-remote-gid (vec id-format)
8546 (with-connection-property vec (format "gid-%s" id-format)
8547 (let ((res (tramp-send-command-and-read
8549 (format "%s -g%s %s"
8550 (tramp-get-remote-id vec)
8551 (if (equal id-format 'integer) "" "n")
8552 (if (equal id-format 'integer)
8553 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8554 ;; The command might not always return a number.
8555 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8557 (defun tramp-get-local-uid (id-format)
8558 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8560 (defun tramp-get-local-gid (id-format)
8561 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8563 ;; Some predefined connection properties.
8564 (defun tramp-get-inline-compress (vec prop size)
8565 "Return the compress command related to PROP.
8566 PROP is either `inline-compress' or `inline-decompress'. SIZE is
8567 the length of the file to be compressed.
8569 If no corresponding command is found, nil is returned."
8570 (when (and (integerp tramp-inline-compress-start-size)
8571 (> size tramp-inline-compress-start-size))
8572 (with-connection-property vec prop
8573 (tramp-find-inline-compress vec)
8574 (tramp-get-connection-property vec prop nil))))
8576 (defun tramp-get-inline-coding (vec prop size)
8577 "Return the coding command related to PROP.
8578 PROP is either `remote-encoding', `remode-decoding',
8579 `local-encoding' or `local-decoding'.
8581 SIZE is the length of the file to be coded. Depending on SIZE,
8582 compression might be applied.
8584 If no corresponding command is found, nil is returned.
8585 Otherwise, either a string is returned which contains a `%s' mark
8586 to be used for the respective input or output file; or a Lisp
8587 function cell is returned to be applied on a buffer."
8588 ;; We must catch the errors, because we want to return `nil', when
8589 ;; no inline coding is found.
8592 (with-connection-property vec prop
8593 (tramp-find-inline-encoding vec)
8594 (tramp-get-connection-property vec prop nil)))
8595 (prop1 (if (string-match "encoding" prop)
8596 "inline-compress" "inline-decompress"))
8598 ;; The connection property might have been cached. So we must
8599 ;; send the script to the remote side - maybe.
8600 (when (and coding (symbolp coding) (string-match "remote" prop))
8601 (let ((name (symbol-name coding)))
8602 (while (string-match (regexp-quote "-") name)
8603 (setq name (replace-match "_" nil t name)))
8604 (tramp-maybe-send-script vec (symbol-value coding) name)
8605 (setq coding name)))
8607 ;; Check for the `compress' command.
8608 (setq compress (tramp-get-inline-compress vec prop1 size))
8609 ;; Return the value.
8611 ((and compress (symbolp coding))
8612 (if (string-match "decompress" prop1)
8615 (let ((coding-system-for-write 'binary)
8616 (coding-system-for-read 'binary))
8618 'call-process-region (point-min) (point-max)
8619 (car (split-string ,compress)) t t nil
8620 (cdr (split-string ,compress)))))
8622 (let ((coding-system-for-write 'binary)
8623 (coding-system-for-read 'binary))
8625 'call-process-region beg end
8626 (car (split-string ,compress)) t t nil
8627 (cdr (split-string ,compress))))
8628 (,coding (point-min) (point-max)))))
8631 ((and compress (string-match "decoding" prop))
8632 (format "(%s | %s >%%s)" coding compress))
8634 (format "(%s <%%s | %s)" compress coding))
8635 ((string-match "decoding" prop)
8636 (format "%s >%%s" coding))
8638 (format "%s <%%s" coding)))))))
8640 (defun tramp-get-method-parameter (method param)
8641 "Return the method parameter PARAM.
8642 If the `tramp-methods' entry does not exist, return nil."
8643 (let ((entry (assoc param (assoc method tramp-methods))))
8644 (when entry (cadr entry))))
8646 ;; Auto saving to a special directory.
8648 (defun tramp-exists-file-name-handler (operation &rest args)
8649 "Check, whether OPERATION runs a file name handler."
8650 ;; The file name handler is determined on base of either an
8651 ;; argument, `buffer-file-name', or `default-directory'.
8653 (let* ((buffer-file-name "/")
8654 (default-directory "/")
8655 (fnha file-name-handler-alist)
8656 (check-file-name-operation operation)
8657 (file-name-handler-alist
8660 (lambda (operation &rest args)
8661 "Returns OPERATION if it is the one to be checked."
8662 (if (equal check-file-name-operation operation)
8664 (let ((file-name-handler-alist fnha))
8665 (apply operation args))))))))
8666 (equal (apply operation args) operation))
8669 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8670 (defadvice make-auto-save-file-name
8671 (around tramp-advice-make-auto-save-file-name () activate)
8672 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8673 (if (tramp-tramp-file-p (buffer-file-name))
8674 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8675 ;; directly, because this would bypass the locking mechanism.
8676 (setq ad-return-value
8677 (tramp-file-name-handler 'make-auto-save-file-name))
8683 'make-auto-save-file-name
8684 'around 'tramp-advice-make-auto-save-file-name)
8685 (ad-activate 'make-auto-save-file-name))))
8687 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8688 ;; umask. This is a security threat.
8690 (defun tramp-set-auto-save-file-modes ()
8691 "Set permissions of autosaved remote files to the original permissions."
8692 (let ((bfn (buffer-file-name)))
8693 (when (and (tramp-tramp-file-p bfn)
8695 (stringp buffer-auto-save-file-name)
8696 (not (equal bfn buffer-auto-save-file-name)))
8697 (unless (file-exists-p buffer-auto-save-file-name)
8698 (write-region "" nil buffer-auto-save-file-name))
8699 ;; Permissions should be set always, because there might be an old
8700 ;; auto-saved file belonging to another original file. This could
8701 ;; be a security threat.
8702 (set-file-modes buffer-auto-save-file-name
8703 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8705 (unless (and (featurep 'xemacs)
8706 (= emacs-major-version 21)
8707 (> emacs-minor-version 4))
8708 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8709 (add-hook 'tramp-unload-hook
8711 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8713 (defun tramp-subst-strs-in-string (alist string)
8714 "Replace all occurrences of the string FROM with TO in STRING.
8715 ALIST is of the form ((FROM . TO) ...)."
8718 (let* ((pr (car alist))
8721 (while (string-match (regexp-quote from) string)
8722 (setq string (replace-match to t t string)))
8723 (setq alist (cdr alist))))
8726 ;; ------------------------------------------------------------
8727 ;; -- Compatibility functions section --
8728 ;; ------------------------------------------------------------
8730 (defun tramp-read-passwd (proc &optional prompt)
8731 "Read a password from user (compat function).
8732 Consults the auth-source package.
8733 Invokes `password-read' if available, `read-passwd' else."
8734 (let* ((key (tramp-make-tramp-file-name
8735 tramp-current-method tramp-current-user
8736 tramp-current-host ""))
8739 (with-current-buffer (process-buffer proc)
8740 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8741 (format "%s for %s " (capitalize (match-string 1)) key)))))
8742 (with-parsed-tramp-file-name key nil
8745 ;; See if auth-sources contains something useful, if it's bound.
8746 (and (boundp 'auth-sources)
8747 (tramp-get-connection-property v "first-password-request" nil)
8748 ;; Try with Tramp's current method.
8749 (tramp-compat-funcall
8750 'auth-source-user-or-password
8751 "password" tramp-current-host tramp-current-method))
8752 ;; Try the password cache.
8753 (when (functionp 'password-read)
8754 (unless (tramp-get-connection-property
8755 v "first-password-request" nil)
8756 (tramp-compat-funcall 'password-cache-remove key))
8758 (tramp-compat-funcall 'password-read pw-prompt key)))
8759 (tramp-compat-funcall 'password-cache-add key password)
8761 ;; Else, get the password interactively.
8762 (read-passwd pw-prompt))
8763 (tramp-set-connection-property v "first-password-request" nil)))))
8765 (defun tramp-clear-passwd (vec)
8766 "Clear password cache for connection related to VEC."
8767 (tramp-compat-funcall
8768 'password-cache-remove
8769 (tramp-make-tramp-file-name
8770 (tramp-file-name-method vec)
8771 (tramp-file-name-user vec)
8772 (tramp-file-name-host vec)
8775 ;; Snarfed code from time-date.el and parse-time.el
8777 (defconst tramp-half-a-year '(241 17024)
8778 "Evaluated by \"(days-to-time 183)\".")
8780 (defconst tramp-parse-time-months
8781 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8782 ("apr" . 4) ("may" . 5) ("jun" . 6)
8783 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8784 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8785 "Alist mapping month names to integers.")
8787 (defun tramp-time-less-p (t1 t2)
8788 "Say whether time value T1 is less than time value T2."
8789 (unless t1 (setq t1 '(0 0)))
8790 (unless t2 (setq t2 '(0 0)))
8791 (or (< (car t1) (car t2))
8792 (and (= (car t1) (car t2))
8793 (< (nth 1 t1) (nth 1 t2)))))
8795 (defun tramp-time-subtract (t1 t2)
8796 "Subtract two time values.
8797 Return the difference in the format of a time value."
8798 (unless t1 (setq t1 '(0 0)))
8799 (unless t2 (setq t2 '(0 0)))
8800 (let ((borrow (< (cadr t1) (cadr t2))))
8801 (list (- (car t1) (car t2) (if borrow 1 0))
8802 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8804 (defun tramp-time-diff (t1 t2)
8805 "Return the difference between the two times, in seconds.
8806 T1 and T2 are time values (as returned by `current-time' for example)."
8807 ;; Pacify byte-compiler with `symbol-function'.
8808 (cond ((and (fboundp 'subtract-time)
8809 (fboundp 'float-time))
8810 (tramp-compat-funcall
8811 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
8812 ((and (fboundp 'subtract-time)
8813 (fboundp 'time-to-seconds))
8814 (tramp-compat-funcall
8815 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
8816 ((fboundp 'itimer-time-difference)
8817 (tramp-compat-funcall
8818 'itimer-time-difference
8819 (if (< (length t1) 3) (append t1 '(0)) t1)
8820 (if (< (length t2) 3) (append t2 '(0)) t2)))
8822 (let ((time (tramp-time-subtract t1 t2)))
8823 (+ (* (car time) 65536.0)
8825 (/ (or (nth 2 time) 0) 1000000.0))))))
8827 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8828 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8829 EOL-TYPE can be one of `dos', `unix', or `mac'."
8830 (cond ((fboundp 'coding-system-change-eol-conversion)
8831 (tramp-compat-funcall
8832 'coding-system-change-eol-conversion coding-system eol-type))
8833 ((fboundp 'subsidiary-coding-system)
8834 (tramp-compat-funcall
8835 'subsidiary-coding-system coding-system
8836 (cond ((eq eol-type 'dos) 'crlf)
8837 ((eq eol-type 'unix) 'lf)
8838 ((eq eol-type 'mac) 'cr)
8840 (error "Unknown EOL-TYPE `%s', must be %s"
8842 "`dos', `unix', or `mac'")))))
8843 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8845 (defun tramp-set-process-query-on-exit-flag (process flag)
8846 "Specify if query is needed for process when Emacs is exited.
8847 If the second argument flag is non-nil, Emacs will query the user before
8848 exiting if process is running."
8849 (if (fboundp 'set-process-query-on-exit-flag)
8850 (tramp-compat-funcall 'set-process-query-on-exit-flag process flag)
8851 (tramp-compat-funcall 'process-kill-without-query process flag)))
8854 ;; ------------------------------------------------------------
8855 ;; -- Kludges section --
8856 ;; ------------------------------------------------------------
8858 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8859 ;; does not deal well with newline characters. Newline is replaced by
8860 ;; backslash newline. But if, say, the string `a backslash newline b'
8861 ;; is passed to a shell, the shell will expand this into "ab",
8862 ;; completely omitting the newline. This is not what was intended.
8863 ;; It does not appear to be possible to make the function
8864 ;; `shell-quote-argument' work with newlines without making it
8865 ;; dependent on the shell used. But within this package, we know that
8866 ;; we will always use a Bourne-like shell, so we use an approach which
8869 ;; The approach is simple: we call `shell-quote-argument', then
8870 ;; massage the newline part of the result.
8872 ;; This function should produce a string which is grokked by a Unix
8873 ;; shell, even if the Emacs is running on Windows. Since this is the
8874 ;; kludges section, we bind `system-type' in such a way that
8875 ;; `shell-quote-arguments' behaves as if on Unix.
8877 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8878 ;; function to work with Bourne-like shells.
8880 ;; CCC: This function should be rewritten so that
8881 ;; `shell-quote-argument' is not used. This way, we are safe from
8882 ;; changes in `shell-quote-argument'.
8883 (defun tramp-shell-quote-argument (s)
8884 "Similar to `shell-quote-argument', but groks newlines.
8885 Only works for Bourne-like shells."
8886 (let ((system-type 'not-windows))
8888 (let ((result (shell-quote-argument s))
8889 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8890 (when (and (>= (length result) 2)
8891 (string= (substring result 0 2) "\\~"))
8892 (setq result (substring result 1)))
8893 (while (string-match nl result)
8894 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8898 ;; Checklist for `tramp-unload-hook'
8899 ;; - Unload all `tramp-*' packages
8900 ;; - Reset `file-name-handler-alist'
8901 ;; - Cleanup hooks where Tramp functions are in
8902 ;; - Cleanup advised functions
8903 ;; - Cleanup autoloads
8905 (defun tramp-unload-tramp ()
8906 "Discard Tramp from loading remote files."
8908 ;; When Tramp is not loaded yet, its autoloads are still active.
8909 (tramp-unload-file-name-handlers)
8910 ;; ange-ftp settings must be enabled.
8911 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
8912 ;; Maybe its not loaded yet.
8914 (unload-feature 'tramp 'force)
8917 (when (and load-in-progress
8918 (string-match "Loading tramp..." (or (current-message) "")))
8919 (message "Loading tramp...done"))
8925 ;; * Handle nonlocal exits such as C-g.
8926 ;; * But it would probably be better to use with-local-quit at the
8927 ;; place where it's actually needed: around any potentially
8928 ;; indefinitely blocking piece of code. In this case it would be
8929 ;; within Tramp around one of its calls to accept-process-output (or
8930 ;; around one of the loops that calls accept-process-output)
8931 ;; (Stefan Monnier).
8932 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8933 ;; `shell-quote-argument'.
8934 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8935 ;; by the files in that directory. Add this here.
8936 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8937 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8938 ;; * Don't use globbing for directories with many files, as this is
8939 ;; likely to produce long command lines, and some shells choke on
8940 ;; long command lines.
8941 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8942 ;; * abbreviate-file-name
8943 ;; * Better error checking. At least whenever we see something
8944 ;; strange when doing zerop, we should kill the process and start
8945 ;; again. (Greg Stark)
8946 ;; * Remove unneeded parameters from methods.
8947 ;; * Make it work for different encodings, and for different file name
8948 ;; encodings, too. (Daniel Pittman)
8949 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8950 ;; then look if it's the right version (with `perl -v').
8951 ;; * When editing a remote CVS controlled file as a different user, VC
8952 ;; gets confused about the file locking status. Try to find out why
8953 ;; the workaround doesn't work.
8954 ;; * Username and hostname completion.
8955 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8956 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8957 ;; Code is nearly identical.
8958 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8959 ;; until the last but one hop via `start-file-process'. Apply it
8960 ;; also for ftp and smb.
8961 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8962 ;; some shell with root priviledges, it would be nice if I could
8964 ;; trampclient filename.c
8965 ;; as an editor, and the _current_ shell would connect to an Emacs
8966 ;; server and would be used in an existing non-priviledged Emacs
8967 ;; session for doing the editing in question.
8968 ;; That way, I need not tell Emacs my password again and be afraid
8969 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8970 ;; once display a just typed password in the context of a keyboard
8971 ;; sequence prompt for a question immediately following in a shell
8972 ;; script run within Emacs -- nasty).
8973 ;; And if I have some ssh session running to a different computer,
8974 ;; having the possibility of passing a local file there to a local
8975 ;; Emacs session (in case I can arrange for a connection back) would
8977 ;; Likely the corresponding Tramp server should not allow the
8978 ;; equivalent of the emacsclient -eval option in order to make this
8979 ;; reasonably unproblematic. And maybe trampclient should have some
8980 ;; way of passing credentials, like by using an SSL socket or
8981 ;; something. (David Kastrup)
8982 ;; * Reconnect directly to a compliant shell without first going
8983 ;; through the user's default shell. (Pete Forman)
8984 ;; * Make `tramp-default-user' obsolete.
8985 ;; * How can I interrupt the remote process with a signal
8986 ;; (interrupt-process seems not to work)? (Markus Triska)
8987 ;; * Avoid the local shell entirely for starting remote processes. If
8988 ;; so, I think even a signal, when delivered directly to the local
8989 ;; SSH instance, would correctly be propagated to the remote process
8990 ;; automatically; possibly SSH would have to be started with
8991 ;; "-t". (Markus Triska)
8992 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8993 ;; isn't on the remote host. (Mark A. Hershberger)
8994 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8995 ;; * Implement a general server-local-variable mechanism, as there are
8996 ;; probably other variables that need different values for different
8997 ;; servers too. The user could then configure a variable (such as
8998 ;; tramp-server-local-variable-alist) to define any such variables
8999 ;; that they need to, which would then be let bound as appropriate
9000 ;; in tramp functions. (Jason Rumney)
9001 ;; * Optimize out-of-band copying, when both methods are scp-like (not
9003 ;; * Keep a second connection open for out-of-band methods like scp or
9005 ;; * IMHO, it's a drawback that currently Tramp doesn't support
9006 ;; Unicode in Dired file names by default. Is it possible to
9007 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
9008 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
9009 ;; expects only English messages? (Juri Linkov)
9010 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
9011 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
9012 ;; * Try telnet+curl as new method. It might be useful for busybox,
9013 ;; without built-in uuencode/uudecode.
9014 ;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
9015 ;; * I was wondering it it would be possible to use tramp even if I'm
9016 ;; actually using sshfs. But when I launch a command I would like
9017 ;; to get it executed on the remote machine where the files really
9018 ;; are. (Andrea Crotti)
9019 ;; * Run emerge on two remote files. Bug is described here:
9020 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
9023 ;; Functions for file-name-handler-alist:
9024 ;; diff-latest-backup-file -- in diff.el
9026 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
9027 ;;; tramp.el ends here