1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009 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 21.1 and higher, and for XEmacs 21.4
40 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
41 ;; the `with-timeout' macro.)
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) ; from Gnus 5.8, also in tar ball
83 ;; As long as password.el is not part of (X)Emacs, it shouldn't
85 (if (featurep 'xemacs)
86 (load "password" 'noerror)
87 (or (require 'password-cache nil 'noerror)
88 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
94 (if (featurep 'xemacs)
95 (load "auth-source" 'noerror)
96 (require 'auth-source nil 'noerror)))
98 ;; Requiring 'tramp-cache results in an endless loop.
99 (autoload 'tramp-get-file-property "tramp-cache")
100 (autoload 'tramp-set-file-property "tramp-cache")
101 (autoload 'tramp-flush-file-property "tramp-cache")
102 (autoload 'tramp-flush-directory-property "tramp-cache")
103 (autoload 'tramp-get-connection-property "tramp-cache")
104 (autoload 'tramp-set-connection-property "tramp-cache")
105 (autoload 'tramp-flush-connection-property "tramp-cache")
106 (autoload 'tramp-parse-connection-properties "tramp-cache")
107 (add-hook 'tramp-unload-hook
109 (when (featurep 'tramp-cache)
110 (unload-feature 'tramp-cache 'force))))
112 (autoload 'tramp-uuencode-region "tramp-uu"
113 "Implementation of `uuencode' in Lisp.")
114 (add-hook 'tramp-unload-hook
116 (when (featurep 'tramp-uu)
117 (unload-feature 'tramp-uu 'force))))
119 (autoload 'uudecode-decode-region "uudecode")
121 ;; The following Tramp packages must be loaded after tramp.el, because
122 ;; they require it as well.
123 (eval-after-load "tramp"
128 ;; Tramp interactive commands.
131 ;; Load foreign FTP method.
132 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
134 ;; tramp-smb uses "smbclient" from Samba. Not available
135 ;; under Cygwin and Windows, because they don't offer
136 ;; "smbclient". And even not necessary there, because Emacs
137 ;; supports UNC file names like "//host/share/localname".
138 (unless (memq system-type '(cygwin windows-nt)) 'tramp-smb)
140 ;; Load foreign FISH method.
143 ;; tramp-gvfs needs D-Bus messages. Available since Emacs 23
144 ;; on some system types. We don't call `dbus-ping', because
145 ;; this would load dbus.el.
146 (when (and (featurep 'dbusbind)
148 (funcall 'dbus-get-unique-name :session)
150 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
153 ;; Load gateways. It needs `make-network-process' from Emacs 22.
154 (when (functionp 'make-network-process) 'tramp-gw)
156 ;; tramp-imap needs both epa (from Emacs 23.1) and imap-hash
157 ;; (from Emacs 23.2).
158 (when (and (locate-library "epa") (locate-library "imap-hash"))
162 ;; We have used just some basic tests, whether a package shall
163 ;; be added. There might still be other errors during loading,
164 ;; which we will catch here.
165 (catch 'tramp-loading
167 (add-hook 'tramp-unload-hook
169 (when (featurep (quote ,feature))
170 (unload-feature (quote ,feature) 'force)))))
171 (unless (featurep feature)
172 (message "Loading %s failed, ignoring this package" feature)))))
174 ;;; User Customizable Internal Variables:
177 "Edit remote files with a combination of rsh and rcp or similar programs."
181 ;; Maybe we need once a real Tramp mode, with key bindings etc.
183 (defcustom tramp-mode t
184 "*Whether Tramp is enabled.
185 If it is set to nil, all remote file names are used literally."
189 (defcustom tramp-verbose 3
190 "*Verbosity level for Tramp messages.
191 Any level x includes messages for all levels 1 .. x-1. The levels are
193 0 silent (no tramp messages at all)
196 3 connection to remote hosts (default level)
199 6 sent and received strings
201 8 connection properties
208 (when (boundp 'backup-directory-alist)
209 (defcustom tramp-backup-directory-alist nil
210 "Alist of filename patterns and backup directory names.
211 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
212 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
213 is a local file name, the backup directory is prepended with Tramp file
214 name prefix \(method, user, host\) of file.
216 \(setq tramp-backup-directory-alist backup-directory-alist\)
218 gives the same backup policy for Tramp files on their hosts like the
219 policy for local files."
221 :type '(repeat (cons (regexp :tag "Regexp matching filename")
222 (directory :tag "Backup directory name"))))))
224 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
225 ;; the package "backup-dir" might not be loaded yet.
227 (when (featurep 'xemacs)
228 (defcustom tramp-bkup-backup-directory-info nil
229 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
230 It has the same meaning like `bkup-backup-directory-info' from package
231 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
232 file name, the backup directory is prepended with Tramp file name prefix
233 \(method, user, host\) of file.
235 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
237 gives the same backup policy for Tramp files on their hosts like the
238 policy for local files."
240 (list (regexp :tag "File regexp")
241 (string :tag "Backup Dir")
246 (const search-upward))))
249 (defcustom tramp-auto-save-directory nil
250 "*Put auto-save files in this directory, if set.
251 The idea is to use a local directory so that auto-saving is faster."
253 :type '(choice (const nil) string))
255 (defcustom tramp-encoding-shell
256 (if (memq system-type '(windows-nt))
259 "*Use this program for encoding and decoding commands on the local host.
260 This shell is used to execute the encoding and decoding command on the
261 local host, so if you want to use `~' in those commands, you should
262 choose a shell here which groks tilde expansion. `/bin/sh' normally
263 does not understand tilde expansion.
265 For encoding and deocding, commands like the following are executed:
267 /bin/sh -c COMMAND < INPUT > OUTPUT
269 This variable can be used to change the \"/bin/sh\" part. See the
270 variable `tramp-encoding-command-switch' for the \"-c\" part.
272 Note that this variable is not used for remote commands. There are
273 mechanisms in tramp.el which automatically determine the right shell to
274 use for the remote host."
276 :type '(file :must-match t))
278 (defcustom tramp-encoding-command-switch
279 (if (string-match "cmd\\.exe" tramp-encoding-shell)
282 "*Use this switch together with `tramp-encoding-shell' for local commands.
283 See the variable `tramp-encoding-shell' for more information."
287 (defcustom tramp-copy-size-limit 10240
288 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
292 (defcustom tramp-terminal-type "dumb"
293 "*Value of TERM environment variable for logging in to remote host.
294 Because Tramp wants to parse the output of the remote shell, it is easily
295 confused by ANSI color escape sequences and suchlike. Often, shell init
296 files conditionalize this setup based on the TERM environment variable."
300 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
301 ;; root users. It uses the `$' character for other users. In order
302 ;; to guarantee a proper prompt, we use "#$" for the prompt.
304 (defvar tramp-end-of-output
307 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
308 "String used to recognize end of output.
309 The '$' character at the end is quoted; the string cannot be
310 detected as prompt when being sent on echoing hosts, therefore.")
312 (defconst tramp-initial-end-of-output "#$ "
313 "Prompt when establishing a connection.")
315 (defvar tramp-methods
316 `(("rcp" (tramp-login-program "rsh")
317 (tramp-login-args (("%h") ("-l" "%u")))
318 (tramp-remote-sh "/bin/sh")
319 (tramp-copy-program "rcp")
320 (tramp-copy-args (("-p" "%k") ("-r")))
321 (tramp-copy-keep-date t)
322 (tramp-copy-recursive t)
323 (tramp-password-end-of-line nil))
324 ("scp" (tramp-login-program "ssh")
325 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
327 (tramp-remote-sh "/bin/sh")
328 (tramp-copy-program "scp")
329 (tramp-copy-args (("-P" "%p") ("-p" "%k")
331 (tramp-copy-keep-date t)
332 (tramp-copy-recursive t)
333 (tramp-password-end-of-line nil)
334 (tramp-gw-args (("-o"
335 "GlobalKnownHostsFile=/dev/null")
336 ("-o" "UserKnownHostsFile=/dev/null")
337 ("-o" "StrictHostKeyChecking=no")))
338 (tramp-default-port 22))
339 ("scp1" (tramp-login-program "ssh")
340 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
342 (tramp-remote-sh "/bin/sh")
343 (tramp-copy-program "scp")
344 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
346 (tramp-copy-keep-date t)
347 (tramp-copy-recursive t)
348 (tramp-password-end-of-line nil)
349 (tramp-gw-args (("-o"
350 "GlobalKnownHostsFile=/dev/null")
351 ("-o" "UserKnownHostsFile=/dev/null")
352 ("-o" "StrictHostKeyChecking=no")))
353 (tramp-default-port 22))
354 ("scp2" (tramp-login-program "ssh")
355 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
357 (tramp-remote-sh "/bin/sh")
358 (tramp-copy-program "scp")
359 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
361 (tramp-copy-keep-date t)
362 (tramp-copy-recursive t)
363 (tramp-password-end-of-line nil)
364 (tramp-gw-args (("-o"
365 "GlobalKnownHostsFile=/dev/null")
366 ("-o" "UserKnownHostsFile=/dev/null")
367 ("-o" "StrictHostKeyChecking=no")))
368 (tramp-default-port 22))
370 (tramp-login-program "ssh1")
371 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
373 (tramp-remote-sh "/bin/sh")
374 (tramp-copy-program "scp1")
375 (tramp-copy-args (("-p" "%k") ("-r")))
376 (tramp-copy-keep-date t)
377 (tramp-copy-recursive t)
378 (tramp-password-end-of-line nil))
380 (tramp-login-program "ssh2")
381 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
383 (tramp-remote-sh "/bin/sh")
384 (tramp-copy-program "scp2")
385 (tramp-copy-args (("-p" "%k") ("-r")))
386 (tramp-copy-keep-date t)
387 (tramp-copy-recursive t)
388 (tramp-password-end-of-line nil))
389 ("sftp" (tramp-login-program "ssh")
390 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
392 (tramp-remote-sh "/bin/sh")
393 (tramp-copy-program "sftp")
394 (tramp-copy-args nil)
395 (tramp-copy-keep-date nil)
396 (tramp-password-end-of-line nil))
397 ("rsync" (tramp-login-program "ssh")
398 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
400 (tramp-remote-sh "/bin/sh")
401 (tramp-copy-program "rsync")
402 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
403 (tramp-copy-keep-date t)
404 (tramp-copy-keep-tmpfile t)
405 (tramp-copy-recursive t)
406 (tramp-password-end-of-line nil))
408 (tramp-login-program "ssh")
409 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
410 ("-o" "ControlPath=%t.%%r@%%h:%%p")
411 ("-o" "ControlMaster=yes")
413 (tramp-remote-sh "/bin/sh")
414 (tramp-copy-program "rsync")
415 (tramp-copy-args (("-t" "%k") ("-r")))
416 (tramp-copy-env (("RSYNC_RSH")
419 " -o ControlPath=%t.%%r@%%h:%%p"
420 " -o ControlMaster=auto"))))
421 (tramp-copy-keep-date t)
422 (tramp-copy-keep-tmpfile t)
423 (tramp-copy-recursive t)
424 (tramp-password-end-of-line nil))
425 ("remcp" (tramp-login-program "remsh")
426 (tramp-login-args (("%h") ("-l" "%u")))
427 (tramp-remote-sh "/bin/sh")
428 (tramp-copy-program "rcp")
429 (tramp-copy-args (("-p" "%k")))
430 (tramp-copy-keep-date t)
431 (tramp-password-end-of-line nil))
432 ("rsh" (tramp-login-program "rsh")
433 (tramp-login-args (("%h") ("-l" "%u")))
434 (tramp-remote-sh "/bin/sh")
435 (tramp-copy-program nil)
436 (tramp-copy-args nil)
437 (tramp-copy-keep-date nil)
438 (tramp-password-end-of-line nil))
439 ("ssh" (tramp-login-program "ssh")
440 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
442 (tramp-remote-sh "/bin/sh")
443 (tramp-copy-program nil)
444 (tramp-copy-args nil)
445 (tramp-copy-keep-date nil)
446 (tramp-password-end-of-line nil)
447 (tramp-gw-args (("-o"
448 "GlobalKnownHostsFile=/dev/null")
449 ("-o" "UserKnownHostsFile=/dev/null")
450 ("-o" "StrictHostKeyChecking=no")))
451 (tramp-default-port 22))
452 ("ssh1" (tramp-login-program "ssh")
453 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
455 (tramp-remote-sh "/bin/sh")
456 (tramp-copy-program nil)
457 (tramp-copy-args nil)
458 (tramp-copy-keep-date nil)
459 (tramp-password-end-of-line nil)
460 (tramp-gw-args (("-o"
461 "GlobalKnownHostsFile=/dev/null")
462 ("-o" "UserKnownHostsFile=/dev/null")
463 ("-o" "StrictHostKeyChecking=no")))
464 (tramp-default-port 22))
465 ("ssh2" (tramp-login-program "ssh")
466 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
468 (tramp-remote-sh "/bin/sh")
469 (tramp-copy-program nil)
470 (tramp-copy-args nil)
471 (tramp-copy-keep-date nil)
472 (tramp-password-end-of-line nil)
473 (tramp-gw-args (("-o"
474 "GlobalKnownHostsFile=/dev/null")
475 ("-o" "UserKnownHostsFile=/dev/null")
476 ("-o" "StrictHostKeyChecking=no")))
477 (tramp-default-port 22))
479 (tramp-login-program "ssh1")
480 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
482 (tramp-remote-sh "/bin/sh")
483 (tramp-copy-program nil)
484 (tramp-copy-args nil)
485 (tramp-copy-keep-date nil)
486 (tramp-password-end-of-line nil))
488 (tramp-login-program "ssh2")
489 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
491 (tramp-remote-sh "/bin/sh")
492 (tramp-copy-program nil)
493 (tramp-copy-args nil)
494 (tramp-copy-keep-date nil)
495 (tramp-password-end-of-line nil))
496 ("remsh" (tramp-login-program "remsh")
497 (tramp-login-args (("%h") ("-l" "%u")))
498 (tramp-remote-sh "/bin/sh")
499 (tramp-copy-program nil)
500 (tramp-copy-args nil)
501 (tramp-copy-keep-date nil)
502 (tramp-password-end-of-line nil))
504 (tramp-login-program "telnet")
505 (tramp-login-args (("%h") ("%p")))
506 (tramp-remote-sh "/bin/sh")
507 (tramp-copy-program nil)
508 (tramp-copy-args nil)
509 (tramp-copy-keep-date nil)
510 (tramp-password-end-of-line nil)
511 (tramp-default-port 23))
512 ("su" (tramp-login-program "su")
513 (tramp-login-args (("-") ("%u")))
514 (tramp-remote-sh "/bin/sh")
515 (tramp-copy-program nil)
516 (tramp-copy-args nil)
517 (tramp-copy-keep-date nil)
518 (tramp-password-end-of-line nil))
519 ("sudo" (tramp-login-program "sudo")
520 (tramp-login-args (("-u" "%u")
521 ("-s") ("-H") ("-p" "Password:")))
522 (tramp-remote-sh "/bin/sh")
523 (tramp-copy-program nil)
524 (tramp-copy-args nil)
525 (tramp-copy-keep-date nil)
526 (tramp-password-end-of-line nil))
527 ("scpc" (tramp-login-program "ssh")
528 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
529 ("-o" "ControlPath=%t.%%r@%%h:%%p")
530 ("-o" "ControlMaster=yes")
532 (tramp-remote-sh "/bin/sh")
533 (tramp-copy-program "scp")
534 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
535 ("-o" "ControlPath=%t.%%r@%%h:%%p")
536 ("-o" "ControlMaster=auto")))
537 (tramp-copy-keep-date t)
538 (tramp-password-end-of-line nil)
539 (tramp-gw-args (("-o"
540 "GlobalKnownHostsFile=/dev/null")
541 ("-o" "UserKnownHostsFile=/dev/null")
542 ("-o" "StrictHostKeyChecking=no")))
543 (tramp-default-port 22))
544 ("scpx" (tramp-login-program "ssh")
545 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
546 ("-e" "none" "-t" "-t" "/bin/sh")))
547 (tramp-remote-sh "/bin/sh")
548 (tramp-copy-program "scp")
549 (tramp-copy-args (("-p" "%k")))
550 (tramp-copy-keep-date t)
551 (tramp-password-end-of-line nil)
552 (tramp-gw-args (("-o"
553 "GlobalKnownHostsFile=/dev/null")
554 ("-o" "UserKnownHostsFile=/dev/null")
555 ("-o" "StrictHostKeyChecking=no")))
556 (tramp-default-port 22))
557 ("sshx" (tramp-login-program "ssh")
558 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
559 ("-e" "none" "-t" "-t" "/bin/sh")))
560 (tramp-remote-sh "/bin/sh")
561 (tramp-copy-program nil)
562 (tramp-copy-args nil)
563 (tramp-copy-keep-date nil)
564 (tramp-password-end-of-line nil)
565 (tramp-gw-args (("-o"
566 "GlobalKnownHostsFile=/dev/null")
567 ("-o" "UserKnownHostsFile=/dev/null")
568 ("-o" "StrictHostKeyChecking=no")))
569 (tramp-default-port 22))
571 (tramp-login-program "krlogin")
572 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
573 (tramp-remote-sh "/bin/sh")
574 (tramp-copy-program nil)
575 (tramp-copy-args nil)
576 (tramp-copy-keep-date nil)
577 (tramp-password-end-of-line nil))
578 ("plink" (tramp-login-program "plink")
579 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
581 (tramp-remote-sh "/bin/sh")
582 (tramp-copy-program nil)
583 (tramp-copy-args nil)
584 (tramp-copy-keep-date nil)
585 (tramp-password-end-of-line "xy") ;see docstring for "xy"
586 (tramp-default-port 22))
588 (tramp-login-program "plink")
589 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
591 (tramp-remote-sh "/bin/sh")
592 (tramp-copy-program nil)
593 (tramp-copy-args nil)
594 (tramp-copy-keep-date nil)
595 (tramp-password-end-of-line "xy") ;see docstring for "xy"
596 (tramp-default-port 22))
598 (tramp-login-program "plink")
599 ;; ("%h") must be a single element, see
600 ;; `tramp-compute-multi-hops'.
601 (tramp-login-args (("-load") ("%h") ("-t")
603 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
605 tramp-initial-end-of-output))
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 nil))
612 ("pscp" (tramp-login-program "plink")
613 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
615 (tramp-remote-sh "/bin/sh")
616 (tramp-copy-program "pscp")
617 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
618 (tramp-copy-keep-date t)
619 (tramp-password-end-of-line "xy") ;see docstring for "xy"
620 (tramp-default-port 22))
621 ("psftp" (tramp-login-program "plink")
622 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
624 (tramp-remote-sh "/bin/sh")
625 (tramp-copy-program "pscp")
626 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
627 (tramp-copy-keep-date t)
628 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
629 ("fcp" (tramp-login-program "fsh")
630 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
631 (tramp-remote-sh "/bin/sh -i")
632 (tramp-copy-program "fcp")
633 (tramp-copy-args (("-p" "%k")))
634 (tramp-copy-keep-date t)
635 (tramp-password-end-of-line nil)))
636 "*Alist of methods for remote files.
637 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
638 Each NAME stands for a remote access method. Each PARAM is a
639 pair of the form (KEY VALUE). The following KEYs are defined:
641 This specifies the Bourne shell to use on the remote host. This
642 MUST be a Bourne-like shell. It is normally not necessary to set
643 this to any value other than \"/bin/sh\": Tramp wants to use a shell
644 which groks tilde expansion, but it can search for it. Also note
645 that \"/bin/sh\" exists on all Unixen, this might not be true for
646 the value that you decide to use. You Have Been Warned.
647 * `tramp-login-program'
648 This specifies the name of the program to use for logging in to the
649 remote host. This may be the name of rsh or a workalike program,
650 or the name of telnet or a workalike, or the name of su or a workalike.
652 This specifies the list of arguments to pass to the above
653 mentioned program. Please note that this is a list of list of arguments,
654 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
655 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
656 There are some patterns: \"%h\" in this list is replaced by the host
657 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
658 port number, and \"%%\" can be used to obtain a literal percent character.
659 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
660 expansion (i.e. no host or no user specified), this list is not used as
661 argument. By this, arguments like (\"-l\" \"%u\") are optional.
662 \"%t\" is replaced by the temporary file name produced with
663 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
664 parameter of a program, if exists.
665 * `tramp-copy-program'
666 This specifies the name of the program to use for remotely copying
667 the file; this might be the absolute filename of rcp or the name of
670 This specifies the list of parameters to pass to the above mentioned
671 program, the hints for `tramp-login-args' also apply here.
672 * `tramp-copy-keep-date'
673 This specifies whether the copying program when the preserves the
674 timestamp of the original file.
675 * `tramp-copy-keep-tmpfile'
676 This specifies whether a temporary local file shall be kept
677 for optimization reasons (useful for \"rsync\" methods).
678 * `tramp-copy-recursive'
679 Whether the operation copies directories recursively.
680 * `tramp-default-port'
681 The default port of a method is needed in case of gateway connections.
682 Additionally, it is used as indication which method is prepared for
685 As the attribute name says, additional arguments are specified here
686 when a method is applied via a gateway.
687 * `tramp-password-end-of-line'
688 This specifies the string to use for terminating the line after
689 submitting the password. If this method parameter is nil, then the
690 value of the normal variable `tramp-default-password-end-of-line'
691 is used. This parameter is necessary because the \"plink\" program
692 requires any two characters after sending the password. These do
693 not have to be newline or carriage return characters. Other login
694 programs are happy with just one character, the newline character.
695 We use \"xy\" as the value for methods using \"plink\".
697 What does all this mean? Well, you should specify `tramp-login-program'
698 for all methods; this program is used to log in to the remote site. Then,
699 there are two ways to actually transfer the files between the local and the
700 remote side. One way is using an additional rcp-like program. If you want
701 to do this, set `tramp-copy-program' in the method.
703 Another possibility for file transfer is inline transfer, i.e. the
704 file is passed through the same buffer used by `tramp-login-program'. In
705 this case, the file contents need to be protected since the
706 `tramp-login-program' might use escape codes or the connection might not
707 be eight-bit clean. Therefore, file contents are encoded for transit.
708 See the variables `tramp-local-coding-commands' and
709 `tramp-remote-coding-commands' for details.
711 So, to summarize: if the method is an out-of-band method, then you
712 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
713 inline method, then these two parameters should be nil. Methods which
714 are fit for gateways must have `tramp-default-port' at least.
718 When using `su' or `sudo' the phrase `open connection to a remote
719 host' sounds strange, but it is used nevertheless, for consistency.
720 No connection is opened to a remote host, but `su' or `sudo' is
721 started on the local host. You should specify a remote host
722 `localhost' or the name of the local host. Another host name is
723 useful only in combination with `tramp-default-proxies-alist'.")
725 (defcustom tramp-default-method
726 ;; An external copy method seems to be preferred, because it is much
727 ;; more performant for large files, and it hasn't too serious delays
728 ;; for small files. But it must be ensured that there aren't
729 ;; permanent password queries. Either a password agent like
730 ;; "ssh-agent" or "Pageant" shall run, or the optional
731 ;; password-cache.el or auth-sources.el packages shall be active for
732 ;; password caching. "scpc" would be another good choice because of
733 ;; the "ControlMaster" option, but this is a more modern alternative
734 ;; in OpenSSH 4, which cannot be taken as default.
736 ;; PuTTY is installed.
737 ((executable-find "pscp")
738 (if (or (fboundp 'password-read)
739 (fboundp 'auth-source-user-or-password)
740 ;; Pageant is running.
741 (tramp-compat-process-running-p "Pageant"))
744 ;; There is an ssh installation.
745 ((executable-find "scp")
746 (if (or (fboundp 'password-read)
747 (fboundp 'auth-source-user-or-password)
748 ;; ssh-agent is running.
749 (getenv "SSH_AUTH_SOCK")
750 (getenv "SSH_AGENT_PID"))
755 "*Default method to use for transferring files.
756 See `tramp-methods' for possibilities.
757 Also see `tramp-default-method-alist'."
761 (defcustom tramp-default-method-alist
762 '(("\\`localhost\\'" "\\`root\\'" "su"))
763 "*Default method to use for specific host/user pairs.
764 This is an alist of items (HOST USER METHOD). The first matching item
765 specifies the method to use for a file name which does not specify a
766 method. HOST and USER are regular expressions or nil, which is
767 interpreted as a regular expression which always matches. If no entry
768 matches, the variable `tramp-default-method' takes effect.
770 If the file name does not specify the user, lookup is done using the
771 empty string for the user name.
773 See `tramp-methods' for a list of possibilities for METHOD."
775 :type '(repeat (list (regexp :tag "Host regexp")
776 (regexp :tag "User regexp")
777 (string :tag "Method"))))
779 (defcustom tramp-default-user
781 "*Default user to use for transferring files.
782 It is nil by default; otherwise settings in configuration files like
783 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
785 This variable is regarded as obsolete, and will be removed soon."
787 :type '(choice (const nil) string))
789 (defcustom tramp-default-user-alist
790 `(("\\`su\\(do\\)?\\'" nil "root")
791 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
792 nil ,(user-login-name)))
793 "*Default user to use for specific method/host pairs.
794 This is an alist of items (METHOD HOST USER). The first matching item
795 specifies the user to use for a file name which does not specify a
796 user. METHOD and USER are regular expressions or nil, which is
797 interpreted as a regular expression which always matches. If no entry
798 matches, the variable `tramp-default-user' takes effect.
800 If the file name does not specify the method, lookup is done using the
801 empty string for the method name."
803 :type '(repeat (list (regexp :tag "Method regexp")
804 (regexp :tag "Host regexp")
805 (string :tag "User"))))
807 (defcustom tramp-default-host
809 "*Default host to use for transferring files.
810 Useful for su and sudo methods mostly."
814 (defcustom tramp-default-proxies-alist nil
815 "*Route to be followed for specific host/user pairs.
816 This is an alist of items (HOST USER PROXY). The first matching
817 item specifies the proxy to be passed for a file name located on
818 a remote target matching USER@HOST. HOST and USER are regular
819 expressions. PROXY must be a Tramp filename without a localname
820 part. Method and user name on PROXY are optional, which is
821 interpreted with the default values. PROXY can contain the
822 patterns %h and %u, which are replaced by the strings matching
823 HOST or USER, respectively.
825 HOST, USER or PROXY could also be Lisp forms, which will be
826 evaluated. The result must be a string or nil, which is
827 interpreted as a regular expression which always matches."
829 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
830 (choice :tag "User regexp" regexp sexp)
831 (choice :tag "Proxy remote name" string (const nil)))))
833 (defconst tramp-local-host-regexp
835 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
836 "*Host names which are regarded as local host.")
838 (defconst tramp-completion-function-alist-rsh
839 '((tramp-parse-rhosts "/etc/hosts.equiv")
840 (tramp-parse-rhosts "~/.rhosts"))
841 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
843 (defconst tramp-completion-function-alist-ssh
844 '((tramp-parse-rhosts "/etc/hosts.equiv")
845 (tramp-parse-rhosts "/etc/shosts.equiv")
846 (tramp-parse-shosts "/etc/ssh_known_hosts")
847 (tramp-parse-sconfig "/etc/ssh_config")
848 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
849 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
850 (tramp-parse-rhosts "~/.rhosts")
851 (tramp-parse-rhosts "~/.shosts")
852 (tramp-parse-shosts "~/.ssh/known_hosts")
853 (tramp-parse-sconfig "~/.ssh/config")
854 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
855 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
856 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
858 (defconst tramp-completion-function-alist-telnet
859 '((tramp-parse-hosts "/etc/hosts"))
860 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
862 (defconst tramp-completion-function-alist-su
863 '((tramp-parse-passwd "/etc/passwd"))
864 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
866 (defconst tramp-completion-function-alist-putty
868 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
869 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
871 (defvar tramp-completion-function-alist nil
872 "*Alist of methods for remote files.
873 This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
874 Each NAME stands for a remote access method. Each PAIR is of the form
875 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
876 names from FILE for completion. The following predefined FUNCTIONs exists:
878 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
879 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
880 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
881 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
882 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
883 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
884 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
885 * `tramp-parse-netrc' for \"~/.netrc\" like files.
886 * `tramp-parse-putty' for PuTTY registry keys.
888 FUNCTION can also be a customer defined function. For more details see
891 (eval-after-load "tramp"
893 (tramp-set-completion-function
894 "rcp" tramp-completion-function-alist-rsh)
895 (tramp-set-completion-function
896 "scp" tramp-completion-function-alist-ssh)
897 (tramp-set-completion-function
898 "scp1" tramp-completion-function-alist-ssh)
899 (tramp-set-completion-function
900 "scp2" tramp-completion-function-alist-ssh)
901 (tramp-set-completion-function
902 "scp1_old" tramp-completion-function-alist-ssh)
903 (tramp-set-completion-function
904 "scp2_old" tramp-completion-function-alist-ssh)
905 (tramp-set-completion-function
906 "rsync" tramp-completion-function-alist-ssh)
907 (tramp-set-completion-function
908 "rsyncc" tramp-completion-function-alist-ssh)
909 (tramp-set-completion-function
910 "remcp" tramp-completion-function-alist-rsh)
911 (tramp-set-completion-function
912 "rsh" tramp-completion-function-alist-rsh)
913 (tramp-set-completion-function
914 "ssh" tramp-completion-function-alist-ssh)
915 (tramp-set-completion-function
916 "ssh1" tramp-completion-function-alist-ssh)
917 (tramp-set-completion-function
918 "ssh2" tramp-completion-function-alist-ssh)
919 (tramp-set-completion-function
920 "ssh1_old" tramp-completion-function-alist-ssh)
921 (tramp-set-completion-function
922 "ssh2_old" tramp-completion-function-alist-ssh)
923 (tramp-set-completion-function
924 "remsh" tramp-completion-function-alist-rsh)
925 (tramp-set-completion-function
926 "telnet" tramp-completion-function-alist-telnet)
927 (tramp-set-completion-function
928 "su" tramp-completion-function-alist-su)
929 (tramp-set-completion-function
930 "sudo" tramp-completion-function-alist-su)
931 (tramp-set-completion-function
932 "scpx" tramp-completion-function-alist-ssh)
933 (tramp-set-completion-function
934 "sshx" tramp-completion-function-alist-ssh)
935 (tramp-set-completion-function
936 "krlogin" tramp-completion-function-alist-rsh)
937 (tramp-set-completion-function
938 "plink" tramp-completion-function-alist-ssh)
939 (tramp-set-completion-function
940 "plink1" tramp-completion-function-alist-ssh)
941 (tramp-set-completion-function
942 "plinkx" tramp-completion-function-alist-putty)
943 (tramp-set-completion-function
944 "pscp" tramp-completion-function-alist-ssh)
945 (tramp-set-completion-function
946 "fcp" tramp-completion-function-alist-ssh)))
948 (defconst tramp-echo-mark-marker "_echo"
949 "String marker to surround echoed commands.")
951 (defconst tramp-echo-mark "_echo\b\b\b\b\b"
952 "String mark to be transmitted around shell commands.
953 Used to separate their echo from the output they produce. This
954 will only be used if we cannot disable remote echo via stty.
955 This string must have no effect on the remote shell except for
956 producing some echo which can later be detected by
957 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
958 followed by an equal number of backspaces to erase them will
961 (defconst tramp-echoed-echo-mark-regexp "_echo\\(\b\\( \b\\)?\\)\\{5\\}"
962 "Regexp which matches `tramp-echo-mark' as it gets echoed by
965 (defcustom tramp-rsh-end-of-line "\n"
966 "*String used for end of line in rsh connections.
967 I don't think this ever needs to be changed, so please tell me about it
968 if you need to change this.
969 Also see the method parameter `tramp-password-end-of-line' and the normal
970 variable `tramp-default-password-end-of-line'."
974 (defcustom tramp-default-password-end-of-line
975 tramp-rsh-end-of-line
976 "*String used for end of line after sending a password.
977 This variable provides the default value for the method parameter
978 `tramp-password-end-of-line', see `tramp-methods' for more details.
980 It seems that people using plink under Windows need to send
981 \"\\r\\n\" (carriage-return, then newline) after a password, but just
982 \"\\n\" after all other lines. This variable can be used for the
983 password, see `tramp-rsh-end-of-line' for the other cases.
985 The default value is to use the same value as `tramp-rsh-end-of-line'."
989 ;; "getconf PATH" yields:
990 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
991 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
992 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
993 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
994 (defcustom tramp-remote-path
995 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
996 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
997 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
998 "*List of directories to search for executables on remote host.
999 For every remote host, this variable will be set buffer local,
1000 keeping the list of existing directories on that host.
1002 You can use `~' in this list, but when searching for a shell which groks
1003 tilde expansion, all directory names starting with `~' will be ignored.
1005 `Default Directories' represent the list of directories given by
1006 the command \"getconf PATH\". It is recommended to use this
1007 entry on top of this list, because these are the default
1008 directories for POSIX compatible commands.
1010 `Private Directories' are the settings of the $PATH environment,
1011 as given in your `~/.profile'."
1013 :type '(repeat (choice
1014 (const :tag "Default Directories" tramp-default-remote-path)
1015 (const :tag "Private Directories" tramp-own-remote-path)
1016 (string :tag "Directory"))))
1018 (defcustom tramp-remote-process-environment
1019 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1020 ,(concat "TERM=" tramp-terminal-type)
1021 "EMACS=t" ;; Deprecated.
1022 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
1023 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1024 "autocorrect=" "correct=")
1026 "*List of environment variables to be set on the remote host.
1028 Each element should be a string of the form ENVVARNAME=VALUE. An
1029 entry ENVVARNAME= diables the corresponding environment variable,
1030 which might have been set in the init files like ~/.profile.
1032 Special handling is applied to the PATH environment, which should
1033 not be set here. Instead of, it should be set via `tramp-remote-path'."
1035 :type '(repeat string))
1037 (defcustom tramp-login-prompt-regexp
1038 ".*ogin\\( .*\\)?: *"
1039 "*Regexp matching login-like prompts.
1040 The regexp should match at end of buffer.
1042 Sometimes the prompt is reported to look like \"login as:\"."
1046 (defcustom tramp-shell-prompt-pattern
1047 ;; Allow a prompt to start right after a ^M since it indeed would be
1048 ;; displayed at the beginning of the line (and Zsh uses it).
1049 "\\(?:^\\|\r\\)[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
1050 "Regexp to match prompts from remote shell.
1051 Normally, Tramp expects you to configure `shell-prompt-pattern'
1052 correctly, but sometimes it happens that you are connecting to a
1053 remote host which sends a different kind of shell prompt. Therefore,
1054 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1055 and also things matched by this variable. The default value of this
1056 variable is similar to the default value of `shell-prompt-pattern',
1057 which should work well in many cases.
1059 This regexp must match both `tramp-initial-end-of-output' and
1060 `tramp-end-of-output'."
1064 (defcustom tramp-password-prompt-regexp
1065 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1066 "*Regexp matching password-like prompts.
1067 The regexp should match at end of buffer.
1069 The `sudo' program appears to insert a `^@' character into the prompt."
1073 (defcustom tramp-wrong-passwd-regexp
1075 ;; These strings should be on the last line
1076 (regexp-opt '("Permission denied"
1079 "Connection refused"
1082 "Name or service not known"
1083 "Host key verification failed."
1084 "No supported authentication methods left to try!") t)
1088 ;; Here comes a list of regexes, separated by \\|
1089 "Received signal [0-9]+"
1091 "*Regexp matching a `login failed' message.
1092 The regexp should match at end of buffer."
1096 (defcustom tramp-yesno-prompt-regexp
1098 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1100 "Regular expression matching all yes/no queries which need to be confirmed.
1101 The confirmation should be done with yes or no.
1102 The regexp should match at end of buffer.
1103 See also `tramp-yn-prompt-regexp'."
1107 (defcustom tramp-yn-prompt-regexp
1109 (regexp-opt '("Store key in cache? (y/n)"
1110 "Update cached key? (y/n, Return cancels connection)") t)
1112 "Regular expression matching all y/n queries which need to be confirmed.
1113 The confirmation should be done with y or n.
1114 The regexp should match at end of buffer.
1115 See also `tramp-yesno-prompt-regexp'."
1119 (defcustom tramp-terminal-prompt-regexp
1123 "Terminal type\\? \\[.*\\]"
1125 "Regular expression matching all terminal setting prompts.
1126 The regexp should match at end of buffer.
1127 The answer will be provided by `tramp-action-terminal', which see."
1131 (defcustom tramp-operation-not-permitted-regexp
1132 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1133 (regexp-opt '("Operation not permitted") t))
1134 "Regular expression matching keep-date problems in (s)cp operations.
1135 Copying has been performed successfully already, so this message can
1140 (defcustom tramp-copy-failed-regexp
1142 (regexp-opt '("Permission denied"
1143 "not a regular file"
1145 "No such file or directory") t)
1147 "Regular expression matching copy problems in (s)cp operations."
1151 (defcustom tramp-process-alive-regexp
1153 "Regular expression indicating a process has finished.
1154 In fact this expression is empty by intention, it will be used only to
1155 check regularly the status of the associated process.
1156 The answer will be provided by `tramp-action-process-alive',
1157 `tramp-action-out-of-band', which see."
1161 (defcustom tramp-temp-name-prefix "tramp."
1162 "*Prefix to use for temporary files.
1163 If this is a relative file name (such as \"tramp.\"), it is considered
1164 relative to the directory name returned by the function
1165 `tramp-compat-temporary-file-directory' (which see). It may also be an
1166 absolute file name; don't forget to include a prefix for the filename
1171 (defconst tramp-temp-buffer-name " *tramp temp*"
1172 "Buffer name for a temporary buffer.
1173 It shall be used in combination with `generate-new-buffer-name'.")
1175 (defvar tramp-temp-buffer-file-name nil
1176 "File name of a persistent local temporary file.
1177 Useful for \"rsync\" like methods.")
1178 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1180 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1181 "*Alist specifying extra arguments to pass to the remote shell.
1182 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1183 matching the shell file name and ARGS is a string specifying the
1186 This variable is only used when Tramp needs to start up another shell
1187 for tilde expansion. The extra arguments should typically prevent the
1188 shell from reading its init file."
1190 ;; This might be the wrong way to test whether the widget type
1191 ;; `alist' is available. Who knows the right way to test it?
1192 :type (if (get 'alist 'widget-type)
1193 '(alist :key-type string :value-type string)
1194 '(repeat (cons string string))))
1196 ;; XEmacs is distributed with few Lisp packages. Further packages are
1197 ;; installed using EFS. If we use a unified filename format, then
1198 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1199 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1200 ;; just like before.) Another reason for using a separate filename
1201 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1202 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1203 ;; the other places.
1205 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1207 (defcustom tramp-syntax
1208 (if (featurep 'xemacs) 'sep 'ftp)
1209 "Tramp filename syntax to be used.
1211 It can have the following values:
1213 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1214 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1215 'url -- URL-like syntax."
1217 :type (if (featurep 'xemacs)
1218 '(choice (const :tag "EFS" ftp)
1219 (const :tag "XEmacs" sep)
1220 (const :tag "URL" url))
1221 '(choice (const :tag "Ange-FTP" ftp)
1222 (const :tag "URL" url))))
1224 (defconst tramp-prefix-format
1225 (cond ((equal tramp-syntax 'ftp) "/")
1226 ((equal tramp-syntax 'sep) "/[")
1227 ((equal tramp-syntax 'url) "/")
1228 (t (error "Wrong `tramp-syntax' defined")))
1229 "*String matching the very beginning of Tramp file names.
1230 Used in `tramp-make-tramp-file-name'.")
1232 (defconst tramp-prefix-regexp
1233 (concat "^" (regexp-quote tramp-prefix-format))
1234 "*Regexp matching the very beginning of Tramp file names.
1235 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1237 (defconst tramp-method-regexp
1239 "*Regexp matching methods identifiers.")
1241 (defconst tramp-postfix-method-format
1242 (cond ((equal tramp-syntax 'ftp) ":")
1243 ((equal tramp-syntax 'sep) "/")
1244 ((equal tramp-syntax 'url) "://")
1245 (t (error "Wrong `tramp-syntax' defined")))
1246 "*String matching delimeter between method and user or host names.
1247 Used in `tramp-make-tramp-file-name'.")
1249 (defconst tramp-postfix-method-regexp
1250 (regexp-quote tramp-postfix-method-format)
1251 "*Regexp matching delimeter between method and user or host names.
1252 Derived from `tramp-postfix-method-format'.")
1254 (defconst tramp-user-regexp
1256 "*Regexp matching user names.")
1258 (defconst tramp-prefix-domain-format "%"
1259 "*String matching delimeter between user and domain names.")
1261 (defconst tramp-prefix-domain-regexp
1262 (regexp-quote tramp-prefix-domain-format)
1263 "*Regexp matching delimeter between user and domain names.
1264 Derived from `tramp-prefix-domain-format'.")
1266 (defconst tramp-domain-regexp
1268 "*Regexp matching domain names.")
1270 (defconst tramp-user-with-domain-regexp
1271 (concat "\\(" tramp-user-regexp "\\)"
1272 tramp-prefix-domain-regexp
1273 "\\(" tramp-domain-regexp "\\)")
1274 "*Regexp matching user names with domain names.")
1276 (defconst tramp-postfix-user-format
1278 "*String matching delimeter between user and host names.
1279 Used in `tramp-make-tramp-file-name'.")
1281 (defconst tramp-postfix-user-regexp
1282 (regexp-quote tramp-postfix-user-format)
1283 "*Regexp matching delimeter between user and host names.
1284 Derived from `tramp-postfix-user-format'.")
1286 (defconst tramp-host-regexp
1288 "*Regexp matching host names.")
1290 (defconst tramp-prefix-ipv6-format
1291 (cond ((equal tramp-syntax 'ftp) "[")
1292 ((equal tramp-syntax 'sep) "")
1293 ((equal tramp-syntax 'url) "[")
1294 (t (error "Wrong `tramp-syntax' defined")))
1295 "*String matching left hand side of IPv6 addresses.
1296 Used in `tramp-make-tramp-file-name'.")
1298 (defconst tramp-prefix-ipv6-regexp
1299 (regexp-quote tramp-prefix-ipv6-format)
1300 "*Regexp matching left hand side of IPv6 addresses.
1301 Derived from `tramp-prefix-ipv6-format'.")
1303 ;; The following regexp is a bit sloppy. But it shall serve our
1304 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1305 ;; "::ffff:192.168.0.1".
1306 (defconst tramp-ipv6-regexp
1307 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1308 "*Regexp matching IPv6 addresses.")
1310 (defconst tramp-postfix-ipv6-format
1311 (cond ((equal tramp-syntax 'ftp) "]")
1312 ((equal tramp-syntax 'sep) "")
1313 ((equal tramp-syntax 'url) "]")
1314 (t (error "Wrong `tramp-syntax' defined")))
1315 "*String matching right hand side of IPv6 addresses.
1316 Used in `tramp-make-tramp-file-name'.")
1318 (defconst tramp-postfix-ipv6-regexp
1319 (regexp-quote tramp-postfix-ipv6-format)
1320 "*Regexp matching right hand side of IPv6 addresses.
1321 Derived from `tramp-postfix-ipv6-format'.")
1323 (defconst tramp-prefix-port-format
1324 (cond ((equal tramp-syntax 'ftp) "#")
1325 ((equal tramp-syntax 'sep) "#")
1326 ((equal tramp-syntax 'url) ":")
1327 (t (error "Wrong `tramp-syntax' defined")))
1328 "*String matching delimeter between host names and port numbers.")
1330 (defconst tramp-prefix-port-regexp
1331 (regexp-quote tramp-prefix-port-format)
1332 "*Regexp matching delimeter between host names and port numbers.
1333 Derived from `tramp-prefix-port-format'.")
1335 (defconst tramp-port-regexp
1337 "*Regexp matching port numbers.")
1339 (defconst tramp-host-with-port-regexp
1340 (concat "\\(" tramp-host-regexp "\\)"
1341 tramp-prefix-port-regexp
1342 "\\(" tramp-port-regexp "\\)")
1343 "*Regexp matching host names with port numbers.")
1345 (defconst tramp-postfix-host-format
1346 (cond ((equal tramp-syntax 'ftp) ":")
1347 ((equal tramp-syntax 'sep) "]")
1348 ((equal tramp-syntax 'url) "")
1349 (t (error "Wrong `tramp-syntax' defined")))
1350 "*String matching delimeter between host names and localnames.
1351 Used in `tramp-make-tramp-file-name'.")
1353 (defconst tramp-postfix-host-regexp
1354 (regexp-quote tramp-postfix-host-format)
1355 "*Regexp matching delimeter between host names and localnames.
1356 Derived from `tramp-postfix-host-format'.")
1358 (defconst tramp-localname-regexp
1360 "*Regexp matching localnames.")
1362 ;; File name format.
1364 (defconst tramp-file-name-structure
1368 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1369 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1370 "\\(" "\\(" tramp-host-regexp
1372 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1373 tramp-postfix-ipv6-regexp "\\)"
1374 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1375 tramp-postfix-host-regexp
1376 "\\(" tramp-localname-regexp "\\)")
1379 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1380 the Tramp file name structure.
1382 The first element REGEXP is a regular expression matching a Tramp file
1383 name. The regex should contain parentheses around the method name,
1384 the user name, the host name, and the file name parts.
1386 The second element METHOD is a number, saying which pair of
1387 parentheses matches the method name. The third element USER is
1388 similar, but for the user name. The fourth element HOST is similar,
1389 but for the host name. The fifth element FILE is for the file name.
1390 These numbers are passed directly to `match-string', which see. That
1391 means the opening parentheses are counted to identify the pair.
1393 See also `tramp-file-name-regexp'.")
1396 (defconst tramp-file-name-regexp-unified
1397 "\\`/\\([^[/:]+\\|[^/]+]\\):"
1398 "Value for `tramp-file-name-regexp' for unified remoting.
1399 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1400 Tramp. See `tramp-file-name-structure' for more explanations.")
1403 (defconst tramp-file-name-regexp-separate
1405 "Value for `tramp-file-name-regexp' for separate remoting.
1406 XEmacs uses a separate filename syntax for Tramp and EFS.
1407 See `tramp-file-name-structure' for more explanations.")
1410 (defconst tramp-file-name-regexp-url
1412 "Value for `tramp-file-name-regexp' for URL-like remoting.
1413 See `tramp-file-name-structure' for more explanations.")
1416 (defconst tramp-file-name-regexp
1417 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1418 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1419 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1420 (t (error "Wrong `tramp-syntax' defined")))
1421 "*Regular expression matching file names handled by Tramp.
1422 This regexp should match Tramp file names but no other file names.
1423 \(When tramp.el is loaded, this regular expression is prepended to
1424 `file-name-handler-alist', and that is searched sequentially. Thus,
1425 if the Tramp entry appears rather early in the `file-name-handler-alist'
1426 and is a bit too general, then some files might be considered Tramp
1427 files which are not really Tramp files.
1429 Please note that the entry in `file-name-handler-alist' is made when
1430 this file (tramp.el) is loaded. This means that this variable must be set
1431 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1432 updated after changing this variable.
1434 Also see `tramp-file-name-structure'.")
1437 (defconst tramp-root-regexp
1438 (if (memq system-type '(cygwin windows-nt))
1439 "\\`\\([a-zA-Z]:\\)?/"
1441 "Beginning of an incomplete Tramp file name.
1442 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1443 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1446 (defconst tramp-completion-file-name-regexp-unified
1447 (concat tramp-root-regexp "[^/]*\\'")
1448 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1449 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1450 See `tramp-file-name-structure' for more explanations.")
1453 (defconst tramp-completion-file-name-regexp-separate
1454 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1455 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1456 XEmacs uses a separate filename syntax for Tramp and EFS.
1457 See `tramp-file-name-structure' for more explanations.")
1460 (defconst tramp-completion-file-name-regexp-url
1461 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1462 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1463 See `tramp-file-name-structure' for more explanations.")
1466 (defconst tramp-completion-file-name-regexp
1467 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1468 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1469 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1470 (t (error "Wrong `tramp-syntax' defined")))
1471 "*Regular expression matching file names handled by Tramp completion.
1472 This regexp should match partial Tramp file names only.
1474 Please note that the entry in `file-name-handler-alist' is made when
1475 this file (tramp.el) is loaded. This means that this variable must be set
1476 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1477 updated after changing this variable.
1479 Also see `tramp-file-name-structure'.")
1481 (defconst tramp-actions-before-shell
1482 '((tramp-login-prompt-regexp tramp-action-login)
1483 (tramp-password-prompt-regexp tramp-action-password)
1484 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1485 (shell-prompt-pattern tramp-action-succeed)
1486 (tramp-shell-prompt-pattern tramp-action-succeed)
1487 (tramp-yesno-prompt-regexp tramp-action-yesno)
1488 (tramp-yn-prompt-regexp tramp-action-yn)
1489 (tramp-terminal-prompt-regexp tramp-action-terminal)
1490 (tramp-process-alive-regexp tramp-action-process-alive))
1491 "List of pattern/action pairs.
1492 Whenever a pattern matches, the corresponding action is performed.
1493 Each item looks like (PATTERN ACTION).
1495 The PATTERN should be a symbol, a variable. The value of this
1496 variable gives the regular expression to search for. Note that the
1497 regexp must match at the end of the buffer, \"\\'\" is implicitly
1500 The ACTION should also be a symbol, but a function. When the
1501 corresponding PATTERN matches, the ACTION function is called.")
1503 (defconst tramp-actions-copy-out-of-band
1504 '((tramp-password-prompt-regexp tramp-action-password)
1505 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1506 (tramp-copy-failed-regexp tramp-action-permission-denied)
1507 (tramp-process-alive-regexp tramp-action-out-of-band))
1508 "List of pattern/action pairs.
1509 This list is used for copying/renaming with out-of-band methods.
1511 See `tramp-actions-before-shell' for more info.")
1513 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1514 ;; known to have a bug in `process-send-string'; some ssh connections appear
1515 ;; to drop bytes when data is sent too quickly. There is also a connection
1516 ;; buffer local variable, which is computed depending on remote host properties
1517 ;; when `tramp-chunksize' is zero or nil.
1518 (defcustom tramp-chunksize
1519 (when (and (not (featurep 'xemacs))
1520 (memq system-type '(hpux)))
1522 ;; Parentheses in docstring starting at beginning of line are escaped.
1523 ;; Fontification is messed up when
1524 ;; `open-paren-in-column-0-is-defun-start' set to t.
1525 "*If non-nil, chunksize for sending input to local process.
1526 It is necessary only on systems which have a buggy `process-send-string'
1527 implementation. The necessity, whether this variable must be set, can be
1528 checked via the following code:
1531 (let* ((user \"xxx\") (host \"yyy\")
1533 (sent init) (received init))
1534 (while (= sent received)
1535 (setq sent (+ sent step))
1537 (let ((proc (start-process (buffer-name) (current-buffer)
1538 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1539 (when (memq (process-status proc) '(run open))
1540 (process-send-string proc (make-string sent ?\\ ))
1541 (process-send-eof proc)
1542 (process-send-eof proc))
1543 (while (not (progn (goto-char (point-min))
1544 (re-search-forward \"\\\\w+\" (point-max) t)))
1545 (accept-process-output proc 1))
1546 (when (memq (process-status proc) '(run open))
1547 (setq received (string-to-number (match-string 0)))
1548 (delete-process proc)
1549 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1551 (if (> sent (+ init step))
1552 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1554 (message \"Test does not work\")
1555 (display-buffer (current-buffer))
1558 In the Emacs normally running Tramp, evaluate the above code
1559 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1560 respectively). You can do this, for example, by pasting it into
1561 the `*scratch*' buffer and then hitting C-j with the cursor after the
1562 last closing parenthesis. Note that it works only if you have configured
1563 \"ssh\" to run without password query, see ssh-agent(1).
1565 You will see the number of bytes sent successfully to the remote host.
1566 If that number exceeds 1000, you can stop the execution by hitting
1567 C-g, because your Emacs is likely clean.
1569 When it is necessary to set `tramp-chunksize', you might consider to
1570 use an out-of-the-band method (like \"scp\") instead of an internal one
1571 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
1574 If your Emacs is buggy, the code stops and gives you an indication
1575 about the value `tramp-chunksize' should be set. Maybe you could just
1576 experiment a bit, e.g. changing the values of `init' and `step'
1577 in the third line of the code.
1579 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1580 this variable to be set as well."
1582 :type '(choice (const nil) integer))
1584 ;; Logging in to a remote host normally requires obtaining a pty. But
1585 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1586 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1587 ;; for an override of the system default.
1588 (defcustom tramp-process-connection-type t
1589 "Overrides `process-connection-type' for connections from Tramp.
1590 Tramp binds process-connection-type to the value given here before
1591 opening a connection to a remote host."
1593 :type '(choice (const nil) (const t) (const pty)))
1595 (defcustom tramp-completion-reread-directory-timeout 10
1596 "Defines seconds since last remote command before rereading a directory.
1597 A remote directory might have changed its contents. In order to
1598 make it visible during file name completion in the minibuffer,
1599 Tramp flushes its cache and rereads the directory contents when
1600 more than `tramp-completion-reread-directory-timeout' seconds
1601 have been gone since last remote command execution. A value of 0
1602 would require an immediate reread during filename completion, nil
1603 means to use always cached values for the directory contents."
1605 :type '(choice (const nil) integer))
1607 ;;; Internal Variables:
1609 (defvar tramp-current-method nil
1610 "Connection method for this *tramp* buffer.")
1612 (defvar tramp-current-user nil
1613 "Remote login name for this *tramp* buffer.")
1615 (defvar tramp-current-host nil
1616 "Remote host for this *tramp* buffer.")
1618 (defconst tramp-uudecode
1619 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1621 rm -f /tmp/tramp.$$"
1622 "Shell function to implement `uudecode' to standard output.
1623 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1624 for this or `uudecode -p', but some systems don't, and for them
1625 we have this shell function.")
1627 (defconst tramp-perl-file-truename
1630 use Cwd \"realpath\";
1633 my ($volume, @dirs) = @_;
1634 my $real = realpath(File::Spec->catpath(
1635 $volume, File::Spec->catdir(@dirs), \"\"));
1637 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1638 return ($vol, File::Spec->splitdir($dir));
1641 my $last = pop(@dirs);
1642 ($volume, @dirs) = recursive($volume, @dirs);
1644 return ($volume, @dirs);
1648 $result = realpath($ARGV[0]);
1650 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1651 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1653 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1656 if ($ARGV[0] =~ /\\/$/) {
1657 $result = $result . \"/\";
1660 print \"\\\"$result\\\"\\n\";
1661 ' \"$1\" 2>/dev/null"
1662 "Perl script to produce output suitable for use with `file-truename'
1663 on the remote file system.
1664 Escape sequence %s is replaced with name of Perl binary.
1665 This string is passed to `format', so percent characters need to be doubled.")
1667 (defconst tramp-perl-file-name-all-completions
1677 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1678 @files = readdir(d); closedir(d);
1679 foreach $f (@files) {
1680 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1681 if (-d \"$ARGV[0]/$f\") {
1690 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1691 "Perl script to produce output suitable for use with
1692 `file-name-all-completions' on the remote file system. Escape
1693 sequence %s is replaced with name of Perl binary. This string is
1694 passed to `format', so percent characters need to be doubled.")
1696 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1697 ;; output. If you are hacking on this, note that you get *no* output
1698 ;; unless this spits out a complete line, including the '\n' at the
1700 ;; The device number is returned as "-1", because there will be a virtual
1701 ;; device number set in `tramp-handle-file-attributes'.
1702 (defconst tramp-perl-file-attributes
1704 @stat = lstat($ARGV[0]);
1709 if (($stat[2] & 0170000) == 0120000)
1711 $type = readlink($ARGV[0]);
1712 $type = \"\\\"$type\\\"\";
1714 elsif (($stat[2] & 0170000) == 040000)
1722 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1723 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1725 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1730 $stat[8] >> 16 & 0xffff,
1732 $stat[9] >> 16 & 0xffff,
1734 $stat[10] >> 16 & 0xffff,
1738 $stat[1] >> 16 & 0xffff,
1740 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1741 "Perl script to produce output suitable for use with `file-attributes'
1742 on the remote file system.
1743 Escape sequence %s is replaced with name of Perl binary.
1744 This string is passed to `format', so percent characters need to be doubled.")
1746 (defconst tramp-perl-directory-files-and-attributes
1748 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1749 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1750 @list = readdir(DIR);
1754 for($i = 0; $i < $n; $i++)
1756 $filename = $list[$i];
1757 @stat = lstat($filename);
1758 if (($stat[2] & 0170000) == 0120000)
1760 $type = readlink($filename);
1761 $type = \"\\\"$type\\\"\";
1763 elsif (($stat[2] & 0170000) == 040000)
1771 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1772 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1774 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1780 $stat[8] >> 16 & 0xffff,
1782 $stat[9] >> 16 & 0xffff,
1784 $stat[10] >> 16 & 0xffff,
1788 $stat[1] >> 16 & 0xffff,
1790 $stat[0] >> 16 & 0xffff,
1793 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1794 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1796 Escape sequence %s is replaced with name of Perl binary.
1797 This string is passed to `format', so percent characters need to be doubled.")
1799 ;; ;; These two use uu encoding.
1800 ;; (defvar tramp-perl-encode "%s -e'\
1801 ;; print qq(begin 644 xxx\n);
1804 ;; while (read(STDIN, $s, 45)) {
1805 ;; print pack(q(u), $s);
1810 ;; "Perl program to use for encoding a file.
1811 ;; Escape sequence %s is replaced with name of Perl binary.")
1813 ;; (defvar tramp-perl-decode "%s -ne '
1814 ;; print unpack q(u), $_;
1816 ;; "Perl program to use for decoding a file.
1817 ;; Escape sequence %s is replaced with name of Perl binary.")
1819 ;; These two use base64 encoding.
1820 (defconst tramp-perl-encode-with-module
1821 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1822 "Perl program to use for encoding a file.
1823 Escape sequence %s is replaced with name of Perl binary.
1824 This string is passed to `format', so percent characters need to be doubled.
1825 This implementation requires the MIME::Base64 Perl module to be installed
1826 on the remote host.")
1828 (defconst tramp-perl-decode-with-module
1829 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1830 "Perl program to use for decoding a file.
1831 Escape sequence %s is replaced with name of Perl binary.
1832 This string is passed to `format', so percent characters need to be doubled.
1833 This implementation requires the MIME::Base64 Perl module to be installed
1834 on the remote host.")
1836 (defconst tramp-perl-encode
1838 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1839 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
1840 # Free Software Foundation, Inc.
1845 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1846 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1851 # We read in chunks of 54 bytes, to generate output lines
1852 # of 72 chars (plus end of line)
1855 while (my $data = <STDIN>) {
1858 # Only for the last chunk, and only if did not fill the last three-byte packet
1860 my $mod = length($data) %% 3;
1861 $pad = q(=) x (3 - $mod) if $mod;
1864 # Not the fastest method, but it is simple: unpack to binary string, split
1865 # by groups of 6 bits and convert back from binary to byte; then map into
1866 # the translation table
1870 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1874 "Perl program to use for encoding a file.
1875 Escape sequence %s is replaced with name of Perl binary.
1876 This string is passed to `format', so percent characters need to be doubled.")
1878 (defconst tramp-perl-decode
1880 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1881 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
1882 # Free Software Foundation, Inc.
1887 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1888 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1891 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1895 # We are going to accumulate into $pending to accept any line length
1896 # (we do not check they are <= 76 chars as the RFC says)
1899 while (my $data = <STDIN>) {
1902 # If we find one or two =, we have reached the end and
1903 # any following data is to be discarded
1904 my $finished = $data =~ s/(==?).*/$1/;
1907 my $len = length($pending);
1908 my $chunk = substr($pending, 0, $len & ~3);
1909 $pending = substr($pending, $len & ~3 + 1);
1911 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1912 # split in 8-bit chunks and convert back to char.
1915 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1919 "Perl program to use for decoding a file.
1920 Escape sequence %s is replaced with name of Perl binary.
1921 This string is passed to `format', so percent characters need to be doubled.")
1923 (defconst tramp-vc-registered-read-file-names
1925 for file in \"$@\"; do
1927 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1929 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1932 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1934 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1938 "Script to check existence of VC related files.
1939 It must be send formatted with two strings; the tests for file
1940 existence, and file readability.")
1942 (defconst tramp-file-mode-type-map
1943 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1945 (2 . "c") ; character device
1946 (3 . "m") ; multiplexed character device (v7)
1947 (4 . "d") ; directory
1948 (5 . "?") ; Named special file (XENIX)
1949 (6 . "b") ; block device
1950 (7 . "?") ; multiplexed block device (v7)
1951 (8 . "-") ; regular file
1952 (9 . "n") ; network special file (HP-UX)
1953 (10 . "l") ; symlink
1954 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1956 (13 . "D") ; door special (Solaris)
1957 (14 . "w")) ; whiteout (BSD)
1958 "A list of file types returned from the `stat' system call.
1959 This is used to map a mode number to a permission string.")
1961 ;; New handlers should be added here. The following operations can be
1962 ;; handled using the normal primitives: file-name-sans-versions,
1964 (defconst tramp-file-name-handler-alist
1965 '((load . tramp-handle-load)
1966 (make-symbolic-link . tramp-handle-make-symbolic-link)
1967 (file-name-as-directory . tramp-handle-file-name-as-directory)
1968 (file-name-directory . tramp-handle-file-name-directory)
1969 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1970 (file-truename . tramp-handle-file-truename)
1971 (file-exists-p . tramp-handle-file-exists-p)
1972 (file-directory-p . tramp-handle-file-directory-p)
1973 (file-executable-p . tramp-handle-file-executable-p)
1974 (file-readable-p . tramp-handle-file-readable-p)
1975 (file-regular-p . tramp-handle-file-regular-p)
1976 (file-symlink-p . tramp-handle-file-symlink-p)
1977 (file-writable-p . tramp-handle-file-writable-p)
1978 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1979 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1980 (file-attributes . tramp-handle-file-attributes)
1981 (file-modes . tramp-handle-file-modes)
1982 (directory-files . tramp-handle-directory-files)
1983 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1984 (file-name-all-completions . tramp-handle-file-name-all-completions)
1985 (file-name-completion . tramp-handle-file-name-completion)
1986 (add-name-to-file . tramp-handle-add-name-to-file)
1987 (copy-file . tramp-handle-copy-file)
1988 (copy-directory . tramp-handle-copy-directory)
1989 (rename-file . tramp-handle-rename-file)
1990 (set-file-modes . tramp-handle-set-file-modes)
1991 (set-file-times . tramp-handle-set-file-times)
1992 (make-directory . tramp-handle-make-directory)
1993 (delete-directory . tramp-handle-delete-directory)
1994 (delete-file . tramp-handle-delete-file)
1995 (directory-file-name . tramp-handle-directory-file-name)
1996 ;; `executable-find' is not official yet.
1997 (executable-find . tramp-handle-executable-find)
1998 (start-file-process . tramp-handle-start-file-process)
1999 (process-file . tramp-handle-process-file)
2000 (shell-command . tramp-handle-shell-command)
2001 (insert-directory . tramp-handle-insert-directory)
2002 (expand-file-name . tramp-handle-expand-file-name)
2003 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2004 (file-local-copy . tramp-handle-file-local-copy)
2005 (file-remote-p . tramp-handle-file-remote-p)
2006 (insert-file-contents . tramp-handle-insert-file-contents)
2007 (insert-file-contents-literally
2008 . tramp-handle-insert-file-contents-literally)
2009 (write-region . tramp-handle-write-region)
2010 (find-backup-file-name . tramp-handle-find-backup-file-name)
2011 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2012 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2013 (dired-compress-file . tramp-handle-dired-compress-file)
2014 (dired-recursive-delete-directory
2015 . tramp-handle-dired-recursive-delete-directory)
2016 (dired-uncache . tramp-handle-dired-uncache)
2017 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2018 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2019 (vc-registered . tramp-handle-vc-registered))
2020 "Alist of handler functions.
2021 Operations not mentioned here will be handled by the normal Emacs functions.")
2023 ;; Handlers for partial Tramp file names. For Emacs just
2024 ;; `file-name-all-completions' is needed.
2026 (defconst tramp-completion-file-name-handler-alist
2027 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2028 (file-name-completion . tramp-completion-handle-file-name-completion))
2029 "Alist of completion handler functions.
2030 Used for file names matching `tramp-file-name-regexp'. Operations not
2031 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2032 normal Emacs functions.")
2034 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2035 (defvar tramp-foreign-file-name-handler-alist
2036 ;; (identity . tramp-sh-file-name-handler) should always be the last
2037 ;; entry, because `identity' always matches.
2038 '((identity . tramp-sh-file-name-handler))
2039 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2040 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2043 ;;; Internal functions which must come first:
2045 (defsubst tramp-debug-message (vec fmt-string &rest args)
2046 "Append message to debug buffer.
2047 Message is formatted with FMT-STRING as control string and the remaining
2048 ARGS to actually emit the message (if applicable)."
2049 (when (get-buffer (tramp-buffer-name vec))
2050 (with-current-buffer (tramp-get-debug-buffer vec)
2051 (goto-char (point-max))
2056 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2057 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2058 emacs-version tramp-version)))
2062 (let ((now (current-time)))
2063 (insert (format-time-string "%T." now))
2064 (insert (format "%06d " (nth 2 now))))
2065 ;; Calling function.
2066 (let ((btn 1) btf fn)
2068 (setq btf (nth 1 (backtrace-frame btn)))
2072 (setq fn (symbol-name btf))
2073 (unless (and (string-match "^tramp" fn)
2075 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
2078 (setq btn (1+ btn))))
2079 ;; The following code inserts filename and line number.
2080 ;; Should be deactivated by default, because it is time
2082 ; (let ((ffn (find-function-noselect (intern fn))))
2086 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2087 ; (with-current-buffer (car ffn)
2088 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2089 (insert (format "%s " fn)))
2091 (insert (apply 'format fmt-string args)))))
2093 (defvar tramp-message-show-message t
2094 "Show Tramp message in the minibuffer.
2095 This variable is used to disable messages from `tramp-error'.
2096 The messages are visible anyway, because an error is raised.")
2098 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2099 "Emit a message depending on verbosity level.
2100 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2101 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2102 less than LEVEL. The message is emitted only if `tramp-verbose' is
2103 greater than or equal to LEVEL.
2105 The message is also logged into the debug buffer when `tramp-verbose'
2106 is greater than or equal 4.
2108 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2109 control string and the remaining ARGS to actually emit the message (if
2112 (when (<= level tramp-verbose)
2113 ;; Match data must be preserved!
2115 ;; Display only when there is a minimum level.
2116 (when (and tramp-message-show-message (<= level 3))
2122 ((= level 2) "Warning: ")
2126 ;; Log only when there is a minimum level.
2127 (when (>= tramp-verbose 4)
2128 (when (and vec-or-proc
2129 (processp vec-or-proc)
2130 (buffer-name (process-buffer vec-or-proc)))
2131 (with-current-buffer (process-buffer vec-or-proc)
2132 ;; Translate proc to vec.
2133 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2134 (when (and vec-or-proc (vectorp vec-or-proc))
2135 (apply 'tramp-debug-message
2137 (concat (format "(%d) # " level) fmt-string)
2139 ;; Suppress all errors.
2142 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2144 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2145 signal identifier to be raised, remaining args passed to
2146 `tramp-message'. Finally, signal SIGNAL is raised."
2147 (let (tramp-message-show-message)
2150 (error-message-string
2152 (get signal 'error-message)
2153 (apply 'format fmt-string args))))
2154 (signal signal (list (apply 'format fmt-string args)))))
2156 (defsubst tramp-error-with-buffer
2157 (buffer vec-or-proc signal fmt-string &rest args)
2158 "Emit an error, and show BUFFER.
2159 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2160 an input event arrives. The other arguments are passed to `tramp-error'."
2161 (save-window-excursion
2163 (apply 'tramp-error vec-or-proc signal fmt-string args)
2164 (when (and vec-or-proc (not (zerop tramp-verbose)))
2165 (let ((enable-recursive-minibuffers t))
2167 (or (and (bufferp buffer) buffer)
2168 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2169 (tramp-get-buffer vec-or-proc)))
2172 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2173 "Parse a Tramp filename and make components available in the body.
2175 First arg FILENAME is evaluated and dissected into its components.
2176 Second arg VAR is a symbol. It is used as a variable name to hold
2177 the filename structure. It is also used as a prefix for the variables
2178 holding the components. For example, if VAR is the symbol `foo', then
2179 `foo' will be bound to the whole structure, `foo-method' will be bound to
2180 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2182 Remaining args are Lisp expressions to be evaluated (inside an implicit
2185 If VAR is nil, then we bind `v' to the structure and `method', `user',
2186 `host', `localname' to the components."
2187 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2188 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2189 (tramp-file-name-method ,(or var 'v)))
2190 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2191 (tramp-file-name-user ,(or var 'v)))
2192 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2193 (tramp-file-name-host ,(or var 'v)))
2194 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2195 (tramp-file-name-localname ,(or var 'v))))
2198 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2199 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2200 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2202 (defmacro with-file-property (vec file property &rest body)
2203 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2204 FILE must be a local file name on a connection identified via VEC."
2205 `(if (file-name-absolute-p ,file)
2206 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2207 (when (eq value 'undef)
2208 ;; We cannot pass @body as parameter to
2209 ;; `tramp-set-file-property' because it mangles our
2211 (setq value (progn ,@body))
2212 (tramp-set-file-property ,vec ,file ,property value))
2216 (put 'with-file-property 'lisp-indent-function 3)
2217 (put 'with-file-property 'edebug-form-spec t)
2218 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2220 (defmacro with-connection-property (key property &rest body)
2221 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2222 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2223 (when (eq value 'undef)
2224 ;; We cannot pass ,@body as parameter to
2225 ;; `tramp-set-connection-property' because it mangles our debug
2227 (setq value (progn ,@body))
2228 (tramp-set-connection-property ,key ,property value))
2231 (put 'with-connection-property 'lisp-indent-function 2)
2232 (put 'with-connection-property 'edebug-form-spec t)
2233 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2235 (eval-and-compile ; silence compiler
2236 (if (memq system-type '(cygwin windows-nt))
2237 (defun tramp-drop-volume-letter (name)
2238 "Cut off unnecessary drive letter from file NAME.
2239 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2240 locally on a remote file name. When the local system is a W32 system
2241 but the remote system is Unix, this introduces a superfluous drive
2242 letter into the file name. This function removes it."
2244 (if (string-match tramp-root-regexp name)
2245 (replace-match "/" nil t name)
2248 (defalias 'tramp-drop-volume-letter 'identity)))
2250 (defsubst tramp-make-tramp-temp-file (vec)
2251 "Create a temporary file on the remote host identified by VEC.
2252 Return the local name of the temporary file."
2254 (tramp-make-tramp-file-name
2255 (tramp-file-name-method vec)
2256 (tramp-file-name-user vec)
2257 (tramp-file-name-host vec)
2258 (tramp-drop-volume-letter
2260 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2263 ;; `make-temp-file' would be the natural choice for
2264 ;; implementation. But it calls `write-region' internally,
2265 ;; which also needs a temporary file - we would end in an
2267 (setq result (make-temp-name prefix))
2268 (if (file-exists-p result)
2270 ;; This creates the file by side effect.
2271 (set-file-times result)
2272 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2274 ;; Return the local part.
2275 (with-parsed-tramp-file-name result nil localname)))
2278 ;;; Config Manipulation Functions:
2280 (defun tramp-set-completion-function (method function-list)
2281 "Sets the list of completion functions for METHOD.
2282 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2283 The FUNCTION is intended to parse FILE according its syntax.
2284 It might be a predefined FUNCTION, or a user defined FUNCTION.
2285 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2286 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2287 and `tramp-parse-netrc'.
2291 (tramp-set-completion-function
2293 '((tramp-parse-sconfig \"/etc/ssh_config\")
2294 (tramp-parse-sconfig \"~/.ssh/config\")))"
2296 (let ((r function-list)
2298 (setq tramp-completion-function-alist
2299 (delete (assoc method tramp-completion-function-alist)
2300 tramp-completion-function-alist))
2303 ;; Remove double entries.
2304 (when (member (car v) (cdr v))
2305 (setcdr v (delete (car v) (cdr v))))
2306 ;; Check for function and file or registry key.
2307 (unless (and (functionp (nth 0 (car v)))
2308 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2309 ;; Windows registry.
2310 (and (memq system-type '(cygwin windows-nt))
2312 (tramp-local-call-process
2313 "reg" nil nil nil "query" (nth 1 (car v)))))
2314 ;; Configuration file.
2315 (file-exists-p (nth 1 (car v)))))
2316 (setq r (delete (car v) r)))
2320 (add-to-list 'tramp-completion-function-alist
2323 (defun tramp-get-completion-function (method)
2324 "Returns a list of completion functions for METHOD.
2325 For definition of that list see `tramp-set-completion-function'."
2327 ;; Hosts visited once shall be remembered.
2328 `(tramp-parse-connection-properties ,method)
2329 ;; The method related defaults.
2330 (cdr (assoc method tramp-completion-function-alist))))
2333 ;;; Fontification of `read-file-name':
2335 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2336 (defvar tramp-rfn-eshadow-overlay)
2337 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2339 (defun tramp-rfn-eshadow-setup-minibuffer ()
2340 "Set up a minibuffer for `file-name-shadow-mode'.
2341 Adds another overlay hiding filename parts according to Tramp's
2342 special handling of `substitute-in-file-name'."
2343 (when (symbol-value 'minibuffer-completing-file-name)
2344 (setq tramp-rfn-eshadow-overlay
2345 (funcall (symbol-function 'make-overlay)
2346 (funcall (symbol-function 'minibuffer-prompt-end))
2347 (funcall (symbol-function 'minibuffer-prompt-end))))
2348 ;; Copy rfn-eshadow-overlay properties.
2349 (let ((props (funcall (symbol-function 'overlay-properties)
2350 (symbol-value 'rfn-eshadow-overlay))))
2352 (funcall (symbol-function 'overlay-put)
2353 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2355 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2356 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2357 'tramp-rfn-eshadow-setup-minibuffer)
2358 (add-hook 'tramp-unload-hook
2360 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2361 'tramp-rfn-eshadow-setup-minibuffer))))
2363 (defconst tramp-rfn-eshadow-update-overlay-regexp
2364 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2366 (defun tramp-rfn-eshadow-update-overlay ()
2367 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2368 This is intended to be used as a minibuffer `post-command-hook' for
2369 `file-name-shadow-mode'; the minibuffer should have already
2370 been set up by `rfn-eshadow-setup-minibuffer'."
2371 ;; In remote files name, there is a shadowing just for the local part.
2372 (let ((end (or (funcall (symbol-function 'overlay-end)
2373 (symbol-value 'rfn-eshadow-overlay))
2374 (funcall (symbol-function 'minibuffer-prompt-end)))))
2375 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
2379 (1+ (or (string-match
2380 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2383 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2384 (rfn-eshadow-update-overlay-hook nil))
2385 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
2386 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
2388 (when (boundp 'rfn-eshadow-update-overlay-hook)
2389 (add-hook 'rfn-eshadow-update-overlay-hook
2390 'tramp-rfn-eshadow-update-overlay)
2391 (add-hook 'tramp-unload-hook
2393 (remove-hook 'rfn-eshadow-update-overlay-hook
2394 'tramp-rfn-eshadow-update-overlay))))
2397 ;;; Integration of eshell.el:
2400 (defvar eshell-path-env))
2402 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2403 ;; when `default-directory' points to another host.
2404 (defun tramp-eshell-directory-change ()
2405 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2406 (setq eshell-path-env
2407 (if (file-remote-p default-directory)
2408 (with-parsed-tramp-file-name default-directory nil
2411 (tramp-get-remote-path v)
2415 (eval-after-load "esh-util"
2417 (tramp-eshell-directory-change)
2418 (add-hook 'eshell-directory-change-hook
2419 'tramp-eshell-directory-change)
2420 (add-hook 'tramp-unload-hook
2422 (remove-hook 'eshell-directory-change-hook
2423 'tramp-eshell-directory-change)))))
2426 ;;; File Name Handler Functions:
2428 (defun tramp-handle-make-symbolic-link
2429 (filename linkname &optional ok-if-already-exists)
2430 "Like `make-symbolic-link' for Tramp files.
2431 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2432 the symlink. If LINKNAME is a Tramp file, only the localname component is
2433 used as the target of the symlink.
2435 If LINKNAME is a Tramp file and the localname component is relative, then
2436 it is expanded first, before the localname component is taken. Note that
2437 this can give surprising results if the user/host for the source and
2438 target of the symlink differ."
2439 (with-parsed-tramp-file-name linkname l
2440 (let ((ln (tramp-get-remote-ln l))
2441 (cwd (tramp-run-real-handler
2442 'file-name-directory (list l-localname))))
2446 "Making a symbolic link. ln(1) does not exist on the remote host."))
2448 ;; Do the 'confirm if exists' thing.
2449 (when (file-exists-p linkname)
2451 (if (or (null ok-if-already-exists) ; not allowed to exist
2452 (and (numberp ok-if-already-exists)
2455 "File %s already exists; make it a link anyway? "
2458 l 'file-already-exists "File %s already exists" l-localname)
2459 (delete-file linkname)))
2461 ;; If FILENAME is a Tramp name, use just the localname component.
2462 (when (tramp-tramp-file-p filename)
2464 (tramp-file-name-localname
2465 (tramp-dissect-file-name (expand-file-name filename)))))
2467 ;; Right, they are on the same host, regardless of user, method, etc.
2468 ;; We now make the link on the remote machine. This will occur as the user
2469 ;; that FILENAME belongs to.
2471 (tramp-send-command-and-check
2474 "cd %s && %s -sf %s %s"
2475 (tramp-shell-quote-argument cwd)
2477 (tramp-shell-quote-argument filename)
2478 (tramp-shell-quote-argument l-localname))
2481 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2482 "Like `load' for Tramp files."
2483 (with-parsed-tramp-file-name (expand-file-name file) nil
2485 (cond ((file-exists-p (concat file ".elc"))
2486 (setq file (concat file ".elc")))
2487 ((file-exists-p (concat file ".el"))
2488 (setq file (concat file ".el")))))
2490 ;; The first condition is always true for absolute file names.
2491 ;; Included for safety's sake.
2492 (unless (or (file-name-directory file)
2493 (string-match "\\.elc?\\'" file))
2496 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2498 (when (not (file-exists-p file))
2499 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2500 (if (not (file-exists-p file))
2502 (unless nomessage (tramp-message v 0 "Loading %s..." file))
2503 (let ((local-copy (file-local-copy file)))
2504 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2506 (load local-copy noerror t t)
2507 (delete-file local-copy)))
2508 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
2511 ;; Localname manipulation functions that grok Tramp localnames...
2512 (defun tramp-handle-file-name-as-directory (file)
2513 "Like `file-name-as-directory' but aware of Tramp files."
2514 ;; `file-name-as-directory' would be sufficient except localname is
2515 ;; the empty string.
2516 (let ((v (tramp-dissect-file-name file t)))
2517 ;; Run the command on the localname portion only.
2518 (tramp-make-tramp-file-name
2519 (tramp-file-name-method v)
2520 (tramp-file-name-user v)
2521 (tramp-file-name-host v)
2522 (tramp-run-real-handler
2523 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2525 (defun tramp-handle-file-name-directory (file)
2526 "Like `file-name-directory' but aware of Tramp files."
2527 ;; Everything except the last filename thing is the directory. We
2528 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2529 ;; the remote file name parts. This is a problem when we are in
2530 ;; file name completion.
2531 (let ((v (tramp-dissect-file-name file t)))
2532 ;; Run the command on the localname portion only.
2533 (tramp-make-tramp-file-name
2534 (tramp-file-name-method v)
2535 (tramp-file-name-user v)
2536 (tramp-file-name-host v)
2537 (tramp-run-real-handler
2538 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2540 (defun tramp-handle-file-name-nondirectory (file)
2541 "Like `file-name-nondirectory' but aware of Tramp files."
2542 (with-parsed-tramp-file-name file nil
2543 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2545 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2546 "Like `file-truename' for Tramp files."
2547 (with-parsed-tramp-file-name (expand-file-name filename) nil
2548 (with-file-property v localname "file-truename"
2549 (let ((result nil)) ; result steps in reverse order
2550 (tramp-message v 4 "Finding true name for `%s'" filename)
2552 ;; Use GNU readlink --canonicalize-missing where available.
2553 ((tramp-get-remote-readlink v)
2555 (tramp-send-command-and-read
2557 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2558 (tramp-get-remote-readlink v)
2559 (tramp-shell-quote-argument localname)))))
2561 ;; Use Perl implementation.
2562 ((and (tramp-get-remote-perl v)
2563 (tramp-get-connection-property v "perl-file-spec" nil)
2564 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2565 (tramp-maybe-send-script
2566 v tramp-perl-file-truename "tramp_perl_file_truename")
2568 (tramp-send-command-and-read
2570 (format "tramp_perl_file_truename %s"
2571 (tramp-shell-quote-argument localname)))))
2573 ;; Do it yourself. We bind `directory-sep-char' here for
2574 ;; XEmacs on Windows, which would otherwise use backslash.
2575 (t (let* ((directory-sep-char ?/)
2576 (steps (tramp-compat-split-string localname "/"))
2577 (localnamedir (tramp-run-real-handler
2578 'file-name-as-directory (list localname)))
2579 (is-dir (string= localname localnamedir))
2582 ;; Don't make the following value larger than
2583 ;; necessary. People expect an error message in a
2584 ;; timely fashion when something is wrong;
2585 ;; otherwise they might think that Emacs is hung.
2586 ;; Of course, correctness has to come first.
2589 (while (and steps (< numchase numchase-limit))
2590 (setq thisstep (pop steps))
2593 (mapconcat 'identity
2594 (append '("") (reverse result) (list thisstep))
2596 (setq symlink-target
2597 (nth 0 (file-attributes
2598 (tramp-make-tramp-file-name
2600 (mapconcat 'identity
2605 (cond ((string= "." thisstep)
2606 (tramp-message v 5 "Ignoring step `.'"))
2607 ((string= ".." thisstep)
2608 (tramp-message v 5 "Processing step `..'")
2610 ((stringp symlink-target)
2611 ;; It's a symlink, follow it.
2612 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2613 (setq numchase (1+ numchase))
2614 (when (file-name-absolute-p symlink-target)
2616 ;; If the symlink was absolute, we'll get a string like
2617 ;; "/user@host:/some/target"; extract the
2618 ;; "/some/target" part from it.
2619 (when (tramp-tramp-file-p symlink-target)
2620 (unless (tramp-equal-remote filename symlink-target)
2623 "Symlink target `%s' on wrong host" symlink-target))
2624 (setq symlink-target localname))
2626 (append (tramp-compat-split-string
2631 (setq result (cons thisstep result)))))
2632 (when (>= numchase numchase-limit)
2635 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2636 (setq result (reverse result))
2637 ;; Combine list to form string.
2640 (mapconcat 'identity (cons "" result) "/")
2642 (when (and is-dir (or (string= "" result)
2643 (not (string= (substring result -1) "/"))))
2644 (setq result (concat result "/"))))))
2646 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2647 (tramp-make-tramp-file-name method user host result)))))
2651 (defun tramp-handle-file-exists-p (filename)
2652 "Like `file-exists-p' for Tramp files."
2653 (with-parsed-tramp-file-name filename nil
2654 (with-file-property v localname "file-exists-p"
2655 (or (not (null (tramp-get-file-property
2656 v localname "file-attributes-integer" nil)))
2657 (not (null (tramp-get-file-property
2658 v localname "file-attributes-string" nil)))
2659 (zerop (tramp-send-command-and-check
2663 (tramp-get-file-exists-command v)
2664 (tramp-shell-quote-argument localname))))))))
2666 ;; Inodes don't exist for some file systems. Therefore we must
2667 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2668 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2669 ;; performance isn't the major issue given that file transfer will
2671 (defvar tramp-inodes nil
2672 "Keeps virtual inodes numbers.")
2674 ;; Devices must distinguish physical file systems. The device numbers
2675 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2676 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2677 ;; EFS use device number "-1". In order to be different, we use device number
2678 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2679 (defvar tramp-devices nil
2680 "Keeps virtual device numbers.")
2682 ;; CCC: This should check for an error condition and signal failure
2683 ;; when something goes wrong.
2684 ;; Daniel Pittman <daniel@danann.net>
2685 (defun tramp-handle-file-attributes (filename &optional id-format)
2686 "Like `file-attributes' for Tramp files."
2687 (unless id-format (setq id-format 'integer))
2688 ;; Don't modify `last-coding-system-used' by accident.
2689 (let ((last-coding-system-used last-coding-system-used))
2690 (with-parsed-tramp-file-name (expand-file-name filename) nil
2691 (with-file-property v localname (format "file-attributes-%s" id-format)
2693 (tramp-convert-file-attributes
2696 ((tramp-get-remote-stat v)
2697 (tramp-do-file-attributes-with-stat v localname id-format))
2698 ((tramp-get-remote-perl v)
2699 (tramp-do-file-attributes-with-perl v localname id-format))
2701 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2703 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2704 "Implement `file-attributes' for Tramp files using the ls(1) command."
2706 res-inode res-filemodes res-numlinks
2707 res-uid res-gid res-size res-symlink-target)
2708 (tramp-message vec 5 "file attributes with ls: %s" localname)
2711 (format "(%s %s || %s -h %s) && %s %s %s"
2712 (tramp-get-file-exists-command vec)
2713 (tramp-shell-quote-argument localname)
2714 (tramp-get-test-command vec)
2715 (tramp-shell-quote-argument localname)
2716 (tramp-get-ls-command vec)
2717 (if (eq id-format 'integer) "-ildn" "-ild")
2718 (tramp-shell-quote-argument localname)))
2719 ;; parse `ls -l' output ...
2720 (with-current-buffer (tramp-get-buffer vec)
2721 (when (> (buffer-size) 0)
2722 (goto-char (point-min))
2726 (read (current-buffer))
2727 (invalid-read-syntax
2728 (when (and (equal (cadr err)
2729 "Integer constant overflow in reader")
2731 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2733 (let* ((big (read (substring (car (cddr err)) 0
2734 (match-beginning 1))))
2735 (small (read (match-string 1 (car (cddr err)))))
2736 (twiddle (/ small 65536)))
2737 (cons (+ big twiddle)
2738 (- small (* twiddle 65536))))))))
2739 ;; ... file mode flags
2740 (setq res-filemodes (symbol-name (read (current-buffer))))
2742 (setq res-numlinks (read (current-buffer)))
2744 (setq res-uid (read (current-buffer)))
2745 (setq res-gid (read (current-buffer)))
2746 (if (eq id-format 'integer)
2748 (unless (numberp res-uid) (setq res-uid -1))
2749 (unless (numberp res-gid) (setq res-gid -1)))
2751 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2752 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2754 (setq res-size (read (current-buffer)))
2755 ;; From the file modes, figure out other stuff.
2756 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2757 (setq dirp (eq ?d (aref res-filemodes 0)))
2758 ;; if symlink, find out file name pointed to
2760 (search-forward "-> ")
2761 (setq res-symlink-target
2762 (buffer-substring (point) (tramp-compat-line-end-position))))
2763 ;; return data gathered
2765 ;; 0. t for directory, string (name linked to) for symbolic
2767 (or dirp res-symlink-target)
2768 ;; 1. Number of links to file.
2774 ;; 4. Last access time, as a list of two integers. First
2775 ;; integer has high-order 16 bits of time, second has low 16
2777 ;; 5. Last modification time, likewise.
2778 ;; 6. Last status change time, likewise.
2779 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2780 ;; 7. Size in bytes (-1, if number is out of range).
2782 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2784 ;; 9. t if file's gid would change if file were deleted and
2785 ;; recreated. Will be set in `tramp-convert-file-attributes'
2787 ;; 10. inode number.
2789 ;; 11. Device number. Will be replaced by a virtual device number.
2793 (defun tramp-do-file-attributes-with-perl
2794 (vec localname &optional id-format)
2795 "Implement `file-attributes' for Tramp files using a Perl script."
2796 (tramp-message vec 5 "file attributes with perl: %s" localname)
2797 (tramp-maybe-send-script
2798 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2799 (tramp-send-command-and-read
2801 (format "tramp_perl_file_attributes %s %s"
2802 (tramp-shell-quote-argument localname) id-format)))
2804 (defun tramp-do-file-attributes-with-stat
2805 (vec localname &optional id-format)
2806 "Implement `file-attributes' for Tramp files using stat(1) command."
2807 (tramp-message vec 5 "file attributes with stat: %s" localname)
2808 (tramp-send-command-and-read
2811 "((%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s || echo nil)"
2812 (tramp-get-file-exists-command vec)
2813 (tramp-shell-quote-argument localname)
2814 (tramp-get-test-command vec)
2815 (tramp-shell-quote-argument localname)
2816 (tramp-get-remote-stat vec)
2817 (if (eq id-format 'integer) "%u" "\"%U\"")
2818 (if (eq id-format 'integer) "%g" "\"%G\"")
2819 (tramp-shell-quote-argument localname))))
2821 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2822 "Like `set-visited-file-modtime' for Tramp files."
2823 (unless (buffer-file-name)
2824 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2827 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2828 (let ((f (buffer-file-name))
2830 (with-parsed-tramp-file-name f nil
2831 (let* ((attr (file-attributes f))
2832 ;; '(-1 65535) means file doesn't exists yet.
2833 (modtime (or (nth 5 attr) '(-1 65535))))
2834 (when (boundp 'last-coding-system-used)
2835 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2836 ;; We use '(0 0) as a don't-know value. See also
2837 ;; `tramp-do-file-attributes-with-ls'.
2838 (if (not (equal modtime '(0 0)))
2839 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2843 (format "%s -ild %s"
2844 (tramp-get-ls-command v)
2845 (tramp-shell-quote-argument localname)))
2846 (setq attr (buffer-substring (point)
2847 (progn (end-of-line) (point)))))
2848 (tramp-set-file-property
2849 v localname "visited-file-modtime-ild" attr))
2850 (when (boundp 'last-coding-system-used)
2851 (set 'last-coding-system-used coding-system-used))
2854 ;; This function makes the same assumption as
2855 ;; `tramp-handle-set-visited-file-modtime'.
2856 (defun tramp-handle-verify-visited-file-modtime (buf)
2857 "Like `verify-visited-file-modtime' for Tramp files.
2858 At the time `verify-visited-file-modtime' calls this function, we
2859 already know that the buffer is visiting a file and that
2860 `visited-file-modtime' does not return 0. Do not call this
2861 function directly, unless those two cases are already taken care
2863 (with-current-buffer buf
2864 ;; There is no file visiting the buffer, or the buffer has no
2865 ;; recorded last modification time.
2866 (if (or (not (buffer-file-name))
2867 (eq (visited-file-modtime) 0))
2869 (let ((f (buffer-file-name)))
2870 (with-parsed-tramp-file-name f nil
2871 (tramp-flush-file-property v localname)
2872 (let* ((attr (file-attributes f))
2873 (modtime (nth 5 attr))
2874 (mt (visited-file-modtime)))
2877 ;; File exists, and has a known modtime.
2878 ((and attr (not (equal modtime '(0 0))))
2879 (< (abs (tramp-time-diff
2881 ;; For compatibility, deal with both the old
2882 ;; (HIGH . LOW) and the new (HIGH LOW) return
2883 ;; values of `visited-file-modtime'.
2885 (list (car mt) (cdr mt))
2888 ;; Modtime has the don't know value.
2892 (format "%s -ild %s"
2893 (tramp-get-ls-command v)
2894 (tramp-shell-quote-argument localname)))
2895 (with-current-buffer (tramp-get-buffer v)
2896 (setq attr (buffer-substring
2897 (point) (progn (end-of-line) (point)))))
2900 (tramp-get-file-property
2901 v localname "visited-file-modtime-ild" "")))
2902 ;; If file does not exist, say it is not modified if and
2903 ;; only if that agrees with the buffer's record.
2904 (t (equal mt '(-1 65535))))))))))
2906 (defun tramp-handle-set-file-modes (filename mode)
2907 "Like `set-file-modes' for Tramp files."
2908 (with-parsed-tramp-file-name filename nil
2909 (tramp-flush-file-property v localname)
2910 (unless (zerop (tramp-send-command-and-check
2912 (format "chmod %s %s"
2913 (tramp-decimal-to-octal mode)
2914 (tramp-shell-quote-argument localname))))
2915 ;; FIXME: extract the proper text from chmod's stderr.
2917 v 'file-error "Error while changing file's mode %s" filename))))
2919 (defun tramp-handle-set-file-times (filename &optional time)
2920 "Like `set-file-times' for Tramp files."
2922 (if (file-remote-p filename)
2923 (with-parsed-tramp-file-name filename nil
2924 (tramp-flush-file-property v localname)
2925 (let ((time (if (or (null time) (equal time '(0 0)))
2929 ;; With GNU Emacs, `format-time-string' has an
2930 ;; optional parameter UNIVERSAL. This is preferred,
2931 ;; because we could handle the case when the remote
2932 ;; host is located in a different time zone as the
2934 (and (functionp 'subr-arity)
2935 (subrp (symbol-function 'format-time-string))
2936 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2938 'format-time-string)))))))
2939 (tramp-send-command-and-check
2940 v (format "%s touch -t %s %s"
2941 (if utc "TZ=UTC; export TZ;" "")
2943 (format-time-string "%Y%m%d%H%M.%S" time t)
2944 (format-time-string "%Y%m%d%H%M.%S" time))
2945 (tramp-shell-quote-argument localname)))))
2947 ;; We handle also the local part, because in older Emacsen,
2948 ;; without `set-file-times', this function is an alias for this.
2949 ;; We are local, so we don't need the UTC settings.
2950 (tramp-local-call-process
2951 "touch" nil nil nil "-t"
2952 (format-time-string "%Y%m%d%H%M.%S" time)
2953 (tramp-shell-quote-argument filename)))))
2955 (defun tramp-set-file-uid-gid (filename &optional uid gid)
2956 "Set the ownership for FILENAME.
2957 If UID and GID are provided, these values are used; otherwise uid
2958 and gid of the corresponding user is taken. Both parameters must be integers."
2959 ;; Modern Unices allow chown only for root. So we might need
2960 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2961 ;; working with su(do)? when it is needed, so it shall succeed in
2962 ;; the majority of cases.
2963 ;; Don't modify `last-coding-system-used' by accident.
2964 (let ((last-coding-system-used last-coding-system-used))
2965 (if (file-remote-p filename)
2966 (with-parsed-tramp-file-name filename nil
2967 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2968 ;; If we are root on the local host, we can do it directly.
2969 (tramp-set-file-uid-gid localname uid gid)
2970 (let ((uid (or (and (integerp uid) uid)
2971 (tramp-get-remote-uid v 'integer)))
2972 (gid (or (and (integerp gid) gid)
2973 (tramp-get-remote-gid v 'integer))))
2976 "chown %d:%d %s" uid gid
2977 (tramp-shell-quote-argument localname))))))
2979 ;; We handle also the local part, because there doesn't exist
2980 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2981 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2982 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2983 (tramp-local-call-process
2985 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
2987 ;; Simple functions using the `test' command.
2989 (defun tramp-handle-file-executable-p (filename)
2990 "Like `file-executable-p' for Tramp files."
2991 (with-parsed-tramp-file-name filename nil
2992 (with-file-property v localname "file-executable-p"
2993 ;; Examine `file-attributes' cache to see if request can be
2994 ;; satisfied without remote operation.
2995 (or (tramp-check-cached-permissions v ?x)
2996 (zerop (tramp-run-test "-x" filename))))))
2998 (defun tramp-handle-file-readable-p (filename)
2999 "Like `file-readable-p' for Tramp files."
3000 (with-parsed-tramp-file-name filename nil
3001 (with-file-property v localname "file-readable-p"
3002 ;; Examine `file-attributes' cache to see if request can be
3003 ;; satisfied without remote operation.
3004 (or (tramp-check-cached-permissions v ?r)
3005 (zerop (tramp-run-test "-r" filename))))))
3007 ;; When the remote shell is started, it looks for a shell which groks
3008 ;; tilde expansion. Here, we assume that all shells which grok tilde
3009 ;; expansion will also provide a `test' command which groks `-nt' (for
3010 ;; newer than). If this breaks, tell me about it and I'll try to do
3011 ;; something smarter about it.
3012 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3013 "Like `file-newer-than-file-p' for Tramp files."
3014 (cond ((not (file-exists-p file1))
3016 ((not (file-exists-p file2))
3018 ;; We are sure both files exist at this point.
3021 ;; We try to get the mtime of both files. If they are not
3022 ;; equal to the "dont-know" value, then we subtract the times
3023 ;; and obtain the result.
3024 (let ((fa1 (file-attributes file1))
3025 (fa2 (file-attributes file2)))
3026 (if (and (not (equal (nth 5 fa1) '(0 0)))
3027 (not (equal (nth 5 fa2) '(0 0))))
3028 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3029 ;; If one of them is the dont-know value, then we can
3030 ;; still try to run a shell command on the remote host.
3031 ;; However, this only works if both files are Tramp
3032 ;; files and both have the same method, same user, same
3034 (unless (tramp-equal-remote file1 file2)
3035 (with-parsed-tramp-file-name
3036 (if (tramp-tramp-file-p file1) file1 file2) nil
3039 "Files %s and %s must have same method, user, host"
3041 (with-parsed-tramp-file-name file1 nil
3042 (zerop (tramp-run-test2
3043 (tramp-get-test-nt-command v) file1 file2)))))))))
3045 ;; Functions implemented using the basic functions above.
3047 (defun tramp-handle-file-modes (filename)
3048 "Like `file-modes' for Tramp files."
3049 (let ((truename (or (file-truename filename) filename)))
3050 (when (file-exists-p truename)
3051 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3053 (defun tramp-default-file-modes (filename)
3054 "Return file modes of FILENAME as integer.
3055 If the file modes of FILENAME cannot be determined, return the
3056 value of `default-file-modes', without execute permissions."
3057 (or (file-modes filename)
3058 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3060 (defun tramp-handle-file-directory-p (filename)
3061 "Like `file-directory-p' for Tramp files."
3062 ;; Care must be taken that this function returns `t' for symlinks
3063 ;; pointing to directories. Surely the most obvious implementation
3064 ;; would be `test -d', but that returns false for such symlinks.
3065 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3066 ;; I now think he's right. So we could be using `test -d', couldn't
3069 ;; Alternatives: `cd %s', `test -d %s'
3070 (with-parsed-tramp-file-name filename nil
3071 (with-file-property v localname "file-directory-p"
3072 (zerop (tramp-run-test "-d" filename)))))
3074 (defun tramp-handle-file-regular-p (filename)
3075 "Like `file-regular-p' for Tramp files."
3076 (and (file-exists-p filename)
3077 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3079 (defun tramp-handle-file-symlink-p (filename)
3080 "Like `file-symlink-p' for Tramp files."
3081 (with-parsed-tramp-file-name filename nil
3082 (let ((x (car (file-attributes filename))))
3084 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3085 ;; might do weird things.
3086 (if (file-name-absolute-p x)
3087 (tramp-make-tramp-file-name method user host x)
3090 (defun tramp-handle-file-writable-p (filename)
3091 "Like `file-writable-p' for Tramp files."
3092 (with-parsed-tramp-file-name filename nil
3093 (with-file-property v localname "file-writable-p"
3094 (if (file-exists-p filename)
3095 ;; Examine `file-attributes' cache to see if request can be
3096 ;; satisfied without remote operation.
3097 (or (tramp-check-cached-permissions v ?w)
3098 (zerop (tramp-run-test "-w" filename)))
3099 ;; If file doesn't exist, check if directory is writable.
3100 (and (zerop (tramp-run-test
3101 "-d" (file-name-directory filename)))
3102 (zerop (tramp-run-test
3103 "-w" (file-name-directory filename))))))))
3105 (defun tramp-handle-file-ownership-preserved-p (filename)
3106 "Like `file-ownership-preserved-p' for Tramp files."
3107 (with-parsed-tramp-file-name filename nil
3108 (with-file-property v localname "file-ownership-preserved-p"
3109 (let ((attributes (file-attributes filename)))
3110 ;; Return t if the file doesn't exist, since it's true that no
3111 ;; information would be lost by an (attempted) delete and create.
3112 (or (null attributes)
3113 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3115 ;; Other file name ops.
3117 (defun tramp-handle-directory-file-name (directory)
3118 "Like `directory-file-name' for Tramp files."
3119 ;; If localname component of filename is "/", leave it unchanged.
3120 ;; Otherwise, remove any trailing slash from localname component.
3121 ;; Method, host, etc, are unchanged. Does it make sense to try
3122 ;; to avoid parsing the filename?
3123 (with-parsed-tramp-file-name directory nil
3124 (if (and (not (zerop (length localname)))
3125 (eq (aref localname (1- (length localname))) ?/)
3126 (not (string= localname "/")))
3127 (substring directory 0 -1)
3130 ;; Directory listings.
3132 (defun tramp-handle-directory-files
3133 (directory &optional full match nosort files-only)
3134 "Like `directory-files' for Tramp files."
3135 ;; FILES-ONLY is valid for XEmacs only.
3136 (when (file-directory-p directory)
3137 (setq directory (expand-file-name directory))
3138 (let ((temp (nreverse (file-name-all-completions "" directory)))
3142 (setq item (directory-file-name (pop temp)))
3143 (when (and (or (null match) (string-match match item))
3144 (or (null files-only)
3146 (and (equal files-only t) (file-regular-p item))
3148 (file-directory-p item)))
3149 (push (if full (expand-file-name item directory) item)
3153 (defun tramp-handle-directory-files-and-attributes
3154 (directory &optional full match nosort id-format)
3155 "Like `directory-files-and-attributes' for Tramp files."
3156 (unless id-format (setq id-format 'integer))
3157 (when (file-directory-p directory)
3158 (setq directory (expand-file-name directory))
3160 (tramp-compat-copy-tree
3161 (with-parsed-tramp-file-name directory nil
3164 (format "directory-files-and-attributes-%s" id-format)
3169 (tramp-convert-file-attributes v (cdr x))))
3171 ((tramp-get-remote-stat v)
3172 (tramp-do-directory-files-and-attributes-with-stat
3173 v localname id-format))
3174 ((tramp-get-remote-perl v)
3175 (tramp-do-directory-files-and-attributes-with-perl
3176 v localname id-format)))))))))
3180 (setq item (pop temp))
3181 (when (or (null match) (string-match match (car item)))
3183 (setcar item (expand-file-name (car item) directory)))
3184 (push item result)))
3188 (sort result (lambda (x y) (string< (car x) (car y))))))))
3190 (defun tramp-do-directory-files-and-attributes-with-perl
3191 (vec localname &optional id-format)
3192 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3193 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3194 (tramp-maybe-send-script
3195 vec tramp-perl-directory-files-and-attributes
3196 "tramp_perl_directory_files_and_attributes")
3198 (tramp-send-command-and-read
3200 (format "tramp_perl_directory_files_and_attributes %s %s"
3201 (tramp-shell-quote-argument localname) id-format))))
3202 (when (stringp object) (tramp-error vec 'file-error object))
3205 (defun tramp-do-directory-files-and-attributes-with-stat
3206 (vec localname &optional id-format)
3207 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3208 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3209 (tramp-send-command-and-read
3213 ;; We must care about filenames with spaces, or starting with
3214 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3215 ;; but it does not work on all remote systems. Therefore, we
3216 ;; quote the filenames via sed.
3217 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3218 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3220 (tramp-shell-quote-argument localname)
3221 (tramp-get-ls-command vec)
3222 (tramp-get-remote-stat vec)
3223 (if (eq id-format 'integer) "%u" "\"%U\"")
3224 (if (eq id-format 'integer) "%g" "\"%G\""))))
3226 ;; This function should return "foo/" for directories and "bar" for
3228 (defun tramp-handle-file-name-all-completions (filename directory)
3229 "Like `file-name-all-completions' for Tramp files."
3230 (unless (save-match-data (string-match "/" filename))
3231 (with-parsed-tramp-file-name (expand-file-name directory) nil
3240 ;; Ignore if expired
3241 (or (not (integerp tramp-completion-reread-directory-timeout))
3242 (<= (tramp-time-diff
3244 (tramp-get-file-property
3245 v localname "last-completion" '(0 0 0)))
3246 tramp-completion-reread-directory-timeout))
3248 ;; Try cache entries for filename, filename with last
3249 ;; character removed, filename with last two characters
3250 ;; removed, ..., and finally the empty string - all
3251 ;; concatenated to the local directory name
3253 ;; This is inefficient for very long filenames, pity
3254 ;; `reduce' is not available...
3261 (tramp-get-file-property
3263 (concat localname (substring filename 0 x))
3264 "file-name-all-completions"
3266 (when cache-hit (list cache-hit))))
3267 (tramp-compat-number-sequence (length filename) 0 -1)))))
3269 ;; Cache expired or no matching cache entry found so we need
3270 ;; to perform a remote operation
3272 ;; Get a list of directories and files, including reliably
3273 ;; tagging the directories with a trailing '/'. Because I
3274 ;; rock. --daniel@danann.net
3276 ;; Changed to perform `cd' in the same remote op and only
3277 ;; get entries starting with `filename'. Capture any `cd'
3278 ;; error messages. Ensure any `cd' and `echo' aliases are
3282 (if (tramp-get-remote-perl v)
3284 (tramp-maybe-send-script
3285 v tramp-perl-file-name-all-completions
3286 "tramp_perl_file_name_all_completions")
3287 (format "tramp_perl_file_name_all_completions %s %s %d"
3288 (tramp-shell-quote-argument localname)
3289 (tramp-shell-quote-argument filename)
3291 'read-file-name-completion-ignore-case)
3295 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3296 ;; `ls' with wildcard might fail with `Argument
3297 ;; list too long' error in some corner cases; if
3298 ;; `ls' fails after `cd' succeeded, chances are
3299 ;; that's the case, so let's retry without
3300 ;; wildcard. This will return "too many" entries
3301 ;; but that isn't harmful.
3302 " || %s -a 2>/dev/null)"
3303 " | while read f; do"
3304 " if %s -d \"$f\" 2>/dev/null;"
3305 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3306 " && \\echo ok) || \\echo fail")
3307 (tramp-shell-quote-argument localname)
3308 (tramp-get-ls-command v)
3309 ;; When `filename' is empty, just `ls' without
3310 ;; filename argument is more efficient than `ls *'
3311 ;; for very large directories and might avoid the
3312 ;; `Argument list too long' error.
3314 ;; With and only with wildcard, we need to add
3315 ;; `-d' to prevent `ls' from descending into
3317 (if (zerop (length filename))
3319 (concat (tramp-shell-quote-argument filename) "* -d"))
3320 (tramp-get-ls-command v)
3321 (tramp-get-test-command v))))
3323 ;; Now grab the output.
3324 (with-current-buffer (tramp-get-buffer v)
3325 (goto-char (point-max))
3327 ;; Check result code, found in last line of output
3329 (if (looking-at "^fail$")
3331 ;; Grab error message from line before last line
3332 ;; (it was put there by `cd 2>&1')
3336 "tramp-handle-file-name-all-completions: %s"
3338 (point) (tramp-compat-line-end-position))))
3339 ;; For peace of mind, if buffer doesn't end in `fail'
3340 ;; then it should end in `ok'. If neither are in the
3341 ;; buffer something went seriously wrong on the remote
3343 (unless (looking-at "^ok$")
3347 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3348 (tramp-shell-quote-argument localname) (buffer-string))))
3350 (while (zerop (forward-line -1))
3351 (push (buffer-substring
3352 (point) (tramp-compat-line-end-position))
3355 ;; Because the remote op went through OK we know the
3356 ;; directory we `cd'-ed to exists
3357 (tramp-set-file-property
3358 v localname "file-exists-p" t)
3360 ;; Because the remote op went through OK we know every
3361 ;; file listed by `ls' exists.
3362 (mapc (lambda (entry)
3363 (tramp-set-file-property
3364 v (concat localname entry) "file-exists-p" t))
3367 (tramp-set-file-property
3368 v localname "last-completion" (current-time))
3370 ;; Store result in the cache
3371 (tramp-set-file-property
3372 v (concat localname filename)
3373 "file-name-all-completions"
3376 ;; The following isn't needed for Emacs 20 but for 19.34?
3377 (defun tramp-handle-file-name-completion
3378 (filename directory &optional predicate)
3379 "Like `file-name-completion' for Tramp files."
3380 (unless (tramp-tramp-file-p directory)
3382 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3386 (mapcar 'list (file-name-all-completions filename directory))
3388 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3392 (defun tramp-handle-add-name-to-file
3393 (filename newname &optional ok-if-already-exists)
3394 "Like `add-name-to-file' for Tramp files."
3395 (unless (tramp-equal-remote filename newname)
3396 (with-parsed-tramp-file-name
3397 (if (tramp-tramp-file-p filename) filename newname) nil
3400 "add-name-to-file: %s"
3401 "only implemented for same method, same user, same host")))
3402 (with-parsed-tramp-file-name filename v1
3403 (with-parsed-tramp-file-name newname v2
3404 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3405 (when (and (not ok-if-already-exists)
3406 (file-exists-p newname)
3407 (not (numberp ok-if-already-exists))
3410 "File %s already exists; make it a new name anyway? "
3414 "add-name-to-file: file %s already exists" newname))
3415 (tramp-flush-file-property v2 v2-localname)
3416 (tramp-barf-unless-okay
3418 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3419 (tramp-shell-quote-argument v2-localname))
3420 "error with add-name-to-file, see buffer `%s' for details"
3423 (defun tramp-handle-copy-file
3424 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3425 "Like `copy-file' for Tramp files."
3426 ;; Check if both files are local -- invoke normal copy-file.
3427 ;; Otherwise, use Tramp from local system.
3428 (setq filename (expand-file-name filename))
3429 (setq newname (expand-file-name newname))
3431 ;; At least one file a Tramp file?
3432 ((or (tramp-tramp-file-p filename)
3433 (tramp-tramp-file-p newname))
3434 (tramp-do-copy-or-rename-file
3435 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3438 (tramp-run-real-handler
3440 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3442 (tramp-run-real-handler
3443 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3445 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3446 "Like `copy-directory' for Tramp files."
3447 (let ((t1 (tramp-tramp-file-p dirname))
3448 (t2 (tramp-tramp-file-p newname)))
3449 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3450 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3451 ;; When DIRNAME and NEWNAME are remote, they must have
3453 (or (null t1) (null t2)
3455 (tramp-file-name-method (tramp-dissect-file-name dirname))
3456 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3457 ;; scp or rsync DTRT.
3459 (setq dirname (directory-file-name (expand-file-name dirname))
3460 newname (directory-file-name (expand-file-name newname)))
3461 (if (and (file-directory-p newname)
3462 (not (string-equal (file-name-nondirectory dirname)
3463 (file-name-nondirectory newname))))
3466 (file-name-nondirectory dirname) newname)))
3467 (if (not (file-directory-p (file-name-directory newname)))
3468 (make-directory (file-name-directory newname) parents))
3469 (tramp-do-copy-or-rename-file-out-of-band
3470 'copy dirname newname keep-date))
3471 ;; We must do it file-wise.
3472 (tramp-run-real-handler
3473 'copy-directory (list dirname newname keep-date parents))))))
3475 (defun tramp-handle-rename-file
3476 (filename newname &optional ok-if-already-exists)
3477 "Like `rename-file' for Tramp files."
3478 ;; Check if both files are local -- invoke normal rename-file.
3479 ;; Otherwise, use Tramp from local system.
3480 (setq filename (expand-file-name filename))
3481 (setq newname (expand-file-name newname))
3482 ;; At least one file a Tramp file?
3483 (if (or (tramp-tramp-file-p filename)
3484 (tramp-tramp-file-p newname))
3485 (tramp-do-copy-or-rename-file
3486 'rename filename newname ok-if-already-exists t t)
3487 (tramp-run-real-handler
3488 'rename-file (list filename newname ok-if-already-exists))))
3490 (defun tramp-do-copy-or-rename-file
3491 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3492 "Copy or rename a remote file.
3493 OP must be `copy' or `rename' and indicates the operation to perform.
3494 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3495 the new file (for copy) or the new name of the file (for rename).
3496 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3497 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3498 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3499 the uid and gid if both files are on the same host.
3501 This function is invoked by `tramp-handle-copy-file' and
3502 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3503 and `rename'. FILENAME and NEWNAME must be absolute file names."
3504 (unless (memq op '(copy rename))
3505 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3506 (let ((t1 (tramp-tramp-file-p filename))
3507 (t2 (tramp-tramp-file-p newname)))
3509 (when (and (not ok-if-already-exists) (file-exists-p newname))
3510 (with-parsed-tramp-file-name (if t1 filename newname) nil
3512 v 'file-already-exists "File %s already exists" newname)))
3514 (with-parsed-tramp-file-name (if t1 filename newname) nil
3515 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3519 ;; Both are Tramp files.
3521 (with-parsed-tramp-file-name filename v1
3522 (with-parsed-tramp-file-name newname v2
3524 ;; Shortcut: if method, host, user are the same for both
3525 ;; files, we invoke `cp' or `mv' on the remote host
3527 ((tramp-equal-remote filename newname)
3528 (tramp-do-copy-or-rename-file-directly
3530 ok-if-already-exists keep-date preserve-uid-gid))
3532 ;; Try out-of-band operation.
3533 ((tramp-method-out-of-band-p
3534 v1 (nth 7 (file-attributes filename)))
3535 (tramp-do-copy-or-rename-file-out-of-band
3536 op filename newname keep-date))
3538 ;; No shortcut was possible. So we copy the
3539 ;; file first. If the operation was `rename', we go
3540 ;; back and delete the original file (if the copy was
3541 ;; successful). The approach is simple-minded: we
3542 ;; create a new buffer, insert the contents of the
3543 ;; source file into it, then write out the buffer to
3544 ;; the target file. The advantage is that it doesn't
3545 ;; matter which filename handlers are used for the
3546 ;; source and target file.
3548 (tramp-do-copy-or-rename-file-via-buffer
3549 op filename newname keep-date))))))
3551 ;; One file is a Tramp file, the other one is local.
3553 (with-parsed-tramp-file-name (if t1 filename newname) nil
3555 ;; Fast track on local machine.
3556 ((tramp-local-host-p v)
3557 (tramp-do-copy-or-rename-file-directly
3559 ok-if-already-exists keep-date preserve-uid-gid))
3561 ;; If the Tramp file has an out-of-band method, the corresponding
3562 ;; copy-program can be invoked.
3563 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3564 (tramp-do-copy-or-rename-file-out-of-band
3565 op filename newname keep-date))
3567 ;; Use the inline method via a Tramp buffer.
3568 (t (tramp-do-copy-or-rename-file-via-buffer
3569 op filename newname keep-date)))))
3572 ;; One of them must be a Tramp file.
3573 (error "Tramp implementation says this cannot happen")))
3575 ;; In case of `rename', we must flush the cache of the source file.
3576 (when (and t1 (eq op 'rename))
3577 (with-parsed-tramp-file-name filename nil
3578 (tramp-flush-file-property v localname)))
3580 ;; When newname did exist, we have wrong cached values.
3582 (with-parsed-tramp-file-name newname nil
3583 (tramp-flush-file-property v localname)))
3585 (with-parsed-tramp-file-name (if t1 filename newname) nil
3586 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
3588 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3589 "Use an Emacs buffer to copy or rename a file.
3590 First arg OP is either `copy' or `rename' and indicates the operation.
3591 FILENAME is the source file, NEWNAME the target file.
3592 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3594 ;; We must disable multibyte, because binary data shall not be
3596 (set-buffer-multibyte nil)
3597 (let ((coding-system-for-read 'binary)
3598 (jka-compr-inhibit t))
3599 (insert-file-contents-literally filename))
3600 ;; We don't want the target file to be compressed, so we let-bind
3601 ;; `jka-compr-inhibit' to t.
3602 (let ((coding-system-for-write 'binary)
3603 (jka-compr-inhibit t))
3604 (write-region (point-min) (point-max) newname)))
3605 ;; KEEP-DATE handling.
3606 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3608 (set-file-modes newname (tramp-default-file-modes filename))
3609 ;; If the operation was `rename', delete the original file.
3610 (unless (eq op 'copy) (delete-file filename)))
3612 (defun tramp-do-copy-or-rename-file-directly
3613 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3614 "Invokes `cp' or `mv' on the remote system.
3615 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3616 respectively. FILENAME specifies the file to copy or rename,
3617 NEWNAME is the name of the new file (for copy) or the new name of
3618 the file (for rename). Both files must reside on the same host.
3619 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3620 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3621 the uid and gid from FILENAME."
3622 (let ((t1 (tramp-tramp-file-p filename))
3623 (t2 (tramp-tramp-file-p newname))
3624 (file-times (nth 5 (file-attributes filename)))
3625 (file-modes (tramp-default-file-modes filename)))
3626 (with-parsed-tramp-file-name (if t1 filename newname) nil
3627 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3628 ((eq op 'copy) "cp -f")
3629 ((eq op 'rename) "mv -f")
3632 "Unknown operation `%s', must be `copy' or `rename'"
3635 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3637 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
3638 (prefix (file-remote-p (if t1 filename newname)))
3642 ;; Both files are on a remote host, with same user.
3645 (tramp-send-command-and-check
3647 (format "%s %s %s" cmd
3648 (tramp-shell-quote-argument localname1)
3649 (tramp-shell-quote-argument localname2))))
3650 (with-current-buffer (tramp-get-buffer v)
3651 (goto-char (point-min))
3655 ;; Mask cp -f error.
3657 tramp-operation-not-permitted-regexp nil t))
3659 (tramp-error-with-buffer
3661 "Copying directly failed, see buffer `%s' for details."
3664 ;; We are on the local host.
3667 ;; We can do it directly.
3668 ((let (file-name-handler-alist)
3669 (and (file-readable-p localname1)
3670 (file-writable-p (file-name-directory localname2))
3671 (or (file-directory-p localname2)
3672 (file-writable-p localname2))))
3674 (tramp-compat-copy-file
3675 localname1 localname2 ok-if-already-exists
3676 keep-date preserve-uid-gid)
3677 (tramp-run-real-handler
3678 'rename-file (list localname1 localname2 ok-if-already-exists))))
3680 ;; We can do it directly with `tramp-send-command'
3681 ((and (file-readable-p (concat prefix localname1))
3683 (file-name-directory (concat prefix localname2)))
3684 (or (file-directory-p (concat prefix localname2))
3685 (file-writable-p (concat prefix localname2))))
3686 (tramp-do-copy-or-rename-file-directly
3687 op (concat prefix localname1) (concat prefix localname2)
3688 ok-if-already-exists keep-date t)
3689 ;; We must change the ownership to the local user.
3690 (tramp-set-file-uid-gid
3691 (concat prefix localname2)
3692 (tramp-get-local-uid 'integer)
3693 (tramp-get-local-gid 'integer)))
3695 ;; We need a temporary file in between.
3697 ;; Create the temporary file.
3698 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3705 (tramp-send-command-and-check
3708 (tramp-shell-quote-argument localname1)
3709 (tramp-shell-quote-argument tmpfile))))
3710 (tramp-error-with-buffer
3712 "Copying directly failed, see buffer `%s' for details."
3713 (tramp-get-buffer v)))
3714 ;; We must change the ownership as remote user.
3715 ;; Since this does not work reliable, we also
3716 ;; give read permissions.
3718 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3719 (tramp-set-file-uid-gid
3720 (concat prefix tmpfile)
3721 (tramp-get-local-uid 'integer)
3722 (tramp-get-local-gid 'integer)))
3725 (tramp-compat-copy-file
3726 localname1 tmpfile t
3727 keep-date preserve-uid-gid)
3728 (tramp-run-real-handler
3730 (list localname1 tmpfile t)))
3731 ;; We must change the ownership as local user.
3732 ;; Since this does not work reliable, we also
3733 ;; give read permissions.
3734 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3735 (tramp-set-file-uid-gid
3737 (tramp-get-remote-uid v 'integer)
3738 (tramp-get-remote-gid v 'integer))))
3740 ;; Move the temporary file to its destination.
3745 (tramp-send-command-and-check
3748 (tramp-shell-quote-argument tmpfile)
3749 (tramp-shell-quote-argument localname2))))
3750 (tramp-error-with-buffer
3752 "Copying directly failed, see buffer `%s' for details."
3753 (tramp-get-buffer v))))
3755 (tramp-run-real-handler
3757 (list tmpfile localname2 ok-if-already-exists)))))
3761 (delete-file tmpfile)
3764 ;; Set the time and mode. Mask possible errors.
3767 (set-file-times newname file-times)
3768 (set-file-modes newname file-modes))
3771 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3772 "Invoke rcp program to copy.
3773 The method used must be an out-of-band method."
3774 (let ((t1 (tramp-tramp-file-p filename))
3775 (t2 (tramp-tramp-file-p newname))
3776 copy-program copy-args copy-env copy-keep-date port spec
3779 (with-parsed-tramp-file-name (if t1 filename newname) nil
3782 ;; Both are Tramp files. We shall optimize it, when the
3783 ;; methods for filename and newname are the same.
3784 (let ((tmpfile (tramp-compat-make-temp-file localname)))
3787 (tramp-do-copy-or-rename-file-out-of-band
3788 op filename tmpfile keep-date)
3789 (tramp-do-copy-or-rename-file-out-of-band
3790 'rename tmpfile newname keep-date))
3793 (delete-file tmpfile)
3796 ;; Expand hops. Might be necessary for gateway methods.
3797 (setq v (car (tramp-compute-multi-hops v)))
3798 (aset v 3 localname)
3800 ;; Check which ones of source and target are Tramp files.
3801 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3803 (if (and (file-directory-p filename)
3805 (file-name-nondirectory filename)
3806 (file-name-nondirectory newname)))
3807 'file-name-directory
3809 (if t2 (tramp-make-copy-program-file-name v) newname)))
3811 ;; Check for port number. Until now, there's no need for handling
3812 ;; like method, user, host.
3813 (setq host (tramp-file-name-real-host v)
3814 port (tramp-file-name-port v)
3815 port (or (and port (number-to-string port)) ""))
3817 ;; Compose copy command.
3818 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3819 (?t . ,(tramp-get-connection-property
3820 (tramp-get-connection-process v) "temp-file" ""))
3821 (?k . ,(if keep-date " " "")))
3822 copy-program (tramp-get-method-parameter
3823 method 'tramp-copy-program)
3824 copy-keep-date (tramp-get-method-parameter
3825 method 'tramp-copy-keep-date)
3833 ;; " " is indication for keep-date argument.
3834 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3835 (unless (member "" x) (mapconcat 'identity x " ")))
3836 (tramp-get-method-parameter method 'tramp-copy-args)))
3842 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3843 (unless (member "" x) (mapconcat 'identity x " ")))
3844 (tramp-get-method-parameter method 'tramp-copy-env))))
3846 ;; Check for program.
3847 (when (and (fboundp 'executable-find)
3848 (not (let ((default-directory
3849 (tramp-compat-temporary-file-directory)))
3850 (executable-find copy-program))))
3852 v 'file-error "Cannot find copy program: %s" copy-program))
3854 ;; Set variables for computing the prompt for reading
3856 (setq tramp-current-method (tramp-file-name-method v)
3857 tramp-current-user (tramp-file-name-user v)
3858 tramp-current-host (tramp-file-name-host v))
3862 ;; The default directory must be remote.
3863 (let ((default-directory
3864 (file-name-directory (if t1 filename newname)))
3865 (process-environment (copy-sequence process-environment)))
3866 ;; Set the transfer process properties.
3867 (tramp-set-connection-property
3868 v "process-name" (buffer-name (current-buffer)))
3869 (tramp-set-connection-property
3870 v "process-buffer" (current-buffer))
3872 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3873 (setenv (pop copy-env) (pop copy-env)))
3875 ;; Use an asynchronous process. By this, password can
3876 ;; be handled. The default directory must be local, in
3877 ;; order to apply the correct `copy-program'. We don't
3878 ;; set a timeout, because the copying of large files can
3879 ;; last longer than 60 secs.
3880 (let ((p (let ((default-directory
3881 (tramp-compat-temporary-file-directory)))
3882 (apply 'start-process
3883 (tramp-get-connection-property
3884 v "process-name" nil)
3885 (tramp-get-connection-property
3886 v "process-buffer" nil)
3888 (append copy-args (list source target))))))
3890 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3891 (tramp-set-process-query-on-exit-flag p nil)
3892 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
3894 ;; Reset the transfer process properties.
3895 (tramp-set-connection-property v "process-name" nil)
3896 (tramp-set-connection-property v "process-buffer" nil))
3898 ;; Handle KEEP-DATE argument.
3899 (when (and keep-date (not copy-keep-date))
3900 (set-file-times newname (nth 5 (file-attributes filename))))
3903 (unless (and keep-date copy-keep-date)
3904 (set-file-modes newname (tramp-default-file-modes filename))))
3906 ;; If the operation was `rename', delete the original file.
3907 (unless (eq op 'copy)
3908 (delete-file filename)))))
3910 (defun tramp-handle-make-directory (dir &optional parents)
3911 "Like `make-directory' for Tramp files."
3912 (setq dir (expand-file-name dir))
3913 (with-parsed-tramp-file-name dir nil
3914 (tramp-flush-directory-property v (file-name-directory localname))
3916 (tramp-barf-unless-okay
3919 (if parents "mkdir -p" "mkdir")
3920 (tramp-shell-quote-argument localname))
3921 "Couldn't make directory %s" dir))))
3923 (defun tramp-handle-delete-directory (directory &optional recursive)
3924 "Like `delete-directory' for Tramp files."
3925 (setq directory (expand-file-name directory))
3926 (with-parsed-tramp-file-name directory nil
3927 (tramp-flush-directory-property v localname)
3928 (unless (zerop (tramp-send-command-and-check
3932 (if recursive "rm -rf" "rmdir")
3933 (tramp-shell-quote-argument localname))))
3934 (tramp-error v 'file-error "Couldn't delete %s" directory))))
3936 (defun tramp-handle-delete-file (filename)
3937 "Like `delete-file' for Tramp files."
3938 (setq filename (expand-file-name filename))
3939 (with-parsed-tramp-file-name filename nil
3940 (tramp-flush-file-property v localname)
3941 (unless (zerop (tramp-send-command-and-check
3944 (tramp-shell-quote-argument localname))))
3945 (tramp-error v 'file-error "Couldn't delete %s" filename))))
3949 ;; CCC: This does not seem to be enough. Something dies when
3950 ;; we try and delete two directories under Tramp :/
3951 (defun tramp-handle-dired-recursive-delete-directory (filename)
3952 "Recursively delete the directory given.
3953 This is like `dired-recursive-delete-directory' for Tramp files."
3954 (with-parsed-tramp-file-name filename nil
3955 ;; Run a shell command 'rm -r <localname>'
3956 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
3957 (unless (file-exists-p filename)
3958 (tramp-error v 'file-error "No such directory: %s" filename))
3959 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
3962 (format "rm -rf %s" (tramp-shell-quote-argument localname))
3963 ;; Don't read the output, do it explicitely.
3965 ;; Wait for the remote system to return to us...
3966 ;; This might take a while, allow it plenty of time.
3967 (tramp-wait-for-output (tramp-get-connection-process v) 120)
3968 ;; Make sure that it worked...
3969 (tramp-flush-directory-property v localname)
3970 (and (file-exists-p filename)
3972 v 'file-error "Failed to recursively delete %s" filename))))
3974 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
3975 "Like `dired-compress-file' for Tramp files."
3976 ;; OK-FLAG is valid for XEmacs only, but not implemented.
3977 ;; Code stolen mainly from dired-aux.el.
3978 (with-parsed-tramp-file-name file nil
3979 (tramp-flush-file-property v localname)
3982 (if (not (featurep 'xemacs))
3984 (symbol-value 'dired-compress-file-suffixes)
3985 ;; XEmacs has `dired-compression-method-alist', which is
3986 ;; transformed into `dired-compress-file-suffixes' structure.
3989 (list (concat (regexp-quote (nth 1 x)) "\\'")
3991 (mapconcat 'identity (nth 3 x) " ")))
3992 (symbol-value 'dired-compression-method-alist))))
3994 ;; See if any suffix rule matches this file name.
3996 (let (case-fold-search)
3997 (if (string-match (car (car suffixes)) localname)
3998 (setq suffix (car suffixes) suffixes nil))
3999 (setq suffixes (cdr suffixes))))
4001 (cond ((file-symlink-p file)
4003 ((and suffix (nth 2 suffix))
4004 ;; We found an uncompression rule.
4005 (tramp-message v 0 "Uncompressing %s..." file)
4006 (when (zerop (tramp-send-command-and-check
4007 v (concat (nth 2 suffix) " "
4008 (tramp-shell-quote-argument localname))))
4009 (tramp-message v 0 "Uncompressing %s...done" file)
4010 ;; `dired-remove-file' is not defined in XEmacs
4011 (funcall (symbol-function 'dired-remove-file) file)
4012 (string-match (car suffix) file)
4013 (concat (substring file 0 (match-beginning 0)))))
4015 ;; We don't recognize the file as compressed, so compress it.
4017 (tramp-message v 0 "Compressing %s..." file)
4018 (when (zerop (tramp-send-command-and-check
4019 v (concat "gzip -f "
4020 (tramp-shell-quote-argument localname))))
4021 (tramp-message v 0 "Compressing %s...done" file)
4022 ;; `dired-remove-file' is not defined in XEmacs
4023 (funcall (symbol-function 'dired-remove-file) file)
4024 (cond ((file-exists-p (concat file ".gz"))
4025 (concat file ".gz"))
4026 ((file-exists-p (concat file ".z"))
4030 (defun tramp-handle-dired-uncache (dir)
4031 "Like `dired-uncache' for Tramp files."
4032 (with-parsed-tramp-file-name dir nil
4033 (tramp-flush-file-property v localname)))
4035 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4036 ;; not sure at all that this is the right way to do it, but let's hope
4037 ;; it works for now, and wait for a guru to point out the Right Way to
4039 ;;(eval-when-compile
4040 ;; (unless (fboundp 'dired-insert-set-properties)
4041 ;; (fset 'dired-insert-set-properties 'ignore)))
4042 ;; Gerd suggests this:
4043 (eval-when-compile (require 'dired))
4044 ;; Note that dired is required at run-time, too, when it is needed.
4045 ;; It is only needed on XEmacs for the function
4046 ;; `dired-insert-set-properties'.
4048 (defun tramp-handle-insert-directory
4049 (filename switches &optional wildcard full-directory-p)
4050 "Like `insert-directory' for Tramp files."
4051 (setq filename (expand-file-name filename))
4052 (with-parsed-tramp-file-name filename nil
4053 (if (and (featurep 'ls-lisp)
4054 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4055 (tramp-run-real-handler
4056 'insert-directory (list filename switches wildcard full-directory-p))
4057 (when (and (string-match "^--dired\\s-+" switches)
4058 (not (tramp-get-ls-command-with-dired v)))
4059 (setq switches (replace-match "" nil t switches)))
4061 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4062 switches filename (if wildcard "yes" "no")
4063 (if full-directory-p "yes" "no"))
4065 (setq wildcard (tramp-run-real-handler
4066 'file-name-nondirectory (list localname)))
4067 (setq localname (tramp-run-real-handler
4068 'file-name-directory (list localname))))
4069 (when (listp switches)
4070 (setq switches (mapconcat 'identity switches " ")))
4071 (unless full-directory-p
4072 (setq switches (concat "-d " switches)))
4074 (setq switches (concat switches " " wildcard)))
4075 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4076 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4077 (if full-directory-p
4080 (format "%s %s %s 2>/dev/null"
4081 (tramp-get-ls-command v)
4085 (tramp-shell-quote-argument (concat localname ".")))))
4086 (tramp-barf-unless-okay
4088 (format "cd %s" (tramp-shell-quote-argument
4089 (tramp-run-real-handler
4090 'file-name-directory (list localname))))
4092 (tramp-shell-quote-argument
4093 (tramp-run-real-handler 'file-name-directory (list localname))))
4097 (tramp-get-ls-command v)
4101 (tramp-run-real-handler
4102 'file-name-nondirectory (list localname)))))
4104 (tramp-shell-quote-argument
4105 (tramp-run-real-handler
4106 'file-name-nondirectory (list localname)))))))
4107 (let ((beg (point)))
4108 ;; We cannot use `insert-buffer-substring' because the Tramp
4109 ;; buffer changes its contents before insertion due to calling
4110 ;; `expand-file' and alike.
4112 (with-current-buffer (tramp-get-buffer v)
4115 ;; Check for "--dired" output.
4117 (when (looking-at "//DIRED//")
4118 (let ((end (tramp-compat-line-end-position))
4120 ;; Now read the numeric positions of file names.
4124 (while (< (point) end)
4125 (let ((start (+ beg (read (current-buffer))))
4126 (end (+ beg (read (current-buffer)))))
4127 (if (memq (char-after end) '(?\n ?\ ))
4128 ;; End is followed by \n or by " -> ".
4129 (put-text-property start end 'dired-filename t))))))
4130 ;; Remove trailing lines.
4131 (goto-char (tramp-compat-line-beginning-position))
4132 (while (looking-at "//")
4134 (delete-region (match-beginning 0) (point)))
4135 (goto-char (point-max))))))
4137 (defun tramp-handle-unhandled-file-name-directory (filename)
4138 "Like `unhandled-file-name-directory' for Tramp files."
4139 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4140 ;; for backward compatibility.
4141 (expand-file-name "~/"))
4143 ;; Canonicalization of file names.
4145 (defun tramp-handle-expand-file-name (name &optional dir)
4146 "Like `expand-file-name' for Tramp files.
4147 If the localname part of the given filename starts with \"/../\" then
4148 the result will be a local, non-Tramp, filename."
4149 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4150 (setq dir (or dir default-directory "/"))
4151 ;; Unless NAME is absolute, concat DIR and NAME.
4152 (unless (file-name-absolute-p name)
4153 (setq name (concat (file-name-as-directory dir) name)))
4154 ;; If NAME is not a Tramp file, run the real handler.
4155 (if (not (tramp-tramp-file-p name))
4156 (tramp-run-real-handler 'expand-file-name (list name nil))
4158 (with-parsed-tramp-file-name name nil
4159 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4160 (setq localname (concat "~/" localname)))
4161 ;; Tilde expansion if necessary. This needs a shell which
4162 ;; groks tilde expansion! The function `tramp-find-shell' is
4163 ;; supposed to find such a shell on the remote host. Please
4164 ;; tell me about it when this doesn't work on your system.
4165 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4166 (let ((uname (match-string 1 localname))
4167 (fname (match-string 2 localname)))
4168 ;; We cannot simply apply "~/", because under sudo "~/" is
4169 ;; expanded to the local user home directory but to the
4170 ;; root home directory. On the other hand, using always
4171 ;; the default user name for tilde expansion is not
4172 ;; appropriate either, because ssh and companions might
4173 ;; use a user name from the config file.
4174 (when (and (string-equal uname "~")
4175 (string-match "\\`su\\(do\\)?\\'" method))
4176 (setq uname (concat uname user)))
4178 (with-connection-property v uname
4180 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4181 (with-current-buffer (tramp-get-buffer v)
4182 (goto-char (point-min))
4184 (point) (tramp-compat-line-end-position)))))
4185 (setq localname (concat uname fname))))
4186 ;; There might be a double slash, for example when "~/"
4187 ;; expands to "/". Remove this.
4188 (while (string-match "//" localname)
4189 (setq localname (replace-match "/" t t localname)))
4190 ;; No tilde characters in file name, do normal
4191 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4192 ;; `directory-sep-char' here for XEmacs on Windows, which would
4193 ;; otherwise use backslash. `default-directory' is bound,
4194 ;; because on Windows there would be problems with UNC shares or
4196 (let ((directory-sep-char ?/)
4197 (default-directory (tramp-compat-temporary-file-directory)))
4198 (tramp-make-tramp-file-name
4200 (tramp-drop-volume-letter
4201 (tramp-run-real-handler
4202 'expand-file-name (list localname))))))))
4204 (defun tramp-replace-environment-variables (filename)
4205 "Replace environment variables in FILENAME.
4206 Return the string with the replaced variables."
4208 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4209 ;; `$' is coded as `$$'.
4211 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4212 (getenv (match-string 1 filename)))
4215 (substitute-in-file-name (match-string 0 filename))
4219 (defun tramp-handle-substitute-in-file-name (filename)
4220 "Like `substitute-in-file-name' for Tramp files.
4221 \"//\" and \"/~\" substitute only in the local filename part.
4222 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4223 beginning of local filename are not substituted."
4224 ;; First, we must replace environment variables.
4225 (setq filename (tramp-replace-environment-variables filename))
4226 (with-parsed-tramp-file-name filename nil
4227 (if (equal tramp-syntax 'url)
4228 ;; We need to check localname only. The other parts cannot contain
4230 (if (and (> (length localname) 1)
4231 (or (string-match "//" localname)
4232 (string-match "/~" localname 1)))
4233 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4234 (tramp-make-tramp-file-name
4235 (when method (substitute-in-file-name method))
4236 (when user (substitute-in-file-name user))
4237 (when host (substitute-in-file-name host))
4239 (tramp-run-real-handler
4240 'substitute-in-file-name (list localname)))))
4241 ;; Ignore in LOCALNAME everything before "//" or "/~".
4242 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4244 (concat (file-remote-p filename)
4245 (replace-match "\\1" nil nil localname)))
4246 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4247 (when (string-match "~$" filename)
4248 (setq filename (concat filename "/"))))
4249 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4251 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4252 ;; which calls corresponding functions (see minibuf.el).
4253 (when (fboundp 'minibuffer-electric-separator)
4258 (around ,(intern (format "tramp-advice-%s" x)) activate)
4259 "Invoke `substitute-in-file-name' for Tramp files."
4260 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4261 (tramp-tramp-file-p (buffer-substring)))
4262 ;; We don't need to handle `last-input-event', because
4263 ;; due to the key map we know it must be ?/ or ?~.
4264 (let ((s (concat (buffer-substring (point-min) (point))
4265 (string last-command-char))))
4266 (delete-region (point-min) (point))
4267 (insert (substitute-in-file-name s))
4268 (setq ad-return-value last-command-char))
4274 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4275 (ad-activate ',x)))))
4277 '(minibuffer-electric-separator
4278 minibuffer-electric-tilde)))
4281 ;;; Remote commands:
4283 (defun tramp-handle-executable-find (command)
4284 "Like `executable-find' for Tramp files."
4285 (with-parsed-tramp-file-name default-directory nil
4286 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4288 ;; We use BUFFER also as connection buffer during setup. Because of
4289 ;; this, its original contents must be saved, and restored once
4290 ;; connection has been setup.
4291 (defun tramp-handle-start-file-process (name buffer program &rest args)
4292 "Like `start-file-process' for Tramp files."
4293 (with-parsed-tramp-file-name default-directory nil
4294 (unless (stringp program)
4296 v 'file-error "pty association is not supported for `%s'" name))
4298 (let ((command (format "cd %s; exec %s"
4299 (tramp-shell-quote-argument localname)
4300 (mapconcat 'tramp-shell-quote-argument
4301 (cons program args) " ")))
4305 ;; BUFFER can be nil. We use a temporary buffer.
4306 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4307 (while (get-process name1)
4308 ;; NAME must be unique as process name.
4310 name1 (format "%s<%d>" name i)))
4312 ;; Set the new process properties.
4313 (tramp-set-connection-property v "process-name" name)
4314 (tramp-set-connection-property v "process-buffer" buffer)
4315 ;; Activate narrowing in order to save BUFFER contents.
4316 ;; Clear also the modification time; otherwise we might be
4317 ;; interrupted by `verify-visited-file-modtime'.
4318 (with-current-buffer (tramp-get-connection-buffer v)
4319 (clear-visited-file-modtime)
4320 (narrow-to-region (point-max) (point-max)))
4321 ;; Send the command. `tramp-send-command' opens a new
4323 (tramp-send-command v command nil t) ; nooutput
4324 ;; Set query flag for this process.
4325 (tramp-set-process-query-on-exit-flag
4326 (tramp-get-connection-process v) t)
4328 (tramp-get-connection-process v))
4330 (with-current-buffer (tramp-get-connection-buffer v)
4331 (if (string-match tramp-temp-buffer-name (buffer-name))
4333 (set-process-buffer (tramp-get-connection-process v) nil)
4334 (kill-buffer (current-buffer)))
4336 (goto-char (point-max))))
4337 (tramp-set-connection-property v "process-name" nil)
4338 (tramp-set-connection-property v "process-buffer" nil))))
4340 (defun tramp-handle-process-file
4341 (program &optional infile destination display &rest args)
4342 "Like `process-file' for Tramp files."
4343 ;; The implementation is not complete yet.
4344 (when (and (numberp destination) (zerop destination))
4345 (error "Implementation does not handle immediate return"))
4347 (with-parsed-tramp-file-name default-directory nil
4348 (let (command input tmpinput stderr tmpstderr outbuf ret)
4350 (setq command (mapconcat 'tramp-shell-quote-argument
4351 (cons program args) " "))
4354 (setq input "/dev/null")
4355 (setq infile (expand-file-name infile))
4356 (if (tramp-equal-remote default-directory infile)
4357 ;; INFILE is on the same remote host.
4358 (setq input (with-parsed-tramp-file-name infile nil localname))
4359 ;; INFILE must be copied to remote host.
4360 (setq input (tramp-make-tramp-temp-file v)
4361 tmpinput (tramp-make-tramp-file-name method user host input))
4362 (copy-file infile tmpinput t)))
4363 (when input (setq command (format "%s <%s" command input)))
4365 ;; Determine output.
4368 ((bufferp destination)
4369 (setq outbuf destination))
4371 ((stringp destination)
4372 (setq outbuf (get-buffer-create destination)))
4373 ;; (REAL-DESTINATION ERROR-DESTINATION)
4374 ((consp destination)
4377 ((bufferp (car destination))
4378 (setq outbuf (car destination)))
4379 ((stringp (car destination))
4380 (setq outbuf (get-buffer-create (car destination))))
4382 (setq outbuf (current-buffer))))
4385 ((stringp (cadr destination))
4386 (setcar (cdr destination) (expand-file-name (cadr destination)))
4387 (if (tramp-equal-remote default-directory (cadr destination))
4388 ;; stderr is on the same remote host.
4389 (setq stderr (with-parsed-tramp-file-name
4390 (cadr destination) nil localname))
4391 ;; stderr must be copied to remote host. The temporary
4392 ;; file must be deleted after execution.
4393 (setq stderr (tramp-make-tramp-temp-file v)
4394 tmpstderr (tramp-make-tramp-file-name
4395 method user host stderr))))
4396 ;; stderr to be discarded.
4397 ((null (cadr destination))
4398 (setq stderr "/dev/null"))))
4401 (setq outbuf (current-buffer))))
4402 (when stderr (setq command (format "%s 2>%s" command stderr)))
4404 ;; Send the command. It might not return in time, so we protect it.
4408 (tramp-send-command-and-check
4409 v (format "\\cd %s; %s"
4410 (tramp-shell-quote-argument localname)
4413 ;; We should show the output anyway.
4415 (with-current-buffer outbuf
4417 (with-current-buffer (tramp-get-connection-buffer v)
4419 (when display (display-buffer outbuf))))
4420 ;; When the user did interrupt, we should do it also. We use
4421 ;; return code -1 as marker.
4423 (kill-buffer (tramp-get-connection-buffer v))
4427 (kill-buffer (tramp-get-connection-buffer v))
4430 ;; Provide error file.
4431 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4433 ;; Cleanup. We remove all file cache values for the connection,
4434 ;; because the remote process could have changed them.
4435 (when tmpinput (delete-file tmpinput))
4437 ;; `process-file-side-effects' has been introduced with GNU
4438 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4439 ;; by `program'. If it doesn't exist, we assume its default
4441 (unless (and (boundp 'process-file-side-effects)
4442 (not (symbol-value 'process-file-side-effects)))
4443 (tramp-flush-directory-property v ""))
4445 ;; Return exit status.
4450 (defun tramp-local-call-process
4451 (program &optional infile destination display &rest args)
4452 "Calls `call-process' on the local host.
4453 This is needed because for some Emacs flavors Tramp has
4454 defadviced `call-process' to behave like `process-file'. The
4455 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4456 (let ((default-directory
4457 (if (file-remote-p default-directory)
4458 (tramp-compat-temporary-file-directory)
4459 default-directory)))
4460 (if (executable-find program)
4461 (apply 'call-process program infile destination display args)
4464 (defun tramp-handle-call-process-region
4465 (start end program &optional delete buffer display &rest args)
4466 "Like `call-process-region' for Tramp files."
4467 (let ((tmpfile (tramp-compat-make-temp-file "")))
4468 (write-region start end tmpfile)
4469 (when delete (delete-region start end))
4471 (apply 'call-process program tmpfile buffer display args)
4472 (delete-file tmpfile))))
4474 (defun tramp-handle-shell-command
4475 (command &optional output-buffer error-buffer)
4476 "Like `shell-command' for Tramp files."
4477 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4478 ;; We cannot use `shell-file-name' and `shell-command-switch',
4479 ;; they are variables of the local host.
4480 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
4484 ((bufferp output-buffer) output-buffer)
4485 ((stringp output-buffer) (get-buffer-create output-buffer))
4487 (setq current-buffer-p t)
4489 (t (get-buffer-create
4491 "*Async Shell Command*"
4492 "*Shell Command Output*")))))
4495 ((bufferp error-buffer) error-buffer)
4496 ((stringp error-buffer) (get-buffer-create error-buffer))))
4498 (if (and (not asynchronous) error-buffer)
4499 (with-parsed-tramp-file-name default-directory nil
4500 (list output-buffer (tramp-make-tramp-temp-file v)))
4502 (p (get-buffer-process output-buffer)))
4504 ;; Check whether there is another process running. Tramp does not
4505 ;; support 2 (asynchronous) processes in parallel.
4507 (if (yes-or-no-p "A command is running. Kill it? ")
4511 (error "Shell command in progress")))
4513 (if current-buffer-p
4515 (barf-if-buffer-read-only)
4517 (with-current-buffer output-buffer
4518 (setq buffer-read-only nil)
4521 (if (and (not current-buffer-p) (integerp asynchronous))
4524 (apply 'start-file-process "*Async Shell*" buffer args)
4526 (pop-to-buffer output-buffer)
4527 (setq mode-line-process '(":%s"))
4528 (require 'shell) (shell-mode))
4532 (apply 'process-file (car args) nil buffer nil (cdr args))
4533 ;; Insert error messages if they were separated.
4534 (when (listp buffer)
4535 (with-current-buffer error-buffer
4536 (insert-file-contents (cadr buffer)))
4537 (delete-file (cadr buffer)))
4538 (if current-buffer-p
4539 ;; This is like exchange-point-and-mark, but doesn't
4540 ;; activate the mark. It is cleaner to avoid activation,
4541 ;; even though the command loop would deactivate the mark
4542 ;; because we inserted text.
4543 (goto-char (prog1 (mark t)
4544 (set-marker (mark-marker) (point)
4546 ;; There's some output, display it.
4547 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4548 (if (functionp 'display-message-or-buffer)
4549 (funcall (symbol-function 'display-message-or-buffer)
4551 (pop-to-buffer output-buffer))))))))
4555 (defvar tramp-handle-file-local-copy-hook nil
4556 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4558 (defun tramp-handle-file-local-copy (filename)
4559 "Like `file-local-copy' for Tramp files."
4561 (with-parsed-tramp-file-name filename nil
4562 (unless (file-exists-p filename)
4565 "Cannot make local copy of non-existing file `%s'" filename))
4567 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
4568 (loc-dec (tramp-get-local-coding v "local-decoding"))
4569 (tmpfile (tramp-compat-make-temp-file filename)))
4573 ;; `copy-file' handles direct copy and out-of-band methods.
4574 ((or (tramp-local-host-p v)
4575 (tramp-method-out-of-band-p
4576 v (nth 7 (file-attributes filename))))
4577 (copy-file filename tmpfile t t))
4579 ;; Use inline encoding for file transfer.
4582 (tramp-message v 5 "Encoding remote file %s..." filename)
4583 (tramp-barf-unless-okay
4585 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4586 "Encoding remote file failed")
4587 (tramp-message v 5 "Encoding remote file %s...done" filename)
4589 (if (and (symbolp loc-dec) (fboundp loc-dec))
4590 ;; If local decoding is a function, we call it. We
4591 ;; must disable multibyte, because
4592 ;; `uudecode-decode-region' doesn't handle it
4595 (set-buffer-multibyte nil)
4596 (insert-buffer-substring (tramp-get-buffer v))
4598 v 5 "Decoding remote file %s with function %s..."
4600 (funcall loc-dec (point-min) (point-max))
4601 ;; Unset `file-name-handler-alist'. Otherwise,
4602 ;; epa-file gets confused.
4603 (let (file-name-handler-alist
4604 (coding-system-for-write 'binary))
4605 (write-region (point-min) (point-max) tmpfile)))
4607 ;; If tramp-decoding-function is not defined for this
4608 ;; method, we invoke tramp-decoding-command instead.
4609 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4610 ;; Unset `file-name-handler-alist'. Otherwise,
4611 ;; epa-file gets confused.
4612 (let (file-name-handler-alist
4613 (coding-system-for-write 'binary))
4614 (write-region (point-min) (point-max) tmpfile2))
4616 v 5 "Decoding remote file %s with command %s..."
4619 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4620 (delete-file tmpfile2))))
4622 (tramp-message v 5 "Decoding remote file %s...done" filename)
4623 ;; Set proper permissions.
4624 (set-file-modes tmpfile (tramp-default-file-modes filename))
4625 ;; Set local user ownership.
4626 (tramp-set-file-uid-gid tmpfile)))
4628 ;; Oops, I don't know what to do.
4630 v 'file-error "Wrong method specification for `%s'" method)))
4634 (delete-file tmpfile)
4635 (signal (car err) (cdr err))))
4637 (run-hooks 'tramp-handle-file-local-copy-hook)
4640 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4641 "Like `file-remote-p' for Tramp files."
4642 (when (tramp-tramp-file-p filename)
4643 (with-parsed-tramp-file-name (expand-file-name filename) nil
4644 (and (or (not connected)
4645 (let ((p (tramp-get-connection-process v)))
4646 (and p (processp p) (memq (process-status p) '(run open)))))
4648 ((eq identification 'method) method)
4649 ((eq identification 'user) user)
4650 ((eq identification 'host) host)
4651 ((eq identification 'localname) localname)
4652 (t (tramp-make-tramp-file-name method user host "")))))))
4654 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4655 "Like `find-operation-coding-system' for Tramp filenames.
4656 Tramp's `insert-file-contents' and `write-region' work over
4657 temporary file names. If `file-coding-system-alist' contains an
4658 expression, which matches more than the file name suffix, the
4659 coding system might not be determined. This function repairs it."
4661 (dolist (elt file-coding-system-alist result)
4662 (when (and (consp elt) (string-match (car elt) filename))
4663 ;; We found a matching entry in `file-coding-system-alist'.
4664 ;; So we add a similar entry, but with the temporary file name
4667 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4669 (defun tramp-handle-insert-file-contents
4670 (filename &optional visit beg end replace)
4671 "Like `insert-file-contents' for Tramp files."
4672 (barf-if-buffer-read-only)
4673 (setq filename (expand-file-name filename))
4674 (let (coding-system-used result local-copy remote-copy)
4675 (with-parsed-tramp-file-name filename nil
4677 (if (not (file-exists-p filename))
4678 ;; We don't raise a Tramp error, because it might be
4679 ;; suppressed, like in `find-file-noselect-1'.
4681 (list "File not found on remote host" filename))
4683 (if (and (tramp-local-host-p v)
4684 (let (file-name-handler-alist)
4685 (file-readable-p localname)))
4686 ;; Short track: if we are on the local host, we can
4689 (tramp-run-real-handler
4690 'insert-file-contents
4691 (list localname visit beg end replace)))
4693 ;; When we shall insert only a part of the file, we copy
4696 (setq remote-copy (tramp-make-tramp-temp-file v))
4701 (format "tail -c +%d %s | head -c +%d >%s"
4702 (1+ beg) (tramp-shell-quote-argument localname)
4703 (- end beg) remote-copy))
4705 (format "tail -c +%d %s >%s"
4706 (1+ beg) (tramp-shell-quote-argument localname)
4709 (format "head -c +%d %s >%s"
4710 (1+ end) (tramp-shell-quote-argument localname)
4713 ;; `insert-file-contents-literally' takes care to avoid
4714 ;; calling jka-compr. By let-binding
4715 ;; `inhibit-file-name-operation', we propagate that care
4716 ;; to the `file-local-copy' operation.
4718 (let ((inhibit-file-name-operation
4719 (when (eq inhibit-file-name-operation
4720 'insert-file-contents)
4723 ((stringp remote-copy)
4725 (tramp-make-tramp-file-name
4726 method user host remote-copy)))
4727 ((stringp tramp-temp-buffer-file-name)
4728 (copy-file filename tramp-temp-buffer-file-name 'ok)
4729 tramp-temp-buffer-file-name)
4730 (t (file-local-copy filename)))))
4732 (when (and (null remote-copy)
4733 (tramp-get-method-parameter
4734 method 'tramp-copy-keep-tmpfile))
4735 ;; We keep the local file for performance reasons,
4736 ;; useful for "rsync".
4737 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4738 (setq tramp-temp-buffer-file-name local-copy)
4739 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4742 v 4 "Inserting local temp file `%s'..." local-copy)
4744 ;; We must ensure that `file-coding-system-alist'
4745 ;; matches `local-copy'.
4746 (let ((file-coding-system-alist
4747 (tramp-find-file-name-coding-system-alist
4748 filename local-copy)))
4750 (insert-file-contents
4751 local-copy nil nil nil replace))
4752 ;; Now `last-coding-system-used' has right value.
4754 (when (boundp 'last-coding-system-used)
4755 (setq coding-system-used
4756 (symbol-value 'last-coding-system-used))))
4759 v 4 "Inserting local temp file `%s'...done" local-copy)
4760 (when (boundp 'last-coding-system-used)
4761 (set 'last-coding-system-used coding-system-used))))
4766 (setq buffer-file-name filename)
4767 (setq buffer-read-only (not (file-writable-p filename)))
4768 (set-visited-file-modtime)
4769 (set-buffer-modified-p nil))
4770 (when (and (stringp local-copy)
4771 (or remote-copy (null tramp-temp-buffer-file-name)))
4772 (delete-file local-copy))
4773 (when (stringp remote-copy)
4775 (tramp-make-tramp-file-name method user host remote-copy))))))
4778 (list (expand-file-name filename)
4781 ;; This is needed for XEmacs only. Code stolen from files.el.
4782 (defun tramp-handle-insert-file-contents-literally
4783 (filename &optional visit beg end replace)
4784 "Like `insert-file-contents-literally' for Tramp files."
4785 (let ((format-alist nil)
4786 (after-insert-file-functions nil)
4787 (coding-system-for-read 'no-conversion)
4788 (coding-system-for-write 'no-conversion)
4789 (find-buffer-file-type-function
4790 (if (fboundp 'find-buffer-file-type)
4791 (symbol-function 'find-buffer-file-type)
4793 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4794 (inhibit-file-name-operation 'insert-file-contents))
4797 (fset 'find-buffer-file-type (lambda (filename) t))
4798 (insert-file-contents filename visit beg end replace))
4800 (if find-buffer-file-type-function
4801 (fset 'find-buffer-file-type find-buffer-file-type-function)
4802 (fmakunbound 'find-buffer-file-type)))))
4804 (defun tramp-handle-find-backup-file-name (filename)
4805 "Like `find-backup-file-name' for Tramp files."
4806 (with-parsed-tramp-file-name filename nil
4807 ;; We set both variables. It doesn't matter whether it is
4809 (let ((backup-directory-alist
4811 (when (boundp 'backup-directory-alist)
4812 (if (symbol-value 'tramp-backup-directory-alist)
4817 (if (and (stringp (cdr x))
4818 (file-name-absolute-p (cdr x))
4819 (not (tramp-file-name-p (cdr x))))
4820 (tramp-make-tramp-file-name method user host (cdr x))
4822 (symbol-value 'tramp-backup-directory-alist))
4823 (symbol-value 'backup-directory-alist))))
4825 (bkup-backup-directory-info
4827 (when (boundp 'bkup-backup-directory-info)
4828 (if (symbol-value 'tramp-bkup-backup-directory-info)
4834 (if (and (stringp (car (cdr x)))
4835 (file-name-absolute-p (car (cdr x)))
4836 (not (tramp-file-name-p (car (cdr x)))))
4837 (tramp-make-tramp-file-name
4838 method user host (car (cdr x)))
4841 (symbol-value 'tramp-bkup-backup-directory-info))
4842 (symbol-value 'bkup-backup-directory-info)))))
4844 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
4846 (defun tramp-handle-make-auto-save-file-name ()
4847 "Like `make-auto-save-file-name' for Tramp files.
4848 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
4849 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4851 (tramp-subst-strs-in-string
4858 (buffer-file-name))))
4859 ;; File name must be unique. This is ensured with Emacs 22 (see
4860 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4861 ;; all other cases we must do it ourselves.
4862 (when (boundp 'auto-save-file-name-transforms)
4865 (when (and (string-match (car x) buffer-file-name)
4866 (not (car (cddr x))))
4867 (setq tramp-auto-save-directory
4868 (or tramp-auto-save-directory
4869 (tramp-compat-temporary-file-directory)))))
4870 (symbol-value 'auto-save-file-name-transforms)))
4871 ;; Create directory.
4872 (when tramp-auto-save-directory
4873 (setq buffer-file-name
4874 (expand-file-name buffer-file-name tramp-auto-save-directory))
4875 (unless (file-exists-p tramp-auto-save-directory)
4876 (make-directory tramp-auto-save-directory t)))
4877 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4878 ;; it is not a magic file name operation (since Emacs 22).
4879 ;; We must deactivate it temporarily.
4880 (if (not (ad-is-active 'make-auto-save-file-name))
4881 (tramp-run-real-handler 'make-auto-save-file-name nil)
4883 (ad-deactivate 'make-auto-save-file-name)
4885 (tramp-run-real-handler 'make-auto-save-file-name nil)
4886 (ad-activate 'make-auto-save-file-name)))))
4888 (defvar tramp-handle-write-region-hook nil
4889 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4891 ;; CCC grok LOCKNAME
4892 (defun tramp-handle-write-region
4893 (start end filename &optional append visit lockname confirm)
4894 "Like `write-region' for Tramp files."
4895 (setq filename (expand-file-name filename))
4896 (with-parsed-tramp-file-name filename nil
4897 ;; Following part commented out because we don't know what to do about
4898 ;; file locking, and it does not appear to be a problem to ignore it.
4899 ;; Ange-ftp ignores it, too.
4900 ;; (when (and lockname (stringp lockname))
4901 ;; (setq lockname (expand-file-name lockname)))
4902 ;; (unless (or (eq lockname nil)
4903 ;; (string= lockname filename))
4905 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
4907 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
4908 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4909 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4910 (tramp-error v 'file-error "File not overwritten")))
4912 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
4913 (tramp-get-remote-uid v 'integer)))
4914 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
4915 (tramp-get-remote-gid v 'integer))))
4917 (if (and (tramp-local-host-p v)
4918 ;; `file-writable-p' calls `file-expand-file-name'. We
4919 ;; cannot use `tramp-run-real-handler' therefore.
4920 (let (file-name-handler-alist)
4922 (file-writable-p (file-name-directory localname))
4923 (or (file-directory-p localname)
4924 (file-writable-p localname)))))
4925 ;; Short track: if we are on the local host, we can run directly.
4927 (tramp-run-real-handler
4929 (list start end localname append 'no-message lockname confirm))
4930 (tramp-flush-file-property v localname))
4932 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4933 (loc-enc (tramp-get-local-coding v "local-encoding"))
4934 (modes (save-excursion (tramp-default-file-modes filename)))
4935 ;; We use this to save the value of
4936 ;; `last-coding-system-used' after writing the tmp file.
4937 ;; At the end of the function, we set
4938 ;; `last-coding-system-used' to this saved value. This
4939 ;; way, any intermediary coding systems used while
4940 ;; talking to the remote shell or suchlike won't hose
4941 ;; this variable. This approach was snarfed from
4944 ;; Write region into a tmp file. This isn't really
4945 ;; needed if we use an encoding function, but currently
4946 ;; we use it always because this makes the logic
4948 (tmpfile (or tramp-temp-buffer-file-name
4949 (tramp-compat-make-temp-file filename))))
4951 ;; If `append' is non-nil, we copy the file locally, and let
4952 ;; the native `write-region' implementation do the job.
4953 (when append (copy-file filename tmpfile 'ok))
4955 ;; We say `no-message' here because we don't want the
4956 ;; visited file modtime data to be clobbered from the temp
4957 ;; file. We call `set-visited-file-modtime' ourselves later
4958 ;; on. We must ensure that `file-coding-system-alist'
4959 ;; matches `tmpfile'.
4960 (let ((file-coding-system-alist
4961 (tramp-find-file-name-coding-system-alist filename tmpfile)))
4963 (tramp-run-real-handler
4965 (list start end tmpfile append 'no-message lockname confirm))
4967 (setq tramp-temp-buffer-file-name nil)
4968 (delete-file tmpfile)
4969 (signal (car err) (cdr err))))
4971 ;; Now, `last-coding-system-used' has the right value. Remember it.
4972 (when (boundp 'last-coding-system-used)
4973 (setq coding-system-used
4974 (symbol-value 'last-coding-system-used))))
4976 ;; The permissions of the temporary file should be set. If
4977 ;; filename does not exist (eq modes nil) it has been
4978 ;; renamed to the backup file. This case `save-buffer'
4979 ;; handles permissions.
4980 (when modes (set-file-modes tmpfile modes))
4982 ;; This is a bit lengthy due to the different methods
4983 ;; possible for file transfer. First, we check whether the
4984 ;; method uses an rcp program. If so, we call it.
4985 ;; Otherwise, both encoding and decoding command must be
4986 ;; specified. However, if the method _also_ specifies an
4987 ;; encoding function, then that is used for encoding the
4988 ;; contents of the tmp file.
4990 ;; `rename-file' handles direct copy and out-of-band methods.
4991 ((or (tramp-local-host-p v)
4992 (tramp-method-out-of-band-p
4993 v (- (or end (point-max)) (or start (point-min)))))
4994 (if (and (= (or end (point-max)) (point-max))
4995 (= (or start (point-min)) (point-min))
4996 (tramp-get-method-parameter
4997 method 'tramp-copy-keep-tmpfile))
4999 (setq tramp-temp-buffer-file-name tmpfile)
5001 ;; We keep the local file for performance
5002 ;; reasons, useful for "rsync".
5003 (copy-file tmpfile filename t)
5005 (setq tramp-temp-buffer-file-name nil)
5006 (delete-file tmpfile)
5007 (signal (car err) (cdr err)))))
5008 (setq tramp-temp-buffer-file-name nil)
5009 ;; Don't rename, in order to keep context in SELinux.
5011 (copy-file tmpfile filename t)
5012 (delete-file tmpfile))))
5014 ;; Use inline file transfer.
5017 (tramp-message v 5 "Encoding region...")
5020 ;; Use encoding function or command.
5021 (if (and (symbolp loc-enc) (fboundp loc-enc))
5024 v 5 "Encoding region using function `%s'..."
5025 (symbol-name loc-enc))
5026 (let ((coding-system-for-read 'binary))
5027 (insert-file-contents-literally tmpfile))
5028 ;; The following `let' is a workaround for the
5029 ;; base64.el that comes with pgnus-0.84. If
5030 ;; both of the following conditions are
5031 ;; satisfied, it tries to write to a local
5032 ;; file in default-directory, but at this
5033 ;; point, default-directory is remote.
5034 ;; (`call-process-region' can't write to
5035 ;; remote files, it seems.) The file in
5036 ;; question is a tmp file anyway.
5037 (let ((default-directory
5038 (tramp-compat-temporary-file-directory)))
5039 (funcall loc-enc (point-min) (point-max))))
5042 v 5 "Encoding region using command `%s'..." loc-enc)
5043 (unless (equal 0 (tramp-call-local-coding-command
5047 "Cannot write to `%s', local encoding command `%s' failed"
5050 ;; Send buffer into remote decoding command which
5051 ;; writes to remote file. Because this happens on
5052 ;; the remote host, we cannot use the function.
5053 (goto-char (point-max))
5054 (unless (bolp) (newline))
5056 v 5 "Decoding region into remote file %s..." filename)
5060 "%s >%s <<'EOF'\n%sEOF"
5062 (tramp-shell-quote-argument localname)
5064 (tramp-barf-unless-okay
5066 "Couldn't write region to `%s', decode using `%s' failed"
5068 ;; When `file-precious-flag' is set, the region is
5069 ;; written to a temporary file. Check that the
5070 ;; checksum is equal to that from the local tmpfile.
5071 (when file-precious-flag
5074 ;; cksum runs locally, if possible.
5075 (zerop (tramp-local-call-process "cksum" tmpfile t))
5076 ;; cksum runs remotely.
5078 (tramp-send-command-and-check
5081 "cksum <%s" (tramp-shell-quote-argument localname))))
5082 ;; ... they are different.
5086 (with-current-buffer (tramp-get-buffer v)
5090 (concat "Couldn't write region to `%s',"
5091 " decode using `%s' failed")
5094 v 5 "Decoding region into remote file %s...done" filename)
5095 (tramp-flush-file-property v localname))
5098 (delete-file tmpfile)))
5100 ;; That's not expected.
5104 (concat "Method `%s' should specify both encoding and "
5105 "decoding command or an rcp program")
5108 ;; Make `last-coding-system-used' have the right value.
5109 (when coding-system-used
5110 (set 'last-coding-system-used coding-system-used))))
5112 ;; We must protect `last-coding-system-used', now we have set it
5113 ;; to its correct value.
5114 (let (last-coding-system-used (need-chown t))
5115 ;; Set file modification time.
5116 (when (or (eq visit t) (stringp visit))
5117 (let ((file-attr (file-attributes filename)))
5118 (set-visited-file-modtime
5119 ;; We must pass modtime explicitely, because filename can
5120 ;; be different from (buffer-file-name), f.e. if
5121 ;; `file-precious-flag' is set.
5123 (when (and (eq (nth 2 file-attr) uid)
5124 (eq (nth 3 file-attr) gid))
5125 (setq need-chown nil))))
5127 ;; Set the ownership.
5129 (tramp-set-file-uid-gid filename uid gid))
5130 (when (or (eq visit t) (null visit) (stringp visit))
5131 (tramp-message v 0 "Wrote %s" filename))
5132 (run-hooks 'tramp-handle-write-region-hook)))))
5134 (defvar tramp-vc-registered-file-names nil
5135 "List used to collect file names, which are checked during `vc-registered'.")
5137 ;; VC backends check for the existence of various different special
5138 ;; files. This is very time consuming, because every single check
5139 ;; requires a remote command (the file cache must be invalidated).
5140 ;; Therefore, we apply a kind of optimization. We install the file
5141 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5142 ;; remembers all file names for which `file-exists-p' or
5143 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5144 ;; is performed. Afterwards, a script is applied for all collected
5145 ;; file names, using just one remote command. The result of this
5146 ;; script is used to fill the file cache with actual values. Now we
5147 ;; can reset the file name handlers, and we make a second run of
5148 ;; `vc-registered', which returns the expected result without sending
5149 ;; any other remote command.
5150 (defun tramp-handle-vc-registered (file)
5151 "Like `vc-registered' for Tramp files."
5152 (with-parsed-tramp-file-name file nil
5154 ;; There could be new files, created by the vc backend. We cannot
5155 ;; reuse the old cache entries, therefore.
5156 (let (tramp-vc-registered-file-names
5157 (tramp-cache-inhibit-cache (current-time))
5158 (file-name-handler-alist
5159 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5161 ;; Here we collect only file names, which need an operation.
5162 (tramp-run-real-handler 'vc-registered (list file))
5163 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5165 ;; Send just one command, in order to fill the cache.
5166 (when tramp-vc-registered-file-names
5167 (tramp-maybe-send-script
5169 (format tramp-vc-registered-read-file-names
5170 (tramp-get-file-exists-command v)
5171 (format "%s -r" (tramp-get-test-command v)))
5172 "tramp_vc_registered_read_file_names")
5176 (tramp-send-command-and-read
5179 "tramp_vc_registered_read_file_names %s"
5180 (mapconcat 'tramp-shell-quote-argument
5181 tramp-vc-registered-file-names
5184 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
5186 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
5187 ;; shall be answered from the file cache.
5188 ;; We unset `process-file-side-effects' in order to keep the cache
5189 ;; when `process-file' calls appear.
5190 (let (process-file-side-effects)
5191 (tramp-run-real-handler 'vc-registered (list file)))))
5194 (progn (defun tramp-run-real-handler (operation args)
5195 "Invoke normal file name handler for OPERATION.
5196 First arg specifies the OPERATION, second arg is a list of arguments to
5197 pass to the OPERATION."
5198 (let* ((inhibit-file-name-handlers
5199 `(tramp-file-name-handler
5200 tramp-vc-file-name-handler
5201 tramp-completion-file-name-handler
5202 cygwin-mount-name-hook-function
5203 cygwin-mount-map-drive-hook-function
5205 ,(and (eq inhibit-file-name-operation operation)
5206 inhibit-file-name-handlers)))
5207 (inhibit-file-name-operation operation))
5208 (apply operation args))))
5211 (progn (defun tramp-completion-run-real-handler (operation args)
5212 "Invoke `tramp-file-name-handler' for OPERATION.
5213 First arg specifies the OPERATION, second arg is a list of arguments to
5214 pass to the OPERATION."
5215 (let* ((inhibit-file-name-handlers
5216 `(tramp-completion-file-name-handler
5217 cygwin-mount-name-hook-function
5218 cygwin-mount-map-drive-hook-function
5220 ,(and (eq inhibit-file-name-operation operation)
5221 inhibit-file-name-handlers)))
5222 (inhibit-file-name-operation operation))
5223 (apply operation args))))
5225 ;; We handle here all file primitives. Most of them have the file
5226 ;; name as first parameter; nevertheless we check for them explicitly
5227 ;; in order to be signaled if a new primitive appears. This
5228 ;; scenario is needed because there isn't a way to decide by
5229 ;; syntactical means whether a foreign method must be called. It would
5230 ;; ease the life if `file-name-handler-alist' would support a decision
5231 ;; function as well but regexp only.
5232 (defun tramp-file-name-for-operation (operation &rest args)
5233 "Return file name related to OPERATION file primitive.
5234 ARGS are the arguments OPERATION has been called with."
5236 ; FILE resp DIRECTORY
5238 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5239 'delete-file 'diff-latest-backup-file 'directory-file-name
5240 'directory-files 'directory-files-and-attributes
5241 'dired-compress-file 'dired-uncache
5242 'file-accessible-directory-p 'file-attributes
5243 'file-directory-p 'file-executable-p 'file-exists-p
5244 'file-local-copy 'file-remote-p 'file-modes
5245 'file-name-as-directory 'file-name-directory
5246 'file-name-nondirectory 'file-name-sans-versions
5247 'file-ownership-preserved-p 'file-readable-p
5248 'file-regular-p 'file-symlink-p 'file-truename
5249 'file-writable-p 'find-backup-file-name 'find-file-noselect
5250 'get-file-buffer 'insert-directory 'insert-file-contents
5251 'load 'make-directory 'make-directory-internal
5252 'set-file-modes 'substitute-in-file-name
5253 'unhandled-file-name-directory 'vc-registered
5257 'abbreviate-file-name 'create-file-buffer
5258 'dired-file-modtime 'dired-make-compressed-filename
5259 'dired-recursive-delete-directory 'dired-set-file-modtime
5260 'dired-shell-unhandle-file-name 'dired-uucode-file
5261 'insert-file-contents-literally 'make-temp-name 'recover-file
5262 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5263 (if (file-name-absolute-p (nth 0 args))
5265 (expand-file-name (nth 0 args))))
5266 ; FILE DIRECTORY resp FILE1 FILE2
5268 (list 'add-name-to-file 'copy-file 'expand-file-name
5269 'file-name-all-completions 'file-name-completion
5270 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5274 'dired-make-relative-symlink
5275 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5278 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5279 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5280 (t (buffer-file-name (current-buffer))))))
5282 ((eq operation 'write-region)
5286 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5287 ; since Emacs 22 only
5288 'make-auto-save-file-name
5292 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5295 (list ; not in Emacs 23
5299 ; since Emacs 22 only
5301 ; since Emacs 23 only
5304 'dired-print-file 'dired-shell-call-process
5306 'executable-find 'start-process 'call-process))
5308 ; unknown file primitive
5309 (t (error "unknown file I/O primitive: %s" operation))))
5311 (defun tramp-find-foreign-file-name-handler (filename)
5312 "Return foreign file name handler if exists."
5313 (when (and (stringp filename) (tramp-tramp-file-p filename))
5314 (let ((v (tramp-dissect-file-name filename t))
5315 (handler tramp-foreign-file-name-handler-alist)
5317 ;; When we are not fully sure that filename completion is safe,
5318 ;; we should not return a handler.
5319 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5320 (and (tramp-file-name-host v)
5321 (not (member (tramp-file-name-host v)
5322 (mapcar 'car tramp-methods))))
5323 (not (tramp-completion-mode-p)))
5325 (setq elt (car handler)
5326 handler (cdr handler))
5327 (when (funcall (car elt) filename)
5334 (defun tramp-file-name-handler (operation &rest args)
5335 "Invoke Tramp file name handler.
5336 Falls back to normal file name handler if no Tramp file name handler exists."
5340 (tramp-replace-environment-variables
5341 (apply 'tramp-file-name-for-operation operation args)))
5342 (completion (tramp-completion-mode-p))
5343 (foreign (tramp-find-foreign-file-name-handler filename)))
5344 (with-parsed-tramp-file-name filename nil
5346 ;; When we are in completion mode, some operations
5347 ;; shouldn't be handled by backend.
5348 ((and completion (zerop (length localname))
5349 (memq operation '(file-exists-p file-directory-p)))
5351 ((and completion (zerop (length localname))
5352 (memq operation '(file-name-as-directory)))
5354 ;; Call the backend function.
5355 (foreign (apply foreign operation args))
5356 ;; Nothing to do for us.
5357 (t (tramp-run-real-handler operation args))))))
5358 ;; When `tramp-mode' is not enabled, we don't do anything.
5359 (tramp-run-real-handler operation args)))
5361 ;; In Emacs, there is some concurrency due to timers. If a timer
5362 ;; interrupts Tramp and wishes to use the same connection buffer as
5363 ;; the "main" Emacs, then garbage might occur in the connection
5364 ;; buffer. Therefore, we need to make sure that a timer does not use
5365 ;; the same connection buffer as the "main" Emacs. We implement a
5366 ;; cheap global lock, instead of locking each connection buffer
5367 ;; separately. The global lock is based on two variables,
5368 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5369 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5370 ;; processing of a single file operation, so we need to allow
5371 ;; recursive calls. That's where the `tramp-locker' variable comes in
5372 ;; -- it is let-bound to t during the execution of the current
5373 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5374 ;; then we should just proceed because we have been called
5375 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5376 ;; interrupting the "main" Emacs, and then we signal an error.
5378 (defvar tramp-locked nil
5379 "If non-nil, then Tramp is currently busy.
5380 Together with `tramp-locker', this implements a locking mechanism
5381 preventing reentrant calls of Tramp.")
5383 (defvar tramp-locker nil
5384 "If non-nil, then a caller has locked Tramp.
5385 Together with `tramp-locked', this implements a locking mechanism
5386 preventing reentrant calls of Tramp.")
5388 (defun tramp-sh-file-name-handler (operation &rest args)
5389 "Invoke remote-shell Tramp file name handler.
5390 Fall back to normal file name handler if no Tramp handler exists."
5391 (when (and tramp-locked (not tramp-locker))
5392 (setq tramp-locked nil)
5393 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5394 (let ((tl tramp-locked))
5397 (setq tramp-locked t)
5398 (let ((tramp-locker t))
5400 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5402 (apply (cdr fn) args)
5403 (tramp-run-real-handler operation args))))))
5404 (setq tramp-locked tl))))
5406 (defun tramp-vc-file-name-handler (operation &rest args)
5407 "Invoke special file name handler, which collects files to be handled."
5410 (tramp-replace-environment-variables
5411 (apply 'tramp-file-name-for-operation operation args)))
5412 (fn (assoc operation tramp-file-name-handler-alist)))
5413 (with-parsed-tramp-file-name filename nil
5415 ;; That's what we want: file names, for which checks are
5416 ;; applied. We assume, that VC uses only `file-exists-p' and
5417 ;; `file-readable-p' checks; otherwise we must extend the
5418 ;; list. We do not perform any action, but return nil, in
5419 ;; order to keep `vc-registered' running.
5420 ((and fn (memq operation '(file-exists-p file-readable-p)))
5421 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5423 ;; Tramp file name handlers like `expand-file-name'. They
5426 (save-match-data (apply (cdr fn) args)))
5427 ;; Default file name handlers, we don't care.
5428 (t (tramp-run-real-handler operation args)))))))
5431 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5432 "Invoke Tramp file name completion handler.
5433 Falls back to normal file name handler if no Tramp file name handler exists."
5434 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5435 ;; would otherwise use backslash.
5436 (let ((directory-sep-char ?/)
5437 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5439 ;; When `tramp-mode' is not enabled, we don't do anything.
5441 ;; For other syntaxes than `sep', the regexp matches many common
5442 ;; situations where the user doesn't actually want to use Tramp.
5443 ;; So to avoid autoloading Tramp after typing just "/s", we
5444 ;; disable this part of the completion, unless the user implicitly
5445 ;; indicated his interest in using a fancier completion system.
5446 (or (eq tramp-syntax 'sep)
5447 (featurep 'tramp) ; If it's loaded, we may as well use it.
5448 (and (boundp 'partial-completion-mode) partial-completion-mode)
5449 ;; FIXME: These may have been loaded even if the user never
5450 ;; intended to use them.
5452 (featurep 'icicles)))
5453 (save-match-data (apply (cdr fn) args))
5454 (tramp-completion-run-real-handler operation args)))))
5457 (progn (defun tramp-register-file-name-handlers ()
5458 "Add Tramp file name handlers to `file-name-handler-alist'."
5459 ;; Remove autoloaded handlers from file name handler alist. Useful,
5460 ;; if `tramp-syntax' has been changed.
5461 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5462 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5464 'tramp-completion-file-name-handler file-name-handler-alist)))
5465 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5466 ;; Add the handlers.
5467 (add-to-list 'file-name-handler-alist
5468 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5469 (add-to-list 'file-name-handler-alist
5470 (cons tramp-completion-file-name-regexp
5471 'tramp-completion-file-name-handler))
5472 (put 'tramp-completion-file-name-handler 'safe-magic t)
5473 ;; If jka-compr or epa-file are already loaded, move them to the
5474 ;; front of `file-name-handler-alist'.
5475 (dolist (fnh '(epa-file-handler jka-compr-handler))
5476 (let ((entry (rassoc fnh file-name-handler-alist)))
5478 (setq file-name-handler-alist
5479 (cons entry (delete entry file-name-handler-alist))))))))
5481 ;; `tramp-file-name-handler' must be registered before evaluation of
5482 ;; site-start and init files, because there might exist remote files
5483 ;; already, f.e. files kept via recentf-mode.
5484 ;;;###autoload(tramp-register-file-name-handlers)
5485 (tramp-register-file-name-handlers)
5488 (defun tramp-unload-file-name-handlers ()
5489 (setq file-name-handler-alist
5490 (delete (rassoc 'tramp-file-name-handler
5491 file-name-handler-alist)
5492 (delete (rassoc 'tramp-completion-file-name-handler
5493 file-name-handler-alist)
5494 file-name-handler-alist))))
5496 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5498 ;;; File name handler functions for completion mode:
5500 (defvar tramp-completion-mode nil
5501 "If non-nil, external packages signal that they are in file name completion.
5503 This is necessary, because Tramp uses a heuristic depending on last
5504 input event. This fails when external packages use other characters
5505 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5506 should never be set globally, the intention is to let-bind it.")
5508 ;; Necessary because `tramp-file-name-regexp-unified' and
5509 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5510 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5511 ;; to `tramp-file-name-handler'). Otherwise, it takes
5512 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5513 ;; risky, because completing a file might require loading other files,
5514 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5515 ;; variable. On the other hand, those files shouldn't have partial
5516 ;; Tramp file name syntax. Maybe another variable should be introduced
5517 ;; overwriting this check in such cases. Or we change Tramp file name
5518 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5519 (defun tramp-completion-mode-p ()
5520 "Checks whether method / user name / host name completion is active."
5522 ;; Signal from outside.
5523 tramp-completion-mode
5525 (equal last-input-event 'tab)
5526 (and (natnump last-input-event)
5528 ;; ?\t has event-modifier 'control.
5529 (equal last-input-event ?\t)
5530 (and (not (event-modifiers last-input-event))
5531 (or (equal last-input-event ?\?)
5532 (equal last-input-event ?\ )))))
5534 (and (featurep 'xemacs)
5535 ;; `last-input-event' might be nil.
5536 (not (null last-input-event))
5537 ;; `last-input-event' may have no character approximation.
5538 (funcall (symbol-function 'event-to-character) last-input-event)
5540 ;; ?\t has event-modifier 'control.
5542 (funcall (symbol-function 'event-to-character)
5543 last-input-event) ?\t)
5544 (and (not (event-modifiers last-input-event))
5546 (funcall (symbol-function 'event-to-character)
5547 last-input-event) ?\?)
5549 (funcall (symbol-function 'event-to-character)
5550 last-input-event) ?\ )))))))
5552 ;; Method, host name and user name completion.
5553 ;; `tramp-completion-dissect-file-name' returns a list of
5554 ;; tramp-file-name structures. For all of them we return possible completions.
5556 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5557 "Like `file-name-all-completions' for partial Tramp files."
5559 (let* ((fullname (tramp-drop-volume-letter
5560 (expand-file-name filename directory)))
5561 ;; Possible completion structures.
5562 (v (tramp-completion-dissect-file-name fullname))
5566 (let* ((car (car v))
5567 (method (tramp-file-name-method car))
5568 (user (tramp-file-name-user car))
5569 (host (tramp-file-name-host car))
5570 (localname (tramp-file-name-localname car))
5571 (m (tramp-find-method method user host))
5572 (tramp-current-user user) ; see `tramp-parse-passwd'
5575 (unless localname ;; Nothing to complete.
5579 ;; Method dependent user / host combinations.
5583 (setq all-user-hosts
5584 (append all-user-hosts
5585 (funcall (nth 0 x) (nth 1 x)))))
5586 (tramp-get-completion-function m))
5592 (tramp-get-completion-user-host
5593 method user host (nth 0 x) (nth 1 x)))
5594 (delq nil all-user-hosts)))))
5596 ;; Possible methods.
5598 (append result (tramp-get-completion-methods m)))))
5602 ;; Unify list, remove nil elements.
5604 (let ((car (car result)))
5608 (substring car (length (tramp-drop-volume-letter directory)))))
5609 (setq result (cdr result))))
5611 ;; Complete local parts.
5615 (tramp-completion-run-real-handler
5616 'file-name-all-completions (list filename directory))
5619 ;; Method, host name and user name completion for a file.
5621 (defun tramp-completion-handle-file-name-completion
5622 (filename directory &optional predicate)
5623 "Like `file-name-completion' for Tramp files."
5626 (mapcar 'list (file-name-all-completions filename directory))
5628 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5630 ;; I misuse a little bit the tramp-file-name structure in order to handle
5631 ;; completion possibilities for partial methods / user names / host names.
5632 ;; Return value is a list of tramp-file-name structures according to possible
5633 ;; completions. If "localname" is non-nil it means there
5634 ;; shouldn't be a completion anymore.
5636 ;; Expected results:
5638 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5639 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5640 ;; [nil "x" nil nil]
5641 ;; ["x" nil nil nil]
5643 ;; "/x:" "/x:y" "/x:y:"
5644 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5646 ;; ["x" nil "" nil] ["x" nil "y" nil]
5647 ;; ["x" "" nil nil] ["x" "y" nil nil]
5649 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5650 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5651 ;; "/[x/y@" "/[x/y@z"
5652 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5653 (defun tramp-completion-dissect-file-name (name)
5654 "Returns a list of `tramp-file-name' structures.
5655 They are collected by `tramp-completion-dissect-file-name1'."
5659 (tramp-completion-ipv6-regexp
5662 (if (zerop (length tramp-postfix-ipv6-format))
5663 tramp-postfix-host-format
5664 tramp-postfix-ipv6-format)))
5665 ;; "/method" "/[method"
5666 (tramp-completion-file-name-structure1
5667 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5670 (tramp-completion-file-name-structure2
5671 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5674 (tramp-completion-file-name-structure3
5675 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5677 ;; "/[ipv6" "/[ipv6"
5678 (tramp-completion-file-name-structure4
5679 (list (concat tramp-prefix-regexp
5680 tramp-prefix-ipv6-regexp
5681 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5683 ;; "/user@host" "/[user@host"
5684 (tramp-completion-file-name-structure5
5685 (list (concat tramp-prefix-regexp
5686 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5687 "\\(" tramp-host-regexp x-nil "\\)$")
5689 ;; "/user@[ipv6" "/[user@ipv6"
5690 (tramp-completion-file-name-structure6
5691 (list (concat tramp-prefix-regexp
5692 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5693 tramp-prefix-ipv6-regexp
5694 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5696 ;; "/method:user" "/[method/user" "/method://user"
5697 (tramp-completion-file-name-structure7
5698 (list (concat tramp-prefix-regexp
5699 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5700 "\\(" tramp-user-regexp x-nil "\\)$")
5702 ;; "/method:host" "/[method/host" "/method://host"
5703 (tramp-completion-file-name-structure8
5704 (list (concat tramp-prefix-regexp
5705 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5706 "\\(" tramp-host-regexp x-nil "\\)$")
5708 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5709 (tramp-completion-file-name-structure9
5710 (list (concat tramp-prefix-regexp
5711 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5712 tramp-prefix-ipv6-regexp
5713 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5715 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5716 (tramp-completion-file-name-structure10
5717 (list (concat tramp-prefix-regexp
5718 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5719 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5720 "\\(" tramp-host-regexp x-nil "\\)$")
5722 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5723 (tramp-completion-file-name-structure11
5724 (list (concat tramp-prefix-regexp
5725 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5726 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5727 tramp-prefix-ipv6-regexp
5728 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5730 ;; "/method: "/method:/"
5731 (tramp-completion-file-name-structure12
5733 (if (equal tramp-syntax 'url)
5734 (concat tramp-prefix-regexp
5735 "\\(" tramp-method-regexp "\\)"
5736 "\\(" (substring tramp-postfix-method-regexp 0 1)
5737 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5739 ;; Should not match if not URL syntax.
5740 (concat tramp-prefix-regexp "/$"))
5742 ;; "/method: "/method:/"
5743 (tramp-completion-file-name-structure13
5745 (if (equal tramp-syntax 'url)
5746 (concat tramp-prefix-regexp
5747 "\\(" tramp-method-regexp "\\)"
5748 "\\(" (substring tramp-postfix-method-regexp 0 1)
5749 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5751 ;; Should not match if not URL syntax.
5752 (concat tramp-prefix-regexp "/$"))
5755 (mapc (lambda (regexp)
5756 (add-to-list 'result
5757 (tramp-completion-dissect-file-name1 regexp name)))
5759 tramp-completion-file-name-structure1
5760 tramp-completion-file-name-structure2
5761 tramp-completion-file-name-structure3
5762 tramp-completion-file-name-structure4
5763 tramp-completion-file-name-structure5
5764 tramp-completion-file-name-structure6
5765 tramp-completion-file-name-structure7
5766 tramp-completion-file-name-structure8
5767 tramp-completion-file-name-structure9
5768 tramp-completion-file-name-structure10
5769 tramp-completion-file-name-structure11
5770 tramp-completion-file-name-structure12
5771 tramp-completion-file-name-structure13
5772 tramp-file-name-structure))
5776 (defun tramp-completion-dissect-file-name1 (structure name)
5777 "Returns a `tramp-file-name' structure matching STRUCTURE.
5778 The structure consists of remote method, remote user,
5779 remote host and localname (filename on remote host)."
5782 (when (string-match (nth 0 structure) name)
5783 (let ((method (and (nth 1 structure)
5784 (match-string (nth 1 structure) name)))
5785 (user (and (nth 2 structure)
5786 (match-string (nth 2 structure) name)))
5787 (host (and (nth 3 structure)
5788 (match-string (nth 3 structure) name)))
5789 (localname (and (nth 4 structure)
5790 (match-string (nth 4 structure) name))))
5791 (vector method user host localname)))))
5793 ;; This function returns all possible method completions, adding the
5794 ;; trailing method delimeter.
5795 (defun tramp-get-completion-methods (partial-method)
5796 "Returns all method completions for PARTIAL-METHOD."
5800 (string-match (concat "^" (regexp-quote partial-method)) method)
5801 (tramp-completion-make-tramp-file-name method nil nil nil)))
5802 (mapcar 'car tramp-methods)))
5804 ;; Compares partial user and host names with possible completions.
5805 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
5806 "Returns the most expanded string for user and host name completion.
5807 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5810 ((and partial-user partial-host)
5812 (string-match (concat "^" (regexp-quote partial-host)) host)
5813 (string-equal partial-user (or user partial-user)))
5814 (setq user partial-user)
5821 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5827 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5833 (unless (zerop (+ (length user) (length host)))
5834 (tramp-completion-make-tramp-file-name method user host nil)))
5836 (defun tramp-parse-rhosts (filename)
5837 "Return a list of (user host) tuples allowed to access.
5838 Either user or host may be nil."
5839 ;; On Windows, there are problems in completion when
5840 ;; `default-directory' is remote.
5841 (let ((default-directory (tramp-compat-temporary-file-directory))
5843 (when (file-readable-p filename)
5845 (insert-file-contents filename)
5846 (goto-char (point-min))
5848 (push (tramp-parse-rhosts-group) res))))
5851 (defun tramp-parse-rhosts-group ()
5852 "Return a (user host) tuple allowed to access.
5853 Either user or host may be nil."
5857 "^\\(" tramp-host-regexp "\\)"
5858 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5859 (narrow-to-region (point) (tramp-compat-line-end-position))
5860 (when (re-search-forward regexp nil t)
5861 (setq result (append (list (match-string 3) (match-string 1)))))
5866 (defun tramp-parse-shosts (filename)
5867 "Return a list of (user host) tuples allowed to access.
5868 User is always nil."
5869 ;; On Windows, there are problems in completion when
5870 ;; `default-directory' is remote.
5871 (let ((default-directory (tramp-compat-temporary-file-directory))
5873 (when (file-readable-p filename)
5875 (insert-file-contents filename)
5876 (goto-char (point-min))
5878 (push (tramp-parse-shosts-group) res))))
5881 (defun tramp-parse-shosts-group ()
5882 "Return a (user host) tuple allowed to access.
5883 User is always nil."
5885 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
5886 (narrow-to-region (point) (tramp-compat-line-end-position))
5887 (when (re-search-forward regexp nil t)
5888 (setq result (list nil (match-string 1))))
5891 (> (skip-chars-forward ",") 0)
5895 (defun tramp-parse-sconfig (filename)
5896 "Return a list of (user host) tuples allowed to access.
5897 User is always nil."
5898 ;; On Windows, there are problems in completion when
5899 ;; `default-directory' is remote.
5900 (let ((default-directory (tramp-compat-temporary-file-directory))
5902 (when (file-readable-p filename)
5904 (insert-file-contents filename)
5905 (goto-char (point-min))
5907 (push (tramp-parse-sconfig-group) res))))
5910 (defun tramp-parse-sconfig-group ()
5911 "Return a (user host) tuple allowed to access.
5912 User is always nil."
5914 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
5915 (narrow-to-region (point) (tramp-compat-line-end-position))
5916 (when (re-search-forward regexp nil t)
5917 (setq result (list nil (match-string 1))))
5920 (> (skip-chars-forward ",") 0)
5924 (defun tramp-parse-shostkeys (dirname)
5925 "Return a list of (user host) tuples allowed to access.
5926 User is always nil."
5927 ;; On Windows, there are problems in completion when
5928 ;; `default-directory' is remote.
5929 (let* ((default-directory (tramp-compat-temporary-file-directory))
5930 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
5931 (files (when (file-directory-p dirname) (directory-files dirname)))
5934 (when (string-match regexp (car files))
5935 (push (list nil (match-string 1 (car files))) result))
5936 (setq files (cdr files)))
5939 (defun tramp-parse-sknownhosts (dirname)
5940 "Return a list of (user host) tuples allowed to access.
5941 User is always nil."
5942 ;; On Windows, there are problems in completion when
5943 ;; `default-directory' is remote.
5944 (let* ((default-directory (tramp-compat-temporary-file-directory))
5945 (regexp (concat "^\\(" tramp-host-regexp
5946 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
5947 (files (when (file-directory-p dirname) (directory-files dirname)))
5950 (when (string-match regexp (car files))
5951 (push (list nil (match-string 1 (car files))) result))
5952 (setq files (cdr files)))
5955 (defun tramp-parse-hosts (filename)
5956 "Return a list of (user host) tuples allowed to access.
5957 User is always nil."
5958 ;; On Windows, there are problems in completion when
5959 ;; `default-directory' is remote.
5960 (let ((default-directory (tramp-compat-temporary-file-directory))
5962 (when (file-readable-p filename)
5964 (insert-file-contents filename)
5965 (goto-char (point-min))
5967 (push (tramp-parse-hosts-group) res))))
5970 (defun tramp-parse-hosts-group ()
5971 "Return a (user host) tuple allowed to access.
5972 User is always nil."
5975 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
5976 (narrow-to-region (point) (tramp-compat-line-end-position))
5977 (when (re-search-forward regexp nil t)
5978 (setq result (list nil (match-string 1))))
5981 (> (skip-chars-forward " \t") 0)
5985 ;; For su-alike methods it would be desirable to return "root@localhost"
5986 ;; as default. Unfortunately, we have no information whether any user name
5987 ;; has been typed already. So we use `tramp-current-user' as indication,
5988 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
5989 (defun tramp-parse-passwd (filename)
5990 "Return a list of (user host) tuples allowed to access.
5991 Host is always \"localhost\"."
5992 ;; On Windows, there are problems in completion when
5993 ;; `default-directory' is remote.
5994 (let ((default-directory (tramp-compat-temporary-file-directory))
5996 (if (zerop (length tramp-current-user))
5998 (when (file-readable-p filename)
6000 (insert-file-contents filename)
6001 (goto-char (point-min))
6003 (push (tramp-parse-passwd-group) res))))
6006 (defun tramp-parse-passwd-group ()
6007 "Return a (user host) tuple allowed to access.
6008 Host is always \"localhost\"."
6010 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6011 (narrow-to-region (point) (tramp-compat-line-end-position))
6012 (when (re-search-forward regexp nil t)
6013 (setq result (list (match-string 1) "localhost")))
6018 (defun tramp-parse-netrc (filename)
6019 "Return a list of (user host) tuples allowed to access.
6021 ;; On Windows, there are problems in completion when
6022 ;; `default-directory' is remote.
6023 (let ((default-directory (tramp-compat-temporary-file-directory))
6025 (when (file-readable-p filename)
6027 (insert-file-contents filename)
6028 (goto-char (point-min))
6030 (push (tramp-parse-netrc-group) res))))
6033 (defun tramp-parse-netrc-group ()
6034 "Return a (user host) tuple allowed to access.
6039 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6040 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6041 (narrow-to-region (point) (tramp-compat-line-end-position))
6042 (when (re-search-forward regexp nil t)
6043 (setq result (list (match-string 3) (match-string 1))))
6048 (defun tramp-parse-putty (registry)
6049 "Return a list of (user host) tuples allowed to access.
6050 User is always nil."
6051 ;; On Windows, there are problems in completion when
6052 ;; `default-directory' is remote.
6053 (let ((default-directory (tramp-compat-temporary-file-directory))
6056 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6057 (goto-char (point-min))
6059 (push (tramp-parse-putty-group registry) res))))
6062 (defun tramp-parse-putty-group (registry)
6063 "Return a (user host) tuple allowed to access.
6064 User is always nil."
6066 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6067 (narrow-to-region (point) (tramp-compat-line-end-position))
6068 (when (re-search-forward regexp nil t)
6069 (setq result (list nil (match-string 1))))
6074 ;;; Internal Functions:
6076 (defun tramp-maybe-send-script (vec script name)
6077 "Define in remote shell function NAME implemented as SCRIPT.
6078 Only send the definition if it has not already been done."
6079 (let* ((p (tramp-get-connection-process vec))
6080 (scripts (tramp-get-connection-property p "scripts" nil)))
6081 (unless (member name scripts)
6082 (tramp-message vec 5 "Sending script `%s'..." name)
6083 ;; The script could contain a call of Perl. This is masked with `%s'.
6084 (tramp-send-command-and-check
6086 (format "%s () {\n%s\n}" name
6087 (format script (tramp-get-remote-perl vec))))
6088 (tramp-set-connection-property p "scripts" (cons name scripts))
6089 (tramp-message vec 5 "Sending script `%s'...done." name))))
6091 (defun tramp-set-auto-save ()
6092 (when (and ;; ange-ftp has its own auto-save mechanism
6093 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6094 'tramp-sh-file-name-handler)
6096 (auto-save-mode 1)))
6097 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6098 (add-hook 'tramp-unload-hook
6100 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6102 (defun tramp-run-test (switch filename)
6103 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6104 Returns the exit code of the `test' program."
6105 (with-parsed-tramp-file-name filename nil
6106 (tramp-send-command-and-check
6110 (tramp-get-test-command v)
6112 (tramp-shell-quote-argument localname)))))
6114 (defun tramp-run-test2 (format-string file1 file2)
6115 "Run `test'-like program on the remote system, given FILE1, FILE2.
6116 FORMAT-STRING contains the program name, switches, and place holders.
6117 Returns the exit code of the `test' program. Barfs if the methods,
6118 hosts, or files, disagree."
6119 (unless (tramp-equal-remote file1 file2)
6120 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6123 "tramp-run-test2 only implemented for same method, user, host")))
6124 (with-parsed-tramp-file-name file1 v1
6125 (with-parsed-tramp-file-name file1 v2
6126 (tramp-send-command-and-check
6128 (format format-string
6129 (tramp-shell-quote-argument v1-localname)
6130 (tramp-shell-quote-argument v2-localname))))))
6132 (defun tramp-buffer-name (vec)
6133 "A name for the connection buffer VEC."
6134 ;; We must use `tramp-file-name-real-host', because for gateway
6135 ;; methods the default port will be expanded later on, which would
6137 (let ((method (tramp-file-name-method vec))
6138 (user (tramp-file-name-user vec))
6139 (host (tramp-file-name-real-host vec)))
6140 (if (not (zerop (length user)))
6141 (format "*tramp/%s %s@%s*" method user host)
6142 (format "*tramp/%s %s*" method host))))
6144 (defun tramp-delete-temp-file-function ()
6145 "Remove temporary files related to current buffer."
6146 (when (stringp tramp-temp-buffer-file-name)
6148 (delete-file tramp-temp-buffer-file-name)
6151 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6152 (add-hook 'tramp-cache-unload-hook
6154 (remove-hook 'kill-buffer-hook
6155 'tramp-delete-temp-file-function)))
6157 (defun tramp-get-buffer (vec)
6158 "Get the connection buffer to be used for VEC."
6159 (or (get-buffer (tramp-buffer-name vec))
6160 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6161 (setq buffer-undo-list t)
6162 (setq default-directory
6163 (tramp-make-tramp-file-name
6164 (tramp-file-name-method vec)
6165 (tramp-file-name-user vec)
6166 (tramp-file-name-host vec)
6170 (defun tramp-get-connection-buffer (vec)
6171 "Get the connection buffer to be used for VEC.
6172 In case a second asynchronous communication has been started, it is different
6173 from `tramp-get-buffer'."
6174 (or (tramp-get-connection-property vec "process-buffer" nil)
6175 (tramp-get-buffer vec)))
6177 (defun tramp-get-connection-process (vec)
6178 "Get the connection process to be used for VEC.
6179 In case a second asynchronous communication has been started, it is different
6180 from the default one."
6182 (or (tramp-get-connection-property vec "process-name" nil)
6183 (tramp-buffer-name vec))))
6185 (defun tramp-debug-buffer-name (vec)
6186 "A name for the debug buffer for VEC."
6187 ;; We must use `tramp-file-name-real-host', because for gateway
6188 ;; methods the default port will be expanded later on, which would
6190 (let ((method (tramp-file-name-method vec))
6191 (user (tramp-file-name-user vec))
6192 (host (tramp-file-name-real-host vec)))
6193 (if (not (zerop (length user)))
6194 (format "*debug tramp/%s %s@%s*" method user host)
6195 (format "*debug tramp/%s %s*" method host))))
6197 (defun tramp-get-debug-buffer (vec)
6198 "Get the debug buffer for VEC."
6199 (with-current-buffer
6200 (get-buffer-create (tramp-debug-buffer-name vec))
6202 (setq buffer-undo-list t)
6203 ;; Activate outline-mode. This runs `text-mode-hook' and
6204 ;; `outline-mode-hook'. We must prevent that local processes
6205 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
6207 (let ((default-directory (tramp-compat-temporary-file-directory)))
6209 (set (make-local-variable 'outline-regexp)
6210 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6211 ; (set (make-local-variable 'outline-regexp)
6212 ; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
6213 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6216 (defun tramp-outline-level ()
6217 "Return the depth to which a statement is nested in the outline.
6218 Point must be at the beginning of a header line.
6220 The outline level is equal to the verbosity of the Tramp message."
6221 (1+ (string-to-number (match-string 1))))
6223 (defun tramp-find-executable
6224 (vec progname dirlist &optional ignore-tilde ignore-path)
6225 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6226 First arg VEC specifies the connection, PROGNAME is the program
6227 to search for, and DIRLIST gives the list of directories to
6228 search. If IGNORE-TILDE is non-nil, directory names starting
6229 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6232 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6234 This function expects to be in the right *tramp* buffer."
6235 (with-current-buffer (tramp-get-buffer vec)
6237 ;; Check whether the executable is in $PATH. "which(1)" does not
6238 ;; report always a correct error code; therefore we check the
6239 ;; number of words it returns.
6241 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6242 (goto-char (point-min))
6243 (if (looking-at "^1$")
6244 (setq result (concat "\\" progname))))
6247 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
6248 ;; `remove' is in CL, and we want to avoid CL dependencies.
6251 (setq d (car dirlist))
6252 (setq dirlist (cdr dirlist))
6253 (unless (char-equal ?~ (aref d 0))
6254 (setq newdl (cons d newdl))))
6255 (setq dirlist (nreverse newdl))))
6258 (format (concat "while read d; "
6259 "do if test -x $d/%s -a -f $d/%s; "
6260 "then echo tramp_executable $d/%s; "
6261 "break; fi; done <<'EOF'\n"
6263 progname progname progname (mapconcat 'identity dirlist "\n")))
6264 (goto-char (point-max))
6265 (when (search-backward "tramp_executable " nil t)
6266 (skip-chars-forward "^ ")
6267 (skip-chars-forward " ")
6268 (setq result (buffer-substring
6269 (point) (tramp-compat-line-end-position)))))
6272 (defun tramp-set-remote-path (vec)
6273 "Sets the remote environment PATH to existing directories.
6274 I.e., for each directory in `tramp-remote-path', it is tested
6275 whether it exists and if so, it is added to the environment
6277 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6279 vec (format "PATH=%s; export PATH"
6280 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6282 ;; ------------------------------------------------------------
6283 ;; -- Communication with external shell --
6284 ;; ------------------------------------------------------------
6286 (defun tramp-find-file-exists-command (vec)
6287 "Find a command on the remote host for checking if a file exists.
6288 Here, we are looking for a command which has zero exit status if the
6289 file exists and nonzero exit status otherwise."
6290 (let ((existing "/")
6292 (tramp-shell-quote-argument "/ this file does not exist "))
6294 ;; The algorithm is as follows: we try a list of several commands.
6295 ;; For each command, we first run `$cmd /' -- this should return
6296 ;; true, as the root directory always exists. And then we run
6297 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6298 ;; does not exist. This should return false. We use the first
6299 ;; command we find that seems to work.
6300 ;; The list of commands to try is as follows:
6301 ;; `ls -d' This works on most systems, but NetBSD 1.4
6302 ;; has a bug: `ls' always returns zero exit
6303 ;; status, even for files which don't exist.
6304 ;; `test -e' Some Bourne shells have a `test' builtin
6305 ;; which does not know the `-e' option.
6306 ;; `/bin/test -e' For those, the `test' binary on disk normally
6307 ;; provides the option. Alas, the binary
6308 ;; is sometimes `/bin/test' and sometimes it's
6310 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6312 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6313 (zerop (tramp-send-command-and-check
6314 vec (format "%s %s" result existing)))
6315 (not (zerop (tramp-send-command-and-check
6316 vec (format "%s %s" result nonexisting)))))
6317 (and (setq result "/bin/test -e")
6318 (zerop (tramp-send-command-and-check
6319 vec (format "%s %s" result existing)))
6320 (not (zerop (tramp-send-command-and-check
6321 vec (format "%s %s" result nonexisting)))))
6322 (and (setq result "/usr/bin/test -e")
6323 (zerop (tramp-send-command-and-check
6324 vec (format "%s %s" result existing)))
6325 (not (zerop (tramp-send-command-and-check
6326 vec (format "%s %s" result nonexisting)))))
6327 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6328 (zerop (tramp-send-command-and-check
6329 vec (format "%s %s" result existing)))
6330 (not (zerop (tramp-send-command-and-check
6331 vec (format "%s %s" result nonexisting))))))
6333 vec 'file-error "Couldn't find command to check if file exists"))
6336 ;; CCC test ksh or bash found for tilde expansion?
6337 (defun tramp-find-shell (vec)
6338 "Opens a shell on the remote host which groks tilde expansion."
6339 (unless (tramp-get-connection-property vec "remote-shell" nil)
6341 (with-current-buffer (tramp-get-buffer vec)
6342 (tramp-send-command vec "echo ~root" t)
6344 ((string-match "^~root$" (buffer-string))
6346 (or (tramp-find-executable
6347 vec "bash" (tramp-get-remote-path vec) t)
6348 (tramp-find-executable
6349 vec "ksh" (tramp-get-remote-path vec) t)))
6353 "Couldn't find a shell which groks tilde expansion"))
6354 ;; Find arguments for this shell.
6355 (let ((alist tramp-sh-extra-args)
6357 (while (and alist (null extra-args))
6358 (setq item (pop alist))
6359 (when (string-match (car item) shell)
6360 (setq extra-args (cdr item))))
6361 (when extra-args (setq shell (concat shell " " extra-args))))
6363 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
6364 (let ((tramp-end-of-output tramp-initial-end-of-output))
6367 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6368 (shell-quote-argument tramp-end-of-output) shell)
6371 (tramp-message vec 5 "Setting remote shell prompt...")
6373 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6374 (tramp-send-command vec "PS2=''" t)
6375 (tramp-send-command vec "PS3=''" t)
6376 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6377 (tramp-message vec 5 "Setting remote shell prompt...done"))
6380 vec 5 "Remote `%s' groks tilde expansion, good"
6381 (tramp-get-method-parameter
6382 (tramp-file-name-method vec) 'tramp-remote-sh))
6383 (tramp-set-connection-property
6385 (tramp-get-method-parameter
6386 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
6388 ;; ------------------------------------------------------------
6389 ;; -- Functions for establishing connection --
6390 ;; ------------------------------------------------------------
6392 ;; The following functions are actions to be taken when seeing certain
6393 ;; prompts from the remote host. See the variable
6394 ;; `tramp-actions-before-shell' for usage of these functions.
6396 (defun tramp-action-login (proc vec)
6397 "Send the login name."
6398 (when (not (stringp tramp-current-user))
6399 (save-window-excursion
6400 (let ((enable-recursive-minibuffers t))
6401 (pop-to-buffer (tramp-get-connection-buffer vec))
6402 (setq tramp-current-user (read-string (match-string 0))))))
6403 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6404 (with-current-buffer (tramp-get-connection-buffer vec)
6405 (tramp-message vec 6 "\n%s" (buffer-string)))
6406 (tramp-send-string vec tramp-current-user))
6408 (defun tramp-action-password (proc vec)
6409 "Query the user for a password."
6410 (with-current-buffer (process-buffer proc)
6411 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6412 (tramp-message vec 3 "Sending %s" (match-string 1)))
6413 (tramp-enter-password proc))
6415 (defun tramp-action-succeed (proc vec)
6416 "Signal success in finding shell prompt."
6417 (throw 'tramp-action 'ok))
6419 (defun tramp-action-permission-denied (proc vec)
6420 "Signal permission denied."
6422 (throw 'tramp-action 'permission-denied))
6424 (defun tramp-action-yesno (proc vec)
6425 "Ask the user for confirmation using `yes-or-no-p'.
6426 Send \"yes\" to remote process on confirmation, abort otherwise.
6427 See also `tramp-action-yn'."
6428 (save-window-excursion
6429 (let ((enable-recursive-minibuffers t))
6430 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6431 (unless (yes-or-no-p (match-string 0))
6433 (throw 'tramp-action 'permission-denied))
6434 (with-current-buffer (tramp-get-connection-buffer vec)
6435 (tramp-message vec 6 "\n%s" (buffer-string)))
6436 (tramp-send-string vec "yes"))))
6438 (defun tramp-action-yn (proc vec)
6439 "Ask the user for confirmation using `y-or-n-p'.
6440 Send \"y\" to remote process on confirmation, abort otherwise.
6441 See also `tramp-action-yesno'."
6442 (save-window-excursion
6443 (let ((enable-recursive-minibuffers t))
6444 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6445 (unless (y-or-n-p (match-string 0))
6447 (throw 'tramp-action 'permission-denied))
6448 (with-current-buffer (tramp-get-connection-buffer vec)
6449 (tramp-message vec 6 "\n%s" (buffer-string)))
6450 (tramp-send-string vec "y"))))
6452 (defun tramp-action-terminal (proc vec)
6453 "Tell the remote host which terminal type to use.
6454 The terminal type can be configured with `tramp-terminal-type'."
6455 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6456 (with-current-buffer (tramp-get-connection-buffer vec)
6457 (tramp-message vec 6 "\n%s" (buffer-string)))
6458 (tramp-send-string vec tramp-terminal-type))
6460 (defun tramp-action-process-alive (proc vec)
6461 "Check whether a process has finished."
6462 (unless (memq (process-status proc) '(run open))
6463 (throw 'tramp-action 'process-died)))
6465 (defun tramp-action-out-of-band (proc vec)
6466 "Check whether an out-of-band copy has finished."
6467 (cond ((and (memq (process-status proc) '(stop exit))
6468 (zerop (process-exit-status proc)))
6469 (tramp-message vec 3 "Process has finished.")
6470 (throw 'tramp-action 'ok))
6471 ((or (and (memq (process-status proc) '(stop exit))
6472 (not (zerop (process-exit-status proc))))
6473 (memq (process-status proc) '(signal)))
6474 ;; `scp' could have copied correctly, but set modes could have failed.
6475 ;; This can be ignored.
6476 (with-current-buffer (process-buffer proc)
6477 (goto-char (point-min))
6478 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6480 (tramp-message vec 5 "'set mode' error ignored.")
6481 (tramp-message vec 3 "Process has finished.")
6482 (throw 'tramp-action 'ok))
6483 (tramp-message vec 3 "Process has died.")
6484 (throw 'tramp-action 'process-died))))
6487 ;; Functions for processing the actions.
6489 (defun tramp-process-one-action (proc vec actions)
6490 "Wait for output from the shell and perform one action."
6491 (let (found todo item pattern action)
6493 ;; Reread output once all actions have been performed.
6494 ;; Obviously, the output was not complete.
6495 (tramp-accept-process-output proc 1)
6498 (setq item (pop todo))
6499 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6500 (setq action (nth 1 item))
6502 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6503 (when (tramp-check-for-regexp proc pattern)
6504 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6505 (setq found (funcall action proc vec)))))
6508 (defun tramp-process-actions (proc vec actions &optional timeout)
6509 "Perform actions until success or TIMEOUT."
6510 ;; Enable auth-source and password-cache.
6511 (tramp-set-connection-property proc "first-password-request" t)
6514 (tramp-message proc 3 "Waiting for prompts from remote shell")
6516 (catch 'tramp-action
6518 (with-timeout (timeout)
6519 (tramp-process-one-action proc vec actions))
6520 (tramp-process-one-action proc vec actions)))))
6521 (with-current-buffer (tramp-get-connection-buffer vec)
6522 (tramp-message vec 6 "\n%s" (buffer-string)))
6523 (unless (eq exit 'ok)
6524 (tramp-clear-passwd vec)
6525 (tramp-error-with-buffer
6528 ((eq exit 'permission-denied) "Permission denied")
6529 ((eq exit 'process-died) "Process died")
6530 (t "Login failed"))))))
6532 ;; Utility functions.
6534 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6535 "Like `accept-process-output' for Tramp processes.
6536 This is needed in order to hide `last-coding-system-used', which is set
6537 for process communication also."
6538 (with-current-buffer (process-buffer proc)
6539 (tramp-message proc 10 "%s %s" proc (process-status proc))
6540 (let (buffer-read-only last-coding-system-used)
6541 ;; Under Windows XP, accept-process-output doesn't return
6542 ;; sometimes. So we add an additional timeout.
6543 (with-timeout ((or timeout 1))
6544 (accept-process-output proc timeout timeout-msecs)))
6545 (tramp-message proc 10 "\n%s" (buffer-string))))
6547 (defun tramp-check-for-regexp (proc regexp)
6548 "Check whether REGEXP is contained in process buffer of PROC.
6549 Erase echoed commands if exists."
6550 (with-current-buffer (process-buffer proc)
6551 (goto-char (point-min))
6553 ;; Check whether we need to remove echo output.
6554 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6555 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6556 (let ((begin (match-beginning 0)))
6557 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6558 ;; Discard echo from remote output.
6559 (tramp-set-connection-property proc "check-remote-echo" nil)
6560 (tramp-message proc 5 "echo-mark found")
6562 (delete-region begin (point))
6563 (goto-char (point-min)))))
6565 (when (not (tramp-get-connection-property proc "check-remote-echo" nil))
6566 ;; No echo to be handled, now we can look for the regexp.
6567 (goto-char (point-min))
6568 (re-search-forward regexp nil t))))
6570 (defun tramp-wait-for-regexp (proc timeout regexp)
6571 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6572 Expects the output of PROC to be sent to the current buffer. Returns
6573 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6575 (with-current-buffer (process-buffer proc)
6576 (let ((found (tramp-check-for-regexp proc regexp))
6577 (start-time (current-time)))
6579 ;; Work around a bug in XEmacs 21, where the timeout
6580 ;; expires faster than it should. This degenerates
6581 ;; to polling for buggy XEmacsen, but oh, well.
6582 (while (and (not found)
6583 (< (tramp-time-diff (current-time) start-time)
6585 (with-timeout (timeout)
6587 (tramp-accept-process-output proc 1)
6588 (unless (memq (process-status proc) '(run open))
6589 (tramp-error-with-buffer
6590 nil proc 'file-error "Process has died"))
6591 (setq found (tramp-check-for-regexp proc regexp))))))
6594 (tramp-accept-process-output proc 1)
6595 (unless (memq (process-status proc) '(run open))
6596 (tramp-error-with-buffer
6597 nil proc 'file-error "Process has died"))
6598 (setq found (tramp-check-for-regexp proc regexp)))))
6599 (tramp-message proc 6 "\n%s" (buffer-string))
6603 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6605 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6608 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6609 "Wait for shell prompt and barf if none appears.
6610 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6611 seconds. If not, it produces an error message with the given ERROR-ARGS."
6613 (tramp-wait-for-regexp
6616 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6617 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6619 ;; We don't call `tramp-send-string' in order to hide the password
6620 ;; from the debug buffer, and because end-of-line handling of the
6622 (defun tramp-enter-password (proc)
6623 "Prompt for a password and send it to the remote end."
6624 (process-send-string
6625 proc (concat (tramp-read-passwd proc)
6626 (or (tramp-get-method-parameter
6627 tramp-current-method
6628 'tramp-password-end-of-line)
6629 tramp-default-password-end-of-line))))
6631 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6632 "Set up an interactive shell.
6633 Mainly sets the prompt and the echo correctly. PROC is the shell
6634 process to set up. VEC specifies the connection."
6635 (let ((tramp-end-of-output tramp-initial-end-of-output))
6636 ;; It is useful to set the prompt in the following command because
6637 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6638 ;; about and thus /bin/sh will display a strange prompt. For
6639 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6640 ;; display the current working directory but /bin/sh will display
6641 ;; a dollar sign. The following command line sets $PS1 to a sane
6642 ;; value, and works under Bourne-ish shells as well as csh-like
6643 ;; shells. Daniel Pittman reports that the unusual positioning of
6644 ;; the single quotes makes it work under `rc', too. We also unset
6645 ;; the variable $ENV because that is read by some sh
6646 ;; implementations (eg, bash when called as sh) on startup; this
6647 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6648 ;; is another way to set the prompt in /bin/bash, it must be
6649 ;; discarded as well.
6653 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6654 (shell-quote-argument tramp-end-of-output)
6655 (tramp-get-method-parameter
6656 (tramp-file-name-method vec) 'tramp-remote-sh))
6660 (tramp-message vec 5 "Setting up remote shell environment")
6661 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6662 ;; Check whether the echo has really been disabled. Some
6663 ;; implementations, like busybox of embedded GNU/Linux, don't
6664 ;; support disabling.
6665 (tramp-send-command vec "echo foo" t)
6666 (with-current-buffer (process-buffer proc)
6667 (goto-char (point-min))
6668 (when (looking-at "echo foo")
6669 (tramp-set-connection-property proc "remote-echo" t)
6670 (tramp-message vec 5 "Remote echo still on. Ok.")
6671 ;; Make sure backspaces and their echo are enabled and no line
6672 ;; width magic interferes with them.
6673 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6675 (tramp-message vec 5 "Setting shell prompt")
6677 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6678 (tramp-send-command vec "PS2=''" t)
6679 (tramp-send-command vec "PS3=''" t)
6680 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6682 ;; Try to set up the coding system correctly.
6683 ;; CCC this can't be the right way to do it. Hm.
6684 (tramp-message vec 5 "Determining coding system")
6685 (tramp-send-command vec "echo foo ; echo bar" t)
6686 (with-current-buffer (process-buffer proc)
6687 (goto-char (point-min))
6688 (if (featurep 'mule)
6689 ;; Use MULE to select the right EOL convention for communicating
6690 ;; with the process.
6691 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
6692 (cons 'undecided 'undecided)))
6693 cs-decode cs-encode)
6694 (when (symbolp cs) (setq cs (cons cs cs)))
6695 (setq cs-decode (car cs))
6696 (setq cs-encode (cdr cs))
6697 (unless cs-decode (setq cs-decode 'undecided))
6698 (unless cs-encode (setq cs-encode 'undecided))
6699 (setq cs-encode (tramp-coding-system-change-eol-conversion
6701 (when (search-forward "\r" nil t)
6702 (setq cs-decode (tramp-coding-system-change-eol-conversion
6704 (funcall (symbol-function 'set-buffer-process-coding-system)
6705 cs-decode cs-encode)
6707 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6708 ;; Look for ^M and do something useful if found.
6709 (when (search-forward "\r" nil t)
6710 ;; We have found a ^M but cannot frob the process coding system
6711 ;; because we're running on a non-MULE Emacs. Let's try
6713 (tramp-send-command vec "stty -onlcr" t))))
6714 (tramp-send-command vec "set +o vi +o emacs" t)
6716 ;; Check whether the output of "uname -sr" has been changed. If
6717 ;; yes, this is a strong indication that we must expire all
6718 ;; connection properties. We start again with
6719 ;; `tramp-maybe-open-connection', it will be catched there.
6720 (tramp-message vec 5 "Checking system information")
6721 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6723 (tramp-set-connection-property
6725 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6726 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
6727 (with-current-buffer (tramp-get-debug-buffer vec)
6728 ;; Keep the debug buffer
6730 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
6731 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6732 (if (= (point-min) (point-max))
6734 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6735 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6736 (tramp-get-buffer vec)
6739 "Connection reset, because remote host changed from `%s' to `%s'"
6740 old-uname new-uname)
6741 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
6743 ;; Check whether the remote host suffers from buggy
6744 ;; `send-process-string'. This is known for FreeBSD (see comment in
6745 ;; `send_process', file process.c). I've tested sending 624 bytes
6746 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6747 ;; this host type is detected locally. It cannot handle remote
6749 (with-connection-property proc "chunksize"
6751 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6755 vec 5 "Checking remote host type for `send-process-string' bug")
6757 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
6760 ;; Set remote PATH variable.
6761 (tramp-set-remote-path vec)
6763 ;; Search for a good shell before searching for a command which
6764 ;; checks if a file exists. This is done because Tramp wants to use
6765 ;; "test foo; echo $?" to check if various conditions hold, and
6766 ;; there are buggy /bin/sh implementations which don't execute the
6767 ;; "echo $?" part if the "test" part has an error. In particular,
6768 ;; the Solaris /bin/sh is a problem. I'm betting that all systems
6769 ;; with buggy /bin/sh implementations will have a working bash or
6771 (tramp-find-shell vec)
6773 ;; Disable unexpected output.
6774 (tramp-send-command vec "mesg n; biff n" t)
6776 ;; Set the environment.
6777 (tramp-message vec 5 "Setting default environment")
6779 ;; On OpenSolaris, there is a bug when HISTFILE is changed in place
6780 ;; <http://bugs.opensolaris.org/view_bug.do?bug_id=6834184>. We
6781 ;; apply the workaround.
6782 (if (string-equal (tramp-get-connection-property vec "uname" "") "SunOS 5.11")
6783 (tramp-send-command vec "unset HISTFILE"))
6785 (let ((env (copy-sequence tramp-remote-process-environment))
6788 (setq item (tramp-compat-split-string (car env) "="))
6789 (if (and (stringp (cadr item)) (not (string-equal (cadr item) "")))
6791 vec (format "%s=%s; export %s" (car item) (cadr item) (car item)) t)
6792 (push (car item) unset))
6793 (setq env (cdr env)))
6796 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
6798 ;; CCC: We should either implement a Perl version of base64 encoding
6799 ;; and decoding. Then we just use that in the last item. The other
6800 ;; alternative is to use the Perl version of UU encoding. But then
6801 ;; we need a Lisp version of uuencode.
6803 ;; Old text from documentation of tramp-methods:
6804 ;; Using a uuencode/uudecode inline method is discouraged, please use one
6805 ;; of the base64 methods instead since base64 encoding is much more
6806 ;; reliable and the commands are more standardized between the different
6807 ;; Unix versions. But if you can't use base64 for some reason, please
6808 ;; note that the default uudecode command does not work well for some
6809 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
6810 ;; the following command for uudecode:
6812 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6814 ;; For Irix, no solution is known yet.
6816 (defconst tramp-local-coding-commands
6817 '((b64 base64-encode-region base64-decode-region)
6818 (uu tramp-uuencode-region uudecode-decode-region)
6820 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6821 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6822 "List of local coding commands for inline transfer.
6823 Each item is a list that looks like this:
6825 \(FORMAT ENCODING DECODING)
6827 FORMAT is symbol describing the encoding/decoding format. It can be
6828 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6830 ENCODING and DECODING can be strings, giving commands, or symbols,
6831 giving functions. If they are strings, then they can contain
6832 the \"%s\" format specifier. If that specifier is present, the input
6833 filename will be put into the command line at that spot. If the
6834 specifier is not present, the input should be read from standard
6837 If they are functions, they will be called with two arguments, start
6838 and end of region, and are expected to replace the region contents
6839 with the encoded or decoded results, respectively.")
6841 (defconst tramp-remote-coding-commands
6842 '((b64 "base64" "base64 -d")
6843 (b64 "mimencode -b" "mimencode -u -b")
6844 (b64 "mmencode -b" "mmencode -u -b")
6845 (b64 "recode data..base64" "recode base64..data")
6846 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6847 (b64 tramp-perl-encode tramp-perl-decode)
6848 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6849 (uu "uuencode xxx" "uudecode -o -")
6850 (uu "uuencode xxx" "uudecode -p")
6851 (uu "uuencode xxx" tramp-uudecode)
6853 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6854 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6855 "List of remote coding commands for inline transfer.
6856 Each item is a list that looks like this:
6858 \(FORMAT ENCODING DECODING)
6860 FORMAT is symbol describing the encoding/decoding format. It can be
6861 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6863 ENCODING and DECODING can be strings, giving commands, or symbols,
6864 giving variables. If they are strings, then they can contain
6865 the \"%s\" format specifier. If that specifier is present, the input
6866 filename will be put into the command line at that spot. If the
6867 specifier is not present, the input should be read from standard
6870 If they are variables, this variable is a string containing a Perl
6871 implementation for this functionality. This Perl program will be transferred
6872 to the remote host, and it is avalible as shell function with the same name.")
6874 (defun tramp-find-inline-encoding (vec)
6875 "Find an inline transfer encoding that works.
6876 Goes through the list `tramp-local-coding-commands' and
6877 `tramp-remote-coding-commands'."
6879 (let ((local-commands tramp-local-coding-commands)
6881 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6882 (while (and local-commands (not found))
6883 (setq litem (pop local-commands))
6884 (catch 'wont-work-local
6885 (let ((format (nth 0 litem))
6886 (remote-commands tramp-remote-coding-commands))
6887 (setq loc-enc (nth 1 litem))
6888 (setq loc-dec (nth 2 litem))
6889 ;; If the local encoder or decoder is a string, the
6890 ;; corresponding command has to work locally.
6891 (if (not (stringp loc-enc))
6893 vec 5 "Checking local encoding function `%s'" loc-enc)
6895 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6896 (unless (zerop (tramp-call-local-coding-command
6898 (throw 'wont-work-local nil)))
6899 (if (not (stringp loc-dec))
6901 vec 5 "Checking local decoding function `%s'" loc-dec)
6903 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
6904 (unless (zerop (tramp-call-local-coding-command
6906 (throw 'wont-work-local nil)))
6907 ;; Search for remote coding commands with the same format
6908 (while (and remote-commands (not found))
6909 (setq ritem (pop remote-commands))
6910 (catch 'wont-work-remote
6911 (when (equal format (nth 0 ritem))
6912 (setq rem-enc (nth 1 ritem))
6913 (setq rem-dec (nth 2 ritem))
6914 ;; Check if remote encoding and decoding commands can be
6915 ;; called remotely with null input and output. This makes
6916 ;; sure there are no syntax errors and the command is really
6917 ;; found. Note that we do not redirect stdout to /dev/null,
6918 ;; for two reasons: when checking the decoding command, we
6919 ;; actually check the output it gives. And also, when
6920 ;; redirecting "mimencode" output to /dev/null, then as root
6921 ;; it might change the permissions of /dev/null!
6922 (when (not (stringp rem-enc))
6923 (let ((name (symbol-name rem-enc)))
6924 (while (string-match (regexp-quote "-") name)
6925 (setq name (replace-match "_" nil t name)))
6926 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
6927 (setq rem-enc name)))
6930 "Checking remote encoding command `%s' for sanity" rem-enc)
6931 (unless (zerop (tramp-send-command-and-check
6932 vec (format "%s </dev/null" rem-enc) t))
6933 (throw 'wont-work-remote nil))
6935 (when (not (stringp rem-dec))
6936 (let ((name (symbol-name rem-dec)))
6937 (while (string-match (regexp-quote "-") name)
6938 (setq name (replace-match "_" nil t name)))
6939 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
6940 (setq rem-dec name)))
6943 "Checking remote decoding command `%s' for sanity" rem-dec)
6944 (unless (zerop (tramp-send-command-and-check
6946 (format "echo %s | %s | %s"
6947 magic rem-enc rem-dec)
6949 (throw 'wont-work-remote nil))
6951 (with-current-buffer (tramp-get-buffer vec)
6952 (goto-char (point-min))
6953 (unless (looking-at (regexp-quote magic))
6954 (throw 'wont-work-remote nil)))
6956 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
6957 (setq rem-enc (nth 1 ritem))
6958 (setq rem-dec (nth 2 ritem))
6959 (setq found t)))))))
6961 ;; Did we find something?
6963 (tramp-message vec 2 "Couldn't find an inline transfer encoding"))
6965 ;; Set connection properties.
6966 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
6967 (tramp-set-connection-property vec "local-encoding" loc-enc)
6968 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
6969 (tramp-set-connection-property vec "local-decoding" loc-dec)
6970 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
6971 (tramp-set-connection-property vec "remote-encoding" rem-enc)
6972 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
6973 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
6975 (defun tramp-call-local-coding-command (cmd input output)
6976 "Call the local encoding or decoding command.
6977 If CMD contains \"%s\", provide input file INPUT there in command.
6978 Otherwise, INPUT is passed via standard input.
6979 INPUT can also be nil which means `/dev/null'.
6980 OUTPUT can be a string (which specifies a filename), or t (which
6981 means standard output and thus the current buffer), or nil (which
6983 (tramp-local-call-process
6984 tramp-encoding-shell
6985 (when (and input (not (string-match "%s" cmd))) input)
6986 (if (eq output t) t nil)
6988 tramp-encoding-command-switch
6990 (if (string-match "%s" cmd) (format cmd input) cmd)
6991 (if (stringp output) (concat "> " output) ""))))
6993 (defun tramp-compute-multi-hops (vec)
6994 "Expands VEC according to `tramp-default-proxies-alist'.
6995 Gateway hops are already opened."
6996 (let ((target-alist `(,vec))
6997 (choices tramp-default-proxies-alist)
7000 ;; Look for proxy hosts to be passed.
7002 (setq item (pop choices)
7003 proxy (eval (nth 2 item)))
7006 (string-match (or (eval (nth 0 item)) "")
7007 (or (tramp-file-name-host (car target-alist)) ""))
7009 (string-match (or (eval (nth 1 item)) "")
7010 (or (tramp-file-name-user (car target-alist)) "")))
7012 ;; No more hops needed.
7014 ;; Replace placeholders.
7018 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
7019 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
7020 (with-parsed-tramp-file-name proxy l
7022 (add-to-list 'target-alist l)
7023 ;; Start next search.
7024 (setq choices tramp-default-proxies-alist)))))
7027 (when (and (boundp 'tramp-gw-tunnel-method)
7028 (string-match (format
7030 (symbol-value 'tramp-gw-tunnel-method)
7031 (symbol-value 'tramp-gw-socks-method))
7032 (tramp-file-name-method (car target-alist))))
7033 (let ((gw (pop target-alist))
7034 (hop (pop target-alist)))
7035 ;; Is the method prepared for gateways?
7036 (unless (tramp-get-method-parameter
7037 (tramp-file-name-method hop) 'tramp-default-port)
7040 "Method `%s' is not supported for gateway access."
7041 (tramp-file-name-method hop)))
7042 ;; Add default port if needed.
7045 tramp-host-with-port-regexp (tramp-file-name-host hop))
7048 (tramp-file-name-host hop) tramp-prefix-port-format
7050 (tramp-get-method-parameter
7051 (tramp-file-name-method hop) 'tramp-default-port)))))
7052 ;; Open the gateway connection.
7056 (tramp-file-name-method hop) (tramp-file-name-user hop)
7057 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
7058 ;; For the password prompt, we need the correct values.
7059 ;; Therefore, we must remember the gateway vector. But we
7060 ;; cannot do it as connection property, because it shouldn't
7061 ;; be persistent. And we have no started process yet either.
7062 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7064 ;; Foreign and out-of-band methods are not supported for multi-hops.
7065 (when (cdr target-alist)
7066 (setq choices target-alist)
7068 (setq item (pop choices))
7072 (tramp-get-method-parameter
7073 (tramp-file-name-method item) 'tramp-login-program))
7074 (tramp-get-method-parameter
7075 (tramp-file-name-method item) 'tramp-copy-program))
7078 "Method `%s' is not supported for multi-hops."
7079 (tramp-file-name-method item)))))
7081 ;; In case the host name is not used for the remote shell
7082 ;; command, the user could be misguided by applying a random
7084 (let* ((v (car target-alist))
7085 (method (tramp-file-name-method v))
7086 (host (tramp-file-name-host v)))
7089 ;; There are multi-hops.
7091 ;; The host name is used for the remote shell command.
7093 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7094 ;; The host is local. We cannot use `tramp-local-host-p'
7095 ;; here, because it opens a connection as well.
7096 (string-match tramp-local-host-regexp host))
7099 "Host `%s' looks like a remote host, `%s' can only use the local host"
7105 (defun tramp-maybe-open-connection (vec)
7106 "Maybe open a connection VEC.
7107 Does not do anything if a connection is already open, but re-opens the
7108 connection if a previous connection has died for some reason."
7109 (catch 'uname-changed
7110 (let ((p (tramp-get-connection-process vec))
7111 (process-environment (copy-sequence process-environment)))
7113 ;; If too much time has passed since last command was sent, look
7114 ;; whether process is still alive. If it isn't, kill it. When
7115 ;; using ssh, it can sometimes happen that the remote end has
7116 ;; hung up but the local ssh client doesn't recognize this until
7117 ;; it tries to send some data to the remote end. So that's why
7118 ;; we try to send a command from time to time, then look again
7119 ;; whether the process is really alive.
7121 (when (and (> (tramp-time-diff
7123 (tramp-get-connection-property
7124 p "last-cmd-time" '(0 0 0)))
7126 p (processp p) (memq (process-status p) '(run open)))
7127 (tramp-send-command vec "echo are you awake" t t)
7128 (unless (and (memq (process-status p) '(run open))
7129 (tramp-wait-for-output p 10))
7130 ;; The error will be catched locally.
7131 (tramp-error vec 'file-error "Awake did fail")))
7133 (tramp-flush-connection-property vec)
7134 (tramp-flush-connection-property p)
7138 ;; New connection must be opened.
7139 (unless (and p (processp p) (memq (process-status p) '(run open)))
7141 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7142 ;; messages from the beginning.
7143 (tramp-get-buffer vec)
7144 (if (zerop (length (tramp-file-name-user vec)))
7146 vec 3 "Opening connection for %s using %s..."
7147 (tramp-file-name-host vec)
7148 (tramp-file-name-method vec))
7150 vec 3 "Opening connection for %s@%s using %s..."
7151 (tramp-file-name-user vec)
7152 (tramp-file-name-host vec)
7153 (tramp-file-name-method vec)))
7155 ;; Start new process.
7156 (when (and p (processp p))
7158 (setenv "TERM" tramp-terminal-type)
7159 (setenv "LC_ALL" "C")
7160 (setenv "PROMPT_COMMAND")
7161 (setenv "PS1" tramp-initial-end-of-output)
7162 (let* ((target-alist (tramp-compute-multi-hops vec))
7163 (process-connection-type tramp-process-connection-type)
7164 (process-adaptive-read-buffering nil)
7165 (coding-system-for-read nil)
7166 ;; This must be done in order to avoid our file name handler.
7167 (p (let ((default-directory
7168 (tramp-compat-temporary-file-directory)))
7170 (or (tramp-get-connection-property vec "process-name" nil)
7171 (tramp-buffer-name vec))
7172 (tramp-get-connection-buffer vec)
7173 tramp-encoding-shell))))
7176 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7178 ;; Check whether process is alive.
7179 (tramp-set-process-query-on-exit-flag p nil)
7180 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
7181 (tramp-barf-if-no-shell-prompt
7182 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7184 ;; Now do all the connections as specified.
7186 (let* ((hop (car target-alist))
7187 (l-method (tramp-file-name-method hop))
7188 (l-user (tramp-file-name-user hop))
7189 (l-host (tramp-file-name-host hop))
7192 (tramp-get-method-parameter l-method 'tramp-login-program))
7194 (tramp-get-method-parameter l-method 'tramp-login-args))
7196 (tramp-get-method-parameter l-method 'tramp-gw-args))
7197 (gw (tramp-get-file-property hop "" "gateway" nil))
7198 (g-method (and gw (tramp-file-name-method gw)))
7199 (g-user (and gw (tramp-file-name-user gw)))
7200 (g-host (and gw (tramp-file-name-host gw)))
7201 (command login-program)
7202 ;; We don't create the temporary file. In fact, it
7203 ;; is just a prefix for the ControlPath option of
7204 ;; ssh; the real temporary file has another name, and
7205 ;; it is created and protected by ssh. It is also
7206 ;; removed by ssh, when the connection is closed.
7208 (tramp-set-connection-property
7212 tramp-temp-name-prefix
7213 (tramp-compat-temporary-file-directory)))))
7216 ;; Add gateway arguments if necessary.
7217 (when (and gw gw-args)
7218 (setq login-args (append login-args gw-args)))
7220 ;; Check for port number. Until now, there's no need
7221 ;; for handling like method, user, host.
7222 (when (string-match tramp-host-with-port-regexp l-host)
7223 (setq l-port (match-string 2 l-host)
7224 l-host (match-string 1 l-host)))
7226 ;; Set variables for computing the prompt for reading
7227 ;; password. They can also be derived from a gateway.
7228 (setq tramp-current-method (or g-method l-method)
7229 tramp-current-user (or g-user l-user)
7230 tramp-current-host (or g-host l-host))
7232 ;; Replace login-args place holders.
7234 l-host (or l-host "")
7235 l-user (or l-user "")
7236 l-port (or l-port "")
7237 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
7241 ;; We do not want to see the trailing local prompt in
7242 ;; `start-file-process'.
7243 (unless (memq system-type '(windows-nt)) "exec ")
7247 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7248 (unless (member "" x) (mapconcat 'identity x " ")))
7250 ;; Local shell could be a Windows COMSPEC. It doesn't
7251 ;; know the ";" syntax, but we must exit always for
7252 ;; `start-file-process'. "exec" does not work either.
7253 (if (memq system-type '(windows-nt)) " && exit || exit")))
7255 ;; Send the command.
7256 (tramp-message vec 3 "Sending command `%s'" command)
7257 (tramp-send-command vec command t t)
7258 (tramp-process-actions p vec tramp-actions-before-shell 60)
7259 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
7261 (setq target-alist (cdr target-alist)))
7263 ;; Make initial shell settings.
7264 (tramp-open-connection-setup-interactive-shell p vec))))))
7266 (defun tramp-send-command (vec command &optional neveropen nooutput)
7267 "Send the COMMAND to connection VEC.
7268 Erases temporary buffer before sending the command. If optional
7269 arg NEVEROPEN is non-nil, never try to open the connection. This
7270 is meant to be used from `tramp-maybe-open-connection' only. The
7271 function waits for output unless NOOUTPUT is set."
7272 (unless neveropen (tramp-maybe-open-connection vec))
7273 (let ((p (tramp-get-connection-process vec)))
7274 (when (tramp-get-connection-property p "remote-echo" nil)
7275 ;; We mark the command string that it can be erased in the output buffer.
7276 (tramp-set-connection-property p "check-remote-echo" t)
7277 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7278 (tramp-message vec 6 "%s" command)
7279 (tramp-send-string vec command)
7280 (unless nooutput (tramp-wait-for-output p))))
7282 (defun tramp-wait-for-output (proc &optional timeout)
7283 "Wait for output from remote rsh command."
7284 (with-current-buffer (process-buffer proc)
7285 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7286 ;; be leading escape sequences, which must be ignored.
7287 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7288 ;; Sometimes, the commands do not return a newline but a
7289 ;; null byte before the shell prompt, for example "git
7290 ;; ls-files -c -z ...".
7291 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7292 (found (tramp-wait-for-regexp proc timeout regexp1)))
7294 (let (buffer-read-only)
7295 (goto-char (point-max))
7296 (re-search-backward regexp nil t)
7297 (delete-region (point) (point-max)))
7301 "[[Remote prompt `%s' not found in %d secs]]"
7302 tramp-end-of-output timeout)
7305 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7306 ;; Return value is whether end-of-output sentinel was found.
7309 (defun tramp-send-command-and-check
7310 (vec command &optional subshell dont-suppress-err)
7311 "Run COMMAND and check its exit status.
7312 Sends `echo $?' along with the COMMAND for checking the exit status. If
7313 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7315 If the optional argument SUBSHELL is non-nil, the command is
7316 executed in a subshell, ie surrounded by parentheses. If
7317 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7320 (concat (if subshell "( " "")
7322 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7323 "echo tramp_exit_status $?"
7324 (if subshell " )" "")))
7325 (with-current-buffer (tramp-get-connection-buffer vec)
7326 (goto-char (point-max))
7327 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7329 vec 'file-error "Couldn't find exit status of `%s'" command))
7330 (skip-chars-forward "^ ")
7332 (read (current-buffer))
7333 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7335 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7336 "Run COMMAND, check exit status, throw error if exit status not okay.
7337 Similar to `tramp-send-command-and-check' but accepts two more arguments
7338 FMT and ARGS which are passed to `error'."
7339 (unless (zerop (tramp-send-command-and-check vec command))
7340 (apply 'tramp-error vec 'file-error fmt args)))
7342 (defun tramp-send-command-and-read (vec command)
7343 "Run COMMAND and return the output, which must be a Lisp expression.
7344 In case there is no valid Lisp expression, it raises an error"
7345 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7346 (with-current-buffer (tramp-get-connection-buffer vec)
7347 ;; Read the expression.
7348 (goto-char (point-min))
7350 (prog1 (read (current-buffer))
7352 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7356 "`%s' does not return a valid Lisp expression: `%s'"
7357 command (buffer-string))))))
7359 ;; It seems that Tru64 Unix does not like it if long strings are sent
7360 ;; to it in one go. (This happens when sending the Perl
7361 ;; `file-attributes' implementation, for instance.) Therefore, we
7362 ;; have this function which sends the string in chunks.
7363 (defun tramp-send-string (vec string)
7364 "Send the STRING via connection VEC.
7366 The STRING is expected to use Unix line-endings, but the lines sent to
7367 the remote host use line-endings as defined in the variable
7368 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7369 (let* ((p (tramp-get-connection-process vec))
7370 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7373 vec 'file-error "Can't send string to remote host -- not logged in"))
7374 (tramp-set-connection-property p "last-cmd-time" (current-time))
7375 (tramp-message vec 10 "%s" string)
7376 (with-current-buffer (tramp-get-connection-buffer vec)
7377 ;; Clean up the buffer. We cannot call `erase-buffer' because
7378 ;; narrowing might be in effect.
7379 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7380 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7382 (mapconcat 'identity
7383 (tramp-compat-split-string string "\n")
7384 tramp-rsh-end-of-line))
7385 (unless (or (string= string "")
7386 (string-equal (substring string -1) tramp-rsh-end-of-line))
7387 (setq string (concat string tramp-rsh-end-of-line)))
7389 (if (and chunksize (not (zerop chunksize)))
7391 (end (length string)))
7394 vec 10 "Sending chunk from %s to %s"
7395 pos (min (+ pos chunksize) end))
7396 (process-send-string
7397 p (substring string pos (min (+ pos chunksize) end)))
7398 (setq pos (+ pos chunksize))))
7399 (process-send-string p string)))))
7401 (defun tramp-mode-string-to-int (mode-string)
7402 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7403 (let* (case-fold-search
7404 (mode-chars (string-to-vector mode-string))
7405 (owner-read (aref mode-chars 1))
7406 (owner-write (aref mode-chars 2))
7407 (owner-execute-or-setid (aref mode-chars 3))
7408 (group-read (aref mode-chars 4))
7409 (group-write (aref mode-chars 5))
7410 (group-execute-or-setid (aref mode-chars 6))
7411 (other-read (aref mode-chars 7))
7412 (other-write (aref mode-chars 8))
7413 (other-execute-or-sticky (aref mode-chars 9)))
7417 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7418 ((char-equal owner-read ?-) 0)
7419 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7421 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7422 ((char-equal owner-write ?-) 0)
7423 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7425 ((char-equal owner-execute-or-setid ?x)
7426 (tramp-octal-to-decimal "00100"))
7427 ((char-equal owner-execute-or-setid ?S)
7428 (tramp-octal-to-decimal "04000"))
7429 ((char-equal owner-execute-or-setid ?s)
7430 (tramp-octal-to-decimal "04100"))
7431 ((char-equal owner-execute-or-setid ?-) 0)
7432 (t (error "Fourth char `%c' must be one of `xsS-'"
7433 owner-execute-or-setid)))
7435 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7436 ((char-equal group-read ?-) 0)
7437 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7439 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7440 ((char-equal group-write ?-) 0)
7441 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7443 ((char-equal group-execute-or-setid ?x)
7444 (tramp-octal-to-decimal "00010"))
7445 ((char-equal group-execute-or-setid ?S)
7446 (tramp-octal-to-decimal "02000"))
7447 ((char-equal group-execute-or-setid ?s)
7448 (tramp-octal-to-decimal "02010"))
7449 ((char-equal group-execute-or-setid ?-) 0)
7450 (t (error "Seventh char `%c' must be one of `xsS-'"
7451 group-execute-or-setid)))
7453 ((char-equal other-read ?r)
7454 (tramp-octal-to-decimal "00004"))
7455 ((char-equal other-read ?-) 0)
7456 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7458 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7459 ((char-equal other-write ?-) 0)
7460 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7462 ((char-equal other-execute-or-sticky ?x)
7463 (tramp-octal-to-decimal "00001"))
7464 ((char-equal other-execute-or-sticky ?T)
7465 (tramp-octal-to-decimal "01000"))
7466 ((char-equal other-execute-or-sticky ?t)
7467 (tramp-octal-to-decimal "01001"))
7468 ((char-equal other-execute-or-sticky ?-) 0)
7469 (t (error "Tenth char `%c' must be one of `xtT-'"
7470 other-execute-or-sticky)))))))
7472 (defun tramp-convert-file-attributes (vec attr)
7473 "Convert file-attributes ATTR generated by perl script, stat or ls.
7474 Convert file mode bits to string and set virtual device number.
7477 ;; Convert last access time.
7478 (unless (listp (nth 4 attr))
7479 (setcar (nthcdr 4 attr)
7480 (list (floor (nth 4 attr) 65536)
7481 (floor (mod (nth 4 attr) 65536)))))
7482 ;; Convert last modification time.
7483 (unless (listp (nth 5 attr))
7484 (setcar (nthcdr 5 attr)
7485 (list (floor (nth 5 attr) 65536)
7486 (floor (mod (nth 5 attr) 65536)))))
7487 ;; Convert last status change time.
7488 (unless (listp (nth 6 attr))
7489 (setcar (nthcdr 6 attr)
7490 (list (floor (nth 6 attr) 65536)
7491 (floor (mod (nth 6 attr) 65536)))))
7492 ;; Convert file size.
7493 (when (< (nth 7 attr) 0)
7494 (setcar (nthcdr 7 attr) -1))
7495 (when (and (floatp (nth 7 attr))
7496 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7497 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7498 ;; Convert file mode bits to string.
7499 (unless (stringp (nth 8 attr))
7500 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7501 (when (stringp (car attr))
7502 (aset (nth 8 attr) 0 ?l)))
7503 ;; Convert directory indication bit.
7504 (when (string-match "^d" (nth 8 attr))
7506 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7507 (when (consp (car attr))
7508 (if (and (stringp (caar attr))
7509 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7510 (setcar attr (match-string 1 (caar attr)))
7512 ;; Set file's gid change bit.
7513 (setcar (nthcdr 9 attr)
7514 (if (numberp (nth 3 attr))
7515 (not (= (nth 3 attr)
7516 (tramp-get-remote-gid vec 'integer)))
7519 (tramp-get-remote-gid vec 'string)))))
7521 (unless (listp (nth 10 attr))
7522 (setcar (nthcdr 10 attr)
7524 (cons (floor (nth 10 attr) 65536)
7525 (floor (mod (nth 10 attr) 65536)))
7526 ;; Inodes can be incredible huge. We must hide this.
7527 (error (tramp-get-inode vec)))))
7528 ;; Set virtual device number.
7529 (setcar (nthcdr 11 attr)
7530 (tramp-get-device vec))
7533 (defun tramp-check-cached-permissions (vec access)
7534 "Check `file-attributes' caches for VEC.
7535 Return t if according to the cache access type ACCESS is known to
7541 ((eq ?x access) 3))))
7542 (dolist (suffix '("string" "integer") result)
7548 (tramp-get-file-property
7549 vec (tramp-file-name-localname vec)
7550 (concat "file-attributes-" suffix) nil))
7552 (tramp-get-connection-property
7553 vec (concat "uid-" suffix) nil))
7555 (tramp-get-connection-property
7556 vec (concat "gid-" suffix) nil)))
7561 (eq t (car file-attr))
7562 (null (car file-attr)))
7564 ;; World accessible.
7565 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7566 ;; User accessible and owned by user.
7568 (eq access (aref (nth 8 file-attr) offset))
7569 (equal remote-uid (nth 2 file-attr)))
7570 ;; Group accessible and owned by user's
7573 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7574 (equal remote-gid (nth 3 file-attr)))))))))))
7576 (defun tramp-get-inode (vec)
7577 "Returns the virtual inode number.
7578 If it doesn't exist, generate a new one."
7579 (let ((string (tramp-make-tramp-file-name
7580 (tramp-file-name-method vec)
7581 (tramp-file-name-user vec)
7582 (tramp-file-name-host vec)
7584 (unless (assoc string tramp-inodes)
7585 (add-to-list 'tramp-inodes
7586 (list string (length tramp-inodes))))
7587 (nth 1 (assoc string tramp-inodes))))
7589 (defun tramp-get-device (vec)
7590 "Returns the virtual device number.
7591 If it doesn't exist, generate a new one."
7592 (let ((string (tramp-make-tramp-file-name
7593 (tramp-file-name-method vec)
7594 (tramp-file-name-user vec)
7595 (tramp-file-name-host vec)
7597 (unless (assoc string tramp-devices)
7598 (add-to-list 'tramp-devices
7599 (list string (length tramp-devices))))
7600 (cons -1 (nth 1 (assoc string tramp-devices)))))
7602 (defun tramp-file-mode-from-int (mode)
7603 "Turn an integer representing a file mode into an ls(1)-like string."
7604 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7605 (user (logand (lsh mode -6) 7))
7606 (group (logand (lsh mode -3) 7))
7607 (other (logand (lsh mode -0) 7))
7608 (suid (> (logand (lsh mode -9) 4) 0))
7609 (sgid (> (logand (lsh mode -9) 2) 0))
7610 (sticky (> (logand (lsh mode -9) 1) 0)))
7611 (setq user (tramp-file-mode-permissions user suid "s"))
7612 (setq group (tramp-file-mode-permissions group sgid "s"))
7613 (setq other (tramp-file-mode-permissions other sticky "t"))
7614 (concat type user group other)))
7616 (defun tramp-file-mode-permissions (perm suid suid-text)
7617 "Convert a permission bitset into a string.
7618 This is used internally by `tramp-file-mode-from-int'."
7619 (let ((r (> (logand perm 4) 0))
7620 (w (> (logand perm 2) 0))
7621 (x (> (logand perm 1) 0)))
7622 (concat (or (and r "r") "-")
7623 (or (and w "w") "-")
7624 (or (and suid x suid-text) ; suid, execute
7625 (and suid (upcase suid-text)) ; suid, !execute
7626 (and x "x") "-")))) ; !suid
7628 (defun tramp-decimal-to-octal (i)
7629 "Return a string consisting of the octal digits of I.
7630 Not actually used. Use `(format \"%o\" i)' instead?"
7631 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7632 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7634 (t (concat (tramp-decimal-to-octal (/ i 8))
7635 (number-to-string (% i 8))))))
7637 ;; Kudos to Gerd Moellmann for this suggestion.
7638 (defun tramp-octal-to-decimal (ostr)
7639 "Given a string of octal digits, return a decimal number."
7640 (let ((x (or ostr "")))
7641 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7642 (unless (string-match "\\`[0-7]*\\'" x)
7643 (error "Non-octal junk in string `%s'" x))
7644 (string-to-number ostr 8)))
7646 (defun tramp-shell-case-fold (string)
7647 "Converts STRING to shell glob pattern which ignores case."
7650 (if (equal (downcase c) (upcase c))
7652 (format "[%c%c]" (downcase c) (upcase c))))
7657 ;; ------------------------------------------------------------
7658 ;; -- Tramp file names --
7659 ;; ------------------------------------------------------------
7660 ;; Conversion functions between external representation and
7661 ;; internal data structure. Convenience functions for internal
7664 (defun tramp-file-name-p (vec)
7665 "Check whether VEC is a Tramp object."
7666 (and (vectorp vec) (= 4 (length vec))))
7668 (defun tramp-file-name-method (vec)
7669 "Return method component of VEC."
7670 (and (tramp-file-name-p vec) (aref vec 0)))
7672 (defun tramp-file-name-user (vec)
7673 "Return user component of VEC."
7674 (and (tramp-file-name-p vec) (aref vec 1)))
7676 (defun tramp-file-name-host (vec)
7677 "Return host component of VEC."
7678 (and (tramp-file-name-p vec) (aref vec 2)))
7680 (defun tramp-file-name-localname (vec)
7681 "Return localname component of VEC."
7682 (and (tramp-file-name-p vec) (aref vec 3)))
7684 ;; The user part of a Tramp file name vector can be of kind
7685 ;; "user%domain". Sometimes, we must extract these parts.
7686 (defun tramp-file-name-real-user (vec)
7687 "Return the user name of VEC without domain."
7689 (let ((user (tramp-file-name-user vec)))
7690 (if (and (stringp user)
7691 (string-match tramp-user-with-domain-regexp user))
7692 (match-string 1 user)
7695 (defun tramp-file-name-domain (vec)
7696 "Return the domain name of VEC."
7698 (let ((user (tramp-file-name-user vec)))
7700 (string-match tramp-user-with-domain-regexp user)
7701 (match-string 2 user)))))
7703 ;; The host part of a Tramp file name vector can be of kind
7704 ;; "host#port". Sometimes, we must extract these parts.
7705 (defun tramp-file-name-real-host (vec)
7706 "Return the host name of VEC without port."
7708 (let ((host (tramp-file-name-host vec)))
7709 (if (and (stringp host)
7710 (string-match tramp-host-with-port-regexp host))
7711 (match-string 1 host)
7714 (defun tramp-file-name-port (vec)
7715 "Return the port number of VEC."
7717 (let ((host (tramp-file-name-host vec)))
7719 (string-match tramp-host-with-port-regexp host)
7720 (string-to-number (match-string 2 host))))))
7722 (defun tramp-tramp-file-p (name)
7723 "Return t if NAME is a string with Tramp file name syntax."
7725 (and (stringp name) (string-match tramp-file-name-regexp name))))
7727 (defun tramp-find-method (method user host)
7728 "Return the right method string to use.
7729 This is METHOD, if non-nil. Otherwise, do a lookup in
7730 `tramp-default-method-alist'."
7732 (let ((choices tramp-default-method-alist)
7735 (setq item (pop choices))
7736 (when (and (string-match (or (nth 0 item) "") (or host ""))
7737 (string-match (or (nth 1 item) "") (or user "")))
7738 (setq lmethod (nth 2 item))
7739 (setq choices nil)))
7741 tramp-default-method))
7743 (defun tramp-find-user (method user host)
7744 "Return the right user string to use.
7745 This is USER, if non-nil. Otherwise, do a lookup in
7746 `tramp-default-user-alist'."
7748 (let ((choices tramp-default-user-alist)
7751 (setq item (pop choices))
7752 (when (and (string-match (or (nth 0 item) "") (or method ""))
7753 (string-match (or (nth 1 item) "") (or host "")))
7754 (setq luser (nth 2 item))
7755 (setq choices nil)))
7757 tramp-default-user))
7759 (defun tramp-find-host (method user host)
7760 "Return the right host string to use.
7761 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7762 (or (and (> (length host) 0) host)
7763 tramp-default-host))
7765 (defun tramp-dissect-file-name (name &optional nodefault)
7766 "Return a `tramp-file-name' structure.
7767 The structure consists of remote method, remote user, remote host
7768 and localname (file name on remote host). If NODEFAULT is
7769 non-nil, the file name parts are not expanded to their default
7772 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
7773 (unless match (error "Not a Tramp file name: %s" name))
7774 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7775 (user (match-string (nth 2 tramp-file-name-structure) name))
7776 (host (match-string (nth 3 tramp-file-name-structure) name))
7777 (localname (match-string (nth 4 tramp-file-name-structure) name)))
7778 (when (member method '("multi" "multiu"))
7780 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7783 (when (string-match tramp-prefix-ipv6-regexp host)
7784 (setq host (replace-match "" nil t host)))
7785 (when (string-match tramp-postfix-ipv6-regexp host)
7786 (setq host (replace-match "" nil t host))))
7788 (vector method user host localname)
7790 (tramp-find-method method user host)
7791 (tramp-find-user method user host)
7792 (tramp-find-host method user host)
7795 (defun tramp-equal-remote (file1 file2)
7796 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7797 The check depends on method, user and host name of the files. If
7798 one of the components is missing, the default values are used.
7799 The local file name parts of FILE1 and FILE2 are not taken into
7804 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7806 would yield `t'. On the other hand, the following check results in nil:
7808 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
7809 (and (stringp (file-remote-p file1))
7810 (stringp (file-remote-p file2))
7811 (string-equal (file-remote-p file1) (file-remote-p file2))))
7813 (defun tramp-make-tramp-file-name (method user host localname)
7814 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7815 (concat tramp-prefix-format
7816 (when (not (zerop (length method)))
7817 (concat method tramp-postfix-method-format))
7818 (when (not (zerop (length user)))
7819 (concat user tramp-postfix-user-format))
7821 (if (string-match tramp-ipv6-regexp host)
7822 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7824 tramp-postfix-host-format
7825 (when localname localname)))
7827 (defun tramp-completion-make-tramp-file-name (method user host localname)
7828 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7829 It must not be a complete Tramp file name, but as long as there are
7830 necessary only. This function will be used in file name completion."
7831 (concat tramp-prefix-format
7832 (when (not (zerop (length method)))
7833 (concat method tramp-postfix-method-format))
7834 (when (not (zerop (length user)))
7835 (concat user tramp-postfix-user-format))
7836 (when (not (zerop (length host)))
7838 (if (string-match tramp-ipv6-regexp host)
7839 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7841 tramp-postfix-host-format))
7842 (when localname localname)))
7844 (defun tramp-make-copy-program-file-name (vec)
7845 "Create a file name suitable to be passed to `rcp' and workalikes."
7846 (let ((user (tramp-file-name-user vec))
7847 (host (tramp-file-name-real-host vec))
7848 (localname (tramp-shell-quote-argument
7849 (tramp-file-name-localname vec))))
7850 (if (not (zerop (length user)))
7851 (format "%s@%s:%s" user host localname)
7852 (format "%s:%s" host localname))))
7854 (defun tramp-method-out-of-band-p (vec size)
7855 "Return t if this is an out-of-band method, nil otherwise."
7857 ;; It shall be an out-of-band method.
7858 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7859 ;; Either the file size is large enough, or (in rare cases) there
7860 ;; does not exist a remote encoding.
7861 (or (> size tramp-copy-size-limit)
7862 (null (tramp-get-remote-coding vec "remote-encoding")))))
7864 (defun tramp-local-host-p (vec)
7865 "Return t if this points to the local host, nil otherwise."
7866 ;; We cannot use `tramp-file-name-real-host'. A port is an
7867 ;; indication for an ssh tunnel or alike.
7868 (let ((host (tramp-file-name-host vec)))
7871 (string-match tramp-local-host-regexp host)
7872 ;; The method shall be applied to one of the shell file name
7873 ;; handler. `tramp-local-host-p' is also called for "smb" and
7874 ;; alike, where it must fail.
7875 (tramp-get-method-parameter
7876 (tramp-file-name-method vec) 'tramp-login-program)
7877 ;; The local temp directory must be writable for the other user.
7879 (tramp-make-tramp-file-name
7880 (tramp-file-name-method vec)
7881 (tramp-file-name-user vec)
7883 (tramp-compat-temporary-file-directory)))
7884 ;; On some systems, chown runs only for root.
7885 (or (zerop (user-uid))
7886 (zerop (tramp-get-remote-uid vec 'integer))))))
7888 ;; Variables local to connection.
7890 (defun tramp-get-remote-path (vec)
7891 (with-connection-property
7892 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
7893 ;; cache the result for the session only. Otherwise, the result
7894 ;; is cached persistently.
7895 (if (memq 'tramp-own-remote-path tramp-remote-path)
7896 (tramp-get-connection-process vec)
7899 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
7900 (elt1 (memq 'tramp-default-remote-path remote-path))
7901 (elt2 (memq 'tramp-own-remote-path remote-path))
7902 (default-remote-path
7905 (tramp-send-command-and-read
7906 vec "echo \\\"`getconf PATH`\\\"")
7907 ;; Default if "getconf" is not available.
7911 "`getconf PATH' not successful, using default value \"%s\"."
7917 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
7918 ;; Default if "getconf" is not available.
7921 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
7924 ;; Replace place holder `tramp-default-remote-path'.
7928 (tramp-compat-split-string default-remote-path ":")
7930 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
7932 ;; Replace place holder `tramp-own-remote-path'.
7936 (tramp-compat-split-string own-remote-path ":")
7938 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
7940 ;; Remove double entries.
7941 (setq elt1 remote-path)
7943 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
7945 (setq elt1 (cdr elt1)))
7947 ;; Remove non-existing directories.
7955 (tramp-make-tramp-file-name
7956 (tramp-file-name-method vec)
7957 (tramp-file-name-user vec)
7958 (tramp-file-name-host vec)
7963 (defun tramp-get-remote-tmpdir (vec)
7964 (with-connection-property vec "tmp-directory"
7965 (let ((dir (tramp-shell-quote-argument "/tmp")))
7967 (tramp-send-command-and-check
7968 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
7970 (tramp-send-command-and-check
7971 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
7973 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
7975 (defun tramp-get-ls-command (vec)
7976 (with-connection-property vec "ls"
7977 (tramp-message vec 5 "Finding a suitable `ls' command")
7980 (dolist (cmd '("ls" "gnuls" "gls"))
7981 (let ((dl (tramp-get-remote-path vec))
7983 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
7985 (when (zerop (tramp-send-command-and-check
7986 vec (format "%s -lnd /" result)))
7987 (throw 'ls-found result))
7988 (setq dl (cdr dl))))))
7989 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
7991 (defun tramp-get-ls-command-with-dired (vec)
7993 (with-connection-property vec "ls-dired"
7994 (tramp-message vec 5 "Checking, whether `ls --dired' works")
7995 (zerop (tramp-send-command-and-check
7996 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
7998 (defun tramp-get-test-command (vec)
7999 (with-connection-property vec "test"
8000 (tramp-message vec 5 "Finding a suitable `test' command")
8001 (if (zerop (tramp-send-command-and-check vec "test 0"))
8003 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8005 (defun tramp-get-test-nt-command (vec)
8006 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8007 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8008 ;; for otherwise the shell crashes.
8009 (with-connection-property vec "test-nt"
8013 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8014 (with-current-buffer (tramp-get-buffer vec)
8015 (goto-char (point-min))
8016 (when (looking-at (regexp-quote tramp-end-of-output))
8017 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8022 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8023 (tramp-get-test-command vec)))
8024 "tramp_test_nt %s %s"))))
8026 (defun tramp-get-file-exists-command (vec)
8027 (with-connection-property vec "file-exists"
8028 (tramp-message vec 5 "Finding command to check if file exists")
8029 (tramp-find-file-exists-command vec)))
8031 (defun tramp-get-remote-ln (vec)
8032 (with-connection-property vec "ln"
8033 (tramp-message vec 5 "Finding a suitable `ln' command")
8034 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8036 (defun tramp-get-remote-perl (vec)
8037 (with-connection-property vec "perl"
8038 (tramp-message vec 5 "Finding a suitable `perl' command")
8040 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8041 (tramp-find-executable
8042 vec "perl" (tramp-get-remote-path vec)))))
8043 ;; We must check also for some Perl modules.
8045 (with-connection-property vec "perl-file-spec"
8047 (tramp-send-command-and-check
8048 vec (format "%s -e 'use File::Spec;'" result))))
8049 (with-connection-property vec "perl-cwd-realpath"
8051 (tramp-send-command-and-check
8052 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8055 (defun tramp-get-remote-stat (vec)
8056 (with-connection-property vec "stat"
8057 (tramp-message vec 5 "Finding a suitable `stat' command")
8058 (let ((result (tramp-find-executable
8059 vec "stat" (tramp-get-remote-path vec)))
8061 ;; Check whether stat(1) returns usable syntax. %s does not
8062 ;; work on older AIX systems.
8065 ;; We don't want to display an error message.
8066 (with-temp-message (or (current-message) "")
8068 (tramp-send-command-and-read
8069 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8071 (unless (and (listp tmp) (stringp (car tmp))
8072 (string-match "^./.$" (car tmp))
8073 (integerp (cadr tmp)))
8077 (defun tramp-get-remote-readlink (vec)
8078 (with-connection-property vec "readlink"
8079 (tramp-message vec 5 "Finding a suitable `readlink' command")
8080 (let ((result (tramp-find-executable
8081 vec "readlink" (tramp-get-remote-path vec))))
8083 ;; We don't want to display an error message.
8084 (with-temp-message (or (current-message) "")
8087 (tramp-send-command-and-check
8088 vec (format "%s --canonicalize-missing /" result)))
8092 (defun tramp-get-remote-id (vec)
8093 (with-connection-property vec "id"
8094 (tramp-message vec 5 "Finding POSIX `id' command")
8097 (let ((dl (tramp-get-remote-path vec))
8099 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8100 ;; Check POSIX parameter.
8101 (when (zerop (tramp-send-command-and-check
8102 vec (format "%s -u" result)))
8103 (throw 'id-found result))
8104 (setq dl (cdr dl)))))
8105 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8107 (defun tramp-get-remote-uid (vec id-format)
8108 (with-connection-property vec (format "uid-%s" id-format)
8109 (let ((res (tramp-send-command-and-read
8111 (format "%s -u%s %s"
8112 (tramp-get-remote-id vec)
8113 (if (equal id-format 'integer) "" "n")
8114 (if (equal id-format 'integer)
8115 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8116 ;; The command might not always return a number.
8117 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8119 (defun tramp-get-remote-gid (vec id-format)
8120 (with-connection-property vec (format "gid-%s" id-format)
8121 (let ((res (tramp-send-command-and-read
8123 (format "%s -g%s %s"
8124 (tramp-get-remote-id vec)
8125 (if (equal id-format 'integer) "" "n")
8126 (if (equal id-format 'integer)
8127 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8128 ;; The command might not always return a number.
8129 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8131 (defun tramp-get-local-uid (id-format)
8132 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8134 (defun tramp-get-local-gid (id-format)
8135 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8137 ;; Some predefined connection properties.
8138 (defun tramp-get-remote-coding (vec prop)
8139 ;; Local coding handles properties like remote coding. So we could
8140 ;; call it without pain.
8141 (let ((ret (tramp-get-local-coding vec prop)))
8142 ;; The connection property might have been cached. So we must send
8143 ;; the script - maybe.
8144 (when (and ret (symbolp ret))
8145 (let ((name (symbol-name ret)))
8146 (while (string-match (regexp-quote "-") name)
8147 (setq name (replace-match "_" nil t name)))
8148 (tramp-maybe-send-script vec (symbol-value ret) name)
8150 ;; Return the value.
8153 (defun tramp-get-local-coding (vec prop)
8155 (tramp-get-connection-property vec prop nil)
8157 (tramp-find-inline-encoding vec)
8158 (tramp-get-connection-property vec prop nil))))
8160 (defun tramp-get-method-parameter (method param)
8161 "Return the method parameter PARAM.
8162 If the `tramp-methods' entry does not exist, return NIL."
8163 (let ((entry (assoc param (assoc method tramp-methods))))
8164 (when entry (cadr entry))))
8166 ;; Auto saving to a special directory.
8168 (defun tramp-exists-file-name-handler (operation &rest args)
8169 "Checks whether OPERATION runs a file name handler."
8170 ;; The file name handler is determined on base of either an
8171 ;; argument, `buffer-file-name', or `default-directory'.
8173 (let* ((buffer-file-name "/")
8174 (default-directory "/")
8175 (fnha file-name-handler-alist)
8176 (check-file-name-operation operation)
8177 (file-name-handler-alist
8180 (lambda (operation &rest args)
8181 "Returns OPERATION if it is the one to be checked."
8182 (if (equal check-file-name-operation operation)
8184 (let ((file-name-handler-alist fnha))
8185 (apply operation args))))))))
8186 (equal (apply operation args) operation))
8189 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8190 (defadvice make-auto-save-file-name
8191 (around tramp-advice-make-auto-save-file-name () activate)
8192 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8193 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
8194 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8195 ;; directly, because this would bypass the locking mechanism.
8196 (setq ad-return-value
8197 (tramp-file-name-handler 'make-auto-save-file-name))
8203 'make-auto-save-file-name
8204 'around 'tramp-advice-make-auto-save-file-name)
8205 (ad-activate 'make-auto-save-file-name))))
8207 ;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
8208 ;; permission 0666 minus umask. This is a security threat.
8210 (defun tramp-set-auto-save-file-modes ()
8211 "Set permissions of autosaved remote files to the original permissions."
8212 (let ((bfn (buffer-file-name)))
8213 (when (and (stringp bfn)
8214 (tramp-tramp-file-p bfn)
8216 (stringp buffer-auto-save-file-name)
8217 (not (equal bfn buffer-auto-save-file-name)))
8218 (unless (file-exists-p buffer-auto-save-file-name)
8219 (write-region "" nil buffer-auto-save-file-name))
8220 ;; Permissions should be set always, because there might be an old
8221 ;; auto-saved file belonging to another original file. This could
8222 ;; be a security threat.
8223 (set-file-modes buffer-auto-save-file-name
8224 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8226 (unless (or (> emacs-major-version 21)
8227 (and (featurep 'xemacs)
8228 (= emacs-major-version 21)
8229 (> emacs-minor-version 4)))
8230 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8231 (add-hook 'tramp-unload-hook
8233 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8235 (defun tramp-subst-strs-in-string (alist string)
8236 "Replace all occurrences of the string FROM with TO in STRING.
8237 ALIST is of the form ((FROM . TO) ...)."
8240 (let* ((pr (car alist))
8243 (while (string-match (regexp-quote from) string)
8244 (setq string (replace-match to t t string)))
8245 (setq alist (cdr alist))))
8248 ;; ------------------------------------------------------------
8249 ;; -- Compatibility functions section --
8250 ;; ------------------------------------------------------------
8252 (defun tramp-read-passwd (proc &optional prompt)
8253 "Read a password from user (compat function).
8254 Consults the auth-source package.
8255 Invokes `password-read' if available, `read-passwd' else."
8256 (let* ((key (tramp-make-tramp-file-name
8257 tramp-current-method tramp-current-user
8258 tramp-current-host ""))
8261 (with-current-buffer (process-buffer proc)
8262 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8263 (format "%s for %s " (capitalize (match-string 1)) key)))))
8266 ;; See if auth-sources contains something useful, if it's bound.
8267 (and (boundp 'auth-sources)
8268 (tramp-get-connection-property proc "first-password-request" nil)
8269 ;; Try with Tramp's current method.
8270 (funcall (symbol-function 'auth-source-user-or-password)
8271 "password" tramp-current-host tramp-current-method))
8272 ;; Try the password cache.
8273 (when (functionp 'password-read)
8274 (unless (tramp-get-connection-property
8275 proc "first-password-request" nil)
8276 (funcall (symbol-function 'password-cache-remove) key))
8278 (funcall (symbol-function 'password-read) pw-prompt key)))
8279 (funcall (symbol-function 'password-cache-add) key password)
8281 ;; Else, get the password interactively.
8282 (read-passwd pw-prompt))
8283 (tramp-set-connection-property proc "first-password-request" nil))))
8285 (defun tramp-clear-passwd (vec)
8286 "Clear password cache for connection related to VEC."
8287 (when (functionp 'password-cache-remove)
8289 (symbol-function 'password-cache-remove)
8290 (tramp-make-tramp-file-name
8291 (tramp-file-name-method vec)
8292 (tramp-file-name-user vec)
8293 (tramp-file-name-host vec)
8296 ;; Snarfed code from time-date.el and parse-time.el
8298 (defconst tramp-half-a-year '(241 17024)
8299 "Evaluated by \"(days-to-time 183)\".")
8301 (defconst tramp-parse-time-months
8302 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8303 ("apr" . 4) ("may" . 5) ("jun" . 6)
8304 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8305 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8306 "Alist mapping month names to integers.")
8308 (defun tramp-time-less-p (t1 t2)
8309 "Say whether time value T1 is less than time value T2."
8310 (unless t1 (setq t1 '(0 0)))
8311 (unless t2 (setq t2 '(0 0)))
8312 (or (< (car t1) (car t2))
8313 (and (= (car t1) (car t2))
8314 (< (nth 1 t1) (nth 1 t2)))))
8316 (defun tramp-time-subtract (t1 t2)
8317 "Subtract two time values.
8318 Return the difference in the format of a time value."
8319 (unless t1 (setq t1 '(0 0)))
8320 (unless t2 (setq t2 '(0 0)))
8321 (let ((borrow (< (cadr t1) (cadr t2))))
8322 (list (- (car t1) (car t2) (if borrow 1 0))
8323 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8325 (defun tramp-time-diff (t1 t2)
8326 "Return the difference between the two times, in seconds.
8327 T1 and T2 are time values (as returned by `current-time' for example)."
8328 ;; Pacify byte-compiler with `symbol-function'.
8329 (cond ((and (fboundp 'subtract-time)
8330 (fboundp 'float-time))
8331 (funcall (symbol-function 'float-time)
8332 (funcall (symbol-function 'subtract-time) t1 t2)))
8333 ((and (fboundp 'subtract-time)
8334 (fboundp 'time-to-seconds))
8335 (funcall (symbol-function 'time-to-seconds)
8336 (funcall (symbol-function 'subtract-time) t1 t2)))
8337 ((fboundp 'itimer-time-difference)
8338 (funcall (symbol-function 'itimer-time-difference)
8339 (if (< (length t1) 3) (append t1 '(0)) t1)
8340 (if (< (length t2) 3) (append t2 '(0)) t2)))
8342 (let ((time (tramp-time-subtract t1 t2)))
8343 (+ (* (car time) 65536.0)
8345 (/ (or (nth 2 time) 0) 1000000.0))))))
8347 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8348 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8349 EOL-TYPE can be one of `dos', `unix', or `mac'."
8350 (cond ((fboundp 'coding-system-change-eol-conversion)
8351 (funcall (symbol-function 'coding-system-change-eol-conversion)
8352 coding-system eol-type))
8353 ((fboundp 'subsidiary-coding-system)
8354 (funcall (symbol-function 'subsidiary-coding-system)
8356 (cond ((eq eol-type 'dos) 'crlf)
8357 ((eq eol-type 'unix) 'lf)
8358 ((eq eol-type 'mac) 'cr)
8360 (error "Unknown EOL-TYPE `%s', must be %s"
8362 "`dos', `unix', or `mac'")))))
8363 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8365 (defun tramp-set-process-query-on-exit-flag (process flag)
8366 "Specify if query is needed for process when Emacs is exited.
8367 If the second argument flag is non-nil, Emacs will query the user before
8368 exiting if process is running."
8369 (if (fboundp 'set-process-query-on-exit-flag)
8370 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
8371 (funcall (symbol-function 'process-kill-without-query) process flag)))
8374 ;; ------------------------------------------------------------
8375 ;; -- Kludges section --
8376 ;; ------------------------------------------------------------
8378 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8379 ;; does not deal well with newline characters. Newline is replaced by
8380 ;; backslash newline. But if, say, the string `a backslash newline b'
8381 ;; is passed to a shell, the shell will expand this into "ab",
8382 ;; completely omitting the newline. This is not what was intended.
8383 ;; It does not appear to be possible to make the function
8384 ;; `shell-quote-argument' work with newlines without making it
8385 ;; dependent on the shell used. But within this package, we know that
8386 ;; we will always use a Bourne-like shell, so we use an approach which
8389 ;; The approach is simple: we call `shell-quote-argument', then
8390 ;; massage the newline part of the result.
8392 ;; This function should produce a string which is grokked by a Unix
8393 ;; shell, even if the Emacs is running on Windows. Since this is the
8394 ;; kludges section, we bind `system-type' in such a way that
8395 ;; `shell-quote-arguments' behaves as if on Unix.
8397 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8398 ;; function to work with Bourne-like shells.
8400 ;; CCC: This function should be rewritten so that
8401 ;; `shell-quote-argument' is not used. This way, we are safe from
8402 ;; changes in `shell-quote-argument'.
8403 (defun tramp-shell-quote-argument (s)
8404 "Similar to `shell-quote-argument', but groks newlines.
8405 Only works for Bourne-like shells."
8406 (let ((system-type 'not-windows))
8408 (let ((result (shell-quote-argument s))
8409 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8410 (when (and (>= (length result) 2)
8411 (string= (substring result 0 2) "\\~"))
8412 (setq result (substring result 1)))
8413 (while (string-match nl result)
8414 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8418 ;; We currently (sometimes) use "[" and "]" in the filename format.
8419 ;; This means that Emacs wants to expand wildcards if
8420 ;; `find-file-wildcards' is non-nil, and then barfs because no
8421 ;; expansion could be found. We detect this situation and do
8422 ;; something really awful: we have `file-expand-wildcards' return the
8423 ;; original filename if it can't expand anything. Let's just hope
8424 ;; that this doesn't break anything else.
8425 ;; CCC: This check is now also really awful; we should search all
8426 ;; of the filename format, not just the prefix.
8427 (when (string-match "\\[" tramp-prefix-format)
8428 (defadvice file-expand-wildcards
8429 (around tramp-advice-file-expand-wildcards activate)
8430 (let ((name (ad-get-arg 0)))
8431 ;; If it's a Tramp file, dissect it and look if wildcards need
8432 ;; to be expanded at all.
8434 (tramp-tramp-file-p name)
8437 (tramp-file-name-localname (tramp-dissect-file-name name)))))
8438 (setq ad-return-value (list name))
8439 ;; Otherwise, just run the original function.
8445 'file-expand-wildcards 'around 'tramp-advice-file-expand-wildcards)
8446 (ad-activate 'file-expand-wildcards))))
8448 ;; Checklist for `tramp-unload-hook'
8449 ;; - Unload all `tramp-*' packages
8450 ;; - Reset `file-name-handler-alist'
8451 ;; - Cleanup hooks where Tramp functions are in
8452 ;; - Cleanup advised functions
8453 ;; - Cleanup autoloads
8455 (defun tramp-unload-tramp ()
8456 "Discard Tramp from loading remote files."
8458 ;; When Tramp is not loaded yet, its autoloads are still active.
8459 (tramp-unload-file-name-handlers)
8460 ;; ange-ftp settings must be enabled.
8461 (when (functionp 'tramp-ftp-enable-ange-ftp)
8462 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
8463 ;; Maybe its not loaded yet.
8465 (unload-feature 'tramp 'force)
8468 (when (and load-in-progress
8469 (string-match "Loading tramp..." (or (current-message) "")))
8470 (message "Loading tramp...done"))
8476 ;; * Handle nonlocal exits such as C-g.
8477 ;; * But it would probably be better to use with-local-quit at the
8478 ;; place where it's actually needed: around any potentially
8479 ;; indefinitely blocking piece of code. In this case it would be
8480 ;; within Tramp around one of its calls to accept-process-output (or
8481 ;; around one of the loops that calls accept-process-output)
8482 ;; (Stefan Monnier).
8483 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8484 ;; `shell-quote-argument'.
8485 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8486 ;; by the files in that directory. Add this here.
8487 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8488 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8489 ;; * Case-insensitive filename completion. (Norbert Goevert.)
8490 ;; * Don't use globbing for directories with many files, as this is
8491 ;; likely to produce long command lines, and some shells choke on
8492 ;; long command lines.
8493 ;; * `vc-directory' does not work. It never displays any files, even
8494 ;; if it does show files when run locally.
8495 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8496 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8497 ;; * abbreviate-file-name
8498 ;; * Better error checking. At least whenever we see something
8499 ;; strange when doing zerop, we should kill the process and start
8500 ;; again. (Greg Stark)
8501 ;; * Remove unneeded parameters from methods.
8502 ;; * Make it work for different encodings, and for different file name
8503 ;; encodings, too. (Daniel Pittman)
8504 ;; * Progress reports while copying files. (Michael Kifer)
8505 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8506 ;; then look if it's the right version (with `perl -v').
8507 ;; * When editing a remote CVS controlled file as a different user, VC
8508 ;; gets confused about the file locking status. Try to find out why
8509 ;; the workaround doesn't work.
8510 ;; * Username and hostname completion.
8511 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8512 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8513 ;; Code is nearly identical.
8514 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8515 ;; until the last but one hop via `start-file-process'. Apply it
8516 ;; also for ftp and smb.
8517 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8518 ;; some shell with root priviledges, it would be nice if I could
8520 ;; trampclient filename.c
8521 ;; as an editor, and the _current_ shell would connect to an Emacs
8522 ;; server and would be used in an existing non-priviledged Emacs
8523 ;; session for doing the editing in question.
8524 ;; That way, I need not tell Emacs my password again and be afraid
8525 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8526 ;; once display a just typed password in the context of a keyboard
8527 ;; sequence prompt for a question immediately following in a shell
8528 ;; script run within Emacs -- nasty).
8529 ;; And if I have some ssh session running to a different computer,
8530 ;; having the possibility of passing a local file there to a local
8531 ;; Emacs session (in case I can arrange for a connection back) would
8533 ;; Likely the corresponding Tramp server should not allow the
8534 ;; equivalent of the emacsclient -eval option in order to make this
8535 ;; reasonably unproblematic. And maybe trampclient should have some
8536 ;; way of passing credentials, like by using an SSL socket or
8537 ;; something. (David Kastrup)
8538 ;; * Reconnect directly to a compliant shell without first going
8539 ;; through the user's default shell. (Pete Forman)
8540 ;; * Make `tramp-default-user' obsolete.
8541 ;; * Tramp shall reconnect automatically to its ssh connection when it
8542 ;; detects that the process "has died". (David Reitter)
8543 ;; * How can I interrupt the remote process with a signal
8544 ;; (interrupt-process seems not to work)? (Markus Triska)
8545 ;; * Avoid the local shell entirely for starting remote processes. If
8546 ;; so, I think even a signal, when delivered directly to the local
8547 ;; SSH instance, would correctly be propagated to the remote process
8548 ;; automatically; possibly SSH would have to be started with
8549 ;; "-t". (Markus Triska)
8550 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8551 ;; isn't on the remote host. (Mark A. Hershberger)
8552 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8553 ;; * Implement a general server-local-variable mechanism, as there are
8554 ;; probably other variables that need different values for different
8555 ;; servers too. The user could then configure a variable (such as
8556 ;; tramp-server-local-variable-alist) to define any such variables
8557 ;; that they need to, which would then be let bound as appropriate
8558 ;; in tramp functions. (Jason Rumney)
8559 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8561 ;; * Keep a second connection open for out-of-band methods like scp or
8563 ;; * Support ptys in `tramp-handle-start-file-process'.
8565 ;; Functions for file-name-handler-alist:
8566 ;; diff-latest-backup-file -- in diff.el
8568 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8569 ;;; tramp.el ends here