* dired.el (dired-mode-map): Rebind "\C-t\C-t" from
[emacs.git] / lisp / net / tramp.el
blob91b35481730dfa4678fa2b5953c1c7fd6896b3b3
1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; (copyright statements below in code to be updated with the above notice)
8 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
9 ;; Michael Albinus <michael.albinus@gmx.de>
10 ;; Keywords: comm, processes
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
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.
36 ;; Notes:
37 ;; -----
39 ;; This package only works for Emacs 22.1 and higher, and for XEmacs 21.4
40 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
41 ;; the `with-timeout' macro.
43 ;; Also see the todo list at the bottom of this file.
45 ;; The current version of Tramp can be retrieved from the following URL:
46 ;; http://ftp.gnu.org/gnu/tramp/
48 ;; There's a mailing list for this, as well. Its name is:
49 ;; tramp-devel@gnu.org
50 ;; You can use the Web to subscribe, under the following URL:
51 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
53 ;; For the adventurous, the current development sources are available
54 ;; via CVS. You can find instructions about this at the following URL:
55 ;; http://savannah.gnu.org/projects/tramp/
56 ;; Click on "CVS" in the navigation bar near the top.
58 ;; Don't forget to put on your asbestos longjohns, first!
60 ;;; Code:
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.
70 (require 'trampver)
71 (add-hook 'tramp-unload-hook
72 (lambda ()
73 (when (featurep 'trampver)
74 (unload-feature 'trampver 'force))))
76 (require 'tramp-compat)
77 (add-hook 'tramp-unload-hook
78 (lambda ()
79 (when (featurep 'tramp-compat)
80 (unload-feature 'tramp-compat 'force))))
82 (require 'format-spec)
83 ;; As long as password.el is not part of (X)Emacs, it shouldn't
84 ;; be mandatory
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
90 (require 'shell)
91 (require 'advice)
93 (eval-and-compile
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
108 (lambda ()
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
115 (lambda ()
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"
124 '(dolist
125 (feature
126 (list
128 ;; Tramp interactive commands.
129 'tramp-cmds
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.
141 'tramp-fish
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)
147 (condition-case nil
148 (tramp-compat-funcall 'dbus-get-unique-name :session)
149 (error nil))
150 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
151 'tramp-gvfs)
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"))
159 'tramp-imap)))
161 (when feature
162 ;; We have used just some basic tests, whether a package shall
163 ;; be added. There might still be other errors during loading,
164 ;; which we will catch here.
165 (catch 'tramp-loading
166 (require feature)
167 (add-hook 'tramp-unload-hook
168 `(lambda ()
169 (when (featurep (quote ,feature))
170 (unload-feature (quote ,feature) 'force)))))
171 (unless (featurep feature)
172 (message "Loading %s failed, ignoring this package" feature)))))
174 ;;; User Customizable Internal Variables:
176 (defgroup tramp nil
177 "Edit remote files with a combination of rsh and rcp or similar programs."
178 :group 'files
179 :group 'comm
180 :version "22.1")
182 ;; Maybe we need once a real Tramp mode, with key bindings etc.
183 ;;;###autoload
184 (defcustom tramp-mode t
185 "*Whether Tramp is enabled.
186 If it is set to nil, all remote file names are used literally."
187 :group 'tramp
188 :type 'boolean)
190 (defcustom tramp-verbose 3
191 "*Verbosity level for Tramp messages.
192 Any level x includes messages for all levels 1 .. x-1. The levels are
194 0 silent (no tramp messages at all)
195 1 errors
196 2 warnings
197 3 connection to remote hosts (default level)
198 4 activities
199 5 internal
200 6 sent and received strings
201 7 file caching
202 8 connection properties
203 10 traces (huge)."
204 :group 'tramp
205 :type 'integer)
207 ;; Emacs case.
208 (eval-and-compile
209 (when (boundp 'backup-directory-alist)
210 (defcustom tramp-backup-directory-alist nil
211 "Alist of filename patterns and backup directory names.
212 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
213 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
214 is a local file name, the backup directory is prepended with Tramp file
215 name prefix \(method, user, host\) of file.
217 \(setq tramp-backup-directory-alist backup-directory-alist\)
219 gives the same backup policy for Tramp files on their hosts like the
220 policy for local files."
221 :group 'tramp
222 :type '(repeat (cons (regexp :tag "Regexp matching filename")
223 (directory :tag "Backup directory name"))))))
225 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
226 ;; the package "backup-dir" might not be loaded yet.
227 (eval-and-compile
228 (when (featurep 'xemacs)
229 (defcustom tramp-bkup-backup-directory-info nil
230 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
231 It has the same meaning like `bkup-backup-directory-info' from package
232 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
233 file name, the backup directory is prepended with Tramp file name prefix
234 \(method, user, host\) of file.
236 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
238 gives the same backup policy for Tramp files on their hosts like the
239 policy for local files."
240 :type '(repeat
241 (list (regexp :tag "File regexp")
242 (string :tag "Backup Dir")
243 (set :inline t
244 (const ok-create)
245 (const full-path)
246 (const prepend-name)
247 (const search-upward))))
248 :group 'tramp)))
250 (defcustom tramp-auto-save-directory nil
251 "*Put auto-save files in this directory, if set.
252 The idea is to use a local directory so that auto-saving is faster."
253 :group 'tramp
254 :type '(choice (const nil) string))
256 (defcustom tramp-encoding-shell
257 (if (memq system-type '(windows-nt))
258 (getenv "COMSPEC")
259 "/bin/sh")
260 "*Use this program for encoding and decoding commands on the local host.
261 This shell is used to execute the encoding and decoding command on the
262 local host, so if you want to use `~' in those commands, you should
263 choose a shell here which groks tilde expansion. `/bin/sh' normally
264 does not understand tilde expansion.
266 For encoding and deocding, commands like the following are executed:
268 /bin/sh -c COMMAND < INPUT > OUTPUT
270 This variable can be used to change the \"/bin/sh\" part. See the
271 variable `tramp-encoding-command-switch' for the \"-c\" part.
273 Note that this variable is not used for remote commands. There are
274 mechanisms in tramp.el which automatically determine the right shell to
275 use for the remote host."
276 :group 'tramp
277 :type '(file :must-match t))
279 (defcustom tramp-encoding-command-switch
280 (if (string-match "cmd\\.exe" tramp-encoding-shell)
281 "/c"
282 "-c")
283 "*Use this switch together with `tramp-encoding-shell' for local commands.
284 See the variable `tramp-encoding-shell' for more information."
285 :group 'tramp
286 :type 'string)
288 (defcustom tramp-inline-compress-start-size 4096
289 "*The minimum size of compressing where inline transfer.
290 When inline transfer, compress transfered data of file
291 whose size is this value or above (up to `tramp-copy-size-limit').
292 If it is nil, no compression at all will be applied."
293 :group 'tramp
294 :type '(choice (const nil) integer))
296 (defcustom tramp-copy-size-limit 10240
297 "*The maximum file size where inline copying is preferred over an out-of-the-band copy.
298 If it is nil, inline out-of-the-band copy will be used without a check."
299 :group 'tramp
300 :type '(choice (const nil) integer))
302 (defcustom tramp-terminal-type "dumb"
303 "*Value of TERM environment variable for logging in to remote host.
304 Because Tramp wants to parse the output of the remote shell, it is easily
305 confused by ANSI color escape sequences and suchlike. Often, shell init
306 files conditionalize this setup based on the TERM environment variable."
307 :group 'tramp
308 :type 'string)
310 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
311 ;; root users. It uses the `$' character for other users. In order
312 ;; to guarantee a proper prompt, we use "#$" for the prompt.
314 (defvar tramp-end-of-output
315 (format
316 "///%s#$"
317 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
318 "String used to recognize end of output.
319 The '$' character at the end is quoted; the string cannot be
320 detected as prompt when being sent on echoing hosts, therefore.")
322 (defconst tramp-initial-end-of-output "#$ "
323 "Prompt when establishing a connection.")
325 (defvar tramp-methods
326 `(("rcp" (tramp-login-program "rsh")
327 (tramp-login-args (("%h") ("-l" "%u")))
328 (tramp-remote-sh "/bin/sh")
329 (tramp-copy-program "rcp")
330 (tramp-copy-args (("-p" "%k") ("-r")))
331 (tramp-copy-keep-date t)
332 (tramp-copy-recursive t)
333 (tramp-password-end-of-line nil))
334 ("scp" (tramp-login-program "ssh")
335 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
336 ("-e" "none")))
337 (tramp-async-args (("-q")))
338 (tramp-remote-sh "/bin/sh")
339 (tramp-copy-program "scp")
340 (tramp-copy-args (("-P" "%p") ("-p" "%k")
341 ("-q") ("-r")))
342 (tramp-copy-keep-date t)
343 (tramp-copy-recursive t)
344 (tramp-password-end-of-line nil)
345 (tramp-gw-args (("-o"
346 "GlobalKnownHostsFile=/dev/null")
347 ("-o" "UserKnownHostsFile=/dev/null")
348 ("-o" "StrictHostKeyChecking=no")))
349 (tramp-default-port 22))
350 ("scp1" (tramp-login-program "ssh")
351 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
352 ("-1" "-e" "none")))
353 (tramp-async-args (("-q")))
354 (tramp-remote-sh "/bin/sh")
355 (tramp-copy-program "scp")
356 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
357 ("-q") ("-r")))
358 (tramp-copy-keep-date t)
359 (tramp-copy-recursive t)
360 (tramp-password-end-of-line nil)
361 (tramp-gw-args (("-o"
362 "GlobalKnownHostsFile=/dev/null")
363 ("-o" "UserKnownHostsFile=/dev/null")
364 ("-o" "StrictHostKeyChecking=no")))
365 (tramp-default-port 22))
366 ("scp2" (tramp-login-program "ssh")
367 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
368 ("-2" "-e" "none")))
369 (tramp-async-args (("-q")))
370 (tramp-remote-sh "/bin/sh")
371 (tramp-copy-program "scp")
372 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
373 ("-q") ("-r")))
374 (tramp-copy-keep-date t)
375 (tramp-copy-recursive t)
376 (tramp-password-end-of-line nil)
377 (tramp-gw-args (("-o"
378 "GlobalKnownHostsFile=/dev/null")
379 ("-o" "UserKnownHostsFile=/dev/null")
380 ("-o" "StrictHostKeyChecking=no")))
381 (tramp-default-port 22))
382 ("scp1_old"
383 (tramp-login-program "ssh1")
384 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
385 ("-e" "none")))
386 (tramp-remote-sh "/bin/sh")
387 (tramp-copy-program "scp1")
388 (tramp-copy-args (("-p" "%k") ("-r")))
389 (tramp-copy-keep-date t)
390 (tramp-copy-recursive t)
391 (tramp-password-end-of-line nil))
392 ("scp2_old"
393 (tramp-login-program "ssh2")
394 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
395 ("-e" "none")))
396 (tramp-remote-sh "/bin/sh")
397 (tramp-copy-program "scp2")
398 (tramp-copy-args (("-p" "%k") ("-r")))
399 (tramp-copy-keep-date t)
400 (tramp-copy-recursive t)
401 (tramp-password-end-of-line nil))
402 ("sftp" (tramp-login-program "ssh")
403 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
404 ("-e" "none")))
405 (tramp-async-args (("-q")))
406 (tramp-remote-sh "/bin/sh")
407 (tramp-copy-program "sftp")
408 (tramp-copy-args nil)
409 (tramp-copy-keep-date nil)
410 (tramp-password-end-of-line nil))
411 ("rsync" (tramp-login-program "ssh")
412 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
413 ("-e" "none")))
414 (tramp-async-args (("-q")))
415 (tramp-remote-sh "/bin/sh")
416 (tramp-copy-program "rsync")
417 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
418 (tramp-copy-keep-date t)
419 (tramp-copy-keep-tmpfile t)
420 (tramp-copy-recursive t)
421 (tramp-password-end-of-line nil))
422 ("rsyncc"
423 (tramp-login-program "ssh")
424 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
425 ("-o" "ControlPath=%t.%%r@%%h:%%p")
426 ("-o" "ControlMaster=yes")
427 ("-e" "none")))
428 (tramp-async-args (("-q")))
429 (tramp-remote-sh "/bin/sh")
430 (tramp-copy-program "rsync")
431 (tramp-copy-args (("-t" "%k") ("-r")))
432 (tramp-copy-env (("RSYNC_RSH")
433 (,(concat
434 "ssh"
435 " -o ControlPath=%t.%%r@%%h:%%p"
436 " -o ControlMaster=auto"))))
437 (tramp-copy-keep-date t)
438 (tramp-copy-keep-tmpfile t)
439 (tramp-copy-recursive t)
440 (tramp-password-end-of-line nil))
441 ("remcp" (tramp-login-program "remsh")
442 (tramp-login-args (("%h") ("-l" "%u")))
443 (tramp-remote-sh "/bin/sh")
444 (tramp-copy-program "rcp")
445 (tramp-copy-args (("-p" "%k")))
446 (tramp-copy-keep-date t)
447 (tramp-password-end-of-line nil))
448 ("rsh" (tramp-login-program "rsh")
449 (tramp-login-args (("%h") ("-l" "%u")))
450 (tramp-remote-sh "/bin/sh")
451 (tramp-copy-program nil)
452 (tramp-copy-args nil)
453 (tramp-copy-keep-date nil)
454 (tramp-password-end-of-line nil))
455 ("ssh" (tramp-login-program "ssh")
456 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
457 ("-e" "none")))
458 (tramp-async-args (("-q")))
459 (tramp-remote-sh "/bin/sh")
460 (tramp-copy-program nil)
461 (tramp-copy-args nil)
462 (tramp-copy-keep-date nil)
463 (tramp-password-end-of-line nil)
464 (tramp-gw-args (("-o"
465 "GlobalKnownHostsFile=/dev/null")
466 ("-o" "UserKnownHostsFile=/dev/null")
467 ("-o" "StrictHostKeyChecking=no")))
468 (tramp-default-port 22))
469 ("ssh1" (tramp-login-program "ssh")
470 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
471 ("-1" "-e" "none")))
472 (tramp-async-args (("-q")))
473 (tramp-remote-sh "/bin/sh")
474 (tramp-copy-program nil)
475 (tramp-copy-args nil)
476 (tramp-copy-keep-date nil)
477 (tramp-password-end-of-line nil)
478 (tramp-gw-args (("-o"
479 "GlobalKnownHostsFile=/dev/null")
480 ("-o" "UserKnownHostsFile=/dev/null")
481 ("-o" "StrictHostKeyChecking=no")))
482 (tramp-default-port 22))
483 ("ssh2" (tramp-login-program "ssh")
484 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
485 ("-2" "-e" "none")))
486 (tramp-async-args (("-q")))
487 (tramp-remote-sh "/bin/sh")
488 (tramp-copy-program nil)
489 (tramp-copy-args nil)
490 (tramp-copy-keep-date nil)
491 (tramp-password-end-of-line nil)
492 (tramp-gw-args (("-o"
493 "GlobalKnownHostsFile=/dev/null")
494 ("-o" "UserKnownHostsFile=/dev/null")
495 ("-o" "StrictHostKeyChecking=no")))
496 (tramp-default-port 22))
497 ("ssh1_old"
498 (tramp-login-program "ssh1")
499 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
500 ("-e" "none")))
501 (tramp-async-args (("-q")))
502 (tramp-remote-sh "/bin/sh")
503 (tramp-copy-program nil)
504 (tramp-copy-args nil)
505 (tramp-copy-keep-date nil)
506 (tramp-password-end-of-line nil))
507 ("ssh2_old"
508 (tramp-login-program "ssh2")
509 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
510 ("-e" "none")))
511 (tramp-remote-sh "/bin/sh")
512 (tramp-copy-program nil)
513 (tramp-copy-args nil)
514 (tramp-copy-keep-date nil)
515 (tramp-password-end-of-line nil))
516 ("remsh" (tramp-login-program "remsh")
517 (tramp-login-args (("%h") ("-l" "%u")))
518 (tramp-remote-sh "/bin/sh")
519 (tramp-copy-program nil)
520 (tramp-copy-args nil)
521 (tramp-copy-keep-date nil)
522 (tramp-password-end-of-line nil))
523 ("telnet"
524 (tramp-login-program "telnet")
525 (tramp-login-args (("%h") ("%p")))
526 (tramp-remote-sh "/bin/sh")
527 (tramp-copy-program nil)
528 (tramp-copy-args nil)
529 (tramp-copy-keep-date nil)
530 (tramp-password-end-of-line nil)
531 (tramp-default-port 23))
532 ("su" (tramp-login-program "su")
533 (tramp-login-args (("-") ("%u")))
534 (tramp-remote-sh "/bin/sh")
535 (tramp-copy-program nil)
536 (tramp-copy-args nil)
537 (tramp-copy-keep-date nil)
538 (tramp-password-end-of-line nil))
539 ("sudo" (tramp-login-program "sudo")
540 (tramp-login-args (("-u" "%u")
541 ("-s") ("-H") ("-p" "Password:")))
542 (tramp-remote-sh "/bin/sh")
543 (tramp-copy-program nil)
544 (tramp-copy-args nil)
545 (tramp-copy-keep-date nil)
546 (tramp-password-end-of-line nil))
547 ("scpc" (tramp-login-program "ssh")
548 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
549 ("-o" "ControlPath=%t.%%r@%%h:%%p")
550 ("-o" "ControlMaster=yes")
551 ("-e" "none")))
552 (tramp-async-args (("-q")))
553 (tramp-remote-sh "/bin/sh")
554 (tramp-copy-program "scp")
555 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
556 ("-o" "ControlPath=%t.%%r@%%h:%%p")
557 ("-o" "ControlMaster=auto")))
558 (tramp-copy-keep-date t)
559 (tramp-password-end-of-line nil)
560 (tramp-gw-args (("-o"
561 "GlobalKnownHostsFile=/dev/null")
562 ("-o" "UserKnownHostsFile=/dev/null")
563 ("-o" "StrictHostKeyChecking=no")))
564 (tramp-default-port 22))
565 ("scpx" (tramp-login-program "ssh")
566 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
567 ("-e" "none" "-t" "-t" "/bin/sh")))
568 (tramp-async-args (("-q")))
569 (tramp-remote-sh "/bin/sh")
570 (tramp-copy-program "scp")
571 (tramp-copy-args (("-p" "%k")))
572 (tramp-copy-keep-date t)
573 (tramp-password-end-of-line nil)
574 (tramp-gw-args (("-o"
575 "GlobalKnownHostsFile=/dev/null")
576 ("-o" "UserKnownHostsFile=/dev/null")
577 ("-o" "StrictHostKeyChecking=no")))
578 (tramp-default-port 22))
579 ("sshx" (tramp-login-program "ssh")
580 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
581 ("-e" "none" "-t" "-t" "/bin/sh")))
582 (tramp-async-args (("-q")))
583 (tramp-remote-sh "/bin/sh")
584 (tramp-copy-program nil)
585 (tramp-copy-args nil)
586 (tramp-copy-keep-date nil)
587 (tramp-password-end-of-line nil)
588 (tramp-gw-args (("-o"
589 "GlobalKnownHostsFile=/dev/null")
590 ("-o" "UserKnownHostsFile=/dev/null")
591 ("-o" "StrictHostKeyChecking=no")))
592 (tramp-default-port 22))
593 ("krlogin"
594 (tramp-login-program "krlogin")
595 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
596 (tramp-remote-sh "/bin/sh")
597 (tramp-copy-program nil)
598 (tramp-copy-args nil)
599 (tramp-copy-keep-date nil)
600 (tramp-password-end-of-line nil))
601 ("plink" (tramp-login-program "plink")
602 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
603 ("-ssh")))
604 (tramp-remote-sh "/bin/sh")
605 (tramp-copy-program nil)
606 (tramp-copy-args nil)
607 (tramp-copy-keep-date nil)
608 (tramp-password-end-of-line "xy") ;see docstring for "xy"
609 (tramp-default-port 22))
610 ("plink1"
611 (tramp-login-program "plink")
612 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
613 ("-1" "-ssh")))
614 (tramp-remote-sh "/bin/sh")
615 (tramp-copy-program nil)
616 (tramp-copy-args nil)
617 (tramp-copy-keep-date nil)
618 (tramp-password-end-of-line "xy") ;see docstring for "xy"
619 (tramp-default-port 22))
620 ("plinkx"
621 (tramp-login-program "plink")
622 ;; ("%h") must be a single element, see
623 ;; `tramp-compute-multi-hops'.
624 (tramp-login-args (("-load") ("%h") ("-t")
625 (,(format
626 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
627 tramp-terminal-type
628 tramp-initial-end-of-output))
629 ("/bin/sh")))
630 (tramp-remote-sh "/bin/sh")
631 (tramp-copy-program nil)
632 (tramp-copy-args nil)
633 (tramp-copy-keep-date nil)
634 (tramp-password-end-of-line nil))
635 ("pscp" (tramp-login-program "plink")
636 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
637 ("-ssh")))
638 (tramp-remote-sh "/bin/sh")
639 (tramp-copy-program "pscp")
640 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
641 (tramp-copy-keep-date t)
642 (tramp-password-end-of-line "xy") ;see docstring for "xy"
643 (tramp-default-port 22))
644 ("psftp" (tramp-login-program "plink")
645 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
646 ("-ssh")))
647 (tramp-remote-sh "/bin/sh")
648 (tramp-copy-program "pscp")
649 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
650 (tramp-copy-keep-date t)
651 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
652 ("fcp" (tramp-login-program "fsh")
653 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
654 (tramp-remote-sh "/bin/sh -i")
655 (tramp-copy-program "fcp")
656 (tramp-copy-args (("-p" "%k")))
657 (tramp-copy-keep-date t)
658 (tramp-password-end-of-line nil)))
659 "*Alist of methods for remote files.
660 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
661 Each NAME stands for a remote access method. Each PARAM is a
662 pair of the form (KEY VALUE). The following KEYs are defined:
663 * `tramp-remote-sh'
664 This specifies the Bourne shell to use on the remote host. This
665 MUST be a Bourne-like shell. It is normally not necessary to set
666 this to any value other than \"/bin/sh\": Tramp wants to use a shell
667 which groks tilde expansion, but it can search for it. Also note
668 that \"/bin/sh\" exists on all Unixen, this might not be true for
669 the value that you decide to use. You Have Been Warned.
670 * `tramp-login-program'
671 This specifies the name of the program to use for logging in to the
672 remote host. This may be the name of rsh or a workalike program,
673 or the name of telnet or a workalike, or the name of su or a workalike.
674 * `tramp-login-args'
675 This specifies the list of arguments to pass to the above
676 mentioned program. Please note that this is a list of list of arguments,
677 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
678 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
679 There are some patterns: \"%h\" in this list is replaced by the host
680 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
681 port number, and \"%%\" can be used to obtain a literal percent character.
682 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
683 expansion (i.e. no host or no user specified), this list is not used as
684 argument. By this, arguments like (\"-l\" \"%u\") are optional.
685 \"%t\" is replaced by the temporary file name produced with
686 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
687 parameter of a program, if exists.
688 * `tramp-async-args'
689 When an asynchronous process is started, we know already that
690 the connection works. Therefore, we can pass additional
691 parameters to suppress diagnostic messages, in order not to
692 tamper the process output.
693 * `tramp-copy-program'
694 This specifies the name of the program to use for remotely copying
695 the file; this might be the absolute filename of rcp or the name of
696 a workalike program.
697 * `tramp-copy-args'
698 This specifies the list of parameters to pass to the above mentioned
699 program, the hints for `tramp-login-args' also apply here.
700 * `tramp-copy-keep-date'
701 This specifies whether the copying program when the preserves the
702 timestamp of the original file.
703 * `tramp-copy-keep-tmpfile'
704 This specifies whether a temporary local file shall be kept
705 for optimization reasons (useful for \"rsync\" methods).
706 * `tramp-copy-recursive'
707 Whether the operation copies directories recursively.
708 * `tramp-default-port'
709 The default port of a method is needed in case of gateway connections.
710 Additionally, it is used as indication which method is prepared for
711 passing gateways.
712 * `tramp-gw-args'
713 As the attribute name says, additional arguments are specified here
714 when a method is applied via a gateway.
715 * `tramp-password-end-of-line'
716 This specifies the string to use for terminating the line after
717 submitting the password. If this method parameter is nil, then the
718 value of the normal variable `tramp-default-password-end-of-line'
719 is used. This parameter is necessary because the \"plink\" program
720 requires any two characters after sending the password. These do
721 not have to be newline or carriage return characters. Other login
722 programs are happy with just one character, the newline character.
723 We use \"xy\" as the value for methods using \"plink\".
725 What does all this mean? Well, you should specify `tramp-login-program'
726 for all methods; this program is used to log in to the remote site. Then,
727 there are two ways to actually transfer the files between the local and the
728 remote side. One way is using an additional rcp-like program. If you want
729 to do this, set `tramp-copy-program' in the method.
731 Another possibility for file transfer is inline transfer, i.e. the
732 file is passed through the same buffer used by `tramp-login-program'. In
733 this case, the file contents need to be protected since the
734 `tramp-login-program' might use escape codes or the connection might not
735 be eight-bit clean. Therefore, file contents are encoded for transit.
736 See the variables `tramp-local-coding-commands' and
737 `tramp-remote-coding-commands' for details.
739 So, to summarize: if the method is an out-of-band method, then you
740 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
741 inline method, then these two parameters should be nil. Methods which
742 are fit for gateways must have `tramp-default-port' at least.
744 Notes:
746 When using `su' or `sudo' the phrase `open connection to a remote
747 host' sounds strange, but it is used nevertheless, for consistency.
748 No connection is opened to a remote host, but `su' or `sudo' is
749 started on the local host. You should specify a remote host
750 `localhost' or the name of the local host. Another host name is
751 useful only in combination with `tramp-default-proxies-alist'.")
753 (defun tramp-detect-ssh-controlmaster ()
754 "Call ssh to detect whether it supports the ControlMaster argument.
755 This function may return nil when the argument is supported, but
756 shouldn't return t when it isn't."
757 (ignore-errors
758 (with-temp-buffer
759 (call-process "ssh" nil t nil "-o" "ControlMaster")
760 (goto-char (point-min))
761 (search-forward-regexp "Missing ControlMaster argument" nil t))))
763 (defcustom tramp-default-method
764 ;; An external copy method seems to be preferred, because it is much
765 ;; more performant for large files, and it hasn't too serious delays
766 ;; for small files. But it must be ensured that there aren't
767 ;; permanent password queries. Either a password agent like
768 ;; "ssh-agent" or "Pageant" shall run, or the optional
769 ;; password-cache.el or auth-sources.el packages shall be active for
770 ;; password caching. "scpc" is chosen if we detect that the user is
771 ;; running OpenSSH 4.0 or newer.
772 (cond
773 ;; PuTTY is installed.
774 ((executable-find "pscp")
775 (if (or (fboundp 'password-read)
776 (fboundp 'auth-source-user-or-password)
777 ;; Pageant is running.
778 (tramp-compat-process-running-p "Pageant"))
779 "pscp"
780 "plink"))
781 ;; There is an ssh installation.
782 ((executable-find "scp")
783 (cond
784 ((tramp-detect-ssh-controlmaster) "scpc")
785 ((or (fboundp 'password-read)
786 (fboundp 'auth-source-user-or-password)
787 ;; ssh-agent is running.
788 (getenv "SSH_AUTH_SOCK")
789 (getenv "SSH_AGENT_PID"))
790 "scp")
791 (t "ssh")))
792 ;; Fallback.
793 (t "ftp"))
794 "*Default method to use for transferring files.
795 See `tramp-methods' for possibilities.
796 Also see `tramp-default-method-alist'."
797 :group 'tramp
798 :type 'string)
800 (defcustom tramp-default-method-alist
801 '(("\\`localhost\\'" "\\`root\\'" "su"))
802 "*Default method to use for specific host/user pairs.
803 This is an alist of items (HOST USER METHOD). The first matching item
804 specifies the method to use for a file name which does not specify a
805 method. HOST and USER are regular expressions or nil, which is
806 interpreted as a regular expression which always matches. If no entry
807 matches, the variable `tramp-default-method' takes effect.
809 If the file name does not specify the user, lookup is done using the
810 empty string for the user name.
812 See `tramp-methods' for a list of possibilities for METHOD."
813 :group 'tramp
814 :type '(repeat (list (regexp :tag "Host regexp")
815 (regexp :tag "User regexp")
816 (string :tag "Method"))))
818 (defcustom tramp-default-user
820 "*Default user to use for transferring files.
821 It is nil by default; otherwise settings in configuration files like
822 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
824 This variable is regarded as obsolete, and will be removed soon."
825 :group 'tramp
826 :type '(choice (const nil) string))
828 (defcustom tramp-default-user-alist
829 `(("\\`su\\(do\\)?\\'" nil "root")
830 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
831 nil ,(user-login-name)))
832 "*Default user to use for specific method/host pairs.
833 This is an alist of items (METHOD HOST USER). The first matching item
834 specifies the user to use for a file name which does not specify a
835 user. METHOD and USER are regular expressions or nil, which is
836 interpreted as a regular expression which always matches. If no entry
837 matches, the variable `tramp-default-user' takes effect.
839 If the file name does not specify the method, lookup is done using the
840 empty string for the method name."
841 :group 'tramp
842 :type '(repeat (list (regexp :tag "Method regexp")
843 (regexp :tag "Host regexp")
844 (string :tag "User"))))
846 (defcustom tramp-default-host
847 (system-name)
848 "*Default host to use for transferring files.
849 Useful for su and sudo methods mostly."
850 :group 'tramp
851 :type 'string)
853 (defcustom tramp-default-proxies-alist nil
854 "*Route to be followed for specific host/user pairs.
855 This is an alist of items (HOST USER PROXY). The first matching
856 item specifies the proxy to be passed for a file name located on
857 a remote target matching USER@HOST. HOST and USER are regular
858 expressions. PROXY must be a Tramp filename without a localname
859 part. Method and user name on PROXY are optional, which is
860 interpreted with the default values. PROXY can contain the
861 patterns %h and %u, which are replaced by the strings matching
862 HOST or USER, respectively.
864 HOST, USER or PROXY could also be Lisp forms, which will be
865 evaluated. The result must be a string or nil, which is
866 interpreted as a regular expression which always matches."
867 :group 'tramp
868 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
869 (choice :tag "User regexp" regexp sexp)
870 (choice :tag "Proxy remote name" string (const nil)))))
872 (defconst tramp-local-host-regexp
873 (concat
874 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
875 "*Host names which are regarded as local host.")
877 (defconst tramp-completion-function-alist-rsh
878 '((tramp-parse-rhosts "/etc/hosts.equiv")
879 (tramp-parse-rhosts "~/.rhosts"))
880 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
882 (defconst tramp-completion-function-alist-ssh
883 '((tramp-parse-rhosts "/etc/hosts.equiv")
884 (tramp-parse-rhosts "/etc/shosts.equiv")
885 (tramp-parse-shosts "/etc/ssh_known_hosts")
886 (tramp-parse-sconfig "/etc/ssh_config")
887 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
888 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
889 (tramp-parse-rhosts "~/.rhosts")
890 (tramp-parse-rhosts "~/.shosts")
891 (tramp-parse-shosts "~/.ssh/known_hosts")
892 (tramp-parse-sconfig "~/.ssh/config")
893 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
894 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
895 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
897 (defconst tramp-completion-function-alist-telnet
898 '((tramp-parse-hosts "/etc/hosts"))
899 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
901 (defconst tramp-completion-function-alist-su
902 '((tramp-parse-passwd "/etc/passwd"))
903 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
905 (defconst tramp-completion-function-alist-putty
906 '((tramp-parse-putty
907 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
908 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
910 (defvar tramp-completion-function-alist nil
911 "*Alist of methods for remote files.
912 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
913 Each NAME stands for a remote access method. Each PAIR is of the form
914 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
915 names from FILE for completion. The following predefined FUNCTIONs exists:
917 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
918 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
919 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
920 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
921 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
922 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
923 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
924 * `tramp-parse-netrc' for \"~/.netrc\" like files.
925 * `tramp-parse-putty' for PuTTY registry keys.
927 FUNCTION can also be a customer defined function. For more details see
928 the info pages.")
930 (eval-after-load "tramp"
931 '(progn
932 (tramp-set-completion-function
933 "rcp" tramp-completion-function-alist-rsh)
934 (tramp-set-completion-function
935 "scp" tramp-completion-function-alist-ssh)
936 (tramp-set-completion-function
937 "scp1" tramp-completion-function-alist-ssh)
938 (tramp-set-completion-function
939 "scp2" tramp-completion-function-alist-ssh)
940 (tramp-set-completion-function
941 "scp1_old" tramp-completion-function-alist-ssh)
942 (tramp-set-completion-function
943 "scp2_old" tramp-completion-function-alist-ssh)
944 (tramp-set-completion-function
945 "rsync" tramp-completion-function-alist-ssh)
946 (tramp-set-completion-function
947 "rsyncc" tramp-completion-function-alist-ssh)
948 (tramp-set-completion-function
949 "remcp" tramp-completion-function-alist-rsh)
950 (tramp-set-completion-function
951 "rsh" tramp-completion-function-alist-rsh)
952 (tramp-set-completion-function
953 "ssh" tramp-completion-function-alist-ssh)
954 (tramp-set-completion-function
955 "ssh1" tramp-completion-function-alist-ssh)
956 (tramp-set-completion-function
957 "ssh2" tramp-completion-function-alist-ssh)
958 (tramp-set-completion-function
959 "ssh1_old" tramp-completion-function-alist-ssh)
960 (tramp-set-completion-function
961 "ssh2_old" tramp-completion-function-alist-ssh)
962 (tramp-set-completion-function
963 "remsh" tramp-completion-function-alist-rsh)
964 (tramp-set-completion-function
965 "telnet" tramp-completion-function-alist-telnet)
966 (tramp-set-completion-function
967 "su" tramp-completion-function-alist-su)
968 (tramp-set-completion-function
969 "sudo" tramp-completion-function-alist-su)
970 (tramp-set-completion-function
971 "scpx" tramp-completion-function-alist-ssh)
972 (tramp-set-completion-function
973 "sshx" tramp-completion-function-alist-ssh)
974 (tramp-set-completion-function
975 "krlogin" tramp-completion-function-alist-rsh)
976 (tramp-set-completion-function
977 "plink" tramp-completion-function-alist-ssh)
978 (tramp-set-completion-function
979 "plink1" tramp-completion-function-alist-ssh)
980 (tramp-set-completion-function
981 "plinkx" tramp-completion-function-alist-putty)
982 (tramp-set-completion-function
983 "pscp" tramp-completion-function-alist-ssh)
984 (tramp-set-completion-function
985 "fcp" tramp-completion-function-alist-ssh)))
987 (defconst tramp-echo-mark-marker "_echo"
988 "String marker to surround echoed commands.")
990 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
991 "String length of `tramp-echo-mark-marker'.")
993 (defconst tramp-echo-mark
994 (concat tramp-echo-mark-marker
995 (make-string tramp-echo-mark-marker-length ?\b))
996 "String mark to be transmitted around shell commands.
997 Used to separate their echo from the output they produce. This
998 will only be used if we cannot disable remote echo via stty.
999 This string must have no effect on the remote shell except for
1000 producing some echo which can later be detected by
1001 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
1002 followed by an equal number of backspaces to erase them will
1003 usually suffice.")
1005 (defconst tramp-echoed-echo-mark-regexp
1006 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
1007 tramp-echo-mark-marker tramp-echo-mark-marker-length)
1008 "Regexp which matches `tramp-echo-mark' as it gets echoed by
1009 the remote shell.")
1011 (defcustom tramp-rsh-end-of-line "\n"
1012 "*String used for end of line in rsh connections.
1013 I don't think this ever needs to be changed, so please tell me about it
1014 if you need to change this.
1015 Also see the method parameter `tramp-password-end-of-line' and the normal
1016 variable `tramp-default-password-end-of-line'."
1017 :group 'tramp
1018 :type 'string)
1020 (defcustom tramp-default-password-end-of-line
1021 tramp-rsh-end-of-line
1022 "*String used for end of line after sending a password.
1023 This variable provides the default value for the method parameter
1024 `tramp-password-end-of-line', see `tramp-methods' for more details.
1026 It seems that people using plink under Windows need to send
1027 \"\\r\\n\" (carriage-return, then newline) after a password, but just
1028 \"\\n\" after all other lines. This variable can be used for the
1029 password, see `tramp-rsh-end-of-line' for the other cases.
1031 The default value is to use the same value as `tramp-rsh-end-of-line'."
1032 :group 'tramp
1033 :type 'string)
1035 ;; "getconf PATH" yields:
1036 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
1037 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
1038 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1039 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1040 (defcustom tramp-remote-path
1041 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1042 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1043 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1044 "*List of directories to search for executables on remote host.
1045 For every remote host, this variable will be set buffer local,
1046 keeping the list of existing directories on that host.
1048 You can use `~' in this list, but when searching for a shell which groks
1049 tilde expansion, all directory names starting with `~' will be ignored.
1051 `Default Directories' represent the list of directories given by
1052 the command \"getconf PATH\". It is recommended to use this
1053 entry on top of this list, because these are the default
1054 directories for POSIX compatible commands.
1056 `Private Directories' are the settings of the $PATH environment,
1057 as given in your `~/.profile'."
1058 :group 'tramp
1059 :type '(repeat (choice
1060 (const :tag "Default Directories" tramp-default-remote-path)
1061 (const :tag "Private Directories" tramp-own-remote-path)
1062 (string :tag "Directory"))))
1064 (defcustom tramp-remote-process-environment
1065 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1066 ,(format "TERM=%s" tramp-terminal-type)
1067 "EMACS=t" ;; Deprecated.
1068 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
1069 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1070 "autocorrect=" "correct=")
1072 "*List of environment variables to be set on the remote host.
1074 Each element should be a string of the form ENVVARNAME=VALUE. An
1075 entry ENVVARNAME= diables the corresponding environment variable,
1076 which might have been set in the init files like ~/.profile.
1078 Special handling is applied to the PATH environment, which should
1079 not be set here. Instead of, it should be set via `tramp-remote-path'."
1080 :group 'tramp
1081 :type '(repeat string))
1083 (defcustom tramp-login-prompt-regexp
1084 ".*ogin\\( .*\\)?: *"
1085 "*Regexp matching login-like prompts.
1086 The regexp should match at end of buffer.
1088 Sometimes the prompt is reported to look like \"login as:\"."
1089 :group 'tramp
1090 :type 'regexp)
1092 (defcustom tramp-shell-prompt-pattern
1093 ;; Allow a prompt to start right after a ^M since it indeed would be
1094 ;; displayed at the beginning of the line (and Zsh uses it).
1095 "\\(?:^\\|\r\\)[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
1096 "Regexp to match prompts from remote shell.
1097 Normally, Tramp expects you to configure `shell-prompt-pattern'
1098 correctly, but sometimes it happens that you are connecting to a
1099 remote host which sends a different kind of shell prompt. Therefore,
1100 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1101 and also things matched by this variable. The default value of this
1102 variable is similar to the default value of `shell-prompt-pattern',
1103 which should work well in many cases.
1105 This regexp must match both `tramp-initial-end-of-output' and
1106 `tramp-end-of-output'."
1107 :group 'tramp
1108 :type 'regexp)
1110 (defcustom tramp-password-prompt-regexp
1111 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1112 "*Regexp matching password-like prompts.
1113 The regexp should match at end of buffer.
1115 The `sudo' program appears to insert a `^@' character into the prompt."
1116 :group 'tramp
1117 :type 'regexp)
1119 (defcustom tramp-wrong-passwd-regexp
1120 (concat "^.*"
1121 ;; These strings should be on the last line
1122 (regexp-opt '("Permission denied"
1123 "Login incorrect"
1124 "Login Incorrect"
1125 "Connection refused"
1126 "Connection closed"
1127 "Timeout, server not responding."
1128 "Sorry, try again."
1129 "Name or service not known"
1130 "Host key verification failed."
1131 "No supported authentication methods left to try!") t)
1132 ".*"
1133 "\\|"
1134 "^.*\\("
1135 ;; Here comes a list of regexes, separated by \\|
1136 "Received signal [0-9]+"
1137 "\\).*")
1138 "*Regexp matching a `login failed' message.
1139 The regexp should match at end of buffer."
1140 :group 'tramp
1141 :type 'regexp)
1143 (defcustom tramp-yesno-prompt-regexp
1144 (concat
1145 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1146 "\\s-*")
1147 "Regular expression matching all yes/no queries which need to be confirmed.
1148 The confirmation should be done with yes or no.
1149 The regexp should match at end of buffer.
1150 See also `tramp-yn-prompt-regexp'."
1151 :group 'tramp
1152 :type 'regexp)
1154 (defcustom tramp-yn-prompt-regexp
1155 (concat
1156 (regexp-opt '("Store key in cache? (y/n)"
1157 "Update cached key? (y/n, Return cancels connection)") t)
1158 "\\s-*")
1159 "Regular expression matching all y/n queries which need to be confirmed.
1160 The confirmation should be done with y or n.
1161 The regexp should match at end of buffer.
1162 See also `tramp-yesno-prompt-regexp'."
1163 :group 'tramp
1164 :type 'regexp)
1166 (defcustom tramp-terminal-prompt-regexp
1167 (concat "\\("
1168 "TERM = (.*)"
1169 "\\|"
1170 "Terminal type\\? \\[.*\\]"
1171 "\\)\\s-*")
1172 "Regular expression matching all terminal setting prompts.
1173 The regexp should match at end of buffer.
1174 The answer will be provided by `tramp-action-terminal', which see."
1175 :group 'tramp
1176 :type 'regexp)
1178 (defcustom tramp-operation-not-permitted-regexp
1179 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1180 (regexp-opt '("Operation not permitted") t))
1181 "Regular expression matching keep-date problems in (s)cp operations.
1182 Copying has been performed successfully already, so this message can
1183 be ignored safely."
1184 :group 'tramp
1185 :type 'regexp)
1187 (defcustom tramp-copy-failed-regexp
1188 (concat "\\(.+: "
1189 (regexp-opt '("Permission denied"
1190 "not a regular file"
1191 "is a directory"
1192 "No such file or directory") t)
1193 "\\)\\s-*")
1194 "Regular expression matching copy problems in (s)cp operations."
1195 :group 'tramp
1196 :type 'regexp)
1198 (defcustom tramp-process-alive-regexp
1200 "Regular expression indicating a process has finished.
1201 In fact this expression is empty by intention, it will be used only to
1202 check regularly the status of the associated process.
1203 The answer will be provided by `tramp-action-process-alive',
1204 `tramp-action-out-of-band', which see."
1205 :group 'tramp
1206 :type 'regexp)
1208 (defcustom tramp-temp-name-prefix "tramp."
1209 "*Prefix to use for temporary files.
1210 If this is a relative file name (such as \"tramp.\"), it is considered
1211 relative to the directory name returned by the function
1212 `tramp-compat-temporary-file-directory' (which see). It may also be an
1213 absolute file name; don't forget to include a prefix for the filename
1214 part, though."
1215 :group 'tramp
1216 :type 'string)
1218 (defconst tramp-temp-buffer-name " *tramp temp*"
1219 "Buffer name for a temporary buffer.
1220 It shall be used in combination with `generate-new-buffer-name'.")
1222 (defvar tramp-temp-buffer-file-name nil
1223 "File name of a persistent local temporary file.
1224 Useful for \"rsync\" like methods.")
1225 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1227 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1228 "*Alist specifying extra arguments to pass to the remote shell.
1229 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1230 matching the shell file name and ARGS is a string specifying the
1231 arguments.
1233 This variable is only used when Tramp needs to start up another shell
1234 for tilde expansion. The extra arguments should typically prevent the
1235 shell from reading its init file."
1236 :group 'tramp
1237 ;; This might be the wrong way to test whether the widget type
1238 ;; `alist' is available. Who knows the right way to test it?
1239 :type (if (get 'alist 'widget-type)
1240 '(alist :key-type string :value-type string)
1241 '(repeat (cons string string))))
1243 ;; XEmacs is distributed with few Lisp packages. Further packages are
1244 ;; installed using EFS. If we use a unified filename format, then
1245 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1246 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1247 ;; just like before.) Another reason for using a separate filename
1248 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1249 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1250 ;; the other places.
1252 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1253 ;;;###autoload
1254 (defcustom tramp-syntax
1255 (if (featurep 'xemacs) 'sep 'ftp)
1256 "Tramp filename syntax to be used.
1258 It can have the following values:
1260 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1261 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1262 'url -- URL-like syntax."
1263 :group 'tramp
1264 :type (if (featurep 'xemacs)
1265 '(choice (const :tag "EFS" ftp)
1266 (const :tag "XEmacs" sep)
1267 (const :tag "URL" url))
1268 '(choice (const :tag "Ange-FTP" ftp)
1269 (const :tag "URL" url))))
1271 (defconst tramp-prefix-format
1272 (cond ((equal tramp-syntax 'ftp) "/")
1273 ((equal tramp-syntax 'sep) "/[")
1274 ((equal tramp-syntax 'url) "/")
1275 (t (error "Wrong `tramp-syntax' defined")))
1276 "*String matching the very beginning of Tramp file names.
1277 Used in `tramp-make-tramp-file-name'.")
1279 (defconst tramp-prefix-regexp
1280 (concat "^" (regexp-quote tramp-prefix-format))
1281 "*Regexp matching the very beginning of Tramp file names.
1282 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1284 (defconst tramp-method-regexp
1285 "[a-zA-Z_0-9-]+"
1286 "*Regexp matching methods identifiers.")
1288 (defconst tramp-postfix-method-format
1289 (cond ((equal tramp-syntax 'ftp) ":")
1290 ((equal tramp-syntax 'sep) "/")
1291 ((equal tramp-syntax 'url) "://")
1292 (t (error "Wrong `tramp-syntax' defined")))
1293 "*String matching delimeter between method and user or host names.
1294 Used in `tramp-make-tramp-file-name'.")
1296 (defconst tramp-postfix-method-regexp
1297 (regexp-quote tramp-postfix-method-format)
1298 "*Regexp matching delimeter between method and user or host names.
1299 Derived from `tramp-postfix-method-format'.")
1301 (defconst tramp-user-regexp
1302 "[^:/ \t]+"
1303 "*Regexp matching user names.")
1305 (defconst tramp-prefix-domain-format "%"
1306 "*String matching delimeter between user and domain names.")
1308 (defconst tramp-prefix-domain-regexp
1309 (regexp-quote tramp-prefix-domain-format)
1310 "*Regexp matching delimeter between user and domain names.
1311 Derived from `tramp-prefix-domain-format'.")
1313 (defconst tramp-domain-regexp
1314 "[-a-zA-Z0-9_.]+"
1315 "*Regexp matching domain names.")
1317 (defconst tramp-user-with-domain-regexp
1318 (concat "\\(" tramp-user-regexp "\\)"
1319 tramp-prefix-domain-regexp
1320 "\\(" tramp-domain-regexp "\\)")
1321 "*Regexp matching user names with domain names.")
1323 (defconst tramp-postfix-user-format
1325 "*String matching delimeter between user and host names.
1326 Used in `tramp-make-tramp-file-name'.")
1328 (defconst tramp-postfix-user-regexp
1329 (regexp-quote tramp-postfix-user-format)
1330 "*Regexp matching delimeter between user and host names.
1331 Derived from `tramp-postfix-user-format'.")
1333 (defconst tramp-host-regexp
1334 "[a-zA-Z0-9_.-]+"
1335 "*Regexp matching host names.")
1337 (defconst tramp-prefix-ipv6-format
1338 (cond ((equal tramp-syntax 'ftp) "[")
1339 ((equal tramp-syntax 'sep) "")
1340 ((equal tramp-syntax 'url) "[")
1341 (t (error "Wrong `tramp-syntax' defined")))
1342 "*String matching left hand side of IPv6 addresses.
1343 Used in `tramp-make-tramp-file-name'.")
1345 (defconst tramp-prefix-ipv6-regexp
1346 (regexp-quote tramp-prefix-ipv6-format)
1347 "*Regexp matching left hand side of IPv6 addresses.
1348 Derived from `tramp-prefix-ipv6-format'.")
1350 ;; The following regexp is a bit sloppy. But it shall serve our
1351 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1352 ;; "::ffff:192.168.0.1".
1353 (defconst tramp-ipv6-regexp
1354 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1355 "*Regexp matching IPv6 addresses.")
1357 (defconst tramp-postfix-ipv6-format
1358 (cond ((equal tramp-syntax 'ftp) "]")
1359 ((equal tramp-syntax 'sep) "")
1360 ((equal tramp-syntax 'url) "]")
1361 (t (error "Wrong `tramp-syntax' defined")))
1362 "*String matching right hand side of IPv6 addresses.
1363 Used in `tramp-make-tramp-file-name'.")
1365 (defconst tramp-postfix-ipv6-regexp
1366 (regexp-quote tramp-postfix-ipv6-format)
1367 "*Regexp matching right hand side of IPv6 addresses.
1368 Derived from `tramp-postfix-ipv6-format'.")
1370 (defconst tramp-prefix-port-format
1371 (cond ((equal tramp-syntax 'ftp) "#")
1372 ((equal tramp-syntax 'sep) "#")
1373 ((equal tramp-syntax 'url) ":")
1374 (t (error "Wrong `tramp-syntax' defined")))
1375 "*String matching delimeter between host names and port numbers.")
1377 (defconst tramp-prefix-port-regexp
1378 (regexp-quote tramp-prefix-port-format)
1379 "*Regexp matching delimeter between host names and port numbers.
1380 Derived from `tramp-prefix-port-format'.")
1382 (defconst tramp-port-regexp
1383 "[0-9]+"
1384 "*Regexp matching port numbers.")
1386 (defconst tramp-host-with-port-regexp
1387 (concat "\\(" tramp-host-regexp "\\)"
1388 tramp-prefix-port-regexp
1389 "\\(" tramp-port-regexp "\\)")
1390 "*Regexp matching host names with port numbers.")
1392 (defconst tramp-postfix-host-format
1393 (cond ((equal tramp-syntax 'ftp) ":")
1394 ((equal tramp-syntax 'sep) "]")
1395 ((equal tramp-syntax 'url) "")
1396 (t (error "Wrong `tramp-syntax' defined")))
1397 "*String matching delimeter between host names and localnames.
1398 Used in `tramp-make-tramp-file-name'.")
1400 (defconst tramp-postfix-host-regexp
1401 (regexp-quote tramp-postfix-host-format)
1402 "*Regexp matching delimeter between host names and localnames.
1403 Derived from `tramp-postfix-host-format'.")
1405 (defconst tramp-localname-regexp
1406 ".*$"
1407 "*Regexp matching localnames.")
1409 ;; File name format.
1411 (defconst tramp-file-name-structure
1412 (list
1413 (concat
1414 tramp-prefix-regexp
1415 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1416 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1417 "\\(" "\\(" tramp-host-regexp
1418 "\\|"
1419 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1420 tramp-postfix-ipv6-regexp "\\)"
1421 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1422 tramp-postfix-host-regexp
1423 "\\(" tramp-localname-regexp "\\)")
1424 2 4 5 8)
1426 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1427 the Tramp file name structure.
1429 The first element REGEXP is a regular expression matching a Tramp file
1430 name. The regex should contain parentheses around the method name,
1431 the user name, the host name, and the file name parts.
1433 The second element METHOD is a number, saying which pair of
1434 parentheses matches the method name. The third element USER is
1435 similar, but for the user name. The fourth element HOST is similar,
1436 but for the host name. The fifth element FILE is for the file name.
1437 These numbers are passed directly to `match-string', which see. That
1438 means the opening parentheses are counted to identify the pair.
1440 See also `tramp-file-name-regexp'.")
1442 ;;;###autoload
1443 (defconst tramp-file-name-regexp-unified
1444 "\\`/\\([^[/:]+\\|[^/]+]\\):"
1445 "Value for `tramp-file-name-regexp' for unified remoting.
1446 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1447 Tramp. See `tramp-file-name-structure' for more explanations.")
1449 ;;;###autoload
1450 (defconst tramp-file-name-regexp-separate
1451 "\\`/\\[.*\\]"
1452 "Value for `tramp-file-name-regexp' for separate remoting.
1453 XEmacs uses a separate filename syntax for Tramp and EFS.
1454 See `tramp-file-name-structure' for more explanations.")
1456 ;;;###autoload
1457 (defconst tramp-file-name-regexp-url
1458 "\\`/[^/:]+://"
1459 "Value for `tramp-file-name-regexp' for URL-like remoting.
1460 See `tramp-file-name-structure' for more explanations.")
1462 ;;;###autoload
1463 (defconst tramp-file-name-regexp
1464 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1465 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1466 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1467 (t (error "Wrong `tramp-syntax' defined")))
1468 "*Regular expression matching file names handled by Tramp.
1469 This regexp should match Tramp file names but no other file names.
1470 When tramp.el is loaded, this regular expression is prepended to
1471 `file-name-handler-alist', and that is searched sequentially. Thus,
1472 if the Tramp entry appears rather early in the `file-name-handler-alist'
1473 and is a bit too general, then some files might be considered Tramp
1474 files which are not really Tramp files.
1476 Please note that the entry in `file-name-handler-alist' is made when
1477 this file \(tramp.el\) is loaded. This means that this variable must be set
1478 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1479 updated after changing this variable.
1481 Also see `tramp-file-name-structure'.")
1483 ;;;###autoload
1484 (defconst tramp-root-regexp
1485 (if (memq system-type '(cygwin windows-nt))
1486 "\\`\\([a-zA-Z]:\\)?/"
1487 "\\`/")
1488 "Beginning of an incomplete Tramp file name.
1489 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1490 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1492 ;;;###autoload
1493 (defconst tramp-completion-file-name-regexp-unified
1494 (concat tramp-root-regexp "[^/]*\\'")
1495 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1496 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1497 See `tramp-file-name-structure' for more explanations.")
1499 ;;;###autoload
1500 (defconst tramp-completion-file-name-regexp-separate
1501 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1502 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1503 XEmacs uses a separate filename syntax for Tramp and EFS.
1504 See `tramp-file-name-structure' for more explanations.")
1506 ;;;###autoload
1507 (defconst tramp-completion-file-name-regexp-url
1508 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1509 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1510 See `tramp-file-name-structure' for more explanations.")
1512 ;;;###autoload
1513 (defconst tramp-completion-file-name-regexp
1514 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1515 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1516 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1517 (t (error "Wrong `tramp-syntax' defined")))
1518 "*Regular expression matching file names handled by Tramp completion.
1519 This regexp should match partial Tramp file names only.
1521 Please note that the entry in `file-name-handler-alist' is made when
1522 this file (tramp.el) is loaded. This means that this variable must be set
1523 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1524 updated after changing this variable.
1526 Also see `tramp-file-name-structure'.")
1528 (defconst tramp-actions-before-shell
1529 '((tramp-login-prompt-regexp tramp-action-login)
1530 (tramp-password-prompt-regexp tramp-action-password)
1531 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1532 (shell-prompt-pattern tramp-action-succeed)
1533 (tramp-shell-prompt-pattern tramp-action-succeed)
1534 (tramp-yesno-prompt-regexp tramp-action-yesno)
1535 (tramp-yn-prompt-regexp tramp-action-yn)
1536 (tramp-terminal-prompt-regexp tramp-action-terminal)
1537 (tramp-process-alive-regexp tramp-action-process-alive))
1538 "List of pattern/action pairs.
1539 Whenever a pattern matches, the corresponding action is performed.
1540 Each item looks like (PATTERN ACTION).
1542 The PATTERN should be a symbol, a variable. The value of this
1543 variable gives the regular expression to search for. Note that the
1544 regexp must match at the end of the buffer, \"\\'\" is implicitly
1545 appended to it.
1547 The ACTION should also be a symbol, but a function. When the
1548 corresponding PATTERN matches, the ACTION function is called.")
1550 (defconst tramp-actions-copy-out-of-band
1551 '((tramp-password-prompt-regexp tramp-action-password)
1552 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1553 (tramp-copy-failed-regexp tramp-action-permission-denied)
1554 (tramp-process-alive-regexp tramp-action-out-of-band))
1555 "List of pattern/action pairs.
1556 This list is used for copying/renaming with out-of-band methods.
1558 See `tramp-actions-before-shell' for more info.")
1560 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1561 ;; known to have a bug in `process-send-string'; some ssh connections appear
1562 ;; to drop bytes when data is sent too quickly. There is also a connection
1563 ;; buffer local variable, which is computed depending on remote host properties
1564 ;; when `tramp-chunksize' is zero or nil.
1565 (defcustom tramp-chunksize
1566 (when (and (not (featurep 'xemacs))
1567 (memq system-type '(hpux)))
1568 500)
1569 ;; Parentheses in docstring starting at beginning of line are escaped.
1570 ;; Fontification is messed up when
1571 ;; `open-paren-in-column-0-is-defun-start' set to t.
1572 "*If non-nil, chunksize for sending input to local process.
1573 It is necessary only on systems which have a buggy `process-send-string'
1574 implementation. The necessity, whether this variable must be set, can be
1575 checked via the following code:
1577 (with-temp-buffer
1578 (let* ((user \"xxx\") (host \"yyy\")
1579 (init 0) (step 50)
1580 (sent init) (received init))
1581 (while (= sent received)
1582 (setq sent (+ sent step))
1583 (erase-buffer)
1584 (let ((proc (start-process (buffer-name) (current-buffer)
1585 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1586 (when (memq (process-status proc) '(run open))
1587 (process-send-string proc (make-string sent ?\\ ))
1588 (process-send-eof proc)
1589 (process-send-eof proc))
1590 (while (not (progn (goto-char (point-min))
1591 (re-search-forward \"\\\\w+\" (point-max) t)))
1592 (accept-process-output proc 1))
1593 (when (memq (process-status proc) '(run open))
1594 (setq received (string-to-number (match-string 0)))
1595 (delete-process proc)
1596 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1597 (sit-for 0))))
1598 (if (> sent (+ init step))
1599 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1600 (- sent step))
1601 (message \"Test does not work\")
1602 (display-buffer (current-buffer))
1603 (sit-for 30))))
1605 In the Emacs normally running Tramp, evaluate the above code
1606 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1607 respectively\). You can do this, for example, by pasting it into
1608 the `*scratch*' buffer and then hitting C-j with the cursor after the
1609 last closing parenthesis. Note that it works only if you have configured
1610 \"ssh\" to run without password query, see ssh-agent\(1\).
1612 You will see the number of bytes sent successfully to the remote host.
1613 If that number exceeds 1000, you can stop the execution by hitting
1614 C-g, because your Emacs is likely clean.
1616 When it is necessary to set `tramp-chunksize', you might consider to
1617 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1618 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
1619 performance.
1621 If your Emacs is buggy, the code stops and gives you an indication
1622 about the value `tramp-chunksize' should be set. Maybe you could just
1623 experiment a bit, e.g. changing the values of `init' and `step'
1624 in the third line of the code.
1626 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1627 this variable to be set as well."
1628 :group 'tramp
1629 :type '(choice (const nil) integer))
1631 ;; Logging in to a remote host normally requires obtaining a pty. But
1632 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1633 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1634 ;; for an override of the system default.
1635 (defcustom tramp-process-connection-type t
1636 "Overrides `process-connection-type' for connections from Tramp.
1637 Tramp binds process-connection-type to the value given here before
1638 opening a connection to a remote host."
1639 :group 'tramp
1640 :type '(choice (const nil) (const t) (const pty)))
1642 (defcustom tramp-completion-reread-directory-timeout 10
1643 "Defines seconds since last remote command before rereading a directory.
1644 A remote directory might have changed its contents. In order to
1645 make it visible during file name completion in the minibuffer,
1646 Tramp flushes its cache and rereads the directory contents when
1647 more than `tramp-completion-reread-directory-timeout' seconds
1648 have been gone since last remote command execution. A value of 0
1649 would require an immediate reread during filename completion, nil
1650 means to use always cached values for the directory contents."
1651 :group 'tramp
1652 :type '(choice (const nil) integer))
1654 ;;; Internal Variables:
1656 (defvar tramp-current-method nil
1657 "Connection method for this *tramp* buffer.")
1659 (defvar tramp-current-user nil
1660 "Remote login name for this *tramp* buffer.")
1662 (defvar tramp-current-host nil
1663 "Remote host for this *tramp* buffer.")
1665 (defconst tramp-uudecode
1666 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1667 cat /tmp/tramp.$$
1668 rm -f /tmp/tramp.$$"
1669 "Shell function to implement `uudecode' to standard output.
1670 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1671 for this or `uudecode -p', but some systems don't, and for them
1672 we have this shell function.")
1674 (defconst tramp-perl-file-truename
1675 "%s -e '
1676 use File::Spec;
1677 use Cwd \"realpath\";
1679 sub recursive {
1680 my ($volume, @dirs) = @_;
1681 my $real = realpath(File::Spec->catpath(
1682 $volume, File::Spec->catdir(@dirs), \"\"));
1683 if ($real) {
1684 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1685 return ($vol, File::Spec->splitdir($dir));
1687 else {
1688 my $last = pop(@dirs);
1689 ($volume, @dirs) = recursive($volume, @dirs);
1690 push(@dirs, $last);
1691 return ($volume, @dirs);
1695 $result = realpath($ARGV[0]);
1696 if (!$result) {
1697 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1698 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1700 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1703 if ($ARGV[0] =~ /\\/$/) {
1704 $result = $result . \"/\";
1707 print \"\\\"$result\\\"\\n\";
1708 ' \"$1\" 2>/dev/null"
1709 "Perl script to produce output suitable for use with `file-truename'
1710 on the remote file system.
1711 Escape sequence %s is replaced with name of Perl binary.
1712 This string is passed to `format', so percent characters need to be doubled.")
1714 (defconst tramp-perl-file-name-all-completions
1715 "%s -e 'sub case {
1716 my $str = shift;
1717 if ($ARGV[2]) {
1718 return lc($str);
1720 else {
1721 return $str;
1724 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1725 @files = readdir(d); closedir(d);
1726 foreach $f (@files) {
1727 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1728 if (-d \"$ARGV[0]/$f\") {
1729 print \"$f/\\n\";
1731 else {
1732 print \"$f\\n\";
1736 print \"ok\\n\"
1737 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1738 "Perl script to produce output suitable for use with
1739 `file-name-all-completions' on the remote file system. Escape
1740 sequence %s is replaced with name of Perl binary. This string is
1741 passed to `format', so percent characters need to be doubled.")
1743 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1744 ;; output. If you are hacking on this, note that you get *no* output
1745 ;; unless this spits out a complete line, including the '\n' at the
1746 ;; end.
1747 ;; The device number is returned as "-1", because there will be a virtual
1748 ;; device number set in `tramp-handle-file-attributes'.
1749 (defconst tramp-perl-file-attributes
1750 "%s -e '
1751 @stat = lstat($ARGV[0]);
1752 if (!@stat) {
1753 print \"nil\\n\";
1754 exit 0;
1756 if (($stat[2] & 0170000) == 0120000)
1758 $type = readlink($ARGV[0]);
1759 $type = \"\\\"$type\\\"\";
1761 elsif (($stat[2] & 0170000) == 040000)
1763 $type = \"t\";
1765 else
1767 $type = \"nil\"
1769 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1770 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1771 printf(
1772 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1773 $type,
1774 $stat[3],
1775 $uid,
1776 $gid,
1777 $stat[8] >> 16 & 0xffff,
1778 $stat[8] & 0xffff,
1779 $stat[9] >> 16 & 0xffff,
1780 $stat[9] & 0xffff,
1781 $stat[10] >> 16 & 0xffff,
1782 $stat[10] & 0xffff,
1783 $stat[7],
1784 $stat[2],
1785 $stat[1] >> 16 & 0xffff,
1786 $stat[1] & 0xffff
1787 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1788 "Perl script to produce output suitable for use with `file-attributes'
1789 on the remote file system.
1790 Escape sequence %s is replaced with name of Perl binary.
1791 This string is passed to `format', so percent characters need to be doubled.")
1793 (defconst tramp-perl-directory-files-and-attributes
1794 "%s -e '
1795 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1796 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1797 @list = readdir(DIR);
1798 closedir(DIR);
1799 $n = scalar(@list);
1800 printf(\"(\\n\");
1801 for($i = 0; $i < $n; $i++)
1803 $filename = $list[$i];
1804 @stat = lstat($filename);
1805 if (($stat[2] & 0170000) == 0120000)
1807 $type = readlink($filename);
1808 $type = \"\\\"$type\\\"\";
1810 elsif (($stat[2] & 0170000) == 040000)
1812 $type = \"t\";
1814 else
1816 $type = \"nil\"
1818 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1819 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1820 printf(
1821 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1822 $filename,
1823 $type,
1824 $stat[3],
1825 $uid,
1826 $gid,
1827 $stat[8] >> 16 & 0xffff,
1828 $stat[8] & 0xffff,
1829 $stat[9] >> 16 & 0xffff,
1830 $stat[9] & 0xffff,
1831 $stat[10] >> 16 & 0xffff,
1832 $stat[10] & 0xffff,
1833 $stat[7],
1834 $stat[2],
1835 $stat[1] >> 16 & 0xffff,
1836 $stat[1] & 0xffff,
1837 $stat[0] >> 16 & 0xffff,
1838 $stat[0] & 0xffff);
1840 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1841 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1842 output.
1843 Escape sequence %s is replaced with name of Perl binary.
1844 This string is passed to `format', so percent characters need to be doubled.")
1846 ;; ;; These two use uu encoding.
1847 ;; (defvar tramp-perl-encode "%s -e'\
1848 ;; print qq(begin 644 xxx\n);
1849 ;; my $s = q();
1850 ;; my $res = q();
1851 ;; while (read(STDIN, $s, 45)) {
1852 ;; print pack(q(u), $s);
1853 ;; }
1854 ;; print qq(`\n);
1855 ;; print qq(end\n);
1856 ;; '"
1857 ;; "Perl program to use for encoding a file.
1858 ;; Escape sequence %s is replaced with name of Perl binary.")
1860 ;; (defvar tramp-perl-decode "%s -ne '
1861 ;; print unpack q(u), $_;
1862 ;; '"
1863 ;; "Perl program to use for decoding a file.
1864 ;; Escape sequence %s is replaced with name of Perl binary.")
1866 ;; These two use base64 encoding.
1867 (defconst tramp-perl-encode-with-module
1868 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1869 "Perl program to use for encoding a file.
1870 Escape sequence %s is replaced with name of Perl binary.
1871 This string is passed to `format', so percent characters need to be doubled.
1872 This implementation requires the MIME::Base64 Perl module to be installed
1873 on the remote host.")
1875 (defconst tramp-perl-decode-with-module
1876 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1877 "Perl program to use for decoding a file.
1878 Escape sequence %s is replaced with name of Perl binary.
1879 This string is passed to `format', so percent characters need to be doubled.
1880 This implementation requires the MIME::Base64 Perl module to be installed
1881 on the remote host.")
1883 (defconst tramp-perl-encode
1884 "%s -e '
1885 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1886 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1887 # Free Software Foundation, Inc.
1888 use strict;
1890 my %%trans = do {
1891 my $i = 0;
1892 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1893 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1896 binmode(\\*STDIN);
1898 # We read in chunks of 54 bytes, to generate output lines
1899 # of 72 chars (plus end of line)
1900 $/ = \\54;
1902 while (my $data = <STDIN>) {
1903 my $pad = q();
1905 # Only for the last chunk, and only if did not fill the last three-byte packet
1906 if (eof) {
1907 my $mod = length($data) %% 3;
1908 $pad = q(=) x (3 - $mod) if $mod;
1911 # Not the fastest method, but it is simple: unpack to binary string, split
1912 # by groups of 6 bits and convert back from binary to byte; then map into
1913 # the translation table
1914 print
1915 join q(),
1916 map($trans{$_},
1917 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1918 $pad,
1919 qq(\\n);
1920 }' 2>/dev/null"
1921 "Perl program to use for encoding a file.
1922 Escape sequence %s is replaced with name of Perl binary.
1923 This string is passed to `format', so percent characters need to be doubled.")
1925 (defconst tramp-perl-decode
1926 "%s -e '
1927 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1928 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1929 # Free Software Foundation, Inc.
1930 use strict;
1932 my %%trans = do {
1933 my $i = 0;
1934 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1935 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1938 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1940 binmode(\\*STDOUT);
1942 # We are going to accumulate into $pending to accept any line length
1943 # (we do not check they are <= 76 chars as the RFC says)
1944 my $pending = q();
1946 while (my $data = <STDIN>) {
1947 chomp $data;
1949 # If we find one or two =, we have reached the end and
1950 # any following data is to be discarded
1951 my $finished = $data =~ s/(==?).*/$1/;
1952 $pending .= $data;
1954 my $len = length($pending);
1955 my $chunk = substr($pending, 0, $len & ~3);
1956 $pending = substr($pending, $len & ~3 + 1);
1958 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1959 # split in 8-bit chunks and convert back to char.
1960 print join q(),
1961 map $bytes{$_},
1962 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1964 last if $finished;
1965 }' 2>/dev/null"
1966 "Perl program to use for decoding a file.
1967 Escape sequence %s is replaced with name of Perl binary.
1968 This string is passed to `format', so percent characters need to be doubled.")
1970 (defconst tramp-vc-registered-read-file-names
1971 "echo \"(\"
1972 for file in \"$@\"; do
1973 if %s $file; then
1974 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1975 else
1976 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1978 if %s $file; then
1979 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1980 else
1981 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1983 done
1984 echo \")\""
1985 "Script to check existence of VC related files.
1986 It must be send formatted with two strings; the tests for file
1987 existence, and file readability.")
1989 (defconst tramp-file-mode-type-map
1990 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1991 (1 . "p") ; fifo
1992 (2 . "c") ; character device
1993 (3 . "m") ; multiplexed character device (v7)
1994 (4 . "d") ; directory
1995 (5 . "?") ; Named special file (XENIX)
1996 (6 . "b") ; block device
1997 (7 . "?") ; multiplexed block device (v7)
1998 (8 . "-") ; regular file
1999 (9 . "n") ; network special file (HP-UX)
2000 (10 . "l") ; symlink
2001 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
2002 (12 . "s") ; socket
2003 (13 . "D") ; door special (Solaris)
2004 (14 . "w")) ; whiteout (BSD)
2005 "A list of file types returned from the `stat' system call.
2006 This is used to map a mode number to a permission string.")
2008 ;; New handlers should be added here. The following operations can be
2009 ;; handled using the normal primitives: file-name-sans-versions,
2010 ;; get-file-buffer.
2011 (defconst tramp-file-name-handler-alist
2012 '((load . tramp-handle-load)
2013 (make-symbolic-link . tramp-handle-make-symbolic-link)
2014 (file-name-as-directory . tramp-handle-file-name-as-directory)
2015 (file-name-directory . tramp-handle-file-name-directory)
2016 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
2017 (file-truename . tramp-handle-file-truename)
2018 (file-exists-p . tramp-handle-file-exists-p)
2019 (file-directory-p . tramp-handle-file-directory-p)
2020 (file-executable-p . tramp-handle-file-executable-p)
2021 (file-readable-p . tramp-handle-file-readable-p)
2022 (file-regular-p . tramp-handle-file-regular-p)
2023 (file-symlink-p . tramp-handle-file-symlink-p)
2024 (file-writable-p . tramp-handle-file-writable-p)
2025 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
2026 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
2027 (file-attributes . tramp-handle-file-attributes)
2028 (file-modes . tramp-handle-file-modes)
2029 (directory-files . tramp-handle-directory-files)
2030 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
2031 (file-name-all-completions . tramp-handle-file-name-all-completions)
2032 (file-name-completion . tramp-handle-file-name-completion)
2033 (add-name-to-file . tramp-handle-add-name-to-file)
2034 (copy-file . tramp-handle-copy-file)
2035 (copy-directory . tramp-handle-copy-directory)
2036 (rename-file . tramp-handle-rename-file)
2037 (set-file-modes . tramp-handle-set-file-modes)
2038 (set-file-times . tramp-handle-set-file-times)
2039 (make-directory . tramp-handle-make-directory)
2040 (delete-directory . tramp-handle-delete-directory)
2041 (delete-file . tramp-handle-delete-file)
2042 (directory-file-name . tramp-handle-directory-file-name)
2043 ;; `executable-find' is not official yet.
2044 (executable-find . tramp-handle-executable-find)
2045 (start-file-process . tramp-handle-start-file-process)
2046 (process-file . tramp-handle-process-file)
2047 (shell-command . tramp-handle-shell-command)
2048 (insert-directory . tramp-handle-insert-directory)
2049 (expand-file-name . tramp-handle-expand-file-name)
2050 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2051 (file-local-copy . tramp-handle-file-local-copy)
2052 (file-remote-p . tramp-handle-file-remote-p)
2053 (insert-file-contents . tramp-handle-insert-file-contents)
2054 (insert-file-contents-literally
2055 . tramp-handle-insert-file-contents-literally)
2056 (write-region . tramp-handle-write-region)
2057 (find-backup-file-name . tramp-handle-find-backup-file-name)
2058 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2059 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2060 (dired-compress-file . tramp-handle-dired-compress-file)
2061 (dired-recursive-delete-directory
2062 . tramp-handle-dired-recursive-delete-directory)
2063 (dired-uncache . tramp-handle-dired-uncache)
2064 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2065 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2066 (file-selinux-context . tramp-handle-file-selinux-context)
2067 (set-file-selinux-context . tramp-handle-set-file-selinux-context)
2068 (vc-registered . tramp-handle-vc-registered))
2069 "Alist of handler functions.
2070 Operations not mentioned here will be handled by the normal Emacs functions.")
2072 ;; Handlers for partial Tramp file names. For Emacs just
2073 ;; `file-name-all-completions' is needed.
2074 ;;;###autoload
2075 (defconst tramp-completion-file-name-handler-alist
2076 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2077 (file-name-completion . tramp-completion-handle-file-name-completion))
2078 "Alist of completion handler functions.
2079 Used for file names matching `tramp-file-name-regexp'. Operations not
2080 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2081 normal Emacs functions.")
2083 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2084 (defvar tramp-foreign-file-name-handler-alist
2085 ;; (identity . tramp-sh-file-name-handler) should always be the last
2086 ;; entry, because `identity' always matches.
2087 '((identity . tramp-sh-file-name-handler))
2088 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2089 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2090 calling HANDLER.")
2092 ;;; Internal functions which must come first:
2094 (defsubst tramp-debug-message (vec fmt-string &rest args)
2095 "Append message to debug buffer.
2096 Message is formatted with FMT-STRING as control string and the remaining
2097 ARGS to actually emit the message (if applicable)."
2098 (when (get-buffer (tramp-buffer-name vec))
2099 (with-current-buffer (tramp-get-debug-buffer vec)
2100 (goto-char (point-max))
2101 ;; Headline.
2102 (when (bobp)
2103 (insert
2104 (format
2105 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2106 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2107 emacs-version tramp-version)))
2108 (unless (bolp)
2109 (insert "\n"))
2110 ;; Timestamp.
2111 (let ((now (current-time)))
2112 (insert (format-time-string "%T." now))
2113 (insert (format "%06d " (nth 2 now))))
2114 ;; Calling function.
2115 (let ((btn 1) btf fn)
2116 (while (not fn)
2117 (setq btf (nth 1 (backtrace-frame btn)))
2118 (if (not btf)
2119 (setq fn "")
2120 (when (symbolp btf)
2121 (setq fn (symbol-name btf))
2122 (unless (and (string-match "^tramp" fn)
2123 (not (string-match
2124 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
2125 fn)))
2126 (setq fn nil)))
2127 (setq btn (1+ btn))))
2128 ;; The following code inserts filename and line number.
2129 ;; Should be deactivated by default, because it is time
2130 ;; consuming.
2131 ; (let ((ffn (find-function-noselect (intern fn))))
2132 ; (insert
2133 ; (format
2134 ; "%s:%d: "
2135 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2136 ; (with-current-buffer (car ffn)
2137 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2138 (insert (format "%s " fn)))
2139 ;; The message.
2140 (insert (apply 'format fmt-string args)))))
2142 (defvar tramp-message-show-message t
2143 "Show Tramp message in the minibuffer.
2144 This variable is used to disable messages from `tramp-error'.
2145 The messages are visible anyway, because an error is raised.")
2147 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2148 "Emit a message depending on verbosity level.
2149 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2150 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2151 less than LEVEL. The message is emitted only if `tramp-verbose' is
2152 greater than or equal to LEVEL.
2154 The message is also logged into the debug buffer when `tramp-verbose'
2155 is greater than or equal 4.
2157 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2158 control string and the remaining ARGS to actually emit the message (if
2159 applicable)."
2160 (condition-case nil
2161 (when (<= level tramp-verbose)
2162 ;; Match data must be preserved!
2163 (save-match-data
2164 ;; Display only when there is a minimum level.
2165 (when (and tramp-message-show-message (<= level 3))
2166 (apply 'message
2167 (concat
2168 (cond
2169 ((= level 0) "")
2170 ((= level 1) "")
2171 ((= level 2) "Warning: ")
2172 (t "Tramp: "))
2173 fmt-string)
2174 args))
2175 ;; Log only when there is a minimum level.
2176 (when (>= tramp-verbose 4)
2177 (when (and vec-or-proc
2178 (processp vec-or-proc)
2179 (buffer-name (process-buffer vec-or-proc)))
2180 (with-current-buffer (process-buffer vec-or-proc)
2181 ;; Translate proc to vec.
2182 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2183 (when (and vec-or-proc (vectorp vec-or-proc))
2184 (apply 'tramp-debug-message
2185 vec-or-proc
2186 (concat (format "(%d) # " level) fmt-string)
2187 args)))))
2188 ;; Suppress all errors.
2189 (error nil)))
2191 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2192 "Emit an error.
2193 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2194 signal identifier to be raised, remaining args passed to
2195 `tramp-message'. Finally, signal SIGNAL is raised."
2196 (let (tramp-message-show-message)
2197 (tramp-message
2198 vec-or-proc 1 "%s"
2199 (error-message-string
2200 (list signal
2201 (get signal 'error-message)
2202 (apply 'format fmt-string args))))
2203 (signal signal (list (apply 'format fmt-string args)))))
2205 (defsubst tramp-error-with-buffer
2206 (buffer vec-or-proc signal fmt-string &rest args)
2207 "Emit an error, and show BUFFER.
2208 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2209 an input event arrives. The other arguments are passed to `tramp-error'."
2210 (save-window-excursion
2211 (unwind-protect
2212 (apply 'tramp-error vec-or-proc signal fmt-string args)
2213 (when (and vec-or-proc
2214 (not (zerop tramp-verbose))
2215 (not (tramp-completion-mode-p)))
2216 (let ((enable-recursive-minibuffers t))
2217 (pop-to-buffer
2218 (or (and (bufferp buffer) buffer)
2219 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2220 (tramp-get-buffer vec-or-proc)))
2221 (sit-for 30))))))
2223 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2224 "Parse a Tramp filename and make components available in the body.
2226 First arg FILENAME is evaluated and dissected into its components.
2227 Second arg VAR is a symbol. It is used as a variable name to hold
2228 the filename structure. It is also used as a prefix for the variables
2229 holding the components. For example, if VAR is the symbol `foo', then
2230 `foo' will be bound to the whole structure, `foo-method' will be bound to
2231 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2233 Remaining args are Lisp expressions to be evaluated (inside an implicit
2234 `progn').
2236 If VAR is nil, then we bind `v' to the structure and `method', `user',
2237 `host', `localname' to the components."
2238 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2239 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2240 (tramp-file-name-method ,(or var 'v)))
2241 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2242 (tramp-file-name-user ,(or var 'v)))
2243 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2244 (tramp-file-name-host ,(or var 'v)))
2245 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2246 (tramp-file-name-localname ,(or var 'v))))
2247 ,@body))
2249 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2250 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2251 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2253 (defmacro with-file-property (vec file property &rest body)
2254 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2255 FILE must be a local file name on a connection identified via VEC."
2256 `(if (file-name-absolute-p ,file)
2257 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2258 (when (eq value 'undef)
2259 ;; We cannot pass @body as parameter to
2260 ;; `tramp-set-file-property' because it mangles our
2261 ;; debug messages.
2262 (setq value (progn ,@body))
2263 (tramp-set-file-property ,vec ,file ,property value))
2264 value)
2265 ,@body))
2267 (put 'with-file-property 'lisp-indent-function 3)
2268 (put 'with-file-property 'edebug-form-spec t)
2269 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2271 (defmacro with-connection-property (key property &rest body)
2272 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
2273 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2274 (when (eq value 'undef)
2275 ;; We cannot pass ,@body as parameter to
2276 ;; `tramp-set-connection-property' because it mangles our debug
2277 ;; messages.
2278 (setq value (progn ,@body))
2279 (tramp-set-connection-property ,key ,property value))
2280 value))
2282 (put 'with-connection-property 'lisp-indent-function 2)
2283 (put 'with-connection-property 'edebug-form-spec t)
2284 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2286 (defun tramp-progress-reporter-update (reporter &optional value)
2287 (let* ((parameters (cdr reporter))
2288 (message (aref parameters 3)))
2289 (when (string-match message (or (current-message) ""))
2290 (funcall 'progress-reporter-update reporter value))))
2292 (defmacro with-progress-reporter (vec level message &rest body)
2293 "Executes BODY, spinning a progress reporter with MESSAGE."
2294 `(let (pr tm)
2295 (tramp-message ,vec ,level "%s..." ,message)
2296 ;; We start a pulsing progress reporter after 3 seconds. Feature
2297 ;; introduced in Emacs 24.1.
2298 (when (and tramp-message-show-message
2299 ;; Display only when there is a minimum level.
2300 (<= ,level (min tramp-verbose 3)))
2301 (condition-case nil
2302 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
2303 tm (when pr
2304 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))
2305 (error nil)))
2306 (unwind-protect
2307 ;; Execute the body.
2308 (let ((tramp-message-show-message
2309 (and tramp-message-show-message (not tm))))
2310 ,@body)
2311 ;; Stop progress reporter.
2312 (if tm (tramp-compat-funcall 'cancel-timer tm))
2313 (tramp-message ,vec ,level "%s...done" ,message))))
2315 (put 'with-progress-reporter 'lisp-indent-function 3)
2316 (put 'with-progress-reporter 'edebug-form-spec t)
2317 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
2319 (eval-and-compile ;; Silence compiler.
2320 (if (memq system-type '(cygwin windows-nt))
2321 (defun tramp-drop-volume-letter (name)
2322 "Cut off unnecessary drive letter from file NAME.
2323 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2324 locally on a remote file name. When the local system is a W32 system
2325 but the remote system is Unix, this introduces a superfluous drive
2326 letter into the file name. This function removes it."
2327 (save-match-data
2328 (if (string-match tramp-root-regexp name)
2329 (replace-match "/" nil t name)
2330 name)))
2332 (defalias 'tramp-drop-volume-letter 'identity)))
2334 (defsubst tramp-make-tramp-temp-file (vec)
2335 "Create a temporary file on the remote host identified by VEC.
2336 Return the local name of the temporary file."
2337 (let ((prefix
2338 (tramp-make-tramp-file-name
2339 (tramp-file-name-method vec)
2340 (tramp-file-name-user vec)
2341 (tramp-file-name-host vec)
2342 (tramp-drop-volume-letter
2343 (expand-file-name
2344 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2345 result)
2346 (while (not result)
2347 ;; `make-temp-file' would be the natural choice for
2348 ;; implementation. But it calls `write-region' internally,
2349 ;; which also needs a temporary file - we would end in an
2350 ;; infinite loop.
2351 (setq result (make-temp-name prefix))
2352 (if (file-exists-p result)
2353 (setq result nil)
2354 ;; This creates the file by side effect.
2355 (set-file-times result)
2356 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2358 ;; Return the local part.
2359 (with-parsed-tramp-file-name result nil localname)))
2362 ;;; Config Manipulation Functions:
2364 (defun tramp-set-completion-function (method function-list)
2365 "Sets the list of completion functions for METHOD.
2366 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2367 The FUNCTION is intended to parse FILE according its syntax.
2368 It might be a predefined FUNCTION, or a user defined FUNCTION.
2369 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2370 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2371 and `tramp-parse-netrc'.
2373 Example:
2375 (tramp-set-completion-function
2376 \"ssh\"
2377 '((tramp-parse-sconfig \"/etc/ssh_config\")
2378 (tramp-parse-sconfig \"~/.ssh/config\")))"
2380 (let ((r function-list)
2381 (v function-list))
2382 (setq tramp-completion-function-alist
2383 (delete (assoc method tramp-completion-function-alist)
2384 tramp-completion-function-alist))
2386 (while v
2387 ;; Remove double entries.
2388 (when (member (car v) (cdr v))
2389 (setcdr v (delete (car v) (cdr v))))
2390 ;; Check for function and file or registry key.
2391 (unless (and (functionp (nth 0 (car v)))
2392 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2393 ;; Windows registry.
2394 (and (memq system-type '(cygwin windows-nt))
2395 (zerop
2396 (tramp-local-call-process
2397 "reg" nil nil nil "query" (nth 1 (car v)))))
2398 ;; Configuration file.
2399 (file-exists-p (nth 1 (car v)))))
2400 (setq r (delete (car v) r)))
2401 (setq v (cdr v)))
2403 (when r
2404 (add-to-list 'tramp-completion-function-alist
2405 (cons method r)))))
2407 (defun tramp-get-completion-function (method)
2408 "Returns a list of completion functions for METHOD.
2409 For definition of that list see `tramp-set-completion-function'."
2410 (cons
2411 ;; Hosts visited once shall be remembered.
2412 `(tramp-parse-connection-properties ,method)
2413 ;; The method related defaults.
2414 (cdr (assoc method tramp-completion-function-alist))))
2417 ;;; Fontification of `read-file-name':
2419 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2420 (defvar tramp-rfn-eshadow-overlay)
2421 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2423 (defun tramp-rfn-eshadow-setup-minibuffer ()
2424 "Set up a minibuffer for `file-name-shadow-mode'.
2425 Adds another overlay hiding filename parts according to Tramp's
2426 special handling of `substitute-in-file-name'."
2427 (when (symbol-value 'minibuffer-completing-file-name)
2428 (setq tramp-rfn-eshadow-overlay
2429 (tramp-compat-funcall
2430 'make-overlay
2431 (tramp-compat-funcall 'minibuffer-prompt-end)
2432 (tramp-compat-funcall 'minibuffer-prompt-end)))
2433 ;; Copy rfn-eshadow-overlay properties.
2434 (let ((props (tramp-compat-funcall
2435 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
2436 (while props
2437 (tramp-compat-funcall
2438 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2440 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2441 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2442 'tramp-rfn-eshadow-setup-minibuffer)
2443 (add-hook 'tramp-unload-hook
2444 (lambda ()
2445 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2446 'tramp-rfn-eshadow-setup-minibuffer))))
2448 (defconst tramp-rfn-eshadow-update-overlay-regexp
2449 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2451 (defun tramp-rfn-eshadow-update-overlay ()
2452 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2453 This is intended to be used as a minibuffer `post-command-hook' for
2454 `file-name-shadow-mode'; the minibuffer should have already
2455 been set up by `rfn-eshadow-setup-minibuffer'."
2456 ;; In remote files name, there is a shadowing just for the local part.
2457 (let ((end (or (tramp-compat-funcall
2458 'overlay-end (symbol-value 'rfn-eshadow-overlay))
2459 (tramp-compat-funcall 'minibuffer-prompt-end))))
2460 (when
2461 (file-remote-p
2462 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
2463 (save-excursion
2464 (save-restriction
2465 (narrow-to-region
2466 (1+ (or (string-match
2467 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2468 end))
2469 (point-max))
2470 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2471 (rfn-eshadow-update-overlay-hook nil))
2472 (tramp-compat-funcall
2473 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
2474 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
2476 (when (boundp 'rfn-eshadow-update-overlay-hook)
2477 (add-hook 'rfn-eshadow-update-overlay-hook
2478 'tramp-rfn-eshadow-update-overlay)
2479 (add-hook 'tramp-unload-hook
2480 (lambda ()
2481 (remove-hook 'rfn-eshadow-update-overlay-hook
2482 'tramp-rfn-eshadow-update-overlay))))
2485 ;;; Integration of eshell.el:
2487 (eval-when-compile
2488 (defvar eshell-path-env))
2490 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2491 ;; when `default-directory' points to another host.
2492 (defun tramp-eshell-directory-change ()
2493 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2494 (setq eshell-path-env
2495 (if (file-remote-p default-directory)
2496 (with-parsed-tramp-file-name default-directory nil
2497 (mapconcat
2498 'identity
2499 (tramp-get-remote-path v)
2500 ":"))
2501 (getenv "PATH"))))
2503 (eval-after-load "esh-util"
2504 '(progn
2505 (tramp-eshell-directory-change)
2506 (add-hook 'eshell-directory-change-hook
2507 'tramp-eshell-directory-change)
2508 (add-hook 'tramp-unload-hook
2509 (lambda ()
2510 (remove-hook 'eshell-directory-change-hook
2511 'tramp-eshell-directory-change)))))
2514 ;;; File Name Handler Functions:
2516 (defun tramp-handle-make-symbolic-link
2517 (filename linkname &optional ok-if-already-exists)
2518 "Like `make-symbolic-link' for Tramp files.
2519 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2520 the symlink. If LINKNAME is a Tramp file, only the localname component is
2521 used as the target of the symlink.
2523 If LINKNAME is a Tramp file and the localname component is relative, then
2524 it is expanded first, before the localname component is taken. Note that
2525 this can give surprising results if the user/host for the source and
2526 target of the symlink differ."
2527 (with-parsed-tramp-file-name linkname l
2528 (let ((ln (tramp-get-remote-ln l))
2529 (cwd (tramp-run-real-handler
2530 'file-name-directory (list l-localname))))
2531 (unless ln
2532 (tramp-error
2533 l 'file-error
2534 "Making a symbolic link. ln(1) does not exist on the remote host."))
2536 ;; Do the 'confirm if exists' thing.
2537 (when (file-exists-p linkname)
2538 ;; What to do?
2539 (if (or (null ok-if-already-exists) ; not allowed to exist
2540 (and (numberp ok-if-already-exists)
2541 (not (yes-or-no-p
2542 (format
2543 "File %s already exists; make it a link anyway? "
2544 l-localname)))))
2545 (tramp-error
2546 l 'file-already-exists "File %s already exists" l-localname)
2547 (tramp-compat-delete-file linkname 'force)))
2549 ;; If FILENAME is a Tramp name, use just the localname component.
2550 (when (tramp-tramp-file-p filename)
2551 (setq filename
2552 (tramp-file-name-localname
2553 (tramp-dissect-file-name (expand-file-name filename)))))
2555 ;; Right, they are on the same host, regardless of user, method, etc.
2556 ;; We now make the link on the remote machine. This will occur as the user
2557 ;; that FILENAME belongs to.
2558 (zerop
2559 (tramp-send-command-and-check
2561 (format
2562 "cd %s && %s -sf %s %s"
2563 (tramp-shell-quote-argument cwd)
2565 (tramp-shell-quote-argument filename)
2566 (tramp-shell-quote-argument l-localname))
2567 t)))))
2569 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2570 "Like `load' for Tramp files."
2571 (with-parsed-tramp-file-name (expand-file-name file) nil
2572 (unless nosuffix
2573 (cond ((file-exists-p (concat file ".elc"))
2574 (setq file (concat file ".elc")))
2575 ((file-exists-p (concat file ".el"))
2576 (setq file (concat file ".el")))))
2577 (when must-suffix
2578 ;; The first condition is always true for absolute file names.
2579 ;; Included for safety's sake.
2580 (unless (or (file-name-directory file)
2581 (string-match "\\.elc?\\'" file))
2582 (tramp-error
2583 v 'file-error
2584 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2585 (unless noerror
2586 (when (not (file-exists-p file))
2587 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2588 (if (not (file-exists-p file))
2590 (let ((tramp-message-show-message (not nomessage)))
2591 (with-progress-reporter v 0 (format "Loading %s" file)
2592 (let ((local-copy (file-local-copy file)))
2593 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2594 (unwind-protect
2595 (load local-copy noerror t t)
2596 (tramp-compat-delete-file local-copy 'force)))))
2597 t)))
2599 ;; Localname manipulation functions that grok Tramp localnames...
2600 (defun tramp-handle-file-name-as-directory (file)
2601 "Like `file-name-as-directory' but aware of Tramp files."
2602 ;; `file-name-as-directory' would be sufficient except localname is
2603 ;; the empty string.
2604 (let ((v (tramp-dissect-file-name file t)))
2605 ;; Run the command on the localname portion only.
2606 (tramp-make-tramp-file-name
2607 (tramp-file-name-method v)
2608 (tramp-file-name-user v)
2609 (tramp-file-name-host v)
2610 (tramp-run-real-handler
2611 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2613 (defun tramp-handle-file-name-directory (file)
2614 "Like `file-name-directory' but aware of Tramp files."
2615 ;; Everything except the last filename thing is the directory. We
2616 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2617 ;; the remote file name parts. This is a problem when we are in
2618 ;; file name completion.
2619 (let ((v (tramp-dissect-file-name file t)))
2620 ;; Run the command on the localname portion only.
2621 (tramp-make-tramp-file-name
2622 (tramp-file-name-method v)
2623 (tramp-file-name-user v)
2624 (tramp-file-name-host v)
2625 (tramp-run-real-handler
2626 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2628 (defun tramp-handle-file-name-nondirectory (file)
2629 "Like `file-name-nondirectory' but aware of Tramp files."
2630 (with-parsed-tramp-file-name file nil
2631 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2633 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2634 "Like `file-truename' for Tramp files."
2635 (with-parsed-tramp-file-name (expand-file-name filename) nil
2636 (with-file-property v localname "file-truename"
2637 (let ((result nil)) ; result steps in reverse order
2638 (tramp-message v 4 "Finding true name for `%s'" filename)
2639 (cond
2640 ;; Use GNU readlink --canonicalize-missing where available.
2641 ((tramp-get-remote-readlink v)
2642 (setq result
2643 (tramp-send-command-and-read
2645 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2646 (tramp-get-remote-readlink v)
2647 (tramp-shell-quote-argument localname)))))
2649 ;; Use Perl implementation.
2650 ((and (tramp-get-remote-perl v)
2651 (tramp-get-connection-property v "perl-file-spec" nil)
2652 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2653 (tramp-maybe-send-script
2654 v tramp-perl-file-truename "tramp_perl_file_truename")
2655 (setq result
2656 (tramp-send-command-and-read
2658 (format "tramp_perl_file_truename %s"
2659 (tramp-shell-quote-argument localname)))))
2661 ;; Do it yourself. We bind `directory-sep-char' here for
2662 ;; XEmacs on Windows, which would otherwise use backslash.
2663 (t (let* ((directory-sep-char ?/)
2664 (steps (tramp-compat-split-string localname "/"))
2665 (localnamedir (tramp-run-real-handler
2666 'file-name-as-directory (list localname)))
2667 (is-dir (string= localname localnamedir))
2668 (thisstep nil)
2669 (numchase 0)
2670 ;; Don't make the following value larger than
2671 ;; necessary. People expect an error message in a
2672 ;; timely fashion when something is wrong;
2673 ;; otherwise they might think that Emacs is hung.
2674 ;; Of course, correctness has to come first.
2675 (numchase-limit 20)
2676 symlink-target)
2677 (while (and steps (< numchase numchase-limit))
2678 (setq thisstep (pop steps))
2679 (tramp-message
2680 v 5 "Check %s"
2681 (mapconcat 'identity
2682 (append '("") (reverse result) (list thisstep))
2683 "/"))
2684 (setq symlink-target
2685 (nth 0 (file-attributes
2686 (tramp-make-tramp-file-name
2687 method user host
2688 (mapconcat 'identity
2689 (append '("")
2690 (reverse result)
2691 (list thisstep))
2692 "/")))))
2693 (cond ((string= "." thisstep)
2694 (tramp-message v 5 "Ignoring step `.'"))
2695 ((string= ".." thisstep)
2696 (tramp-message v 5 "Processing step `..'")
2697 (pop result))
2698 ((stringp symlink-target)
2699 ;; It's a symlink, follow it.
2700 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2701 (setq numchase (1+ numchase))
2702 (when (file-name-absolute-p symlink-target)
2703 (setq result nil))
2704 ;; If the symlink was absolute, we'll get a string like
2705 ;; "/user@host:/some/target"; extract the
2706 ;; "/some/target" part from it.
2707 (when (tramp-tramp-file-p symlink-target)
2708 (unless (tramp-equal-remote filename symlink-target)
2709 (tramp-error
2710 v 'file-error
2711 "Symlink target `%s' on wrong host" symlink-target))
2712 (setq symlink-target localname))
2713 (setq steps
2714 (append (tramp-compat-split-string
2715 symlink-target "/")
2716 steps)))
2718 ;; It's a file.
2719 (setq result (cons thisstep result)))))
2720 (when (>= numchase numchase-limit)
2721 (tramp-error
2722 v 'file-error
2723 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2724 (setq result (reverse result))
2725 ;; Combine list to form string.
2726 (setq result
2727 (if result
2728 (mapconcat 'identity (cons "" result) "/")
2729 "/"))
2730 (when (and is-dir (or (string= "" result)
2731 (not (string= (substring result -1) "/"))))
2732 (setq result (concat result "/"))))))
2734 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2735 (tramp-make-tramp-file-name method user host result)))))
2737 ;; Basic functions.
2739 (defun tramp-handle-file-exists-p (filename)
2740 "Like `file-exists-p' for Tramp files."
2741 (with-parsed-tramp-file-name filename nil
2742 (with-file-property v localname "file-exists-p"
2743 (or (not (null (tramp-get-file-property
2744 v localname "file-attributes-integer" nil)))
2745 (not (null (tramp-get-file-property
2746 v localname "file-attributes-string" nil)))
2747 (zerop (tramp-send-command-and-check
2749 (format
2750 "%s %s"
2751 (tramp-get-file-exists-command v)
2752 (tramp-shell-quote-argument localname))))))))
2754 ;; Inodes don't exist for some file systems. Therefore we must
2755 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2756 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2757 ;; performance isn't the major issue given that file transfer will
2758 ;; take time.
2759 (defvar tramp-inodes nil
2760 "Keeps virtual inodes numbers.")
2762 ;; Devices must distinguish physical file systems. The device numbers
2763 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2764 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2765 ;; EFS use device number "-1". In order to be different, we use device number
2766 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2767 (defvar tramp-devices nil
2768 "Keeps virtual device numbers.")
2770 ;; CCC: This should check for an error condition and signal failure
2771 ;; when something goes wrong.
2772 ;; Daniel Pittman <daniel@danann.net>
2773 (defun tramp-handle-file-attributes (filename &optional id-format)
2774 "Like `file-attributes' for Tramp files."
2775 (unless id-format (setq id-format 'integer))
2776 ;; Don't modify `last-coding-system-used' by accident.
2777 (let ((last-coding-system-used last-coding-system-used))
2778 (with-parsed-tramp-file-name (expand-file-name filename) nil
2779 (with-file-property v localname (format "file-attributes-%s" id-format)
2780 (save-excursion
2781 (tramp-convert-file-attributes
2783 (cond
2784 ((tramp-get-remote-stat v)
2785 (tramp-do-file-attributes-with-stat v localname id-format))
2786 ((tramp-get-remote-perl v)
2787 (tramp-do-file-attributes-with-perl v localname id-format))
2789 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2791 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2792 "Implement `file-attributes' for Tramp files using the ls(1) command."
2793 (let (symlinkp dirp
2794 res-inode res-filemodes res-numlinks
2795 res-uid res-gid res-size res-symlink-target)
2796 (tramp-message vec 5 "file attributes with ls: %s" localname)
2797 (tramp-send-command
2799 (format "(%s %s || %s -h %s) && %s %s %s"
2800 (tramp-get-file-exists-command vec)
2801 (tramp-shell-quote-argument localname)
2802 (tramp-get-test-command vec)
2803 (tramp-shell-quote-argument localname)
2804 (tramp-get-ls-command vec)
2805 (if (eq id-format 'integer) "-ildn" "-ild")
2806 (tramp-shell-quote-argument localname)))
2807 ;; parse `ls -l' output ...
2808 (with-current-buffer (tramp-get-buffer vec)
2809 (when (> (buffer-size) 0)
2810 (goto-char (point-min))
2811 ;; ... inode
2812 (setq res-inode
2813 (condition-case err
2814 (read (current-buffer))
2815 (invalid-read-syntax
2816 (when (and (equal (cadr err)
2817 "Integer constant overflow in reader")
2818 (string-match
2819 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2820 (car (cddr err))))
2821 (let* ((big (read (substring (car (cddr err)) 0
2822 (match-beginning 1))))
2823 (small (read (match-string 1 (car (cddr err)))))
2824 (twiddle (/ small 65536)))
2825 (cons (+ big twiddle)
2826 (- small (* twiddle 65536))))))))
2827 ;; ... file mode flags
2828 (setq res-filemodes (symbol-name (read (current-buffer))))
2829 ;; ... number links
2830 (setq res-numlinks (read (current-buffer)))
2831 ;; ... uid and gid
2832 (setq res-uid (read (current-buffer)))
2833 (setq res-gid (read (current-buffer)))
2834 (if (eq id-format 'integer)
2835 (progn
2836 (unless (numberp res-uid) (setq res-uid -1))
2837 (unless (numberp res-gid) (setq res-gid -1)))
2838 (progn
2839 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2840 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2841 ;; ... size
2842 (setq res-size (read (current-buffer)))
2843 ;; From the file modes, figure out other stuff.
2844 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2845 (setq dirp (eq ?d (aref res-filemodes 0)))
2846 ;; if symlink, find out file name pointed to
2847 (when symlinkp
2848 (search-forward "-> ")
2849 (setq res-symlink-target
2850 (buffer-substring (point) (tramp-compat-line-end-position))))
2851 ;; return data gathered
2852 (list
2853 ;; 0. t for directory, string (name linked to) for symbolic
2854 ;; link, or nil.
2855 (or dirp res-symlink-target)
2856 ;; 1. Number of links to file.
2857 res-numlinks
2858 ;; 2. File uid.
2859 res-uid
2860 ;; 3. File gid.
2861 res-gid
2862 ;; 4. Last access time, as a list of two integers. First
2863 ;; integer has high-order 16 bits of time, second has low 16
2864 ;; bits.
2865 ;; 5. Last modification time, likewise.
2866 ;; 6. Last status change time, likewise.
2867 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2868 ;; 7. Size in bytes (-1, if number is out of range).
2869 res-size
2870 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2871 res-filemodes
2872 ;; 9. t if file's gid would change if file were deleted and
2873 ;; recreated. Will be set in `tramp-convert-file-attributes'
2875 ;; 10. inode number.
2876 res-inode
2877 ;; 11. Device number. Will be replaced by a virtual device number.
2879 )))))
2881 (defun tramp-do-file-attributes-with-perl
2882 (vec localname &optional id-format)
2883 "Implement `file-attributes' for Tramp files using a Perl script."
2884 (tramp-message vec 5 "file attributes with perl: %s" localname)
2885 (tramp-maybe-send-script
2886 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2887 (tramp-send-command-and-read
2889 (format "tramp_perl_file_attributes %s %s"
2890 (tramp-shell-quote-argument localname) id-format)))
2892 (defun tramp-do-file-attributes-with-stat
2893 (vec localname &optional id-format)
2894 "Implement `file-attributes' for Tramp files using stat(1) command."
2895 (tramp-message vec 5 "file attributes with stat: %s" localname)
2896 (tramp-send-command-and-read
2898 (format
2899 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
2900 ;; parse correctly the sequence "((". Therefore, we add a space.
2901 "( (%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)"
2902 (tramp-get-file-exists-command vec)
2903 (tramp-shell-quote-argument localname)
2904 (tramp-get-test-command vec)
2905 (tramp-shell-quote-argument localname)
2906 (tramp-get-remote-stat vec)
2907 (if (eq id-format 'integer) "%u" "\"%U\"")
2908 (if (eq id-format 'integer) "%g" "\"%G\"")
2909 (tramp-shell-quote-argument localname))))
2911 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2912 "Like `set-visited-file-modtime' for Tramp files."
2913 (unless (buffer-file-name)
2914 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2915 (buffer-name)))
2916 (if time-list
2917 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2918 (let ((f (buffer-file-name))
2919 coding-system-used)
2920 (with-parsed-tramp-file-name f nil
2921 (let* ((attr (file-attributes f))
2922 ;; '(-1 65535) means file doesn't exists yet.
2923 (modtime (or (nth 5 attr) '(-1 65535))))
2924 (when (boundp 'last-coding-system-used)
2925 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2926 ;; We use '(0 0) as a don't-know value. See also
2927 ;; `tramp-do-file-attributes-with-ls'.
2928 (if (not (equal modtime '(0 0)))
2929 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2930 (progn
2931 (tramp-send-command
2933 (format "%s -ild %s"
2934 (tramp-get-ls-command v)
2935 (tramp-shell-quote-argument localname)))
2936 (setq attr (buffer-substring (point)
2937 (progn (end-of-line) (point)))))
2938 (tramp-set-file-property
2939 v localname "visited-file-modtime-ild" attr))
2940 (when (boundp 'last-coding-system-used)
2941 (set 'last-coding-system-used coding-system-used))
2942 nil)))))
2944 ;; This function makes the same assumption as
2945 ;; `tramp-handle-set-visited-file-modtime'.
2946 (defun tramp-handle-verify-visited-file-modtime (buf)
2947 "Like `verify-visited-file-modtime' for Tramp files.
2948 At the time `verify-visited-file-modtime' calls this function, we
2949 already know that the buffer is visiting a file and that
2950 `visited-file-modtime' does not return 0. Do not call this
2951 function directly, unless those two cases are already taken care
2952 of."
2953 (with-current-buffer buf
2954 (let ((f (buffer-file-name)))
2955 ;; There is no file visiting the buffer, or the buffer has no
2956 ;; recorded last modification time, or there is no established
2957 ;; connection.
2958 (if (or (not f)
2959 (eq (visited-file-modtime) 0)
2960 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
2962 (with-parsed-tramp-file-name f nil
2963 (tramp-flush-file-property v localname)
2964 (let* ((attr (file-attributes f))
2965 (modtime (nth 5 attr))
2966 (mt (visited-file-modtime)))
2968 (cond
2969 ;; File exists, and has a known modtime.
2970 ((and attr (not (equal modtime '(0 0))))
2971 (< (abs (tramp-time-diff
2972 modtime
2973 ;; For compatibility, deal with both the old
2974 ;; (HIGH . LOW) and the new (HIGH LOW) return
2975 ;; values of `visited-file-modtime'.
2976 (if (atom (cdr mt))
2977 (list (car mt) (cdr mt))
2978 mt)))
2980 ;; Modtime has the don't know value.
2981 (attr
2982 (tramp-send-command
2984 (format "%s -ild %s"
2985 (tramp-get-ls-command v)
2986 (tramp-shell-quote-argument localname)))
2987 (with-current-buffer (tramp-get-buffer v)
2988 (setq attr (buffer-substring
2989 (point) (progn (end-of-line) (point)))))
2990 (equal
2991 attr
2992 (tramp-get-file-property
2993 v localname "visited-file-modtime-ild" "")))
2994 ;; If file does not exist, say it is not modified if and
2995 ;; only if that agrees with the buffer's record.
2996 (t (equal mt '(-1 65535))))))))))
2998 (defun tramp-handle-set-file-modes (filename mode)
2999 "Like `set-file-modes' for Tramp files."
3000 (with-parsed-tramp-file-name filename nil
3001 (tramp-flush-file-property v localname)
3002 (unless (zerop (tramp-send-command-and-check
3004 (format "chmod %s %s"
3005 (tramp-decimal-to-octal mode)
3006 (tramp-shell-quote-argument localname))))
3007 ;; FIXME: extract the proper text from chmod's stderr.
3008 (tramp-error
3009 v 'file-error "Error while changing file's mode %s" filename))))
3011 (defun tramp-handle-set-file-times (filename &optional time)
3012 "Like `set-file-times' for Tramp files."
3013 (zerop
3014 (if (file-remote-p filename)
3015 (with-parsed-tramp-file-name filename nil
3016 (tramp-flush-file-property v localname)
3017 (let ((time (if (or (null time) (equal time '(0 0)))
3018 (current-time)
3019 time))
3020 ;; With GNU Emacs, `format-time-string' has an optional
3021 ;; parameter UNIVERSAL. This is preferred, because we
3022 ;; could handle the case when the remote host is
3023 ;; located in a different time zone as the local host.
3024 (utc (not (featurep 'xemacs))))
3025 (tramp-send-command-and-check
3026 v (format "%s touch -t %s %s"
3027 (if utc "TZ=UTC; export TZ;" "")
3028 (if utc
3029 (format-time-string "%Y%m%d%H%M.%S" time t)
3030 (format-time-string "%Y%m%d%H%M.%S" time))
3031 (tramp-shell-quote-argument localname)))))
3033 ;; We handle also the local part, because in older Emacsen,
3034 ;; without `set-file-times', this function is an alias for this.
3035 ;; We are local, so we don't need the UTC settings.
3036 (tramp-local-call-process
3037 "touch" nil nil nil "-t"
3038 (format-time-string "%Y%m%d%H%M.%S" time)
3039 (tramp-shell-quote-argument filename)))))
3041 (defun tramp-set-file-uid-gid (filename &optional uid gid)
3042 "Set the ownership for FILENAME.
3043 If UID and GID are provided, these values are used; otherwise uid
3044 and gid of the corresponding user is taken. Both parameters must be integers."
3045 ;; Modern Unices allow chown only for root. So we might need
3046 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
3047 ;; working with su(do)? when it is needed, so it shall succeed in
3048 ;; the majority of cases.
3049 ;; Don't modify `last-coding-system-used' by accident.
3050 (let ((last-coding-system-used last-coding-system-used))
3051 (if (file-remote-p filename)
3052 (with-parsed-tramp-file-name filename nil
3053 (if (and (zerop (user-uid)) (tramp-local-host-p v))
3054 ;; If we are root on the local host, we can do it directly.
3055 (tramp-set-file-uid-gid localname uid gid)
3056 (let ((uid (or (and (integerp uid) uid)
3057 (tramp-get-remote-uid v 'integer)))
3058 (gid (or (and (integerp gid) gid)
3059 (tramp-get-remote-gid v 'integer))))
3060 (tramp-send-command
3061 v (format
3062 "chown %d:%d %s" uid gid
3063 (tramp-shell-quote-argument localname))))))
3065 ;; We handle also the local part, because there doesn't exist
3066 ;; `set-file-uid-gid'. On W32 "chown" might not work.
3067 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
3068 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
3069 (tramp-local-call-process
3070 "chown" nil nil nil
3071 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
3073 (defun tramp-remote-selinux-p (vec)
3074 "Check, whether SELINUX is enabled on the remote host."
3075 (with-connection-property (tramp-get-connection-process vec) "selinux-p"
3076 (let ((result (tramp-find-executable
3077 vec "getenforce" (tramp-get-remote-path vec) t t)))
3078 (and result
3079 (string-equal
3080 (tramp-send-command-and-read
3081 vec (format "echo \\\"`%S`\\\"" result))
3082 "Enforcing")))))
3084 (defun tramp-handle-file-selinux-context (filename)
3085 "Like `file-selinux-context' for Tramp files."
3086 (with-parsed-tramp-file-name filename nil
3087 (with-file-property v localname "file-selinux-context"
3088 (let ((context '(nil nil nil nil))
3089 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
3090 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
3091 (when (and (tramp-remote-selinux-p v)
3092 (zerop (tramp-send-command-and-check
3093 v (format
3094 "%s -d -Z %s"
3095 (tramp-get-ls-command v)
3096 (tramp-shell-quote-argument localname)))))
3097 (with-current-buffer (tramp-get-connection-buffer v)
3098 (goto-char (point-min))
3099 (when (re-search-forward regexp (tramp-compat-line-end-position) t)
3100 (setq context (list (match-string 1) (match-string 2)
3101 (match-string 3) (match-string 4))))))
3102 ;; Return the context.
3103 context))))
3105 (defun tramp-handle-set-file-selinux-context (filename context)
3106 "Like `set-file-selinux-context' for Tramp files."
3107 (with-parsed-tramp-file-name filename nil
3108 (if (and (consp context)
3109 (tramp-remote-selinux-p v)
3110 (zerop (tramp-send-command-and-check
3111 v (format "chcon %s %s %s %s %s"
3112 (if (stringp (nth 0 context))
3113 (format "--user=%s" (nth 0 context)) "")
3114 (if (stringp (nth 1 context))
3115 (format "--role=%s" (nth 1 context)) "")
3116 (if (stringp (nth 2 context))
3117 (format "--type=%s" (nth 2 context)) "")
3118 (if (stringp (nth 3 context))
3119 (format "--range=%s" (nth 3 context)) "")
3120 (tramp-shell-quote-argument localname)))))
3121 (tramp-set-file-property v localname "file-selinux-context" context)
3122 (tramp-set-file-property v localname "file-selinux-context" 'undef)))
3123 ;; We always return nil.
3124 nil)
3126 ;; Simple functions using the `test' command.
3128 (defun tramp-handle-file-executable-p (filename)
3129 "Like `file-executable-p' for Tramp files."
3130 (with-parsed-tramp-file-name filename nil
3131 (with-file-property v localname "file-executable-p"
3132 ;; Examine `file-attributes' cache to see if request can be
3133 ;; satisfied without remote operation.
3134 (or (tramp-check-cached-permissions v ?x)
3135 (zerop (tramp-run-test "-x" filename))))))
3137 (defun tramp-handle-file-readable-p (filename)
3138 "Like `file-readable-p' for Tramp files."
3139 (with-parsed-tramp-file-name filename nil
3140 (with-file-property v localname "file-readable-p"
3141 ;; Examine `file-attributes' cache to see if request can be
3142 ;; satisfied without remote operation.
3143 (or (tramp-check-cached-permissions v ?r)
3144 (zerop (tramp-run-test "-r" filename))))))
3146 ;; When the remote shell is started, it looks for a shell which groks
3147 ;; tilde expansion. Here, we assume that all shells which grok tilde
3148 ;; expansion will also provide a `test' command which groks `-nt' (for
3149 ;; newer than). If this breaks, tell me about it and I'll try to do
3150 ;; something smarter about it.
3151 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3152 "Like `file-newer-than-file-p' for Tramp files."
3153 (cond ((not (file-exists-p file1))
3154 nil)
3155 ((not (file-exists-p file2))
3157 ;; We are sure both files exist at this point.
3159 (save-excursion
3160 ;; We try to get the mtime of both files. If they are not
3161 ;; equal to the "dont-know" value, then we subtract the times
3162 ;; and obtain the result.
3163 (let ((fa1 (file-attributes file1))
3164 (fa2 (file-attributes file2)))
3165 (if (and (not (equal (nth 5 fa1) '(0 0)))
3166 (not (equal (nth 5 fa2) '(0 0))))
3167 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3168 ;; If one of them is the dont-know value, then we can
3169 ;; still try to run a shell command on the remote host.
3170 ;; However, this only works if both files are Tramp
3171 ;; files and both have the same method, same user, same
3172 ;; host.
3173 (unless (tramp-equal-remote file1 file2)
3174 (with-parsed-tramp-file-name
3175 (if (tramp-tramp-file-p file1) file1 file2) nil
3176 (tramp-error
3177 v 'file-error
3178 "Files %s and %s must have same method, user, host"
3179 file1 file2)))
3180 (with-parsed-tramp-file-name file1 nil
3181 (zerop (tramp-run-test2
3182 (tramp-get-test-nt-command v) file1 file2)))))))))
3184 ;; Functions implemented using the basic functions above.
3186 (defun tramp-handle-file-modes (filename)
3187 "Like `file-modes' for Tramp files."
3188 (let ((truename (or (file-truename filename) filename)))
3189 (when (file-exists-p truename)
3190 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3192 (defun tramp-default-file-modes (filename)
3193 "Return file modes of FILENAME as integer.
3194 If the file modes of FILENAME cannot be determined, return the
3195 value of `default-file-modes', without execute permissions."
3196 (or (file-modes filename)
3197 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3199 (defun tramp-handle-file-directory-p (filename)
3200 "Like `file-directory-p' for Tramp files."
3201 ;; Care must be taken that this function returns `t' for symlinks
3202 ;; pointing to directories. Surely the most obvious implementation
3203 ;; would be `test -d', but that returns false for such symlinks.
3204 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3205 ;; I now think he's right. So we could be using `test -d', couldn't
3206 ;; we?
3208 ;; Alternatives: `cd %s', `test -d %s'
3209 (with-parsed-tramp-file-name filename nil
3210 (with-file-property v localname "file-directory-p"
3211 (zerop (tramp-run-test "-d" filename)))))
3213 (defun tramp-handle-file-regular-p (filename)
3214 "Like `file-regular-p' for Tramp files."
3215 (and (file-exists-p filename)
3216 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3218 (defun tramp-handle-file-symlink-p (filename)
3219 "Like `file-symlink-p' for Tramp files."
3220 (with-parsed-tramp-file-name filename nil
3221 (let ((x (car (file-attributes filename))))
3222 (when (stringp x)
3223 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3224 ;; might do weird things.
3225 (if (file-name-absolute-p x)
3226 (tramp-make-tramp-file-name method user host x)
3227 x)))))
3229 (defun tramp-handle-file-writable-p (filename)
3230 "Like `file-writable-p' for Tramp files."
3231 (with-parsed-tramp-file-name filename nil
3232 (with-file-property v localname "file-writable-p"
3233 (if (file-exists-p filename)
3234 ;; Examine `file-attributes' cache to see if request can be
3235 ;; satisfied without remote operation.
3236 (or (tramp-check-cached-permissions v ?w)
3237 (zerop (tramp-run-test "-w" filename)))
3238 ;; If file doesn't exist, check if directory is writable.
3239 (and (zerop (tramp-run-test
3240 "-d" (file-name-directory filename)))
3241 (zerop (tramp-run-test
3242 "-w" (file-name-directory filename))))))))
3244 (defun tramp-handle-file-ownership-preserved-p (filename)
3245 "Like `file-ownership-preserved-p' for Tramp files."
3246 (with-parsed-tramp-file-name filename nil
3247 (with-file-property v localname "file-ownership-preserved-p"
3248 (let ((attributes (file-attributes filename)))
3249 ;; Return t if the file doesn't exist, since it's true that no
3250 ;; information would be lost by an (attempted) delete and create.
3251 (or (null attributes)
3252 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3254 ;; Other file name ops.
3256 (defun tramp-handle-directory-file-name (directory)
3257 "Like `directory-file-name' for Tramp files."
3258 ;; If localname component of filename is "/", leave it unchanged.
3259 ;; Otherwise, remove any trailing slash from localname component.
3260 ;; Method, host, etc, are unchanged. Does it make sense to try
3261 ;; to avoid parsing the filename?
3262 (with-parsed-tramp-file-name directory nil
3263 (if (and (not (zerop (length localname)))
3264 (eq (aref localname (1- (length localname))) ?/)
3265 (not (string= localname "/")))
3266 (substring directory 0 -1)
3267 directory)))
3269 ;; Directory listings.
3271 (defun tramp-handle-directory-files
3272 (directory &optional full match nosort files-only)
3273 "Like `directory-files' for Tramp files."
3274 ;; FILES-ONLY is valid for XEmacs only.
3275 (when (file-directory-p directory)
3276 (setq directory (file-name-as-directory (expand-file-name directory)))
3277 (let ((temp (nreverse (file-name-all-completions "" directory)))
3278 result item)
3280 (while temp
3281 (setq item (directory-file-name (pop temp)))
3282 (when (and (or (null match) (string-match match item))
3283 (or (null files-only)
3284 ;; Files only.
3285 (and (equal files-only t) (file-regular-p item))
3286 ;; Directories only.
3287 (file-directory-p item)))
3288 (push (if full (concat directory item) item)
3289 result)))
3290 (if nosort result (sort result 'string<)))))
3292 (defun tramp-handle-directory-files-and-attributes
3293 (directory &optional full match nosort id-format)
3294 "Like `directory-files-and-attributes' for Tramp files."
3295 (unless id-format (setq id-format 'integer))
3296 (when (file-directory-p directory)
3297 (setq directory (expand-file-name directory))
3298 (let* ((temp
3299 (copy-tree
3300 (with-parsed-tramp-file-name directory nil
3301 (with-file-property
3302 v localname
3303 (format "directory-files-and-attributes-%s" id-format)
3304 (save-excursion
3305 (mapcar
3306 (lambda (x)
3307 (cons (car x)
3308 (tramp-convert-file-attributes v (cdr x))))
3309 (cond
3310 ((tramp-get-remote-stat v)
3311 (tramp-do-directory-files-and-attributes-with-stat
3312 v localname id-format))
3313 ((tramp-get-remote-perl v)
3314 (tramp-do-directory-files-and-attributes-with-perl
3315 v localname id-format)))))))))
3316 result item)
3318 (while temp
3319 (setq item (pop temp))
3320 (when (or (null match) (string-match match (car item)))
3321 (when full
3322 (setcar item (expand-file-name (car item) directory)))
3323 (push item result)))
3325 (if nosort
3326 result
3327 (sort result (lambda (x y) (string< (car x) (car y))))))))
3329 (defun tramp-do-directory-files-and-attributes-with-perl
3330 (vec localname &optional id-format)
3331 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3332 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3333 (tramp-maybe-send-script
3334 vec tramp-perl-directory-files-and-attributes
3335 "tramp_perl_directory_files_and_attributes")
3336 (let ((object
3337 (tramp-send-command-and-read
3339 (format "tramp_perl_directory_files_and_attributes %s %s"
3340 (tramp-shell-quote-argument localname) id-format))))
3341 (when (stringp object) (tramp-error vec 'file-error object))
3342 object))
3344 (defun tramp-do-directory-files-and-attributes-with-stat
3345 (vec localname &optional id-format)
3346 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3347 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3348 (tramp-send-command-and-read
3350 (format
3351 (concat
3352 ;; We must care about filenames with spaces, or starting with
3353 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3354 ;; but it does not work on all remote systems. Therefore, we
3355 ;; quote the filenames via sed.
3356 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3357 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3358 "echo \")\"")
3359 (tramp-shell-quote-argument localname)
3360 (tramp-get-ls-command vec)
3361 (tramp-get-remote-stat vec)
3362 (if (eq id-format 'integer) "%u" "\"%U\"")
3363 (if (eq id-format 'integer) "%g" "\"%G\""))))
3365 ;; This function should return "foo/" for directories and "bar" for
3366 ;; files.
3367 (defun tramp-handle-file-name-all-completions (filename directory)
3368 "Like `file-name-all-completions' for Tramp files."
3369 (unless (save-match-data (string-match "/" filename))
3370 (with-parsed-tramp-file-name (expand-file-name directory) nil
3372 (all-completions
3373 filename
3374 (mapcar
3375 'list
3377 ;; Try cache first
3378 (and
3379 ;; Ignore if expired
3380 (or (not (integerp tramp-completion-reread-directory-timeout))
3381 (<= (tramp-time-diff
3382 (current-time)
3383 (tramp-get-file-property
3384 v localname "last-completion" '(0 0 0)))
3385 tramp-completion-reread-directory-timeout))
3387 ;; Try cache entries for filename, filename with last
3388 ;; character removed, filename with last two characters
3389 ;; removed, ..., and finally the empty string - all
3390 ;; concatenated to the local directory name
3392 ;; This is inefficient for very long filenames, pity
3393 ;; `reduce' is not available...
3394 (car
3395 (apply
3396 'append
3397 (mapcar
3398 (lambda (x)
3399 (let ((cache-hit
3400 (tramp-get-file-property
3402 (concat localname (substring filename 0 x))
3403 "file-name-all-completions"
3404 nil)))
3405 (when cache-hit (list cache-hit))))
3406 (tramp-compat-number-sequence (length filename) 0 -1)))))
3408 ;; Cache expired or no matching cache entry found so we need
3409 ;; to perform a remote operation
3410 (let (result)
3411 ;; Get a list of directories and files, including reliably
3412 ;; tagging the directories with a trailing '/'. Because I
3413 ;; rock. --daniel@danann.net
3415 ;; Changed to perform `cd' in the same remote op and only
3416 ;; get entries starting with `filename'. Capture any `cd'
3417 ;; error messages. Ensure any `cd' and `echo' aliases are
3418 ;; ignored.
3419 (tramp-send-command
3421 (if (tramp-get-remote-perl v)
3422 (progn
3423 (tramp-maybe-send-script
3424 v tramp-perl-file-name-all-completions
3425 "tramp_perl_file_name_all_completions")
3426 (format "tramp_perl_file_name_all_completions %s %s %d"
3427 (tramp-shell-quote-argument localname)
3428 (tramp-shell-quote-argument filename)
3429 (if (symbol-value
3430 ;; `read-file-name-completion-ignore-case'
3431 ;; is introduced with Emacs 22.1.
3432 (if (boundp
3433 'read-file-name-completion-ignore-case)
3434 'read-file-name-completion-ignore-case
3435 'completion-ignore-case))
3436 1 0)))
3438 (format (concat
3439 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3440 ;; `ls' with wildcard might fail with `Argument
3441 ;; list too long' error in some corner cases; if
3442 ;; `ls' fails after `cd' succeeded, chances are
3443 ;; that's the case, so let's retry without
3444 ;; wildcard. This will return "too many" entries
3445 ;; but that isn't harmful.
3446 " || %s -a 2>/dev/null)"
3447 " | while read f; do"
3448 " if %s -d \"$f\" 2>/dev/null;"
3449 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3450 " && \\echo ok) || \\echo fail")
3451 (tramp-shell-quote-argument localname)
3452 (tramp-get-ls-command v)
3453 ;; When `filename' is empty, just `ls' without
3454 ;; filename argument is more efficient than `ls *'
3455 ;; for very large directories and might avoid the
3456 ;; `Argument list too long' error.
3458 ;; With and only with wildcard, we need to add
3459 ;; `-d' to prevent `ls' from descending into
3460 ;; sub-directories.
3461 (if (zerop (length filename))
3463 (concat (tramp-shell-quote-argument filename) "* -d"))
3464 (tramp-get-ls-command v)
3465 (tramp-get-test-command v))))
3467 ;; Now grab the output.
3468 (with-current-buffer (tramp-get-buffer v)
3469 (goto-char (point-max))
3471 ;; Check result code, found in last line of output
3472 (forward-line -1)
3473 (if (looking-at "^fail$")
3474 (progn
3475 ;; Grab error message from line before last line
3476 ;; (it was put there by `cd 2>&1')
3477 (forward-line -1)
3478 (tramp-error
3479 v 'file-error
3480 "tramp-handle-file-name-all-completions: %s"
3481 (buffer-substring
3482 (point) (tramp-compat-line-end-position))))
3483 ;; For peace of mind, if buffer doesn't end in `fail'
3484 ;; then it should end in `ok'. If neither are in the
3485 ;; buffer something went seriously wrong on the remote
3486 ;; side.
3487 (unless (looking-at "^ok$")
3488 (tramp-error
3489 v 'file-error
3491 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3492 (tramp-shell-quote-argument localname) (buffer-string))))
3494 (while (zerop (forward-line -1))
3495 (push (buffer-substring
3496 (point) (tramp-compat-line-end-position))
3497 result)))
3499 ;; Because the remote op went through OK we know the
3500 ;; directory we `cd'-ed to exists
3501 (tramp-set-file-property
3502 v localname "file-exists-p" t)
3504 ;; Because the remote op went through OK we know every
3505 ;; file listed by `ls' exists.
3506 (mapc (lambda (entry)
3507 (tramp-set-file-property
3508 v (concat localname entry) "file-exists-p" t))
3509 result)
3511 (tramp-set-file-property
3512 v localname "last-completion" (current-time))
3514 ;; Store result in the cache
3515 (tramp-set-file-property
3516 v (concat localname filename)
3517 "file-name-all-completions"
3518 result))))))))
3520 (defun tramp-handle-file-name-completion
3521 (filename directory &optional predicate)
3522 "Like `file-name-completion' for Tramp files."
3523 (unless (tramp-tramp-file-p directory)
3524 (error
3525 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3526 directory))
3527 (try-completion
3528 filename
3529 (mapcar 'list (file-name-all-completions filename directory))
3530 (when predicate
3531 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3533 ;; cp, mv and ln
3535 (defun tramp-handle-add-name-to-file
3536 (filename newname &optional ok-if-already-exists)
3537 "Like `add-name-to-file' for Tramp files."
3538 (unless (tramp-equal-remote filename newname)
3539 (with-parsed-tramp-file-name
3540 (if (tramp-tramp-file-p filename) filename newname) nil
3541 (tramp-error
3542 v 'file-error
3543 "add-name-to-file: %s"
3544 "only implemented for same method, same user, same host")))
3545 (with-parsed-tramp-file-name filename v1
3546 (with-parsed-tramp-file-name newname v2
3547 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3548 (when (and (not ok-if-already-exists)
3549 (file-exists-p newname)
3550 (not (numberp ok-if-already-exists))
3551 (y-or-n-p
3552 (format
3553 "File %s already exists; make it a new name anyway? "
3554 newname)))
3555 (tramp-error
3556 v2 'file-error
3557 "add-name-to-file: file %s already exists" newname))
3558 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3559 (tramp-flush-file-property v2 v2-localname)
3560 (tramp-barf-unless-okay
3562 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3563 (tramp-shell-quote-argument v2-localname))
3564 "error with add-name-to-file, see buffer `%s' for details"
3565 (buffer-name))))))
3567 (defun tramp-handle-copy-file
3568 (filename newname &optional ok-if-already-exists keep-date
3569 preserve-uid-gid preserve-selinux-context)
3570 "Like `copy-file' for Tramp files."
3571 (setq filename (expand-file-name filename))
3572 (setq newname (expand-file-name newname))
3573 (cond
3574 ;; At least one file a Tramp file?
3575 ((or (tramp-tramp-file-p filename)
3576 (tramp-tramp-file-p newname))
3577 (tramp-do-copy-or-rename-file
3578 'copy filename newname ok-if-already-exists keep-date
3579 preserve-uid-gid preserve-selinux-context))
3580 ;; Compat section.
3581 (preserve-selinux-context
3582 (tramp-run-real-handler
3583 'copy-file
3584 (list filename newname ok-if-already-exists keep-date
3585 preserve-uid-gid preserve-selinux-context)))
3586 (preserve-uid-gid
3587 (tramp-run-real-handler
3588 'copy-file
3589 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3591 (tramp-run-real-handler
3592 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3594 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3595 "Like `copy-directory' for Tramp files."
3596 (let ((t1 (tramp-tramp-file-p dirname))
3597 (t2 (tramp-tramp-file-p newname)))
3598 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3599 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3600 ;; When DIRNAME and NEWNAME are remote, they must have
3601 ;; the same method.
3602 (or (null t1) (null t2)
3603 (string-equal
3604 (tramp-file-name-method (tramp-dissect-file-name dirname))
3605 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3606 ;; scp or rsync DTRT.
3607 (progn
3608 (setq dirname (directory-file-name (expand-file-name dirname))
3609 newname (directory-file-name (expand-file-name newname)))
3610 (if (and (file-directory-p newname)
3611 (not (string-equal (file-name-nondirectory dirname)
3612 (file-name-nondirectory newname))))
3613 (setq newname
3614 (expand-file-name
3615 (file-name-nondirectory dirname) newname)))
3616 (if (not (file-directory-p (file-name-directory newname)))
3617 (make-directory (file-name-directory newname) parents))
3618 (tramp-do-copy-or-rename-file-out-of-band
3619 'copy dirname newname keep-date))
3620 ;; We must do it file-wise.
3621 (tramp-run-real-handler
3622 'copy-directory (list dirname newname keep-date parents)))
3624 ;; When newname did exist, we have wrong cached values.
3625 (when t2
3626 (with-parsed-tramp-file-name newname nil
3627 (tramp-flush-file-property v (file-name-directory localname))
3628 (tramp-flush-file-property v localname))))))
3630 (defun tramp-handle-rename-file
3631 (filename newname &optional ok-if-already-exists)
3632 "Like `rename-file' for Tramp files."
3633 ;; Check if both files are local -- invoke normal rename-file.
3634 ;; Otherwise, use Tramp from local system.
3635 (setq filename (expand-file-name filename))
3636 (setq newname (expand-file-name newname))
3637 ;; At least one file a Tramp file?
3638 (if (or (tramp-tramp-file-p filename)
3639 (tramp-tramp-file-p newname))
3640 (tramp-do-copy-or-rename-file
3641 'rename filename newname ok-if-already-exists t t)
3642 (tramp-run-real-handler
3643 'rename-file (list filename newname ok-if-already-exists))))
3645 (defun tramp-do-copy-or-rename-file
3646 (op filename newname &optional ok-if-already-exists keep-date
3647 preserve-uid-gid preserve-selinux-context)
3648 "Copy or rename a remote file.
3649 OP must be `copy' or `rename' and indicates the operation to perform.
3650 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3651 the new file (for copy) or the new name of the file (for rename).
3652 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3653 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3654 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3655 the uid and gid if both files are on the same host.
3656 PRESERVE-SELINUX-CONTEXT activates selinux commands.
3658 This function is invoked by `tramp-handle-copy-file' and
3659 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3660 and `rename'. FILENAME and NEWNAME must be absolute file names."
3661 (unless (memq op '(copy rename))
3662 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3663 (let ((t1 (tramp-tramp-file-p filename))
3664 (t2 (tramp-tramp-file-p newname))
3665 (context (and preserve-selinux-context
3666 (apply 'file-selinux-context (list filename))))
3667 pr tm)
3669 (with-parsed-tramp-file-name (if t1 filename newname) nil
3670 (when (and (not ok-if-already-exists) (file-exists-p newname))
3671 (tramp-error
3672 v 'file-already-exists "File %s already exists" newname))
3674 (with-progress-reporter
3675 v 0 (format "%s %s to %s"
3676 (if (eq op 'copy) "Copying" "Renaming")
3677 filename newname)
3679 (cond
3680 ;; Both are Tramp files.
3681 ((and t1 t2)
3682 (with-parsed-tramp-file-name filename v1
3683 (with-parsed-tramp-file-name newname v2
3684 (cond
3685 ;; Shortcut: if method, host, user are the same for
3686 ;; both files, we invoke `cp' or `mv' on the remote
3687 ;; host directly.
3688 ((tramp-equal-remote filename newname)
3689 (tramp-do-copy-or-rename-file-directly
3690 op filename newname
3691 ok-if-already-exists keep-date preserve-uid-gid))
3693 ;; Try out-of-band operation.
3694 ((tramp-method-out-of-band-p
3695 v1 (nth 7 (file-attributes filename)))
3696 (tramp-do-copy-or-rename-file-out-of-band
3697 op filename newname keep-date))
3699 ;; No shortcut was possible. So we copy the file
3700 ;; first. If the operation was `rename', we go back
3701 ;; and delete the original file (if the copy was
3702 ;; successful). The approach is simple-minded: we
3703 ;; create a new buffer, insert the contents of the
3704 ;; source file into it, then write out the buffer to
3705 ;; the target file. The advantage is that it doesn't
3706 ;; matter which filename handlers are used for the
3707 ;; source and target file.
3709 (tramp-do-copy-or-rename-file-via-buffer
3710 op filename newname keep-date))))))
3712 ;; One file is a Tramp file, the other one is local.
3713 ((or t1 t2)
3714 (cond
3715 ;; Fast track on local machine.
3716 ((tramp-local-host-p v)
3717 (tramp-do-copy-or-rename-file-directly
3718 op filename newname
3719 ok-if-already-exists keep-date preserve-uid-gid))
3721 ;; If the Tramp file has an out-of-band method, the
3722 ;; corresponding copy-program can be invoked.
3723 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3724 (tramp-do-copy-or-rename-file-out-of-band
3725 op filename newname keep-date))
3727 ;; Use the inline method via a Tramp buffer.
3728 (t (tramp-do-copy-or-rename-file-via-buffer
3729 op filename newname keep-date))))
3732 ;; One of them must be a Tramp file.
3733 (error "Tramp implementation says this cannot happen")))
3735 ;; Handle `preserve-selinux-context'.
3736 (when context (apply 'set-file-selinux-context (list newname context)))
3738 ;; In case of `rename', we must flush the cache of the source file.
3739 (when (and t1 (eq op 'rename))
3740 (with-parsed-tramp-file-name filename v1
3741 (tramp-flush-file-property v1 (file-name-directory localname))
3742 (tramp-flush-file-property v1 localname)))
3744 ;; When newname did exist, we have wrong cached values.
3745 (when t2
3746 (with-parsed-tramp-file-name newname v2
3747 (tramp-flush-file-property v2 (file-name-directory localname))
3748 (tramp-flush-file-property v2 localname)))))))
3750 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3751 "Use an Emacs buffer to copy or rename a file.
3752 First arg OP is either `copy' or `rename' and indicates the operation.
3753 FILENAME is the source file, NEWNAME the target file.
3754 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3755 (with-temp-buffer
3756 ;; We must disable multibyte, because binary data shall not be
3757 ;; converted.
3758 (set-buffer-multibyte nil)
3759 (let ((coding-system-for-read 'binary)
3760 (jka-compr-inhibit t))
3761 (insert-file-contents-literally filename))
3762 ;; We don't want the target file to be compressed, so we let-bind
3763 ;; `jka-compr-inhibit' to t.
3764 (let ((coding-system-for-write 'binary)
3765 (jka-compr-inhibit t))
3766 (write-region (point-min) (point-max) newname)))
3767 ;; KEEP-DATE handling.
3768 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3769 ;; Set the mode.
3770 (set-file-modes newname (tramp-default-file-modes filename))
3771 ;; If the operation was `rename', delete the original file.
3772 (unless (eq op 'copy) (tramp-compat-delete-file filename 'force)))
3774 (defun tramp-do-copy-or-rename-file-directly
3775 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3776 "Invokes `cp' or `mv' on the remote system.
3777 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3778 respectively. FILENAME specifies the file to copy or rename,
3779 NEWNAME is the name of the new file (for copy) or the new name of
3780 the file (for rename). Both files must reside on the same host.
3781 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3782 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3783 the uid and gid from FILENAME."
3784 (let ((t1 (tramp-tramp-file-p filename))
3785 (t2 (tramp-tramp-file-p newname))
3786 (file-times (nth 5 (file-attributes filename)))
3787 (file-modes (tramp-default-file-modes filename)))
3788 (with-parsed-tramp-file-name (if t1 filename newname) nil
3789 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3790 ((eq op 'copy) "cp -f")
3791 ((eq op 'rename) "mv -f")
3792 (t (tramp-error
3793 v 'file-error
3794 "Unknown operation `%s', must be `copy' or `rename'"
3795 op))))
3796 (localname1
3797 (if t1
3798 (tramp-file-name-handler 'file-remote-p filename 'localname)
3799 filename))
3800 (localname2
3801 (if t2
3802 (tramp-file-name-handler 'file-remote-p newname 'localname)
3803 newname))
3804 (prefix (file-remote-p (if t1 filename newname)))
3805 cmd-result)
3807 (cond
3808 ;; Both files are on a remote host, with same user.
3809 ((and t1 t2)
3810 (setq cmd-result
3811 (tramp-send-command-and-check
3813 (format "%s %s %s" cmd
3814 (tramp-shell-quote-argument localname1)
3815 (tramp-shell-quote-argument localname2))))
3816 (with-current-buffer (tramp-get-buffer v)
3817 (goto-char (point-min))
3818 (unless
3820 (and keep-date
3821 ;; Mask cp -f error.
3822 (re-search-forward
3823 tramp-operation-not-permitted-regexp nil t))
3824 (zerop cmd-result))
3825 (tramp-error-with-buffer
3826 nil v 'file-error
3827 "Copying directly failed, see buffer `%s' for details."
3828 (buffer-name)))))
3830 ;; We are on the local host.
3831 ((or t1 t2)
3832 (cond
3833 ;; We can do it directly.
3834 ((let (file-name-handler-alist)
3835 (and (file-readable-p localname1)
3836 (file-writable-p (file-name-directory localname2))
3837 (or (file-directory-p localname2)
3838 (file-writable-p localname2))))
3839 (if (eq op 'copy)
3840 (tramp-compat-copy-file
3841 localname1 localname2 ok-if-already-exists
3842 keep-date preserve-uid-gid)
3843 (tramp-run-real-handler
3844 'rename-file (list localname1 localname2 ok-if-already-exists))))
3846 ;; We can do it directly with `tramp-send-command'
3847 ((and (file-readable-p (concat prefix localname1))
3848 (file-writable-p
3849 (file-name-directory (concat prefix localname2)))
3850 (or (file-directory-p (concat prefix localname2))
3851 (file-writable-p (concat prefix localname2))))
3852 (tramp-do-copy-or-rename-file-directly
3853 op (concat prefix localname1) (concat prefix localname2)
3854 ok-if-already-exists keep-date t)
3855 ;; We must change the ownership to the local user.
3856 (tramp-set-file-uid-gid
3857 (concat prefix localname2)
3858 (tramp-get-local-uid 'integer)
3859 (tramp-get-local-gid 'integer)))
3861 ;; We need a temporary file in between.
3863 ;; Create the temporary file.
3864 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3865 (unwind-protect
3866 (progn
3867 (cond
3870 (zerop
3871 (tramp-send-command-and-check
3872 v (format
3873 "%s %s %s" cmd
3874 (tramp-shell-quote-argument localname1)
3875 (tramp-shell-quote-argument tmpfile))))
3876 (tramp-error-with-buffer
3877 nil v 'file-error
3878 "Copying directly failed, see buffer `%s' for details."
3879 (tramp-get-buffer v)))
3880 ;; We must change the ownership as remote user.
3881 ;; Since this does not work reliable, we also
3882 ;; give read permissions.
3883 (set-file-modes
3884 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3885 (tramp-set-file-uid-gid
3886 (concat prefix tmpfile)
3887 (tramp-get-local-uid 'integer)
3888 (tramp-get-local-gid 'integer)))
3890 (if (eq op 'copy)
3891 (tramp-compat-copy-file
3892 localname1 tmpfile t
3893 keep-date preserve-uid-gid)
3894 (tramp-run-real-handler
3895 'rename-file
3896 (list localname1 tmpfile t)))
3897 ;; We must change the ownership as local user.
3898 ;; Since this does not work reliable, we also
3899 ;; give read permissions.
3900 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3901 (tramp-set-file-uid-gid
3902 tmpfile
3903 (tramp-get-remote-uid v 'integer)
3904 (tramp-get-remote-gid v 'integer))))
3906 ;; Move the temporary file to its destination.
3907 (cond
3910 (zerop
3911 (tramp-send-command-and-check
3912 v (format
3913 "cp -f -p %s %s"
3914 (tramp-shell-quote-argument tmpfile)
3915 (tramp-shell-quote-argument localname2))))
3916 (tramp-error-with-buffer
3917 nil v 'file-error
3918 "Copying directly failed, see buffer `%s' for details."
3919 (tramp-get-buffer v))))
3921 (tramp-run-real-handler
3922 'rename-file
3923 (list tmpfile localname2 ok-if-already-exists)))))
3925 ;; Save exit.
3926 (condition-case nil
3927 (tramp-compat-delete-file tmpfile 'force)
3928 (error)))))))))
3930 ;; Set the time and mode. Mask possible errors.
3931 (condition-case nil
3932 (when keep-date
3933 (set-file-times newname file-times)
3934 (set-file-modes newname file-modes))
3935 (error)))))
3937 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3938 "Invoke rcp program to copy.
3939 The method used must be an out-of-band method."
3940 (let ((t1 (tramp-tramp-file-p filename))
3941 (t2 (tramp-tramp-file-p newname))
3942 copy-program copy-args copy-env copy-keep-date port spec
3943 source target)
3945 (with-parsed-tramp-file-name (if t1 filename newname) nil
3946 (if (and t1 t2)
3948 ;; Both are Tramp files. We shall optimize it, when the
3949 ;; methods for filename and newname are the same.
3950 (let* ((dir-flag (file-directory-p filename))
3951 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3952 (if dir-flag
3953 (setq tmpfile
3954 (expand-file-name
3955 (file-name-nondirectory newname) tmpfile)))
3956 (unwind-protect
3957 (progn
3958 (tramp-do-copy-or-rename-file-out-of-band
3959 op filename tmpfile keep-date)
3960 (tramp-do-copy-or-rename-file-out-of-band
3961 'rename tmpfile newname keep-date))
3962 ;; Save exit.
3963 (condition-case nil
3964 (if dir-flag
3965 (tramp-compat-delete-directory
3966 (expand-file-name ".." tmpfile) 'recursive)
3967 (tramp-compat-delete-file tmpfile 'force))
3968 (error))))
3970 ;; Expand hops. Might be necessary for gateway methods.
3971 (setq v (car (tramp-compute-multi-hops v)))
3972 (aset v 3 localname)
3974 ;; Check which ones of source and target are Tramp files.
3975 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3976 target (funcall
3977 (if (and (file-directory-p filename)
3978 (string-equal
3979 (file-name-nondirectory filename)
3980 (file-name-nondirectory newname)))
3981 'file-name-directory
3982 'identity)
3983 (if t2 (tramp-make-copy-program-file-name v) newname)))
3985 ;; Check for port number. Until now, there's no need for handling
3986 ;; like method, user, host.
3987 (setq host (tramp-file-name-real-host v)
3988 port (tramp-file-name-port v)
3989 port (or (and port (number-to-string port)) ""))
3991 ;; Compose copy command.
3992 (setq spec (format-spec-make
3993 ?h host ?u user ?p port
3994 ?t (tramp-get-connection-property
3995 (tramp-get-connection-process v) "temp-file" "")
3996 ?k (if keep-date " " ""))
3997 copy-program (tramp-get-method-parameter
3998 method 'tramp-copy-program)
3999 copy-keep-date (tramp-get-method-parameter
4000 method 'tramp-copy-keep-date)
4001 copy-args
4002 (delq
4004 (mapcar
4005 (lambda (x)
4006 (setq
4008 ;; " " is indication for keep-date argument.
4009 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
4010 (unless (member "" x) (mapconcat 'identity x " ")))
4011 (tramp-get-method-parameter method 'tramp-copy-args)))
4012 copy-env
4013 (delq
4015 (mapcar
4016 (lambda (x)
4017 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4018 (unless (member "" x) (mapconcat 'identity x " ")))
4019 (tramp-get-method-parameter method 'tramp-copy-env))))
4021 ;; Check for program.
4022 (when (and (fboundp 'executable-find)
4023 (not (let ((default-directory
4024 (tramp-compat-temporary-file-directory)))
4025 (executable-find copy-program))))
4026 (tramp-error
4027 v 'file-error "Cannot find copy program: %s" copy-program))
4029 ;; Set variables for computing the prompt for reading
4030 ;; password.
4031 (setq tramp-current-method (tramp-file-name-method v)
4032 tramp-current-user (tramp-file-name-user v)
4033 tramp-current-host (tramp-file-name-host v))
4035 (unwind-protect
4036 (with-temp-buffer
4037 ;; The default directory must be remote.
4038 (let ((default-directory
4039 (file-name-directory (if t1 filename newname)))
4040 (process-environment (copy-sequence process-environment)))
4041 ;; Set the transfer process properties.
4042 (tramp-set-connection-property
4043 v "process-name" (buffer-name (current-buffer)))
4044 (tramp-set-connection-property
4045 v "process-buffer" (current-buffer))
4046 (while copy-env
4047 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
4048 (setenv (pop copy-env) (pop copy-env)))
4050 ;; Use an asynchronous process. By this, password can
4051 ;; be handled. The default directory must be local, in
4052 ;; order to apply the correct `copy-program'. We don't
4053 ;; set a timeout, because the copying of large files can
4054 ;; last longer than 60 secs.
4055 (let ((p (let ((default-directory
4056 (tramp-compat-temporary-file-directory)))
4057 (apply 'start-process
4058 (tramp-get-connection-property
4059 v "process-name" nil)
4060 (tramp-get-connection-property
4061 v "process-buffer" nil)
4062 copy-program
4063 (append copy-args (list source target))))))
4064 (tramp-message
4065 v 6 "%s" (mapconcat 'identity (process-command p) " "))
4066 (tramp-set-process-query-on-exit-flag p nil)
4067 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
4069 ;; Reset the transfer process properties.
4070 (tramp-set-connection-property v "process-name" nil)
4071 (tramp-set-connection-property v "process-buffer" nil))
4073 ;; Handle KEEP-DATE argument.
4074 (when (and keep-date (not copy-keep-date))
4075 (set-file-times newname (nth 5 (file-attributes filename))))
4077 ;; Set the mode.
4078 (unless (and keep-date copy-keep-date)
4079 (ignore-errors
4080 (set-file-modes newname (tramp-default-file-modes filename)))))
4082 ;; If the operation was `rename', delete the original file.
4083 (unless (eq op 'copy)
4084 (if (file-regular-p filename)
4085 (tramp-compat-delete-file filename 'force)
4086 (tramp-compat-delete-directory filename 'recursive))))))
4088 (defun tramp-handle-make-directory (dir &optional parents)
4089 "Like `make-directory' for Tramp files."
4090 (setq dir (expand-file-name dir))
4091 (with-parsed-tramp-file-name dir nil
4092 (tramp-flush-directory-property v (file-name-directory localname))
4093 (save-excursion
4094 (tramp-barf-unless-okay
4096 (format "%s %s"
4097 (if parents "mkdir -p" "mkdir")
4098 (tramp-shell-quote-argument localname))
4099 "Couldn't make directory %s" dir))))
4101 (defun tramp-handle-delete-directory (directory &optional recursive)
4102 "Like `delete-directory' for Tramp files."
4103 (setq directory (expand-file-name directory))
4104 (with-parsed-tramp-file-name directory nil
4105 (tramp-flush-file-property v (file-name-directory localname))
4106 (tramp-flush-directory-property v localname)
4107 (unless (zerop (tramp-send-command-and-check
4109 (format
4110 "%s %s"
4111 (if recursive "rm -rf" "rmdir")
4112 (tramp-shell-quote-argument localname))))
4113 (tramp-error v 'file-error "Couldn't delete %s" directory))))
4115 (defun tramp-handle-delete-file (filename &optional force)
4116 "Like `delete-file' for Tramp files."
4117 (setq filename (expand-file-name filename))
4118 (with-parsed-tramp-file-name filename nil
4119 (tramp-flush-file-property v (file-name-directory localname))
4120 (tramp-flush-file-property v localname)
4121 (unless (zerop (tramp-send-command-and-check
4123 (format "rm -f %s"
4124 (tramp-shell-quote-argument localname))))
4125 (tramp-error v 'file-error "Couldn't delete %s" filename))))
4127 ;; Dired.
4129 ;; CCC: This does not seem to be enough. Something dies when
4130 ;; we try and delete two directories under Tramp :/
4131 (defun tramp-handle-dired-recursive-delete-directory (filename)
4132 "Recursively delete the directory given.
4133 This is like `dired-recursive-delete-directory' for Tramp files."
4134 (with-parsed-tramp-file-name filename nil
4135 ;; Run a shell command 'rm -r <localname>'
4136 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
4137 (unless (file-exists-p filename)
4138 (tramp-error v 'file-error "No such directory: %s" filename))
4139 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
4140 (tramp-send-command
4142 (format "rm -rf %s" (tramp-shell-quote-argument localname))
4143 ;; Don't read the output, do it explicitely.
4144 nil t)
4145 ;; Wait for the remote system to return to us...
4146 ;; This might take a while, allow it plenty of time.
4147 (tramp-wait-for-output (tramp-get-connection-process v) 120)
4148 ;; Make sure that it worked...
4149 (tramp-flush-file-property v (file-name-directory localname))
4150 (tramp-flush-directory-property v localname)
4151 (and (file-exists-p filename)
4152 (tramp-error
4153 v 'file-error "Failed to recursively delete %s" filename))))
4155 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4156 "Like `dired-compress-file' for Tramp files."
4157 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4158 ;; Code stolen mainly from dired-aux.el.
4159 (with-parsed-tramp-file-name file nil
4160 (tramp-flush-file-property v localname)
4161 (save-excursion
4162 (let ((suffixes
4163 (if (not (featurep 'xemacs))
4164 ;; Emacs case
4165 (symbol-value 'dired-compress-file-suffixes)
4166 ;; XEmacs has `dired-compression-method-alist', which is
4167 ;; transformed into `dired-compress-file-suffixes' structure.
4168 (mapcar
4169 (lambda (x)
4170 (list (concat (regexp-quote (nth 1 x)) "\\'")
4172 (mapconcat 'identity (nth 3 x) " ")))
4173 (symbol-value 'dired-compression-method-alist))))
4174 suffix)
4175 ;; See if any suffix rule matches this file name.
4176 (while suffixes
4177 (let (case-fold-search)
4178 (if (string-match (car (car suffixes)) localname)
4179 (setq suffix (car suffixes) suffixes nil))
4180 (setq suffixes (cdr suffixes))))
4182 (cond ((file-symlink-p file)
4183 nil)
4184 ((and suffix (nth 2 suffix))
4185 ;; We found an uncompression rule.
4186 (with-progress-reporter v 0 (format "Uncompressing %s" file)
4187 (when (zerop
4188 (tramp-send-command-and-check
4189 v (concat (nth 2 suffix) " "
4190 (tramp-shell-quote-argument localname))))
4191 ;; `dired-remove-file' is not defined in XEmacs.
4192 (tramp-compat-funcall 'dired-remove-file file)
4193 (string-match (car suffix) file)
4194 (concat (substring file 0 (match-beginning 0))))))
4196 ;; We don't recognize the file as compressed, so compress it.
4197 ;; Try gzip.
4198 (with-progress-reporter v 0 (format "Compressing %s" file)
4199 (when (zerop
4200 (tramp-send-command-and-check
4201 v (concat "gzip -f "
4202 (tramp-shell-quote-argument localname))))
4203 ;; `dired-remove-file' is not defined in XEmacs.
4204 (tramp-compat-funcall 'dired-remove-file file)
4205 (cond ((file-exists-p (concat file ".gz"))
4206 (concat file ".gz"))
4207 ((file-exists-p (concat file ".z"))
4208 (concat file ".z"))
4209 (t nil))))))))))
4211 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4212 "Like `dired-uncache' for Tramp files."
4213 ;; DIR-P is valid for XEmacs only.
4214 (with-parsed-tramp-file-name
4215 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4216 (tramp-flush-file-property v localname)))
4218 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4219 ;; not sure at all that this is the right way to do it, but let's hope
4220 ;; it works for now, and wait for a guru to point out the Right Way to
4221 ;; achieve this.
4222 ;;(eval-when-compile
4223 ;; (unless (fboundp 'dired-insert-set-properties)
4224 ;; (fset 'dired-insert-set-properties 'ignore)))
4225 ;; Gerd suggests this:
4226 (eval-when-compile (require 'dired))
4227 ;; Note that dired is required at run-time, too, when it is needed.
4228 ;; It is only needed on XEmacs for the function
4229 ;; `dired-insert-set-properties'.
4231 (defun tramp-handle-insert-directory
4232 (filename switches &optional wildcard full-directory-p)
4233 "Like `insert-directory' for Tramp files."
4234 (setq filename (expand-file-name filename))
4235 (with-parsed-tramp-file-name filename nil
4236 (if (and (featurep 'ls-lisp)
4237 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4238 (tramp-run-real-handler
4239 'insert-directory (list filename switches wildcard full-directory-p))
4240 (when (stringp switches)
4241 (setq switches (split-string switches)))
4242 (when (and (member "--dired" switches)
4243 (not (tramp-get-ls-command-with-dired v)))
4244 (setq switches (delete "--dired" switches)))
4245 (when wildcard
4246 (setq wildcard (tramp-run-real-handler
4247 'file-name-nondirectory (list localname)))
4248 (setq localname (tramp-run-real-handler
4249 'file-name-directory (list localname))))
4250 (unless full-directory-p
4251 (setq switches (add-to-list 'switches "-d" 'append)))
4252 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4253 (when wildcard
4254 (setq switches (concat switches " " wildcard)))
4255 (tramp-message
4256 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4257 switches filename (if wildcard "yes" "no")
4258 (if full-directory-p "yes" "no"))
4259 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4260 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4261 (if full-directory-p
4262 (tramp-send-command
4264 (format "%s %s %s 2>/dev/null"
4265 (tramp-get-ls-command v)
4266 switches
4267 (if wildcard
4268 localname
4269 (tramp-shell-quote-argument (concat localname ".")))))
4270 (tramp-barf-unless-okay
4272 (format "cd %s" (tramp-shell-quote-argument
4273 (tramp-run-real-handler
4274 'file-name-directory (list localname))))
4275 "Couldn't `cd %s'"
4276 (tramp-shell-quote-argument
4277 (tramp-run-real-handler 'file-name-directory (list localname))))
4278 (tramp-send-command
4280 (format "%s %s %s"
4281 (tramp-get-ls-command v)
4282 switches
4283 (if (or wildcard
4284 (zerop (length
4285 (tramp-run-real-handler
4286 'file-name-nondirectory (list localname)))))
4288 (tramp-shell-quote-argument
4289 (tramp-run-real-handler
4290 'file-name-nondirectory (list localname)))))))
4291 (let ((beg (point)))
4292 ;; We cannot use `insert-buffer-substring' because the Tramp
4293 ;; buffer changes its contents before insertion due to calling
4294 ;; `expand-file' and alike.
4295 (insert
4296 (with-current-buffer (tramp-get-buffer v)
4297 (buffer-string)))
4299 ;; Check for "--dired" output.
4300 (forward-line -2)
4301 (when (looking-at "//SUBDIRED//")
4302 (forward-line -1))
4303 (when (looking-at "//DIRED//\\s-+")
4304 (let ((databeg (match-end 0))
4305 (end (tramp-compat-line-end-position)))
4306 ;; Now read the numeric positions of file names.
4307 (goto-char databeg)
4308 (while (< (point) end)
4309 (let ((start (+ beg (read (current-buffer))))
4310 (end (+ beg (read (current-buffer)))))
4311 (if (memq (char-after end) '(?\n ?\ ))
4312 ;; End is followed by \n or by " -> ".
4313 (put-text-property start end 'dired-filename t))))))
4314 ;; Remove trailing lines.
4315 (goto-char (tramp-compat-line-beginning-position))
4316 (while (looking-at "//")
4317 (forward-line 1)
4318 (delete-region (match-beginning 0) (point)))
4320 ;; The inserted file could be from somewhere else.
4321 (when (and (not wildcard) (not full-directory-p))
4322 (goto-char (point-max))
4323 (when (file-symlink-p filename)
4324 (goto-char (search-backward "->" beg 'noerror)))
4325 (search-backward
4326 (if (zerop (length (file-name-nondirectory filename)))
4328 (file-name-nondirectory filename))
4329 beg 'noerror)
4330 (replace-match (file-relative-name filename) t))
4332 (goto-char (point-max))))))
4334 (defun tramp-handle-unhandled-file-name-directory (filename)
4335 "Like `unhandled-file-name-directory' for Tramp files."
4336 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4337 ;; for backward compatibility.
4338 (expand-file-name "~/"))
4340 ;; Canonicalization of file names.
4342 (defun tramp-handle-expand-file-name (name &optional dir)
4343 "Like `expand-file-name' for Tramp files.
4344 If the localname part of the given filename starts with \"/../\" then
4345 the result will be a local, non-Tramp, filename."
4346 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4347 (setq dir (or dir default-directory "/"))
4348 ;; Unless NAME is absolute, concat DIR and NAME.
4349 (unless (file-name-absolute-p name)
4350 (setq name (concat (file-name-as-directory dir) name)))
4351 ;; If NAME is not a Tramp file, run the real handler.
4352 (if (not (tramp-connectable-p name))
4353 (tramp-run-real-handler 'expand-file-name (list name nil))
4354 ;; Dissect NAME.
4355 (with-parsed-tramp-file-name name nil
4356 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4357 (setq localname (concat "~/" localname)))
4358 ;; Tilde expansion if necessary. This needs a shell which
4359 ;; groks tilde expansion! The function `tramp-find-shell' is
4360 ;; supposed to find such a shell on the remote host. Please
4361 ;; tell me about it when this doesn't work on your system.
4362 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4363 (let ((uname (match-string 1 localname))
4364 (fname (match-string 2 localname)))
4365 ;; We cannot simply apply "~/", because under sudo "~/" is
4366 ;; expanded to the local user home directory but to the
4367 ;; root home directory. On the other hand, using always
4368 ;; the default user name for tilde expansion is not
4369 ;; appropriate either, because ssh and companions might
4370 ;; use a user name from the config file.
4371 (when (and (string-equal uname "~")
4372 (string-match "\\`su\\(do\\)?\\'" method))
4373 (setq uname (concat uname user)))
4374 (setq uname
4375 (with-connection-property v uname
4376 (tramp-send-command
4377 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4378 (with-current-buffer (tramp-get-buffer v)
4379 (goto-char (point-min))
4380 (buffer-substring
4381 (point) (tramp-compat-line-end-position)))))
4382 (setq localname (concat uname fname))))
4383 ;; There might be a double slash, for example when "~/"
4384 ;; expands to "/". Remove this.
4385 (while (string-match "//" localname)
4386 (setq localname (replace-match "/" t t localname)))
4387 ;; No tilde characters in file name, do normal
4388 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4389 ;; `directory-sep-char' here for XEmacs on Windows, which would
4390 ;; otherwise use backslash. `default-directory' is bound,
4391 ;; because on Windows there would be problems with UNC shares or
4392 ;; Cygwin mounts.
4393 (let ((directory-sep-char ?/)
4394 (default-directory (tramp-compat-temporary-file-directory)))
4395 (tramp-make-tramp-file-name
4396 method user host
4397 (tramp-drop-volume-letter
4398 (tramp-run-real-handler
4399 'expand-file-name (list localname))))))))
4401 (defun tramp-replace-environment-variables (filename)
4402 "Replace environment variables in FILENAME.
4403 Return the string with the replaced variables."
4404 (save-match-data
4405 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4406 ;; `$' is coded as `$$'.
4407 (when (and idx
4408 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4409 (getenv (match-string 1 filename)))
4410 (setq filename
4411 (replace-match
4412 (substitute-in-file-name (match-string 0 filename))
4413 t nil filename)))
4414 filename)))
4416 (defun tramp-handle-substitute-in-file-name (filename)
4417 "Like `substitute-in-file-name' for Tramp files.
4418 \"//\" and \"/~\" substitute only in the local filename part.
4419 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4420 beginning of local filename are not substituted."
4421 ;; First, we must replace environment variables.
4422 (setq filename (tramp-replace-environment-variables filename))
4423 (with-parsed-tramp-file-name filename nil
4424 (if (equal tramp-syntax 'url)
4425 ;; We need to check localname only. The other parts cannot contain
4426 ;; "//" or "/~".
4427 (if (and (> (length localname) 1)
4428 (or (string-match "//" localname)
4429 (string-match "/~" localname 1)))
4430 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4431 (tramp-make-tramp-file-name
4432 (when method (substitute-in-file-name method))
4433 (when user (substitute-in-file-name user))
4434 (when host (substitute-in-file-name host))
4435 (when localname
4436 (tramp-run-real-handler
4437 'substitute-in-file-name (list localname)))))
4438 ;; Ignore in LOCALNAME everything before "//" or "/~".
4439 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4440 (setq filename
4441 (concat (file-remote-p filename)
4442 (replace-match "\\1" nil nil localname)))
4443 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4444 (when (string-match "~$" filename)
4445 (setq filename (concat filename "/"))))
4446 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4448 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4449 ;; which calls corresponding functions (see minibuf.el).
4450 (when (fboundp 'minibuffer-electric-separator)
4451 (mapc
4452 (lambda (x)
4453 (eval
4454 `(defadvice ,x
4455 (around ,(intern (format "tramp-advice-%s" x)) activate)
4456 "Invoke `substitute-in-file-name' for Tramp files."
4457 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4458 (tramp-tramp-file-p (buffer-substring)))
4459 ;; We don't need to handle `last-input-event', because
4460 ;; due to the key map we know it must be ?/ or ?~.
4461 (let ((s (concat (buffer-substring (point-min) (point))
4462 (string last-command-char))))
4463 (delete-region (point-min) (point))
4464 (insert (substitute-in-file-name s))
4465 (setq ad-return-value last-command-char))
4466 ad-do-it)))
4467 (eval
4468 `(add-hook
4469 'tramp-unload-hook
4470 (lambda ()
4471 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4472 (ad-activate ',x)))))
4474 '(minibuffer-electric-separator
4475 minibuffer-electric-tilde)))
4478 ;;; Remote commands:
4480 (defun tramp-handle-executable-find (command)
4481 "Like `executable-find' for Tramp files."
4482 (with-parsed-tramp-file-name default-directory nil
4483 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4485 ;; We use BUFFER also as connection buffer during setup. Because of
4486 ;; this, its original contents must be saved, and restored once
4487 ;; connection has been setup.
4488 (defun tramp-handle-start-file-process (name buffer program &rest args)
4489 "Like `start-file-process' for Tramp files."
4490 (with-parsed-tramp-file-name default-directory nil
4491 (unless (stringp program)
4492 (tramp-error
4493 v 'file-error "pty association is not supported for `%s'" name))
4494 (unwind-protect
4495 (let ((command (format "cd %s; exec %s"
4496 (tramp-shell-quote-argument localname)
4497 (mapconcat 'tramp-shell-quote-argument
4498 (cons program args) " ")))
4499 (name1 name)
4500 (i 0))
4501 (unless buffer
4502 ;; BUFFER can be nil. We use a temporary buffer.
4503 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4504 (while (get-process name1)
4505 ;; NAME must be unique as process name.
4506 (setq i (1+ i)
4507 name1 (format "%s<%d>" name i)))
4508 (setq name name1)
4509 ;; Set the new process properties.
4510 (tramp-set-connection-property v "process-name" name)
4511 (tramp-set-connection-property v "process-buffer" buffer)
4512 ;; Activate narrowing in order to save BUFFER contents.
4513 ;; Clear also the modification time; otherwise we might be
4514 ;; interrupted by `verify-visited-file-modtime'.
4515 (with-current-buffer (tramp-get-connection-buffer v)
4516 (clear-visited-file-modtime)
4517 (narrow-to-region (point-max) (point-max)))
4518 ;; Send the command. `tramp-send-command' opens a new
4519 ;; connection.
4520 (tramp-send-command v command nil t) ; nooutput
4521 ;; Set query flag for this process.
4522 (tramp-set-process-query-on-exit-flag
4523 (tramp-get-connection-process v) t)
4524 ;; Return process.
4525 (tramp-get-connection-process v))
4526 ;; Save exit.
4527 (with-current-buffer (tramp-get-connection-buffer v)
4528 (if (string-match tramp-temp-buffer-name (buffer-name))
4529 (progn
4530 (set-process-buffer (tramp-get-connection-process v) nil)
4531 (kill-buffer (current-buffer)))
4532 (widen)
4533 (goto-char (point-max))))
4534 (tramp-set-connection-property v "process-name" nil)
4535 (tramp-set-connection-property v "process-buffer" nil))))
4537 (defun tramp-handle-process-file
4538 (program &optional infile destination display &rest args)
4539 "Like `process-file' for Tramp files."
4540 ;; The implementation is not complete yet.
4541 (when (and (numberp destination) (zerop destination))
4542 (error "Implementation does not handle immediate return"))
4544 (with-parsed-tramp-file-name default-directory nil
4545 (let (command input tmpinput stderr tmpstderr outbuf ret)
4546 ;; Compute command.
4547 (setq command (mapconcat 'tramp-shell-quote-argument
4548 (cons program args) " "))
4549 ;; Determine input.
4550 (if (null infile)
4551 (setq input "/dev/null")
4552 (setq infile (expand-file-name infile))
4553 (if (tramp-equal-remote default-directory infile)
4554 ;; INFILE is on the same remote host.
4555 (setq input (with-parsed-tramp-file-name infile nil localname))
4556 ;; INFILE must be copied to remote host.
4557 (setq input (tramp-make-tramp-temp-file v)
4558 tmpinput (tramp-make-tramp-file-name method user host input))
4559 (copy-file infile tmpinput t)))
4560 (when input (setq command (format "%s <%s" command input)))
4562 ;; Determine output.
4563 (cond
4564 ;; Just a buffer.
4565 ((bufferp destination)
4566 (setq outbuf destination))
4567 ;; A buffer name.
4568 ((stringp destination)
4569 (setq outbuf (get-buffer-create destination)))
4570 ;; (REAL-DESTINATION ERROR-DESTINATION)
4571 ((consp destination)
4572 ;; output.
4573 (cond
4574 ((bufferp (car destination))
4575 (setq outbuf (car destination)))
4576 ((stringp (car destination))
4577 (setq outbuf (get-buffer-create (car destination))))
4578 ((car destination)
4579 (setq outbuf (current-buffer))))
4580 ;; stderr.
4581 (cond
4582 ((stringp (cadr destination))
4583 (setcar (cdr destination) (expand-file-name (cadr destination)))
4584 (if (tramp-equal-remote default-directory (cadr destination))
4585 ;; stderr is on the same remote host.
4586 (setq stderr (with-parsed-tramp-file-name
4587 (cadr destination) nil localname))
4588 ;; stderr must be copied to remote host. The temporary
4589 ;; file must be deleted after execution.
4590 (setq stderr (tramp-make-tramp-temp-file v)
4591 tmpstderr (tramp-make-tramp-file-name
4592 method user host stderr))))
4593 ;; stderr to be discarded.
4594 ((null (cadr destination))
4595 (setq stderr "/dev/null"))))
4596 ;; 't
4597 (destination
4598 (setq outbuf (current-buffer))))
4599 (when stderr (setq command (format "%s 2>%s" command stderr)))
4601 ;; Send the command. It might not return in time, so we protect it.
4602 (condition-case nil
4603 (unwind-protect
4604 (setq ret
4605 (tramp-send-command-and-check
4606 v (format "\\cd %s; %s"
4607 (tramp-shell-quote-argument localname)
4608 command)
4609 nil t))
4610 ;; We should show the output anyway.
4611 (when outbuf
4612 (with-current-buffer outbuf
4613 (insert
4614 (with-current-buffer (tramp-get-connection-buffer v)
4615 (buffer-string))))
4616 (when display (display-buffer outbuf))))
4617 ;; When the user did interrupt, we should do it also. We use
4618 ;; return code -1 as marker.
4619 (quit
4620 (kill-buffer (tramp-get-connection-buffer v))
4621 (setq ret -1))
4622 ;; Handle errors.
4623 (error
4624 (kill-buffer (tramp-get-connection-buffer v))
4625 (setq ret 1)))
4627 ;; Provide error file.
4628 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4630 ;; Cleanup. We remove all file cache values for the connection,
4631 ;; because the remote process could have changed them.
4632 (when tmpinput (tramp-compat-delete-file tmpinput 'force))
4634 ;; `process-file-side-effects' has been introduced with GNU
4635 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4636 ;; by `program'. If it doesn't exist, we assume its default
4637 ;; value 't'.
4638 (unless (and (boundp 'process-file-side-effects)
4639 (not (symbol-value 'process-file-side-effects)))
4640 (tramp-flush-directory-property v ""))
4642 ;; Return exit status.
4643 (if (equal ret -1)
4644 (keyboard-quit)
4645 ret))))
4647 (defun tramp-local-call-process
4648 (program &optional infile destination display &rest args)
4649 "Calls `call-process' on the local host.
4650 This is needed because for some Emacs flavors Tramp has
4651 defadviced `call-process' to behave like `process-file'. The
4652 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4653 (let ((default-directory
4654 (if (file-remote-p default-directory)
4655 (tramp-compat-temporary-file-directory)
4656 default-directory)))
4657 (if (executable-find program)
4658 (apply 'call-process program infile destination display args)
4659 1)))
4661 (defun tramp-handle-call-process-region
4662 (start end program &optional delete buffer display &rest args)
4663 "Like `call-process-region' for Tramp files."
4664 (let ((tmpfile (tramp-compat-make-temp-file "")))
4665 (write-region start end tmpfile)
4666 (when delete (delete-region start end))
4667 (unwind-protect
4668 (apply 'call-process program tmpfile buffer display args)
4669 (tramp-compat-delete-file tmpfile 'force))))
4671 (defun tramp-handle-shell-command
4672 (command &optional output-buffer error-buffer)
4673 "Like `shell-command' for Tramp files."
4674 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4675 ;; We cannot use `shell-file-name' and `shell-command-switch',
4676 ;; they are variables of the local host.
4677 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
4678 current-buffer-p
4679 (output-buffer
4680 (cond
4681 ((bufferp output-buffer) output-buffer)
4682 ((stringp output-buffer) (get-buffer-create output-buffer))
4683 (output-buffer
4684 (setq current-buffer-p t)
4685 (current-buffer))
4686 (t (get-buffer-create
4687 (if asynchronous
4688 "*Async Shell Command*"
4689 "*Shell Command Output*")))))
4690 (error-buffer
4691 (cond
4692 ((bufferp error-buffer) error-buffer)
4693 ((stringp error-buffer) (get-buffer-create error-buffer))))
4694 (buffer
4695 (if (and (not asynchronous) error-buffer)
4696 (with-parsed-tramp-file-name default-directory nil
4697 (list output-buffer (tramp-make-tramp-temp-file v)))
4698 output-buffer))
4699 (p (get-buffer-process output-buffer)))
4701 ;; Check whether there is another process running. Tramp does not
4702 ;; support 2 (asynchronous) processes in parallel.
4703 (when p
4704 (if (yes-or-no-p "A command is running. Kill it? ")
4705 (condition-case nil
4706 (kill-process p)
4707 (error nil))
4708 (error "Shell command in progress")))
4710 (if current-buffer-p
4711 (progn
4712 (barf-if-buffer-read-only)
4713 (push-mark nil t))
4714 (with-current-buffer output-buffer
4715 (setq buffer-read-only nil)
4716 (erase-buffer)))
4718 (if (and (not current-buffer-p) (integerp asynchronous))
4719 (prog1
4720 ;; Run the process.
4721 (apply 'start-file-process "*Async Shell*" buffer args)
4722 ;; Display output.
4723 (pop-to-buffer output-buffer)
4724 (setq mode-line-process '(":%s"))
4725 (require 'shell) (shell-mode))
4727 (prog1
4728 ;; Run the process.
4729 (apply 'process-file (car args) nil buffer nil (cdr args))
4730 ;; Insert error messages if they were separated.
4731 (when (listp buffer)
4732 (with-current-buffer error-buffer
4733 (insert-file-contents (cadr buffer)))
4734 (tramp-compat-delete-file (cadr buffer) 'force))
4735 (if current-buffer-p
4736 ;; This is like exchange-point-and-mark, but doesn't
4737 ;; activate the mark. It is cleaner to avoid activation,
4738 ;; even though the command loop would deactivate the mark
4739 ;; because we inserted text.
4740 (goto-char (prog1 (mark t)
4741 (set-marker (mark-marker) (point)
4742 (current-buffer))))
4743 ;; There's some output, display it.
4744 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4745 (if (functionp 'display-message-or-buffer)
4746 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
4747 (pop-to-buffer output-buffer))))))))
4749 ;; File Editing.
4751 (defvar tramp-handle-file-local-copy-hook nil
4752 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4754 (defun tramp-handle-file-local-copy (filename)
4755 "Like `file-local-copy' for Tramp files."
4757 (with-parsed-tramp-file-name filename nil
4758 (unless (file-exists-p filename)
4759 (tramp-error
4760 v 'file-error
4761 "Cannot make local copy of non-existing file `%s'" filename))
4763 (let* ((size (nth 7 (file-attributes filename)))
4764 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
4765 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
4766 (tmpfile (tramp-compat-make-temp-file filename)))
4768 (condition-case err
4769 (cond
4770 ;; `copy-file' handles direct copy and out-of-band methods.
4771 ((or (tramp-local-host-p v)
4772 (tramp-method-out-of-band-p v size))
4773 (copy-file filename tmpfile t t))
4775 ;; Use inline encoding for file transfer.
4776 (rem-enc
4777 (save-excursion
4778 (with-progress-reporter
4779 v 3 (format "Encoding remote file %s" filename)
4780 (tramp-barf-unless-okay
4781 v (format rem-enc (tramp-shell-quote-argument localname))
4782 "Encoding remote file failed"))
4784 (if (functionp loc-dec)
4785 ;; If local decoding is a function, we call it. We
4786 ;; must disable multibyte, because
4787 ;; `uudecode-decode-region' doesn't handle it
4788 ;; correctly.
4789 (with-temp-buffer
4790 (set-buffer-multibyte nil)
4791 (insert-buffer-substring (tramp-get-buffer v))
4792 (with-progress-reporter
4793 v 3 (format "Decoding remote file %s with function %s"
4794 filename loc-dec)
4795 (funcall loc-dec (point-min) (point-max))
4796 ;; Unset `file-name-handler-alist'. Otherwise,
4797 ;; epa-file gets confused.
4798 (let (file-name-handler-alist
4799 (coding-system-for-write 'binary))
4800 (write-region (point-min) (point-max) tmpfile))))
4802 ;; If tramp-decoding-function is not defined for this
4803 ;; method, we invoke tramp-decoding-command instead.
4804 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4805 ;; Unset `file-name-handler-alist'. Otherwise,
4806 ;; epa-file gets confused.
4807 (let (file-name-handler-alist
4808 (coding-system-for-write 'binary))
4809 (write-region (point-min) (point-max) tmpfile2))
4810 (with-progress-reporter
4811 v 3 (format "Decoding remote file %s with command %s"
4812 filename loc-dec)
4813 (unwind-protect
4814 (tramp-call-local-coding-command
4815 loc-dec tmpfile2 tmpfile)
4816 (tramp-compat-delete-file tmpfile2 'force)))))
4818 ;; Set proper permissions.
4819 (set-file-modes tmpfile (tramp-default-file-modes filename))
4820 ;; Set local user ownership.
4821 (tramp-set-file-uid-gid tmpfile)))
4823 ;; Oops, I don't know what to do.
4824 (t (tramp-error
4825 v 'file-error "Wrong method specification for `%s'" method)))
4827 ;; Error handling.
4828 ((error quit)
4829 (tramp-compat-delete-file tmpfile 'force)
4830 (signal (car err) (cdr err))))
4832 (run-hooks 'tramp-handle-file-local-copy-hook)
4833 tmpfile)))
4835 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4836 "Like `file-remote-p' for Tramp files."
4837 (let ((tramp-verbose 3))
4838 (when (tramp-tramp-file-p filename)
4839 (let* ((v (tramp-dissect-file-name filename))
4840 (p (tramp-get-connection-process v))
4841 (c (and p (processp p) (memq (process-status p) '(run open)))))
4842 ;; We expand the file name only, if there is already a connection.
4843 (with-parsed-tramp-file-name
4844 (if c (expand-file-name filename) filename) nil
4845 (and (or (not connected) c)
4846 (cond
4847 ((eq identification 'method) method)
4848 ((eq identification 'user) user)
4849 ((eq identification 'host) host)
4850 ((eq identification 'localname) localname)
4851 (t (tramp-make-tramp-file-name method user host "")))))))))
4853 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4854 "Like `find-operation-coding-system' for Tramp filenames.
4855 Tramp's `insert-file-contents' and `write-region' work over
4856 temporary file names. If `file-coding-system-alist' contains an
4857 expression, which matches more than the file name suffix, the
4858 coding system might not be determined. This function repairs it."
4859 (let (result)
4860 (dolist (elt file-coding-system-alist result)
4861 (when (and (consp elt) (string-match (car elt) filename))
4862 ;; We found a matching entry in `file-coding-system-alist'.
4863 ;; So we add a similar entry, but with the temporary file name
4864 ;; as regexp.
4865 (add-to-list
4866 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4868 (defun tramp-handle-insert-file-contents
4869 (filename &optional visit beg end replace)
4870 "Like `insert-file-contents' for Tramp files."
4871 (barf-if-buffer-read-only)
4872 (setq filename (expand-file-name filename))
4873 (let (result local-copy remote-copy)
4874 (with-parsed-tramp-file-name filename nil
4875 (unwind-protect
4876 (if (not (file-exists-p filename))
4877 ;; We don't raise a Tramp error, because it might be
4878 ;; suppressed, like in `find-file-noselect-1'.
4879 (signal 'file-error
4880 (list "File not found on remote host" filename))
4882 (if (and (tramp-local-host-p v)
4883 (let (file-name-handler-alist)
4884 (file-readable-p localname)))
4885 ;; Short track: if we are on the local host, we can
4886 ;; run directly.
4887 (setq result
4888 (tramp-run-real-handler
4889 'insert-file-contents
4890 (list localname visit beg end replace)))
4892 ;; When we shall insert only a part of the file, we copy
4893 ;; this part.
4894 (when (or beg end)
4895 (setq remote-copy (tramp-make-tramp-temp-file v))
4896 (tramp-send-command
4898 (cond
4899 ((and beg end)
4900 (format "tail -c +%d %s | head -c +%d >%s"
4901 (1+ beg) (tramp-shell-quote-argument localname)
4902 (- end beg) remote-copy))
4903 (beg
4904 (format "tail -c +%d %s >%s"
4905 (1+ beg) (tramp-shell-quote-argument localname)
4906 remote-copy))
4907 (end
4908 (format "head -c +%d %s >%s"
4909 (1+ end) (tramp-shell-quote-argument localname)
4910 remote-copy)))))
4912 ;; `insert-file-contents-literally' takes care to avoid
4913 ;; calling jka-compr. By let-binding
4914 ;; `inhibit-file-name-operation', we propagate that care
4915 ;; to the `file-local-copy' operation.
4916 (setq local-copy
4917 (let ((inhibit-file-name-operation
4918 (when (eq inhibit-file-name-operation
4919 'insert-file-contents)
4920 'file-local-copy)))
4921 (cond
4922 ((stringp remote-copy)
4923 (file-local-copy
4924 (tramp-make-tramp-file-name
4925 method user host remote-copy)))
4926 ((stringp tramp-temp-buffer-file-name)
4927 (copy-file filename tramp-temp-buffer-file-name 'ok)
4928 tramp-temp-buffer-file-name)
4929 (t (file-local-copy filename)))))
4931 ;; When the file is not readable for the owner, it
4932 ;; cannot be inserted, even it is redable for the group
4933 ;; or for everybody.
4934 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4936 (when (and (null remote-copy)
4937 (tramp-get-method-parameter
4938 method 'tramp-copy-keep-tmpfile))
4939 ;; We keep the local file for performance reasons,
4940 ;; useful for "rsync".
4941 (setq tramp-temp-buffer-file-name local-copy)
4942 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4944 (with-progress-reporter
4945 v 3 (format "Inserting local temp file `%s'" local-copy)
4946 ;; We must ensure that `file-coding-system-alist'
4947 ;; matches `local-copy'.
4948 (let ((file-coding-system-alist
4949 (tramp-find-file-name-coding-system-alist
4950 filename local-copy)))
4951 (setq result
4952 (insert-file-contents
4953 local-copy nil nil nil replace))))))
4955 ;; Save exit.
4956 (progn
4957 (when visit
4958 (setq buffer-file-name filename)
4959 (setq buffer-read-only (not (file-writable-p filename)))
4960 (set-visited-file-modtime)
4961 (set-buffer-modified-p nil))
4962 (when (and (stringp local-copy)
4963 (or remote-copy (null tramp-temp-buffer-file-name)))
4964 (tramp-compat-delete-file local-copy 'force))
4965 (when (stringp remote-copy)
4966 (tramp-compat-delete-file
4967 (tramp-make-tramp-file-name method user host remote-copy)
4968 'force)))))
4970 ;; Result.
4971 (list (expand-file-name filename)
4972 (cadr result))))
4974 ;; This is needed for XEmacs only. Code stolen from files.el.
4975 (defun tramp-handle-insert-file-contents-literally
4976 (filename &optional visit beg end replace)
4977 "Like `insert-file-contents-literally' for Tramp files."
4978 (let ((format-alist nil)
4979 (after-insert-file-functions nil)
4980 (coding-system-for-read 'no-conversion)
4981 (coding-system-for-write 'no-conversion)
4982 (find-buffer-file-type-function
4983 (if (fboundp 'find-buffer-file-type)
4984 (symbol-function 'find-buffer-file-type)
4985 nil))
4986 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4987 (inhibit-file-name-operation 'insert-file-contents))
4988 (unwind-protect
4989 (progn
4990 (fset 'find-buffer-file-type (lambda (filename) t))
4991 (insert-file-contents filename visit beg end replace))
4992 ;; Save exit.
4993 (if find-buffer-file-type-function
4994 (fset 'find-buffer-file-type find-buffer-file-type-function)
4995 (fmakunbound 'find-buffer-file-type)))))
4997 (defun tramp-handle-find-backup-file-name (filename)
4998 "Like `find-backup-file-name' for Tramp files."
4999 (with-parsed-tramp-file-name filename nil
5000 ;; We set both variables. It doesn't matter whether it is
5001 ;; Emacs or XEmacs.
5002 (let ((backup-directory-alist
5003 ;; Emacs case.
5004 (when (boundp 'backup-directory-alist)
5005 (if (symbol-value 'tramp-backup-directory-alist)
5006 (mapcar
5007 (lambda (x)
5008 (cons
5009 (car x)
5010 (if (and (stringp (cdr x))
5011 (file-name-absolute-p (cdr x))
5012 (not (tramp-file-name-p (cdr x))))
5013 (tramp-make-tramp-file-name method user host (cdr x))
5014 (cdr x))))
5015 (symbol-value 'tramp-backup-directory-alist))
5016 (symbol-value 'backup-directory-alist))))
5018 (bkup-backup-directory-info
5019 ;; XEmacs case.
5020 (when (boundp 'bkup-backup-directory-info)
5021 (if (symbol-value 'tramp-bkup-backup-directory-info)
5022 (mapcar
5023 (lambda (x)
5024 (nconc
5025 (list (car x))
5026 (list
5027 (if (and (stringp (car (cdr x)))
5028 (file-name-absolute-p (car (cdr x)))
5029 (not (tramp-file-name-p (car (cdr x)))))
5030 (tramp-make-tramp-file-name
5031 method user host (car (cdr x)))
5032 (car (cdr x))))
5033 (cdr (cdr x))))
5034 (symbol-value 'tramp-bkup-backup-directory-info))
5035 (symbol-value 'bkup-backup-directory-info)))))
5037 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
5039 (defun tramp-handle-make-auto-save-file-name ()
5040 "Like `make-auto-save-file-name' for Tramp files.
5041 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
5042 (let ((tramp-auto-save-directory tramp-auto-save-directory)
5043 (buffer-file-name
5044 (tramp-subst-strs-in-string
5045 '(("_" . "|")
5046 ("/" . "_a")
5047 (":" . "_b")
5048 ("|" . "__")
5049 ("[" . "_l")
5050 ("]" . "_r"))
5051 (buffer-file-name))))
5052 ;; File name must be unique. This is ensured with Emacs 22 (see
5053 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
5054 ;; all other cases we must do it ourselves.
5055 (when (boundp 'auto-save-file-name-transforms)
5056 (mapc
5057 (lambda (x)
5058 (when (and (string-match (car x) buffer-file-name)
5059 (not (car (cddr x))))
5060 (setq tramp-auto-save-directory
5061 (or tramp-auto-save-directory
5062 (tramp-compat-temporary-file-directory)))))
5063 (symbol-value 'auto-save-file-name-transforms)))
5064 ;; Create directory.
5065 (when tramp-auto-save-directory
5066 (setq buffer-file-name
5067 (expand-file-name buffer-file-name tramp-auto-save-directory))
5068 (unless (file-exists-p tramp-auto-save-directory)
5069 (make-directory tramp-auto-save-directory t)))
5070 ;; Run plain `make-auto-save-file-name'. There might be an advice when
5071 ;; it is not a magic file name operation (since Emacs 22).
5072 ;; We must deactivate it temporarily.
5073 (if (not (ad-is-active 'make-auto-save-file-name))
5074 (tramp-run-real-handler 'make-auto-save-file-name nil)
5075 ;; else
5076 (ad-deactivate 'make-auto-save-file-name)
5077 (prog1
5078 (tramp-run-real-handler 'make-auto-save-file-name nil)
5079 (ad-activate 'make-auto-save-file-name)))))
5081 (defvar tramp-handle-write-region-hook nil
5082 "Normal hook to be run at the end of `tramp-handle-write-region'.")
5084 ;; CCC grok LOCKNAME
5085 (defun tramp-handle-write-region
5086 (start end filename &optional append visit lockname confirm)
5087 "Like `write-region' for Tramp files."
5088 (setq filename (expand-file-name filename))
5089 (with-parsed-tramp-file-name filename nil
5090 ;; Following part commented out because we don't know what to do about
5091 ;; file locking, and it does not appear to be a problem to ignore it.
5092 ;; Ange-ftp ignores it, too.
5093 ;; (when (and lockname (stringp lockname))
5094 ;; (setq lockname (expand-file-name lockname)))
5095 ;; (unless (or (eq lockname nil)
5096 ;; (string= lockname filename))
5097 ;; (error
5098 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
5100 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
5101 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
5102 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
5103 (tramp-error v 'file-error "File not overwritten")))
5105 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
5106 (tramp-get-remote-uid v 'integer)))
5107 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
5108 (tramp-get-remote-gid v 'integer))))
5110 (if (and (tramp-local-host-p v)
5111 ;; `file-writable-p' calls `file-expand-file-name'. We
5112 ;; cannot use `tramp-run-real-handler' therefore.
5113 (let (file-name-handler-alist)
5114 (and
5115 (file-writable-p (file-name-directory localname))
5116 (or (file-directory-p localname)
5117 (file-writable-p localname)))))
5118 ;; Short track: if we are on the local host, we can run directly.
5119 (tramp-run-real-handler
5120 'write-region
5121 (list start end localname append 'no-message lockname confirm))
5123 (let ((modes (save-excursion (tramp-default-file-modes filename)))
5124 ;; We use this to save the value of
5125 ;; `last-coding-system-used' after writing the tmp
5126 ;; file. At the end of the function, we set
5127 ;; `last-coding-system-used' to this saved value. This
5128 ;; way, any intermediary coding systems used while
5129 ;; talking to the remote shell or suchlike won't hose
5130 ;; this variable. This approach was snarfed from
5131 ;; ange-ftp.el.
5132 coding-system-used
5133 ;; Write region into a tmp file. This isn't really
5134 ;; needed if we use an encoding function, but currently
5135 ;; we use it always because this makes the logic
5136 ;; simpler.
5137 (tmpfile (or tramp-temp-buffer-file-name
5138 (tramp-compat-make-temp-file filename))))
5140 ;; If `append' is non-nil, we copy the file locally, and let
5141 ;; the native `write-region' implementation do the job.
5142 (when append (copy-file filename tmpfile 'ok))
5144 ;; We say `no-message' here because we don't want the
5145 ;; visited file modtime data to be clobbered from the temp
5146 ;; file. We call `set-visited-file-modtime' ourselves later
5147 ;; on. We must ensure that `file-coding-system-alist'
5148 ;; matches `tmpfile'.
5149 (let (file-name-handler-alist
5150 (file-coding-system-alist
5151 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5152 (condition-case err
5153 (tramp-run-real-handler
5154 'write-region
5155 (list start end tmpfile append 'no-message lockname confirm))
5156 ((error quit)
5157 (setq tramp-temp-buffer-file-name nil)
5158 (tramp-compat-delete-file tmpfile 'force)
5159 (signal (car err) (cdr err))))
5161 ;; Now, `last-coding-system-used' has the right value. Remember it.
5162 (when (boundp 'last-coding-system-used)
5163 (setq coding-system-used
5164 (symbol-value 'last-coding-system-used))))
5166 ;; The permissions of the temporary file should be set. If
5167 ;; filename does not exist (eq modes nil) it has been
5168 ;; renamed to the backup file. This case `save-buffer'
5169 ;; handles permissions.
5170 ;; Ensure, that it is still readable.
5171 (when modes
5172 (set-file-modes
5173 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
5175 ;; This is a bit lengthy due to the different methods
5176 ;; possible for file transfer. First, we check whether the
5177 ;; method uses an rcp program. If so, we call it.
5178 ;; Otherwise, both encoding and decoding command must be
5179 ;; specified. However, if the method _also_ specifies an
5180 ;; encoding function, then that is used for encoding the
5181 ;; contents of the tmp file.
5182 (let* ((size (nth 7 (file-attributes tmpfile)))
5183 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
5184 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
5185 (cond
5186 ;; `copy-file' handles direct copy and out-of-band methods.
5187 ((or (tramp-local-host-p v)
5188 (tramp-method-out-of-band-p v size))
5189 (if (and (not (stringp start))
5190 (= (or end (point-max)) (point-max))
5191 (= (or start (point-min)) (point-min))
5192 (tramp-get-method-parameter
5193 method 'tramp-copy-keep-tmpfile))
5194 (progn
5195 (setq tramp-temp-buffer-file-name tmpfile)
5196 (condition-case err
5197 ;; We keep the local file for performance
5198 ;; reasons, useful for "rsync".
5199 (copy-file tmpfile filename t)
5200 ((error quit)
5201 (setq tramp-temp-buffer-file-name nil)
5202 (tramp-compat-delete-file tmpfile 'force)
5203 (signal (car err) (cdr err)))))
5204 (setq tramp-temp-buffer-file-name nil)
5205 ;; Don't rename, in order to keep context in SELinux.
5206 (unwind-protect
5207 (copy-file tmpfile filename t)
5208 (tramp-compat-delete-file tmpfile 'force))))
5210 ;; Use inline file transfer.
5211 (rem-dec
5212 ;; Encode tmpfile.
5213 (unwind-protect
5214 (with-temp-buffer
5215 (set-buffer-multibyte nil)
5216 ;; Use encoding function or command.
5217 (if (functionp loc-enc)
5218 (with-progress-reporter
5219 v 3 (format "Encoding region using function `%s'"
5220 loc-enc)
5221 (let ((coding-system-for-read 'binary))
5222 (insert-file-contents-literally tmpfile))
5223 ;; The following `let' is a workaround for the
5224 ;; base64.el that comes with pgnus-0.84. If
5225 ;; both of the following conditions are
5226 ;; satisfied, it tries to write to a local
5227 ;; file in default-directory, but at this
5228 ;; point, default-directory is remote.
5229 ;; (`call-process-region' can't write to
5230 ;; remote files, it seems.) The file in
5231 ;; question is a tmp file anyway.
5232 (let ((default-directory
5233 (tramp-compat-temporary-file-directory)))
5234 (funcall loc-enc (point-min) (point-max))))
5236 (with-progress-reporter
5237 v 3 (format "Encoding region using command `%s'"
5238 loc-enc)
5239 (unless (zerop (tramp-call-local-coding-command
5240 loc-enc tmpfile t))
5241 (tramp-error
5242 v 'file-error
5243 (concat "Cannot write to `%s', "
5244 "local encoding command `%s' failed")
5245 filename loc-enc))))
5247 ;; Send buffer into remote decoding command which
5248 ;; writes to remote file. Because this happens on
5249 ;; the remote host, we cannot use the function.
5250 (with-progress-reporter
5252 (format "Decoding region into remote file %s" filename)
5253 (goto-char (point-max))
5254 (unless (bolp) (newline))
5255 (tramp-send-command
5257 (format
5258 (concat rem-dec " <<'EOF'\n%sEOF")
5259 (tramp-shell-quote-argument localname)
5260 (buffer-string)))
5261 (tramp-barf-unless-okay
5262 v nil
5263 "Couldn't write region to `%s', decode using `%s' failed"
5264 filename rem-dec)
5265 ;; When `file-precious-flag' is set, the region is
5266 ;; written to a temporary file. Check that the
5267 ;; checksum is equal to that from the local tmpfile.
5268 (when file-precious-flag
5269 (erase-buffer)
5270 (and
5271 ;; cksum runs locally, if possible.
5272 (zerop (tramp-local-call-process "cksum" tmpfile t))
5273 ;; cksum runs remotely.
5274 (zerop
5275 (tramp-send-command-and-check
5277 (format
5278 "cksum <%s"
5279 (tramp-shell-quote-argument localname))))
5280 ;; ... they are different.
5281 (not
5282 (string-equal
5283 (buffer-string)
5284 (with-current-buffer (tramp-get-buffer v)
5285 (buffer-string))))
5286 (tramp-error
5287 v 'file-error
5288 (concat "Couldn't write region to `%s',"
5289 " decode using `%s' failed")
5290 filename rem-dec)))))
5292 ;; Save exit.
5293 (tramp-compat-delete-file tmpfile 'force)))
5295 ;; That's not expected.
5297 (tramp-error
5298 v 'file-error
5299 (concat "Method `%s' should specify both encoding and "
5300 "decoding command or an rcp program")
5301 method))))
5303 ;; Make `last-coding-system-used' have the right value.
5304 (when coding-system-used
5305 (set 'last-coding-system-used coding-system-used))))
5307 (tramp-flush-file-property v (file-name-directory localname))
5308 (tramp-flush-file-property v localname)
5310 ;; We must protect `last-coding-system-used', now we have set it
5311 ;; to its correct value.
5312 (let (last-coding-system-used (need-chown t))
5313 ;; Set file modification time.
5314 (when (or (eq visit t) (stringp visit))
5315 (let ((file-attr (file-attributes filename)))
5316 (set-visited-file-modtime
5317 ;; We must pass modtime explicitely, because filename can
5318 ;; be different from (buffer-file-name), f.e. if
5319 ;; `file-precious-flag' is set.
5320 (nth 5 file-attr))
5321 (when (and (eq (nth 2 file-attr) uid)
5322 (eq (nth 3 file-attr) gid))
5323 (setq need-chown nil))))
5325 ;; Set the ownership.
5326 (when need-chown
5327 (tramp-set-file-uid-gid filename uid gid))
5328 (when (or (eq visit t) (null visit) (stringp visit))
5329 (tramp-message v 0 "Wrote %s" filename))
5330 (run-hooks 'tramp-handle-write-region-hook)))))
5332 (defvar tramp-vc-registered-file-names nil
5333 "List used to collect file names, which are checked during `vc-registered'.")
5335 ;; VC backends check for the existence of various different special
5336 ;; files. This is very time consuming, because every single check
5337 ;; requires a remote command (the file cache must be invalidated).
5338 ;; Therefore, we apply a kind of optimization. We install the file
5339 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5340 ;; remembers all file names for which `file-exists-p' or
5341 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5342 ;; is performed. Afterwards, a script is applied for all collected
5343 ;; file names, using just one remote command. The result of this
5344 ;; script is used to fill the file cache with actual values. Now we
5345 ;; can reset the file name handlers, and we make a second run of
5346 ;; `vc-registered', which returns the expected result without sending
5347 ;; any other remote command.
5348 (defun tramp-handle-vc-registered (file)
5349 "Like `vc-registered' for Tramp files."
5350 (with-temp-message ""
5351 (with-parsed-tramp-file-name file nil
5352 (with-progress-reporter
5353 v 3 (format "Checking `vc-registered' for %s" file)
5355 ;; There could be new files, created by the vc backend. We
5356 ;; cannot reuse the old cache entries, therefore.
5357 (let (tramp-vc-registered-file-names
5358 (tramp-cache-inhibit-cache (current-time))
5359 (file-name-handler-alist
5360 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5362 ;; Here we collect only file names, which need an operation.
5363 (tramp-run-real-handler 'vc-registered (list file))
5364 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5366 ;; Send just one command, in order to fill the cache.
5367 (when tramp-vc-registered-file-names
5368 (tramp-maybe-send-script
5370 (format tramp-vc-registered-read-file-names
5371 (tramp-get-file-exists-command v)
5372 (format "%s -r" (tramp-get-test-command v)))
5373 "tramp_vc_registered_read_file_names")
5375 (dolist
5376 (elt
5377 (tramp-send-command-and-read
5379 (format
5380 "tramp_vc_registered_read_file_names %s"
5381 (mapconcat 'tramp-shell-quote-argument
5382 tramp-vc-registered-file-names
5383 " "))))
5385 (tramp-set-file-property
5386 v (car elt) (cadr elt) (cadr (cdr elt))))))
5388 ;; Second run. Now all `file-exists-p' or `file-readable-p'
5389 ;; calls shall be answered from the file cache. We unset
5390 ;; `process-file-side-effects' in order to keep the cache when
5391 ;; `process-file' calls appear.
5392 (let (process-file-side-effects)
5393 (tramp-run-real-handler 'vc-registered (list file)))))))
5395 ;;;###autoload
5396 (progn (defun tramp-run-real-handler (operation args)
5397 "Invoke normal file name handler for OPERATION.
5398 First arg specifies the OPERATION, second arg is a list of arguments to
5399 pass to the OPERATION."
5400 (let* ((inhibit-file-name-handlers
5401 `(tramp-file-name-handler
5402 tramp-vc-file-name-handler
5403 tramp-completion-file-name-handler
5404 cygwin-mount-name-hook-function
5405 cygwin-mount-map-drive-hook-function
5407 ,(and (eq inhibit-file-name-operation operation)
5408 inhibit-file-name-handlers)))
5409 (inhibit-file-name-operation operation))
5410 (apply operation args))))
5412 ;;;###autoload
5413 (progn (defun tramp-completion-run-real-handler (operation args)
5414 "Invoke `tramp-file-name-handler' for OPERATION.
5415 First arg specifies the OPERATION, second arg is a list of arguments to
5416 pass to the OPERATION."
5417 (let* ((inhibit-file-name-handlers
5418 `(tramp-completion-file-name-handler
5419 cygwin-mount-name-hook-function
5420 cygwin-mount-map-drive-hook-function
5422 ,(and (eq inhibit-file-name-operation operation)
5423 inhibit-file-name-handlers)))
5424 (inhibit-file-name-operation operation))
5425 (apply operation args))))
5427 ;; We handle here all file primitives. Most of them have the file
5428 ;; name as first parameter; nevertheless we check for them explicitly
5429 ;; in order to be signaled if a new primitive appears. This
5430 ;; scenario is needed because there isn't a way to decide by
5431 ;; syntactical means whether a foreign method must be called. It would
5432 ;; ease the life if `file-name-handler-alist' would support a decision
5433 ;; function as well but regexp only.
5434 (defun tramp-file-name-for-operation (operation &rest args)
5435 "Return file name related to OPERATION file primitive.
5436 ARGS are the arguments OPERATION has been called with."
5437 (cond
5438 ;; FILE resp DIRECTORY.
5439 ((member operation
5440 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5441 'delete-file 'diff-latest-backup-file 'directory-file-name
5442 'directory-files 'directory-files-and-attributes
5443 'dired-compress-file 'dired-uncache
5444 'file-accessible-directory-p 'file-attributes
5445 'file-directory-p 'file-executable-p 'file-exists-p
5446 'file-local-copy 'file-remote-p 'file-modes
5447 'file-name-as-directory 'file-name-directory
5448 'file-name-nondirectory 'file-name-sans-versions
5449 'file-ownership-preserved-p 'file-readable-p
5450 'file-regular-p 'file-symlink-p 'file-truename
5451 'file-writable-p 'find-backup-file-name 'find-file-noselect
5452 'get-file-buffer 'insert-directory 'insert-file-contents
5453 'load 'make-directory 'make-directory-internal
5454 'set-file-modes 'substitute-in-file-name
5455 'unhandled-file-name-directory 'vc-registered
5456 ;; Emacs 22+ only.
5457 'set-file-times
5458 ;; Emacs 24+ only.
5459 'file-selinux-context 'set-file-selinux-context
5460 ;; XEmacs only.
5461 'abbreviate-file-name 'create-file-buffer
5462 'dired-file-modtime 'dired-make-compressed-filename
5463 'dired-recursive-delete-directory 'dired-set-file-modtime
5464 'dired-shell-unhandle-file-name 'dired-uucode-file
5465 'insert-file-contents-literally 'make-temp-name 'recover-file
5466 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5467 (if (file-name-absolute-p (nth 0 args))
5468 (nth 0 args)
5469 (expand-file-name (nth 0 args))))
5470 ;; FILE DIRECTORY resp FILE1 FILE2.
5471 ((member operation
5472 (list 'add-name-to-file 'copy-file 'expand-file-name
5473 'file-name-all-completions 'file-name-completion
5474 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5475 ;; Emacs 23+ only.
5476 'copy-directory
5477 ;; XEmacs only.
5478 'dired-make-relative-symlink
5479 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5480 (save-match-data
5481 (cond
5482 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5483 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5484 (t (buffer-file-name (current-buffer))))))
5485 ;; START END FILE.
5486 ((eq operation 'write-region)
5487 (nth 2 args))
5488 ;; BUFFER.
5489 ((member operation
5490 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5491 ;; Emacs 22+ only.
5492 'make-auto-save-file-name
5493 ;; XEmacs only.
5494 'backup-buffer))
5495 (buffer-file-name
5496 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5497 ;; COMMAND.
5498 ((member operation
5499 (list ;; not in Emacs 23+.
5500 'dired-call-process
5501 ;; Emacs only.
5502 'shell-command
5503 ;; Emacs 22+ only.
5504 'process-file
5505 ;; Emacs 23+ only.
5506 'start-file-process
5507 ;; XEmacs only.
5508 'dired-print-file 'dired-shell-call-process
5509 ;; nowhere yet.
5510 'executable-find 'start-process 'call-process))
5511 default-directory)
5512 ;; Unknown file primitive.
5513 (t (error "unknown file I/O primitive: %s" operation))))
5515 (defun tramp-find-foreign-file-name-handler (filename)
5516 "Return foreign file name handler if exists."
5517 (when (tramp-tramp-file-p filename)
5518 (let ((v (tramp-dissect-file-name filename t))
5519 (handler tramp-foreign-file-name-handler-alist)
5520 elt res)
5521 ;; When we are not fully sure that filename completion is safe,
5522 ;; we should not return a handler.
5523 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5524 (and (tramp-file-name-host v)
5525 (not (member (tramp-file-name-host v)
5526 (mapcar 'car tramp-methods))))
5527 (not (tramp-completion-mode-p)))
5528 (while handler
5529 (setq elt (car handler)
5530 handler (cdr handler))
5531 (when (funcall (car elt) filename)
5532 (setq handler nil
5533 res (cdr elt))))
5534 res))))
5536 ;; Main function.
5537 ;;;###autoload
5538 (defun tramp-file-name-handler (operation &rest args)
5539 "Invoke Tramp file name handler.
5540 Falls back to normal file name handler if no Tramp file name handler exists."
5541 (if tramp-mode
5542 (save-match-data
5543 (let* ((filename
5544 (tramp-replace-environment-variables
5545 (apply 'tramp-file-name-for-operation operation args)))
5546 (completion (tramp-completion-mode-p))
5547 (foreign (tramp-find-foreign-file-name-handler filename)))
5548 (with-parsed-tramp-file-name filename nil
5549 ;; Call the backend function.
5550 (if foreign
5551 (condition-case err
5552 (apply foreign operation args)
5553 (error
5554 (cond
5555 ;; When we are in completion mode, some failed
5556 ;; operations shall return at least a default
5557 ;; value in order to give the user a chance to
5558 ;; correct the file name in the minibuffer.
5559 ((and completion (zerop (length localname))
5560 (memq operation '(file-exists-p file-directory-p)))
5562 ((and completion (zerop (length localname))
5563 (memq operation
5564 '(expand-file-name file-name-as-directory)))
5565 filename)
5566 ;; Propagate the error.
5567 (t (signal (car err) (cdr err))))))
5568 ;; Nothing to do for us.
5569 (tramp-run-real-handler operation args)))))
5571 ;; When `tramp-mode' is not enabled, we don't do anything.
5572 (tramp-run-real-handler operation args)))
5574 ;; In Emacs, there is some concurrency due to timers. If a timer
5575 ;; interrupts Tramp and wishes to use the same connection buffer as
5576 ;; the "main" Emacs, then garbage might occur in the connection
5577 ;; buffer. Therefore, we need to make sure that a timer does not use
5578 ;; the same connection buffer as the "main" Emacs. We implement a
5579 ;; cheap global lock, instead of locking each connection buffer
5580 ;; separately. The global lock is based on two variables,
5581 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5582 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5583 ;; processing of a single file operation, so we need to allow
5584 ;; recursive calls. That's where the `tramp-locker' variable comes in
5585 ;; -- it is let-bound to t during the execution of the current
5586 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5587 ;; then we should just proceed because we have been called
5588 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5589 ;; interrupting the "main" Emacs, and then we signal an error.
5591 (defvar tramp-locked nil
5592 "If non-nil, then Tramp is currently busy.
5593 Together with `tramp-locker', this implements a locking mechanism
5594 preventing reentrant calls of Tramp.")
5596 (defvar tramp-locker nil
5597 "If non-nil, then a caller has locked Tramp.
5598 Together with `tramp-locked', this implements a locking mechanism
5599 preventing reentrant calls of Tramp.")
5601 (defun tramp-sh-file-name-handler (operation &rest args)
5602 "Invoke remote-shell Tramp file name handler.
5603 Fall back to normal file name handler if no Tramp handler exists."
5604 (when (and tramp-locked (not tramp-locker))
5605 (setq tramp-locked nil)
5606 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5607 (let ((tl tramp-locked))
5608 (unwind-protect
5609 (progn
5610 (setq tramp-locked t)
5611 (let ((tramp-locker t))
5612 (save-match-data
5613 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5614 (if fn
5615 (apply (cdr fn) args)
5616 (tramp-run-real-handler operation args))))))
5617 (setq tramp-locked tl))))
5619 (defun tramp-vc-file-name-handler (operation &rest args)
5620 "Invoke special file name handler, which collects files to be handled."
5621 (save-match-data
5622 (let ((filename
5623 (tramp-replace-environment-variables
5624 (apply 'tramp-file-name-for-operation operation args)))
5625 (fn (assoc operation tramp-file-name-handler-alist)))
5626 (with-parsed-tramp-file-name filename nil
5627 (cond
5628 ;; That's what we want: file names, for which checks are
5629 ;; applied. We assume, that VC uses only `file-exists-p' and
5630 ;; `file-readable-p' checks; otherwise we must extend the
5631 ;; list. We do not perform any action, but return nil, in
5632 ;; order to keep `vc-registered' running.
5633 ((and fn (memq operation '(file-exists-p file-readable-p)))
5634 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5635 nil)
5636 ;; Tramp file name handlers like `expand-file-name'. They
5637 ;; must still work.
5639 (save-match-data (apply (cdr fn) args)))
5640 ;; Default file name handlers, we don't care.
5641 (t (tramp-run-real-handler operation args)))))))
5643 ;;;###autoload
5644 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5645 "Invoke Tramp file name completion handler.
5646 Falls back to normal file name handler if no Tramp file name handler exists."
5647 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5648 ;; would otherwise use backslash.
5649 (let ((directory-sep-char ?/)
5650 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5651 (if (and
5652 ;; When `tramp-mode' is not enabled, we don't do anything.
5653 fn tramp-mode
5654 ;; For other syntaxes than `sep', the regexp matches many common
5655 ;; situations where the user doesn't actually want to use Tramp.
5656 ;; So to avoid autoloading Tramp after typing just "/s", we
5657 ;; disable this part of the completion, unless the user implicitly
5658 ;; indicated his interest in using a fancier completion system.
5659 (or (eq tramp-syntax 'sep)
5660 (featurep 'tramp) ;; If it's loaded, we may as well use it.
5661 ;; `partial-completion-mode' does not exist in XEmacs.
5662 ;; It is obsoleted with Emacs 24.1.
5663 (and (boundp 'partial-completion-mode)
5664 (symbol-value 'partial-completion-mode))
5665 ;; FIXME: These may have been loaded even if the user never
5666 ;; intended to use them.
5667 (featurep 'ido)
5668 (featurep 'icicles)))
5669 (save-match-data (apply (cdr fn) args))
5670 (tramp-completion-run-real-handler operation args)))))
5672 ;;;###autoload
5673 (progn (defun tramp-register-file-name-handlers ()
5674 "Add Tramp file name handlers to `file-name-handler-alist'."
5675 ;; Remove autoloaded handlers from file name handler alist. Useful,
5676 ;; if `tramp-syntax' has been changed.
5677 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5678 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5679 (let ((a1 (rassq
5680 'tramp-completion-file-name-handler file-name-handler-alist)))
5681 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5682 ;; Add the handlers.
5683 (add-to-list 'file-name-handler-alist
5684 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5685 (put 'tramp-file-name-handler 'safe-magic t)
5686 (add-to-list 'file-name-handler-alist
5687 (cons tramp-completion-file-name-regexp
5688 'tramp-completion-file-name-handler))
5689 (put 'tramp-completion-file-name-handler 'safe-magic t)
5690 ;; If jka-compr or epa-file are already loaded, move them to the
5691 ;; front of `file-name-handler-alist'.
5692 (dolist (fnh '(epa-file-handler jka-compr-handler))
5693 (let ((entry (rassoc fnh file-name-handler-alist)))
5694 (when entry
5695 (setq file-name-handler-alist
5696 (cons entry (delete entry file-name-handler-alist))))))))
5698 ;; `tramp-file-name-handler' must be registered before evaluation of
5699 ;; site-start and init files, because there might exist remote files
5700 ;; already, f.e. files kept via recentf-mode.
5701 ;;;###autoload(tramp-register-file-name-handlers)
5702 (tramp-register-file-name-handlers)
5704 ;;;###autoload
5705 (defun tramp-unload-file-name-handlers ()
5706 (setq file-name-handler-alist
5707 (delete (rassoc 'tramp-file-name-handler
5708 file-name-handler-alist)
5709 (delete (rassoc 'tramp-completion-file-name-handler
5710 file-name-handler-alist)
5711 file-name-handler-alist))))
5713 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5715 ;;; File name handler functions for completion mode:
5717 (defvar tramp-completion-mode nil
5718 "If non-nil, external packages signal that they are in file name completion.
5720 This is necessary, because Tramp uses a heuristic depending on last
5721 input event. This fails when external packages use other characters
5722 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5723 should never be set globally, the intention is to let-bind it.")
5725 ;; Necessary because `tramp-file-name-regexp-unified' and
5726 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5727 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5728 ;; to `tramp-file-name-handler'). Otherwise, it takes
5729 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5730 ;; risky, because completing a file might require loading other files,
5731 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5732 ;; variable. On the other hand, those files shouldn't have partial
5733 ;; Tramp file name syntax. Maybe another variable should be introduced
5734 ;; overwriting this check in such cases. Or we change Tramp file name
5735 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5736 (defun tramp-completion-mode-p ()
5737 "Check, whether method / user name / host name completion is active."
5739 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5740 (and (boundp 'non-essential) (symbol-value 'non-essential))
5741 tramp-completion-mode
5742 ;; Emacs.
5743 (equal last-input-event 'tab)
5744 (and (natnump last-input-event)
5746 ;; ?\t has event-modifier 'control.
5747 (equal last-input-event ?\t)
5748 (and (not (event-modifiers last-input-event))
5749 (or (equal last-input-event ?\?)
5750 (equal last-input-event ?\ )))))
5751 ;; XEmacs.
5752 (and (featurep 'xemacs)
5753 ;; `last-input-event' might be nil.
5754 (not (null last-input-event))
5755 ;; `last-input-event' may have no character approximation.
5756 (tramp-compat-funcall 'event-to-character last-input-event)
5758 ;; ?\t has event-modifier 'control.
5759 (equal
5760 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
5761 (and (not (event-modifiers last-input-event))
5762 (or (equal
5763 (tramp-compat-funcall 'event-to-character last-input-event)
5764 ?\?)
5765 (equal
5766 (tramp-compat-funcall 'event-to-character last-input-event)
5767 ?\ )))))))
5769 (defun tramp-connectable-p (filename)
5770 "Check, whether it is possible to connect the remote host w/o side-effects.
5771 This is true, if either the remote host is already connected, or if we are
5772 not in completion mode."
5773 (and (tramp-tramp-file-p filename)
5774 (with-parsed-tramp-file-name filename nil
5775 (or (get-buffer (tramp-buffer-name v))
5776 (not (tramp-completion-mode-p))))))
5778 ;; Method, host name and user name completion.
5779 ;; `tramp-completion-dissect-file-name' returns a list of
5780 ;; tramp-file-name structures. For all of them we return possible completions.
5781 ;;;###autoload
5782 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5783 "Like `file-name-all-completions' for partial Tramp files."
5785 (let* ((fullname (tramp-drop-volume-letter
5786 (expand-file-name filename directory)))
5787 ;; Possible completion structures.
5788 (v (tramp-completion-dissect-file-name fullname))
5789 result result1)
5791 (while v
5792 (let* ((car (car v))
5793 (method (tramp-file-name-method car))
5794 (user (tramp-file-name-user car))
5795 (host (tramp-file-name-host car))
5796 (localname (tramp-file-name-localname car))
5797 (m (tramp-find-method method user host))
5798 (tramp-current-user user) ; see `tramp-parse-passwd'
5799 all-user-hosts)
5801 (unless localname ;; Nothing to complete.
5803 (if (or user host)
5805 ;; Method dependent user / host combinations.
5806 (progn
5807 (mapc
5808 (lambda (x)
5809 (setq all-user-hosts
5810 (append all-user-hosts
5811 (funcall (nth 0 x) (nth 1 x)))))
5812 (tramp-get-completion-function m))
5814 (setq result
5815 (append result
5816 (mapcar
5817 (lambda (x)
5818 (tramp-get-completion-user-host
5819 method user host (nth 0 x) (nth 1 x)))
5820 (delq nil all-user-hosts)))))
5822 ;; Possible methods.
5823 (setq result
5824 (append result (tramp-get-completion-methods m)))))
5826 (setq v (cdr v))))
5828 ;; Unify list, remove nil elements.
5829 (while result
5830 (let ((car (car result)))
5831 (when car
5832 (add-to-list
5833 'result1
5834 (substring car (length (tramp-drop-volume-letter directory)))))
5835 (setq result (cdr result))))
5837 ;; Complete local parts.
5838 (append
5839 result1
5840 (condition-case nil
5841 (apply (if (tramp-connectable-p fullname)
5842 'tramp-completion-run-real-handler
5843 'tramp-run-real-handler)
5844 'file-name-all-completions (list (list filename directory)))
5845 (error nil)))))
5847 ;; Method, host name and user name completion for a file.
5848 ;;;###autoload
5849 (defun tramp-completion-handle-file-name-completion
5850 (filename directory &optional predicate)
5851 "Like `file-name-completion' for Tramp files."
5852 (try-completion
5853 filename
5854 (mapcar 'list (file-name-all-completions filename directory))
5855 (when (and predicate
5856 (tramp-connectable-p (expand-file-name filename directory)))
5857 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5859 ;; I misuse a little bit the tramp-file-name structure in order to handle
5860 ;; completion possibilities for partial methods / user names / host names.
5861 ;; Return value is a list of tramp-file-name structures according to possible
5862 ;; completions. If "localname" is non-nil it means there
5863 ;; shouldn't be a completion anymore.
5865 ;; Expected results:
5867 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5868 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5869 ;; [nil "x" nil nil]
5870 ;; ["x" nil nil nil]
5872 ;; "/x:" "/x:y" "/x:y:"
5873 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5874 ;; "/[x/" "/[x/y"
5875 ;; ["x" nil "" nil] ["x" nil "y" nil]
5876 ;; ["x" "" nil nil] ["x" "y" nil nil]
5878 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5879 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5880 ;; "/[x/y@" "/[x/y@z"
5881 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5882 (defun tramp-completion-dissect-file-name (name)
5883 "Returns a list of `tramp-file-name' structures.
5884 They are collected by `tramp-completion-dissect-file-name1'."
5886 (let* ((result)
5887 (x-nil "\\|\\(\\)")
5888 (tramp-completion-ipv6-regexp
5889 (format
5890 "[^%s]*"
5891 (if (zerop (length tramp-postfix-ipv6-format))
5892 tramp-postfix-host-format
5893 tramp-postfix-ipv6-format)))
5894 ;; "/method" "/[method"
5895 (tramp-completion-file-name-structure1
5896 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5897 1 nil nil nil))
5898 ;; "/user" "/[user"
5899 (tramp-completion-file-name-structure2
5900 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5901 nil 1 nil nil))
5902 ;; "/host" "/[host"
5903 (tramp-completion-file-name-structure3
5904 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5905 nil nil 1 nil))
5906 ;; "/[ipv6" "/[ipv6"
5907 (tramp-completion-file-name-structure4
5908 (list (concat tramp-prefix-regexp
5909 tramp-prefix-ipv6-regexp
5910 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5911 nil nil 1 nil))
5912 ;; "/user@host" "/[user@host"
5913 (tramp-completion-file-name-structure5
5914 (list (concat tramp-prefix-regexp
5915 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5916 "\\(" tramp-host-regexp x-nil "\\)$")
5917 nil 1 2 nil))
5918 ;; "/user@[ipv6" "/[user@ipv6"
5919 (tramp-completion-file-name-structure6
5920 (list (concat tramp-prefix-regexp
5921 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5922 tramp-prefix-ipv6-regexp
5923 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5924 nil 1 2 nil))
5925 ;; "/method:user" "/[method/user" "/method://user"
5926 (tramp-completion-file-name-structure7
5927 (list (concat tramp-prefix-regexp
5928 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5929 "\\(" tramp-user-regexp x-nil "\\)$")
5930 1 2 nil nil))
5931 ;; "/method:host" "/[method/host" "/method://host"
5932 (tramp-completion-file-name-structure8
5933 (list (concat tramp-prefix-regexp
5934 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5935 "\\(" tramp-host-regexp x-nil "\\)$")
5936 1 nil 2 nil))
5937 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5938 (tramp-completion-file-name-structure9
5939 (list (concat tramp-prefix-regexp
5940 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5941 tramp-prefix-ipv6-regexp
5942 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5943 1 nil 2 nil))
5944 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5945 (tramp-completion-file-name-structure10
5946 (list (concat tramp-prefix-regexp
5947 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5948 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5949 "\\(" tramp-host-regexp x-nil "\\)$")
5950 1 2 3 nil))
5951 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5952 (tramp-completion-file-name-structure11
5953 (list (concat tramp-prefix-regexp
5954 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5955 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5956 tramp-prefix-ipv6-regexp
5957 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5958 1 2 3 nil))
5959 ;; "/method: "/method:/"
5960 (tramp-completion-file-name-structure12
5961 (list
5962 (if (equal tramp-syntax 'url)
5963 (concat tramp-prefix-regexp
5964 "\\(" tramp-method-regexp "\\)"
5965 "\\(" (substring tramp-postfix-method-regexp 0 1)
5966 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5967 "\\(" "\\)$")
5968 ;; Should not match if not URL syntax.
5969 (concat tramp-prefix-regexp "/$"))
5970 1 3 nil nil))
5971 ;; "/method: "/method:/"
5972 (tramp-completion-file-name-structure13
5973 (list
5974 (if (equal tramp-syntax 'url)
5975 (concat tramp-prefix-regexp
5976 "\\(" tramp-method-regexp "\\)"
5977 "\\(" (substring tramp-postfix-method-regexp 0 1)
5978 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5979 "\\(" "\\)$")
5980 ;; Should not match if not URL syntax.
5981 (concat tramp-prefix-regexp "/$"))
5982 1 nil 3 nil)))
5984 (mapc (lambda (regexp)
5985 (add-to-list 'result
5986 (tramp-completion-dissect-file-name1 regexp name)))
5987 (list
5988 tramp-completion-file-name-structure1
5989 tramp-completion-file-name-structure2
5990 tramp-completion-file-name-structure3
5991 tramp-completion-file-name-structure4
5992 tramp-completion-file-name-structure5
5993 tramp-completion-file-name-structure6
5994 tramp-completion-file-name-structure7
5995 tramp-completion-file-name-structure8
5996 tramp-completion-file-name-structure9
5997 tramp-completion-file-name-structure10
5998 tramp-completion-file-name-structure11
5999 tramp-completion-file-name-structure12
6000 tramp-completion-file-name-structure13
6001 tramp-file-name-structure))
6003 (delq nil result)))
6005 (defun tramp-completion-dissect-file-name1 (structure name)
6006 "Returns a `tramp-file-name' structure matching STRUCTURE.
6007 The structure consists of remote method, remote user,
6008 remote host and localname (filename on remote host)."
6010 (save-match-data
6011 (when (string-match (nth 0 structure) name)
6012 (let ((method (and (nth 1 structure)
6013 (match-string (nth 1 structure) name)))
6014 (user (and (nth 2 structure)
6015 (match-string (nth 2 structure) name)))
6016 (host (and (nth 3 structure)
6017 (match-string (nth 3 structure) name)))
6018 (localname (and (nth 4 structure)
6019 (match-string (nth 4 structure) name))))
6020 (vector method user host localname)))))
6022 ;; This function returns all possible method completions, adding the
6023 ;; trailing method delimeter.
6024 (defun tramp-get-completion-methods (partial-method)
6025 "Returns all method completions for PARTIAL-METHOD."
6026 (mapcar
6027 (lambda (method)
6028 (and method
6029 (string-match (concat "^" (regexp-quote partial-method)) method)
6030 (tramp-completion-make-tramp-file-name method nil nil nil)))
6031 (mapcar 'car tramp-methods)))
6033 ;; Compares partial user and host names with possible completions.
6034 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
6035 "Returns the most expanded string for user and host name completion.
6036 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
6037 (cond
6039 ((and partial-user partial-host)
6040 (if (and host
6041 (string-match (concat "^" (regexp-quote partial-host)) host)
6042 (string-equal partial-user (or user partial-user)))
6043 (setq user partial-user)
6044 (setq user nil
6045 host nil)))
6047 (partial-user
6048 (setq host nil)
6049 (unless
6050 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
6051 (setq user nil)))
6053 (partial-host
6054 (setq user nil)
6055 (unless
6056 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
6057 (setq host nil)))
6059 (t (setq user nil
6060 host nil)))
6062 (unless (zerop (+ (length user) (length host)))
6063 (tramp-completion-make-tramp-file-name method user host nil)))
6065 (defun tramp-parse-rhosts (filename)
6066 "Return a list of (user host) tuples allowed to access.
6067 Either user or host may be nil."
6068 ;; On Windows, there are problems in completion when
6069 ;; `default-directory' is remote.
6070 (let ((default-directory (tramp-compat-temporary-file-directory))
6071 res)
6072 (when (file-readable-p filename)
6073 (with-temp-buffer
6074 (insert-file-contents filename)
6075 (goto-char (point-min))
6076 (while (not (eobp))
6077 (push (tramp-parse-rhosts-group) res))))
6078 res))
6080 (defun tramp-parse-rhosts-group ()
6081 "Return a (user host) tuple allowed to access.
6082 Either user or host may be nil."
6083 (let ((result)
6084 (regexp
6085 (concat
6086 "^\\(" tramp-host-regexp "\\)"
6087 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6088 (narrow-to-region (point) (tramp-compat-line-end-position))
6089 (when (re-search-forward regexp nil t)
6090 (setq result (append (list (match-string 3) (match-string 1)))))
6091 (widen)
6092 (forward-line 1)
6093 result))
6095 (defun tramp-parse-shosts (filename)
6096 "Return a list of (user host) tuples allowed to access.
6097 User is always nil."
6098 ;; On Windows, there are problems in completion when
6099 ;; `default-directory' is remote.
6100 (let ((default-directory (tramp-compat-temporary-file-directory))
6101 res)
6102 (when (file-readable-p filename)
6103 (with-temp-buffer
6104 (insert-file-contents filename)
6105 (goto-char (point-min))
6106 (while (not (eobp))
6107 (push (tramp-parse-shosts-group) res))))
6108 res))
6110 (defun tramp-parse-shosts-group ()
6111 "Return a (user host) tuple allowed to access.
6112 User is always nil."
6113 (let ((result)
6114 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
6115 (narrow-to-region (point) (tramp-compat-line-end-position))
6116 (when (re-search-forward regexp nil t)
6117 (setq result (list nil (match-string 1))))
6118 (widen)
6120 (> (skip-chars-forward ",") 0)
6121 (forward-line 1))
6122 result))
6124 (defun tramp-parse-sconfig (filename)
6125 "Return a list of (user host) tuples allowed to access.
6126 User is always nil."
6127 ;; On Windows, there are problems in completion when
6128 ;; `default-directory' is remote.
6129 (let ((default-directory (tramp-compat-temporary-file-directory))
6130 res)
6131 (when (file-readable-p filename)
6132 (with-temp-buffer
6133 (insert-file-contents filename)
6134 (goto-char (point-min))
6135 (while (not (eobp))
6136 (push (tramp-parse-sconfig-group) res))))
6137 res))
6139 (defun tramp-parse-sconfig-group ()
6140 "Return a (user host) tuple allowed to access.
6141 User is always nil."
6142 (let ((result)
6143 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
6144 (narrow-to-region (point) (tramp-compat-line-end-position))
6145 (when (re-search-forward regexp nil t)
6146 (setq result (list nil (match-string 1))))
6147 (widen)
6149 (> (skip-chars-forward ",") 0)
6150 (forward-line 1))
6151 result))
6153 (defun tramp-parse-shostkeys (dirname)
6154 "Return a list of (user host) tuples allowed to access.
6155 User is always nil."
6156 ;; On Windows, there are problems in completion when
6157 ;; `default-directory' is remote.
6158 (let* ((default-directory (tramp-compat-temporary-file-directory))
6159 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6160 (files (when (file-directory-p dirname) (directory-files dirname)))
6161 result)
6162 (while files
6163 (when (string-match regexp (car files))
6164 (push (list nil (match-string 1 (car files))) result))
6165 (setq files (cdr files)))
6166 result))
6168 (defun tramp-parse-sknownhosts (dirname)
6169 "Return a list of (user host) tuples allowed to access.
6170 User is always nil."
6171 ;; On Windows, there are problems in completion when
6172 ;; `default-directory' is remote.
6173 (let* ((default-directory (tramp-compat-temporary-file-directory))
6174 (regexp (concat "^\\(" tramp-host-regexp
6175 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6176 (files (when (file-directory-p dirname) (directory-files dirname)))
6177 result)
6178 (while files
6179 (when (string-match regexp (car files))
6180 (push (list nil (match-string 1 (car files))) result))
6181 (setq files (cdr files)))
6182 result))
6184 (defun tramp-parse-hosts (filename)
6185 "Return a list of (user host) tuples allowed to access.
6186 User is always nil."
6187 ;; On Windows, there are problems in completion when
6188 ;; `default-directory' is remote.
6189 (let ((default-directory (tramp-compat-temporary-file-directory))
6190 res)
6191 (when (file-readable-p filename)
6192 (with-temp-buffer
6193 (insert-file-contents filename)
6194 (goto-char (point-min))
6195 (while (not (eobp))
6196 (push (tramp-parse-hosts-group) res))))
6197 res))
6199 (defun tramp-parse-hosts-group ()
6200 "Return a (user host) tuple allowed to access.
6201 User is always nil."
6202 (let ((result)
6203 (regexp
6204 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6205 (narrow-to-region (point) (tramp-compat-line-end-position))
6206 (when (re-search-forward regexp nil t)
6207 (setq result (list nil (match-string 1))))
6208 (widen)
6210 (> (skip-chars-forward " \t") 0)
6211 (forward-line 1))
6212 result))
6214 ;; For su-alike methods it would be desirable to return "root@localhost"
6215 ;; as default. Unfortunately, we have no information whether any user name
6216 ;; has been typed already. So we use `tramp-current-user' as indication,
6217 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6218 (defun tramp-parse-passwd (filename)
6219 "Return a list of (user host) tuples allowed to access.
6220 Host is always \"localhost\"."
6221 ;; On Windows, there are problems in completion when
6222 ;; `default-directory' is remote.
6223 (let ((default-directory (tramp-compat-temporary-file-directory))
6224 res)
6225 (if (zerop (length tramp-current-user))
6226 '(("root" nil))
6227 (when (file-readable-p filename)
6228 (with-temp-buffer
6229 (insert-file-contents filename)
6230 (goto-char (point-min))
6231 (while (not (eobp))
6232 (push (tramp-parse-passwd-group) res))))
6233 res)))
6235 (defun tramp-parse-passwd-group ()
6236 "Return a (user host) tuple allowed to access.
6237 Host is always \"localhost\"."
6238 (let ((result)
6239 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6240 (narrow-to-region (point) (tramp-compat-line-end-position))
6241 (when (re-search-forward regexp nil t)
6242 (setq result (list (match-string 1) "localhost")))
6243 (widen)
6244 (forward-line 1)
6245 result))
6247 (defun tramp-parse-netrc (filename)
6248 "Return a list of (user host) tuples allowed to access.
6249 User may be nil."
6250 ;; On Windows, there are problems in completion when
6251 ;; `default-directory' is remote.
6252 (let ((default-directory (tramp-compat-temporary-file-directory))
6253 res)
6254 (when (file-readable-p filename)
6255 (with-temp-buffer
6256 (insert-file-contents filename)
6257 (goto-char (point-min))
6258 (while (not (eobp))
6259 (push (tramp-parse-netrc-group) res))))
6260 res))
6262 (defun tramp-parse-netrc-group ()
6263 "Return a (user host) tuple allowed to access.
6264 User may be nil."
6265 (let ((result)
6266 (regexp
6267 (concat
6268 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6269 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6270 (narrow-to-region (point) (tramp-compat-line-end-position))
6271 (when (re-search-forward regexp nil t)
6272 (setq result (list (match-string 3) (match-string 1))))
6273 (widen)
6274 (forward-line 1)
6275 result))
6277 (defun tramp-parse-putty (registry)
6278 "Return a list of (user host) tuples allowed to access.
6279 User is always nil."
6280 ;; On Windows, there are problems in completion when
6281 ;; `default-directory' is remote.
6282 (let ((default-directory (tramp-compat-temporary-file-directory))
6283 res)
6284 (with-temp-buffer
6285 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6286 (goto-char (point-min))
6287 (while (not (eobp))
6288 (push (tramp-parse-putty-group registry) res))))
6289 res))
6291 (defun tramp-parse-putty-group (registry)
6292 "Return a (user host) tuple allowed to access.
6293 User is always nil."
6294 (let ((result)
6295 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6296 (narrow-to-region (point) (tramp-compat-line-end-position))
6297 (when (re-search-forward regexp nil t)
6298 (setq result (list nil (match-string 1))))
6299 (widen)
6300 (forward-line 1)
6301 result))
6303 ;;; Internal Functions:
6305 (defun tramp-maybe-send-script (vec script name)
6306 "Define in remote shell function NAME implemented as SCRIPT.
6307 Only send the definition if it has not already been done."
6308 (let* ((p (tramp-get-connection-process vec))
6309 (scripts (tramp-get-connection-property p "scripts" nil)))
6310 (unless (member name scripts)
6311 (with-progress-reporter vec 5 (format "Sending script `%s'" name)
6312 ;; The script could contain a call of Perl. This is masked with `%s'.
6313 (tramp-send-command-and-check
6315 (format "%s () {\n%s\n}" name
6316 (format script (tramp-get-remote-perl vec))))
6317 (tramp-set-connection-property p "scripts" (cons name scripts))))))
6319 (defun tramp-set-auto-save ()
6320 (when (and ;; ange-ftp has its own auto-save mechanism
6321 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6322 'tramp-sh-file-name-handler)
6323 auto-save-default)
6324 (auto-save-mode 1)))
6325 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6326 (add-hook 'tramp-unload-hook
6327 (lambda ()
6328 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6330 (defun tramp-run-test (switch filename)
6331 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6332 Returns the exit code of the `test' program."
6333 (with-parsed-tramp-file-name filename nil
6334 (tramp-send-command-and-check
6336 (format
6337 "%s %s %s"
6338 (tramp-get-test-command v)
6339 switch
6340 (tramp-shell-quote-argument localname)))))
6342 (defun tramp-run-test2 (format-string file1 file2)
6343 "Run `test'-like program on the remote system, given FILE1, FILE2.
6344 FORMAT-STRING contains the program name, switches, and place holders.
6345 Returns the exit code of the `test' program. Barfs if the methods,
6346 hosts, or files, disagree."
6347 (unless (tramp-equal-remote file1 file2)
6348 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6349 (tramp-error
6350 v 'file-error
6351 "tramp-run-test2 only implemented for same method, user, host")))
6352 (with-parsed-tramp-file-name file1 v1
6353 (with-parsed-tramp-file-name file1 v2
6354 (tramp-send-command-and-check
6356 (format format-string
6357 (tramp-shell-quote-argument v1-localname)
6358 (tramp-shell-quote-argument v2-localname))))))
6360 (defun tramp-buffer-name (vec)
6361 "A name for the connection buffer VEC."
6362 ;; We must use `tramp-file-name-real-host', because for gateway
6363 ;; methods the default port will be expanded later on, which would
6364 ;; tamper the name.
6365 (let ((method (tramp-file-name-method vec))
6366 (user (tramp-file-name-user vec))
6367 (host (tramp-file-name-real-host vec)))
6368 (if (not (zerop (length user)))
6369 (format "*tramp/%s %s@%s*" method user host)
6370 (format "*tramp/%s %s*" method host))))
6372 (defun tramp-delete-temp-file-function ()
6373 "Remove temporary files related to current buffer."
6374 (when (stringp tramp-temp-buffer-file-name)
6375 (condition-case nil
6376 (tramp-compat-delete-file tramp-temp-buffer-file-name 'force)
6377 (error nil))))
6379 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6380 (add-hook 'tramp-cache-unload-hook
6381 (lambda ()
6382 (remove-hook 'kill-buffer-hook
6383 'tramp-delete-temp-file-function)))
6385 (defun tramp-get-buffer (vec)
6386 "Get the connection buffer to be used for VEC."
6387 (or (get-buffer (tramp-buffer-name vec))
6388 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6389 (setq buffer-undo-list t)
6390 (setq default-directory
6391 (tramp-make-tramp-file-name
6392 (tramp-file-name-method vec)
6393 (tramp-file-name-user vec)
6394 (tramp-file-name-host vec)
6395 "/"))
6396 (current-buffer))))
6398 (defun tramp-get-connection-buffer (vec)
6399 "Get the connection buffer to be used for VEC.
6400 In case a second asynchronous communication has been started, it is different
6401 from `tramp-get-buffer'."
6402 (or (tramp-get-connection-property vec "process-buffer" nil)
6403 (tramp-get-buffer vec)))
6405 (defun tramp-get-connection-process (vec)
6406 "Get the connection process to be used for VEC.
6407 In case a second asynchronous communication has been started, it is different
6408 from the default one."
6409 (get-process
6410 (or (tramp-get-connection-property vec "process-name" nil)
6411 (tramp-buffer-name vec))))
6413 (defun tramp-debug-buffer-name (vec)
6414 "A name for the debug buffer for VEC."
6415 ;; We must use `tramp-file-name-real-host', because for gateway
6416 ;; methods the default port will be expanded later on, which would
6417 ;; tamper the name.
6418 (let ((method (tramp-file-name-method vec))
6419 (user (tramp-file-name-user vec))
6420 (host (tramp-file-name-real-host vec)))
6421 (if (not (zerop (length user)))
6422 (format "*debug tramp/%s %s@%s*" method user host)
6423 (format "*debug tramp/%s %s*" method host))))
6425 (defconst tramp-debug-outline-regexp
6426 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6428 (defun tramp-get-debug-buffer (vec)
6429 "Get the debug buffer for VEC."
6430 (with-current-buffer
6431 (get-buffer-create (tramp-debug-buffer-name vec))
6432 (when (bobp)
6433 (setq buffer-undo-list t)
6434 ;; Activate `outline-mode'. This runs `text-mode-hook' and
6435 ;; `outline-mode-hook'. We must prevent that local processes
6436 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6437 ;; Furthermore, `outline-regexp' must have the correct value
6438 ;; already, because it is used by `font-lock-compile-keywords'.
6439 (let ((default-directory (tramp-compat-temporary-file-directory))
6440 (outline-regexp tramp-debug-outline-regexp))
6441 (outline-mode))
6442 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
6443 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6444 (current-buffer)))
6446 (defun tramp-outline-level ()
6447 "Return the depth to which a statement is nested in the outline.
6448 Point must be at the beginning of a header line.
6450 The outline level is equal to the verbosity of the Tramp message."
6451 (1+ (string-to-number (match-string 1))))
6453 (defun tramp-find-executable
6454 (vec progname dirlist &optional ignore-tilde ignore-path)
6455 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6456 First arg VEC specifies the connection, PROGNAME is the program
6457 to search for, and DIRLIST gives the list of directories to
6458 search. If IGNORE-TILDE is non-nil, directory names starting
6459 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6460 only in DIRLIST.
6462 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6464 This function expects to be in the right *tramp* buffer."
6465 (with-current-buffer (tramp-get-connection-buffer vec)
6466 (let (result)
6467 ;; Check whether the executable is in $PATH. "which(1)" does not
6468 ;; report always a correct error code; therefore we check the
6469 ;; number of words it returns.
6470 (unless ignore-path
6471 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6472 (goto-char (point-min))
6473 (if (looking-at "^\\s-*1$")
6474 (setq result (concat "\\" progname))))
6475 (unless result
6476 (when ignore-tilde
6477 ;; Remove all ~/foo directories from dirlist. In XEmacs,
6478 ;; `remove' is in CL, and we want to avoid CL dependencies.
6479 (let (newdl d)
6480 (while dirlist
6481 (setq d (car dirlist))
6482 (setq dirlist (cdr dirlist))
6483 (unless (char-equal ?~ (aref d 0))
6484 (setq newdl (cons d newdl))))
6485 (setq dirlist (nreverse newdl))))
6486 (tramp-send-command
6488 (format (concat "while read d; "
6489 "do if test -x $d/%s -a -f $d/%s; "
6490 "then echo tramp_executable $d/%s; "
6491 "break; fi; done <<'EOF'\n"
6492 "%s\nEOF")
6493 progname progname progname (mapconcat 'identity dirlist "\n")))
6494 (goto-char (point-max))
6495 (when (search-backward "tramp_executable " nil t)
6496 (skip-chars-forward "^ ")
6497 (skip-chars-forward " ")
6498 (setq result (buffer-substring
6499 (point) (tramp-compat-line-end-position)))))
6500 result)))
6502 (defun tramp-set-remote-path (vec)
6503 "Sets the remote environment PATH to existing directories.
6504 I.e., for each directory in `tramp-remote-path', it is tested
6505 whether it exists and if so, it is added to the environment
6506 variable PATH."
6507 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6508 (tramp-send-command
6509 vec (format "PATH=%s; export PATH"
6510 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6512 ;; ------------------------------------------------------------
6513 ;; -- Communication with external shell --
6514 ;; ------------------------------------------------------------
6516 (defun tramp-find-file-exists-command (vec)
6517 "Find a command on the remote host for checking if a file exists.
6518 Here, we are looking for a command which has zero exit status if the
6519 file exists and nonzero exit status otherwise."
6520 (let ((existing "/")
6521 (nonexisting
6522 (tramp-shell-quote-argument "/ this file does not exist "))
6523 result)
6524 ;; The algorithm is as follows: we try a list of several commands.
6525 ;; For each command, we first run `$cmd /' -- this should return
6526 ;; true, as the root directory always exists. And then we run
6527 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6528 ;; does not exist. This should return false. We use the first
6529 ;; command we find that seems to work.
6530 ;; The list of commands to try is as follows:
6531 ;; `ls -d' This works on most systems, but NetBSD 1.4
6532 ;; has a bug: `ls' always returns zero exit
6533 ;; status, even for files which don't exist.
6534 ;; `test -e' Some Bourne shells have a `test' builtin
6535 ;; which does not know the `-e' option.
6536 ;; `/bin/test -e' For those, the `test' binary on disk normally
6537 ;; provides the option. Alas, the binary
6538 ;; is sometimes `/bin/test' and sometimes it's
6539 ;; `/usr/bin/test'.
6540 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6541 (unless (or
6542 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6543 (zerop (tramp-send-command-and-check
6544 vec (format "%s %s" result existing)))
6545 (not (zerop (tramp-send-command-and-check
6546 vec (format "%s %s" result nonexisting)))))
6547 (and (setq result "/bin/test -e")
6548 (zerop (tramp-send-command-and-check
6549 vec (format "%s %s" result existing)))
6550 (not (zerop (tramp-send-command-and-check
6551 vec (format "%s %s" result nonexisting)))))
6552 (and (setq result "/usr/bin/test -e")
6553 (zerop (tramp-send-command-and-check
6554 vec (format "%s %s" result existing)))
6555 (not (zerop (tramp-send-command-and-check
6556 vec (format "%s %s" result nonexisting)))))
6557 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6558 (zerop (tramp-send-command-and-check
6559 vec (format "%s %s" result existing)))
6560 (not (zerop (tramp-send-command-and-check
6561 vec (format "%s %s" result nonexisting))))))
6562 (tramp-error
6563 vec 'file-error "Couldn't find command to check if file exists"))
6564 result))
6566 ;; CCC test ksh or bash found for tilde expansion?
6567 (defun tramp-find-shell (vec)
6568 "Opens a shell on the remote host which groks tilde expansion."
6569 (unless (tramp-get-connection-property vec "remote-shell" nil)
6570 (let (shell)
6571 (with-current-buffer (tramp-get-buffer vec)
6572 (tramp-send-command vec "echo ~root" t)
6573 (cond
6574 ((or (string-match "^~root$" (buffer-string))
6575 ;; The default shell (ksh93) of OpenSolaris is buggy.
6576 (string-equal (tramp-get-connection-property vec "uname" "")
6577 "SunOS 5.11"))
6578 (setq shell
6579 (or (tramp-find-executable
6580 vec "bash" (tramp-get-remote-path vec) t t)
6581 (tramp-find-executable
6582 vec "ksh" (tramp-get-remote-path vec) t t)))
6583 (unless shell
6584 (tramp-error
6585 vec 'file-error
6586 "Couldn't find a shell which groks tilde expansion"))
6587 ;; Find arguments for this shell.
6588 (let ((alist tramp-sh-extra-args)
6589 item extra-args)
6590 (while (and alist (null extra-args))
6591 (setq item (pop alist))
6592 (when (string-match (car item) shell)
6593 (setq extra-args (cdr item))))
6594 (when extra-args (setq shell (concat shell " " extra-args))))
6595 (tramp-message
6596 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
6597 (let ((tramp-end-of-output tramp-initial-end-of-output))
6598 (tramp-send-command
6600 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6601 (shell-quote-argument tramp-end-of-output) shell)
6603 ;; Setting prompts.
6604 (with-progress-reporter vec 5 (format "Setting remote shell prompt")
6605 (tramp-send-command
6606 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6607 (tramp-send-command vec "PS2=''" t)
6608 (tramp-send-command vec "PS3=''" t)
6609 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
6611 (t (tramp-message
6612 vec 5 "Remote `%s' groks tilde expansion, good"
6613 (tramp-get-method-parameter
6614 (tramp-file-name-method vec) 'tramp-remote-sh))
6615 (tramp-set-connection-property
6616 vec "remote-shell"
6617 (tramp-get-method-parameter
6618 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
6620 ;; ------------------------------------------------------------
6621 ;; -- Functions for establishing connection --
6622 ;; ------------------------------------------------------------
6624 ;; The following functions are actions to be taken when seeing certain
6625 ;; prompts from the remote host. See the variable
6626 ;; `tramp-actions-before-shell' for usage of these functions.
6628 (defun tramp-action-login (proc vec)
6629 "Send the login name."
6630 (when (not (stringp tramp-current-user))
6631 (save-window-excursion
6632 (let ((enable-recursive-minibuffers t))
6633 (pop-to-buffer (tramp-get-connection-buffer vec))
6634 (setq tramp-current-user (read-string (match-string 0))))))
6635 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6636 (with-current-buffer (tramp-get-connection-buffer vec)
6637 (tramp-message vec 6 "\n%s" (buffer-string)))
6638 (tramp-send-string vec tramp-current-user))
6640 (defun tramp-action-password (proc vec)
6641 "Query the user for a password."
6642 (with-current-buffer (process-buffer proc)
6643 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6644 (tramp-message vec 3 "Sending %s" (match-string 1)))
6645 (tramp-enter-password proc))
6647 (defun tramp-action-succeed (proc vec)
6648 "Signal success in finding shell prompt."
6649 (throw 'tramp-action 'ok))
6651 (defun tramp-action-permission-denied (proc vec)
6652 "Signal permission denied."
6653 (kill-process proc)
6654 (throw 'tramp-action 'permission-denied))
6656 (defun tramp-action-yesno (proc vec)
6657 "Ask the user for confirmation using `yes-or-no-p'.
6658 Send \"yes\" to remote process on confirmation, abort otherwise.
6659 See also `tramp-action-yn'."
6660 (save-window-excursion
6661 (let ((enable-recursive-minibuffers t))
6662 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6663 (unless (yes-or-no-p (match-string 0))
6664 (kill-process proc)
6665 (throw 'tramp-action 'permission-denied))
6666 (with-current-buffer (tramp-get-connection-buffer vec)
6667 (tramp-message vec 6 "\n%s" (buffer-string)))
6668 (tramp-send-string vec "yes"))))
6670 (defun tramp-action-yn (proc vec)
6671 "Ask the user for confirmation using `y-or-n-p'.
6672 Send \"y\" to remote process on confirmation, abort otherwise.
6673 See also `tramp-action-yesno'."
6674 (save-window-excursion
6675 (let ((enable-recursive-minibuffers t))
6676 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6677 (unless (y-or-n-p (match-string 0))
6678 (kill-process proc)
6679 (throw 'tramp-action 'permission-denied))
6680 (with-current-buffer (tramp-get-connection-buffer vec)
6681 (tramp-message vec 6 "\n%s" (buffer-string)))
6682 (tramp-send-string vec "y"))))
6684 (defun tramp-action-terminal (proc vec)
6685 "Tell the remote host which terminal type to use.
6686 The terminal type can be configured with `tramp-terminal-type'."
6687 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6688 (with-current-buffer (tramp-get-connection-buffer vec)
6689 (tramp-message vec 6 "\n%s" (buffer-string)))
6690 (tramp-send-string vec tramp-terminal-type))
6692 (defun tramp-action-process-alive (proc vec)
6693 "Check, whether a process has finished."
6694 (unless (memq (process-status proc) '(run open))
6695 (throw 'tramp-action 'process-died)))
6697 (defun tramp-action-out-of-band (proc vec)
6698 "Check, whether an out-of-band copy has finished."
6699 (cond ((and (memq (process-status proc) '(stop exit))
6700 (zerop (process-exit-status proc)))
6701 (tramp-message vec 3 "Process has finished.")
6702 (throw 'tramp-action 'ok))
6703 ((or (and (memq (process-status proc) '(stop exit))
6704 (not (zerop (process-exit-status proc))))
6705 (memq (process-status proc) '(signal)))
6706 ;; `scp' could have copied correctly, but set modes could have failed.
6707 ;; This can be ignored.
6708 (with-current-buffer (process-buffer proc)
6709 (goto-char (point-min))
6710 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6711 (progn
6712 (tramp-message vec 5 "'set mode' error ignored.")
6713 (tramp-message vec 3 "Process has finished.")
6714 (throw 'tramp-action 'ok))
6715 (tramp-message vec 3 "Process has died.")
6716 (throw 'tramp-action 'process-died))))
6717 (t nil)))
6719 ;; Functions for processing the actions.
6721 (defun tramp-process-one-action (proc vec actions)
6722 "Wait for output from the shell and perform one action."
6723 (let (found todo item pattern action)
6724 (while (not found)
6725 ;; Reread output once all actions have been performed.
6726 ;; Obviously, the output was not complete.
6727 (tramp-accept-process-output proc 1)
6728 (setq todo actions)
6729 (while todo
6730 (setq item (pop todo))
6731 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6732 (setq action (nth 1 item))
6733 (tramp-message
6734 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6735 (when (tramp-check-for-regexp proc pattern)
6736 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6737 (setq found (funcall action proc vec)))))
6738 found))
6740 (defun tramp-process-actions (proc vec actions &optional timeout)
6741 "Perform actions until success or TIMEOUT."
6742 ;; Preserve message for `progress-reporter'.
6743 (with-temp-message ""
6744 ;; Enable auth-source and password-cache.
6745 (tramp-set-connection-property vec "first-password-request" t)
6746 (let (exit)
6747 (while (not exit)
6748 (tramp-message proc 3 "Waiting for prompts from remote shell")
6749 (setq exit
6750 (catch 'tramp-action
6751 (if timeout
6752 (with-timeout (timeout)
6753 (tramp-process-one-action proc vec actions))
6754 (tramp-process-one-action proc vec actions)))))
6755 (with-current-buffer (tramp-get-connection-buffer vec)
6756 (tramp-message vec 6 "\n%s" (buffer-string)))
6757 (unless (eq exit 'ok)
6758 (tramp-clear-passwd vec)
6759 (tramp-error-with-buffer
6760 nil vec 'file-error
6761 (cond
6762 ((eq exit 'permission-denied) "Permission denied")
6763 ((eq exit 'process-died) "Process died")
6764 (t "Login failed")))))))
6766 ;; Utility functions.
6768 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6769 "Like `accept-process-output' for Tramp processes.
6770 This is needed in order to hide `last-coding-system-used', which is set
6771 for process communication also."
6772 (with-current-buffer (process-buffer proc)
6773 (tramp-message proc 10 "%s %s" proc (process-status proc))
6774 (let (buffer-read-only last-coding-system-used)
6775 ;; Under Windows XP, accept-process-output doesn't return
6776 ;; sometimes. So we add an additional timeout.
6777 (with-timeout ((or timeout 1))
6778 (accept-process-output proc timeout timeout-msecs)))
6779 (tramp-message proc 10 "\n%s" (buffer-string))))
6781 (defun tramp-check-for-regexp (proc regexp)
6782 "Check, whether REGEXP is contained in process buffer of PROC.
6783 Erase echoed commands if exists."
6784 (with-current-buffer (process-buffer proc)
6785 (goto-char (point-min))
6787 ;; Check whether we need to remove echo output.
6788 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6789 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6790 (let ((begin (match-beginning 0)))
6791 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6792 ;; Discard echo from remote output.
6793 (tramp-set-connection-property proc "check-remote-echo" nil)
6794 (tramp-message proc 5 "echo-mark found")
6795 (forward-line 1)
6796 (delete-region begin (point))
6797 (goto-char (point-min)))))
6799 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6800 ;; Sometimes, the echo string is suppressed on the remote side.
6801 (not (string-equal
6802 (tramp-compat-funcall
6803 'substring-no-properties tramp-echo-mark-marker
6804 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6805 (tramp-compat-funcall
6806 'buffer-substring-no-properties
6807 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6808 ;; No echo to be handled, now we can look for the regexp.
6809 (goto-char (point-min))
6810 (re-search-forward regexp nil t))))
6812 (defun tramp-wait-for-regexp (proc timeout regexp)
6813 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6814 Expects the output of PROC to be sent to the current buffer. Returns
6815 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6816 nil."
6817 (with-current-buffer (process-buffer proc)
6818 (let ((found (tramp-check-for-regexp proc regexp))
6819 (start-time (current-time)))
6820 (cond (timeout
6821 ;; Work around a bug in XEmacs 21, where the timeout
6822 ;; expires faster than it should. This degenerates
6823 ;; to polling for buggy XEmacsen, but oh, well.
6824 (while (and (not found)
6825 (< (tramp-time-diff (current-time) start-time)
6826 timeout))
6827 (with-timeout (timeout)
6828 (while (not found)
6829 (tramp-accept-process-output proc 1)
6830 (unless (memq (process-status proc) '(run open))
6831 (tramp-error-with-buffer
6832 nil proc 'file-error "Process has died"))
6833 (setq found (tramp-check-for-regexp proc regexp))))))
6835 (while (not found)
6836 (tramp-accept-process-output proc 1)
6837 (unless (memq (process-status proc) '(run open))
6838 (tramp-error-with-buffer
6839 nil proc 'file-error "Process has died"))
6840 (setq found (tramp-check-for-regexp proc regexp)))))
6841 (tramp-message proc 6 "\n%s" (buffer-string))
6842 (when (not found)
6843 (if timeout
6844 (tramp-error
6845 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6846 regexp timeout)
6847 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6848 found)))
6850 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6851 "Wait for shell prompt and barf if none appears.
6852 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6853 seconds. If not, it produces an error message with the given ERROR-ARGS."
6854 (unless
6855 (tramp-wait-for-regexp
6856 proc timeout
6857 (format
6858 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6859 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6861 ;; We don't call `tramp-send-string' in order to hide the password
6862 ;; from the debug buffer, and because end-of-line handling of the
6863 ;; string.
6864 (defun tramp-enter-password (proc)
6865 "Prompt for a password and send it to the remote end."
6866 (process-send-string
6867 proc (concat (tramp-read-passwd proc)
6868 (or (tramp-get-method-parameter
6869 tramp-current-method
6870 'tramp-password-end-of-line)
6871 tramp-default-password-end-of-line))))
6873 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6874 "Set up an interactive shell.
6875 Mainly sets the prompt and the echo correctly. PROC is the shell
6876 process to set up. VEC specifies the connection."
6877 (let ((tramp-end-of-output tramp-initial-end-of-output))
6878 ;; It is useful to set the prompt in the following command because
6879 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6880 ;; about and thus /bin/sh will display a strange prompt. For
6881 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6882 ;; display the current working directory but /bin/sh will display
6883 ;; a dollar sign. The following command line sets $PS1 to a sane
6884 ;; value, and works under Bourne-ish shells as well as csh-like
6885 ;; shells. Daniel Pittman reports that the unusual positioning of
6886 ;; the single quotes makes it work under `rc', too. We also unset
6887 ;; the variable $ENV because that is read by some sh
6888 ;; implementations (eg, bash when called as sh) on startup; this
6889 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6890 ;; is another way to set the prompt in /bin/bash, it must be
6891 ;; discarded as well.
6892 (tramp-send-command
6894 (format
6895 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6896 (shell-quote-argument tramp-end-of-output)
6897 (tramp-get-method-parameter
6898 (tramp-file-name-method vec) 'tramp-remote-sh))
6901 ;; Disable echo.
6902 (tramp-message vec 5 "Setting up remote shell environment")
6903 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6904 ;; Check whether the echo has really been disabled. Some
6905 ;; implementations, like busybox of embedded GNU/Linux, don't
6906 ;; support disabling.
6907 (tramp-send-command vec "echo foo" t)
6908 (with-current-buffer (process-buffer proc)
6909 (goto-char (point-min))
6910 (when (looking-at "echo foo")
6911 (tramp-set-connection-property proc "remote-echo" t)
6912 (tramp-message vec 5 "Remote echo still on. Ok.")
6913 ;; Make sure backspaces and their echo are enabled and no line
6914 ;; width magic interferes with them.
6915 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6917 (tramp-message vec 5 "Setting shell prompt")
6918 (tramp-send-command
6919 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6920 (tramp-send-command vec "PS2=''" t)
6921 (tramp-send-command vec "PS3=''" t)
6922 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6924 ;; Try to set up the coding system correctly.
6925 ;; CCC this can't be the right way to do it. Hm.
6926 (tramp-message vec 5 "Determining coding system")
6927 (tramp-send-command vec "echo foo ; echo bar" t)
6928 (with-current-buffer (process-buffer proc)
6929 (goto-char (point-min))
6930 (if (featurep 'mule)
6931 ;; Use MULE to select the right EOL convention for communicating
6932 ;; with the process.
6933 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
6934 (cons 'undecided 'undecided)))
6935 cs-decode cs-encode)
6936 (when (symbolp cs) (setq cs (cons cs cs)))
6937 (setq cs-decode (car cs))
6938 (setq cs-encode (cdr cs))
6939 (unless cs-decode (setq cs-decode 'undecided))
6940 (unless cs-encode (setq cs-encode 'undecided))
6941 (setq cs-encode (tramp-coding-system-change-eol-conversion
6942 cs-encode 'unix))
6943 (when (search-forward "\r" nil t)
6944 (setq cs-decode (tramp-coding-system-change-eol-conversion
6945 cs-decode 'dos)))
6946 (tramp-compat-funcall
6947 'set-buffer-process-coding-system cs-decode cs-encode)
6948 (tramp-message
6949 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6950 ;; Look for ^M and do something useful if found.
6951 (when (search-forward "\r" nil t)
6952 ;; We have found a ^M but cannot frob the process coding system
6953 ;; because we're running on a non-MULE Emacs. Let's try
6954 ;; stty, instead.
6955 (tramp-send-command vec "stty -onlcr" t))))
6956 ;; Dump stty settings in the traces.
6957 (when (>= tramp-verbose 10)
6958 (tramp-send-command vec "stty -a" t))
6959 (tramp-send-command vec "set +o vi +o emacs" t)
6961 ;; Check whether the output of "uname -sr" has been changed. If
6962 ;; yes, this is a strong indication that we must expire all
6963 ;; connection properties. We start again with
6964 ;; `tramp-maybe-open-connection', it will be catched there.
6965 (tramp-message vec 5 "Checking system information")
6966 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6967 (new-uname
6968 (tramp-set-connection-property
6969 vec "uname"
6970 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6971 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
6972 (with-current-buffer (tramp-get-debug-buffer vec)
6973 ;; Keep the debug buffer.
6974 (rename-buffer
6975 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
6976 (tramp-compat-funcall 'tramp-cleanup-connection vec)
6977 (if (= (point-min) (point-max))
6978 (kill-buffer nil)
6979 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6980 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6981 (tramp-get-buffer vec)
6982 (tramp-message
6983 vec 3
6984 "Connection reset, because remote host changed from `%s' to `%s'"
6985 old-uname new-uname)
6986 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
6988 ;; Check whether the remote host suffers from buggy
6989 ;; `send-process-string'. This is known for FreeBSD (see comment in
6990 ;; `send_process', file process.c). I've tested sending 624 bytes
6991 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6992 ;; this host type is detected locally. It cannot handle remote
6993 ;; hosts, though.
6994 (with-connection-property proc "chunksize"
6995 (cond
6996 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6997 tramp-chunksize)
6999 (tramp-message
7000 vec 5 "Checking remote host type for `send-process-string' bug")
7001 (if (string-match
7002 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
7003 500 0))))
7005 ;; Set remote PATH variable.
7006 (tramp-set-remote-path vec)
7008 ;; Search for a good shell before searching for a command which
7009 ;; checks if a file exists. This is done because Tramp wants to use
7010 ;; "test foo; echo $?" to check if various conditions hold, and
7011 ;; there are buggy /bin/sh implementations which don't execute the
7012 ;; "echo $?" part if the "test" part has an error. In particular,
7013 ;; the OpenSolaris /bin/sh is a problem. There are also other
7014 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
7015 ;; in in function declarations, or changing HISTFILE in place.
7016 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
7017 ;; detected.
7018 (tramp-find-shell vec)
7020 ;; Disable unexpected output.
7021 (tramp-send-command vec "mesg n; biff n" t)
7023 ;; Set the environment.
7024 (tramp-message vec 5 "Setting default environment")
7026 (let ((env (copy-sequence tramp-remote-process-environment))
7027 unset item)
7028 (while env
7029 (setq item (tramp-compat-split-string (car env) "="))
7030 (setcdr item (mapconcat 'identity (cdr item) "="))
7031 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
7032 (tramp-send-command
7033 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
7034 (push (car item) unset))
7035 (setq env (cdr env)))
7036 (when unset
7037 (tramp-send-command
7038 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
7040 ;; CCC: We should either implement a Perl version of base64 encoding
7041 ;; and decoding. Then we just use that in the last item. The other
7042 ;; alternative is to use the Perl version of UU encoding. But then
7043 ;; we need a Lisp version of uuencode.
7045 ;; Old text from documentation of tramp-methods:
7046 ;; Using a uuencode/uudecode inline method is discouraged, please use one
7047 ;; of the base64 methods instead since base64 encoding is much more
7048 ;; reliable and the commands are more standardized between the different
7049 ;; Unix versions. But if you can't use base64 for some reason, please
7050 ;; note that the default uudecode command does not work well for some
7051 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
7052 ;; the following command for uudecode:
7054 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
7056 ;; For Irix, no solution is known yet.
7058 (defconst tramp-local-coding-commands
7059 '((b64 base64-encode-region base64-decode-region)
7060 (uu tramp-uuencode-region uudecode-decode-region)
7061 (pack
7062 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7063 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7064 "List of local coding commands for inline transfer.
7065 Each item is a list that looks like this:
7067 \(FORMAT ENCODING DECODING\)
7069 FORMAT is symbol describing the encoding/decoding format. It can be
7070 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7072 ENCODING and DECODING can be strings, giving commands, or symbols,
7073 giving functions. If they are strings, then they can contain
7074 the \"%s\" format specifier. If that specifier is present, the input
7075 filename will be put into the command line at that spot. If the
7076 specifier is not present, the input should be read from standard
7077 input.
7079 If they are functions, they will be called with two arguments, start
7080 and end of region, and are expected to replace the region contents
7081 with the encoded or decoded results, respectively.")
7083 (defconst tramp-remote-coding-commands
7084 '((b64 "base64" "base64 -d")
7085 (b64 "mimencode -b" "mimencode -u -b")
7086 (b64 "mmencode -b" "mmencode -u -b")
7087 (b64 "recode data..base64" "recode base64..data")
7088 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
7089 (b64 tramp-perl-encode tramp-perl-decode)
7090 (uu "uuencode xxx" "uudecode -o /dev/stdout")
7091 (uu "uuencode xxx" "uudecode -o -")
7092 (uu "uuencode xxx" "uudecode -p")
7093 (uu "uuencode xxx" tramp-uudecode)
7094 (pack
7095 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7096 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7097 "List of remote coding commands for inline transfer.
7098 Each item is a list that looks like this:
7100 \(FORMAT ENCODING DECODING\)
7102 FORMAT is symbol describing the encoding/decoding format. It can be
7103 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7105 ENCODING and DECODING can be strings, giving commands, or symbols,
7106 giving variables. If they are strings, then they can contain
7107 the \"%s\" format specifier. If that specifier is present, the input
7108 filename will be put into the command line at that spot. If the
7109 specifier is not present, the input should be read from standard
7110 input.
7112 If they are variables, this variable is a string containing a Perl
7113 implementation for this functionality. This Perl program will be transferred
7114 to the remote host, and it is available as shell function with the same name.")
7116 (defun tramp-find-inline-encoding (vec)
7117 "Find an inline transfer encoding that works.
7118 Goes through the list `tramp-local-coding-commands' and
7119 `tramp-remote-coding-commands'."
7120 (save-excursion
7121 (let ((local-commands tramp-local-coding-commands)
7122 (magic "xyzzy")
7123 loc-enc loc-dec rem-enc rem-dec litem ritem found)
7124 (while (and local-commands (not found))
7125 (setq litem (pop local-commands))
7126 (catch 'wont-work-local
7127 (let ((format (nth 0 litem))
7128 (remote-commands tramp-remote-coding-commands))
7129 (setq loc-enc (nth 1 litem))
7130 (setq loc-dec (nth 2 litem))
7131 ;; If the local encoder or decoder is a string, the
7132 ;; corresponding command has to work locally.
7133 (if (not (stringp loc-enc))
7134 (tramp-message
7135 vec 5 "Checking local encoding function `%s'" loc-enc)
7136 (tramp-message
7137 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
7138 (unless (zerop (tramp-call-local-coding-command
7139 loc-enc nil nil))
7140 (throw 'wont-work-local nil)))
7141 (if (not (stringp loc-dec))
7142 (tramp-message
7143 vec 5 "Checking local decoding function `%s'" loc-dec)
7144 (tramp-message
7145 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7146 (unless (zerop (tramp-call-local-coding-command
7147 loc-dec nil nil))
7148 (throw 'wont-work-local nil)))
7149 ;; Search for remote coding commands with the same format
7150 (while (and remote-commands (not found))
7151 (setq ritem (pop remote-commands))
7152 (catch 'wont-work-remote
7153 (when (equal format (nth 0 ritem))
7154 (setq rem-enc (nth 1 ritem))
7155 (setq rem-dec (nth 2 ritem))
7156 ;; Check if remote encoding and decoding commands can be
7157 ;; called remotely with null input and output. This makes
7158 ;; sure there are no syntax errors and the command is really
7159 ;; found. Note that we do not redirect stdout to /dev/null,
7160 ;; for two reasons: when checking the decoding command, we
7161 ;; actually check the output it gives. And also, when
7162 ;; redirecting "mimencode" output to /dev/null, then as root
7163 ;; it might change the permissions of /dev/null!
7164 (when (not (stringp rem-enc))
7165 (let ((name (symbol-name rem-enc)))
7166 (while (string-match (regexp-quote "-") name)
7167 (setq name (replace-match "_" nil t name)))
7168 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7169 (setq rem-enc name)))
7170 (tramp-message
7171 vec 5
7172 "Checking remote encoding command `%s' for sanity" rem-enc)
7173 (unless (zerop (tramp-send-command-and-check
7174 vec (format "%s </dev/null" rem-enc) t))
7175 (throw 'wont-work-remote nil))
7177 (when (not (stringp rem-dec))
7178 (let ((name (symbol-name rem-dec)))
7179 (while (string-match (regexp-quote "-") name)
7180 (setq name (replace-match "_" nil t name)))
7181 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7182 (setq rem-dec name)))
7183 (tramp-message
7184 vec 5
7185 "Checking remote decoding command `%s' for sanity" rem-dec)
7186 (unless (zerop (tramp-send-command-and-check
7188 (format "echo %s | %s | %s"
7189 magic rem-enc rem-dec)
7191 (throw 'wont-work-remote nil))
7193 (with-current-buffer (tramp-get-buffer vec)
7194 (goto-char (point-min))
7195 (unless (looking-at (regexp-quote magic))
7196 (throw 'wont-work-remote nil)))
7198 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7199 (setq rem-enc (nth 1 ritem))
7200 (setq rem-dec (nth 2 ritem))
7201 (setq found t)))))))
7203 ;; Did we find something?
7204 (unless found
7205 (tramp-error
7206 vec 'file-error "Couldn't find an inline transfer encoding"))
7208 ;; Set connection properties.
7209 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7210 (tramp-set-connection-property vec "local-encoding" loc-enc)
7211 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7212 (tramp-set-connection-property vec "local-decoding" loc-dec)
7213 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7214 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7215 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7216 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7218 (defun tramp-call-local-coding-command (cmd input output)
7219 "Call the local encoding or decoding command.
7220 If CMD contains \"%s\", provide input file INPUT there in command.
7221 Otherwise, INPUT is passed via standard input.
7222 INPUT can also be nil which means `/dev/null'.
7223 OUTPUT can be a string (which specifies a filename), or t (which
7224 means standard output and thus the current buffer), or nil (which
7225 means discard it)."
7226 (tramp-local-call-process
7227 tramp-encoding-shell
7228 (when (and input (not (string-match "%s" cmd))) input)
7229 (if (eq output t) t nil)
7231 tramp-encoding-command-switch
7232 (concat
7233 (if (string-match "%s" cmd) (format cmd input) cmd)
7234 (if (stringp output) (concat "> " output) ""))))
7236 (defconst tramp-inline-compress-commands
7237 '(("gzip" "gzip -d")
7238 ("bzip2" "bzip2 -d")
7239 ("compress" "compress -d"))
7240 "List of compress and decompress commands for inline transfer.
7241 Each item is a list that looks like this:
7243 \(COMPRESS DECOMPRESS\)
7245 COMPRESS or DECOMPRESS are strings with the respective commands.")
7247 (defun tramp-find-inline-compress (vec)
7248 "Find an inline transfer compress command that works.
7249 Goes through the list `tramp-inline-compress-commands'."
7250 (save-excursion
7251 (let ((commands tramp-inline-compress-commands)
7252 (magic "xyzzy")
7253 item compress decompress
7254 found)
7255 (while (and commands (not found))
7256 (catch 'next
7257 (setq item (pop commands)
7258 compress (nth 0 item)
7259 decompress (nth 1 item))
7260 (tramp-message
7261 vec 5
7262 "Checking local compress command `%s', `%s' for sanity"
7263 compress decompress)
7264 (unless (zerop (tramp-call-local-coding-command
7265 (format "echo %s | %s | %s"
7266 magic compress decompress) nil nil))
7267 (throw 'next nil))
7268 (tramp-message
7269 vec 5
7270 "Checking remote compress command `%s', `%s' for sanity"
7271 compress decompress)
7272 (unless (zerop (tramp-send-command-and-check
7273 vec (format "echo %s | %s | %s"
7274 magic compress decompress) t))
7275 (throw 'next nil))
7276 (setq found t)))
7278 ;; Did we find something?
7279 (if found
7280 (progn
7281 ;; Set connection properties.
7282 (tramp-message
7283 vec 5 "Using inline transfer compress command `%s'" compress)
7284 (tramp-set-connection-property vec "inline-compress" compress)
7285 (tramp-message
7286 vec 5 "Using inline transfer decompress command `%s'" decompress)
7287 (tramp-set-connection-property vec "inline-decompress" decompress))
7289 (tramp-set-connection-property vec "inline-compress" nil)
7290 (tramp-set-connection-property vec "inline-decompress" nil)
7291 (tramp-message
7292 vec 2 "Couldn't find an inline transfer compress command")))))
7294 (defun tramp-compute-multi-hops (vec)
7295 "Expands VEC according to `tramp-default-proxies-alist'.
7296 Gateway hops are already opened."
7297 (let ((target-alist `(,vec))
7298 (choices tramp-default-proxies-alist)
7299 item proxy)
7301 ;; Look for proxy hosts to be passed.
7302 (while choices
7303 (setq item (pop choices)
7304 proxy (eval (nth 2 item)))
7305 (when (and
7306 ;; host
7307 (string-match (or (eval (nth 0 item)) "")
7308 (or (tramp-file-name-host (car target-alist)) ""))
7309 ;; user
7310 (string-match (or (eval (nth 1 item)) "")
7311 (or (tramp-file-name-user (car target-alist)) "")))
7312 (if (null proxy)
7313 ;; No more hops needed.
7314 (setq choices nil)
7315 ;; Replace placeholders.
7316 (setq proxy
7317 (format-spec
7318 proxy
7319 (format-spec-make
7320 ?u (or (tramp-file-name-user (car target-alist)) "")
7321 ?h (or (tramp-file-name-host (car target-alist)) ""))))
7322 (with-parsed-tramp-file-name proxy l
7323 ;; Add the hop.
7324 (add-to-list 'target-alist l)
7325 ;; Start next search.
7326 (setq choices tramp-default-proxies-alist)))))
7328 ;; Handle gateways.
7329 (when (and (boundp 'tramp-gw-tunnel-method)
7330 (string-match (format
7331 "^\\(%s\\|%s\\)$"
7332 (symbol-value 'tramp-gw-tunnel-method)
7333 (symbol-value 'tramp-gw-socks-method))
7334 (tramp-file-name-method (car target-alist))))
7335 (let ((gw (pop target-alist))
7336 (hop (pop target-alist)))
7337 ;; Is the method prepared for gateways?
7338 (unless (tramp-get-method-parameter
7339 (tramp-file-name-method hop) 'tramp-default-port)
7340 (tramp-error
7341 vec 'file-error
7342 "Method `%s' is not supported for gateway access."
7343 (tramp-file-name-method hop)))
7344 ;; Add default port if needed.
7345 (unless
7346 (string-match
7347 tramp-host-with-port-regexp (tramp-file-name-host hop))
7348 (aset hop 2
7349 (concat
7350 (tramp-file-name-host hop) tramp-prefix-port-format
7351 (number-to-string
7352 (tramp-get-method-parameter
7353 (tramp-file-name-method hop) 'tramp-default-port)))))
7354 ;; Open the gateway connection.
7355 (add-to-list
7356 'target-alist
7357 (vector
7358 (tramp-file-name-method hop) (tramp-file-name-user hop)
7359 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil))
7360 ;; For the password prompt, we need the correct values.
7361 ;; Therefore, we must remember the gateway vector. But we
7362 ;; cannot do it as connection property, because it shouldn't
7363 ;; be persistent. And we have no started process yet either.
7364 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7366 ;; Foreign and out-of-band methods are not supported for multi-hops.
7367 (when (cdr target-alist)
7368 (setq choices target-alist)
7369 (while choices
7370 (setq item (pop choices))
7371 (when
7373 (not
7374 (tramp-get-method-parameter
7375 (tramp-file-name-method item) 'tramp-login-program))
7376 (tramp-get-method-parameter
7377 (tramp-file-name-method item) 'tramp-copy-program))
7378 (tramp-error
7379 vec 'file-error
7380 "Method `%s' is not supported for multi-hops."
7381 (tramp-file-name-method item)))))
7383 ;; In case the host name is not used for the remote shell
7384 ;; command, the user could be misguided by applying a random
7385 ;; hostname.
7386 (let* ((v (car target-alist))
7387 (method (tramp-file-name-method v))
7388 (host (tramp-file-name-host v)))
7389 (unless
7391 ;; There are multi-hops.
7392 (cdr target-alist)
7393 ;; The host name is used for the remote shell command.
7394 (member
7395 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7396 ;; The host is local. We cannot use `tramp-local-host-p'
7397 ;; here, because it opens a connection as well.
7398 (string-match tramp-local-host-regexp host))
7399 (tramp-error
7400 v 'file-error
7401 "Host `%s' looks like a remote host, `%s' can only use the local host"
7402 host method)))
7404 ;; Result.
7405 target-alist))
7407 (defun tramp-maybe-open-connection (vec)
7408 "Maybe open a connection VEC.
7409 Does not do anything if a connection is already open, but re-opens the
7410 connection if a previous connection has died for some reason."
7411 (catch 'uname-changed
7412 (let ((p (tramp-get-connection-process vec))
7413 (process-name (tramp-get-connection-property vec "process-name" nil))
7414 (process-environment (copy-sequence process-environment)))
7416 ;; If too much time has passed since last command was sent, look
7417 ;; whether process is still alive. If it isn't, kill it. When
7418 ;; using ssh, it can sometimes happen that the remote end has
7419 ;; hung up but the local ssh client doesn't recognize this until
7420 ;; it tries to send some data to the remote end. So that's why
7421 ;; we try to send a command from time to time, then look again
7422 ;; whether the process is really alive.
7423 (condition-case nil
7424 (when (and (> (tramp-time-diff
7425 (current-time)
7426 (tramp-get-connection-property
7427 p "last-cmd-time" '(0 0 0)))
7429 p (processp p) (memq (process-status p) '(run open)))
7430 (tramp-send-command vec "echo are you awake" t t)
7431 (unless (and (memq (process-status p) '(run open))
7432 (tramp-wait-for-output p 10))
7433 ;; The error will be catched locally.
7434 (tramp-error vec 'file-error "Awake did fail")))
7435 (file-error
7436 (tramp-flush-connection-property vec)
7437 (tramp-flush-connection-property p)
7438 (delete-process p)
7439 (setq p nil)))
7441 ;; New connection must be opened.
7442 (unless (and p (processp p) (memq (process-status p) '(run open)))
7444 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7445 ;; messages from the beginning.
7446 (tramp-get-buffer vec)
7447 (with-progress-reporter
7448 vec 3
7449 (if (zerop (length (tramp-file-name-user vec)))
7450 (format "Opening connection for %s using %s"
7451 (tramp-file-name-host vec)
7452 (tramp-file-name-method vec))
7453 (format "Opening connection for %s@%s using %s"
7454 (tramp-file-name-user vec)
7455 (tramp-file-name-host vec)
7456 (tramp-file-name-method vec)))
7458 ;; Start new process.
7459 (when (and p (processp p))
7460 (delete-process p))
7461 (setenv "TERM" tramp-terminal-type)
7462 (setenv "LC_ALL" "C")
7463 (setenv "PROMPT_COMMAND")
7464 (setenv "PS1" tramp-initial-end-of-output)
7465 (let* ((target-alist (tramp-compute-multi-hops vec))
7466 (process-connection-type tramp-process-connection-type)
7467 (process-adaptive-read-buffering nil)
7468 (coding-system-for-read nil)
7469 ;; This must be done in order to avoid our file name handler.
7470 (p (let ((default-directory
7471 (tramp-compat-temporary-file-directory)))
7472 (start-process
7473 (or process-name (tramp-buffer-name vec))
7474 (tramp-get-connection-buffer vec)
7475 tramp-encoding-shell))))
7477 (tramp-message
7478 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7480 ;; Check whether process is alive.
7481 (tramp-set-process-query-on-exit-flag p nil)
7482 (tramp-barf-if-no-shell-prompt
7483 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7485 ;; Now do all the connections as specified.
7486 (while target-alist
7487 (let* ((hop (car target-alist))
7488 (l-method (tramp-file-name-method hop))
7489 (l-user (tramp-file-name-user hop))
7490 (l-host (tramp-file-name-host hop))
7491 (l-port nil)
7492 (login-program
7493 (tramp-get-method-parameter
7494 l-method 'tramp-login-program))
7495 (login-args
7496 (tramp-get-method-parameter l-method 'tramp-login-args))
7497 (async-args
7498 (tramp-get-method-parameter l-method 'tramp-async-args))
7499 (gw-args
7500 (tramp-get-method-parameter l-method 'tramp-gw-args))
7501 (gw (tramp-get-file-property hop "" "gateway" nil))
7502 (g-method (and gw (tramp-file-name-method gw)))
7503 (g-user (and gw (tramp-file-name-user gw)))
7504 (g-host (and gw (tramp-file-name-host gw)))
7505 (command login-program)
7506 ;; We don't create the temporary file. In fact,
7507 ;; it is just a prefix for the ControlPath option
7508 ;; of ssh; the real temporary file has another
7509 ;; name, and it is created and protected by ssh.
7510 ;; It is also removed by ssh, when the connection
7511 ;; is closed.
7512 (tmpfile
7513 (tramp-set-connection-property
7514 p "temp-file"
7515 (make-temp-name
7516 (expand-file-name
7517 tramp-temp-name-prefix
7518 (tramp-compat-temporary-file-directory)))))
7519 spec)
7521 ;; Add arguments for asynchrononous processes.
7522 (when (and process-name async-args)
7523 (setq login-args (append login-args async-args)))
7525 ;; Add gateway arguments if necessary.
7526 (when (and gw gw-args)
7527 (setq login-args (append login-args gw-args)))
7529 ;; Check for port number. Until now, there's no need
7530 ;; for handling like method, user, host.
7531 (when (string-match tramp-host-with-port-regexp l-host)
7532 (setq l-port (match-string 2 l-host)
7533 l-host (match-string 1 l-host)))
7535 ;; Set variables for computing the prompt for reading
7536 ;; password. They can also be derived from a gateway.
7537 (setq tramp-current-method (or g-method l-method)
7538 tramp-current-user (or g-user l-user)
7539 tramp-current-host (or g-host l-host))
7541 ;; Replace login-args place holders.
7542 (setq
7543 l-host (or l-host "")
7544 l-user (or l-user "")
7545 l-port (or l-port "")
7546 spec (format-spec-make
7547 ?h l-host ?u l-user ?p l-port ?t tmpfile)
7548 command
7549 (concat
7550 ;; We do not want to see the trailing local prompt in
7551 ;; `start-file-process'.
7552 (unless (memq system-type '(windows-nt)) "exec ")
7553 command " "
7554 (mapconcat
7555 (lambda (x)
7556 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7557 (unless (member "" x) (mapconcat 'identity x " ")))
7558 login-args " ")
7559 ;; Local shell could be a Windows COMSPEC. It
7560 ;; doesn't know the ";" syntax, but we must exit
7561 ;; always for `start-file-process'. "exec" does not
7562 ;; work either.
7563 (if (memq system-type '(windows-nt)) " && exit || exit")))
7565 ;; Send the command.
7566 (tramp-message vec 3 "Sending command `%s'" command)
7567 (tramp-send-command vec command t t)
7568 (tramp-process-actions p vec tramp-actions-before-shell 60)
7569 (tramp-message
7570 vec 3 "Found remote shell prompt on `%s'" l-host))
7571 ;; Next hop.
7572 (setq target-alist (cdr target-alist)))
7574 ;; Make initial shell settings.
7575 (tramp-open-connection-setup-interactive-shell p vec)))))))
7577 (defun tramp-send-command (vec command &optional neveropen nooutput)
7578 "Send the COMMAND to connection VEC.
7579 Erases temporary buffer before sending the command. If optional
7580 arg NEVEROPEN is non-nil, never try to open the connection. This
7581 is meant to be used from `tramp-maybe-open-connection' only. The
7582 function waits for output unless NOOUTPUT is set."
7583 (unless neveropen (tramp-maybe-open-connection vec))
7584 (let ((p (tramp-get-connection-process vec)))
7585 (when (tramp-get-connection-property p "remote-echo" nil)
7586 ;; We mark the command string that it can be erased in the output buffer.
7587 (tramp-set-connection-property p "check-remote-echo" t)
7588 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7589 (tramp-message vec 6 "%s" command)
7590 (tramp-send-string vec command)
7591 (unless nooutput (tramp-wait-for-output p))))
7593 (defun tramp-wait-for-output (proc &optional timeout)
7594 "Wait for output from remote command."
7595 (unless (buffer-live-p (process-buffer proc))
7596 (delete-process proc)
7597 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7598 (with-current-buffer (process-buffer proc)
7599 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7600 ;; be leading escape sequences, which must be ignored.
7601 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7602 ;; Sometimes, the commands do not return a newline but a
7603 ;; null byte before the shell prompt, for example "git
7604 ;; ls-files -c -z ...".
7605 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7606 (found (tramp-wait-for-regexp proc timeout regexp1)))
7607 (if found
7608 (let (buffer-read-only)
7609 ;; A simple-minded busybox has sent " ^H" sequences.
7610 ;; Delete them.
7611 (goto-char (point-min))
7612 (when (re-search-forward
7613 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7614 (forward-line 1)
7615 (delete-region (point-min) (point)))
7616 ;; Delete the prompt.
7617 (goto-char (point-max))
7618 (re-search-backward regexp nil t)
7619 (delete-region (point) (point-max)))
7620 (if timeout
7621 (tramp-error
7622 proc 'file-error
7623 "[[Remote prompt `%s' not found in %d secs]]"
7624 tramp-end-of-output timeout)
7625 (tramp-error
7626 proc 'file-error
7627 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7628 ;; Return value is whether end-of-output sentinel was found.
7629 found)))
7631 (defun tramp-send-command-and-check
7632 (vec command &optional subshell dont-suppress-err)
7633 "Run COMMAND and check its exit status.
7634 Sends `echo $?' along with the COMMAND for checking the exit status. If
7635 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7637 If the optional argument SUBSHELL is non-nil, the command is
7638 executed in a subshell, ie surrounded by parentheses. If
7639 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7640 (tramp-send-command
7642 (concat (if subshell "( " "")
7643 command
7644 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7645 "echo tramp_exit_status $?"
7646 (if subshell " )" "")))
7647 (with-current-buffer (tramp-get-connection-buffer vec)
7648 (goto-char (point-max))
7649 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7650 (tramp-error
7651 vec 'file-error "Couldn't find exit status of `%s'" command))
7652 (skip-chars-forward "^ ")
7653 (prog1
7654 (read (current-buffer))
7655 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7657 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7658 "Run COMMAND, check exit status, throw error if exit status not okay.
7659 Similar to `tramp-send-command-and-check' but accepts two more arguments
7660 FMT and ARGS which are passed to `error'."
7661 (unless (zerop (tramp-send-command-and-check vec command))
7662 (apply 'tramp-error vec 'file-error fmt args)))
7664 (defun tramp-send-command-and-read (vec command)
7665 "Run COMMAND and return the output, which must be a Lisp expression.
7666 In case there is no valid Lisp expression, it raises an error"
7667 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7668 (with-current-buffer (tramp-get-connection-buffer vec)
7669 ;; Read the expression.
7670 (goto-char (point-min))
7671 (condition-case nil
7672 (prog1 (read (current-buffer))
7673 ;; Error handling.
7674 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7675 (error nil)))
7676 (error (tramp-error
7677 vec 'file-error
7678 "`%s' does not return a valid Lisp expression: `%s'"
7679 command (buffer-string))))))
7681 ;; It seems that Tru64 Unix does not like it if long strings are sent
7682 ;; to it in one go. (This happens when sending the Perl
7683 ;; `file-attributes' implementation, for instance.) Therefore, we
7684 ;; have this function which sends the string in chunks.
7685 (defun tramp-send-string (vec string)
7686 "Send the STRING via connection VEC.
7688 The STRING is expected to use Unix line-endings, but the lines sent to
7689 the remote host use line-endings as defined in the variable
7690 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7691 (let* ((p (tramp-get-connection-process vec))
7692 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7693 (unless p
7694 (tramp-error
7695 vec 'file-error "Can't send string to remote host -- not logged in"))
7696 (tramp-set-connection-property p "last-cmd-time" (current-time))
7697 (tramp-message vec 10 "%s" string)
7698 (with-current-buffer (tramp-get-connection-buffer vec)
7699 ;; Clean up the buffer. We cannot call `erase-buffer' because
7700 ;; narrowing might be in effect.
7701 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7702 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7703 (setq string
7704 (mapconcat 'identity
7705 (tramp-compat-split-string string "\n")
7706 tramp-rsh-end-of-line))
7707 (unless (or (string= string "")
7708 (string-equal (substring string -1) tramp-rsh-end-of-line))
7709 (setq string (concat string tramp-rsh-end-of-line)))
7710 ;; Send the string.
7711 (if (and chunksize (not (zerop chunksize)))
7712 (let ((pos 0)
7713 (end (length string)))
7714 (while (< pos end)
7715 (tramp-message
7716 vec 10 "Sending chunk from %s to %s"
7717 pos (min (+ pos chunksize) end))
7718 (process-send-string
7719 p (substring string pos (min (+ pos chunksize) end)))
7720 (setq pos (+ pos chunksize))))
7721 (process-send-string p string)))))
7723 (defun tramp-mode-string-to-int (mode-string)
7724 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7725 (let* (case-fold-search
7726 (mode-chars (string-to-vector mode-string))
7727 (owner-read (aref mode-chars 1))
7728 (owner-write (aref mode-chars 2))
7729 (owner-execute-or-setid (aref mode-chars 3))
7730 (group-read (aref mode-chars 4))
7731 (group-write (aref mode-chars 5))
7732 (group-execute-or-setid (aref mode-chars 6))
7733 (other-read (aref mode-chars 7))
7734 (other-write (aref mode-chars 8))
7735 (other-execute-or-sticky (aref mode-chars 9)))
7736 (save-match-data
7737 (logior
7738 (cond
7739 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7740 ((char-equal owner-read ?-) 0)
7741 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7742 (cond
7743 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7744 ((char-equal owner-write ?-) 0)
7745 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7746 (cond
7747 ((char-equal owner-execute-or-setid ?x)
7748 (tramp-octal-to-decimal "00100"))
7749 ((char-equal owner-execute-or-setid ?S)
7750 (tramp-octal-to-decimal "04000"))
7751 ((char-equal owner-execute-or-setid ?s)
7752 (tramp-octal-to-decimal "04100"))
7753 ((char-equal owner-execute-or-setid ?-) 0)
7754 (t (error "Fourth char `%c' must be one of `xsS-'"
7755 owner-execute-or-setid)))
7756 (cond
7757 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7758 ((char-equal group-read ?-) 0)
7759 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7760 (cond
7761 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7762 ((char-equal group-write ?-) 0)
7763 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7764 (cond
7765 ((char-equal group-execute-or-setid ?x)
7766 (tramp-octal-to-decimal "00010"))
7767 ((char-equal group-execute-or-setid ?S)
7768 (tramp-octal-to-decimal "02000"))
7769 ((char-equal group-execute-or-setid ?s)
7770 (tramp-octal-to-decimal "02010"))
7771 ((char-equal group-execute-or-setid ?-) 0)
7772 (t (error "Seventh char `%c' must be one of `xsS-'"
7773 group-execute-or-setid)))
7774 (cond
7775 ((char-equal other-read ?r)
7776 (tramp-octal-to-decimal "00004"))
7777 ((char-equal other-read ?-) 0)
7778 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7779 (cond
7780 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7781 ((char-equal other-write ?-) 0)
7782 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7783 (cond
7784 ((char-equal other-execute-or-sticky ?x)
7785 (tramp-octal-to-decimal "00001"))
7786 ((char-equal other-execute-or-sticky ?T)
7787 (tramp-octal-to-decimal "01000"))
7788 ((char-equal other-execute-or-sticky ?t)
7789 (tramp-octal-to-decimal "01001"))
7790 ((char-equal other-execute-or-sticky ?-) 0)
7791 (t (error "Tenth char `%c' must be one of `xtT-'"
7792 other-execute-or-sticky)))))))
7794 (defun tramp-convert-file-attributes (vec attr)
7795 "Convert file-attributes ATTR generated by perl script, stat or ls.
7796 Convert file mode bits to string and set virtual device number.
7797 Return ATTR."
7798 (when attr
7799 ;; Convert last access time.
7800 (unless (listp (nth 4 attr))
7801 (setcar (nthcdr 4 attr)
7802 (list (floor (nth 4 attr) 65536)
7803 (floor (mod (nth 4 attr) 65536)))))
7804 ;; Convert last modification time.
7805 (unless (listp (nth 5 attr))
7806 (setcar (nthcdr 5 attr)
7807 (list (floor (nth 5 attr) 65536)
7808 (floor (mod (nth 5 attr) 65536)))))
7809 ;; Convert last status change time.
7810 (unless (listp (nth 6 attr))
7811 (setcar (nthcdr 6 attr)
7812 (list (floor (nth 6 attr) 65536)
7813 (floor (mod (nth 6 attr) 65536)))))
7814 ;; Convert file size.
7815 (when (< (nth 7 attr) 0)
7816 (setcar (nthcdr 7 attr) -1))
7817 (when (and (floatp (nth 7 attr))
7818 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7819 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7820 ;; Convert file mode bits to string.
7821 (unless (stringp (nth 8 attr))
7822 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7823 (when (stringp (car attr))
7824 (aset (nth 8 attr) 0 ?l)))
7825 ;; Convert directory indication bit.
7826 (when (string-match "^d" (nth 8 attr))
7827 (setcar attr t))
7828 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7829 (when (consp (car attr))
7830 (if (and (stringp (caar attr))
7831 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7832 (setcar attr (match-string 1 (caar attr)))
7833 (setcar attr nil)))
7834 ;; Set file's gid change bit.
7835 (setcar (nthcdr 9 attr)
7836 (if (numberp (nth 3 attr))
7837 (not (= (nth 3 attr)
7838 (tramp-get-remote-gid vec 'integer)))
7839 (not (string-equal
7840 (nth 3 attr)
7841 (tramp-get-remote-gid vec 'string)))))
7842 ;; Convert inode.
7843 (unless (listp (nth 10 attr))
7844 (setcar (nthcdr 10 attr)
7845 (condition-case nil
7846 (cons (floor (nth 10 attr) 65536)
7847 (floor (mod (nth 10 attr) 65536)))
7848 ;; Inodes can be incredible huge. We must hide this.
7849 (error (tramp-get-inode vec)))))
7850 ;; Set virtual device number.
7851 (setcar (nthcdr 11 attr)
7852 (tramp-get-device vec))
7853 attr))
7855 (defun tramp-check-cached-permissions (vec access)
7856 "Check `file-attributes' caches for VEC.
7857 Return t if according to the cache access type ACCESS is known to
7858 be granted."
7859 (let ((result nil)
7860 (offset (cond
7861 ((eq ?r access) 1)
7862 ((eq ?w access) 2)
7863 ((eq ?x access) 3))))
7864 (dolist (suffix '("string" "integer") result)
7865 (setq
7866 result
7868 result
7869 (let ((file-attr
7870 (tramp-get-file-property
7871 vec (tramp-file-name-localname vec)
7872 (concat "file-attributes-" suffix) nil))
7873 (remote-uid
7874 (tramp-get-connection-property
7875 vec (concat "uid-" suffix) nil))
7876 (remote-gid
7877 (tramp-get-connection-property
7878 vec (concat "gid-" suffix) nil)))
7879 (and
7880 file-attr
7882 ;; Not a symlink
7883 (eq t (car file-attr))
7884 (null (car file-attr)))
7886 ;; World accessible.
7887 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7888 ;; User accessible and owned by user.
7889 (and
7890 (eq access (aref (nth 8 file-attr) offset))
7891 (equal remote-uid (nth 2 file-attr)))
7892 ;; Group accessible and owned by user's
7893 ;; principal group.
7894 (and
7895 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7896 (equal remote-gid (nth 3 file-attr)))))))))))
7898 (defun tramp-get-inode (vec)
7899 "Returns the virtual inode number.
7900 If it doesn't exist, generate a new one."
7901 (let ((string (tramp-make-tramp-file-name
7902 (tramp-file-name-method vec)
7903 (tramp-file-name-user vec)
7904 (tramp-file-name-host vec)
7905 "")))
7906 (unless (assoc string tramp-inodes)
7907 (add-to-list 'tramp-inodes
7908 (list string (length tramp-inodes))))
7909 (nth 1 (assoc string tramp-inodes))))
7911 (defun tramp-get-device (vec)
7912 "Returns the virtual device number.
7913 If it doesn't exist, generate a new one."
7914 (let ((string (tramp-make-tramp-file-name
7915 (tramp-file-name-method vec)
7916 (tramp-file-name-user vec)
7917 (tramp-file-name-host vec)
7918 "")))
7919 (unless (assoc string tramp-devices)
7920 (add-to-list 'tramp-devices
7921 (list string (length tramp-devices))))
7922 (cons -1 (nth 1 (assoc string tramp-devices)))))
7924 (defun tramp-file-mode-from-int (mode)
7925 "Turn an integer representing a file mode into an ls(1)-like string."
7926 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7927 (user (logand (lsh mode -6) 7))
7928 (group (logand (lsh mode -3) 7))
7929 (other (logand (lsh mode -0) 7))
7930 (suid (> (logand (lsh mode -9) 4) 0))
7931 (sgid (> (logand (lsh mode -9) 2) 0))
7932 (sticky (> (logand (lsh mode -9) 1) 0)))
7933 (setq user (tramp-file-mode-permissions user suid "s"))
7934 (setq group (tramp-file-mode-permissions group sgid "s"))
7935 (setq other (tramp-file-mode-permissions other sticky "t"))
7936 (concat type user group other)))
7938 (defun tramp-file-mode-permissions (perm suid suid-text)
7939 "Convert a permission bitset into a string.
7940 This is used internally by `tramp-file-mode-from-int'."
7941 (let ((r (> (logand perm 4) 0))
7942 (w (> (logand perm 2) 0))
7943 (x (> (logand perm 1) 0)))
7944 (concat (or (and r "r") "-")
7945 (or (and w "w") "-")
7946 (or (and suid x suid-text) ; suid, execute
7947 (and suid (upcase suid-text)) ; suid, !execute
7948 (and x "x") "-")))) ; !suid
7950 (defun tramp-decimal-to-octal (i)
7951 "Return a string consisting of the octal digits of I.
7952 Not actually used. Use `(format \"%o\" i)' instead?"
7953 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7954 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7955 ((zerop i) "0")
7956 (t (concat (tramp-decimal-to-octal (/ i 8))
7957 (number-to-string (% i 8))))))
7959 ;; Kudos to Gerd Moellmann for this suggestion.
7960 (defun tramp-octal-to-decimal (ostr)
7961 "Given a string of octal digits, return a decimal number."
7962 (let ((x (or ostr "")))
7963 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7964 (unless (string-match "\\`[0-7]*\\'" x)
7965 (error "Non-octal junk in string `%s'" x))
7966 (string-to-number ostr 8)))
7968 (defun tramp-shell-case-fold (string)
7969 "Converts STRING to shell glob pattern which ignores case."
7970 (mapconcat
7971 (lambda (c)
7972 (if (equal (downcase c) (upcase c))
7973 (vector c)
7974 (format "[%c%c]" (downcase c) (upcase c))))
7975 string
7976 ""))
7979 ;; ------------------------------------------------------------
7980 ;; -- Tramp file names --
7981 ;; ------------------------------------------------------------
7982 ;; Conversion functions between external representation and
7983 ;; internal data structure. Convenience functions for internal
7984 ;; data structure.
7986 (defun tramp-file-name-p (vec)
7987 "Check, whether VEC is a Tramp object."
7988 (and (vectorp vec) (= 4 (length vec))))
7990 (defun tramp-file-name-method (vec)
7991 "Return method component of VEC."
7992 (and (tramp-file-name-p vec) (aref vec 0)))
7994 (defun tramp-file-name-user (vec)
7995 "Return user component of VEC."
7996 (and (tramp-file-name-p vec) (aref vec 1)))
7998 (defun tramp-file-name-host (vec)
7999 "Return host component of VEC."
8000 (and (tramp-file-name-p vec) (aref vec 2)))
8002 (defun tramp-file-name-localname (vec)
8003 "Return localname component of VEC."
8004 (and (tramp-file-name-p vec) (aref vec 3)))
8006 ;; The user part of a Tramp file name vector can be of kind
8007 ;; "user%domain". Sometimes, we must extract these parts.
8008 (defun tramp-file-name-real-user (vec)
8009 "Return the user name of VEC without domain."
8010 (save-match-data
8011 (let ((user (tramp-file-name-user vec)))
8012 (if (and (stringp user)
8013 (string-match tramp-user-with-domain-regexp user))
8014 (match-string 1 user)
8015 user))))
8017 (defun tramp-file-name-domain (vec)
8018 "Return the domain name of VEC."
8019 (save-match-data
8020 (let ((user (tramp-file-name-user vec)))
8021 (and (stringp user)
8022 (string-match tramp-user-with-domain-regexp user)
8023 (match-string 2 user)))))
8025 ;; The host part of a Tramp file name vector can be of kind
8026 ;; "host#port". Sometimes, we must extract these parts.
8027 (defun tramp-file-name-real-host (vec)
8028 "Return the host name of VEC without port."
8029 (save-match-data
8030 (let ((host (tramp-file-name-host vec)))
8031 (if (and (stringp host)
8032 (string-match tramp-host-with-port-regexp host))
8033 (match-string 1 host)
8034 host))))
8036 (defun tramp-file-name-port (vec)
8037 "Return the port number of VEC."
8038 (save-match-data
8039 (let ((host (tramp-file-name-host vec)))
8040 (and (stringp host)
8041 (string-match tramp-host-with-port-regexp host)
8042 (string-to-number (match-string 2 host))))))
8044 (defun tramp-tramp-file-p (name)
8045 "Return t if NAME is a string with Tramp file name syntax."
8046 (save-match-data
8047 (and (stringp name) (string-match tramp-file-name-regexp name))))
8049 (defun tramp-find-method (method user host)
8050 "Return the right method string to use.
8051 This is METHOD, if non-nil. Otherwise, do a lookup in
8052 `tramp-default-method-alist'."
8053 (or method
8054 (let ((choices tramp-default-method-alist)
8055 lmethod item)
8056 (while choices
8057 (setq item (pop choices))
8058 (when (and (string-match (or (nth 0 item) "") (or host ""))
8059 (string-match (or (nth 1 item) "") (or user "")))
8060 (setq lmethod (nth 2 item))
8061 (setq choices nil)))
8062 lmethod)
8063 tramp-default-method))
8065 (defun tramp-find-user (method user host)
8066 "Return the right user string to use.
8067 This is USER, if non-nil. Otherwise, do a lookup in
8068 `tramp-default-user-alist'."
8069 (or user
8070 (let ((choices tramp-default-user-alist)
8071 luser item)
8072 (while choices
8073 (setq item (pop choices))
8074 (when (and (string-match (or (nth 0 item) "") (or method ""))
8075 (string-match (or (nth 1 item) "") (or host "")))
8076 (setq luser (nth 2 item))
8077 (setq choices nil)))
8078 luser)
8079 tramp-default-user))
8081 (defun tramp-find-host (method user host)
8082 "Return the right host string to use.
8083 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
8084 (or (and (> (length host) 0) host)
8085 tramp-default-host))
8087 (defun tramp-dissect-file-name (name &optional nodefault)
8088 "Return a `tramp-file-name' structure.
8089 The structure consists of remote method, remote user, remote host
8090 and localname (file name on remote host). If NODEFAULT is
8091 non-nil, the file name parts are not expanded to their default
8092 values."
8093 (save-match-data
8094 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
8095 (unless match (error "Not a Tramp file name: %s" name))
8096 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
8097 (user (match-string (nth 2 tramp-file-name-structure) name))
8098 (host (match-string (nth 3 tramp-file-name-structure) name))
8099 (localname (match-string (nth 4 tramp-file-name-structure) name)))
8100 (when (member method '("multi" "multiu"))
8101 (error
8102 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
8103 method))
8104 (when host
8105 (when (string-match tramp-prefix-ipv6-regexp host)
8106 (setq host (replace-match "" nil t host)))
8107 (when (string-match tramp-postfix-ipv6-regexp host)
8108 (setq host (replace-match "" nil t host))))
8109 (if nodefault
8110 (vector method user host localname)
8111 (vector
8112 (tramp-find-method method user host)
8113 (tramp-find-user method user host)
8114 (tramp-find-host method user host)
8115 localname))))))
8117 (defun tramp-equal-remote (file1 file2)
8118 "Check, whether the remote parts of FILE1 and FILE2 are identical.
8119 The check depends on method, user and host name of the files. If
8120 one of the components is missing, the default values are used.
8121 The local file name parts of FILE1 and FILE2 are not taken into
8122 account.
8124 Example:
8126 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
8128 would yield `t'. On the other hand, the following check results in nil:
8130 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
8131 (and (stringp (file-remote-p file1))
8132 (stringp (file-remote-p file2))
8133 (string-equal (file-remote-p file1) (file-remote-p file2))))
8135 (defun tramp-make-tramp-file-name (method user host localname)
8136 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
8137 (concat tramp-prefix-format
8138 (when (not (zerop (length method)))
8139 (concat method tramp-postfix-method-format))
8140 (when (not (zerop (length user)))
8141 (concat user tramp-postfix-user-format))
8142 (when host
8143 (if (string-match tramp-ipv6-regexp host)
8144 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8145 host))
8146 tramp-postfix-host-format
8147 (when localname localname)))
8149 (defun tramp-completion-make-tramp-file-name (method user host localname)
8150 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
8151 It must not be a complete Tramp file name, but as long as there are
8152 necessary only. This function will be used in file name completion."
8153 (concat tramp-prefix-format
8154 (when (not (zerop (length method)))
8155 (concat method tramp-postfix-method-format))
8156 (when (not (zerop (length user)))
8157 (concat user tramp-postfix-user-format))
8158 (when (not (zerop (length host)))
8159 (concat
8160 (if (string-match tramp-ipv6-regexp host)
8161 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8162 host)
8163 tramp-postfix-host-format))
8164 (when localname localname)))
8166 (defun tramp-make-copy-program-file-name (vec)
8167 "Create a file name suitable to be passed to `rcp' and workalikes."
8168 (let ((user (tramp-file-name-user vec))
8169 (host (tramp-file-name-real-host vec))
8170 (localname (tramp-shell-quote-argument
8171 (tramp-file-name-localname vec))))
8172 (if (not (zerop (length user)))
8173 (format "%s@%s:%s" user host localname)
8174 (format "%s:%s" host localname))))
8176 (defun tramp-method-out-of-band-p (vec size)
8177 "Return t if this is an out-of-band method, nil otherwise."
8178 (and
8179 ;; It shall be an out-of-band method.
8180 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
8181 ;; Either the file size is large enough, or (in rare cases) there
8182 ;; does not exist a remote encoding.
8183 (or (null tramp-copy-size-limit)
8184 (> size tramp-copy-size-limit)
8185 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
8187 (defun tramp-local-host-p (vec)
8188 "Return t if this points to the local host, nil otherwise."
8189 ;; We cannot use `tramp-file-name-real-host'. A port is an
8190 ;; indication for an ssh tunnel or alike.
8191 (let ((host (tramp-file-name-host vec)))
8192 (and
8193 (stringp host)
8194 (string-match tramp-local-host-regexp host)
8195 ;; The method shall be applied to one of the shell file name
8196 ;; handler. `tramp-local-host-p' is also called for "smb" and
8197 ;; alike, where it must fail.
8198 (tramp-get-method-parameter
8199 (tramp-file-name-method vec) 'tramp-login-program)
8200 ;; The local temp directory must be writable for the other user.
8201 (file-writable-p
8202 (tramp-make-tramp-file-name
8203 (tramp-file-name-method vec)
8204 (tramp-file-name-user vec)
8205 host
8206 (tramp-compat-temporary-file-directory)))
8207 ;; On some systems, chown runs only for root.
8208 (or (zerop (user-uid))
8209 (zerop (tramp-get-remote-uid vec 'integer))))))
8211 ;; Variables local to connection.
8213 (defun tramp-get-remote-path (vec)
8214 (with-connection-property
8215 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8216 ;; cache the result for the session only. Otherwise, the result
8217 ;; is cached persistently.
8218 (if (memq 'tramp-own-remote-path tramp-remote-path)
8219 (tramp-get-connection-process vec)
8220 vec)
8221 "remote-path"
8222 (let* ((remote-path (copy-tree tramp-remote-path))
8223 (elt1 (memq 'tramp-default-remote-path remote-path))
8224 (elt2 (memq 'tramp-own-remote-path remote-path))
8225 (default-remote-path
8226 (when elt1
8227 (condition-case nil
8228 (tramp-send-command-and-read
8229 vec "echo \\\"`getconf PATH`\\\"")
8230 ;; Default if "getconf" is not available.
8231 (error
8232 (tramp-message
8233 vec 3
8234 "`getconf PATH' not successful, using default value \"%s\"."
8235 "/bin:/usr/bin")
8236 "/bin:/usr/bin"))))
8237 (own-remote-path
8238 (when elt2
8239 (condition-case nil
8240 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8241 ;; Default if "getconf" is not available.
8242 (error
8243 (tramp-message
8244 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8245 nil)))))
8247 ;; Replace place holder `tramp-default-remote-path'.
8248 (when elt1
8249 (setcdr elt1
8250 (append
8251 (tramp-compat-split-string default-remote-path ":")
8252 (cdr elt1)))
8253 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8255 ;; Replace place holder `tramp-own-remote-path'.
8256 (when elt2
8257 (setcdr elt2
8258 (append
8259 (tramp-compat-split-string own-remote-path ":")
8260 (cdr elt2)))
8261 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8263 ;; Remove double entries.
8264 (setq elt1 remote-path)
8265 (while (consp elt1)
8266 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8267 (setcar elt2 nil))
8268 (setq elt1 (cdr elt1)))
8270 ;; Remove non-existing directories.
8271 (delq
8273 (mapcar
8274 (lambda (x)
8275 (and
8276 (stringp x)
8277 (file-directory-p
8278 (tramp-make-tramp-file-name
8279 (tramp-file-name-method vec)
8280 (tramp-file-name-user vec)
8281 (tramp-file-name-host vec)
8284 remote-path)))))
8286 (defun tramp-get-remote-tmpdir (vec)
8287 (with-connection-property vec "tmp-directory"
8288 (let ((dir (tramp-shell-quote-argument "/tmp")))
8289 (if (and (zerop
8290 (tramp-send-command-and-check
8291 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8292 (zerop
8293 (tramp-send-command-and-check
8294 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8296 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8298 (defun tramp-get-ls-command (vec)
8299 (with-connection-property vec "ls"
8300 (tramp-message vec 5 "Finding a suitable `ls' command")
8302 (catch 'ls-found
8303 (dolist (cmd '("ls" "gnuls" "gls"))
8304 (let ((dl (tramp-get-remote-path vec))
8305 result)
8306 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8307 ;; Check parameters. On busybox, "ls" output coloring is
8308 ;; enabled by default sometimes. So we try to disable it
8309 ;; when possible. $LS_COLORING is not supported there.
8310 (when (zerop (tramp-send-command-and-check
8311 vec (format "%s -lnd /" result)))
8312 (when (zerop (tramp-send-command-and-check
8313 vec (format "%s --color=never /" result)))
8314 (setq result (concat result " --color=never")))
8315 (throw 'ls-found result))
8316 (setq dl (cdr dl))))))
8317 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8319 (defun tramp-get-ls-command-with-dired (vec)
8320 (save-match-data
8321 (with-connection-property vec "ls-dired"
8322 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8323 (zerop (tramp-send-command-and-check
8324 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8326 (defun tramp-get-test-command (vec)
8327 (with-connection-property vec "test"
8328 (tramp-message vec 5 "Finding a suitable `test' command")
8329 (if (zerop (tramp-send-command-and-check vec "test 0"))
8330 "test"
8331 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8333 (defun tramp-get-test-nt-command (vec)
8334 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8335 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8336 ;; for otherwise the shell crashes.
8337 (with-connection-property vec "test-nt"
8339 (progn
8340 (tramp-send-command
8341 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8342 (with-current-buffer (tramp-get-buffer vec)
8343 (goto-char (point-min))
8344 (when (looking-at (regexp-quote tramp-end-of-output))
8345 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8346 (progn
8347 (tramp-send-command
8349 (format
8350 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8351 (tramp-get-test-command vec)))
8352 "tramp_test_nt %s %s"))))
8354 (defun tramp-get-file-exists-command (vec)
8355 (with-connection-property vec "file-exists"
8356 (tramp-message vec 5 "Finding command to check if file exists")
8357 (tramp-find-file-exists-command vec)))
8359 (defun tramp-get-remote-ln (vec)
8360 (with-connection-property vec "ln"
8361 (tramp-message vec 5 "Finding a suitable `ln' command")
8362 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8364 (defun tramp-get-remote-perl (vec)
8365 (with-connection-property vec "perl"
8366 (tramp-message vec 5 "Finding a suitable `perl' command")
8367 (let ((result
8368 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8369 (tramp-find-executable
8370 vec "perl" (tramp-get-remote-path vec)))))
8371 ;; We must check also for some Perl modules.
8372 (when result
8373 (with-connection-property vec "perl-file-spec"
8374 (zerop
8375 (tramp-send-command-and-check
8376 vec (format "%s -e 'use File::Spec;'" result))))
8377 (with-connection-property vec "perl-cwd-realpath"
8378 (zerop
8379 (tramp-send-command-and-check
8380 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8381 result)))
8383 (defun tramp-get-remote-stat (vec)
8384 (with-connection-property vec "stat"
8385 (tramp-message vec 5 "Finding a suitable `stat' command")
8386 (let ((result (tramp-find-executable
8387 vec "stat" (tramp-get-remote-path vec)))
8388 tmp)
8389 ;; Check whether stat(1) returns usable syntax. %s does not
8390 ;; work on older AIX systems.
8391 (when result
8392 (setq tmp
8393 ;; We don't want to display an error message.
8394 (with-temp-message (or (current-message) "")
8395 (condition-case nil
8396 (tramp-send-command-and-read
8397 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8398 (error nil))))
8399 (unless (and (listp tmp) (stringp (car tmp))
8400 (string-match "^./.$" (car tmp))
8401 (integerp (cadr tmp)))
8402 (setq result nil)))
8403 result)))
8405 (defun tramp-get-remote-readlink (vec)
8406 (with-connection-property vec "readlink"
8407 (tramp-message vec 5 "Finding a suitable `readlink' command")
8408 (let ((result (tramp-find-executable
8409 vec "readlink" (tramp-get-remote-path vec))))
8410 (when (and result
8411 ;; We don't want to display an error message.
8412 (with-temp-message (or (current-message) "")
8413 (condition-case nil
8414 (zerop
8415 (tramp-send-command-and-check
8416 vec (format "%s --canonicalize-missing /" result)))
8417 (error nil))))
8418 result))))
8420 (defun tramp-get-remote-id (vec)
8421 (with-connection-property vec "id"
8422 (tramp-message vec 5 "Finding POSIX `id' command")
8424 (catch 'id-found
8425 (let ((dl (tramp-get-remote-path vec))
8426 result)
8427 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8428 ;; Check POSIX parameter.
8429 (when (zerop (tramp-send-command-and-check
8430 vec (format "%s -u" result)))
8431 (throw 'id-found result))
8432 (setq dl (cdr dl)))))
8433 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8435 (defun tramp-get-remote-uid (vec id-format)
8436 (with-connection-property vec (format "uid-%s" id-format)
8437 (let ((res (tramp-send-command-and-read
8439 (format "%s -u%s %s"
8440 (tramp-get-remote-id vec)
8441 (if (equal id-format 'integer) "" "n")
8442 (if (equal id-format 'integer)
8443 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8444 ;; The command might not always return a number.
8445 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8447 (defun tramp-get-remote-gid (vec id-format)
8448 (with-connection-property vec (format "gid-%s" id-format)
8449 (let ((res (tramp-send-command-and-read
8451 (format "%s -g%s %s"
8452 (tramp-get-remote-id vec)
8453 (if (equal id-format 'integer) "" "n")
8454 (if (equal id-format 'integer)
8455 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8456 ;; The command might not always return a number.
8457 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8459 (defun tramp-get-local-uid (id-format)
8460 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8462 (defun tramp-get-local-gid (id-format)
8463 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8465 ;; Some predefined connection properties.
8466 (defun tramp-get-inline-compress (vec prop size)
8467 "Return the compress command related to PROP.
8468 PROP is either `inline-compress' or `inline-decompress'. SIZE is
8469 the length of the file to be compressed.
8471 If no corresponding command is found, nil is returned."
8472 (when (and (integerp tramp-inline-compress-start-size)
8473 (> size tramp-inline-compress-start-size))
8474 (with-connection-property vec prop
8475 (tramp-find-inline-compress vec)
8476 (tramp-get-connection-property vec prop nil))))
8478 (defun tramp-get-inline-coding (vec prop size)
8479 "Return the coding command related to PROP.
8480 PROP is either `remote-encoding', `remode-decoding',
8481 `local-encoding' or `local-decoding'.
8483 SIZE is the length of the file to be coded. Depending on SIZE,
8484 compression might be applied.
8486 If no corresponding command is found, nil is returned.
8487 Otherwise, either a string is returned which contains a `%s' mark
8488 to be used for the respective input or output file; or a Lisp
8489 function cell is returned to be applied on a buffer."
8490 (let ((coding
8491 (with-connection-property vec prop
8492 (tramp-find-inline-encoding vec)
8493 (tramp-get-connection-property vec prop nil)))
8494 (prop1 (if (string-match "encoding" prop)
8495 "inline-compress" "inline-decompress"))
8496 compress)
8497 ;; The connection property might have been cached. So we must send
8498 ;; the script to the remote side - maybe.
8499 (when (and coding (symbolp coding) (string-match "remote" prop))
8500 (let ((name (symbol-name coding)))
8501 (while (string-match (regexp-quote "-") name)
8502 (setq name (replace-match "_" nil t name)))
8503 (tramp-maybe-send-script vec (symbol-value coding) name)
8504 (setq coding name)))
8505 (when coding
8506 ;; Check for the `compress' command.
8507 (setq compress (tramp-get-inline-compress vec prop1 size))
8508 ;; Return the value.
8509 (cond
8510 ((and compress (symbolp coding))
8511 (if (string-match "decompress" prop1)
8512 `(lambda (beg end)
8513 (,coding beg end)
8514 (let ((coding-system-for-write 'binary)
8515 (coding-system-for-read 'binary))
8516 (apply
8517 'call-process-region (point-min) (point-max)
8518 (car (split-string ,compress)) t t nil
8519 (cdr (split-string ,compress)))))
8520 `(lambda (beg end)
8521 (let ((coding-system-for-write 'binary)
8522 (coding-system-for-read 'binary))
8523 (apply
8524 'call-process-region beg end
8525 (car (split-string ,compress)) t t nil
8526 (cdr (split-string ,compress))))
8527 (,coding (point-min) (point-max)))))
8528 ((symbolp coding)
8529 coding)
8530 ((and compress (string-match "decoding" prop))
8531 (format "(%s | %s >%%s)" coding compress))
8532 (compress
8533 (format "(%s <%%s | %s)" compress coding))
8534 ((string-match "decoding" prop)
8535 (format "%s >%%s" coding))
8537 (format "%s <%%s" coding))))))
8539 (defun tramp-get-method-parameter (method param)
8540 "Return the method parameter PARAM.
8541 If the `tramp-methods' entry does not exist, return nil."
8542 (let ((entry (assoc param (assoc method tramp-methods))))
8543 (when entry (cadr entry))))
8545 ;; Auto saving to a special directory.
8547 (defun tramp-exists-file-name-handler (operation &rest args)
8548 "Check, whether OPERATION runs a file name handler."
8549 ;; The file name handler is determined on base of either an
8550 ;; argument, `buffer-file-name', or `default-directory'.
8551 (condition-case nil
8552 (let* ((buffer-file-name "/")
8553 (default-directory "/")
8554 (fnha file-name-handler-alist)
8555 (check-file-name-operation operation)
8556 (file-name-handler-alist
8557 (list
8558 (cons "/"
8559 (lambda (operation &rest args)
8560 "Returns OPERATION if it is the one to be checked."
8561 (if (equal check-file-name-operation operation)
8562 operation
8563 (let ((file-name-handler-alist fnha))
8564 (apply operation args))))))))
8565 (equal (apply operation args) operation))
8566 (error nil)))
8568 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8569 (defadvice make-auto-save-file-name
8570 (around tramp-advice-make-auto-save-file-name () activate)
8571 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8572 (if (tramp-tramp-file-p (buffer-file-name))
8573 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8574 ;; directly, because this would bypass the locking mechanism.
8575 (setq ad-return-value
8576 (tramp-file-name-handler 'make-auto-save-file-name))
8577 ad-do-it))
8578 (add-hook
8579 'tramp-unload-hook
8580 (lambda ()
8581 (ad-remove-advice
8582 'make-auto-save-file-name
8583 'around 'tramp-advice-make-auto-save-file-name)
8584 (ad-activate 'make-auto-save-file-name))))
8586 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8587 ;; umask. This is a security threat.
8589 (defun tramp-set-auto-save-file-modes ()
8590 "Set permissions of autosaved remote files to the original permissions."
8591 (let ((bfn (buffer-file-name)))
8592 (when (and (tramp-tramp-file-p bfn)
8593 (buffer-modified-p)
8594 (stringp buffer-auto-save-file-name)
8595 (not (equal bfn buffer-auto-save-file-name)))
8596 (unless (file-exists-p buffer-auto-save-file-name)
8597 (write-region "" nil buffer-auto-save-file-name))
8598 ;; Permissions should be set always, because there might be an old
8599 ;; auto-saved file belonging to another original file. This could
8600 ;; be a security threat.
8601 (set-file-modes buffer-auto-save-file-name
8602 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8604 (unless (and (featurep 'xemacs)
8605 (= emacs-major-version 21)
8606 (> emacs-minor-version 4))
8607 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8608 (add-hook 'tramp-unload-hook
8609 (lambda ()
8610 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8612 (defun tramp-subst-strs-in-string (alist string)
8613 "Replace all occurrences of the string FROM with TO in STRING.
8614 ALIST is of the form ((FROM . TO) ...)."
8615 (save-match-data
8616 (while alist
8617 (let* ((pr (car alist))
8618 (from (car pr))
8619 (to (cdr pr)))
8620 (while (string-match (regexp-quote from) string)
8621 (setq string (replace-match to t t string)))
8622 (setq alist (cdr alist))))
8623 string))
8625 ;; ------------------------------------------------------------
8626 ;; -- Compatibility functions section --
8627 ;; ------------------------------------------------------------
8629 (defun tramp-read-passwd (proc &optional prompt)
8630 "Read a password from user (compat function).
8631 Consults the auth-source package.
8632 Invokes `password-read' if available, `read-passwd' else."
8633 (let* ((key (tramp-make-tramp-file-name
8634 tramp-current-method tramp-current-user
8635 tramp-current-host ""))
8636 (pw-prompt
8637 (or prompt
8638 (with-current-buffer (process-buffer proc)
8639 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8640 (format "%s for %s " (capitalize (match-string 1)) key)))))
8641 (with-parsed-tramp-file-name key nil
8642 (prog1
8644 ;; See if auth-sources contains something useful, if it's bound.
8645 (and (boundp 'auth-sources)
8646 (tramp-get-connection-property v "first-password-request" nil)
8647 ;; Try with Tramp's current method.
8648 (tramp-compat-funcall
8649 'auth-source-user-or-password
8650 "password" tramp-current-host tramp-current-method))
8651 ;; Try the password cache.
8652 (when (functionp 'password-read)
8653 (unless (tramp-get-connection-property
8654 v "first-password-request" nil)
8655 (tramp-compat-funcall 'password-cache-remove key))
8656 (let ((password
8657 (tramp-compat-funcall 'password-read pw-prompt key)))
8658 (tramp-compat-funcall 'password-cache-add key password)
8659 password))
8660 ;; Else, get the password interactively.
8661 (read-passwd pw-prompt))
8662 (tramp-set-connection-property v "first-password-request" nil)))))
8664 (defun tramp-clear-passwd (vec)
8665 "Clear password cache for connection related to VEC."
8666 (tramp-compat-funcall
8667 'password-cache-remove
8668 (tramp-make-tramp-file-name
8669 (tramp-file-name-method vec)
8670 (tramp-file-name-user vec)
8671 (tramp-file-name-host vec)
8672 "")))
8674 ;; Snarfed code from time-date.el and parse-time.el
8676 (defconst tramp-half-a-year '(241 17024)
8677 "Evaluated by \"(days-to-time 183)\".")
8679 (defconst tramp-parse-time-months
8680 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8681 ("apr" . 4) ("may" . 5) ("jun" . 6)
8682 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8683 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8684 "Alist mapping month names to integers.")
8686 (defun tramp-time-less-p (t1 t2)
8687 "Say whether time value T1 is less than time value T2."
8688 (unless t1 (setq t1 '(0 0)))
8689 (unless t2 (setq t2 '(0 0)))
8690 (or (< (car t1) (car t2))
8691 (and (= (car t1) (car t2))
8692 (< (nth 1 t1) (nth 1 t2)))))
8694 (defun tramp-time-subtract (t1 t2)
8695 "Subtract two time values.
8696 Return the difference in the format of a time value."
8697 (unless t1 (setq t1 '(0 0)))
8698 (unless t2 (setq t2 '(0 0)))
8699 (let ((borrow (< (cadr t1) (cadr t2))))
8700 (list (- (car t1) (car t2) (if borrow 1 0))
8701 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8703 (defun tramp-time-diff (t1 t2)
8704 "Return the difference between the two times, in seconds.
8705 T1 and T2 are time values (as returned by `current-time' for example)."
8706 ;; Pacify byte-compiler with `symbol-function'.
8707 (cond ((and (fboundp 'subtract-time)
8708 (fboundp 'float-time))
8709 (tramp-compat-funcall
8710 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
8711 ((and (fboundp 'subtract-time)
8712 (fboundp 'time-to-seconds))
8713 (tramp-compat-funcall
8714 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
8715 ((fboundp 'itimer-time-difference)
8716 (tramp-compat-funcall
8717 'itimer-time-difference
8718 (if (< (length t1) 3) (append t1 '(0)) t1)
8719 (if (< (length t2) 3) (append t2 '(0)) t2)))
8721 (let ((time (tramp-time-subtract t1 t2)))
8722 (+ (* (car time) 65536.0)
8723 (cadr time)
8724 (/ (or (nth 2 time) 0) 1000000.0))))))
8726 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8727 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8728 EOL-TYPE can be one of `dos', `unix', or `mac'."
8729 (cond ((fboundp 'coding-system-change-eol-conversion)
8730 (tramp-compat-funcall
8731 'coding-system-change-eol-conversion coding-system eol-type))
8732 ((fboundp 'subsidiary-coding-system)
8733 (tramp-compat-funcall
8734 'subsidiary-coding-system coding-system
8735 (cond ((eq eol-type 'dos) 'crlf)
8736 ((eq eol-type 'unix) 'lf)
8737 ((eq eol-type 'mac) 'cr)
8739 (error "Unknown EOL-TYPE `%s', must be %s"
8740 eol-type
8741 "`dos', `unix', or `mac'")))))
8742 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8744 (defun tramp-set-process-query-on-exit-flag (process flag)
8745 "Specify if query is needed for process when Emacs is exited.
8746 If the second argument flag is non-nil, Emacs will query the user before
8747 exiting if process is running."
8748 (if (fboundp 'set-process-query-on-exit-flag)
8749 (tramp-compat-funcall 'set-process-query-on-exit-flag process flag)
8750 (tramp-compat-funcall 'process-kill-without-query) process flag))
8753 ;; ------------------------------------------------------------
8754 ;; -- Kludges section --
8755 ;; ------------------------------------------------------------
8757 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8758 ;; does not deal well with newline characters. Newline is replaced by
8759 ;; backslash newline. But if, say, the string `a backslash newline b'
8760 ;; is passed to a shell, the shell will expand this into "ab",
8761 ;; completely omitting the newline. This is not what was intended.
8762 ;; It does not appear to be possible to make the function
8763 ;; `shell-quote-argument' work with newlines without making it
8764 ;; dependent on the shell used. But within this package, we know that
8765 ;; we will always use a Bourne-like shell, so we use an approach which
8766 ;; groks newlines.
8768 ;; The approach is simple: we call `shell-quote-argument', then
8769 ;; massage the newline part of the result.
8771 ;; This function should produce a string which is grokked by a Unix
8772 ;; shell, even if the Emacs is running on Windows. Since this is the
8773 ;; kludges section, we bind `system-type' in such a way that
8774 ;; `shell-quote-arguments' behaves as if on Unix.
8776 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8777 ;; function to work with Bourne-like shells.
8779 ;; CCC: This function should be rewritten so that
8780 ;; `shell-quote-argument' is not used. This way, we are safe from
8781 ;; changes in `shell-quote-argument'.
8782 (defun tramp-shell-quote-argument (s)
8783 "Similar to `shell-quote-argument', but groks newlines.
8784 Only works for Bourne-like shells."
8785 (let ((system-type 'not-windows))
8786 (save-match-data
8787 (let ((result (shell-quote-argument s))
8788 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8789 (when (and (>= (length result) 2)
8790 (string= (substring result 0 2) "\\~"))
8791 (setq result (substring result 1)))
8792 (while (string-match nl result)
8793 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8794 t t result)))
8795 result))))
8797 ;; Checklist for `tramp-unload-hook'
8798 ;; - Unload all `tramp-*' packages
8799 ;; - Reset `file-name-handler-alist'
8800 ;; - Cleanup hooks where Tramp functions are in
8801 ;; - Cleanup advised functions
8802 ;; - Cleanup autoloads
8803 ;;;###autoload
8804 (defun tramp-unload-tramp ()
8805 "Discard Tramp from loading remote files."
8806 (interactive)
8807 ;; When Tramp is not loaded yet, its autoloads are still active.
8808 (tramp-unload-file-name-handlers)
8809 ;; ange-ftp settings must be enabled.
8810 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
8811 ;; Maybe its not loaded yet.
8812 (condition-case nil
8813 (unload-feature 'tramp 'force)
8814 (error nil)))
8816 (when (and load-in-progress
8817 (string-match "Loading tramp..." (or (current-message) "")))
8818 (message "Loading tramp...done"))
8820 (provide 'tramp)
8822 ;;; TODO:
8824 ;; * Handle nonlocal exits such as C-g.
8825 ;; * But it would probably be better to use with-local-quit at the
8826 ;; place where it's actually needed: around any potentially
8827 ;; indefinitely blocking piece of code. In this case it would be
8828 ;; within Tramp around one of its calls to accept-process-output (or
8829 ;; around one of the loops that calls accept-process-output)
8830 ;; (Stefan Monnier).
8831 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8832 ;; `shell-quote-argument'.
8833 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8834 ;; by the files in that directory. Add this here.
8835 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8836 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8837 ;; * Case-insensitive filename completion. (Norbert Goevert.)
8838 ;; * Don't use globbing for directories with many files, as this is
8839 ;; likely to produce long command lines, and some shells choke on
8840 ;; long command lines.
8841 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8842 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8843 ;; * abbreviate-file-name
8844 ;; * Better error checking. At least whenever we see something
8845 ;; strange when doing zerop, we should kill the process and start
8846 ;; again. (Greg Stark)
8847 ;; * Remove unneeded parameters from methods.
8848 ;; * Make it work for different encodings, and for different file name
8849 ;; encodings, too. (Daniel Pittman)
8850 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8851 ;; then look if it's the right version (with `perl -v').
8852 ;; * When editing a remote CVS controlled file as a different user, VC
8853 ;; gets confused about the file locking status. Try to find out why
8854 ;; the workaround doesn't work.
8855 ;; * Username and hostname completion.
8856 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8857 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8858 ;; Code is nearly identical.
8859 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8860 ;; until the last but one hop via `start-file-process'. Apply it
8861 ;; also for ftp and smb.
8862 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8863 ;; some shell with root priviledges, it would be nice if I could
8864 ;; just call
8865 ;; trampclient filename.c
8866 ;; as an editor, and the _current_ shell would connect to an Emacs
8867 ;; server and would be used in an existing non-priviledged Emacs
8868 ;; session for doing the editing in question.
8869 ;; That way, I need not tell Emacs my password again and be afraid
8870 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8871 ;; once display a just typed password in the context of a keyboard
8872 ;; sequence prompt for a question immediately following in a shell
8873 ;; script run within Emacs -- nasty).
8874 ;; And if I have some ssh session running to a different computer,
8875 ;; having the possibility of passing a local file there to a local
8876 ;; Emacs session (in case I can arrange for a connection back) would
8877 ;; be nice.
8878 ;; Likely the corresponding Tramp server should not allow the
8879 ;; equivalent of the emacsclient -eval option in order to make this
8880 ;; reasonably unproblematic. And maybe trampclient should have some
8881 ;; way of passing credentials, like by using an SSL socket or
8882 ;; something. (David Kastrup)
8883 ;; * Reconnect directly to a compliant shell without first going
8884 ;; through the user's default shell. (Pete Forman)
8885 ;; * Make `tramp-default-user' obsolete.
8886 ;; * How can I interrupt the remote process with a signal
8887 ;; (interrupt-process seems not to work)? (Markus Triska)
8888 ;; * Avoid the local shell entirely for starting remote processes. If
8889 ;; so, I think even a signal, when delivered directly to the local
8890 ;; SSH instance, would correctly be propagated to the remote process
8891 ;; automatically; possibly SSH would have to be started with
8892 ;; "-t". (Markus Triska)
8893 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8894 ;; isn't on the remote host. (Mark A. Hershberger)
8895 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8896 ;; * Implement a general server-local-variable mechanism, as there are
8897 ;; probably other variables that need different values for different
8898 ;; servers too. The user could then configure a variable (such as
8899 ;; tramp-server-local-variable-alist) to define any such variables
8900 ;; that they need to, which would then be let bound as appropriate
8901 ;; in tramp functions. (Jason Rumney)
8902 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8903 ;; rsync).
8904 ;; * Keep a second connection open for out-of-band methods like scp or
8905 ;; rsync.
8906 ;; * Support ptys in `tramp-handle-start-file-process'. (Bug#4604)
8907 ;; * IMHO, it's a drawback that currently Tramp doesn't support
8908 ;; Unicode in Dired file names by default. Is it possible to
8909 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8910 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
8911 ;; expects only English messages? (Juri Linkov)
8912 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8913 ;; * Do not handle files with drive letter as remote. (Bug#5447)
8914 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
8915 ;; * Try telnet+curl as new method. It might be useful for busybox,
8916 ;; without built-in uuencode/uudecode.
8917 ;; * Let `shell-dynamic-complete-*' and `comint-dynamic-complete' work
8918 ;; on remote hosts.
8919 ;; * Use secrets.el for password handling.
8920 ;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
8922 ;; Functions for file-name-handler-alist:
8923 ;; diff-latest-backup-file -- in diff.el
8925 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8926 ;;; tramp.el ends here
8928 ;; Local Variables:
8929 ;; mode: Emacs-Lisp
8930 ;; coding: utf-8
8931 ;; End: