Reorganize Custom groups.
[emacs.git] / lisp / net / tramp.el
blob09a3392856fcd95e97172edca6cf03d83b9f56c7
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 :group 'net
180 :version "22.1")
182 ;; Maybe we need once a real Tramp mode, with key bindings etc.
183 ;;;###autoload
184 (defcustom tramp-mode t
185 "*Whether Tramp is enabled.
186 If it is set to nil, all remote file names are used literally."
187 :group 'tramp
188 :type 'boolean)
190 (defcustom tramp-verbose 3
191 "*Verbosity level for Tramp messages.
192 Any level x includes messages for all levels 1 .. x-1. The levels are
194 0 silent (no tramp messages at all)
195 1 errors
196 2 warnings
197 3 connection to remote hosts (default level)
198 4 activities
199 5 internal
200 6 sent and received strings
201 7 file caching
202 8 connection properties
203 10 traces (huge)."
204 :group 'tramp
205 :type 'integer)
207 ;; Emacs case.
208 (eval-and-compile
209 (when (boundp 'backup-directory-alist)
210 (defcustom tramp-backup-directory-alist nil
211 "Alist of filename patterns and backup directory names.
212 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
213 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
214 is a local file name, the backup directory is prepended with Tramp file
215 name prefix \(method, user, host\) of file.
217 \(setq tramp-backup-directory-alist backup-directory-alist\)
219 gives the same backup policy for Tramp files on their hosts like the
220 policy for local files."
221 :group 'tramp
222 :type '(repeat (cons (regexp :tag "Regexp matching filename")
223 (directory :tag "Backup directory name"))))))
225 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
226 ;; the package "backup-dir" might not be loaded yet.
227 (eval-and-compile
228 (when (featurep 'xemacs)
229 (defcustom tramp-bkup-backup-directory-info nil
230 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
231 It has the same meaning like `bkup-backup-directory-info' from package
232 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
233 file name, the backup directory is prepended with Tramp file name prefix
234 \(method, user, host\) of file.
236 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
238 gives the same backup policy for Tramp files on their hosts like the
239 policy for local files."
240 :type '(repeat
241 (list (regexp :tag "File regexp")
242 (string :tag "Backup Dir")
243 (set :inline t
244 (const ok-create)
245 (const full-path)
246 (const prepend-name)
247 (const search-upward))))
248 :group 'tramp)))
250 (defcustom tramp-auto-save-directory nil
251 "*Put auto-save files in this directory, if set.
252 The idea is to use a local directory so that auto-saving is faster."
253 :group 'tramp
254 :type '(choice (const nil) string))
256 (defcustom tramp-encoding-shell
257 (if (memq system-type '(windows-nt))
258 (getenv "COMSPEC")
259 "/bin/sh")
260 "*Use this program for encoding and decoding commands on the local host.
261 This shell is used to execute the encoding and decoding command on the
262 local host, so if you want to use `~' in those commands, you should
263 choose a shell here which groks tilde expansion. `/bin/sh' normally
264 does not understand tilde expansion.
266 For encoding and deocding, commands like the following are executed:
268 /bin/sh -c COMMAND < INPUT > OUTPUT
270 This variable can be used to change the \"/bin/sh\" part. See the
271 variable `tramp-encoding-command-switch' for the \"-c\" part.
273 Note that this variable is not used for remote commands. There are
274 mechanisms in tramp.el which automatically determine the right shell to
275 use for the remote host."
276 :group 'tramp
277 :type '(file :must-match t))
279 (defcustom tramp-encoding-command-switch
280 (if (string-match "cmd\\.exe" tramp-encoding-shell)
281 "/c"
282 "-c")
283 "*Use this switch together with `tramp-encoding-shell' for local commands.
284 See the variable `tramp-encoding-shell' for more information."
285 :group 'tramp
286 :type 'string)
288 (defcustom tramp-copy-size-limit 10240
289 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
290 :group 'tramp
291 :type 'integer)
293 (defcustom tramp-terminal-type "dumb"
294 "*Value of TERM environment variable for logging in to remote host.
295 Because Tramp wants to parse the output of the remote shell, it is easily
296 confused by ANSI color escape sequences and suchlike. Often, shell init
297 files conditionalize this setup based on the TERM environment variable."
298 :group 'tramp
299 :type 'string)
301 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
302 ;; root users. It uses the `$' character for other users. In order
303 ;; to guarantee a proper prompt, we use "#$" for the prompt.
305 (defvar tramp-end-of-output
306 (format
307 "///%s#$"
308 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
309 "String used to recognize end of output.
310 The '$' character at the end is quoted; the string cannot be
311 detected as prompt when being sent on echoing hosts, therefore.")
313 (defconst tramp-initial-end-of-output "#$ "
314 "Prompt when establishing a connection.")
316 (defvar tramp-methods
317 `(("rcp" (tramp-login-program "rsh")
318 (tramp-login-args (("%h") ("-l" "%u")))
319 (tramp-remote-sh "/bin/sh")
320 (tramp-copy-program "rcp")
321 (tramp-copy-args (("-p" "%k") ("-r")))
322 (tramp-copy-keep-date t)
323 (tramp-copy-recursive t)
324 (tramp-password-end-of-line nil))
325 ("scp" (tramp-login-program "ssh")
326 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
327 ("-e" "none")))
328 (tramp-remote-sh "/bin/sh")
329 (tramp-copy-program "scp")
330 (tramp-copy-args (("-P" "%p") ("-p" "%k")
331 ("-q") ("-r")))
332 (tramp-copy-keep-date t)
333 (tramp-copy-recursive t)
334 (tramp-password-end-of-line nil)
335 (tramp-gw-args (("-o"
336 "GlobalKnownHostsFile=/dev/null")
337 ("-o" "UserKnownHostsFile=/dev/null")
338 ("-o" "StrictHostKeyChecking=no")))
339 (tramp-default-port 22))
340 ("scp1" (tramp-login-program "ssh")
341 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
342 ("-1" "-e" "none")))
343 (tramp-remote-sh "/bin/sh")
344 (tramp-copy-program "scp")
345 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
346 ("-q") ("-r")))
347 (tramp-copy-keep-date t)
348 (tramp-copy-recursive t)
349 (tramp-password-end-of-line nil)
350 (tramp-gw-args (("-o"
351 "GlobalKnownHostsFile=/dev/null")
352 ("-o" "UserKnownHostsFile=/dev/null")
353 ("-o" "StrictHostKeyChecking=no")))
354 (tramp-default-port 22))
355 ("scp2" (tramp-login-program "ssh")
356 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
357 ("-2" "-e" "none")))
358 (tramp-remote-sh "/bin/sh")
359 (tramp-copy-program "scp")
360 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
361 ("-q") ("-r")))
362 (tramp-copy-keep-date t)
363 (tramp-copy-recursive t)
364 (tramp-password-end-of-line nil)
365 (tramp-gw-args (("-o"
366 "GlobalKnownHostsFile=/dev/null")
367 ("-o" "UserKnownHostsFile=/dev/null")
368 ("-o" "StrictHostKeyChecking=no")))
369 (tramp-default-port 22))
370 ("scp1_old"
371 (tramp-login-program "ssh1")
372 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
373 ("-e" "none")))
374 (tramp-remote-sh "/bin/sh")
375 (tramp-copy-program "scp1")
376 (tramp-copy-args (("-p" "%k") ("-r")))
377 (tramp-copy-keep-date t)
378 (tramp-copy-recursive t)
379 (tramp-password-end-of-line nil))
380 ("scp2_old"
381 (tramp-login-program "ssh2")
382 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
383 ("-e" "none")))
384 (tramp-remote-sh "/bin/sh")
385 (tramp-copy-program "scp2")
386 (tramp-copy-args (("-p" "%k") ("-r")))
387 (tramp-copy-keep-date t)
388 (tramp-copy-recursive t)
389 (tramp-password-end-of-line nil))
390 ("sftp" (tramp-login-program "ssh")
391 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
392 ("-e" "none")))
393 (tramp-remote-sh "/bin/sh")
394 (tramp-copy-program "sftp")
395 (tramp-copy-args nil)
396 (tramp-copy-keep-date nil)
397 (tramp-password-end-of-line nil))
398 ("rsync" (tramp-login-program "ssh")
399 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
400 ("-e" "none")))
401 (tramp-remote-sh "/bin/sh")
402 (tramp-copy-program "rsync")
403 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
404 (tramp-copy-keep-date t)
405 (tramp-copy-keep-tmpfile t)
406 (tramp-copy-recursive t)
407 (tramp-password-end-of-line nil))
408 ("rsyncc"
409 (tramp-login-program "ssh")
410 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
411 ("-o" "ControlPath=%t.%%r@%%h:%%p")
412 ("-o" "ControlMaster=yes")
413 ("-e" "none")))
414 (tramp-remote-sh "/bin/sh")
415 (tramp-copy-program "rsync")
416 (tramp-copy-args (("-t" "%k") ("-r")))
417 (tramp-copy-env (("RSYNC_RSH")
418 (,(concat
419 "ssh"
420 " -o ControlPath=%t.%%r@%%h:%%p"
421 " -o ControlMaster=auto"))))
422 (tramp-copy-keep-date t)
423 (tramp-copy-keep-tmpfile t)
424 (tramp-copy-recursive t)
425 (tramp-password-end-of-line nil))
426 ("remcp" (tramp-login-program "remsh")
427 (tramp-login-args (("%h") ("-l" "%u")))
428 (tramp-remote-sh "/bin/sh")
429 (tramp-copy-program "rcp")
430 (tramp-copy-args (("-p" "%k")))
431 (tramp-copy-keep-date t)
432 (tramp-password-end-of-line nil))
433 ("rsh" (tramp-login-program "rsh")
434 (tramp-login-args (("%h") ("-l" "%u")))
435 (tramp-remote-sh "/bin/sh")
436 (tramp-copy-program nil)
437 (tramp-copy-args nil)
438 (tramp-copy-keep-date nil)
439 (tramp-password-end-of-line nil))
440 ("ssh" (tramp-login-program "ssh")
441 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
442 ("-e" "none")))
443 (tramp-remote-sh "/bin/sh")
444 (tramp-copy-program nil)
445 (tramp-copy-args nil)
446 (tramp-copy-keep-date nil)
447 (tramp-password-end-of-line nil)
448 (tramp-gw-args (("-o"
449 "GlobalKnownHostsFile=/dev/null")
450 ("-o" "UserKnownHostsFile=/dev/null")
451 ("-o" "StrictHostKeyChecking=no")))
452 (tramp-default-port 22))
453 ("ssh1" (tramp-login-program "ssh")
454 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
455 ("-1" "-e" "none")))
456 (tramp-remote-sh "/bin/sh")
457 (tramp-copy-program nil)
458 (tramp-copy-args nil)
459 (tramp-copy-keep-date nil)
460 (tramp-password-end-of-line nil)
461 (tramp-gw-args (("-o"
462 "GlobalKnownHostsFile=/dev/null")
463 ("-o" "UserKnownHostsFile=/dev/null")
464 ("-o" "StrictHostKeyChecking=no")))
465 (tramp-default-port 22))
466 ("ssh2" (tramp-login-program "ssh")
467 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
468 ("-2" "-e" "none")))
469 (tramp-remote-sh "/bin/sh")
470 (tramp-copy-program nil)
471 (tramp-copy-args nil)
472 (tramp-copy-keep-date nil)
473 (tramp-password-end-of-line nil)
474 (tramp-gw-args (("-o"
475 "GlobalKnownHostsFile=/dev/null")
476 ("-o" "UserKnownHostsFile=/dev/null")
477 ("-o" "StrictHostKeyChecking=no")))
478 (tramp-default-port 22))
479 ("ssh1_old"
480 (tramp-login-program "ssh1")
481 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
482 ("-e" "none")))
483 (tramp-remote-sh "/bin/sh")
484 (tramp-copy-program nil)
485 (tramp-copy-args nil)
486 (tramp-copy-keep-date nil)
487 (tramp-password-end-of-line nil))
488 ("ssh2_old"
489 (tramp-login-program "ssh2")
490 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
491 ("-e" "none")))
492 (tramp-remote-sh "/bin/sh")
493 (tramp-copy-program nil)
494 (tramp-copy-args nil)
495 (tramp-copy-keep-date nil)
496 (tramp-password-end-of-line nil))
497 ("remsh" (tramp-login-program "remsh")
498 (tramp-login-args (("%h") ("-l" "%u")))
499 (tramp-remote-sh "/bin/sh")
500 (tramp-copy-program nil)
501 (tramp-copy-args nil)
502 (tramp-copy-keep-date nil)
503 (tramp-password-end-of-line nil))
504 ("telnet"
505 (tramp-login-program "telnet")
506 (tramp-login-args (("%h") ("%p")))
507 (tramp-remote-sh "/bin/sh")
508 (tramp-copy-program nil)
509 (tramp-copy-args nil)
510 (tramp-copy-keep-date nil)
511 (tramp-password-end-of-line nil)
512 (tramp-default-port 23))
513 ("su" (tramp-login-program "su")
514 (tramp-login-args (("-") ("%u")))
515 (tramp-remote-sh "/bin/sh")
516 (tramp-copy-program nil)
517 (tramp-copy-args nil)
518 (tramp-copy-keep-date nil)
519 (tramp-password-end-of-line nil))
520 ("sudo" (tramp-login-program "sudo")
521 (tramp-login-args (("-u" "%u")
522 ("-s") ("-H") ("-p" "Password:")))
523 (tramp-remote-sh "/bin/sh")
524 (tramp-copy-program nil)
525 (tramp-copy-args nil)
526 (tramp-copy-keep-date nil)
527 (tramp-password-end-of-line nil))
528 ("scpc" (tramp-login-program "ssh")
529 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
530 ("-o" "ControlPath=%t.%%r@%%h:%%p")
531 ("-o" "ControlMaster=yes")
532 ("-e" "none")))
533 (tramp-remote-sh "/bin/sh")
534 (tramp-copy-program "scp")
535 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
536 ("-o" "ControlPath=%t.%%r@%%h:%%p")
537 ("-o" "ControlMaster=auto")))
538 (tramp-copy-keep-date t)
539 (tramp-password-end-of-line nil)
540 (tramp-gw-args (("-o"
541 "GlobalKnownHostsFile=/dev/null")
542 ("-o" "UserKnownHostsFile=/dev/null")
543 ("-o" "StrictHostKeyChecking=no")))
544 (tramp-default-port 22))
545 ("scpx" (tramp-login-program "ssh")
546 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
547 ("-e" "none" "-t" "-t" "/bin/sh")))
548 (tramp-remote-sh "/bin/sh")
549 (tramp-copy-program "scp")
550 (tramp-copy-args (("-p" "%k")))
551 (tramp-copy-keep-date t)
552 (tramp-password-end-of-line nil)
553 (tramp-gw-args (("-o"
554 "GlobalKnownHostsFile=/dev/null")
555 ("-o" "UserKnownHostsFile=/dev/null")
556 ("-o" "StrictHostKeyChecking=no")))
557 (tramp-default-port 22))
558 ("sshx" (tramp-login-program "ssh")
559 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
560 ("-e" "none" "-t" "-t" "/bin/sh")))
561 (tramp-remote-sh "/bin/sh")
562 (tramp-copy-program nil)
563 (tramp-copy-args nil)
564 (tramp-copy-keep-date nil)
565 (tramp-password-end-of-line nil)
566 (tramp-gw-args (("-o"
567 "GlobalKnownHostsFile=/dev/null")
568 ("-o" "UserKnownHostsFile=/dev/null")
569 ("-o" "StrictHostKeyChecking=no")))
570 (tramp-default-port 22))
571 ("krlogin"
572 (tramp-login-program "krlogin")
573 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
574 (tramp-remote-sh "/bin/sh")
575 (tramp-copy-program nil)
576 (tramp-copy-args nil)
577 (tramp-copy-keep-date nil)
578 (tramp-password-end-of-line nil))
579 ("plink" (tramp-login-program "plink")
580 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
581 ("-ssh")))
582 (tramp-remote-sh "/bin/sh")
583 (tramp-copy-program nil)
584 (tramp-copy-args nil)
585 (tramp-copy-keep-date nil)
586 (tramp-password-end-of-line "xy") ;see docstring for "xy"
587 (tramp-default-port 22))
588 ("plink1"
589 (tramp-login-program "plink")
590 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
591 ("-1" "-ssh")))
592 (tramp-remote-sh "/bin/sh")
593 (tramp-copy-program nil)
594 (tramp-copy-args nil)
595 (tramp-copy-keep-date nil)
596 (tramp-password-end-of-line "xy") ;see docstring for "xy"
597 (tramp-default-port 22))
598 ("plinkx"
599 (tramp-login-program "plink")
600 ;; ("%h") must be a single element, see
601 ;; `tramp-compute-multi-hops'.
602 (tramp-login-args (("-load") ("%h") ("-t")
603 (,(format
604 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
605 tramp-terminal-type
606 tramp-initial-end-of-output))
607 ("/bin/sh")))
608 (tramp-remote-sh "/bin/sh")
609 (tramp-copy-program nil)
610 (tramp-copy-args nil)
611 (tramp-copy-keep-date nil)
612 (tramp-password-end-of-line nil))
613 ("pscp" (tramp-login-program "plink")
614 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
615 ("-ssh")))
616 (tramp-remote-sh "/bin/sh")
617 (tramp-copy-program "pscp")
618 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
619 (tramp-copy-keep-date t)
620 (tramp-password-end-of-line "xy") ;see docstring for "xy"
621 (tramp-default-port 22))
622 ("psftp" (tramp-login-program "plink")
623 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
624 ("-ssh")))
625 (tramp-remote-sh "/bin/sh")
626 (tramp-copy-program "pscp")
627 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
628 (tramp-copy-keep-date t)
629 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
630 ("fcp" (tramp-login-program "fsh")
631 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
632 (tramp-remote-sh "/bin/sh -i")
633 (tramp-copy-program "fcp")
634 (tramp-copy-args (("-p" "%k")))
635 (tramp-copy-keep-date t)
636 (tramp-password-end-of-line nil)))
637 "*Alist of methods for remote files.
638 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
639 Each NAME stands for a remote access method. Each PARAM is a
640 pair of the form (KEY VALUE). The following KEYs are defined:
641 * `tramp-remote-sh'
642 This specifies the Bourne shell to use on the remote host. This
643 MUST be a Bourne-like shell. It is normally not necessary to set
644 this to any value other than \"/bin/sh\": Tramp wants to use a shell
645 which groks tilde expansion, but it can search for it. Also note
646 that \"/bin/sh\" exists on all Unixen, this might not be true for
647 the value that you decide to use. You Have Been Warned.
648 * `tramp-login-program'
649 This specifies the name of the program to use for logging in to the
650 remote host. This may be the name of rsh or a workalike program,
651 or the name of telnet or a workalike, or the name of su or a workalike.
652 * `tramp-login-args'
653 This specifies the list of arguments to pass to the above
654 mentioned program. Please note that this is a list of list of arguments,
655 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
656 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
657 There are some patterns: \"%h\" in this list is replaced by the host
658 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
659 port number, and \"%%\" can be used to obtain a literal percent character.
660 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
661 expansion (i.e. no host or no user specified), this list is not used as
662 argument. By this, arguments like (\"-l\" \"%u\") are optional.
663 \"%t\" is replaced by the temporary file name produced with
664 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
665 parameter of a program, if exists.
666 * `tramp-copy-program'
667 This specifies the name of the program to use for remotely copying
668 the file; this might be the absolute filename of rcp or the name of
669 a workalike program.
670 * `tramp-copy-args'
671 This specifies the list of parameters to pass to the above mentioned
672 program, the hints for `tramp-login-args' also apply here.
673 * `tramp-copy-keep-date'
674 This specifies whether the copying program when the preserves the
675 timestamp of the original file.
676 * `tramp-copy-keep-tmpfile'
677 This specifies whether a temporary local file shall be kept
678 for optimization reasons (useful for \"rsync\" methods).
679 * `tramp-copy-recursive'
680 Whether the operation copies directories recursively.
681 * `tramp-default-port'
682 The default port of a method is needed in case of gateway connections.
683 Additionally, it is used as indication which method is prepared for
684 passing gateways.
685 * `tramp-gw-args'
686 As the attribute name says, additional arguments are specified here
687 when a method is applied via a gateway.
688 * `tramp-password-end-of-line'
689 This specifies the string to use for terminating the line after
690 submitting the password. If this method parameter is nil, then the
691 value of the normal variable `tramp-default-password-end-of-line'
692 is used. This parameter is necessary because the \"plink\" program
693 requires any two characters after sending the password. These do
694 not have to be newline or carriage return characters. Other login
695 programs are happy with just one character, the newline character.
696 We use \"xy\" as the value for methods using \"plink\".
698 What does all this mean? Well, you should specify `tramp-login-program'
699 for all methods; this program is used to log in to the remote site. Then,
700 there are two ways to actually transfer the files between the local and the
701 remote side. One way is using an additional rcp-like program. If you want
702 to do this, set `tramp-copy-program' in the method.
704 Another possibility for file transfer is inline transfer, i.e. the
705 file is passed through the same buffer used by `tramp-login-program'. In
706 this case, the file contents need to be protected since the
707 `tramp-login-program' might use escape codes or the connection might not
708 be eight-bit clean. Therefore, file contents are encoded for transit.
709 See the variables `tramp-local-coding-commands' and
710 `tramp-remote-coding-commands' for details.
712 So, to summarize: if the method is an out-of-band method, then you
713 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
714 inline method, then these two parameters should be nil. Methods which
715 are fit for gateways must have `tramp-default-port' at least.
717 Notes:
719 When using `su' or `sudo' the phrase `open connection to a remote
720 host' sounds strange, but it is used nevertheless, for consistency.
721 No connection is opened to a remote host, but `su' or `sudo' is
722 started on the local host. You should specify a remote host
723 `localhost' or the name of the local host. Another host name is
724 useful only in combination with `tramp-default-proxies-alist'.")
726 (defcustom tramp-default-method
727 ;; An external copy method seems to be preferred, because it is much
728 ;; more performant for large files, and it hasn't too serious delays
729 ;; for small files. But it must be ensured that there aren't
730 ;; permanent password queries. Either a password agent like
731 ;; "ssh-agent" or "Pageant" shall run, or the optional
732 ;; password-cache.el or auth-sources.el packages shall be active for
733 ;; password caching. "scpc" would be another good choice because of
734 ;; the "ControlMaster" option, but this is a more modern alternative
735 ;; in OpenSSH 4, which cannot be taken as default.
736 (cond
737 ;; PuTTY is installed.
738 ((executable-find "pscp")
739 (if (or (fboundp 'password-read)
740 (fboundp 'auth-source-user-or-password)
741 ;; Pageant is running.
742 (tramp-compat-process-running-p "Pageant"))
743 "pscp"
744 "plink"))
745 ;; There is an ssh installation.
746 ((executable-find "scp")
747 (if (or (fboundp 'password-read)
748 (fboundp 'auth-source-user-or-password)
749 ;; ssh-agent is running.
750 (getenv "SSH_AUTH_SOCK")
751 (getenv "SSH_AGENT_PID"))
752 "scp"
753 "ssh"))
754 ;; Fallback.
755 (t "ftp"))
756 "*Default method to use for transferring files.
757 See `tramp-methods' for possibilities.
758 Also see `tramp-default-method-alist'."
759 :group 'tramp
760 :type 'string)
762 (defcustom tramp-default-method-alist
763 '(("\\`localhost\\'" "\\`root\\'" "su"))
764 "*Default method to use for specific host/user pairs.
765 This is an alist of items (HOST USER METHOD). The first matching item
766 specifies the method to use for a file name which does not specify a
767 method. HOST and USER are regular expressions or nil, which is
768 interpreted as a regular expression which always matches. If no entry
769 matches, the variable `tramp-default-method' takes effect.
771 If the file name does not specify the user, lookup is done using the
772 empty string for the user name.
774 See `tramp-methods' for a list of possibilities for METHOD."
775 :group 'tramp
776 :type '(repeat (list (regexp :tag "Host regexp")
777 (regexp :tag "User regexp")
778 (string :tag "Method"))))
780 (defcustom tramp-default-user
782 "*Default user to use for transferring files.
783 It is nil by default; otherwise settings in configuration files like
784 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
786 This variable is regarded as obsolete, and will be removed soon."
787 :group 'tramp
788 :type '(choice (const nil) string))
790 (defcustom tramp-default-user-alist
791 `(("\\`su\\(do\\)?\\'" nil "root")
792 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
793 nil ,(user-login-name)))
794 "*Default user to use for specific method/host pairs.
795 This is an alist of items (METHOD HOST USER). The first matching item
796 specifies the user to use for a file name which does not specify a
797 user. METHOD and USER are regular expressions or nil, which is
798 interpreted as a regular expression which always matches. If no entry
799 matches, the variable `tramp-default-user' takes effect.
801 If the file name does not specify the method, lookup is done using the
802 empty string for the method name."
803 :group 'tramp
804 :type '(repeat (list (regexp :tag "Method regexp")
805 (regexp :tag "Host regexp")
806 (string :tag "User"))))
808 (defcustom tramp-default-host
809 (system-name)
810 "*Default host to use for transferring files.
811 Useful for su and sudo methods mostly."
812 :group 'tramp
813 :type 'string)
815 (defcustom tramp-default-proxies-alist nil
816 "*Route to be followed for specific host/user pairs.
817 This is an alist of items (HOST USER PROXY). The first matching
818 item specifies the proxy to be passed for a file name located on
819 a remote target matching USER@HOST. HOST and USER are regular
820 expressions. PROXY must be a Tramp filename without a localname
821 part. Method and user name on PROXY are optional, which is
822 interpreted with the default values. PROXY can contain the
823 patterns %h and %u, which are replaced by the strings matching
824 HOST or USER, respectively.
826 HOST, USER or PROXY could also be Lisp forms, which will be
827 evaluated. The result must be a string or nil, which is
828 interpreted as a regular expression which always matches."
829 :group 'tramp
830 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
831 (choice :tag "User regexp" regexp sexp)
832 (choice :tag "Proxy remote name" string (const nil)))))
834 (defconst tramp-local-host-regexp
835 (concat
836 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
837 "*Host names which are regarded as local host.")
839 (defconst tramp-completion-function-alist-rsh
840 '((tramp-parse-rhosts "/etc/hosts.equiv")
841 (tramp-parse-rhosts "~/.rhosts"))
842 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
844 (defconst tramp-completion-function-alist-ssh
845 '((tramp-parse-rhosts "/etc/hosts.equiv")
846 (tramp-parse-rhosts "/etc/shosts.equiv")
847 (tramp-parse-shosts "/etc/ssh_known_hosts")
848 (tramp-parse-sconfig "/etc/ssh_config")
849 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
850 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
851 (tramp-parse-rhosts "~/.rhosts")
852 (tramp-parse-rhosts "~/.shosts")
853 (tramp-parse-shosts "~/.ssh/known_hosts")
854 (tramp-parse-sconfig "~/.ssh/config")
855 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
856 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
857 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
859 (defconst tramp-completion-function-alist-telnet
860 '((tramp-parse-hosts "/etc/hosts"))
861 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
863 (defconst tramp-completion-function-alist-su
864 '((tramp-parse-passwd "/etc/passwd"))
865 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
867 (defconst tramp-completion-function-alist-putty
868 '((tramp-parse-putty
869 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
870 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
872 (defvar tramp-completion-function-alist nil
873 "*Alist of methods for remote files.
874 This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
875 Each NAME stands for a remote access method. Each PAIR is of the form
876 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
877 names from FILE for completion. The following predefined FUNCTIONs exists:
879 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
880 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
881 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
882 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
883 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
884 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
885 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
886 * `tramp-parse-netrc' for \"~/.netrc\" like files.
887 * `tramp-parse-putty' for PuTTY registry keys.
889 FUNCTION can also be a customer defined function. For more details see
890 the info pages.")
892 (eval-after-load "tramp"
893 '(progn
894 (tramp-set-completion-function
895 "rcp" tramp-completion-function-alist-rsh)
896 (tramp-set-completion-function
897 "scp" tramp-completion-function-alist-ssh)
898 (tramp-set-completion-function
899 "scp1" tramp-completion-function-alist-ssh)
900 (tramp-set-completion-function
901 "scp2" tramp-completion-function-alist-ssh)
902 (tramp-set-completion-function
903 "scp1_old" tramp-completion-function-alist-ssh)
904 (tramp-set-completion-function
905 "scp2_old" tramp-completion-function-alist-ssh)
906 (tramp-set-completion-function
907 "rsync" tramp-completion-function-alist-ssh)
908 (tramp-set-completion-function
909 "rsyncc" tramp-completion-function-alist-ssh)
910 (tramp-set-completion-function
911 "remcp" tramp-completion-function-alist-rsh)
912 (tramp-set-completion-function
913 "rsh" tramp-completion-function-alist-rsh)
914 (tramp-set-completion-function
915 "ssh" tramp-completion-function-alist-ssh)
916 (tramp-set-completion-function
917 "ssh1" tramp-completion-function-alist-ssh)
918 (tramp-set-completion-function
919 "ssh2" tramp-completion-function-alist-ssh)
920 (tramp-set-completion-function
921 "ssh1_old" tramp-completion-function-alist-ssh)
922 (tramp-set-completion-function
923 "ssh2_old" tramp-completion-function-alist-ssh)
924 (tramp-set-completion-function
925 "remsh" tramp-completion-function-alist-rsh)
926 (tramp-set-completion-function
927 "telnet" tramp-completion-function-alist-telnet)
928 (tramp-set-completion-function
929 "su" tramp-completion-function-alist-su)
930 (tramp-set-completion-function
931 "sudo" tramp-completion-function-alist-su)
932 (tramp-set-completion-function
933 "scpx" tramp-completion-function-alist-ssh)
934 (tramp-set-completion-function
935 "sshx" tramp-completion-function-alist-ssh)
936 (tramp-set-completion-function
937 "krlogin" tramp-completion-function-alist-rsh)
938 (tramp-set-completion-function
939 "plink" tramp-completion-function-alist-ssh)
940 (tramp-set-completion-function
941 "plink1" tramp-completion-function-alist-ssh)
942 (tramp-set-completion-function
943 "plinkx" tramp-completion-function-alist-putty)
944 (tramp-set-completion-function
945 "pscp" tramp-completion-function-alist-ssh)
946 (tramp-set-completion-function
947 "fcp" tramp-completion-function-alist-ssh)))
949 (defconst tramp-echo-mark-marker "_echo"
950 "String marker to surround echoed commands.")
952 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
953 "String length of `tramp-echo-mark-marker'.")
955 (defconst tramp-echo-mark
956 (concat tramp-echo-mark-marker
957 (make-string tramp-echo-mark-marker-length ?\b))
958 "String mark to be transmitted around shell commands.
959 Used to separate their echo from the output they produce. This
960 will only be used if we cannot disable remote echo via stty.
961 This string must have no effect on the remote shell except for
962 producing some echo which can later be detected by
963 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
964 followed by an equal number of backspaces to erase them will
965 usually suffice.")
967 (defconst tramp-echoed-echo-mark-regexp
968 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
969 tramp-echo-mark-marker tramp-echo-mark-marker-length)
970 "Regexp which matches `tramp-echo-mark' as it gets echoed by
971 the remote shell.")
973 (defcustom tramp-rsh-end-of-line "\n"
974 "*String used for end of line in rsh connections.
975 I don't think this ever needs to be changed, so please tell me about it
976 if you need to change this.
977 Also see the method parameter `tramp-password-end-of-line' and the normal
978 variable `tramp-default-password-end-of-line'."
979 :group 'tramp
980 :type 'string)
982 (defcustom tramp-default-password-end-of-line
983 tramp-rsh-end-of-line
984 "*String used for end of line after sending a password.
985 This variable provides the default value for the method parameter
986 `tramp-password-end-of-line', see `tramp-methods' for more details.
988 It seems that people using plink under Windows need to send
989 \"\\r\\n\" (carriage-return, then newline) after a password, but just
990 \"\\n\" after all other lines. This variable can be used for the
991 password, see `tramp-rsh-end-of-line' for the other cases.
993 The default value is to use the same value as `tramp-rsh-end-of-line'."
994 :group 'tramp
995 :type 'string)
997 ;; "getconf PATH" yields:
998 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
999 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
1000 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1001 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1002 (defcustom tramp-remote-path
1003 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1004 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1005 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1006 "*List of directories to search for executables on remote host.
1007 For every remote host, this variable will be set buffer local,
1008 keeping the list of existing directories on that host.
1010 You can use `~' in this list, but when searching for a shell which groks
1011 tilde expansion, all directory names starting with `~' will be ignored.
1013 `Default Directories' represent the list of directories given by
1014 the command \"getconf PATH\". It is recommended to use this
1015 entry on top of this list, because these are the default
1016 directories for POSIX compatible commands.
1018 `Private Directories' are the settings of the $PATH environment,
1019 as given in your `~/.profile'."
1020 :group 'tramp
1021 :type '(repeat (choice
1022 (const :tag "Default Directories" tramp-default-remote-path)
1023 (const :tag "Private Directories" tramp-own-remote-path)
1024 (string :tag "Directory"))))
1026 (defcustom tramp-remote-process-environment
1027 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1028 ,(concat "TERM=" tramp-terminal-type)
1029 "EMACS=t" ;; Deprecated.
1030 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
1031 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1032 "autocorrect=" "correct=")
1034 "*List of environment variables to be set on the remote host.
1036 Each element should be a string of the form ENVVARNAME=VALUE. An
1037 entry ENVVARNAME= diables the corresponding environment variable,
1038 which might have been set in the init files like ~/.profile.
1040 Special handling is applied to the PATH environment, which should
1041 not be set here. Instead of, it should be set via `tramp-remote-path'."
1042 :group 'tramp
1043 :type '(repeat string))
1045 (defcustom tramp-login-prompt-regexp
1046 ".*ogin\\( .*\\)?: *"
1047 "*Regexp matching login-like prompts.
1048 The regexp should match at end of buffer.
1050 Sometimes the prompt is reported to look like \"login as:\"."
1051 :group 'tramp
1052 :type 'regexp)
1054 (defcustom tramp-shell-prompt-pattern
1055 ;; Allow a prompt to start right after a ^M since it indeed would be
1056 ;; displayed at the beginning of the line (and Zsh uses it).
1057 "\\(?:^\\|\r\\)[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
1058 "Regexp to match prompts from remote shell.
1059 Normally, Tramp expects you to configure `shell-prompt-pattern'
1060 correctly, but sometimes it happens that you are connecting to a
1061 remote host which sends a different kind of shell prompt. Therefore,
1062 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1063 and also things matched by this variable. The default value of this
1064 variable is similar to the default value of `shell-prompt-pattern',
1065 which should work well in many cases.
1067 This regexp must match both `tramp-initial-end-of-output' and
1068 `tramp-end-of-output'."
1069 :group 'tramp
1070 :type 'regexp)
1072 (defcustom tramp-password-prompt-regexp
1073 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1074 "*Regexp matching password-like prompts.
1075 The regexp should match at end of buffer.
1077 The `sudo' program appears to insert a `^@' character into the prompt."
1078 :group 'tramp
1079 :type 'regexp)
1081 (defcustom tramp-wrong-passwd-regexp
1082 (concat "^.*"
1083 ;; These strings should be on the last line
1084 (regexp-opt '("Permission denied"
1085 "Login incorrect"
1086 "Login Incorrect"
1087 "Connection refused"
1088 "Connection closed"
1089 "Timeout, server not responding."
1090 "Sorry, try again."
1091 "Name or service not known"
1092 "Host key verification failed."
1093 "No supported authentication methods left to try!") t)
1094 ".*"
1095 "\\|"
1096 "^.*\\("
1097 ;; Here comes a list of regexes, separated by \\|
1098 "Received signal [0-9]+"
1099 "\\).*")
1100 "*Regexp matching a `login failed' message.
1101 The regexp should match at end of buffer."
1102 :group 'tramp
1103 :type 'regexp)
1105 (defcustom tramp-yesno-prompt-regexp
1106 (concat
1107 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1108 "\\s-*")
1109 "Regular expression matching all yes/no queries which need to be confirmed.
1110 The confirmation should be done with yes or no.
1111 The regexp should match at end of buffer.
1112 See also `tramp-yn-prompt-regexp'."
1113 :group 'tramp
1114 :type 'regexp)
1116 (defcustom tramp-yn-prompt-regexp
1117 (concat
1118 (regexp-opt '("Store key in cache? (y/n)"
1119 "Update cached key? (y/n, Return cancels connection)") t)
1120 "\\s-*")
1121 "Regular expression matching all y/n queries which need to be confirmed.
1122 The confirmation should be done with y or n.
1123 The regexp should match at end of buffer.
1124 See also `tramp-yesno-prompt-regexp'."
1125 :group 'tramp
1126 :type 'regexp)
1128 (defcustom tramp-terminal-prompt-regexp
1129 (concat "\\("
1130 "TERM = (.*)"
1131 "\\|"
1132 "Terminal type\\? \\[.*\\]"
1133 "\\)\\s-*")
1134 "Regular expression matching all terminal setting prompts.
1135 The regexp should match at end of buffer.
1136 The answer will be provided by `tramp-action-terminal', which see."
1137 :group 'tramp
1138 :type 'regexp)
1140 (defcustom tramp-operation-not-permitted-regexp
1141 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1142 (regexp-opt '("Operation not permitted") t))
1143 "Regular expression matching keep-date problems in (s)cp operations.
1144 Copying has been performed successfully already, so this message can
1145 be ignored safely."
1146 :group 'tramp
1147 :type 'regexp)
1149 (defcustom tramp-copy-failed-regexp
1150 (concat "\\(.+: "
1151 (regexp-opt '("Permission denied"
1152 "not a regular file"
1153 "is a directory"
1154 "No such file or directory") t)
1155 "\\)\\s-*")
1156 "Regular expression matching copy problems in (s)cp operations."
1157 :group 'tramp
1158 :type 'regexp)
1160 (defcustom tramp-process-alive-regexp
1162 "Regular expression indicating a process has finished.
1163 In fact this expression is empty by intention, it will be used only to
1164 check regularly the status of the associated process.
1165 The answer will be provided by `tramp-action-process-alive',
1166 `tramp-action-out-of-band', which see."
1167 :group 'tramp
1168 :type 'regexp)
1170 (defcustom tramp-temp-name-prefix "tramp."
1171 "*Prefix to use for temporary files.
1172 If this is a relative file name (such as \"tramp.\"), it is considered
1173 relative to the directory name returned by the function
1174 `tramp-compat-temporary-file-directory' (which see). It may also be an
1175 absolute file name; don't forget to include a prefix for the filename
1176 part, though."
1177 :group 'tramp
1178 :type 'string)
1180 (defconst tramp-temp-buffer-name " *tramp temp*"
1181 "Buffer name for a temporary buffer.
1182 It shall be used in combination with `generate-new-buffer-name'.")
1184 (defvar tramp-temp-buffer-file-name nil
1185 "File name of a persistent local temporary file.
1186 Useful for \"rsync\" like methods.")
1187 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1189 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1190 "*Alist specifying extra arguments to pass to the remote shell.
1191 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1192 matching the shell file name and ARGS is a string specifying the
1193 arguments.
1195 This variable is only used when Tramp needs to start up another shell
1196 for tilde expansion. The extra arguments should typically prevent the
1197 shell from reading its init file."
1198 :group 'tramp
1199 ;; This might be the wrong way to test whether the widget type
1200 ;; `alist' is available. Who knows the right way to test it?
1201 :type (if (get 'alist 'widget-type)
1202 '(alist :key-type string :value-type string)
1203 '(repeat (cons string string))))
1205 ;; XEmacs is distributed with few Lisp packages. Further packages are
1206 ;; installed using EFS. If we use a unified filename format, then
1207 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1208 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1209 ;; just like before.) Another reason for using a separate filename
1210 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1211 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1212 ;; the other places.
1214 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1215 ;;;###autoload
1216 (defcustom tramp-syntax
1217 (if (featurep 'xemacs) 'sep 'ftp)
1218 "Tramp filename syntax to be used.
1220 It can have the following values:
1222 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1223 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1224 'url -- URL-like syntax."
1225 :group 'tramp
1226 :type (if (featurep 'xemacs)
1227 '(choice (const :tag "EFS" ftp)
1228 (const :tag "XEmacs" sep)
1229 (const :tag "URL" url))
1230 '(choice (const :tag "Ange-FTP" ftp)
1231 (const :tag "URL" url))))
1233 (defconst tramp-prefix-format
1234 (cond ((equal tramp-syntax 'ftp) "/")
1235 ((equal tramp-syntax 'sep) "/[")
1236 ((equal tramp-syntax 'url) "/")
1237 (t (error "Wrong `tramp-syntax' defined")))
1238 "*String matching the very beginning of Tramp file names.
1239 Used in `tramp-make-tramp-file-name'.")
1241 (defconst tramp-prefix-regexp
1242 (concat "^" (regexp-quote tramp-prefix-format))
1243 "*Regexp matching the very beginning of Tramp file names.
1244 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1246 (defconst tramp-method-regexp
1247 "[a-zA-Z_0-9-]+"
1248 "*Regexp matching methods identifiers.")
1250 (defconst tramp-postfix-method-format
1251 (cond ((equal tramp-syntax 'ftp) ":")
1252 ((equal tramp-syntax 'sep) "/")
1253 ((equal tramp-syntax 'url) "://")
1254 (t (error "Wrong `tramp-syntax' defined")))
1255 "*String matching delimeter between method and user or host names.
1256 Used in `tramp-make-tramp-file-name'.")
1258 (defconst tramp-postfix-method-regexp
1259 (regexp-quote tramp-postfix-method-format)
1260 "*Regexp matching delimeter between method and user or host names.
1261 Derived from `tramp-postfix-method-format'.")
1263 (defconst tramp-user-regexp
1264 "[^:/ \t]+"
1265 "*Regexp matching user names.")
1267 (defconst tramp-prefix-domain-format "%"
1268 "*String matching delimeter between user and domain names.")
1270 (defconst tramp-prefix-domain-regexp
1271 (regexp-quote tramp-prefix-domain-format)
1272 "*Regexp matching delimeter between user and domain names.
1273 Derived from `tramp-prefix-domain-format'.")
1275 (defconst tramp-domain-regexp
1276 "[-a-zA-Z0-9_.]+"
1277 "*Regexp matching domain names.")
1279 (defconst tramp-user-with-domain-regexp
1280 (concat "\\(" tramp-user-regexp "\\)"
1281 tramp-prefix-domain-regexp
1282 "\\(" tramp-domain-regexp "\\)")
1283 "*Regexp matching user names with domain names.")
1285 (defconst tramp-postfix-user-format
1287 "*String matching delimeter between user and host names.
1288 Used in `tramp-make-tramp-file-name'.")
1290 (defconst tramp-postfix-user-regexp
1291 (regexp-quote tramp-postfix-user-format)
1292 "*Regexp matching delimeter between user and host names.
1293 Derived from `tramp-postfix-user-format'.")
1295 (defconst tramp-host-regexp
1296 "[a-zA-Z0-9_.-]+"
1297 "*Regexp matching host names.")
1299 (defconst tramp-prefix-ipv6-format
1300 (cond ((equal tramp-syntax 'ftp) "[")
1301 ((equal tramp-syntax 'sep) "")
1302 ((equal tramp-syntax 'url) "[")
1303 (t (error "Wrong `tramp-syntax' defined")))
1304 "*String matching left hand side of IPv6 addresses.
1305 Used in `tramp-make-tramp-file-name'.")
1307 (defconst tramp-prefix-ipv6-regexp
1308 (regexp-quote tramp-prefix-ipv6-format)
1309 "*Regexp matching left hand side of IPv6 addresses.
1310 Derived from `tramp-prefix-ipv6-format'.")
1312 ;; The following regexp is a bit sloppy. But it shall serve our
1313 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1314 ;; "::ffff:192.168.0.1".
1315 (defconst tramp-ipv6-regexp
1316 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1317 "*Regexp matching IPv6 addresses.")
1319 (defconst tramp-postfix-ipv6-format
1320 (cond ((equal tramp-syntax 'ftp) "]")
1321 ((equal tramp-syntax 'sep) "")
1322 ((equal tramp-syntax 'url) "]")
1323 (t (error "Wrong `tramp-syntax' defined")))
1324 "*String matching right hand side of IPv6 addresses.
1325 Used in `tramp-make-tramp-file-name'.")
1327 (defconst tramp-postfix-ipv6-regexp
1328 (regexp-quote tramp-postfix-ipv6-format)
1329 "*Regexp matching right hand side of IPv6 addresses.
1330 Derived from `tramp-postfix-ipv6-format'.")
1332 (defconst tramp-prefix-port-format
1333 (cond ((equal tramp-syntax 'ftp) "#")
1334 ((equal tramp-syntax 'sep) "#")
1335 ((equal tramp-syntax 'url) ":")
1336 (t (error "Wrong `tramp-syntax' defined")))
1337 "*String matching delimeter between host names and port numbers.")
1339 (defconst tramp-prefix-port-regexp
1340 (regexp-quote tramp-prefix-port-format)
1341 "*Regexp matching delimeter between host names and port numbers.
1342 Derived from `tramp-prefix-port-format'.")
1344 (defconst tramp-port-regexp
1345 "[0-9]+"
1346 "*Regexp matching port numbers.")
1348 (defconst tramp-host-with-port-regexp
1349 (concat "\\(" tramp-host-regexp "\\)"
1350 tramp-prefix-port-regexp
1351 "\\(" tramp-port-regexp "\\)")
1352 "*Regexp matching host names with port numbers.")
1354 (defconst tramp-postfix-host-format
1355 (cond ((equal tramp-syntax 'ftp) ":")
1356 ((equal tramp-syntax 'sep) "]")
1357 ((equal tramp-syntax 'url) "")
1358 (t (error "Wrong `tramp-syntax' defined")))
1359 "*String matching delimeter between host names and localnames.
1360 Used in `tramp-make-tramp-file-name'.")
1362 (defconst tramp-postfix-host-regexp
1363 (regexp-quote tramp-postfix-host-format)
1364 "*Regexp matching delimeter between host names and localnames.
1365 Derived from `tramp-postfix-host-format'.")
1367 (defconst tramp-localname-regexp
1368 ".*$"
1369 "*Regexp matching localnames.")
1371 ;; File name format.
1373 (defconst tramp-file-name-structure
1374 (list
1375 (concat
1376 tramp-prefix-regexp
1377 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1378 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1379 "\\(" "\\(" tramp-host-regexp
1380 "\\|"
1381 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1382 tramp-postfix-ipv6-regexp "\\)"
1383 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1384 tramp-postfix-host-regexp
1385 "\\(" tramp-localname-regexp "\\)")
1386 2 4 5 8)
1388 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1389 the Tramp file name structure.
1391 The first element REGEXP is a regular expression matching a Tramp file
1392 name. The regex should contain parentheses around the method name,
1393 the user name, the host name, and the file name parts.
1395 The second element METHOD is a number, saying which pair of
1396 parentheses matches the method name. The third element USER is
1397 similar, but for the user name. The fourth element HOST is similar,
1398 but for the host name. The fifth element FILE is for the file name.
1399 These numbers are passed directly to `match-string', which see. That
1400 means the opening parentheses are counted to identify the pair.
1402 See also `tramp-file-name-regexp'.")
1404 ;;;###autoload
1405 (defconst tramp-file-name-regexp-unified
1406 "\\`/\\([^[/:]+\\|[^/]+]\\):"
1407 "Value for `tramp-file-name-regexp' for unified remoting.
1408 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1409 Tramp. See `tramp-file-name-structure' for more explanations.")
1411 ;;;###autoload
1412 (defconst tramp-file-name-regexp-separate
1413 "\\`/\\[.*\\]"
1414 "Value for `tramp-file-name-regexp' for separate remoting.
1415 XEmacs uses a separate filename syntax for Tramp and EFS.
1416 See `tramp-file-name-structure' for more explanations.")
1418 ;;;###autoload
1419 (defconst tramp-file-name-regexp-url
1420 "\\`/[^/:]+://"
1421 "Value for `tramp-file-name-regexp' for URL-like remoting.
1422 See `tramp-file-name-structure' for more explanations.")
1424 ;;;###autoload
1425 (defconst tramp-file-name-regexp
1426 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1427 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1428 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1429 (t (error "Wrong `tramp-syntax' defined")))
1430 "*Regular expression matching file names handled by Tramp.
1431 This regexp should match Tramp file names but no other file names.
1432 \(When tramp.el is loaded, this regular expression is prepended to
1433 `file-name-handler-alist', and that is searched sequentially. Thus,
1434 if the Tramp entry appears rather early in the `file-name-handler-alist'
1435 and is a bit too general, then some files might be considered Tramp
1436 files which are not really Tramp files.
1438 Please note that the entry in `file-name-handler-alist' is made when
1439 this file (tramp.el) is loaded. This means that this variable must be set
1440 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1441 updated after changing this variable.
1443 Also see `tramp-file-name-structure'.")
1445 ;;;###autoload
1446 (defconst tramp-root-regexp
1447 (if (memq system-type '(cygwin windows-nt))
1448 "\\`\\([a-zA-Z]:\\)?/"
1449 "\\`/")
1450 "Beginning of an incomplete Tramp file name.
1451 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1452 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1454 ;;;###autoload
1455 (defconst tramp-completion-file-name-regexp-unified
1456 (concat tramp-root-regexp "[^/]*\\'")
1457 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1458 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1459 See `tramp-file-name-structure' for more explanations.")
1461 ;;;###autoload
1462 (defconst tramp-completion-file-name-regexp-separate
1463 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1464 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1465 XEmacs uses a separate filename syntax for Tramp and EFS.
1466 See `tramp-file-name-structure' for more explanations.")
1468 ;;;###autoload
1469 (defconst tramp-completion-file-name-regexp-url
1470 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1471 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1472 See `tramp-file-name-structure' for more explanations.")
1474 ;;;###autoload
1475 (defconst tramp-completion-file-name-regexp
1476 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1477 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1478 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1479 (t (error "Wrong `tramp-syntax' defined")))
1480 "*Regular expression matching file names handled by Tramp completion.
1481 This regexp should match partial Tramp file names only.
1483 Please note that the entry in `file-name-handler-alist' is made when
1484 this file (tramp.el) is loaded. This means that this variable must be set
1485 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1486 updated after changing this variable.
1488 Also see `tramp-file-name-structure'.")
1490 (defconst tramp-actions-before-shell
1491 '((tramp-login-prompt-regexp tramp-action-login)
1492 (tramp-password-prompt-regexp tramp-action-password)
1493 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1494 (shell-prompt-pattern tramp-action-succeed)
1495 (tramp-shell-prompt-pattern tramp-action-succeed)
1496 (tramp-yesno-prompt-regexp tramp-action-yesno)
1497 (tramp-yn-prompt-regexp tramp-action-yn)
1498 (tramp-terminal-prompt-regexp tramp-action-terminal)
1499 (tramp-process-alive-regexp tramp-action-process-alive))
1500 "List of pattern/action pairs.
1501 Whenever a pattern matches, the corresponding action is performed.
1502 Each item looks like (PATTERN ACTION).
1504 The PATTERN should be a symbol, a variable. The value of this
1505 variable gives the regular expression to search for. Note that the
1506 regexp must match at the end of the buffer, \"\\'\" is implicitly
1507 appended to it.
1509 The ACTION should also be a symbol, but a function. When the
1510 corresponding PATTERN matches, the ACTION function is called.")
1512 (defconst tramp-actions-copy-out-of-band
1513 '((tramp-password-prompt-regexp tramp-action-password)
1514 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1515 (tramp-copy-failed-regexp tramp-action-permission-denied)
1516 (tramp-process-alive-regexp tramp-action-out-of-band))
1517 "List of pattern/action pairs.
1518 This list is used for copying/renaming with out-of-band methods.
1520 See `tramp-actions-before-shell' for more info.")
1522 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1523 ;; known to have a bug in `process-send-string'; some ssh connections appear
1524 ;; to drop bytes when data is sent too quickly. There is also a connection
1525 ;; buffer local variable, which is computed depending on remote host properties
1526 ;; when `tramp-chunksize' is zero or nil.
1527 (defcustom tramp-chunksize
1528 (when (and (not (featurep 'xemacs))
1529 (memq system-type '(hpux)))
1530 500)
1531 ;; Parentheses in docstring starting at beginning of line are escaped.
1532 ;; Fontification is messed up when
1533 ;; `open-paren-in-column-0-is-defun-start' set to t.
1534 "*If non-nil, chunksize for sending input to local process.
1535 It is necessary only on systems which have a buggy `process-send-string'
1536 implementation. The necessity, whether this variable must be set, can be
1537 checked via the following code:
1539 (with-temp-buffer
1540 (let* ((user \"xxx\") (host \"yyy\")
1541 (init 0) (step 50)
1542 (sent init) (received init))
1543 (while (= sent received)
1544 (setq sent (+ sent step))
1545 (erase-buffer)
1546 (let ((proc (start-process (buffer-name) (current-buffer)
1547 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1548 (when (memq (process-status proc) '(run open))
1549 (process-send-string proc (make-string sent ?\\ ))
1550 (process-send-eof proc)
1551 (process-send-eof proc))
1552 (while (not (progn (goto-char (point-min))
1553 (re-search-forward \"\\\\w+\" (point-max) t)))
1554 (accept-process-output proc 1))
1555 (when (memq (process-status proc) '(run open))
1556 (setq received (string-to-number (match-string 0)))
1557 (delete-process proc)
1558 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1559 (sit-for 0))))
1560 (if (> sent (+ init step))
1561 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1562 (- sent step))
1563 (message \"Test does not work\")
1564 (display-buffer (current-buffer))
1565 (sit-for 30))))
1567 In the Emacs normally running Tramp, evaluate the above code
1568 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1569 respectively). You can do this, for example, by pasting it into
1570 the `*scratch*' buffer and then hitting C-j with the cursor after the
1571 last closing parenthesis. Note that it works only if you have configured
1572 \"ssh\" to run without password query, see ssh-agent(1).
1574 You will see the number of bytes sent successfully to the remote host.
1575 If that number exceeds 1000, you can stop the execution by hitting
1576 C-g, because your Emacs is likely clean.
1578 When it is necessary to set `tramp-chunksize', you might consider to
1579 use an out-of-the-band method (like \"scp\") instead of an internal one
1580 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
1581 performance.
1583 If your Emacs is buggy, the code stops and gives you an indication
1584 about the value `tramp-chunksize' should be set. Maybe you could just
1585 experiment a bit, e.g. changing the values of `init' and `step'
1586 in the third line of the code.
1588 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1589 this variable to be set as well."
1590 :group 'tramp
1591 :type '(choice (const nil) integer))
1593 ;; Logging in to a remote host normally requires obtaining a pty. But
1594 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1595 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1596 ;; for an override of the system default.
1597 (defcustom tramp-process-connection-type t
1598 "Overrides `process-connection-type' for connections from Tramp.
1599 Tramp binds process-connection-type to the value given here before
1600 opening a connection to a remote host."
1601 :group 'tramp
1602 :type '(choice (const nil) (const t) (const pty)))
1604 (defcustom tramp-completion-reread-directory-timeout 10
1605 "Defines seconds since last remote command before rereading a directory.
1606 A remote directory might have changed its contents. In order to
1607 make it visible during file name completion in the minibuffer,
1608 Tramp flushes its cache and rereads the directory contents when
1609 more than `tramp-completion-reread-directory-timeout' seconds
1610 have been gone since last remote command execution. A value of 0
1611 would require an immediate reread during filename completion, nil
1612 means to use always cached values for the directory contents."
1613 :group 'tramp
1614 :type '(choice (const nil) integer))
1616 ;;; Internal Variables:
1618 (defvar tramp-current-method nil
1619 "Connection method for this *tramp* buffer.")
1621 (defvar tramp-current-user nil
1622 "Remote login name for this *tramp* buffer.")
1624 (defvar tramp-current-host nil
1625 "Remote host for this *tramp* buffer.")
1627 (defconst tramp-uudecode
1628 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1629 cat /tmp/tramp.$$
1630 rm -f /tmp/tramp.$$"
1631 "Shell function to implement `uudecode' to standard output.
1632 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1633 for this or `uudecode -p', but some systems don't, and for them
1634 we have this shell function.")
1636 (defconst tramp-perl-file-truename
1637 "%s -e '
1638 use File::Spec;
1639 use Cwd \"realpath\";
1641 sub recursive {
1642 my ($volume, @dirs) = @_;
1643 my $real = realpath(File::Spec->catpath(
1644 $volume, File::Spec->catdir(@dirs), \"\"));
1645 if ($real) {
1646 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1647 return ($vol, File::Spec->splitdir($dir));
1649 else {
1650 my $last = pop(@dirs);
1651 ($volume, @dirs) = recursive($volume, @dirs);
1652 push(@dirs, $last);
1653 return ($volume, @dirs);
1657 $result = realpath($ARGV[0]);
1658 if (!$result) {
1659 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1660 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1662 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1665 if ($ARGV[0] =~ /\\/$/) {
1666 $result = $result . \"/\";
1669 print \"\\\"$result\\\"\\n\";
1670 ' \"$1\" 2>/dev/null"
1671 "Perl script to produce output suitable for use with `file-truename'
1672 on the remote file system.
1673 Escape sequence %s is replaced with name of Perl binary.
1674 This string is passed to `format', so percent characters need to be doubled.")
1676 (defconst tramp-perl-file-name-all-completions
1677 "%s -e 'sub case {
1678 my $str = shift;
1679 if ($ARGV[2]) {
1680 return lc($str);
1682 else {
1683 return $str;
1686 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1687 @files = readdir(d); closedir(d);
1688 foreach $f (@files) {
1689 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1690 if (-d \"$ARGV[0]/$f\") {
1691 print \"$f/\\n\";
1693 else {
1694 print \"$f\\n\";
1698 print \"ok\\n\"
1699 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1700 "Perl script to produce output suitable for use with
1701 `file-name-all-completions' on the remote file system. Escape
1702 sequence %s is replaced with name of Perl binary. This string is
1703 passed to `format', so percent characters need to be doubled.")
1705 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1706 ;; output. If you are hacking on this, note that you get *no* output
1707 ;; unless this spits out a complete line, including the '\n' at the
1708 ;; end.
1709 ;; The device number is returned as "-1", because there will be a virtual
1710 ;; device number set in `tramp-handle-file-attributes'.
1711 (defconst tramp-perl-file-attributes
1712 "%s -e '
1713 @stat = lstat($ARGV[0]);
1714 if (!@stat) {
1715 print \"nil\\n\";
1716 exit 0;
1718 if (($stat[2] & 0170000) == 0120000)
1720 $type = readlink($ARGV[0]);
1721 $type = \"\\\"$type\\\"\";
1723 elsif (($stat[2] & 0170000) == 040000)
1725 $type = \"t\";
1727 else
1729 $type = \"nil\"
1731 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1732 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1733 printf(
1734 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1735 $type,
1736 $stat[3],
1737 $uid,
1738 $gid,
1739 $stat[8] >> 16 & 0xffff,
1740 $stat[8] & 0xffff,
1741 $stat[9] >> 16 & 0xffff,
1742 $stat[9] & 0xffff,
1743 $stat[10] >> 16 & 0xffff,
1744 $stat[10] & 0xffff,
1745 $stat[7],
1746 $stat[2],
1747 $stat[1] >> 16 & 0xffff,
1748 $stat[1] & 0xffff
1749 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1750 "Perl script to produce output suitable for use with `file-attributes'
1751 on the remote file system.
1752 Escape sequence %s is replaced with name of Perl binary.
1753 This string is passed to `format', so percent characters need to be doubled.")
1755 (defconst tramp-perl-directory-files-and-attributes
1756 "%s -e '
1757 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1758 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1759 @list = readdir(DIR);
1760 closedir(DIR);
1761 $n = scalar(@list);
1762 printf(\"(\\n\");
1763 for($i = 0; $i < $n; $i++)
1765 $filename = $list[$i];
1766 @stat = lstat($filename);
1767 if (($stat[2] & 0170000) == 0120000)
1769 $type = readlink($filename);
1770 $type = \"\\\"$type\\\"\";
1772 elsif (($stat[2] & 0170000) == 040000)
1774 $type = \"t\";
1776 else
1778 $type = \"nil\"
1780 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1781 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1782 printf(
1783 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1784 $filename,
1785 $type,
1786 $stat[3],
1787 $uid,
1788 $gid,
1789 $stat[8] >> 16 & 0xffff,
1790 $stat[8] & 0xffff,
1791 $stat[9] >> 16 & 0xffff,
1792 $stat[9] & 0xffff,
1793 $stat[10] >> 16 & 0xffff,
1794 $stat[10] & 0xffff,
1795 $stat[7],
1796 $stat[2],
1797 $stat[1] >> 16 & 0xffff,
1798 $stat[1] & 0xffff,
1799 $stat[0] >> 16 & 0xffff,
1800 $stat[0] & 0xffff);
1802 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1803 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1804 output.
1805 Escape sequence %s is replaced with name of Perl binary.
1806 This string is passed to `format', so percent characters need to be doubled.")
1808 ;; ;; These two use uu encoding.
1809 ;; (defvar tramp-perl-encode "%s -e'\
1810 ;; print qq(begin 644 xxx\n);
1811 ;; my $s = q();
1812 ;; my $res = q();
1813 ;; while (read(STDIN, $s, 45)) {
1814 ;; print pack(q(u), $s);
1815 ;; }
1816 ;; print qq(`\n);
1817 ;; print qq(end\n);
1818 ;; '"
1819 ;; "Perl program to use for encoding a file.
1820 ;; Escape sequence %s is replaced with name of Perl binary.")
1822 ;; (defvar tramp-perl-decode "%s -ne '
1823 ;; print unpack q(u), $_;
1824 ;; '"
1825 ;; "Perl program to use for decoding a file.
1826 ;; Escape sequence %s is replaced with name of Perl binary.")
1828 ;; These two use base64 encoding.
1829 (defconst tramp-perl-encode-with-module
1830 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1831 "Perl program to use for encoding a file.
1832 Escape sequence %s is replaced with name of Perl binary.
1833 This string is passed to `format', so percent characters need to be doubled.
1834 This implementation requires the MIME::Base64 Perl module to be installed
1835 on the remote host.")
1837 (defconst tramp-perl-decode-with-module
1838 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1839 "Perl program to use for decoding a file.
1840 Escape sequence %s is replaced with name of Perl binary.
1841 This string is passed to `format', so percent characters need to be doubled.
1842 This implementation requires the MIME::Base64 Perl module to be installed
1843 on the remote host.")
1845 (defconst tramp-perl-encode
1846 "%s -e '
1847 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1848 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1849 # Free Software Foundation, Inc.
1850 use strict;
1852 my %%trans = do {
1853 my $i = 0;
1854 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1855 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1858 binmode(\\*STDIN);
1860 # We read in chunks of 54 bytes, to generate output lines
1861 # of 72 chars (plus end of line)
1862 $/ = \\54;
1864 while (my $data = <STDIN>) {
1865 my $pad = q();
1867 # Only for the last chunk, and only if did not fill the last three-byte packet
1868 if (eof) {
1869 my $mod = length($data) %% 3;
1870 $pad = q(=) x (3 - $mod) if $mod;
1873 # Not the fastest method, but it is simple: unpack to binary string, split
1874 # by groups of 6 bits and convert back from binary to byte; then map into
1875 # the translation table
1876 print
1877 join q(),
1878 map($trans{$_},
1879 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1880 $pad,
1881 qq(\\n);
1882 }' 2>/dev/null"
1883 "Perl program to use for encoding a file.
1884 Escape sequence %s is replaced with name of Perl binary.
1885 This string is passed to `format', so percent characters need to be doubled.")
1887 (defconst tramp-perl-decode
1888 "%s -e '
1889 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1890 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1891 # Free Software Foundation, Inc.
1892 use strict;
1894 my %%trans = do {
1895 my $i = 0;
1896 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1897 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1900 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1902 binmode(\\*STDOUT);
1904 # We are going to accumulate into $pending to accept any line length
1905 # (we do not check they are <= 76 chars as the RFC says)
1906 my $pending = q();
1908 while (my $data = <STDIN>) {
1909 chomp $data;
1911 # If we find one or two =, we have reached the end and
1912 # any following data is to be discarded
1913 my $finished = $data =~ s/(==?).*/$1/;
1914 $pending .= $data;
1916 my $len = length($pending);
1917 my $chunk = substr($pending, 0, $len & ~3);
1918 $pending = substr($pending, $len & ~3 + 1);
1920 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1921 # split in 8-bit chunks and convert back to char.
1922 print join q(),
1923 map $bytes{$_},
1924 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1926 last if $finished;
1927 }' 2>/dev/null"
1928 "Perl program to use for decoding a file.
1929 Escape sequence %s is replaced with name of Perl binary.
1930 This string is passed to `format', so percent characters need to be doubled.")
1932 (defconst tramp-vc-registered-read-file-names
1933 "echo \"(\"
1934 for file in \"$@\"; do
1935 if %s $file; then
1936 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1937 else
1938 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1940 if %s $file; then
1941 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1942 else
1943 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1945 done
1946 echo \")\""
1947 "Script to check existence of VC related files.
1948 It must be send formatted with two strings; the tests for file
1949 existence, and file readability.")
1951 (defconst tramp-file-mode-type-map
1952 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1953 (1 . "p") ; fifo
1954 (2 . "c") ; character device
1955 (3 . "m") ; multiplexed character device (v7)
1956 (4 . "d") ; directory
1957 (5 . "?") ; Named special file (XENIX)
1958 (6 . "b") ; block device
1959 (7 . "?") ; multiplexed block device (v7)
1960 (8 . "-") ; regular file
1961 (9 . "n") ; network special file (HP-UX)
1962 (10 . "l") ; symlink
1963 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1964 (12 . "s") ; socket
1965 (13 . "D") ; door special (Solaris)
1966 (14 . "w")) ; whiteout (BSD)
1967 "A list of file types returned from the `stat' system call.
1968 This is used to map a mode number to a permission string.")
1970 ;; New handlers should be added here. The following operations can be
1971 ;; handled using the normal primitives: file-name-sans-versions,
1972 ;; get-file-buffer.
1973 (defconst tramp-file-name-handler-alist
1974 '((load . tramp-handle-load)
1975 (make-symbolic-link . tramp-handle-make-symbolic-link)
1976 (file-name-as-directory . tramp-handle-file-name-as-directory)
1977 (file-name-directory . tramp-handle-file-name-directory)
1978 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1979 (file-truename . tramp-handle-file-truename)
1980 (file-exists-p . tramp-handle-file-exists-p)
1981 (file-directory-p . tramp-handle-file-directory-p)
1982 (file-executable-p . tramp-handle-file-executable-p)
1983 (file-readable-p . tramp-handle-file-readable-p)
1984 (file-regular-p . tramp-handle-file-regular-p)
1985 (file-symlink-p . tramp-handle-file-symlink-p)
1986 (file-writable-p . tramp-handle-file-writable-p)
1987 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1988 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1989 (file-attributes . tramp-handle-file-attributes)
1990 (file-modes . tramp-handle-file-modes)
1991 (directory-files . tramp-handle-directory-files)
1992 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1993 (file-name-all-completions . tramp-handle-file-name-all-completions)
1994 (file-name-completion . tramp-handle-file-name-completion)
1995 (add-name-to-file . tramp-handle-add-name-to-file)
1996 (copy-file . tramp-handle-copy-file)
1997 (copy-directory . tramp-handle-copy-directory)
1998 (rename-file . tramp-handle-rename-file)
1999 (set-file-modes . tramp-handle-set-file-modes)
2000 (set-file-times . tramp-handle-set-file-times)
2001 (make-directory . tramp-handle-make-directory)
2002 (delete-directory . tramp-handle-delete-directory)
2003 (delete-file . tramp-handle-delete-file)
2004 (directory-file-name . tramp-handle-directory-file-name)
2005 ;; `executable-find' is not official yet.
2006 (executable-find . tramp-handle-executable-find)
2007 (start-file-process . tramp-handle-start-file-process)
2008 (process-file . tramp-handle-process-file)
2009 (shell-command . tramp-handle-shell-command)
2010 (insert-directory . tramp-handle-insert-directory)
2011 (expand-file-name . tramp-handle-expand-file-name)
2012 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2013 (file-local-copy . tramp-handle-file-local-copy)
2014 (file-remote-p . tramp-handle-file-remote-p)
2015 (insert-file-contents . tramp-handle-insert-file-contents)
2016 (insert-file-contents-literally
2017 . tramp-handle-insert-file-contents-literally)
2018 (write-region . tramp-handle-write-region)
2019 (find-backup-file-name . tramp-handle-find-backup-file-name)
2020 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2021 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2022 (dired-compress-file . tramp-handle-dired-compress-file)
2023 (dired-recursive-delete-directory
2024 . tramp-handle-dired-recursive-delete-directory)
2025 (dired-uncache . tramp-handle-dired-uncache)
2026 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2027 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2028 (vc-registered . tramp-handle-vc-registered))
2029 "Alist of handler functions.
2030 Operations not mentioned here will be handled by the normal Emacs functions.")
2032 ;; Handlers for partial Tramp file names. For Emacs just
2033 ;; `file-name-all-completions' is needed.
2034 ;;;###autoload
2035 (defconst tramp-completion-file-name-handler-alist
2036 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2037 (file-name-completion . tramp-completion-handle-file-name-completion))
2038 "Alist of completion handler functions.
2039 Used for file names matching `tramp-file-name-regexp'. Operations not
2040 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2041 normal Emacs functions.")
2043 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2044 (defvar tramp-foreign-file-name-handler-alist
2045 ;; (identity . tramp-sh-file-name-handler) should always be the last
2046 ;; entry, because `identity' always matches.
2047 '((identity . tramp-sh-file-name-handler))
2048 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2049 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2050 calling HANDLER.")
2052 ;;; Internal functions which must come first:
2054 (defsubst tramp-debug-message (vec fmt-string &rest args)
2055 "Append message to debug buffer.
2056 Message is formatted with FMT-STRING as control string and the remaining
2057 ARGS to actually emit the message (if applicable)."
2058 (when (get-buffer (tramp-buffer-name vec))
2059 (with-current-buffer (tramp-get-debug-buffer vec)
2060 (goto-char (point-max))
2061 ;; Headline.
2062 (when (bobp)
2063 (insert
2064 (format
2065 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2066 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2067 emacs-version tramp-version)))
2068 (unless (bolp)
2069 (insert "\n"))
2070 ;; Timestamp.
2071 (let ((now (current-time)))
2072 (insert (format-time-string "%T." now))
2073 (insert (format "%06d " (nth 2 now))))
2074 ;; Calling function.
2075 (let ((btn 1) btf fn)
2076 (while (not fn)
2077 (setq btf (nth 1 (backtrace-frame btn)))
2078 (if (not btf)
2079 (setq fn "")
2080 (when (symbolp btf)
2081 (setq fn (symbol-name btf))
2082 (unless (and (string-match "^tramp" fn)
2083 (not (string-match
2084 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
2085 fn)))
2086 (setq fn nil)))
2087 (setq btn (1+ btn))))
2088 ;; The following code inserts filename and line number.
2089 ;; Should be deactivated by default, because it is time
2090 ;; consuming.
2091 ; (let ((ffn (find-function-noselect (intern fn))))
2092 ; (insert
2093 ; (format
2094 ; "%s:%d: "
2095 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2096 ; (with-current-buffer (car ffn)
2097 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2098 (insert (format "%s " fn)))
2099 ;; The message.
2100 (insert (apply 'format fmt-string args)))))
2102 (defvar tramp-message-show-message t
2103 "Show Tramp message in the minibuffer.
2104 This variable is used to disable messages from `tramp-error'.
2105 The messages are visible anyway, because an error is raised.")
2107 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2108 "Emit a message depending on verbosity level.
2109 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2110 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2111 less than LEVEL. The message is emitted only if `tramp-verbose' is
2112 greater than or equal to LEVEL.
2114 The message is also logged into the debug buffer when `tramp-verbose'
2115 is greater than or equal 4.
2117 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2118 control string and the remaining ARGS to actually emit the message (if
2119 applicable)."
2120 (condition-case nil
2121 (when (<= level tramp-verbose)
2122 ;; Match data must be preserved!
2123 (save-match-data
2124 ;; Display only when there is a minimum level.
2125 (when (and tramp-message-show-message (<= level 3))
2126 (apply 'message
2127 (concat
2128 (cond
2129 ((= level 0) "")
2130 ((= level 1) "")
2131 ((= level 2) "Warning: ")
2132 (t "Tramp: "))
2133 fmt-string)
2134 args))
2135 ;; Log only when there is a minimum level.
2136 (when (>= tramp-verbose 4)
2137 (when (and vec-or-proc
2138 (processp vec-or-proc)
2139 (buffer-name (process-buffer vec-or-proc)))
2140 (with-current-buffer (process-buffer vec-or-proc)
2141 ;; Translate proc to vec.
2142 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2143 (when (and vec-or-proc (vectorp vec-or-proc))
2144 (apply 'tramp-debug-message
2145 vec-or-proc
2146 (concat (format "(%d) # " level) fmt-string)
2147 args)))))
2148 ;; Suppress all errors.
2149 (error nil)))
2151 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2152 "Emit an error.
2153 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2154 signal identifier to be raised, remaining args passed to
2155 `tramp-message'. Finally, signal SIGNAL is raised."
2156 (let (tramp-message-show-message)
2157 (tramp-message
2158 vec-or-proc 1 "%s"
2159 (error-message-string
2160 (list signal
2161 (get signal 'error-message)
2162 (apply 'format fmt-string args))))
2163 (signal signal (list (apply 'format fmt-string args)))))
2165 (defsubst tramp-error-with-buffer
2166 (buffer vec-or-proc signal fmt-string &rest args)
2167 "Emit an error, and show BUFFER.
2168 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2169 an input event arrives. The other arguments are passed to `tramp-error'."
2170 (save-window-excursion
2171 (unwind-protect
2172 (apply 'tramp-error vec-or-proc signal fmt-string args)
2173 (when (and vec-or-proc (not (zerop tramp-verbose)))
2174 (let ((enable-recursive-minibuffers t))
2175 (pop-to-buffer
2176 (or (and (bufferp buffer) buffer)
2177 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2178 (tramp-get-buffer vec-or-proc)))
2179 (sit-for 30))))))
2181 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2182 "Parse a Tramp filename and make components available in the body.
2184 First arg FILENAME is evaluated and dissected into its components.
2185 Second arg VAR is a symbol. It is used as a variable name to hold
2186 the filename structure. It is also used as a prefix for the variables
2187 holding the components. For example, if VAR is the symbol `foo', then
2188 `foo' will be bound to the whole structure, `foo-method' will be bound to
2189 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2191 Remaining args are Lisp expressions to be evaluated (inside an implicit
2192 `progn').
2194 If VAR is nil, then we bind `v' to the structure and `method', `user',
2195 `host', `localname' to the components."
2196 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2197 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2198 (tramp-file-name-method ,(or var 'v)))
2199 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2200 (tramp-file-name-user ,(or var 'v)))
2201 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2202 (tramp-file-name-host ,(or var 'v)))
2203 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2204 (tramp-file-name-localname ,(or var 'v))))
2205 ,@body))
2207 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2208 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2209 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2211 (defmacro with-file-property (vec file property &rest body)
2212 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2213 FILE must be a local file name on a connection identified via VEC."
2214 `(if (file-name-absolute-p ,file)
2215 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2216 (when (eq value 'undef)
2217 ;; We cannot pass @body as parameter to
2218 ;; `tramp-set-file-property' because it mangles our
2219 ;; debug messages.
2220 (setq value (progn ,@body))
2221 (tramp-set-file-property ,vec ,file ,property value))
2222 value)
2223 ,@body))
2225 (put 'with-file-property 'lisp-indent-function 3)
2226 (put 'with-file-property 'edebug-form-spec t)
2227 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2229 (defmacro with-connection-property (key property &rest body)
2230 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2231 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2232 (when (eq value 'undef)
2233 ;; We cannot pass ,@body as parameter to
2234 ;; `tramp-set-connection-property' because it mangles our debug
2235 ;; messages.
2236 (setq value (progn ,@body))
2237 (tramp-set-connection-property ,key ,property value))
2238 value))
2240 (put 'with-connection-property 'lisp-indent-function 2)
2241 (put 'with-connection-property 'edebug-form-spec t)
2242 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2244 (eval-and-compile ; silence compiler
2245 (if (memq system-type '(cygwin windows-nt))
2246 (defun tramp-drop-volume-letter (name)
2247 "Cut off unnecessary drive letter from file NAME.
2248 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2249 locally on a remote file name. When the local system is a W32 system
2250 but the remote system is Unix, this introduces a superfluous drive
2251 letter into the file name. This function removes it."
2252 (save-match-data
2253 (if (string-match tramp-root-regexp name)
2254 (replace-match "/" nil t name)
2255 name)))
2257 (defalias 'tramp-drop-volume-letter 'identity)))
2259 (defsubst tramp-make-tramp-temp-file (vec)
2260 "Create a temporary file on the remote host identified by VEC.
2261 Return the local name of the temporary file."
2262 (let ((prefix
2263 (tramp-make-tramp-file-name
2264 (tramp-file-name-method vec)
2265 (tramp-file-name-user vec)
2266 (tramp-file-name-host vec)
2267 (tramp-drop-volume-letter
2268 (expand-file-name
2269 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2270 result)
2271 (while (not result)
2272 ;; `make-temp-file' would be the natural choice for
2273 ;; implementation. But it calls `write-region' internally,
2274 ;; which also needs a temporary file - we would end in an
2275 ;; infinite loop.
2276 (setq result (make-temp-name prefix))
2277 (if (file-exists-p result)
2278 (setq result nil)
2279 ;; This creates the file by side effect.
2280 (set-file-times result)
2281 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2283 ;; Return the local part.
2284 (with-parsed-tramp-file-name result nil localname)))
2287 ;;; Config Manipulation Functions:
2289 (defun tramp-set-completion-function (method function-list)
2290 "Sets the list of completion functions for METHOD.
2291 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2292 The FUNCTION is intended to parse FILE according its syntax.
2293 It might be a predefined FUNCTION, or a user defined FUNCTION.
2294 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2295 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2296 and `tramp-parse-netrc'.
2298 Example:
2300 (tramp-set-completion-function
2301 \"ssh\"
2302 '((tramp-parse-sconfig \"/etc/ssh_config\")
2303 (tramp-parse-sconfig \"~/.ssh/config\")))"
2305 (let ((r function-list)
2306 (v function-list))
2307 (setq tramp-completion-function-alist
2308 (delete (assoc method tramp-completion-function-alist)
2309 tramp-completion-function-alist))
2311 (while v
2312 ;; Remove double entries.
2313 (when (member (car v) (cdr v))
2314 (setcdr v (delete (car v) (cdr v))))
2315 ;; Check for function and file or registry key.
2316 (unless (and (functionp (nth 0 (car v)))
2317 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2318 ;; Windows registry.
2319 (and (memq system-type '(cygwin windows-nt))
2320 (zerop
2321 (tramp-local-call-process
2322 "reg" nil nil nil "query" (nth 1 (car v)))))
2323 ;; Configuration file.
2324 (file-exists-p (nth 1 (car v)))))
2325 (setq r (delete (car v) r)))
2326 (setq v (cdr v)))
2328 (when r
2329 (add-to-list 'tramp-completion-function-alist
2330 (cons method r)))))
2332 (defun tramp-get-completion-function (method)
2333 "Returns a list of completion functions for METHOD.
2334 For definition of that list see `tramp-set-completion-function'."
2335 (cons
2336 ;; Hosts visited once shall be remembered.
2337 `(tramp-parse-connection-properties ,method)
2338 ;; The method related defaults.
2339 (cdr (assoc method tramp-completion-function-alist))))
2342 ;;; Fontification of `read-file-name':
2344 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2345 (defvar tramp-rfn-eshadow-overlay)
2346 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2348 (defun tramp-rfn-eshadow-setup-minibuffer ()
2349 "Set up a minibuffer for `file-name-shadow-mode'.
2350 Adds another overlay hiding filename parts according to Tramp's
2351 special handling of `substitute-in-file-name'."
2352 (when (symbol-value 'minibuffer-completing-file-name)
2353 (setq tramp-rfn-eshadow-overlay
2354 (funcall (symbol-function 'make-overlay)
2355 (funcall (symbol-function 'minibuffer-prompt-end))
2356 (funcall (symbol-function 'minibuffer-prompt-end))))
2357 ;; Copy rfn-eshadow-overlay properties.
2358 (let ((props (funcall (symbol-function 'overlay-properties)
2359 (symbol-value 'rfn-eshadow-overlay))))
2360 (while props
2361 (funcall (symbol-function 'overlay-put)
2362 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2364 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2365 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2366 'tramp-rfn-eshadow-setup-minibuffer)
2367 (add-hook 'tramp-unload-hook
2368 (lambda ()
2369 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2370 'tramp-rfn-eshadow-setup-minibuffer))))
2372 (defconst tramp-rfn-eshadow-update-overlay-regexp
2373 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2375 (defun tramp-rfn-eshadow-update-overlay ()
2376 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2377 This is intended to be used as a minibuffer `post-command-hook' for
2378 `file-name-shadow-mode'; the minibuffer should have already
2379 been set up by `rfn-eshadow-setup-minibuffer'."
2380 ;; In remote files name, there is a shadowing just for the local part.
2381 (let ((end (or (funcall (symbol-function 'overlay-end)
2382 (symbol-value 'rfn-eshadow-overlay))
2383 (funcall (symbol-function 'minibuffer-prompt-end)))))
2384 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
2385 (save-excursion
2386 (save-restriction
2387 (narrow-to-region
2388 (1+ (or (string-match
2389 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2390 end))
2391 (point-max))
2392 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2393 (rfn-eshadow-update-overlay-hook nil))
2394 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
2395 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
2397 (when (boundp 'rfn-eshadow-update-overlay-hook)
2398 (add-hook 'rfn-eshadow-update-overlay-hook
2399 'tramp-rfn-eshadow-update-overlay)
2400 (add-hook 'tramp-unload-hook
2401 (lambda ()
2402 (remove-hook 'rfn-eshadow-update-overlay-hook
2403 'tramp-rfn-eshadow-update-overlay))))
2406 ;;; Integration of eshell.el:
2408 (eval-when-compile
2409 (defvar eshell-path-env))
2411 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2412 ;; when `default-directory' points to another host.
2413 (defun tramp-eshell-directory-change ()
2414 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2415 (setq eshell-path-env
2416 (if (file-remote-p default-directory)
2417 (with-parsed-tramp-file-name default-directory nil
2418 (mapconcat
2419 'identity
2420 (tramp-get-remote-path v)
2421 ":"))
2422 (getenv "PATH"))))
2424 (eval-after-load "esh-util"
2425 '(progn
2426 (tramp-eshell-directory-change)
2427 (add-hook 'eshell-directory-change-hook
2428 'tramp-eshell-directory-change)
2429 (add-hook 'tramp-unload-hook
2430 (lambda ()
2431 (remove-hook 'eshell-directory-change-hook
2432 'tramp-eshell-directory-change)))))
2435 ;;; File Name Handler Functions:
2437 (defun tramp-handle-make-symbolic-link
2438 (filename linkname &optional ok-if-already-exists)
2439 "Like `make-symbolic-link' for Tramp files.
2440 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2441 the symlink. If LINKNAME is a Tramp file, only the localname component is
2442 used as the target of the symlink.
2444 If LINKNAME is a Tramp file and the localname component is relative, then
2445 it is expanded first, before the localname component is taken. Note that
2446 this can give surprising results if the user/host for the source and
2447 target of the symlink differ."
2448 (with-parsed-tramp-file-name linkname l
2449 (let ((ln (tramp-get-remote-ln l))
2450 (cwd (tramp-run-real-handler
2451 'file-name-directory (list l-localname))))
2452 (unless ln
2453 (tramp-error
2454 l 'file-error
2455 "Making a symbolic link. ln(1) does not exist on the remote host."))
2457 ;; Do the 'confirm if exists' thing.
2458 (when (file-exists-p linkname)
2459 ;; What to do?
2460 (if (or (null ok-if-already-exists) ; not allowed to exist
2461 (and (numberp ok-if-already-exists)
2462 (not (yes-or-no-p
2463 (format
2464 "File %s already exists; make it a link anyway? "
2465 l-localname)))))
2466 (tramp-error
2467 l 'file-already-exists "File %s already exists" l-localname)
2468 (delete-file linkname)))
2470 ;; If FILENAME is a Tramp name, use just the localname component.
2471 (when (tramp-tramp-file-p filename)
2472 (setq filename
2473 (tramp-file-name-localname
2474 (tramp-dissect-file-name (expand-file-name filename)))))
2476 ;; Right, they are on the same host, regardless of user, method, etc.
2477 ;; We now make the link on the remote machine. This will occur as the user
2478 ;; that FILENAME belongs to.
2479 (zerop
2480 (tramp-send-command-and-check
2482 (format
2483 "cd %s && %s -sf %s %s"
2484 (tramp-shell-quote-argument cwd)
2486 (tramp-shell-quote-argument filename)
2487 (tramp-shell-quote-argument l-localname))
2488 t)))))
2490 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2491 "Like `load' for Tramp files."
2492 (with-parsed-tramp-file-name (expand-file-name file) nil
2493 (unless nosuffix
2494 (cond ((file-exists-p (concat file ".elc"))
2495 (setq file (concat file ".elc")))
2496 ((file-exists-p (concat file ".el"))
2497 (setq file (concat file ".el")))))
2498 (when must-suffix
2499 ;; The first condition is always true for absolute file names.
2500 ;; Included for safety's sake.
2501 (unless (or (file-name-directory file)
2502 (string-match "\\.elc?\\'" file))
2503 (tramp-error
2504 v 'file-error
2505 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2506 (unless noerror
2507 (when (not (file-exists-p file))
2508 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2509 (if (not (file-exists-p file))
2511 (unless nomessage (tramp-message v 0 "Loading %s..." file))
2512 (let ((local-copy (file-local-copy file)))
2513 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2514 (unwind-protect
2515 (load local-copy noerror t t)
2516 (delete-file local-copy)))
2517 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
2518 t)))
2520 ;; Localname manipulation functions that grok Tramp localnames...
2521 (defun tramp-handle-file-name-as-directory (file)
2522 "Like `file-name-as-directory' but aware of Tramp files."
2523 ;; `file-name-as-directory' would be sufficient except localname is
2524 ;; the empty string.
2525 (let ((v (tramp-dissect-file-name file t)))
2526 ;; Run the command on the localname portion only.
2527 (tramp-make-tramp-file-name
2528 (tramp-file-name-method v)
2529 (tramp-file-name-user v)
2530 (tramp-file-name-host v)
2531 (tramp-run-real-handler
2532 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2534 (defun tramp-handle-file-name-directory (file)
2535 "Like `file-name-directory' but aware of Tramp files."
2536 ;; Everything except the last filename thing is the directory. We
2537 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2538 ;; the remote file name parts. This is a problem when we are in
2539 ;; file name completion.
2540 (let ((v (tramp-dissect-file-name file t)))
2541 ;; Run the command on the localname portion only.
2542 (tramp-make-tramp-file-name
2543 (tramp-file-name-method v)
2544 (tramp-file-name-user v)
2545 (tramp-file-name-host v)
2546 (tramp-run-real-handler
2547 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2549 (defun tramp-handle-file-name-nondirectory (file)
2550 "Like `file-name-nondirectory' but aware of Tramp files."
2551 (with-parsed-tramp-file-name file nil
2552 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2554 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2555 "Like `file-truename' for Tramp files."
2556 (with-parsed-tramp-file-name (expand-file-name filename) nil
2557 (with-file-property v localname "file-truename"
2558 (let ((result nil)) ; result steps in reverse order
2559 (tramp-message v 4 "Finding true name for `%s'" filename)
2560 (cond
2561 ;; Use GNU readlink --canonicalize-missing where available.
2562 ((tramp-get-remote-readlink v)
2563 (setq result
2564 (tramp-send-command-and-read
2566 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2567 (tramp-get-remote-readlink v)
2568 (tramp-shell-quote-argument localname)))))
2570 ;; Use Perl implementation.
2571 ((and (tramp-get-remote-perl v)
2572 (tramp-get-connection-property v "perl-file-spec" nil)
2573 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2574 (tramp-maybe-send-script
2575 v tramp-perl-file-truename "tramp_perl_file_truename")
2576 (setq result
2577 (tramp-send-command-and-read
2579 (format "tramp_perl_file_truename %s"
2580 (tramp-shell-quote-argument localname)))))
2582 ;; Do it yourself. We bind `directory-sep-char' here for
2583 ;; XEmacs on Windows, which would otherwise use backslash.
2584 (t (let* ((directory-sep-char ?/)
2585 (steps (tramp-compat-split-string localname "/"))
2586 (localnamedir (tramp-run-real-handler
2587 'file-name-as-directory (list localname)))
2588 (is-dir (string= localname localnamedir))
2589 (thisstep nil)
2590 (numchase 0)
2591 ;; Don't make the following value larger than
2592 ;; necessary. People expect an error message in a
2593 ;; timely fashion when something is wrong;
2594 ;; otherwise they might think that Emacs is hung.
2595 ;; Of course, correctness has to come first.
2596 (numchase-limit 20)
2597 symlink-target)
2598 (while (and steps (< numchase numchase-limit))
2599 (setq thisstep (pop steps))
2600 (tramp-message
2601 v 5 "Check %s"
2602 (mapconcat 'identity
2603 (append '("") (reverse result) (list thisstep))
2604 "/"))
2605 (setq symlink-target
2606 (nth 0 (file-attributes
2607 (tramp-make-tramp-file-name
2608 method user host
2609 (mapconcat 'identity
2610 (append '("")
2611 (reverse result)
2612 (list thisstep))
2613 "/")))))
2614 (cond ((string= "." thisstep)
2615 (tramp-message v 5 "Ignoring step `.'"))
2616 ((string= ".." thisstep)
2617 (tramp-message v 5 "Processing step `..'")
2618 (pop result))
2619 ((stringp symlink-target)
2620 ;; It's a symlink, follow it.
2621 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2622 (setq numchase (1+ numchase))
2623 (when (file-name-absolute-p symlink-target)
2624 (setq result nil))
2625 ;; If the symlink was absolute, we'll get a string like
2626 ;; "/user@host:/some/target"; extract the
2627 ;; "/some/target" part from it.
2628 (when (tramp-tramp-file-p symlink-target)
2629 (unless (tramp-equal-remote filename symlink-target)
2630 (tramp-error
2631 v 'file-error
2632 "Symlink target `%s' on wrong host" symlink-target))
2633 (setq symlink-target localname))
2634 (setq steps
2635 (append (tramp-compat-split-string
2636 symlink-target "/")
2637 steps)))
2639 ;; It's a file.
2640 (setq result (cons thisstep result)))))
2641 (when (>= numchase numchase-limit)
2642 (tramp-error
2643 v 'file-error
2644 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2645 (setq result (reverse result))
2646 ;; Combine list to form string.
2647 (setq result
2648 (if result
2649 (mapconcat 'identity (cons "" result) "/")
2650 "/"))
2651 (when (and is-dir (or (string= "" result)
2652 (not (string= (substring result -1) "/"))))
2653 (setq result (concat result "/"))))))
2655 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2656 (tramp-make-tramp-file-name method user host result)))))
2658 ;; Basic functions.
2660 (defun tramp-handle-file-exists-p (filename)
2661 "Like `file-exists-p' for Tramp files."
2662 (with-parsed-tramp-file-name filename nil
2663 (with-file-property v localname "file-exists-p"
2664 (or (not (null (tramp-get-file-property
2665 v localname "file-attributes-integer" nil)))
2666 (not (null (tramp-get-file-property
2667 v localname "file-attributes-string" nil)))
2668 (zerop (tramp-send-command-and-check
2670 (format
2671 "%s %s"
2672 (tramp-get-file-exists-command v)
2673 (tramp-shell-quote-argument localname))))))))
2675 ;; Inodes don't exist for some file systems. Therefore we must
2676 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2677 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2678 ;; performance isn't the major issue given that file transfer will
2679 ;; take time.
2680 (defvar tramp-inodes nil
2681 "Keeps virtual inodes numbers.")
2683 ;; Devices must distinguish physical file systems. The device numbers
2684 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2685 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2686 ;; EFS use device number "-1". In order to be different, we use device number
2687 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2688 (defvar tramp-devices nil
2689 "Keeps virtual device numbers.")
2691 ;; CCC: This should check for an error condition and signal failure
2692 ;; when something goes wrong.
2693 ;; Daniel Pittman <daniel@danann.net>
2694 (defun tramp-handle-file-attributes (filename &optional id-format)
2695 "Like `file-attributes' for Tramp files."
2696 (unless id-format (setq id-format 'integer))
2697 ;; Don't modify `last-coding-system-used' by accident.
2698 (let ((last-coding-system-used last-coding-system-used))
2699 (with-parsed-tramp-file-name (expand-file-name filename) nil
2700 (with-file-property v localname (format "file-attributes-%s" id-format)
2701 (save-excursion
2702 (tramp-convert-file-attributes
2704 (cond
2705 ((tramp-get-remote-stat v)
2706 (tramp-do-file-attributes-with-stat v localname id-format))
2707 ((tramp-get-remote-perl v)
2708 (tramp-do-file-attributes-with-perl v localname id-format))
2710 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2712 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2713 "Implement `file-attributes' for Tramp files using the ls(1) command."
2714 (let (symlinkp dirp
2715 res-inode res-filemodes res-numlinks
2716 res-uid res-gid res-size res-symlink-target)
2717 (tramp-message vec 5 "file attributes with ls: %s" localname)
2718 (tramp-send-command
2720 (format "(%s %s || %s -h %s) && %s %s %s"
2721 (tramp-get-file-exists-command vec)
2722 (tramp-shell-quote-argument localname)
2723 (tramp-get-test-command vec)
2724 (tramp-shell-quote-argument localname)
2725 (tramp-get-ls-command vec)
2726 (if (eq id-format 'integer) "-ildn" "-ild")
2727 (tramp-shell-quote-argument localname)))
2728 ;; parse `ls -l' output ...
2729 (with-current-buffer (tramp-get-buffer vec)
2730 (when (> (buffer-size) 0)
2731 (goto-char (point-min))
2732 ;; ... inode
2733 (setq res-inode
2734 (condition-case err
2735 (read (current-buffer))
2736 (invalid-read-syntax
2737 (when (and (equal (cadr err)
2738 "Integer constant overflow in reader")
2739 (string-match
2740 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2741 (car (cddr err))))
2742 (let* ((big (read (substring (car (cddr err)) 0
2743 (match-beginning 1))))
2744 (small (read (match-string 1 (car (cddr err)))))
2745 (twiddle (/ small 65536)))
2746 (cons (+ big twiddle)
2747 (- small (* twiddle 65536))))))))
2748 ;; ... file mode flags
2749 (setq res-filemodes (symbol-name (read (current-buffer))))
2750 ;; ... number links
2751 (setq res-numlinks (read (current-buffer)))
2752 ;; ... uid and gid
2753 (setq res-uid (read (current-buffer)))
2754 (setq res-gid (read (current-buffer)))
2755 (if (eq id-format 'integer)
2756 (progn
2757 (unless (numberp res-uid) (setq res-uid -1))
2758 (unless (numberp res-gid) (setq res-gid -1)))
2759 (progn
2760 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2761 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2762 ;; ... size
2763 (setq res-size (read (current-buffer)))
2764 ;; From the file modes, figure out other stuff.
2765 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2766 (setq dirp (eq ?d (aref res-filemodes 0)))
2767 ;; if symlink, find out file name pointed to
2768 (when symlinkp
2769 (search-forward "-> ")
2770 (setq res-symlink-target
2771 (buffer-substring (point) (tramp-compat-line-end-position))))
2772 ;; return data gathered
2773 (list
2774 ;; 0. t for directory, string (name linked to) for symbolic
2775 ;; link, or nil.
2776 (or dirp res-symlink-target)
2777 ;; 1. Number of links to file.
2778 res-numlinks
2779 ;; 2. File uid.
2780 res-uid
2781 ;; 3. File gid.
2782 res-gid
2783 ;; 4. Last access time, as a list of two integers. First
2784 ;; integer has high-order 16 bits of time, second has low 16
2785 ;; bits.
2786 ;; 5. Last modification time, likewise.
2787 ;; 6. Last status change time, likewise.
2788 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2789 ;; 7. Size in bytes (-1, if number is out of range).
2790 res-size
2791 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2792 res-filemodes
2793 ;; 9. t if file's gid would change if file were deleted and
2794 ;; recreated. Will be set in `tramp-convert-file-attributes'
2796 ;; 10. inode number.
2797 res-inode
2798 ;; 11. Device number. Will be replaced by a virtual device number.
2800 )))))
2802 (defun tramp-do-file-attributes-with-perl
2803 (vec localname &optional id-format)
2804 "Implement `file-attributes' for Tramp files using a Perl script."
2805 (tramp-message vec 5 "file attributes with perl: %s" localname)
2806 (tramp-maybe-send-script
2807 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2808 (tramp-send-command-and-read
2810 (format "tramp_perl_file_attributes %s %s"
2811 (tramp-shell-quote-argument localname) id-format)))
2813 (defun tramp-do-file-attributes-with-stat
2814 (vec localname &optional id-format)
2815 "Implement `file-attributes' for Tramp files using stat(1) command."
2816 (tramp-message vec 5 "file attributes with stat: %s" localname)
2817 (tramp-send-command-and-read
2819 (format
2820 "((%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s || echo nil)"
2821 (tramp-get-file-exists-command vec)
2822 (tramp-shell-quote-argument localname)
2823 (tramp-get-test-command vec)
2824 (tramp-shell-quote-argument localname)
2825 (tramp-get-remote-stat vec)
2826 (if (eq id-format 'integer) "%u" "\"%U\"")
2827 (if (eq id-format 'integer) "%g" "\"%G\"")
2828 (tramp-shell-quote-argument localname))))
2830 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2831 "Like `set-visited-file-modtime' for Tramp files."
2832 (unless (buffer-file-name)
2833 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2834 (buffer-name)))
2835 (if time-list
2836 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2837 (let ((f (buffer-file-name))
2838 coding-system-used)
2839 (with-parsed-tramp-file-name f nil
2840 (let* ((attr (file-attributes f))
2841 ;; '(-1 65535) means file doesn't exists yet.
2842 (modtime (or (nth 5 attr) '(-1 65535))))
2843 (when (boundp 'last-coding-system-used)
2844 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2845 ;; We use '(0 0) as a don't-know value. See also
2846 ;; `tramp-do-file-attributes-with-ls'.
2847 (if (not (equal modtime '(0 0)))
2848 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2849 (progn
2850 (tramp-send-command
2852 (format "%s -ild %s"
2853 (tramp-get-ls-command v)
2854 (tramp-shell-quote-argument localname)))
2855 (setq attr (buffer-substring (point)
2856 (progn (end-of-line) (point)))))
2857 (tramp-set-file-property
2858 v localname "visited-file-modtime-ild" attr))
2859 (when (boundp 'last-coding-system-used)
2860 (set 'last-coding-system-used coding-system-used))
2861 nil)))))
2863 ;; This function makes the same assumption as
2864 ;; `tramp-handle-set-visited-file-modtime'.
2865 (defun tramp-handle-verify-visited-file-modtime (buf)
2866 "Like `verify-visited-file-modtime' for Tramp files.
2867 At the time `verify-visited-file-modtime' calls this function, we
2868 already know that the buffer is visiting a file and that
2869 `visited-file-modtime' does not return 0. Do not call this
2870 function directly, unless those two cases are already taken care
2871 of."
2872 (with-current-buffer buf
2873 ;; There is no file visiting the buffer, or the buffer has no
2874 ;; recorded last modification time.
2875 (if (or (not (buffer-file-name))
2876 (eq (visited-file-modtime) 0))
2878 (let ((f (buffer-file-name)))
2879 (with-parsed-tramp-file-name f nil
2880 (tramp-flush-file-property v localname)
2881 (let* ((attr (file-attributes f))
2882 (modtime (nth 5 attr))
2883 (mt (visited-file-modtime)))
2885 (cond
2886 ;; File exists, and has a known modtime.
2887 ((and attr (not (equal modtime '(0 0))))
2888 (< (abs (tramp-time-diff
2889 modtime
2890 ;; For compatibility, deal with both the old
2891 ;; (HIGH . LOW) and the new (HIGH LOW) return
2892 ;; values of `visited-file-modtime'.
2893 (if (atom (cdr mt))
2894 (list (car mt) (cdr mt))
2895 mt)))
2897 ;; Modtime has the don't know value.
2898 (attr
2899 (tramp-send-command
2901 (format "%s -ild %s"
2902 (tramp-get-ls-command v)
2903 (tramp-shell-quote-argument localname)))
2904 (with-current-buffer (tramp-get-buffer v)
2905 (setq attr (buffer-substring
2906 (point) (progn (end-of-line) (point)))))
2907 (equal
2908 attr
2909 (tramp-get-file-property
2910 v localname "visited-file-modtime-ild" "")))
2911 ;; If file does not exist, say it is not modified if and
2912 ;; only if that agrees with the buffer's record.
2913 (t (equal mt '(-1 65535))))))))))
2915 (defun tramp-handle-set-file-modes (filename mode)
2916 "Like `set-file-modes' for Tramp files."
2917 (with-parsed-tramp-file-name filename nil
2918 (tramp-flush-file-property v localname)
2919 (unless (zerop (tramp-send-command-and-check
2921 (format "chmod %s %s"
2922 (tramp-decimal-to-octal mode)
2923 (tramp-shell-quote-argument localname))))
2924 ;; FIXME: extract the proper text from chmod's stderr.
2925 (tramp-error
2926 v 'file-error "Error while changing file's mode %s" filename))))
2928 (defun tramp-handle-set-file-times (filename &optional time)
2929 "Like `set-file-times' for Tramp files."
2930 (zerop
2931 (if (file-remote-p filename)
2932 (with-parsed-tramp-file-name filename nil
2933 (tramp-flush-file-property v localname)
2934 (let ((time (if (or (null time) (equal time '(0 0)))
2935 (current-time)
2936 time))
2937 (utc
2938 ;; With GNU Emacs, `format-time-string' has an
2939 ;; optional parameter UNIVERSAL. This is preferred,
2940 ;; because we could handle the case when the remote
2941 ;; host is located in a different time zone as the
2942 ;; local host.
2943 (and (functionp 'subr-arity)
2944 (subrp (symbol-function 'format-time-string))
2945 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2946 (symbol-function
2947 'format-time-string)))))))
2948 (tramp-send-command-and-check
2949 v (format "%s touch -t %s %s"
2950 (if utc "TZ=UTC; export TZ;" "")
2951 (if utc
2952 (format-time-string "%Y%m%d%H%M.%S" time t)
2953 (format-time-string "%Y%m%d%H%M.%S" time))
2954 (tramp-shell-quote-argument localname)))))
2956 ;; We handle also the local part, because in older Emacsen,
2957 ;; without `set-file-times', this function is an alias for this.
2958 ;; We are local, so we don't need the UTC settings.
2959 (tramp-local-call-process
2960 "touch" nil nil nil "-t"
2961 (format-time-string "%Y%m%d%H%M.%S" time)
2962 (tramp-shell-quote-argument filename)))))
2964 (defun tramp-set-file-uid-gid (filename &optional uid gid)
2965 "Set the ownership for FILENAME.
2966 If UID and GID are provided, these values are used; otherwise uid
2967 and gid of the corresponding user is taken. Both parameters must be integers."
2968 ;; Modern Unices allow chown only for root. So we might need
2969 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2970 ;; working with su(do)? when it is needed, so it shall succeed in
2971 ;; the majority of cases.
2972 ;; Don't modify `last-coding-system-used' by accident.
2973 (let ((last-coding-system-used last-coding-system-used))
2974 (if (file-remote-p filename)
2975 (with-parsed-tramp-file-name filename nil
2976 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2977 ;; If we are root on the local host, we can do it directly.
2978 (tramp-set-file-uid-gid localname uid gid)
2979 (let ((uid (or (and (integerp uid) uid)
2980 (tramp-get-remote-uid v 'integer)))
2981 (gid (or (and (integerp gid) gid)
2982 (tramp-get-remote-gid v 'integer))))
2983 (tramp-send-command
2984 v (format
2985 "chown %d:%d %s" uid gid
2986 (tramp-shell-quote-argument localname))))))
2988 ;; We handle also the local part, because there doesn't exist
2989 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2990 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2991 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2992 (tramp-local-call-process
2993 "chown" nil nil nil
2994 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
2996 ;; Simple functions using the `test' command.
2998 (defun tramp-handle-file-executable-p (filename)
2999 "Like `file-executable-p' for Tramp files."
3000 (with-parsed-tramp-file-name filename nil
3001 (with-file-property v localname "file-executable-p"
3002 ;; Examine `file-attributes' cache to see if request can be
3003 ;; satisfied without remote operation.
3004 (or (tramp-check-cached-permissions v ?x)
3005 (zerop (tramp-run-test "-x" filename))))))
3007 (defun tramp-handle-file-readable-p (filename)
3008 "Like `file-readable-p' for Tramp files."
3009 (with-parsed-tramp-file-name filename nil
3010 (with-file-property v localname "file-readable-p"
3011 ;; Examine `file-attributes' cache to see if request can be
3012 ;; satisfied without remote operation.
3013 (or (tramp-check-cached-permissions v ?r)
3014 (zerop (tramp-run-test "-r" filename))))))
3016 ;; When the remote shell is started, it looks for a shell which groks
3017 ;; tilde expansion. Here, we assume that all shells which grok tilde
3018 ;; expansion will also provide a `test' command which groks `-nt' (for
3019 ;; newer than). If this breaks, tell me about it and I'll try to do
3020 ;; something smarter about it.
3021 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3022 "Like `file-newer-than-file-p' for Tramp files."
3023 (cond ((not (file-exists-p file1))
3024 nil)
3025 ((not (file-exists-p file2))
3027 ;; We are sure both files exist at this point.
3029 (save-excursion
3030 ;; We try to get the mtime of both files. If they are not
3031 ;; equal to the "dont-know" value, then we subtract the times
3032 ;; and obtain the result.
3033 (let ((fa1 (file-attributes file1))
3034 (fa2 (file-attributes file2)))
3035 (if (and (not (equal (nth 5 fa1) '(0 0)))
3036 (not (equal (nth 5 fa2) '(0 0))))
3037 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3038 ;; If one of them is the dont-know value, then we can
3039 ;; still try to run a shell command on the remote host.
3040 ;; However, this only works if both files are Tramp
3041 ;; files and both have the same method, same user, same
3042 ;; host.
3043 (unless (tramp-equal-remote file1 file2)
3044 (with-parsed-tramp-file-name
3045 (if (tramp-tramp-file-p file1) file1 file2) nil
3046 (tramp-error
3047 v 'file-error
3048 "Files %s and %s must have same method, user, host"
3049 file1 file2)))
3050 (with-parsed-tramp-file-name file1 nil
3051 (zerop (tramp-run-test2
3052 (tramp-get-test-nt-command v) file1 file2)))))))))
3054 ;; Functions implemented using the basic functions above.
3056 (defun tramp-handle-file-modes (filename)
3057 "Like `file-modes' for Tramp files."
3058 (let ((truename (or (file-truename filename) filename)))
3059 (when (file-exists-p truename)
3060 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3062 (defun tramp-default-file-modes (filename)
3063 "Return file modes of FILENAME as integer.
3064 If the file modes of FILENAME cannot be determined, return the
3065 value of `default-file-modes', without execute permissions."
3066 (or (file-modes filename)
3067 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3069 (defun tramp-handle-file-directory-p (filename)
3070 "Like `file-directory-p' for Tramp files."
3071 ;; Care must be taken that this function returns `t' for symlinks
3072 ;; pointing to directories. Surely the most obvious implementation
3073 ;; would be `test -d', but that returns false for such symlinks.
3074 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3075 ;; I now think he's right. So we could be using `test -d', couldn't
3076 ;; we?
3078 ;; Alternatives: `cd %s', `test -d %s'
3079 (with-parsed-tramp-file-name filename nil
3080 (with-file-property v localname "file-directory-p"
3081 (zerop (tramp-run-test "-d" filename)))))
3083 (defun tramp-handle-file-regular-p (filename)
3084 "Like `file-regular-p' for Tramp files."
3085 (and (file-exists-p filename)
3086 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3088 (defun tramp-handle-file-symlink-p (filename)
3089 "Like `file-symlink-p' for Tramp files."
3090 (with-parsed-tramp-file-name filename nil
3091 (let ((x (car (file-attributes filename))))
3092 (when (stringp x)
3093 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3094 ;; might do weird things.
3095 (if (file-name-absolute-p x)
3096 (tramp-make-tramp-file-name method user host x)
3097 x)))))
3099 (defun tramp-handle-file-writable-p (filename)
3100 "Like `file-writable-p' for Tramp files."
3101 (with-parsed-tramp-file-name filename nil
3102 (with-file-property v localname "file-writable-p"
3103 (if (file-exists-p filename)
3104 ;; Examine `file-attributes' cache to see if request can be
3105 ;; satisfied without remote operation.
3106 (or (tramp-check-cached-permissions v ?w)
3107 (zerop (tramp-run-test "-w" filename)))
3108 ;; If file doesn't exist, check if directory is writable.
3109 (and (zerop (tramp-run-test
3110 "-d" (file-name-directory filename)))
3111 (zerop (tramp-run-test
3112 "-w" (file-name-directory filename))))))))
3114 (defun tramp-handle-file-ownership-preserved-p (filename)
3115 "Like `file-ownership-preserved-p' for Tramp files."
3116 (with-parsed-tramp-file-name filename nil
3117 (with-file-property v localname "file-ownership-preserved-p"
3118 (let ((attributes (file-attributes filename)))
3119 ;; Return t if the file doesn't exist, since it's true that no
3120 ;; information would be lost by an (attempted) delete and create.
3121 (or (null attributes)
3122 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3124 ;; Other file name ops.
3126 (defun tramp-handle-directory-file-name (directory)
3127 "Like `directory-file-name' for Tramp files."
3128 ;; If localname component of filename is "/", leave it unchanged.
3129 ;; Otherwise, remove any trailing slash from localname component.
3130 ;; Method, host, etc, are unchanged. Does it make sense to try
3131 ;; to avoid parsing the filename?
3132 (with-parsed-tramp-file-name directory nil
3133 (if (and (not (zerop (length localname)))
3134 (eq (aref localname (1- (length localname))) ?/)
3135 (not (string= localname "/")))
3136 (substring directory 0 -1)
3137 directory)))
3139 ;; Directory listings.
3141 (defun tramp-handle-directory-files
3142 (directory &optional full match nosort files-only)
3143 "Like `directory-files' for Tramp files."
3144 ;; FILES-ONLY is valid for XEmacs only.
3145 (when (file-directory-p directory)
3146 (setq directory (file-name-as-directory (expand-file-name directory)))
3147 (let ((temp (nreverse (file-name-all-completions "" directory)))
3148 result item)
3150 (while temp
3151 (setq item (directory-file-name (pop temp)))
3152 (when (and (or (null match) (string-match match item))
3153 (or (null files-only)
3154 ;; Files only.
3155 (and (equal files-only t) (file-regular-p item))
3156 ;; Directories only.
3157 (file-directory-p item)))
3158 (push (if full (concat directory item) item)
3159 result)))
3160 (if nosort result (sort result 'string<)))))
3162 (defun tramp-handle-directory-files-and-attributes
3163 (directory &optional full match nosort id-format)
3164 "Like `directory-files-and-attributes' for Tramp files."
3165 (unless id-format (setq id-format 'integer))
3166 (when (file-directory-p directory)
3167 (setq directory (expand-file-name directory))
3168 (let* ((temp
3169 (tramp-compat-copy-tree
3170 (with-parsed-tramp-file-name directory nil
3171 (with-file-property
3172 v localname
3173 (format "directory-files-and-attributes-%s" id-format)
3174 (save-excursion
3175 (mapcar
3176 (lambda (x)
3177 (cons (car x)
3178 (tramp-convert-file-attributes v (cdr x))))
3179 (cond
3180 ((tramp-get-remote-stat v)
3181 (tramp-do-directory-files-and-attributes-with-stat
3182 v localname id-format))
3183 ((tramp-get-remote-perl v)
3184 (tramp-do-directory-files-and-attributes-with-perl
3185 v localname id-format)))))))))
3186 result item)
3188 (while temp
3189 (setq item (pop temp))
3190 (when (or (null match) (string-match match (car item)))
3191 (when full
3192 (setcar item (expand-file-name (car item) directory)))
3193 (push item result)))
3195 (if nosort
3196 result
3197 (sort result (lambda (x y) (string< (car x) (car y))))))))
3199 (defun tramp-do-directory-files-and-attributes-with-perl
3200 (vec localname &optional id-format)
3201 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3202 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3203 (tramp-maybe-send-script
3204 vec tramp-perl-directory-files-and-attributes
3205 "tramp_perl_directory_files_and_attributes")
3206 (let ((object
3207 (tramp-send-command-and-read
3209 (format "tramp_perl_directory_files_and_attributes %s %s"
3210 (tramp-shell-quote-argument localname) id-format))))
3211 (when (stringp object) (tramp-error vec 'file-error object))
3212 object))
3214 (defun tramp-do-directory-files-and-attributes-with-stat
3215 (vec localname &optional id-format)
3216 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3217 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3218 (tramp-send-command-and-read
3220 (format
3221 (concat
3222 ;; We must care about filenames with spaces, or starting with
3223 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3224 ;; but it does not work on all remote systems. Therefore, we
3225 ;; quote the filenames via sed.
3226 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3227 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3228 "echo \")\"")
3229 (tramp-shell-quote-argument localname)
3230 (tramp-get-ls-command vec)
3231 (tramp-get-remote-stat vec)
3232 (if (eq id-format 'integer) "%u" "\"%U\"")
3233 (if (eq id-format 'integer) "%g" "\"%G\""))))
3235 ;; This function should return "foo/" for directories and "bar" for
3236 ;; files.
3237 (defun tramp-handle-file-name-all-completions (filename directory)
3238 "Like `file-name-all-completions' for Tramp files."
3239 (unless (save-match-data (string-match "/" filename))
3240 (with-parsed-tramp-file-name (expand-file-name directory) nil
3242 (all-completions
3243 filename
3244 (mapcar
3245 'list
3247 ;; Try cache first
3248 (and
3249 ;; Ignore if expired
3250 (or (not (integerp tramp-completion-reread-directory-timeout))
3251 (<= (tramp-time-diff
3252 (current-time)
3253 (tramp-get-file-property
3254 v localname "last-completion" '(0 0 0)))
3255 tramp-completion-reread-directory-timeout))
3257 ;; Try cache entries for filename, filename with last
3258 ;; character removed, filename with last two characters
3259 ;; removed, ..., and finally the empty string - all
3260 ;; concatenated to the local directory name
3262 ;; This is inefficient for very long filenames, pity
3263 ;; `reduce' is not available...
3264 (car
3265 (apply
3266 'append
3267 (mapcar
3268 (lambda (x)
3269 (let ((cache-hit
3270 (tramp-get-file-property
3272 (concat localname (substring filename 0 x))
3273 "file-name-all-completions"
3274 nil)))
3275 (when cache-hit (list cache-hit))))
3276 (tramp-compat-number-sequence (length filename) 0 -1)))))
3278 ;; Cache expired or no matching cache entry found so we need
3279 ;; to perform a remote operation
3280 (let (result)
3281 ;; Get a list of directories and files, including reliably
3282 ;; tagging the directories with a trailing '/'. Because I
3283 ;; rock. --daniel@danann.net
3285 ;; Changed to perform `cd' in the same remote op and only
3286 ;; get entries starting with `filename'. Capture any `cd'
3287 ;; error messages. Ensure any `cd' and `echo' aliases are
3288 ;; ignored.
3289 (tramp-send-command
3291 (if (tramp-get-remote-perl v)
3292 (progn
3293 (tramp-maybe-send-script
3294 v tramp-perl-file-name-all-completions
3295 "tramp_perl_file_name_all_completions")
3296 (format "tramp_perl_file_name_all_completions %s %s %d"
3297 (tramp-shell-quote-argument localname)
3298 (tramp-shell-quote-argument filename)
3299 (if (symbol-value
3300 'read-file-name-completion-ignore-case)
3301 1 0)))
3303 (format (concat
3304 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3305 ;; `ls' with wildcard might fail with `Argument
3306 ;; list too long' error in some corner cases; if
3307 ;; `ls' fails after `cd' succeeded, chances are
3308 ;; that's the case, so let's retry without
3309 ;; wildcard. This will return "too many" entries
3310 ;; but that isn't harmful.
3311 " || %s -a 2>/dev/null)"
3312 " | while read f; do"
3313 " if %s -d \"$f\" 2>/dev/null;"
3314 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3315 " && \\echo ok) || \\echo fail")
3316 (tramp-shell-quote-argument localname)
3317 (tramp-get-ls-command v)
3318 ;; When `filename' is empty, just `ls' without
3319 ;; filename argument is more efficient than `ls *'
3320 ;; for very large directories and might avoid the
3321 ;; `Argument list too long' error.
3323 ;; With and only with wildcard, we need to add
3324 ;; `-d' to prevent `ls' from descending into
3325 ;; sub-directories.
3326 (if (zerop (length filename))
3328 (concat (tramp-shell-quote-argument filename) "* -d"))
3329 (tramp-get-ls-command v)
3330 (tramp-get-test-command v))))
3332 ;; Now grab the output.
3333 (with-current-buffer (tramp-get-buffer v)
3334 (goto-char (point-max))
3336 ;; Check result code, found in last line of output
3337 (forward-line -1)
3338 (if (looking-at "^fail$")
3339 (progn
3340 ;; Grab error message from line before last line
3341 ;; (it was put there by `cd 2>&1')
3342 (forward-line -1)
3343 (tramp-error
3344 v 'file-error
3345 "tramp-handle-file-name-all-completions: %s"
3346 (buffer-substring
3347 (point) (tramp-compat-line-end-position))))
3348 ;; For peace of mind, if buffer doesn't end in `fail'
3349 ;; then it should end in `ok'. If neither are in the
3350 ;; buffer something went seriously wrong on the remote
3351 ;; side.
3352 (unless (looking-at "^ok$")
3353 (tramp-error
3354 v 'file-error
3356 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3357 (tramp-shell-quote-argument localname) (buffer-string))))
3359 (while (zerop (forward-line -1))
3360 (push (buffer-substring
3361 (point) (tramp-compat-line-end-position))
3362 result)))
3364 ;; Because the remote op went through OK we know the
3365 ;; directory we `cd'-ed to exists
3366 (tramp-set-file-property
3367 v localname "file-exists-p" t)
3369 ;; Because the remote op went through OK we know every
3370 ;; file listed by `ls' exists.
3371 (mapc (lambda (entry)
3372 (tramp-set-file-property
3373 v (concat localname entry) "file-exists-p" t))
3374 result)
3376 (tramp-set-file-property
3377 v localname "last-completion" (current-time))
3379 ;; Store result in the cache
3380 (tramp-set-file-property
3381 v (concat localname filename)
3382 "file-name-all-completions"
3383 result))))))))
3385 ;; The following isn't needed for Emacs 20 but for 19.34?
3386 (defun tramp-handle-file-name-completion
3387 (filename directory &optional predicate)
3388 "Like `file-name-completion' for Tramp files."
3389 (unless (tramp-tramp-file-p directory)
3390 (error
3391 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3392 directory))
3393 (try-completion
3394 filename
3395 (mapcar 'list (file-name-all-completions filename directory))
3396 (when predicate
3397 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3399 ;; cp, mv and ln
3401 (defun tramp-handle-add-name-to-file
3402 (filename newname &optional ok-if-already-exists)
3403 "Like `add-name-to-file' for Tramp files."
3404 (unless (tramp-equal-remote filename newname)
3405 (with-parsed-tramp-file-name
3406 (if (tramp-tramp-file-p filename) filename newname) nil
3407 (tramp-error
3408 v 'file-error
3409 "add-name-to-file: %s"
3410 "only implemented for same method, same user, same host")))
3411 (with-parsed-tramp-file-name filename v1
3412 (with-parsed-tramp-file-name newname v2
3413 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3414 (when (and (not ok-if-already-exists)
3415 (file-exists-p newname)
3416 (not (numberp ok-if-already-exists))
3417 (y-or-n-p
3418 (format
3419 "File %s already exists; make it a new name anyway? "
3420 newname)))
3421 (tramp-error
3422 v2 'file-error
3423 "add-name-to-file: file %s already exists" newname))
3424 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3425 (tramp-flush-file-property v2 v2-localname)
3426 (tramp-barf-unless-okay
3428 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3429 (tramp-shell-quote-argument v2-localname))
3430 "error with add-name-to-file, see buffer `%s' for details"
3431 (buffer-name))))))
3433 (defun tramp-handle-copy-file
3434 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3435 "Like `copy-file' for Tramp files."
3436 ;; Check if both files are local -- invoke normal copy-file.
3437 ;; Otherwise, use Tramp from local system.
3438 (setq filename (expand-file-name filename))
3439 (setq newname (expand-file-name newname))
3440 (cond
3441 ;; At least one file a Tramp file?
3442 ((or (tramp-tramp-file-p filename)
3443 (tramp-tramp-file-p newname))
3444 (tramp-do-copy-or-rename-file
3445 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3446 ;; Compat section.
3447 (preserve-uid-gid
3448 (tramp-run-real-handler
3449 'copy-file
3450 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3452 (tramp-run-real-handler
3453 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3455 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3456 "Like `copy-directory' for Tramp files."
3457 (let ((t1 (tramp-tramp-file-p dirname))
3458 (t2 (tramp-tramp-file-p newname)))
3459 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3460 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3461 ;; When DIRNAME and NEWNAME are remote, they must have
3462 ;; the same method.
3463 (or (null t1) (null t2)
3464 (string-equal
3465 (tramp-file-name-method (tramp-dissect-file-name dirname))
3466 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3467 ;; scp or rsync DTRT.
3468 (progn
3469 (setq dirname (directory-file-name (expand-file-name dirname))
3470 newname (directory-file-name (expand-file-name newname)))
3471 (if (and (file-directory-p newname)
3472 (not (string-equal (file-name-nondirectory dirname)
3473 (file-name-nondirectory newname))))
3474 (setq newname
3475 (expand-file-name
3476 (file-name-nondirectory dirname) newname)))
3477 (if (not (file-directory-p (file-name-directory newname)))
3478 (make-directory (file-name-directory newname) parents))
3479 (tramp-do-copy-or-rename-file-out-of-band
3480 'copy dirname newname keep-date))
3481 ;; We must do it file-wise.
3482 (tramp-run-real-handler
3483 'copy-directory (list dirname newname keep-date parents)))
3485 ;; When newname did exist, we have wrong cached values.
3486 (when t2
3487 (with-parsed-tramp-file-name newname nil
3488 (tramp-flush-file-property v (file-name-directory localname))
3489 (tramp-flush-file-property v localname))))))
3491 (defun tramp-handle-rename-file
3492 (filename newname &optional ok-if-already-exists)
3493 "Like `rename-file' for Tramp files."
3494 ;; Check if both files are local -- invoke normal rename-file.
3495 ;; Otherwise, use Tramp from local system.
3496 (setq filename (expand-file-name filename))
3497 (setq newname (expand-file-name newname))
3498 ;; At least one file a Tramp file?
3499 (if (or (tramp-tramp-file-p filename)
3500 (tramp-tramp-file-p newname))
3501 (tramp-do-copy-or-rename-file
3502 'rename filename newname ok-if-already-exists t t)
3503 (tramp-run-real-handler
3504 'rename-file (list filename newname ok-if-already-exists))))
3506 (defun tramp-do-copy-or-rename-file
3507 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3508 "Copy or rename a remote file.
3509 OP must be `copy' or `rename' and indicates the operation to perform.
3510 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3511 the new file (for copy) or the new name of the file (for rename).
3512 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3513 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3514 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3515 the uid and gid if both files are on the same host.
3517 This function is invoked by `tramp-handle-copy-file' and
3518 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3519 and `rename'. FILENAME and NEWNAME must be absolute file names."
3520 (unless (memq op '(copy rename))
3521 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3522 (let ((t1 (tramp-tramp-file-p filename))
3523 (t2 (tramp-tramp-file-p newname)))
3525 (when (and (not ok-if-already-exists) (file-exists-p newname))
3526 (with-parsed-tramp-file-name (if t1 filename newname) nil
3527 (tramp-error
3528 v 'file-already-exists "File %s already exists" newname)))
3530 (with-parsed-tramp-file-name (if t1 filename newname) nil
3531 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3533 (prog1
3534 (cond
3535 ;; Both are Tramp files.
3536 ((and t1 t2)
3537 (with-parsed-tramp-file-name filename v1
3538 (with-parsed-tramp-file-name newname v2
3539 (cond
3540 ;; Shortcut: if method, host, user are the same for both
3541 ;; files, we invoke `cp' or `mv' on the remote host
3542 ;; directly.
3543 ((tramp-equal-remote filename newname)
3544 (tramp-do-copy-or-rename-file-directly
3545 op filename newname
3546 ok-if-already-exists keep-date preserve-uid-gid))
3548 ;; Try out-of-band operation.
3549 ((tramp-method-out-of-band-p
3550 v1 (nth 7 (file-attributes filename)))
3551 (tramp-do-copy-or-rename-file-out-of-band
3552 op filename newname keep-date))
3554 ;; No shortcut was possible. So we copy the
3555 ;; file first. If the operation was `rename', we go
3556 ;; back and delete the original file (if the copy was
3557 ;; successful). The approach is simple-minded: we
3558 ;; create a new buffer, insert the contents of the
3559 ;; source file into it, then write out the buffer to
3560 ;; the target file. The advantage is that it doesn't
3561 ;; matter which filename handlers are used for the
3562 ;; source and target file.
3564 (tramp-do-copy-or-rename-file-via-buffer
3565 op filename newname keep-date))))))
3567 ;; One file is a Tramp file, the other one is local.
3568 ((or t1 t2)
3569 (with-parsed-tramp-file-name (if t1 filename newname) nil
3570 (cond
3571 ;; Fast track on local machine.
3572 ((tramp-local-host-p v)
3573 (tramp-do-copy-or-rename-file-directly
3574 op filename newname
3575 ok-if-already-exists keep-date preserve-uid-gid))
3577 ;; If the Tramp file has an out-of-band method, the corresponding
3578 ;; copy-program can be invoked.
3579 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3580 (tramp-do-copy-or-rename-file-out-of-band
3581 op filename newname keep-date))
3583 ;; Use the inline method via a Tramp buffer.
3584 (t (tramp-do-copy-or-rename-file-via-buffer
3585 op filename newname keep-date)))))
3588 ;; One of them must be a Tramp file.
3589 (error "Tramp implementation says this cannot happen")))
3591 ;; In case of `rename', we must flush the cache of the source file.
3592 (when (and t1 (eq op 'rename))
3593 (with-parsed-tramp-file-name filename nil
3594 (tramp-flush-file-property v (file-name-directory localname))
3595 (tramp-flush-file-property v localname)))
3597 ;; When newname did exist, we have wrong cached values.
3598 (when t2
3599 (with-parsed-tramp-file-name newname nil
3600 (tramp-flush-file-property v (file-name-directory localname))
3601 (tramp-flush-file-property v localname)))
3603 (with-parsed-tramp-file-name (if t1 filename newname) nil
3604 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
3606 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3607 "Use an Emacs buffer to copy or rename a file.
3608 First arg OP is either `copy' or `rename' and indicates the operation.
3609 FILENAME is the source file, NEWNAME the target file.
3610 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3611 (with-temp-buffer
3612 ;; We must disable multibyte, because binary data shall not be
3613 ;; converted.
3614 (set-buffer-multibyte nil)
3615 (let ((coding-system-for-read 'binary)
3616 (jka-compr-inhibit t))
3617 (insert-file-contents-literally filename))
3618 ;; We don't want the target file to be compressed, so we let-bind
3619 ;; `jka-compr-inhibit' to t.
3620 (let ((coding-system-for-write 'binary)
3621 (jka-compr-inhibit t))
3622 (write-region (point-min) (point-max) newname)))
3623 ;; KEEP-DATE handling.
3624 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3625 ;; Set the mode.
3626 (set-file-modes newname (tramp-default-file-modes filename))
3627 ;; If the operation was `rename', delete the original file.
3628 (unless (eq op 'copy) (delete-file filename)))
3630 (defun tramp-do-copy-or-rename-file-directly
3631 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3632 "Invokes `cp' or `mv' on the remote system.
3633 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3634 respectively. FILENAME specifies the file to copy or rename,
3635 NEWNAME is the name of the new file (for copy) or the new name of
3636 the file (for rename). Both files must reside on the same host.
3637 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3638 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3639 the uid and gid from FILENAME."
3640 (let ((t1 (tramp-tramp-file-p filename))
3641 (t2 (tramp-tramp-file-p newname))
3642 (file-times (nth 5 (file-attributes filename)))
3643 (file-modes (tramp-default-file-modes filename)))
3644 (with-parsed-tramp-file-name (if t1 filename newname) nil
3645 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3646 ((eq op 'copy) "cp -f")
3647 ((eq op 'rename) "mv -f")
3648 (t (tramp-error
3649 v 'file-error
3650 "Unknown operation `%s', must be `copy' or `rename'"
3651 op))))
3652 (localname1
3653 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3654 (localname2
3655 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
3656 (prefix (file-remote-p (if t1 filename newname)))
3657 cmd-result)
3659 (cond
3660 ;; Both files are on a remote host, with same user.
3661 ((and t1 t2)
3662 (setq cmd-result
3663 (tramp-send-command-and-check
3665 (format "%s %s %s" cmd
3666 (tramp-shell-quote-argument localname1)
3667 (tramp-shell-quote-argument localname2))))
3668 (with-current-buffer (tramp-get-buffer v)
3669 (goto-char (point-min))
3670 (unless
3672 (and keep-date
3673 ;; Mask cp -f error.
3674 (re-search-forward
3675 tramp-operation-not-permitted-regexp nil t))
3676 (zerop cmd-result))
3677 (tramp-error-with-buffer
3678 nil v 'file-error
3679 "Copying directly failed, see buffer `%s' for details."
3680 (buffer-name)))))
3682 ;; We are on the local host.
3683 ((or t1 t2)
3684 (cond
3685 ;; We can do it directly.
3686 ((let (file-name-handler-alist)
3687 (and (file-readable-p localname1)
3688 (file-writable-p (file-name-directory localname2))
3689 (or (file-directory-p localname2)
3690 (file-writable-p localname2))))
3691 (if (eq op 'copy)
3692 (tramp-compat-copy-file
3693 localname1 localname2 ok-if-already-exists
3694 keep-date preserve-uid-gid)
3695 (tramp-run-real-handler
3696 'rename-file (list localname1 localname2 ok-if-already-exists))))
3698 ;; We can do it directly with `tramp-send-command'
3699 ((and (file-readable-p (concat prefix localname1))
3700 (file-writable-p
3701 (file-name-directory (concat prefix localname2)))
3702 (or (file-directory-p (concat prefix localname2))
3703 (file-writable-p (concat prefix localname2))))
3704 (tramp-do-copy-or-rename-file-directly
3705 op (concat prefix localname1) (concat prefix localname2)
3706 ok-if-already-exists keep-date t)
3707 ;; We must change the ownership to the local user.
3708 (tramp-set-file-uid-gid
3709 (concat prefix localname2)
3710 (tramp-get-local-uid 'integer)
3711 (tramp-get-local-gid 'integer)))
3713 ;; We need a temporary file in between.
3715 ;; Create the temporary file.
3716 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3717 (unwind-protect
3718 (progn
3719 (cond
3722 (zerop
3723 (tramp-send-command-and-check
3724 v (format
3725 "%s %s %s" cmd
3726 (tramp-shell-quote-argument localname1)
3727 (tramp-shell-quote-argument tmpfile))))
3728 (tramp-error-with-buffer
3729 nil v 'file-error
3730 "Copying directly failed, see buffer `%s' for details."
3731 (tramp-get-buffer v)))
3732 ;; We must change the ownership as remote user.
3733 ;; Since this does not work reliable, we also
3734 ;; give read permissions.
3735 (set-file-modes
3736 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3737 (tramp-set-file-uid-gid
3738 (concat prefix tmpfile)
3739 (tramp-get-local-uid 'integer)
3740 (tramp-get-local-gid 'integer)))
3742 (if (eq op 'copy)
3743 (tramp-compat-copy-file
3744 localname1 tmpfile t
3745 keep-date preserve-uid-gid)
3746 (tramp-run-real-handler
3747 'rename-file
3748 (list localname1 tmpfile t)))
3749 ;; We must change the ownership as local user.
3750 ;; Since this does not work reliable, we also
3751 ;; give read permissions.
3752 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3753 (tramp-set-file-uid-gid
3754 tmpfile
3755 (tramp-get-remote-uid v 'integer)
3756 (tramp-get-remote-gid v 'integer))))
3758 ;; Move the temporary file to its destination.
3759 (cond
3762 (zerop
3763 (tramp-send-command-and-check
3764 v (format
3765 "cp -f -p %s %s"
3766 (tramp-shell-quote-argument tmpfile)
3767 (tramp-shell-quote-argument localname2))))
3768 (tramp-error-with-buffer
3769 nil v 'file-error
3770 "Copying directly failed, see buffer `%s' for details."
3771 (tramp-get-buffer v))))
3773 (tramp-run-real-handler
3774 'rename-file
3775 (list tmpfile localname2 ok-if-already-exists)))))
3777 ;; Save exit.
3778 (condition-case nil
3779 (delete-file tmpfile)
3780 (error)))))))))
3782 ;; Set the time and mode. Mask possible errors.
3783 (condition-case nil
3784 (when keep-date
3785 (set-file-times newname file-times)
3786 (set-file-modes newname file-modes))
3787 (error)))))
3789 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3790 "Invoke rcp program to copy.
3791 The method used must be an out-of-band method."
3792 (let ((t1 (tramp-tramp-file-p filename))
3793 (t2 (tramp-tramp-file-p newname))
3794 copy-program copy-args copy-env copy-keep-date port spec
3795 source target)
3797 (with-parsed-tramp-file-name (if t1 filename newname) nil
3798 (if (and t1 t2)
3800 ;; Both are Tramp files. We shall optimize it, when the
3801 ;; methods for filename and newname are the same.
3802 (let* ((dir-flag (file-directory-p filename))
3803 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3804 (if dir-flag
3805 (setq tmpfile
3806 (expand-file-name
3807 (file-name-nondirectory newname) tmpfile)))
3808 (unwind-protect
3809 (progn
3810 (tramp-do-copy-or-rename-file-out-of-band
3811 op filename tmpfile keep-date)
3812 (tramp-do-copy-or-rename-file-out-of-band
3813 'rename tmpfile newname keep-date))
3814 ;; Save exit.
3815 (condition-case nil
3816 (if dir-flag
3817 (delete-directory
3818 (expand-file-name ".." tmpfile) 'recursive)
3819 (delete-file tmpfile))
3820 (error))))
3822 ;; Expand hops. Might be necessary for gateway methods.
3823 (setq v (car (tramp-compute-multi-hops v)))
3824 (aset v 3 localname)
3826 ;; Check which ones of source and target are Tramp files.
3827 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3828 target (funcall
3829 (if (and (file-directory-p filename)
3830 (string-equal
3831 (file-name-nondirectory filename)
3832 (file-name-nondirectory newname)))
3833 'file-name-directory
3834 'identity)
3835 (if t2 (tramp-make-copy-program-file-name v) newname)))
3837 ;; Check for port number. Until now, there's no need for handling
3838 ;; like method, user, host.
3839 (setq host (tramp-file-name-real-host v)
3840 port (tramp-file-name-port v)
3841 port (or (and port (number-to-string port)) ""))
3843 ;; Compose copy command.
3844 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3845 (?t . ,(tramp-get-connection-property
3846 (tramp-get-connection-process v) "temp-file" ""))
3847 (?k . ,(if keep-date " " "")))
3848 copy-program (tramp-get-method-parameter
3849 method 'tramp-copy-program)
3850 copy-keep-date (tramp-get-method-parameter
3851 method 'tramp-copy-keep-date)
3852 copy-args
3853 (delq
3855 (mapcar
3856 (lambda (x)
3857 (setq
3859 ;; " " is indication for keep-date argument.
3860 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3861 (unless (member "" x) (mapconcat 'identity x " ")))
3862 (tramp-get-method-parameter method 'tramp-copy-args)))
3863 copy-env
3864 (delq
3866 (mapcar
3867 (lambda (x)
3868 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3869 (unless (member "" x) (mapconcat 'identity x " ")))
3870 (tramp-get-method-parameter method 'tramp-copy-env))))
3872 ;; Check for program.
3873 (when (and (fboundp 'executable-find)
3874 (not (let ((default-directory
3875 (tramp-compat-temporary-file-directory)))
3876 (executable-find copy-program))))
3877 (tramp-error
3878 v 'file-error "Cannot find copy program: %s" copy-program))
3880 ;; Set variables for computing the prompt for reading
3881 ;; password.
3882 (setq tramp-current-method (tramp-file-name-method v)
3883 tramp-current-user (tramp-file-name-user v)
3884 tramp-current-host (tramp-file-name-host v))
3886 (unwind-protect
3887 (with-temp-buffer
3888 ;; The default directory must be remote.
3889 (let ((default-directory
3890 (file-name-directory (if t1 filename newname)))
3891 (process-environment (copy-sequence process-environment)))
3892 ;; Set the transfer process properties.
3893 (tramp-set-connection-property
3894 v "process-name" (buffer-name (current-buffer)))
3895 (tramp-set-connection-property
3896 v "process-buffer" (current-buffer))
3897 (while copy-env
3898 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3899 (setenv (pop copy-env) (pop copy-env)))
3901 ;; Use an asynchronous process. By this, password can
3902 ;; be handled. The default directory must be local, in
3903 ;; order to apply the correct `copy-program'. We don't
3904 ;; set a timeout, because the copying of large files can
3905 ;; last longer than 60 secs.
3906 (let ((p (let ((default-directory
3907 (tramp-compat-temporary-file-directory)))
3908 (apply 'start-process
3909 (tramp-get-connection-property
3910 v "process-name" nil)
3911 (tramp-get-connection-property
3912 v "process-buffer" nil)
3913 copy-program
3914 (append copy-args (list source target))))))
3915 (tramp-message
3916 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3917 (tramp-set-process-query-on-exit-flag p nil)
3918 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
3920 ;; Reset the transfer process properties.
3921 (tramp-set-connection-property v "process-name" nil)
3922 (tramp-set-connection-property v "process-buffer" nil))
3924 ;; Handle KEEP-DATE argument.
3925 (when (and keep-date (not copy-keep-date))
3926 (set-file-times newname (nth 5 (file-attributes filename))))
3928 ;; Set the mode.
3929 (unless (and keep-date copy-keep-date)
3930 (ignore-errors
3931 (set-file-modes newname (tramp-default-file-modes filename)))))
3933 ;; If the operation was `rename', delete the original file.
3934 (unless (eq op 'copy)
3935 (if (file-regular-p filename)
3936 (delete-file filename)
3937 (delete-directory filename 'recursive))))))
3939 (defun tramp-handle-make-directory (dir &optional parents)
3940 "Like `make-directory' for Tramp files."
3941 (setq dir (expand-file-name dir))
3942 (with-parsed-tramp-file-name dir nil
3943 (tramp-flush-directory-property v (file-name-directory localname))
3944 (save-excursion
3945 (tramp-barf-unless-okay
3947 (format "%s %s"
3948 (if parents "mkdir -p" "mkdir")
3949 (tramp-shell-quote-argument localname))
3950 "Couldn't make directory %s" dir))))
3952 (defun tramp-handle-delete-directory (directory &optional recursive)
3953 "Like `delete-directory' for Tramp files."
3954 (setq directory (expand-file-name directory))
3955 (with-parsed-tramp-file-name directory nil
3956 (tramp-flush-file-property v (file-name-directory localname))
3957 (tramp-flush-directory-property v localname)
3958 (unless (zerop (tramp-send-command-and-check
3960 (format
3961 "%s %s"
3962 (if recursive "rm -rf" "rmdir")
3963 (tramp-shell-quote-argument localname))))
3964 (tramp-error v 'file-error "Couldn't delete %s" directory))))
3966 (defun tramp-handle-delete-file (filename)
3967 "Like `delete-file' for Tramp files."
3968 (setq filename (expand-file-name filename))
3969 (with-parsed-tramp-file-name filename nil
3970 (tramp-flush-file-property v (file-name-directory localname))
3971 (tramp-flush-file-property v localname)
3972 (unless (zerop (tramp-send-command-and-check
3974 (format "rm -f %s"
3975 (tramp-shell-quote-argument localname))))
3976 (tramp-error v 'file-error "Couldn't delete %s" filename))))
3978 ;; Dired.
3980 ;; CCC: This does not seem to be enough. Something dies when
3981 ;; we try and delete two directories under Tramp :/
3982 (defun tramp-handle-dired-recursive-delete-directory (filename)
3983 "Recursively delete the directory given.
3984 This is like `dired-recursive-delete-directory' for Tramp files."
3985 (with-parsed-tramp-file-name filename nil
3986 ;; Run a shell command 'rm -r <localname>'
3987 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
3988 (unless (file-exists-p filename)
3989 (tramp-error v 'file-error "No such directory: %s" filename))
3990 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
3991 (tramp-send-command
3993 (format "rm -rf %s" (tramp-shell-quote-argument localname))
3994 ;; Don't read the output, do it explicitely.
3995 nil t)
3996 ;; Wait for the remote system to return to us...
3997 ;; This might take a while, allow it plenty of time.
3998 (tramp-wait-for-output (tramp-get-connection-process v) 120)
3999 ;; Make sure that it worked...
4000 (tramp-flush-file-property v (file-name-directory localname))
4001 (tramp-flush-directory-property v localname)
4002 (and (file-exists-p filename)
4003 (tramp-error
4004 v 'file-error "Failed to recursively delete %s" filename))))
4006 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4007 "Like `dired-compress-file' for Tramp files."
4008 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4009 ;; Code stolen mainly from dired-aux.el.
4010 (with-parsed-tramp-file-name file nil
4011 (tramp-flush-file-property v localname)
4012 (save-excursion
4013 (let ((suffixes
4014 (if (not (featurep 'xemacs))
4015 ;; Emacs case
4016 (symbol-value 'dired-compress-file-suffixes)
4017 ;; XEmacs has `dired-compression-method-alist', which is
4018 ;; transformed into `dired-compress-file-suffixes' structure.
4019 (mapcar
4020 (lambda (x)
4021 (list (concat (regexp-quote (nth 1 x)) "\\'")
4023 (mapconcat 'identity (nth 3 x) " ")))
4024 (symbol-value 'dired-compression-method-alist))))
4025 suffix)
4026 ;; See if any suffix rule matches this file name.
4027 (while suffixes
4028 (let (case-fold-search)
4029 (if (string-match (car (car suffixes)) localname)
4030 (setq suffix (car suffixes) suffixes nil))
4031 (setq suffixes (cdr suffixes))))
4033 (cond ((file-symlink-p file)
4034 nil)
4035 ((and suffix (nth 2 suffix))
4036 ;; We found an uncompression rule.
4037 (tramp-message v 0 "Uncompressing %s..." file)
4038 (when (zerop (tramp-send-command-and-check
4039 v (concat (nth 2 suffix) " "
4040 (tramp-shell-quote-argument localname))))
4041 (tramp-message v 0 "Uncompressing %s...done" file)
4042 ;; `dired-remove-file' is not defined in XEmacs
4043 (funcall (symbol-function 'dired-remove-file) file)
4044 (string-match (car suffix) file)
4045 (concat (substring file 0 (match-beginning 0)))))
4047 ;; We don't recognize the file as compressed, so compress it.
4048 ;; Try gzip.
4049 (tramp-message v 0 "Compressing %s..." file)
4050 (when (zerop (tramp-send-command-and-check
4051 v (concat "gzip -f "
4052 (tramp-shell-quote-argument localname))))
4053 (tramp-message v 0 "Compressing %s...done" file)
4054 ;; `dired-remove-file' is not defined in XEmacs
4055 (funcall (symbol-function 'dired-remove-file) file)
4056 (cond ((file-exists-p (concat file ".gz"))
4057 (concat file ".gz"))
4058 ((file-exists-p (concat file ".z"))
4059 (concat file ".z"))
4060 (t nil)))))))))
4062 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4063 "Like `dired-uncache' for Tramp files."
4064 ;; DIR-P is valid for XEmacs only.
4065 (with-parsed-tramp-file-name
4066 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4067 (tramp-flush-file-property v localname)))
4069 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4070 ;; not sure at all that this is the right way to do it, but let's hope
4071 ;; it works for now, and wait for a guru to point out the Right Way to
4072 ;; achieve this.
4073 ;;(eval-when-compile
4074 ;; (unless (fboundp 'dired-insert-set-properties)
4075 ;; (fset 'dired-insert-set-properties 'ignore)))
4076 ;; Gerd suggests this:
4077 (eval-when-compile (require 'dired))
4078 ;; Note that dired is required at run-time, too, when it is needed.
4079 ;; It is only needed on XEmacs for the function
4080 ;; `dired-insert-set-properties'.
4082 (defun tramp-handle-insert-directory
4083 (filename switches &optional wildcard full-directory-p)
4084 "Like `insert-directory' for Tramp files."
4085 (setq filename (expand-file-name filename))
4086 (with-parsed-tramp-file-name filename nil
4087 (if (and (featurep 'ls-lisp)
4088 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4089 (tramp-run-real-handler
4090 'insert-directory (list filename switches wildcard full-directory-p))
4091 (when (stringp switches)
4092 (setq switches (split-string switches)))
4093 (when (and (member "--dired" switches)
4094 (not (tramp-get-ls-command-with-dired v)))
4095 (setq switches (delete "--dired" switches)))
4096 (when wildcard
4097 (setq wildcard (tramp-run-real-handler
4098 'file-name-nondirectory (list localname)))
4099 (setq localname (tramp-run-real-handler
4100 'file-name-directory (list localname))))
4101 (unless full-directory-p
4102 (setq switches (add-to-list 'switches "-d" 'append)))
4103 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4104 (when wildcard
4105 (setq switches (concat switches " " wildcard)))
4106 (tramp-message
4107 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4108 switches filename (if wildcard "yes" "no")
4109 (if full-directory-p "yes" "no"))
4110 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4111 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4112 (if full-directory-p
4113 (tramp-send-command
4115 (format "%s %s %s 2>/dev/null"
4116 (tramp-get-ls-command v)
4117 switches
4118 (if wildcard
4119 localname
4120 (tramp-shell-quote-argument (concat localname ".")))))
4121 (tramp-barf-unless-okay
4123 (format "cd %s" (tramp-shell-quote-argument
4124 (tramp-run-real-handler
4125 'file-name-directory (list localname))))
4126 "Couldn't `cd %s'"
4127 (tramp-shell-quote-argument
4128 (tramp-run-real-handler 'file-name-directory (list localname))))
4129 (tramp-send-command
4131 (format "%s %s %s"
4132 (tramp-get-ls-command v)
4133 switches
4134 (if (or wildcard
4135 (zerop (length
4136 (tramp-run-real-handler
4137 'file-name-nondirectory (list localname)))))
4139 (tramp-shell-quote-argument
4140 (tramp-run-real-handler
4141 'file-name-nondirectory (list localname)))))))
4142 (let ((beg (point)))
4143 ;; We cannot use `insert-buffer-substring' because the Tramp
4144 ;; buffer changes its contents before insertion due to calling
4145 ;; `expand-file' and alike.
4146 (insert
4147 (with-current-buffer (tramp-get-buffer v)
4148 (buffer-string)))
4150 ;; Check for "--dired" output.
4151 (forward-line -2)
4152 (when (looking-at "//SUBDIRED//")
4153 (forward-line -1))
4154 (when (looking-at "//DIRED//")
4155 (let ((end (tramp-compat-line-end-position))
4156 (linebeg (point)))
4157 ;; Now read the numeric positions of file names.
4158 (goto-char linebeg)
4159 (forward-word 1)
4160 (forward-char 3)
4161 (while (< (point) end)
4162 (let ((start (+ beg (read (current-buffer))))
4163 (end (+ beg (read (current-buffer)))))
4164 (if (memq (char-after end) '(?\n ?\ ))
4165 ;; End is followed by \n or by " -> ".
4166 (put-text-property start end 'dired-filename t))))))
4167 ;; Remove trailing lines.
4168 (goto-char (tramp-compat-line-beginning-position))
4169 (while (looking-at "//")
4170 (forward-line 1)
4171 (delete-region (match-beginning 0) (point)))
4173 ;; The inserted file could be from somewhere else.
4174 (when (and (not wildcard) (not full-directory-p))
4175 (goto-char (point-max))
4176 (when (file-symlink-p filename)
4177 (goto-char (search-backward "->" beg 'noerror)))
4178 (search-backward
4179 (if (zerop (length (file-name-nondirectory filename)))
4181 (file-name-nondirectory filename))
4182 beg 'noerror)
4183 (replace-match (file-relative-name filename) t))
4185 (goto-char (point-max))))))
4187 (defun tramp-handle-unhandled-file-name-directory (filename)
4188 "Like `unhandled-file-name-directory' for Tramp files."
4189 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4190 ;; for backward compatibility.
4191 (expand-file-name "~/"))
4193 ;; Canonicalization of file names.
4195 (defun tramp-handle-expand-file-name (name &optional dir)
4196 "Like `expand-file-name' for Tramp files.
4197 If the localname part of the given filename starts with \"/../\" then
4198 the result will be a local, non-Tramp, filename."
4199 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4200 (setq dir (or dir default-directory "/"))
4201 ;; Unless NAME is absolute, concat DIR and NAME.
4202 (unless (file-name-absolute-p name)
4203 (setq name (concat (file-name-as-directory dir) name)))
4204 ;; If NAME is not a Tramp file, run the real handler.
4205 (if (not (tramp-tramp-file-p name))
4206 (tramp-run-real-handler 'expand-file-name (list name nil))
4207 ;; Dissect NAME.
4208 (with-parsed-tramp-file-name name nil
4209 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4210 (setq localname (concat "~/" localname)))
4211 ;; Tilde expansion if necessary. This needs a shell which
4212 ;; groks tilde expansion! The function `tramp-find-shell' is
4213 ;; supposed to find such a shell on the remote host. Please
4214 ;; tell me about it when this doesn't work on your system.
4215 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4216 (let ((uname (match-string 1 localname))
4217 (fname (match-string 2 localname)))
4218 ;; We cannot simply apply "~/", because under sudo "~/" is
4219 ;; expanded to the local user home directory but to the
4220 ;; root home directory. On the other hand, using always
4221 ;; the default user name for tilde expansion is not
4222 ;; appropriate either, because ssh and companions might
4223 ;; use a user name from the config file.
4224 (when (and (string-equal uname "~")
4225 (string-match "\\`su\\(do\\)?\\'" method))
4226 (setq uname (concat uname user)))
4227 (setq uname
4228 (with-connection-property v uname
4229 (tramp-send-command
4230 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4231 (with-current-buffer (tramp-get-buffer v)
4232 (goto-char (point-min))
4233 (buffer-substring
4234 (point) (tramp-compat-line-end-position)))))
4235 (setq localname (concat uname fname))))
4236 ;; There might be a double slash, for example when "~/"
4237 ;; expands to "/". Remove this.
4238 (while (string-match "//" localname)
4239 (setq localname (replace-match "/" t t localname)))
4240 ;; No tilde characters in file name, do normal
4241 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4242 ;; `directory-sep-char' here for XEmacs on Windows, which would
4243 ;; otherwise use backslash. `default-directory' is bound,
4244 ;; because on Windows there would be problems with UNC shares or
4245 ;; Cygwin mounts.
4246 (let ((directory-sep-char ?/)
4247 (default-directory (tramp-compat-temporary-file-directory)))
4248 (tramp-make-tramp-file-name
4249 method user host
4250 (tramp-drop-volume-letter
4251 (tramp-run-real-handler
4252 'expand-file-name (list localname))))))))
4254 (defun tramp-replace-environment-variables (filename)
4255 "Replace environment variables in FILENAME.
4256 Return the string with the replaced variables."
4257 (save-match-data
4258 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4259 ;; `$' is coded as `$$'.
4260 (when (and idx
4261 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4262 (getenv (match-string 1 filename)))
4263 (setq filename
4264 (replace-match
4265 (substitute-in-file-name (match-string 0 filename))
4266 t nil filename)))
4267 filename)))
4269 (defun tramp-handle-substitute-in-file-name (filename)
4270 "Like `substitute-in-file-name' for Tramp files.
4271 \"//\" and \"/~\" substitute only in the local filename part.
4272 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4273 beginning of local filename are not substituted."
4274 ;; First, we must replace environment variables.
4275 (setq filename (tramp-replace-environment-variables filename))
4276 (with-parsed-tramp-file-name filename nil
4277 (if (equal tramp-syntax 'url)
4278 ;; We need to check localname only. The other parts cannot contain
4279 ;; "//" or "/~".
4280 (if (and (> (length localname) 1)
4281 (or (string-match "//" localname)
4282 (string-match "/~" localname 1)))
4283 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4284 (tramp-make-tramp-file-name
4285 (when method (substitute-in-file-name method))
4286 (when user (substitute-in-file-name user))
4287 (when host (substitute-in-file-name host))
4288 (when localname
4289 (tramp-run-real-handler
4290 'substitute-in-file-name (list localname)))))
4291 ;; Ignore in LOCALNAME everything before "//" or "/~".
4292 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4293 (setq filename
4294 (concat (file-remote-p filename)
4295 (replace-match "\\1" nil nil localname)))
4296 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4297 (when (string-match "~$" filename)
4298 (setq filename (concat filename "/"))))
4299 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4301 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4302 ;; which calls corresponding functions (see minibuf.el).
4303 (when (fboundp 'minibuffer-electric-separator)
4304 (mapc
4305 (lambda (x)
4306 (eval
4307 `(defadvice ,x
4308 (around ,(intern (format "tramp-advice-%s" x)) activate)
4309 "Invoke `substitute-in-file-name' for Tramp files."
4310 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4311 (tramp-tramp-file-p (buffer-substring)))
4312 ;; We don't need to handle `last-input-event', because
4313 ;; due to the key map we know it must be ?/ or ?~.
4314 (let ((s (concat (buffer-substring (point-min) (point))
4315 (string last-command-char))))
4316 (delete-region (point-min) (point))
4317 (insert (substitute-in-file-name s))
4318 (setq ad-return-value last-command-char))
4319 ad-do-it)))
4320 (eval
4321 `(add-hook
4322 'tramp-unload-hook
4323 (lambda ()
4324 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4325 (ad-activate ',x)))))
4327 '(minibuffer-electric-separator
4328 minibuffer-electric-tilde)))
4331 ;;; Remote commands:
4333 (defun tramp-handle-executable-find (command)
4334 "Like `executable-find' for Tramp files."
4335 (with-parsed-tramp-file-name default-directory nil
4336 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4338 ;; We use BUFFER also as connection buffer during setup. Because of
4339 ;; this, its original contents must be saved, and restored once
4340 ;; connection has been setup.
4341 (defun tramp-handle-start-file-process (name buffer program &rest args)
4342 "Like `start-file-process' for Tramp files."
4343 (with-parsed-tramp-file-name default-directory nil
4344 (unless (stringp program)
4345 (tramp-error
4346 v 'file-error "pty association is not supported for `%s'" name))
4347 (unwind-protect
4348 (let ((command (format "cd %s; exec %s"
4349 (tramp-shell-quote-argument localname)
4350 (mapconcat 'tramp-shell-quote-argument
4351 (cons program args) " ")))
4352 (name1 name)
4353 (i 0))
4354 (unless buffer
4355 ;; BUFFER can be nil. We use a temporary buffer.
4356 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4357 (while (get-process name1)
4358 ;; NAME must be unique as process name.
4359 (setq i (1+ i)
4360 name1 (format "%s<%d>" name i)))
4361 (setq name name1)
4362 ;; Set the new process properties.
4363 (tramp-set-connection-property v "process-name" name)
4364 (tramp-set-connection-property v "process-buffer" buffer)
4365 ;; Activate narrowing in order to save BUFFER contents.
4366 ;; Clear also the modification time; otherwise we might be
4367 ;; interrupted by `verify-visited-file-modtime'.
4368 (with-current-buffer (tramp-get-connection-buffer v)
4369 (clear-visited-file-modtime)
4370 (narrow-to-region (point-max) (point-max)))
4371 ;; Send the command. `tramp-send-command' opens a new
4372 ;; connection.
4373 (tramp-send-command v command nil t) ; nooutput
4374 ;; Set query flag for this process.
4375 (tramp-set-process-query-on-exit-flag
4376 (tramp-get-connection-process v) t)
4377 ;; Return process.
4378 (tramp-get-connection-process v))
4379 ;; Save exit.
4380 (with-current-buffer (tramp-get-connection-buffer v)
4381 (if (string-match tramp-temp-buffer-name (buffer-name))
4382 (progn
4383 (set-process-buffer (tramp-get-connection-process v) nil)
4384 (kill-buffer (current-buffer)))
4385 (widen)
4386 (goto-char (point-max))))
4387 (tramp-set-connection-property v "process-name" nil)
4388 (tramp-set-connection-property v "process-buffer" nil))))
4390 (defun tramp-handle-process-file
4391 (program &optional infile destination display &rest args)
4392 "Like `process-file' for Tramp files."
4393 ;; The implementation is not complete yet.
4394 (when (and (numberp destination) (zerop destination))
4395 (error "Implementation does not handle immediate return"))
4397 (with-parsed-tramp-file-name default-directory nil
4398 (let (command input tmpinput stderr tmpstderr outbuf ret)
4399 ;; Compute command.
4400 (setq command (mapconcat 'tramp-shell-quote-argument
4401 (cons program args) " "))
4402 ;; Determine input.
4403 (if (null infile)
4404 (setq input "/dev/null")
4405 (setq infile (expand-file-name infile))
4406 (if (tramp-equal-remote default-directory infile)
4407 ;; INFILE is on the same remote host.
4408 (setq input (with-parsed-tramp-file-name infile nil localname))
4409 ;; INFILE must be copied to remote host.
4410 (setq input (tramp-make-tramp-temp-file v)
4411 tmpinput (tramp-make-tramp-file-name method user host input))
4412 (copy-file infile tmpinput t)))
4413 (when input (setq command (format "%s <%s" command input)))
4415 ;; Determine output.
4416 (cond
4417 ;; Just a buffer.
4418 ((bufferp destination)
4419 (setq outbuf destination))
4420 ;; A buffer name.
4421 ((stringp destination)
4422 (setq outbuf (get-buffer-create destination)))
4423 ;; (REAL-DESTINATION ERROR-DESTINATION)
4424 ((consp destination)
4425 ;; output.
4426 (cond
4427 ((bufferp (car destination))
4428 (setq outbuf (car destination)))
4429 ((stringp (car destination))
4430 (setq outbuf (get-buffer-create (car destination))))
4431 ((car destination)
4432 (setq outbuf (current-buffer))))
4433 ;; stderr.
4434 (cond
4435 ((stringp (cadr destination))
4436 (setcar (cdr destination) (expand-file-name (cadr destination)))
4437 (if (tramp-equal-remote default-directory (cadr destination))
4438 ;; stderr is on the same remote host.
4439 (setq stderr (with-parsed-tramp-file-name
4440 (cadr destination) nil localname))
4441 ;; stderr must be copied to remote host. The temporary
4442 ;; file must be deleted after execution.
4443 (setq stderr (tramp-make-tramp-temp-file v)
4444 tmpstderr (tramp-make-tramp-file-name
4445 method user host stderr))))
4446 ;; stderr to be discarded.
4447 ((null (cadr destination))
4448 (setq stderr "/dev/null"))))
4449 ;; 't
4450 (destination
4451 (setq outbuf (current-buffer))))
4452 (when stderr (setq command (format "%s 2>%s" command stderr)))
4454 ;; Send the command. It might not return in time, so we protect it.
4455 (condition-case nil
4456 (unwind-protect
4457 (setq ret
4458 (tramp-send-command-and-check
4459 v (format "\\cd %s; %s"
4460 (tramp-shell-quote-argument localname)
4461 command)
4462 nil t))
4463 ;; We should show the output anyway.
4464 (when outbuf
4465 (with-current-buffer outbuf
4466 (insert
4467 (with-current-buffer (tramp-get-connection-buffer v)
4468 (buffer-string))))
4469 (when display (display-buffer outbuf))))
4470 ;; When the user did interrupt, we should do it also. We use
4471 ;; return code -1 as marker.
4472 (quit
4473 (kill-buffer (tramp-get-connection-buffer v))
4474 (setq ret -1))
4475 ;; Handle errors.
4476 (error
4477 (kill-buffer (tramp-get-connection-buffer v))
4478 (setq ret 1)))
4480 ;; Provide error file.
4481 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4483 ;; Cleanup. We remove all file cache values for the connection,
4484 ;; because the remote process could have changed them.
4485 (when tmpinput (delete-file tmpinput))
4487 ;; `process-file-side-effects' has been introduced with GNU
4488 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4489 ;; by `program'. If it doesn't exist, we assume its default
4490 ;; value 't'.
4491 (unless (and (boundp 'process-file-side-effects)
4492 (not (symbol-value 'process-file-side-effects)))
4493 (tramp-flush-directory-property v ""))
4495 ;; Return exit status.
4496 (if (equal ret -1)
4497 (keyboard-quit)
4498 ret))))
4500 (defun tramp-local-call-process
4501 (program &optional infile destination display &rest args)
4502 "Calls `call-process' on the local host.
4503 This is needed because for some Emacs flavors Tramp has
4504 defadviced `call-process' to behave like `process-file'. The
4505 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4506 (let ((default-directory
4507 (if (file-remote-p default-directory)
4508 (tramp-compat-temporary-file-directory)
4509 default-directory)))
4510 (if (executable-find program)
4511 (apply 'call-process program infile destination display args)
4512 1)))
4514 (defun tramp-handle-call-process-region
4515 (start end program &optional delete buffer display &rest args)
4516 "Like `call-process-region' for Tramp files."
4517 (let ((tmpfile (tramp-compat-make-temp-file "")))
4518 (write-region start end tmpfile)
4519 (when delete (delete-region start end))
4520 (unwind-protect
4521 (apply 'call-process program tmpfile buffer display args)
4522 (delete-file tmpfile))))
4524 (defun tramp-handle-shell-command
4525 (command &optional output-buffer error-buffer)
4526 "Like `shell-command' for Tramp files."
4527 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4528 ;; We cannot use `shell-file-name' and `shell-command-switch',
4529 ;; they are variables of the local host.
4530 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
4531 current-buffer-p
4532 (output-buffer
4533 (cond
4534 ((bufferp output-buffer) output-buffer)
4535 ((stringp output-buffer) (get-buffer-create output-buffer))
4536 (output-buffer
4537 (setq current-buffer-p t)
4538 (current-buffer))
4539 (t (get-buffer-create
4540 (if asynchronous
4541 "*Async Shell Command*"
4542 "*Shell Command Output*")))))
4543 (error-buffer
4544 (cond
4545 ((bufferp error-buffer) error-buffer)
4546 ((stringp error-buffer) (get-buffer-create error-buffer))))
4547 (buffer
4548 (if (and (not asynchronous) error-buffer)
4549 (with-parsed-tramp-file-name default-directory nil
4550 (list output-buffer (tramp-make-tramp-temp-file v)))
4551 output-buffer))
4552 (p (get-buffer-process output-buffer)))
4554 ;; Check whether there is another process running. Tramp does not
4555 ;; support 2 (asynchronous) processes in parallel.
4556 (when p
4557 (if (yes-or-no-p "A command is running. Kill it? ")
4558 (condition-case nil
4559 (kill-process p)
4560 (error nil))
4561 (error "Shell command in progress")))
4563 (if current-buffer-p
4564 (progn
4565 (barf-if-buffer-read-only)
4566 (push-mark nil t))
4567 (with-current-buffer output-buffer
4568 (setq buffer-read-only nil)
4569 (erase-buffer)))
4571 (if (and (not current-buffer-p) (integerp asynchronous))
4572 (prog1
4573 ;; Run the process.
4574 (apply 'start-file-process "*Async Shell*" buffer args)
4575 ;; Display output.
4576 (pop-to-buffer output-buffer)
4577 (setq mode-line-process '(":%s"))
4578 (require 'shell) (shell-mode))
4580 (prog1
4581 ;; Run the process.
4582 (apply 'process-file (car args) nil buffer nil (cdr args))
4583 ;; Insert error messages if they were separated.
4584 (when (listp buffer)
4585 (with-current-buffer error-buffer
4586 (insert-file-contents (cadr buffer)))
4587 (delete-file (cadr buffer)))
4588 (if current-buffer-p
4589 ;; This is like exchange-point-and-mark, but doesn't
4590 ;; activate the mark. It is cleaner to avoid activation,
4591 ;; even though the command loop would deactivate the mark
4592 ;; because we inserted text.
4593 (goto-char (prog1 (mark t)
4594 (set-marker (mark-marker) (point)
4595 (current-buffer))))
4596 ;; There's some output, display it.
4597 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4598 (if (functionp 'display-message-or-buffer)
4599 (funcall (symbol-function 'display-message-or-buffer)
4600 output-buffer)
4601 (pop-to-buffer output-buffer))))))))
4603 ;; File Editing.
4605 (defvar tramp-handle-file-local-copy-hook nil
4606 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4608 (defun tramp-handle-file-local-copy (filename)
4609 "Like `file-local-copy' for Tramp files."
4611 (with-parsed-tramp-file-name filename nil
4612 (unless (file-exists-p filename)
4613 (tramp-error
4614 v 'file-error
4615 "Cannot make local copy of non-existing file `%s'" filename))
4617 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
4618 (loc-dec (tramp-get-local-coding v "local-decoding"))
4619 (tmpfile (tramp-compat-make-temp-file filename)))
4621 (condition-case err
4622 (cond
4623 ;; `copy-file' handles direct copy and out-of-band methods.
4624 ((or (tramp-local-host-p v)
4625 (tramp-method-out-of-band-p
4626 v (nth 7 (file-attributes filename))))
4627 (copy-file filename tmpfile t t))
4629 ;; Use inline encoding for file transfer.
4630 (rem-enc
4631 (save-excursion
4632 (tramp-message v 5 "Encoding remote file %s..." filename)
4633 (tramp-barf-unless-okay
4635 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4636 "Encoding remote file failed")
4637 (tramp-message v 5 "Encoding remote file %s...done" filename)
4639 (if (and (symbolp loc-dec) (fboundp loc-dec))
4640 ;; If local decoding is a function, we call it. We
4641 ;; must disable multibyte, because
4642 ;; `uudecode-decode-region' doesn't handle it
4643 ;; correctly.
4644 (with-temp-buffer
4645 (set-buffer-multibyte nil)
4646 (insert-buffer-substring (tramp-get-buffer v))
4647 (tramp-message
4648 v 5 "Decoding remote file %s with function %s..."
4649 filename loc-dec)
4650 (funcall loc-dec (point-min) (point-max))
4651 ;; Unset `file-name-handler-alist'. Otherwise,
4652 ;; epa-file gets confused.
4653 (let (file-name-handler-alist
4654 (coding-system-for-write 'binary))
4655 (write-region (point-min) (point-max) tmpfile)))
4657 ;; If tramp-decoding-function is not defined for this
4658 ;; method, we invoke tramp-decoding-command instead.
4659 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4660 ;; Unset `file-name-handler-alist'. Otherwise,
4661 ;; epa-file gets confused.
4662 (let (file-name-handler-alist
4663 (coding-system-for-write 'binary))
4664 (write-region (point-min) (point-max) tmpfile2))
4665 (tramp-message
4666 v 5 "Decoding remote file %s with command %s..."
4667 filename loc-dec)
4668 (unwind-protect
4669 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4670 (delete-file tmpfile2))))
4672 (tramp-message v 5 "Decoding remote file %s...done" filename)
4673 ;; Set proper permissions.
4674 (set-file-modes tmpfile (tramp-default-file-modes filename))
4675 ;; Set local user ownership.
4676 (tramp-set-file-uid-gid tmpfile)))
4678 ;; Oops, I don't know what to do.
4679 (t (tramp-error
4680 v 'file-error "Wrong method specification for `%s'" method)))
4682 ;; Error handling.
4683 ((error quit)
4684 (delete-file tmpfile)
4685 (signal (car err) (cdr err))))
4687 (run-hooks 'tramp-handle-file-local-copy-hook)
4688 tmpfile)))
4690 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4691 "Like `file-remote-p' for Tramp files."
4692 (let ((tramp-verbose 3))
4693 (when (tramp-tramp-file-p filename)
4694 (let* ((v (tramp-dissect-file-name filename))
4695 (p (tramp-get-connection-process v))
4696 (c (and p (processp p) (memq (process-status p) '(run open)))))
4697 ;; We expand the file name only, if there is already a connection.
4698 (with-parsed-tramp-file-name
4699 (if c (expand-file-name filename) filename) nil
4700 (and (or (not connected) c)
4701 (cond
4702 ((eq identification 'method) method)
4703 ((eq identification 'user) user)
4704 ((eq identification 'host) host)
4705 ((eq identification 'localname) localname)
4706 (t (tramp-make-tramp-file-name method user host "")))))))))
4708 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4709 "Like `find-operation-coding-system' for Tramp filenames.
4710 Tramp's `insert-file-contents' and `write-region' work over
4711 temporary file names. If `file-coding-system-alist' contains an
4712 expression, which matches more than the file name suffix, the
4713 coding system might not be determined. This function repairs it."
4714 (let (result)
4715 (dolist (elt file-coding-system-alist result)
4716 (when (and (consp elt) (string-match (car elt) filename))
4717 ;; We found a matching entry in `file-coding-system-alist'.
4718 ;; So we add a similar entry, but with the temporary file name
4719 ;; as regexp.
4720 (add-to-list
4721 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4723 (defun tramp-handle-insert-file-contents
4724 (filename &optional visit beg end replace)
4725 "Like `insert-file-contents' for Tramp files."
4726 (barf-if-buffer-read-only)
4727 (setq filename (expand-file-name filename))
4728 (let (coding-system-used result local-copy remote-copy)
4729 (with-parsed-tramp-file-name filename nil
4730 (unwind-protect
4731 (if (not (file-exists-p filename))
4732 ;; We don't raise a Tramp error, because it might be
4733 ;; suppressed, like in `find-file-noselect-1'.
4734 (signal 'file-error
4735 (list "File not found on remote host" filename))
4737 (if (and (tramp-local-host-p v)
4738 (let (file-name-handler-alist)
4739 (file-readable-p localname)))
4740 ;; Short track: if we are on the local host, we can
4741 ;; run directly.
4742 (setq result
4743 (tramp-run-real-handler
4744 'insert-file-contents
4745 (list localname visit beg end replace)))
4747 ;; When we shall insert only a part of the file, we copy
4748 ;; this part.
4749 (when (or beg end)
4750 (setq remote-copy (tramp-make-tramp-temp-file v))
4751 (tramp-send-command
4753 (cond
4754 ((and beg end)
4755 (format "tail -c +%d %s | head -c +%d >%s"
4756 (1+ beg) (tramp-shell-quote-argument localname)
4757 (- end beg) remote-copy))
4758 (beg
4759 (format "tail -c +%d %s >%s"
4760 (1+ beg) (tramp-shell-quote-argument localname)
4761 remote-copy))
4762 (end
4763 (format "head -c +%d %s >%s"
4764 (1+ end) (tramp-shell-quote-argument localname)
4765 remote-copy)))))
4767 ;; `insert-file-contents-literally' takes care to avoid
4768 ;; calling jka-compr. By let-binding
4769 ;; `inhibit-file-name-operation', we propagate that care
4770 ;; to the `file-local-copy' operation.
4771 (setq local-copy
4772 (let ((inhibit-file-name-operation
4773 (when (eq inhibit-file-name-operation
4774 'insert-file-contents)
4775 'file-local-copy)))
4776 (cond
4777 ((stringp remote-copy)
4778 (file-local-copy
4779 (tramp-make-tramp-file-name
4780 method user host remote-copy)))
4781 ((stringp tramp-temp-buffer-file-name)
4782 (copy-file filename tramp-temp-buffer-file-name 'ok)
4783 tramp-temp-buffer-file-name)
4784 (t (file-local-copy filename)))))
4786 ;; When the file is not readable for the owner, it
4787 ;; cannot be inserted, even it is redable for the group
4788 ;; or for everybody.
4789 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4791 (when (and (null remote-copy)
4792 (tramp-get-method-parameter
4793 method 'tramp-copy-keep-tmpfile))
4794 ;; We keep the local file for performance reasons,
4795 ;; useful for "rsync".
4796 (setq tramp-temp-buffer-file-name local-copy)
4797 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4799 (tramp-message
4800 v 4 "Inserting local temp file `%s'..." local-copy)
4802 ;; We must ensure that `file-coding-system-alist'
4803 ;; matches `local-copy'.
4804 (let ((file-coding-system-alist
4805 (tramp-find-file-name-coding-system-alist
4806 filename local-copy)))
4807 (setq result
4808 (insert-file-contents
4809 local-copy nil nil nil replace))
4810 ;; Now `last-coding-system-used' has right value.
4811 ;; Remember it.
4812 (when (boundp 'last-coding-system-used)
4813 (setq coding-system-used
4814 (symbol-value 'last-coding-system-used))))
4816 (tramp-message
4817 v 4 "Inserting local temp file `%s'...done" local-copy)
4818 (when (boundp 'last-coding-system-used)
4819 (set 'last-coding-system-used coding-system-used))))
4821 ;; Save exit.
4822 (progn
4823 (when visit
4824 (setq buffer-file-name filename)
4825 (setq buffer-read-only (not (file-writable-p filename)))
4826 (set-visited-file-modtime)
4827 (set-buffer-modified-p nil))
4828 (when (and (stringp local-copy)
4829 (or remote-copy (null tramp-temp-buffer-file-name)))
4830 (delete-file local-copy))
4831 (when (stringp remote-copy)
4832 (delete-file
4833 (tramp-make-tramp-file-name method user host remote-copy))))))
4835 ;; Result.
4836 (list (expand-file-name filename)
4837 (cadr result))))
4839 ;; This is needed for XEmacs only. Code stolen from files.el.
4840 (defun tramp-handle-insert-file-contents-literally
4841 (filename &optional visit beg end replace)
4842 "Like `insert-file-contents-literally' for Tramp files."
4843 (let ((format-alist nil)
4844 (after-insert-file-functions nil)
4845 (coding-system-for-read 'no-conversion)
4846 (coding-system-for-write 'no-conversion)
4847 (find-buffer-file-type-function
4848 (if (fboundp 'find-buffer-file-type)
4849 (symbol-function 'find-buffer-file-type)
4850 nil))
4851 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4852 (inhibit-file-name-operation 'insert-file-contents))
4853 (unwind-protect
4854 (progn
4855 (fset 'find-buffer-file-type (lambda (filename) t))
4856 (insert-file-contents filename visit beg end replace))
4857 ;; Save exit.
4858 (if find-buffer-file-type-function
4859 (fset 'find-buffer-file-type find-buffer-file-type-function)
4860 (fmakunbound 'find-buffer-file-type)))))
4862 (defun tramp-handle-find-backup-file-name (filename)
4863 "Like `find-backup-file-name' for Tramp files."
4864 (with-parsed-tramp-file-name filename nil
4865 ;; We set both variables. It doesn't matter whether it is
4866 ;; Emacs or XEmacs
4867 (let ((backup-directory-alist
4868 ;; Emacs case
4869 (when (boundp 'backup-directory-alist)
4870 (if (symbol-value 'tramp-backup-directory-alist)
4871 (mapcar
4872 (lambda (x)
4873 (cons
4874 (car x)
4875 (if (and (stringp (cdr x))
4876 (file-name-absolute-p (cdr x))
4877 (not (tramp-file-name-p (cdr x))))
4878 (tramp-make-tramp-file-name method user host (cdr x))
4879 (cdr x))))
4880 (symbol-value 'tramp-backup-directory-alist))
4881 (symbol-value 'backup-directory-alist))))
4883 (bkup-backup-directory-info
4884 ;; XEmacs case
4885 (when (boundp 'bkup-backup-directory-info)
4886 (if (symbol-value 'tramp-bkup-backup-directory-info)
4887 (mapcar
4888 (lambda (x)
4889 (nconc
4890 (list (car x))
4891 (list
4892 (if (and (stringp (car (cdr x)))
4893 (file-name-absolute-p (car (cdr x)))
4894 (not (tramp-file-name-p (car (cdr x)))))
4895 (tramp-make-tramp-file-name
4896 method user host (car (cdr x)))
4897 (car (cdr x))))
4898 (cdr (cdr x))))
4899 (symbol-value 'tramp-bkup-backup-directory-info))
4900 (symbol-value 'bkup-backup-directory-info)))))
4902 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
4904 (defun tramp-handle-make-auto-save-file-name ()
4905 "Like `make-auto-save-file-name' for Tramp files.
4906 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
4907 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4908 (buffer-file-name
4909 (tramp-subst-strs-in-string
4910 '(("_" . "|")
4911 ("/" . "_a")
4912 (":" . "_b")
4913 ("|" . "__")
4914 ("[" . "_l")
4915 ("]" . "_r"))
4916 (buffer-file-name))))
4917 ;; File name must be unique. This is ensured with Emacs 22 (see
4918 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4919 ;; all other cases we must do it ourselves.
4920 (when (boundp 'auto-save-file-name-transforms)
4921 (mapc
4922 (lambda (x)
4923 (when (and (string-match (car x) buffer-file-name)
4924 (not (car (cddr x))))
4925 (setq tramp-auto-save-directory
4926 (or tramp-auto-save-directory
4927 (tramp-compat-temporary-file-directory)))))
4928 (symbol-value 'auto-save-file-name-transforms)))
4929 ;; Create directory.
4930 (when tramp-auto-save-directory
4931 (setq buffer-file-name
4932 (expand-file-name buffer-file-name tramp-auto-save-directory))
4933 (unless (file-exists-p tramp-auto-save-directory)
4934 (make-directory tramp-auto-save-directory t)))
4935 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4936 ;; it is not a magic file name operation (since Emacs 22).
4937 ;; We must deactivate it temporarily.
4938 (if (not (ad-is-active 'make-auto-save-file-name))
4939 (tramp-run-real-handler 'make-auto-save-file-name nil)
4940 ;; else
4941 (ad-deactivate 'make-auto-save-file-name)
4942 (prog1
4943 (tramp-run-real-handler 'make-auto-save-file-name nil)
4944 (ad-activate 'make-auto-save-file-name)))))
4946 (defvar tramp-handle-write-region-hook nil
4947 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4949 ;; CCC grok LOCKNAME
4950 (defun tramp-handle-write-region
4951 (start end filename &optional append visit lockname confirm)
4952 "Like `write-region' for Tramp files."
4953 (setq filename (expand-file-name filename))
4954 (with-parsed-tramp-file-name filename nil
4955 ;; Following part commented out because we don't know what to do about
4956 ;; file locking, and it does not appear to be a problem to ignore it.
4957 ;; Ange-ftp ignores it, too.
4958 ;; (when (and lockname (stringp lockname))
4959 ;; (setq lockname (expand-file-name lockname)))
4960 ;; (unless (or (eq lockname nil)
4961 ;; (string= lockname filename))
4962 ;; (error
4963 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
4965 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
4966 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4967 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4968 (tramp-error v 'file-error "File not overwritten")))
4970 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
4971 (tramp-get-remote-uid v 'integer)))
4972 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
4973 (tramp-get-remote-gid v 'integer))))
4975 (if (and (tramp-local-host-p v)
4976 ;; `file-writable-p' calls `file-expand-file-name'. We
4977 ;; cannot use `tramp-run-real-handler' therefore.
4978 (let (file-name-handler-alist)
4979 (and
4980 (file-writable-p (file-name-directory localname))
4981 (or (file-directory-p localname)
4982 (file-writable-p localname)))))
4983 ;; Short track: if we are on the local host, we can run directly.
4984 (tramp-run-real-handler
4985 'write-region
4986 (list start end localname append 'no-message lockname confirm))
4988 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4989 (loc-enc (tramp-get-local-coding v "local-encoding"))
4990 (modes (save-excursion (tramp-default-file-modes filename)))
4991 ;; We use this to save the value of
4992 ;; `last-coding-system-used' after writing the tmp file.
4993 ;; At the end of the function, we set
4994 ;; `last-coding-system-used' to this saved value. This
4995 ;; way, any intermediary coding systems used while
4996 ;; talking to the remote shell or suchlike won't hose
4997 ;; this variable. This approach was snarfed from
4998 ;; ange-ftp.el.
4999 coding-system-used
5000 ;; Write region into a tmp file. This isn't really
5001 ;; needed if we use an encoding function, but currently
5002 ;; we use it always because this makes the logic
5003 ;; simpler.
5004 (tmpfile (or tramp-temp-buffer-file-name
5005 (tramp-compat-make-temp-file filename))))
5007 ;; If `append' is non-nil, we copy the file locally, and let
5008 ;; the native `write-region' implementation do the job.
5009 (when append (copy-file filename tmpfile 'ok))
5011 ;; We say `no-message' here because we don't want the
5012 ;; visited file modtime data to be clobbered from the temp
5013 ;; file. We call `set-visited-file-modtime' ourselves later
5014 ;; on. We must ensure that `file-coding-system-alist'
5015 ;; matches `tmpfile'.
5016 (let ((file-coding-system-alist
5017 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5018 (condition-case err
5019 (tramp-run-real-handler
5020 'write-region
5021 (list start end tmpfile append 'no-message lockname confirm))
5022 ((error quit)
5023 (setq tramp-temp-buffer-file-name nil)
5024 (delete-file tmpfile)
5025 (signal (car err) (cdr err))))
5027 ;; Now, `last-coding-system-used' has the right value. Remember it.
5028 (when (boundp 'last-coding-system-used)
5029 (setq coding-system-used
5030 (symbol-value 'last-coding-system-used))))
5032 ;; The permissions of the temporary file should be set. If
5033 ;; filename does not exist (eq modes nil) it has been
5034 ;; renamed to the backup file. This case `save-buffer'
5035 ;; handles permissions.
5036 ;; Ensure, that it is still readable.
5037 (when modes
5038 (set-file-modes
5039 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
5041 ;; This is a bit lengthy due to the different methods
5042 ;; possible for file transfer. First, we check whether the
5043 ;; method uses an rcp program. If so, we call it.
5044 ;; Otherwise, both encoding and decoding command must be
5045 ;; specified. However, if the method _also_ specifies an
5046 ;; encoding function, then that is used for encoding the
5047 ;; contents of the tmp file.
5048 (cond
5049 ;; `copy-file' handles direct copy and out-of-band methods.
5050 ((or (tramp-local-host-p v)
5051 (tramp-method-out-of-band-p
5052 v (nth 7 (file-attributes tmpfile))))
5053 (if (and (not (stringp start))
5054 (= (or end (point-max)) (point-max))
5055 (= (or start (point-min)) (point-min))
5056 (tramp-get-method-parameter
5057 method 'tramp-copy-keep-tmpfile))
5058 (progn
5059 (setq tramp-temp-buffer-file-name tmpfile)
5060 (condition-case err
5061 ;; We keep the local file for performance
5062 ;; reasons, useful for "rsync".
5063 (copy-file tmpfile filename t)
5064 ((error quit)
5065 (setq tramp-temp-buffer-file-name nil)
5066 (delete-file tmpfile)
5067 (signal (car err) (cdr err)))))
5068 (setq tramp-temp-buffer-file-name nil)
5069 ;; Don't rename, in order to keep context in SELinux.
5070 (unwind-protect
5071 (copy-file tmpfile filename t)
5072 (delete-file tmpfile))))
5074 ;; Use inline file transfer.
5075 (rem-dec
5076 ;; Encode tmpfile.
5077 (tramp-message v 5 "Encoding region...")
5078 (unwind-protect
5079 (with-temp-buffer
5080 ;; Use encoding function or command.
5081 (if (and (symbolp loc-enc) (fboundp loc-enc))
5082 (progn
5083 (tramp-message
5084 v 5 "Encoding region using function `%s'..."
5085 (symbol-name loc-enc))
5086 (let ((coding-system-for-read 'binary))
5087 (insert-file-contents-literally tmpfile))
5088 ;; The following `let' is a workaround for the
5089 ;; base64.el that comes with pgnus-0.84. If
5090 ;; both of the following conditions are
5091 ;; satisfied, it tries to write to a local
5092 ;; file in default-directory, but at this
5093 ;; point, default-directory is remote.
5094 ;; (`call-process-region' can't write to
5095 ;; remote files, it seems.) The file in
5096 ;; question is a tmp file anyway.
5097 (let ((default-directory
5098 (tramp-compat-temporary-file-directory)))
5099 (funcall loc-enc (point-min) (point-max))))
5101 (tramp-message
5102 v 5 "Encoding region using command `%s'..." loc-enc)
5103 (unless (equal 0 (tramp-call-local-coding-command
5104 loc-enc tmpfile t))
5105 (tramp-error
5106 v 'file-error
5107 "Cannot write to `%s', local encoding command `%s' failed"
5108 filename loc-enc)))
5110 ;; Send buffer into remote decoding command which
5111 ;; writes to remote file. Because this happens on
5112 ;; the remote host, we cannot use the function.
5113 (goto-char (point-max))
5114 (unless (bolp) (newline))
5115 (tramp-message
5116 v 5 "Decoding region into remote file %s..." filename)
5117 (tramp-send-command
5119 (format
5120 "%s >%s <<'EOF'\n%sEOF"
5121 rem-dec
5122 (tramp-shell-quote-argument localname)
5123 (buffer-string)))
5124 (tramp-barf-unless-okay
5125 v nil
5126 "Couldn't write region to `%s', decode using `%s' failed"
5127 filename rem-dec)
5128 ;; When `file-precious-flag' is set, the region is
5129 ;; written to a temporary file. Check that the
5130 ;; checksum is equal to that from the local tmpfile.
5131 (when file-precious-flag
5132 (erase-buffer)
5133 (and
5134 ;; cksum runs locally, if possible.
5135 (zerop (tramp-local-call-process "cksum" tmpfile t))
5136 ;; cksum runs remotely.
5137 (zerop
5138 (tramp-send-command-and-check
5140 (format
5141 "cksum <%s" (tramp-shell-quote-argument localname))))
5142 ;; ... they are different.
5143 (not
5144 (string-equal
5145 (buffer-string)
5146 (with-current-buffer (tramp-get-buffer v)
5147 (buffer-string))))
5148 (tramp-error
5149 v 'file-error
5150 (concat "Couldn't write region to `%s',"
5151 " decode using `%s' failed")
5152 filename rem-dec)))
5153 (tramp-message
5154 v 5 "Decoding region into remote file %s...done" filename))
5156 ;; Save exit.
5157 (delete-file tmpfile)))
5159 ;; That's not expected.
5161 (tramp-error
5162 v 'file-error
5163 (concat "Method `%s' should specify both encoding and "
5164 "decoding command or an rcp program")
5165 method)))
5167 ;; Make `last-coding-system-used' have the right value.
5168 (when coding-system-used
5169 (set 'last-coding-system-used coding-system-used))))
5171 (tramp-flush-file-property v (file-name-directory localname))
5172 (tramp-flush-file-property v localname)
5174 ;; We must protect `last-coding-system-used', now we have set it
5175 ;; to its correct value.
5176 (let (last-coding-system-used (need-chown t))
5177 ;; Set file modification time.
5178 (when (or (eq visit t) (stringp visit))
5179 (let ((file-attr (file-attributes filename)))
5180 (set-visited-file-modtime
5181 ;; We must pass modtime explicitely, because filename can
5182 ;; be different from (buffer-file-name), f.e. if
5183 ;; `file-precious-flag' is set.
5184 (nth 5 file-attr))
5185 (when (and (eq (nth 2 file-attr) uid)
5186 (eq (nth 3 file-attr) gid))
5187 (setq need-chown nil))))
5189 ;; Set the ownership.
5190 (when need-chown
5191 (tramp-set-file-uid-gid filename uid gid))
5192 (when (or (eq visit t) (null visit) (stringp visit))
5193 (tramp-message v 0 "Wrote %s" filename))
5194 (run-hooks 'tramp-handle-write-region-hook)))))
5196 (defvar tramp-vc-registered-file-names nil
5197 "List used to collect file names, which are checked during `vc-registered'.")
5199 ;; VC backends check for the existence of various different special
5200 ;; files. This is very time consuming, because every single check
5201 ;; requires a remote command (the file cache must be invalidated).
5202 ;; Therefore, we apply a kind of optimization. We install the file
5203 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5204 ;; remembers all file names for which `file-exists-p' or
5205 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5206 ;; is performed. Afterwards, a script is applied for all collected
5207 ;; file names, using just one remote command. The result of this
5208 ;; script is used to fill the file cache with actual values. Now we
5209 ;; can reset the file name handlers, and we make a second run of
5210 ;; `vc-registered', which returns the expected result without sending
5211 ;; any other remote command.
5212 (defun tramp-handle-vc-registered (file)
5213 "Like `vc-registered' for Tramp files."
5214 (with-parsed-tramp-file-name file nil
5216 ;; There could be new files, created by the vc backend. We cannot
5217 ;; reuse the old cache entries, therefore.
5218 (let (tramp-vc-registered-file-names
5219 (tramp-cache-inhibit-cache (current-time))
5220 (file-name-handler-alist
5221 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5223 ;; Here we collect only file names, which need an operation.
5224 (tramp-run-real-handler 'vc-registered (list file))
5225 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5227 ;; Send just one command, in order to fill the cache.
5228 (when tramp-vc-registered-file-names
5229 (tramp-maybe-send-script
5231 (format tramp-vc-registered-read-file-names
5232 (tramp-get-file-exists-command v)
5233 (format "%s -r" (tramp-get-test-command v)))
5234 "tramp_vc_registered_read_file_names")
5236 (dolist
5237 (elt
5238 (tramp-send-command-and-read
5240 (format
5241 "tramp_vc_registered_read_file_names %s"
5242 (mapconcat 'tramp-shell-quote-argument
5243 tramp-vc-registered-file-names
5244 " "))))
5246 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
5248 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
5249 ;; shall be answered from the file cache.
5250 ;; We unset `process-file-side-effects' in order to keep the cache
5251 ;; when `process-file' calls appear.
5252 (let (process-file-side-effects)
5253 (tramp-run-real-handler 'vc-registered (list file)))))
5255 ;;;###autoload
5256 (progn (defun tramp-run-real-handler (operation args)
5257 "Invoke normal file name handler for OPERATION.
5258 First arg specifies the OPERATION, second arg is a list of arguments to
5259 pass to the OPERATION."
5260 (let* ((inhibit-file-name-handlers
5261 `(tramp-file-name-handler
5262 tramp-vc-file-name-handler
5263 tramp-completion-file-name-handler
5264 cygwin-mount-name-hook-function
5265 cygwin-mount-map-drive-hook-function
5267 ,(and (eq inhibit-file-name-operation operation)
5268 inhibit-file-name-handlers)))
5269 (inhibit-file-name-operation operation))
5270 (apply operation args))))
5272 ;;;###autoload
5273 (progn (defun tramp-completion-run-real-handler (operation args)
5274 "Invoke `tramp-file-name-handler' for OPERATION.
5275 First arg specifies the OPERATION, second arg is a list of arguments to
5276 pass to the OPERATION."
5277 (let* ((inhibit-file-name-handlers
5278 `(tramp-completion-file-name-handler
5279 cygwin-mount-name-hook-function
5280 cygwin-mount-map-drive-hook-function
5282 ,(and (eq inhibit-file-name-operation operation)
5283 inhibit-file-name-handlers)))
5284 (inhibit-file-name-operation operation))
5285 (apply operation args))))
5287 ;; We handle here all file primitives. Most of them have the file
5288 ;; name as first parameter; nevertheless we check for them explicitly
5289 ;; in order to be signaled if a new primitive appears. This
5290 ;; scenario is needed because there isn't a way to decide by
5291 ;; syntactical means whether a foreign method must be called. It would
5292 ;; ease the life if `file-name-handler-alist' would support a decision
5293 ;; function as well but regexp only.
5294 (defun tramp-file-name-for-operation (operation &rest args)
5295 "Return file name related to OPERATION file primitive.
5296 ARGS are the arguments OPERATION has been called with."
5297 (cond
5298 ; FILE resp DIRECTORY
5299 ((member operation
5300 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5301 'delete-file 'diff-latest-backup-file 'directory-file-name
5302 'directory-files 'directory-files-and-attributes
5303 'dired-compress-file 'dired-uncache
5304 'file-accessible-directory-p 'file-attributes
5305 'file-directory-p 'file-executable-p 'file-exists-p
5306 'file-local-copy 'file-remote-p 'file-modes
5307 'file-name-as-directory 'file-name-directory
5308 'file-name-nondirectory 'file-name-sans-versions
5309 'file-ownership-preserved-p 'file-readable-p
5310 'file-regular-p 'file-symlink-p 'file-truename
5311 'file-writable-p 'find-backup-file-name 'find-file-noselect
5312 'get-file-buffer 'insert-directory 'insert-file-contents
5313 'load 'make-directory 'make-directory-internal
5314 'set-file-modes 'substitute-in-file-name
5315 'unhandled-file-name-directory 'vc-registered
5316 ; Emacs 22 only
5317 'set-file-times
5318 ; XEmacs only
5319 'abbreviate-file-name 'create-file-buffer
5320 'dired-file-modtime 'dired-make-compressed-filename
5321 'dired-recursive-delete-directory 'dired-set-file-modtime
5322 'dired-shell-unhandle-file-name 'dired-uucode-file
5323 'insert-file-contents-literally 'make-temp-name 'recover-file
5324 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5325 (if (file-name-absolute-p (nth 0 args))
5326 (nth 0 args)
5327 (expand-file-name (nth 0 args))))
5328 ; FILE DIRECTORY resp FILE1 FILE2
5329 ((member operation
5330 (list 'add-name-to-file 'copy-file 'expand-file-name
5331 'file-name-all-completions 'file-name-completion
5332 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5333 ; Emacs 23 only
5334 'copy-directory
5335 ; XEmacs only
5336 'dired-make-relative-symlink
5337 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5338 (save-match-data
5339 (cond
5340 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5341 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5342 (t (buffer-file-name (current-buffer))))))
5343 ; START END FILE
5344 ((eq operation 'write-region)
5345 (nth 2 args))
5346 ; BUF
5347 ((member operation
5348 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5349 ; since Emacs 22 only
5350 'make-auto-save-file-name
5351 ; XEmacs only
5352 'backup-buffer))
5353 (buffer-file-name
5354 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5355 ; COMMAND
5356 ((member operation
5357 (list ; not in Emacs 23
5358 'dired-call-process
5359 ; Emacs only
5360 'shell-command
5361 ; since Emacs 22 only
5362 'process-file
5363 ; since Emacs 23 only
5364 'start-file-process
5365 ; XEmacs only
5366 'dired-print-file 'dired-shell-call-process
5367 ; nowhere yet
5368 'executable-find 'start-process 'call-process))
5369 default-directory)
5370 ; unknown file primitive
5371 (t (error "unknown file I/O primitive: %s" operation))))
5373 (defun tramp-find-foreign-file-name-handler (filename)
5374 "Return foreign file name handler if exists."
5375 (when (and (stringp filename) (tramp-tramp-file-p filename))
5376 (let ((v (tramp-dissect-file-name filename t))
5377 (handler tramp-foreign-file-name-handler-alist)
5378 elt res)
5379 ;; When we are not fully sure that filename completion is safe,
5380 ;; we should not return a handler.
5381 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5382 (and (tramp-file-name-host v)
5383 (not (member (tramp-file-name-host v)
5384 (mapcar 'car tramp-methods))))
5385 (not (tramp-completion-mode-p)))
5386 (while handler
5387 (setq elt (car handler)
5388 handler (cdr handler))
5389 (when (funcall (car elt) filename)
5390 (setq handler nil
5391 res (cdr elt))))
5392 res))))
5394 ;; Main function.
5395 ;;;###autoload
5396 (defun tramp-file-name-handler (operation &rest args)
5397 "Invoke Tramp file name handler.
5398 Falls back to normal file name handler if no Tramp file name handler exists."
5399 (if tramp-mode
5400 (save-match-data
5401 (let* ((filename
5402 (tramp-replace-environment-variables
5403 (apply 'tramp-file-name-for-operation operation args)))
5404 (completion (tramp-completion-mode-p))
5405 (foreign (tramp-find-foreign-file-name-handler filename)))
5406 (with-parsed-tramp-file-name filename nil
5407 (cond
5408 ;; When we are in completion mode, some operations
5409 ;; shouldn't be handled by backend.
5410 ((and completion (zerop (length localname))
5411 (memq operation '(file-exists-p file-directory-p)))
5413 ((and completion (zerop (length localname))
5414 (memq operation '(file-name-as-directory)))
5415 filename)
5416 ;; Call the backend function.
5417 (foreign (apply foreign operation args))
5418 ;; Nothing to do for us.
5419 (t (tramp-run-real-handler operation args))))))
5420 ;; When `tramp-mode' is not enabled, we don't do anything.
5421 (tramp-run-real-handler operation args)))
5423 ;; In Emacs, there is some concurrency due to timers. If a timer
5424 ;; interrupts Tramp and wishes to use the same connection buffer as
5425 ;; the "main" Emacs, then garbage might occur in the connection
5426 ;; buffer. Therefore, we need to make sure that a timer does not use
5427 ;; the same connection buffer as the "main" Emacs. We implement a
5428 ;; cheap global lock, instead of locking each connection buffer
5429 ;; separately. The global lock is based on two variables,
5430 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5431 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5432 ;; processing of a single file operation, so we need to allow
5433 ;; recursive calls. That's where the `tramp-locker' variable comes in
5434 ;; -- it is let-bound to t during the execution of the current
5435 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5436 ;; then we should just proceed because we have been called
5437 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5438 ;; interrupting the "main" Emacs, and then we signal an error.
5440 (defvar tramp-locked nil
5441 "If non-nil, then Tramp is currently busy.
5442 Together with `tramp-locker', this implements a locking mechanism
5443 preventing reentrant calls of Tramp.")
5445 (defvar tramp-locker nil
5446 "If non-nil, then a caller has locked Tramp.
5447 Together with `tramp-locked', this implements a locking mechanism
5448 preventing reentrant calls of Tramp.")
5450 (defun tramp-sh-file-name-handler (operation &rest args)
5451 "Invoke remote-shell Tramp file name handler.
5452 Fall back to normal file name handler if no Tramp handler exists."
5453 (when (and tramp-locked (not tramp-locker))
5454 (setq tramp-locked nil)
5455 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5456 (let ((tl tramp-locked))
5457 (unwind-protect
5458 (progn
5459 (setq tramp-locked t)
5460 (let ((tramp-locker t))
5461 (save-match-data
5462 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5463 (if fn
5464 (apply (cdr fn) args)
5465 (tramp-run-real-handler operation args))))))
5466 (setq tramp-locked tl))))
5468 (defun tramp-vc-file-name-handler (operation &rest args)
5469 "Invoke special file name handler, which collects files to be handled."
5470 (save-match-data
5471 (let ((filename
5472 (tramp-replace-environment-variables
5473 (apply 'tramp-file-name-for-operation operation args)))
5474 (fn (assoc operation tramp-file-name-handler-alist)))
5475 (with-parsed-tramp-file-name filename nil
5476 (cond
5477 ;; That's what we want: file names, for which checks are
5478 ;; applied. We assume, that VC uses only `file-exists-p' and
5479 ;; `file-readable-p' checks; otherwise we must extend the
5480 ;; list. We do not perform any action, but return nil, in
5481 ;; order to keep `vc-registered' running.
5482 ((and fn (memq operation '(file-exists-p file-readable-p)))
5483 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5484 nil)
5485 ;; Tramp file name handlers like `expand-file-name'. They
5486 ;; must still work.
5488 (save-match-data (apply (cdr fn) args)))
5489 ;; Default file name handlers, we don't care.
5490 (t (tramp-run-real-handler operation args)))))))
5492 ;;;###autoload
5493 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5494 "Invoke Tramp file name completion handler.
5495 Falls back to normal file name handler if no Tramp file name handler exists."
5496 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5497 ;; would otherwise use backslash.
5498 (let ((directory-sep-char ?/)
5499 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5500 (if (and
5501 ;; When `tramp-mode' is not enabled, we don't do anything.
5502 fn tramp-mode
5503 ;; For other syntaxes than `sep', the regexp matches many common
5504 ;; situations where the user doesn't actually want to use Tramp.
5505 ;; So to avoid autoloading Tramp after typing just "/s", we
5506 ;; disable this part of the completion, unless the user implicitly
5507 ;; indicated his interest in using a fancier completion system.
5508 (or (eq tramp-syntax 'sep)
5509 (featurep 'tramp) ; If it's loaded, we may as well use it.
5510 (and (boundp 'partial-completion-mode) partial-completion-mode)
5511 ;; FIXME: These may have been loaded even if the user never
5512 ;; intended to use them.
5513 (featurep 'ido)
5514 (featurep 'icicles)))
5515 (save-match-data (apply (cdr fn) args))
5516 (tramp-completion-run-real-handler operation args)))))
5518 ;;;###autoload
5519 (progn (defun tramp-register-file-name-handlers ()
5520 "Add Tramp file name handlers to `file-name-handler-alist'."
5521 ;; Remove autoloaded handlers from file name handler alist. Useful,
5522 ;; if `tramp-syntax' has been changed.
5523 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5524 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5525 (let ((a1 (rassq
5526 'tramp-completion-file-name-handler file-name-handler-alist)))
5527 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5528 ;; Add the handlers.
5529 (add-to-list 'file-name-handler-alist
5530 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5531 (put 'tramp-file-name-handler 'safe-magic t)
5532 (add-to-list 'file-name-handler-alist
5533 (cons tramp-completion-file-name-regexp
5534 'tramp-completion-file-name-handler))
5535 (put 'tramp-completion-file-name-handler 'safe-magic t)
5536 ;; If jka-compr or epa-file are already loaded, move them to the
5537 ;; front of `file-name-handler-alist'.
5538 (dolist (fnh '(epa-file-handler jka-compr-handler))
5539 (let ((entry (rassoc fnh file-name-handler-alist)))
5540 (when entry
5541 (setq file-name-handler-alist
5542 (cons entry (delete entry file-name-handler-alist))))))))
5544 ;; `tramp-file-name-handler' must be registered before evaluation of
5545 ;; site-start and init files, because there might exist remote files
5546 ;; already, f.e. files kept via recentf-mode.
5547 ;;;###autoload(tramp-register-file-name-handlers)
5548 (tramp-register-file-name-handlers)
5550 ;;;###autoload
5551 (defun tramp-unload-file-name-handlers ()
5552 (setq file-name-handler-alist
5553 (delete (rassoc 'tramp-file-name-handler
5554 file-name-handler-alist)
5555 (delete (rassoc 'tramp-completion-file-name-handler
5556 file-name-handler-alist)
5557 file-name-handler-alist))))
5559 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5561 ;;; File name handler functions for completion mode:
5563 (defvar tramp-completion-mode nil
5564 "If non-nil, external packages signal that they are in file name completion.
5566 This is necessary, because Tramp uses a heuristic depending on last
5567 input event. This fails when external packages use other characters
5568 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5569 should never be set globally, the intention is to let-bind it.")
5571 ;; Necessary because `tramp-file-name-regexp-unified' and
5572 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5573 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5574 ;; to `tramp-file-name-handler'). Otherwise, it takes
5575 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5576 ;; risky, because completing a file might require loading other files,
5577 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5578 ;; variable. On the other hand, those files shouldn't have partial
5579 ;; Tramp file name syntax. Maybe another variable should be introduced
5580 ;; overwriting this check in such cases. Or we change Tramp file name
5581 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5582 (defun tramp-completion-mode-p ()
5583 "Checks whether method / user name / host name completion is active."
5585 ;; Signal from outside.
5586 tramp-completion-mode
5587 ;; Emacs.
5588 (equal last-input-event 'tab)
5589 (and (natnump last-input-event)
5591 ;; ?\t has event-modifier 'control.
5592 (equal last-input-event ?\t)
5593 (and (not (event-modifiers last-input-event))
5594 (or (equal last-input-event ?\?)
5595 (equal last-input-event ?\ )))))
5596 ;; XEmacs.
5597 (and (featurep 'xemacs)
5598 ;; `last-input-event' might be nil.
5599 (not (null last-input-event))
5600 ;; `last-input-event' may have no character approximation.
5601 (funcall (symbol-function 'event-to-character) last-input-event)
5603 ;; ?\t has event-modifier 'control.
5604 (equal
5605 (funcall (symbol-function 'event-to-character)
5606 last-input-event) ?\t)
5607 (and (not (event-modifiers last-input-event))
5608 (or (equal
5609 (funcall (symbol-function 'event-to-character)
5610 last-input-event) ?\?)
5611 (equal
5612 (funcall (symbol-function 'event-to-character)
5613 last-input-event) ?\ )))))))
5615 ;; Method, host name and user name completion.
5616 ;; `tramp-completion-dissect-file-name' returns a list of
5617 ;; tramp-file-name structures. For all of them we return possible completions.
5618 ;;;###autoload
5619 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5620 "Like `file-name-all-completions' for partial Tramp files."
5622 (let* ((fullname (tramp-drop-volume-letter
5623 (expand-file-name filename directory)))
5624 ;; Possible completion structures.
5625 (v (tramp-completion-dissect-file-name fullname))
5626 result result1)
5628 (while v
5629 (let* ((car (car v))
5630 (method (tramp-file-name-method car))
5631 (user (tramp-file-name-user car))
5632 (host (tramp-file-name-host car))
5633 (localname (tramp-file-name-localname car))
5634 (m (tramp-find-method method user host))
5635 (tramp-current-user user) ; see `tramp-parse-passwd'
5636 all-user-hosts)
5638 (unless localname ;; Nothing to complete.
5640 (if (or user host)
5642 ;; Method dependent user / host combinations.
5643 (progn
5644 (mapc
5645 (lambda (x)
5646 (setq all-user-hosts
5647 (append all-user-hosts
5648 (funcall (nth 0 x) (nth 1 x)))))
5649 (tramp-get-completion-function m))
5651 (setq result
5652 (append result
5653 (mapcar
5654 (lambda (x)
5655 (tramp-get-completion-user-host
5656 method user host (nth 0 x) (nth 1 x)))
5657 (delq nil all-user-hosts)))))
5659 ;; Possible methods.
5660 (setq result
5661 (append result (tramp-get-completion-methods m)))))
5663 (setq v (cdr v))))
5665 ;; Unify list, remove nil elements.
5666 (while result
5667 (let ((car (car result)))
5668 (when car
5669 (add-to-list
5670 'result1
5671 (substring car (length (tramp-drop-volume-letter directory)))))
5672 (setq result (cdr result))))
5674 ;; Complete local parts.
5675 (append
5676 result1
5677 (condition-case nil
5678 (tramp-completion-run-real-handler
5679 'file-name-all-completions (list filename directory))
5680 (error nil)))))
5682 ;; Method, host name and user name completion for a file.
5683 ;;;###autoload
5684 (defun tramp-completion-handle-file-name-completion
5685 (filename directory &optional predicate)
5686 "Like `file-name-completion' for Tramp files."
5687 (try-completion
5688 filename
5689 (mapcar 'list (file-name-all-completions filename directory))
5690 (when predicate
5691 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5693 ;; I misuse a little bit the tramp-file-name structure in order to handle
5694 ;; completion possibilities for partial methods / user names / host names.
5695 ;; Return value is a list of tramp-file-name structures according to possible
5696 ;; completions. If "localname" is non-nil it means there
5697 ;; shouldn't be a completion anymore.
5699 ;; Expected results:
5701 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5702 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5703 ;; [nil "x" nil nil]
5704 ;; ["x" nil nil nil]
5706 ;; "/x:" "/x:y" "/x:y:"
5707 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5708 ;; "/[x/" "/[x/y"
5709 ;; ["x" nil "" nil] ["x" nil "y" nil]
5710 ;; ["x" "" nil nil] ["x" "y" nil nil]
5712 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5713 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5714 ;; "/[x/y@" "/[x/y@z"
5715 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5716 (defun tramp-completion-dissect-file-name (name)
5717 "Returns a list of `tramp-file-name' structures.
5718 They are collected by `tramp-completion-dissect-file-name1'."
5720 (let* ((result)
5721 (x-nil "\\|\\(\\)")
5722 (tramp-completion-ipv6-regexp
5723 (format
5724 "[^%s]*"
5725 (if (zerop (length tramp-postfix-ipv6-format))
5726 tramp-postfix-host-format
5727 tramp-postfix-ipv6-format)))
5728 ;; "/method" "/[method"
5729 (tramp-completion-file-name-structure1
5730 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5731 1 nil nil nil))
5732 ;; "/user" "/[user"
5733 (tramp-completion-file-name-structure2
5734 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5735 nil 1 nil nil))
5736 ;; "/host" "/[host"
5737 (tramp-completion-file-name-structure3
5738 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5739 nil nil 1 nil))
5740 ;; "/[ipv6" "/[ipv6"
5741 (tramp-completion-file-name-structure4
5742 (list (concat tramp-prefix-regexp
5743 tramp-prefix-ipv6-regexp
5744 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5745 nil nil 1 nil))
5746 ;; "/user@host" "/[user@host"
5747 (tramp-completion-file-name-structure5
5748 (list (concat tramp-prefix-regexp
5749 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5750 "\\(" tramp-host-regexp x-nil "\\)$")
5751 nil 1 2 nil))
5752 ;; "/user@[ipv6" "/[user@ipv6"
5753 (tramp-completion-file-name-structure6
5754 (list (concat tramp-prefix-regexp
5755 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5756 tramp-prefix-ipv6-regexp
5757 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5758 nil 1 2 nil))
5759 ;; "/method:user" "/[method/user" "/method://user"
5760 (tramp-completion-file-name-structure7
5761 (list (concat tramp-prefix-regexp
5762 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5763 "\\(" tramp-user-regexp x-nil "\\)$")
5764 1 2 nil nil))
5765 ;; "/method:host" "/[method/host" "/method://host"
5766 (tramp-completion-file-name-structure8
5767 (list (concat tramp-prefix-regexp
5768 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5769 "\\(" tramp-host-regexp x-nil "\\)$")
5770 1 nil 2 nil))
5771 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5772 (tramp-completion-file-name-structure9
5773 (list (concat tramp-prefix-regexp
5774 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5775 tramp-prefix-ipv6-regexp
5776 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5777 1 nil 2 nil))
5778 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5779 (tramp-completion-file-name-structure10
5780 (list (concat tramp-prefix-regexp
5781 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5782 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5783 "\\(" tramp-host-regexp x-nil "\\)$")
5784 1 2 3 nil))
5785 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5786 (tramp-completion-file-name-structure11
5787 (list (concat tramp-prefix-regexp
5788 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5789 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5790 tramp-prefix-ipv6-regexp
5791 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5792 1 2 3 nil))
5793 ;; "/method: "/method:/"
5794 (tramp-completion-file-name-structure12
5795 (list
5796 (if (equal tramp-syntax 'url)
5797 (concat tramp-prefix-regexp
5798 "\\(" tramp-method-regexp "\\)"
5799 "\\(" (substring tramp-postfix-method-regexp 0 1)
5800 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5801 "\\(" "\\)$")
5802 ;; Should not match if not URL syntax.
5803 (concat tramp-prefix-regexp "/$"))
5804 1 3 nil nil))
5805 ;; "/method: "/method:/"
5806 (tramp-completion-file-name-structure13
5807 (list
5808 (if (equal tramp-syntax 'url)
5809 (concat tramp-prefix-regexp
5810 "\\(" tramp-method-regexp "\\)"
5811 "\\(" (substring tramp-postfix-method-regexp 0 1)
5812 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5813 "\\(" "\\)$")
5814 ;; Should not match if not URL syntax.
5815 (concat tramp-prefix-regexp "/$"))
5816 1 nil 3 nil)))
5818 (mapc (lambda (regexp)
5819 (add-to-list 'result
5820 (tramp-completion-dissect-file-name1 regexp name)))
5821 (list
5822 tramp-completion-file-name-structure1
5823 tramp-completion-file-name-structure2
5824 tramp-completion-file-name-structure3
5825 tramp-completion-file-name-structure4
5826 tramp-completion-file-name-structure5
5827 tramp-completion-file-name-structure6
5828 tramp-completion-file-name-structure7
5829 tramp-completion-file-name-structure8
5830 tramp-completion-file-name-structure9
5831 tramp-completion-file-name-structure10
5832 tramp-completion-file-name-structure11
5833 tramp-completion-file-name-structure12
5834 tramp-completion-file-name-structure13
5835 tramp-file-name-structure))
5837 (delq nil result)))
5839 (defun tramp-completion-dissect-file-name1 (structure name)
5840 "Returns a `tramp-file-name' structure matching STRUCTURE.
5841 The structure consists of remote method, remote user,
5842 remote host and localname (filename on remote host)."
5844 (save-match-data
5845 (when (string-match (nth 0 structure) name)
5846 (let ((method (and (nth 1 structure)
5847 (match-string (nth 1 structure) name)))
5848 (user (and (nth 2 structure)
5849 (match-string (nth 2 structure) name)))
5850 (host (and (nth 3 structure)
5851 (match-string (nth 3 structure) name)))
5852 (localname (and (nth 4 structure)
5853 (match-string (nth 4 structure) name))))
5854 (vector method user host localname)))))
5856 ;; This function returns all possible method completions, adding the
5857 ;; trailing method delimeter.
5858 (defun tramp-get-completion-methods (partial-method)
5859 "Returns all method completions for PARTIAL-METHOD."
5860 (mapcar
5861 (lambda (method)
5862 (and method
5863 (string-match (concat "^" (regexp-quote partial-method)) method)
5864 (tramp-completion-make-tramp-file-name method nil nil nil)))
5865 (mapcar 'car tramp-methods)))
5867 ;; Compares partial user and host names with possible completions.
5868 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
5869 "Returns the most expanded string for user and host name completion.
5870 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5871 (cond
5873 ((and partial-user partial-host)
5874 (if (and host
5875 (string-match (concat "^" (regexp-quote partial-host)) host)
5876 (string-equal partial-user (or user partial-user)))
5877 (setq user partial-user)
5878 (setq user nil
5879 host nil)))
5881 (partial-user
5882 (setq host nil)
5883 (unless
5884 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5885 (setq user nil)))
5887 (partial-host
5888 (setq user nil)
5889 (unless
5890 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5891 (setq host nil)))
5893 (t (setq user nil
5894 host nil)))
5896 (unless (zerop (+ (length user) (length host)))
5897 (tramp-completion-make-tramp-file-name method user host nil)))
5899 (defun tramp-parse-rhosts (filename)
5900 "Return a list of (user host) tuples allowed to access.
5901 Either user or host may be nil."
5902 ;; On Windows, there are problems in completion when
5903 ;; `default-directory' is remote.
5904 (let ((default-directory (tramp-compat-temporary-file-directory))
5905 res)
5906 (when (file-readable-p filename)
5907 (with-temp-buffer
5908 (insert-file-contents filename)
5909 (goto-char (point-min))
5910 (while (not (eobp))
5911 (push (tramp-parse-rhosts-group) res))))
5912 res))
5914 (defun tramp-parse-rhosts-group ()
5915 "Return a (user host) tuple allowed to access.
5916 Either user or host may be nil."
5917 (let ((result)
5918 (regexp
5919 (concat
5920 "^\\(" tramp-host-regexp "\\)"
5921 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5922 (narrow-to-region (point) (tramp-compat-line-end-position))
5923 (when (re-search-forward regexp nil t)
5924 (setq result (append (list (match-string 3) (match-string 1)))))
5925 (widen)
5926 (forward-line 1)
5927 result))
5929 (defun tramp-parse-shosts (filename)
5930 "Return a list of (user host) tuples allowed to access.
5931 User is always nil."
5932 ;; On Windows, there are problems in completion when
5933 ;; `default-directory' is remote.
5934 (let ((default-directory (tramp-compat-temporary-file-directory))
5935 res)
5936 (when (file-readable-p filename)
5937 (with-temp-buffer
5938 (insert-file-contents filename)
5939 (goto-char (point-min))
5940 (while (not (eobp))
5941 (push (tramp-parse-shosts-group) res))))
5942 res))
5944 (defun tramp-parse-shosts-group ()
5945 "Return a (user host) tuple allowed to access.
5946 User is always nil."
5947 (let ((result)
5948 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
5949 (narrow-to-region (point) (tramp-compat-line-end-position))
5950 (when (re-search-forward regexp nil t)
5951 (setq result (list nil (match-string 1))))
5952 (widen)
5954 (> (skip-chars-forward ",") 0)
5955 (forward-line 1))
5956 result))
5958 (defun tramp-parse-sconfig (filename)
5959 "Return a list of (user host) tuples allowed to access.
5960 User is always nil."
5961 ;; On Windows, there are problems in completion when
5962 ;; `default-directory' is remote.
5963 (let ((default-directory (tramp-compat-temporary-file-directory))
5964 res)
5965 (when (file-readable-p filename)
5966 (with-temp-buffer
5967 (insert-file-contents filename)
5968 (goto-char (point-min))
5969 (while (not (eobp))
5970 (push (tramp-parse-sconfig-group) res))))
5971 res))
5973 (defun tramp-parse-sconfig-group ()
5974 "Return a (user host) tuple allowed to access.
5975 User is always nil."
5976 (let ((result)
5977 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
5978 (narrow-to-region (point) (tramp-compat-line-end-position))
5979 (when (re-search-forward regexp nil t)
5980 (setq result (list nil (match-string 1))))
5981 (widen)
5983 (> (skip-chars-forward ",") 0)
5984 (forward-line 1))
5985 result))
5987 (defun tramp-parse-shostkeys (dirname)
5988 "Return a list of (user host) tuples allowed to access.
5989 User is always nil."
5990 ;; On Windows, there are problems in completion when
5991 ;; `default-directory' is remote.
5992 (let* ((default-directory (tramp-compat-temporary-file-directory))
5993 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
5994 (files (when (file-directory-p dirname) (directory-files dirname)))
5995 result)
5996 (while files
5997 (when (string-match regexp (car files))
5998 (push (list nil (match-string 1 (car files))) result))
5999 (setq files (cdr files)))
6000 result))
6002 (defun tramp-parse-sknownhosts (dirname)
6003 "Return a list of (user host) tuples allowed to access.
6004 User is always nil."
6005 ;; On Windows, there are problems in completion when
6006 ;; `default-directory' is remote.
6007 (let* ((default-directory (tramp-compat-temporary-file-directory))
6008 (regexp (concat "^\\(" tramp-host-regexp
6009 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6010 (files (when (file-directory-p dirname) (directory-files dirname)))
6011 result)
6012 (while files
6013 (when (string-match regexp (car files))
6014 (push (list nil (match-string 1 (car files))) result))
6015 (setq files (cdr files)))
6016 result))
6018 (defun tramp-parse-hosts (filename)
6019 "Return a list of (user host) tuples allowed to access.
6020 User is always nil."
6021 ;; On Windows, there are problems in completion when
6022 ;; `default-directory' is remote.
6023 (let ((default-directory (tramp-compat-temporary-file-directory))
6024 res)
6025 (when (file-readable-p filename)
6026 (with-temp-buffer
6027 (insert-file-contents filename)
6028 (goto-char (point-min))
6029 (while (not (eobp))
6030 (push (tramp-parse-hosts-group) res))))
6031 res))
6033 (defun tramp-parse-hosts-group ()
6034 "Return a (user host) tuple allowed to access.
6035 User is always nil."
6036 (let ((result)
6037 (regexp
6038 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6039 (narrow-to-region (point) (tramp-compat-line-end-position))
6040 (when (re-search-forward regexp nil t)
6041 (setq result (list nil (match-string 1))))
6042 (widen)
6044 (> (skip-chars-forward " \t") 0)
6045 (forward-line 1))
6046 result))
6048 ;; For su-alike methods it would be desirable to return "root@localhost"
6049 ;; as default. Unfortunately, we have no information whether any user name
6050 ;; has been typed already. So we use `tramp-current-user' as indication,
6051 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6052 (defun tramp-parse-passwd (filename)
6053 "Return a list of (user host) tuples allowed to access.
6054 Host is always \"localhost\"."
6055 ;; On Windows, there are problems in completion when
6056 ;; `default-directory' is remote.
6057 (let ((default-directory (tramp-compat-temporary-file-directory))
6058 res)
6059 (if (zerop (length tramp-current-user))
6060 '(("root" nil))
6061 (when (file-readable-p filename)
6062 (with-temp-buffer
6063 (insert-file-contents filename)
6064 (goto-char (point-min))
6065 (while (not (eobp))
6066 (push (tramp-parse-passwd-group) res))))
6067 res)))
6069 (defun tramp-parse-passwd-group ()
6070 "Return a (user host) tuple allowed to access.
6071 Host is always \"localhost\"."
6072 (let ((result)
6073 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6074 (narrow-to-region (point) (tramp-compat-line-end-position))
6075 (when (re-search-forward regexp nil t)
6076 (setq result (list (match-string 1) "localhost")))
6077 (widen)
6078 (forward-line 1)
6079 result))
6081 (defun tramp-parse-netrc (filename)
6082 "Return a list of (user host) tuples allowed to access.
6083 User may be nil."
6084 ;; On Windows, there are problems in completion when
6085 ;; `default-directory' is remote.
6086 (let ((default-directory (tramp-compat-temporary-file-directory))
6087 res)
6088 (when (file-readable-p filename)
6089 (with-temp-buffer
6090 (insert-file-contents filename)
6091 (goto-char (point-min))
6092 (while (not (eobp))
6093 (push (tramp-parse-netrc-group) res))))
6094 res))
6096 (defun tramp-parse-netrc-group ()
6097 "Return a (user host) tuple allowed to access.
6098 User may be nil."
6099 (let ((result)
6100 (regexp
6101 (concat
6102 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6103 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6104 (narrow-to-region (point) (tramp-compat-line-end-position))
6105 (when (re-search-forward regexp nil t)
6106 (setq result (list (match-string 3) (match-string 1))))
6107 (widen)
6108 (forward-line 1)
6109 result))
6111 (defun tramp-parse-putty (registry)
6112 "Return a list of (user host) tuples allowed to access.
6113 User is always nil."
6114 ;; On Windows, there are problems in completion when
6115 ;; `default-directory' is remote.
6116 (let ((default-directory (tramp-compat-temporary-file-directory))
6117 res)
6118 (with-temp-buffer
6119 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6120 (goto-char (point-min))
6121 (while (not (eobp))
6122 (push (tramp-parse-putty-group registry) res))))
6123 res))
6125 (defun tramp-parse-putty-group (registry)
6126 "Return a (user host) tuple allowed to access.
6127 User is always nil."
6128 (let ((result)
6129 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6130 (narrow-to-region (point) (tramp-compat-line-end-position))
6131 (when (re-search-forward regexp nil t)
6132 (setq result (list nil (match-string 1))))
6133 (widen)
6134 (forward-line 1)
6135 result))
6137 ;;; Internal Functions:
6139 (defun tramp-maybe-send-script (vec script name)
6140 "Define in remote shell function NAME implemented as SCRIPT.
6141 Only send the definition if it has not already been done."
6142 (let* ((p (tramp-get-connection-process vec))
6143 (scripts (tramp-get-connection-property p "scripts" nil)))
6144 (unless (member name scripts)
6145 (tramp-message vec 5 "Sending script `%s'..." name)
6146 ;; The script could contain a call of Perl. This is masked with `%s'.
6147 (tramp-send-command-and-check
6149 (format "%s () {\n%s\n}" name
6150 (format script (tramp-get-remote-perl vec))))
6151 (tramp-set-connection-property p "scripts" (cons name scripts))
6152 (tramp-message vec 5 "Sending script `%s'...done." name))))
6154 (defun tramp-set-auto-save ()
6155 (when (and ;; ange-ftp has its own auto-save mechanism
6156 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6157 'tramp-sh-file-name-handler)
6158 auto-save-default)
6159 (auto-save-mode 1)))
6160 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6161 (add-hook 'tramp-unload-hook
6162 (lambda ()
6163 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6165 (defun tramp-run-test (switch filename)
6166 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6167 Returns the exit code of the `test' program."
6168 (with-parsed-tramp-file-name filename nil
6169 (tramp-send-command-and-check
6171 (format
6172 "%s %s %s"
6173 (tramp-get-test-command v)
6174 switch
6175 (tramp-shell-quote-argument localname)))))
6177 (defun tramp-run-test2 (format-string file1 file2)
6178 "Run `test'-like program on the remote system, given FILE1, FILE2.
6179 FORMAT-STRING contains the program name, switches, and place holders.
6180 Returns the exit code of the `test' program. Barfs if the methods,
6181 hosts, or files, disagree."
6182 (unless (tramp-equal-remote file1 file2)
6183 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6184 (tramp-error
6185 v 'file-error
6186 "tramp-run-test2 only implemented for same method, user, host")))
6187 (with-parsed-tramp-file-name file1 v1
6188 (with-parsed-tramp-file-name file1 v2
6189 (tramp-send-command-and-check
6191 (format format-string
6192 (tramp-shell-quote-argument v1-localname)
6193 (tramp-shell-quote-argument v2-localname))))))
6195 (defun tramp-buffer-name (vec)
6196 "A name for the connection buffer VEC."
6197 ;; We must use `tramp-file-name-real-host', because for gateway
6198 ;; methods the default port will be expanded later on, which would
6199 ;; tamper the name.
6200 (let ((method (tramp-file-name-method vec))
6201 (user (tramp-file-name-user vec))
6202 (host (tramp-file-name-real-host vec)))
6203 (if (not (zerop (length user)))
6204 (format "*tramp/%s %s@%s*" method user host)
6205 (format "*tramp/%s %s*" method host))))
6207 (defun tramp-delete-temp-file-function ()
6208 "Remove temporary files related to current buffer."
6209 (when (stringp tramp-temp-buffer-file-name)
6210 (condition-case nil
6211 (delete-file tramp-temp-buffer-file-name)
6212 (error nil))))
6214 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6215 (add-hook 'tramp-cache-unload-hook
6216 (lambda ()
6217 (remove-hook 'kill-buffer-hook
6218 'tramp-delete-temp-file-function)))
6220 (defun tramp-get-buffer (vec)
6221 "Get the connection buffer to be used for VEC."
6222 (or (get-buffer (tramp-buffer-name vec))
6223 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6224 (setq buffer-undo-list t)
6225 (setq default-directory
6226 (tramp-make-tramp-file-name
6227 (tramp-file-name-method vec)
6228 (tramp-file-name-user vec)
6229 (tramp-file-name-host vec)
6230 "/"))
6231 (current-buffer))))
6233 (defun tramp-get-connection-buffer (vec)
6234 "Get the connection buffer to be used for VEC.
6235 In case a second asynchronous communication has been started, it is different
6236 from `tramp-get-buffer'."
6237 (or (tramp-get-connection-property vec "process-buffer" nil)
6238 (tramp-get-buffer vec)))
6240 (defun tramp-get-connection-process (vec)
6241 "Get the connection process to be used for VEC.
6242 In case a second asynchronous communication has been started, it is different
6243 from the default one."
6244 (get-process
6245 (or (tramp-get-connection-property vec "process-name" nil)
6246 (tramp-buffer-name vec))))
6248 (defun tramp-debug-buffer-name (vec)
6249 "A name for the debug buffer for VEC."
6250 ;; We must use `tramp-file-name-real-host', because for gateway
6251 ;; methods the default port will be expanded later on, which would
6252 ;; tamper the name.
6253 (let ((method (tramp-file-name-method vec))
6254 (user (tramp-file-name-user vec))
6255 (host (tramp-file-name-real-host vec)))
6256 (if (not (zerop (length user)))
6257 (format "*debug tramp/%s %s@%s*" method user host)
6258 (format "*debug tramp/%s %s*" method host))))
6260 (defun tramp-get-debug-buffer (vec)
6261 "Get the debug buffer for VEC."
6262 (with-current-buffer
6263 (get-buffer-create (tramp-debug-buffer-name vec))
6264 (when (bobp)
6265 (setq buffer-undo-list t)
6266 ;; Activate outline-mode. This runs `text-mode-hook' and
6267 ;; `outline-mode-hook'. We must prevent that local processes
6268 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
6269 ;; ...
6270 (let ((default-directory (tramp-compat-temporary-file-directory)))
6271 (outline-mode))
6272 (set (make-local-variable 'outline-regexp)
6273 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6274 ; (set (make-local-variable 'outline-regexp)
6275 ; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
6276 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6277 (current-buffer)))
6279 (defun tramp-outline-level ()
6280 "Return the depth to which a statement is nested in the outline.
6281 Point must be at the beginning of a header line.
6283 The outline level is equal to the verbosity of the Tramp message."
6284 (1+ (string-to-number (match-string 1))))
6286 (defun tramp-find-executable
6287 (vec progname dirlist &optional ignore-tilde ignore-path)
6288 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6289 First arg VEC specifies the connection, PROGNAME is the program
6290 to search for, and DIRLIST gives the list of directories to
6291 search. If IGNORE-TILDE is non-nil, directory names starting
6292 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6293 only in DIRLIST.
6295 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6297 This function expects to be in the right *tramp* buffer."
6298 (with-current-buffer (tramp-get-buffer vec)
6299 (let (result)
6300 ;; Check whether the executable is in $PATH. "which(1)" does not
6301 ;; report always a correct error code; therefore we check the
6302 ;; number of words it returns.
6303 (unless ignore-path
6304 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6305 (goto-char (point-min))
6306 (if (looking-at "^1$")
6307 (setq result (concat "\\" progname))))
6308 (unless result
6309 (when ignore-tilde
6310 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
6311 ;; `remove' is in CL, and we want to avoid CL dependencies.
6312 (let (newdl d)
6313 (while dirlist
6314 (setq d (car dirlist))
6315 (setq dirlist (cdr dirlist))
6316 (unless (char-equal ?~ (aref d 0))
6317 (setq newdl (cons d newdl))))
6318 (setq dirlist (nreverse newdl))))
6319 (tramp-send-command
6321 (format (concat "while read d; "
6322 "do if test -x $d/%s -a -f $d/%s; "
6323 "then echo tramp_executable $d/%s; "
6324 "break; fi; done <<'EOF'\n"
6325 "%s\nEOF")
6326 progname progname progname (mapconcat 'identity dirlist "\n")))
6327 (goto-char (point-max))
6328 (when (search-backward "tramp_executable " nil t)
6329 (skip-chars-forward "^ ")
6330 (skip-chars-forward " ")
6331 (setq result (buffer-substring
6332 (point) (tramp-compat-line-end-position)))))
6333 result)))
6335 (defun tramp-set-remote-path (vec)
6336 "Sets the remote environment PATH to existing directories.
6337 I.e., for each directory in `tramp-remote-path', it is tested
6338 whether it exists and if so, it is added to the environment
6339 variable PATH."
6340 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6341 (tramp-send-command
6342 vec (format "PATH=%s; export PATH"
6343 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6345 ;; ------------------------------------------------------------
6346 ;; -- Communication with external shell --
6347 ;; ------------------------------------------------------------
6349 (defun tramp-find-file-exists-command (vec)
6350 "Find a command on the remote host for checking if a file exists.
6351 Here, we are looking for a command which has zero exit status if the
6352 file exists and nonzero exit status otherwise."
6353 (let ((existing "/")
6354 (nonexisting
6355 (tramp-shell-quote-argument "/ this file does not exist "))
6356 result)
6357 ;; The algorithm is as follows: we try a list of several commands.
6358 ;; For each command, we first run `$cmd /' -- this should return
6359 ;; true, as the root directory always exists. And then we run
6360 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6361 ;; does not exist. This should return false. We use the first
6362 ;; command we find that seems to work.
6363 ;; The list of commands to try is as follows:
6364 ;; `ls -d' This works on most systems, but NetBSD 1.4
6365 ;; has a bug: `ls' always returns zero exit
6366 ;; status, even for files which don't exist.
6367 ;; `test -e' Some Bourne shells have a `test' builtin
6368 ;; which does not know the `-e' option.
6369 ;; `/bin/test -e' For those, the `test' binary on disk normally
6370 ;; provides the option. Alas, the binary
6371 ;; is sometimes `/bin/test' and sometimes it's
6372 ;; `/usr/bin/test'.
6373 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6374 (unless (or
6375 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6376 (zerop (tramp-send-command-and-check
6377 vec (format "%s %s" result existing)))
6378 (not (zerop (tramp-send-command-and-check
6379 vec (format "%s %s" result nonexisting)))))
6380 (and (setq result "/bin/test -e")
6381 (zerop (tramp-send-command-and-check
6382 vec (format "%s %s" result existing)))
6383 (not (zerop (tramp-send-command-and-check
6384 vec (format "%s %s" result nonexisting)))))
6385 (and (setq result "/usr/bin/test -e")
6386 (zerop (tramp-send-command-and-check
6387 vec (format "%s %s" result existing)))
6388 (not (zerop (tramp-send-command-and-check
6389 vec (format "%s %s" result nonexisting)))))
6390 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6391 (zerop (tramp-send-command-and-check
6392 vec (format "%s %s" result existing)))
6393 (not (zerop (tramp-send-command-and-check
6394 vec (format "%s %s" result nonexisting))))))
6395 (tramp-error
6396 vec 'file-error "Couldn't find command to check if file exists"))
6397 result))
6399 ;; CCC test ksh or bash found for tilde expansion?
6400 (defun tramp-find-shell (vec)
6401 "Opens a shell on the remote host which groks tilde expansion."
6402 (unless (tramp-get-connection-property vec "remote-shell" nil)
6403 (let (shell)
6404 (with-current-buffer (tramp-get-buffer vec)
6405 (tramp-send-command vec "echo ~root" t)
6406 (cond
6407 ((string-match "^~root$" (buffer-string))
6408 (setq shell
6409 (or (tramp-find-executable
6410 vec "bash" (tramp-get-remote-path vec) t)
6411 (tramp-find-executable
6412 vec "ksh" (tramp-get-remote-path vec) t)))
6413 (unless shell
6414 (tramp-error
6415 vec 'file-error
6416 "Couldn't find a shell which groks tilde expansion"))
6417 ;; Find arguments for this shell.
6418 (let ((alist tramp-sh-extra-args)
6419 item extra-args)
6420 (while (and alist (null extra-args))
6421 (setq item (pop alist))
6422 (when (string-match (car item) shell)
6423 (setq extra-args (cdr item))))
6424 (when extra-args (setq shell (concat shell " " extra-args))))
6425 (tramp-message
6426 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
6427 (let ((tramp-end-of-output tramp-initial-end-of-output))
6428 (tramp-send-command
6430 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6431 (shell-quote-argument tramp-end-of-output) shell)
6433 ;; Setting prompts.
6434 (tramp-message vec 5 "Setting remote shell prompt...")
6435 (tramp-send-command
6436 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6437 (tramp-send-command vec "PS2=''" t)
6438 (tramp-send-command vec "PS3=''" t)
6439 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6440 (tramp-message vec 5 "Setting remote shell prompt...done"))
6442 (t (tramp-message
6443 vec 5 "Remote `%s' groks tilde expansion, good"
6444 (tramp-get-method-parameter
6445 (tramp-file-name-method vec) 'tramp-remote-sh))
6446 (tramp-set-connection-property
6447 vec "remote-shell"
6448 (tramp-get-method-parameter
6449 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
6451 ;; ------------------------------------------------------------
6452 ;; -- Functions for establishing connection --
6453 ;; ------------------------------------------------------------
6455 ;; The following functions are actions to be taken when seeing certain
6456 ;; prompts from the remote host. See the variable
6457 ;; `tramp-actions-before-shell' for usage of these functions.
6459 (defun tramp-action-login (proc vec)
6460 "Send the login name."
6461 (when (not (stringp tramp-current-user))
6462 (save-window-excursion
6463 (let ((enable-recursive-minibuffers t))
6464 (pop-to-buffer (tramp-get-connection-buffer vec))
6465 (setq tramp-current-user (read-string (match-string 0))))))
6466 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6467 (with-current-buffer (tramp-get-connection-buffer vec)
6468 (tramp-message vec 6 "\n%s" (buffer-string)))
6469 (tramp-send-string vec tramp-current-user))
6471 (defun tramp-action-password (proc vec)
6472 "Query the user for a password."
6473 (with-current-buffer (process-buffer proc)
6474 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6475 (tramp-message vec 3 "Sending %s" (match-string 1)))
6476 (tramp-enter-password proc))
6478 (defun tramp-action-succeed (proc vec)
6479 "Signal success in finding shell prompt."
6480 (throw 'tramp-action 'ok))
6482 (defun tramp-action-permission-denied (proc vec)
6483 "Signal permission denied."
6484 (kill-process proc)
6485 (throw 'tramp-action 'permission-denied))
6487 (defun tramp-action-yesno (proc vec)
6488 "Ask the user for confirmation using `yes-or-no-p'.
6489 Send \"yes\" to remote process on confirmation, abort otherwise.
6490 See also `tramp-action-yn'."
6491 (save-window-excursion
6492 (let ((enable-recursive-minibuffers t))
6493 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6494 (unless (yes-or-no-p (match-string 0))
6495 (kill-process proc)
6496 (throw 'tramp-action 'permission-denied))
6497 (with-current-buffer (tramp-get-connection-buffer vec)
6498 (tramp-message vec 6 "\n%s" (buffer-string)))
6499 (tramp-send-string vec "yes"))))
6501 (defun tramp-action-yn (proc vec)
6502 "Ask the user for confirmation using `y-or-n-p'.
6503 Send \"y\" to remote process on confirmation, abort otherwise.
6504 See also `tramp-action-yesno'."
6505 (save-window-excursion
6506 (let ((enable-recursive-minibuffers t))
6507 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6508 (unless (y-or-n-p (match-string 0))
6509 (kill-process proc)
6510 (throw 'tramp-action 'permission-denied))
6511 (with-current-buffer (tramp-get-connection-buffer vec)
6512 (tramp-message vec 6 "\n%s" (buffer-string)))
6513 (tramp-send-string vec "y"))))
6515 (defun tramp-action-terminal (proc vec)
6516 "Tell the remote host which terminal type to use.
6517 The terminal type can be configured with `tramp-terminal-type'."
6518 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6519 (with-current-buffer (tramp-get-connection-buffer vec)
6520 (tramp-message vec 6 "\n%s" (buffer-string)))
6521 (tramp-send-string vec tramp-terminal-type))
6523 (defun tramp-action-process-alive (proc vec)
6524 "Check whether a process has finished."
6525 (unless (memq (process-status proc) '(run open))
6526 (throw 'tramp-action 'process-died)))
6528 (defun tramp-action-out-of-band (proc vec)
6529 "Check whether an out-of-band copy has finished."
6530 (cond ((and (memq (process-status proc) '(stop exit))
6531 (zerop (process-exit-status proc)))
6532 (tramp-message vec 3 "Process has finished.")
6533 (throw 'tramp-action 'ok))
6534 ((or (and (memq (process-status proc) '(stop exit))
6535 (not (zerop (process-exit-status proc))))
6536 (memq (process-status proc) '(signal)))
6537 ;; `scp' could have copied correctly, but set modes could have failed.
6538 ;; This can be ignored.
6539 (with-current-buffer (process-buffer proc)
6540 (goto-char (point-min))
6541 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6542 (progn
6543 (tramp-message vec 5 "'set mode' error ignored.")
6544 (tramp-message vec 3 "Process has finished.")
6545 (throw 'tramp-action 'ok))
6546 (tramp-message vec 3 "Process has died.")
6547 (throw 'tramp-action 'process-died))))
6548 (t nil)))
6550 ;; Functions for processing the actions.
6552 (defun tramp-process-one-action (proc vec actions)
6553 "Wait for output from the shell and perform one action."
6554 (let (found todo item pattern action)
6555 (while (not found)
6556 ;; Reread output once all actions have been performed.
6557 ;; Obviously, the output was not complete.
6558 (tramp-accept-process-output proc 1)
6559 (setq todo actions)
6560 (while todo
6561 (setq item (pop todo))
6562 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6563 (setq action (nth 1 item))
6564 (tramp-message
6565 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6566 (when (tramp-check-for-regexp proc pattern)
6567 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6568 (setq found (funcall action proc vec)))))
6569 found))
6571 (defun tramp-process-actions (proc vec actions &optional timeout)
6572 "Perform actions until success or TIMEOUT."
6573 ;; Enable auth-source and password-cache.
6574 (tramp-set-connection-property vec "first-password-request" t)
6575 (let (exit)
6576 (while (not exit)
6577 (tramp-message proc 3 "Waiting for prompts from remote shell")
6578 (setq exit
6579 (catch 'tramp-action
6580 (if timeout
6581 (with-timeout (timeout)
6582 (tramp-process-one-action proc vec actions))
6583 (tramp-process-one-action proc vec actions)))))
6584 (with-current-buffer (tramp-get-connection-buffer vec)
6585 (tramp-message vec 6 "\n%s" (buffer-string)))
6586 (unless (eq exit 'ok)
6587 (tramp-clear-passwd vec)
6588 (tramp-error-with-buffer
6589 nil vec 'file-error
6590 (cond
6591 ((eq exit 'permission-denied) "Permission denied")
6592 ((eq exit 'process-died) "Process died")
6593 (t "Login failed"))))))
6595 ;; Utility functions.
6597 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6598 "Like `accept-process-output' for Tramp processes.
6599 This is needed in order to hide `last-coding-system-used', which is set
6600 for process communication also."
6601 (with-current-buffer (process-buffer proc)
6602 (tramp-message proc 10 "%s %s" proc (process-status proc))
6603 (let (buffer-read-only last-coding-system-used)
6604 ;; Under Windows XP, accept-process-output doesn't return
6605 ;; sometimes. So we add an additional timeout.
6606 (with-timeout ((or timeout 1))
6607 (accept-process-output proc timeout timeout-msecs)))
6608 (tramp-message proc 10 "\n%s" (buffer-string))))
6610 (defun tramp-check-for-regexp (proc regexp)
6611 "Check whether REGEXP is contained in process buffer of PROC.
6612 Erase echoed commands if exists."
6613 (with-current-buffer (process-buffer proc)
6614 (goto-char (point-min))
6616 ;; Check whether we need to remove echo output.
6617 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6618 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6619 (let ((begin (match-beginning 0)))
6620 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6621 ;; Discard echo from remote output.
6622 (tramp-set-connection-property proc "check-remote-echo" nil)
6623 (tramp-message proc 5 "echo-mark found")
6624 (forward-line)
6625 (delete-region begin (point))
6626 (goto-char (point-min)))))
6628 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6629 ;; Sometimes, the echo string is suppressed on the remote side.
6630 (not (string-equal
6631 (substring-no-properties
6632 tramp-echo-mark-marker
6633 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6634 (buffer-substring-no-properties
6635 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6636 ;; No echo to be handled, now we can look for the regexp.
6637 (goto-char (point-min))
6638 (re-search-forward regexp nil t))))
6640 (defun tramp-wait-for-regexp (proc timeout regexp)
6641 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6642 Expects the output of PROC to be sent to the current buffer. Returns
6643 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6644 nil."
6645 (with-current-buffer (process-buffer proc)
6646 (let ((found (tramp-check-for-regexp proc regexp))
6647 (start-time (current-time)))
6648 (cond (timeout
6649 ;; Work around a bug in XEmacs 21, where the timeout
6650 ;; expires faster than it should. This degenerates
6651 ;; to polling for buggy XEmacsen, but oh, well.
6652 (while (and (not found)
6653 (< (tramp-time-diff (current-time) start-time)
6654 timeout))
6655 (with-timeout (timeout)
6656 (while (not found)
6657 (tramp-accept-process-output proc 1)
6658 (unless (memq (process-status proc) '(run open))
6659 (tramp-error-with-buffer
6660 nil proc 'file-error "Process has died"))
6661 (setq found (tramp-check-for-regexp proc regexp))))))
6663 (while (not found)
6664 (tramp-accept-process-output proc 1)
6665 (unless (memq (process-status proc) '(run open))
6666 (tramp-error-with-buffer
6667 nil proc 'file-error "Process has died"))
6668 (setq found (tramp-check-for-regexp proc regexp)))))
6669 (tramp-message proc 6 "\n%s" (buffer-string))
6670 (when (not found)
6671 (if timeout
6672 (tramp-error
6673 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6674 regexp timeout)
6675 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6676 found)))
6678 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6679 "Wait for shell prompt and barf if none appears.
6680 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6681 seconds. If not, it produces an error message with the given ERROR-ARGS."
6682 (unless
6683 (tramp-wait-for-regexp
6684 proc timeout
6685 (format
6686 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6687 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6689 ;; We don't call `tramp-send-string' in order to hide the password
6690 ;; from the debug buffer, and because end-of-line handling of the
6691 ;; string.
6692 (defun tramp-enter-password (proc)
6693 "Prompt for a password and send it to the remote end."
6694 (process-send-string
6695 proc (concat (tramp-read-passwd proc)
6696 (or (tramp-get-method-parameter
6697 tramp-current-method
6698 'tramp-password-end-of-line)
6699 tramp-default-password-end-of-line))))
6701 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6702 "Set up an interactive shell.
6703 Mainly sets the prompt and the echo correctly. PROC is the shell
6704 process to set up. VEC specifies the connection."
6705 (let ((tramp-end-of-output tramp-initial-end-of-output))
6706 ;; It is useful to set the prompt in the following command because
6707 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6708 ;; about and thus /bin/sh will display a strange prompt. For
6709 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6710 ;; display the current working directory but /bin/sh will display
6711 ;; a dollar sign. The following command line sets $PS1 to a sane
6712 ;; value, and works under Bourne-ish shells as well as csh-like
6713 ;; shells. Daniel Pittman reports that the unusual positioning of
6714 ;; the single quotes makes it work under `rc', too. We also unset
6715 ;; the variable $ENV because that is read by some sh
6716 ;; implementations (eg, bash when called as sh) on startup; this
6717 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6718 ;; is another way to set the prompt in /bin/bash, it must be
6719 ;; discarded as well.
6720 (tramp-send-command
6722 (format
6723 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6724 (shell-quote-argument tramp-end-of-output)
6725 (tramp-get-method-parameter
6726 (tramp-file-name-method vec) 'tramp-remote-sh))
6729 ;; Disable echo.
6730 (tramp-message vec 5 "Setting up remote shell environment")
6731 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6732 ;; Check whether the echo has really been disabled. Some
6733 ;; implementations, like busybox of embedded GNU/Linux, don't
6734 ;; support disabling.
6735 (tramp-send-command vec "echo foo" t)
6736 (with-current-buffer (process-buffer proc)
6737 (goto-char (point-min))
6738 (when (looking-at "echo foo")
6739 (tramp-set-connection-property proc "remote-echo" t)
6740 (tramp-message vec 5 "Remote echo still on. Ok.")
6741 ;; Make sure backspaces and their echo are enabled and no line
6742 ;; width magic interferes with them.
6743 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6745 (tramp-message vec 5 "Setting shell prompt")
6746 (tramp-send-command
6747 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6748 (tramp-send-command vec "PS2=''" t)
6749 (tramp-send-command vec "PS3=''" t)
6750 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6752 ;; Try to set up the coding system correctly.
6753 ;; CCC this can't be the right way to do it. Hm.
6754 (tramp-message vec 5 "Determining coding system")
6755 (tramp-send-command vec "echo foo ; echo bar" t)
6756 (with-current-buffer (process-buffer proc)
6757 (goto-char (point-min))
6758 (if (featurep 'mule)
6759 ;; Use MULE to select the right EOL convention for communicating
6760 ;; with the process.
6761 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
6762 (cons 'undecided 'undecided)))
6763 cs-decode cs-encode)
6764 (when (symbolp cs) (setq cs (cons cs cs)))
6765 (setq cs-decode (car cs))
6766 (setq cs-encode (cdr cs))
6767 (unless cs-decode (setq cs-decode 'undecided))
6768 (unless cs-encode (setq cs-encode 'undecided))
6769 (setq cs-encode (tramp-coding-system-change-eol-conversion
6770 cs-encode 'unix))
6771 (when (search-forward "\r" nil t)
6772 (setq cs-decode (tramp-coding-system-change-eol-conversion
6773 cs-decode 'dos)))
6774 (funcall (symbol-function 'set-buffer-process-coding-system)
6775 cs-decode cs-encode)
6776 (tramp-message
6777 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6778 ;; Look for ^M and do something useful if found.
6779 (when (search-forward "\r" nil t)
6780 ;; We have found a ^M but cannot frob the process coding system
6781 ;; because we're running on a non-MULE Emacs. Let's try
6782 ;; stty, instead.
6783 (tramp-send-command vec "stty -onlcr" t))))
6784 ;; Dump stty settings in the traces.
6785 (when (>= tramp-verbose 10)
6786 (tramp-send-command vec "stty -a" t))
6787 (tramp-send-command vec "set +o vi +o emacs" t)
6789 ;; Check whether the output of "uname -sr" has been changed. If
6790 ;; yes, this is a strong indication that we must expire all
6791 ;; connection properties. We start again with
6792 ;; `tramp-maybe-open-connection', it will be catched there.
6793 (tramp-message vec 5 "Checking system information")
6794 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6795 (new-uname
6796 (tramp-set-connection-property
6797 vec "uname"
6798 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6799 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
6800 (with-current-buffer (tramp-get-debug-buffer vec)
6801 ;; Keep the debug buffer
6802 (rename-buffer
6803 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
6804 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6805 (if (= (point-min) (point-max))
6806 (kill-buffer nil)
6807 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6808 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6809 (tramp-get-buffer vec)
6810 (tramp-message
6811 vec 3
6812 "Connection reset, because remote host changed from `%s' to `%s'"
6813 old-uname new-uname)
6814 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
6816 ;; Check whether the remote host suffers from buggy
6817 ;; `send-process-string'. This is known for FreeBSD (see comment in
6818 ;; `send_process', file process.c). I've tested sending 624 bytes
6819 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6820 ;; this host type is detected locally. It cannot handle remote
6821 ;; hosts, though.
6822 (with-connection-property proc "chunksize"
6823 (cond
6824 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6825 tramp-chunksize)
6827 (tramp-message
6828 vec 5 "Checking remote host type for `send-process-string' bug")
6829 (if (string-match
6830 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
6831 500 0))))
6833 ;; Set remote PATH variable.
6834 (tramp-set-remote-path vec)
6836 ;; Search for a good shell before searching for a command which
6837 ;; checks if a file exists. This is done because Tramp wants to use
6838 ;; "test foo; echo $?" to check if various conditions hold, and
6839 ;; there are buggy /bin/sh implementations which don't execute the
6840 ;; "echo $?" part if the "test" part has an error. In particular,
6841 ;; the Solaris /bin/sh is a problem. I'm betting that all systems
6842 ;; with buggy /bin/sh implementations will have a working bash or
6843 ;; ksh. Whee...
6844 (tramp-find-shell vec)
6846 ;; Disable unexpected output.
6847 (tramp-send-command vec "mesg n; biff n" t)
6849 ;; Set the environment.
6850 (tramp-message vec 5 "Setting default environment")
6852 ;; On OpenSolaris, there is a bug when HISTFILE is changed in place
6853 ;; <http://bugs.opensolaris.org/view_bug.do?bug_id=6834184>. We
6854 ;; apply the workaround.
6855 (if (string-equal (tramp-get-connection-property vec "uname" "") "SunOS 5.11")
6856 (tramp-send-command vec "unset HISTFILE" t))
6858 (let ((env (copy-sequence tramp-remote-process-environment))
6859 unset item)
6860 (while env
6861 (setq item (tramp-compat-split-string (car env) "="))
6862 (setcdr item (mapconcat 'identity (cdr item) "="))
6863 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
6864 (tramp-send-command
6865 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
6866 (push (car item) unset))
6867 (setq env (cdr env)))
6868 (when unset
6869 (tramp-send-command
6870 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
6872 ;; CCC: We should either implement a Perl version of base64 encoding
6873 ;; and decoding. Then we just use that in the last item. The other
6874 ;; alternative is to use the Perl version of UU encoding. But then
6875 ;; we need a Lisp version of uuencode.
6877 ;; Old text from documentation of tramp-methods:
6878 ;; Using a uuencode/uudecode inline method is discouraged, please use one
6879 ;; of the base64 methods instead since base64 encoding is much more
6880 ;; reliable and the commands are more standardized between the different
6881 ;; Unix versions. But if you can't use base64 for some reason, please
6882 ;; note that the default uudecode command does not work well for some
6883 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
6884 ;; the following command for uudecode:
6886 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6888 ;; For Irix, no solution is known yet.
6890 (defconst tramp-local-coding-commands
6891 '((b64 base64-encode-region base64-decode-region)
6892 (uu tramp-uuencode-region uudecode-decode-region)
6893 (pack
6894 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6895 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6896 "List of local coding commands for inline transfer.
6897 Each item is a list that looks like this:
6899 \(FORMAT ENCODING DECODING)
6901 FORMAT is symbol describing the encoding/decoding format. It can be
6902 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6904 ENCODING and DECODING can be strings, giving commands, or symbols,
6905 giving functions. If they are strings, then they can contain
6906 the \"%s\" format specifier. If that specifier is present, the input
6907 filename will be put into the command line at that spot. If the
6908 specifier is not present, the input should be read from standard
6909 input.
6911 If they are functions, they will be called with two arguments, start
6912 and end of region, and are expected to replace the region contents
6913 with the encoded or decoded results, respectively.")
6915 (defconst tramp-remote-coding-commands
6916 '((b64 "base64" "base64 -d")
6917 (b64 "mimencode -b" "mimencode -u -b")
6918 (b64 "mmencode -b" "mmencode -u -b")
6919 (b64 "recode data..base64" "recode base64..data")
6920 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6921 (b64 tramp-perl-encode tramp-perl-decode)
6922 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6923 (uu "uuencode xxx" "uudecode -o -")
6924 (uu "uuencode xxx" "uudecode -p")
6925 (uu "uuencode xxx" tramp-uudecode)
6926 (pack
6927 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6928 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6929 "List of remote coding commands for inline transfer.
6930 Each item is a list that looks like this:
6932 \(FORMAT ENCODING DECODING)
6934 FORMAT is symbol describing the encoding/decoding format. It can be
6935 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6937 ENCODING and DECODING can be strings, giving commands, or symbols,
6938 giving variables. If they are strings, then they can contain
6939 the \"%s\" format specifier. If that specifier is present, the input
6940 filename will be put into the command line at that spot. If the
6941 specifier is not present, the input should be read from standard
6942 input.
6944 If they are variables, this variable is a string containing a Perl
6945 implementation for this functionality. This Perl program will be transferred
6946 to the remote host, and it is available as shell function with the same name.")
6948 (defun tramp-find-inline-encoding (vec)
6949 "Find an inline transfer encoding that works.
6950 Goes through the list `tramp-local-coding-commands' and
6951 `tramp-remote-coding-commands'."
6952 (save-excursion
6953 (let ((local-commands tramp-local-coding-commands)
6954 (magic "xyzzy")
6955 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6956 (while (and local-commands (not found))
6957 (setq litem (pop local-commands))
6958 (catch 'wont-work-local
6959 (let ((format (nth 0 litem))
6960 (remote-commands tramp-remote-coding-commands))
6961 (setq loc-enc (nth 1 litem))
6962 (setq loc-dec (nth 2 litem))
6963 ;; If the local encoder or decoder is a string, the
6964 ;; corresponding command has to work locally.
6965 (if (not (stringp loc-enc))
6966 (tramp-message
6967 vec 5 "Checking local encoding function `%s'" loc-enc)
6968 (tramp-message
6969 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6970 (unless (zerop (tramp-call-local-coding-command
6971 loc-enc nil nil))
6972 (throw 'wont-work-local nil)))
6973 (if (not (stringp loc-dec))
6974 (tramp-message
6975 vec 5 "Checking local decoding function `%s'" loc-dec)
6976 (tramp-message
6977 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
6978 (unless (zerop (tramp-call-local-coding-command
6979 loc-dec nil nil))
6980 (throw 'wont-work-local nil)))
6981 ;; Search for remote coding commands with the same format
6982 (while (and remote-commands (not found))
6983 (setq ritem (pop remote-commands))
6984 (catch 'wont-work-remote
6985 (when (equal format (nth 0 ritem))
6986 (setq rem-enc (nth 1 ritem))
6987 (setq rem-dec (nth 2 ritem))
6988 ;; Check if remote encoding and decoding commands can be
6989 ;; called remotely with null input and output. This makes
6990 ;; sure there are no syntax errors and the command is really
6991 ;; found. Note that we do not redirect stdout to /dev/null,
6992 ;; for two reasons: when checking the decoding command, we
6993 ;; actually check the output it gives. And also, when
6994 ;; redirecting "mimencode" output to /dev/null, then as root
6995 ;; it might change the permissions of /dev/null!
6996 (when (not (stringp rem-enc))
6997 (let ((name (symbol-name rem-enc)))
6998 (while (string-match (regexp-quote "-") name)
6999 (setq name (replace-match "_" nil t name)))
7000 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7001 (setq rem-enc name)))
7002 (tramp-message
7003 vec 5
7004 "Checking remote encoding command `%s' for sanity" rem-enc)
7005 (unless (zerop (tramp-send-command-and-check
7006 vec (format "%s </dev/null" rem-enc) t))
7007 (throw 'wont-work-remote nil))
7009 (when (not (stringp rem-dec))
7010 (let ((name (symbol-name rem-dec)))
7011 (while (string-match (regexp-quote "-") name)
7012 (setq name (replace-match "_" nil t name)))
7013 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7014 (setq rem-dec name)))
7015 (tramp-message
7016 vec 5
7017 "Checking remote decoding command `%s' for sanity" rem-dec)
7018 (unless (zerop (tramp-send-command-and-check
7020 (format "echo %s | %s | %s"
7021 magic rem-enc rem-dec)
7023 (throw 'wont-work-remote nil))
7025 (with-current-buffer (tramp-get-buffer vec)
7026 (goto-char (point-min))
7027 (unless (looking-at (regexp-quote magic))
7028 (throw 'wont-work-remote nil)))
7030 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7031 (setq rem-enc (nth 1 ritem))
7032 (setq rem-dec (nth 2 ritem))
7033 (setq found t)))))))
7035 ;; Did we find something?
7036 (unless found
7037 (tramp-error
7038 vec 'file-error "Couldn't find an inline transfer encoding"))
7040 ;; Set connection properties.
7041 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7042 (tramp-set-connection-property vec "local-encoding" loc-enc)
7043 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7044 (tramp-set-connection-property vec "local-decoding" loc-dec)
7045 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7046 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7047 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7048 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7050 (defun tramp-call-local-coding-command (cmd input output)
7051 "Call the local encoding or decoding command.
7052 If CMD contains \"%s\", provide input file INPUT there in command.
7053 Otherwise, INPUT is passed via standard input.
7054 INPUT can also be nil which means `/dev/null'.
7055 OUTPUT can be a string (which specifies a filename), or t (which
7056 means standard output and thus the current buffer), or nil (which
7057 means discard it)."
7058 (tramp-local-call-process
7059 tramp-encoding-shell
7060 (when (and input (not (string-match "%s" cmd))) input)
7061 (if (eq output t) t nil)
7063 tramp-encoding-command-switch
7064 (concat
7065 (if (string-match "%s" cmd) (format cmd input) cmd)
7066 (if (stringp output) (concat "> " output) ""))))
7068 (defun tramp-compute-multi-hops (vec)
7069 "Expands VEC according to `tramp-default-proxies-alist'.
7070 Gateway hops are already opened."
7071 (let ((target-alist `(,vec))
7072 (choices tramp-default-proxies-alist)
7073 item proxy)
7075 ;; Look for proxy hosts to be passed.
7076 (while choices
7077 (setq item (pop choices)
7078 proxy (eval (nth 2 item)))
7079 (when (and
7080 ;; host
7081 (string-match (or (eval (nth 0 item)) "")
7082 (or (tramp-file-name-host (car target-alist)) ""))
7083 ;; user
7084 (string-match (or (eval (nth 1 item)) "")
7085 (or (tramp-file-name-user (car target-alist)) "")))
7086 (if (null proxy)
7087 ;; No more hops needed.
7088 (setq choices nil)
7089 ;; Replace placeholders.
7090 (setq proxy
7091 (format-spec
7092 proxy
7093 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
7094 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
7095 (with-parsed-tramp-file-name proxy l
7096 ;; Add the hop.
7097 (add-to-list 'target-alist l)
7098 ;; Start next search.
7099 (setq choices tramp-default-proxies-alist)))))
7101 ;; Handle gateways.
7102 (when (and (boundp 'tramp-gw-tunnel-method)
7103 (string-match (format
7104 "^\\(%s\\|%s\\)$"
7105 (symbol-value 'tramp-gw-tunnel-method)
7106 (symbol-value 'tramp-gw-socks-method))
7107 (tramp-file-name-method (car target-alist))))
7108 (let ((gw (pop target-alist))
7109 (hop (pop target-alist)))
7110 ;; Is the method prepared for gateways?
7111 (unless (tramp-get-method-parameter
7112 (tramp-file-name-method hop) 'tramp-default-port)
7113 (tramp-error
7114 vec 'file-error
7115 "Method `%s' is not supported for gateway access."
7116 (tramp-file-name-method hop)))
7117 ;; Add default port if needed.
7118 (unless
7119 (string-match
7120 tramp-host-with-port-regexp (tramp-file-name-host hop))
7121 (aset hop 2
7122 (concat
7123 (tramp-file-name-host hop) tramp-prefix-port-format
7124 (number-to-string
7125 (tramp-get-method-parameter
7126 (tramp-file-name-method hop) 'tramp-default-port)))))
7127 ;; Open the gateway connection.
7128 (add-to-list
7129 'target-alist
7130 (vector
7131 (tramp-file-name-method hop) (tramp-file-name-user hop)
7132 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
7133 ;; For the password prompt, we need the correct values.
7134 ;; Therefore, we must remember the gateway vector. But we
7135 ;; cannot do it as connection property, because it shouldn't
7136 ;; be persistent. And we have no started process yet either.
7137 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7139 ;; Foreign and out-of-band methods are not supported for multi-hops.
7140 (when (cdr target-alist)
7141 (setq choices target-alist)
7142 (while choices
7143 (setq item (pop choices))
7144 (when
7146 (not
7147 (tramp-get-method-parameter
7148 (tramp-file-name-method item) 'tramp-login-program))
7149 (tramp-get-method-parameter
7150 (tramp-file-name-method item) 'tramp-copy-program))
7151 (tramp-error
7152 vec 'file-error
7153 "Method `%s' is not supported for multi-hops."
7154 (tramp-file-name-method item)))))
7156 ;; In case the host name is not used for the remote shell
7157 ;; command, the user could be misguided by applying a random
7158 ;; hostname.
7159 (let* ((v (car target-alist))
7160 (method (tramp-file-name-method v))
7161 (host (tramp-file-name-host v)))
7162 (unless
7164 ;; There are multi-hops.
7165 (cdr target-alist)
7166 ;; The host name is used for the remote shell command.
7167 (member
7168 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7169 ;; The host is local. We cannot use `tramp-local-host-p'
7170 ;; here, because it opens a connection as well.
7171 (string-match tramp-local-host-regexp host))
7172 (tramp-error
7173 v 'file-error
7174 "Host `%s' looks like a remote host, `%s' can only use the local host"
7175 host method)))
7177 ;; Result.
7178 target-alist))
7180 (defun tramp-maybe-open-connection (vec)
7181 "Maybe open a connection VEC.
7182 Does not do anything if a connection is already open, but re-opens the
7183 connection if a previous connection has died for some reason."
7184 (catch 'uname-changed
7185 (let ((p (tramp-get-connection-process vec))
7186 (process-environment (copy-sequence process-environment)))
7188 ;; If too much time has passed since last command was sent, look
7189 ;; whether process is still alive. If it isn't, kill it. When
7190 ;; using ssh, it can sometimes happen that the remote end has
7191 ;; hung up but the local ssh client doesn't recognize this until
7192 ;; it tries to send some data to the remote end. So that's why
7193 ;; we try to send a command from time to time, then look again
7194 ;; whether the process is really alive.
7195 (condition-case nil
7196 (when (and (> (tramp-time-diff
7197 (current-time)
7198 (tramp-get-connection-property
7199 p "last-cmd-time" '(0 0 0)))
7201 p (processp p) (memq (process-status p) '(run open)))
7202 (tramp-send-command vec "echo are you awake" t t)
7203 (unless (and (memq (process-status p) '(run open))
7204 (tramp-wait-for-output p 10))
7205 ;; The error will be catched locally.
7206 (tramp-error vec 'file-error "Awake did fail")))
7207 (file-error
7208 (tramp-flush-connection-property vec)
7209 (tramp-flush-connection-property p)
7210 (delete-process p)
7211 (setq p nil)))
7213 ;; New connection must be opened.
7214 (unless (and p (processp p) (memq (process-status p) '(run open)))
7216 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7217 ;; messages from the beginning.
7218 (tramp-get-buffer vec)
7219 (if (zerop (length (tramp-file-name-user vec)))
7220 (tramp-message
7221 vec 3 "Opening connection for %s using %s..."
7222 (tramp-file-name-host vec)
7223 (tramp-file-name-method vec))
7224 (tramp-message
7225 vec 3 "Opening connection for %s@%s using %s..."
7226 (tramp-file-name-user vec)
7227 (tramp-file-name-host vec)
7228 (tramp-file-name-method vec)))
7230 ;; Start new process.
7231 (when (and p (processp p))
7232 (delete-process p))
7233 (setenv "TERM" tramp-terminal-type)
7234 (setenv "LC_ALL" "C")
7235 (setenv "PROMPT_COMMAND")
7236 (setenv "PS1" tramp-initial-end-of-output)
7237 (let* ((target-alist (tramp-compute-multi-hops vec))
7238 (process-connection-type tramp-process-connection-type)
7239 (process-adaptive-read-buffering nil)
7240 (coding-system-for-read nil)
7241 ;; This must be done in order to avoid our file name handler.
7242 (p (let ((default-directory
7243 (tramp-compat-temporary-file-directory)))
7244 (start-process
7245 (or (tramp-get-connection-property vec "process-name" nil)
7246 (tramp-buffer-name vec))
7247 (tramp-get-connection-buffer vec)
7248 tramp-encoding-shell))))
7250 (tramp-message
7251 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7253 ;; Check whether process is alive.
7254 (tramp-set-process-query-on-exit-flag p nil)
7255 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
7256 (tramp-barf-if-no-shell-prompt
7257 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7259 ;; Now do all the connections as specified.
7260 (while target-alist
7261 (let* ((hop (car target-alist))
7262 (l-method (tramp-file-name-method hop))
7263 (l-user (tramp-file-name-user hop))
7264 (l-host (tramp-file-name-host hop))
7265 (l-port nil)
7266 (login-program
7267 (tramp-get-method-parameter l-method 'tramp-login-program))
7268 (login-args
7269 (tramp-get-method-parameter l-method 'tramp-login-args))
7270 (gw-args
7271 (tramp-get-method-parameter l-method 'tramp-gw-args))
7272 (gw (tramp-get-file-property hop "" "gateway" nil))
7273 (g-method (and gw (tramp-file-name-method gw)))
7274 (g-user (and gw (tramp-file-name-user gw)))
7275 (g-host (and gw (tramp-file-name-host gw)))
7276 (command login-program)
7277 ;; We don't create the temporary file. In fact, it
7278 ;; is just a prefix for the ControlPath option of
7279 ;; ssh; the real temporary file has another name, and
7280 ;; it is created and protected by ssh. It is also
7281 ;; removed by ssh, when the connection is closed.
7282 (tmpfile
7283 (tramp-set-connection-property
7284 p "temp-file"
7285 (make-temp-name
7286 (expand-file-name
7287 tramp-temp-name-prefix
7288 (tramp-compat-temporary-file-directory)))))
7289 spec)
7291 ;; Add gateway arguments if necessary.
7292 (when (and gw gw-args)
7293 (setq login-args (append login-args gw-args)))
7295 ;; Check for port number. Until now, there's no need
7296 ;; for handling like method, user, host.
7297 (when (string-match tramp-host-with-port-regexp l-host)
7298 (setq l-port (match-string 2 l-host)
7299 l-host (match-string 1 l-host)))
7301 ;; Set variables for computing the prompt for reading
7302 ;; password. They can also be derived from a gateway.
7303 (setq tramp-current-method (or g-method l-method)
7304 tramp-current-user (or g-user l-user)
7305 tramp-current-host (or g-host l-host))
7307 ;; Replace login-args place holders.
7308 (setq
7309 l-host (or l-host "")
7310 l-user (or l-user "")
7311 l-port (or l-port "")
7312 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
7313 (?t . ,tmpfile))
7314 command
7315 (concat
7316 ;; We do not want to see the trailing local prompt in
7317 ;; `start-file-process'.
7318 (unless (memq system-type '(windows-nt)) "exec ")
7319 command " "
7320 (mapconcat
7321 (lambda (x)
7322 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7323 (unless (member "" x) (mapconcat 'identity x " ")))
7324 login-args " ")
7325 ;; Local shell could be a Windows COMSPEC. It doesn't
7326 ;; know the ";" syntax, but we must exit always for
7327 ;; `start-file-process'. "exec" does not work either.
7328 (if (memq system-type '(windows-nt)) " && exit || exit")))
7330 ;; Send the command.
7331 (tramp-message vec 3 "Sending command `%s'" command)
7332 (tramp-send-command vec command t t)
7333 (tramp-process-actions p vec tramp-actions-before-shell 60)
7334 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
7335 ;; Next hop.
7336 (setq target-alist (cdr target-alist)))
7338 ;; Make initial shell settings.
7339 (tramp-open-connection-setup-interactive-shell p vec))))))
7341 (defun tramp-send-command (vec command &optional neveropen nooutput)
7342 "Send the COMMAND to connection VEC.
7343 Erases temporary buffer before sending the command. If optional
7344 arg NEVEROPEN is non-nil, never try to open the connection. This
7345 is meant to be used from `tramp-maybe-open-connection' only. The
7346 function waits for output unless NOOUTPUT is set."
7347 (unless neveropen (tramp-maybe-open-connection vec))
7348 (let ((p (tramp-get-connection-process vec)))
7349 (when (tramp-get-connection-property p "remote-echo" nil)
7350 ;; We mark the command string that it can be erased in the output buffer.
7351 (tramp-set-connection-property p "check-remote-echo" t)
7352 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7353 (tramp-message vec 6 "%s" command)
7354 (tramp-send-string vec command)
7355 (unless nooutput (tramp-wait-for-output p))))
7357 (defun tramp-wait-for-output (proc &optional timeout)
7358 "Wait for output from remote command."
7359 (unless (buffer-live-p (process-buffer proc))
7360 (delete-process proc)
7361 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7362 (with-current-buffer (process-buffer proc)
7363 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7364 ;; be leading escape sequences, which must be ignored.
7365 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7366 ;; Sometimes, the commands do not return a newline but a
7367 ;; null byte before the shell prompt, for example "git
7368 ;; ls-files -c -z ...".
7369 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7370 (found (tramp-wait-for-regexp proc timeout regexp1)))
7371 (if found
7372 (let (buffer-read-only)
7373 ;; A simple-minded busybox has sent " ^H" sequences.
7374 ;; Delete them.
7375 (goto-char (point-min))
7376 (when (re-search-forward
7377 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7378 (forward-line 1)
7379 (delete-region (point-min) (point)))
7380 ;; Delete the prompt.
7381 (goto-char (point-max))
7382 (re-search-backward regexp nil t)
7383 (delete-region (point) (point-max)))
7384 (if timeout
7385 (tramp-error
7386 proc 'file-error
7387 "[[Remote prompt `%s' not found in %d secs]]"
7388 tramp-end-of-output timeout)
7389 (tramp-error
7390 proc 'file-error
7391 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7392 ;; Return value is whether end-of-output sentinel was found.
7393 found)))
7395 (defun tramp-send-command-and-check
7396 (vec command &optional subshell dont-suppress-err)
7397 "Run COMMAND and check its exit status.
7398 Sends `echo $?' along with the COMMAND for checking the exit status. If
7399 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7401 If the optional argument SUBSHELL is non-nil, the command is
7402 executed in a subshell, ie surrounded by parentheses. If
7403 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7404 (tramp-send-command
7406 (concat (if subshell "( " "")
7407 command
7408 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7409 "echo tramp_exit_status $?"
7410 (if subshell " )" "")))
7411 (with-current-buffer (tramp-get-connection-buffer vec)
7412 (goto-char (point-max))
7413 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7414 (tramp-error
7415 vec 'file-error "Couldn't find exit status of `%s'" command))
7416 (skip-chars-forward "^ ")
7417 (prog1
7418 (read (current-buffer))
7419 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7421 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7422 "Run COMMAND, check exit status, throw error if exit status not okay.
7423 Similar to `tramp-send-command-and-check' but accepts two more arguments
7424 FMT and ARGS which are passed to `error'."
7425 (unless (zerop (tramp-send-command-and-check vec command))
7426 (apply 'tramp-error vec 'file-error fmt args)))
7428 (defun tramp-send-command-and-read (vec command)
7429 "Run COMMAND and return the output, which must be a Lisp expression.
7430 In case there is no valid Lisp expression, it raises an error"
7431 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7432 (with-current-buffer (tramp-get-connection-buffer vec)
7433 ;; Read the expression.
7434 (goto-char (point-min))
7435 (condition-case nil
7436 (prog1 (read (current-buffer))
7437 ;; Error handling.
7438 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7439 (error nil)))
7440 (error (tramp-error
7441 vec 'file-error
7442 "`%s' does not return a valid Lisp expression: `%s'"
7443 command (buffer-string))))))
7445 ;; It seems that Tru64 Unix does not like it if long strings are sent
7446 ;; to it in one go. (This happens when sending the Perl
7447 ;; `file-attributes' implementation, for instance.) Therefore, we
7448 ;; have this function which sends the string in chunks.
7449 (defun tramp-send-string (vec string)
7450 "Send the STRING via connection VEC.
7452 The STRING is expected to use Unix line-endings, but the lines sent to
7453 the remote host use line-endings as defined in the variable
7454 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7455 (let* ((p (tramp-get-connection-process vec))
7456 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7457 (unless p
7458 (tramp-error
7459 vec 'file-error "Can't send string to remote host -- not logged in"))
7460 (tramp-set-connection-property p "last-cmd-time" (current-time))
7461 (tramp-message vec 10 "%s" string)
7462 (with-current-buffer (tramp-get-connection-buffer vec)
7463 ;; Clean up the buffer. We cannot call `erase-buffer' because
7464 ;; narrowing might be in effect.
7465 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7466 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7467 (setq string
7468 (mapconcat 'identity
7469 (tramp-compat-split-string string "\n")
7470 tramp-rsh-end-of-line))
7471 (unless (or (string= string "")
7472 (string-equal (substring string -1) tramp-rsh-end-of-line))
7473 (setq string (concat string tramp-rsh-end-of-line)))
7474 ;; Send the string.
7475 (if (and chunksize (not (zerop chunksize)))
7476 (let ((pos 0)
7477 (end (length string)))
7478 (while (< pos end)
7479 (tramp-message
7480 vec 10 "Sending chunk from %s to %s"
7481 pos (min (+ pos chunksize) end))
7482 (process-send-string
7483 p (substring string pos (min (+ pos chunksize) end)))
7484 (setq pos (+ pos chunksize))))
7485 (process-send-string p string)))))
7487 (defun tramp-mode-string-to-int (mode-string)
7488 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7489 (let* (case-fold-search
7490 (mode-chars (string-to-vector mode-string))
7491 (owner-read (aref mode-chars 1))
7492 (owner-write (aref mode-chars 2))
7493 (owner-execute-or-setid (aref mode-chars 3))
7494 (group-read (aref mode-chars 4))
7495 (group-write (aref mode-chars 5))
7496 (group-execute-or-setid (aref mode-chars 6))
7497 (other-read (aref mode-chars 7))
7498 (other-write (aref mode-chars 8))
7499 (other-execute-or-sticky (aref mode-chars 9)))
7500 (save-match-data
7501 (logior
7502 (cond
7503 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7504 ((char-equal owner-read ?-) 0)
7505 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7506 (cond
7507 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7508 ((char-equal owner-write ?-) 0)
7509 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7510 (cond
7511 ((char-equal owner-execute-or-setid ?x)
7512 (tramp-octal-to-decimal "00100"))
7513 ((char-equal owner-execute-or-setid ?S)
7514 (tramp-octal-to-decimal "04000"))
7515 ((char-equal owner-execute-or-setid ?s)
7516 (tramp-octal-to-decimal "04100"))
7517 ((char-equal owner-execute-or-setid ?-) 0)
7518 (t (error "Fourth char `%c' must be one of `xsS-'"
7519 owner-execute-or-setid)))
7520 (cond
7521 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7522 ((char-equal group-read ?-) 0)
7523 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7524 (cond
7525 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7526 ((char-equal group-write ?-) 0)
7527 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7528 (cond
7529 ((char-equal group-execute-or-setid ?x)
7530 (tramp-octal-to-decimal "00010"))
7531 ((char-equal group-execute-or-setid ?S)
7532 (tramp-octal-to-decimal "02000"))
7533 ((char-equal group-execute-or-setid ?s)
7534 (tramp-octal-to-decimal "02010"))
7535 ((char-equal group-execute-or-setid ?-) 0)
7536 (t (error "Seventh char `%c' must be one of `xsS-'"
7537 group-execute-or-setid)))
7538 (cond
7539 ((char-equal other-read ?r)
7540 (tramp-octal-to-decimal "00004"))
7541 ((char-equal other-read ?-) 0)
7542 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7543 (cond
7544 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7545 ((char-equal other-write ?-) 0)
7546 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7547 (cond
7548 ((char-equal other-execute-or-sticky ?x)
7549 (tramp-octal-to-decimal "00001"))
7550 ((char-equal other-execute-or-sticky ?T)
7551 (tramp-octal-to-decimal "01000"))
7552 ((char-equal other-execute-or-sticky ?t)
7553 (tramp-octal-to-decimal "01001"))
7554 ((char-equal other-execute-or-sticky ?-) 0)
7555 (t (error "Tenth char `%c' must be one of `xtT-'"
7556 other-execute-or-sticky)))))))
7558 (defun tramp-convert-file-attributes (vec attr)
7559 "Convert file-attributes ATTR generated by perl script, stat or ls.
7560 Convert file mode bits to string and set virtual device number.
7561 Return ATTR."
7562 (when attr
7563 ;; Convert last access time.
7564 (unless (listp (nth 4 attr))
7565 (setcar (nthcdr 4 attr)
7566 (list (floor (nth 4 attr) 65536)
7567 (floor (mod (nth 4 attr) 65536)))))
7568 ;; Convert last modification time.
7569 (unless (listp (nth 5 attr))
7570 (setcar (nthcdr 5 attr)
7571 (list (floor (nth 5 attr) 65536)
7572 (floor (mod (nth 5 attr) 65536)))))
7573 ;; Convert last status change time.
7574 (unless (listp (nth 6 attr))
7575 (setcar (nthcdr 6 attr)
7576 (list (floor (nth 6 attr) 65536)
7577 (floor (mod (nth 6 attr) 65536)))))
7578 ;; Convert file size.
7579 (when (< (nth 7 attr) 0)
7580 (setcar (nthcdr 7 attr) -1))
7581 (when (and (floatp (nth 7 attr))
7582 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7583 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7584 ;; Convert file mode bits to string.
7585 (unless (stringp (nth 8 attr))
7586 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7587 (when (stringp (car attr))
7588 (aset (nth 8 attr) 0 ?l)))
7589 ;; Convert directory indication bit.
7590 (when (string-match "^d" (nth 8 attr))
7591 (setcar attr t))
7592 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7593 (when (consp (car attr))
7594 (if (and (stringp (caar attr))
7595 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7596 (setcar attr (match-string 1 (caar attr)))
7597 (setcar attr nil)))
7598 ;; Set file's gid change bit.
7599 (setcar (nthcdr 9 attr)
7600 (if (numberp (nth 3 attr))
7601 (not (= (nth 3 attr)
7602 (tramp-get-remote-gid vec 'integer)))
7603 (not (string-equal
7604 (nth 3 attr)
7605 (tramp-get-remote-gid vec 'string)))))
7606 ;; Convert inode.
7607 (unless (listp (nth 10 attr))
7608 (setcar (nthcdr 10 attr)
7609 (condition-case nil
7610 (cons (floor (nth 10 attr) 65536)
7611 (floor (mod (nth 10 attr) 65536)))
7612 ;; Inodes can be incredible huge. We must hide this.
7613 (error (tramp-get-inode vec)))))
7614 ;; Set virtual device number.
7615 (setcar (nthcdr 11 attr)
7616 (tramp-get-device vec))
7617 attr))
7619 (defun tramp-check-cached-permissions (vec access)
7620 "Check `file-attributes' caches for VEC.
7621 Return t if according to the cache access type ACCESS is known to
7622 be granted."
7623 (let ((result nil)
7624 (offset (cond
7625 ((eq ?r access) 1)
7626 ((eq ?w access) 2)
7627 ((eq ?x access) 3))))
7628 (dolist (suffix '("string" "integer") result)
7629 (setq
7630 result
7632 result
7633 (let ((file-attr
7634 (tramp-get-file-property
7635 vec (tramp-file-name-localname vec)
7636 (concat "file-attributes-" suffix) nil))
7637 (remote-uid
7638 (tramp-get-connection-property
7639 vec (concat "uid-" suffix) nil))
7640 (remote-gid
7641 (tramp-get-connection-property
7642 vec (concat "gid-" suffix) nil)))
7643 (and
7644 file-attr
7646 ;; Not a symlink
7647 (eq t (car file-attr))
7648 (null (car file-attr)))
7650 ;; World accessible.
7651 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7652 ;; User accessible and owned by user.
7653 (and
7654 (eq access (aref (nth 8 file-attr) offset))
7655 (equal remote-uid (nth 2 file-attr)))
7656 ;; Group accessible and owned by user's
7657 ;; principal group.
7658 (and
7659 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7660 (equal remote-gid (nth 3 file-attr)))))))))))
7662 (defun tramp-get-inode (vec)
7663 "Returns the virtual inode number.
7664 If it doesn't exist, generate a new one."
7665 (let ((string (tramp-make-tramp-file-name
7666 (tramp-file-name-method vec)
7667 (tramp-file-name-user vec)
7668 (tramp-file-name-host vec)
7669 "")))
7670 (unless (assoc string tramp-inodes)
7671 (add-to-list 'tramp-inodes
7672 (list string (length tramp-inodes))))
7673 (nth 1 (assoc string tramp-inodes))))
7675 (defun tramp-get-device (vec)
7676 "Returns the virtual device number.
7677 If it doesn't exist, generate a new one."
7678 (let ((string (tramp-make-tramp-file-name
7679 (tramp-file-name-method vec)
7680 (tramp-file-name-user vec)
7681 (tramp-file-name-host vec)
7682 "")))
7683 (unless (assoc string tramp-devices)
7684 (add-to-list 'tramp-devices
7685 (list string (length tramp-devices))))
7686 (cons -1 (nth 1 (assoc string tramp-devices)))))
7688 (defun tramp-file-mode-from-int (mode)
7689 "Turn an integer representing a file mode into an ls(1)-like string."
7690 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7691 (user (logand (lsh mode -6) 7))
7692 (group (logand (lsh mode -3) 7))
7693 (other (logand (lsh mode -0) 7))
7694 (suid (> (logand (lsh mode -9) 4) 0))
7695 (sgid (> (logand (lsh mode -9) 2) 0))
7696 (sticky (> (logand (lsh mode -9) 1) 0)))
7697 (setq user (tramp-file-mode-permissions user suid "s"))
7698 (setq group (tramp-file-mode-permissions group sgid "s"))
7699 (setq other (tramp-file-mode-permissions other sticky "t"))
7700 (concat type user group other)))
7702 (defun tramp-file-mode-permissions (perm suid suid-text)
7703 "Convert a permission bitset into a string.
7704 This is used internally by `tramp-file-mode-from-int'."
7705 (let ((r (> (logand perm 4) 0))
7706 (w (> (logand perm 2) 0))
7707 (x (> (logand perm 1) 0)))
7708 (concat (or (and r "r") "-")
7709 (or (and w "w") "-")
7710 (or (and suid x suid-text) ; suid, execute
7711 (and suid (upcase suid-text)) ; suid, !execute
7712 (and x "x") "-")))) ; !suid
7714 (defun tramp-decimal-to-octal (i)
7715 "Return a string consisting of the octal digits of I.
7716 Not actually used. Use `(format \"%o\" i)' instead?"
7717 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7718 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7719 ((zerop i) "0")
7720 (t (concat (tramp-decimal-to-octal (/ i 8))
7721 (number-to-string (% i 8))))))
7723 ;; Kudos to Gerd Moellmann for this suggestion.
7724 (defun tramp-octal-to-decimal (ostr)
7725 "Given a string of octal digits, return a decimal number."
7726 (let ((x (or ostr "")))
7727 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7728 (unless (string-match "\\`[0-7]*\\'" x)
7729 (error "Non-octal junk in string `%s'" x))
7730 (string-to-number ostr 8)))
7732 (defun tramp-shell-case-fold (string)
7733 "Converts STRING to shell glob pattern which ignores case."
7734 (mapconcat
7735 (lambda (c)
7736 (if (equal (downcase c) (upcase c))
7737 (vector c)
7738 (format "[%c%c]" (downcase c) (upcase c))))
7739 string
7740 ""))
7743 ;; ------------------------------------------------------------
7744 ;; -- Tramp file names --
7745 ;; ------------------------------------------------------------
7746 ;; Conversion functions between external representation and
7747 ;; internal data structure. Convenience functions for internal
7748 ;; data structure.
7750 (defun tramp-file-name-p (vec)
7751 "Check whether VEC is a Tramp object."
7752 (and (vectorp vec) (= 4 (length vec))))
7754 (defun tramp-file-name-method (vec)
7755 "Return method component of VEC."
7756 (and (tramp-file-name-p vec) (aref vec 0)))
7758 (defun tramp-file-name-user (vec)
7759 "Return user component of VEC."
7760 (and (tramp-file-name-p vec) (aref vec 1)))
7762 (defun tramp-file-name-host (vec)
7763 "Return host component of VEC."
7764 (and (tramp-file-name-p vec) (aref vec 2)))
7766 (defun tramp-file-name-localname (vec)
7767 "Return localname component of VEC."
7768 (and (tramp-file-name-p vec) (aref vec 3)))
7770 ;; The user part of a Tramp file name vector can be of kind
7771 ;; "user%domain". Sometimes, we must extract these parts.
7772 (defun tramp-file-name-real-user (vec)
7773 "Return the user name of VEC without domain."
7774 (save-match-data
7775 (let ((user (tramp-file-name-user vec)))
7776 (if (and (stringp user)
7777 (string-match tramp-user-with-domain-regexp user))
7778 (match-string 1 user)
7779 user))))
7781 (defun tramp-file-name-domain (vec)
7782 "Return the domain name of VEC."
7783 (save-match-data
7784 (let ((user (tramp-file-name-user vec)))
7785 (and (stringp user)
7786 (string-match tramp-user-with-domain-regexp user)
7787 (match-string 2 user)))))
7789 ;; The host part of a Tramp file name vector can be of kind
7790 ;; "host#port". Sometimes, we must extract these parts.
7791 (defun tramp-file-name-real-host (vec)
7792 "Return the host name of VEC without port."
7793 (save-match-data
7794 (let ((host (tramp-file-name-host vec)))
7795 (if (and (stringp host)
7796 (string-match tramp-host-with-port-regexp host))
7797 (match-string 1 host)
7798 host))))
7800 (defun tramp-file-name-port (vec)
7801 "Return the port number of VEC."
7802 (save-match-data
7803 (let ((host (tramp-file-name-host vec)))
7804 (and (stringp host)
7805 (string-match tramp-host-with-port-regexp host)
7806 (string-to-number (match-string 2 host))))))
7808 (defun tramp-tramp-file-p (name)
7809 "Return t if NAME is a string with Tramp file name syntax."
7810 (save-match-data
7811 (and (stringp name) (string-match tramp-file-name-regexp name))))
7813 (defun tramp-find-method (method user host)
7814 "Return the right method string to use.
7815 This is METHOD, if non-nil. Otherwise, do a lookup in
7816 `tramp-default-method-alist'."
7817 (or method
7818 (let ((choices tramp-default-method-alist)
7819 lmethod item)
7820 (while choices
7821 (setq item (pop choices))
7822 (when (and (string-match (or (nth 0 item) "") (or host ""))
7823 (string-match (or (nth 1 item) "") (or user "")))
7824 (setq lmethod (nth 2 item))
7825 (setq choices nil)))
7826 lmethod)
7827 tramp-default-method))
7829 (defun tramp-find-user (method user host)
7830 "Return the right user string to use.
7831 This is USER, if non-nil. Otherwise, do a lookup in
7832 `tramp-default-user-alist'."
7833 (or user
7834 (let ((choices tramp-default-user-alist)
7835 luser item)
7836 (while choices
7837 (setq item (pop choices))
7838 (when (and (string-match (or (nth 0 item) "") (or method ""))
7839 (string-match (or (nth 1 item) "") (or host "")))
7840 (setq luser (nth 2 item))
7841 (setq choices nil)))
7842 luser)
7843 tramp-default-user))
7845 (defun tramp-find-host (method user host)
7846 "Return the right host string to use.
7847 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7848 (or (and (> (length host) 0) host)
7849 tramp-default-host))
7851 (defun tramp-dissect-file-name (name &optional nodefault)
7852 "Return a `tramp-file-name' structure.
7853 The structure consists of remote method, remote user, remote host
7854 and localname (file name on remote host). If NODEFAULT is
7855 non-nil, the file name parts are not expanded to their default
7856 values."
7857 (save-match-data
7858 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
7859 (unless match (error "Not a Tramp file name: %s" name))
7860 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7861 (user (match-string (nth 2 tramp-file-name-structure) name))
7862 (host (match-string (nth 3 tramp-file-name-structure) name))
7863 (localname (match-string (nth 4 tramp-file-name-structure) name)))
7864 (when (member method '("multi" "multiu"))
7865 (error
7866 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7867 method))
7868 (when host
7869 (when (string-match tramp-prefix-ipv6-regexp host)
7870 (setq host (replace-match "" nil t host)))
7871 (when (string-match tramp-postfix-ipv6-regexp host)
7872 (setq host (replace-match "" nil t host))))
7873 (if nodefault
7874 (vector method user host localname)
7875 (vector
7876 (tramp-find-method method user host)
7877 (tramp-find-user method user host)
7878 (tramp-find-host method user host)
7879 localname))))))
7881 (defun tramp-equal-remote (file1 file2)
7882 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7883 The check depends on method, user and host name of the files. If
7884 one of the components is missing, the default values are used.
7885 The local file name parts of FILE1 and FILE2 are not taken into
7886 account.
7888 Example:
7890 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7892 would yield `t'. On the other hand, the following check results in nil:
7894 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
7895 (and (stringp (file-remote-p file1))
7896 (stringp (file-remote-p file2))
7897 (string-equal (file-remote-p file1) (file-remote-p file2))))
7899 (defun tramp-make-tramp-file-name (method user host localname)
7900 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7901 (concat tramp-prefix-format
7902 (when (not (zerop (length method)))
7903 (concat method tramp-postfix-method-format))
7904 (when (not (zerop (length user)))
7905 (concat user tramp-postfix-user-format))
7906 (when host
7907 (if (string-match tramp-ipv6-regexp host)
7908 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7909 host))
7910 tramp-postfix-host-format
7911 (when localname localname)))
7913 (defun tramp-completion-make-tramp-file-name (method user host localname)
7914 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7915 It must not be a complete Tramp file name, but as long as there are
7916 necessary only. This function will be used in file name completion."
7917 (concat tramp-prefix-format
7918 (when (not (zerop (length method)))
7919 (concat method tramp-postfix-method-format))
7920 (when (not (zerop (length user)))
7921 (concat user tramp-postfix-user-format))
7922 (when (not (zerop (length host)))
7923 (concat
7924 (if (string-match tramp-ipv6-regexp host)
7925 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7926 host)
7927 tramp-postfix-host-format))
7928 (when localname localname)))
7930 (defun tramp-make-copy-program-file-name (vec)
7931 "Create a file name suitable to be passed to `rcp' and workalikes."
7932 (let ((user (tramp-file-name-user vec))
7933 (host (tramp-file-name-real-host vec))
7934 (localname (tramp-shell-quote-argument
7935 (tramp-file-name-localname vec))))
7936 (if (not (zerop (length user)))
7937 (format "%s@%s:%s" user host localname)
7938 (format "%s:%s" host localname))))
7940 (defun tramp-method-out-of-band-p (vec size)
7941 "Return t if this is an out-of-band method, nil otherwise."
7942 (and
7943 ;; It shall be an out-of-band method.
7944 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7945 ;; Either the file size is large enough, or (in rare cases) there
7946 ;; does not exist a remote encoding.
7947 (or (> size tramp-copy-size-limit)
7948 (null (tramp-get-remote-coding vec "remote-encoding")))))
7950 (defun tramp-local-host-p (vec)
7951 "Return t if this points to the local host, nil otherwise."
7952 ;; We cannot use `tramp-file-name-real-host'. A port is an
7953 ;; indication for an ssh tunnel or alike.
7954 (let ((host (tramp-file-name-host vec)))
7955 (and
7956 (stringp host)
7957 (string-match tramp-local-host-regexp host)
7958 ;; The method shall be applied to one of the shell file name
7959 ;; handler. `tramp-local-host-p' is also called for "smb" and
7960 ;; alike, where it must fail.
7961 (tramp-get-method-parameter
7962 (tramp-file-name-method vec) 'tramp-login-program)
7963 ;; The local temp directory must be writable for the other user.
7964 (file-writable-p
7965 (tramp-make-tramp-file-name
7966 (tramp-file-name-method vec)
7967 (tramp-file-name-user vec)
7968 host
7969 (tramp-compat-temporary-file-directory)))
7970 ;; On some systems, chown runs only for root.
7971 (or (zerop (user-uid))
7972 (zerop (tramp-get-remote-uid vec 'integer))))))
7974 ;; Variables local to connection.
7976 (defun tramp-get-remote-path (vec)
7977 (with-connection-property
7978 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
7979 ;; cache the result for the session only. Otherwise, the result
7980 ;; is cached persistently.
7981 (if (memq 'tramp-own-remote-path tramp-remote-path)
7982 (tramp-get-connection-process vec)
7983 vec)
7984 "remote-path"
7985 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
7986 (elt1 (memq 'tramp-default-remote-path remote-path))
7987 (elt2 (memq 'tramp-own-remote-path remote-path))
7988 (default-remote-path
7989 (when elt1
7990 (condition-case nil
7991 (tramp-send-command-and-read
7992 vec "echo \\\"`getconf PATH`\\\"")
7993 ;; Default if "getconf" is not available.
7994 (error
7995 (tramp-message
7996 vec 3
7997 "`getconf PATH' not successful, using default value \"%s\"."
7998 "/bin:/usr/bin")
7999 "/bin:/usr/bin"))))
8000 (own-remote-path
8001 (when elt2
8002 (condition-case nil
8003 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8004 ;; Default if "getconf" is not available.
8005 (error
8006 (tramp-message
8007 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8008 nil)))))
8010 ;; Replace place holder `tramp-default-remote-path'.
8011 (when elt1
8012 (setcdr elt1
8013 (append
8014 (tramp-compat-split-string default-remote-path ":")
8015 (cdr elt1)))
8016 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8018 ;; Replace place holder `tramp-own-remote-path'.
8019 (when elt2
8020 (setcdr elt2
8021 (append
8022 (tramp-compat-split-string own-remote-path ":")
8023 (cdr elt2)))
8024 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8026 ;; Remove double entries.
8027 (setq elt1 remote-path)
8028 (while (consp elt1)
8029 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8030 (setcar elt2 nil))
8031 (setq elt1 (cdr elt1)))
8033 ;; Remove non-existing directories.
8034 (delq
8036 (mapcar
8037 (lambda (x)
8038 (and
8039 (stringp x)
8040 (file-directory-p
8041 (tramp-make-tramp-file-name
8042 (tramp-file-name-method vec)
8043 (tramp-file-name-user vec)
8044 (tramp-file-name-host vec)
8047 remote-path)))))
8049 (defun tramp-get-remote-tmpdir (vec)
8050 (with-connection-property vec "tmp-directory"
8051 (let ((dir (tramp-shell-quote-argument "/tmp")))
8052 (if (and (zerop
8053 (tramp-send-command-and-check
8054 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8055 (zerop
8056 (tramp-send-command-and-check
8057 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8059 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8061 (defun tramp-get-ls-command (vec)
8062 (with-connection-property vec "ls"
8063 (tramp-message vec 5 "Finding a suitable `ls' command")
8065 (catch 'ls-found
8066 (dolist (cmd '("ls" "gnuls" "gls"))
8067 (let ((dl (tramp-get-remote-path vec))
8068 result)
8069 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8070 ;; Check parameters. On busybox, "ls" output coloring is
8071 ;; enabled by default sometimes. So we try to disable it
8072 ;; when possible. $LS_COLORING is not supported there.
8073 (when (zerop (tramp-send-command-and-check
8074 vec (format "%s -lnd /" result)))
8075 (when (zerop (tramp-send-command-and-check
8076 vec (format "%s --color=never /" result)))
8077 (setq result (concat result " --color=never")))
8078 (throw 'ls-found result))
8079 (setq dl (cdr dl))))))
8080 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8082 (defun tramp-get-ls-command-with-dired (vec)
8083 (save-match-data
8084 (with-connection-property vec "ls-dired"
8085 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8086 (zerop (tramp-send-command-and-check
8087 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8089 (defun tramp-get-test-command (vec)
8090 (with-connection-property vec "test"
8091 (tramp-message vec 5 "Finding a suitable `test' command")
8092 (if (zerop (tramp-send-command-and-check vec "test 0"))
8093 "test"
8094 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8096 (defun tramp-get-test-nt-command (vec)
8097 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8098 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8099 ;; for otherwise the shell crashes.
8100 (with-connection-property vec "test-nt"
8102 (progn
8103 (tramp-send-command
8104 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8105 (with-current-buffer (tramp-get-buffer vec)
8106 (goto-char (point-min))
8107 (when (looking-at (regexp-quote tramp-end-of-output))
8108 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8109 (progn
8110 (tramp-send-command
8112 (format
8113 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8114 (tramp-get-test-command vec)))
8115 "tramp_test_nt %s %s"))))
8117 (defun tramp-get-file-exists-command (vec)
8118 (with-connection-property vec "file-exists"
8119 (tramp-message vec 5 "Finding command to check if file exists")
8120 (tramp-find-file-exists-command vec)))
8122 (defun tramp-get-remote-ln (vec)
8123 (with-connection-property vec "ln"
8124 (tramp-message vec 5 "Finding a suitable `ln' command")
8125 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8127 (defun tramp-get-remote-perl (vec)
8128 (with-connection-property vec "perl"
8129 (tramp-message vec 5 "Finding a suitable `perl' command")
8130 (let ((result
8131 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8132 (tramp-find-executable
8133 vec "perl" (tramp-get-remote-path vec)))))
8134 ;; We must check also for some Perl modules.
8135 (when result
8136 (with-connection-property vec "perl-file-spec"
8137 (zerop
8138 (tramp-send-command-and-check
8139 vec (format "%s -e 'use File::Spec;'" result))))
8140 (with-connection-property vec "perl-cwd-realpath"
8141 (zerop
8142 (tramp-send-command-and-check
8143 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8144 result)))
8146 (defun tramp-get-remote-stat (vec)
8147 (with-connection-property vec "stat"
8148 (tramp-message vec 5 "Finding a suitable `stat' command")
8149 (let ((result (tramp-find-executable
8150 vec "stat" (tramp-get-remote-path vec)))
8151 tmp)
8152 ;; Check whether stat(1) returns usable syntax. %s does not
8153 ;; work on older AIX systems.
8154 (when result
8155 (setq tmp
8156 ;; We don't want to display an error message.
8157 (with-temp-message (or (current-message) "")
8158 (condition-case nil
8159 (tramp-send-command-and-read
8160 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8161 (error nil))))
8162 (unless (and (listp tmp) (stringp (car tmp))
8163 (string-match "^./.$" (car tmp))
8164 (integerp (cadr tmp)))
8165 (setq result nil)))
8166 result)))
8168 (defun tramp-get-remote-readlink (vec)
8169 (with-connection-property vec "readlink"
8170 (tramp-message vec 5 "Finding a suitable `readlink' command")
8171 (let ((result (tramp-find-executable
8172 vec "readlink" (tramp-get-remote-path vec))))
8173 (when (and result
8174 ;; We don't want to display an error message.
8175 (with-temp-message (or (current-message) "")
8176 (condition-case nil
8177 (zerop
8178 (tramp-send-command-and-check
8179 vec (format "%s --canonicalize-missing /" result)))
8180 (error nil))))
8181 result))))
8183 (defun tramp-get-remote-id (vec)
8184 (with-connection-property vec "id"
8185 (tramp-message vec 5 "Finding POSIX `id' command")
8187 (catch 'id-found
8188 (let ((dl (tramp-get-remote-path vec))
8189 result)
8190 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8191 ;; Check POSIX parameter.
8192 (when (zerop (tramp-send-command-and-check
8193 vec (format "%s -u" result)))
8194 (throw 'id-found result))
8195 (setq dl (cdr dl)))))
8196 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8198 (defun tramp-get-remote-uid (vec id-format)
8199 (with-connection-property vec (format "uid-%s" id-format)
8200 (let ((res (tramp-send-command-and-read
8202 (format "%s -u%s %s"
8203 (tramp-get-remote-id vec)
8204 (if (equal id-format 'integer) "" "n")
8205 (if (equal id-format 'integer)
8206 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8207 ;; The command might not always return a number.
8208 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8210 (defun tramp-get-remote-gid (vec id-format)
8211 (with-connection-property vec (format "gid-%s" id-format)
8212 (let ((res (tramp-send-command-and-read
8214 (format "%s -g%s %s"
8215 (tramp-get-remote-id vec)
8216 (if (equal id-format 'integer) "" "n")
8217 (if (equal id-format 'integer)
8218 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8219 ;; The command might not always return a number.
8220 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8222 (defun tramp-get-local-uid (id-format)
8223 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8225 (defun tramp-get-local-gid (id-format)
8226 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8228 ;; Some predefined connection properties.
8229 (defun tramp-get-remote-coding (vec prop)
8230 ;; Local coding handles properties like remote coding. So we could
8231 ;; call it without pain.
8232 (let ((ret (tramp-get-local-coding vec prop)))
8233 ;; The connection property might have been cached. So we must send
8234 ;; the script - maybe.
8235 (when (and ret (symbolp ret))
8236 (let ((name (symbol-name ret)))
8237 (while (string-match (regexp-quote "-") name)
8238 (setq name (replace-match "_" nil t name)))
8239 (tramp-maybe-send-script vec (symbol-value ret) name)
8240 (setq ret name)))
8241 ;; Return the value.
8242 ret))
8244 (defun tramp-get-local-coding (vec prop)
8246 (tramp-get-connection-property vec prop nil)
8247 (progn
8248 (tramp-find-inline-encoding vec)
8249 (tramp-get-connection-property vec prop nil))))
8251 (defun tramp-get-method-parameter (method param)
8252 "Return the method parameter PARAM.
8253 If the `tramp-methods' entry does not exist, return NIL."
8254 (let ((entry (assoc param (assoc method tramp-methods))))
8255 (when entry (cadr entry))))
8257 ;; Auto saving to a special directory.
8259 (defun tramp-exists-file-name-handler (operation &rest args)
8260 "Checks whether OPERATION runs a file name handler."
8261 ;; The file name handler is determined on base of either an
8262 ;; argument, `buffer-file-name', or `default-directory'.
8263 (condition-case nil
8264 (let* ((buffer-file-name "/")
8265 (default-directory "/")
8266 (fnha file-name-handler-alist)
8267 (check-file-name-operation operation)
8268 (file-name-handler-alist
8269 (list
8270 (cons "/"
8271 (lambda (operation &rest args)
8272 "Returns OPERATION if it is the one to be checked."
8273 (if (equal check-file-name-operation operation)
8274 operation
8275 (let ((file-name-handler-alist fnha))
8276 (apply operation args))))))))
8277 (equal (apply operation args) operation))
8278 (error nil)))
8280 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8281 (defadvice make-auto-save-file-name
8282 (around tramp-advice-make-auto-save-file-name () activate)
8283 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8284 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
8285 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8286 ;; directly, because this would bypass the locking mechanism.
8287 (setq ad-return-value
8288 (tramp-file-name-handler 'make-auto-save-file-name))
8289 ad-do-it))
8290 (add-hook
8291 'tramp-unload-hook
8292 (lambda ()
8293 (ad-remove-advice
8294 'make-auto-save-file-name
8295 'around 'tramp-advice-make-auto-save-file-name)
8296 (ad-activate 'make-auto-save-file-name))))
8298 ;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
8299 ;; permission 0666 minus umask. This is a security threat.
8301 (defun tramp-set-auto-save-file-modes ()
8302 "Set permissions of autosaved remote files to the original permissions."
8303 (let ((bfn (buffer-file-name)))
8304 (when (and (stringp bfn)
8305 (tramp-tramp-file-p bfn)
8306 (buffer-modified-p)
8307 (stringp buffer-auto-save-file-name)
8308 (not (equal bfn buffer-auto-save-file-name)))
8309 (unless (file-exists-p buffer-auto-save-file-name)
8310 (write-region "" nil buffer-auto-save-file-name))
8311 ;; Permissions should be set always, because there might be an old
8312 ;; auto-saved file belonging to another original file. This could
8313 ;; be a security threat.
8314 (set-file-modes buffer-auto-save-file-name
8315 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8317 (unless (or (> emacs-major-version 21)
8318 (and (featurep 'xemacs)
8319 (= emacs-major-version 21)
8320 (> emacs-minor-version 4)))
8321 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8322 (add-hook 'tramp-unload-hook
8323 (lambda ()
8324 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8326 (defun tramp-subst-strs-in-string (alist string)
8327 "Replace all occurrences of the string FROM with TO in STRING.
8328 ALIST is of the form ((FROM . TO) ...)."
8329 (save-match-data
8330 (while alist
8331 (let* ((pr (car alist))
8332 (from (car pr))
8333 (to (cdr pr)))
8334 (while (string-match (regexp-quote from) string)
8335 (setq string (replace-match to t t string)))
8336 (setq alist (cdr alist))))
8337 string))
8339 ;; ------------------------------------------------------------
8340 ;; -- Compatibility functions section --
8341 ;; ------------------------------------------------------------
8343 (defun tramp-read-passwd (proc &optional prompt)
8344 "Read a password from user (compat function).
8345 Consults the auth-source package.
8346 Invokes `password-read' if available, `read-passwd' else."
8347 (let* ((key (tramp-make-tramp-file-name
8348 tramp-current-method tramp-current-user
8349 tramp-current-host ""))
8350 (pw-prompt
8351 (or prompt
8352 (with-current-buffer (process-buffer proc)
8353 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8354 (format "%s for %s " (capitalize (match-string 1)) key)))))
8355 (with-parsed-tramp-file-name key nil
8356 (prog1
8358 ;; See if auth-sources contains something useful, if it's bound.
8359 (and (boundp 'auth-sources)
8360 (tramp-get-connection-property v "first-password-request" nil)
8361 ;; Try with Tramp's current method.
8362 (funcall (symbol-function 'auth-source-user-or-password)
8363 "password" tramp-current-host tramp-current-method))
8364 ;; Try the password cache.
8365 (when (functionp 'password-read)
8366 (unless (tramp-get-connection-property
8367 v "first-password-request" nil)
8368 (funcall (symbol-function 'password-cache-remove) key))
8369 (let ((password
8370 (funcall (symbol-function 'password-read) pw-prompt key)))
8371 (funcall (symbol-function 'password-cache-add) key password)
8372 password))
8373 ;; Else, get the password interactively.
8374 (read-passwd pw-prompt))
8375 (tramp-set-connection-property v "first-password-request" nil)))))
8377 (defun tramp-clear-passwd (vec)
8378 "Clear password cache for connection related to VEC."
8379 (when (functionp 'password-cache-remove)
8380 (funcall
8381 (symbol-function 'password-cache-remove)
8382 (tramp-make-tramp-file-name
8383 (tramp-file-name-method vec)
8384 (tramp-file-name-user vec)
8385 (tramp-file-name-host vec)
8386 ""))))
8388 ;; Snarfed code from time-date.el and parse-time.el
8390 (defconst tramp-half-a-year '(241 17024)
8391 "Evaluated by \"(days-to-time 183)\".")
8393 (defconst tramp-parse-time-months
8394 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8395 ("apr" . 4) ("may" . 5) ("jun" . 6)
8396 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8397 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8398 "Alist mapping month names to integers.")
8400 (defun tramp-time-less-p (t1 t2)
8401 "Say whether time value T1 is less than time value T2."
8402 (unless t1 (setq t1 '(0 0)))
8403 (unless t2 (setq t2 '(0 0)))
8404 (or (< (car t1) (car t2))
8405 (and (= (car t1) (car t2))
8406 (< (nth 1 t1) (nth 1 t2)))))
8408 (defun tramp-time-subtract (t1 t2)
8409 "Subtract two time values.
8410 Return the difference in the format of a time value."
8411 (unless t1 (setq t1 '(0 0)))
8412 (unless t2 (setq t2 '(0 0)))
8413 (let ((borrow (< (cadr t1) (cadr t2))))
8414 (list (- (car t1) (car t2) (if borrow 1 0))
8415 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8417 (defun tramp-time-diff (t1 t2)
8418 "Return the difference between the two times, in seconds.
8419 T1 and T2 are time values (as returned by `current-time' for example)."
8420 ;; Pacify byte-compiler with `symbol-function'.
8421 (cond ((and (fboundp 'subtract-time)
8422 (fboundp 'float-time))
8423 (funcall (symbol-function 'float-time)
8424 (funcall (symbol-function 'subtract-time) t1 t2)))
8425 ((and (fboundp 'subtract-time)
8426 (fboundp 'time-to-seconds))
8427 (funcall (symbol-function 'time-to-seconds)
8428 (funcall (symbol-function 'subtract-time) t1 t2)))
8429 ((fboundp 'itimer-time-difference)
8430 (funcall (symbol-function 'itimer-time-difference)
8431 (if (< (length t1) 3) (append t1 '(0)) t1)
8432 (if (< (length t2) 3) (append t2 '(0)) t2)))
8434 (let ((time (tramp-time-subtract t1 t2)))
8435 (+ (* (car time) 65536.0)
8436 (cadr time)
8437 (/ (or (nth 2 time) 0) 1000000.0))))))
8439 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8440 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8441 EOL-TYPE can be one of `dos', `unix', or `mac'."
8442 (cond ((fboundp 'coding-system-change-eol-conversion)
8443 (funcall (symbol-function 'coding-system-change-eol-conversion)
8444 coding-system eol-type))
8445 ((fboundp 'subsidiary-coding-system)
8446 (funcall (symbol-function 'subsidiary-coding-system)
8447 coding-system
8448 (cond ((eq eol-type 'dos) 'crlf)
8449 ((eq eol-type 'unix) 'lf)
8450 ((eq eol-type 'mac) 'cr)
8452 (error "Unknown EOL-TYPE `%s', must be %s"
8453 eol-type
8454 "`dos', `unix', or `mac'")))))
8455 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8457 (defun tramp-set-process-query-on-exit-flag (process flag)
8458 "Specify if query is needed for process when Emacs is exited.
8459 If the second argument flag is non-nil, Emacs will query the user before
8460 exiting if process is running."
8461 (if (fboundp 'set-process-query-on-exit-flag)
8462 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
8463 (funcall (symbol-function 'process-kill-without-query) process flag)))
8466 ;; ------------------------------------------------------------
8467 ;; -- Kludges section --
8468 ;; ------------------------------------------------------------
8470 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8471 ;; does not deal well with newline characters. Newline is replaced by
8472 ;; backslash newline. But if, say, the string `a backslash newline b'
8473 ;; is passed to a shell, the shell will expand this into "ab",
8474 ;; completely omitting the newline. This is not what was intended.
8475 ;; It does not appear to be possible to make the function
8476 ;; `shell-quote-argument' work with newlines without making it
8477 ;; dependent on the shell used. But within this package, we know that
8478 ;; we will always use a Bourne-like shell, so we use an approach which
8479 ;; groks newlines.
8481 ;; The approach is simple: we call `shell-quote-argument', then
8482 ;; massage the newline part of the result.
8484 ;; This function should produce a string which is grokked by a Unix
8485 ;; shell, even if the Emacs is running on Windows. Since this is the
8486 ;; kludges section, we bind `system-type' in such a way that
8487 ;; `shell-quote-arguments' behaves as if on Unix.
8489 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8490 ;; function to work with Bourne-like shells.
8492 ;; CCC: This function should be rewritten so that
8493 ;; `shell-quote-argument' is not used. This way, we are safe from
8494 ;; changes in `shell-quote-argument'.
8495 (defun tramp-shell-quote-argument (s)
8496 "Similar to `shell-quote-argument', but groks newlines.
8497 Only works for Bourne-like shells."
8498 (let ((system-type 'not-windows))
8499 (save-match-data
8500 (let ((result (shell-quote-argument s))
8501 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8502 (when (and (>= (length result) 2)
8503 (string= (substring result 0 2) "\\~"))
8504 (setq result (substring result 1)))
8505 (while (string-match nl result)
8506 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8507 t t result)))
8508 result))))
8510 ;; Checklist for `tramp-unload-hook'
8511 ;; - Unload all `tramp-*' packages
8512 ;; - Reset `file-name-handler-alist'
8513 ;; - Cleanup hooks where Tramp functions are in
8514 ;; - Cleanup advised functions
8515 ;; - Cleanup autoloads
8516 ;;;###autoload
8517 (defun tramp-unload-tramp ()
8518 "Discard Tramp from loading remote files."
8519 (interactive)
8520 ;; When Tramp is not loaded yet, its autoloads are still active.
8521 (tramp-unload-file-name-handlers)
8522 ;; ange-ftp settings must be enabled.
8523 (when (functionp 'tramp-ftp-enable-ange-ftp)
8524 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
8525 ;; Maybe its not loaded yet.
8526 (condition-case nil
8527 (unload-feature 'tramp 'force)
8528 (error nil)))
8530 (when (and load-in-progress
8531 (string-match "Loading tramp..." (or (current-message) "")))
8532 (message "Loading tramp...done"))
8534 (provide 'tramp)
8536 ;;; TODO:
8538 ;; * Handle nonlocal exits such as C-g.
8539 ;; * But it would probably be better to use with-local-quit at the
8540 ;; place where it's actually needed: around any potentially
8541 ;; indefinitely blocking piece of code. In this case it would be
8542 ;; within Tramp around one of its calls to accept-process-output (or
8543 ;; around one of the loops that calls accept-process-output)
8544 ;; (Stefan Monnier).
8545 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8546 ;; `shell-quote-argument'.
8547 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8548 ;; by the files in that directory. Add this here.
8549 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8550 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8551 ;; * Case-insensitive filename completion. (Norbert Goevert.)
8552 ;; * Don't use globbing for directories with many files, as this is
8553 ;; likely to produce long command lines, and some shells choke on
8554 ;; long command lines.
8555 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8556 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8557 ;; * abbreviate-file-name
8558 ;; * Better error checking. At least whenever we see something
8559 ;; strange when doing zerop, we should kill the process and start
8560 ;; again. (Greg Stark)
8561 ;; * Remove unneeded parameters from methods.
8562 ;; * Make it work for different encodings, and for different file name
8563 ;; encodings, too. (Daniel Pittman)
8564 ;; * Progress reports while copying files. (Michael Kifer)
8565 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8566 ;; then look if it's the right version (with `perl -v').
8567 ;; * When editing a remote CVS controlled file as a different user, VC
8568 ;; gets confused about the file locking status. Try to find out why
8569 ;; the workaround doesn't work.
8570 ;; * Username and hostname completion.
8571 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8572 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8573 ;; Code is nearly identical.
8574 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8575 ;; until the last but one hop via `start-file-process'. Apply it
8576 ;; also for ftp and smb.
8577 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8578 ;; some shell with root priviledges, it would be nice if I could
8579 ;; just call
8580 ;; trampclient filename.c
8581 ;; as an editor, and the _current_ shell would connect to an Emacs
8582 ;; server and would be used in an existing non-priviledged Emacs
8583 ;; session for doing the editing in question.
8584 ;; That way, I need not tell Emacs my password again and be afraid
8585 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8586 ;; once display a just typed password in the context of a keyboard
8587 ;; sequence prompt for a question immediately following in a shell
8588 ;; script run within Emacs -- nasty).
8589 ;; And if I have some ssh session running to a different computer,
8590 ;; having the possibility of passing a local file there to a local
8591 ;; Emacs session (in case I can arrange for a connection back) would
8592 ;; be nice.
8593 ;; Likely the corresponding Tramp server should not allow the
8594 ;; equivalent of the emacsclient -eval option in order to make this
8595 ;; reasonably unproblematic. And maybe trampclient should have some
8596 ;; way of passing credentials, like by using an SSL socket or
8597 ;; something. (David Kastrup)
8598 ;; * Reconnect directly to a compliant shell without first going
8599 ;; through the user's default shell. (Pete Forman)
8600 ;; * Make `tramp-default-user' obsolete.
8601 ;; * How can I interrupt the remote process with a signal
8602 ;; (interrupt-process seems not to work)? (Markus Triska)
8603 ;; * Avoid the local shell entirely for starting remote processes. If
8604 ;; so, I think even a signal, when delivered directly to the local
8605 ;; SSH instance, would correctly be propagated to the remote process
8606 ;; automatically; possibly SSH would have to be started with
8607 ;; "-t". (Markus Triska)
8608 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8609 ;; isn't on the remote host. (Mark A. Hershberger)
8610 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8611 ;; * Implement a general server-local-variable mechanism, as there are
8612 ;; probably other variables that need different values for different
8613 ;; servers too. The user could then configure a variable (such as
8614 ;; tramp-server-local-variable-alist) to define any such variables
8615 ;; that they need to, which would then be let bound as appropriate
8616 ;; in tramp functions. (Jason Rumney)
8617 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8618 ;; rsync).
8619 ;; * Keep a second connection open for out-of-band methods like scp or
8620 ;; rsync.
8621 ;; * Support ptys in `tramp-handle-start-file-process'. (Bug#4604)
8622 ;; * IMHO, it's a drawback that currently Tramp doesn't support
8623 ;; Unicode in Dired file names by default. Is it possible to
8624 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8625 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
8626 ;; expects only English messages? (Juri Linkov)
8627 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8628 ;; * Do not handle files with drive letter as remote. (Bug#5447)
8629 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448)
8630 ;; * Try telnet+curl as new method. It might be useful for busybox,
8631 ;; without built-in uuencode/uudecode.
8632 ;; * Let `shell-dynamic-complete-*' and `comint-dynamic-complete' work
8633 ;; on remote hosts.
8634 ;; * Use secrets.el for password handling.
8636 ;; Functions for file-name-handler-alist:
8637 ;; diff-latest-backup-file -- in diff.el
8639 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8640 ;;; tramp.el ends here
8642 ;; Local Variables:
8643 ;; mode: Emacs-Lisp
8644 ;; coding: utf-8
8645 ;; End: