Fix permissions handling (CVE-2010-0825).
[emacs.git] / lisp / net / tramp.el
bloba0fe20c2a99cd513c82385c79cd46bf8408c57bf
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 21.1 and higher, and for XEmacs 21.4
40 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
41 ;; the `with-timeout' macro.
43 ;; Also see the todo list at the bottom of this file.
45 ;; The current version of Tramp can be retrieved from the following URL:
46 ;; http://ftp.gnu.org/gnu/tramp/
48 ;; There's a mailing list for this, as well. Its name is:
49 ;; tramp-devel@gnu.org
50 ;; You can use the Web to subscribe, under the following URL:
51 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
53 ;; For the adventurous, the current development sources are available
54 ;; via CVS. You can find instructions about this at the following URL:
55 ;; http://savannah.gnu.org/projects/tramp/
56 ;; Click on "CVS" in the navigation bar near the top.
58 ;; Don't forget to put on your asbestos longjohns, first!
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) ; from Gnus 5.8, also in tar ball
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 (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 :version "22.1")
181 ;; Maybe we need once a real Tramp mode, with key bindings etc.
182 ;;;###autoload
183 (defcustom tramp-mode t
184 "*Whether Tramp is enabled.
185 If it is set to nil, all remote file names are used literally."
186 :group 'tramp
187 :type 'boolean)
189 (defcustom tramp-verbose 3
190 "*Verbosity level for Tramp messages.
191 Any level x includes messages for all levels 1 .. x-1. The levels are
193 0 silent (no tramp messages at all)
194 1 errors
195 2 warnings
196 3 connection to remote hosts (default level)
197 4 activities
198 5 internal
199 6 sent and received strings
200 7 file caching
201 8 connection properties
202 10 traces (huge)."
203 :group 'tramp
204 :type 'integer)
206 ;; Emacs case.
207 (eval-and-compile
208 (when (boundp 'backup-directory-alist)
209 (defcustom tramp-backup-directory-alist nil
210 "Alist of filename patterns and backup directory names.
211 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
212 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
213 is a local file name, the backup directory is prepended with Tramp file
214 name prefix \(method, user, host\) of file.
216 \(setq tramp-backup-directory-alist backup-directory-alist\)
218 gives the same backup policy for Tramp files on their hosts like the
219 policy for local files."
220 :group 'tramp
221 :type '(repeat (cons (regexp :tag "Regexp matching filename")
222 (directory :tag "Backup directory name"))))))
224 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
225 ;; the package "backup-dir" might not be loaded yet.
226 (eval-and-compile
227 (when (featurep 'xemacs)
228 (defcustom tramp-bkup-backup-directory-info nil
229 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
230 It has the same meaning like `bkup-backup-directory-info' from package
231 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
232 file name, the backup directory is prepended with Tramp file name prefix
233 \(method, user, host\) of file.
235 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
237 gives the same backup policy for Tramp files on their hosts like the
238 policy for local files."
239 :type '(repeat
240 (list (regexp :tag "File regexp")
241 (string :tag "Backup Dir")
242 (set :inline t
243 (const ok-create)
244 (const full-path)
245 (const prepend-name)
246 (const search-upward))))
247 :group 'tramp)))
249 (defcustom tramp-auto-save-directory nil
250 "*Put auto-save files in this directory, if set.
251 The idea is to use a local directory so that auto-saving is faster."
252 :group 'tramp
253 :type '(choice (const nil) string))
255 (defcustom tramp-encoding-shell
256 (if (memq system-type '(windows-nt))
257 (getenv "COMSPEC")
258 "/bin/sh")
259 "*Use this program for encoding and decoding commands on the local host.
260 This shell is used to execute the encoding and decoding command on the
261 local host, so if you want to use `~' in those commands, you should
262 choose a shell here which groks tilde expansion. `/bin/sh' normally
263 does not understand tilde expansion.
265 For encoding and deocding, commands like the following are executed:
267 /bin/sh -c COMMAND < INPUT > OUTPUT
269 This variable can be used to change the \"/bin/sh\" part. See the
270 variable `tramp-encoding-command-switch' for the \"-c\" part.
272 Note that this variable is not used for remote commands. There are
273 mechanisms in tramp.el which automatically determine the right shell to
274 use for the remote host."
275 :group 'tramp
276 :type '(file :must-match t))
278 (defcustom tramp-encoding-command-switch
279 (if (string-match "cmd\\.exe" tramp-encoding-shell)
280 "/c"
281 "-c")
282 "*Use this switch together with `tramp-encoding-shell' for local commands.
283 See the variable `tramp-encoding-shell' for more information."
284 :group 'tramp
285 :type 'string)
287 (defcustom tramp-copy-size-limit 10240
288 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
289 :group 'tramp
290 :type 'integer)
292 (defcustom tramp-terminal-type "dumb"
293 "*Value of TERM environment variable for logging in to remote host.
294 Because Tramp wants to parse the output of the remote shell, it is easily
295 confused by ANSI color escape sequences and suchlike. Often, shell init
296 files conditionalize this setup based on the TERM environment variable."
297 :group 'tramp
298 :type 'string)
300 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
301 ;; root users. It uses the `$' character for other users. In order
302 ;; to guarantee a proper prompt, we use "#$" for the prompt.
304 (defvar tramp-end-of-output
305 (format
306 "///%s#$"
307 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
308 "String used to recognize end of output.
309 The '$' character at the end is quoted; the string cannot be
310 detected as prompt when being sent on echoing hosts, therefore.")
312 (defconst tramp-initial-end-of-output "#$ "
313 "Prompt when establishing a connection.")
315 (defvar tramp-methods
316 `(("rcp" (tramp-login-program "rsh")
317 (tramp-login-args (("%h") ("-l" "%u")))
318 (tramp-remote-sh "/bin/sh")
319 (tramp-copy-program "rcp")
320 (tramp-copy-args (("-p" "%k") ("-r")))
321 (tramp-copy-keep-date t)
322 (tramp-copy-recursive t)
323 (tramp-password-end-of-line nil))
324 ("scp" (tramp-login-program "ssh")
325 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
326 ("-e" "none")))
327 (tramp-remote-sh "/bin/sh")
328 (tramp-copy-program "scp")
329 (tramp-copy-args (("-P" "%p") ("-p" "%k")
330 ("-q") ("-r")))
331 (tramp-copy-keep-date t)
332 (tramp-copy-recursive t)
333 (tramp-password-end-of-line nil)
334 (tramp-gw-args (("-o"
335 "GlobalKnownHostsFile=/dev/null")
336 ("-o" "UserKnownHostsFile=/dev/null")
337 ("-o" "StrictHostKeyChecking=no")))
338 (tramp-default-port 22))
339 ("scp1" (tramp-login-program "ssh")
340 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
341 ("-1" "-e" "none")))
342 (tramp-remote-sh "/bin/sh")
343 (tramp-copy-program "scp")
344 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
345 ("-q") ("-r")))
346 (tramp-copy-keep-date t)
347 (tramp-copy-recursive t)
348 (tramp-password-end-of-line nil)
349 (tramp-gw-args (("-o"
350 "GlobalKnownHostsFile=/dev/null")
351 ("-o" "UserKnownHostsFile=/dev/null")
352 ("-o" "StrictHostKeyChecking=no")))
353 (tramp-default-port 22))
354 ("scp2" (tramp-login-program "ssh")
355 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
356 ("-2" "-e" "none")))
357 (tramp-remote-sh "/bin/sh")
358 (tramp-copy-program "scp")
359 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
360 ("-q") ("-r")))
361 (tramp-copy-keep-date t)
362 (tramp-copy-recursive t)
363 (tramp-password-end-of-line nil)
364 (tramp-gw-args (("-o"
365 "GlobalKnownHostsFile=/dev/null")
366 ("-o" "UserKnownHostsFile=/dev/null")
367 ("-o" "StrictHostKeyChecking=no")))
368 (tramp-default-port 22))
369 ("scp1_old"
370 (tramp-login-program "ssh1")
371 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
372 ("-e" "none")))
373 (tramp-remote-sh "/bin/sh")
374 (tramp-copy-program "scp1")
375 (tramp-copy-args (("-p" "%k") ("-r")))
376 (tramp-copy-keep-date t)
377 (tramp-copy-recursive t)
378 (tramp-password-end-of-line nil))
379 ("scp2_old"
380 (tramp-login-program "ssh2")
381 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
382 ("-e" "none")))
383 (tramp-remote-sh "/bin/sh")
384 (tramp-copy-program "scp2")
385 (tramp-copy-args (("-p" "%k") ("-r")))
386 (tramp-copy-keep-date t)
387 (tramp-copy-recursive t)
388 (tramp-password-end-of-line nil))
389 ("sftp" (tramp-login-program "ssh")
390 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
391 ("-e" "none")))
392 (tramp-remote-sh "/bin/sh")
393 (tramp-copy-program "sftp")
394 (tramp-copy-args nil)
395 (tramp-copy-keep-date nil)
396 (tramp-password-end-of-line nil))
397 ("rsync" (tramp-login-program "ssh")
398 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
399 ("-e" "none")))
400 (tramp-remote-sh "/bin/sh")
401 (tramp-copy-program "rsync")
402 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
403 (tramp-copy-keep-date t)
404 (tramp-copy-keep-tmpfile t)
405 (tramp-copy-recursive t)
406 (tramp-password-end-of-line nil))
407 ("rsyncc"
408 (tramp-login-program "ssh")
409 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
410 ("-o" "ControlPath=%t.%%r@%%h:%%p")
411 ("-o" "ControlMaster=yes")
412 ("-e" "none")))
413 (tramp-remote-sh "/bin/sh")
414 (tramp-copy-program "rsync")
415 (tramp-copy-args (("-t" "%k") ("-r")))
416 (tramp-copy-env (("RSYNC_RSH")
417 (,(concat
418 "ssh"
419 " -o ControlPath=%t.%%r@%%h:%%p"
420 " -o ControlMaster=auto"))))
421 (tramp-copy-keep-date t)
422 (tramp-copy-keep-tmpfile t)
423 (tramp-copy-recursive t)
424 (tramp-password-end-of-line nil))
425 ("remcp" (tramp-login-program "remsh")
426 (tramp-login-args (("%h") ("-l" "%u")))
427 (tramp-remote-sh "/bin/sh")
428 (tramp-copy-program "rcp")
429 (tramp-copy-args (("-p" "%k")))
430 (tramp-copy-keep-date t)
431 (tramp-password-end-of-line nil))
432 ("rsh" (tramp-login-program "rsh")
433 (tramp-login-args (("%h") ("-l" "%u")))
434 (tramp-remote-sh "/bin/sh")
435 (tramp-copy-program nil)
436 (tramp-copy-args nil)
437 (tramp-copy-keep-date nil)
438 (tramp-password-end-of-line nil))
439 ("ssh" (tramp-login-program "ssh")
440 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
441 ("-e" "none")))
442 (tramp-remote-sh "/bin/sh")
443 (tramp-copy-program nil)
444 (tramp-copy-args nil)
445 (tramp-copy-keep-date nil)
446 (tramp-password-end-of-line nil)
447 (tramp-gw-args (("-o"
448 "GlobalKnownHostsFile=/dev/null")
449 ("-o" "UserKnownHostsFile=/dev/null")
450 ("-o" "StrictHostKeyChecking=no")))
451 (tramp-default-port 22))
452 ("ssh1" (tramp-login-program "ssh")
453 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
454 ("-1" "-e" "none")))
455 (tramp-remote-sh "/bin/sh")
456 (tramp-copy-program nil)
457 (tramp-copy-args nil)
458 (tramp-copy-keep-date nil)
459 (tramp-password-end-of-line nil)
460 (tramp-gw-args (("-o"
461 "GlobalKnownHostsFile=/dev/null")
462 ("-o" "UserKnownHostsFile=/dev/null")
463 ("-o" "StrictHostKeyChecking=no")))
464 (tramp-default-port 22))
465 ("ssh2" (tramp-login-program "ssh")
466 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
467 ("-2" "-e" "none")))
468 (tramp-remote-sh "/bin/sh")
469 (tramp-copy-program nil)
470 (tramp-copy-args nil)
471 (tramp-copy-keep-date nil)
472 (tramp-password-end-of-line nil)
473 (tramp-gw-args (("-o"
474 "GlobalKnownHostsFile=/dev/null")
475 ("-o" "UserKnownHostsFile=/dev/null")
476 ("-o" "StrictHostKeyChecking=no")))
477 (tramp-default-port 22))
478 ("ssh1_old"
479 (tramp-login-program "ssh1")
480 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
481 ("-e" "none")))
482 (tramp-remote-sh "/bin/sh")
483 (tramp-copy-program nil)
484 (tramp-copy-args nil)
485 (tramp-copy-keep-date nil)
486 (tramp-password-end-of-line nil))
487 ("ssh2_old"
488 (tramp-login-program "ssh2")
489 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
490 ("-e" "none")))
491 (tramp-remote-sh "/bin/sh")
492 (tramp-copy-program nil)
493 (tramp-copy-args nil)
494 (tramp-copy-keep-date nil)
495 (tramp-password-end-of-line nil))
496 ("remsh" (tramp-login-program "remsh")
497 (tramp-login-args (("%h") ("-l" "%u")))
498 (tramp-remote-sh "/bin/sh")
499 (tramp-copy-program nil)
500 (tramp-copy-args nil)
501 (tramp-copy-keep-date nil)
502 (tramp-password-end-of-line nil))
503 ("telnet"
504 (tramp-login-program "telnet")
505 (tramp-login-args (("%h") ("%p")))
506 (tramp-remote-sh "/bin/sh")
507 (tramp-copy-program nil)
508 (tramp-copy-args nil)
509 (tramp-copy-keep-date nil)
510 (tramp-password-end-of-line nil)
511 (tramp-default-port 23))
512 ("su" (tramp-login-program "su")
513 (tramp-login-args (("-") ("%u")))
514 (tramp-remote-sh "/bin/sh")
515 (tramp-copy-program nil)
516 (tramp-copy-args nil)
517 (tramp-copy-keep-date nil)
518 (tramp-password-end-of-line nil))
519 ("sudo" (tramp-login-program "sudo")
520 (tramp-login-args (("-u" "%u")
521 ("-s") ("-H") ("-p" "Password:")))
522 (tramp-remote-sh "/bin/sh")
523 (tramp-copy-program nil)
524 (tramp-copy-args nil)
525 (tramp-copy-keep-date nil)
526 (tramp-password-end-of-line nil))
527 ("scpc" (tramp-login-program "ssh")
528 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
529 ("-o" "ControlPath=%t.%%r@%%h:%%p")
530 ("-o" "ControlMaster=yes")
531 ("-e" "none")))
532 (tramp-remote-sh "/bin/sh")
533 (tramp-copy-program "scp")
534 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
535 ("-o" "ControlPath=%t.%%r@%%h:%%p")
536 ("-o" "ControlMaster=auto")))
537 (tramp-copy-keep-date t)
538 (tramp-password-end-of-line nil)
539 (tramp-gw-args (("-o"
540 "GlobalKnownHostsFile=/dev/null")
541 ("-o" "UserKnownHostsFile=/dev/null")
542 ("-o" "StrictHostKeyChecking=no")))
543 (tramp-default-port 22))
544 ("scpx" (tramp-login-program "ssh")
545 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
546 ("-e" "none" "-t" "-t" "/bin/sh")))
547 (tramp-remote-sh "/bin/sh")
548 (tramp-copy-program "scp")
549 (tramp-copy-args (("-p" "%k")))
550 (tramp-copy-keep-date t)
551 (tramp-password-end-of-line nil)
552 (tramp-gw-args (("-o"
553 "GlobalKnownHostsFile=/dev/null")
554 ("-o" "UserKnownHostsFile=/dev/null")
555 ("-o" "StrictHostKeyChecking=no")))
556 (tramp-default-port 22))
557 ("sshx" (tramp-login-program "ssh")
558 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
559 ("-e" "none" "-t" "-t" "/bin/sh")))
560 (tramp-remote-sh "/bin/sh")
561 (tramp-copy-program nil)
562 (tramp-copy-args nil)
563 (tramp-copy-keep-date nil)
564 (tramp-password-end-of-line nil)
565 (tramp-gw-args (("-o"
566 "GlobalKnownHostsFile=/dev/null")
567 ("-o" "UserKnownHostsFile=/dev/null")
568 ("-o" "StrictHostKeyChecking=no")))
569 (tramp-default-port 22))
570 ("krlogin"
571 (tramp-login-program "krlogin")
572 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
573 (tramp-remote-sh "/bin/sh")
574 (tramp-copy-program nil)
575 (tramp-copy-args nil)
576 (tramp-copy-keep-date nil)
577 (tramp-password-end-of-line nil))
578 ("plink" (tramp-login-program "plink")
579 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
580 ("-ssh")))
581 (tramp-remote-sh "/bin/sh")
582 (tramp-copy-program nil)
583 (tramp-copy-args nil)
584 (tramp-copy-keep-date nil)
585 (tramp-password-end-of-line "xy") ;see docstring for "xy"
586 (tramp-default-port 22))
587 ("plink1"
588 (tramp-login-program "plink")
589 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
590 ("-1" "-ssh")))
591 (tramp-remote-sh "/bin/sh")
592 (tramp-copy-program nil)
593 (tramp-copy-args nil)
594 (tramp-copy-keep-date nil)
595 (tramp-password-end-of-line "xy") ;see docstring for "xy"
596 (tramp-default-port 22))
597 ("plinkx"
598 (tramp-login-program "plink")
599 ;; ("%h") must be a single element, see
600 ;; `tramp-compute-multi-hops'.
601 (tramp-login-args (("-load") ("%h") ("-t")
602 (,(format
603 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
604 tramp-terminal-type
605 tramp-initial-end-of-output))
606 ("/bin/sh")))
607 (tramp-remote-sh "/bin/sh")
608 (tramp-copy-program nil)
609 (tramp-copy-args nil)
610 (tramp-copy-keep-date nil)
611 (tramp-password-end-of-line nil))
612 ("pscp" (tramp-login-program "plink")
613 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
614 ("-ssh")))
615 (tramp-remote-sh "/bin/sh")
616 (tramp-copy-program "pscp")
617 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
618 (tramp-copy-keep-date t)
619 (tramp-password-end-of-line "xy") ;see docstring for "xy"
620 (tramp-default-port 22))
621 ("psftp" (tramp-login-program "plink")
622 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
623 ("-ssh")))
624 (tramp-remote-sh "/bin/sh")
625 (tramp-copy-program "pscp")
626 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
627 (tramp-copy-keep-date t)
628 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
629 ("fcp" (tramp-login-program "fsh")
630 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
631 (tramp-remote-sh "/bin/sh -i")
632 (tramp-copy-program "fcp")
633 (tramp-copy-args (("-p" "%k")))
634 (tramp-copy-keep-date t)
635 (tramp-password-end-of-line nil)))
636 "*Alist of methods for remote files.
637 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
638 Each NAME stands for a remote access method. Each PARAM is a
639 pair of the form (KEY VALUE). The following KEYs are defined:
640 * `tramp-remote-sh'
641 This specifies the Bourne shell to use on the remote host. This
642 MUST be a Bourne-like shell. It is normally not necessary to set
643 this to any value other than \"/bin/sh\": Tramp wants to use a shell
644 which groks tilde expansion, but it can search for it. Also note
645 that \"/bin/sh\" exists on all Unixen, this might not be true for
646 the value that you decide to use. You Have Been Warned.
647 * `tramp-login-program'
648 This specifies the name of the program to use for logging in to the
649 remote host. This may be the name of rsh or a workalike program,
650 or the name of telnet or a workalike, or the name of su or a workalike.
651 * `tramp-login-args'
652 This specifies the list of arguments to pass to the above
653 mentioned program. Please note that this is a list of list of arguments,
654 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
655 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
656 There are some patterns: \"%h\" in this list is replaced by the host
657 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
658 port number, and \"%%\" can be used to obtain a literal percent character.
659 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
660 expansion (i.e. no host or no user specified), this list is not used as
661 argument. By this, arguments like (\"-l\" \"%u\") are optional.
662 \"%t\" is replaced by the temporary file name produced with
663 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
664 parameter of a program, if exists.
665 * `tramp-copy-program'
666 This specifies the name of the program to use for remotely copying
667 the file; this might be the absolute filename of rcp or the name of
668 a workalike program.
669 * `tramp-copy-args'
670 This specifies the list of parameters to pass to the above mentioned
671 program, the hints for `tramp-login-args' also apply here.
672 * `tramp-copy-keep-date'
673 This specifies whether the copying program when the preserves the
674 timestamp of the original file.
675 * `tramp-copy-keep-tmpfile'
676 This specifies whether a temporary local file shall be kept
677 for optimization reasons (useful for \"rsync\" methods).
678 * `tramp-copy-recursive'
679 Whether the operation copies directories recursively.
680 * `tramp-default-port'
681 The default port of a method is needed in case of gateway connections.
682 Additionally, it is used as indication which method is prepared for
683 passing gateways.
684 * `tramp-gw-args'
685 As the attribute name says, additional arguments are specified here
686 when a method is applied via a gateway.
687 * `tramp-password-end-of-line'
688 This specifies the string to use for terminating the line after
689 submitting the password. If this method parameter is nil, then the
690 value of the normal variable `tramp-default-password-end-of-line'
691 is used. This parameter is necessary because the \"plink\" program
692 requires any two characters after sending the password. These do
693 not have to be newline or carriage return characters. Other login
694 programs are happy with just one character, the newline character.
695 We use \"xy\" as the value for methods using \"plink\".
697 What does all this mean? Well, you should specify `tramp-login-program'
698 for all methods; this program is used to log in to the remote site. Then,
699 there are two ways to actually transfer the files between the local and the
700 remote side. One way is using an additional rcp-like program. If you want
701 to do this, set `tramp-copy-program' in the method.
703 Another possibility for file transfer is inline transfer, i.e. the
704 file is passed through the same buffer used by `tramp-login-program'. In
705 this case, the file contents need to be protected since the
706 `tramp-login-program' might use escape codes or the connection might not
707 be eight-bit clean. Therefore, file contents are encoded for transit.
708 See the variables `tramp-local-coding-commands' and
709 `tramp-remote-coding-commands' for details.
711 So, to summarize: if the method is an out-of-band method, then you
712 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
713 inline method, then these two parameters should be nil. Methods which
714 are fit for gateways must have `tramp-default-port' at least.
716 Notes:
718 When using `su' or `sudo' the phrase `open connection to a remote
719 host' sounds strange, but it is used nevertheless, for consistency.
720 No connection is opened to a remote host, but `su' or `sudo' is
721 started on the local host. You should specify a remote host
722 `localhost' or the name of the local host. Another host name is
723 useful only in combination with `tramp-default-proxies-alist'.")
725 (defcustom tramp-default-method
726 ;; An external copy method seems to be preferred, because it is much
727 ;; more performant for large files, and it hasn't too serious delays
728 ;; for small files. But it must be ensured that there aren't
729 ;; permanent password queries. Either a password agent like
730 ;; "ssh-agent" or "Pageant" shall run, or the optional
731 ;; password-cache.el or auth-sources.el packages shall be active for
732 ;; password caching. "scpc" would be another good choice because of
733 ;; the "ControlMaster" option, but this is a more modern alternative
734 ;; in OpenSSH 4, which cannot be taken as default.
735 (cond
736 ;; PuTTY is installed.
737 ((executable-find "pscp")
738 (if (or (fboundp 'password-read)
739 (fboundp 'auth-source-user-or-password)
740 ;; Pageant is running.
741 (tramp-compat-process-running-p "Pageant"))
742 "pscp"
743 "plink"))
744 ;; There is an ssh installation.
745 ((executable-find "scp")
746 (if (or (fboundp 'password-read)
747 (fboundp 'auth-source-user-or-password)
748 ;; ssh-agent is running.
749 (getenv "SSH_AUTH_SOCK")
750 (getenv "SSH_AGENT_PID"))
751 "scp"
752 "ssh"))
753 ;; Fallback.
754 (t "ftp"))
755 "*Default method to use for transferring files.
756 See `tramp-methods' for possibilities.
757 Also see `tramp-default-method-alist'."
758 :group 'tramp
759 :type 'string)
761 (defcustom tramp-default-method-alist
762 '(("\\`localhost\\'" "\\`root\\'" "su"))
763 "*Default method to use for specific host/user pairs.
764 This is an alist of items (HOST USER METHOD). The first matching item
765 specifies the method to use for a file name which does not specify a
766 method. HOST and USER are regular expressions or nil, which is
767 interpreted as a regular expression which always matches. If no entry
768 matches, the variable `tramp-default-method' takes effect.
770 If the file name does not specify the user, lookup is done using the
771 empty string for the user name.
773 See `tramp-methods' for a list of possibilities for METHOD."
774 :group 'tramp
775 :type '(repeat (list (regexp :tag "Host regexp")
776 (regexp :tag "User regexp")
777 (string :tag "Method"))))
779 (defcustom tramp-default-user
781 "*Default user to use for transferring files.
782 It is nil by default; otherwise settings in configuration files like
783 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
785 This variable is regarded as obsolete, and will be removed soon."
786 :group 'tramp
787 :type '(choice (const nil) string))
789 (defcustom tramp-default-user-alist
790 `(("\\`su\\(do\\)?\\'" nil "root")
791 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
792 nil ,(user-login-name)))
793 "*Default user to use for specific method/host pairs.
794 This is an alist of items (METHOD HOST USER). The first matching item
795 specifies the user to use for a file name which does not specify a
796 user. METHOD and USER are regular expressions or nil, which is
797 interpreted as a regular expression which always matches. If no entry
798 matches, the variable `tramp-default-user' takes effect.
800 If the file name does not specify the method, lookup is done using the
801 empty string for the method name."
802 :group 'tramp
803 :type '(repeat (list (regexp :tag "Method regexp")
804 (regexp :tag "Host regexp")
805 (string :tag "User"))))
807 (defcustom tramp-default-host
808 (system-name)
809 "*Default host to use for transferring files.
810 Useful for su and sudo methods mostly."
811 :group 'tramp
812 :type 'string)
814 (defcustom tramp-default-proxies-alist nil
815 "*Route to be followed for specific host/user pairs.
816 This is an alist of items (HOST USER PROXY). The first matching
817 item specifies the proxy to be passed for a file name located on
818 a remote target matching USER@HOST. HOST and USER are regular
819 expressions. PROXY must be a Tramp filename without a localname
820 part. Method and user name on PROXY are optional, which is
821 interpreted with the default values. PROXY can contain the
822 patterns %h and %u, which are replaced by the strings matching
823 HOST or USER, respectively.
825 HOST, USER or PROXY could also be Lisp forms, which will be
826 evaluated. The result must be a string or nil, which is
827 interpreted as a regular expression which always matches."
828 :group 'tramp
829 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
830 (choice :tag "User regexp" regexp sexp)
831 (choice :tag "Proxy remote name" string (const nil)))))
833 (defconst tramp-local-host-regexp
834 (concat
835 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
836 "*Host names which are regarded as local host.")
838 (defconst tramp-completion-function-alist-rsh
839 '((tramp-parse-rhosts "/etc/hosts.equiv")
840 (tramp-parse-rhosts "~/.rhosts"))
841 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
843 (defconst tramp-completion-function-alist-ssh
844 '((tramp-parse-rhosts "/etc/hosts.equiv")
845 (tramp-parse-rhosts "/etc/shosts.equiv")
846 (tramp-parse-shosts "/etc/ssh_known_hosts")
847 (tramp-parse-sconfig "/etc/ssh_config")
848 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
849 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
850 (tramp-parse-rhosts "~/.rhosts")
851 (tramp-parse-rhosts "~/.shosts")
852 (tramp-parse-shosts "~/.ssh/known_hosts")
853 (tramp-parse-sconfig "~/.ssh/config")
854 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
855 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
856 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
858 (defconst tramp-completion-function-alist-telnet
859 '((tramp-parse-hosts "/etc/hosts"))
860 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
862 (defconst tramp-completion-function-alist-su
863 '((tramp-parse-passwd "/etc/passwd"))
864 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
866 (defconst tramp-completion-function-alist-putty
867 '((tramp-parse-putty
868 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
869 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
871 (defvar tramp-completion-function-alist nil
872 "*Alist of methods for remote files.
873 This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
874 Each NAME stands for a remote access method. Each PAIR is of the form
875 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
876 names from FILE for completion. The following predefined FUNCTIONs exists:
878 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
879 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
880 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
881 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
882 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
883 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
884 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
885 * `tramp-parse-netrc' for \"~/.netrc\" like files.
886 * `tramp-parse-putty' for PuTTY registry keys.
888 FUNCTION can also be a customer defined function. For more details see
889 the info pages.")
891 (eval-after-load "tramp"
892 '(progn
893 (tramp-set-completion-function
894 "rcp" tramp-completion-function-alist-rsh)
895 (tramp-set-completion-function
896 "scp" tramp-completion-function-alist-ssh)
897 (tramp-set-completion-function
898 "scp1" tramp-completion-function-alist-ssh)
899 (tramp-set-completion-function
900 "scp2" tramp-completion-function-alist-ssh)
901 (tramp-set-completion-function
902 "scp1_old" tramp-completion-function-alist-ssh)
903 (tramp-set-completion-function
904 "scp2_old" tramp-completion-function-alist-ssh)
905 (tramp-set-completion-function
906 "rsync" tramp-completion-function-alist-ssh)
907 (tramp-set-completion-function
908 "rsyncc" tramp-completion-function-alist-ssh)
909 (tramp-set-completion-function
910 "remcp" tramp-completion-function-alist-rsh)
911 (tramp-set-completion-function
912 "rsh" tramp-completion-function-alist-rsh)
913 (tramp-set-completion-function
914 "ssh" tramp-completion-function-alist-ssh)
915 (tramp-set-completion-function
916 "ssh1" tramp-completion-function-alist-ssh)
917 (tramp-set-completion-function
918 "ssh2" tramp-completion-function-alist-ssh)
919 (tramp-set-completion-function
920 "ssh1_old" tramp-completion-function-alist-ssh)
921 (tramp-set-completion-function
922 "ssh2_old" tramp-completion-function-alist-ssh)
923 (tramp-set-completion-function
924 "remsh" tramp-completion-function-alist-rsh)
925 (tramp-set-completion-function
926 "telnet" tramp-completion-function-alist-telnet)
927 (tramp-set-completion-function
928 "su" tramp-completion-function-alist-su)
929 (tramp-set-completion-function
930 "sudo" tramp-completion-function-alist-su)
931 (tramp-set-completion-function
932 "scpx" tramp-completion-function-alist-ssh)
933 (tramp-set-completion-function
934 "sshx" tramp-completion-function-alist-ssh)
935 (tramp-set-completion-function
936 "krlogin" tramp-completion-function-alist-rsh)
937 (tramp-set-completion-function
938 "plink" tramp-completion-function-alist-ssh)
939 (tramp-set-completion-function
940 "plink1" tramp-completion-function-alist-ssh)
941 (tramp-set-completion-function
942 "plinkx" tramp-completion-function-alist-putty)
943 (tramp-set-completion-function
944 "pscp" tramp-completion-function-alist-ssh)
945 (tramp-set-completion-function
946 "fcp" tramp-completion-function-alist-ssh)))
948 (defconst tramp-echo-mark-marker "_echo"
949 "String marker to surround echoed commands.")
951 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
952 "String length of `tramp-echo-mark-marker'.")
954 (defconst tramp-echo-mark
955 (concat tramp-echo-mark-marker
956 (make-string tramp-echo-mark-marker-length ?\b))
957 "String mark to be transmitted around shell commands.
958 Used to separate their echo from the output they produce. This
959 will only be used if we cannot disable remote echo via stty.
960 This string must have no effect on the remote shell except for
961 producing some echo which can later be detected by
962 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
963 followed by an equal number of backspaces to erase them will
964 usually suffice.")
966 (defconst tramp-echoed-echo-mark-regexp
967 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
968 tramp-echo-mark-marker tramp-echo-mark-marker-length)
969 "Regexp which matches `tramp-echo-mark' as it gets echoed by
970 the remote shell.")
972 (defcustom tramp-rsh-end-of-line "\n"
973 "*String used for end of line in rsh connections.
974 I don't think this ever needs to be changed, so please tell me about it
975 if you need to change this.
976 Also see the method parameter `tramp-password-end-of-line' and the normal
977 variable `tramp-default-password-end-of-line'."
978 :group 'tramp
979 :type 'string)
981 (defcustom tramp-default-password-end-of-line
982 tramp-rsh-end-of-line
983 "*String used for end of line after sending a password.
984 This variable provides the default value for the method parameter
985 `tramp-password-end-of-line', see `tramp-methods' for more details.
987 It seems that people using plink under Windows need to send
988 \"\\r\\n\" (carriage-return, then newline) after a password, but just
989 \"\\n\" after all other lines. This variable can be used for the
990 password, see `tramp-rsh-end-of-line' for the other cases.
992 The default value is to use the same value as `tramp-rsh-end-of-line'."
993 :group 'tramp
994 :type 'string)
996 ;; "getconf PATH" yields:
997 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
998 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
999 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1000 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1001 (defcustom tramp-remote-path
1002 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1003 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1004 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1005 "*List of directories to search for executables on remote host.
1006 For every remote host, this variable will be set buffer local,
1007 keeping the list of existing directories on that host.
1009 You can use `~' in this list, but when searching for a shell which groks
1010 tilde expansion, all directory names starting with `~' will be ignored.
1012 `Default Directories' represent the list of directories given by
1013 the command \"getconf PATH\". It is recommended to use this
1014 entry on top of this list, because these are the default
1015 directories for POSIX compatible commands.
1017 `Private Directories' are the settings of the $PATH environment,
1018 as given in your `~/.profile'."
1019 :group 'tramp
1020 :type '(repeat (choice
1021 (const :tag "Default Directories" tramp-default-remote-path)
1022 (const :tag "Private Directories" tramp-own-remote-path)
1023 (string :tag "Directory"))))
1025 (defcustom tramp-remote-process-environment
1026 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1027 ,(concat "TERM=" tramp-terminal-type)
1028 "EMACS=t" ;; Deprecated.
1029 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
1030 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1031 "autocorrect=" "correct=")
1033 "*List of environment variables to be set on the remote host.
1035 Each element should be a string of the form ENVVARNAME=VALUE. An
1036 entry ENVVARNAME= diables the corresponding environment variable,
1037 which might have been set in the init files like ~/.profile.
1039 Special handling is applied to the PATH environment, which should
1040 not be set here. Instead of, it should be set via `tramp-remote-path'."
1041 :group 'tramp
1042 :type '(repeat string))
1044 (defcustom tramp-login-prompt-regexp
1045 ".*ogin\\( .*\\)?: *"
1046 "*Regexp matching login-like prompts.
1047 The regexp should match at end of buffer.
1049 Sometimes the prompt is reported to look like \"login as:\"."
1050 :group 'tramp
1051 :type 'regexp)
1053 (defcustom tramp-shell-prompt-pattern
1054 ;; Allow a prompt to start right after a ^M since it indeed would be
1055 ;; displayed at the beginning of the line (and Zsh uses it).
1056 "\\(?:^\\|\r\\)[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
1057 "Regexp to match prompts from remote shell.
1058 Normally, Tramp expects you to configure `shell-prompt-pattern'
1059 correctly, but sometimes it happens that you are connecting to a
1060 remote host which sends a different kind of shell prompt. Therefore,
1061 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1062 and also things matched by this variable. The default value of this
1063 variable is similar to the default value of `shell-prompt-pattern',
1064 which should work well in many cases.
1066 This regexp must match both `tramp-initial-end-of-output' and
1067 `tramp-end-of-output'."
1068 :group 'tramp
1069 :type 'regexp)
1071 (defcustom tramp-password-prompt-regexp
1072 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1073 "*Regexp matching password-like prompts.
1074 The regexp should match at end of buffer.
1076 The `sudo' program appears to insert a `^@' character into the prompt."
1077 :group 'tramp
1078 :type 'regexp)
1080 (defcustom tramp-wrong-passwd-regexp
1081 (concat "^.*"
1082 ;; These strings should be on the last line
1083 (regexp-opt '("Permission denied"
1084 "Login incorrect"
1085 "Login Incorrect"
1086 "Connection refused"
1087 "Connection closed"
1088 "Timeout, server not responding."
1089 "Sorry, try again."
1090 "Name or service not known"
1091 "Host key verification failed."
1092 "No supported authentication methods left to try!") t)
1093 ".*"
1094 "\\|"
1095 "^.*\\("
1096 ;; Here comes a list of regexes, separated by \\|
1097 "Received signal [0-9]+"
1098 "\\).*")
1099 "*Regexp matching a `login failed' message.
1100 The regexp should match at end of buffer."
1101 :group 'tramp
1102 :type 'regexp)
1104 (defcustom tramp-yesno-prompt-regexp
1105 (concat
1106 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1107 "\\s-*")
1108 "Regular expression matching all yes/no queries which need to be confirmed.
1109 The confirmation should be done with yes or no.
1110 The regexp should match at end of buffer.
1111 See also `tramp-yn-prompt-regexp'."
1112 :group 'tramp
1113 :type 'regexp)
1115 (defcustom tramp-yn-prompt-regexp
1116 (concat
1117 (regexp-opt '("Store key in cache? (y/n)"
1118 "Update cached key? (y/n, Return cancels connection)") t)
1119 "\\s-*")
1120 "Regular expression matching all y/n queries which need to be confirmed.
1121 The confirmation should be done with y or n.
1122 The regexp should match at end of buffer.
1123 See also `tramp-yesno-prompt-regexp'."
1124 :group 'tramp
1125 :type 'regexp)
1127 (defcustom tramp-terminal-prompt-regexp
1128 (concat "\\("
1129 "TERM = (.*)"
1130 "\\|"
1131 "Terminal type\\? \\[.*\\]"
1132 "\\)\\s-*")
1133 "Regular expression matching all terminal setting prompts.
1134 The regexp should match at end of buffer.
1135 The answer will be provided by `tramp-action-terminal', which see."
1136 :group 'tramp
1137 :type 'regexp)
1139 (defcustom tramp-operation-not-permitted-regexp
1140 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1141 (regexp-opt '("Operation not permitted") t))
1142 "Regular expression matching keep-date problems in (s)cp operations.
1143 Copying has been performed successfully already, so this message can
1144 be ignored safely."
1145 :group 'tramp
1146 :type 'regexp)
1148 (defcustom tramp-copy-failed-regexp
1149 (concat "\\(.+: "
1150 (regexp-opt '("Permission denied"
1151 "not a regular file"
1152 "is a directory"
1153 "No such file or directory") t)
1154 "\\)\\s-*")
1155 "Regular expression matching copy problems in (s)cp operations."
1156 :group 'tramp
1157 :type 'regexp)
1159 (defcustom tramp-process-alive-regexp
1161 "Regular expression indicating a process has finished.
1162 In fact this expression is empty by intention, it will be used only to
1163 check regularly the status of the associated process.
1164 The answer will be provided by `tramp-action-process-alive',
1165 `tramp-action-out-of-band', which see."
1166 :group 'tramp
1167 :type 'regexp)
1169 (defcustom tramp-temp-name-prefix "tramp."
1170 "*Prefix to use for temporary files.
1171 If this is a relative file name (such as \"tramp.\"), it is considered
1172 relative to the directory name returned by the function
1173 `tramp-compat-temporary-file-directory' (which see). It may also be an
1174 absolute file name; don't forget to include a prefix for the filename
1175 part, though."
1176 :group 'tramp
1177 :type 'string)
1179 (defconst tramp-temp-buffer-name " *tramp temp*"
1180 "Buffer name for a temporary buffer.
1181 It shall be used in combination with `generate-new-buffer-name'.")
1183 (defvar tramp-temp-buffer-file-name nil
1184 "File name of a persistent local temporary file.
1185 Useful for \"rsync\" like methods.")
1186 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1188 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1189 "*Alist specifying extra arguments to pass to the remote shell.
1190 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1191 matching the shell file name and ARGS is a string specifying the
1192 arguments.
1194 This variable is only used when Tramp needs to start up another shell
1195 for tilde expansion. The extra arguments should typically prevent the
1196 shell from reading its init file."
1197 :group 'tramp
1198 ;; This might be the wrong way to test whether the widget type
1199 ;; `alist' is available. Who knows the right way to test it?
1200 :type (if (get 'alist 'widget-type)
1201 '(alist :key-type string :value-type string)
1202 '(repeat (cons string string))))
1204 ;; XEmacs is distributed with few Lisp packages. Further packages are
1205 ;; installed using EFS. If we use a unified filename format, then
1206 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1207 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1208 ;; just like before.) Another reason for using a separate filename
1209 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1210 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1211 ;; the other places.
1213 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1214 ;;;###autoload
1215 (defcustom tramp-syntax
1216 (if (featurep 'xemacs) 'sep 'ftp)
1217 "Tramp filename syntax to be used.
1219 It can have the following values:
1221 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1222 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1223 'url -- URL-like syntax."
1224 :group 'tramp
1225 :type (if (featurep 'xemacs)
1226 '(choice (const :tag "EFS" ftp)
1227 (const :tag "XEmacs" sep)
1228 (const :tag "URL" url))
1229 '(choice (const :tag "Ange-FTP" ftp)
1230 (const :tag "URL" url))))
1232 (defconst tramp-prefix-format
1233 (cond ((equal tramp-syntax 'ftp) "/")
1234 ((equal tramp-syntax 'sep) "/[")
1235 ((equal tramp-syntax 'url) "/")
1236 (t (error "Wrong `tramp-syntax' defined")))
1237 "*String matching the very beginning of Tramp file names.
1238 Used in `tramp-make-tramp-file-name'.")
1240 (defconst tramp-prefix-regexp
1241 (concat "^" (regexp-quote tramp-prefix-format))
1242 "*Regexp matching the very beginning of Tramp file names.
1243 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1245 (defconst tramp-method-regexp
1246 "[a-zA-Z_0-9-]+"
1247 "*Regexp matching methods identifiers.")
1249 (defconst tramp-postfix-method-format
1250 (cond ((equal tramp-syntax 'ftp) ":")
1251 ((equal tramp-syntax 'sep) "/")
1252 ((equal tramp-syntax 'url) "://")
1253 (t (error "Wrong `tramp-syntax' defined")))
1254 "*String matching delimeter between method and user or host names.
1255 Used in `tramp-make-tramp-file-name'.")
1257 (defconst tramp-postfix-method-regexp
1258 (regexp-quote tramp-postfix-method-format)
1259 "*Regexp matching delimeter between method and user or host names.
1260 Derived from `tramp-postfix-method-format'.")
1262 (defconst tramp-user-regexp
1263 "[^:/ \t]+"
1264 "*Regexp matching user names.")
1266 (defconst tramp-prefix-domain-format "%"
1267 "*String matching delimeter between user and domain names.")
1269 (defconst tramp-prefix-domain-regexp
1270 (regexp-quote tramp-prefix-domain-format)
1271 "*Regexp matching delimeter between user and domain names.
1272 Derived from `tramp-prefix-domain-format'.")
1274 (defconst tramp-domain-regexp
1275 "[-a-zA-Z0-9_.]+"
1276 "*Regexp matching domain names.")
1278 (defconst tramp-user-with-domain-regexp
1279 (concat "\\(" tramp-user-regexp "\\)"
1280 tramp-prefix-domain-regexp
1281 "\\(" tramp-domain-regexp "\\)")
1282 "*Regexp matching user names with domain names.")
1284 (defconst tramp-postfix-user-format
1286 "*String matching delimeter between user and host names.
1287 Used in `tramp-make-tramp-file-name'.")
1289 (defconst tramp-postfix-user-regexp
1290 (regexp-quote tramp-postfix-user-format)
1291 "*Regexp matching delimeter between user and host names.
1292 Derived from `tramp-postfix-user-format'.")
1294 (defconst tramp-host-regexp
1295 "[a-zA-Z0-9_.-]+"
1296 "*Regexp matching host names.")
1298 (defconst tramp-prefix-ipv6-format
1299 (cond ((equal tramp-syntax 'ftp) "[")
1300 ((equal tramp-syntax 'sep) "")
1301 ((equal tramp-syntax 'url) "[")
1302 (t (error "Wrong `tramp-syntax' defined")))
1303 "*String matching left hand side of IPv6 addresses.
1304 Used in `tramp-make-tramp-file-name'.")
1306 (defconst tramp-prefix-ipv6-regexp
1307 (regexp-quote tramp-prefix-ipv6-format)
1308 "*Regexp matching left hand side of IPv6 addresses.
1309 Derived from `tramp-prefix-ipv6-format'.")
1311 ;; The following regexp is a bit sloppy. But it shall serve our
1312 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1313 ;; "::ffff:192.168.0.1".
1314 (defconst tramp-ipv6-regexp
1315 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1316 "*Regexp matching IPv6 addresses.")
1318 (defconst tramp-postfix-ipv6-format
1319 (cond ((equal tramp-syntax 'ftp) "]")
1320 ((equal tramp-syntax 'sep) "")
1321 ((equal tramp-syntax 'url) "]")
1322 (t (error "Wrong `tramp-syntax' defined")))
1323 "*String matching right hand side of IPv6 addresses.
1324 Used in `tramp-make-tramp-file-name'.")
1326 (defconst tramp-postfix-ipv6-regexp
1327 (regexp-quote tramp-postfix-ipv6-format)
1328 "*Regexp matching right hand side of IPv6 addresses.
1329 Derived from `tramp-postfix-ipv6-format'.")
1331 (defconst tramp-prefix-port-format
1332 (cond ((equal tramp-syntax 'ftp) "#")
1333 ((equal tramp-syntax 'sep) "#")
1334 ((equal tramp-syntax 'url) ":")
1335 (t (error "Wrong `tramp-syntax' defined")))
1336 "*String matching delimeter between host names and port numbers.")
1338 (defconst tramp-prefix-port-regexp
1339 (regexp-quote tramp-prefix-port-format)
1340 "*Regexp matching delimeter between host names and port numbers.
1341 Derived from `tramp-prefix-port-format'.")
1343 (defconst tramp-port-regexp
1344 "[0-9]+"
1345 "*Regexp matching port numbers.")
1347 (defconst tramp-host-with-port-regexp
1348 (concat "\\(" tramp-host-regexp "\\)"
1349 tramp-prefix-port-regexp
1350 "\\(" tramp-port-regexp "\\)")
1351 "*Regexp matching host names with port numbers.")
1353 (defconst tramp-postfix-host-format
1354 (cond ((equal tramp-syntax 'ftp) ":")
1355 ((equal tramp-syntax 'sep) "]")
1356 ((equal tramp-syntax 'url) "")
1357 (t (error "Wrong `tramp-syntax' defined")))
1358 "*String matching delimeter between host names and localnames.
1359 Used in `tramp-make-tramp-file-name'.")
1361 (defconst tramp-postfix-host-regexp
1362 (regexp-quote tramp-postfix-host-format)
1363 "*Regexp matching delimeter between host names and localnames.
1364 Derived from `tramp-postfix-host-format'.")
1366 (defconst tramp-localname-regexp
1367 ".*$"
1368 "*Regexp matching localnames.")
1370 ;; File name format.
1372 (defconst tramp-file-name-structure
1373 (list
1374 (concat
1375 tramp-prefix-regexp
1376 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1377 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1378 "\\(" "\\(" tramp-host-regexp
1379 "\\|"
1380 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1381 tramp-postfix-ipv6-regexp "\\)"
1382 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1383 tramp-postfix-host-regexp
1384 "\\(" tramp-localname-regexp "\\)")
1385 2 4 5 8)
1387 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1388 the Tramp file name structure.
1390 The first element REGEXP is a regular expression matching a Tramp file
1391 name. The regex should contain parentheses around the method name,
1392 the user name, the host name, and the file name parts.
1394 The second element METHOD is a number, saying which pair of
1395 parentheses matches the method name. The third element USER is
1396 similar, but for the user name. The fourth element HOST is similar,
1397 but for the host name. The fifth element FILE is for the file name.
1398 These numbers are passed directly to `match-string', which see. That
1399 means the opening parentheses are counted to identify the pair.
1401 See also `tramp-file-name-regexp'.")
1403 ;;;###autoload
1404 (defconst tramp-file-name-regexp-unified
1405 "\\`/\\([^[/:]+\\|[^/]+]\\):"
1406 "Value for `tramp-file-name-regexp' for unified remoting.
1407 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1408 Tramp. See `tramp-file-name-structure' for more explanations.")
1410 ;;;###autoload
1411 (defconst tramp-file-name-regexp-separate
1412 "\\`/\\[.*\\]"
1413 "Value for `tramp-file-name-regexp' for separate remoting.
1414 XEmacs uses a separate filename syntax for Tramp and EFS.
1415 See `tramp-file-name-structure' for more explanations.")
1417 ;;;###autoload
1418 (defconst tramp-file-name-regexp-url
1419 "\\`/[^/:]+://"
1420 "Value for `tramp-file-name-regexp' for URL-like remoting.
1421 See `tramp-file-name-structure' for more explanations.")
1423 ;;;###autoload
1424 (defconst tramp-file-name-regexp
1425 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1426 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1427 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1428 (t (error "Wrong `tramp-syntax' defined")))
1429 "*Regular expression matching file names handled by Tramp.
1430 This regexp should match Tramp file names but no other file names.
1431 \(When tramp.el is loaded, this regular expression is prepended to
1432 `file-name-handler-alist', and that is searched sequentially. Thus,
1433 if the Tramp entry appears rather early in the `file-name-handler-alist'
1434 and is a bit too general, then some files might be considered Tramp
1435 files which are not really Tramp files.
1437 Please note that the entry in `file-name-handler-alist' is made when
1438 this file (tramp.el) is loaded. This means that this variable must be set
1439 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1440 updated after changing this variable.
1442 Also see `tramp-file-name-structure'.")
1444 ;;;###autoload
1445 (defconst tramp-root-regexp
1446 (if (memq system-type '(cygwin windows-nt))
1447 "\\`\\([a-zA-Z]:\\)?/"
1448 "\\`/")
1449 "Beginning of an incomplete Tramp file name.
1450 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1451 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1453 ;;;###autoload
1454 (defconst tramp-completion-file-name-regexp-unified
1455 (concat tramp-root-regexp "[^/]*\\'")
1456 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1457 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1458 See `tramp-file-name-structure' for more explanations.")
1460 ;;;###autoload
1461 (defconst tramp-completion-file-name-regexp-separate
1462 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1463 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1464 XEmacs uses a separate filename syntax for Tramp and EFS.
1465 See `tramp-file-name-structure' for more explanations.")
1467 ;;;###autoload
1468 (defconst tramp-completion-file-name-regexp-url
1469 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1470 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1471 See `tramp-file-name-structure' for more explanations.")
1473 ;;;###autoload
1474 (defconst tramp-completion-file-name-regexp
1475 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1476 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1477 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1478 (t (error "Wrong `tramp-syntax' defined")))
1479 "*Regular expression matching file names handled by Tramp completion.
1480 This regexp should match partial Tramp file names only.
1482 Please note that the entry in `file-name-handler-alist' is made when
1483 this file (tramp.el) is loaded. This means that this variable must be set
1484 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1485 updated after changing this variable.
1487 Also see `tramp-file-name-structure'.")
1489 (defconst tramp-actions-before-shell
1490 '((tramp-login-prompt-regexp tramp-action-login)
1491 (tramp-password-prompt-regexp tramp-action-password)
1492 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1493 (shell-prompt-pattern tramp-action-succeed)
1494 (tramp-shell-prompt-pattern tramp-action-succeed)
1495 (tramp-yesno-prompt-regexp tramp-action-yesno)
1496 (tramp-yn-prompt-regexp tramp-action-yn)
1497 (tramp-terminal-prompt-regexp tramp-action-terminal)
1498 (tramp-process-alive-regexp tramp-action-process-alive))
1499 "List of pattern/action pairs.
1500 Whenever a pattern matches, the corresponding action is performed.
1501 Each item looks like (PATTERN ACTION).
1503 The PATTERN should be a symbol, a variable. The value of this
1504 variable gives the regular expression to search for. Note that the
1505 regexp must match at the end of the buffer, \"\\'\" is implicitly
1506 appended to it.
1508 The ACTION should also be a symbol, but a function. When the
1509 corresponding PATTERN matches, the ACTION function is called.")
1511 (defconst tramp-actions-copy-out-of-band
1512 '((tramp-password-prompt-regexp tramp-action-password)
1513 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1514 (tramp-copy-failed-regexp tramp-action-permission-denied)
1515 (tramp-process-alive-regexp tramp-action-out-of-band))
1516 "List of pattern/action pairs.
1517 This list is used for copying/renaming with out-of-band methods.
1519 See `tramp-actions-before-shell' for more info.")
1521 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1522 ;; known to have a bug in `process-send-string'; some ssh connections appear
1523 ;; to drop bytes when data is sent too quickly. There is also a connection
1524 ;; buffer local variable, which is computed depending on remote host properties
1525 ;; when `tramp-chunksize' is zero or nil.
1526 (defcustom tramp-chunksize
1527 (when (and (not (featurep 'xemacs))
1528 (memq system-type '(hpux)))
1529 500)
1530 ;; Parentheses in docstring starting at beginning of line are escaped.
1531 ;; Fontification is messed up when
1532 ;; `open-paren-in-column-0-is-defun-start' set to t.
1533 "*If non-nil, chunksize for sending input to local process.
1534 It is necessary only on systems which have a buggy `process-send-string'
1535 implementation. The necessity, whether this variable must be set, can be
1536 checked via the following code:
1538 (with-temp-buffer
1539 (let* ((user \"xxx\") (host \"yyy\")
1540 (init 0) (step 50)
1541 (sent init) (received init))
1542 (while (= sent received)
1543 (setq sent (+ sent step))
1544 (erase-buffer)
1545 (let ((proc (start-process (buffer-name) (current-buffer)
1546 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1547 (when (memq (process-status proc) '(run open))
1548 (process-send-string proc (make-string sent ?\\ ))
1549 (process-send-eof proc)
1550 (process-send-eof proc))
1551 (while (not (progn (goto-char (point-min))
1552 (re-search-forward \"\\\\w+\" (point-max) t)))
1553 (accept-process-output proc 1))
1554 (when (memq (process-status proc) '(run open))
1555 (setq received (string-to-number (match-string 0)))
1556 (delete-process proc)
1557 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1558 (sit-for 0))))
1559 (if (> sent (+ init step))
1560 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1561 (- sent step))
1562 (message \"Test does not work\")
1563 (display-buffer (current-buffer))
1564 (sit-for 30))))
1566 In the Emacs normally running Tramp, evaluate the above code
1567 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1568 respectively). You can do this, for example, by pasting it into
1569 the `*scratch*' buffer and then hitting C-j with the cursor after the
1570 last closing parenthesis. Note that it works only if you have configured
1571 \"ssh\" to run without password query, see ssh-agent(1).
1573 You will see the number of bytes sent successfully to the remote host.
1574 If that number exceeds 1000, you can stop the execution by hitting
1575 C-g, because your Emacs is likely clean.
1577 When it is necessary to set `tramp-chunksize', you might consider to
1578 use an out-of-the-band method (like \"scp\") instead of an internal one
1579 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
1580 performance.
1582 If your Emacs is buggy, the code stops and gives you an indication
1583 about the value `tramp-chunksize' should be set. Maybe you could just
1584 experiment a bit, e.g. changing the values of `init' and `step'
1585 in the third line of the code.
1587 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1588 this variable to be set as well."
1589 :group 'tramp
1590 :type '(choice (const nil) integer))
1592 ;; Logging in to a remote host normally requires obtaining a pty. But
1593 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1594 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1595 ;; for an override of the system default.
1596 (defcustom tramp-process-connection-type t
1597 "Overrides `process-connection-type' for connections from Tramp.
1598 Tramp binds process-connection-type to the value given here before
1599 opening a connection to a remote host."
1600 :group 'tramp
1601 :type '(choice (const nil) (const t) (const pty)))
1603 (defcustom tramp-completion-reread-directory-timeout 10
1604 "Defines seconds since last remote command before rereading a directory.
1605 A remote directory might have changed its contents. In order to
1606 make it visible during file name completion in the minibuffer,
1607 Tramp flushes its cache and rereads the directory contents when
1608 more than `tramp-completion-reread-directory-timeout' seconds
1609 have been gone since last remote command execution. A value of 0
1610 would require an immediate reread during filename completion, nil
1611 means to use always cached values for the directory contents."
1612 :group 'tramp
1613 :type '(choice (const nil) integer))
1615 ;;; Internal Variables:
1617 (defvar tramp-current-method nil
1618 "Connection method for this *tramp* buffer.")
1620 (defvar tramp-current-user nil
1621 "Remote login name for this *tramp* buffer.")
1623 (defvar tramp-current-host nil
1624 "Remote host for this *tramp* buffer.")
1626 (defconst tramp-uudecode
1627 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1628 cat /tmp/tramp.$$
1629 rm -f /tmp/tramp.$$"
1630 "Shell function to implement `uudecode' to standard output.
1631 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1632 for this or `uudecode -p', but some systems don't, and for them
1633 we have this shell function.")
1635 (defconst tramp-perl-file-truename
1636 "%s -e '
1637 use File::Spec;
1638 use Cwd \"realpath\";
1640 sub recursive {
1641 my ($volume, @dirs) = @_;
1642 my $real = realpath(File::Spec->catpath(
1643 $volume, File::Spec->catdir(@dirs), \"\"));
1644 if ($real) {
1645 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1646 return ($vol, File::Spec->splitdir($dir));
1648 else {
1649 my $last = pop(@dirs);
1650 ($volume, @dirs) = recursive($volume, @dirs);
1651 push(@dirs, $last);
1652 return ($volume, @dirs);
1656 $result = realpath($ARGV[0]);
1657 if (!$result) {
1658 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1659 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1661 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1664 if ($ARGV[0] =~ /\\/$/) {
1665 $result = $result . \"/\";
1668 print \"\\\"$result\\\"\\n\";
1669 ' \"$1\" 2>/dev/null"
1670 "Perl script to produce output suitable for use with `file-truename'
1671 on the remote file system.
1672 Escape sequence %s is replaced with name of Perl binary.
1673 This string is passed to `format', so percent characters need to be doubled.")
1675 (defconst tramp-perl-file-name-all-completions
1676 "%s -e 'sub case {
1677 my $str = shift;
1678 if ($ARGV[2]) {
1679 return lc($str);
1681 else {
1682 return $str;
1685 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1686 @files = readdir(d); closedir(d);
1687 foreach $f (@files) {
1688 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1689 if (-d \"$ARGV[0]/$f\") {
1690 print \"$f/\\n\";
1692 else {
1693 print \"$f\\n\";
1697 print \"ok\\n\"
1698 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1699 "Perl script to produce output suitable for use with
1700 `file-name-all-completions' on the remote file system. Escape
1701 sequence %s is replaced with name of Perl binary. This string is
1702 passed to `format', so percent characters need to be doubled.")
1704 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1705 ;; output. If you are hacking on this, note that you get *no* output
1706 ;; unless this spits out a complete line, including the '\n' at the
1707 ;; end.
1708 ;; The device number is returned as "-1", because there will be a virtual
1709 ;; device number set in `tramp-handle-file-attributes'.
1710 (defconst tramp-perl-file-attributes
1711 "%s -e '
1712 @stat = lstat($ARGV[0]);
1713 if (!@stat) {
1714 print \"nil\\n\";
1715 exit 0;
1717 if (($stat[2] & 0170000) == 0120000)
1719 $type = readlink($ARGV[0]);
1720 $type = \"\\\"$type\\\"\";
1722 elsif (($stat[2] & 0170000) == 040000)
1724 $type = \"t\";
1726 else
1728 $type = \"nil\"
1730 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1731 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1732 printf(
1733 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1734 $type,
1735 $stat[3],
1736 $uid,
1737 $gid,
1738 $stat[8] >> 16 & 0xffff,
1739 $stat[8] & 0xffff,
1740 $stat[9] >> 16 & 0xffff,
1741 $stat[9] & 0xffff,
1742 $stat[10] >> 16 & 0xffff,
1743 $stat[10] & 0xffff,
1744 $stat[7],
1745 $stat[2],
1746 $stat[1] >> 16 & 0xffff,
1747 $stat[1] & 0xffff
1748 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1749 "Perl script to produce output suitable for use with `file-attributes'
1750 on the remote file system.
1751 Escape sequence %s is replaced with name of Perl binary.
1752 This string is passed to `format', so percent characters need to be doubled.")
1754 (defconst tramp-perl-directory-files-and-attributes
1755 "%s -e '
1756 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1757 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1758 @list = readdir(DIR);
1759 closedir(DIR);
1760 $n = scalar(@list);
1761 printf(\"(\\n\");
1762 for($i = 0; $i < $n; $i++)
1764 $filename = $list[$i];
1765 @stat = lstat($filename);
1766 if (($stat[2] & 0170000) == 0120000)
1768 $type = readlink($filename);
1769 $type = \"\\\"$type\\\"\";
1771 elsif (($stat[2] & 0170000) == 040000)
1773 $type = \"t\";
1775 else
1777 $type = \"nil\"
1779 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1780 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1781 printf(
1782 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1783 $filename,
1784 $type,
1785 $stat[3],
1786 $uid,
1787 $gid,
1788 $stat[8] >> 16 & 0xffff,
1789 $stat[8] & 0xffff,
1790 $stat[9] >> 16 & 0xffff,
1791 $stat[9] & 0xffff,
1792 $stat[10] >> 16 & 0xffff,
1793 $stat[10] & 0xffff,
1794 $stat[7],
1795 $stat[2],
1796 $stat[1] >> 16 & 0xffff,
1797 $stat[1] & 0xffff,
1798 $stat[0] >> 16 & 0xffff,
1799 $stat[0] & 0xffff);
1801 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1802 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1803 output.
1804 Escape sequence %s is replaced with name of Perl binary.
1805 This string is passed to `format', so percent characters need to be doubled.")
1807 ;; ;; These two use uu encoding.
1808 ;; (defvar tramp-perl-encode "%s -e'\
1809 ;; print qq(begin 644 xxx\n);
1810 ;; my $s = q();
1811 ;; my $res = q();
1812 ;; while (read(STDIN, $s, 45)) {
1813 ;; print pack(q(u), $s);
1814 ;; }
1815 ;; print qq(`\n);
1816 ;; print qq(end\n);
1817 ;; '"
1818 ;; "Perl program to use for encoding a file.
1819 ;; Escape sequence %s is replaced with name of Perl binary.")
1821 ;; (defvar tramp-perl-decode "%s -ne '
1822 ;; print unpack q(u), $_;
1823 ;; '"
1824 ;; "Perl program to use for decoding a file.
1825 ;; Escape sequence %s is replaced with name of Perl binary.")
1827 ;; These two use base64 encoding.
1828 (defconst tramp-perl-encode-with-module
1829 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1830 "Perl program to use for encoding a file.
1831 Escape sequence %s is replaced with name of Perl binary.
1832 This string is passed to `format', so percent characters need to be doubled.
1833 This implementation requires the MIME::Base64 Perl module to be installed
1834 on the remote host.")
1836 (defconst tramp-perl-decode-with-module
1837 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1838 "Perl program to use for decoding a file.
1839 Escape sequence %s is replaced with name of Perl binary.
1840 This string is passed to `format', so percent characters need to be doubled.
1841 This implementation requires the MIME::Base64 Perl module to be installed
1842 on the remote host.")
1844 (defconst tramp-perl-encode
1845 "%s -e '
1846 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1847 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1848 # Free Software Foundation, Inc.
1849 use strict;
1851 my %%trans = do {
1852 my $i = 0;
1853 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1854 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1857 binmode(\\*STDIN);
1859 # We read in chunks of 54 bytes, to generate output lines
1860 # of 72 chars (plus end of line)
1861 $/ = \\54;
1863 while (my $data = <STDIN>) {
1864 my $pad = q();
1866 # Only for the last chunk, and only if did not fill the last three-byte packet
1867 if (eof) {
1868 my $mod = length($data) %% 3;
1869 $pad = q(=) x (3 - $mod) if $mod;
1872 # Not the fastest method, but it is simple: unpack to binary string, split
1873 # by groups of 6 bits and convert back from binary to byte; then map into
1874 # the translation table
1875 print
1876 join q(),
1877 map($trans{$_},
1878 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1879 $pad,
1880 qq(\\n);
1881 }' 2>/dev/null"
1882 "Perl program to use for encoding a file.
1883 Escape sequence %s is replaced with name of Perl binary.
1884 This string is passed to `format', so percent characters need to be doubled.")
1886 (defconst tramp-perl-decode
1887 "%s -e '
1888 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1889 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1890 # Free Software Foundation, Inc.
1891 use strict;
1893 my %%trans = do {
1894 my $i = 0;
1895 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1896 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1899 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1901 binmode(\\*STDOUT);
1903 # We are going to accumulate into $pending to accept any line length
1904 # (we do not check they are <= 76 chars as the RFC says)
1905 my $pending = q();
1907 while (my $data = <STDIN>) {
1908 chomp $data;
1910 # If we find one or two =, we have reached the end and
1911 # any following data is to be discarded
1912 my $finished = $data =~ s/(==?).*/$1/;
1913 $pending .= $data;
1915 my $len = length($pending);
1916 my $chunk = substr($pending, 0, $len & ~3);
1917 $pending = substr($pending, $len & ~3 + 1);
1919 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1920 # split in 8-bit chunks and convert back to char.
1921 print join q(),
1922 map $bytes{$_},
1923 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1925 last if $finished;
1926 }' 2>/dev/null"
1927 "Perl program to use for decoding a file.
1928 Escape sequence %s is replaced with name of Perl binary.
1929 This string is passed to `format', so percent characters need to be doubled.")
1931 (defconst tramp-vc-registered-read-file-names
1932 "echo \"(\"
1933 for file in \"$@\"; do
1934 if %s $file; then
1935 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1936 else
1937 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1939 if %s $file; then
1940 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1941 else
1942 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1944 done
1945 echo \")\""
1946 "Script to check existence of VC related files.
1947 It must be send formatted with two strings; the tests for file
1948 existence, and file readability.")
1950 (defconst tramp-file-mode-type-map
1951 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1952 (1 . "p") ; fifo
1953 (2 . "c") ; character device
1954 (3 . "m") ; multiplexed character device (v7)
1955 (4 . "d") ; directory
1956 (5 . "?") ; Named special file (XENIX)
1957 (6 . "b") ; block device
1958 (7 . "?") ; multiplexed block device (v7)
1959 (8 . "-") ; regular file
1960 (9 . "n") ; network special file (HP-UX)
1961 (10 . "l") ; symlink
1962 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1963 (12 . "s") ; socket
1964 (13 . "D") ; door special (Solaris)
1965 (14 . "w")) ; whiteout (BSD)
1966 "A list of file types returned from the `stat' system call.
1967 This is used to map a mode number to a permission string.")
1969 ;; New handlers should be added here. The following operations can be
1970 ;; handled using the normal primitives: file-name-sans-versions,
1971 ;; get-file-buffer.
1972 (defconst tramp-file-name-handler-alist
1973 '((load . tramp-handle-load)
1974 (make-symbolic-link . tramp-handle-make-symbolic-link)
1975 (file-name-as-directory . tramp-handle-file-name-as-directory)
1976 (file-name-directory . tramp-handle-file-name-directory)
1977 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1978 (file-truename . tramp-handle-file-truename)
1979 (file-exists-p . tramp-handle-file-exists-p)
1980 (file-directory-p . tramp-handle-file-directory-p)
1981 (file-executable-p . tramp-handle-file-executable-p)
1982 (file-readable-p . tramp-handle-file-readable-p)
1983 (file-regular-p . tramp-handle-file-regular-p)
1984 (file-symlink-p . tramp-handle-file-symlink-p)
1985 (file-writable-p . tramp-handle-file-writable-p)
1986 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1987 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1988 (file-attributes . tramp-handle-file-attributes)
1989 (file-modes . tramp-handle-file-modes)
1990 (directory-files . tramp-handle-directory-files)
1991 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1992 (file-name-all-completions . tramp-handle-file-name-all-completions)
1993 (file-name-completion . tramp-handle-file-name-completion)
1994 (add-name-to-file . tramp-handle-add-name-to-file)
1995 (copy-file . tramp-handle-copy-file)
1996 (copy-directory . tramp-handle-copy-directory)
1997 (rename-file . tramp-handle-rename-file)
1998 (set-file-modes . tramp-handle-set-file-modes)
1999 (set-file-times . tramp-handle-set-file-times)
2000 (make-directory . tramp-handle-make-directory)
2001 (delete-directory . tramp-handle-delete-directory)
2002 (delete-file . tramp-handle-delete-file)
2003 (directory-file-name . tramp-handle-directory-file-name)
2004 ;; `executable-find' is not official yet.
2005 (executable-find . tramp-handle-executable-find)
2006 (start-file-process . tramp-handle-start-file-process)
2007 (process-file . tramp-handle-process-file)
2008 (shell-command . tramp-handle-shell-command)
2009 (insert-directory . tramp-handle-insert-directory)
2010 (expand-file-name . tramp-handle-expand-file-name)
2011 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2012 (file-local-copy . tramp-handle-file-local-copy)
2013 (file-remote-p . tramp-handle-file-remote-p)
2014 (insert-file-contents . tramp-handle-insert-file-contents)
2015 (insert-file-contents-literally
2016 . tramp-handle-insert-file-contents-literally)
2017 (write-region . tramp-handle-write-region)
2018 (find-backup-file-name . tramp-handle-find-backup-file-name)
2019 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2020 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2021 (dired-compress-file . tramp-handle-dired-compress-file)
2022 (dired-recursive-delete-directory
2023 . tramp-handle-dired-recursive-delete-directory)
2024 (dired-uncache . tramp-handle-dired-uncache)
2025 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2026 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2027 (vc-registered . tramp-handle-vc-registered))
2028 "Alist of handler functions.
2029 Operations not mentioned here will be handled by the normal Emacs functions.")
2031 ;; Handlers for partial Tramp file names. For Emacs just
2032 ;; `file-name-all-completions' is needed.
2033 ;;;###autoload
2034 (defconst tramp-completion-file-name-handler-alist
2035 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2036 (file-name-completion . tramp-completion-handle-file-name-completion))
2037 "Alist of completion handler functions.
2038 Used for file names matching `tramp-file-name-regexp'. Operations not
2039 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2040 normal Emacs functions.")
2042 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2043 (defvar tramp-foreign-file-name-handler-alist
2044 ;; (identity . tramp-sh-file-name-handler) should always be the last
2045 ;; entry, because `identity' always matches.
2046 '((identity . tramp-sh-file-name-handler))
2047 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2048 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2049 calling HANDLER.")
2051 ;;; Internal functions which must come first:
2053 (defsubst tramp-debug-message (vec fmt-string &rest args)
2054 "Append message to debug buffer.
2055 Message is formatted with FMT-STRING as control string and the remaining
2056 ARGS to actually emit the message (if applicable)."
2057 (when (get-buffer (tramp-buffer-name vec))
2058 (with-current-buffer (tramp-get-debug-buffer vec)
2059 (goto-char (point-max))
2060 ;; Headline.
2061 (when (bobp)
2062 (insert
2063 (format
2064 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2065 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2066 emacs-version tramp-version)))
2067 (unless (bolp)
2068 (insert "\n"))
2069 ;; Timestamp.
2070 (let ((now (current-time)))
2071 (insert (format-time-string "%T." now))
2072 (insert (format "%06d " (nth 2 now))))
2073 ;; Calling function.
2074 (let ((btn 1) btf fn)
2075 (while (not fn)
2076 (setq btf (nth 1 (backtrace-frame btn)))
2077 (if (not btf)
2078 (setq fn "")
2079 (when (symbolp btf)
2080 (setq fn (symbol-name btf))
2081 (unless (and (string-match "^tramp" fn)
2082 (not (string-match
2083 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
2084 fn)))
2085 (setq fn nil)))
2086 (setq btn (1+ btn))))
2087 ;; The following code inserts filename and line number.
2088 ;; Should be deactivated by default, because it is time
2089 ;; consuming.
2090 ; (let ((ffn (find-function-noselect (intern fn))))
2091 ; (insert
2092 ; (format
2093 ; "%s:%d: "
2094 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2095 ; (with-current-buffer (car ffn)
2096 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2097 (insert (format "%s " fn)))
2098 ;; The message.
2099 (insert (apply 'format fmt-string args)))))
2101 (defvar tramp-message-show-message t
2102 "Show Tramp message in the minibuffer.
2103 This variable is used to disable messages from `tramp-error'.
2104 The messages are visible anyway, because an error is raised.")
2106 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2107 "Emit a message depending on verbosity level.
2108 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2109 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2110 less than LEVEL. The message is emitted only if `tramp-verbose' is
2111 greater than or equal to LEVEL.
2113 The message is also logged into the debug buffer when `tramp-verbose'
2114 is greater than or equal 4.
2116 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2117 control string and the remaining ARGS to actually emit the message (if
2118 applicable)."
2119 (condition-case nil
2120 (when (<= level tramp-verbose)
2121 ;; Match data must be preserved!
2122 (save-match-data
2123 ;; Display only when there is a minimum level.
2124 (when (and tramp-message-show-message (<= level 3))
2125 (apply 'message
2126 (concat
2127 (cond
2128 ((= level 0) "")
2129 ((= level 1) "")
2130 ((= level 2) "Warning: ")
2131 (t "Tramp: "))
2132 fmt-string)
2133 args))
2134 ;; Log only when there is a minimum level.
2135 (when (>= tramp-verbose 4)
2136 (when (and vec-or-proc
2137 (processp vec-or-proc)
2138 (buffer-name (process-buffer vec-or-proc)))
2139 (with-current-buffer (process-buffer vec-or-proc)
2140 ;; Translate proc to vec.
2141 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2142 (when (and vec-or-proc (vectorp vec-or-proc))
2143 (apply 'tramp-debug-message
2144 vec-or-proc
2145 (concat (format "(%d) # " level) fmt-string)
2146 args)))))
2147 ;; Suppress all errors.
2148 (error nil)))
2150 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2151 "Emit an error.
2152 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2153 signal identifier to be raised, remaining args passed to
2154 `tramp-message'. Finally, signal SIGNAL is raised."
2155 (let (tramp-message-show-message)
2156 (tramp-message
2157 vec-or-proc 1 "%s"
2158 (error-message-string
2159 (list signal
2160 (get signal 'error-message)
2161 (apply 'format fmt-string args))))
2162 (signal signal (list (apply 'format fmt-string args)))))
2164 (defsubst tramp-error-with-buffer
2165 (buffer vec-or-proc signal fmt-string &rest args)
2166 "Emit an error, and show BUFFER.
2167 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2168 an input event arrives. The other arguments are passed to `tramp-error'."
2169 (save-window-excursion
2170 (unwind-protect
2171 (apply 'tramp-error vec-or-proc signal fmt-string args)
2172 (when (and vec-or-proc (not (zerop tramp-verbose)))
2173 (let ((enable-recursive-minibuffers t))
2174 (pop-to-buffer
2175 (or (and (bufferp buffer) buffer)
2176 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2177 (tramp-get-buffer vec-or-proc)))
2178 (sit-for 30))))))
2180 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2181 "Parse a Tramp filename and make components available in the body.
2183 First arg FILENAME is evaluated and dissected into its components.
2184 Second arg VAR is a symbol. It is used as a variable name to hold
2185 the filename structure. It is also used as a prefix for the variables
2186 holding the components. For example, if VAR is the symbol `foo', then
2187 `foo' will be bound to the whole structure, `foo-method' will be bound to
2188 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2190 Remaining args are Lisp expressions to be evaluated (inside an implicit
2191 `progn').
2193 If VAR is nil, then we bind `v' to the structure and `method', `user',
2194 `host', `localname' to the components."
2195 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2196 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2197 (tramp-file-name-method ,(or var 'v)))
2198 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2199 (tramp-file-name-user ,(or var 'v)))
2200 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2201 (tramp-file-name-host ,(or var 'v)))
2202 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2203 (tramp-file-name-localname ,(or var 'v))))
2204 ,@body))
2206 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2207 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2208 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2210 (defmacro with-file-property (vec file property &rest body)
2211 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2212 FILE must be a local file name on a connection identified via VEC."
2213 `(if (file-name-absolute-p ,file)
2214 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2215 (when (eq value 'undef)
2216 ;; We cannot pass @body as parameter to
2217 ;; `tramp-set-file-property' because it mangles our
2218 ;; debug messages.
2219 (setq value (progn ,@body))
2220 (tramp-set-file-property ,vec ,file ,property value))
2221 value)
2222 ,@body))
2224 (put 'with-file-property 'lisp-indent-function 3)
2225 (put 'with-file-property 'edebug-form-spec t)
2226 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2228 (defmacro with-connection-property (key property &rest body)
2229 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2230 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2231 (when (eq value 'undef)
2232 ;; We cannot pass ,@body as parameter to
2233 ;; `tramp-set-connection-property' because it mangles our debug
2234 ;; messages.
2235 (setq value (progn ,@body))
2236 (tramp-set-connection-property ,key ,property value))
2237 value))
2239 (put 'with-connection-property 'lisp-indent-function 2)
2240 (put 'with-connection-property 'edebug-form-spec t)
2241 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2243 (eval-and-compile ; silence compiler
2244 (if (memq system-type '(cygwin windows-nt))
2245 (defun tramp-drop-volume-letter (name)
2246 "Cut off unnecessary drive letter from file NAME.
2247 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2248 locally on a remote file name. When the local system is a W32 system
2249 but the remote system is Unix, this introduces a superfluous drive
2250 letter into the file name. This function removes it."
2251 (save-match-data
2252 (if (string-match tramp-root-regexp name)
2253 (replace-match "/" nil t name)
2254 name)))
2256 (defalias 'tramp-drop-volume-letter 'identity)))
2258 (defsubst tramp-make-tramp-temp-file (vec)
2259 "Create a temporary file on the remote host identified by VEC.
2260 Return the local name of the temporary file."
2261 (let ((prefix
2262 (tramp-make-tramp-file-name
2263 (tramp-file-name-method vec)
2264 (tramp-file-name-user vec)
2265 (tramp-file-name-host vec)
2266 (tramp-drop-volume-letter
2267 (expand-file-name
2268 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2269 result)
2270 (while (not result)
2271 ;; `make-temp-file' would be the natural choice for
2272 ;; implementation. But it calls `write-region' internally,
2273 ;; which also needs a temporary file - we would end in an
2274 ;; infinite loop.
2275 (setq result (make-temp-name prefix))
2276 (if (file-exists-p result)
2277 (setq result nil)
2278 ;; This creates the file by side effect.
2279 (set-file-times result)
2280 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2282 ;; Return the local part.
2283 (with-parsed-tramp-file-name result nil localname)))
2286 ;;; Config Manipulation Functions:
2288 (defun tramp-set-completion-function (method function-list)
2289 "Sets the list of completion functions for METHOD.
2290 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2291 The FUNCTION is intended to parse FILE according its syntax.
2292 It might be a predefined FUNCTION, or a user defined FUNCTION.
2293 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2294 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2295 and `tramp-parse-netrc'.
2297 Example:
2299 (tramp-set-completion-function
2300 \"ssh\"
2301 '((tramp-parse-sconfig \"/etc/ssh_config\")
2302 (tramp-parse-sconfig \"~/.ssh/config\")))"
2304 (let ((r function-list)
2305 (v function-list))
2306 (setq tramp-completion-function-alist
2307 (delete (assoc method tramp-completion-function-alist)
2308 tramp-completion-function-alist))
2310 (while v
2311 ;; Remove double entries.
2312 (when (member (car v) (cdr v))
2313 (setcdr v (delete (car v) (cdr v))))
2314 ;; Check for function and file or registry key.
2315 (unless (and (functionp (nth 0 (car v)))
2316 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2317 ;; Windows registry.
2318 (and (memq system-type '(cygwin windows-nt))
2319 (zerop
2320 (tramp-local-call-process
2321 "reg" nil nil nil "query" (nth 1 (car v)))))
2322 ;; Configuration file.
2323 (file-exists-p (nth 1 (car v)))))
2324 (setq r (delete (car v) r)))
2325 (setq v (cdr v)))
2327 (when r
2328 (add-to-list 'tramp-completion-function-alist
2329 (cons method r)))))
2331 (defun tramp-get-completion-function (method)
2332 "Returns a list of completion functions for METHOD.
2333 For definition of that list see `tramp-set-completion-function'."
2334 (cons
2335 ;; Hosts visited once shall be remembered.
2336 `(tramp-parse-connection-properties ,method)
2337 ;; The method related defaults.
2338 (cdr (assoc method tramp-completion-function-alist))))
2341 ;;; Fontification of `read-file-name':
2343 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2344 (defvar tramp-rfn-eshadow-overlay)
2345 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2347 (defun tramp-rfn-eshadow-setup-minibuffer ()
2348 "Set up a minibuffer for `file-name-shadow-mode'.
2349 Adds another overlay hiding filename parts according to Tramp's
2350 special handling of `substitute-in-file-name'."
2351 (when (symbol-value 'minibuffer-completing-file-name)
2352 (setq tramp-rfn-eshadow-overlay
2353 (funcall (symbol-function 'make-overlay)
2354 (funcall (symbol-function 'minibuffer-prompt-end))
2355 (funcall (symbol-function 'minibuffer-prompt-end))))
2356 ;; Copy rfn-eshadow-overlay properties.
2357 (let ((props (funcall (symbol-function 'overlay-properties)
2358 (symbol-value 'rfn-eshadow-overlay))))
2359 (while props
2360 (funcall (symbol-function 'overlay-put)
2361 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2363 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2364 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2365 'tramp-rfn-eshadow-setup-minibuffer)
2366 (add-hook 'tramp-unload-hook
2367 (lambda ()
2368 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2369 'tramp-rfn-eshadow-setup-minibuffer))))
2371 (defconst tramp-rfn-eshadow-update-overlay-regexp
2372 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2374 (defun tramp-rfn-eshadow-update-overlay ()
2375 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2376 This is intended to be used as a minibuffer `post-command-hook' for
2377 `file-name-shadow-mode'; the minibuffer should have already
2378 been set up by `rfn-eshadow-setup-minibuffer'."
2379 ;; In remote files name, there is a shadowing just for the local part.
2380 (let ((end (or (funcall (symbol-function 'overlay-end)
2381 (symbol-value 'rfn-eshadow-overlay))
2382 (funcall (symbol-function 'minibuffer-prompt-end)))))
2383 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
2384 (save-excursion
2385 (save-restriction
2386 (narrow-to-region
2387 (1+ (or (string-match
2388 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2389 end))
2390 (point-max))
2391 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2392 (rfn-eshadow-update-overlay-hook nil))
2393 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
2394 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
2396 (when (boundp 'rfn-eshadow-update-overlay-hook)
2397 (add-hook 'rfn-eshadow-update-overlay-hook
2398 'tramp-rfn-eshadow-update-overlay)
2399 (add-hook 'tramp-unload-hook
2400 (lambda ()
2401 (remove-hook 'rfn-eshadow-update-overlay-hook
2402 'tramp-rfn-eshadow-update-overlay))))
2405 ;;; Integration of eshell.el:
2407 (eval-when-compile
2408 (defvar eshell-path-env))
2410 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2411 ;; when `default-directory' points to another host.
2412 (defun tramp-eshell-directory-change ()
2413 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2414 (setq eshell-path-env
2415 (if (file-remote-p default-directory)
2416 (with-parsed-tramp-file-name default-directory nil
2417 (mapconcat
2418 'identity
2419 (tramp-get-remote-path v)
2420 ":"))
2421 (getenv "PATH"))))
2423 (eval-after-load "esh-util"
2424 '(progn
2425 (tramp-eshell-directory-change)
2426 (add-hook 'eshell-directory-change-hook
2427 'tramp-eshell-directory-change)
2428 (add-hook 'tramp-unload-hook
2429 (lambda ()
2430 (remove-hook 'eshell-directory-change-hook
2431 'tramp-eshell-directory-change)))))
2434 ;;; File Name Handler Functions:
2436 (defun tramp-handle-make-symbolic-link
2437 (filename linkname &optional ok-if-already-exists)
2438 "Like `make-symbolic-link' for Tramp files.
2439 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2440 the symlink. If LINKNAME is a Tramp file, only the localname component is
2441 used as the target of the symlink.
2443 If LINKNAME is a Tramp file and the localname component is relative, then
2444 it is expanded first, before the localname component is taken. Note that
2445 this can give surprising results if the user/host for the source and
2446 target of the symlink differ."
2447 (with-parsed-tramp-file-name linkname l
2448 (let ((ln (tramp-get-remote-ln l))
2449 (cwd (tramp-run-real-handler
2450 'file-name-directory (list l-localname))))
2451 (unless ln
2452 (tramp-error
2453 l 'file-error
2454 "Making a symbolic link. ln(1) does not exist on the remote host."))
2456 ;; Do the 'confirm if exists' thing.
2457 (when (file-exists-p linkname)
2458 ;; What to do?
2459 (if (or (null ok-if-already-exists) ; not allowed to exist
2460 (and (numberp ok-if-already-exists)
2461 (not (yes-or-no-p
2462 (format
2463 "File %s already exists; make it a link anyway? "
2464 l-localname)))))
2465 (tramp-error
2466 l 'file-already-exists "File %s already exists" l-localname)
2467 (delete-file linkname)))
2469 ;; If FILENAME is a Tramp name, use just the localname component.
2470 (when (tramp-tramp-file-p filename)
2471 (setq filename
2472 (tramp-file-name-localname
2473 (tramp-dissect-file-name (expand-file-name filename)))))
2475 ;; Right, they are on the same host, regardless of user, method, etc.
2476 ;; We now make the link on the remote machine. This will occur as the user
2477 ;; that FILENAME belongs to.
2478 (zerop
2479 (tramp-send-command-and-check
2481 (format
2482 "cd %s && %s -sf %s %s"
2483 (tramp-shell-quote-argument cwd)
2485 (tramp-shell-quote-argument filename)
2486 (tramp-shell-quote-argument l-localname))
2487 t)))))
2489 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2490 "Like `load' for Tramp files."
2491 (with-parsed-tramp-file-name (expand-file-name file) nil
2492 (unless nosuffix
2493 (cond ((file-exists-p (concat file ".elc"))
2494 (setq file (concat file ".elc")))
2495 ((file-exists-p (concat file ".el"))
2496 (setq file (concat file ".el")))))
2497 (when must-suffix
2498 ;; The first condition is always true for absolute file names.
2499 ;; Included for safety's sake.
2500 (unless (or (file-name-directory file)
2501 (string-match "\\.elc?\\'" file))
2502 (tramp-error
2503 v 'file-error
2504 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2505 (unless noerror
2506 (when (not (file-exists-p file))
2507 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2508 (if (not (file-exists-p file))
2510 (unless nomessage (tramp-message v 0 "Loading %s..." file))
2511 (let ((local-copy (file-local-copy file)))
2512 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2513 (unwind-protect
2514 (load local-copy noerror t t)
2515 (delete-file local-copy)))
2516 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
2517 t)))
2519 ;; Localname manipulation functions that grok Tramp localnames...
2520 (defun tramp-handle-file-name-as-directory (file)
2521 "Like `file-name-as-directory' but aware of Tramp files."
2522 ;; `file-name-as-directory' would be sufficient except localname is
2523 ;; the empty string.
2524 (let ((v (tramp-dissect-file-name file t)))
2525 ;; Run the command on the localname portion only.
2526 (tramp-make-tramp-file-name
2527 (tramp-file-name-method v)
2528 (tramp-file-name-user v)
2529 (tramp-file-name-host v)
2530 (tramp-run-real-handler
2531 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2533 (defun tramp-handle-file-name-directory (file)
2534 "Like `file-name-directory' but aware of Tramp files."
2535 ;; Everything except the last filename thing is the directory. We
2536 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2537 ;; the remote file name parts. This is a problem when we are in
2538 ;; file name completion.
2539 (let ((v (tramp-dissect-file-name file t)))
2540 ;; Run the command on the localname portion only.
2541 (tramp-make-tramp-file-name
2542 (tramp-file-name-method v)
2543 (tramp-file-name-user v)
2544 (tramp-file-name-host v)
2545 (tramp-run-real-handler
2546 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2548 (defun tramp-handle-file-name-nondirectory (file)
2549 "Like `file-name-nondirectory' but aware of Tramp files."
2550 (with-parsed-tramp-file-name file nil
2551 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2553 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2554 "Like `file-truename' for Tramp files."
2555 (with-parsed-tramp-file-name (expand-file-name filename) nil
2556 (with-file-property v localname "file-truename"
2557 (let ((result nil)) ; result steps in reverse order
2558 (tramp-message v 4 "Finding true name for `%s'" filename)
2559 (cond
2560 ;; Use GNU readlink --canonicalize-missing where available.
2561 ((tramp-get-remote-readlink v)
2562 (setq result
2563 (tramp-send-command-and-read
2565 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2566 (tramp-get-remote-readlink v)
2567 (tramp-shell-quote-argument localname)))))
2569 ;; Use Perl implementation.
2570 ((and (tramp-get-remote-perl v)
2571 (tramp-get-connection-property v "perl-file-spec" nil)
2572 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2573 (tramp-maybe-send-script
2574 v tramp-perl-file-truename "tramp_perl_file_truename")
2575 (setq result
2576 (tramp-send-command-and-read
2578 (format "tramp_perl_file_truename %s"
2579 (tramp-shell-quote-argument localname)))))
2581 ;; Do it yourself. We bind `directory-sep-char' here for
2582 ;; XEmacs on Windows, which would otherwise use backslash.
2583 (t (let* ((directory-sep-char ?/)
2584 (steps (tramp-compat-split-string localname "/"))
2585 (localnamedir (tramp-run-real-handler
2586 'file-name-as-directory (list localname)))
2587 (is-dir (string= localname localnamedir))
2588 (thisstep nil)
2589 (numchase 0)
2590 ;; Don't make the following value larger than
2591 ;; necessary. People expect an error message in a
2592 ;; timely fashion when something is wrong;
2593 ;; otherwise they might think that Emacs is hung.
2594 ;; Of course, correctness has to come first.
2595 (numchase-limit 20)
2596 symlink-target)
2597 (while (and steps (< numchase numchase-limit))
2598 (setq thisstep (pop steps))
2599 (tramp-message
2600 v 5 "Check %s"
2601 (mapconcat 'identity
2602 (append '("") (reverse result) (list thisstep))
2603 "/"))
2604 (setq symlink-target
2605 (nth 0 (file-attributes
2606 (tramp-make-tramp-file-name
2607 method user host
2608 (mapconcat 'identity
2609 (append '("")
2610 (reverse result)
2611 (list thisstep))
2612 "/")))))
2613 (cond ((string= "." thisstep)
2614 (tramp-message v 5 "Ignoring step `.'"))
2615 ((string= ".." thisstep)
2616 (tramp-message v 5 "Processing step `..'")
2617 (pop result))
2618 ((stringp symlink-target)
2619 ;; It's a symlink, follow it.
2620 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2621 (setq numchase (1+ numchase))
2622 (when (file-name-absolute-p symlink-target)
2623 (setq result nil))
2624 ;; If the symlink was absolute, we'll get a string like
2625 ;; "/user@host:/some/target"; extract the
2626 ;; "/some/target" part from it.
2627 (when (tramp-tramp-file-p symlink-target)
2628 (unless (tramp-equal-remote filename symlink-target)
2629 (tramp-error
2630 v 'file-error
2631 "Symlink target `%s' on wrong host" symlink-target))
2632 (setq symlink-target localname))
2633 (setq steps
2634 (append (tramp-compat-split-string
2635 symlink-target "/")
2636 steps)))
2638 ;; It's a file.
2639 (setq result (cons thisstep result)))))
2640 (when (>= numchase numchase-limit)
2641 (tramp-error
2642 v 'file-error
2643 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2644 (setq result (reverse result))
2645 ;; Combine list to form string.
2646 (setq result
2647 (if result
2648 (mapconcat 'identity (cons "" result) "/")
2649 "/"))
2650 (when (and is-dir (or (string= "" result)
2651 (not (string= (substring result -1) "/"))))
2652 (setq result (concat result "/"))))))
2654 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2655 (tramp-make-tramp-file-name method user host result)))))
2657 ;; Basic functions.
2659 (defun tramp-handle-file-exists-p (filename)
2660 "Like `file-exists-p' for Tramp files."
2661 (with-parsed-tramp-file-name filename nil
2662 (with-file-property v localname "file-exists-p"
2663 (or (not (null (tramp-get-file-property
2664 v localname "file-attributes-integer" nil)))
2665 (not (null (tramp-get-file-property
2666 v localname "file-attributes-string" nil)))
2667 (zerop (tramp-send-command-and-check
2669 (format
2670 "%s %s"
2671 (tramp-get-file-exists-command v)
2672 (tramp-shell-quote-argument localname))))))))
2674 ;; Inodes don't exist for some file systems. Therefore we must
2675 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2676 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2677 ;; performance isn't the major issue given that file transfer will
2678 ;; take time.
2679 (defvar tramp-inodes nil
2680 "Keeps virtual inodes numbers.")
2682 ;; Devices must distinguish physical file systems. The device numbers
2683 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2684 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2685 ;; EFS use device number "-1". In order to be different, we use device number
2686 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2687 (defvar tramp-devices nil
2688 "Keeps virtual device numbers.")
2690 ;; CCC: This should check for an error condition and signal failure
2691 ;; when something goes wrong.
2692 ;; Daniel Pittman <daniel@danann.net>
2693 (defun tramp-handle-file-attributes (filename &optional id-format)
2694 "Like `file-attributes' for Tramp files."
2695 (unless id-format (setq id-format 'integer))
2696 ;; Don't modify `last-coding-system-used' by accident.
2697 (let ((last-coding-system-used last-coding-system-used))
2698 (with-parsed-tramp-file-name (expand-file-name filename) nil
2699 (with-file-property v localname (format "file-attributes-%s" id-format)
2700 (save-excursion
2701 (tramp-convert-file-attributes
2703 (cond
2704 ((tramp-get-remote-stat v)
2705 (tramp-do-file-attributes-with-stat v localname id-format))
2706 ((tramp-get-remote-perl v)
2707 (tramp-do-file-attributes-with-perl v localname id-format))
2709 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2711 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2712 "Implement `file-attributes' for Tramp files using the ls(1) command."
2713 (let (symlinkp dirp
2714 res-inode res-filemodes res-numlinks
2715 res-uid res-gid res-size res-symlink-target)
2716 (tramp-message vec 5 "file attributes with ls: %s" localname)
2717 (tramp-send-command
2719 (format "(%s %s || %s -h %s) && %s %s %s"
2720 (tramp-get-file-exists-command vec)
2721 (tramp-shell-quote-argument localname)
2722 (tramp-get-test-command vec)
2723 (tramp-shell-quote-argument localname)
2724 (tramp-get-ls-command vec)
2725 (if (eq id-format 'integer) "-ildn" "-ild")
2726 (tramp-shell-quote-argument localname)))
2727 ;; parse `ls -l' output ...
2728 (with-current-buffer (tramp-get-buffer vec)
2729 (when (> (buffer-size) 0)
2730 (goto-char (point-min))
2731 ;; ... inode
2732 (setq res-inode
2733 (condition-case err
2734 (read (current-buffer))
2735 (invalid-read-syntax
2736 (when (and (equal (cadr err)
2737 "Integer constant overflow in reader")
2738 (string-match
2739 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2740 (car (cddr err))))
2741 (let* ((big (read (substring (car (cddr err)) 0
2742 (match-beginning 1))))
2743 (small (read (match-string 1 (car (cddr err)))))
2744 (twiddle (/ small 65536)))
2745 (cons (+ big twiddle)
2746 (- small (* twiddle 65536))))))))
2747 ;; ... file mode flags
2748 (setq res-filemodes (symbol-name (read (current-buffer))))
2749 ;; ... number links
2750 (setq res-numlinks (read (current-buffer)))
2751 ;; ... uid and gid
2752 (setq res-uid (read (current-buffer)))
2753 (setq res-gid (read (current-buffer)))
2754 (if (eq id-format 'integer)
2755 (progn
2756 (unless (numberp res-uid) (setq res-uid -1))
2757 (unless (numberp res-gid) (setq res-gid -1)))
2758 (progn
2759 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2760 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2761 ;; ... size
2762 (setq res-size (read (current-buffer)))
2763 ;; From the file modes, figure out other stuff.
2764 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2765 (setq dirp (eq ?d (aref res-filemodes 0)))
2766 ;; if symlink, find out file name pointed to
2767 (when symlinkp
2768 (search-forward "-> ")
2769 (setq res-symlink-target
2770 (buffer-substring (point) (tramp-compat-line-end-position))))
2771 ;; return data gathered
2772 (list
2773 ;; 0. t for directory, string (name linked to) for symbolic
2774 ;; link, or nil.
2775 (or dirp res-symlink-target)
2776 ;; 1. Number of links to file.
2777 res-numlinks
2778 ;; 2. File uid.
2779 res-uid
2780 ;; 3. File gid.
2781 res-gid
2782 ;; 4. Last access time, as a list of two integers. First
2783 ;; integer has high-order 16 bits of time, second has low 16
2784 ;; bits.
2785 ;; 5. Last modification time, likewise.
2786 ;; 6. Last status change time, likewise.
2787 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2788 ;; 7. Size in bytes (-1, if number is out of range).
2789 res-size
2790 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2791 res-filemodes
2792 ;; 9. t if file's gid would change if file were deleted and
2793 ;; recreated. Will be set in `tramp-convert-file-attributes'
2795 ;; 10. inode number.
2796 res-inode
2797 ;; 11. Device number. Will be replaced by a virtual device number.
2799 )))))
2801 (defun tramp-do-file-attributes-with-perl
2802 (vec localname &optional id-format)
2803 "Implement `file-attributes' for Tramp files using a Perl script."
2804 (tramp-message vec 5 "file attributes with perl: %s" localname)
2805 (tramp-maybe-send-script
2806 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2807 (tramp-send-command-and-read
2809 (format "tramp_perl_file_attributes %s %s"
2810 (tramp-shell-quote-argument localname) id-format)))
2812 (defun tramp-do-file-attributes-with-stat
2813 (vec localname &optional id-format)
2814 "Implement `file-attributes' for Tramp files using stat(1) command."
2815 (tramp-message vec 5 "file attributes with stat: %s" localname)
2816 (tramp-send-command-and-read
2818 (format
2819 "((%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)"
2820 (tramp-get-file-exists-command vec)
2821 (tramp-shell-quote-argument localname)
2822 (tramp-get-test-command vec)
2823 (tramp-shell-quote-argument localname)
2824 (tramp-get-remote-stat vec)
2825 (if (eq id-format 'integer) "%u" "\"%U\"")
2826 (if (eq id-format 'integer) "%g" "\"%G\"")
2827 (tramp-shell-quote-argument localname))))
2829 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2830 "Like `set-visited-file-modtime' for Tramp files."
2831 (unless (buffer-file-name)
2832 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2833 (buffer-name)))
2834 (if time-list
2835 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2836 (let ((f (buffer-file-name))
2837 coding-system-used)
2838 (with-parsed-tramp-file-name f nil
2839 (let* ((attr (file-attributes f))
2840 ;; '(-1 65535) means file doesn't exists yet.
2841 (modtime (or (nth 5 attr) '(-1 65535))))
2842 (when (boundp 'last-coding-system-used)
2843 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2844 ;; We use '(0 0) as a don't-know value. See also
2845 ;; `tramp-do-file-attributes-with-ls'.
2846 (if (not (equal modtime '(0 0)))
2847 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2848 (progn
2849 (tramp-send-command
2851 (format "%s -ild %s"
2852 (tramp-get-ls-command v)
2853 (tramp-shell-quote-argument localname)))
2854 (setq attr (buffer-substring (point)
2855 (progn (end-of-line) (point)))))
2856 (tramp-set-file-property
2857 v localname "visited-file-modtime-ild" attr))
2858 (when (boundp 'last-coding-system-used)
2859 (set 'last-coding-system-used coding-system-used))
2860 nil)))))
2862 ;; This function makes the same assumption as
2863 ;; `tramp-handle-set-visited-file-modtime'.
2864 (defun tramp-handle-verify-visited-file-modtime (buf)
2865 "Like `verify-visited-file-modtime' for Tramp files.
2866 At the time `verify-visited-file-modtime' calls this function, we
2867 already know that the buffer is visiting a file and that
2868 `visited-file-modtime' does not return 0. Do not call this
2869 function directly, unless those two cases are already taken care
2870 of."
2871 (with-current-buffer buf
2872 ;; There is no file visiting the buffer, or the buffer has no
2873 ;; recorded last modification time.
2874 (if (or (not (buffer-file-name))
2875 (eq (visited-file-modtime) 0))
2877 (let ((f (buffer-file-name)))
2878 (with-parsed-tramp-file-name f nil
2879 (tramp-flush-file-property v localname)
2880 (let* ((attr (file-attributes f))
2881 (modtime (nth 5 attr))
2882 (mt (visited-file-modtime)))
2884 (cond
2885 ;; File exists, and has a known modtime.
2886 ((and attr (not (equal modtime '(0 0))))
2887 (< (abs (tramp-time-diff
2888 modtime
2889 ;; For compatibility, deal with both the old
2890 ;; (HIGH . LOW) and the new (HIGH LOW) return
2891 ;; values of `visited-file-modtime'.
2892 (if (atom (cdr mt))
2893 (list (car mt) (cdr mt))
2894 mt)))
2896 ;; Modtime has the don't know value.
2897 (attr
2898 (tramp-send-command
2900 (format "%s -ild %s"
2901 (tramp-get-ls-command v)
2902 (tramp-shell-quote-argument localname)))
2903 (with-current-buffer (tramp-get-buffer v)
2904 (setq attr (buffer-substring
2905 (point) (progn (end-of-line) (point)))))
2906 (equal
2907 attr
2908 (tramp-get-file-property
2909 v localname "visited-file-modtime-ild" "")))
2910 ;; If file does not exist, say it is not modified if and
2911 ;; only if that agrees with the buffer's record.
2912 (t (equal mt '(-1 65535))))))))))
2914 (defun tramp-handle-set-file-modes (filename mode)
2915 "Like `set-file-modes' for Tramp files."
2916 (with-parsed-tramp-file-name filename nil
2917 (tramp-flush-file-property v localname)
2918 (unless (zerop (tramp-send-command-and-check
2920 (format "chmod %s %s"
2921 (tramp-decimal-to-octal mode)
2922 (tramp-shell-quote-argument localname))))
2923 ;; FIXME: extract the proper text from chmod's stderr.
2924 (tramp-error
2925 v 'file-error "Error while changing file's mode %s" filename))))
2927 (defun tramp-handle-set-file-times (filename &optional time)
2928 "Like `set-file-times' for Tramp files."
2929 (zerop
2930 (if (file-remote-p filename)
2931 (with-parsed-tramp-file-name filename nil
2932 (tramp-flush-file-property v localname)
2933 (let ((time (if (or (null time) (equal time '(0 0)))
2934 (current-time)
2935 time))
2936 (utc
2937 ;; With GNU Emacs, `format-time-string' has an
2938 ;; optional parameter UNIVERSAL. This is preferred,
2939 ;; because we could handle the case when the remote
2940 ;; host is located in a different time zone as the
2941 ;; local host.
2942 (and (functionp 'subr-arity)
2943 (subrp (symbol-function 'format-time-string))
2944 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2945 (symbol-function
2946 'format-time-string)))))))
2947 (tramp-send-command-and-check
2948 v (format "%s touch -t %s %s"
2949 (if utc "TZ=UTC; export TZ;" "")
2950 (if utc
2951 (format-time-string "%Y%m%d%H%M.%S" time t)
2952 (format-time-string "%Y%m%d%H%M.%S" time))
2953 (tramp-shell-quote-argument localname)))))
2955 ;; We handle also the local part, because in older Emacsen,
2956 ;; without `set-file-times', this function is an alias for this.
2957 ;; We are local, so we don't need the UTC settings.
2958 (tramp-local-call-process
2959 "touch" nil nil nil "-t"
2960 (format-time-string "%Y%m%d%H%M.%S" time)
2961 (tramp-shell-quote-argument filename)))))
2963 (defun tramp-set-file-uid-gid (filename &optional uid gid)
2964 "Set the ownership for FILENAME.
2965 If UID and GID are provided, these values are used; otherwise uid
2966 and gid of the corresponding user is taken. Both parameters must be integers."
2967 ;; Modern Unices allow chown only for root. So we might need
2968 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2969 ;; working with su(do)? when it is needed, so it shall succeed in
2970 ;; the majority of cases.
2971 ;; Don't modify `last-coding-system-used' by accident.
2972 (let ((last-coding-system-used last-coding-system-used))
2973 (if (file-remote-p filename)
2974 (with-parsed-tramp-file-name filename nil
2975 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2976 ;; If we are root on the local host, we can do it directly.
2977 (tramp-set-file-uid-gid localname uid gid)
2978 (let ((uid (or (and (integerp uid) uid)
2979 (tramp-get-remote-uid v 'integer)))
2980 (gid (or (and (integerp gid) gid)
2981 (tramp-get-remote-gid v 'integer))))
2982 (tramp-send-command
2983 v (format
2984 "chown %d:%d %s" uid gid
2985 (tramp-shell-quote-argument localname))))))
2987 ;; We handle also the local part, because there doesn't exist
2988 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2989 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2990 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2991 (tramp-local-call-process
2992 "chown" nil nil nil
2993 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
2995 ;; Simple functions using the `test' command.
2997 (defun tramp-handle-file-executable-p (filename)
2998 "Like `file-executable-p' for Tramp files."
2999 (with-parsed-tramp-file-name filename nil
3000 (with-file-property v localname "file-executable-p"
3001 ;; Examine `file-attributes' cache to see if request can be
3002 ;; satisfied without remote operation.
3003 (or (tramp-check-cached-permissions v ?x)
3004 (zerop (tramp-run-test "-x" filename))))))
3006 (defun tramp-handle-file-readable-p (filename)
3007 "Like `file-readable-p' for Tramp files."
3008 (with-parsed-tramp-file-name filename nil
3009 (with-file-property v localname "file-readable-p"
3010 ;; Examine `file-attributes' cache to see if request can be
3011 ;; satisfied without remote operation.
3012 (or (tramp-check-cached-permissions v ?r)
3013 (zerop (tramp-run-test "-r" filename))))))
3015 ;; When the remote shell is started, it looks for a shell which groks
3016 ;; tilde expansion. Here, we assume that all shells which grok tilde
3017 ;; expansion will also provide a `test' command which groks `-nt' (for
3018 ;; newer than). If this breaks, tell me about it and I'll try to do
3019 ;; something smarter about it.
3020 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3021 "Like `file-newer-than-file-p' for Tramp files."
3022 (cond ((not (file-exists-p file1))
3023 nil)
3024 ((not (file-exists-p file2))
3026 ;; We are sure both files exist at this point.
3028 (save-excursion
3029 ;; We try to get the mtime of both files. If they are not
3030 ;; equal to the "dont-know" value, then we subtract the times
3031 ;; and obtain the result.
3032 (let ((fa1 (file-attributes file1))
3033 (fa2 (file-attributes file2)))
3034 (if (and (not (equal (nth 5 fa1) '(0 0)))
3035 (not (equal (nth 5 fa2) '(0 0))))
3036 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3037 ;; If one of them is the dont-know value, then we can
3038 ;; still try to run a shell command on the remote host.
3039 ;; However, this only works if both files are Tramp
3040 ;; files and both have the same method, same user, same
3041 ;; host.
3042 (unless (tramp-equal-remote file1 file2)
3043 (with-parsed-tramp-file-name
3044 (if (tramp-tramp-file-p file1) file1 file2) nil
3045 (tramp-error
3046 v 'file-error
3047 "Files %s and %s must have same method, user, host"
3048 file1 file2)))
3049 (with-parsed-tramp-file-name file1 nil
3050 (zerop (tramp-run-test2
3051 (tramp-get-test-nt-command v) file1 file2)))))))))
3053 ;; Functions implemented using the basic functions above.
3055 (defun tramp-handle-file-modes (filename)
3056 "Like `file-modes' for Tramp files."
3057 (let ((truename (or (file-truename filename) filename)))
3058 (when (file-exists-p truename)
3059 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3061 (defun tramp-default-file-modes (filename)
3062 "Return file modes of FILENAME as integer.
3063 If the file modes of FILENAME cannot be determined, return the
3064 value of `default-file-modes', without execute permissions."
3065 (or (file-modes filename)
3066 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3068 (defun tramp-handle-file-directory-p (filename)
3069 "Like `file-directory-p' for Tramp files."
3070 ;; Care must be taken that this function returns `t' for symlinks
3071 ;; pointing to directories. Surely the most obvious implementation
3072 ;; would be `test -d', but that returns false for such symlinks.
3073 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3074 ;; I now think he's right. So we could be using `test -d', couldn't
3075 ;; we?
3077 ;; Alternatives: `cd %s', `test -d %s'
3078 (with-parsed-tramp-file-name filename nil
3079 (with-file-property v localname "file-directory-p"
3080 (zerop (tramp-run-test "-d" filename)))))
3082 (defun tramp-handle-file-regular-p (filename)
3083 "Like `file-regular-p' for Tramp files."
3084 (and (file-exists-p filename)
3085 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3087 (defun tramp-handle-file-symlink-p (filename)
3088 "Like `file-symlink-p' for Tramp files."
3089 (with-parsed-tramp-file-name filename nil
3090 (let ((x (car (file-attributes filename))))
3091 (when (stringp x)
3092 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3093 ;; might do weird things.
3094 (if (file-name-absolute-p x)
3095 (tramp-make-tramp-file-name method user host x)
3096 x)))))
3098 (defun tramp-handle-file-writable-p (filename)
3099 "Like `file-writable-p' for Tramp files."
3100 (with-parsed-tramp-file-name filename nil
3101 (with-file-property v localname "file-writable-p"
3102 (if (file-exists-p filename)
3103 ;; Examine `file-attributes' cache to see if request can be
3104 ;; satisfied without remote operation.
3105 (or (tramp-check-cached-permissions v ?w)
3106 (zerop (tramp-run-test "-w" filename)))
3107 ;; If file doesn't exist, check if directory is writable.
3108 (and (zerop (tramp-run-test
3109 "-d" (file-name-directory filename)))
3110 (zerop (tramp-run-test
3111 "-w" (file-name-directory filename))))))))
3113 (defun tramp-handle-file-ownership-preserved-p (filename)
3114 "Like `file-ownership-preserved-p' for Tramp files."
3115 (with-parsed-tramp-file-name filename nil
3116 (with-file-property v localname "file-ownership-preserved-p"
3117 (let ((attributes (file-attributes filename)))
3118 ;; Return t if the file doesn't exist, since it's true that no
3119 ;; information would be lost by an (attempted) delete and create.
3120 (or (null attributes)
3121 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3123 ;; Other file name ops.
3125 (defun tramp-handle-directory-file-name (directory)
3126 "Like `directory-file-name' for Tramp files."
3127 ;; If localname component of filename is "/", leave it unchanged.
3128 ;; Otherwise, remove any trailing slash from localname component.
3129 ;; Method, host, etc, are unchanged. Does it make sense to try
3130 ;; to avoid parsing the filename?
3131 (with-parsed-tramp-file-name directory nil
3132 (if (and (not (zerop (length localname)))
3133 (eq (aref localname (1- (length localname))) ?/)
3134 (not (string= localname "/")))
3135 (substring directory 0 -1)
3136 directory)))
3138 ;; Directory listings.
3140 (defun tramp-handle-directory-files
3141 (directory &optional full match nosort files-only)
3142 "Like `directory-files' for Tramp files."
3143 ;; FILES-ONLY is valid for XEmacs only.
3144 (when (file-directory-p directory)
3145 (setq directory (file-name-as-directory (expand-file-name directory)))
3146 (let ((temp (nreverse (file-name-all-completions "" directory)))
3147 result item)
3149 (while temp
3150 (setq item (directory-file-name (pop temp)))
3151 (when (and (or (null match) (string-match match item))
3152 (or (null files-only)
3153 ;; Files only.
3154 (and (equal files-only t) (file-regular-p item))
3155 ;; Directories only.
3156 (file-directory-p item)))
3157 (push (if full (concat directory item) item)
3158 result)))
3159 (if nosort result (sort result 'string<)))))
3161 (defun tramp-handle-directory-files-and-attributes
3162 (directory &optional full match nosort id-format)
3163 "Like `directory-files-and-attributes' for Tramp files."
3164 (unless id-format (setq id-format 'integer))
3165 (when (file-directory-p directory)
3166 (setq directory (expand-file-name directory))
3167 (let* ((temp
3168 (tramp-compat-copy-tree
3169 (with-parsed-tramp-file-name directory nil
3170 (with-file-property
3171 v localname
3172 (format "directory-files-and-attributes-%s" id-format)
3173 (save-excursion
3174 (mapcar
3175 (lambda (x)
3176 (cons (car x)
3177 (tramp-convert-file-attributes v (cdr x))))
3178 (cond
3179 ((tramp-get-remote-stat v)
3180 (tramp-do-directory-files-and-attributes-with-stat
3181 v localname id-format))
3182 ((tramp-get-remote-perl v)
3183 (tramp-do-directory-files-and-attributes-with-perl
3184 v localname id-format)))))))))
3185 result item)
3187 (while temp
3188 (setq item (pop temp))
3189 (when (or (null match) (string-match match (car item)))
3190 (when full
3191 (setcar item (expand-file-name (car item) directory)))
3192 (push item result)))
3194 (if nosort
3195 result
3196 (sort result (lambda (x y) (string< (car x) (car y))))))))
3198 (defun tramp-do-directory-files-and-attributes-with-perl
3199 (vec localname &optional id-format)
3200 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3201 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3202 (tramp-maybe-send-script
3203 vec tramp-perl-directory-files-and-attributes
3204 "tramp_perl_directory_files_and_attributes")
3205 (let ((object
3206 (tramp-send-command-and-read
3208 (format "tramp_perl_directory_files_and_attributes %s %s"
3209 (tramp-shell-quote-argument localname) id-format))))
3210 (when (stringp object) (tramp-error vec 'file-error object))
3211 object))
3213 (defun tramp-do-directory-files-and-attributes-with-stat
3214 (vec localname &optional id-format)
3215 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3216 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3217 (tramp-send-command-and-read
3219 (format
3220 (concat
3221 ;; We must care about filenames with spaces, or starting with
3222 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3223 ;; but it does not work on all remote systems. Therefore, we
3224 ;; quote the filenames via sed.
3225 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3226 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3227 "echo \")\"")
3228 (tramp-shell-quote-argument localname)
3229 (tramp-get-ls-command vec)
3230 (tramp-get-remote-stat vec)
3231 (if (eq id-format 'integer) "%u" "\"%U\"")
3232 (if (eq id-format 'integer) "%g" "\"%G\""))))
3234 ;; This function should return "foo/" for directories and "bar" for
3235 ;; files.
3236 (defun tramp-handle-file-name-all-completions (filename directory)
3237 "Like `file-name-all-completions' for Tramp files."
3238 (unless (save-match-data (string-match "/" filename))
3239 (with-parsed-tramp-file-name (expand-file-name directory) nil
3241 (all-completions
3242 filename
3243 (mapcar
3244 'list
3246 ;; Try cache first
3247 (and
3248 ;; Ignore if expired
3249 (or (not (integerp tramp-completion-reread-directory-timeout))
3250 (<= (tramp-time-diff
3251 (current-time)
3252 (tramp-get-file-property
3253 v localname "last-completion" '(0 0 0)))
3254 tramp-completion-reread-directory-timeout))
3256 ;; Try cache entries for filename, filename with last
3257 ;; character removed, filename with last two characters
3258 ;; removed, ..., and finally the empty string - all
3259 ;; concatenated to the local directory name
3261 ;; This is inefficient for very long filenames, pity
3262 ;; `reduce' is not available...
3263 (car
3264 (apply
3265 'append
3266 (mapcar
3267 (lambda (x)
3268 (let ((cache-hit
3269 (tramp-get-file-property
3271 (concat localname (substring filename 0 x))
3272 "file-name-all-completions"
3273 nil)))
3274 (when cache-hit (list cache-hit))))
3275 (tramp-compat-number-sequence (length filename) 0 -1)))))
3277 ;; Cache expired or no matching cache entry found so we need
3278 ;; to perform a remote operation
3279 (let (result)
3280 ;; Get a list of directories and files, including reliably
3281 ;; tagging the directories with a trailing '/'. Because I
3282 ;; rock. --daniel@danann.net
3284 ;; Changed to perform `cd' in the same remote op and only
3285 ;; get entries starting with `filename'. Capture any `cd'
3286 ;; error messages. Ensure any `cd' and `echo' aliases are
3287 ;; ignored.
3288 (tramp-send-command
3290 (if (tramp-get-remote-perl v)
3291 (progn
3292 (tramp-maybe-send-script
3293 v tramp-perl-file-name-all-completions
3294 "tramp_perl_file_name_all_completions")
3295 (format "tramp_perl_file_name_all_completions %s %s %d"
3296 (tramp-shell-quote-argument localname)
3297 (tramp-shell-quote-argument filename)
3298 (if (symbol-value
3299 'read-file-name-completion-ignore-case)
3300 1 0)))
3302 (format (concat
3303 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3304 ;; `ls' with wildcard might fail with `Argument
3305 ;; list too long' error in some corner cases; if
3306 ;; `ls' fails after `cd' succeeded, chances are
3307 ;; that's the case, so let's retry without
3308 ;; wildcard. This will return "too many" entries
3309 ;; but that isn't harmful.
3310 " || %s -a 2>/dev/null)"
3311 " | while read f; do"
3312 " if %s -d \"$f\" 2>/dev/null;"
3313 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3314 " && \\echo ok) || \\echo fail")
3315 (tramp-shell-quote-argument localname)
3316 (tramp-get-ls-command v)
3317 ;; When `filename' is empty, just `ls' without
3318 ;; filename argument is more efficient than `ls *'
3319 ;; for very large directories and might avoid the
3320 ;; `Argument list too long' error.
3322 ;; With and only with wildcard, we need to add
3323 ;; `-d' to prevent `ls' from descending into
3324 ;; sub-directories.
3325 (if (zerop (length filename))
3327 (concat (tramp-shell-quote-argument filename) "* -d"))
3328 (tramp-get-ls-command v)
3329 (tramp-get-test-command v))))
3331 ;; Now grab the output.
3332 (with-current-buffer (tramp-get-buffer v)
3333 (goto-char (point-max))
3335 ;; Check result code, found in last line of output
3336 (forward-line -1)
3337 (if (looking-at "^fail$")
3338 (progn
3339 ;; Grab error message from line before last line
3340 ;; (it was put there by `cd 2>&1')
3341 (forward-line -1)
3342 (tramp-error
3343 v 'file-error
3344 "tramp-handle-file-name-all-completions: %s"
3345 (buffer-substring
3346 (point) (tramp-compat-line-end-position))))
3347 ;; For peace of mind, if buffer doesn't end in `fail'
3348 ;; then it should end in `ok'. If neither are in the
3349 ;; buffer something went seriously wrong on the remote
3350 ;; side.
3351 (unless (looking-at "^ok$")
3352 (tramp-error
3353 v 'file-error
3355 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3356 (tramp-shell-quote-argument localname) (buffer-string))))
3358 (while (zerop (forward-line -1))
3359 (push (buffer-substring
3360 (point) (tramp-compat-line-end-position))
3361 result)))
3363 ;; Because the remote op went through OK we know the
3364 ;; directory we `cd'-ed to exists
3365 (tramp-set-file-property
3366 v localname "file-exists-p" t)
3368 ;; Because the remote op went through OK we know every
3369 ;; file listed by `ls' exists.
3370 (mapc (lambda (entry)
3371 (tramp-set-file-property
3372 v (concat localname entry) "file-exists-p" t))
3373 result)
3375 (tramp-set-file-property
3376 v localname "last-completion" (current-time))
3378 ;; Store result in the cache
3379 (tramp-set-file-property
3380 v (concat localname filename)
3381 "file-name-all-completions"
3382 result))))))))
3384 ;; The following isn't needed for Emacs 20 but for 19.34?
3385 (defun tramp-handle-file-name-completion
3386 (filename directory &optional predicate)
3387 "Like `file-name-completion' for Tramp files."
3388 (unless (tramp-tramp-file-p directory)
3389 (error
3390 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3391 directory))
3392 (try-completion
3393 filename
3394 (mapcar 'list (file-name-all-completions filename directory))
3395 (when predicate
3396 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3398 ;; cp, mv and ln
3400 (defun tramp-handle-add-name-to-file
3401 (filename newname &optional ok-if-already-exists)
3402 "Like `add-name-to-file' for Tramp files."
3403 (unless (tramp-equal-remote filename newname)
3404 (with-parsed-tramp-file-name
3405 (if (tramp-tramp-file-p filename) filename newname) nil
3406 (tramp-error
3407 v 'file-error
3408 "add-name-to-file: %s"
3409 "only implemented for same method, same user, same host")))
3410 (with-parsed-tramp-file-name filename v1
3411 (with-parsed-tramp-file-name newname v2
3412 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3413 (when (and (not ok-if-already-exists)
3414 (file-exists-p newname)
3415 (not (numberp ok-if-already-exists))
3416 (y-or-n-p
3417 (format
3418 "File %s already exists; make it a new name anyway? "
3419 newname)))
3420 (tramp-error
3421 v2 'file-error
3422 "add-name-to-file: file %s already exists" newname))
3423 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3424 (tramp-flush-file-property v2 v2-localname)
3425 (tramp-barf-unless-okay
3427 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3428 (tramp-shell-quote-argument v2-localname))
3429 "error with add-name-to-file, see buffer `%s' for details"
3430 (buffer-name))))))
3432 (defun tramp-handle-copy-file
3433 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3434 "Like `copy-file' for Tramp files."
3435 ;; Check if both files are local -- invoke normal copy-file.
3436 ;; Otherwise, use Tramp from local system.
3437 (setq filename (expand-file-name filename))
3438 (setq newname (expand-file-name newname))
3439 (cond
3440 ;; At least one file a Tramp file?
3441 ((or (tramp-tramp-file-p filename)
3442 (tramp-tramp-file-p newname))
3443 (tramp-do-copy-or-rename-file
3444 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3445 ;; Compat section.
3446 (preserve-uid-gid
3447 (tramp-run-real-handler
3448 'copy-file
3449 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3451 (tramp-run-real-handler
3452 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3454 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3455 "Like `copy-directory' for Tramp files."
3456 (let ((t1 (tramp-tramp-file-p dirname))
3457 (t2 (tramp-tramp-file-p newname)))
3458 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3459 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3460 ;; When DIRNAME and NEWNAME are remote, they must have
3461 ;; the same method.
3462 (or (null t1) (null t2)
3463 (string-equal
3464 (tramp-file-name-method (tramp-dissect-file-name dirname))
3465 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3466 ;; scp or rsync DTRT.
3467 (progn
3468 (setq dirname (directory-file-name (expand-file-name dirname))
3469 newname (directory-file-name (expand-file-name newname)))
3470 (if (and (file-directory-p newname)
3471 (not (string-equal (file-name-nondirectory dirname)
3472 (file-name-nondirectory newname))))
3473 (setq newname
3474 (expand-file-name
3475 (file-name-nondirectory dirname) newname)))
3476 (if (not (file-directory-p (file-name-directory newname)))
3477 (make-directory (file-name-directory newname) parents))
3478 (tramp-do-copy-or-rename-file-out-of-band
3479 'copy dirname newname keep-date))
3480 ;; We must do it file-wise.
3481 (tramp-run-real-handler
3482 'copy-directory (list dirname newname keep-date parents)))
3484 ;; When newname did exist, we have wrong cached values.
3485 (when t2
3486 (with-parsed-tramp-file-name newname nil
3487 (tramp-flush-file-property v (file-name-directory localname))
3488 (tramp-flush-file-property v localname))))))
3490 (defun tramp-handle-rename-file
3491 (filename newname &optional ok-if-already-exists)
3492 "Like `rename-file' for Tramp files."
3493 ;; Check if both files are local -- invoke normal rename-file.
3494 ;; Otherwise, use Tramp from local system.
3495 (setq filename (expand-file-name filename))
3496 (setq newname (expand-file-name newname))
3497 ;; At least one file a Tramp file?
3498 (if (or (tramp-tramp-file-p filename)
3499 (tramp-tramp-file-p newname))
3500 (tramp-do-copy-or-rename-file
3501 'rename filename newname ok-if-already-exists t t)
3502 (tramp-run-real-handler
3503 'rename-file (list filename newname ok-if-already-exists))))
3505 (defun tramp-do-copy-or-rename-file
3506 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3507 "Copy or rename a remote file.
3508 OP must be `copy' or `rename' and indicates the operation to perform.
3509 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3510 the new file (for copy) or the new name of the file (for rename).
3511 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3512 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3513 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3514 the uid and gid if both files are on the same host.
3516 This function is invoked by `tramp-handle-copy-file' and
3517 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3518 and `rename'. FILENAME and NEWNAME must be absolute file names."
3519 (unless (memq op '(copy rename))
3520 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3521 (let ((t1 (tramp-tramp-file-p filename))
3522 (t2 (tramp-tramp-file-p newname)))
3524 (when (and (not ok-if-already-exists) (file-exists-p newname))
3525 (with-parsed-tramp-file-name (if t1 filename newname) nil
3526 (tramp-error
3527 v 'file-already-exists "File %s already exists" newname)))
3529 (with-parsed-tramp-file-name (if t1 filename newname) nil
3530 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3532 (prog1
3533 (cond
3534 ;; Both are Tramp files.
3535 ((and t1 t2)
3536 (with-parsed-tramp-file-name filename v1
3537 (with-parsed-tramp-file-name newname v2
3538 (cond
3539 ;; Shortcut: if method, host, user are the same for both
3540 ;; files, we invoke `cp' or `mv' on the remote host
3541 ;; directly.
3542 ((tramp-equal-remote filename newname)
3543 (tramp-do-copy-or-rename-file-directly
3544 op filename newname
3545 ok-if-already-exists keep-date preserve-uid-gid))
3547 ;; Try out-of-band operation.
3548 ((tramp-method-out-of-band-p
3549 v1 (nth 7 (file-attributes filename)))
3550 (tramp-do-copy-or-rename-file-out-of-band
3551 op filename newname keep-date))
3553 ;; No shortcut was possible. So we copy the
3554 ;; file first. If the operation was `rename', we go
3555 ;; back and delete the original file (if the copy was
3556 ;; successful). The approach is simple-minded: we
3557 ;; create a new buffer, insert the contents of the
3558 ;; source file into it, then write out the buffer to
3559 ;; the target file. The advantage is that it doesn't
3560 ;; matter which filename handlers are used for the
3561 ;; source and target file.
3563 (tramp-do-copy-or-rename-file-via-buffer
3564 op filename newname keep-date))))))
3566 ;; One file is a Tramp file, the other one is local.
3567 ((or t1 t2)
3568 (with-parsed-tramp-file-name (if t1 filename newname) nil
3569 (cond
3570 ;; Fast track on local machine.
3571 ((tramp-local-host-p v)
3572 (tramp-do-copy-or-rename-file-directly
3573 op filename newname
3574 ok-if-already-exists keep-date preserve-uid-gid))
3576 ;; If the Tramp file has an out-of-band method, the corresponding
3577 ;; copy-program can be invoked.
3578 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3579 (tramp-do-copy-or-rename-file-out-of-band
3580 op filename newname keep-date))
3582 ;; Use the inline method via a Tramp buffer.
3583 (t (tramp-do-copy-or-rename-file-via-buffer
3584 op filename newname keep-date)))))
3587 ;; One of them must be a Tramp file.
3588 (error "Tramp implementation says this cannot happen")))
3590 ;; In case of `rename', we must flush the cache of the source file.
3591 (when (and t1 (eq op 'rename))
3592 (with-parsed-tramp-file-name filename nil
3593 (tramp-flush-file-property v (file-name-directory localname))
3594 (tramp-flush-file-property v localname)))
3596 ;; When newname did exist, we have wrong cached values.
3597 (when t2
3598 (with-parsed-tramp-file-name newname nil
3599 (tramp-flush-file-property v (file-name-directory localname))
3600 (tramp-flush-file-property v localname)))
3602 (with-parsed-tramp-file-name (if t1 filename newname) nil
3603 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
3605 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3606 "Use an Emacs buffer to copy or rename a file.
3607 First arg OP is either `copy' or `rename' and indicates the operation.
3608 FILENAME is the source file, NEWNAME the target file.
3609 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3610 (with-temp-buffer
3611 ;; We must disable multibyte, because binary data shall not be
3612 ;; converted.
3613 (set-buffer-multibyte nil)
3614 (let ((coding-system-for-read 'binary)
3615 (jka-compr-inhibit t))
3616 (insert-file-contents-literally filename))
3617 ;; We don't want the target file to be compressed, so we let-bind
3618 ;; `jka-compr-inhibit' to t.
3619 (let ((coding-system-for-write 'binary)
3620 (jka-compr-inhibit t))
3621 (write-region (point-min) (point-max) newname)))
3622 ;; KEEP-DATE handling.
3623 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3624 ;; Set the mode.
3625 (set-file-modes newname (tramp-default-file-modes filename))
3626 ;; If the operation was `rename', delete the original file.
3627 (unless (eq op 'copy) (delete-file filename)))
3629 (defun tramp-do-copy-or-rename-file-directly
3630 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3631 "Invokes `cp' or `mv' on the remote system.
3632 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3633 respectively. FILENAME specifies the file to copy or rename,
3634 NEWNAME is the name of the new file (for copy) or the new name of
3635 the file (for rename). Both files must reside on the same host.
3636 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3637 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3638 the uid and gid from FILENAME."
3639 (let ((t1 (tramp-tramp-file-p filename))
3640 (t2 (tramp-tramp-file-p newname))
3641 (file-times (nth 5 (file-attributes filename)))
3642 (file-modes (tramp-default-file-modes filename)))
3643 (with-parsed-tramp-file-name (if t1 filename newname) nil
3644 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3645 ((eq op 'copy) "cp -f")
3646 ((eq op 'rename) "mv -f")
3647 (t (tramp-error
3648 v 'file-error
3649 "Unknown operation `%s', must be `copy' or `rename'"
3650 op))))
3651 (localname1
3652 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3653 (localname2
3654 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
3655 (prefix (file-remote-p (if t1 filename newname)))
3656 cmd-result)
3658 (cond
3659 ;; Both files are on a remote host, with same user.
3660 ((and t1 t2)
3661 (setq cmd-result
3662 (tramp-send-command-and-check
3664 (format "%s %s %s" cmd
3665 (tramp-shell-quote-argument localname1)
3666 (tramp-shell-quote-argument localname2))))
3667 (with-current-buffer (tramp-get-buffer v)
3668 (goto-char (point-min))
3669 (unless
3671 (and keep-date
3672 ;; Mask cp -f error.
3673 (re-search-forward
3674 tramp-operation-not-permitted-regexp nil t))
3675 (zerop cmd-result))
3676 (tramp-error-with-buffer
3677 nil v 'file-error
3678 "Copying directly failed, see buffer `%s' for details."
3679 (buffer-name)))))
3681 ;; We are on the local host.
3682 ((or t1 t2)
3683 (cond
3684 ;; We can do it directly.
3685 ((let (file-name-handler-alist)
3686 (and (file-readable-p localname1)
3687 (file-writable-p (file-name-directory localname2))
3688 (or (file-directory-p localname2)
3689 (file-writable-p localname2))))
3690 (if (eq op 'copy)
3691 (tramp-compat-copy-file
3692 localname1 localname2 ok-if-already-exists
3693 keep-date preserve-uid-gid)
3694 (tramp-run-real-handler
3695 'rename-file (list localname1 localname2 ok-if-already-exists))))
3697 ;; We can do it directly with `tramp-send-command'
3698 ((and (file-readable-p (concat prefix localname1))
3699 (file-writable-p
3700 (file-name-directory (concat prefix localname2)))
3701 (or (file-directory-p (concat prefix localname2))
3702 (file-writable-p (concat prefix localname2))))
3703 (tramp-do-copy-or-rename-file-directly
3704 op (concat prefix localname1) (concat prefix localname2)
3705 ok-if-already-exists keep-date t)
3706 ;; We must change the ownership to the local user.
3707 (tramp-set-file-uid-gid
3708 (concat prefix localname2)
3709 (tramp-get-local-uid 'integer)
3710 (tramp-get-local-gid 'integer)))
3712 ;; We need a temporary file in between.
3714 ;; Create the temporary file.
3715 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3716 (unwind-protect
3717 (progn
3718 (cond
3721 (zerop
3722 (tramp-send-command-and-check
3723 v (format
3724 "%s %s %s" cmd
3725 (tramp-shell-quote-argument localname1)
3726 (tramp-shell-quote-argument tmpfile))))
3727 (tramp-error-with-buffer
3728 nil v 'file-error
3729 "Copying directly failed, see buffer `%s' for details."
3730 (tramp-get-buffer v)))
3731 ;; We must change the ownership as remote user.
3732 ;; Since this does not work reliable, we also
3733 ;; give read permissions.
3734 (set-file-modes
3735 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3736 (tramp-set-file-uid-gid
3737 (concat prefix tmpfile)
3738 (tramp-get-local-uid 'integer)
3739 (tramp-get-local-gid 'integer)))
3741 (if (eq op 'copy)
3742 (tramp-compat-copy-file
3743 localname1 tmpfile t
3744 keep-date preserve-uid-gid)
3745 (tramp-run-real-handler
3746 'rename-file
3747 (list localname1 tmpfile t)))
3748 ;; We must change the ownership as local user.
3749 ;; Since this does not work reliable, we also
3750 ;; give read permissions.
3751 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3752 (tramp-set-file-uid-gid
3753 tmpfile
3754 (tramp-get-remote-uid v 'integer)
3755 (tramp-get-remote-gid v 'integer))))
3757 ;; Move the temporary file to its destination.
3758 (cond
3761 (zerop
3762 (tramp-send-command-and-check
3763 v (format
3764 "cp -f -p %s %s"
3765 (tramp-shell-quote-argument tmpfile)
3766 (tramp-shell-quote-argument localname2))))
3767 (tramp-error-with-buffer
3768 nil v 'file-error
3769 "Copying directly failed, see buffer `%s' for details."
3770 (tramp-get-buffer v))))
3772 (tramp-run-real-handler
3773 'rename-file
3774 (list tmpfile localname2 ok-if-already-exists)))))
3776 ;; Save exit.
3777 (condition-case nil
3778 (delete-file tmpfile)
3779 (error)))))))))
3781 ;; Set the time and mode. Mask possible errors.
3782 (condition-case nil
3783 (when keep-date
3784 (set-file-times newname file-times)
3785 (set-file-modes newname file-modes))
3786 (error)))))
3788 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3789 "Invoke rcp program to copy.
3790 The method used must be an out-of-band method."
3791 (let ((t1 (tramp-tramp-file-p filename))
3792 (t2 (tramp-tramp-file-p newname))
3793 copy-program copy-args copy-env copy-keep-date port spec
3794 source target)
3796 (with-parsed-tramp-file-name (if t1 filename newname) nil
3797 (if (and t1 t2)
3799 ;; Both are Tramp files. We shall optimize it, when the
3800 ;; methods for filename and newname are the same.
3801 (let* ((dir-flag (file-directory-p filename))
3802 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3803 (if dir-flag
3804 (setq tmpfile
3805 (expand-file-name
3806 (file-name-nondirectory newname) tmpfile)))
3807 (unwind-protect
3808 (progn
3809 (tramp-do-copy-or-rename-file-out-of-band
3810 op filename tmpfile keep-date)
3811 (tramp-do-copy-or-rename-file-out-of-band
3812 'rename tmpfile newname keep-date))
3813 ;; Save exit.
3814 (condition-case nil
3815 (if dir-flag
3816 (delete-directory
3817 (expand-file-name ".." tmpfile) 'recursive)
3818 (delete-file tmpfile))
3819 (error))))
3821 ;; Expand hops. Might be necessary for gateway methods.
3822 (setq v (car (tramp-compute-multi-hops v)))
3823 (aset v 3 localname)
3825 ;; Check which ones of source and target are Tramp files.
3826 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3827 target (funcall
3828 (if (and (file-directory-p filename)
3829 (string-equal
3830 (file-name-nondirectory filename)
3831 (file-name-nondirectory newname)))
3832 'file-name-directory
3833 'identity)
3834 (if t2 (tramp-make-copy-program-file-name v) newname)))
3836 ;; Check for port number. Until now, there's no need for handling
3837 ;; like method, user, host.
3838 (setq host (tramp-file-name-real-host v)
3839 port (tramp-file-name-port v)
3840 port (or (and port (number-to-string port)) ""))
3842 ;; Compose copy command.
3843 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3844 (?t . ,(tramp-get-connection-property
3845 (tramp-get-connection-process v) "temp-file" ""))
3846 (?k . ,(if keep-date " " "")))
3847 copy-program (tramp-get-method-parameter
3848 method 'tramp-copy-program)
3849 copy-keep-date (tramp-get-method-parameter
3850 method 'tramp-copy-keep-date)
3851 copy-args
3852 (delq
3854 (mapcar
3855 (lambda (x)
3856 (setq
3858 ;; " " is indication for keep-date argument.
3859 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3860 (unless (member "" x) (mapconcat 'identity x " ")))
3861 (tramp-get-method-parameter method 'tramp-copy-args)))
3862 copy-env
3863 (delq
3865 (mapcar
3866 (lambda (x)
3867 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3868 (unless (member "" x) (mapconcat 'identity x " ")))
3869 (tramp-get-method-parameter method 'tramp-copy-env))))
3871 ;; Check for program.
3872 (when (and (fboundp 'executable-find)
3873 (not (let ((default-directory
3874 (tramp-compat-temporary-file-directory)))
3875 (executable-find copy-program))))
3876 (tramp-error
3877 v 'file-error "Cannot find copy program: %s" copy-program))
3879 ;; Set variables for computing the prompt for reading
3880 ;; password.
3881 (setq tramp-current-method (tramp-file-name-method v)
3882 tramp-current-user (tramp-file-name-user v)
3883 tramp-current-host (tramp-file-name-host v))
3885 (unwind-protect
3886 (with-temp-buffer
3887 ;; The default directory must be remote.
3888 (let ((default-directory
3889 (file-name-directory (if t1 filename newname)))
3890 (process-environment (copy-sequence process-environment)))
3891 ;; Set the transfer process properties.
3892 (tramp-set-connection-property
3893 v "process-name" (buffer-name (current-buffer)))
3894 (tramp-set-connection-property
3895 v "process-buffer" (current-buffer))
3896 (while copy-env
3897 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3898 (setenv (pop copy-env) (pop copy-env)))
3900 ;; Use an asynchronous process. By this, password can
3901 ;; be handled. The default directory must be local, in
3902 ;; order to apply the correct `copy-program'. We don't
3903 ;; set a timeout, because the copying of large files can
3904 ;; last longer than 60 secs.
3905 (let ((p (let ((default-directory
3906 (tramp-compat-temporary-file-directory)))
3907 (apply 'start-process
3908 (tramp-get-connection-property
3909 v "process-name" nil)
3910 (tramp-get-connection-property
3911 v "process-buffer" nil)
3912 copy-program
3913 (append copy-args (list source target))))))
3914 (tramp-message
3915 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3916 (tramp-set-process-query-on-exit-flag p nil)
3917 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
3919 ;; Reset the transfer process properties.
3920 (tramp-set-connection-property v "process-name" nil)
3921 (tramp-set-connection-property v "process-buffer" nil))
3923 ;; Handle KEEP-DATE argument.
3924 (when (and keep-date (not copy-keep-date))
3925 (set-file-times newname (nth 5 (file-attributes filename))))
3927 ;; Set the mode.
3928 (unless (and keep-date copy-keep-date)
3929 (ignore-errors
3930 (set-file-modes newname (tramp-default-file-modes filename)))))
3932 ;; If the operation was `rename', delete the original file.
3933 (unless (eq op 'copy)
3934 (if (file-regular-p filename)
3935 (delete-file filename)
3936 (delete-directory filename 'recursive))))))
3938 (defun tramp-handle-make-directory (dir &optional parents)
3939 "Like `make-directory' for Tramp files."
3940 (setq dir (expand-file-name dir))
3941 (with-parsed-tramp-file-name dir nil
3942 (tramp-flush-directory-property v (file-name-directory localname))
3943 (save-excursion
3944 (tramp-barf-unless-okay
3946 (format "%s %s"
3947 (if parents "mkdir -p" "mkdir")
3948 (tramp-shell-quote-argument localname))
3949 "Couldn't make directory %s" dir))))
3951 (defun tramp-handle-delete-directory (directory &optional recursive)
3952 "Like `delete-directory' for Tramp files."
3953 (setq directory (expand-file-name directory))
3954 (with-parsed-tramp-file-name directory nil
3955 (tramp-flush-file-property v (file-name-directory localname))
3956 (tramp-flush-directory-property v localname)
3957 (unless (zerop (tramp-send-command-and-check
3959 (format
3960 "%s %s"
3961 (if recursive "rm -rf" "rmdir")
3962 (tramp-shell-quote-argument localname))))
3963 (tramp-error v 'file-error "Couldn't delete %s" directory))))
3965 (defun tramp-handle-delete-file (filename)
3966 "Like `delete-file' for Tramp files."
3967 (setq filename (expand-file-name filename))
3968 (with-parsed-tramp-file-name filename nil
3969 (tramp-flush-file-property v (file-name-directory localname))
3970 (tramp-flush-file-property v localname)
3971 (unless (zerop (tramp-send-command-and-check
3973 (format "rm -f %s"
3974 (tramp-shell-quote-argument localname))))
3975 (tramp-error v 'file-error "Couldn't delete %s" filename))))
3977 ;; Dired.
3979 ;; CCC: This does not seem to be enough. Something dies when
3980 ;; we try and delete two directories under Tramp :/
3981 (defun tramp-handle-dired-recursive-delete-directory (filename)
3982 "Recursively delete the directory given.
3983 This is like `dired-recursive-delete-directory' for Tramp files."
3984 (with-parsed-tramp-file-name filename nil
3985 ;; Run a shell command 'rm -r <localname>'
3986 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
3987 (unless (file-exists-p filename)
3988 (tramp-error v 'file-error "No such directory: %s" filename))
3989 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
3990 (tramp-send-command
3992 (format "rm -rf %s" (tramp-shell-quote-argument localname))
3993 ;; Don't read the output, do it explicitely.
3994 nil t)
3995 ;; Wait for the remote system to return to us...
3996 ;; This might take a while, allow it plenty of time.
3997 (tramp-wait-for-output (tramp-get-connection-process v) 120)
3998 ;; Make sure that it worked...
3999 (tramp-flush-file-property v (file-name-directory localname))
4000 (tramp-flush-directory-property v localname)
4001 (and (file-exists-p filename)
4002 (tramp-error
4003 v 'file-error "Failed to recursively delete %s" filename))))
4005 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4006 "Like `dired-compress-file' for Tramp files."
4007 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4008 ;; Code stolen mainly from dired-aux.el.
4009 (with-parsed-tramp-file-name file nil
4010 (tramp-flush-file-property v localname)
4011 (save-excursion
4012 (let ((suffixes
4013 (if (not (featurep 'xemacs))
4014 ;; Emacs case
4015 (symbol-value 'dired-compress-file-suffixes)
4016 ;; XEmacs has `dired-compression-method-alist', which is
4017 ;; transformed into `dired-compress-file-suffixes' structure.
4018 (mapcar
4019 (lambda (x)
4020 (list (concat (regexp-quote (nth 1 x)) "\\'")
4022 (mapconcat 'identity (nth 3 x) " ")))
4023 (symbol-value 'dired-compression-method-alist))))
4024 suffix)
4025 ;; See if any suffix rule matches this file name.
4026 (while suffixes
4027 (let (case-fold-search)
4028 (if (string-match (car (car suffixes)) localname)
4029 (setq suffix (car suffixes) suffixes nil))
4030 (setq suffixes (cdr suffixes))))
4032 (cond ((file-symlink-p file)
4033 nil)
4034 ((and suffix (nth 2 suffix))
4035 ;; We found an uncompression rule.
4036 (tramp-message v 0 "Uncompressing %s..." file)
4037 (when (zerop (tramp-send-command-and-check
4038 v (concat (nth 2 suffix) " "
4039 (tramp-shell-quote-argument localname))))
4040 (tramp-message v 0 "Uncompressing %s...done" file)
4041 ;; `dired-remove-file' is not defined in XEmacs
4042 (funcall (symbol-function 'dired-remove-file) file)
4043 (string-match (car suffix) file)
4044 (concat (substring file 0 (match-beginning 0)))))
4046 ;; We don't recognize the file as compressed, so compress it.
4047 ;; Try gzip.
4048 (tramp-message v 0 "Compressing %s..." file)
4049 (when (zerop (tramp-send-command-and-check
4050 v (concat "gzip -f "
4051 (tramp-shell-quote-argument localname))))
4052 (tramp-message v 0 "Compressing %s...done" file)
4053 ;; `dired-remove-file' is not defined in XEmacs
4054 (funcall (symbol-function 'dired-remove-file) file)
4055 (cond ((file-exists-p (concat file ".gz"))
4056 (concat file ".gz"))
4057 ((file-exists-p (concat file ".z"))
4058 (concat file ".z"))
4059 (t nil)))))))))
4061 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4062 "Like `dired-uncache' for Tramp files."
4063 ;; DIR-P is valid for XEmacs only.
4064 (with-parsed-tramp-file-name
4065 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4066 (tramp-flush-file-property v localname)))
4068 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4069 ;; not sure at all that this is the right way to do it, but let's hope
4070 ;; it works for now, and wait for a guru to point out the Right Way to
4071 ;; achieve this.
4072 ;;(eval-when-compile
4073 ;; (unless (fboundp 'dired-insert-set-properties)
4074 ;; (fset 'dired-insert-set-properties 'ignore)))
4075 ;; Gerd suggests this:
4076 (eval-when-compile (require 'dired))
4077 ;; Note that dired is required at run-time, too, when it is needed.
4078 ;; It is only needed on XEmacs for the function
4079 ;; `dired-insert-set-properties'.
4081 (defun tramp-handle-insert-directory
4082 (filename switches &optional wildcard full-directory-p)
4083 "Like `insert-directory' for Tramp files."
4084 (setq filename (expand-file-name filename))
4085 (with-parsed-tramp-file-name filename nil
4086 (if (and (featurep 'ls-lisp)
4087 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4088 (tramp-run-real-handler
4089 'insert-directory (list filename switches wildcard full-directory-p))
4090 (when (stringp switches)
4091 (setq switches (split-string switches)))
4092 (when (and (member "--dired" switches)
4093 (not (tramp-get-ls-command-with-dired v)))
4094 (setq switches (delete "--dired" switches)))
4095 (when wildcard
4096 (setq wildcard (tramp-run-real-handler
4097 'file-name-nondirectory (list localname)))
4098 (setq localname (tramp-run-real-handler
4099 'file-name-directory (list localname))))
4100 (unless full-directory-p
4101 (setq switches (add-to-list 'switches "-d" 'append)))
4102 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4103 (when wildcard
4104 (setq switches (concat switches " " wildcard)))
4105 (tramp-message
4106 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4107 switches filename (if wildcard "yes" "no")
4108 (if full-directory-p "yes" "no"))
4109 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4110 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4111 (if full-directory-p
4112 (tramp-send-command
4114 (format "%s %s %s 2>/dev/null"
4115 (tramp-get-ls-command v)
4116 switches
4117 (if wildcard
4118 localname
4119 (tramp-shell-quote-argument (concat localname ".")))))
4120 (tramp-barf-unless-okay
4122 (format "cd %s" (tramp-shell-quote-argument
4123 (tramp-run-real-handler
4124 'file-name-directory (list localname))))
4125 "Couldn't `cd %s'"
4126 (tramp-shell-quote-argument
4127 (tramp-run-real-handler 'file-name-directory (list localname))))
4128 (tramp-send-command
4130 (format "%s %s %s"
4131 (tramp-get-ls-command v)
4132 switches
4133 (if (or wildcard
4134 (zerop (length
4135 (tramp-run-real-handler
4136 'file-name-nondirectory (list localname)))))
4138 (tramp-shell-quote-argument
4139 (tramp-run-real-handler
4140 'file-name-nondirectory (list localname)))))))
4141 (let ((beg (point)))
4142 ;; We cannot use `insert-buffer-substring' because the Tramp
4143 ;; buffer changes its contents before insertion due to calling
4144 ;; `expand-file' and alike.
4145 (insert
4146 (with-current-buffer (tramp-get-buffer v)
4147 (buffer-string)))
4149 ;; Check for "--dired" output.
4150 (forward-line -2)
4151 (when (looking-at "//SUBDIRED//")
4152 (forward-line -1))
4153 (when (looking-at "//DIRED//")
4154 (let ((end (tramp-compat-line-end-position))
4155 (linebeg (point)))
4156 ;; Now read the numeric positions of file names.
4157 (goto-char linebeg)
4158 (forward-word 1)
4159 (forward-char 3)
4160 (while (< (point) end)
4161 (let ((start (+ beg (read (current-buffer))))
4162 (end (+ beg (read (current-buffer)))))
4163 (if (memq (char-after end) '(?\n ?\ ))
4164 ;; End is followed by \n or by " -> ".
4165 (put-text-property start end 'dired-filename t))))))
4166 ;; Remove trailing lines.
4167 (goto-char (tramp-compat-line-beginning-position))
4168 (while (looking-at "//")
4169 (forward-line 1)
4170 (delete-region (match-beginning 0) (point)))
4172 ;; The inserted file could be from somewhere else.
4173 (when (and (not wildcard) (not full-directory-p))
4174 (goto-char (point-max))
4175 (when (file-symlink-p filename)
4176 (goto-char (search-backward "->" beg 'noerror)))
4177 (search-backward
4178 (if (zerop (length (file-name-nondirectory filename)))
4180 (file-name-nondirectory filename))
4181 beg 'noerror)
4182 (replace-match (file-relative-name filename) t))
4184 (goto-char (point-max))))))
4186 (defun tramp-handle-unhandled-file-name-directory (filename)
4187 "Like `unhandled-file-name-directory' for Tramp files."
4188 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4189 ;; for backward compatibility.
4190 (expand-file-name "~/"))
4192 ;; Canonicalization of file names.
4194 (defun tramp-handle-expand-file-name (name &optional dir)
4195 "Like `expand-file-name' for Tramp files.
4196 If the localname part of the given filename starts with \"/../\" then
4197 the result will be a local, non-Tramp, filename."
4198 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4199 (setq dir (or dir default-directory "/"))
4200 ;; Unless NAME is absolute, concat DIR and NAME.
4201 (unless (file-name-absolute-p name)
4202 (setq name (concat (file-name-as-directory dir) name)))
4203 ;; If NAME is not a Tramp file, run the real handler.
4204 (if (not (tramp-tramp-file-p name))
4205 (tramp-run-real-handler 'expand-file-name (list name nil))
4206 ;; Dissect NAME.
4207 (with-parsed-tramp-file-name name nil
4208 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4209 (setq localname (concat "~/" localname)))
4210 ;; Tilde expansion if necessary. This needs a shell which
4211 ;; groks tilde expansion! The function `tramp-find-shell' is
4212 ;; supposed to find such a shell on the remote host. Please
4213 ;; tell me about it when this doesn't work on your system.
4214 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4215 (let ((uname (match-string 1 localname))
4216 (fname (match-string 2 localname)))
4217 ;; We cannot simply apply "~/", because under sudo "~/" is
4218 ;; expanded to the local user home directory but to the
4219 ;; root home directory. On the other hand, using always
4220 ;; the default user name for tilde expansion is not
4221 ;; appropriate either, because ssh and companions might
4222 ;; use a user name from the config file.
4223 (when (and (string-equal uname "~")
4224 (string-match "\\`su\\(do\\)?\\'" method))
4225 (setq uname (concat uname user)))
4226 (setq uname
4227 (with-connection-property v uname
4228 (tramp-send-command
4229 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4230 (with-current-buffer (tramp-get-buffer v)
4231 (goto-char (point-min))
4232 (buffer-substring
4233 (point) (tramp-compat-line-end-position)))))
4234 (setq localname (concat uname fname))))
4235 ;; There might be a double slash, for example when "~/"
4236 ;; expands to "/". Remove this.
4237 (while (string-match "//" localname)
4238 (setq localname (replace-match "/" t t localname)))
4239 ;; No tilde characters in file name, do normal
4240 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4241 ;; `directory-sep-char' here for XEmacs on Windows, which would
4242 ;; otherwise use backslash. `default-directory' is bound,
4243 ;; because on Windows there would be problems with UNC shares or
4244 ;; Cygwin mounts.
4245 (let ((directory-sep-char ?/)
4246 (default-directory (tramp-compat-temporary-file-directory)))
4247 (tramp-make-tramp-file-name
4248 method user host
4249 (tramp-drop-volume-letter
4250 (tramp-run-real-handler
4251 'expand-file-name (list localname))))))))
4253 (defun tramp-replace-environment-variables (filename)
4254 "Replace environment variables in FILENAME.
4255 Return the string with the replaced variables."
4256 (save-match-data
4257 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4258 ;; `$' is coded as `$$'.
4259 (when (and idx
4260 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4261 (getenv (match-string 1 filename)))
4262 (setq filename
4263 (replace-match
4264 (substitute-in-file-name (match-string 0 filename))
4265 t nil filename)))
4266 filename)))
4268 (defun tramp-handle-substitute-in-file-name (filename)
4269 "Like `substitute-in-file-name' for Tramp files.
4270 \"//\" and \"/~\" substitute only in the local filename part.
4271 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4272 beginning of local filename are not substituted."
4273 ;; First, we must replace environment variables.
4274 (setq filename (tramp-replace-environment-variables filename))
4275 (with-parsed-tramp-file-name filename nil
4276 (if (equal tramp-syntax 'url)
4277 ;; We need to check localname only. The other parts cannot contain
4278 ;; "//" or "/~".
4279 (if (and (> (length localname) 1)
4280 (or (string-match "//" localname)
4281 (string-match "/~" localname 1)))
4282 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4283 (tramp-make-tramp-file-name
4284 (when method (substitute-in-file-name method))
4285 (when user (substitute-in-file-name user))
4286 (when host (substitute-in-file-name host))
4287 (when localname
4288 (tramp-run-real-handler
4289 'substitute-in-file-name (list localname)))))
4290 ;; Ignore in LOCALNAME everything before "//" or "/~".
4291 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4292 (setq filename
4293 (concat (file-remote-p filename)
4294 (replace-match "\\1" nil nil localname)))
4295 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4296 (when (string-match "~$" filename)
4297 (setq filename (concat filename "/"))))
4298 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4300 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4301 ;; which calls corresponding functions (see minibuf.el).
4302 (when (fboundp 'minibuffer-electric-separator)
4303 (mapc
4304 (lambda (x)
4305 (eval
4306 `(defadvice ,x
4307 (around ,(intern (format "tramp-advice-%s" x)) activate)
4308 "Invoke `substitute-in-file-name' for Tramp files."
4309 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4310 (tramp-tramp-file-p (buffer-substring)))
4311 ;; We don't need to handle `last-input-event', because
4312 ;; due to the key map we know it must be ?/ or ?~.
4313 (let ((s (concat (buffer-substring (point-min) (point))
4314 (string last-command-char))))
4315 (delete-region (point-min) (point))
4316 (insert (substitute-in-file-name s))
4317 (setq ad-return-value last-command-char))
4318 ad-do-it)))
4319 (eval
4320 `(add-hook
4321 'tramp-unload-hook
4322 (lambda ()
4323 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4324 (ad-activate ',x)))))
4326 '(minibuffer-electric-separator
4327 minibuffer-electric-tilde)))
4330 ;;; Remote commands:
4332 (defun tramp-handle-executable-find (command)
4333 "Like `executable-find' for Tramp files."
4334 (with-parsed-tramp-file-name default-directory nil
4335 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4337 ;; We use BUFFER also as connection buffer during setup. Because of
4338 ;; this, its original contents must be saved, and restored once
4339 ;; connection has been setup.
4340 (defun tramp-handle-start-file-process (name buffer program &rest args)
4341 "Like `start-file-process' for Tramp files."
4342 (with-parsed-tramp-file-name default-directory nil
4343 (unless (stringp program)
4344 (tramp-error
4345 v 'file-error "pty association is not supported for `%s'" name))
4346 (unwind-protect
4347 (let ((command (format "cd %s; exec %s"
4348 (tramp-shell-quote-argument localname)
4349 (mapconcat 'tramp-shell-quote-argument
4350 (cons program args) " ")))
4351 (name1 name)
4352 (i 0))
4353 (unless buffer
4354 ;; BUFFER can be nil. We use a temporary buffer.
4355 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4356 (while (get-process name1)
4357 ;; NAME must be unique as process name.
4358 (setq i (1+ i)
4359 name1 (format "%s<%d>" name i)))
4360 (setq name name1)
4361 ;; Set the new process properties.
4362 (tramp-set-connection-property v "process-name" name)
4363 (tramp-set-connection-property v "process-buffer" buffer)
4364 ;; Activate narrowing in order to save BUFFER contents.
4365 ;; Clear also the modification time; otherwise we might be
4366 ;; interrupted by `verify-visited-file-modtime'.
4367 (with-current-buffer (tramp-get-connection-buffer v)
4368 (clear-visited-file-modtime)
4369 (narrow-to-region (point-max) (point-max)))
4370 ;; Send the command. `tramp-send-command' opens a new
4371 ;; connection.
4372 (tramp-send-command v command nil t) ; nooutput
4373 ;; Set query flag for this process.
4374 (tramp-set-process-query-on-exit-flag
4375 (tramp-get-connection-process v) t)
4376 ;; Return process.
4377 (tramp-get-connection-process v))
4378 ;; Save exit.
4379 (with-current-buffer (tramp-get-connection-buffer v)
4380 (if (string-match tramp-temp-buffer-name (buffer-name))
4381 (progn
4382 (set-process-buffer (tramp-get-connection-process v) nil)
4383 (kill-buffer (current-buffer)))
4384 (widen)
4385 (goto-char (point-max))))
4386 (tramp-set-connection-property v "process-name" nil)
4387 (tramp-set-connection-property v "process-buffer" nil))))
4389 (defun tramp-handle-process-file
4390 (program &optional infile destination display &rest args)
4391 "Like `process-file' for Tramp files."
4392 ;; The implementation is not complete yet.
4393 (when (and (numberp destination) (zerop destination))
4394 (error "Implementation does not handle immediate return"))
4396 (with-parsed-tramp-file-name default-directory nil
4397 (let (command input tmpinput stderr tmpstderr outbuf ret)
4398 ;; Compute command.
4399 (setq command (mapconcat 'tramp-shell-quote-argument
4400 (cons program args) " "))
4401 ;; Determine input.
4402 (if (null infile)
4403 (setq input "/dev/null")
4404 (setq infile (expand-file-name infile))
4405 (if (tramp-equal-remote default-directory infile)
4406 ;; INFILE is on the same remote host.
4407 (setq input (with-parsed-tramp-file-name infile nil localname))
4408 ;; INFILE must be copied to remote host.
4409 (setq input (tramp-make-tramp-temp-file v)
4410 tmpinput (tramp-make-tramp-file-name method user host input))
4411 (copy-file infile tmpinput t)))
4412 (when input (setq command (format "%s <%s" command input)))
4414 ;; Determine output.
4415 (cond
4416 ;; Just a buffer.
4417 ((bufferp destination)
4418 (setq outbuf destination))
4419 ;; A buffer name.
4420 ((stringp destination)
4421 (setq outbuf (get-buffer-create destination)))
4422 ;; (REAL-DESTINATION ERROR-DESTINATION)
4423 ((consp destination)
4424 ;; output.
4425 (cond
4426 ((bufferp (car destination))
4427 (setq outbuf (car destination)))
4428 ((stringp (car destination))
4429 (setq outbuf (get-buffer-create (car destination))))
4430 ((car destination)
4431 (setq outbuf (current-buffer))))
4432 ;; stderr.
4433 (cond
4434 ((stringp (cadr destination))
4435 (setcar (cdr destination) (expand-file-name (cadr destination)))
4436 (if (tramp-equal-remote default-directory (cadr destination))
4437 ;; stderr is on the same remote host.
4438 (setq stderr (with-parsed-tramp-file-name
4439 (cadr destination) nil localname))
4440 ;; stderr must be copied to remote host. The temporary
4441 ;; file must be deleted after execution.
4442 (setq stderr (tramp-make-tramp-temp-file v)
4443 tmpstderr (tramp-make-tramp-file-name
4444 method user host stderr))))
4445 ;; stderr to be discarded.
4446 ((null (cadr destination))
4447 (setq stderr "/dev/null"))))
4448 ;; 't
4449 (destination
4450 (setq outbuf (current-buffer))))
4451 (when stderr (setq command (format "%s 2>%s" command stderr)))
4453 ;; Send the command. It might not return in time, so we protect it.
4454 (condition-case nil
4455 (unwind-protect
4456 (setq ret
4457 (tramp-send-command-and-check
4458 v (format "\\cd %s; %s"
4459 (tramp-shell-quote-argument localname)
4460 command)
4461 nil t))
4462 ;; We should show the output anyway.
4463 (when outbuf
4464 (with-current-buffer outbuf
4465 (insert
4466 (with-current-buffer (tramp-get-connection-buffer v)
4467 (buffer-string))))
4468 (when display (display-buffer outbuf))))
4469 ;; When the user did interrupt, we should do it also. We use
4470 ;; return code -1 as marker.
4471 (quit
4472 (kill-buffer (tramp-get-connection-buffer v))
4473 (setq ret -1))
4474 ;; Handle errors.
4475 (error
4476 (kill-buffer (tramp-get-connection-buffer v))
4477 (setq ret 1)))
4479 ;; Provide error file.
4480 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4482 ;; Cleanup. We remove all file cache values for the connection,
4483 ;; because the remote process could have changed them.
4484 (when tmpinput (delete-file tmpinput))
4486 ;; `process-file-side-effects' has been introduced with GNU
4487 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4488 ;; by `program'. If it doesn't exist, we assume its default
4489 ;; value 't'.
4490 (unless (and (boundp 'process-file-side-effects)
4491 (not (symbol-value 'process-file-side-effects)))
4492 (tramp-flush-directory-property v ""))
4494 ;; Return exit status.
4495 (if (equal ret -1)
4496 (keyboard-quit)
4497 ret))))
4499 (defun tramp-local-call-process
4500 (program &optional infile destination display &rest args)
4501 "Calls `call-process' on the local host.
4502 This is needed because for some Emacs flavors Tramp has
4503 defadviced `call-process' to behave like `process-file'. The
4504 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4505 (let ((default-directory
4506 (if (file-remote-p default-directory)
4507 (tramp-compat-temporary-file-directory)
4508 default-directory)))
4509 (if (executable-find program)
4510 (apply 'call-process program infile destination display args)
4511 1)))
4513 (defun tramp-handle-call-process-region
4514 (start end program &optional delete buffer display &rest args)
4515 "Like `call-process-region' for Tramp files."
4516 (let ((tmpfile (tramp-compat-make-temp-file "")))
4517 (write-region start end tmpfile)
4518 (when delete (delete-region start end))
4519 (unwind-protect
4520 (apply 'call-process program tmpfile buffer display args)
4521 (delete-file tmpfile))))
4523 (defun tramp-handle-shell-command
4524 (command &optional output-buffer error-buffer)
4525 "Like `shell-command' for Tramp files."
4526 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4527 ;; We cannot use `shell-file-name' and `shell-command-switch',
4528 ;; they are variables of the local host.
4529 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
4530 current-buffer-p
4531 (output-buffer
4532 (cond
4533 ((bufferp output-buffer) output-buffer)
4534 ((stringp output-buffer) (get-buffer-create output-buffer))
4535 (output-buffer
4536 (setq current-buffer-p t)
4537 (current-buffer))
4538 (t (get-buffer-create
4539 (if asynchronous
4540 "*Async Shell Command*"
4541 "*Shell Command Output*")))))
4542 (error-buffer
4543 (cond
4544 ((bufferp error-buffer) error-buffer)
4545 ((stringp error-buffer) (get-buffer-create error-buffer))))
4546 (buffer
4547 (if (and (not asynchronous) error-buffer)
4548 (with-parsed-tramp-file-name default-directory nil
4549 (list output-buffer (tramp-make-tramp-temp-file v)))
4550 output-buffer))
4551 (p (get-buffer-process output-buffer)))
4553 ;; Check whether there is another process running. Tramp does not
4554 ;; support 2 (asynchronous) processes in parallel.
4555 (when p
4556 (if (yes-or-no-p "A command is running. Kill it? ")
4557 (condition-case nil
4558 (kill-process p)
4559 (error nil))
4560 (error "Shell command in progress")))
4562 (if current-buffer-p
4563 (progn
4564 (barf-if-buffer-read-only)
4565 (push-mark nil t))
4566 (with-current-buffer output-buffer
4567 (setq buffer-read-only nil)
4568 (erase-buffer)))
4570 (if (and (not current-buffer-p) (integerp asynchronous))
4571 (prog1
4572 ;; Run the process.
4573 (apply 'start-file-process "*Async Shell*" buffer args)
4574 ;; Display output.
4575 (pop-to-buffer output-buffer)
4576 (setq mode-line-process '(":%s"))
4577 (require 'shell) (shell-mode))
4579 (prog1
4580 ;; Run the process.
4581 (apply 'process-file (car args) nil buffer nil (cdr args))
4582 ;; Insert error messages if they were separated.
4583 (when (listp buffer)
4584 (with-current-buffer error-buffer
4585 (insert-file-contents (cadr buffer)))
4586 (delete-file (cadr buffer)))
4587 (if current-buffer-p
4588 ;; This is like exchange-point-and-mark, but doesn't
4589 ;; activate the mark. It is cleaner to avoid activation,
4590 ;; even though the command loop would deactivate the mark
4591 ;; because we inserted text.
4592 (goto-char (prog1 (mark t)
4593 (set-marker (mark-marker) (point)
4594 (current-buffer))))
4595 ;; There's some output, display it.
4596 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4597 (if (functionp 'display-message-or-buffer)
4598 (funcall (symbol-function 'display-message-or-buffer)
4599 output-buffer)
4600 (pop-to-buffer output-buffer))))))))
4602 ;; File Editing.
4604 (defvar tramp-handle-file-local-copy-hook nil
4605 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4607 (defun tramp-handle-file-local-copy (filename)
4608 "Like `file-local-copy' for Tramp files."
4610 (with-parsed-tramp-file-name filename nil
4611 (unless (file-exists-p filename)
4612 (tramp-error
4613 v 'file-error
4614 "Cannot make local copy of non-existing file `%s'" filename))
4616 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
4617 (loc-dec (tramp-get-local-coding v "local-decoding"))
4618 (tmpfile (tramp-compat-make-temp-file filename)))
4620 (condition-case err
4621 (cond
4622 ;; `copy-file' handles direct copy and out-of-band methods.
4623 ((or (tramp-local-host-p v)
4624 (tramp-method-out-of-band-p
4625 v (nth 7 (file-attributes filename))))
4626 (copy-file filename tmpfile t t))
4628 ;; Use inline encoding for file transfer.
4629 (rem-enc
4630 (save-excursion
4631 (tramp-message v 5 "Encoding remote file %s..." filename)
4632 (tramp-barf-unless-okay
4634 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4635 "Encoding remote file failed")
4636 (tramp-message v 5 "Encoding remote file %s...done" filename)
4638 (if (and (symbolp loc-dec) (fboundp loc-dec))
4639 ;; If local decoding is a function, we call it. We
4640 ;; must disable multibyte, because
4641 ;; `uudecode-decode-region' doesn't handle it
4642 ;; correctly.
4643 (with-temp-buffer
4644 (set-buffer-multibyte nil)
4645 (insert-buffer-substring (tramp-get-buffer v))
4646 (tramp-message
4647 v 5 "Decoding remote file %s with function %s..."
4648 filename loc-dec)
4649 (funcall loc-dec (point-min) (point-max))
4650 ;; Unset `file-name-handler-alist'. Otherwise,
4651 ;; epa-file gets confused.
4652 (let (file-name-handler-alist
4653 (coding-system-for-write 'binary))
4654 (write-region (point-min) (point-max) tmpfile)))
4656 ;; If tramp-decoding-function is not defined for this
4657 ;; method, we invoke tramp-decoding-command instead.
4658 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4659 ;; Unset `file-name-handler-alist'. Otherwise,
4660 ;; epa-file gets confused.
4661 (let (file-name-handler-alist
4662 (coding-system-for-write 'binary))
4663 (write-region (point-min) (point-max) tmpfile2))
4664 (tramp-message
4665 v 5 "Decoding remote file %s with command %s..."
4666 filename loc-dec)
4667 (unwind-protect
4668 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4669 (delete-file tmpfile2))))
4671 (tramp-message v 5 "Decoding remote file %s...done" filename)
4672 ;; Set proper permissions.
4673 (set-file-modes tmpfile (tramp-default-file-modes filename))
4674 ;; Set local user ownership.
4675 (tramp-set-file-uid-gid tmpfile)))
4677 ;; Oops, I don't know what to do.
4678 (t (tramp-error
4679 v 'file-error "Wrong method specification for `%s'" method)))
4681 ;; Error handling.
4682 ((error quit)
4683 (delete-file tmpfile)
4684 (signal (car err) (cdr err))))
4686 (run-hooks 'tramp-handle-file-local-copy-hook)
4687 tmpfile)))
4689 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4690 "Like `file-remote-p' for Tramp files."
4691 (let ((tramp-verbose 3))
4692 (when (tramp-tramp-file-p filename)
4693 (let* ((v (tramp-dissect-file-name filename))
4694 (p (tramp-get-connection-process v))
4695 (c (and p (processp p) (memq (process-status p) '(run open)))))
4696 ;; We expand the file name only, if there is already a connection.
4697 (with-parsed-tramp-file-name
4698 (if c (expand-file-name filename) filename) nil
4699 (and (or (not connected) c)
4700 (cond
4701 ((eq identification 'method) method)
4702 ((eq identification 'user) user)
4703 ((eq identification 'host) host)
4704 ((eq identification 'localname) localname)
4705 (t (tramp-make-tramp-file-name method user host "")))))))))
4707 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4708 "Like `find-operation-coding-system' for Tramp filenames.
4709 Tramp's `insert-file-contents' and `write-region' work over
4710 temporary file names. If `file-coding-system-alist' contains an
4711 expression, which matches more than the file name suffix, the
4712 coding system might not be determined. This function repairs it."
4713 (let (result)
4714 (dolist (elt file-coding-system-alist result)
4715 (when (and (consp elt) (string-match (car elt) filename))
4716 ;; We found a matching entry in `file-coding-system-alist'.
4717 ;; So we add a similar entry, but with the temporary file name
4718 ;; as regexp.
4719 (add-to-list
4720 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4722 (defun tramp-handle-insert-file-contents
4723 (filename &optional visit beg end replace)
4724 "Like `insert-file-contents' for Tramp files."
4725 (barf-if-buffer-read-only)
4726 (setq filename (expand-file-name filename))
4727 (let (coding-system-used result local-copy remote-copy)
4728 (with-parsed-tramp-file-name filename nil
4729 (unwind-protect
4730 (if (not (file-exists-p filename))
4731 ;; We don't raise a Tramp error, because it might be
4732 ;; suppressed, like in `find-file-noselect-1'.
4733 (signal 'file-error
4734 (list "File not found on remote host" filename))
4736 (if (and (tramp-local-host-p v)
4737 (let (file-name-handler-alist)
4738 (file-readable-p localname)))
4739 ;; Short track: if we are on the local host, we can
4740 ;; run directly.
4741 (setq result
4742 (tramp-run-real-handler
4743 'insert-file-contents
4744 (list localname visit beg end replace)))
4746 ;; When we shall insert only a part of the file, we copy
4747 ;; this part.
4748 (when (or beg end)
4749 (setq remote-copy (tramp-make-tramp-temp-file v))
4750 (tramp-send-command
4752 (cond
4753 ((and beg end)
4754 (format "tail -c +%d %s | head -c +%d >%s"
4755 (1+ beg) (tramp-shell-quote-argument localname)
4756 (- end beg) remote-copy))
4757 (beg
4758 (format "tail -c +%d %s >%s"
4759 (1+ beg) (tramp-shell-quote-argument localname)
4760 remote-copy))
4761 (end
4762 (format "head -c +%d %s >%s"
4763 (1+ end) (tramp-shell-quote-argument localname)
4764 remote-copy)))))
4766 ;; `insert-file-contents-literally' takes care to avoid
4767 ;; calling jka-compr. By let-binding
4768 ;; `inhibit-file-name-operation', we propagate that care
4769 ;; to the `file-local-copy' operation.
4770 (setq local-copy
4771 (let ((inhibit-file-name-operation
4772 (when (eq inhibit-file-name-operation
4773 'insert-file-contents)
4774 'file-local-copy)))
4775 (cond
4776 ((stringp remote-copy)
4777 (file-local-copy
4778 (tramp-make-tramp-file-name
4779 method user host remote-copy)))
4780 ((stringp tramp-temp-buffer-file-name)
4781 (copy-file filename tramp-temp-buffer-file-name 'ok)
4782 tramp-temp-buffer-file-name)
4783 (t (file-local-copy filename)))))
4785 ;; When the file is not readable for the owner, it
4786 ;; cannot be inserted, even it is redable for the group
4787 ;; or for everybody.
4788 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4790 (when (and (null remote-copy)
4791 (tramp-get-method-parameter
4792 method 'tramp-copy-keep-tmpfile))
4793 ;; We keep the local file for performance reasons,
4794 ;; useful for "rsync".
4795 (setq tramp-temp-buffer-file-name local-copy)
4796 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4798 (tramp-message
4799 v 4 "Inserting local temp file `%s'..." local-copy)
4801 ;; We must ensure that `file-coding-system-alist'
4802 ;; matches `local-copy'.
4803 (let ((file-coding-system-alist
4804 (tramp-find-file-name-coding-system-alist
4805 filename local-copy)))
4806 (setq result
4807 (insert-file-contents
4808 local-copy nil nil nil replace))
4809 ;; Now `last-coding-system-used' has right value.
4810 ;; Remember it.
4811 (when (boundp 'last-coding-system-used)
4812 (setq coding-system-used
4813 (symbol-value 'last-coding-system-used))))
4815 (tramp-message
4816 v 4 "Inserting local temp file `%s'...done" local-copy)
4817 (when (boundp 'last-coding-system-used)
4818 (set 'last-coding-system-used coding-system-used))))
4820 ;; Save exit.
4821 (progn
4822 (when visit
4823 (setq buffer-file-name filename)
4824 (setq buffer-read-only (not (file-writable-p filename)))
4825 (set-visited-file-modtime)
4826 (set-buffer-modified-p nil))
4827 (when (and (stringp local-copy)
4828 (or remote-copy (null tramp-temp-buffer-file-name)))
4829 (delete-file local-copy))
4830 (when (stringp remote-copy)
4831 (delete-file
4832 (tramp-make-tramp-file-name method user host remote-copy))))))
4834 ;; Result.
4835 (list (expand-file-name filename)
4836 (cadr result))))
4838 ;; This is needed for XEmacs only. Code stolen from files.el.
4839 (defun tramp-handle-insert-file-contents-literally
4840 (filename &optional visit beg end replace)
4841 "Like `insert-file-contents-literally' for Tramp files."
4842 (let ((format-alist nil)
4843 (after-insert-file-functions nil)
4844 (coding-system-for-read 'no-conversion)
4845 (coding-system-for-write 'no-conversion)
4846 (find-buffer-file-type-function
4847 (if (fboundp 'find-buffer-file-type)
4848 (symbol-function 'find-buffer-file-type)
4849 nil))
4850 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4851 (inhibit-file-name-operation 'insert-file-contents))
4852 (unwind-protect
4853 (progn
4854 (fset 'find-buffer-file-type (lambda (filename) t))
4855 (insert-file-contents filename visit beg end replace))
4856 ;; Save exit.
4857 (if find-buffer-file-type-function
4858 (fset 'find-buffer-file-type find-buffer-file-type-function)
4859 (fmakunbound 'find-buffer-file-type)))))
4861 (defun tramp-handle-find-backup-file-name (filename)
4862 "Like `find-backup-file-name' for Tramp files."
4863 (with-parsed-tramp-file-name filename nil
4864 ;; We set both variables. It doesn't matter whether it is
4865 ;; Emacs or XEmacs
4866 (let ((backup-directory-alist
4867 ;; Emacs case
4868 (when (boundp 'backup-directory-alist)
4869 (if (symbol-value 'tramp-backup-directory-alist)
4870 (mapcar
4871 (lambda (x)
4872 (cons
4873 (car x)
4874 (if (and (stringp (cdr x))
4875 (file-name-absolute-p (cdr x))
4876 (not (tramp-file-name-p (cdr x))))
4877 (tramp-make-tramp-file-name method user host (cdr x))
4878 (cdr x))))
4879 (symbol-value 'tramp-backup-directory-alist))
4880 (symbol-value 'backup-directory-alist))))
4882 (bkup-backup-directory-info
4883 ;; XEmacs case
4884 (when (boundp 'bkup-backup-directory-info)
4885 (if (symbol-value 'tramp-bkup-backup-directory-info)
4886 (mapcar
4887 (lambda (x)
4888 (nconc
4889 (list (car x))
4890 (list
4891 (if (and (stringp (car (cdr x)))
4892 (file-name-absolute-p (car (cdr x)))
4893 (not (tramp-file-name-p (car (cdr x)))))
4894 (tramp-make-tramp-file-name
4895 method user host (car (cdr x)))
4896 (car (cdr x))))
4897 (cdr (cdr x))))
4898 (symbol-value 'tramp-bkup-backup-directory-info))
4899 (symbol-value 'bkup-backup-directory-info)))))
4901 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
4903 (defun tramp-handle-make-auto-save-file-name ()
4904 "Like `make-auto-save-file-name' for Tramp files.
4905 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
4906 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4907 (buffer-file-name
4908 (tramp-subst-strs-in-string
4909 '(("_" . "|")
4910 ("/" . "_a")
4911 (":" . "_b")
4912 ("|" . "__")
4913 ("[" . "_l")
4914 ("]" . "_r"))
4915 (buffer-file-name))))
4916 ;; File name must be unique. This is ensured with Emacs 22 (see
4917 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4918 ;; all other cases we must do it ourselves.
4919 (when (boundp 'auto-save-file-name-transforms)
4920 (mapc
4921 (lambda (x)
4922 (when (and (string-match (car x) buffer-file-name)
4923 (not (car (cddr x))))
4924 (setq tramp-auto-save-directory
4925 (or tramp-auto-save-directory
4926 (tramp-compat-temporary-file-directory)))))
4927 (symbol-value 'auto-save-file-name-transforms)))
4928 ;; Create directory.
4929 (when tramp-auto-save-directory
4930 (setq buffer-file-name
4931 (expand-file-name buffer-file-name tramp-auto-save-directory))
4932 (unless (file-exists-p tramp-auto-save-directory)
4933 (make-directory tramp-auto-save-directory t)))
4934 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4935 ;; it is not a magic file name operation (since Emacs 22).
4936 ;; We must deactivate it temporarily.
4937 (if (not (ad-is-active 'make-auto-save-file-name))
4938 (tramp-run-real-handler 'make-auto-save-file-name nil)
4939 ;; else
4940 (ad-deactivate 'make-auto-save-file-name)
4941 (prog1
4942 (tramp-run-real-handler 'make-auto-save-file-name nil)
4943 (ad-activate 'make-auto-save-file-name)))))
4945 (defvar tramp-handle-write-region-hook nil
4946 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4948 ;; CCC grok LOCKNAME
4949 (defun tramp-handle-write-region
4950 (start end filename &optional append visit lockname confirm)
4951 "Like `write-region' for Tramp files."
4952 (setq filename (expand-file-name filename))
4953 (with-parsed-tramp-file-name filename nil
4954 ;; Following part commented out because we don't know what to do about
4955 ;; file locking, and it does not appear to be a problem to ignore it.
4956 ;; Ange-ftp ignores it, too.
4957 ;; (when (and lockname (stringp lockname))
4958 ;; (setq lockname (expand-file-name lockname)))
4959 ;; (unless (or (eq lockname nil)
4960 ;; (string= lockname filename))
4961 ;; (error
4962 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
4964 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
4965 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4966 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4967 (tramp-error v 'file-error "File not overwritten")))
4969 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
4970 (tramp-get-remote-uid v 'integer)))
4971 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
4972 (tramp-get-remote-gid v 'integer))))
4974 (if (and (tramp-local-host-p v)
4975 ;; `file-writable-p' calls `file-expand-file-name'. We
4976 ;; cannot use `tramp-run-real-handler' therefore.
4977 (let (file-name-handler-alist)
4978 (and
4979 (file-writable-p (file-name-directory localname))
4980 (or (file-directory-p localname)
4981 (file-writable-p localname)))))
4982 ;; Short track: if we are on the local host, we can run directly.
4983 (tramp-run-real-handler
4984 'write-region
4985 (list start end localname append 'no-message lockname confirm))
4987 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4988 (loc-enc (tramp-get-local-coding v "local-encoding"))
4989 (modes (save-excursion (tramp-default-file-modes filename)))
4990 ;; We use this to save the value of
4991 ;; `last-coding-system-used' after writing the tmp file.
4992 ;; At the end of the function, we set
4993 ;; `last-coding-system-used' to this saved value. This
4994 ;; way, any intermediary coding systems used while
4995 ;; talking to the remote shell or suchlike won't hose
4996 ;; this variable. This approach was snarfed from
4997 ;; ange-ftp.el.
4998 coding-system-used
4999 ;; Write region into a tmp file. This isn't really
5000 ;; needed if we use an encoding function, but currently
5001 ;; we use it always because this makes the logic
5002 ;; simpler.
5003 (tmpfile (or tramp-temp-buffer-file-name
5004 (tramp-compat-make-temp-file filename))))
5006 ;; If `append' is non-nil, we copy the file locally, and let
5007 ;; the native `write-region' implementation do the job.
5008 (when append (copy-file filename tmpfile 'ok))
5010 ;; We say `no-message' here because we don't want the
5011 ;; visited file modtime data to be clobbered from the temp
5012 ;; file. We call `set-visited-file-modtime' ourselves later
5013 ;; on. We must ensure that `file-coding-system-alist'
5014 ;; matches `tmpfile'.
5015 (let ((file-coding-system-alist
5016 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5017 (condition-case err
5018 (tramp-run-real-handler
5019 'write-region
5020 (list start end tmpfile append 'no-message lockname confirm))
5021 ((error quit)
5022 (setq tramp-temp-buffer-file-name nil)
5023 (delete-file tmpfile)
5024 (signal (car err) (cdr err))))
5026 ;; Now, `last-coding-system-used' has the right value. Remember it.
5027 (when (boundp 'last-coding-system-used)
5028 (setq coding-system-used
5029 (symbol-value 'last-coding-system-used))))
5031 ;; The permissions of the temporary file should be set. If
5032 ;; filename does not exist (eq modes nil) it has been
5033 ;; renamed to the backup file. This case `save-buffer'
5034 ;; handles permissions.
5035 ;; Ensure, that it is still readable.
5036 (when modes
5037 (set-file-modes
5038 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
5040 ;; This is a bit lengthy due to the different methods
5041 ;; possible for file transfer. First, we check whether the
5042 ;; method uses an rcp program. If so, we call it.
5043 ;; Otherwise, both encoding and decoding command must be
5044 ;; specified. However, if the method _also_ specifies an
5045 ;; encoding function, then that is used for encoding the
5046 ;; contents of the tmp file.
5047 (cond
5048 ;; `copy-file' handles direct copy and out-of-band methods.
5049 ((or (tramp-local-host-p v)
5050 (tramp-method-out-of-band-p
5051 v (nth 7 (file-attributes tmpfile))))
5052 (if (and (not (stringp start))
5053 (= (or end (point-max)) (point-max))
5054 (= (or start (point-min)) (point-min))
5055 (tramp-get-method-parameter
5056 method 'tramp-copy-keep-tmpfile))
5057 (progn
5058 (setq tramp-temp-buffer-file-name tmpfile)
5059 (condition-case err
5060 ;; We keep the local file for performance
5061 ;; reasons, useful for "rsync".
5062 (copy-file tmpfile filename t)
5063 ((error quit)
5064 (setq tramp-temp-buffer-file-name nil)
5065 (delete-file tmpfile)
5066 (signal (car err) (cdr err)))))
5067 (setq tramp-temp-buffer-file-name nil)
5068 ;; Don't rename, in order to keep context in SELinux.
5069 (unwind-protect
5070 (copy-file tmpfile filename t)
5071 (delete-file tmpfile))))
5073 ;; Use inline file transfer.
5074 (rem-dec
5075 ;; Encode tmpfile.
5076 (tramp-message v 5 "Encoding region...")
5077 (unwind-protect
5078 (with-temp-buffer
5079 ;; Use encoding function or command.
5080 (if (and (symbolp loc-enc) (fboundp loc-enc))
5081 (progn
5082 (tramp-message
5083 v 5 "Encoding region using function `%s'..."
5084 (symbol-name loc-enc))
5085 (let ((coding-system-for-read 'binary))
5086 (insert-file-contents-literally tmpfile))
5087 ;; The following `let' is a workaround for the
5088 ;; base64.el that comes with pgnus-0.84. If
5089 ;; both of the following conditions are
5090 ;; satisfied, it tries to write to a local
5091 ;; file in default-directory, but at this
5092 ;; point, default-directory is remote.
5093 ;; (`call-process-region' can't write to
5094 ;; remote files, it seems.) The file in
5095 ;; question is a tmp file anyway.
5096 (let ((default-directory
5097 (tramp-compat-temporary-file-directory)))
5098 (funcall loc-enc (point-min) (point-max))))
5100 (tramp-message
5101 v 5 "Encoding region using command `%s'..." loc-enc)
5102 (unless (equal 0 (tramp-call-local-coding-command
5103 loc-enc tmpfile t))
5104 (tramp-error
5105 v 'file-error
5106 "Cannot write to `%s', local encoding command `%s' failed"
5107 filename loc-enc)))
5109 ;; Send buffer into remote decoding command which
5110 ;; writes to remote file. Because this happens on
5111 ;; the remote host, we cannot use the function.
5112 (goto-char (point-max))
5113 (unless (bolp) (newline))
5114 (tramp-message
5115 v 5 "Decoding region into remote file %s..." filename)
5116 (tramp-send-command
5118 (format
5119 "%s >%s <<'EOF'\n%sEOF"
5120 rem-dec
5121 (tramp-shell-quote-argument localname)
5122 (buffer-string)))
5123 (tramp-barf-unless-okay
5124 v nil
5125 "Couldn't write region to `%s', decode using `%s' failed"
5126 filename rem-dec)
5127 ;; When `file-precious-flag' is set, the region is
5128 ;; written to a temporary file. Check that the
5129 ;; checksum is equal to that from the local tmpfile.
5130 (when file-precious-flag
5131 (erase-buffer)
5132 (and
5133 ;; cksum runs locally, if possible.
5134 (zerop (tramp-local-call-process "cksum" tmpfile t))
5135 ;; cksum runs remotely.
5136 (zerop
5137 (tramp-send-command-and-check
5139 (format
5140 "cksum <%s" (tramp-shell-quote-argument localname))))
5141 ;; ... they are different.
5142 (not
5143 (string-equal
5144 (buffer-string)
5145 (with-current-buffer (tramp-get-buffer v)
5146 (buffer-string))))
5147 (tramp-error
5148 v 'file-error
5149 (concat "Couldn't write region to `%s',"
5150 " decode using `%s' failed")
5151 filename rem-dec)))
5152 (tramp-message
5153 v 5 "Decoding region into remote file %s...done" filename))
5155 ;; Save exit.
5156 (delete-file tmpfile)))
5158 ;; That's not expected.
5160 (tramp-error
5161 v 'file-error
5162 (concat "Method `%s' should specify both encoding and "
5163 "decoding command or an rcp program")
5164 method)))
5166 ;; Make `last-coding-system-used' have the right value.
5167 (when coding-system-used
5168 (set 'last-coding-system-used coding-system-used))))
5170 (tramp-flush-file-property v (file-name-directory localname))
5171 (tramp-flush-file-property v localname)
5173 ;; We must protect `last-coding-system-used', now we have set it
5174 ;; to its correct value.
5175 (let (last-coding-system-used (need-chown t))
5176 ;; Set file modification time.
5177 (when (or (eq visit t) (stringp visit))
5178 (let ((file-attr (file-attributes filename)))
5179 (set-visited-file-modtime
5180 ;; We must pass modtime explicitely, because filename can
5181 ;; be different from (buffer-file-name), f.e. if
5182 ;; `file-precious-flag' is set.
5183 (nth 5 file-attr))
5184 (when (and (eq (nth 2 file-attr) uid)
5185 (eq (nth 3 file-attr) gid))
5186 (setq need-chown nil))))
5188 ;; Set the ownership.
5189 (when need-chown
5190 (tramp-set-file-uid-gid filename uid gid))
5191 (when (or (eq visit t) (null visit) (stringp visit))
5192 (tramp-message v 0 "Wrote %s" filename))
5193 (run-hooks 'tramp-handle-write-region-hook)))))
5195 (defvar tramp-vc-registered-file-names nil
5196 "List used to collect file names, which are checked during `vc-registered'.")
5198 ;; VC backends check for the existence of various different special
5199 ;; files. This is very time consuming, because every single check
5200 ;; requires a remote command (the file cache must be invalidated).
5201 ;; Therefore, we apply a kind of optimization. We install the file
5202 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5203 ;; remembers all file names for which `file-exists-p' or
5204 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5205 ;; is performed. Afterwards, a script is applied for all collected
5206 ;; file names, using just one remote command. The result of this
5207 ;; script is used to fill the file cache with actual values. Now we
5208 ;; can reset the file name handlers, and we make a second run of
5209 ;; `vc-registered', which returns the expected result without sending
5210 ;; any other remote command.
5211 (defun tramp-handle-vc-registered (file)
5212 "Like `vc-registered' for Tramp files."
5213 (with-parsed-tramp-file-name file nil
5215 ;; There could be new files, created by the vc backend. We cannot
5216 ;; reuse the old cache entries, therefore.
5217 (let (tramp-vc-registered-file-names
5218 (tramp-cache-inhibit-cache (current-time))
5219 (file-name-handler-alist
5220 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5222 ;; Here we collect only file names, which need an operation.
5223 (tramp-run-real-handler 'vc-registered (list file))
5224 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5226 ;; Send just one command, in order to fill the cache.
5227 (when tramp-vc-registered-file-names
5228 (tramp-maybe-send-script
5230 (format tramp-vc-registered-read-file-names
5231 (tramp-get-file-exists-command v)
5232 (format "%s -r" (tramp-get-test-command v)))
5233 "tramp_vc_registered_read_file_names")
5235 (dolist
5236 (elt
5237 (tramp-send-command-and-read
5239 (format
5240 "tramp_vc_registered_read_file_names %s"
5241 (mapconcat 'tramp-shell-quote-argument
5242 tramp-vc-registered-file-names
5243 " "))))
5245 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
5247 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
5248 ;; shall be answered from the file cache.
5249 ;; We unset `process-file-side-effects' in order to keep the cache
5250 ;; when `process-file' calls appear.
5251 (let (process-file-side-effects)
5252 (tramp-run-real-handler 'vc-registered (list file)))))
5254 ;;;###autoload
5255 (progn (defun tramp-run-real-handler (operation args)
5256 "Invoke normal file name handler for OPERATION.
5257 First arg specifies the OPERATION, second arg is a list of arguments to
5258 pass to the OPERATION."
5259 (let* ((inhibit-file-name-handlers
5260 `(tramp-file-name-handler
5261 tramp-vc-file-name-handler
5262 tramp-completion-file-name-handler
5263 cygwin-mount-name-hook-function
5264 cygwin-mount-map-drive-hook-function
5266 ,(and (eq inhibit-file-name-operation operation)
5267 inhibit-file-name-handlers)))
5268 (inhibit-file-name-operation operation))
5269 (apply operation args))))
5271 ;;;###autoload
5272 (progn (defun tramp-completion-run-real-handler (operation args)
5273 "Invoke `tramp-file-name-handler' for OPERATION.
5274 First arg specifies the OPERATION, second arg is a list of arguments to
5275 pass to the OPERATION."
5276 (let* ((inhibit-file-name-handlers
5277 `(tramp-completion-file-name-handler
5278 cygwin-mount-name-hook-function
5279 cygwin-mount-map-drive-hook-function
5281 ,(and (eq inhibit-file-name-operation operation)
5282 inhibit-file-name-handlers)))
5283 (inhibit-file-name-operation operation))
5284 (apply operation args))))
5286 ;; We handle here all file primitives. Most of them have the file
5287 ;; name as first parameter; nevertheless we check for them explicitly
5288 ;; in order to be signaled if a new primitive appears. This
5289 ;; scenario is needed because there isn't a way to decide by
5290 ;; syntactical means whether a foreign method must be called. It would
5291 ;; ease the life if `file-name-handler-alist' would support a decision
5292 ;; function as well but regexp only.
5293 (defun tramp-file-name-for-operation (operation &rest args)
5294 "Return file name related to OPERATION file primitive.
5295 ARGS are the arguments OPERATION has been called with."
5296 (cond
5297 ; FILE resp DIRECTORY
5298 ((member operation
5299 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5300 'delete-file 'diff-latest-backup-file 'directory-file-name
5301 'directory-files 'directory-files-and-attributes
5302 'dired-compress-file 'dired-uncache
5303 'file-accessible-directory-p 'file-attributes
5304 'file-directory-p 'file-executable-p 'file-exists-p
5305 'file-local-copy 'file-remote-p 'file-modes
5306 'file-name-as-directory 'file-name-directory
5307 'file-name-nondirectory 'file-name-sans-versions
5308 'file-ownership-preserved-p 'file-readable-p
5309 'file-regular-p 'file-symlink-p 'file-truename
5310 'file-writable-p 'find-backup-file-name 'find-file-noselect
5311 'get-file-buffer 'insert-directory 'insert-file-contents
5312 'load 'make-directory 'make-directory-internal
5313 'set-file-modes 'substitute-in-file-name
5314 'unhandled-file-name-directory 'vc-registered
5315 ; Emacs 22 only
5316 'set-file-times
5317 ; XEmacs only
5318 'abbreviate-file-name 'create-file-buffer
5319 'dired-file-modtime 'dired-make-compressed-filename
5320 'dired-recursive-delete-directory 'dired-set-file-modtime
5321 'dired-shell-unhandle-file-name 'dired-uucode-file
5322 'insert-file-contents-literally 'make-temp-name 'recover-file
5323 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5324 (if (file-name-absolute-p (nth 0 args))
5325 (nth 0 args)
5326 (expand-file-name (nth 0 args))))
5327 ; FILE DIRECTORY resp FILE1 FILE2
5328 ((member operation
5329 (list 'add-name-to-file 'copy-file 'expand-file-name
5330 'file-name-all-completions 'file-name-completion
5331 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5332 ; Emacs 23 only
5333 'copy-directory
5334 ; XEmacs only
5335 'dired-make-relative-symlink
5336 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5337 (save-match-data
5338 (cond
5339 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5340 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5341 (t (buffer-file-name (current-buffer))))))
5342 ; START END FILE
5343 ((eq operation 'write-region)
5344 (nth 2 args))
5345 ; BUF
5346 ((member operation
5347 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5348 ; since Emacs 22 only
5349 'make-auto-save-file-name
5350 ; XEmacs only
5351 'backup-buffer))
5352 (buffer-file-name
5353 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5354 ; COMMAND
5355 ((member operation
5356 (list ; not in Emacs 23
5357 'dired-call-process
5358 ; Emacs only
5359 'shell-command
5360 ; since Emacs 22 only
5361 'process-file
5362 ; since Emacs 23 only
5363 'start-file-process
5364 ; XEmacs only
5365 'dired-print-file 'dired-shell-call-process
5366 ; nowhere yet
5367 'executable-find 'start-process 'call-process))
5368 default-directory)
5369 ; unknown file primitive
5370 (t (error "unknown file I/O primitive: %s" operation))))
5372 (defun tramp-find-foreign-file-name-handler (filename)
5373 "Return foreign file name handler if exists."
5374 (when (and (stringp filename) (tramp-tramp-file-p filename))
5375 (let ((v (tramp-dissect-file-name filename t))
5376 (handler tramp-foreign-file-name-handler-alist)
5377 elt res)
5378 ;; When we are not fully sure that filename completion is safe,
5379 ;; we should not return a handler.
5380 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5381 (and (tramp-file-name-host v)
5382 (not (member (tramp-file-name-host v)
5383 (mapcar 'car tramp-methods))))
5384 (not (tramp-completion-mode-p)))
5385 (while handler
5386 (setq elt (car handler)
5387 handler (cdr handler))
5388 (when (funcall (car elt) filename)
5389 (setq handler nil
5390 res (cdr elt))))
5391 res))))
5393 ;; Main function.
5394 ;;;###autoload
5395 (defun tramp-file-name-handler (operation &rest args)
5396 "Invoke Tramp file name handler.
5397 Falls back to normal file name handler if no Tramp file name handler exists."
5398 (if tramp-mode
5399 (save-match-data
5400 (let* ((filename
5401 (tramp-replace-environment-variables
5402 (apply 'tramp-file-name-for-operation operation args)))
5403 (completion (tramp-completion-mode-p))
5404 (foreign (tramp-find-foreign-file-name-handler filename)))
5405 (with-parsed-tramp-file-name filename nil
5406 (cond
5407 ;; When we are in completion mode, some operations
5408 ;; shouldn't be handled by backend.
5409 ((and completion (zerop (length localname))
5410 (memq operation '(file-exists-p file-directory-p)))
5412 ((and completion (zerop (length localname))
5413 (memq operation '(file-name-as-directory)))
5414 filename)
5415 ;; Call the backend function.
5416 (foreign (apply foreign operation args))
5417 ;; Nothing to do for us.
5418 (t (tramp-run-real-handler operation args))))))
5419 ;; When `tramp-mode' is not enabled, we don't do anything.
5420 (tramp-run-real-handler operation args)))
5422 ;; In Emacs, there is some concurrency due to timers. If a timer
5423 ;; interrupts Tramp and wishes to use the same connection buffer as
5424 ;; the "main" Emacs, then garbage might occur in the connection
5425 ;; buffer. Therefore, we need to make sure that a timer does not use
5426 ;; the same connection buffer as the "main" Emacs. We implement a
5427 ;; cheap global lock, instead of locking each connection buffer
5428 ;; separately. The global lock is based on two variables,
5429 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5430 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5431 ;; processing of a single file operation, so we need to allow
5432 ;; recursive calls. That's where the `tramp-locker' variable comes in
5433 ;; -- it is let-bound to t during the execution of the current
5434 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5435 ;; then we should just proceed because we have been called
5436 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5437 ;; interrupting the "main" Emacs, and then we signal an error.
5439 (defvar tramp-locked nil
5440 "If non-nil, then Tramp is currently busy.
5441 Together with `tramp-locker', this implements a locking mechanism
5442 preventing reentrant calls of Tramp.")
5444 (defvar tramp-locker nil
5445 "If non-nil, then a caller has locked Tramp.
5446 Together with `tramp-locked', this implements a locking mechanism
5447 preventing reentrant calls of Tramp.")
5449 (defun tramp-sh-file-name-handler (operation &rest args)
5450 "Invoke remote-shell Tramp file name handler.
5451 Fall back to normal file name handler if no Tramp handler exists."
5452 (when (and tramp-locked (not tramp-locker))
5453 (setq tramp-locked nil)
5454 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5455 (let ((tl tramp-locked))
5456 (unwind-protect
5457 (progn
5458 (setq tramp-locked t)
5459 (let ((tramp-locker t))
5460 (save-match-data
5461 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5462 (if fn
5463 (apply (cdr fn) args)
5464 (tramp-run-real-handler operation args))))))
5465 (setq tramp-locked tl))))
5467 (defun tramp-vc-file-name-handler (operation &rest args)
5468 "Invoke special file name handler, which collects files to be handled."
5469 (save-match-data
5470 (let ((filename
5471 (tramp-replace-environment-variables
5472 (apply 'tramp-file-name-for-operation operation args)))
5473 (fn (assoc operation tramp-file-name-handler-alist)))
5474 (with-parsed-tramp-file-name filename nil
5475 (cond
5476 ;; That's what we want: file names, for which checks are
5477 ;; applied. We assume, that VC uses only `file-exists-p' and
5478 ;; `file-readable-p' checks; otherwise we must extend the
5479 ;; list. We do not perform any action, but return nil, in
5480 ;; order to keep `vc-registered' running.
5481 ((and fn (memq operation '(file-exists-p file-readable-p)))
5482 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5483 nil)
5484 ;; Tramp file name handlers like `expand-file-name'. They
5485 ;; must still work.
5487 (save-match-data (apply (cdr fn) args)))
5488 ;; Default file name handlers, we don't care.
5489 (t (tramp-run-real-handler operation args)))))))
5491 ;;;###autoload
5492 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5493 "Invoke Tramp file name completion handler.
5494 Falls back to normal file name handler if no Tramp file name handler exists."
5495 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5496 ;; would otherwise use backslash.
5497 (let ((directory-sep-char ?/)
5498 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5499 (if (and
5500 ;; When `tramp-mode' is not enabled, we don't do anything.
5501 fn tramp-mode
5502 ;; For other syntaxes than `sep', the regexp matches many common
5503 ;; situations where the user doesn't actually want to use Tramp.
5504 ;; So to avoid autoloading Tramp after typing just "/s", we
5505 ;; disable this part of the completion, unless the user implicitly
5506 ;; indicated his interest in using a fancier completion system.
5507 (or (eq tramp-syntax 'sep)
5508 (featurep 'tramp) ; If it's loaded, we may as well use it.
5509 (and (boundp 'partial-completion-mode) partial-completion-mode)
5510 ;; FIXME: These may have been loaded even if the user never
5511 ;; intended to use them.
5512 (featurep 'ido)
5513 (featurep 'icicles)))
5514 (save-match-data (apply (cdr fn) args))
5515 (tramp-completion-run-real-handler operation args)))))
5517 ;;;###autoload
5518 (progn (defun tramp-register-file-name-handlers ()
5519 "Add Tramp file name handlers to `file-name-handler-alist'."
5520 ;; Remove autoloaded handlers from file name handler alist. Useful,
5521 ;; if `tramp-syntax' has been changed.
5522 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5523 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5524 (let ((a1 (rassq
5525 'tramp-completion-file-name-handler file-name-handler-alist)))
5526 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5527 ;; Add the handlers.
5528 (add-to-list 'file-name-handler-alist
5529 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5530 (put 'tramp-file-name-handler 'safe-magic t)
5531 (add-to-list 'file-name-handler-alist
5532 (cons tramp-completion-file-name-regexp
5533 'tramp-completion-file-name-handler))
5534 (put 'tramp-completion-file-name-handler 'safe-magic t)
5535 ;; If jka-compr or epa-file are already loaded, move them to the
5536 ;; front of `file-name-handler-alist'.
5537 (dolist (fnh '(epa-file-handler jka-compr-handler))
5538 (let ((entry (rassoc fnh file-name-handler-alist)))
5539 (when entry
5540 (setq file-name-handler-alist
5541 (cons entry (delete entry file-name-handler-alist))))))))
5543 ;; `tramp-file-name-handler' must be registered before evaluation of
5544 ;; site-start and init files, because there might exist remote files
5545 ;; already, f.e. files kept via recentf-mode.
5546 ;;;###autoload(tramp-register-file-name-handlers)
5547 (tramp-register-file-name-handlers)
5549 ;;;###autoload
5550 (defun tramp-unload-file-name-handlers ()
5551 (setq file-name-handler-alist
5552 (delete (rassoc 'tramp-file-name-handler
5553 file-name-handler-alist)
5554 (delete (rassoc 'tramp-completion-file-name-handler
5555 file-name-handler-alist)
5556 file-name-handler-alist))))
5558 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5560 ;;; File name handler functions for completion mode:
5562 (defvar tramp-completion-mode nil
5563 "If non-nil, external packages signal that they are in file name completion.
5565 This is necessary, because Tramp uses a heuristic depending on last
5566 input event. This fails when external packages use other characters
5567 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5568 should never be set globally, the intention is to let-bind it.")
5570 ;; Necessary because `tramp-file-name-regexp-unified' and
5571 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5572 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5573 ;; to `tramp-file-name-handler'). Otherwise, it takes
5574 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5575 ;; risky, because completing a file might require loading other files,
5576 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5577 ;; variable. On the other hand, those files shouldn't have partial
5578 ;; Tramp file name syntax. Maybe another variable should be introduced
5579 ;; overwriting this check in such cases. Or we change Tramp file name
5580 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5581 (defun tramp-completion-mode-p ()
5582 "Checks whether method / user name / host name completion is active."
5584 ;; Signal from outside.
5585 tramp-completion-mode
5586 ;; Emacs.
5587 (equal last-input-event 'tab)
5588 (and (natnump last-input-event)
5590 ;; ?\t has event-modifier 'control.
5591 (equal last-input-event ?\t)
5592 (and (not (event-modifiers last-input-event))
5593 (or (equal last-input-event ?\?)
5594 (equal last-input-event ?\ )))))
5595 ;; XEmacs.
5596 (and (featurep 'xemacs)
5597 ;; `last-input-event' might be nil.
5598 (not (null last-input-event))
5599 ;; `last-input-event' may have no character approximation.
5600 (funcall (symbol-function 'event-to-character) last-input-event)
5602 ;; ?\t has event-modifier 'control.
5603 (equal
5604 (funcall (symbol-function 'event-to-character)
5605 last-input-event) ?\t)
5606 (and (not (event-modifiers last-input-event))
5607 (or (equal
5608 (funcall (symbol-function 'event-to-character)
5609 last-input-event) ?\?)
5610 (equal
5611 (funcall (symbol-function 'event-to-character)
5612 last-input-event) ?\ )))))))
5614 ;; Method, host name and user name completion.
5615 ;; `tramp-completion-dissect-file-name' returns a list of
5616 ;; tramp-file-name structures. For all of them we return possible completions.
5617 ;;;###autoload
5618 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5619 "Like `file-name-all-completions' for partial Tramp files."
5621 (let* ((fullname (tramp-drop-volume-letter
5622 (expand-file-name filename directory)))
5623 ;; Possible completion structures.
5624 (v (tramp-completion-dissect-file-name fullname))
5625 result result1)
5627 (while v
5628 (let* ((car (car v))
5629 (method (tramp-file-name-method car))
5630 (user (tramp-file-name-user car))
5631 (host (tramp-file-name-host car))
5632 (localname (tramp-file-name-localname car))
5633 (m (tramp-find-method method user host))
5634 (tramp-current-user user) ; see `tramp-parse-passwd'
5635 all-user-hosts)
5637 (unless localname ;; Nothing to complete.
5639 (if (or user host)
5641 ;; Method dependent user / host combinations.
5642 (progn
5643 (mapc
5644 (lambda (x)
5645 (setq all-user-hosts
5646 (append all-user-hosts
5647 (funcall (nth 0 x) (nth 1 x)))))
5648 (tramp-get-completion-function m))
5650 (setq result
5651 (append result
5652 (mapcar
5653 (lambda (x)
5654 (tramp-get-completion-user-host
5655 method user host (nth 0 x) (nth 1 x)))
5656 (delq nil all-user-hosts)))))
5658 ;; Possible methods.
5659 (setq result
5660 (append result (tramp-get-completion-methods m)))))
5662 (setq v (cdr v))))
5664 ;; Unify list, remove nil elements.
5665 (while result
5666 (let ((car (car result)))
5667 (when car
5668 (add-to-list
5669 'result1
5670 (substring car (length (tramp-drop-volume-letter directory)))))
5671 (setq result (cdr result))))
5673 ;; Complete local parts.
5674 (append
5675 result1
5676 (condition-case nil
5677 (tramp-completion-run-real-handler
5678 'file-name-all-completions (list filename directory))
5679 (error nil)))))
5681 ;; Method, host name and user name completion for a file.
5682 ;;;###autoload
5683 (defun tramp-completion-handle-file-name-completion
5684 (filename directory &optional predicate)
5685 "Like `file-name-completion' for Tramp files."
5686 (try-completion
5687 filename
5688 (mapcar 'list (file-name-all-completions filename directory))
5689 (when predicate
5690 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5692 ;; I misuse a little bit the tramp-file-name structure in order to handle
5693 ;; completion possibilities for partial methods / user names / host names.
5694 ;; Return value is a list of tramp-file-name structures according to possible
5695 ;; completions. If "localname" is non-nil it means there
5696 ;; shouldn't be a completion anymore.
5698 ;; Expected results:
5700 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5701 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5702 ;; [nil "x" nil nil]
5703 ;; ["x" nil nil nil]
5705 ;; "/x:" "/x:y" "/x:y:"
5706 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5707 ;; "/[x/" "/[x/y"
5708 ;; ["x" nil "" nil] ["x" nil "y" nil]
5709 ;; ["x" "" nil nil] ["x" "y" nil nil]
5711 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5712 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5713 ;; "/[x/y@" "/[x/y@z"
5714 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5715 (defun tramp-completion-dissect-file-name (name)
5716 "Returns a list of `tramp-file-name' structures.
5717 They are collected by `tramp-completion-dissect-file-name1'."
5719 (let* ((result)
5720 (x-nil "\\|\\(\\)")
5721 (tramp-completion-ipv6-regexp
5722 (format
5723 "[^%s]*"
5724 (if (zerop (length tramp-postfix-ipv6-format))
5725 tramp-postfix-host-format
5726 tramp-postfix-ipv6-format)))
5727 ;; "/method" "/[method"
5728 (tramp-completion-file-name-structure1
5729 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5730 1 nil nil nil))
5731 ;; "/user" "/[user"
5732 (tramp-completion-file-name-structure2
5733 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5734 nil 1 nil nil))
5735 ;; "/host" "/[host"
5736 (tramp-completion-file-name-structure3
5737 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5738 nil nil 1 nil))
5739 ;; "/[ipv6" "/[ipv6"
5740 (tramp-completion-file-name-structure4
5741 (list (concat tramp-prefix-regexp
5742 tramp-prefix-ipv6-regexp
5743 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5744 nil nil 1 nil))
5745 ;; "/user@host" "/[user@host"
5746 (tramp-completion-file-name-structure5
5747 (list (concat tramp-prefix-regexp
5748 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5749 "\\(" tramp-host-regexp x-nil "\\)$")
5750 nil 1 2 nil))
5751 ;; "/user@[ipv6" "/[user@ipv6"
5752 (tramp-completion-file-name-structure6
5753 (list (concat tramp-prefix-regexp
5754 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5755 tramp-prefix-ipv6-regexp
5756 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5757 nil 1 2 nil))
5758 ;; "/method:user" "/[method/user" "/method://user"
5759 (tramp-completion-file-name-structure7
5760 (list (concat tramp-prefix-regexp
5761 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5762 "\\(" tramp-user-regexp x-nil "\\)$")
5763 1 2 nil nil))
5764 ;; "/method:host" "/[method/host" "/method://host"
5765 (tramp-completion-file-name-structure8
5766 (list (concat tramp-prefix-regexp
5767 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5768 "\\(" tramp-host-regexp x-nil "\\)$")
5769 1 nil 2 nil))
5770 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5771 (tramp-completion-file-name-structure9
5772 (list (concat tramp-prefix-regexp
5773 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5774 tramp-prefix-ipv6-regexp
5775 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5776 1 nil 2 nil))
5777 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5778 (tramp-completion-file-name-structure10
5779 (list (concat tramp-prefix-regexp
5780 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5781 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5782 "\\(" tramp-host-regexp x-nil "\\)$")
5783 1 2 3 nil))
5784 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5785 (tramp-completion-file-name-structure11
5786 (list (concat tramp-prefix-regexp
5787 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5788 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5789 tramp-prefix-ipv6-regexp
5790 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5791 1 2 3 nil))
5792 ;; "/method: "/method:/"
5793 (tramp-completion-file-name-structure12
5794 (list
5795 (if (equal tramp-syntax 'url)
5796 (concat tramp-prefix-regexp
5797 "\\(" tramp-method-regexp "\\)"
5798 "\\(" (substring tramp-postfix-method-regexp 0 1)
5799 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5800 "\\(" "\\)$")
5801 ;; Should not match if not URL syntax.
5802 (concat tramp-prefix-regexp "/$"))
5803 1 3 nil nil))
5804 ;; "/method: "/method:/"
5805 (tramp-completion-file-name-structure13
5806 (list
5807 (if (equal tramp-syntax 'url)
5808 (concat tramp-prefix-regexp
5809 "\\(" tramp-method-regexp "\\)"
5810 "\\(" (substring tramp-postfix-method-regexp 0 1)
5811 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5812 "\\(" "\\)$")
5813 ;; Should not match if not URL syntax.
5814 (concat tramp-prefix-regexp "/$"))
5815 1 nil 3 nil)))
5817 (mapc (lambda (regexp)
5818 (add-to-list 'result
5819 (tramp-completion-dissect-file-name1 regexp name)))
5820 (list
5821 tramp-completion-file-name-structure1
5822 tramp-completion-file-name-structure2
5823 tramp-completion-file-name-structure3
5824 tramp-completion-file-name-structure4
5825 tramp-completion-file-name-structure5
5826 tramp-completion-file-name-structure6
5827 tramp-completion-file-name-structure7
5828 tramp-completion-file-name-structure8
5829 tramp-completion-file-name-structure9
5830 tramp-completion-file-name-structure10
5831 tramp-completion-file-name-structure11
5832 tramp-completion-file-name-structure12
5833 tramp-completion-file-name-structure13
5834 tramp-file-name-structure))
5836 (delq nil result)))
5838 (defun tramp-completion-dissect-file-name1 (structure name)
5839 "Returns a `tramp-file-name' structure matching STRUCTURE.
5840 The structure consists of remote method, remote user,
5841 remote host and localname (filename on remote host)."
5843 (save-match-data
5844 (when (string-match (nth 0 structure) name)
5845 (let ((method (and (nth 1 structure)
5846 (match-string (nth 1 structure) name)))
5847 (user (and (nth 2 structure)
5848 (match-string (nth 2 structure) name)))
5849 (host (and (nth 3 structure)
5850 (match-string (nth 3 structure) name)))
5851 (localname (and (nth 4 structure)
5852 (match-string (nth 4 structure) name))))
5853 (vector method user host localname)))))
5855 ;; This function returns all possible method completions, adding the
5856 ;; trailing method delimeter.
5857 (defun tramp-get-completion-methods (partial-method)
5858 "Returns all method completions for PARTIAL-METHOD."
5859 (mapcar
5860 (lambda (method)
5861 (and method
5862 (string-match (concat "^" (regexp-quote partial-method)) method)
5863 (tramp-completion-make-tramp-file-name method nil nil nil)))
5864 (mapcar 'car tramp-methods)))
5866 ;; Compares partial user and host names with possible completions.
5867 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
5868 "Returns the most expanded string for user and host name completion.
5869 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5870 (cond
5872 ((and partial-user partial-host)
5873 (if (and host
5874 (string-match (concat "^" (regexp-quote partial-host)) host)
5875 (string-equal partial-user (or user partial-user)))
5876 (setq user partial-user)
5877 (setq user nil
5878 host nil)))
5880 (partial-user
5881 (setq host nil)
5882 (unless
5883 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5884 (setq user nil)))
5886 (partial-host
5887 (setq user nil)
5888 (unless
5889 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5890 (setq host nil)))
5892 (t (setq user nil
5893 host nil)))
5895 (unless (zerop (+ (length user) (length host)))
5896 (tramp-completion-make-tramp-file-name method user host nil)))
5898 (defun tramp-parse-rhosts (filename)
5899 "Return a list of (user host) tuples allowed to access.
5900 Either user or host may be nil."
5901 ;; On Windows, there are problems in completion when
5902 ;; `default-directory' is remote.
5903 (let ((default-directory (tramp-compat-temporary-file-directory))
5904 res)
5905 (when (file-readable-p filename)
5906 (with-temp-buffer
5907 (insert-file-contents filename)
5908 (goto-char (point-min))
5909 (while (not (eobp))
5910 (push (tramp-parse-rhosts-group) res))))
5911 res))
5913 (defun tramp-parse-rhosts-group ()
5914 "Return a (user host) tuple allowed to access.
5915 Either user or host may be nil."
5916 (let ((result)
5917 (regexp
5918 (concat
5919 "^\\(" tramp-host-regexp "\\)"
5920 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5921 (narrow-to-region (point) (tramp-compat-line-end-position))
5922 (when (re-search-forward regexp nil t)
5923 (setq result (append (list (match-string 3) (match-string 1)))))
5924 (widen)
5925 (forward-line 1)
5926 result))
5928 (defun tramp-parse-shosts (filename)
5929 "Return a list of (user host) tuples allowed to access.
5930 User is always nil."
5931 ;; On Windows, there are problems in completion when
5932 ;; `default-directory' is remote.
5933 (let ((default-directory (tramp-compat-temporary-file-directory))
5934 res)
5935 (when (file-readable-p filename)
5936 (with-temp-buffer
5937 (insert-file-contents filename)
5938 (goto-char (point-min))
5939 (while (not (eobp))
5940 (push (tramp-parse-shosts-group) res))))
5941 res))
5943 (defun tramp-parse-shosts-group ()
5944 "Return a (user host) tuple allowed to access.
5945 User is always nil."
5946 (let ((result)
5947 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
5948 (narrow-to-region (point) (tramp-compat-line-end-position))
5949 (when (re-search-forward regexp nil t)
5950 (setq result (list nil (match-string 1))))
5951 (widen)
5953 (> (skip-chars-forward ",") 0)
5954 (forward-line 1))
5955 result))
5957 (defun tramp-parse-sconfig (filename)
5958 "Return a list of (user host) tuples allowed to access.
5959 User is always nil."
5960 ;; On Windows, there are problems in completion when
5961 ;; `default-directory' is remote.
5962 (let ((default-directory (tramp-compat-temporary-file-directory))
5963 res)
5964 (when (file-readable-p filename)
5965 (with-temp-buffer
5966 (insert-file-contents filename)
5967 (goto-char (point-min))
5968 (while (not (eobp))
5969 (push (tramp-parse-sconfig-group) res))))
5970 res))
5972 (defun tramp-parse-sconfig-group ()
5973 "Return a (user host) tuple allowed to access.
5974 User is always nil."
5975 (let ((result)
5976 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
5977 (narrow-to-region (point) (tramp-compat-line-end-position))
5978 (when (re-search-forward regexp nil t)
5979 (setq result (list nil (match-string 1))))
5980 (widen)
5982 (> (skip-chars-forward ",") 0)
5983 (forward-line 1))
5984 result))
5986 (defun tramp-parse-shostkeys (dirname)
5987 "Return a list of (user host) tuples allowed to access.
5988 User is always nil."
5989 ;; On Windows, there are problems in completion when
5990 ;; `default-directory' is remote.
5991 (let* ((default-directory (tramp-compat-temporary-file-directory))
5992 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
5993 (files (when (file-directory-p dirname) (directory-files dirname)))
5994 result)
5995 (while files
5996 (when (string-match regexp (car files))
5997 (push (list nil (match-string 1 (car files))) result))
5998 (setq files (cdr files)))
5999 result))
6001 (defun tramp-parse-sknownhosts (dirname)
6002 "Return a list of (user host) tuples allowed to access.
6003 User is always nil."
6004 ;; On Windows, there are problems in completion when
6005 ;; `default-directory' is remote.
6006 (let* ((default-directory (tramp-compat-temporary-file-directory))
6007 (regexp (concat "^\\(" tramp-host-regexp
6008 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6009 (files (when (file-directory-p dirname) (directory-files dirname)))
6010 result)
6011 (while files
6012 (when (string-match regexp (car files))
6013 (push (list nil (match-string 1 (car files))) result))
6014 (setq files (cdr files)))
6015 result))
6017 (defun tramp-parse-hosts (filename)
6018 "Return a list of (user host) tuples allowed to access.
6019 User is always nil."
6020 ;; On Windows, there are problems in completion when
6021 ;; `default-directory' is remote.
6022 (let ((default-directory (tramp-compat-temporary-file-directory))
6023 res)
6024 (when (file-readable-p filename)
6025 (with-temp-buffer
6026 (insert-file-contents filename)
6027 (goto-char (point-min))
6028 (while (not (eobp))
6029 (push (tramp-parse-hosts-group) res))))
6030 res))
6032 (defun tramp-parse-hosts-group ()
6033 "Return a (user host) tuple allowed to access.
6034 User is always nil."
6035 (let ((result)
6036 (regexp
6037 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6038 (narrow-to-region (point) (tramp-compat-line-end-position))
6039 (when (re-search-forward regexp nil t)
6040 (setq result (list nil (match-string 1))))
6041 (widen)
6043 (> (skip-chars-forward " \t") 0)
6044 (forward-line 1))
6045 result))
6047 ;; For su-alike methods it would be desirable to return "root@localhost"
6048 ;; as default. Unfortunately, we have no information whether any user name
6049 ;; has been typed already. So we use `tramp-current-user' as indication,
6050 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6051 (defun tramp-parse-passwd (filename)
6052 "Return a list of (user host) tuples allowed to access.
6053 Host is always \"localhost\"."
6054 ;; On Windows, there are problems in completion when
6055 ;; `default-directory' is remote.
6056 (let ((default-directory (tramp-compat-temporary-file-directory))
6057 res)
6058 (if (zerop (length tramp-current-user))
6059 '(("root" nil))
6060 (when (file-readable-p filename)
6061 (with-temp-buffer
6062 (insert-file-contents filename)
6063 (goto-char (point-min))
6064 (while (not (eobp))
6065 (push (tramp-parse-passwd-group) res))))
6066 res)))
6068 (defun tramp-parse-passwd-group ()
6069 "Return a (user host) tuple allowed to access.
6070 Host is always \"localhost\"."
6071 (let ((result)
6072 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6073 (narrow-to-region (point) (tramp-compat-line-end-position))
6074 (when (re-search-forward regexp nil t)
6075 (setq result (list (match-string 1) "localhost")))
6076 (widen)
6077 (forward-line 1)
6078 result))
6080 (defun tramp-parse-netrc (filename)
6081 "Return a list of (user host) tuples allowed to access.
6082 User may be nil."
6083 ;; On Windows, there are problems in completion when
6084 ;; `default-directory' is remote.
6085 (let ((default-directory (tramp-compat-temporary-file-directory))
6086 res)
6087 (when (file-readable-p filename)
6088 (with-temp-buffer
6089 (insert-file-contents filename)
6090 (goto-char (point-min))
6091 (while (not (eobp))
6092 (push (tramp-parse-netrc-group) res))))
6093 res))
6095 (defun tramp-parse-netrc-group ()
6096 "Return a (user host) tuple allowed to access.
6097 User may be nil."
6098 (let ((result)
6099 (regexp
6100 (concat
6101 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6102 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6103 (narrow-to-region (point) (tramp-compat-line-end-position))
6104 (when (re-search-forward regexp nil t)
6105 (setq result (list (match-string 3) (match-string 1))))
6106 (widen)
6107 (forward-line 1)
6108 result))
6110 (defun tramp-parse-putty (registry)
6111 "Return a list of (user host) tuples allowed to access.
6112 User is always nil."
6113 ;; On Windows, there are problems in completion when
6114 ;; `default-directory' is remote.
6115 (let ((default-directory (tramp-compat-temporary-file-directory))
6116 res)
6117 (with-temp-buffer
6118 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6119 (goto-char (point-min))
6120 (while (not (eobp))
6121 (push (tramp-parse-putty-group registry) res))))
6122 res))
6124 (defun tramp-parse-putty-group (registry)
6125 "Return a (user host) tuple allowed to access.
6126 User is always nil."
6127 (let ((result)
6128 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6129 (narrow-to-region (point) (tramp-compat-line-end-position))
6130 (when (re-search-forward regexp nil t)
6131 (setq result (list nil (match-string 1))))
6132 (widen)
6133 (forward-line 1)
6134 result))
6136 ;;; Internal Functions:
6138 (defun tramp-maybe-send-script (vec script name)
6139 "Define in remote shell function NAME implemented as SCRIPT.
6140 Only send the definition if it has not already been done."
6141 (let* ((p (tramp-get-connection-process vec))
6142 (scripts (tramp-get-connection-property p "scripts" nil)))
6143 (unless (member name scripts)
6144 (tramp-message vec 5 "Sending script `%s'..." name)
6145 ;; The script could contain a call of Perl. This is masked with `%s'.
6146 (tramp-send-command-and-check
6148 (format "%s () {\n%s\n}" name
6149 (format script (tramp-get-remote-perl vec))))
6150 (tramp-set-connection-property p "scripts" (cons name scripts))
6151 (tramp-message vec 5 "Sending script `%s'...done." name))))
6153 (defun tramp-set-auto-save ()
6154 (when (and ;; ange-ftp has its own auto-save mechanism
6155 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6156 'tramp-sh-file-name-handler)
6157 auto-save-default)
6158 (auto-save-mode 1)))
6159 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6160 (add-hook 'tramp-unload-hook
6161 (lambda ()
6162 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6164 (defun tramp-run-test (switch filename)
6165 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6166 Returns the exit code of the `test' program."
6167 (with-parsed-tramp-file-name filename nil
6168 (tramp-send-command-and-check
6170 (format
6171 "%s %s %s"
6172 (tramp-get-test-command v)
6173 switch
6174 (tramp-shell-quote-argument localname)))))
6176 (defun tramp-run-test2 (format-string file1 file2)
6177 "Run `test'-like program on the remote system, given FILE1, FILE2.
6178 FORMAT-STRING contains the program name, switches, and place holders.
6179 Returns the exit code of the `test' program. Barfs if the methods,
6180 hosts, or files, disagree."
6181 (unless (tramp-equal-remote file1 file2)
6182 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6183 (tramp-error
6184 v 'file-error
6185 "tramp-run-test2 only implemented for same method, user, host")))
6186 (with-parsed-tramp-file-name file1 v1
6187 (with-parsed-tramp-file-name file1 v2
6188 (tramp-send-command-and-check
6190 (format format-string
6191 (tramp-shell-quote-argument v1-localname)
6192 (tramp-shell-quote-argument v2-localname))))))
6194 (defun tramp-buffer-name (vec)
6195 "A name for the connection buffer VEC."
6196 ;; We must use `tramp-file-name-real-host', because for gateway
6197 ;; methods the default port will be expanded later on, which would
6198 ;; tamper the name.
6199 (let ((method (tramp-file-name-method vec))
6200 (user (tramp-file-name-user vec))
6201 (host (tramp-file-name-real-host vec)))
6202 (if (not (zerop (length user)))
6203 (format "*tramp/%s %s@%s*" method user host)
6204 (format "*tramp/%s %s*" method host))))
6206 (defun tramp-delete-temp-file-function ()
6207 "Remove temporary files related to current buffer."
6208 (when (stringp tramp-temp-buffer-file-name)
6209 (condition-case nil
6210 (delete-file tramp-temp-buffer-file-name)
6211 (error nil))))
6213 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6214 (add-hook 'tramp-cache-unload-hook
6215 (lambda ()
6216 (remove-hook 'kill-buffer-hook
6217 'tramp-delete-temp-file-function)))
6219 (defun tramp-get-buffer (vec)
6220 "Get the connection buffer to be used for VEC."
6221 (or (get-buffer (tramp-buffer-name vec))
6222 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6223 (setq buffer-undo-list t)
6224 (setq default-directory
6225 (tramp-make-tramp-file-name
6226 (tramp-file-name-method vec)
6227 (tramp-file-name-user vec)
6228 (tramp-file-name-host vec)
6229 "/"))
6230 (current-buffer))))
6232 (defun tramp-get-connection-buffer (vec)
6233 "Get the connection buffer to be used for VEC.
6234 In case a second asynchronous communication has been started, it is different
6235 from `tramp-get-buffer'."
6236 (or (tramp-get-connection-property vec "process-buffer" nil)
6237 (tramp-get-buffer vec)))
6239 (defun tramp-get-connection-process (vec)
6240 "Get the connection process to be used for VEC.
6241 In case a second asynchronous communication has been started, it is different
6242 from the default one."
6243 (get-process
6244 (or (tramp-get-connection-property vec "process-name" nil)
6245 (tramp-buffer-name vec))))
6247 (defun tramp-debug-buffer-name (vec)
6248 "A name for the debug buffer for VEC."
6249 ;; We must use `tramp-file-name-real-host', because for gateway
6250 ;; methods the default port will be expanded later on, which would
6251 ;; tamper the name.
6252 (let ((method (tramp-file-name-method vec))
6253 (user (tramp-file-name-user vec))
6254 (host (tramp-file-name-real-host vec)))
6255 (if (not (zerop (length user)))
6256 (format "*debug tramp/%s %s@%s*" method user host)
6257 (format "*debug tramp/%s %s*" method host))))
6259 (defun tramp-get-debug-buffer (vec)
6260 "Get the debug buffer for VEC."
6261 (with-current-buffer
6262 (get-buffer-create (tramp-debug-buffer-name vec))
6263 (when (bobp)
6264 (setq buffer-undo-list t)
6265 ;; Activate outline-mode. This runs `text-mode-hook' and
6266 ;; `outline-mode-hook'. We must prevent that local processes
6267 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
6268 ;; ...
6269 (let ((default-directory (tramp-compat-temporary-file-directory)))
6270 (outline-mode))
6271 (set (make-local-variable 'outline-regexp)
6272 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6273 ; (set (make-local-variable 'outline-regexp)
6274 ; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
6275 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6276 (current-buffer)))
6278 (defun tramp-outline-level ()
6279 "Return the depth to which a statement is nested in the outline.
6280 Point must be at the beginning of a header line.
6282 The outline level is equal to the verbosity of the Tramp message."
6283 (1+ (string-to-number (match-string 1))))
6285 (defun tramp-find-executable
6286 (vec progname dirlist &optional ignore-tilde ignore-path)
6287 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6288 First arg VEC specifies the connection, PROGNAME is the program
6289 to search for, and DIRLIST gives the list of directories to
6290 search. If IGNORE-TILDE is non-nil, directory names starting
6291 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6292 only in DIRLIST.
6294 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6296 This function expects to be in the right *tramp* buffer."
6297 (with-current-buffer (tramp-get-connection-buffer vec)
6298 (let (result)
6299 ;; Check whether the executable is in $PATH. "which(1)" does not
6300 ;; report always a correct error code; therefore we check the
6301 ;; number of words it returns.
6302 (unless ignore-path
6303 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6304 (goto-char (point-min))
6305 (if (looking-at "^\\s-*1$")
6306 (setq result (concat "\\" progname))))
6307 (unless result
6308 (when ignore-tilde
6309 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
6310 ;; `remove' is in CL, and we want to avoid CL dependencies.
6311 (let (newdl d)
6312 (while dirlist
6313 (setq d (car dirlist))
6314 (setq dirlist (cdr dirlist))
6315 (unless (char-equal ?~ (aref d 0))
6316 (setq newdl (cons d newdl))))
6317 (setq dirlist (nreverse newdl))))
6318 (tramp-send-command
6320 (format (concat "while read d; "
6321 "do if test -x $d/%s -a -f $d/%s; "
6322 "then echo tramp_executable $d/%s; "
6323 "break; fi; done <<'EOF'\n"
6324 "%s\nEOF")
6325 progname progname progname (mapconcat 'identity dirlist "\n")))
6326 (goto-char (point-max))
6327 (when (search-backward "tramp_executable " nil t)
6328 (skip-chars-forward "^ ")
6329 (skip-chars-forward " ")
6330 (setq result (buffer-substring
6331 (point) (tramp-compat-line-end-position)))))
6332 result)))
6334 (defun tramp-set-remote-path (vec)
6335 "Sets the remote environment PATH to existing directories.
6336 I.e., for each directory in `tramp-remote-path', it is tested
6337 whether it exists and if so, it is added to the environment
6338 variable PATH."
6339 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6340 (tramp-send-command
6341 vec (format "PATH=%s; export PATH"
6342 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6344 ;; ------------------------------------------------------------
6345 ;; -- Communication with external shell --
6346 ;; ------------------------------------------------------------
6348 (defun tramp-find-file-exists-command (vec)
6349 "Find a command on the remote host for checking if a file exists.
6350 Here, we are looking for a command which has zero exit status if the
6351 file exists and nonzero exit status otherwise."
6352 (let ((existing "/")
6353 (nonexisting
6354 (tramp-shell-quote-argument "/ this file does not exist "))
6355 result)
6356 ;; The algorithm is as follows: we try a list of several commands.
6357 ;; For each command, we first run `$cmd /' -- this should return
6358 ;; true, as the root directory always exists. And then we run
6359 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6360 ;; does not exist. This should return false. We use the first
6361 ;; command we find that seems to work.
6362 ;; The list of commands to try is as follows:
6363 ;; `ls -d' This works on most systems, but NetBSD 1.4
6364 ;; has a bug: `ls' always returns zero exit
6365 ;; status, even for files which don't exist.
6366 ;; `test -e' Some Bourne shells have a `test' builtin
6367 ;; which does not know the `-e' option.
6368 ;; `/bin/test -e' For those, the `test' binary on disk normally
6369 ;; provides the option. Alas, the binary
6370 ;; is sometimes `/bin/test' and sometimes it's
6371 ;; `/usr/bin/test'.
6372 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6373 (unless (or
6374 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6375 (zerop (tramp-send-command-and-check
6376 vec (format "%s %s" result existing)))
6377 (not (zerop (tramp-send-command-and-check
6378 vec (format "%s %s" result nonexisting)))))
6379 (and (setq result "/bin/test -e")
6380 (zerop (tramp-send-command-and-check
6381 vec (format "%s %s" result existing)))
6382 (not (zerop (tramp-send-command-and-check
6383 vec (format "%s %s" result nonexisting)))))
6384 (and (setq result "/usr/bin/test -e")
6385 (zerop (tramp-send-command-and-check
6386 vec (format "%s %s" result existing)))
6387 (not (zerop (tramp-send-command-and-check
6388 vec (format "%s %s" result nonexisting)))))
6389 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6390 (zerop (tramp-send-command-and-check
6391 vec (format "%s %s" result existing)))
6392 (not (zerop (tramp-send-command-and-check
6393 vec (format "%s %s" result nonexisting))))))
6394 (tramp-error
6395 vec 'file-error "Couldn't find command to check if file exists"))
6396 result))
6398 ;; CCC test ksh or bash found for tilde expansion?
6399 (defun tramp-find-shell (vec)
6400 "Opens a shell on the remote host which groks tilde expansion."
6401 (unless (tramp-get-connection-property vec "remote-shell" nil)
6402 (let (shell)
6403 (with-current-buffer (tramp-get-buffer vec)
6404 (tramp-send-command vec "echo ~root" t)
6405 (cond
6406 ((or (string-match "^~root$" (buffer-string))
6407 ;; The default shell (ksh93) of OpenSolaris is buggy.
6408 (string-equal (tramp-get-connection-property vec "uname" "")
6409 "SunOS 5.11"))
6410 (setq shell
6411 (or (tramp-find-executable
6412 vec "bash" (tramp-get-remote-path vec) t t)
6413 (tramp-find-executable
6414 vec "ksh" (tramp-get-remote-path vec) t t)))
6415 (unless shell
6416 (tramp-error
6417 vec 'file-error
6418 "Couldn't find a shell which groks tilde expansion"))
6419 ;; Find arguments for this shell.
6420 (let ((alist tramp-sh-extra-args)
6421 item extra-args)
6422 (while (and alist (null extra-args))
6423 (setq item (pop alist))
6424 (when (string-match (car item) shell)
6425 (setq extra-args (cdr item))))
6426 (when extra-args (setq shell (concat shell " " extra-args))))
6427 (tramp-message
6428 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
6429 (let ((tramp-end-of-output tramp-initial-end-of-output))
6430 (tramp-send-command
6432 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6433 (shell-quote-argument tramp-end-of-output) shell)
6435 ;; Setting prompts.
6436 (tramp-message vec 5 "Setting remote shell prompt...")
6437 (tramp-send-command
6438 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6439 (tramp-send-command vec "PS2=''" t)
6440 (tramp-send-command vec "PS3=''" t)
6441 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6442 (tramp-message vec 5 "Setting remote shell prompt...done"))
6444 (t (tramp-message
6445 vec 5 "Remote `%s' groks tilde expansion, good"
6446 (tramp-get-method-parameter
6447 (tramp-file-name-method vec) 'tramp-remote-sh))
6448 (tramp-set-connection-property
6449 vec "remote-shell"
6450 (tramp-get-method-parameter
6451 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
6453 ;; ------------------------------------------------------------
6454 ;; -- Functions for establishing connection --
6455 ;; ------------------------------------------------------------
6457 ;; The following functions are actions to be taken when seeing certain
6458 ;; prompts from the remote host. See the variable
6459 ;; `tramp-actions-before-shell' for usage of these functions.
6461 (defun tramp-action-login (proc vec)
6462 "Send the login name."
6463 (when (not (stringp tramp-current-user))
6464 (save-window-excursion
6465 (let ((enable-recursive-minibuffers t))
6466 (pop-to-buffer (tramp-get-connection-buffer vec))
6467 (setq tramp-current-user (read-string (match-string 0))))))
6468 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6469 (with-current-buffer (tramp-get-connection-buffer vec)
6470 (tramp-message vec 6 "\n%s" (buffer-string)))
6471 (tramp-send-string vec tramp-current-user))
6473 (defun tramp-action-password (proc vec)
6474 "Query the user for a password."
6475 (with-current-buffer (process-buffer proc)
6476 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6477 (tramp-message vec 3 "Sending %s" (match-string 1)))
6478 (tramp-enter-password proc))
6480 (defun tramp-action-succeed (proc vec)
6481 "Signal success in finding shell prompt."
6482 (throw 'tramp-action 'ok))
6484 (defun tramp-action-permission-denied (proc vec)
6485 "Signal permission denied."
6486 (kill-process proc)
6487 (throw 'tramp-action 'permission-denied))
6489 (defun tramp-action-yesno (proc vec)
6490 "Ask the user for confirmation using `yes-or-no-p'.
6491 Send \"yes\" to remote process on confirmation, abort otherwise.
6492 See also `tramp-action-yn'."
6493 (save-window-excursion
6494 (let ((enable-recursive-minibuffers t))
6495 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6496 (unless (yes-or-no-p (match-string 0))
6497 (kill-process proc)
6498 (throw 'tramp-action 'permission-denied))
6499 (with-current-buffer (tramp-get-connection-buffer vec)
6500 (tramp-message vec 6 "\n%s" (buffer-string)))
6501 (tramp-send-string vec "yes"))))
6503 (defun tramp-action-yn (proc vec)
6504 "Ask the user for confirmation using `y-or-n-p'.
6505 Send \"y\" to remote process on confirmation, abort otherwise.
6506 See also `tramp-action-yesno'."
6507 (save-window-excursion
6508 (let ((enable-recursive-minibuffers t))
6509 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6510 (unless (y-or-n-p (match-string 0))
6511 (kill-process proc)
6512 (throw 'tramp-action 'permission-denied))
6513 (with-current-buffer (tramp-get-connection-buffer vec)
6514 (tramp-message vec 6 "\n%s" (buffer-string)))
6515 (tramp-send-string vec "y"))))
6517 (defun tramp-action-terminal (proc vec)
6518 "Tell the remote host which terminal type to use.
6519 The terminal type can be configured with `tramp-terminal-type'."
6520 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6521 (with-current-buffer (tramp-get-connection-buffer vec)
6522 (tramp-message vec 6 "\n%s" (buffer-string)))
6523 (tramp-send-string vec tramp-terminal-type))
6525 (defun tramp-action-process-alive (proc vec)
6526 "Check whether a process has finished."
6527 (unless (memq (process-status proc) '(run open))
6528 (throw 'tramp-action 'process-died)))
6530 (defun tramp-action-out-of-band (proc vec)
6531 "Check whether an out-of-band copy has finished."
6532 (cond ((and (memq (process-status proc) '(stop exit))
6533 (zerop (process-exit-status proc)))
6534 (tramp-message vec 3 "Process has finished.")
6535 (throw 'tramp-action 'ok))
6536 ((or (and (memq (process-status proc) '(stop exit))
6537 (not (zerop (process-exit-status proc))))
6538 (memq (process-status proc) '(signal)))
6539 ;; `scp' could have copied correctly, but set modes could have failed.
6540 ;; This can be ignored.
6541 (with-current-buffer (process-buffer proc)
6542 (goto-char (point-min))
6543 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6544 (progn
6545 (tramp-message vec 5 "'set mode' error ignored.")
6546 (tramp-message vec 3 "Process has finished.")
6547 (throw 'tramp-action 'ok))
6548 (tramp-message vec 3 "Process has died.")
6549 (throw 'tramp-action 'process-died))))
6550 (t nil)))
6552 ;; Functions for processing the actions.
6554 (defun tramp-process-one-action (proc vec actions)
6555 "Wait for output from the shell and perform one action."
6556 (let (found todo item pattern action)
6557 (while (not found)
6558 ;; Reread output once all actions have been performed.
6559 ;; Obviously, the output was not complete.
6560 (tramp-accept-process-output proc 1)
6561 (setq todo actions)
6562 (while todo
6563 (setq item (pop todo))
6564 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6565 (setq action (nth 1 item))
6566 (tramp-message
6567 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6568 (when (tramp-check-for-regexp proc pattern)
6569 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6570 (setq found (funcall action proc vec)))))
6571 found))
6573 (defun tramp-process-actions (proc vec actions &optional timeout)
6574 "Perform actions until success or TIMEOUT."
6575 ;; Enable auth-source and password-cache.
6576 (tramp-set-connection-property vec "first-password-request" t)
6577 (let (exit)
6578 (while (not exit)
6579 (tramp-message proc 3 "Waiting for prompts from remote shell")
6580 (setq exit
6581 (catch 'tramp-action
6582 (if timeout
6583 (with-timeout (timeout)
6584 (tramp-process-one-action proc vec actions))
6585 (tramp-process-one-action proc vec actions)))))
6586 (with-current-buffer (tramp-get-connection-buffer vec)
6587 (tramp-message vec 6 "\n%s" (buffer-string)))
6588 (unless (eq exit 'ok)
6589 (tramp-clear-passwd vec)
6590 (tramp-error-with-buffer
6591 nil vec 'file-error
6592 (cond
6593 ((eq exit 'permission-denied) "Permission denied")
6594 ((eq exit 'process-died) "Process died")
6595 (t "Login failed"))))))
6597 ;; Utility functions.
6599 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6600 "Like `accept-process-output' for Tramp processes.
6601 This is needed in order to hide `last-coding-system-used', which is set
6602 for process communication also."
6603 (with-current-buffer (process-buffer proc)
6604 (tramp-message proc 10 "%s %s" proc (process-status proc))
6605 (let (buffer-read-only last-coding-system-used)
6606 ;; Under Windows XP, accept-process-output doesn't return
6607 ;; sometimes. So we add an additional timeout.
6608 (with-timeout ((or timeout 1))
6609 (accept-process-output proc timeout timeout-msecs)))
6610 (tramp-message proc 10 "\n%s" (buffer-string))))
6612 (defun tramp-check-for-regexp (proc regexp)
6613 "Check whether REGEXP is contained in process buffer of PROC.
6614 Erase echoed commands if exists."
6615 (with-current-buffer (process-buffer proc)
6616 (goto-char (point-min))
6618 ;; Check whether we need to remove echo output.
6619 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6620 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6621 (let ((begin (match-beginning 0)))
6622 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6623 ;; Discard echo from remote output.
6624 (tramp-set-connection-property proc "check-remote-echo" nil)
6625 (tramp-message proc 5 "echo-mark found")
6626 (forward-line)
6627 (delete-region begin (point))
6628 (goto-char (point-min)))))
6630 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6631 ;; Sometimes, the echo string is suppressed on the remote side.
6632 (not (string-equal
6633 (substring-no-properties
6634 tramp-echo-mark-marker
6635 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6636 (buffer-substring-no-properties
6637 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6638 ;; No echo to be handled, now we can look for the regexp.
6639 (goto-char (point-min))
6640 (re-search-forward regexp nil t))))
6642 (defun tramp-wait-for-regexp (proc timeout regexp)
6643 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6644 Expects the output of PROC to be sent to the current buffer. Returns
6645 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6646 nil."
6647 (with-current-buffer (process-buffer proc)
6648 (let ((found (tramp-check-for-regexp proc regexp))
6649 (start-time (current-time)))
6650 (cond (timeout
6651 ;; Work around a bug in XEmacs 21, where the timeout
6652 ;; expires faster than it should. This degenerates
6653 ;; to polling for buggy XEmacsen, but oh, well.
6654 (while (and (not found)
6655 (< (tramp-time-diff (current-time) start-time)
6656 timeout))
6657 (with-timeout (timeout)
6658 (while (not found)
6659 (tramp-accept-process-output proc 1)
6660 (unless (memq (process-status proc) '(run open))
6661 (tramp-error-with-buffer
6662 nil proc 'file-error "Process has died"))
6663 (setq found (tramp-check-for-regexp proc regexp))))))
6665 (while (not found)
6666 (tramp-accept-process-output proc 1)
6667 (unless (memq (process-status proc) '(run open))
6668 (tramp-error-with-buffer
6669 nil proc 'file-error "Process has died"))
6670 (setq found (tramp-check-for-regexp proc regexp)))))
6671 (tramp-message proc 6 "\n%s" (buffer-string))
6672 (when (not found)
6673 (if timeout
6674 (tramp-error
6675 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6676 regexp timeout)
6677 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6678 found)))
6680 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6681 "Wait for shell prompt and barf if none appears.
6682 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6683 seconds. If not, it produces an error message with the given ERROR-ARGS."
6684 (unless
6685 (tramp-wait-for-regexp
6686 proc timeout
6687 (format
6688 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6689 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6691 ;; We don't call `tramp-send-string' in order to hide the password
6692 ;; from the debug buffer, and because end-of-line handling of the
6693 ;; string.
6694 (defun tramp-enter-password (proc)
6695 "Prompt for a password and send it to the remote end."
6696 (process-send-string
6697 proc (concat (tramp-read-passwd proc)
6698 (or (tramp-get-method-parameter
6699 tramp-current-method
6700 'tramp-password-end-of-line)
6701 tramp-default-password-end-of-line))))
6703 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6704 "Set up an interactive shell.
6705 Mainly sets the prompt and the echo correctly. PROC is the shell
6706 process to set up. VEC specifies the connection."
6707 (let ((tramp-end-of-output tramp-initial-end-of-output))
6708 ;; It is useful to set the prompt in the following command because
6709 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6710 ;; about and thus /bin/sh will display a strange prompt. For
6711 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6712 ;; display the current working directory but /bin/sh will display
6713 ;; a dollar sign. The following command line sets $PS1 to a sane
6714 ;; value, and works under Bourne-ish shells as well as csh-like
6715 ;; shells. Daniel Pittman reports that the unusual positioning of
6716 ;; the single quotes makes it work under `rc', too. We also unset
6717 ;; the variable $ENV because that is read by some sh
6718 ;; implementations (eg, bash when called as sh) on startup; this
6719 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6720 ;; is another way to set the prompt in /bin/bash, it must be
6721 ;; discarded as well.
6722 (tramp-send-command
6724 (format
6725 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6726 (shell-quote-argument tramp-end-of-output)
6727 (tramp-get-method-parameter
6728 (tramp-file-name-method vec) 'tramp-remote-sh))
6731 ;; Disable echo.
6732 (tramp-message vec 5 "Setting up remote shell environment")
6733 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6734 ;; Check whether the echo has really been disabled. Some
6735 ;; implementations, like busybox of embedded GNU/Linux, don't
6736 ;; support disabling.
6737 (tramp-send-command vec "echo foo" t)
6738 (with-current-buffer (process-buffer proc)
6739 (goto-char (point-min))
6740 (when (looking-at "echo foo")
6741 (tramp-set-connection-property proc "remote-echo" t)
6742 (tramp-message vec 5 "Remote echo still on. Ok.")
6743 ;; Make sure backspaces and their echo are enabled and no line
6744 ;; width magic interferes with them.
6745 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6747 (tramp-message vec 5 "Setting shell prompt")
6748 (tramp-send-command
6749 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6750 (tramp-send-command vec "PS2=''" t)
6751 (tramp-send-command vec "PS3=''" t)
6752 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6754 ;; Try to set up the coding system correctly.
6755 ;; CCC this can't be the right way to do it. Hm.
6756 (tramp-message vec 5 "Determining coding system")
6757 (tramp-send-command vec "echo foo ; echo bar" t)
6758 (with-current-buffer (process-buffer proc)
6759 (goto-char (point-min))
6760 (if (featurep 'mule)
6761 ;; Use MULE to select the right EOL convention for communicating
6762 ;; with the process.
6763 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
6764 (cons 'undecided 'undecided)))
6765 cs-decode cs-encode)
6766 (when (symbolp cs) (setq cs (cons cs cs)))
6767 (setq cs-decode (car cs))
6768 (setq cs-encode (cdr cs))
6769 (unless cs-decode (setq cs-decode 'undecided))
6770 (unless cs-encode (setq cs-encode 'undecided))
6771 (setq cs-encode (tramp-coding-system-change-eol-conversion
6772 cs-encode 'unix))
6773 (when (search-forward "\r" nil t)
6774 (setq cs-decode (tramp-coding-system-change-eol-conversion
6775 cs-decode 'dos)))
6776 (funcall (symbol-function 'set-buffer-process-coding-system)
6777 cs-decode cs-encode)
6778 (tramp-message
6779 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6780 ;; Look for ^M and do something useful if found.
6781 (when (search-forward "\r" nil t)
6782 ;; We have found a ^M but cannot frob the process coding system
6783 ;; because we're running on a non-MULE Emacs. Let's try
6784 ;; stty, instead.
6785 (tramp-send-command vec "stty -onlcr" t))))
6786 ;; Dump stty settings in the traces.
6787 (when (>= tramp-verbose 10)
6788 (tramp-send-command vec "stty -a" t))
6789 (tramp-send-command vec "set +o vi +o emacs" t)
6791 ;; Check whether the output of "uname -sr" has been changed. If
6792 ;; yes, this is a strong indication that we must expire all
6793 ;; connection properties. We start again with
6794 ;; `tramp-maybe-open-connection', it will be catched there.
6795 (tramp-message vec 5 "Checking system information")
6796 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6797 (new-uname
6798 (tramp-set-connection-property
6799 vec "uname"
6800 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6801 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
6802 (with-current-buffer (tramp-get-debug-buffer vec)
6803 ;; Keep the debug buffer
6804 (rename-buffer
6805 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
6806 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6807 (if (= (point-min) (point-max))
6808 (kill-buffer nil)
6809 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6810 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6811 (tramp-get-buffer vec)
6812 (tramp-message
6813 vec 3
6814 "Connection reset, because remote host changed from `%s' to `%s'"
6815 old-uname new-uname)
6816 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
6818 ;; Check whether the remote host suffers from buggy
6819 ;; `send-process-string'. This is known for FreeBSD (see comment in
6820 ;; `send_process', file process.c). I've tested sending 624 bytes
6821 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6822 ;; this host type is detected locally. It cannot handle remote
6823 ;; hosts, though.
6824 (with-connection-property proc "chunksize"
6825 (cond
6826 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6827 tramp-chunksize)
6829 (tramp-message
6830 vec 5 "Checking remote host type for `send-process-string' bug")
6831 (if (string-match
6832 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
6833 500 0))))
6835 ;; Set remote PATH variable.
6836 (tramp-set-remote-path vec)
6838 ;; Search for a good shell before searching for a command which
6839 ;; checks if a file exists. This is done because Tramp wants to use
6840 ;; "test foo; echo $?" to check if various conditions hold, and
6841 ;; there are buggy /bin/sh implementations which don't execute the
6842 ;; "echo $?" part if the "test" part has an error. In particular,
6843 ;; the OpenSolaris /bin/sh is a problem. There are also other
6844 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
6845 ;; in in function declarations, or changing HISTFILE in place.
6846 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
6847 ;; detected.
6848 (tramp-find-shell vec)
6850 ;; Disable unexpected output.
6851 (tramp-send-command vec "mesg n; biff n" t)
6853 ;; Set the environment.
6854 (tramp-message vec 5 "Setting default environment")
6856 (let ((env (copy-sequence tramp-remote-process-environment))
6857 unset item)
6858 (while env
6859 (setq item (tramp-compat-split-string (car env) "="))
6860 (setcdr item (mapconcat 'identity (cdr item) "="))
6861 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
6862 (tramp-send-command
6863 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
6864 (push (car item) unset))
6865 (setq env (cdr env)))
6866 (when unset
6867 (tramp-send-command
6868 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
6870 ;; CCC: We should either implement a Perl version of base64 encoding
6871 ;; and decoding. Then we just use that in the last item. The other
6872 ;; alternative is to use the Perl version of UU encoding. But then
6873 ;; we need a Lisp version of uuencode.
6875 ;; Old text from documentation of tramp-methods:
6876 ;; Using a uuencode/uudecode inline method is discouraged, please use one
6877 ;; of the base64 methods instead since base64 encoding is much more
6878 ;; reliable and the commands are more standardized between the different
6879 ;; Unix versions. But if you can't use base64 for some reason, please
6880 ;; note that the default uudecode command does not work well for some
6881 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
6882 ;; the following command for uudecode:
6884 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6886 ;; For Irix, no solution is known yet.
6888 (defconst tramp-local-coding-commands
6889 '((b64 base64-encode-region base64-decode-region)
6890 (uu tramp-uuencode-region uudecode-decode-region)
6891 (pack
6892 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6893 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6894 "List of local coding commands for inline transfer.
6895 Each item is a list that looks like this:
6897 \(FORMAT ENCODING DECODING)
6899 FORMAT is symbol describing the encoding/decoding format. It can be
6900 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6902 ENCODING and DECODING can be strings, giving commands, or symbols,
6903 giving functions. If they are strings, then they can contain
6904 the \"%s\" format specifier. If that specifier is present, the input
6905 filename will be put into the command line at that spot. If the
6906 specifier is not present, the input should be read from standard
6907 input.
6909 If they are functions, they will be called with two arguments, start
6910 and end of region, and are expected to replace the region contents
6911 with the encoded or decoded results, respectively.")
6913 (defconst tramp-remote-coding-commands
6914 '((b64 "base64" "base64 -d")
6915 (b64 "mimencode -b" "mimencode -u -b")
6916 (b64 "mmencode -b" "mmencode -u -b")
6917 (b64 "recode data..base64" "recode base64..data")
6918 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6919 (b64 tramp-perl-encode tramp-perl-decode)
6920 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6921 (uu "uuencode xxx" "uudecode -o -")
6922 (uu "uuencode xxx" "uudecode -p")
6923 (uu "uuencode xxx" tramp-uudecode)
6924 (pack
6925 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6926 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6927 "List of remote coding commands for inline transfer.
6928 Each item is a list that looks like this:
6930 \(FORMAT ENCODING DECODING)
6932 FORMAT is symbol describing the encoding/decoding format. It can be
6933 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6935 ENCODING and DECODING can be strings, giving commands, or symbols,
6936 giving variables. If they are strings, then they can contain
6937 the \"%s\" format specifier. If that specifier is present, the input
6938 filename will be put into the command line at that spot. If the
6939 specifier is not present, the input should be read from standard
6940 input.
6942 If they are variables, this variable is a string containing a Perl
6943 implementation for this functionality. This Perl program will be transferred
6944 to the remote host, and it is available as shell function with the same name.")
6946 (defun tramp-find-inline-encoding (vec)
6947 "Find an inline transfer encoding that works.
6948 Goes through the list `tramp-local-coding-commands' and
6949 `tramp-remote-coding-commands'."
6950 (save-excursion
6951 (let ((local-commands tramp-local-coding-commands)
6952 (magic "xyzzy")
6953 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6954 (while (and local-commands (not found))
6955 (setq litem (pop local-commands))
6956 (catch 'wont-work-local
6957 (let ((format (nth 0 litem))
6958 (remote-commands tramp-remote-coding-commands))
6959 (setq loc-enc (nth 1 litem))
6960 (setq loc-dec (nth 2 litem))
6961 ;; If the local encoder or decoder is a string, the
6962 ;; corresponding command has to work locally.
6963 (if (not (stringp loc-enc))
6964 (tramp-message
6965 vec 5 "Checking local encoding function `%s'" loc-enc)
6966 (tramp-message
6967 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6968 (unless (zerop (tramp-call-local-coding-command
6969 loc-enc nil nil))
6970 (throw 'wont-work-local nil)))
6971 (if (not (stringp loc-dec))
6972 (tramp-message
6973 vec 5 "Checking local decoding function `%s'" loc-dec)
6974 (tramp-message
6975 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
6976 (unless (zerop (tramp-call-local-coding-command
6977 loc-dec nil nil))
6978 (throw 'wont-work-local nil)))
6979 ;; Search for remote coding commands with the same format
6980 (while (and remote-commands (not found))
6981 (setq ritem (pop remote-commands))
6982 (catch 'wont-work-remote
6983 (when (equal format (nth 0 ritem))
6984 (setq rem-enc (nth 1 ritem))
6985 (setq rem-dec (nth 2 ritem))
6986 ;; Check if remote encoding and decoding commands can be
6987 ;; called remotely with null input and output. This makes
6988 ;; sure there are no syntax errors and the command is really
6989 ;; found. Note that we do not redirect stdout to /dev/null,
6990 ;; for two reasons: when checking the decoding command, we
6991 ;; actually check the output it gives. And also, when
6992 ;; redirecting "mimencode" output to /dev/null, then as root
6993 ;; it might change the permissions of /dev/null!
6994 (when (not (stringp rem-enc))
6995 (let ((name (symbol-name rem-enc)))
6996 (while (string-match (regexp-quote "-") name)
6997 (setq name (replace-match "_" nil t name)))
6998 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
6999 (setq rem-enc name)))
7000 (tramp-message
7001 vec 5
7002 "Checking remote encoding command `%s' for sanity" rem-enc)
7003 (unless (zerop (tramp-send-command-and-check
7004 vec (format "%s </dev/null" rem-enc) t))
7005 (throw 'wont-work-remote nil))
7007 (when (not (stringp rem-dec))
7008 (let ((name (symbol-name rem-dec)))
7009 (while (string-match (regexp-quote "-") name)
7010 (setq name (replace-match "_" nil t name)))
7011 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7012 (setq rem-dec name)))
7013 (tramp-message
7014 vec 5
7015 "Checking remote decoding command `%s' for sanity" rem-dec)
7016 (unless (zerop (tramp-send-command-and-check
7018 (format "echo %s | %s | %s"
7019 magic rem-enc rem-dec)
7021 (throw 'wont-work-remote nil))
7023 (with-current-buffer (tramp-get-buffer vec)
7024 (goto-char (point-min))
7025 (unless (looking-at (regexp-quote magic))
7026 (throw 'wont-work-remote nil)))
7028 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7029 (setq rem-enc (nth 1 ritem))
7030 (setq rem-dec (nth 2 ritem))
7031 (setq found t)))))))
7033 ;; Did we find something?
7034 (unless found
7035 (tramp-error
7036 vec 'file-error "Couldn't find an inline transfer encoding"))
7038 ;; Set connection properties.
7039 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7040 (tramp-set-connection-property vec "local-encoding" loc-enc)
7041 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7042 (tramp-set-connection-property vec "local-decoding" loc-dec)
7043 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7044 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7045 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7046 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7048 (defun tramp-call-local-coding-command (cmd input output)
7049 "Call the local encoding or decoding command.
7050 If CMD contains \"%s\", provide input file INPUT there in command.
7051 Otherwise, INPUT is passed via standard input.
7052 INPUT can also be nil which means `/dev/null'.
7053 OUTPUT can be a string (which specifies a filename), or t (which
7054 means standard output and thus the current buffer), or nil (which
7055 means discard it)."
7056 (tramp-local-call-process
7057 tramp-encoding-shell
7058 (when (and input (not (string-match "%s" cmd))) input)
7059 (if (eq output t) t nil)
7061 tramp-encoding-command-switch
7062 (concat
7063 (if (string-match "%s" cmd) (format cmd input) cmd)
7064 (if (stringp output) (concat "> " output) ""))))
7066 (defun tramp-compute-multi-hops (vec)
7067 "Expands VEC according to `tramp-default-proxies-alist'.
7068 Gateway hops are already opened."
7069 (let ((target-alist `(,vec))
7070 (choices tramp-default-proxies-alist)
7071 item proxy)
7073 ;; Look for proxy hosts to be passed.
7074 (while choices
7075 (setq item (pop choices)
7076 proxy (eval (nth 2 item)))
7077 (when (and
7078 ;; host
7079 (string-match (or (eval (nth 0 item)) "")
7080 (or (tramp-file-name-host (car target-alist)) ""))
7081 ;; user
7082 (string-match (or (eval (nth 1 item)) "")
7083 (or (tramp-file-name-user (car target-alist)) "")))
7084 (if (null proxy)
7085 ;; No more hops needed.
7086 (setq choices nil)
7087 ;; Replace placeholders.
7088 (setq proxy
7089 (format-spec
7090 proxy
7091 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
7092 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
7093 (with-parsed-tramp-file-name proxy l
7094 ;; Add the hop.
7095 (add-to-list 'target-alist l)
7096 ;; Start next search.
7097 (setq choices tramp-default-proxies-alist)))))
7099 ;; Handle gateways.
7100 (when (and (boundp 'tramp-gw-tunnel-method)
7101 (string-match (format
7102 "^\\(%s\\|%s\\)$"
7103 (symbol-value 'tramp-gw-tunnel-method)
7104 (symbol-value 'tramp-gw-socks-method))
7105 (tramp-file-name-method (car target-alist))))
7106 (let ((gw (pop target-alist))
7107 (hop (pop target-alist)))
7108 ;; Is the method prepared for gateways?
7109 (unless (tramp-get-method-parameter
7110 (tramp-file-name-method hop) 'tramp-default-port)
7111 (tramp-error
7112 vec 'file-error
7113 "Method `%s' is not supported for gateway access."
7114 (tramp-file-name-method hop)))
7115 ;; Add default port if needed.
7116 (unless
7117 (string-match
7118 tramp-host-with-port-regexp (tramp-file-name-host hop))
7119 (aset hop 2
7120 (concat
7121 (tramp-file-name-host hop) tramp-prefix-port-format
7122 (number-to-string
7123 (tramp-get-method-parameter
7124 (tramp-file-name-method hop) 'tramp-default-port)))))
7125 ;; Open the gateway connection.
7126 (add-to-list
7127 'target-alist
7128 (vector
7129 (tramp-file-name-method hop) (tramp-file-name-user hop)
7130 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
7131 ;; For the password prompt, we need the correct values.
7132 ;; Therefore, we must remember the gateway vector. But we
7133 ;; cannot do it as connection property, because it shouldn't
7134 ;; be persistent. And we have no started process yet either.
7135 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7137 ;; Foreign and out-of-band methods are not supported for multi-hops.
7138 (when (cdr target-alist)
7139 (setq choices target-alist)
7140 (while choices
7141 (setq item (pop choices))
7142 (when
7144 (not
7145 (tramp-get-method-parameter
7146 (tramp-file-name-method item) 'tramp-login-program))
7147 (tramp-get-method-parameter
7148 (tramp-file-name-method item) 'tramp-copy-program))
7149 (tramp-error
7150 vec 'file-error
7151 "Method `%s' is not supported for multi-hops."
7152 (tramp-file-name-method item)))))
7154 ;; In case the host name is not used for the remote shell
7155 ;; command, the user could be misguided by applying a random
7156 ;; hostname.
7157 (let* ((v (car target-alist))
7158 (method (tramp-file-name-method v))
7159 (host (tramp-file-name-host v)))
7160 (unless
7162 ;; There are multi-hops.
7163 (cdr target-alist)
7164 ;; The host name is used for the remote shell command.
7165 (member
7166 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7167 ;; The host is local. We cannot use `tramp-local-host-p'
7168 ;; here, because it opens a connection as well.
7169 (string-match tramp-local-host-regexp host))
7170 (tramp-error
7171 v 'file-error
7172 "Host `%s' looks like a remote host, `%s' can only use the local host"
7173 host method)))
7175 ;; Result.
7176 target-alist))
7178 (defun tramp-maybe-open-connection (vec)
7179 "Maybe open a connection VEC.
7180 Does not do anything if a connection is already open, but re-opens the
7181 connection if a previous connection has died for some reason."
7182 (catch 'uname-changed
7183 (let ((p (tramp-get-connection-process vec))
7184 (process-environment (copy-sequence process-environment)))
7186 ;; If too much time has passed since last command was sent, look
7187 ;; whether process is still alive. If it isn't, kill it. When
7188 ;; using ssh, it can sometimes happen that the remote end has
7189 ;; hung up but the local ssh client doesn't recognize this until
7190 ;; it tries to send some data to the remote end. So that's why
7191 ;; we try to send a command from time to time, then look again
7192 ;; whether the process is really alive.
7193 (condition-case nil
7194 (when (and (> (tramp-time-diff
7195 (current-time)
7196 (tramp-get-connection-property
7197 p "last-cmd-time" '(0 0 0)))
7199 p (processp p) (memq (process-status p) '(run open)))
7200 (tramp-send-command vec "echo are you awake" t t)
7201 (unless (and (memq (process-status p) '(run open))
7202 (tramp-wait-for-output p 10))
7203 ;; The error will be catched locally.
7204 (tramp-error vec 'file-error "Awake did fail")))
7205 (file-error
7206 (tramp-flush-connection-property vec)
7207 (tramp-flush-connection-property p)
7208 (delete-process p)
7209 (setq p nil)))
7211 ;; New connection must be opened.
7212 (unless (and p (processp p) (memq (process-status p) '(run open)))
7214 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7215 ;; messages from the beginning.
7216 (tramp-get-buffer vec)
7217 (if (zerop (length (tramp-file-name-user vec)))
7218 (tramp-message
7219 vec 3 "Opening connection for %s using %s..."
7220 (tramp-file-name-host vec)
7221 (tramp-file-name-method vec))
7222 (tramp-message
7223 vec 3 "Opening connection for %s@%s using %s..."
7224 (tramp-file-name-user vec)
7225 (tramp-file-name-host vec)
7226 (tramp-file-name-method vec)))
7228 ;; Start new process.
7229 (when (and p (processp p))
7230 (delete-process p))
7231 (setenv "TERM" tramp-terminal-type)
7232 (setenv "LC_ALL" "C")
7233 (setenv "PROMPT_COMMAND")
7234 (setenv "PS1" tramp-initial-end-of-output)
7235 (let* ((target-alist (tramp-compute-multi-hops vec))
7236 (process-connection-type tramp-process-connection-type)
7237 (process-adaptive-read-buffering nil)
7238 (coding-system-for-read nil)
7239 ;; This must be done in order to avoid our file name handler.
7240 (p (let ((default-directory
7241 (tramp-compat-temporary-file-directory)))
7242 (start-process
7243 (or (tramp-get-connection-property vec "process-name" nil)
7244 (tramp-buffer-name vec))
7245 (tramp-get-connection-buffer vec)
7246 tramp-encoding-shell))))
7248 (tramp-message
7249 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7251 ;; Check whether process is alive.
7252 (tramp-set-process-query-on-exit-flag p nil)
7253 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
7254 (tramp-barf-if-no-shell-prompt
7255 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7257 ;; Now do all the connections as specified.
7258 (while target-alist
7259 (let* ((hop (car target-alist))
7260 (l-method (tramp-file-name-method hop))
7261 (l-user (tramp-file-name-user hop))
7262 (l-host (tramp-file-name-host hop))
7263 (l-port nil)
7264 (login-program
7265 (tramp-get-method-parameter l-method 'tramp-login-program))
7266 (login-args
7267 (tramp-get-method-parameter l-method 'tramp-login-args))
7268 (gw-args
7269 (tramp-get-method-parameter l-method 'tramp-gw-args))
7270 (gw (tramp-get-file-property hop "" "gateway" nil))
7271 (g-method (and gw (tramp-file-name-method gw)))
7272 (g-user (and gw (tramp-file-name-user gw)))
7273 (g-host (and gw (tramp-file-name-host gw)))
7274 (command login-program)
7275 ;; We don't create the temporary file. In fact, it
7276 ;; is just a prefix for the ControlPath option of
7277 ;; ssh; the real temporary file has another name, and
7278 ;; it is created and protected by ssh. It is also
7279 ;; removed by ssh, when the connection is closed.
7280 (tmpfile
7281 (tramp-set-connection-property
7282 p "temp-file"
7283 (make-temp-name
7284 (expand-file-name
7285 tramp-temp-name-prefix
7286 (tramp-compat-temporary-file-directory)))))
7287 spec)
7289 ;; Add gateway arguments if necessary.
7290 (when (and gw gw-args)
7291 (setq login-args (append login-args gw-args)))
7293 ;; Check for port number. Until now, there's no need
7294 ;; for handling like method, user, host.
7295 (when (string-match tramp-host-with-port-regexp l-host)
7296 (setq l-port (match-string 2 l-host)
7297 l-host (match-string 1 l-host)))
7299 ;; Set variables for computing the prompt for reading
7300 ;; password. They can also be derived from a gateway.
7301 (setq tramp-current-method (or g-method l-method)
7302 tramp-current-user (or g-user l-user)
7303 tramp-current-host (or g-host l-host))
7305 ;; Replace login-args place holders.
7306 (setq
7307 l-host (or l-host "")
7308 l-user (or l-user "")
7309 l-port (or l-port "")
7310 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
7311 (?t . ,tmpfile))
7312 command
7313 (concat
7314 ;; We do not want to see the trailing local prompt in
7315 ;; `start-file-process'.
7316 (unless (memq system-type '(windows-nt)) "exec ")
7317 command " "
7318 (mapconcat
7319 (lambda (x)
7320 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7321 (unless (member "" x) (mapconcat 'identity x " ")))
7322 login-args " ")
7323 ;; Local shell could be a Windows COMSPEC. It doesn't
7324 ;; know the ";" syntax, but we must exit always for
7325 ;; `start-file-process'. "exec" does not work either.
7326 (if (memq system-type '(windows-nt)) " && exit || exit")))
7328 ;; Send the command.
7329 (tramp-message vec 3 "Sending command `%s'" command)
7330 (tramp-send-command vec command t t)
7331 (tramp-process-actions p vec tramp-actions-before-shell 60)
7332 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
7333 ;; Next hop.
7334 (setq target-alist (cdr target-alist)))
7336 ;; Make initial shell settings.
7337 (tramp-open-connection-setup-interactive-shell p vec))))))
7339 (defun tramp-send-command (vec command &optional neveropen nooutput)
7340 "Send the COMMAND to connection VEC.
7341 Erases temporary buffer before sending the command. If optional
7342 arg NEVEROPEN is non-nil, never try to open the connection. This
7343 is meant to be used from `tramp-maybe-open-connection' only. The
7344 function waits for output unless NOOUTPUT is set."
7345 (unless neveropen (tramp-maybe-open-connection vec))
7346 (let ((p (tramp-get-connection-process vec)))
7347 (when (tramp-get-connection-property p "remote-echo" nil)
7348 ;; We mark the command string that it can be erased in the output buffer.
7349 (tramp-set-connection-property p "check-remote-echo" t)
7350 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7351 (tramp-message vec 6 "%s" command)
7352 (tramp-send-string vec command)
7353 (unless nooutput (tramp-wait-for-output p))))
7355 (defun tramp-wait-for-output (proc &optional timeout)
7356 "Wait for output from remote command."
7357 (unless (buffer-live-p (process-buffer proc))
7358 (delete-process proc)
7359 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7360 (with-current-buffer (process-buffer proc)
7361 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7362 ;; be leading escape sequences, which must be ignored.
7363 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7364 ;; Sometimes, the commands do not return a newline but a
7365 ;; null byte before the shell prompt, for example "git
7366 ;; ls-files -c -z ...".
7367 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7368 (found (tramp-wait-for-regexp proc timeout regexp1)))
7369 (if found
7370 (let (buffer-read-only)
7371 ;; A simple-minded busybox has sent " ^H" sequences.
7372 ;; Delete them.
7373 (goto-char (point-min))
7374 (when (re-search-forward
7375 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7376 (forward-line 1)
7377 (delete-region (point-min) (point)))
7378 ;; Delete the prompt.
7379 (goto-char (point-max))
7380 (re-search-backward regexp nil t)
7381 (delete-region (point) (point-max)))
7382 (if timeout
7383 (tramp-error
7384 proc 'file-error
7385 "[[Remote prompt `%s' not found in %d secs]]"
7386 tramp-end-of-output timeout)
7387 (tramp-error
7388 proc 'file-error
7389 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7390 ;; Return value is whether end-of-output sentinel was found.
7391 found)))
7393 (defun tramp-send-command-and-check
7394 (vec command &optional subshell dont-suppress-err)
7395 "Run COMMAND and check its exit status.
7396 Sends `echo $?' along with the COMMAND for checking the exit status. If
7397 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7399 If the optional argument SUBSHELL is non-nil, the command is
7400 executed in a subshell, ie surrounded by parentheses. If
7401 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7402 (tramp-send-command
7404 (concat (if subshell "( " "")
7405 command
7406 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7407 "echo tramp_exit_status $?"
7408 (if subshell " )" "")))
7409 (with-current-buffer (tramp-get-connection-buffer vec)
7410 (goto-char (point-max))
7411 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7412 (tramp-error
7413 vec 'file-error "Couldn't find exit status of `%s'" command))
7414 (skip-chars-forward "^ ")
7415 (prog1
7416 (read (current-buffer))
7417 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7419 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7420 "Run COMMAND, check exit status, throw error if exit status not okay.
7421 Similar to `tramp-send-command-and-check' but accepts two more arguments
7422 FMT and ARGS which are passed to `error'."
7423 (unless (zerop (tramp-send-command-and-check vec command))
7424 (apply 'tramp-error vec 'file-error fmt args)))
7426 (defun tramp-send-command-and-read (vec command)
7427 "Run COMMAND and return the output, which must be a Lisp expression.
7428 In case there is no valid Lisp expression, it raises an error"
7429 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7430 (with-current-buffer (tramp-get-connection-buffer vec)
7431 ;; Read the expression.
7432 (goto-char (point-min))
7433 (condition-case nil
7434 (prog1 (read (current-buffer))
7435 ;; Error handling.
7436 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7437 (error nil)))
7438 (error (tramp-error
7439 vec 'file-error
7440 "`%s' does not return a valid Lisp expression: `%s'"
7441 command (buffer-string))))))
7443 ;; It seems that Tru64 Unix does not like it if long strings are sent
7444 ;; to it in one go. (This happens when sending the Perl
7445 ;; `file-attributes' implementation, for instance.) Therefore, we
7446 ;; have this function which sends the string in chunks.
7447 (defun tramp-send-string (vec string)
7448 "Send the STRING via connection VEC.
7450 The STRING is expected to use Unix line-endings, but the lines sent to
7451 the remote host use line-endings as defined in the variable
7452 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7453 (let* ((p (tramp-get-connection-process vec))
7454 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7455 (unless p
7456 (tramp-error
7457 vec 'file-error "Can't send string to remote host -- not logged in"))
7458 (tramp-set-connection-property p "last-cmd-time" (current-time))
7459 (tramp-message vec 10 "%s" string)
7460 (with-current-buffer (tramp-get-connection-buffer vec)
7461 ;; Clean up the buffer. We cannot call `erase-buffer' because
7462 ;; narrowing might be in effect.
7463 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7464 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7465 (setq string
7466 (mapconcat 'identity
7467 (tramp-compat-split-string string "\n")
7468 tramp-rsh-end-of-line))
7469 (unless (or (string= string "")
7470 (string-equal (substring string -1) tramp-rsh-end-of-line))
7471 (setq string (concat string tramp-rsh-end-of-line)))
7472 ;; Send the string.
7473 (if (and chunksize (not (zerop chunksize)))
7474 (let ((pos 0)
7475 (end (length string)))
7476 (while (< pos end)
7477 (tramp-message
7478 vec 10 "Sending chunk from %s to %s"
7479 pos (min (+ pos chunksize) end))
7480 (process-send-string
7481 p (substring string pos (min (+ pos chunksize) end)))
7482 (setq pos (+ pos chunksize))))
7483 (process-send-string p string)))))
7485 (defun tramp-mode-string-to-int (mode-string)
7486 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7487 (let* (case-fold-search
7488 (mode-chars (string-to-vector mode-string))
7489 (owner-read (aref mode-chars 1))
7490 (owner-write (aref mode-chars 2))
7491 (owner-execute-or-setid (aref mode-chars 3))
7492 (group-read (aref mode-chars 4))
7493 (group-write (aref mode-chars 5))
7494 (group-execute-or-setid (aref mode-chars 6))
7495 (other-read (aref mode-chars 7))
7496 (other-write (aref mode-chars 8))
7497 (other-execute-or-sticky (aref mode-chars 9)))
7498 (save-match-data
7499 (logior
7500 (cond
7501 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7502 ((char-equal owner-read ?-) 0)
7503 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7504 (cond
7505 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7506 ((char-equal owner-write ?-) 0)
7507 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7508 (cond
7509 ((char-equal owner-execute-or-setid ?x)
7510 (tramp-octal-to-decimal "00100"))
7511 ((char-equal owner-execute-or-setid ?S)
7512 (tramp-octal-to-decimal "04000"))
7513 ((char-equal owner-execute-or-setid ?s)
7514 (tramp-octal-to-decimal "04100"))
7515 ((char-equal owner-execute-or-setid ?-) 0)
7516 (t (error "Fourth char `%c' must be one of `xsS-'"
7517 owner-execute-or-setid)))
7518 (cond
7519 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7520 ((char-equal group-read ?-) 0)
7521 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7522 (cond
7523 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7524 ((char-equal group-write ?-) 0)
7525 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7526 (cond
7527 ((char-equal group-execute-or-setid ?x)
7528 (tramp-octal-to-decimal "00010"))
7529 ((char-equal group-execute-or-setid ?S)
7530 (tramp-octal-to-decimal "02000"))
7531 ((char-equal group-execute-or-setid ?s)
7532 (tramp-octal-to-decimal "02010"))
7533 ((char-equal group-execute-or-setid ?-) 0)
7534 (t (error "Seventh char `%c' must be one of `xsS-'"
7535 group-execute-or-setid)))
7536 (cond
7537 ((char-equal other-read ?r)
7538 (tramp-octal-to-decimal "00004"))
7539 ((char-equal other-read ?-) 0)
7540 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7541 (cond
7542 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7543 ((char-equal other-write ?-) 0)
7544 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7545 (cond
7546 ((char-equal other-execute-or-sticky ?x)
7547 (tramp-octal-to-decimal "00001"))
7548 ((char-equal other-execute-or-sticky ?T)
7549 (tramp-octal-to-decimal "01000"))
7550 ((char-equal other-execute-or-sticky ?t)
7551 (tramp-octal-to-decimal "01001"))
7552 ((char-equal other-execute-or-sticky ?-) 0)
7553 (t (error "Tenth char `%c' must be one of `xtT-'"
7554 other-execute-or-sticky)))))))
7556 (defun tramp-convert-file-attributes (vec attr)
7557 "Convert file-attributes ATTR generated by perl script, stat or ls.
7558 Convert file mode bits to string and set virtual device number.
7559 Return ATTR."
7560 (when attr
7561 ;; Convert last access time.
7562 (unless (listp (nth 4 attr))
7563 (setcar (nthcdr 4 attr)
7564 (list (floor (nth 4 attr) 65536)
7565 (floor (mod (nth 4 attr) 65536)))))
7566 ;; Convert last modification time.
7567 (unless (listp (nth 5 attr))
7568 (setcar (nthcdr 5 attr)
7569 (list (floor (nth 5 attr) 65536)
7570 (floor (mod (nth 5 attr) 65536)))))
7571 ;; Convert last status change time.
7572 (unless (listp (nth 6 attr))
7573 (setcar (nthcdr 6 attr)
7574 (list (floor (nth 6 attr) 65536)
7575 (floor (mod (nth 6 attr) 65536)))))
7576 ;; Convert file size.
7577 (when (< (nth 7 attr) 0)
7578 (setcar (nthcdr 7 attr) -1))
7579 (when (and (floatp (nth 7 attr))
7580 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7581 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7582 ;; Convert file mode bits to string.
7583 (unless (stringp (nth 8 attr))
7584 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7585 (when (stringp (car attr))
7586 (aset (nth 8 attr) 0 ?l)))
7587 ;; Convert directory indication bit.
7588 (when (string-match "^d" (nth 8 attr))
7589 (setcar attr t))
7590 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7591 (when (consp (car attr))
7592 (if (and (stringp (caar attr))
7593 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7594 (setcar attr (match-string 1 (caar attr)))
7595 (setcar attr nil)))
7596 ;; Set file's gid change bit.
7597 (setcar (nthcdr 9 attr)
7598 (if (numberp (nth 3 attr))
7599 (not (= (nth 3 attr)
7600 (tramp-get-remote-gid vec 'integer)))
7601 (not (string-equal
7602 (nth 3 attr)
7603 (tramp-get-remote-gid vec 'string)))))
7604 ;; Convert inode.
7605 (unless (listp (nth 10 attr))
7606 (setcar (nthcdr 10 attr)
7607 (condition-case nil
7608 (cons (floor (nth 10 attr) 65536)
7609 (floor (mod (nth 10 attr) 65536)))
7610 ;; Inodes can be incredible huge. We must hide this.
7611 (error (tramp-get-inode vec)))))
7612 ;; Set virtual device number.
7613 (setcar (nthcdr 11 attr)
7614 (tramp-get-device vec))
7615 attr))
7617 (defun tramp-check-cached-permissions (vec access)
7618 "Check `file-attributes' caches for VEC.
7619 Return t if according to the cache access type ACCESS is known to
7620 be granted."
7621 (let ((result nil)
7622 (offset (cond
7623 ((eq ?r access) 1)
7624 ((eq ?w access) 2)
7625 ((eq ?x access) 3))))
7626 (dolist (suffix '("string" "integer") result)
7627 (setq
7628 result
7630 result
7631 (let ((file-attr
7632 (tramp-get-file-property
7633 vec (tramp-file-name-localname vec)
7634 (concat "file-attributes-" suffix) nil))
7635 (remote-uid
7636 (tramp-get-connection-property
7637 vec (concat "uid-" suffix) nil))
7638 (remote-gid
7639 (tramp-get-connection-property
7640 vec (concat "gid-" suffix) nil)))
7641 (and
7642 file-attr
7644 ;; Not a symlink
7645 (eq t (car file-attr))
7646 (null (car file-attr)))
7648 ;; World accessible.
7649 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7650 ;; User accessible and owned by user.
7651 (and
7652 (eq access (aref (nth 8 file-attr) offset))
7653 (equal remote-uid (nth 2 file-attr)))
7654 ;; Group accessible and owned by user's
7655 ;; principal group.
7656 (and
7657 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7658 (equal remote-gid (nth 3 file-attr)))))))))))
7660 (defun tramp-get-inode (vec)
7661 "Returns the virtual inode number.
7662 If it doesn't exist, generate a new one."
7663 (let ((string (tramp-make-tramp-file-name
7664 (tramp-file-name-method vec)
7665 (tramp-file-name-user vec)
7666 (tramp-file-name-host vec)
7667 "")))
7668 (unless (assoc string tramp-inodes)
7669 (add-to-list 'tramp-inodes
7670 (list string (length tramp-inodes))))
7671 (nth 1 (assoc string tramp-inodes))))
7673 (defun tramp-get-device (vec)
7674 "Returns the virtual device number.
7675 If it doesn't exist, generate a new one."
7676 (let ((string (tramp-make-tramp-file-name
7677 (tramp-file-name-method vec)
7678 (tramp-file-name-user vec)
7679 (tramp-file-name-host vec)
7680 "")))
7681 (unless (assoc string tramp-devices)
7682 (add-to-list 'tramp-devices
7683 (list string (length tramp-devices))))
7684 (cons -1 (nth 1 (assoc string tramp-devices)))))
7686 (defun tramp-file-mode-from-int (mode)
7687 "Turn an integer representing a file mode into an ls(1)-like string."
7688 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7689 (user (logand (lsh mode -6) 7))
7690 (group (logand (lsh mode -3) 7))
7691 (other (logand (lsh mode -0) 7))
7692 (suid (> (logand (lsh mode -9) 4) 0))
7693 (sgid (> (logand (lsh mode -9) 2) 0))
7694 (sticky (> (logand (lsh mode -9) 1) 0)))
7695 (setq user (tramp-file-mode-permissions user suid "s"))
7696 (setq group (tramp-file-mode-permissions group sgid "s"))
7697 (setq other (tramp-file-mode-permissions other sticky "t"))
7698 (concat type user group other)))
7700 (defun tramp-file-mode-permissions (perm suid suid-text)
7701 "Convert a permission bitset into a string.
7702 This is used internally by `tramp-file-mode-from-int'."
7703 (let ((r (> (logand perm 4) 0))
7704 (w (> (logand perm 2) 0))
7705 (x (> (logand perm 1) 0)))
7706 (concat (or (and r "r") "-")
7707 (or (and w "w") "-")
7708 (or (and suid x suid-text) ; suid, execute
7709 (and suid (upcase suid-text)) ; suid, !execute
7710 (and x "x") "-")))) ; !suid
7712 (defun tramp-decimal-to-octal (i)
7713 "Return a string consisting of the octal digits of I.
7714 Not actually used. Use `(format \"%o\" i)' instead?"
7715 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7716 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7717 ((zerop i) "0")
7718 (t (concat (tramp-decimal-to-octal (/ i 8))
7719 (number-to-string (% i 8))))))
7721 ;; Kudos to Gerd Moellmann for this suggestion.
7722 (defun tramp-octal-to-decimal (ostr)
7723 "Given a string of octal digits, return a decimal number."
7724 (let ((x (or ostr "")))
7725 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7726 (unless (string-match "\\`[0-7]*\\'" x)
7727 (error "Non-octal junk in string `%s'" x))
7728 (string-to-number ostr 8)))
7730 (defun tramp-shell-case-fold (string)
7731 "Converts STRING to shell glob pattern which ignores case."
7732 (mapconcat
7733 (lambda (c)
7734 (if (equal (downcase c) (upcase c))
7735 (vector c)
7736 (format "[%c%c]" (downcase c) (upcase c))))
7737 string
7738 ""))
7741 ;; ------------------------------------------------------------
7742 ;; -- Tramp file names --
7743 ;; ------------------------------------------------------------
7744 ;; Conversion functions between external representation and
7745 ;; internal data structure. Convenience functions for internal
7746 ;; data structure.
7748 (defun tramp-file-name-p (vec)
7749 "Check whether VEC is a Tramp object."
7750 (and (vectorp vec) (= 4 (length vec))))
7752 (defun tramp-file-name-method (vec)
7753 "Return method component of VEC."
7754 (and (tramp-file-name-p vec) (aref vec 0)))
7756 (defun tramp-file-name-user (vec)
7757 "Return user component of VEC."
7758 (and (tramp-file-name-p vec) (aref vec 1)))
7760 (defun tramp-file-name-host (vec)
7761 "Return host component of VEC."
7762 (and (tramp-file-name-p vec) (aref vec 2)))
7764 (defun tramp-file-name-localname (vec)
7765 "Return localname component of VEC."
7766 (and (tramp-file-name-p vec) (aref vec 3)))
7768 ;; The user part of a Tramp file name vector can be of kind
7769 ;; "user%domain". Sometimes, we must extract these parts.
7770 (defun tramp-file-name-real-user (vec)
7771 "Return the user name of VEC without domain."
7772 (save-match-data
7773 (let ((user (tramp-file-name-user vec)))
7774 (if (and (stringp user)
7775 (string-match tramp-user-with-domain-regexp user))
7776 (match-string 1 user)
7777 user))))
7779 (defun tramp-file-name-domain (vec)
7780 "Return the domain name of VEC."
7781 (save-match-data
7782 (let ((user (tramp-file-name-user vec)))
7783 (and (stringp user)
7784 (string-match tramp-user-with-domain-regexp user)
7785 (match-string 2 user)))))
7787 ;; The host part of a Tramp file name vector can be of kind
7788 ;; "host#port". Sometimes, we must extract these parts.
7789 (defun tramp-file-name-real-host (vec)
7790 "Return the host name of VEC without port."
7791 (save-match-data
7792 (let ((host (tramp-file-name-host vec)))
7793 (if (and (stringp host)
7794 (string-match tramp-host-with-port-regexp host))
7795 (match-string 1 host)
7796 host))))
7798 (defun tramp-file-name-port (vec)
7799 "Return the port number of VEC."
7800 (save-match-data
7801 (let ((host (tramp-file-name-host vec)))
7802 (and (stringp host)
7803 (string-match tramp-host-with-port-regexp host)
7804 (string-to-number (match-string 2 host))))))
7806 (defun tramp-tramp-file-p (name)
7807 "Return t if NAME is a string with Tramp file name syntax."
7808 (save-match-data
7809 (and (stringp name) (string-match tramp-file-name-regexp name))))
7811 (defun tramp-find-method (method user host)
7812 "Return the right method string to use.
7813 This is METHOD, if non-nil. Otherwise, do a lookup in
7814 `tramp-default-method-alist'."
7815 (or method
7816 (let ((choices tramp-default-method-alist)
7817 lmethod item)
7818 (while choices
7819 (setq item (pop choices))
7820 (when (and (string-match (or (nth 0 item) "") (or host ""))
7821 (string-match (or (nth 1 item) "") (or user "")))
7822 (setq lmethod (nth 2 item))
7823 (setq choices nil)))
7824 lmethod)
7825 tramp-default-method))
7827 (defun tramp-find-user (method user host)
7828 "Return the right user string to use.
7829 This is USER, if non-nil. Otherwise, do a lookup in
7830 `tramp-default-user-alist'."
7831 (or user
7832 (let ((choices tramp-default-user-alist)
7833 luser item)
7834 (while choices
7835 (setq item (pop choices))
7836 (when (and (string-match (or (nth 0 item) "") (or method ""))
7837 (string-match (or (nth 1 item) "") (or host "")))
7838 (setq luser (nth 2 item))
7839 (setq choices nil)))
7840 luser)
7841 tramp-default-user))
7843 (defun tramp-find-host (method user host)
7844 "Return the right host string to use.
7845 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7846 (or (and (> (length host) 0) host)
7847 tramp-default-host))
7849 (defun tramp-dissect-file-name (name &optional nodefault)
7850 "Return a `tramp-file-name' structure.
7851 The structure consists of remote method, remote user, remote host
7852 and localname (file name on remote host). If NODEFAULT is
7853 non-nil, the file name parts are not expanded to their default
7854 values."
7855 (save-match-data
7856 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
7857 (unless match (error "Not a Tramp file name: %s" name))
7858 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7859 (user (match-string (nth 2 tramp-file-name-structure) name))
7860 (host (match-string (nth 3 tramp-file-name-structure) name))
7861 (localname (match-string (nth 4 tramp-file-name-structure) name)))
7862 (when (member method '("multi" "multiu"))
7863 (error
7864 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7865 method))
7866 (when host
7867 (when (string-match tramp-prefix-ipv6-regexp host)
7868 (setq host (replace-match "" nil t host)))
7869 (when (string-match tramp-postfix-ipv6-regexp host)
7870 (setq host (replace-match "" nil t host))))
7871 (if nodefault
7872 (vector method user host localname)
7873 (vector
7874 (tramp-find-method method user host)
7875 (tramp-find-user method user host)
7876 (tramp-find-host method user host)
7877 localname))))))
7879 (defun tramp-equal-remote (file1 file2)
7880 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7881 The check depends on method, user and host name of the files. If
7882 one of the components is missing, the default values are used.
7883 The local file name parts of FILE1 and FILE2 are not taken into
7884 account.
7886 Example:
7888 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7890 would yield `t'. On the other hand, the following check results in nil:
7892 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
7893 (and (stringp (file-remote-p file1))
7894 (stringp (file-remote-p file2))
7895 (string-equal (file-remote-p file1) (file-remote-p file2))))
7897 (defun tramp-make-tramp-file-name (method user host localname)
7898 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7899 (concat tramp-prefix-format
7900 (when (not (zerop (length method)))
7901 (concat method tramp-postfix-method-format))
7902 (when (not (zerop (length user)))
7903 (concat user tramp-postfix-user-format))
7904 (when host
7905 (if (string-match tramp-ipv6-regexp host)
7906 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7907 host))
7908 tramp-postfix-host-format
7909 (when localname localname)))
7911 (defun tramp-completion-make-tramp-file-name (method user host localname)
7912 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7913 It must not be a complete Tramp file name, but as long as there are
7914 necessary only. This function will be used in file name completion."
7915 (concat tramp-prefix-format
7916 (when (not (zerop (length method)))
7917 (concat method tramp-postfix-method-format))
7918 (when (not (zerop (length user)))
7919 (concat user tramp-postfix-user-format))
7920 (when (not (zerop (length host)))
7921 (concat
7922 (if (string-match tramp-ipv6-regexp host)
7923 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7924 host)
7925 tramp-postfix-host-format))
7926 (when localname localname)))
7928 (defun tramp-make-copy-program-file-name (vec)
7929 "Create a file name suitable to be passed to `rcp' and workalikes."
7930 (let ((user (tramp-file-name-user vec))
7931 (host (tramp-file-name-real-host vec))
7932 (localname (tramp-shell-quote-argument
7933 (tramp-file-name-localname vec))))
7934 (if (not (zerop (length user)))
7935 (format "%s@%s:%s" user host localname)
7936 (format "%s:%s" host localname))))
7938 (defun tramp-method-out-of-band-p (vec size)
7939 "Return t if this is an out-of-band method, nil otherwise."
7940 (and
7941 ;; It shall be an out-of-band method.
7942 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7943 ;; Either the file size is large enough, or (in rare cases) there
7944 ;; does not exist a remote encoding.
7945 (or (> size tramp-copy-size-limit)
7946 (null (tramp-get-remote-coding vec "remote-encoding")))))
7948 (defun tramp-local-host-p (vec)
7949 "Return t if this points to the local host, nil otherwise."
7950 ;; We cannot use `tramp-file-name-real-host'. A port is an
7951 ;; indication for an ssh tunnel or alike.
7952 (let ((host (tramp-file-name-host vec)))
7953 (and
7954 (stringp host)
7955 (string-match tramp-local-host-regexp host)
7956 ;; The method shall be applied to one of the shell file name
7957 ;; handler. `tramp-local-host-p' is also called for "smb" and
7958 ;; alike, where it must fail.
7959 (tramp-get-method-parameter
7960 (tramp-file-name-method vec) 'tramp-login-program)
7961 ;; The local temp directory must be writable for the other user.
7962 (file-writable-p
7963 (tramp-make-tramp-file-name
7964 (tramp-file-name-method vec)
7965 (tramp-file-name-user vec)
7966 host
7967 (tramp-compat-temporary-file-directory)))
7968 ;; On some systems, chown runs only for root.
7969 (or (zerop (user-uid))
7970 (zerop (tramp-get-remote-uid vec 'integer))))))
7972 ;; Variables local to connection.
7974 (defun tramp-get-remote-path (vec)
7975 (with-connection-property
7976 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
7977 ;; cache the result for the session only. Otherwise, the result
7978 ;; is cached persistently.
7979 (if (memq 'tramp-own-remote-path tramp-remote-path)
7980 (tramp-get-connection-process vec)
7981 vec)
7982 "remote-path"
7983 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
7984 (elt1 (memq 'tramp-default-remote-path remote-path))
7985 (elt2 (memq 'tramp-own-remote-path remote-path))
7986 (default-remote-path
7987 (when elt1
7988 (condition-case nil
7989 (tramp-send-command-and-read
7990 vec "echo \\\"`getconf PATH`\\\"")
7991 ;; Default if "getconf" is not available.
7992 (error
7993 (tramp-message
7994 vec 3
7995 "`getconf PATH' not successful, using default value \"%s\"."
7996 "/bin:/usr/bin")
7997 "/bin:/usr/bin"))))
7998 (own-remote-path
7999 (when elt2
8000 (condition-case nil
8001 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8002 ;; Default if "getconf" is not available.
8003 (error
8004 (tramp-message
8005 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8006 nil)))))
8008 ;; Replace place holder `tramp-default-remote-path'.
8009 (when elt1
8010 (setcdr elt1
8011 (append
8012 (tramp-compat-split-string default-remote-path ":")
8013 (cdr elt1)))
8014 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8016 ;; Replace place holder `tramp-own-remote-path'.
8017 (when elt2
8018 (setcdr elt2
8019 (append
8020 (tramp-compat-split-string own-remote-path ":")
8021 (cdr elt2)))
8022 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8024 ;; Remove double entries.
8025 (setq elt1 remote-path)
8026 (while (consp elt1)
8027 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8028 (setcar elt2 nil))
8029 (setq elt1 (cdr elt1)))
8031 ;; Remove non-existing directories.
8032 (delq
8034 (mapcar
8035 (lambda (x)
8036 (and
8037 (stringp x)
8038 (file-directory-p
8039 (tramp-make-tramp-file-name
8040 (tramp-file-name-method vec)
8041 (tramp-file-name-user vec)
8042 (tramp-file-name-host vec)
8045 remote-path)))))
8047 (defun tramp-get-remote-tmpdir (vec)
8048 (with-connection-property vec "tmp-directory"
8049 (let ((dir (tramp-shell-quote-argument "/tmp")))
8050 (if (and (zerop
8051 (tramp-send-command-and-check
8052 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8053 (zerop
8054 (tramp-send-command-and-check
8055 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8057 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8059 (defun tramp-get-ls-command (vec)
8060 (with-connection-property vec "ls"
8061 (tramp-message vec 5 "Finding a suitable `ls' command")
8063 (catch 'ls-found
8064 (dolist (cmd '("ls" "gnuls" "gls"))
8065 (let ((dl (tramp-get-remote-path vec))
8066 result)
8067 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8068 ;; Check parameters. On busybox, "ls" output coloring is
8069 ;; enabled by default sometimes. So we try to disable it
8070 ;; when possible. $LS_COLORING is not supported there.
8071 (when (zerop (tramp-send-command-and-check
8072 vec (format "%s -lnd /" result)))
8073 (when (zerop (tramp-send-command-and-check
8074 vec (format "%s --color=never /" result)))
8075 (setq result (concat result " --color=never")))
8076 (throw 'ls-found result))
8077 (setq dl (cdr dl))))))
8078 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8080 (defun tramp-get-ls-command-with-dired (vec)
8081 (save-match-data
8082 (with-connection-property vec "ls-dired"
8083 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8084 (zerop (tramp-send-command-and-check
8085 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8087 (defun tramp-get-test-command (vec)
8088 (with-connection-property vec "test"
8089 (tramp-message vec 5 "Finding a suitable `test' command")
8090 (if (zerop (tramp-send-command-and-check vec "test 0"))
8091 "test"
8092 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8094 (defun tramp-get-test-nt-command (vec)
8095 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8096 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8097 ;; for otherwise the shell crashes.
8098 (with-connection-property vec "test-nt"
8100 (progn
8101 (tramp-send-command
8102 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8103 (with-current-buffer (tramp-get-buffer vec)
8104 (goto-char (point-min))
8105 (when (looking-at (regexp-quote tramp-end-of-output))
8106 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8107 (progn
8108 (tramp-send-command
8110 (format
8111 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8112 (tramp-get-test-command vec)))
8113 "tramp_test_nt %s %s"))))
8115 (defun tramp-get-file-exists-command (vec)
8116 (with-connection-property vec "file-exists"
8117 (tramp-message vec 5 "Finding command to check if file exists")
8118 (tramp-find-file-exists-command vec)))
8120 (defun tramp-get-remote-ln (vec)
8121 (with-connection-property vec "ln"
8122 (tramp-message vec 5 "Finding a suitable `ln' command")
8123 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8125 (defun tramp-get-remote-perl (vec)
8126 (with-connection-property vec "perl"
8127 (tramp-message vec 5 "Finding a suitable `perl' command")
8128 (let ((result
8129 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8130 (tramp-find-executable
8131 vec "perl" (tramp-get-remote-path vec)))))
8132 ;; We must check also for some Perl modules.
8133 (when result
8134 (with-connection-property vec "perl-file-spec"
8135 (zerop
8136 (tramp-send-command-and-check
8137 vec (format "%s -e 'use File::Spec;'" result))))
8138 (with-connection-property vec "perl-cwd-realpath"
8139 (zerop
8140 (tramp-send-command-and-check
8141 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8142 result)))
8144 (defun tramp-get-remote-stat (vec)
8145 (with-connection-property vec "stat"
8146 (tramp-message vec 5 "Finding a suitable `stat' command")
8147 (let ((result (tramp-find-executable
8148 vec "stat" (tramp-get-remote-path vec)))
8149 tmp)
8150 ;; Check whether stat(1) returns usable syntax. %s does not
8151 ;; work on older AIX systems.
8152 (when result
8153 (setq tmp
8154 ;; We don't want to display an error message.
8155 (with-temp-message (or (current-message) "")
8156 (condition-case nil
8157 (tramp-send-command-and-read
8158 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8159 (error nil))))
8160 (unless (and (listp tmp) (stringp (car tmp))
8161 (string-match "^./.$" (car tmp))
8162 (integerp (cadr tmp)))
8163 (setq result nil)))
8164 result)))
8166 (defun tramp-get-remote-readlink (vec)
8167 (with-connection-property vec "readlink"
8168 (tramp-message vec 5 "Finding a suitable `readlink' command")
8169 (let ((result (tramp-find-executable
8170 vec "readlink" (tramp-get-remote-path vec))))
8171 (when (and result
8172 ;; We don't want to display an error message.
8173 (with-temp-message (or (current-message) "")
8174 (condition-case nil
8175 (zerop
8176 (tramp-send-command-and-check
8177 vec (format "%s --canonicalize-missing /" result)))
8178 (error nil))))
8179 result))))
8181 (defun tramp-get-remote-id (vec)
8182 (with-connection-property vec "id"
8183 (tramp-message vec 5 "Finding POSIX `id' command")
8185 (catch 'id-found
8186 (let ((dl (tramp-get-remote-path vec))
8187 result)
8188 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8189 ;; Check POSIX parameter.
8190 (when (zerop (tramp-send-command-and-check
8191 vec (format "%s -u" result)))
8192 (throw 'id-found result))
8193 (setq dl (cdr dl)))))
8194 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8196 (defun tramp-get-remote-uid (vec id-format)
8197 (with-connection-property vec (format "uid-%s" id-format)
8198 (let ((res (tramp-send-command-and-read
8200 (format "%s -u%s %s"
8201 (tramp-get-remote-id vec)
8202 (if (equal id-format 'integer) "" "n")
8203 (if (equal id-format 'integer)
8204 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8205 ;; The command might not always return a number.
8206 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8208 (defun tramp-get-remote-gid (vec id-format)
8209 (with-connection-property vec (format "gid-%s" id-format)
8210 (let ((res (tramp-send-command-and-read
8212 (format "%s -g%s %s"
8213 (tramp-get-remote-id vec)
8214 (if (equal id-format 'integer) "" "n")
8215 (if (equal id-format 'integer)
8216 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8217 ;; The command might not always return a number.
8218 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8220 (defun tramp-get-local-uid (id-format)
8221 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8223 (defun tramp-get-local-gid (id-format)
8224 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8226 ;; Some predefined connection properties.
8227 (defun tramp-get-remote-coding (vec prop)
8228 ;; Local coding handles properties like remote coding. So we could
8229 ;; call it without pain.
8230 (let ((ret (tramp-get-local-coding vec prop)))
8231 ;; The connection property might have been cached. So we must send
8232 ;; the script - maybe.
8233 (when (and ret (symbolp ret))
8234 (let ((name (symbol-name ret)))
8235 (while (string-match (regexp-quote "-") name)
8236 (setq name (replace-match "_" nil t name)))
8237 (tramp-maybe-send-script vec (symbol-value ret) name)
8238 (setq ret name)))
8239 ;; Return the value.
8240 ret))
8242 (defun tramp-get-local-coding (vec prop)
8244 (tramp-get-connection-property vec prop nil)
8245 (progn
8246 (tramp-find-inline-encoding vec)
8247 (tramp-get-connection-property vec prop nil))))
8249 (defun tramp-get-method-parameter (method param)
8250 "Return the method parameter PARAM.
8251 If the `tramp-methods' entry does not exist, return NIL."
8252 (let ((entry (assoc param (assoc method tramp-methods))))
8253 (when entry (cadr entry))))
8255 ;; Auto saving to a special directory.
8257 (defun tramp-exists-file-name-handler (operation &rest args)
8258 "Checks whether OPERATION runs a file name handler."
8259 ;; The file name handler is determined on base of either an
8260 ;; argument, `buffer-file-name', or `default-directory'.
8261 (condition-case nil
8262 (let* ((buffer-file-name "/")
8263 (default-directory "/")
8264 (fnha file-name-handler-alist)
8265 (check-file-name-operation operation)
8266 (file-name-handler-alist
8267 (list
8268 (cons "/"
8269 (lambda (operation &rest args)
8270 "Returns OPERATION if it is the one to be checked."
8271 (if (equal check-file-name-operation operation)
8272 operation
8273 (let ((file-name-handler-alist fnha))
8274 (apply operation args))))))))
8275 (equal (apply operation args) operation))
8276 (error nil)))
8278 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8279 (defadvice make-auto-save-file-name
8280 (around tramp-advice-make-auto-save-file-name () activate)
8281 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8282 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
8283 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8284 ;; directly, because this would bypass the locking mechanism.
8285 (setq ad-return-value
8286 (tramp-file-name-handler 'make-auto-save-file-name))
8287 ad-do-it))
8288 (add-hook
8289 'tramp-unload-hook
8290 (lambda ()
8291 (ad-remove-advice
8292 'make-auto-save-file-name
8293 'around 'tramp-advice-make-auto-save-file-name)
8294 (ad-activate 'make-auto-save-file-name))))
8296 ;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
8297 ;; permission 0666 minus umask. This is a security threat.
8299 (defun tramp-set-auto-save-file-modes ()
8300 "Set permissions of autosaved remote files to the original permissions."
8301 (let ((bfn (buffer-file-name)))
8302 (when (and (stringp bfn)
8303 (tramp-tramp-file-p bfn)
8304 (buffer-modified-p)
8305 (stringp buffer-auto-save-file-name)
8306 (not (equal bfn buffer-auto-save-file-name)))
8307 (unless (file-exists-p buffer-auto-save-file-name)
8308 (write-region "" nil buffer-auto-save-file-name))
8309 ;; Permissions should be set always, because there might be an old
8310 ;; auto-saved file belonging to another original file. This could
8311 ;; be a security threat.
8312 (set-file-modes buffer-auto-save-file-name
8313 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8315 (unless (or (> emacs-major-version 21)
8316 (and (featurep 'xemacs)
8317 (= emacs-major-version 21)
8318 (> emacs-minor-version 4)))
8319 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8320 (add-hook 'tramp-unload-hook
8321 (lambda ()
8322 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8324 (defun tramp-subst-strs-in-string (alist string)
8325 "Replace all occurrences of the string FROM with TO in STRING.
8326 ALIST is of the form ((FROM . TO) ...)."
8327 (save-match-data
8328 (while alist
8329 (let* ((pr (car alist))
8330 (from (car pr))
8331 (to (cdr pr)))
8332 (while (string-match (regexp-quote from) string)
8333 (setq string (replace-match to t t string)))
8334 (setq alist (cdr alist))))
8335 string))
8337 ;; ------------------------------------------------------------
8338 ;; -- Compatibility functions section --
8339 ;; ------------------------------------------------------------
8341 (defun tramp-read-passwd (proc &optional prompt)
8342 "Read a password from user (compat function).
8343 Consults the auth-source package.
8344 Invokes `password-read' if available, `read-passwd' else."
8345 (let* ((key (tramp-make-tramp-file-name
8346 tramp-current-method tramp-current-user
8347 tramp-current-host ""))
8348 (pw-prompt
8349 (or prompt
8350 (with-current-buffer (process-buffer proc)
8351 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8352 (format "%s for %s " (capitalize (match-string 1)) key)))))
8353 (with-parsed-tramp-file-name key nil
8354 (prog1
8356 ;; See if auth-sources contains something useful, if it's bound.
8357 (and (boundp 'auth-sources)
8358 (tramp-get-connection-property v "first-password-request" nil)
8359 ;; Try with Tramp's current method.
8360 (funcall (symbol-function 'auth-source-user-or-password)
8361 "password" tramp-current-host tramp-current-method))
8362 ;; Try the password cache.
8363 (when (functionp 'password-read)
8364 (unless (tramp-get-connection-property
8365 v "first-password-request" nil)
8366 (funcall (symbol-function 'password-cache-remove) key))
8367 (let ((password
8368 (funcall (symbol-function 'password-read) pw-prompt key)))
8369 (funcall (symbol-function 'password-cache-add) key password)
8370 password))
8371 ;; Else, get the password interactively.
8372 (read-passwd pw-prompt))
8373 (tramp-set-connection-property v "first-password-request" nil)))))
8375 (defun tramp-clear-passwd (vec)
8376 "Clear password cache for connection related to VEC."
8377 (when (functionp 'password-cache-remove)
8378 (funcall
8379 (symbol-function 'password-cache-remove)
8380 (tramp-make-tramp-file-name
8381 (tramp-file-name-method vec)
8382 (tramp-file-name-user vec)
8383 (tramp-file-name-host vec)
8384 ""))))
8386 ;; Snarfed code from time-date.el and parse-time.el
8388 (defconst tramp-half-a-year '(241 17024)
8389 "Evaluated by \"(days-to-time 183)\".")
8391 (defconst tramp-parse-time-months
8392 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8393 ("apr" . 4) ("may" . 5) ("jun" . 6)
8394 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8395 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8396 "Alist mapping month names to integers.")
8398 (defun tramp-time-less-p (t1 t2)
8399 "Say whether time value T1 is less than time value T2."
8400 (unless t1 (setq t1 '(0 0)))
8401 (unless t2 (setq t2 '(0 0)))
8402 (or (< (car t1) (car t2))
8403 (and (= (car t1) (car t2))
8404 (< (nth 1 t1) (nth 1 t2)))))
8406 (defun tramp-time-subtract (t1 t2)
8407 "Subtract two time values.
8408 Return the difference in the format of a time value."
8409 (unless t1 (setq t1 '(0 0)))
8410 (unless t2 (setq t2 '(0 0)))
8411 (let ((borrow (< (cadr t1) (cadr t2))))
8412 (list (- (car t1) (car t2) (if borrow 1 0))
8413 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8415 (defun tramp-time-diff (t1 t2)
8416 "Return the difference between the two times, in seconds.
8417 T1 and T2 are time values (as returned by `current-time' for example)."
8418 ;; Pacify byte-compiler with `symbol-function'.
8419 (cond ((and (fboundp 'subtract-time)
8420 (fboundp 'float-time))
8421 (funcall (symbol-function 'float-time)
8422 (funcall (symbol-function 'subtract-time) t1 t2)))
8423 ((and (fboundp 'subtract-time)
8424 (fboundp 'time-to-seconds))
8425 (funcall (symbol-function 'time-to-seconds)
8426 (funcall (symbol-function 'subtract-time) t1 t2)))
8427 ((fboundp 'itimer-time-difference)
8428 (funcall (symbol-function 'itimer-time-difference)
8429 (if (< (length t1) 3) (append t1 '(0)) t1)
8430 (if (< (length t2) 3) (append t2 '(0)) t2)))
8432 (let ((time (tramp-time-subtract t1 t2)))
8433 (+ (* (car time) 65536.0)
8434 (cadr time)
8435 (/ (or (nth 2 time) 0) 1000000.0))))))
8437 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8438 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8439 EOL-TYPE can be one of `dos', `unix', or `mac'."
8440 (cond ((fboundp 'coding-system-change-eol-conversion)
8441 (funcall (symbol-function 'coding-system-change-eol-conversion)
8442 coding-system eol-type))
8443 ((fboundp 'subsidiary-coding-system)
8444 (funcall (symbol-function 'subsidiary-coding-system)
8445 coding-system
8446 (cond ((eq eol-type 'dos) 'crlf)
8447 ((eq eol-type 'unix) 'lf)
8448 ((eq eol-type 'mac) 'cr)
8450 (error "Unknown EOL-TYPE `%s', must be %s"
8451 eol-type
8452 "`dos', `unix', or `mac'")))))
8453 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8455 (defun tramp-set-process-query-on-exit-flag (process flag)
8456 "Specify if query is needed for process when Emacs is exited.
8457 If the second argument flag is non-nil, Emacs will query the user before
8458 exiting if process is running."
8459 (if (fboundp 'set-process-query-on-exit-flag)
8460 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
8461 (funcall (symbol-function 'process-kill-without-query) process flag)))
8464 ;; ------------------------------------------------------------
8465 ;; -- Kludges section --
8466 ;; ------------------------------------------------------------
8468 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8469 ;; does not deal well with newline characters. Newline is replaced by
8470 ;; backslash newline. But if, say, the string `a backslash newline b'
8471 ;; is passed to a shell, the shell will expand this into "ab",
8472 ;; completely omitting the newline. This is not what was intended.
8473 ;; It does not appear to be possible to make the function
8474 ;; `shell-quote-argument' work with newlines without making it
8475 ;; dependent on the shell used. But within this package, we know that
8476 ;; we will always use a Bourne-like shell, so we use an approach which
8477 ;; groks newlines.
8479 ;; The approach is simple: we call `shell-quote-argument', then
8480 ;; massage the newline part of the result.
8482 ;; This function should produce a string which is grokked by a Unix
8483 ;; shell, even if the Emacs is running on Windows. Since this is the
8484 ;; kludges section, we bind `system-type' in such a way that
8485 ;; `shell-quote-arguments' behaves as if on Unix.
8487 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8488 ;; function to work with Bourne-like shells.
8490 ;; CCC: This function should be rewritten so that
8491 ;; `shell-quote-argument' is not used. This way, we are safe from
8492 ;; changes in `shell-quote-argument'.
8493 (defun tramp-shell-quote-argument (s)
8494 "Similar to `shell-quote-argument', but groks newlines.
8495 Only works for Bourne-like shells."
8496 (let ((system-type 'not-windows))
8497 (save-match-data
8498 (let ((result (shell-quote-argument s))
8499 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8500 (when (and (>= (length result) 2)
8501 (string= (substring result 0 2) "\\~"))
8502 (setq result (substring result 1)))
8503 (while (string-match nl result)
8504 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8505 t t result)))
8506 result))))
8508 ;; Checklist for `tramp-unload-hook'
8509 ;; - Unload all `tramp-*' packages
8510 ;; - Reset `file-name-handler-alist'
8511 ;; - Cleanup hooks where Tramp functions are in
8512 ;; - Cleanup advised functions
8513 ;; - Cleanup autoloads
8514 ;;;###autoload
8515 (defun tramp-unload-tramp ()
8516 "Discard Tramp from loading remote files."
8517 (interactive)
8518 ;; When Tramp is not loaded yet, its autoloads are still active.
8519 (tramp-unload-file-name-handlers)
8520 ;; ange-ftp settings must be enabled.
8521 (when (functionp 'tramp-ftp-enable-ange-ftp)
8522 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
8523 ;; Maybe its not loaded yet.
8524 (condition-case nil
8525 (unload-feature 'tramp 'force)
8526 (error nil)))
8528 (when (and load-in-progress
8529 (string-match "Loading tramp..." (or (current-message) "")))
8530 (message "Loading tramp...done"))
8532 (provide 'tramp)
8534 ;;; TODO:
8536 ;; * Handle nonlocal exits such as C-g.
8537 ;; * But it would probably be better to use with-local-quit at the
8538 ;; place where it's actually needed: around any potentially
8539 ;; indefinitely blocking piece of code. In this case it would be
8540 ;; within Tramp around one of its calls to accept-process-output (or
8541 ;; around one of the loops that calls accept-process-output)
8542 ;; (Stefan Monnier).
8543 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8544 ;; `shell-quote-argument'.
8545 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8546 ;; by the files in that directory. Add this here.
8547 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8548 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8549 ;; * Case-insensitive filename completion. (Norbert Goevert.)
8550 ;; * Don't use globbing for directories with many files, as this is
8551 ;; likely to produce long command lines, and some shells choke on
8552 ;; long command lines.
8553 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8554 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8555 ;; * abbreviate-file-name
8556 ;; * Better error checking. At least whenever we see something
8557 ;; strange when doing zerop, we should kill the process and start
8558 ;; again. (Greg Stark)
8559 ;; * Remove unneeded parameters from methods.
8560 ;; * Make it work for different encodings, and for different file name
8561 ;; encodings, too. (Daniel Pittman)
8562 ;; * Progress reports while copying files. (Michael Kifer)
8563 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8564 ;; then look if it's the right version (with `perl -v').
8565 ;; * When editing a remote CVS controlled file as a different user, VC
8566 ;; gets confused about the file locking status. Try to find out why
8567 ;; the workaround doesn't work.
8568 ;; * Username and hostname completion.
8569 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8570 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8571 ;; Code is nearly identical.
8572 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8573 ;; until the last but one hop via `start-file-process'. Apply it
8574 ;; also for ftp and smb.
8575 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8576 ;; some shell with root priviledges, it would be nice if I could
8577 ;; just call
8578 ;; trampclient filename.c
8579 ;; as an editor, and the _current_ shell would connect to an Emacs
8580 ;; server and would be used in an existing non-priviledged Emacs
8581 ;; session for doing the editing in question.
8582 ;; That way, I need not tell Emacs my password again and be afraid
8583 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8584 ;; once display a just typed password in the context of a keyboard
8585 ;; sequence prompt for a question immediately following in a shell
8586 ;; script run within Emacs -- nasty).
8587 ;; And if I have some ssh session running to a different computer,
8588 ;; having the possibility of passing a local file there to a local
8589 ;; Emacs session (in case I can arrange for a connection back) would
8590 ;; be nice.
8591 ;; Likely the corresponding Tramp server should not allow the
8592 ;; equivalent of the emacsclient -eval option in order to make this
8593 ;; reasonably unproblematic. And maybe trampclient should have some
8594 ;; way of passing credentials, like by using an SSL socket or
8595 ;; something. (David Kastrup)
8596 ;; * Reconnect directly to a compliant shell without first going
8597 ;; through the user's default shell. (Pete Forman)
8598 ;; * Make `tramp-default-user' obsolete.
8599 ;; * How can I interrupt the remote process with a signal
8600 ;; (interrupt-process seems not to work)? (Markus Triska)
8601 ;; * Avoid the local shell entirely for starting remote processes. If
8602 ;; so, I think even a signal, when delivered directly to the local
8603 ;; SSH instance, would correctly be propagated to the remote process
8604 ;; automatically; possibly SSH would have to be started with
8605 ;; "-t". (Markus Triska)
8606 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8607 ;; isn't on the remote host. (Mark A. Hershberger)
8608 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8609 ;; * Implement a general server-local-variable mechanism, as there are
8610 ;; probably other variables that need different values for different
8611 ;; servers too. The user could then configure a variable (such as
8612 ;; tramp-server-local-variable-alist) to define any such variables
8613 ;; that they need to, which would then be let bound as appropriate
8614 ;; in tramp functions. (Jason Rumney)
8615 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8616 ;; rsync).
8617 ;; * Keep a second connection open for out-of-band methods like scp or
8618 ;; rsync.
8619 ;; * Support ptys in `tramp-handle-start-file-process'. (Bug#4604)
8620 ;; * IMHO, it's a drawback that currently Tramp doesn't support
8621 ;; Unicode in Dired file names by default. Is it possible to
8622 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8623 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
8624 ;; expects only English messages? (Juri Linkov)
8625 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8626 ;; * Do not handle files with drive letter as remote. (Bug#5447)
8627 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448)
8628 ;; * Try telnet+curl as new method. It might be useful for busybox,
8629 ;; without built-in uuencode/uudecode.
8630 ;; * Let `shell-dynamic-complete-*' and `comint-dynamic-complete' work
8631 ;; on remote hosts.
8632 ;; * Use secrets.el for password handling.
8634 ;; Functions for file-name-handler-alist:
8635 ;; diff-latest-backup-file -- in diff.el
8637 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8638 ;;; tramp.el ends here
8640 ;; Local Variables:
8641 ;; mode: Emacs-Lisp
8642 ;; coding: utf-8
8643 ;; End: