rmail.el autoloads.
[emacs.git] / lisp / net / tramp.el
blob3f4af0ebf0ef976e198cbbe1df1154ae10a68cb8
1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; (copyright statements below in code to be updated with the above notice)
8 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
9 ;; Michael Albinus <michael.albinus@gmx.de>
10 ;; Keywords: comm, processes
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; This package provides remote file editing, similar to ange-ftp.
30 ;; The difference is that ange-ftp uses FTP to transfer files between
31 ;; the local and the remote host, whereas tramp.el uses a combination
32 ;; of rsh and rcp or other work-alike programs, such as ssh/scp.
34 ;; For more detailed instructions, please see the info file.
36 ;; Notes:
37 ;; -----
39 ;; This package only works for Emacs 21.1 and higher, and for XEmacs 21.4
40 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
41 ;; the `with-timeout' macro.
43 ;; Also see the todo list at the bottom of this file.
45 ;; The current version of Tramp can be retrieved from the following URL:
46 ;; http://ftp.gnu.org/gnu/tramp/
48 ;; There's a mailing list for this, as well. Its name is:
49 ;; tramp-devel@gnu.org
50 ;; You can use the Web to subscribe, under the following URL:
51 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
53 ;; For the adventurous, the current development sources are available
54 ;; via CVS. You can find instructions about this at the following URL:
55 ;; http://savannah.gnu.org/projects/tramp/
56 ;; Click on "CVS" in the navigation bar near the top.
58 ;; Don't forget to put on your asbestos longjohns, first!
60 ;;; Code:
62 ;; Since Emacs 23.1, loading messages have been disabled during
63 ;; autoload. However, loading Tramp takes a while, and it could
64 ;; happen while typing a filename in the minibuffer. Therefore, Tramp
65 ;; shall inform about.
66 (when (and load-in-progress (null (current-message)))
67 (message "Loading tramp..."))
69 ;; The Tramp version number and bug report address, as prepared by configure.
70 (require 'trampver)
71 (add-hook 'tramp-unload-hook
72 (lambda ()
73 (when (featurep 'trampver)
74 (unload-feature 'trampver 'force))))
76 (require 'tramp-compat)
77 (add-hook 'tramp-unload-hook
78 (lambda ()
79 (when (featurep 'tramp-compat)
80 (unload-feature 'tramp-compat 'force))))
82 (require 'format-spec) ; from Gnus 5.8, also in tar ball
83 ;; As long as password.el is not part of (X)Emacs, it shouldn't
84 ;; be mandatory
85 (if (featurep 'xemacs)
86 (load "password" 'noerror)
87 (or (require 'password-cache nil 'noerror)
88 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
90 (require 'shell)
91 (require 'advice)
93 (eval-and-compile
94 (if (featurep 'xemacs)
95 (load "auth-source" 'noerror)
96 (require 'auth-source nil 'noerror)))
98 ;; Requiring 'tramp-cache results in an endless loop.
99 (autoload 'tramp-get-file-property "tramp-cache")
100 (autoload 'tramp-set-file-property "tramp-cache")
101 (autoload 'tramp-flush-file-property "tramp-cache")
102 (autoload 'tramp-flush-directory-property "tramp-cache")
103 (autoload 'tramp-get-connection-property "tramp-cache")
104 (autoload 'tramp-set-connection-property "tramp-cache")
105 (autoload 'tramp-flush-connection-property "tramp-cache")
106 (autoload 'tramp-parse-connection-properties "tramp-cache")
107 (add-hook 'tramp-unload-hook
108 (lambda ()
109 (when (featurep 'tramp-cache)
110 (unload-feature 'tramp-cache 'force))))
112 (autoload 'tramp-uuencode-region "tramp-uu"
113 "Implementation of `uuencode' in Lisp.")
114 (add-hook 'tramp-unload-hook
115 (lambda ()
116 (when (featurep 'tramp-uu)
117 (unload-feature 'tramp-uu 'force))))
119 (autoload 'uudecode-decode-region "uudecode")
121 ;; The following Tramp packages must be loaded after tramp.el, because
122 ;; they require it as well.
123 (eval-after-load "tramp"
124 '(dolist
125 (feature
126 (list
128 ;; Tramp interactive commands.
129 'tramp-cmds
131 ;; Load foreign FTP method.
132 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
134 ;; tramp-smb uses "smbclient" from Samba. Not available
135 ;; under Cygwin and Windows, because they don't offer
136 ;; "smbclient". And even not necessary there, because Emacs
137 ;; supports UNC file names like "//host/share/localname".
138 (unless (memq system-type '(cygwin windows-nt)) 'tramp-smb)
140 ;; Load foreign FISH method.
141 'tramp-fish
143 ;; tramp-gvfs needs D-Bus messages. Available since Emacs 23
144 ;; on some system types. We don't call `dbus-ping', because
145 ;; this would load dbus.el.
146 (when (and (featurep 'dbusbind)
147 (condition-case nil
148 (funcall 'dbus-get-unique-name :session)
149 (error nil))
150 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
151 'tramp-gvfs)
153 ;; Load gateways. It needs `make-network-process' from Emacs 22.
154 (when (functionp 'make-network-process) 'tramp-gw)
156 ;; tramp-imap needs both epa (from Emacs 23.1) and imap-hash
157 ;; (from Emacs 23.2).
158 (when (and (locate-library "epa") (locate-library "imap-hash"))
159 'tramp-imap)))
161 (when feature
162 ;; We have used just some basic tests, whether a package shall
163 ;; be added. There might still be other errors during loading,
164 ;; which we will catch here.
165 (catch 'tramp-loading
166 (require feature)
167 (add-hook 'tramp-unload-hook
168 `(lambda ()
169 (when (featurep (quote ,feature))
170 (unload-feature (quote ,feature) 'force)))))
171 (unless (featurep feature)
172 (message "Loading %s failed, ignoring this package" feature)))))
174 ;;; User Customizable Internal Variables:
176 (defgroup tramp nil
177 "Edit remote files with a combination of rsh and rcp or similar programs."
178 :group 'files
179 :version "22.1")
181 ;; Maybe we need once a real Tramp mode, with key bindings etc.
182 ;;;###autoload
183 (defcustom tramp-mode t
184 "*Whether Tramp is enabled.
185 If it is set to nil, all remote file names are used literally."
186 :group 'tramp
187 :type 'boolean)
189 (defcustom tramp-verbose 3
190 "*Verbosity level for Tramp messages.
191 Any level x includes messages for all levels 1 .. x-1. The levels are
193 0 silent (no tramp messages at all)
194 1 errors
195 2 warnings
196 3 connection to remote hosts (default level)
197 4 activities
198 5 internal
199 6 sent and received strings
200 7 file caching
201 8 connection properties
202 10 traces (huge)."
203 :group 'tramp
204 :type 'integer)
206 ;; Emacs case.
207 (eval-and-compile
208 (when (boundp 'backup-directory-alist)
209 (defcustom tramp-backup-directory-alist nil
210 "Alist of filename patterns and backup directory names.
211 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
212 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
213 is a local file name, the backup directory is prepended with Tramp file
214 name prefix \(method, user, host\) of file.
216 \(setq tramp-backup-directory-alist backup-directory-alist\)
218 gives the same backup policy for Tramp files on their hosts like the
219 policy for local files."
220 :group 'tramp
221 :type '(repeat (cons (regexp :tag "Regexp matching filename")
222 (directory :tag "Backup directory name"))))))
224 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
225 ;; the package "backup-dir" might not be loaded yet.
226 (eval-and-compile
227 (when (featurep 'xemacs)
228 (defcustom tramp-bkup-backup-directory-info nil
229 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
230 It has the same meaning like `bkup-backup-directory-info' from package
231 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
232 file name, the backup directory is prepended with Tramp file name prefix
233 \(method, user, host\) of file.
235 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
237 gives the same backup policy for Tramp files on their hosts like the
238 policy for local files."
239 :type '(repeat
240 (list (regexp :tag "File regexp")
241 (string :tag "Backup Dir")
242 (set :inline t
243 (const ok-create)
244 (const full-path)
245 (const prepend-name)
246 (const search-upward))))
247 :group 'tramp)))
249 (defcustom tramp-auto-save-directory nil
250 "*Put auto-save files in this directory, if set.
251 The idea is to use a local directory so that auto-saving is faster."
252 :group 'tramp
253 :type '(choice (const nil) string))
255 (defcustom tramp-encoding-shell
256 (if (memq system-type '(windows-nt))
257 (getenv "COMSPEC")
258 "/bin/sh")
259 "*Use this program for encoding and decoding commands on the local host.
260 This shell is used to execute the encoding and decoding command on the
261 local host, so if you want to use `~' in those commands, you should
262 choose a shell here which groks tilde expansion. `/bin/sh' normally
263 does not understand tilde expansion.
265 For encoding and deocding, commands like the following are executed:
267 /bin/sh -c COMMAND < INPUT > OUTPUT
269 This variable can be used to change the \"/bin/sh\" part. See the
270 variable `tramp-encoding-command-switch' for the \"-c\" part.
272 Note that this variable is not used for remote commands. There are
273 mechanisms in tramp.el which automatically determine the right shell to
274 use for the remote host."
275 :group 'tramp
276 :type '(file :must-match t))
278 (defcustom tramp-encoding-command-switch
279 (if (string-match "cmd\\.exe" tramp-encoding-shell)
280 "/c"
281 "-c")
282 "*Use this switch together with `tramp-encoding-shell' for local commands.
283 See the variable `tramp-encoding-shell' for more information."
284 :group 'tramp
285 :type 'string)
287 (defcustom tramp-copy-size-limit 10240
288 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
289 :group 'tramp
290 :type 'integer)
292 (defcustom tramp-terminal-type "dumb"
293 "*Value of TERM environment variable for logging in to remote host.
294 Because Tramp wants to parse the output of the remote shell, it is easily
295 confused by ANSI color escape sequences and suchlike. Often, shell init
296 files conditionalize this setup based on the TERM environment variable."
297 :group 'tramp
298 :type 'string)
300 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
301 ;; root users. It uses the `$' character for other users. In order
302 ;; to guarantee a proper prompt, we use "#$" for the prompt.
304 (defvar tramp-end-of-output
305 (format
306 "///%s#$"
307 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
308 "String used to recognize end of output.
309 The '$' character at the end is quoted; the string cannot be
310 detected as prompt when being sent on echoing hosts, therefore.")
312 (defconst tramp-initial-end-of-output "#$ "
313 "Prompt when establishing a connection.")
315 (defvar tramp-methods
316 `(("rcp" (tramp-login-program "rsh")
317 (tramp-login-args (("%h") ("-l" "%u")))
318 (tramp-remote-sh "/bin/sh")
319 (tramp-copy-program "rcp")
320 (tramp-copy-args (("-p" "%k") ("-r")))
321 (tramp-copy-keep-date t)
322 (tramp-copy-recursive t)
323 (tramp-password-end-of-line nil))
324 ("scp" (tramp-login-program "ssh")
325 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
326 ("-e" "none")))
327 (tramp-remote-sh "/bin/sh")
328 (tramp-copy-program "scp")
329 (tramp-copy-args (("-P" "%p") ("-p" "%k")
330 ("-q") ("-r")))
331 (tramp-copy-keep-date t)
332 (tramp-copy-recursive t)
333 (tramp-password-end-of-line nil)
334 (tramp-gw-args (("-o"
335 "GlobalKnownHostsFile=/dev/null")
336 ("-o" "UserKnownHostsFile=/dev/null")
337 ("-o" "StrictHostKeyChecking=no")))
338 (tramp-default-port 22))
339 ("scp1" (tramp-login-program "ssh")
340 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
341 ("-1" "-e" "none")))
342 (tramp-remote-sh "/bin/sh")
343 (tramp-copy-program "scp")
344 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
345 ("-q") ("-r")))
346 (tramp-copy-keep-date t)
347 (tramp-copy-recursive t)
348 (tramp-password-end-of-line nil)
349 (tramp-gw-args (("-o"
350 "GlobalKnownHostsFile=/dev/null")
351 ("-o" "UserKnownHostsFile=/dev/null")
352 ("-o" "StrictHostKeyChecking=no")))
353 (tramp-default-port 22))
354 ("scp2" (tramp-login-program "ssh")
355 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
356 ("-2" "-e" "none")))
357 (tramp-remote-sh "/bin/sh")
358 (tramp-copy-program "scp")
359 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
360 ("-q") ("-r")))
361 (tramp-copy-keep-date t)
362 (tramp-copy-recursive t)
363 (tramp-password-end-of-line nil)
364 (tramp-gw-args (("-o"
365 "GlobalKnownHostsFile=/dev/null")
366 ("-o" "UserKnownHostsFile=/dev/null")
367 ("-o" "StrictHostKeyChecking=no")))
368 (tramp-default-port 22))
369 ("scp1_old"
370 (tramp-login-program "ssh1")
371 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
372 ("-e" "none")))
373 (tramp-remote-sh "/bin/sh")
374 (tramp-copy-program "scp1")
375 (tramp-copy-args (("-p" "%k") ("-r")))
376 (tramp-copy-keep-date t)
377 (tramp-copy-recursive t)
378 (tramp-password-end-of-line nil))
379 ("scp2_old"
380 (tramp-login-program "ssh2")
381 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
382 ("-e" "none")))
383 (tramp-remote-sh "/bin/sh")
384 (tramp-copy-program "scp2")
385 (tramp-copy-args (("-p" "%k") ("-r")))
386 (tramp-copy-keep-date t)
387 (tramp-copy-recursive t)
388 (tramp-password-end-of-line nil))
389 ("sftp" (tramp-login-program "ssh")
390 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
391 ("-e" "none")))
392 (tramp-remote-sh "/bin/sh")
393 (tramp-copy-program "sftp")
394 (tramp-copy-args nil)
395 (tramp-copy-keep-date nil)
396 (tramp-password-end-of-line nil))
397 ("rsync" (tramp-login-program "ssh")
398 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
399 ("-e" "none")))
400 (tramp-remote-sh "/bin/sh")
401 (tramp-copy-program "rsync")
402 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
403 (tramp-copy-keep-date t)
404 (tramp-copy-keep-tmpfile t)
405 (tramp-copy-recursive t)
406 (tramp-password-end-of-line nil))
407 ("rsyncc"
408 (tramp-login-program "ssh")
409 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
410 ("-o" "ControlPath=%t.%%r@%%h:%%p")
411 ("-o" "ControlMaster=yes")
412 ("-e" "none")))
413 (tramp-remote-sh "/bin/sh")
414 (tramp-copy-program "rsync")
415 (tramp-copy-args (("-t" "%k") ("-r")))
416 (tramp-copy-env (("RSYNC_RSH")
417 (,(concat
418 "ssh"
419 " -o ControlPath=%t.%%r@%%h:%%p"
420 " -o ControlMaster=auto"))))
421 (tramp-copy-keep-date t)
422 (tramp-copy-keep-tmpfile t)
423 (tramp-copy-recursive t)
424 (tramp-password-end-of-line nil))
425 ("remcp" (tramp-login-program "remsh")
426 (tramp-login-args (("%h") ("-l" "%u")))
427 (tramp-remote-sh "/bin/sh")
428 (tramp-copy-program "rcp")
429 (tramp-copy-args (("-p" "%k")))
430 (tramp-copy-keep-date t)
431 (tramp-password-end-of-line nil))
432 ("rsh" (tramp-login-program "rsh")
433 (tramp-login-args (("%h") ("-l" "%u")))
434 (tramp-remote-sh "/bin/sh")
435 (tramp-copy-program nil)
436 (tramp-copy-args nil)
437 (tramp-copy-keep-date nil)
438 (tramp-password-end-of-line nil))
439 ("ssh" (tramp-login-program "ssh")
440 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
441 ("-e" "none")))
442 (tramp-remote-sh "/bin/sh")
443 (tramp-copy-program nil)
444 (tramp-copy-args nil)
445 (tramp-copy-keep-date nil)
446 (tramp-password-end-of-line nil)
447 (tramp-gw-args (("-o"
448 "GlobalKnownHostsFile=/dev/null")
449 ("-o" "UserKnownHostsFile=/dev/null")
450 ("-o" "StrictHostKeyChecking=no")))
451 (tramp-default-port 22))
452 ("ssh1" (tramp-login-program "ssh")
453 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
454 ("-1" "-e" "none")))
455 (tramp-remote-sh "/bin/sh")
456 (tramp-copy-program nil)
457 (tramp-copy-args nil)
458 (tramp-copy-keep-date nil)
459 (tramp-password-end-of-line nil)
460 (tramp-gw-args (("-o"
461 "GlobalKnownHostsFile=/dev/null")
462 ("-o" "UserKnownHostsFile=/dev/null")
463 ("-o" "StrictHostKeyChecking=no")))
464 (tramp-default-port 22))
465 ("ssh2" (tramp-login-program "ssh")
466 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
467 ("-2" "-e" "none")))
468 (tramp-remote-sh "/bin/sh")
469 (tramp-copy-program nil)
470 (tramp-copy-args nil)
471 (tramp-copy-keep-date nil)
472 (tramp-password-end-of-line nil)
473 (tramp-gw-args (("-o"
474 "GlobalKnownHostsFile=/dev/null")
475 ("-o" "UserKnownHostsFile=/dev/null")
476 ("-o" "StrictHostKeyChecking=no")))
477 (tramp-default-port 22))
478 ("ssh1_old"
479 (tramp-login-program "ssh1")
480 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
481 ("-e" "none")))
482 (tramp-remote-sh "/bin/sh")
483 (tramp-copy-program nil)
484 (tramp-copy-args nil)
485 (tramp-copy-keep-date nil)
486 (tramp-password-end-of-line nil))
487 ("ssh2_old"
488 (tramp-login-program "ssh2")
489 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
490 ("-e" "none")))
491 (tramp-remote-sh "/bin/sh")
492 (tramp-copy-program nil)
493 (tramp-copy-args nil)
494 (tramp-copy-keep-date nil)
495 (tramp-password-end-of-line nil))
496 ("remsh" (tramp-login-program "remsh")
497 (tramp-login-args (("%h") ("-l" "%u")))
498 (tramp-remote-sh "/bin/sh")
499 (tramp-copy-program nil)
500 (tramp-copy-args nil)
501 (tramp-copy-keep-date nil)
502 (tramp-password-end-of-line nil))
503 ("telnet"
504 (tramp-login-program "telnet")
505 (tramp-login-args (("%h") ("%p")))
506 (tramp-remote-sh "/bin/sh")
507 (tramp-copy-program nil)
508 (tramp-copy-args nil)
509 (tramp-copy-keep-date nil)
510 (tramp-password-end-of-line nil)
511 (tramp-default-port 23))
512 ("su" (tramp-login-program "su")
513 (tramp-login-args (("-") ("%u")))
514 (tramp-remote-sh "/bin/sh")
515 (tramp-copy-program nil)
516 (tramp-copy-args nil)
517 (tramp-copy-keep-date nil)
518 (tramp-password-end-of-line nil))
519 ("sudo" (tramp-login-program "sudo")
520 (tramp-login-args (("-u" "%u")
521 ("-s") ("-H") ("-p" "Password:")))
522 (tramp-remote-sh "/bin/sh")
523 (tramp-copy-program nil)
524 (tramp-copy-args nil)
525 (tramp-copy-keep-date nil)
526 (tramp-password-end-of-line nil))
527 ("scpc" (tramp-login-program "ssh")
528 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
529 ("-o" "ControlPath=%t.%%r@%%h:%%p")
530 ("-o" "ControlMaster=yes")
531 ("-e" "none")))
532 (tramp-remote-sh "/bin/sh")
533 (tramp-copy-program "scp")
534 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
535 ("-o" "ControlPath=%t.%%r@%%h:%%p")
536 ("-o" "ControlMaster=auto")))
537 (tramp-copy-keep-date t)
538 (tramp-password-end-of-line nil)
539 (tramp-gw-args (("-o"
540 "GlobalKnownHostsFile=/dev/null")
541 ("-o" "UserKnownHostsFile=/dev/null")
542 ("-o" "StrictHostKeyChecking=no")))
543 (tramp-default-port 22))
544 ("scpx" (tramp-login-program "ssh")
545 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
546 ("-e" "none" "-t" "-t" "/bin/sh")))
547 (tramp-remote-sh "/bin/sh")
548 (tramp-copy-program "scp")
549 (tramp-copy-args (("-p" "%k")))
550 (tramp-copy-keep-date t)
551 (tramp-password-end-of-line nil)
552 (tramp-gw-args (("-o"
553 "GlobalKnownHostsFile=/dev/null")
554 ("-o" "UserKnownHostsFile=/dev/null")
555 ("-o" "StrictHostKeyChecking=no")))
556 (tramp-default-port 22))
557 ("sshx" (tramp-login-program "ssh")
558 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
559 ("-e" "none" "-t" "-t" "/bin/sh")))
560 (tramp-remote-sh "/bin/sh")
561 (tramp-copy-program nil)
562 (tramp-copy-args nil)
563 (tramp-copy-keep-date nil)
564 (tramp-password-end-of-line nil)
565 (tramp-gw-args (("-o"
566 "GlobalKnownHostsFile=/dev/null")
567 ("-o" "UserKnownHostsFile=/dev/null")
568 ("-o" "StrictHostKeyChecking=no")))
569 (tramp-default-port 22))
570 ("krlogin"
571 (tramp-login-program "krlogin")
572 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
573 (tramp-remote-sh "/bin/sh")
574 (tramp-copy-program nil)
575 (tramp-copy-args nil)
576 (tramp-copy-keep-date nil)
577 (tramp-password-end-of-line nil))
578 ("plink" (tramp-login-program "plink")
579 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
580 ("-ssh")))
581 (tramp-remote-sh "/bin/sh")
582 (tramp-copy-program nil)
583 (tramp-copy-args nil)
584 (tramp-copy-keep-date nil)
585 (tramp-password-end-of-line "xy") ;see docstring for "xy"
586 (tramp-default-port 22))
587 ("plink1"
588 (tramp-login-program "plink")
589 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
590 ("-1" "-ssh")))
591 (tramp-remote-sh "/bin/sh")
592 (tramp-copy-program nil)
593 (tramp-copy-args nil)
594 (tramp-copy-keep-date nil)
595 (tramp-password-end-of-line "xy") ;see docstring for "xy"
596 (tramp-default-port 22))
597 ("plinkx"
598 (tramp-login-program "plink")
599 ;; ("%h") must be a single element, see
600 ;; `tramp-compute-multi-hops'.
601 (tramp-login-args (("-load") ("%h") ("-t")
602 (,(format
603 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
604 tramp-terminal-type
605 tramp-initial-end-of-output))
606 ("/bin/sh")))
607 (tramp-remote-sh "/bin/sh")
608 (tramp-copy-program nil)
609 (tramp-copy-args nil)
610 (tramp-copy-keep-date nil)
611 (tramp-password-end-of-line nil))
612 ("pscp" (tramp-login-program "plink")
613 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
614 ("-ssh")))
615 (tramp-remote-sh "/bin/sh")
616 (tramp-copy-program "pscp")
617 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
618 (tramp-copy-keep-date t)
619 (tramp-password-end-of-line "xy") ;see docstring for "xy"
620 (tramp-default-port 22))
621 ("psftp" (tramp-login-program "plink")
622 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
623 ("-ssh")))
624 (tramp-remote-sh "/bin/sh")
625 (tramp-copy-program "pscp")
626 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
627 (tramp-copy-keep-date t)
628 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
629 ("fcp" (tramp-login-program "fsh")
630 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
631 (tramp-remote-sh "/bin/sh -i")
632 (tramp-copy-program "fcp")
633 (tramp-copy-args (("-p" "%k")))
634 (tramp-copy-keep-date t)
635 (tramp-password-end-of-line nil)))
636 "*Alist of methods for remote files.
637 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
638 Each NAME stands for a remote access method. Each PARAM is a
639 pair of the form (KEY VALUE). The following KEYs are defined:
640 * `tramp-remote-sh'
641 This specifies the Bourne shell to use on the remote host. This
642 MUST be a Bourne-like shell. It is normally not necessary to set
643 this to any value other than \"/bin/sh\": Tramp wants to use a shell
644 which groks tilde expansion, but it can search for it. Also note
645 that \"/bin/sh\" exists on all Unixen, this might not be true for
646 the value that you decide to use. You Have Been Warned.
647 * `tramp-login-program'
648 This specifies the name of the program to use for logging in to the
649 remote host. This may be the name of rsh or a workalike program,
650 or the name of telnet or a workalike, or the name of su or a workalike.
651 * `tramp-login-args'
652 This specifies the list of arguments to pass to the above
653 mentioned program. Please note that this is a list of list of arguments,
654 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
655 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
656 There are some patterns: \"%h\" in this list is replaced by the host
657 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
658 port number, and \"%%\" can be used to obtain a literal percent character.
659 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
660 expansion (i.e. no host or no user specified), this list is not used as
661 argument. By this, arguments like (\"-l\" \"%u\") are optional.
662 \"%t\" is replaced by the temporary file name produced with
663 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
664 parameter of a program, if exists.
665 * `tramp-copy-program'
666 This specifies the name of the program to use for remotely copying
667 the file; this might be the absolute filename of rcp or the name of
668 a workalike program.
669 * `tramp-copy-args'
670 This specifies the list of parameters to pass to the above mentioned
671 program, the hints for `tramp-login-args' also apply here.
672 * `tramp-copy-keep-date'
673 This specifies whether the copying program when the preserves the
674 timestamp of the original file.
675 * `tramp-copy-keep-tmpfile'
676 This specifies whether a temporary local file shall be kept
677 for optimization reasons (useful for \"rsync\" methods).
678 * `tramp-copy-recursive'
679 Whether the operation copies directories recursively.
680 * `tramp-default-port'
681 The default port of a method is needed in case of gateway connections.
682 Additionally, it is used as indication which method is prepared for
683 passing gateways.
684 * `tramp-gw-args'
685 As the attribute name says, additional arguments are specified here
686 when a method is applied via a gateway.
687 * `tramp-password-end-of-line'
688 This specifies the string to use for terminating the line after
689 submitting the password. If this method parameter is nil, then the
690 value of the normal variable `tramp-default-password-end-of-line'
691 is used. This parameter is necessary because the \"plink\" program
692 requires any two characters after sending the password. These do
693 not have to be newline or carriage return characters. Other login
694 programs are happy with just one character, the newline character.
695 We use \"xy\" as the value for methods using \"plink\".
697 What does all this mean? Well, you should specify `tramp-login-program'
698 for all methods; this program is used to log in to the remote site. Then,
699 there are two ways to actually transfer the files between the local and the
700 remote side. One way is using an additional rcp-like program. If you want
701 to do this, set `tramp-copy-program' in the method.
703 Another possibility for file transfer is inline transfer, i.e. the
704 file is passed through the same buffer used by `tramp-login-program'. In
705 this case, the file contents need to be protected since the
706 `tramp-login-program' might use escape codes or the connection might not
707 be eight-bit clean. Therefore, file contents are encoded for transit.
708 See the variables `tramp-local-coding-commands' and
709 `tramp-remote-coding-commands' for details.
711 So, to summarize: if the method is an out-of-band method, then you
712 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
713 inline method, then these two parameters should be nil. Methods which
714 are fit for gateways must have `tramp-default-port' at least.
716 Notes:
718 When using `su' or `sudo' the phrase `open connection to a remote
719 host' sounds strange, but it is used nevertheless, for consistency.
720 No connection is opened to a remote host, but `su' or `sudo' is
721 started on the local host. You should specify a remote host
722 `localhost' or the name of the local host. Another host name is
723 useful only in combination with `tramp-default-proxies-alist'.")
725 (defcustom tramp-default-method
726 ;; An external copy method seems to be preferred, because it is much
727 ;; more performant for large files, and it hasn't too serious delays
728 ;; for small files. But it must be ensured that there aren't
729 ;; permanent password queries. Either a password agent like
730 ;; "ssh-agent" or "Pageant" shall run, or the optional
731 ;; password-cache.el or auth-sources.el packages shall be active for
732 ;; password caching. "scpc" would be another good choice because of
733 ;; the "ControlMaster" option, but this is a more modern alternative
734 ;; in OpenSSH 4, which cannot be taken as default.
735 (cond
736 ;; PuTTY is installed.
737 ((executable-find "pscp")
738 (if (or (fboundp 'password-read)
739 (fboundp 'auth-source-user-or-password)
740 ;; Pageant is running.
741 (tramp-compat-process-running-p "Pageant"))
742 "pscp"
743 "plink"))
744 ;; There is an ssh installation.
745 ((executable-find "scp")
746 (if (or (fboundp 'password-read)
747 (fboundp 'auth-source-user-or-password)
748 ;; ssh-agent is running.
749 (getenv "SSH_AUTH_SOCK")
750 (getenv "SSH_AGENT_PID"))
751 "scp"
752 "ssh"))
753 ;; Fallback.
754 (t "ftp"))
755 "*Default method to use for transferring files.
756 See `tramp-methods' for possibilities.
757 Also see `tramp-default-method-alist'."
758 :group 'tramp
759 :type 'string)
761 (defcustom tramp-default-method-alist
762 '(("\\`localhost\\'" "\\`root\\'" "su"))
763 "*Default method to use for specific host/user pairs.
764 This is an alist of items (HOST USER METHOD). The first matching item
765 specifies the method to use for a file name which does not specify a
766 method. HOST and USER are regular expressions or nil, which is
767 interpreted as a regular expression which always matches. If no entry
768 matches, the variable `tramp-default-method' takes effect.
770 If the file name does not specify the user, lookup is done using the
771 empty string for the user name.
773 See `tramp-methods' for a list of possibilities for METHOD."
774 :group 'tramp
775 :type '(repeat (list (regexp :tag "Host regexp")
776 (regexp :tag "User regexp")
777 (string :tag "Method"))))
779 (defcustom tramp-default-user
781 "*Default user to use for transferring files.
782 It is nil by default; otherwise settings in configuration files like
783 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
785 This variable is regarded as obsolete, and will be removed soon."
786 :group 'tramp
787 :type '(choice (const nil) string))
789 (defcustom tramp-default-user-alist
790 `(("\\`su\\(do\\)?\\'" nil "root")
791 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
792 nil ,(user-login-name)))
793 "*Default user to use for specific method/host pairs.
794 This is an alist of items (METHOD HOST USER). The first matching item
795 specifies the user to use for a file name which does not specify a
796 user. METHOD and USER are regular expressions or nil, which is
797 interpreted as a regular expression which always matches. If no entry
798 matches, the variable `tramp-default-user' takes effect.
800 If the file name does not specify the method, lookup is done using the
801 empty string for the method name."
802 :group 'tramp
803 :type '(repeat (list (regexp :tag "Method regexp")
804 (regexp :tag "Host regexp")
805 (string :tag "User"))))
807 (defcustom tramp-default-host
808 (system-name)
809 "*Default host to use for transferring files.
810 Useful for su and sudo methods mostly."
811 :group 'tramp
812 :type 'string)
814 (defcustom tramp-default-proxies-alist nil
815 "*Route to be followed for specific host/user pairs.
816 This is an alist of items (HOST USER PROXY). The first matching
817 item specifies the proxy to be passed for a file name located on
818 a remote target matching USER@HOST. HOST and USER are regular
819 expressions. PROXY must be a Tramp filename without a localname
820 part. Method and user name on PROXY are optional, which is
821 interpreted with the default values. PROXY can contain the
822 patterns %h and %u, which are replaced by the strings matching
823 HOST or USER, respectively.
825 HOST, USER or PROXY could also be Lisp forms, which will be
826 evaluated. The result must be a string or nil, which is
827 interpreted as a regular expression which always matches."
828 :group 'tramp
829 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
830 (choice :tag "User regexp" regexp sexp)
831 (choice :tag "Proxy remote name" string (const nil)))))
833 (defconst tramp-local-host-regexp
834 (concat
835 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
836 "*Host names which are regarded as local host.")
838 (defconst tramp-completion-function-alist-rsh
839 '((tramp-parse-rhosts "/etc/hosts.equiv")
840 (tramp-parse-rhosts "~/.rhosts"))
841 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
843 (defconst tramp-completion-function-alist-ssh
844 '((tramp-parse-rhosts "/etc/hosts.equiv")
845 (tramp-parse-rhosts "/etc/shosts.equiv")
846 (tramp-parse-shosts "/etc/ssh_known_hosts")
847 (tramp-parse-sconfig "/etc/ssh_config")
848 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
849 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
850 (tramp-parse-rhosts "~/.rhosts")
851 (tramp-parse-rhosts "~/.shosts")
852 (tramp-parse-shosts "~/.ssh/known_hosts")
853 (tramp-parse-sconfig "~/.ssh/config")
854 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
855 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
856 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
858 (defconst tramp-completion-function-alist-telnet
859 '((tramp-parse-hosts "/etc/hosts"))
860 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
862 (defconst tramp-completion-function-alist-su
863 '((tramp-parse-passwd "/etc/passwd"))
864 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
866 (defconst tramp-completion-function-alist-putty
867 '((tramp-parse-putty
868 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
869 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
871 (defvar tramp-completion-function-alist nil
872 "*Alist of methods for remote files.
873 This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
874 Each NAME stands for a remote access method. Each PAIR is of the form
875 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
876 names from FILE for completion. The following predefined FUNCTIONs exists:
878 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
879 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
880 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
881 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
882 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
883 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
884 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
885 * `tramp-parse-netrc' for \"~/.netrc\" like files.
886 * `tramp-parse-putty' for PuTTY registry keys.
888 FUNCTION can also be a customer defined function. For more details see
889 the info pages.")
891 (eval-after-load "tramp"
892 '(progn
893 (tramp-set-completion-function
894 "rcp" tramp-completion-function-alist-rsh)
895 (tramp-set-completion-function
896 "scp" tramp-completion-function-alist-ssh)
897 (tramp-set-completion-function
898 "scp1" tramp-completion-function-alist-ssh)
899 (tramp-set-completion-function
900 "scp2" tramp-completion-function-alist-ssh)
901 (tramp-set-completion-function
902 "scp1_old" tramp-completion-function-alist-ssh)
903 (tramp-set-completion-function
904 "scp2_old" tramp-completion-function-alist-ssh)
905 (tramp-set-completion-function
906 "rsync" tramp-completion-function-alist-ssh)
907 (tramp-set-completion-function
908 "rsyncc" tramp-completion-function-alist-ssh)
909 (tramp-set-completion-function
910 "remcp" tramp-completion-function-alist-rsh)
911 (tramp-set-completion-function
912 "rsh" tramp-completion-function-alist-rsh)
913 (tramp-set-completion-function
914 "ssh" tramp-completion-function-alist-ssh)
915 (tramp-set-completion-function
916 "ssh1" tramp-completion-function-alist-ssh)
917 (tramp-set-completion-function
918 "ssh2" tramp-completion-function-alist-ssh)
919 (tramp-set-completion-function
920 "ssh1_old" tramp-completion-function-alist-ssh)
921 (tramp-set-completion-function
922 "ssh2_old" tramp-completion-function-alist-ssh)
923 (tramp-set-completion-function
924 "remsh" tramp-completion-function-alist-rsh)
925 (tramp-set-completion-function
926 "telnet" tramp-completion-function-alist-telnet)
927 (tramp-set-completion-function
928 "su" tramp-completion-function-alist-su)
929 (tramp-set-completion-function
930 "sudo" tramp-completion-function-alist-su)
931 (tramp-set-completion-function
932 "scpx" tramp-completion-function-alist-ssh)
933 (tramp-set-completion-function
934 "sshx" tramp-completion-function-alist-ssh)
935 (tramp-set-completion-function
936 "krlogin" tramp-completion-function-alist-rsh)
937 (tramp-set-completion-function
938 "plink" tramp-completion-function-alist-ssh)
939 (tramp-set-completion-function
940 "plink1" tramp-completion-function-alist-ssh)
941 (tramp-set-completion-function
942 "plinkx" tramp-completion-function-alist-putty)
943 (tramp-set-completion-function
944 "pscp" tramp-completion-function-alist-ssh)
945 (tramp-set-completion-function
946 "fcp" tramp-completion-function-alist-ssh)))
948 (defconst tramp-echo-mark-marker "_echo"
949 "String marker to surround echoed commands.")
951 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
952 "String length of `tramp-echo-mark-marker'.")
954 (defconst tramp-echo-mark
955 (concat tramp-echo-mark-marker
956 (make-string tramp-echo-mark-marker-length ?\b))
957 "String mark to be transmitted around shell commands.
958 Used to separate their echo from the output they produce. This
959 will only be used if we cannot disable remote echo via stty.
960 This string must have no effect on the remote shell except for
961 producing some echo which can later be detected by
962 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
963 followed by an equal number of backspaces to erase them will
964 usually suffice.")
966 (defconst tramp-echoed-echo-mark-regexp
967 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
968 tramp-echo-mark-marker tramp-echo-mark-marker-length)
969 "Regexp which matches `tramp-echo-mark' as it gets echoed by
970 the remote shell.")
972 (defcustom tramp-rsh-end-of-line "\n"
973 "*String used for end of line in rsh connections.
974 I don't think this ever needs to be changed, so please tell me about it
975 if you need to change this.
976 Also see the method parameter `tramp-password-end-of-line' and the normal
977 variable `tramp-default-password-end-of-line'."
978 :group 'tramp
979 :type 'string)
981 (defcustom tramp-default-password-end-of-line
982 tramp-rsh-end-of-line
983 "*String used for end of line after sending a password.
984 This variable provides the default value for the method parameter
985 `tramp-password-end-of-line', see `tramp-methods' for more details.
987 It seems that people using plink under Windows need to send
988 \"\\r\\n\" (carriage-return, then newline) after a password, but just
989 \"\\n\" after all other lines. This variable can be used for the
990 password, see `tramp-rsh-end-of-line' for the other cases.
992 The default value is to use the same value as `tramp-rsh-end-of-line'."
993 :group 'tramp
994 :type 'string)
996 ;; "getconf PATH" yields:
997 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
998 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
999 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1000 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1001 (defcustom tramp-remote-path
1002 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1003 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1004 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1005 "*List of directories to search for executables on remote host.
1006 For every remote host, this variable will be set buffer local,
1007 keeping the list of existing directories on that host.
1009 You can use `~' in this list, but when searching for a shell which groks
1010 tilde expansion, all directory names starting with `~' will be ignored.
1012 `Default Directories' represent the list of directories given by
1013 the command \"getconf PATH\". It is recommended to use this
1014 entry on top of this list, because these are the default
1015 directories for POSIX compatible commands.
1017 `Private Directories' are the settings of the $PATH environment,
1018 as given in your `~/.profile'."
1019 :group 'tramp
1020 :type '(repeat (choice
1021 (const :tag "Default Directories" tramp-default-remote-path)
1022 (const :tag "Private Directories" tramp-own-remote-path)
1023 (string :tag "Directory"))))
1025 (defcustom tramp-remote-process-environment
1026 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1027 ,(concat "TERM=" tramp-terminal-type)
1028 "EMACS=t" ;; Deprecated.
1029 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
1030 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1031 "autocorrect=" "correct=")
1033 "*List of environment variables to be set on the remote host.
1035 Each element should be a string of the form ENVVARNAME=VALUE. An
1036 entry ENVVARNAME= diables the corresponding environment variable,
1037 which might have been set in the init files like ~/.profile.
1039 Special handling is applied to the PATH environment, which should
1040 not be set here. Instead of, it should be set via `tramp-remote-path'."
1041 :group 'tramp
1042 :type '(repeat string))
1044 (defcustom tramp-login-prompt-regexp
1045 ".*ogin\\( .*\\)?: *"
1046 "*Regexp matching login-like prompts.
1047 The regexp should match at end of buffer.
1049 Sometimes the prompt is reported to look like \"login as:\"."
1050 :group 'tramp
1051 :type 'regexp)
1053 (defcustom tramp-shell-prompt-pattern
1054 ;; Allow a prompt to start right after a ^M since it indeed would be
1055 ;; displayed at the beginning of the line (and Zsh uses it).
1056 "\\(?:^\\|\r\\)[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
1057 "Regexp to match prompts from remote shell.
1058 Normally, Tramp expects you to configure `shell-prompt-pattern'
1059 correctly, but sometimes it happens that you are connecting to a
1060 remote host which sends a different kind of shell prompt. Therefore,
1061 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1062 and also things matched by this variable. The default value of this
1063 variable is similar to the default value of `shell-prompt-pattern',
1064 which should work well in many cases.
1066 This regexp must match both `tramp-initial-end-of-output' and
1067 `tramp-end-of-output'."
1068 :group 'tramp
1069 :type 'regexp)
1071 (defcustom tramp-password-prompt-regexp
1072 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1073 "*Regexp matching password-like prompts.
1074 The regexp should match at end of buffer.
1076 The `sudo' program appears to insert a `^@' character into the prompt."
1077 :group 'tramp
1078 :type 'regexp)
1080 (defcustom tramp-wrong-passwd-regexp
1081 (concat "^.*"
1082 ;; These strings should be on the last line
1083 (regexp-opt '("Permission denied"
1084 "Login incorrect"
1085 "Login Incorrect"
1086 "Connection refused"
1087 "Connection closed"
1088 "Sorry, try again."
1089 "Name or service not known"
1090 "Host key verification failed."
1091 "No supported authentication methods left to try!") t)
1092 ".*"
1093 "\\|"
1094 "^.*\\("
1095 ;; Here comes a list of regexes, separated by \\|
1096 "Received signal [0-9]+"
1097 "\\).*")
1098 "*Regexp matching a `login failed' message.
1099 The regexp should match at end of buffer."
1100 :group 'tramp
1101 :type 'regexp)
1103 (defcustom tramp-yesno-prompt-regexp
1104 (concat
1105 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1106 "\\s-*")
1107 "Regular expression matching all yes/no queries which need to be confirmed.
1108 The confirmation should be done with yes or no.
1109 The regexp should match at end of buffer.
1110 See also `tramp-yn-prompt-regexp'."
1111 :group 'tramp
1112 :type 'regexp)
1114 (defcustom tramp-yn-prompt-regexp
1115 (concat
1116 (regexp-opt '("Store key in cache? (y/n)"
1117 "Update cached key? (y/n, Return cancels connection)") t)
1118 "\\s-*")
1119 "Regular expression matching all y/n queries which need to be confirmed.
1120 The confirmation should be done with y or n.
1121 The regexp should match at end of buffer.
1122 See also `tramp-yesno-prompt-regexp'."
1123 :group 'tramp
1124 :type 'regexp)
1126 (defcustom tramp-terminal-prompt-regexp
1127 (concat "\\("
1128 "TERM = (.*)"
1129 "\\|"
1130 "Terminal type\\? \\[.*\\]"
1131 "\\)\\s-*")
1132 "Regular expression matching all terminal setting prompts.
1133 The regexp should match at end of buffer.
1134 The answer will be provided by `tramp-action-terminal', which see."
1135 :group 'tramp
1136 :type 'regexp)
1138 (defcustom tramp-operation-not-permitted-regexp
1139 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1140 (regexp-opt '("Operation not permitted") t))
1141 "Regular expression matching keep-date problems in (s)cp operations.
1142 Copying has been performed successfully already, so this message can
1143 be ignored safely."
1144 :group 'tramp
1145 :type 'regexp)
1147 (defcustom tramp-copy-failed-regexp
1148 (concat "\\(.+: "
1149 (regexp-opt '("Permission denied"
1150 "not a regular file"
1151 "is a directory"
1152 "No such file or directory") t)
1153 "\\)\\s-*")
1154 "Regular expression matching copy problems in (s)cp operations."
1155 :group 'tramp
1156 :type 'regexp)
1158 (defcustom tramp-process-alive-regexp
1160 "Regular expression indicating a process has finished.
1161 In fact this expression is empty by intention, it will be used only to
1162 check regularly the status of the associated process.
1163 The answer will be provided by `tramp-action-process-alive',
1164 `tramp-action-out-of-band', which see."
1165 :group 'tramp
1166 :type 'regexp)
1168 (defcustom tramp-temp-name-prefix "tramp."
1169 "*Prefix to use for temporary files.
1170 If this is a relative file name (such as \"tramp.\"), it is considered
1171 relative to the directory name returned by the function
1172 `tramp-compat-temporary-file-directory' (which see). It may also be an
1173 absolute file name; don't forget to include a prefix for the filename
1174 part, though."
1175 :group 'tramp
1176 :type 'string)
1178 (defconst tramp-temp-buffer-name " *tramp temp*"
1179 "Buffer name for a temporary buffer.
1180 It shall be used in combination with `generate-new-buffer-name'.")
1182 (defvar tramp-temp-buffer-file-name nil
1183 "File name of a persistent local temporary file.
1184 Useful for \"rsync\" like methods.")
1185 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1187 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1188 "*Alist specifying extra arguments to pass to the remote shell.
1189 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1190 matching the shell file name and ARGS is a string specifying the
1191 arguments.
1193 This variable is only used when Tramp needs to start up another shell
1194 for tilde expansion. The extra arguments should typically prevent the
1195 shell from reading its init file."
1196 :group 'tramp
1197 ;; This might be the wrong way to test whether the widget type
1198 ;; `alist' is available. Who knows the right way to test it?
1199 :type (if (get 'alist 'widget-type)
1200 '(alist :key-type string :value-type string)
1201 '(repeat (cons string string))))
1203 ;; XEmacs is distributed with few Lisp packages. Further packages are
1204 ;; installed using EFS. If we use a unified filename format, then
1205 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1206 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1207 ;; just like before.) Another reason for using a separate filename
1208 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1209 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1210 ;; the other places.
1212 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1213 ;;;###autoload
1214 (defcustom tramp-syntax
1215 (if (featurep 'xemacs) 'sep 'ftp)
1216 "Tramp filename syntax to be used.
1218 It can have the following values:
1220 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1221 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1222 'url -- URL-like syntax."
1223 :group 'tramp
1224 :type (if (featurep 'xemacs)
1225 '(choice (const :tag "EFS" ftp)
1226 (const :tag "XEmacs" sep)
1227 (const :tag "URL" url))
1228 '(choice (const :tag "Ange-FTP" ftp)
1229 (const :tag "URL" url))))
1231 (defconst tramp-prefix-format
1232 (cond ((equal tramp-syntax 'ftp) "/")
1233 ((equal tramp-syntax 'sep) "/[")
1234 ((equal tramp-syntax 'url) "/")
1235 (t (error "Wrong `tramp-syntax' defined")))
1236 "*String matching the very beginning of Tramp file names.
1237 Used in `tramp-make-tramp-file-name'.")
1239 (defconst tramp-prefix-regexp
1240 (concat "^" (regexp-quote tramp-prefix-format))
1241 "*Regexp matching the very beginning of Tramp file names.
1242 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1244 (defconst tramp-method-regexp
1245 "[a-zA-Z_0-9-]+"
1246 "*Regexp matching methods identifiers.")
1248 (defconst tramp-postfix-method-format
1249 (cond ((equal tramp-syntax 'ftp) ":")
1250 ((equal tramp-syntax 'sep) "/")
1251 ((equal tramp-syntax 'url) "://")
1252 (t (error "Wrong `tramp-syntax' defined")))
1253 "*String matching delimeter between method and user or host names.
1254 Used in `tramp-make-tramp-file-name'.")
1256 (defconst tramp-postfix-method-regexp
1257 (regexp-quote tramp-postfix-method-format)
1258 "*Regexp matching delimeter between method and user or host names.
1259 Derived from `tramp-postfix-method-format'.")
1261 (defconst tramp-user-regexp
1262 "[^:/ \t]+"
1263 "*Regexp matching user names.")
1265 (defconst tramp-prefix-domain-format "%"
1266 "*String matching delimeter between user and domain names.")
1268 (defconst tramp-prefix-domain-regexp
1269 (regexp-quote tramp-prefix-domain-format)
1270 "*Regexp matching delimeter between user and domain names.
1271 Derived from `tramp-prefix-domain-format'.")
1273 (defconst tramp-domain-regexp
1274 "[-a-zA-Z0-9_.]+"
1275 "*Regexp matching domain names.")
1277 (defconst tramp-user-with-domain-regexp
1278 (concat "\\(" tramp-user-regexp "\\)"
1279 tramp-prefix-domain-regexp
1280 "\\(" tramp-domain-regexp "\\)")
1281 "*Regexp matching user names with domain names.")
1283 (defconst tramp-postfix-user-format
1285 "*String matching delimeter between user and host names.
1286 Used in `tramp-make-tramp-file-name'.")
1288 (defconst tramp-postfix-user-regexp
1289 (regexp-quote tramp-postfix-user-format)
1290 "*Regexp matching delimeter between user and host names.
1291 Derived from `tramp-postfix-user-format'.")
1293 (defconst tramp-host-regexp
1294 "[a-zA-Z0-9_.-]+"
1295 "*Regexp matching host names.")
1297 (defconst tramp-prefix-ipv6-format
1298 (cond ((equal tramp-syntax 'ftp) "[")
1299 ((equal tramp-syntax 'sep) "")
1300 ((equal tramp-syntax 'url) "[")
1301 (t (error "Wrong `tramp-syntax' defined")))
1302 "*String matching left hand side of IPv6 addresses.
1303 Used in `tramp-make-tramp-file-name'.")
1305 (defconst tramp-prefix-ipv6-regexp
1306 (regexp-quote tramp-prefix-ipv6-format)
1307 "*Regexp matching left hand side of IPv6 addresses.
1308 Derived from `tramp-prefix-ipv6-format'.")
1310 ;; The following regexp is a bit sloppy. But it shall serve our
1311 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1312 ;; "::ffff:192.168.0.1".
1313 (defconst tramp-ipv6-regexp
1314 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1315 "*Regexp matching IPv6 addresses.")
1317 (defconst tramp-postfix-ipv6-format
1318 (cond ((equal tramp-syntax 'ftp) "]")
1319 ((equal tramp-syntax 'sep) "")
1320 ((equal tramp-syntax 'url) "]")
1321 (t (error "Wrong `tramp-syntax' defined")))
1322 "*String matching right hand side of IPv6 addresses.
1323 Used in `tramp-make-tramp-file-name'.")
1325 (defconst tramp-postfix-ipv6-regexp
1326 (regexp-quote tramp-postfix-ipv6-format)
1327 "*Regexp matching right hand side of IPv6 addresses.
1328 Derived from `tramp-postfix-ipv6-format'.")
1330 (defconst tramp-prefix-port-format
1331 (cond ((equal tramp-syntax 'ftp) "#")
1332 ((equal tramp-syntax 'sep) "#")
1333 ((equal tramp-syntax 'url) ":")
1334 (t (error "Wrong `tramp-syntax' defined")))
1335 "*String matching delimeter between host names and port numbers.")
1337 (defconst tramp-prefix-port-regexp
1338 (regexp-quote tramp-prefix-port-format)
1339 "*Regexp matching delimeter between host names and port numbers.
1340 Derived from `tramp-prefix-port-format'.")
1342 (defconst tramp-port-regexp
1343 "[0-9]+"
1344 "*Regexp matching port numbers.")
1346 (defconst tramp-host-with-port-regexp
1347 (concat "\\(" tramp-host-regexp "\\)"
1348 tramp-prefix-port-regexp
1349 "\\(" tramp-port-regexp "\\)")
1350 "*Regexp matching host names with port numbers.")
1352 (defconst tramp-postfix-host-format
1353 (cond ((equal tramp-syntax 'ftp) ":")
1354 ((equal tramp-syntax 'sep) "]")
1355 ((equal tramp-syntax 'url) "")
1356 (t (error "Wrong `tramp-syntax' defined")))
1357 "*String matching delimeter between host names and localnames.
1358 Used in `tramp-make-tramp-file-name'.")
1360 (defconst tramp-postfix-host-regexp
1361 (regexp-quote tramp-postfix-host-format)
1362 "*Regexp matching delimeter between host names and localnames.
1363 Derived from `tramp-postfix-host-format'.")
1365 (defconst tramp-localname-regexp
1366 ".*$"
1367 "*Regexp matching localnames.")
1369 ;; File name format.
1371 (defconst tramp-file-name-structure
1372 (list
1373 (concat
1374 tramp-prefix-regexp
1375 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1376 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1377 "\\(" "\\(" tramp-host-regexp
1378 "\\|"
1379 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1380 tramp-postfix-ipv6-regexp "\\)"
1381 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1382 tramp-postfix-host-regexp
1383 "\\(" tramp-localname-regexp "\\)")
1384 2 4 5 8)
1386 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1387 the Tramp file name structure.
1389 The first element REGEXP is a regular expression matching a Tramp file
1390 name. The regex should contain parentheses around the method name,
1391 the user name, the host name, and the file name parts.
1393 The second element METHOD is a number, saying which pair of
1394 parentheses matches the method name. The third element USER is
1395 similar, but for the user name. The fourth element HOST is similar,
1396 but for the host name. The fifth element FILE is for the file name.
1397 These numbers are passed directly to `match-string', which see. That
1398 means the opening parentheses are counted to identify the pair.
1400 See also `tramp-file-name-regexp'.")
1402 ;;;###autoload
1403 (defconst tramp-file-name-regexp-unified
1404 "\\`/\\([^[/:]+\\|[^/]+]\\):"
1405 "Value for `tramp-file-name-regexp' for unified remoting.
1406 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1407 Tramp. See `tramp-file-name-structure' for more explanations.")
1409 ;;;###autoload
1410 (defconst tramp-file-name-regexp-separate
1411 "\\`/\\[.*\\]"
1412 "Value for `tramp-file-name-regexp' for separate remoting.
1413 XEmacs uses a separate filename syntax for Tramp and EFS.
1414 See `tramp-file-name-structure' for more explanations.")
1416 ;;;###autoload
1417 (defconst tramp-file-name-regexp-url
1418 "\\`/[^/:]+://"
1419 "Value for `tramp-file-name-regexp' for URL-like remoting.
1420 See `tramp-file-name-structure' for more explanations.")
1422 ;;;###autoload
1423 (defconst tramp-file-name-regexp
1424 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1425 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1426 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1427 (t (error "Wrong `tramp-syntax' defined")))
1428 "*Regular expression matching file names handled by Tramp.
1429 This regexp should match Tramp file names but no other file names.
1430 \(When tramp.el is loaded, this regular expression is prepended to
1431 `file-name-handler-alist', and that is searched sequentially. Thus,
1432 if the Tramp entry appears rather early in the `file-name-handler-alist'
1433 and is a bit too general, then some files might be considered Tramp
1434 files which are not really Tramp files.
1436 Please note that the entry in `file-name-handler-alist' is made when
1437 this file (tramp.el) is loaded. This means that this variable must be set
1438 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1439 updated after changing this variable.
1441 Also see `tramp-file-name-structure'.")
1443 ;;;###autoload
1444 (defconst tramp-root-regexp
1445 (if (memq system-type '(cygwin windows-nt))
1446 "\\`\\([a-zA-Z]:\\)?/"
1447 "\\`/")
1448 "Beginning of an incomplete Tramp file name.
1449 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1450 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1452 ;;;###autoload
1453 (defconst tramp-completion-file-name-regexp-unified
1454 (concat tramp-root-regexp "[^/]*\\'")
1455 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1456 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1457 See `tramp-file-name-structure' for more explanations.")
1459 ;;;###autoload
1460 (defconst tramp-completion-file-name-regexp-separate
1461 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1462 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1463 XEmacs uses a separate filename syntax for Tramp and EFS.
1464 See `tramp-file-name-structure' for more explanations.")
1466 ;;;###autoload
1467 (defconst tramp-completion-file-name-regexp-url
1468 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1469 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1470 See `tramp-file-name-structure' for more explanations.")
1472 ;;;###autoload
1473 (defconst tramp-completion-file-name-regexp
1474 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1475 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1476 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1477 (t (error "Wrong `tramp-syntax' defined")))
1478 "*Regular expression matching file names handled by Tramp completion.
1479 This regexp should match partial Tramp file names only.
1481 Please note that the entry in `file-name-handler-alist' is made when
1482 this file (tramp.el) is loaded. This means that this variable must be set
1483 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1484 updated after changing this variable.
1486 Also see `tramp-file-name-structure'.")
1488 (defconst tramp-actions-before-shell
1489 '((tramp-login-prompt-regexp tramp-action-login)
1490 (tramp-password-prompt-regexp tramp-action-password)
1491 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1492 (shell-prompt-pattern tramp-action-succeed)
1493 (tramp-shell-prompt-pattern tramp-action-succeed)
1494 (tramp-yesno-prompt-regexp tramp-action-yesno)
1495 (tramp-yn-prompt-regexp tramp-action-yn)
1496 (tramp-terminal-prompt-regexp tramp-action-terminal)
1497 (tramp-process-alive-regexp tramp-action-process-alive))
1498 "List of pattern/action pairs.
1499 Whenever a pattern matches, the corresponding action is performed.
1500 Each item looks like (PATTERN ACTION).
1502 The PATTERN should be a symbol, a variable. The value of this
1503 variable gives the regular expression to search for. Note that the
1504 regexp must match at the end of the buffer, \"\\'\" is implicitly
1505 appended to it.
1507 The ACTION should also be a symbol, but a function. When the
1508 corresponding PATTERN matches, the ACTION function is called.")
1510 (defconst tramp-actions-copy-out-of-band
1511 '((tramp-password-prompt-regexp tramp-action-password)
1512 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1513 (tramp-copy-failed-regexp tramp-action-permission-denied)
1514 (tramp-process-alive-regexp tramp-action-out-of-band))
1515 "List of pattern/action pairs.
1516 This list is used for copying/renaming with out-of-band methods.
1518 See `tramp-actions-before-shell' for more info.")
1520 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1521 ;; known to have a bug in `process-send-string'; some ssh connections appear
1522 ;; to drop bytes when data is sent too quickly. There is also a connection
1523 ;; buffer local variable, which is computed depending on remote host properties
1524 ;; when `tramp-chunksize' is zero or nil.
1525 (defcustom tramp-chunksize
1526 (when (and (not (featurep 'xemacs))
1527 (memq system-type '(hpux)))
1528 500)
1529 ;; Parentheses in docstring starting at beginning of line are escaped.
1530 ;; Fontification is messed up when
1531 ;; `open-paren-in-column-0-is-defun-start' set to t.
1532 "*If non-nil, chunksize for sending input to local process.
1533 It is necessary only on systems which have a buggy `process-send-string'
1534 implementation. The necessity, whether this variable must be set, can be
1535 checked via the following code:
1537 (with-temp-buffer
1538 (let* ((user \"xxx\") (host \"yyy\")
1539 (init 0) (step 50)
1540 (sent init) (received init))
1541 (while (= sent received)
1542 (setq sent (+ sent step))
1543 (erase-buffer)
1544 (let ((proc (start-process (buffer-name) (current-buffer)
1545 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1546 (when (memq (process-status proc) '(run open))
1547 (process-send-string proc (make-string sent ?\\ ))
1548 (process-send-eof proc)
1549 (process-send-eof proc))
1550 (while (not (progn (goto-char (point-min))
1551 (re-search-forward \"\\\\w+\" (point-max) t)))
1552 (accept-process-output proc 1))
1553 (when (memq (process-status proc) '(run open))
1554 (setq received (string-to-number (match-string 0)))
1555 (delete-process proc)
1556 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1557 (sit-for 0))))
1558 (if (> sent (+ init step))
1559 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1560 (- sent step))
1561 (message \"Test does not work\")
1562 (display-buffer (current-buffer))
1563 (sit-for 30))))
1565 In the Emacs normally running Tramp, evaluate the above code
1566 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1567 respectively). You can do this, for example, by pasting it into
1568 the `*scratch*' buffer and then hitting C-j with the cursor after the
1569 last closing parenthesis. Note that it works only if you have configured
1570 \"ssh\" to run without password query, see ssh-agent(1).
1572 You will see the number of bytes sent successfully to the remote host.
1573 If that number exceeds 1000, you can stop the execution by hitting
1574 C-g, because your Emacs is likely clean.
1576 When it is necessary to set `tramp-chunksize', you might consider to
1577 use an out-of-the-band method (like \"scp\") instead of an internal one
1578 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
1579 performance.
1581 If your Emacs is buggy, the code stops and gives you an indication
1582 about the value `tramp-chunksize' should be set. Maybe you could just
1583 experiment a bit, e.g. changing the values of `init' and `step'
1584 in the third line of the code.
1586 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1587 this variable to be set as well."
1588 :group 'tramp
1589 :type '(choice (const nil) integer))
1591 ;; Logging in to a remote host normally requires obtaining a pty. But
1592 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1593 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1594 ;; for an override of the system default.
1595 (defcustom tramp-process-connection-type t
1596 "Overrides `process-connection-type' for connections from Tramp.
1597 Tramp binds process-connection-type to the value given here before
1598 opening a connection to a remote host."
1599 :group 'tramp
1600 :type '(choice (const nil) (const t) (const pty)))
1602 (defcustom tramp-completion-reread-directory-timeout 10
1603 "Defines seconds since last remote command before rereading a directory.
1604 A remote directory might have changed its contents. In order to
1605 make it visible during file name completion in the minibuffer,
1606 Tramp flushes its cache and rereads the directory contents when
1607 more than `tramp-completion-reread-directory-timeout' seconds
1608 have been gone since last remote command execution. A value of 0
1609 would require an immediate reread during filename completion, nil
1610 means to use always cached values for the directory contents."
1611 :group 'tramp
1612 :type '(choice (const nil) integer))
1614 ;;; Internal Variables:
1616 (defvar tramp-current-method nil
1617 "Connection method for this *tramp* buffer.")
1619 (defvar tramp-current-user nil
1620 "Remote login name for this *tramp* buffer.")
1622 (defvar tramp-current-host nil
1623 "Remote host for this *tramp* buffer.")
1625 (defconst tramp-uudecode
1626 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1627 cat /tmp/tramp.$$
1628 rm -f /tmp/tramp.$$"
1629 "Shell function to implement `uudecode' to standard output.
1630 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1631 for this or `uudecode -p', but some systems don't, and for them
1632 we have this shell function.")
1634 (defconst tramp-perl-file-truename
1635 "%s -e '
1636 use File::Spec;
1637 use Cwd \"realpath\";
1639 sub recursive {
1640 my ($volume, @dirs) = @_;
1641 my $real = realpath(File::Spec->catpath(
1642 $volume, File::Spec->catdir(@dirs), \"\"));
1643 if ($real) {
1644 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1645 return ($vol, File::Spec->splitdir($dir));
1647 else {
1648 my $last = pop(@dirs);
1649 ($volume, @dirs) = recursive($volume, @dirs);
1650 push(@dirs, $last);
1651 return ($volume, @dirs);
1655 $result = realpath($ARGV[0]);
1656 if (!$result) {
1657 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1658 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1660 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1663 if ($ARGV[0] =~ /\\/$/) {
1664 $result = $result . \"/\";
1667 print \"\\\"$result\\\"\\n\";
1668 ' \"$1\" 2>/dev/null"
1669 "Perl script to produce output suitable for use with `file-truename'
1670 on the remote file system.
1671 Escape sequence %s is replaced with name of Perl binary.
1672 This string is passed to `format', so percent characters need to be doubled.")
1674 (defconst tramp-perl-file-name-all-completions
1675 "%s -e 'sub case {
1676 my $str = shift;
1677 if ($ARGV[2]) {
1678 return lc($str);
1680 else {
1681 return $str;
1684 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1685 @files = readdir(d); closedir(d);
1686 foreach $f (@files) {
1687 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1688 if (-d \"$ARGV[0]/$f\") {
1689 print \"$f/\\n\";
1691 else {
1692 print \"$f\\n\";
1696 print \"ok\\n\"
1697 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1698 "Perl script to produce output suitable for use with
1699 `file-name-all-completions' on the remote file system. Escape
1700 sequence %s is replaced with name of Perl binary. This string is
1701 passed to `format', so percent characters need to be doubled.")
1703 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1704 ;; output. If you are hacking on this, note that you get *no* output
1705 ;; unless this spits out a complete line, including the '\n' at the
1706 ;; end.
1707 ;; The device number is returned as "-1", because there will be a virtual
1708 ;; device number set in `tramp-handle-file-attributes'.
1709 (defconst tramp-perl-file-attributes
1710 "%s -e '
1711 @stat = lstat($ARGV[0]);
1712 if (!@stat) {
1713 print \"nil\\n\";
1714 exit 0;
1716 if (($stat[2] & 0170000) == 0120000)
1718 $type = readlink($ARGV[0]);
1719 $type = \"\\\"$type\\\"\";
1721 elsif (($stat[2] & 0170000) == 040000)
1723 $type = \"t\";
1725 else
1727 $type = \"nil\"
1729 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1730 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1731 printf(
1732 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1733 $type,
1734 $stat[3],
1735 $uid,
1736 $gid,
1737 $stat[8] >> 16 & 0xffff,
1738 $stat[8] & 0xffff,
1739 $stat[9] >> 16 & 0xffff,
1740 $stat[9] & 0xffff,
1741 $stat[10] >> 16 & 0xffff,
1742 $stat[10] & 0xffff,
1743 $stat[7],
1744 $stat[2],
1745 $stat[1] >> 16 & 0xffff,
1746 $stat[1] & 0xffff
1747 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1748 "Perl script to produce output suitable for use with `file-attributes'
1749 on the remote file system.
1750 Escape sequence %s is replaced with name of Perl binary.
1751 This string is passed to `format', so percent characters need to be doubled.")
1753 (defconst tramp-perl-directory-files-and-attributes
1754 "%s -e '
1755 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1756 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1757 @list = readdir(DIR);
1758 closedir(DIR);
1759 $n = scalar(@list);
1760 printf(\"(\\n\");
1761 for($i = 0; $i < $n; $i++)
1763 $filename = $list[$i];
1764 @stat = lstat($filename);
1765 if (($stat[2] & 0170000) == 0120000)
1767 $type = readlink($filename);
1768 $type = \"\\\"$type\\\"\";
1770 elsif (($stat[2] & 0170000) == 040000)
1772 $type = \"t\";
1774 else
1776 $type = \"nil\"
1778 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1779 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1780 printf(
1781 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1782 $filename,
1783 $type,
1784 $stat[3],
1785 $uid,
1786 $gid,
1787 $stat[8] >> 16 & 0xffff,
1788 $stat[8] & 0xffff,
1789 $stat[9] >> 16 & 0xffff,
1790 $stat[9] & 0xffff,
1791 $stat[10] >> 16 & 0xffff,
1792 $stat[10] & 0xffff,
1793 $stat[7],
1794 $stat[2],
1795 $stat[1] >> 16 & 0xffff,
1796 $stat[1] & 0xffff,
1797 $stat[0] >> 16 & 0xffff,
1798 $stat[0] & 0xffff);
1800 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1801 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1802 output.
1803 Escape sequence %s is replaced with name of Perl binary.
1804 This string is passed to `format', so percent characters need to be doubled.")
1806 ;; ;; These two use uu encoding.
1807 ;; (defvar tramp-perl-encode "%s -e'\
1808 ;; print qq(begin 644 xxx\n);
1809 ;; my $s = q();
1810 ;; my $res = q();
1811 ;; while (read(STDIN, $s, 45)) {
1812 ;; print pack(q(u), $s);
1813 ;; }
1814 ;; print qq(`\n);
1815 ;; print qq(end\n);
1816 ;; '"
1817 ;; "Perl program to use for encoding a file.
1818 ;; Escape sequence %s is replaced with name of Perl binary.")
1820 ;; (defvar tramp-perl-decode "%s -ne '
1821 ;; print unpack q(u), $_;
1822 ;; '"
1823 ;; "Perl program to use for decoding a file.
1824 ;; Escape sequence %s is replaced with name of Perl binary.")
1826 ;; These two use base64 encoding.
1827 (defconst tramp-perl-encode-with-module
1828 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1829 "Perl program to use for encoding a file.
1830 Escape sequence %s is replaced with name of Perl binary.
1831 This string is passed to `format', so percent characters need to be doubled.
1832 This implementation requires the MIME::Base64 Perl module to be installed
1833 on the remote host.")
1835 (defconst tramp-perl-decode-with-module
1836 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1837 "Perl program to use for decoding a file.
1838 Escape sequence %s is replaced with name of Perl binary.
1839 This string is passed to `format', so percent characters need to be doubled.
1840 This implementation requires the MIME::Base64 Perl module to be installed
1841 on the remote host.")
1843 (defconst tramp-perl-encode
1844 "%s -e '
1845 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1846 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1847 # Free Software Foundation, Inc.
1848 use strict;
1850 my %%trans = do {
1851 my $i = 0;
1852 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1853 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1856 binmode(\\*STDIN);
1858 # We read in chunks of 54 bytes, to generate output lines
1859 # of 72 chars (plus end of line)
1860 $/ = \\54;
1862 while (my $data = <STDIN>) {
1863 my $pad = q();
1865 # Only for the last chunk, and only if did not fill the last three-byte packet
1866 if (eof) {
1867 my $mod = length($data) %% 3;
1868 $pad = q(=) x (3 - $mod) if $mod;
1871 # Not the fastest method, but it is simple: unpack to binary string, split
1872 # by groups of 6 bits and convert back from binary to byte; then map into
1873 # the translation table
1874 print
1875 join q(),
1876 map($trans{$_},
1877 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1878 $pad,
1879 qq(\\n);
1880 }' 2>/dev/null"
1881 "Perl program to use for encoding a file.
1882 Escape sequence %s is replaced with name of Perl binary.
1883 This string is passed to `format', so percent characters need to be doubled.")
1885 (defconst tramp-perl-decode
1886 "%s -e '
1887 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1888 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1889 # Free Software Foundation, Inc.
1890 use strict;
1892 my %%trans = do {
1893 my $i = 0;
1894 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1895 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1898 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1900 binmode(\\*STDOUT);
1902 # We are going to accumulate into $pending to accept any line length
1903 # (we do not check they are <= 76 chars as the RFC says)
1904 my $pending = q();
1906 while (my $data = <STDIN>) {
1907 chomp $data;
1909 # If we find one or two =, we have reached the end and
1910 # any following data is to be discarded
1911 my $finished = $data =~ s/(==?).*/$1/;
1912 $pending .= $data;
1914 my $len = length($pending);
1915 my $chunk = substr($pending, 0, $len & ~3);
1916 $pending = substr($pending, $len & ~3 + 1);
1918 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1919 # split in 8-bit chunks and convert back to char.
1920 print join q(),
1921 map $bytes{$_},
1922 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1924 last if $finished;
1925 }' 2>/dev/null"
1926 "Perl program to use for decoding a file.
1927 Escape sequence %s is replaced with name of Perl binary.
1928 This string is passed to `format', so percent characters need to be doubled.")
1930 (defconst tramp-vc-registered-read-file-names
1931 "echo \"(\"
1932 for file in \"$@\"; do
1933 if %s $file; then
1934 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1935 else
1936 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1938 if %s $file; then
1939 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1940 else
1941 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1943 done
1944 echo \")\""
1945 "Script to check existence of VC related files.
1946 It must be send formatted with two strings; the tests for file
1947 existence, and file readability.")
1949 (defconst tramp-file-mode-type-map
1950 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1951 (1 . "p") ; fifo
1952 (2 . "c") ; character device
1953 (3 . "m") ; multiplexed character device (v7)
1954 (4 . "d") ; directory
1955 (5 . "?") ; Named special file (XENIX)
1956 (6 . "b") ; block device
1957 (7 . "?") ; multiplexed block device (v7)
1958 (8 . "-") ; regular file
1959 (9 . "n") ; network special file (HP-UX)
1960 (10 . "l") ; symlink
1961 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1962 (12 . "s") ; socket
1963 (13 . "D") ; door special (Solaris)
1964 (14 . "w")) ; whiteout (BSD)
1965 "A list of file types returned from the `stat' system call.
1966 This is used to map a mode number to a permission string.")
1968 ;; New handlers should be added here. The following operations can be
1969 ;; handled using the normal primitives: file-name-sans-versions,
1970 ;; get-file-buffer.
1971 (defconst tramp-file-name-handler-alist
1972 '((load . tramp-handle-load)
1973 (make-symbolic-link . tramp-handle-make-symbolic-link)
1974 (file-name-as-directory . tramp-handle-file-name-as-directory)
1975 (file-name-directory . tramp-handle-file-name-directory)
1976 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1977 (file-truename . tramp-handle-file-truename)
1978 (file-exists-p . tramp-handle-file-exists-p)
1979 (file-directory-p . tramp-handle-file-directory-p)
1980 (file-executable-p . tramp-handle-file-executable-p)
1981 (file-readable-p . tramp-handle-file-readable-p)
1982 (file-regular-p . tramp-handle-file-regular-p)
1983 (file-symlink-p . tramp-handle-file-symlink-p)
1984 (file-writable-p . tramp-handle-file-writable-p)
1985 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1986 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1987 (file-attributes . tramp-handle-file-attributes)
1988 (file-modes . tramp-handle-file-modes)
1989 (directory-files . tramp-handle-directory-files)
1990 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1991 (file-name-all-completions . tramp-handle-file-name-all-completions)
1992 (file-name-completion . tramp-handle-file-name-completion)
1993 (add-name-to-file . tramp-handle-add-name-to-file)
1994 (copy-file . tramp-handle-copy-file)
1995 (copy-directory . tramp-handle-copy-directory)
1996 (rename-file . tramp-handle-rename-file)
1997 (set-file-modes . tramp-handle-set-file-modes)
1998 (set-file-times . tramp-handle-set-file-times)
1999 (make-directory . tramp-handle-make-directory)
2000 (delete-directory . tramp-handle-delete-directory)
2001 (delete-file . tramp-handle-delete-file)
2002 (directory-file-name . tramp-handle-directory-file-name)
2003 ;; `executable-find' is not official yet.
2004 (executable-find . tramp-handle-executable-find)
2005 (start-file-process . tramp-handle-start-file-process)
2006 (process-file . tramp-handle-process-file)
2007 (shell-command . tramp-handle-shell-command)
2008 (insert-directory . tramp-handle-insert-directory)
2009 (expand-file-name . tramp-handle-expand-file-name)
2010 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2011 (file-local-copy . tramp-handle-file-local-copy)
2012 (file-remote-p . tramp-handle-file-remote-p)
2013 (insert-file-contents . tramp-handle-insert-file-contents)
2014 (insert-file-contents-literally
2015 . tramp-handle-insert-file-contents-literally)
2016 (write-region . tramp-handle-write-region)
2017 (find-backup-file-name . tramp-handle-find-backup-file-name)
2018 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2019 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2020 (dired-compress-file . tramp-handle-dired-compress-file)
2021 (dired-recursive-delete-directory
2022 . tramp-handle-dired-recursive-delete-directory)
2023 (dired-uncache . tramp-handle-dired-uncache)
2024 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2025 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2026 (vc-registered . tramp-handle-vc-registered))
2027 "Alist of handler functions.
2028 Operations not mentioned here will be handled by the normal Emacs functions.")
2030 ;; Handlers for partial Tramp file names. For Emacs just
2031 ;; `file-name-all-completions' is needed.
2032 ;;;###autoload
2033 (defconst tramp-completion-file-name-handler-alist
2034 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2035 (file-name-completion . tramp-completion-handle-file-name-completion))
2036 "Alist of completion handler functions.
2037 Used for file names matching `tramp-file-name-regexp'. Operations not
2038 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2039 normal Emacs functions.")
2041 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2042 (defvar tramp-foreign-file-name-handler-alist
2043 ;; (identity . tramp-sh-file-name-handler) should always be the last
2044 ;; entry, because `identity' always matches.
2045 '((identity . tramp-sh-file-name-handler))
2046 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2047 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2048 calling HANDLER.")
2050 ;;; Internal functions which must come first:
2052 (defsubst tramp-debug-message (vec fmt-string &rest args)
2053 "Append message to debug buffer.
2054 Message is formatted with FMT-STRING as control string and the remaining
2055 ARGS to actually emit the message (if applicable)."
2056 (when (get-buffer (tramp-buffer-name vec))
2057 (with-current-buffer (tramp-get-debug-buffer vec)
2058 (goto-char (point-max))
2059 ;; Headline.
2060 (when (bobp)
2061 (insert
2062 (format
2063 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2064 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2065 emacs-version tramp-version)))
2066 (unless (bolp)
2067 (insert "\n"))
2068 ;; Timestamp.
2069 (let ((now (current-time)))
2070 (insert (format-time-string "%T." now))
2071 (insert (format "%06d " (nth 2 now))))
2072 ;; Calling function.
2073 (let ((btn 1) btf fn)
2074 (while (not fn)
2075 (setq btf (nth 1 (backtrace-frame btn)))
2076 (if (not btf)
2077 (setq fn "")
2078 (when (symbolp btf)
2079 (setq fn (symbol-name btf))
2080 (unless (and (string-match "^tramp" fn)
2081 (not (string-match
2082 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
2083 fn)))
2084 (setq fn nil)))
2085 (setq btn (1+ btn))))
2086 ;; The following code inserts filename and line number.
2087 ;; Should be deactivated by default, because it is time
2088 ;; consuming.
2089 ; (let ((ffn (find-function-noselect (intern fn))))
2090 ; (insert
2091 ; (format
2092 ; "%s:%d: "
2093 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2094 ; (with-current-buffer (car ffn)
2095 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2096 (insert (format "%s " fn)))
2097 ;; The message.
2098 (insert (apply 'format fmt-string args)))))
2100 (defvar tramp-message-show-message t
2101 "Show Tramp message in the minibuffer.
2102 This variable is used to disable messages from `tramp-error'.
2103 The messages are visible anyway, because an error is raised.")
2105 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2106 "Emit a message depending on verbosity level.
2107 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2108 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2109 less than LEVEL. The message is emitted only if `tramp-verbose' is
2110 greater than or equal to LEVEL.
2112 The message is also logged into the debug buffer when `tramp-verbose'
2113 is greater than or equal 4.
2115 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2116 control string and the remaining ARGS to actually emit the message (if
2117 applicable)."
2118 (condition-case nil
2119 (when (<= level tramp-verbose)
2120 ;; Match data must be preserved!
2121 (save-match-data
2122 ;; Display only when there is a minimum level.
2123 (when (and tramp-message-show-message (<= level 3))
2124 (apply 'message
2125 (concat
2126 (cond
2127 ((= level 0) "")
2128 ((= level 1) "")
2129 ((= level 2) "Warning: ")
2130 (t "Tramp: "))
2131 fmt-string)
2132 args))
2133 ;; Log only when there is a minimum level.
2134 (when (>= tramp-verbose 4)
2135 (when (and vec-or-proc
2136 (processp vec-or-proc)
2137 (buffer-name (process-buffer vec-or-proc)))
2138 (with-current-buffer (process-buffer vec-or-proc)
2139 ;; Translate proc to vec.
2140 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2141 (when (and vec-or-proc (vectorp vec-or-proc))
2142 (apply 'tramp-debug-message
2143 vec-or-proc
2144 (concat (format "(%d) # " level) fmt-string)
2145 args)))))
2146 ;; Suppress all errors.
2147 (error nil)))
2149 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2150 "Emit an error.
2151 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2152 signal identifier to be raised, remaining args passed to
2153 `tramp-message'. Finally, signal SIGNAL is raised."
2154 (let (tramp-message-show-message)
2155 (tramp-message
2156 vec-or-proc 1 "%s"
2157 (error-message-string
2158 (list signal
2159 (get signal 'error-message)
2160 (apply 'format fmt-string args))))
2161 (signal signal (list (apply 'format fmt-string args)))))
2163 (defsubst tramp-error-with-buffer
2164 (buffer vec-or-proc signal fmt-string &rest args)
2165 "Emit an error, and show BUFFER.
2166 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2167 an input event arrives. The other arguments are passed to `tramp-error'."
2168 (save-window-excursion
2169 (unwind-protect
2170 (apply 'tramp-error vec-or-proc signal fmt-string args)
2171 (when (and vec-or-proc (not (zerop tramp-verbose)))
2172 (let ((enable-recursive-minibuffers t))
2173 (pop-to-buffer
2174 (or (and (bufferp buffer) buffer)
2175 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2176 (tramp-get-buffer vec-or-proc)))
2177 (sit-for 30))))))
2179 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2180 "Parse a Tramp filename and make components available in the body.
2182 First arg FILENAME is evaluated and dissected into its components.
2183 Second arg VAR is a symbol. It is used as a variable name to hold
2184 the filename structure. It is also used as a prefix for the variables
2185 holding the components. For example, if VAR is the symbol `foo', then
2186 `foo' will be bound to the whole structure, `foo-method' will be bound to
2187 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2189 Remaining args are Lisp expressions to be evaluated (inside an implicit
2190 `progn').
2192 If VAR is nil, then we bind `v' to the structure and `method', `user',
2193 `host', `localname' to the components."
2194 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2195 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2196 (tramp-file-name-method ,(or var 'v)))
2197 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2198 (tramp-file-name-user ,(or var 'v)))
2199 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2200 (tramp-file-name-host ,(or var 'v)))
2201 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2202 (tramp-file-name-localname ,(or var 'v))))
2203 ,@body))
2205 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2206 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2207 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2209 (defmacro with-file-property (vec file property &rest body)
2210 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2211 FILE must be a local file name on a connection identified via VEC."
2212 `(if (file-name-absolute-p ,file)
2213 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2214 (when (eq value 'undef)
2215 ;; We cannot pass @body as parameter to
2216 ;; `tramp-set-file-property' because it mangles our
2217 ;; debug messages.
2218 (setq value (progn ,@body))
2219 (tramp-set-file-property ,vec ,file ,property value))
2220 value)
2221 ,@body))
2223 (put 'with-file-property 'lisp-indent-function 3)
2224 (put 'with-file-property 'edebug-form-spec t)
2225 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2227 (defmacro with-connection-property (key property &rest body)
2228 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2229 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2230 (when (eq value 'undef)
2231 ;; We cannot pass ,@body as parameter to
2232 ;; `tramp-set-connection-property' because it mangles our debug
2233 ;; messages.
2234 (setq value (progn ,@body))
2235 (tramp-set-connection-property ,key ,property value))
2236 value))
2238 (put 'with-connection-property 'lisp-indent-function 2)
2239 (put 'with-connection-property 'edebug-form-spec t)
2240 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2242 (eval-and-compile ; silence compiler
2243 (if (memq system-type '(cygwin windows-nt))
2244 (defun tramp-drop-volume-letter (name)
2245 "Cut off unnecessary drive letter from file NAME.
2246 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2247 locally on a remote file name. When the local system is a W32 system
2248 but the remote system is Unix, this introduces a superfluous drive
2249 letter into the file name. This function removes it."
2250 (save-match-data
2251 (if (string-match tramp-root-regexp name)
2252 (replace-match "/" nil t name)
2253 name)))
2255 (defalias 'tramp-drop-volume-letter 'identity)))
2257 (defsubst tramp-make-tramp-temp-file (vec)
2258 "Create a temporary file on the remote host identified by VEC.
2259 Return the local name of the temporary file."
2260 (let ((prefix
2261 (tramp-make-tramp-file-name
2262 (tramp-file-name-method vec)
2263 (tramp-file-name-user vec)
2264 (tramp-file-name-host vec)
2265 (tramp-drop-volume-letter
2266 (expand-file-name
2267 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2268 result)
2269 (while (not result)
2270 ;; `make-temp-file' would be the natural choice for
2271 ;; implementation. But it calls `write-region' internally,
2272 ;; which also needs a temporary file - we would end in an
2273 ;; infinite loop.
2274 (setq result (make-temp-name prefix))
2275 (if (file-exists-p result)
2276 (setq result nil)
2277 ;; This creates the file by side effect.
2278 (set-file-times result)
2279 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2281 ;; Return the local part.
2282 (with-parsed-tramp-file-name result nil localname)))
2285 ;;; Config Manipulation Functions:
2287 (defun tramp-set-completion-function (method function-list)
2288 "Sets the list of completion functions for METHOD.
2289 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2290 The FUNCTION is intended to parse FILE according its syntax.
2291 It might be a predefined FUNCTION, or a user defined FUNCTION.
2292 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2293 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2294 and `tramp-parse-netrc'.
2296 Example:
2298 (tramp-set-completion-function
2299 \"ssh\"
2300 '((tramp-parse-sconfig \"/etc/ssh_config\")
2301 (tramp-parse-sconfig \"~/.ssh/config\")))"
2303 (let ((r function-list)
2304 (v function-list))
2305 (setq tramp-completion-function-alist
2306 (delete (assoc method tramp-completion-function-alist)
2307 tramp-completion-function-alist))
2309 (while v
2310 ;; Remove double entries.
2311 (when (member (car v) (cdr v))
2312 (setcdr v (delete (car v) (cdr v))))
2313 ;; Check for function and file or registry key.
2314 (unless (and (functionp (nth 0 (car v)))
2315 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2316 ;; Windows registry.
2317 (and (memq system-type '(cygwin windows-nt))
2318 (zerop
2319 (tramp-local-call-process
2320 "reg" nil nil nil "query" (nth 1 (car v)))))
2321 ;; Configuration file.
2322 (file-exists-p (nth 1 (car v)))))
2323 (setq r (delete (car v) r)))
2324 (setq v (cdr v)))
2326 (when r
2327 (add-to-list 'tramp-completion-function-alist
2328 (cons method r)))))
2330 (defun tramp-get-completion-function (method)
2331 "Returns a list of completion functions for METHOD.
2332 For definition of that list see `tramp-set-completion-function'."
2333 (cons
2334 ;; Hosts visited once shall be remembered.
2335 `(tramp-parse-connection-properties ,method)
2336 ;; The method related defaults.
2337 (cdr (assoc method tramp-completion-function-alist))))
2340 ;;; Fontification of `read-file-name':
2342 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2343 (defvar tramp-rfn-eshadow-overlay)
2344 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2346 (defun tramp-rfn-eshadow-setup-minibuffer ()
2347 "Set up a minibuffer for `file-name-shadow-mode'.
2348 Adds another overlay hiding filename parts according to Tramp's
2349 special handling of `substitute-in-file-name'."
2350 (when (symbol-value 'minibuffer-completing-file-name)
2351 (setq tramp-rfn-eshadow-overlay
2352 (funcall (symbol-function 'make-overlay)
2353 (funcall (symbol-function 'minibuffer-prompt-end))
2354 (funcall (symbol-function 'minibuffer-prompt-end))))
2355 ;; Copy rfn-eshadow-overlay properties.
2356 (let ((props (funcall (symbol-function 'overlay-properties)
2357 (symbol-value 'rfn-eshadow-overlay))))
2358 (while props
2359 (funcall (symbol-function 'overlay-put)
2360 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2362 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2363 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2364 'tramp-rfn-eshadow-setup-minibuffer)
2365 (add-hook 'tramp-unload-hook
2366 (lambda ()
2367 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2368 'tramp-rfn-eshadow-setup-minibuffer))))
2370 (defconst tramp-rfn-eshadow-update-overlay-regexp
2371 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2373 (defun tramp-rfn-eshadow-update-overlay ()
2374 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2375 This is intended to be used as a minibuffer `post-command-hook' for
2376 `file-name-shadow-mode'; the minibuffer should have already
2377 been set up by `rfn-eshadow-setup-minibuffer'."
2378 ;; In remote files name, there is a shadowing just for the local part.
2379 (let ((end (or (funcall (symbol-function 'overlay-end)
2380 (symbol-value 'rfn-eshadow-overlay))
2381 (funcall (symbol-function 'minibuffer-prompt-end)))))
2382 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
2383 (save-excursion
2384 (save-restriction
2385 (narrow-to-region
2386 (1+ (or (string-match
2387 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2388 end))
2389 (point-max))
2390 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2391 (rfn-eshadow-update-overlay-hook nil))
2392 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
2393 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
2395 (when (boundp 'rfn-eshadow-update-overlay-hook)
2396 (add-hook 'rfn-eshadow-update-overlay-hook
2397 'tramp-rfn-eshadow-update-overlay)
2398 (add-hook 'tramp-unload-hook
2399 (lambda ()
2400 (remove-hook 'rfn-eshadow-update-overlay-hook
2401 'tramp-rfn-eshadow-update-overlay))))
2404 ;;; Integration of eshell.el:
2406 (eval-when-compile
2407 (defvar eshell-path-env))
2409 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2410 ;; when `default-directory' points to another host.
2411 (defun tramp-eshell-directory-change ()
2412 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2413 (setq eshell-path-env
2414 (if (file-remote-p default-directory)
2415 (with-parsed-tramp-file-name default-directory nil
2416 (mapconcat
2417 'identity
2418 (tramp-get-remote-path v)
2419 ":"))
2420 (getenv "PATH"))))
2422 (eval-after-load "esh-util"
2423 '(progn
2424 (tramp-eshell-directory-change)
2425 (add-hook 'eshell-directory-change-hook
2426 'tramp-eshell-directory-change)
2427 (add-hook 'tramp-unload-hook
2428 (lambda ()
2429 (remove-hook 'eshell-directory-change-hook
2430 'tramp-eshell-directory-change)))))
2433 ;;; File Name Handler Functions:
2435 (defun tramp-handle-make-symbolic-link
2436 (filename linkname &optional ok-if-already-exists)
2437 "Like `make-symbolic-link' for Tramp files.
2438 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2439 the symlink. If LINKNAME is a Tramp file, only the localname component is
2440 used as the target of the symlink.
2442 If LINKNAME is a Tramp file and the localname component is relative, then
2443 it is expanded first, before the localname component is taken. Note that
2444 this can give surprising results if the user/host for the source and
2445 target of the symlink differ."
2446 (with-parsed-tramp-file-name linkname l
2447 (let ((ln (tramp-get-remote-ln l))
2448 (cwd (tramp-run-real-handler
2449 'file-name-directory (list l-localname))))
2450 (unless ln
2451 (tramp-error
2452 l 'file-error
2453 "Making a symbolic link. ln(1) does not exist on the remote host."))
2455 ;; Do the 'confirm if exists' thing.
2456 (when (file-exists-p linkname)
2457 ;; What to do?
2458 (if (or (null ok-if-already-exists) ; not allowed to exist
2459 (and (numberp ok-if-already-exists)
2460 (not (yes-or-no-p
2461 (format
2462 "File %s already exists; make it a link anyway? "
2463 l-localname)))))
2464 (tramp-error
2465 l 'file-already-exists "File %s already exists" l-localname)
2466 (delete-file linkname)))
2468 ;; If FILENAME is a Tramp name, use just the localname component.
2469 (when (tramp-tramp-file-p filename)
2470 (setq filename
2471 (tramp-file-name-localname
2472 (tramp-dissect-file-name (expand-file-name filename)))))
2474 ;; Right, they are on the same host, regardless of user, method, etc.
2475 ;; We now make the link on the remote machine. This will occur as the user
2476 ;; that FILENAME belongs to.
2477 (zerop
2478 (tramp-send-command-and-check
2480 (format
2481 "cd %s && %s -sf %s %s"
2482 (tramp-shell-quote-argument cwd)
2484 (tramp-shell-quote-argument filename)
2485 (tramp-shell-quote-argument l-localname))
2486 t)))))
2488 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2489 "Like `load' for Tramp files."
2490 (with-parsed-tramp-file-name (expand-file-name file) nil
2491 (unless nosuffix
2492 (cond ((file-exists-p (concat file ".elc"))
2493 (setq file (concat file ".elc")))
2494 ((file-exists-p (concat file ".el"))
2495 (setq file (concat file ".el")))))
2496 (when must-suffix
2497 ;; The first condition is always true for absolute file names.
2498 ;; Included for safety's sake.
2499 (unless (or (file-name-directory file)
2500 (string-match "\\.elc?\\'" file))
2501 (tramp-error
2502 v 'file-error
2503 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2504 (unless noerror
2505 (when (not (file-exists-p file))
2506 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2507 (if (not (file-exists-p file))
2509 (unless nomessage (tramp-message v 0 "Loading %s..." file))
2510 (let ((local-copy (file-local-copy file)))
2511 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2512 (unwind-protect
2513 (load local-copy noerror t t)
2514 (delete-file local-copy)))
2515 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
2516 t)))
2518 ;; Localname manipulation functions that grok Tramp localnames...
2519 (defun tramp-handle-file-name-as-directory (file)
2520 "Like `file-name-as-directory' but aware of Tramp files."
2521 ;; `file-name-as-directory' would be sufficient except localname is
2522 ;; the empty string.
2523 (let ((v (tramp-dissect-file-name file t)))
2524 ;; Run the command on the localname portion only.
2525 (tramp-make-tramp-file-name
2526 (tramp-file-name-method v)
2527 (tramp-file-name-user v)
2528 (tramp-file-name-host v)
2529 (tramp-run-real-handler
2530 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2532 (defun tramp-handle-file-name-directory (file)
2533 "Like `file-name-directory' but aware of Tramp files."
2534 ;; Everything except the last filename thing is the directory. We
2535 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2536 ;; the remote file name parts. This is a problem when we are in
2537 ;; file name completion.
2538 (let ((v (tramp-dissect-file-name file t)))
2539 ;; Run the command on the localname portion only.
2540 (tramp-make-tramp-file-name
2541 (tramp-file-name-method v)
2542 (tramp-file-name-user v)
2543 (tramp-file-name-host v)
2544 (tramp-run-real-handler
2545 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2547 (defun tramp-handle-file-name-nondirectory (file)
2548 "Like `file-name-nondirectory' but aware of Tramp files."
2549 (with-parsed-tramp-file-name file nil
2550 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2552 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2553 "Like `file-truename' for Tramp files."
2554 (with-parsed-tramp-file-name (expand-file-name filename) nil
2555 (with-file-property v localname "file-truename"
2556 (let ((result nil)) ; result steps in reverse order
2557 (tramp-message v 4 "Finding true name for `%s'" filename)
2558 (cond
2559 ;; Use GNU readlink --canonicalize-missing where available.
2560 ((tramp-get-remote-readlink v)
2561 (setq result
2562 (tramp-send-command-and-read
2564 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2565 (tramp-get-remote-readlink v)
2566 (tramp-shell-quote-argument localname)))))
2568 ;; Use Perl implementation.
2569 ((and (tramp-get-remote-perl v)
2570 (tramp-get-connection-property v "perl-file-spec" nil)
2571 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2572 (tramp-maybe-send-script
2573 v tramp-perl-file-truename "tramp_perl_file_truename")
2574 (setq result
2575 (tramp-send-command-and-read
2577 (format "tramp_perl_file_truename %s"
2578 (tramp-shell-quote-argument localname)))))
2580 ;; Do it yourself. We bind `directory-sep-char' here for
2581 ;; XEmacs on Windows, which would otherwise use backslash.
2582 (t (let* ((directory-sep-char ?/)
2583 (steps (tramp-compat-split-string localname "/"))
2584 (localnamedir (tramp-run-real-handler
2585 'file-name-as-directory (list localname)))
2586 (is-dir (string= localname localnamedir))
2587 (thisstep nil)
2588 (numchase 0)
2589 ;; Don't make the following value larger than
2590 ;; necessary. People expect an error message in a
2591 ;; timely fashion when something is wrong;
2592 ;; otherwise they might think that Emacs is hung.
2593 ;; Of course, correctness has to come first.
2594 (numchase-limit 20)
2595 symlink-target)
2596 (while (and steps (< numchase numchase-limit))
2597 (setq thisstep (pop steps))
2598 (tramp-message
2599 v 5 "Check %s"
2600 (mapconcat 'identity
2601 (append '("") (reverse result) (list thisstep))
2602 "/"))
2603 (setq symlink-target
2604 (nth 0 (file-attributes
2605 (tramp-make-tramp-file-name
2606 method user host
2607 (mapconcat 'identity
2608 (append '("")
2609 (reverse result)
2610 (list thisstep))
2611 "/")))))
2612 (cond ((string= "." thisstep)
2613 (tramp-message v 5 "Ignoring step `.'"))
2614 ((string= ".." thisstep)
2615 (tramp-message v 5 "Processing step `..'")
2616 (pop result))
2617 ((stringp symlink-target)
2618 ;; It's a symlink, follow it.
2619 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2620 (setq numchase (1+ numchase))
2621 (when (file-name-absolute-p symlink-target)
2622 (setq result nil))
2623 ;; If the symlink was absolute, we'll get a string like
2624 ;; "/user@host:/some/target"; extract the
2625 ;; "/some/target" part from it.
2626 (when (tramp-tramp-file-p symlink-target)
2627 (unless (tramp-equal-remote filename symlink-target)
2628 (tramp-error
2629 v 'file-error
2630 "Symlink target `%s' on wrong host" symlink-target))
2631 (setq symlink-target localname))
2632 (setq steps
2633 (append (tramp-compat-split-string
2634 symlink-target "/")
2635 steps)))
2637 ;; It's a file.
2638 (setq result (cons thisstep result)))))
2639 (when (>= numchase numchase-limit)
2640 (tramp-error
2641 v 'file-error
2642 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2643 (setq result (reverse result))
2644 ;; Combine list to form string.
2645 (setq result
2646 (if result
2647 (mapconcat 'identity (cons "" result) "/")
2648 "/"))
2649 (when (and is-dir (or (string= "" result)
2650 (not (string= (substring result -1) "/"))))
2651 (setq result (concat result "/"))))))
2653 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2654 (tramp-make-tramp-file-name method user host result)))))
2656 ;; Basic functions.
2658 (defun tramp-handle-file-exists-p (filename)
2659 "Like `file-exists-p' for Tramp files."
2660 (with-parsed-tramp-file-name filename nil
2661 (with-file-property v localname "file-exists-p"
2662 (or (not (null (tramp-get-file-property
2663 v localname "file-attributes-integer" nil)))
2664 (not (null (tramp-get-file-property
2665 v localname "file-attributes-string" nil)))
2666 (zerop (tramp-send-command-and-check
2668 (format
2669 "%s %s"
2670 (tramp-get-file-exists-command v)
2671 (tramp-shell-quote-argument localname))))))))
2673 ;; Inodes don't exist for some file systems. Therefore we must
2674 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2675 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2676 ;; performance isn't the major issue given that file transfer will
2677 ;; take time.
2678 (defvar tramp-inodes nil
2679 "Keeps virtual inodes numbers.")
2681 ;; Devices must distinguish physical file systems. The device numbers
2682 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2683 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2684 ;; EFS use device number "-1". In order to be different, we use device number
2685 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2686 (defvar tramp-devices nil
2687 "Keeps virtual device numbers.")
2689 ;; CCC: This should check for an error condition and signal failure
2690 ;; when something goes wrong.
2691 ;; Daniel Pittman <daniel@danann.net>
2692 (defun tramp-handle-file-attributes (filename &optional id-format)
2693 "Like `file-attributes' for Tramp files."
2694 (unless id-format (setq id-format 'integer))
2695 ;; Don't modify `last-coding-system-used' by accident.
2696 (let ((last-coding-system-used last-coding-system-used))
2697 (with-parsed-tramp-file-name (expand-file-name filename) nil
2698 (with-file-property v localname (format "file-attributes-%s" id-format)
2699 (save-excursion
2700 (tramp-convert-file-attributes
2702 (cond
2703 ((tramp-get-remote-stat v)
2704 (tramp-do-file-attributes-with-stat v localname id-format))
2705 ((tramp-get-remote-perl v)
2706 (tramp-do-file-attributes-with-perl v localname id-format))
2708 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2710 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2711 "Implement `file-attributes' for Tramp files using the ls(1) command."
2712 (let (symlinkp dirp
2713 res-inode res-filemodes res-numlinks
2714 res-uid res-gid res-size res-symlink-target)
2715 (tramp-message vec 5 "file attributes with ls: %s" localname)
2716 (tramp-send-command
2718 (format "(%s %s || %s -h %s) && %s %s %s"
2719 (tramp-get-file-exists-command vec)
2720 (tramp-shell-quote-argument localname)
2721 (tramp-get-test-command vec)
2722 (tramp-shell-quote-argument localname)
2723 (tramp-get-ls-command vec)
2724 (if (eq id-format 'integer) "-ildn" "-ild")
2725 (tramp-shell-quote-argument localname)))
2726 ;; parse `ls -l' output ...
2727 (with-current-buffer (tramp-get-buffer vec)
2728 (when (> (buffer-size) 0)
2729 (goto-char (point-min))
2730 ;; ... inode
2731 (setq res-inode
2732 (condition-case err
2733 (read (current-buffer))
2734 (invalid-read-syntax
2735 (when (and (equal (cadr err)
2736 "Integer constant overflow in reader")
2737 (string-match
2738 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2739 (car (cddr err))))
2740 (let* ((big (read (substring (car (cddr err)) 0
2741 (match-beginning 1))))
2742 (small (read (match-string 1 (car (cddr err)))))
2743 (twiddle (/ small 65536)))
2744 (cons (+ big twiddle)
2745 (- small (* twiddle 65536))))))))
2746 ;; ... file mode flags
2747 (setq res-filemodes (symbol-name (read (current-buffer))))
2748 ;; ... number links
2749 (setq res-numlinks (read (current-buffer)))
2750 ;; ... uid and gid
2751 (setq res-uid (read (current-buffer)))
2752 (setq res-gid (read (current-buffer)))
2753 (if (eq id-format 'integer)
2754 (progn
2755 (unless (numberp res-uid) (setq res-uid -1))
2756 (unless (numberp res-gid) (setq res-gid -1)))
2757 (progn
2758 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2759 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2760 ;; ... size
2761 (setq res-size (read (current-buffer)))
2762 ;; From the file modes, figure out other stuff.
2763 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2764 (setq dirp (eq ?d (aref res-filemodes 0)))
2765 ;; if symlink, find out file name pointed to
2766 (when symlinkp
2767 (search-forward "-> ")
2768 (setq res-symlink-target
2769 (buffer-substring (point) (tramp-compat-line-end-position))))
2770 ;; return data gathered
2771 (list
2772 ;; 0. t for directory, string (name linked to) for symbolic
2773 ;; link, or nil.
2774 (or dirp res-symlink-target)
2775 ;; 1. Number of links to file.
2776 res-numlinks
2777 ;; 2. File uid.
2778 res-uid
2779 ;; 3. File gid.
2780 res-gid
2781 ;; 4. Last access time, as a list of two integers. First
2782 ;; integer has high-order 16 bits of time, second has low 16
2783 ;; bits.
2784 ;; 5. Last modification time, likewise.
2785 ;; 6. Last status change time, likewise.
2786 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2787 ;; 7. Size in bytes (-1, if number is out of range).
2788 res-size
2789 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2790 res-filemodes
2791 ;; 9. t if file's gid would change if file were deleted and
2792 ;; recreated. Will be set in `tramp-convert-file-attributes'
2794 ;; 10. inode number.
2795 res-inode
2796 ;; 11. Device number. Will be replaced by a virtual device number.
2798 )))))
2800 (defun tramp-do-file-attributes-with-perl
2801 (vec localname &optional id-format)
2802 "Implement `file-attributes' for Tramp files using a Perl script."
2803 (tramp-message vec 5 "file attributes with perl: %s" localname)
2804 (tramp-maybe-send-script
2805 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2806 (tramp-send-command-and-read
2808 (format "tramp_perl_file_attributes %s %s"
2809 (tramp-shell-quote-argument localname) id-format)))
2811 (defun tramp-do-file-attributes-with-stat
2812 (vec localname &optional id-format)
2813 "Implement `file-attributes' for Tramp files using stat(1) command."
2814 (tramp-message vec 5 "file attributes with stat: %s" localname)
2815 (tramp-send-command-and-read
2817 (format
2818 "((%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)"
2819 (tramp-get-file-exists-command vec)
2820 (tramp-shell-quote-argument localname)
2821 (tramp-get-test-command vec)
2822 (tramp-shell-quote-argument localname)
2823 (tramp-get-remote-stat vec)
2824 (if (eq id-format 'integer) "%u" "\"%U\"")
2825 (if (eq id-format 'integer) "%g" "\"%G\"")
2826 (tramp-shell-quote-argument localname))))
2828 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2829 "Like `set-visited-file-modtime' for Tramp files."
2830 (unless (buffer-file-name)
2831 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2832 (buffer-name)))
2833 (if time-list
2834 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2835 (let ((f (buffer-file-name))
2836 coding-system-used)
2837 (with-parsed-tramp-file-name f nil
2838 (let* ((attr (file-attributes f))
2839 ;; '(-1 65535) means file doesn't exists yet.
2840 (modtime (or (nth 5 attr) '(-1 65535))))
2841 (when (boundp 'last-coding-system-used)
2842 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2843 ;; We use '(0 0) as a don't-know value. See also
2844 ;; `tramp-do-file-attributes-with-ls'.
2845 (if (not (equal modtime '(0 0)))
2846 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2847 (progn
2848 (tramp-send-command
2850 (format "%s -ild %s"
2851 (tramp-get-ls-command v)
2852 (tramp-shell-quote-argument localname)))
2853 (setq attr (buffer-substring (point)
2854 (progn (end-of-line) (point)))))
2855 (tramp-set-file-property
2856 v localname "visited-file-modtime-ild" attr))
2857 (when (boundp 'last-coding-system-used)
2858 (set 'last-coding-system-used coding-system-used))
2859 nil)))))
2861 ;; This function makes the same assumption as
2862 ;; `tramp-handle-set-visited-file-modtime'.
2863 (defun tramp-handle-verify-visited-file-modtime (buf)
2864 "Like `verify-visited-file-modtime' for Tramp files.
2865 At the time `verify-visited-file-modtime' calls this function, we
2866 already know that the buffer is visiting a file and that
2867 `visited-file-modtime' does not return 0. Do not call this
2868 function directly, unless those two cases are already taken care
2869 of."
2870 (with-current-buffer buf
2871 ;; There is no file visiting the buffer, or the buffer has no
2872 ;; recorded last modification time.
2873 (if (or (not (buffer-file-name))
2874 (eq (visited-file-modtime) 0))
2876 (let ((f (buffer-file-name)))
2877 (with-parsed-tramp-file-name f nil
2878 (tramp-flush-file-property v localname)
2879 (let* ((attr (file-attributes f))
2880 (modtime (nth 5 attr))
2881 (mt (visited-file-modtime)))
2883 (cond
2884 ;; File exists, and has a known modtime.
2885 ((and attr (not (equal modtime '(0 0))))
2886 (< (abs (tramp-time-diff
2887 modtime
2888 ;; For compatibility, deal with both the old
2889 ;; (HIGH . LOW) and the new (HIGH LOW) return
2890 ;; values of `visited-file-modtime'.
2891 (if (atom (cdr mt))
2892 (list (car mt) (cdr mt))
2893 mt)))
2895 ;; Modtime has the don't know value.
2896 (attr
2897 (tramp-send-command
2899 (format "%s -ild %s"
2900 (tramp-get-ls-command v)
2901 (tramp-shell-quote-argument localname)))
2902 (with-current-buffer (tramp-get-buffer v)
2903 (setq attr (buffer-substring
2904 (point) (progn (end-of-line) (point)))))
2905 (equal
2906 attr
2907 (tramp-get-file-property
2908 v localname "visited-file-modtime-ild" "")))
2909 ;; If file does not exist, say it is not modified if and
2910 ;; only if that agrees with the buffer's record.
2911 (t (equal mt '(-1 65535))))))))))
2913 (defun tramp-handle-set-file-modes (filename mode)
2914 "Like `set-file-modes' for Tramp files."
2915 (with-parsed-tramp-file-name filename nil
2916 (tramp-flush-file-property v localname)
2917 (unless (zerop (tramp-send-command-and-check
2919 (format "chmod %s %s"
2920 (tramp-decimal-to-octal mode)
2921 (tramp-shell-quote-argument localname))))
2922 ;; FIXME: extract the proper text from chmod's stderr.
2923 (tramp-error
2924 v 'file-error "Error while changing file's mode %s" filename))))
2926 (defun tramp-handle-set-file-times (filename &optional time)
2927 "Like `set-file-times' for Tramp files."
2928 (zerop
2929 (if (file-remote-p filename)
2930 (with-parsed-tramp-file-name filename nil
2931 (tramp-flush-file-property v localname)
2932 (let ((time (if (or (null time) (equal time '(0 0)))
2933 (current-time)
2934 time))
2935 (utc
2936 ;; With GNU Emacs, `format-time-string' has an
2937 ;; optional parameter UNIVERSAL. This is preferred,
2938 ;; because we could handle the case when the remote
2939 ;; host is located in a different time zone as the
2940 ;; local host.
2941 (and (functionp 'subr-arity)
2942 (subrp (symbol-function 'format-time-string))
2943 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2944 (symbol-function
2945 'format-time-string)))))))
2946 (tramp-send-command-and-check
2947 v (format "%s touch -t %s %s"
2948 (if utc "TZ=UTC; export TZ;" "")
2949 (if utc
2950 (format-time-string "%Y%m%d%H%M.%S" time t)
2951 (format-time-string "%Y%m%d%H%M.%S" time))
2952 (tramp-shell-quote-argument localname)))))
2954 ;; We handle also the local part, because in older Emacsen,
2955 ;; without `set-file-times', this function is an alias for this.
2956 ;; We are local, so we don't need the UTC settings.
2957 (tramp-local-call-process
2958 "touch" nil nil nil "-t"
2959 (format-time-string "%Y%m%d%H%M.%S" time)
2960 (tramp-shell-quote-argument filename)))))
2962 (defun tramp-set-file-uid-gid (filename &optional uid gid)
2963 "Set the ownership for FILENAME.
2964 If UID and GID are provided, these values are used; otherwise uid
2965 and gid of the corresponding user is taken. Both parameters must be integers."
2966 ;; Modern Unices allow chown only for root. So we might need
2967 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2968 ;; working with su(do)? when it is needed, so it shall succeed in
2969 ;; the majority of cases.
2970 ;; Don't modify `last-coding-system-used' by accident.
2971 (let ((last-coding-system-used last-coding-system-used))
2972 (if (file-remote-p filename)
2973 (with-parsed-tramp-file-name filename nil
2974 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2975 ;; If we are root on the local host, we can do it directly.
2976 (tramp-set-file-uid-gid localname uid gid)
2977 (let ((uid (or (and (integerp uid) uid)
2978 (tramp-get-remote-uid v 'integer)))
2979 (gid (or (and (integerp gid) gid)
2980 (tramp-get-remote-gid v 'integer))))
2981 (tramp-send-command
2982 v (format
2983 "chown %d:%d %s" uid gid
2984 (tramp-shell-quote-argument localname))))))
2986 ;; We handle also the local part, because there doesn't exist
2987 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2988 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2989 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2990 (tramp-local-call-process
2991 "chown" nil nil nil
2992 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
2994 ;; Simple functions using the `test' command.
2996 (defun tramp-handle-file-executable-p (filename)
2997 "Like `file-executable-p' for Tramp files."
2998 (with-parsed-tramp-file-name filename nil
2999 (with-file-property v localname "file-executable-p"
3000 ;; Examine `file-attributes' cache to see if request can be
3001 ;; satisfied without remote operation.
3002 (or (tramp-check-cached-permissions v ?x)
3003 (zerop (tramp-run-test "-x" filename))))))
3005 (defun tramp-handle-file-readable-p (filename)
3006 "Like `file-readable-p' for Tramp files."
3007 (with-parsed-tramp-file-name filename nil
3008 (with-file-property v localname "file-readable-p"
3009 ;; Examine `file-attributes' cache to see if request can be
3010 ;; satisfied without remote operation.
3011 (or (tramp-check-cached-permissions v ?r)
3012 (zerop (tramp-run-test "-r" filename))))))
3014 ;; When the remote shell is started, it looks for a shell which groks
3015 ;; tilde expansion. Here, we assume that all shells which grok tilde
3016 ;; expansion will also provide a `test' command which groks `-nt' (for
3017 ;; newer than). If this breaks, tell me about it and I'll try to do
3018 ;; something smarter about it.
3019 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3020 "Like `file-newer-than-file-p' for Tramp files."
3021 (cond ((not (file-exists-p file1))
3022 nil)
3023 ((not (file-exists-p file2))
3025 ;; We are sure both files exist at this point.
3027 (save-excursion
3028 ;; We try to get the mtime of both files. If they are not
3029 ;; equal to the "dont-know" value, then we subtract the times
3030 ;; and obtain the result.
3031 (let ((fa1 (file-attributes file1))
3032 (fa2 (file-attributes file2)))
3033 (if (and (not (equal (nth 5 fa1) '(0 0)))
3034 (not (equal (nth 5 fa2) '(0 0))))
3035 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3036 ;; If one of them is the dont-know value, then we can
3037 ;; still try to run a shell command on the remote host.
3038 ;; However, this only works if both files are Tramp
3039 ;; files and both have the same method, same user, same
3040 ;; host.
3041 (unless (tramp-equal-remote file1 file2)
3042 (with-parsed-tramp-file-name
3043 (if (tramp-tramp-file-p file1) file1 file2) nil
3044 (tramp-error
3045 v 'file-error
3046 "Files %s and %s must have same method, user, host"
3047 file1 file2)))
3048 (with-parsed-tramp-file-name file1 nil
3049 (zerop (tramp-run-test2
3050 (tramp-get-test-nt-command v) file1 file2)))))))))
3052 ;; Functions implemented using the basic functions above.
3054 (defun tramp-handle-file-modes (filename)
3055 "Like `file-modes' for Tramp files."
3056 (let ((truename (or (file-truename filename) filename)))
3057 (when (file-exists-p truename)
3058 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3060 (defun tramp-default-file-modes (filename)
3061 "Return file modes of FILENAME as integer.
3062 If the file modes of FILENAME cannot be determined, return the
3063 value of `default-file-modes', without execute permissions."
3064 (or (file-modes filename)
3065 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3067 (defun tramp-handle-file-directory-p (filename)
3068 "Like `file-directory-p' for Tramp files."
3069 ;; Care must be taken that this function returns `t' for symlinks
3070 ;; pointing to directories. Surely the most obvious implementation
3071 ;; would be `test -d', but that returns false for such symlinks.
3072 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3073 ;; I now think he's right. So we could be using `test -d', couldn't
3074 ;; we?
3076 ;; Alternatives: `cd %s', `test -d %s'
3077 (with-parsed-tramp-file-name filename nil
3078 (with-file-property v localname "file-directory-p"
3079 (zerop (tramp-run-test "-d" filename)))))
3081 (defun tramp-handle-file-regular-p (filename)
3082 "Like `file-regular-p' for Tramp files."
3083 (and (file-exists-p filename)
3084 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3086 (defun tramp-handle-file-symlink-p (filename)
3087 "Like `file-symlink-p' for Tramp files."
3088 (with-parsed-tramp-file-name filename nil
3089 (let ((x (car (file-attributes filename))))
3090 (when (stringp x)
3091 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3092 ;; might do weird things.
3093 (if (file-name-absolute-p x)
3094 (tramp-make-tramp-file-name method user host x)
3095 x)))))
3097 (defun tramp-handle-file-writable-p (filename)
3098 "Like `file-writable-p' for Tramp files."
3099 (with-parsed-tramp-file-name filename nil
3100 (with-file-property v localname "file-writable-p"
3101 (if (file-exists-p filename)
3102 ;; Examine `file-attributes' cache to see if request can be
3103 ;; satisfied without remote operation.
3104 (or (tramp-check-cached-permissions v ?w)
3105 (zerop (tramp-run-test "-w" filename)))
3106 ;; If file doesn't exist, check if directory is writable.
3107 (and (zerop (tramp-run-test
3108 "-d" (file-name-directory filename)))
3109 (zerop (tramp-run-test
3110 "-w" (file-name-directory filename))))))))
3112 (defun tramp-handle-file-ownership-preserved-p (filename)
3113 "Like `file-ownership-preserved-p' for Tramp files."
3114 (with-parsed-tramp-file-name filename nil
3115 (with-file-property v localname "file-ownership-preserved-p"
3116 (let ((attributes (file-attributes filename)))
3117 ;; Return t if the file doesn't exist, since it's true that no
3118 ;; information would be lost by an (attempted) delete and create.
3119 (or (null attributes)
3120 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3122 ;; Other file name ops.
3124 (defun tramp-handle-directory-file-name (directory)
3125 "Like `directory-file-name' for Tramp files."
3126 ;; If localname component of filename is "/", leave it unchanged.
3127 ;; Otherwise, remove any trailing slash from localname component.
3128 ;; Method, host, etc, are unchanged. Does it make sense to try
3129 ;; to avoid parsing the filename?
3130 (with-parsed-tramp-file-name directory nil
3131 (if (and (not (zerop (length localname)))
3132 (eq (aref localname (1- (length localname))) ?/)
3133 (not (string= localname "/")))
3134 (substring directory 0 -1)
3135 directory)))
3137 ;; Directory listings.
3139 (defun tramp-handle-directory-files
3140 (directory &optional full match nosort files-only)
3141 "Like `directory-files' for Tramp files."
3142 ;; FILES-ONLY is valid for XEmacs only.
3143 (when (file-directory-p directory)
3144 (setq directory (expand-file-name directory))
3145 (let ((temp (nreverse (file-name-all-completions "" directory)))
3146 result item)
3148 (while temp
3149 (setq item (directory-file-name (pop temp)))
3150 (when (and (or (null match) (string-match match item))
3151 (or (null files-only)
3152 ;; files only
3153 (and (equal files-only t) (file-regular-p item))
3154 ;; directories only
3155 (file-directory-p item)))
3156 (push (if full (expand-file-name item directory) item)
3157 result)))
3158 result)))
3160 (defun tramp-handle-directory-files-and-attributes
3161 (directory &optional full match nosort id-format)
3162 "Like `directory-files-and-attributes' for Tramp files."
3163 (unless id-format (setq id-format 'integer))
3164 (when (file-directory-p directory)
3165 (setq directory (expand-file-name directory))
3166 (let* ((temp
3167 (tramp-compat-copy-tree
3168 (with-parsed-tramp-file-name directory nil
3169 (with-file-property
3170 v localname
3171 (format "directory-files-and-attributes-%s" id-format)
3172 (save-excursion
3173 (mapcar
3174 (lambda (x)
3175 (cons (car x)
3176 (tramp-convert-file-attributes v (cdr x))))
3177 (cond
3178 ((tramp-get-remote-stat v)
3179 (tramp-do-directory-files-and-attributes-with-stat
3180 v localname id-format))
3181 ((tramp-get-remote-perl v)
3182 (tramp-do-directory-files-and-attributes-with-perl
3183 v localname id-format)))))))))
3184 result item)
3186 (while temp
3187 (setq item (pop temp))
3188 (when (or (null match) (string-match match (car item)))
3189 (when full
3190 (setcar item (expand-file-name (car item) directory)))
3191 (push item result)))
3193 (if nosort
3194 result
3195 (sort result (lambda (x y) (string< (car x) (car y))))))))
3197 (defun tramp-do-directory-files-and-attributes-with-perl
3198 (vec localname &optional id-format)
3199 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3200 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3201 (tramp-maybe-send-script
3202 vec tramp-perl-directory-files-and-attributes
3203 "tramp_perl_directory_files_and_attributes")
3204 (let ((object
3205 (tramp-send-command-and-read
3207 (format "tramp_perl_directory_files_and_attributes %s %s"
3208 (tramp-shell-quote-argument localname) id-format))))
3209 (when (stringp object) (tramp-error vec 'file-error object))
3210 object))
3212 (defun tramp-do-directory-files-and-attributes-with-stat
3213 (vec localname &optional id-format)
3214 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3215 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3216 (tramp-send-command-and-read
3218 (format
3219 (concat
3220 ;; We must care about filenames with spaces, or starting with
3221 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3222 ;; but it does not work on all remote systems. Therefore, we
3223 ;; quote the filenames via sed.
3224 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3225 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3226 "echo \")\"")
3227 (tramp-shell-quote-argument localname)
3228 (tramp-get-ls-command vec)
3229 (tramp-get-remote-stat vec)
3230 (if (eq id-format 'integer) "%u" "\"%U\"")
3231 (if (eq id-format 'integer) "%g" "\"%G\""))))
3233 ;; This function should return "foo/" for directories and "bar" for
3234 ;; files.
3235 (defun tramp-handle-file-name-all-completions (filename directory)
3236 "Like `file-name-all-completions' for Tramp files."
3237 (unless (save-match-data (string-match "/" filename))
3238 (with-parsed-tramp-file-name (expand-file-name directory) nil
3240 (all-completions
3241 filename
3242 (mapcar
3243 'list
3245 ;; Try cache first
3246 (and
3247 ;; Ignore if expired
3248 (or (not (integerp tramp-completion-reread-directory-timeout))
3249 (<= (tramp-time-diff
3250 (current-time)
3251 (tramp-get-file-property
3252 v localname "last-completion" '(0 0 0)))
3253 tramp-completion-reread-directory-timeout))
3255 ;; Try cache entries for filename, filename with last
3256 ;; character removed, filename with last two characters
3257 ;; removed, ..., and finally the empty string - all
3258 ;; concatenated to the local directory name
3260 ;; This is inefficient for very long filenames, pity
3261 ;; `reduce' is not available...
3262 (car
3263 (apply
3264 'append
3265 (mapcar
3266 (lambda (x)
3267 (let ((cache-hit
3268 (tramp-get-file-property
3270 (concat localname (substring filename 0 x))
3271 "file-name-all-completions"
3272 nil)))
3273 (when cache-hit (list cache-hit))))
3274 (tramp-compat-number-sequence (length filename) 0 -1)))))
3276 ;; Cache expired or no matching cache entry found so we need
3277 ;; to perform a remote operation
3278 (let (result)
3279 ;; Get a list of directories and files, including reliably
3280 ;; tagging the directories with a trailing '/'. Because I
3281 ;; rock. --daniel@danann.net
3283 ;; Changed to perform `cd' in the same remote op and only
3284 ;; get entries starting with `filename'. Capture any `cd'
3285 ;; error messages. Ensure any `cd' and `echo' aliases are
3286 ;; ignored.
3287 (tramp-send-command
3289 (if (tramp-get-remote-perl v)
3290 (progn
3291 (tramp-maybe-send-script
3292 v tramp-perl-file-name-all-completions
3293 "tramp_perl_file_name_all_completions")
3294 (format "tramp_perl_file_name_all_completions %s %s %d"
3295 (tramp-shell-quote-argument localname)
3296 (tramp-shell-quote-argument filename)
3297 (if (symbol-value
3298 'read-file-name-completion-ignore-case)
3299 1 0)))
3301 (format (concat
3302 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3303 ;; `ls' with wildcard might fail with `Argument
3304 ;; list too long' error in some corner cases; if
3305 ;; `ls' fails after `cd' succeeded, chances are
3306 ;; that's the case, so let's retry without
3307 ;; wildcard. This will return "too many" entries
3308 ;; but that isn't harmful.
3309 " || %s -a 2>/dev/null)"
3310 " | while read f; do"
3311 " if %s -d \"$f\" 2>/dev/null;"
3312 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3313 " && \\echo ok) || \\echo fail")
3314 (tramp-shell-quote-argument localname)
3315 (tramp-get-ls-command v)
3316 ;; When `filename' is empty, just `ls' without
3317 ;; filename argument is more efficient than `ls *'
3318 ;; for very large directories and might avoid the
3319 ;; `Argument list too long' error.
3321 ;; With and only with wildcard, we need to add
3322 ;; `-d' to prevent `ls' from descending into
3323 ;; sub-directories.
3324 (if (zerop (length filename))
3326 (concat (tramp-shell-quote-argument filename) "* -d"))
3327 (tramp-get-ls-command v)
3328 (tramp-get-test-command v))))
3330 ;; Now grab the output.
3331 (with-current-buffer (tramp-get-buffer v)
3332 (goto-char (point-max))
3334 ;; Check result code, found in last line of output
3335 (forward-line -1)
3336 (if (looking-at "^fail$")
3337 (progn
3338 ;; Grab error message from line before last line
3339 ;; (it was put there by `cd 2>&1')
3340 (forward-line -1)
3341 (tramp-error
3342 v 'file-error
3343 "tramp-handle-file-name-all-completions: %s"
3344 (buffer-substring
3345 (point) (tramp-compat-line-end-position))))
3346 ;; For peace of mind, if buffer doesn't end in `fail'
3347 ;; then it should end in `ok'. If neither are in the
3348 ;; buffer something went seriously wrong on the remote
3349 ;; side.
3350 (unless (looking-at "^ok$")
3351 (tramp-error
3352 v 'file-error
3354 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3355 (tramp-shell-quote-argument localname) (buffer-string))))
3357 (while (zerop (forward-line -1))
3358 (push (buffer-substring
3359 (point) (tramp-compat-line-end-position))
3360 result)))
3362 ;; Because the remote op went through OK we know the
3363 ;; directory we `cd'-ed to exists
3364 (tramp-set-file-property
3365 v localname "file-exists-p" t)
3367 ;; Because the remote op went through OK we know every
3368 ;; file listed by `ls' exists.
3369 (mapc (lambda (entry)
3370 (tramp-set-file-property
3371 v (concat localname entry) "file-exists-p" t))
3372 result)
3374 (tramp-set-file-property
3375 v localname "last-completion" (current-time))
3377 ;; Store result in the cache
3378 (tramp-set-file-property
3379 v (concat localname filename)
3380 "file-name-all-completions"
3381 result))))))))
3383 ;; The following isn't needed for Emacs 20 but for 19.34?
3384 (defun tramp-handle-file-name-completion
3385 (filename directory &optional predicate)
3386 "Like `file-name-completion' for Tramp files."
3387 (unless (tramp-tramp-file-p directory)
3388 (error
3389 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3390 directory))
3391 (try-completion
3392 filename
3393 (mapcar 'list (file-name-all-completions filename directory))
3394 (when predicate
3395 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3397 ;; cp, mv and ln
3399 (defun tramp-handle-add-name-to-file
3400 (filename newname &optional ok-if-already-exists)
3401 "Like `add-name-to-file' for Tramp files."
3402 (unless (tramp-equal-remote filename newname)
3403 (with-parsed-tramp-file-name
3404 (if (tramp-tramp-file-p filename) filename newname) nil
3405 (tramp-error
3406 v 'file-error
3407 "add-name-to-file: %s"
3408 "only implemented for same method, same user, same host")))
3409 (with-parsed-tramp-file-name filename v1
3410 (with-parsed-tramp-file-name newname v2
3411 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3412 (when (and (not ok-if-already-exists)
3413 (file-exists-p newname)
3414 (not (numberp ok-if-already-exists))
3415 (y-or-n-p
3416 (format
3417 "File %s already exists; make it a new name anyway? "
3418 newname)))
3419 (tramp-error
3420 v2 'file-error
3421 "add-name-to-file: file %s already exists" newname))
3422 (tramp-flush-file-property v2 v2-localname)
3423 (tramp-barf-unless-okay
3425 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3426 (tramp-shell-quote-argument v2-localname))
3427 "error with add-name-to-file, see buffer `%s' for details"
3428 (buffer-name))))))
3430 (defun tramp-handle-copy-file
3431 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3432 "Like `copy-file' for Tramp files."
3433 ;; Check if both files are local -- invoke normal copy-file.
3434 ;; Otherwise, use Tramp from local system.
3435 (setq filename (expand-file-name filename))
3436 (setq newname (expand-file-name newname))
3437 (cond
3438 ;; At least one file a Tramp file?
3439 ((or (tramp-tramp-file-p filename)
3440 (tramp-tramp-file-p newname))
3441 (tramp-do-copy-or-rename-file
3442 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3443 ;; Compat section.
3444 (preserve-uid-gid
3445 (tramp-run-real-handler
3446 'copy-file
3447 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3449 (tramp-run-real-handler
3450 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3452 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3453 "Like `copy-directory' for Tramp files."
3454 (let ((t1 (tramp-tramp-file-p dirname))
3455 (t2 (tramp-tramp-file-p newname)))
3456 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3457 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3458 ;; When DIRNAME and NEWNAME are remote, they must have
3459 ;; the same method.
3460 (or (null t1) (null t2)
3461 (string-equal
3462 (tramp-file-name-method (tramp-dissect-file-name dirname))
3463 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3464 ;; scp or rsync DTRT.
3465 (progn
3466 (setq dirname (directory-file-name (expand-file-name dirname))
3467 newname (directory-file-name (expand-file-name newname)))
3468 (if (and (file-directory-p newname)
3469 (not (string-equal (file-name-nondirectory dirname)
3470 (file-name-nondirectory newname))))
3471 (setq newname
3472 (expand-file-name
3473 (file-name-nondirectory dirname) newname)))
3474 (if (not (file-directory-p (file-name-directory newname)))
3475 (make-directory (file-name-directory newname) parents))
3476 (tramp-do-copy-or-rename-file-out-of-band
3477 'copy dirname newname keep-date))
3478 ;; We must do it file-wise.
3479 (tramp-run-real-handler
3480 'copy-directory (list dirname newname keep-date parents))))))
3482 (defun tramp-handle-rename-file
3483 (filename newname &optional ok-if-already-exists)
3484 "Like `rename-file' for Tramp files."
3485 ;; Check if both files are local -- invoke normal rename-file.
3486 ;; Otherwise, use Tramp from local system.
3487 (setq filename (expand-file-name filename))
3488 (setq newname (expand-file-name newname))
3489 ;; At least one file a Tramp file?
3490 (if (or (tramp-tramp-file-p filename)
3491 (tramp-tramp-file-p newname))
3492 (tramp-do-copy-or-rename-file
3493 'rename filename newname ok-if-already-exists t t)
3494 (tramp-run-real-handler
3495 'rename-file (list filename newname ok-if-already-exists))))
3497 (defun tramp-do-copy-or-rename-file
3498 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3499 "Copy or rename a remote file.
3500 OP must be `copy' or `rename' and indicates the operation to perform.
3501 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3502 the new file (for copy) or the new name of the file (for rename).
3503 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3504 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3505 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3506 the uid and gid if both files are on the same host.
3508 This function is invoked by `tramp-handle-copy-file' and
3509 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3510 and `rename'. FILENAME and NEWNAME must be absolute file names."
3511 (unless (memq op '(copy rename))
3512 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3513 (let ((t1 (tramp-tramp-file-p filename))
3514 (t2 (tramp-tramp-file-p newname)))
3516 (when (and (not ok-if-already-exists) (file-exists-p newname))
3517 (with-parsed-tramp-file-name (if t1 filename newname) nil
3518 (tramp-error
3519 v 'file-already-exists "File %s already exists" newname)))
3521 (with-parsed-tramp-file-name (if t1 filename newname) nil
3522 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3524 (prog1
3525 (cond
3526 ;; Both are Tramp files.
3527 ((and t1 t2)
3528 (with-parsed-tramp-file-name filename v1
3529 (with-parsed-tramp-file-name newname v2
3530 (cond
3531 ;; Shortcut: if method, host, user are the same for both
3532 ;; files, we invoke `cp' or `mv' on the remote host
3533 ;; directly.
3534 ((tramp-equal-remote filename newname)
3535 (tramp-do-copy-or-rename-file-directly
3536 op filename newname
3537 ok-if-already-exists keep-date preserve-uid-gid))
3539 ;; Try out-of-band operation.
3540 ((tramp-method-out-of-band-p
3541 v1 (nth 7 (file-attributes filename)))
3542 (tramp-do-copy-or-rename-file-out-of-band
3543 op filename newname keep-date))
3545 ;; No shortcut was possible. So we copy the
3546 ;; file first. If the operation was `rename', we go
3547 ;; back and delete the original file (if the copy was
3548 ;; successful). The approach is simple-minded: we
3549 ;; create a new buffer, insert the contents of the
3550 ;; source file into it, then write out the buffer to
3551 ;; the target file. The advantage is that it doesn't
3552 ;; matter which filename handlers are used for the
3553 ;; source and target file.
3555 (tramp-do-copy-or-rename-file-via-buffer
3556 op filename newname keep-date))))))
3558 ;; One file is a Tramp file, the other one is local.
3559 ((or t1 t2)
3560 (with-parsed-tramp-file-name (if t1 filename newname) nil
3561 (cond
3562 ;; Fast track on local machine.
3563 ((tramp-local-host-p v)
3564 (tramp-do-copy-or-rename-file-directly
3565 op filename newname
3566 ok-if-already-exists keep-date preserve-uid-gid))
3568 ;; If the Tramp file has an out-of-band method, the corresponding
3569 ;; copy-program can be invoked.
3570 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3571 (tramp-do-copy-or-rename-file-out-of-band
3572 op filename newname keep-date))
3574 ;; Use the inline method via a Tramp buffer.
3575 (t (tramp-do-copy-or-rename-file-via-buffer
3576 op filename newname keep-date)))))
3579 ;; One of them must be a Tramp file.
3580 (error "Tramp implementation says this cannot happen")))
3582 ;; In case of `rename', we must flush the cache of the source file.
3583 (when (and t1 (eq op 'rename))
3584 (with-parsed-tramp-file-name filename nil
3585 (tramp-flush-file-property v localname)))
3587 ;; When newname did exist, we have wrong cached values.
3588 (when t2
3589 (with-parsed-tramp-file-name newname nil
3590 (tramp-flush-file-property v localname)))
3592 (with-parsed-tramp-file-name (if t1 filename newname) nil
3593 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
3595 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3596 "Use an Emacs buffer to copy or rename a file.
3597 First arg OP is either `copy' or `rename' and indicates the operation.
3598 FILENAME is the source file, NEWNAME the target file.
3599 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3600 (with-temp-buffer
3601 ;; We must disable multibyte, because binary data shall not be
3602 ;; converted.
3603 (set-buffer-multibyte nil)
3604 (let ((coding-system-for-read 'binary)
3605 (jka-compr-inhibit t))
3606 (insert-file-contents-literally filename))
3607 ;; We don't want the target file to be compressed, so we let-bind
3608 ;; `jka-compr-inhibit' to t.
3609 (let ((coding-system-for-write 'binary)
3610 (jka-compr-inhibit t))
3611 (write-region (point-min) (point-max) newname)))
3612 ;; KEEP-DATE handling.
3613 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3614 ;; Set the mode.
3615 (set-file-modes newname (tramp-default-file-modes filename))
3616 ;; If the operation was `rename', delete the original file.
3617 (unless (eq op 'copy) (delete-file filename)))
3619 (defun tramp-do-copy-or-rename-file-directly
3620 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3621 "Invokes `cp' or `mv' on the remote system.
3622 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3623 respectively. FILENAME specifies the file to copy or rename,
3624 NEWNAME is the name of the new file (for copy) or the new name of
3625 the file (for rename). Both files must reside on the same host.
3626 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3627 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3628 the uid and gid from FILENAME."
3629 (let ((t1 (tramp-tramp-file-p filename))
3630 (t2 (tramp-tramp-file-p newname))
3631 (file-times (nth 5 (file-attributes filename)))
3632 (file-modes (tramp-default-file-modes filename)))
3633 (with-parsed-tramp-file-name (if t1 filename newname) nil
3634 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3635 ((eq op 'copy) "cp -f")
3636 ((eq op 'rename) "mv -f")
3637 (t (tramp-error
3638 v 'file-error
3639 "Unknown operation `%s', must be `copy' or `rename'"
3640 op))))
3641 (localname1
3642 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3643 (localname2
3644 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
3645 (prefix (file-remote-p (if t1 filename newname)))
3646 cmd-result)
3648 (cond
3649 ;; Both files are on a remote host, with same user.
3650 ((and t1 t2)
3651 (setq cmd-result
3652 (tramp-send-command-and-check
3654 (format "%s %s %s" cmd
3655 (tramp-shell-quote-argument localname1)
3656 (tramp-shell-quote-argument localname2))))
3657 (with-current-buffer (tramp-get-buffer v)
3658 (goto-char (point-min))
3659 (unless
3661 (and keep-date
3662 ;; Mask cp -f error.
3663 (re-search-forward
3664 tramp-operation-not-permitted-regexp nil t))
3665 (zerop cmd-result))
3666 (tramp-error-with-buffer
3667 nil v 'file-error
3668 "Copying directly failed, see buffer `%s' for details."
3669 (buffer-name)))))
3671 ;; We are on the local host.
3672 ((or t1 t2)
3673 (cond
3674 ;; We can do it directly.
3675 ((let (file-name-handler-alist)
3676 (and (file-readable-p localname1)
3677 (file-writable-p (file-name-directory localname2))
3678 (or (file-directory-p localname2)
3679 (file-writable-p localname2))))
3680 (if (eq op 'copy)
3681 (tramp-compat-copy-file
3682 localname1 localname2 ok-if-already-exists
3683 keep-date preserve-uid-gid)
3684 (tramp-run-real-handler
3685 'rename-file (list localname1 localname2 ok-if-already-exists))))
3687 ;; We can do it directly with `tramp-send-command'
3688 ((and (file-readable-p (concat prefix localname1))
3689 (file-writable-p
3690 (file-name-directory (concat prefix localname2)))
3691 (or (file-directory-p (concat prefix localname2))
3692 (file-writable-p (concat prefix localname2))))
3693 (tramp-do-copy-or-rename-file-directly
3694 op (concat prefix localname1) (concat prefix localname2)
3695 ok-if-already-exists keep-date t)
3696 ;; We must change the ownership to the local user.
3697 (tramp-set-file-uid-gid
3698 (concat prefix localname2)
3699 (tramp-get-local-uid 'integer)
3700 (tramp-get-local-gid 'integer)))
3702 ;; We need a temporary file in between.
3704 ;; Create the temporary file.
3705 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3706 (unwind-protect
3707 (progn
3708 (cond
3711 (zerop
3712 (tramp-send-command-and-check
3713 v (format
3714 "%s %s %s" cmd
3715 (tramp-shell-quote-argument localname1)
3716 (tramp-shell-quote-argument tmpfile))))
3717 (tramp-error-with-buffer
3718 nil v 'file-error
3719 "Copying directly failed, see buffer `%s' for details."
3720 (tramp-get-buffer v)))
3721 ;; We must change the ownership as remote user.
3722 ;; Since this does not work reliable, we also
3723 ;; give read permissions.
3724 (set-file-modes
3725 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3726 (tramp-set-file-uid-gid
3727 (concat prefix tmpfile)
3728 (tramp-get-local-uid 'integer)
3729 (tramp-get-local-gid 'integer)))
3731 (if (eq op 'copy)
3732 (tramp-compat-copy-file
3733 localname1 tmpfile t
3734 keep-date preserve-uid-gid)
3735 (tramp-run-real-handler
3736 'rename-file
3737 (list localname1 tmpfile t)))
3738 ;; We must change the ownership as local user.
3739 ;; Since this does not work reliable, we also
3740 ;; give read permissions.
3741 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3742 (tramp-set-file-uid-gid
3743 tmpfile
3744 (tramp-get-remote-uid v 'integer)
3745 (tramp-get-remote-gid v 'integer))))
3747 ;; Move the temporary file to its destination.
3748 (cond
3751 (zerop
3752 (tramp-send-command-and-check
3753 v (format
3754 "cp -f -p %s %s"
3755 (tramp-shell-quote-argument tmpfile)
3756 (tramp-shell-quote-argument localname2))))
3757 (tramp-error-with-buffer
3758 nil v 'file-error
3759 "Copying directly failed, see buffer `%s' for details."
3760 (tramp-get-buffer v))))
3762 (tramp-run-real-handler
3763 'rename-file
3764 (list tmpfile localname2 ok-if-already-exists)))))
3766 ;; Save exit.
3767 (condition-case nil
3768 (delete-file tmpfile)
3769 (error)))))))))
3771 ;; Set the time and mode. Mask possible errors.
3772 (condition-case nil
3773 (when keep-date
3774 (set-file-times newname file-times)
3775 (set-file-modes newname file-modes))
3776 (error)))))
3778 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3779 "Invoke rcp program to copy.
3780 The method used must be an out-of-band method."
3781 (let ((t1 (tramp-tramp-file-p filename))
3782 (t2 (tramp-tramp-file-p newname))
3783 copy-program copy-args copy-env copy-keep-date port spec
3784 source target)
3786 (with-parsed-tramp-file-name (if t1 filename newname) nil
3787 (if (and t1 t2)
3789 ;; Both are Tramp files. We shall optimize it, when the
3790 ;; methods for filename and newname are the same.
3791 (let ((tmpfile (tramp-compat-make-temp-file localname)))
3792 (unwind-protect
3793 (progn
3794 (tramp-do-copy-or-rename-file-out-of-band
3795 op filename tmpfile keep-date)
3796 (tramp-do-copy-or-rename-file-out-of-band
3797 'rename tmpfile newname keep-date))
3798 ;; Save exit.
3799 (condition-case nil
3800 (delete-file tmpfile)
3801 (error))))
3803 ;; Expand hops. Might be necessary for gateway methods.
3804 (setq v (car (tramp-compute-multi-hops v)))
3805 (aset v 3 localname)
3807 ;; Check which ones of source and target are Tramp files.
3808 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3809 target (funcall
3810 (if (and (file-directory-p filename)
3811 (string-equal
3812 (file-name-nondirectory filename)
3813 (file-name-nondirectory newname)))
3814 'file-name-directory
3815 'identity)
3816 (if t2 (tramp-make-copy-program-file-name v) newname)))
3818 ;; Check for port number. Until now, there's no need for handling
3819 ;; like method, user, host.
3820 (setq host (tramp-file-name-real-host v)
3821 port (tramp-file-name-port v)
3822 port (or (and port (number-to-string port)) ""))
3824 ;; Compose copy command.
3825 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3826 (?t . ,(tramp-get-connection-property
3827 (tramp-get-connection-process v) "temp-file" ""))
3828 (?k . ,(if keep-date " " "")))
3829 copy-program (tramp-get-method-parameter
3830 method 'tramp-copy-program)
3831 copy-keep-date (tramp-get-method-parameter
3832 method 'tramp-copy-keep-date)
3833 copy-args
3834 (delq
3836 (mapcar
3837 (lambda (x)
3838 (setq
3840 ;; " " is indication for keep-date argument.
3841 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3842 (unless (member "" x) (mapconcat 'identity x " ")))
3843 (tramp-get-method-parameter method 'tramp-copy-args)))
3844 copy-env
3845 (delq
3847 (mapcar
3848 (lambda (x)
3849 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3850 (unless (member "" x) (mapconcat 'identity x " ")))
3851 (tramp-get-method-parameter method 'tramp-copy-env))))
3853 ;; Check for program.
3854 (when (and (fboundp 'executable-find)
3855 (not (let ((default-directory
3856 (tramp-compat-temporary-file-directory)))
3857 (executable-find copy-program))))
3858 (tramp-error
3859 v 'file-error "Cannot find copy program: %s" copy-program))
3861 ;; Set variables for computing the prompt for reading
3862 ;; password.
3863 (setq tramp-current-method (tramp-file-name-method v)
3864 tramp-current-user (tramp-file-name-user v)
3865 tramp-current-host (tramp-file-name-host v))
3867 (unwind-protect
3868 (with-temp-buffer
3869 ;; The default directory must be remote.
3870 (let ((default-directory
3871 (file-name-directory (if t1 filename newname)))
3872 (process-environment (copy-sequence process-environment)))
3873 ;; Set the transfer process properties.
3874 (tramp-set-connection-property
3875 v "process-name" (buffer-name (current-buffer)))
3876 (tramp-set-connection-property
3877 v "process-buffer" (current-buffer))
3878 (while copy-env
3879 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3880 (setenv (pop copy-env) (pop copy-env)))
3882 ;; Use an asynchronous process. By this, password can
3883 ;; be handled. The default directory must be local, in
3884 ;; order to apply the correct `copy-program'. We don't
3885 ;; set a timeout, because the copying of large files can
3886 ;; last longer than 60 secs.
3887 (let ((p (let ((default-directory
3888 (tramp-compat-temporary-file-directory)))
3889 (apply 'start-process
3890 (tramp-get-connection-property
3891 v "process-name" nil)
3892 (tramp-get-connection-property
3893 v "process-buffer" nil)
3894 copy-program
3895 (append copy-args (list source target))))))
3896 (tramp-message
3897 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3898 (tramp-set-process-query-on-exit-flag p nil)
3899 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
3901 ;; Reset the transfer process properties.
3902 (tramp-set-connection-property v "process-name" nil)
3903 (tramp-set-connection-property v "process-buffer" nil))
3905 ;; Handle KEEP-DATE argument.
3906 (when (and keep-date (not copy-keep-date))
3907 (set-file-times newname (nth 5 (file-attributes filename))))
3909 ;; Set the mode.
3910 (unless (and keep-date copy-keep-date)
3911 (set-file-modes newname (tramp-default-file-modes filename))))
3913 ;; If the operation was `rename', delete the original file.
3914 (unless (eq op 'copy)
3915 (delete-file filename)))))
3917 (defun tramp-handle-make-directory (dir &optional parents)
3918 "Like `make-directory' for Tramp files."
3919 (setq dir (expand-file-name dir))
3920 (with-parsed-tramp-file-name dir nil
3921 (tramp-flush-directory-property v (file-name-directory localname))
3922 (save-excursion
3923 (tramp-barf-unless-okay
3925 (format "%s %s"
3926 (if parents "mkdir -p" "mkdir")
3927 (tramp-shell-quote-argument localname))
3928 "Couldn't make directory %s" dir))))
3930 (defun tramp-handle-delete-directory (directory &optional recursive)
3931 "Like `delete-directory' for Tramp files."
3932 (setq directory (expand-file-name directory))
3933 (with-parsed-tramp-file-name directory nil
3934 (tramp-flush-directory-property v localname)
3935 (unless (zerop (tramp-send-command-and-check
3937 (format
3938 "%s %s"
3939 (if recursive "rm -rf" "rmdir")
3940 (tramp-shell-quote-argument localname))))
3941 (tramp-error v 'file-error "Couldn't delete %s" directory))))
3943 (defun tramp-handle-delete-file (filename)
3944 "Like `delete-file' for Tramp files."
3945 (setq filename (expand-file-name filename))
3946 (with-parsed-tramp-file-name filename nil
3947 (tramp-flush-file-property v localname)
3948 (unless (zerop (tramp-send-command-and-check
3950 (format "rm -f %s"
3951 (tramp-shell-quote-argument localname))))
3952 (tramp-error v 'file-error "Couldn't delete %s" filename))))
3954 ;; Dired.
3956 ;; CCC: This does not seem to be enough. Something dies when
3957 ;; we try and delete two directories under Tramp :/
3958 (defun tramp-handle-dired-recursive-delete-directory (filename)
3959 "Recursively delete the directory given.
3960 This is like `dired-recursive-delete-directory' for Tramp files."
3961 (with-parsed-tramp-file-name filename nil
3962 ;; Run a shell command 'rm -r <localname>'
3963 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
3964 (unless (file-exists-p filename)
3965 (tramp-error v 'file-error "No such directory: %s" filename))
3966 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
3967 (tramp-send-command
3969 (format "rm -rf %s" (tramp-shell-quote-argument localname))
3970 ;; Don't read the output, do it explicitely.
3971 nil t)
3972 ;; Wait for the remote system to return to us...
3973 ;; This might take a while, allow it plenty of time.
3974 (tramp-wait-for-output (tramp-get-connection-process v) 120)
3975 ;; Make sure that it worked...
3976 (tramp-flush-directory-property v localname)
3977 (and (file-exists-p filename)
3978 (tramp-error
3979 v 'file-error "Failed to recursively delete %s" filename))))
3981 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
3982 "Like `dired-compress-file' for Tramp files."
3983 ;; OK-FLAG is valid for XEmacs only, but not implemented.
3984 ;; Code stolen mainly from dired-aux.el.
3985 (with-parsed-tramp-file-name file nil
3986 (tramp-flush-file-property v localname)
3987 (save-excursion
3988 (let ((suffixes
3989 (if (not (featurep 'xemacs))
3990 ;; Emacs case
3991 (symbol-value 'dired-compress-file-suffixes)
3992 ;; XEmacs has `dired-compression-method-alist', which is
3993 ;; transformed into `dired-compress-file-suffixes' structure.
3994 (mapcar
3995 (lambda (x)
3996 (list (concat (regexp-quote (nth 1 x)) "\\'")
3998 (mapconcat 'identity (nth 3 x) " ")))
3999 (symbol-value 'dired-compression-method-alist))))
4000 suffix)
4001 ;; See if any suffix rule matches this file name.
4002 (while suffixes
4003 (let (case-fold-search)
4004 (if (string-match (car (car suffixes)) localname)
4005 (setq suffix (car suffixes) suffixes nil))
4006 (setq suffixes (cdr suffixes))))
4008 (cond ((file-symlink-p file)
4009 nil)
4010 ((and suffix (nth 2 suffix))
4011 ;; We found an uncompression rule.
4012 (tramp-message v 0 "Uncompressing %s..." file)
4013 (when (zerop (tramp-send-command-and-check
4014 v (concat (nth 2 suffix) " "
4015 (tramp-shell-quote-argument localname))))
4016 (tramp-message v 0 "Uncompressing %s...done" file)
4017 ;; `dired-remove-file' is not defined in XEmacs
4018 (funcall (symbol-function 'dired-remove-file) file)
4019 (string-match (car suffix) file)
4020 (concat (substring file 0 (match-beginning 0)))))
4022 ;; We don't recognize the file as compressed, so compress it.
4023 ;; Try gzip.
4024 (tramp-message v 0 "Compressing %s..." file)
4025 (when (zerop (tramp-send-command-and-check
4026 v (concat "gzip -f "
4027 (tramp-shell-quote-argument localname))))
4028 (tramp-message v 0 "Compressing %s...done" file)
4029 ;; `dired-remove-file' is not defined in XEmacs
4030 (funcall (symbol-function 'dired-remove-file) file)
4031 (cond ((file-exists-p (concat file ".gz"))
4032 (concat file ".gz"))
4033 ((file-exists-p (concat file ".z"))
4034 (concat file ".z"))
4035 (t nil)))))))))
4037 (defun tramp-handle-dired-uncache (dir)
4038 "Like `dired-uncache' for Tramp files."
4039 (with-parsed-tramp-file-name dir nil
4040 (tramp-flush-file-property v localname)))
4042 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4043 ;; not sure at all that this is the right way to do it, but let's hope
4044 ;; it works for now, and wait for a guru to point out the Right Way to
4045 ;; achieve this.
4046 ;;(eval-when-compile
4047 ;; (unless (fboundp 'dired-insert-set-properties)
4048 ;; (fset 'dired-insert-set-properties 'ignore)))
4049 ;; Gerd suggests this:
4050 (eval-when-compile (require 'dired))
4051 ;; Note that dired is required at run-time, too, when it is needed.
4052 ;; It is only needed on XEmacs for the function
4053 ;; `dired-insert-set-properties'.
4055 (defun tramp-handle-insert-directory
4056 (filename switches &optional wildcard full-directory-p)
4057 "Like `insert-directory' for Tramp files."
4058 (setq filename (expand-file-name filename))
4059 (with-parsed-tramp-file-name filename nil
4060 (if (and (featurep 'ls-lisp)
4061 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4062 (tramp-run-real-handler
4063 'insert-directory (list filename switches wildcard full-directory-p))
4064 (when (and (string-match "^--dired\\s-+" switches)
4065 (not (tramp-get-ls-command-with-dired v)))
4066 (setq switches (replace-match "" nil t switches)))
4067 (tramp-message
4068 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4069 switches filename (if wildcard "yes" "no")
4070 (if full-directory-p "yes" "no"))
4071 (when wildcard
4072 (setq wildcard (tramp-run-real-handler
4073 'file-name-nondirectory (list localname)))
4074 (setq localname (tramp-run-real-handler
4075 'file-name-directory (list localname))))
4076 (when (listp switches)
4077 (setq switches (mapconcat 'identity switches " ")))
4078 (unless full-directory-p
4079 (setq switches (concat "-d " switches)))
4080 (when wildcard
4081 (setq switches (concat switches " " wildcard)))
4082 (when (string-match "'" switches)
4083 (setq switches (replace-match "\\\\'" nil nil switches)))
4084 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4085 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4086 (if full-directory-p
4087 (tramp-send-command
4089 (format "%s %s %s 2>/dev/null"
4090 (tramp-get-ls-command v)
4091 switches
4092 (if wildcard
4093 localname
4094 (tramp-shell-quote-argument (concat localname ".")))))
4095 (tramp-barf-unless-okay
4097 (format "cd %s" (tramp-shell-quote-argument
4098 (tramp-run-real-handler
4099 'file-name-directory (list localname))))
4100 "Couldn't `cd %s'"
4101 (tramp-shell-quote-argument
4102 (tramp-run-real-handler 'file-name-directory (list localname))))
4103 (tramp-send-command
4105 (format "%s %s %s"
4106 (tramp-get-ls-command v)
4107 switches
4108 (if (or wildcard
4109 (zerop (length
4110 (tramp-run-real-handler
4111 'file-name-nondirectory (list localname)))))
4113 (tramp-shell-quote-argument
4114 (tramp-run-real-handler
4115 'file-name-nondirectory (list localname)))))))
4116 (let ((beg (point)))
4117 ;; We cannot use `insert-buffer-substring' because the Tramp
4118 ;; buffer changes its contents before insertion due to calling
4119 ;; `expand-file' and alike.
4120 (insert
4121 (with-current-buffer (tramp-get-buffer v)
4122 (buffer-string)))
4124 ;; Check for "--dired" output.
4125 (forward-line -2)
4126 (when (looking-at "//SUBDIRED//")
4127 (forward-line -1))
4128 (when (looking-at "//DIRED//")
4129 (let ((end (tramp-compat-line-end-position))
4130 (linebeg (point)))
4131 ;; Now read the numeric positions of file names.
4132 (goto-char linebeg)
4133 (forward-word 1)
4134 (forward-char 3)
4135 (while (< (point) end)
4136 (let ((start (+ beg (read (current-buffer))))
4137 (end (+ beg (read (current-buffer)))))
4138 (if (memq (char-after end) '(?\n ?\ ))
4139 ;; End is followed by \n or by " -> ".
4140 (put-text-property start end 'dired-filename t))))))
4141 ;; Remove trailing lines.
4142 (goto-char (tramp-compat-line-beginning-position))
4143 (while (looking-at "//")
4144 (forward-line 1)
4145 (delete-region (match-beginning 0) (point)))
4146 (goto-char (point-max))))))
4148 (defun tramp-handle-unhandled-file-name-directory (filename)
4149 "Like `unhandled-file-name-directory' for Tramp files."
4150 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4151 ;; for backward compatibility.
4152 (expand-file-name "~/"))
4154 ;; Canonicalization of file names.
4156 (defun tramp-handle-expand-file-name (name &optional dir)
4157 "Like `expand-file-name' for Tramp files.
4158 If the localname part of the given filename starts with \"/../\" then
4159 the result will be a local, non-Tramp, filename."
4160 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4161 (setq dir (or dir default-directory "/"))
4162 ;; Unless NAME is absolute, concat DIR and NAME.
4163 (unless (file-name-absolute-p name)
4164 (setq name (concat (file-name-as-directory dir) name)))
4165 ;; If NAME is not a Tramp file, run the real handler.
4166 (if (not (tramp-tramp-file-p name))
4167 (tramp-run-real-handler 'expand-file-name (list name nil))
4168 ;; Dissect NAME.
4169 (with-parsed-tramp-file-name name nil
4170 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4171 (setq localname (concat "~/" localname)))
4172 ;; Tilde expansion if necessary. This needs a shell which
4173 ;; groks tilde expansion! The function `tramp-find-shell' is
4174 ;; supposed to find such a shell on the remote host. Please
4175 ;; tell me about it when this doesn't work on your system.
4176 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4177 (let ((uname (match-string 1 localname))
4178 (fname (match-string 2 localname)))
4179 ;; We cannot simply apply "~/", because under sudo "~/" is
4180 ;; expanded to the local user home directory but to the
4181 ;; root home directory. On the other hand, using always
4182 ;; the default user name for tilde expansion is not
4183 ;; appropriate either, because ssh and companions might
4184 ;; use a user name from the config file.
4185 (when (and (string-equal uname "~")
4186 (string-match "\\`su\\(do\\)?\\'" method))
4187 (setq uname (concat uname user)))
4188 (setq uname
4189 (with-connection-property v uname
4190 (tramp-send-command
4191 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4192 (with-current-buffer (tramp-get-buffer v)
4193 (goto-char (point-min))
4194 (buffer-substring
4195 (point) (tramp-compat-line-end-position)))))
4196 (setq localname (concat uname fname))))
4197 ;; There might be a double slash, for example when "~/"
4198 ;; expands to "/". Remove this.
4199 (while (string-match "//" localname)
4200 (setq localname (replace-match "/" t t localname)))
4201 ;; No tilde characters in file name, do normal
4202 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4203 ;; `directory-sep-char' here for XEmacs on Windows, which would
4204 ;; otherwise use backslash. `default-directory' is bound,
4205 ;; because on Windows there would be problems with UNC shares or
4206 ;; Cygwin mounts.
4207 (let ((directory-sep-char ?/)
4208 (default-directory (tramp-compat-temporary-file-directory)))
4209 (tramp-make-tramp-file-name
4210 method user host
4211 (tramp-drop-volume-letter
4212 (tramp-run-real-handler
4213 'expand-file-name (list localname))))))))
4215 (defun tramp-replace-environment-variables (filename)
4216 "Replace environment variables in FILENAME.
4217 Return the string with the replaced variables."
4218 (save-match-data
4219 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4220 ;; `$' is coded as `$$'.
4221 (when (and idx
4222 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4223 (getenv (match-string 1 filename)))
4224 (setq filename
4225 (replace-match
4226 (substitute-in-file-name (match-string 0 filename))
4227 t nil filename)))
4228 filename)))
4230 (defun tramp-handle-substitute-in-file-name (filename)
4231 "Like `substitute-in-file-name' for Tramp files.
4232 \"//\" and \"/~\" substitute only in the local filename part.
4233 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4234 beginning of local filename are not substituted."
4235 ;; First, we must replace environment variables.
4236 (setq filename (tramp-replace-environment-variables filename))
4237 (with-parsed-tramp-file-name filename nil
4238 (if (equal tramp-syntax 'url)
4239 ;; We need to check localname only. The other parts cannot contain
4240 ;; "//" or "/~".
4241 (if (and (> (length localname) 1)
4242 (or (string-match "//" localname)
4243 (string-match "/~" localname 1)))
4244 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4245 (tramp-make-tramp-file-name
4246 (when method (substitute-in-file-name method))
4247 (when user (substitute-in-file-name user))
4248 (when host (substitute-in-file-name host))
4249 (when localname
4250 (tramp-run-real-handler
4251 'substitute-in-file-name (list localname)))))
4252 ;; Ignore in LOCALNAME everything before "//" or "/~".
4253 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4254 (setq filename
4255 (concat (file-remote-p filename)
4256 (replace-match "\\1" nil nil localname)))
4257 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4258 (when (string-match "~$" filename)
4259 (setq filename (concat filename "/"))))
4260 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4262 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4263 ;; which calls corresponding functions (see minibuf.el).
4264 (when (fboundp 'minibuffer-electric-separator)
4265 (mapc
4266 (lambda (x)
4267 (eval
4268 `(defadvice ,x
4269 (around ,(intern (format "tramp-advice-%s" x)) activate)
4270 "Invoke `substitute-in-file-name' for Tramp files."
4271 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4272 (tramp-tramp-file-p (buffer-substring)))
4273 ;; We don't need to handle `last-input-event', because
4274 ;; due to the key map we know it must be ?/ or ?~.
4275 (let ((s (concat (buffer-substring (point-min) (point))
4276 (string last-command-char))))
4277 (delete-region (point-min) (point))
4278 (insert (substitute-in-file-name s))
4279 (setq ad-return-value last-command-char))
4280 ad-do-it)))
4281 (eval
4282 `(add-hook
4283 'tramp-unload-hook
4284 (lambda ()
4285 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4286 (ad-activate ',x)))))
4288 '(minibuffer-electric-separator
4289 minibuffer-electric-tilde)))
4292 ;;; Remote commands:
4294 (defun tramp-handle-executable-find (command)
4295 "Like `executable-find' for Tramp files."
4296 (with-parsed-tramp-file-name default-directory nil
4297 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4299 ;; We use BUFFER also as connection buffer during setup. Because of
4300 ;; this, its original contents must be saved, and restored once
4301 ;; connection has been setup.
4302 (defun tramp-handle-start-file-process (name buffer program &rest args)
4303 "Like `start-file-process' for Tramp files."
4304 (with-parsed-tramp-file-name default-directory nil
4305 (unless (stringp program)
4306 (tramp-error
4307 v 'file-error "pty association is not supported for `%s'" name))
4308 (unwind-protect
4309 (let ((command (format "cd %s; exec %s"
4310 (tramp-shell-quote-argument localname)
4311 (mapconcat 'tramp-shell-quote-argument
4312 (cons program args) " ")))
4313 (name1 name)
4314 (i 0))
4315 (unless buffer
4316 ;; BUFFER can be nil. We use a temporary buffer.
4317 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4318 (while (get-process name1)
4319 ;; NAME must be unique as process name.
4320 (setq i (1+ i)
4321 name1 (format "%s<%d>" name i)))
4322 (setq name name1)
4323 ;; Set the new process properties.
4324 (tramp-set-connection-property v "process-name" name)
4325 (tramp-set-connection-property v "process-buffer" buffer)
4326 ;; Activate narrowing in order to save BUFFER contents.
4327 ;; Clear also the modification time; otherwise we might be
4328 ;; interrupted by `verify-visited-file-modtime'.
4329 (with-current-buffer (tramp-get-connection-buffer v)
4330 (clear-visited-file-modtime)
4331 (narrow-to-region (point-max) (point-max)))
4332 ;; Send the command. `tramp-send-command' opens a new
4333 ;; connection.
4334 (tramp-send-command v command nil t) ; nooutput
4335 ;; Set query flag for this process.
4336 (tramp-set-process-query-on-exit-flag
4337 (tramp-get-connection-process v) t)
4338 ;; Return process.
4339 (tramp-get-connection-process v))
4340 ;; Save exit.
4341 (with-current-buffer (tramp-get-connection-buffer v)
4342 (if (string-match tramp-temp-buffer-name (buffer-name))
4343 (progn
4344 (set-process-buffer (tramp-get-connection-process v) nil)
4345 (kill-buffer (current-buffer)))
4346 (widen)
4347 (goto-char (point-max))))
4348 (tramp-set-connection-property v "process-name" nil)
4349 (tramp-set-connection-property v "process-buffer" nil))))
4351 (defun tramp-handle-process-file
4352 (program &optional infile destination display &rest args)
4353 "Like `process-file' for Tramp files."
4354 ;; The implementation is not complete yet.
4355 (when (and (numberp destination) (zerop destination))
4356 (error "Implementation does not handle immediate return"))
4358 (with-parsed-tramp-file-name default-directory nil
4359 (let (command input tmpinput stderr tmpstderr outbuf ret)
4360 ;; Compute command.
4361 (setq command (mapconcat 'tramp-shell-quote-argument
4362 (cons program args) " "))
4363 ;; Determine input.
4364 (if (null infile)
4365 (setq input "/dev/null")
4366 (setq infile (expand-file-name infile))
4367 (if (tramp-equal-remote default-directory infile)
4368 ;; INFILE is on the same remote host.
4369 (setq input (with-parsed-tramp-file-name infile nil localname))
4370 ;; INFILE must be copied to remote host.
4371 (setq input (tramp-make-tramp-temp-file v)
4372 tmpinput (tramp-make-tramp-file-name method user host input))
4373 (copy-file infile tmpinput t)))
4374 (when input (setq command (format "%s <%s" command input)))
4376 ;; Determine output.
4377 (cond
4378 ;; Just a buffer.
4379 ((bufferp destination)
4380 (setq outbuf destination))
4381 ;; A buffer name.
4382 ((stringp destination)
4383 (setq outbuf (get-buffer-create destination)))
4384 ;; (REAL-DESTINATION ERROR-DESTINATION)
4385 ((consp destination)
4386 ;; output.
4387 (cond
4388 ((bufferp (car destination))
4389 (setq outbuf (car destination)))
4390 ((stringp (car destination))
4391 (setq outbuf (get-buffer-create (car destination))))
4392 ((car destination)
4393 (setq outbuf (current-buffer))))
4394 ;; stderr.
4395 (cond
4396 ((stringp (cadr destination))
4397 (setcar (cdr destination) (expand-file-name (cadr destination)))
4398 (if (tramp-equal-remote default-directory (cadr destination))
4399 ;; stderr is on the same remote host.
4400 (setq stderr (with-parsed-tramp-file-name
4401 (cadr destination) nil localname))
4402 ;; stderr must be copied to remote host. The temporary
4403 ;; file must be deleted after execution.
4404 (setq stderr (tramp-make-tramp-temp-file v)
4405 tmpstderr (tramp-make-tramp-file-name
4406 method user host stderr))))
4407 ;; stderr to be discarded.
4408 ((null (cadr destination))
4409 (setq stderr "/dev/null"))))
4410 ;; 't
4411 (destination
4412 (setq outbuf (current-buffer))))
4413 (when stderr (setq command (format "%s 2>%s" command stderr)))
4415 ;; Send the command. It might not return in time, so we protect it.
4416 (condition-case nil
4417 (unwind-protect
4418 (setq ret
4419 (tramp-send-command-and-check
4420 v (format "\\cd %s; %s"
4421 (tramp-shell-quote-argument localname)
4422 command)
4423 nil t))
4424 ;; We should show the output anyway.
4425 (when outbuf
4426 (with-current-buffer outbuf
4427 (insert
4428 (with-current-buffer (tramp-get-connection-buffer v)
4429 (buffer-string))))
4430 (when display (display-buffer outbuf))))
4431 ;; When the user did interrupt, we should do it also. We use
4432 ;; return code -1 as marker.
4433 (quit
4434 (kill-buffer (tramp-get-connection-buffer v))
4435 (setq ret -1))
4436 ;; Handle errors.
4437 (error
4438 (kill-buffer (tramp-get-connection-buffer v))
4439 (setq ret 1)))
4441 ;; Provide error file.
4442 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4444 ;; Cleanup. We remove all file cache values for the connection,
4445 ;; because the remote process could have changed them.
4446 (when tmpinput (delete-file tmpinput))
4448 ;; `process-file-side-effects' has been introduced with GNU
4449 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4450 ;; by `program'. If it doesn't exist, we assume its default
4451 ;; value 't'.
4452 (unless (and (boundp 'process-file-side-effects)
4453 (not (symbol-value 'process-file-side-effects)))
4454 (tramp-flush-directory-property v ""))
4456 ;; Return exit status.
4457 (if (equal ret -1)
4458 (keyboard-quit)
4459 ret))))
4461 (defun tramp-local-call-process
4462 (program &optional infile destination display &rest args)
4463 "Calls `call-process' on the local host.
4464 This is needed because for some Emacs flavors Tramp has
4465 defadviced `call-process' to behave like `process-file'. The
4466 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4467 (let ((default-directory
4468 (if (file-remote-p default-directory)
4469 (tramp-compat-temporary-file-directory)
4470 default-directory)))
4471 (if (executable-find program)
4472 (apply 'call-process program infile destination display args)
4473 1)))
4475 (defun tramp-handle-call-process-region
4476 (start end program &optional delete buffer display &rest args)
4477 "Like `call-process-region' for Tramp files."
4478 (let ((tmpfile (tramp-compat-make-temp-file "")))
4479 (write-region start end tmpfile)
4480 (when delete (delete-region start end))
4481 (unwind-protect
4482 (apply 'call-process program tmpfile buffer display args)
4483 (delete-file tmpfile))))
4485 (defun tramp-handle-shell-command
4486 (command &optional output-buffer error-buffer)
4487 "Like `shell-command' for Tramp files."
4488 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4489 ;; We cannot use `shell-file-name' and `shell-command-switch',
4490 ;; they are variables of the local host.
4491 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
4492 current-buffer-p
4493 (output-buffer
4494 (cond
4495 ((bufferp output-buffer) output-buffer)
4496 ((stringp output-buffer) (get-buffer-create output-buffer))
4497 (output-buffer
4498 (setq current-buffer-p t)
4499 (current-buffer))
4500 (t (get-buffer-create
4501 (if asynchronous
4502 "*Async Shell Command*"
4503 "*Shell Command Output*")))))
4504 (error-buffer
4505 (cond
4506 ((bufferp error-buffer) error-buffer)
4507 ((stringp error-buffer) (get-buffer-create error-buffer))))
4508 (buffer
4509 (if (and (not asynchronous) error-buffer)
4510 (with-parsed-tramp-file-name default-directory nil
4511 (list output-buffer (tramp-make-tramp-temp-file v)))
4512 output-buffer))
4513 (p (get-buffer-process output-buffer)))
4515 ;; Check whether there is another process running. Tramp does not
4516 ;; support 2 (asynchronous) processes in parallel.
4517 (when p
4518 (if (yes-or-no-p "A command is running. Kill it? ")
4519 (condition-case nil
4520 (kill-process p)
4521 (error nil))
4522 (error "Shell command in progress")))
4524 (if current-buffer-p
4525 (progn
4526 (barf-if-buffer-read-only)
4527 (push-mark nil t))
4528 (with-current-buffer output-buffer
4529 (setq buffer-read-only nil)
4530 (erase-buffer)))
4532 (if (and (not current-buffer-p) (integerp asynchronous))
4533 (prog1
4534 ;; Run the process.
4535 (apply 'start-file-process "*Async Shell*" buffer args)
4536 ;; Display output.
4537 (pop-to-buffer output-buffer)
4538 (setq mode-line-process '(":%s"))
4539 (require 'shell) (shell-mode))
4541 (prog1
4542 ;; Run the process.
4543 (apply 'process-file (car args) nil buffer nil (cdr args))
4544 ;; Insert error messages if they were separated.
4545 (when (listp buffer)
4546 (with-current-buffer error-buffer
4547 (insert-file-contents (cadr buffer)))
4548 (delete-file (cadr buffer)))
4549 (if current-buffer-p
4550 ;; This is like exchange-point-and-mark, but doesn't
4551 ;; activate the mark. It is cleaner to avoid activation,
4552 ;; even though the command loop would deactivate the mark
4553 ;; because we inserted text.
4554 (goto-char (prog1 (mark t)
4555 (set-marker (mark-marker) (point)
4556 (current-buffer))))
4557 ;; There's some output, display it.
4558 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4559 (if (functionp 'display-message-or-buffer)
4560 (funcall (symbol-function 'display-message-or-buffer)
4561 output-buffer)
4562 (pop-to-buffer output-buffer))))))))
4564 ;; File Editing.
4566 (defvar tramp-handle-file-local-copy-hook nil
4567 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4569 (defun tramp-handle-file-local-copy (filename)
4570 "Like `file-local-copy' for Tramp files."
4572 (with-parsed-tramp-file-name filename nil
4573 (unless (file-exists-p filename)
4574 (tramp-error
4575 v 'file-error
4576 "Cannot make local copy of non-existing file `%s'" filename))
4578 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
4579 (loc-dec (tramp-get-local-coding v "local-decoding"))
4580 (tmpfile (tramp-compat-make-temp-file filename)))
4582 (condition-case err
4583 (cond
4584 ;; `copy-file' handles direct copy and out-of-band methods.
4585 ((or (tramp-local-host-p v)
4586 (tramp-method-out-of-band-p
4587 v (nth 7 (file-attributes filename))))
4588 (copy-file filename tmpfile t t))
4590 ;; Use inline encoding for file transfer.
4591 (rem-enc
4592 (save-excursion
4593 (tramp-message v 5 "Encoding remote file %s..." filename)
4594 (tramp-barf-unless-okay
4596 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4597 "Encoding remote file failed")
4598 (tramp-message v 5 "Encoding remote file %s...done" filename)
4600 (if (and (symbolp loc-dec) (fboundp loc-dec))
4601 ;; If local decoding is a function, we call it. We
4602 ;; must disable multibyte, because
4603 ;; `uudecode-decode-region' doesn't handle it
4604 ;; correctly.
4605 (with-temp-buffer
4606 (set-buffer-multibyte nil)
4607 (insert-buffer-substring (tramp-get-buffer v))
4608 (tramp-message
4609 v 5 "Decoding remote file %s with function %s..."
4610 filename loc-dec)
4611 (funcall loc-dec (point-min) (point-max))
4612 ;; Unset `file-name-handler-alist'. Otherwise,
4613 ;; epa-file gets confused.
4614 (let (file-name-handler-alist
4615 (coding-system-for-write 'binary))
4616 (write-region (point-min) (point-max) tmpfile)))
4618 ;; If tramp-decoding-function is not defined for this
4619 ;; method, we invoke tramp-decoding-command instead.
4620 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4621 ;; Unset `file-name-handler-alist'. Otherwise,
4622 ;; epa-file gets confused.
4623 (let (file-name-handler-alist
4624 (coding-system-for-write 'binary))
4625 (write-region (point-min) (point-max) tmpfile2))
4626 (tramp-message
4627 v 5 "Decoding remote file %s with command %s..."
4628 filename loc-dec)
4629 (unwind-protect
4630 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4631 (delete-file tmpfile2))))
4633 (tramp-message v 5 "Decoding remote file %s...done" filename)
4634 ;; Set proper permissions.
4635 (set-file-modes tmpfile (tramp-default-file-modes filename))
4636 ;; Set local user ownership.
4637 (tramp-set-file-uid-gid tmpfile)))
4639 ;; Oops, I don't know what to do.
4640 (t (tramp-error
4641 v 'file-error "Wrong method specification for `%s'" method)))
4643 ;; Error handling.
4644 ((error quit)
4645 (delete-file tmpfile)
4646 (signal (car err) (cdr err))))
4648 (run-hooks 'tramp-handle-file-local-copy-hook)
4649 tmpfile)))
4651 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4652 "Like `file-remote-p' for Tramp files."
4653 (when (tramp-tramp-file-p filename)
4654 (let* ((v (tramp-dissect-file-name filename))
4655 (p (tramp-get-connection-process v))
4656 (c (and p (processp p) (memq (process-status p) '(run open)))))
4657 ;; We expand the file name only, if there is already a connection.
4658 (with-parsed-tramp-file-name
4659 (if c (expand-file-name filename) filename) nil
4660 (and (or (not connected) c)
4661 (cond
4662 ((eq identification 'method) method)
4663 ((eq identification 'user) user)
4664 ((eq identification 'host) host)
4665 ((eq identification 'localname) localname)
4666 (t (tramp-make-tramp-file-name method user host ""))))))))
4668 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4669 "Like `find-operation-coding-system' for Tramp filenames.
4670 Tramp's `insert-file-contents' and `write-region' work over
4671 temporary file names. If `file-coding-system-alist' contains an
4672 expression, which matches more than the file name suffix, the
4673 coding system might not be determined. This function repairs it."
4674 (let (result)
4675 (dolist (elt file-coding-system-alist result)
4676 (when (and (consp elt) (string-match (car elt) filename))
4677 ;; We found a matching entry in `file-coding-system-alist'.
4678 ;; So we add a similar entry, but with the temporary file name
4679 ;; as regexp.
4680 (add-to-list
4681 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4683 (defun tramp-handle-insert-file-contents
4684 (filename &optional visit beg end replace)
4685 "Like `insert-file-contents' for Tramp files."
4686 (barf-if-buffer-read-only)
4687 (setq filename (expand-file-name filename))
4688 (let (coding-system-used result local-copy remote-copy)
4689 (with-parsed-tramp-file-name filename nil
4690 (unwind-protect
4691 (if (not (file-exists-p filename))
4692 ;; We don't raise a Tramp error, because it might be
4693 ;; suppressed, like in `find-file-noselect-1'.
4694 (signal 'file-error
4695 (list "File not found on remote host" filename))
4697 (if (and (tramp-local-host-p v)
4698 (let (file-name-handler-alist)
4699 (file-readable-p localname)))
4700 ;; Short track: if we are on the local host, we can
4701 ;; run directly.
4702 (setq result
4703 (tramp-run-real-handler
4704 'insert-file-contents
4705 (list localname visit beg end replace)))
4707 ;; When we shall insert only a part of the file, we copy
4708 ;; this part.
4709 (when (or beg end)
4710 (setq remote-copy (tramp-make-tramp-temp-file v))
4711 (tramp-send-command
4713 (cond
4714 ((and beg end)
4715 (format "tail -c +%d %s | head -c +%d >%s"
4716 (1+ beg) (tramp-shell-quote-argument localname)
4717 (- end beg) remote-copy))
4718 (beg
4719 (format "tail -c +%d %s >%s"
4720 (1+ beg) (tramp-shell-quote-argument localname)
4721 remote-copy))
4722 (end
4723 (format "head -c +%d %s >%s"
4724 (1+ end) (tramp-shell-quote-argument localname)
4725 remote-copy)))))
4727 ;; `insert-file-contents-literally' takes care to avoid
4728 ;; calling jka-compr. By let-binding
4729 ;; `inhibit-file-name-operation', we propagate that care
4730 ;; to the `file-local-copy' operation.
4731 (setq local-copy
4732 (let ((inhibit-file-name-operation
4733 (when (eq inhibit-file-name-operation
4734 'insert-file-contents)
4735 'file-local-copy)))
4736 (cond
4737 ((stringp remote-copy)
4738 (file-local-copy
4739 (tramp-make-tramp-file-name
4740 method user host remote-copy)))
4741 ((stringp tramp-temp-buffer-file-name)
4742 (copy-file filename tramp-temp-buffer-file-name 'ok)
4743 tramp-temp-buffer-file-name)
4744 (t (file-local-copy filename)))))
4746 (when (and (null remote-copy)
4747 (tramp-get-method-parameter
4748 method 'tramp-copy-keep-tmpfile))
4749 ;; We keep the local file for performance reasons,
4750 ;; useful for "rsync".
4751 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4752 (setq tramp-temp-buffer-file-name local-copy)
4753 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4755 (tramp-message
4756 v 4 "Inserting local temp file `%s'..." local-copy)
4758 ;; We must ensure that `file-coding-system-alist'
4759 ;; matches `local-copy'.
4760 (let ((file-coding-system-alist
4761 (tramp-find-file-name-coding-system-alist
4762 filename local-copy)))
4763 (setq result
4764 (insert-file-contents
4765 local-copy nil nil nil replace))
4766 ;; Now `last-coding-system-used' has right value.
4767 ;; Remember it.
4768 (when (boundp 'last-coding-system-used)
4769 (setq coding-system-used
4770 (symbol-value 'last-coding-system-used))))
4772 (tramp-message
4773 v 4 "Inserting local temp file `%s'...done" local-copy)
4774 (when (boundp 'last-coding-system-used)
4775 (set 'last-coding-system-used coding-system-used))))
4777 ;; Save exit.
4778 (progn
4779 (when visit
4780 (setq buffer-file-name filename)
4781 (setq buffer-read-only (not (file-writable-p filename)))
4782 (set-visited-file-modtime)
4783 (set-buffer-modified-p nil))
4784 (when (and (stringp local-copy)
4785 (or remote-copy (null tramp-temp-buffer-file-name)))
4786 (delete-file local-copy))
4787 (when (stringp remote-copy)
4788 (delete-file
4789 (tramp-make-tramp-file-name method user host remote-copy))))))
4791 ;; Result.
4792 (list (expand-file-name filename)
4793 (cadr result))))
4795 ;; This is needed for XEmacs only. Code stolen from files.el.
4796 (defun tramp-handle-insert-file-contents-literally
4797 (filename &optional visit beg end replace)
4798 "Like `insert-file-contents-literally' for Tramp files."
4799 (let ((format-alist nil)
4800 (after-insert-file-functions nil)
4801 (coding-system-for-read 'no-conversion)
4802 (coding-system-for-write 'no-conversion)
4803 (find-buffer-file-type-function
4804 (if (fboundp 'find-buffer-file-type)
4805 (symbol-function 'find-buffer-file-type)
4806 nil))
4807 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4808 (inhibit-file-name-operation 'insert-file-contents))
4809 (unwind-protect
4810 (progn
4811 (fset 'find-buffer-file-type (lambda (filename) t))
4812 (insert-file-contents filename visit beg end replace))
4813 ;; Save exit.
4814 (if find-buffer-file-type-function
4815 (fset 'find-buffer-file-type find-buffer-file-type-function)
4816 (fmakunbound 'find-buffer-file-type)))))
4818 (defun tramp-handle-find-backup-file-name (filename)
4819 "Like `find-backup-file-name' for Tramp files."
4820 (with-parsed-tramp-file-name filename nil
4821 ;; We set both variables. It doesn't matter whether it is
4822 ;; Emacs or XEmacs
4823 (let ((backup-directory-alist
4824 ;; Emacs case
4825 (when (boundp 'backup-directory-alist)
4826 (if (symbol-value 'tramp-backup-directory-alist)
4827 (mapcar
4828 (lambda (x)
4829 (cons
4830 (car x)
4831 (if (and (stringp (cdr x))
4832 (file-name-absolute-p (cdr x))
4833 (not (tramp-file-name-p (cdr x))))
4834 (tramp-make-tramp-file-name method user host (cdr x))
4835 (cdr x))))
4836 (symbol-value 'tramp-backup-directory-alist))
4837 (symbol-value 'backup-directory-alist))))
4839 (bkup-backup-directory-info
4840 ;; XEmacs case
4841 (when (boundp 'bkup-backup-directory-info)
4842 (if (symbol-value 'tramp-bkup-backup-directory-info)
4843 (mapcar
4844 (lambda (x)
4845 (nconc
4846 (list (car x))
4847 (list
4848 (if (and (stringp (car (cdr x)))
4849 (file-name-absolute-p (car (cdr x)))
4850 (not (tramp-file-name-p (car (cdr x)))))
4851 (tramp-make-tramp-file-name
4852 method user host (car (cdr x)))
4853 (car (cdr x))))
4854 (cdr (cdr x))))
4855 (symbol-value 'tramp-bkup-backup-directory-info))
4856 (symbol-value 'bkup-backup-directory-info)))))
4858 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
4860 (defun tramp-handle-make-auto-save-file-name ()
4861 "Like `make-auto-save-file-name' for Tramp files.
4862 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
4863 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4864 (buffer-file-name
4865 (tramp-subst-strs-in-string
4866 '(("_" . "|")
4867 ("/" . "_a")
4868 (":" . "_b")
4869 ("|" . "__")
4870 ("[" . "_l")
4871 ("]" . "_r"))
4872 (buffer-file-name))))
4873 ;; File name must be unique. This is ensured with Emacs 22 (see
4874 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4875 ;; all other cases we must do it ourselves.
4876 (when (boundp 'auto-save-file-name-transforms)
4877 (mapc
4878 (lambda (x)
4879 (when (and (string-match (car x) buffer-file-name)
4880 (not (car (cddr x))))
4881 (setq tramp-auto-save-directory
4882 (or tramp-auto-save-directory
4883 (tramp-compat-temporary-file-directory)))))
4884 (symbol-value 'auto-save-file-name-transforms)))
4885 ;; Create directory.
4886 (when tramp-auto-save-directory
4887 (setq buffer-file-name
4888 (expand-file-name buffer-file-name tramp-auto-save-directory))
4889 (unless (file-exists-p tramp-auto-save-directory)
4890 (make-directory tramp-auto-save-directory t)))
4891 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4892 ;; it is not a magic file name operation (since Emacs 22).
4893 ;; We must deactivate it temporarily.
4894 (if (not (ad-is-active 'make-auto-save-file-name))
4895 (tramp-run-real-handler 'make-auto-save-file-name nil)
4896 ;; else
4897 (ad-deactivate 'make-auto-save-file-name)
4898 (prog1
4899 (tramp-run-real-handler 'make-auto-save-file-name nil)
4900 (ad-activate 'make-auto-save-file-name)))))
4902 (defvar tramp-handle-write-region-hook nil
4903 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4905 ;; CCC grok LOCKNAME
4906 (defun tramp-handle-write-region
4907 (start end filename &optional append visit lockname confirm)
4908 "Like `write-region' for Tramp files."
4909 (setq filename (expand-file-name filename))
4910 (with-parsed-tramp-file-name filename nil
4911 ;; Following part commented out because we don't know what to do about
4912 ;; file locking, and it does not appear to be a problem to ignore it.
4913 ;; Ange-ftp ignores it, too.
4914 ;; (when (and lockname (stringp lockname))
4915 ;; (setq lockname (expand-file-name lockname)))
4916 ;; (unless (or (eq lockname nil)
4917 ;; (string= lockname filename))
4918 ;; (error
4919 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
4921 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
4922 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4923 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4924 (tramp-error v 'file-error "File not overwritten")))
4926 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
4927 (tramp-get-remote-uid v 'integer)))
4928 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
4929 (tramp-get-remote-gid v 'integer))))
4931 (if (and (tramp-local-host-p v)
4932 ;; `file-writable-p' calls `file-expand-file-name'. We
4933 ;; cannot use `tramp-run-real-handler' therefore.
4934 (let (file-name-handler-alist)
4935 (and
4936 (file-writable-p (file-name-directory localname))
4937 (or (file-directory-p localname)
4938 (file-writable-p localname)))))
4939 ;; Short track: if we are on the local host, we can run directly.
4940 (progn
4941 (tramp-run-real-handler
4942 'write-region
4943 (list start end localname append 'no-message lockname confirm))
4944 (tramp-flush-file-property v localname))
4946 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4947 (loc-enc (tramp-get-local-coding v "local-encoding"))
4948 (modes (save-excursion (tramp-default-file-modes filename)))
4949 ;; We use this to save the value of
4950 ;; `last-coding-system-used' after writing the tmp file.
4951 ;; At the end of the function, we set
4952 ;; `last-coding-system-used' to this saved value. This
4953 ;; way, any intermediary coding systems used while
4954 ;; talking to the remote shell or suchlike won't hose
4955 ;; this variable. This approach was snarfed from
4956 ;; ange-ftp.el.
4957 coding-system-used
4958 ;; Write region into a tmp file. This isn't really
4959 ;; needed if we use an encoding function, but currently
4960 ;; we use it always because this makes the logic
4961 ;; simpler.
4962 (tmpfile (or tramp-temp-buffer-file-name
4963 (tramp-compat-make-temp-file filename))))
4965 ;; If `append' is non-nil, we copy the file locally, and let
4966 ;; the native `write-region' implementation do the job.
4967 (when append (copy-file filename tmpfile 'ok))
4969 ;; We say `no-message' here because we don't want the
4970 ;; visited file modtime data to be clobbered from the temp
4971 ;; file. We call `set-visited-file-modtime' ourselves later
4972 ;; on. We must ensure that `file-coding-system-alist'
4973 ;; matches `tmpfile'.
4974 (let ((file-coding-system-alist
4975 (tramp-find-file-name-coding-system-alist filename tmpfile)))
4976 (condition-case err
4977 (tramp-run-real-handler
4978 'write-region
4979 (list start end tmpfile append 'no-message lockname confirm))
4980 ((error quit)
4981 (setq tramp-temp-buffer-file-name nil)
4982 (delete-file tmpfile)
4983 (signal (car err) (cdr err))))
4985 ;; Now, `last-coding-system-used' has the right value. Remember it.
4986 (when (boundp 'last-coding-system-used)
4987 (setq coding-system-used
4988 (symbol-value 'last-coding-system-used))))
4990 ;; The permissions of the temporary file should be set. If
4991 ;; filename does not exist (eq modes nil) it has been
4992 ;; renamed to the backup file. This case `save-buffer'
4993 ;; handles permissions.
4994 (when modes (set-file-modes tmpfile modes))
4996 ;; This is a bit lengthy due to the different methods
4997 ;; possible for file transfer. First, we check whether the
4998 ;; method uses an rcp program. If so, we call it.
4999 ;; Otherwise, both encoding and decoding command must be
5000 ;; specified. However, if the method _also_ specifies an
5001 ;; encoding function, then that is used for encoding the
5002 ;; contents of the tmp file.
5003 (cond
5004 ;; `rename-file' handles direct copy and out-of-band methods.
5005 ((or (tramp-local-host-p v)
5006 (tramp-method-out-of-band-p
5007 v (- (or end (point-max)) (or start (point-min)))))
5008 (if (and (= (or end (point-max)) (point-max))
5009 (= (or start (point-min)) (point-min))
5010 (tramp-get-method-parameter
5011 method 'tramp-copy-keep-tmpfile))
5012 (progn
5013 (setq tramp-temp-buffer-file-name tmpfile)
5014 (condition-case err
5015 ;; We keep the local file for performance
5016 ;; reasons, useful for "rsync".
5017 (copy-file tmpfile filename t)
5018 ((error quit)
5019 (setq tramp-temp-buffer-file-name nil)
5020 (delete-file tmpfile)
5021 (signal (car err) (cdr err)))))
5022 (setq tramp-temp-buffer-file-name nil)
5023 ;; Don't rename, in order to keep context in SELinux.
5024 (unwind-protect
5025 (copy-file tmpfile filename t)
5026 (delete-file tmpfile))))
5028 ;; Use inline file transfer.
5029 (rem-dec
5030 ;; Encode tmpfile.
5031 (tramp-message v 5 "Encoding region...")
5032 (unwind-protect
5033 (with-temp-buffer
5034 ;; Use encoding function or command.
5035 (if (and (symbolp loc-enc) (fboundp loc-enc))
5036 (progn
5037 (tramp-message
5038 v 5 "Encoding region using function `%s'..."
5039 (symbol-name loc-enc))
5040 (let ((coding-system-for-read 'binary))
5041 (insert-file-contents-literally tmpfile))
5042 ;; The following `let' is a workaround for the
5043 ;; base64.el that comes with pgnus-0.84. If
5044 ;; both of the following conditions are
5045 ;; satisfied, it tries to write to a local
5046 ;; file in default-directory, but at this
5047 ;; point, default-directory is remote.
5048 ;; (`call-process-region' can't write to
5049 ;; remote files, it seems.) The file in
5050 ;; question is a tmp file anyway.
5051 (let ((default-directory
5052 (tramp-compat-temporary-file-directory)))
5053 (funcall loc-enc (point-min) (point-max))))
5055 (tramp-message
5056 v 5 "Encoding region using command `%s'..." loc-enc)
5057 (unless (equal 0 (tramp-call-local-coding-command
5058 loc-enc tmpfile t))
5059 (tramp-error
5060 v 'file-error
5061 "Cannot write to `%s', local encoding command `%s' failed"
5062 filename loc-enc)))
5064 ;; Send buffer into remote decoding command which
5065 ;; writes to remote file. Because this happens on
5066 ;; the remote host, we cannot use the function.
5067 (goto-char (point-max))
5068 (unless (bolp) (newline))
5069 (tramp-message
5070 v 5 "Decoding region into remote file %s..." filename)
5071 (tramp-send-command
5073 (format
5074 "%s >%s <<'EOF'\n%sEOF"
5075 rem-dec
5076 (tramp-shell-quote-argument localname)
5077 (buffer-string)))
5078 (tramp-barf-unless-okay
5079 v nil
5080 "Couldn't write region to `%s', decode using `%s' failed"
5081 filename rem-dec)
5082 ;; When `file-precious-flag' is set, the region is
5083 ;; written to a temporary file. Check that the
5084 ;; checksum is equal to that from the local tmpfile.
5085 (when file-precious-flag
5086 (erase-buffer)
5087 (and
5088 ;; cksum runs locally, if possible.
5089 (zerop (tramp-local-call-process "cksum" tmpfile t))
5090 ;; cksum runs remotely.
5091 (zerop
5092 (tramp-send-command-and-check
5094 (format
5095 "cksum <%s" (tramp-shell-quote-argument localname))))
5096 ;; ... they are different.
5097 (not
5098 (string-equal
5099 (buffer-string)
5100 (with-current-buffer (tramp-get-buffer v)
5101 (buffer-string))))
5102 (tramp-error
5103 v 'file-error
5104 (concat "Couldn't write region to `%s',"
5105 " decode using `%s' failed")
5106 filename rem-dec)))
5107 (tramp-message
5108 v 5 "Decoding region into remote file %s...done" filename)
5109 (tramp-flush-file-property v localname))
5111 ;; Save exit.
5112 (delete-file tmpfile)))
5114 ;; That's not expected.
5116 (tramp-error
5117 v 'file-error
5118 (concat "Method `%s' should specify both encoding and "
5119 "decoding command or an rcp program")
5120 method)))
5122 ;; Make `last-coding-system-used' have the right value.
5123 (when coding-system-used
5124 (set 'last-coding-system-used coding-system-used))))
5126 ;; We must protect `last-coding-system-used', now we have set it
5127 ;; to its correct value.
5128 (let (last-coding-system-used (need-chown t))
5129 ;; Set file modification time.
5130 (when (or (eq visit t) (stringp visit))
5131 (let ((file-attr (file-attributes filename)))
5132 (set-visited-file-modtime
5133 ;; We must pass modtime explicitely, because filename can
5134 ;; be different from (buffer-file-name), f.e. if
5135 ;; `file-precious-flag' is set.
5136 (nth 5 file-attr))
5137 (when (and (eq (nth 2 file-attr) uid)
5138 (eq (nth 3 file-attr) gid))
5139 (setq need-chown nil))))
5141 ;; Set the ownership.
5142 (when need-chown
5143 (tramp-set-file-uid-gid filename uid gid))
5144 (when (or (eq visit t) (null visit) (stringp visit))
5145 (tramp-message v 0 "Wrote %s" filename))
5146 (run-hooks 'tramp-handle-write-region-hook)))))
5148 (defvar tramp-vc-registered-file-names nil
5149 "List used to collect file names, which are checked during `vc-registered'.")
5151 ;; VC backends check for the existence of various different special
5152 ;; files. This is very time consuming, because every single check
5153 ;; requires a remote command (the file cache must be invalidated).
5154 ;; Therefore, we apply a kind of optimization. We install the file
5155 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5156 ;; remembers all file names for which `file-exists-p' or
5157 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5158 ;; is performed. Afterwards, a script is applied for all collected
5159 ;; file names, using just one remote command. The result of this
5160 ;; script is used to fill the file cache with actual values. Now we
5161 ;; can reset the file name handlers, and we make a second run of
5162 ;; `vc-registered', which returns the expected result without sending
5163 ;; any other remote command.
5164 (defun tramp-handle-vc-registered (file)
5165 "Like `vc-registered' for Tramp files."
5166 (with-parsed-tramp-file-name file nil
5168 ;; There could be new files, created by the vc backend. We cannot
5169 ;; reuse the old cache entries, therefore.
5170 (let (tramp-vc-registered-file-names
5171 (tramp-cache-inhibit-cache (current-time))
5172 (file-name-handler-alist
5173 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5175 ;; Here we collect only file names, which need an operation.
5176 (tramp-run-real-handler 'vc-registered (list file))
5177 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5179 ;; Send just one command, in order to fill the cache.
5180 (when tramp-vc-registered-file-names
5181 (tramp-maybe-send-script
5183 (format tramp-vc-registered-read-file-names
5184 (tramp-get-file-exists-command v)
5185 (format "%s -r" (tramp-get-test-command v)))
5186 "tramp_vc_registered_read_file_names")
5188 (dolist
5189 (elt
5190 (tramp-send-command-and-read
5192 (format
5193 "tramp_vc_registered_read_file_names %s"
5194 (mapconcat 'tramp-shell-quote-argument
5195 tramp-vc-registered-file-names
5196 " "))))
5198 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
5200 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
5201 ;; shall be answered from the file cache.
5202 ;; We unset `process-file-side-effects' in order to keep the cache
5203 ;; when `process-file' calls appear.
5204 (let (process-file-side-effects)
5205 (tramp-run-real-handler 'vc-registered (list file)))))
5207 ;;;###autoload
5208 (progn (defun tramp-run-real-handler (operation args)
5209 "Invoke normal file name handler for OPERATION.
5210 First arg specifies the OPERATION, second arg is a list of arguments to
5211 pass to the OPERATION."
5212 (let* ((inhibit-file-name-handlers
5213 `(tramp-file-name-handler
5214 tramp-vc-file-name-handler
5215 tramp-completion-file-name-handler
5216 cygwin-mount-name-hook-function
5217 cygwin-mount-map-drive-hook-function
5219 ,(and (eq inhibit-file-name-operation operation)
5220 inhibit-file-name-handlers)))
5221 (inhibit-file-name-operation operation))
5222 (apply operation args))))
5224 ;;;###autoload
5225 (progn (defun tramp-completion-run-real-handler (operation args)
5226 "Invoke `tramp-file-name-handler' for OPERATION.
5227 First arg specifies the OPERATION, second arg is a list of arguments to
5228 pass to the OPERATION."
5229 (let* ((inhibit-file-name-handlers
5230 `(tramp-completion-file-name-handler
5231 cygwin-mount-name-hook-function
5232 cygwin-mount-map-drive-hook-function
5234 ,(and (eq inhibit-file-name-operation operation)
5235 inhibit-file-name-handlers)))
5236 (inhibit-file-name-operation operation))
5237 (apply operation args))))
5239 ;; We handle here all file primitives. Most of them have the file
5240 ;; name as first parameter; nevertheless we check for them explicitly
5241 ;; in order to be signaled if a new primitive appears. This
5242 ;; scenario is needed because there isn't a way to decide by
5243 ;; syntactical means whether a foreign method must be called. It would
5244 ;; ease the life if `file-name-handler-alist' would support a decision
5245 ;; function as well but regexp only.
5246 (defun tramp-file-name-for-operation (operation &rest args)
5247 "Return file name related to OPERATION file primitive.
5248 ARGS are the arguments OPERATION has been called with."
5249 (cond
5250 ; FILE resp DIRECTORY
5251 ((member operation
5252 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5253 'delete-file 'diff-latest-backup-file 'directory-file-name
5254 'directory-files 'directory-files-and-attributes
5255 'dired-compress-file 'dired-uncache
5256 'file-accessible-directory-p 'file-attributes
5257 'file-directory-p 'file-executable-p 'file-exists-p
5258 'file-local-copy 'file-remote-p 'file-modes
5259 'file-name-as-directory 'file-name-directory
5260 'file-name-nondirectory 'file-name-sans-versions
5261 'file-ownership-preserved-p 'file-readable-p
5262 'file-regular-p 'file-symlink-p 'file-truename
5263 'file-writable-p 'find-backup-file-name 'find-file-noselect
5264 'get-file-buffer 'insert-directory 'insert-file-contents
5265 'load 'make-directory 'make-directory-internal
5266 'set-file-modes 'substitute-in-file-name
5267 'unhandled-file-name-directory 'vc-registered
5268 ; Emacs 22 only
5269 'set-file-times
5270 ; XEmacs only
5271 'abbreviate-file-name 'create-file-buffer
5272 'dired-file-modtime 'dired-make-compressed-filename
5273 'dired-recursive-delete-directory 'dired-set-file-modtime
5274 'dired-shell-unhandle-file-name 'dired-uucode-file
5275 'insert-file-contents-literally 'make-temp-name 'recover-file
5276 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5277 (if (file-name-absolute-p (nth 0 args))
5278 (nth 0 args)
5279 (expand-file-name (nth 0 args))))
5280 ; FILE DIRECTORY resp FILE1 FILE2
5281 ((member operation
5282 (list 'add-name-to-file 'copy-file 'expand-file-name
5283 'file-name-all-completions 'file-name-completion
5284 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5285 ; Emacs 23 only
5286 'copy-directory
5287 ; XEmacs only
5288 'dired-make-relative-symlink
5289 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5290 (save-match-data
5291 (cond
5292 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5293 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5294 (t (buffer-file-name (current-buffer))))))
5295 ; START END FILE
5296 ((eq operation 'write-region)
5297 (nth 2 args))
5298 ; BUF
5299 ((member operation
5300 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5301 ; since Emacs 22 only
5302 'make-auto-save-file-name
5303 ; XEmacs only
5304 'backup-buffer))
5305 (buffer-file-name
5306 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5307 ; COMMAND
5308 ((member operation
5309 (list ; not in Emacs 23
5310 'dired-call-process
5311 ; Emacs only
5312 'shell-command
5313 ; since Emacs 22 only
5314 'process-file
5315 ; since Emacs 23 only
5316 'start-file-process
5317 ; XEmacs only
5318 'dired-print-file 'dired-shell-call-process
5319 ; nowhere yet
5320 'executable-find 'start-process 'call-process))
5321 default-directory)
5322 ; unknown file primitive
5323 (t (error "unknown file I/O primitive: %s" operation))))
5325 (defun tramp-find-foreign-file-name-handler (filename)
5326 "Return foreign file name handler if exists."
5327 (when (and (stringp filename) (tramp-tramp-file-p filename))
5328 (let ((v (tramp-dissect-file-name filename t))
5329 (handler tramp-foreign-file-name-handler-alist)
5330 elt res)
5331 ;; When we are not fully sure that filename completion is safe,
5332 ;; we should not return a handler.
5333 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5334 (and (tramp-file-name-host v)
5335 (not (member (tramp-file-name-host v)
5336 (mapcar 'car tramp-methods))))
5337 (not (tramp-completion-mode-p)))
5338 (while handler
5339 (setq elt (car handler)
5340 handler (cdr handler))
5341 (when (funcall (car elt) filename)
5342 (setq handler nil
5343 res (cdr elt))))
5344 res))))
5346 ;; Main function.
5347 ;;;###autoload
5348 (defun tramp-file-name-handler (operation &rest args)
5349 "Invoke Tramp file name handler.
5350 Falls back to normal file name handler if no Tramp file name handler exists."
5351 (if tramp-mode
5352 (save-match-data
5353 (let* ((filename
5354 (tramp-replace-environment-variables
5355 (apply 'tramp-file-name-for-operation operation args)))
5356 (completion (tramp-completion-mode-p))
5357 (foreign (tramp-find-foreign-file-name-handler filename)))
5358 (with-parsed-tramp-file-name filename nil
5359 (cond
5360 ;; When we are in completion mode, some operations
5361 ;; shouldn't be handled by backend.
5362 ((and completion (zerop (length localname))
5363 (memq operation '(file-exists-p file-directory-p)))
5365 ((and completion (zerop (length localname))
5366 (memq operation '(file-name-as-directory)))
5367 filename)
5368 ;; Call the backend function.
5369 (foreign (apply foreign operation args))
5370 ;; Nothing to do for us.
5371 (t (tramp-run-real-handler operation args))))))
5372 ;; When `tramp-mode' is not enabled, we don't do anything.
5373 (tramp-run-real-handler operation args)))
5375 ;; In Emacs, there is some concurrency due to timers. If a timer
5376 ;; interrupts Tramp and wishes to use the same connection buffer as
5377 ;; the "main" Emacs, then garbage might occur in the connection
5378 ;; buffer. Therefore, we need to make sure that a timer does not use
5379 ;; the same connection buffer as the "main" Emacs. We implement a
5380 ;; cheap global lock, instead of locking each connection buffer
5381 ;; separately. The global lock is based on two variables,
5382 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5383 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5384 ;; processing of a single file operation, so we need to allow
5385 ;; recursive calls. That's where the `tramp-locker' variable comes in
5386 ;; -- it is let-bound to t during the execution of the current
5387 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5388 ;; then we should just proceed because we have been called
5389 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5390 ;; interrupting the "main" Emacs, and then we signal an error.
5392 (defvar tramp-locked nil
5393 "If non-nil, then Tramp is currently busy.
5394 Together with `tramp-locker', this implements a locking mechanism
5395 preventing reentrant calls of Tramp.")
5397 (defvar tramp-locker nil
5398 "If non-nil, then a caller has locked Tramp.
5399 Together with `tramp-locked', this implements a locking mechanism
5400 preventing reentrant calls of Tramp.")
5402 (defun tramp-sh-file-name-handler (operation &rest args)
5403 "Invoke remote-shell Tramp file name handler.
5404 Fall back to normal file name handler if no Tramp handler exists."
5405 (when (and tramp-locked (not tramp-locker))
5406 (setq tramp-locked nil)
5407 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5408 (let ((tl tramp-locked))
5409 (unwind-protect
5410 (progn
5411 (setq tramp-locked t)
5412 (let ((tramp-locker t))
5413 (save-match-data
5414 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5415 (if fn
5416 (apply (cdr fn) args)
5417 (tramp-run-real-handler operation args))))))
5418 (setq tramp-locked tl))))
5420 (defun tramp-vc-file-name-handler (operation &rest args)
5421 "Invoke special file name handler, which collects files to be handled."
5422 (save-match-data
5423 (let ((filename
5424 (tramp-replace-environment-variables
5425 (apply 'tramp-file-name-for-operation operation args)))
5426 (fn (assoc operation tramp-file-name-handler-alist)))
5427 (with-parsed-tramp-file-name filename nil
5428 (cond
5429 ;; That's what we want: file names, for which checks are
5430 ;; applied. We assume, that VC uses only `file-exists-p' and
5431 ;; `file-readable-p' checks; otherwise we must extend the
5432 ;; list. We do not perform any action, but return nil, in
5433 ;; order to keep `vc-registered' running.
5434 ((and fn (memq operation '(file-exists-p file-readable-p)))
5435 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5436 nil)
5437 ;; Tramp file name handlers like `expand-file-name'. They
5438 ;; must still work.
5440 (save-match-data (apply (cdr fn) args)))
5441 ;; Default file name handlers, we don't care.
5442 (t (tramp-run-real-handler operation args)))))))
5444 ;;;###autoload
5445 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5446 "Invoke Tramp file name completion handler.
5447 Falls back to normal file name handler if no Tramp file name handler exists."
5448 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5449 ;; would otherwise use backslash.
5450 (let ((directory-sep-char ?/)
5451 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5452 (if (and
5453 ;; When `tramp-mode' is not enabled, we don't do anything.
5454 fn tramp-mode
5455 ;; For other syntaxes than `sep', the regexp matches many common
5456 ;; situations where the user doesn't actually want to use Tramp.
5457 ;; So to avoid autoloading Tramp after typing just "/s", we
5458 ;; disable this part of the completion, unless the user implicitly
5459 ;; indicated his interest in using a fancier completion system.
5460 (or (eq tramp-syntax 'sep)
5461 (featurep 'tramp) ; If it's loaded, we may as well use it.
5462 (and (boundp 'partial-completion-mode) partial-completion-mode)
5463 ;; FIXME: These may have been loaded even if the user never
5464 ;; intended to use them.
5465 (featurep 'ido)
5466 (featurep 'icicles)))
5467 (save-match-data (apply (cdr fn) args))
5468 (tramp-completion-run-real-handler operation args)))))
5470 ;;;###autoload
5471 (progn (defun tramp-register-file-name-handlers ()
5472 "Add Tramp file name handlers to `file-name-handler-alist'."
5473 ;; Remove autoloaded handlers from file name handler alist. Useful,
5474 ;; if `tramp-syntax' has been changed.
5475 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5476 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5477 (let ((a1 (rassq
5478 'tramp-completion-file-name-handler file-name-handler-alist)))
5479 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5480 ;; Add the handlers.
5481 (add-to-list 'file-name-handler-alist
5482 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5483 (add-to-list 'file-name-handler-alist
5484 (cons tramp-completion-file-name-regexp
5485 'tramp-completion-file-name-handler))
5486 (put 'tramp-completion-file-name-handler 'safe-magic t)
5487 ;; If jka-compr or epa-file are already loaded, move them to the
5488 ;; front of `file-name-handler-alist'.
5489 (dolist (fnh '(epa-file-handler jka-compr-handler))
5490 (let ((entry (rassoc fnh file-name-handler-alist)))
5491 (when entry
5492 (setq file-name-handler-alist
5493 (cons entry (delete entry file-name-handler-alist))))))))
5495 ;; `tramp-file-name-handler' must be registered before evaluation of
5496 ;; site-start and init files, because there might exist remote files
5497 ;; already, f.e. files kept via recentf-mode.
5498 ;;;###autoload(tramp-register-file-name-handlers)
5499 (tramp-register-file-name-handlers)
5501 ;;;###autoload
5502 (defun tramp-unload-file-name-handlers ()
5503 (setq file-name-handler-alist
5504 (delete (rassoc 'tramp-file-name-handler
5505 file-name-handler-alist)
5506 (delete (rassoc 'tramp-completion-file-name-handler
5507 file-name-handler-alist)
5508 file-name-handler-alist))))
5510 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5512 ;;; File name handler functions for completion mode:
5514 (defvar tramp-completion-mode nil
5515 "If non-nil, external packages signal that they are in file name completion.
5517 This is necessary, because Tramp uses a heuristic depending on last
5518 input event. This fails when external packages use other characters
5519 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5520 should never be set globally, the intention is to let-bind it.")
5522 ;; Necessary because `tramp-file-name-regexp-unified' and
5523 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5524 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5525 ;; to `tramp-file-name-handler'). Otherwise, it takes
5526 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5527 ;; risky, because completing a file might require loading other files,
5528 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5529 ;; variable. On the other hand, those files shouldn't have partial
5530 ;; Tramp file name syntax. Maybe another variable should be introduced
5531 ;; overwriting this check in such cases. Or we change Tramp file name
5532 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5533 (defun tramp-completion-mode-p ()
5534 "Checks whether method / user name / host name completion is active."
5536 ;; Signal from outside.
5537 tramp-completion-mode
5538 ;; Emacs.
5539 (equal last-input-event 'tab)
5540 (and (natnump last-input-event)
5542 ;; ?\t has event-modifier 'control.
5543 (equal last-input-event ?\t)
5544 (and (not (event-modifiers last-input-event))
5545 (or (equal last-input-event ?\?)
5546 (equal last-input-event ?\ )))))
5547 ;; XEmacs.
5548 (and (featurep 'xemacs)
5549 ;; `last-input-event' might be nil.
5550 (not (null last-input-event))
5551 ;; `last-input-event' may have no character approximation.
5552 (funcall (symbol-function 'event-to-character) last-input-event)
5554 ;; ?\t has event-modifier 'control.
5555 (equal
5556 (funcall (symbol-function 'event-to-character)
5557 last-input-event) ?\t)
5558 (and (not (event-modifiers last-input-event))
5559 (or (equal
5560 (funcall (symbol-function 'event-to-character)
5561 last-input-event) ?\?)
5562 (equal
5563 (funcall (symbol-function 'event-to-character)
5564 last-input-event) ?\ )))))))
5566 ;; Method, host name and user name completion.
5567 ;; `tramp-completion-dissect-file-name' returns a list of
5568 ;; tramp-file-name structures. For all of them we return possible completions.
5569 ;;;###autoload
5570 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5571 "Like `file-name-all-completions' for partial Tramp files."
5573 (let* ((fullname (tramp-drop-volume-letter
5574 (expand-file-name filename directory)))
5575 ;; Possible completion structures.
5576 (v (tramp-completion-dissect-file-name fullname))
5577 result result1)
5579 (while v
5580 (let* ((car (car v))
5581 (method (tramp-file-name-method car))
5582 (user (tramp-file-name-user car))
5583 (host (tramp-file-name-host car))
5584 (localname (tramp-file-name-localname car))
5585 (m (tramp-find-method method user host))
5586 (tramp-current-user user) ; see `tramp-parse-passwd'
5587 all-user-hosts)
5589 (unless localname ;; Nothing to complete.
5591 (if (or user host)
5593 ;; Method dependent user / host combinations.
5594 (progn
5595 (mapc
5596 (lambda (x)
5597 (setq all-user-hosts
5598 (append all-user-hosts
5599 (funcall (nth 0 x) (nth 1 x)))))
5600 (tramp-get-completion-function m))
5602 (setq result
5603 (append result
5604 (mapcar
5605 (lambda (x)
5606 (tramp-get-completion-user-host
5607 method user host (nth 0 x) (nth 1 x)))
5608 (delq nil all-user-hosts)))))
5610 ;; Possible methods.
5611 (setq result
5612 (append result (tramp-get-completion-methods m)))))
5614 (setq v (cdr v))))
5616 ;; Unify list, remove nil elements.
5617 (while result
5618 (let ((car (car result)))
5619 (when car
5620 (add-to-list
5621 'result1
5622 (substring car (length (tramp-drop-volume-letter directory)))))
5623 (setq result (cdr result))))
5625 ;; Complete local parts.
5626 (append
5627 result1
5628 (condition-case nil
5629 (tramp-completion-run-real-handler
5630 'file-name-all-completions (list filename directory))
5631 (error nil)))))
5633 ;; Method, host name and user name completion for a file.
5634 ;;;###autoload
5635 (defun tramp-completion-handle-file-name-completion
5636 (filename directory &optional predicate)
5637 "Like `file-name-completion' for Tramp files."
5638 (try-completion
5639 filename
5640 (mapcar 'list (file-name-all-completions filename directory))
5641 (when predicate
5642 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5644 ;; I misuse a little bit the tramp-file-name structure in order to handle
5645 ;; completion possibilities for partial methods / user names / host names.
5646 ;; Return value is a list of tramp-file-name structures according to possible
5647 ;; completions. If "localname" is non-nil it means there
5648 ;; shouldn't be a completion anymore.
5650 ;; Expected results:
5652 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5653 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5654 ;; [nil "x" nil nil]
5655 ;; ["x" nil nil nil]
5657 ;; "/x:" "/x:y" "/x:y:"
5658 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5659 ;; "/[x/" "/[x/y"
5660 ;; ["x" nil "" nil] ["x" nil "y" nil]
5661 ;; ["x" "" nil nil] ["x" "y" nil nil]
5663 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5664 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5665 ;; "/[x/y@" "/[x/y@z"
5666 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5667 (defun tramp-completion-dissect-file-name (name)
5668 "Returns a list of `tramp-file-name' structures.
5669 They are collected by `tramp-completion-dissect-file-name1'."
5671 (let* ((result)
5672 (x-nil "\\|\\(\\)")
5673 (tramp-completion-ipv6-regexp
5674 (format
5675 "[^%s]*"
5676 (if (zerop (length tramp-postfix-ipv6-format))
5677 tramp-postfix-host-format
5678 tramp-postfix-ipv6-format)))
5679 ;; "/method" "/[method"
5680 (tramp-completion-file-name-structure1
5681 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5682 1 nil nil nil))
5683 ;; "/user" "/[user"
5684 (tramp-completion-file-name-structure2
5685 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5686 nil 1 nil nil))
5687 ;; "/host" "/[host"
5688 (tramp-completion-file-name-structure3
5689 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5690 nil nil 1 nil))
5691 ;; "/[ipv6" "/[ipv6"
5692 (tramp-completion-file-name-structure4
5693 (list (concat tramp-prefix-regexp
5694 tramp-prefix-ipv6-regexp
5695 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5696 nil nil 1 nil))
5697 ;; "/user@host" "/[user@host"
5698 (tramp-completion-file-name-structure5
5699 (list (concat tramp-prefix-regexp
5700 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5701 "\\(" tramp-host-regexp x-nil "\\)$")
5702 nil 1 2 nil))
5703 ;; "/user@[ipv6" "/[user@ipv6"
5704 (tramp-completion-file-name-structure6
5705 (list (concat tramp-prefix-regexp
5706 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5707 tramp-prefix-ipv6-regexp
5708 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5709 nil 1 2 nil))
5710 ;; "/method:user" "/[method/user" "/method://user"
5711 (tramp-completion-file-name-structure7
5712 (list (concat tramp-prefix-regexp
5713 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5714 "\\(" tramp-user-regexp x-nil "\\)$")
5715 1 2 nil nil))
5716 ;; "/method:host" "/[method/host" "/method://host"
5717 (tramp-completion-file-name-structure8
5718 (list (concat tramp-prefix-regexp
5719 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5720 "\\(" tramp-host-regexp x-nil "\\)$")
5721 1 nil 2 nil))
5722 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5723 (tramp-completion-file-name-structure9
5724 (list (concat tramp-prefix-regexp
5725 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5726 tramp-prefix-ipv6-regexp
5727 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5728 1 nil 2 nil))
5729 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5730 (tramp-completion-file-name-structure10
5731 (list (concat tramp-prefix-regexp
5732 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5733 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5734 "\\(" tramp-host-regexp x-nil "\\)$")
5735 1 2 3 nil))
5736 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5737 (tramp-completion-file-name-structure11
5738 (list (concat tramp-prefix-regexp
5739 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5740 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5741 tramp-prefix-ipv6-regexp
5742 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5743 1 2 3 nil))
5744 ;; "/method: "/method:/"
5745 (tramp-completion-file-name-structure12
5746 (list
5747 (if (equal tramp-syntax 'url)
5748 (concat tramp-prefix-regexp
5749 "\\(" tramp-method-regexp "\\)"
5750 "\\(" (substring tramp-postfix-method-regexp 0 1)
5751 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5752 "\\(" "\\)$")
5753 ;; Should not match if not URL syntax.
5754 (concat tramp-prefix-regexp "/$"))
5755 1 3 nil nil))
5756 ;; "/method: "/method:/"
5757 (tramp-completion-file-name-structure13
5758 (list
5759 (if (equal tramp-syntax 'url)
5760 (concat tramp-prefix-regexp
5761 "\\(" tramp-method-regexp "\\)"
5762 "\\(" (substring tramp-postfix-method-regexp 0 1)
5763 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5764 "\\(" "\\)$")
5765 ;; Should not match if not URL syntax.
5766 (concat tramp-prefix-regexp "/$"))
5767 1 nil 3 nil)))
5769 (mapc (lambda (regexp)
5770 (add-to-list 'result
5771 (tramp-completion-dissect-file-name1 regexp name)))
5772 (list
5773 tramp-completion-file-name-structure1
5774 tramp-completion-file-name-structure2
5775 tramp-completion-file-name-structure3
5776 tramp-completion-file-name-structure4
5777 tramp-completion-file-name-structure5
5778 tramp-completion-file-name-structure6
5779 tramp-completion-file-name-structure7
5780 tramp-completion-file-name-structure8
5781 tramp-completion-file-name-structure9
5782 tramp-completion-file-name-structure10
5783 tramp-completion-file-name-structure11
5784 tramp-completion-file-name-structure12
5785 tramp-completion-file-name-structure13
5786 tramp-file-name-structure))
5788 (delq nil result)))
5790 (defun tramp-completion-dissect-file-name1 (structure name)
5791 "Returns a `tramp-file-name' structure matching STRUCTURE.
5792 The structure consists of remote method, remote user,
5793 remote host and localname (filename on remote host)."
5795 (save-match-data
5796 (when (string-match (nth 0 structure) name)
5797 (let ((method (and (nth 1 structure)
5798 (match-string (nth 1 structure) name)))
5799 (user (and (nth 2 structure)
5800 (match-string (nth 2 structure) name)))
5801 (host (and (nth 3 structure)
5802 (match-string (nth 3 structure) name)))
5803 (localname (and (nth 4 structure)
5804 (match-string (nth 4 structure) name))))
5805 (vector method user host localname)))))
5807 ;; This function returns all possible method completions, adding the
5808 ;; trailing method delimeter.
5809 (defun tramp-get-completion-methods (partial-method)
5810 "Returns all method completions for PARTIAL-METHOD."
5811 (mapcar
5812 (lambda (method)
5813 (and method
5814 (string-match (concat "^" (regexp-quote partial-method)) method)
5815 (tramp-completion-make-tramp-file-name method nil nil nil)))
5816 (mapcar 'car tramp-methods)))
5818 ;; Compares partial user and host names with possible completions.
5819 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
5820 "Returns the most expanded string for user and host name completion.
5821 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5822 (cond
5824 ((and partial-user partial-host)
5825 (if (and host
5826 (string-match (concat "^" (regexp-quote partial-host)) host)
5827 (string-equal partial-user (or user partial-user)))
5828 (setq user partial-user)
5829 (setq user nil
5830 host nil)))
5832 (partial-user
5833 (setq host nil)
5834 (unless
5835 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5836 (setq user nil)))
5838 (partial-host
5839 (setq user nil)
5840 (unless
5841 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5842 (setq host nil)))
5844 (t (setq user nil
5845 host nil)))
5847 (unless (zerop (+ (length user) (length host)))
5848 (tramp-completion-make-tramp-file-name method user host nil)))
5850 (defun tramp-parse-rhosts (filename)
5851 "Return a list of (user host) tuples allowed to access.
5852 Either user or host may be nil."
5853 ;; On Windows, there are problems in completion when
5854 ;; `default-directory' is remote.
5855 (let ((default-directory (tramp-compat-temporary-file-directory))
5856 res)
5857 (when (file-readable-p filename)
5858 (with-temp-buffer
5859 (insert-file-contents filename)
5860 (goto-char (point-min))
5861 (while (not (eobp))
5862 (push (tramp-parse-rhosts-group) res))))
5863 res))
5865 (defun tramp-parse-rhosts-group ()
5866 "Return a (user host) tuple allowed to access.
5867 Either user or host may be nil."
5868 (let ((result)
5869 (regexp
5870 (concat
5871 "^\\(" tramp-host-regexp "\\)"
5872 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5873 (narrow-to-region (point) (tramp-compat-line-end-position))
5874 (when (re-search-forward regexp nil t)
5875 (setq result (append (list (match-string 3) (match-string 1)))))
5876 (widen)
5877 (forward-line 1)
5878 result))
5880 (defun tramp-parse-shosts (filename)
5881 "Return a list of (user host) tuples allowed to access.
5882 User is always nil."
5883 ;; On Windows, there are problems in completion when
5884 ;; `default-directory' is remote.
5885 (let ((default-directory (tramp-compat-temporary-file-directory))
5886 res)
5887 (when (file-readable-p filename)
5888 (with-temp-buffer
5889 (insert-file-contents filename)
5890 (goto-char (point-min))
5891 (while (not (eobp))
5892 (push (tramp-parse-shosts-group) res))))
5893 res))
5895 (defun tramp-parse-shosts-group ()
5896 "Return a (user host) tuple allowed to access.
5897 User is always nil."
5898 (let ((result)
5899 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
5900 (narrow-to-region (point) (tramp-compat-line-end-position))
5901 (when (re-search-forward regexp nil t)
5902 (setq result (list nil (match-string 1))))
5903 (widen)
5905 (> (skip-chars-forward ",") 0)
5906 (forward-line 1))
5907 result))
5909 (defun tramp-parse-sconfig (filename)
5910 "Return a list of (user host) tuples allowed to access.
5911 User is always nil."
5912 ;; On Windows, there are problems in completion when
5913 ;; `default-directory' is remote.
5914 (let ((default-directory (tramp-compat-temporary-file-directory))
5915 res)
5916 (when (file-readable-p filename)
5917 (with-temp-buffer
5918 (insert-file-contents filename)
5919 (goto-char (point-min))
5920 (while (not (eobp))
5921 (push (tramp-parse-sconfig-group) res))))
5922 res))
5924 (defun tramp-parse-sconfig-group ()
5925 "Return a (user host) tuple allowed to access.
5926 User is always nil."
5927 (let ((result)
5928 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
5929 (narrow-to-region (point) (tramp-compat-line-end-position))
5930 (when (re-search-forward regexp nil t)
5931 (setq result (list nil (match-string 1))))
5932 (widen)
5934 (> (skip-chars-forward ",") 0)
5935 (forward-line 1))
5936 result))
5938 (defun tramp-parse-shostkeys (dirname)
5939 "Return a list of (user host) tuples allowed to access.
5940 User is always nil."
5941 ;; On Windows, there are problems in completion when
5942 ;; `default-directory' is remote.
5943 (let* ((default-directory (tramp-compat-temporary-file-directory))
5944 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
5945 (files (when (file-directory-p dirname) (directory-files dirname)))
5946 result)
5947 (while files
5948 (when (string-match regexp (car files))
5949 (push (list nil (match-string 1 (car files))) result))
5950 (setq files (cdr files)))
5951 result))
5953 (defun tramp-parse-sknownhosts (dirname)
5954 "Return a list of (user host) tuples allowed to access.
5955 User is always nil."
5956 ;; On Windows, there are problems in completion when
5957 ;; `default-directory' is remote.
5958 (let* ((default-directory (tramp-compat-temporary-file-directory))
5959 (regexp (concat "^\\(" tramp-host-regexp
5960 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
5961 (files (when (file-directory-p dirname) (directory-files dirname)))
5962 result)
5963 (while files
5964 (when (string-match regexp (car files))
5965 (push (list nil (match-string 1 (car files))) result))
5966 (setq files (cdr files)))
5967 result))
5969 (defun tramp-parse-hosts (filename)
5970 "Return a list of (user host) tuples allowed to access.
5971 User is always nil."
5972 ;; On Windows, there are problems in completion when
5973 ;; `default-directory' is remote.
5974 (let ((default-directory (tramp-compat-temporary-file-directory))
5975 res)
5976 (when (file-readable-p filename)
5977 (with-temp-buffer
5978 (insert-file-contents filename)
5979 (goto-char (point-min))
5980 (while (not (eobp))
5981 (push (tramp-parse-hosts-group) res))))
5982 res))
5984 (defun tramp-parse-hosts-group ()
5985 "Return a (user host) tuple allowed to access.
5986 User is always nil."
5987 (let ((result)
5988 (regexp
5989 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
5990 (narrow-to-region (point) (tramp-compat-line-end-position))
5991 (when (re-search-forward regexp nil t)
5992 (setq result (list nil (match-string 1))))
5993 (widen)
5995 (> (skip-chars-forward " \t") 0)
5996 (forward-line 1))
5997 result))
5999 ;; For su-alike methods it would be desirable to return "root@localhost"
6000 ;; as default. Unfortunately, we have no information whether any user name
6001 ;; has been typed already. So we use `tramp-current-user' as indication,
6002 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6003 (defun tramp-parse-passwd (filename)
6004 "Return a list of (user host) tuples allowed to access.
6005 Host is always \"localhost\"."
6006 ;; On Windows, there are problems in completion when
6007 ;; `default-directory' is remote.
6008 (let ((default-directory (tramp-compat-temporary-file-directory))
6009 res)
6010 (if (zerop (length tramp-current-user))
6011 '(("root" nil))
6012 (when (file-readable-p filename)
6013 (with-temp-buffer
6014 (insert-file-contents filename)
6015 (goto-char (point-min))
6016 (while (not (eobp))
6017 (push (tramp-parse-passwd-group) res))))
6018 res)))
6020 (defun tramp-parse-passwd-group ()
6021 "Return a (user host) tuple allowed to access.
6022 Host is always \"localhost\"."
6023 (let ((result)
6024 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6025 (narrow-to-region (point) (tramp-compat-line-end-position))
6026 (when (re-search-forward regexp nil t)
6027 (setq result (list (match-string 1) "localhost")))
6028 (widen)
6029 (forward-line 1)
6030 result))
6032 (defun tramp-parse-netrc (filename)
6033 "Return a list of (user host) tuples allowed to access.
6034 User may be nil."
6035 ;; On Windows, there are problems in completion when
6036 ;; `default-directory' is remote.
6037 (let ((default-directory (tramp-compat-temporary-file-directory))
6038 res)
6039 (when (file-readable-p filename)
6040 (with-temp-buffer
6041 (insert-file-contents filename)
6042 (goto-char (point-min))
6043 (while (not (eobp))
6044 (push (tramp-parse-netrc-group) res))))
6045 res))
6047 (defun tramp-parse-netrc-group ()
6048 "Return a (user host) tuple allowed to access.
6049 User may be nil."
6050 (let ((result)
6051 (regexp
6052 (concat
6053 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6054 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6055 (narrow-to-region (point) (tramp-compat-line-end-position))
6056 (when (re-search-forward regexp nil t)
6057 (setq result (list (match-string 3) (match-string 1))))
6058 (widen)
6059 (forward-line 1)
6060 result))
6062 (defun tramp-parse-putty (registry)
6063 "Return a list of (user host) tuples allowed to access.
6064 User is always nil."
6065 ;; On Windows, there are problems in completion when
6066 ;; `default-directory' is remote.
6067 (let ((default-directory (tramp-compat-temporary-file-directory))
6068 res)
6069 (with-temp-buffer
6070 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6071 (goto-char (point-min))
6072 (while (not (eobp))
6073 (push (tramp-parse-putty-group registry) res))))
6074 res))
6076 (defun tramp-parse-putty-group (registry)
6077 "Return a (user host) tuple allowed to access.
6078 User is always nil."
6079 (let ((result)
6080 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6081 (narrow-to-region (point) (tramp-compat-line-end-position))
6082 (when (re-search-forward regexp nil t)
6083 (setq result (list nil (match-string 1))))
6084 (widen)
6085 (forward-line 1)
6086 result))
6088 ;;; Internal Functions:
6090 (defun tramp-maybe-send-script (vec script name)
6091 "Define in remote shell function NAME implemented as SCRIPT.
6092 Only send the definition if it has not already been done."
6093 (let* ((p (tramp-get-connection-process vec))
6094 (scripts (tramp-get-connection-property p "scripts" nil)))
6095 (unless (member name scripts)
6096 (tramp-message vec 5 "Sending script `%s'..." name)
6097 ;; The script could contain a call of Perl. This is masked with `%s'.
6098 (tramp-send-command-and-check
6100 (format "%s () {\n%s\n}" name
6101 (format script (tramp-get-remote-perl vec))))
6102 (tramp-set-connection-property p "scripts" (cons name scripts))
6103 (tramp-message vec 5 "Sending script `%s'...done." name))))
6105 (defun tramp-set-auto-save ()
6106 (when (and ;; ange-ftp has its own auto-save mechanism
6107 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6108 'tramp-sh-file-name-handler)
6109 auto-save-default)
6110 (auto-save-mode 1)))
6111 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6112 (add-hook 'tramp-unload-hook
6113 (lambda ()
6114 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6116 (defun tramp-run-test (switch filename)
6117 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6118 Returns the exit code of the `test' program."
6119 (with-parsed-tramp-file-name filename nil
6120 (tramp-send-command-and-check
6122 (format
6123 "%s %s %s"
6124 (tramp-get-test-command v)
6125 switch
6126 (tramp-shell-quote-argument localname)))))
6128 (defun tramp-run-test2 (format-string file1 file2)
6129 "Run `test'-like program on the remote system, given FILE1, FILE2.
6130 FORMAT-STRING contains the program name, switches, and place holders.
6131 Returns the exit code of the `test' program. Barfs if the methods,
6132 hosts, or files, disagree."
6133 (unless (tramp-equal-remote file1 file2)
6134 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6135 (tramp-error
6136 v 'file-error
6137 "tramp-run-test2 only implemented for same method, user, host")))
6138 (with-parsed-tramp-file-name file1 v1
6139 (with-parsed-tramp-file-name file1 v2
6140 (tramp-send-command-and-check
6142 (format format-string
6143 (tramp-shell-quote-argument v1-localname)
6144 (tramp-shell-quote-argument v2-localname))))))
6146 (defun tramp-buffer-name (vec)
6147 "A name for the connection buffer VEC."
6148 ;; We must use `tramp-file-name-real-host', because for gateway
6149 ;; methods the default port will be expanded later on, which would
6150 ;; tamper the name.
6151 (let ((method (tramp-file-name-method vec))
6152 (user (tramp-file-name-user vec))
6153 (host (tramp-file-name-real-host vec)))
6154 (if (not (zerop (length user)))
6155 (format "*tramp/%s %s@%s*" method user host)
6156 (format "*tramp/%s %s*" method host))))
6158 (defun tramp-delete-temp-file-function ()
6159 "Remove temporary files related to current buffer."
6160 (when (stringp tramp-temp-buffer-file-name)
6161 (condition-case nil
6162 (delete-file tramp-temp-buffer-file-name)
6163 (error nil))))
6165 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6166 (add-hook 'tramp-cache-unload-hook
6167 (lambda ()
6168 (remove-hook 'kill-buffer-hook
6169 'tramp-delete-temp-file-function)))
6171 (defun tramp-get-buffer (vec)
6172 "Get the connection buffer to be used for VEC."
6173 (or (get-buffer (tramp-buffer-name vec))
6174 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6175 (setq buffer-undo-list t)
6176 (setq default-directory
6177 (tramp-make-tramp-file-name
6178 (tramp-file-name-method vec)
6179 (tramp-file-name-user vec)
6180 (tramp-file-name-host vec)
6181 "/"))
6182 (current-buffer))))
6184 (defun tramp-get-connection-buffer (vec)
6185 "Get the connection buffer to be used for VEC.
6186 In case a second asynchronous communication has been started, it is different
6187 from `tramp-get-buffer'."
6188 (or (tramp-get-connection-property vec "process-buffer" nil)
6189 (tramp-get-buffer vec)))
6191 (defun tramp-get-connection-process (vec)
6192 "Get the connection process to be used for VEC.
6193 In case a second asynchronous communication has been started, it is different
6194 from the default one."
6195 (get-process
6196 (or (tramp-get-connection-property vec "process-name" nil)
6197 (tramp-buffer-name vec))))
6199 (defun tramp-debug-buffer-name (vec)
6200 "A name for the debug buffer for VEC."
6201 ;; We must use `tramp-file-name-real-host', because for gateway
6202 ;; methods the default port will be expanded later on, which would
6203 ;; tamper the name.
6204 (let ((method (tramp-file-name-method vec))
6205 (user (tramp-file-name-user vec))
6206 (host (tramp-file-name-real-host vec)))
6207 (if (not (zerop (length user)))
6208 (format "*debug tramp/%s %s@%s*" method user host)
6209 (format "*debug tramp/%s %s*" method host))))
6211 (defun tramp-get-debug-buffer (vec)
6212 "Get the debug buffer for VEC."
6213 (with-current-buffer
6214 (get-buffer-create (tramp-debug-buffer-name vec))
6215 (when (bobp)
6216 (setq buffer-undo-list t)
6217 ;; Activate outline-mode. This runs `text-mode-hook' and
6218 ;; `outline-mode-hook'. We must prevent that local processes
6219 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
6220 ;; ...
6221 (let ((default-directory (tramp-compat-temporary-file-directory)))
6222 (outline-mode))
6223 (set (make-local-variable 'outline-regexp)
6224 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6225 ; (set (make-local-variable 'outline-regexp)
6226 ; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
6227 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6228 (current-buffer)))
6230 (defun tramp-outline-level ()
6231 "Return the depth to which a statement is nested in the outline.
6232 Point must be at the beginning of a header line.
6234 The outline level is equal to the verbosity of the Tramp message."
6235 (1+ (string-to-number (match-string 1))))
6237 (defun tramp-find-executable
6238 (vec progname dirlist &optional ignore-tilde ignore-path)
6239 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6240 First arg VEC specifies the connection, PROGNAME is the program
6241 to search for, and DIRLIST gives the list of directories to
6242 search. If IGNORE-TILDE is non-nil, directory names starting
6243 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6244 only in DIRLIST.
6246 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6248 This function expects to be in the right *tramp* buffer."
6249 (with-current-buffer (tramp-get-buffer vec)
6250 (let (result)
6251 ;; Check whether the executable is in $PATH. "which(1)" does not
6252 ;; report always a correct error code; therefore we check the
6253 ;; number of words it returns.
6254 (unless ignore-path
6255 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6256 (goto-char (point-min))
6257 (if (looking-at "^1$")
6258 (setq result (concat "\\" progname))))
6259 (unless result
6260 (when ignore-tilde
6261 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
6262 ;; `remove' is in CL, and we want to avoid CL dependencies.
6263 (let (newdl d)
6264 (while dirlist
6265 (setq d (car dirlist))
6266 (setq dirlist (cdr dirlist))
6267 (unless (char-equal ?~ (aref d 0))
6268 (setq newdl (cons d newdl))))
6269 (setq dirlist (nreverse newdl))))
6270 (tramp-send-command
6272 (format (concat "while read d; "
6273 "do if test -x $d/%s -a -f $d/%s; "
6274 "then echo tramp_executable $d/%s; "
6275 "break; fi; done <<'EOF'\n"
6276 "%s\nEOF")
6277 progname progname progname (mapconcat 'identity dirlist "\n")))
6278 (goto-char (point-max))
6279 (when (search-backward "tramp_executable " nil t)
6280 (skip-chars-forward "^ ")
6281 (skip-chars-forward " ")
6282 (setq result (buffer-substring
6283 (point) (tramp-compat-line-end-position)))))
6284 result)))
6286 (defun tramp-set-remote-path (vec)
6287 "Sets the remote environment PATH to existing directories.
6288 I.e., for each directory in `tramp-remote-path', it is tested
6289 whether it exists and if so, it is added to the environment
6290 variable PATH."
6291 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6292 (tramp-send-command
6293 vec (format "PATH=%s; export PATH"
6294 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6296 ;; ------------------------------------------------------------
6297 ;; -- Communication with external shell --
6298 ;; ------------------------------------------------------------
6300 (defun tramp-find-file-exists-command (vec)
6301 "Find a command on the remote host for checking if a file exists.
6302 Here, we are looking for a command which has zero exit status if the
6303 file exists and nonzero exit status otherwise."
6304 (let ((existing "/")
6305 (nonexisting
6306 (tramp-shell-quote-argument "/ this file does not exist "))
6307 result)
6308 ;; The algorithm is as follows: we try a list of several commands.
6309 ;; For each command, we first run `$cmd /' -- this should return
6310 ;; true, as the root directory always exists. And then we run
6311 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6312 ;; does not exist. This should return false. We use the first
6313 ;; command we find that seems to work.
6314 ;; The list of commands to try is as follows:
6315 ;; `ls -d' This works on most systems, but NetBSD 1.4
6316 ;; has a bug: `ls' always returns zero exit
6317 ;; status, even for files which don't exist.
6318 ;; `test -e' Some Bourne shells have a `test' builtin
6319 ;; which does not know the `-e' option.
6320 ;; `/bin/test -e' For those, the `test' binary on disk normally
6321 ;; provides the option. Alas, the binary
6322 ;; is sometimes `/bin/test' and sometimes it's
6323 ;; `/usr/bin/test'.
6324 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6325 (unless (or
6326 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6327 (zerop (tramp-send-command-and-check
6328 vec (format "%s %s" result existing)))
6329 (not (zerop (tramp-send-command-and-check
6330 vec (format "%s %s" result nonexisting)))))
6331 (and (setq result "/bin/test -e")
6332 (zerop (tramp-send-command-and-check
6333 vec (format "%s %s" result existing)))
6334 (not (zerop (tramp-send-command-and-check
6335 vec (format "%s %s" result nonexisting)))))
6336 (and (setq result "/usr/bin/test -e")
6337 (zerop (tramp-send-command-and-check
6338 vec (format "%s %s" result existing)))
6339 (not (zerop (tramp-send-command-and-check
6340 vec (format "%s %s" result nonexisting)))))
6341 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6342 (zerop (tramp-send-command-and-check
6343 vec (format "%s %s" result existing)))
6344 (not (zerop (tramp-send-command-and-check
6345 vec (format "%s %s" result nonexisting))))))
6346 (tramp-error
6347 vec 'file-error "Couldn't find command to check if file exists"))
6348 result))
6350 ;; CCC test ksh or bash found for tilde expansion?
6351 (defun tramp-find-shell (vec)
6352 "Opens a shell on the remote host which groks tilde expansion."
6353 (unless (tramp-get-connection-property vec "remote-shell" nil)
6354 (let (shell)
6355 (with-current-buffer (tramp-get-buffer vec)
6356 (tramp-send-command vec "echo ~root" t)
6357 (cond
6358 ((string-match "^~root$" (buffer-string))
6359 (setq shell
6360 (or (tramp-find-executable
6361 vec "bash" (tramp-get-remote-path vec) t)
6362 (tramp-find-executable
6363 vec "ksh" (tramp-get-remote-path vec) t)))
6364 (unless shell
6365 (tramp-error
6366 vec 'file-error
6367 "Couldn't find a shell which groks tilde expansion"))
6368 ;; Find arguments for this shell.
6369 (let ((alist tramp-sh-extra-args)
6370 item extra-args)
6371 (while (and alist (null extra-args))
6372 (setq item (pop alist))
6373 (when (string-match (car item) shell)
6374 (setq extra-args (cdr item))))
6375 (when extra-args (setq shell (concat shell " " extra-args))))
6376 (tramp-message
6377 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
6378 (let ((tramp-end-of-output tramp-initial-end-of-output))
6379 (tramp-send-command
6381 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6382 (shell-quote-argument tramp-end-of-output) shell)
6384 ;; Setting prompts.
6385 (tramp-message vec 5 "Setting remote shell prompt...")
6386 (tramp-send-command
6387 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6388 (tramp-send-command vec "PS2=''" t)
6389 (tramp-send-command vec "PS3=''" t)
6390 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6391 (tramp-message vec 5 "Setting remote shell prompt...done"))
6393 (t (tramp-message
6394 vec 5 "Remote `%s' groks tilde expansion, good"
6395 (tramp-get-method-parameter
6396 (tramp-file-name-method vec) 'tramp-remote-sh))
6397 (tramp-set-connection-property
6398 vec "remote-shell"
6399 (tramp-get-method-parameter
6400 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
6402 ;; ------------------------------------------------------------
6403 ;; -- Functions for establishing connection --
6404 ;; ------------------------------------------------------------
6406 ;; The following functions are actions to be taken when seeing certain
6407 ;; prompts from the remote host. See the variable
6408 ;; `tramp-actions-before-shell' for usage of these functions.
6410 (defun tramp-action-login (proc vec)
6411 "Send the login name."
6412 (when (not (stringp tramp-current-user))
6413 (save-window-excursion
6414 (let ((enable-recursive-minibuffers t))
6415 (pop-to-buffer (tramp-get-connection-buffer vec))
6416 (setq tramp-current-user (read-string (match-string 0))))))
6417 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6418 (with-current-buffer (tramp-get-connection-buffer vec)
6419 (tramp-message vec 6 "\n%s" (buffer-string)))
6420 (tramp-send-string vec tramp-current-user))
6422 (defun tramp-action-password (proc vec)
6423 "Query the user for a password."
6424 (with-current-buffer (process-buffer proc)
6425 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6426 (tramp-message vec 3 "Sending %s" (match-string 1)))
6427 (tramp-enter-password proc))
6429 (defun tramp-action-succeed (proc vec)
6430 "Signal success in finding shell prompt."
6431 (throw 'tramp-action 'ok))
6433 (defun tramp-action-permission-denied (proc vec)
6434 "Signal permission denied."
6435 (kill-process proc)
6436 (throw 'tramp-action 'permission-denied))
6438 (defun tramp-action-yesno (proc vec)
6439 "Ask the user for confirmation using `yes-or-no-p'.
6440 Send \"yes\" to remote process on confirmation, abort otherwise.
6441 See also `tramp-action-yn'."
6442 (save-window-excursion
6443 (let ((enable-recursive-minibuffers t))
6444 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6445 (unless (yes-or-no-p (match-string 0))
6446 (kill-process proc)
6447 (throw 'tramp-action 'permission-denied))
6448 (with-current-buffer (tramp-get-connection-buffer vec)
6449 (tramp-message vec 6 "\n%s" (buffer-string)))
6450 (tramp-send-string vec "yes"))))
6452 (defun tramp-action-yn (proc vec)
6453 "Ask the user for confirmation using `y-or-n-p'.
6454 Send \"y\" to remote process on confirmation, abort otherwise.
6455 See also `tramp-action-yesno'."
6456 (save-window-excursion
6457 (let ((enable-recursive-minibuffers t))
6458 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6459 (unless (y-or-n-p (match-string 0))
6460 (kill-process proc)
6461 (throw 'tramp-action 'permission-denied))
6462 (with-current-buffer (tramp-get-connection-buffer vec)
6463 (tramp-message vec 6 "\n%s" (buffer-string)))
6464 (tramp-send-string vec "y"))))
6466 (defun tramp-action-terminal (proc vec)
6467 "Tell the remote host which terminal type to use.
6468 The terminal type can be configured with `tramp-terminal-type'."
6469 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6470 (with-current-buffer (tramp-get-connection-buffer vec)
6471 (tramp-message vec 6 "\n%s" (buffer-string)))
6472 (tramp-send-string vec tramp-terminal-type))
6474 (defun tramp-action-process-alive (proc vec)
6475 "Check whether a process has finished."
6476 (unless (memq (process-status proc) '(run open))
6477 (throw 'tramp-action 'process-died)))
6479 (defun tramp-action-out-of-band (proc vec)
6480 "Check whether an out-of-band copy has finished."
6481 (cond ((and (memq (process-status proc) '(stop exit))
6482 (zerop (process-exit-status proc)))
6483 (tramp-message vec 3 "Process has finished.")
6484 (throw 'tramp-action 'ok))
6485 ((or (and (memq (process-status proc) '(stop exit))
6486 (not (zerop (process-exit-status proc))))
6487 (memq (process-status proc) '(signal)))
6488 ;; `scp' could have copied correctly, but set modes could have failed.
6489 ;; This can be ignored.
6490 (with-current-buffer (process-buffer proc)
6491 (goto-char (point-min))
6492 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6493 (progn
6494 (tramp-message vec 5 "'set mode' error ignored.")
6495 (tramp-message vec 3 "Process has finished.")
6496 (throw 'tramp-action 'ok))
6497 (tramp-message vec 3 "Process has died.")
6498 (throw 'tramp-action 'process-died))))
6499 (t nil)))
6501 ;; Functions for processing the actions.
6503 (defun tramp-process-one-action (proc vec actions)
6504 "Wait for output from the shell and perform one action."
6505 (let (found todo item pattern action)
6506 (while (not found)
6507 ;; Reread output once all actions have been performed.
6508 ;; Obviously, the output was not complete.
6509 (tramp-accept-process-output proc 1)
6510 (setq todo actions)
6511 (while todo
6512 (setq item (pop todo))
6513 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6514 (setq action (nth 1 item))
6515 (tramp-message
6516 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6517 (when (tramp-check-for-regexp proc pattern)
6518 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6519 (setq found (funcall action proc vec)))))
6520 found))
6522 (defun tramp-process-actions (proc vec actions &optional timeout)
6523 "Perform actions until success or TIMEOUT."
6524 ;; Enable auth-source and password-cache.
6525 (tramp-set-connection-property proc "first-password-request" t)
6526 (let (exit)
6527 (while (not exit)
6528 (tramp-message proc 3 "Waiting for prompts from remote shell")
6529 (setq exit
6530 (catch 'tramp-action
6531 (if timeout
6532 (with-timeout (timeout)
6533 (tramp-process-one-action proc vec actions))
6534 (tramp-process-one-action proc vec actions)))))
6535 (with-current-buffer (tramp-get-connection-buffer vec)
6536 (tramp-message vec 6 "\n%s" (buffer-string)))
6537 (unless (eq exit 'ok)
6538 (tramp-clear-passwd vec)
6539 (tramp-error-with-buffer
6540 nil vec 'file-error
6541 (cond
6542 ((eq exit 'permission-denied) "Permission denied")
6543 ((eq exit 'process-died) "Process died")
6544 (t "Login failed"))))))
6546 ;; Utility functions.
6548 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6549 "Like `accept-process-output' for Tramp processes.
6550 This is needed in order to hide `last-coding-system-used', which is set
6551 for process communication also."
6552 (with-current-buffer (process-buffer proc)
6553 (tramp-message proc 10 "%s %s" proc (process-status proc))
6554 (let (buffer-read-only last-coding-system-used)
6555 ;; Under Windows XP, accept-process-output doesn't return
6556 ;; sometimes. So we add an additional timeout.
6557 (with-timeout ((or timeout 1))
6558 (accept-process-output proc timeout timeout-msecs)))
6559 (tramp-message proc 10 "\n%s" (buffer-string))))
6561 (defun tramp-check-for-regexp (proc regexp)
6562 "Check whether REGEXP is contained in process buffer of PROC.
6563 Erase echoed commands if exists."
6564 (with-current-buffer (process-buffer proc)
6565 (goto-char (point-min))
6567 ;; Check whether we need to remove echo output.
6568 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6569 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6570 (let ((begin (match-beginning 0)))
6571 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6572 ;; Discard echo from remote output.
6573 (tramp-set-connection-property proc "check-remote-echo" nil)
6574 (tramp-message proc 5 "echo-mark found")
6575 (forward-line)
6576 (delete-region begin (point))
6577 (goto-char (point-min)))))
6579 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6580 ;; Sometimes, the echo string is suppressed on the remote side.
6581 (not (string-equal
6582 (substring-no-properties
6583 tramp-echo-mark-marker
6584 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6585 (buffer-substring-no-properties
6586 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6587 ;; No echo to be handled, now we can look for the regexp.
6588 (goto-char (point-min))
6589 (re-search-forward regexp nil t))))
6591 (defun tramp-wait-for-regexp (proc timeout regexp)
6592 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6593 Expects the output of PROC to be sent to the current buffer. Returns
6594 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6595 nil."
6596 (with-current-buffer (process-buffer proc)
6597 (let ((found (tramp-check-for-regexp proc regexp))
6598 (start-time (current-time)))
6599 (cond (timeout
6600 ;; Work around a bug in XEmacs 21, where the timeout
6601 ;; expires faster than it should. This degenerates
6602 ;; to polling for buggy XEmacsen, but oh, well.
6603 (while (and (not found)
6604 (< (tramp-time-diff (current-time) start-time)
6605 timeout))
6606 (with-timeout (timeout)
6607 (while (not found)
6608 (tramp-accept-process-output proc 1)
6609 (unless (memq (process-status proc) '(run open))
6610 (tramp-error-with-buffer
6611 nil proc 'file-error "Process has died"))
6612 (setq found (tramp-check-for-regexp proc regexp))))))
6614 (while (not found)
6615 (tramp-accept-process-output proc 1)
6616 (unless (memq (process-status proc) '(run open))
6617 (tramp-error-with-buffer
6618 nil proc 'file-error "Process has died"))
6619 (setq found (tramp-check-for-regexp proc regexp)))))
6620 (tramp-message proc 6 "\n%s" (buffer-string))
6621 (when (not found)
6622 (if timeout
6623 (tramp-error
6624 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6625 regexp timeout)
6626 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6627 found)))
6629 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6630 "Wait for shell prompt and barf if none appears.
6631 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6632 seconds. If not, it produces an error message with the given ERROR-ARGS."
6633 (unless
6634 (tramp-wait-for-regexp
6635 proc timeout
6636 (format
6637 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6638 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6640 ;; We don't call `tramp-send-string' in order to hide the password
6641 ;; from the debug buffer, and because end-of-line handling of the
6642 ;; string.
6643 (defun tramp-enter-password (proc)
6644 "Prompt for a password and send it to the remote end."
6645 (process-send-string
6646 proc (concat (tramp-read-passwd proc)
6647 (or (tramp-get-method-parameter
6648 tramp-current-method
6649 'tramp-password-end-of-line)
6650 tramp-default-password-end-of-line))))
6652 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6653 "Set up an interactive shell.
6654 Mainly sets the prompt and the echo correctly. PROC is the shell
6655 process to set up. VEC specifies the connection."
6656 (let ((tramp-end-of-output tramp-initial-end-of-output))
6657 ;; It is useful to set the prompt in the following command because
6658 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6659 ;; about and thus /bin/sh will display a strange prompt. For
6660 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6661 ;; display the current working directory but /bin/sh will display
6662 ;; a dollar sign. The following command line sets $PS1 to a sane
6663 ;; value, and works under Bourne-ish shells as well as csh-like
6664 ;; shells. Daniel Pittman reports that the unusual positioning of
6665 ;; the single quotes makes it work under `rc', too. We also unset
6666 ;; the variable $ENV because that is read by some sh
6667 ;; implementations (eg, bash when called as sh) on startup; this
6668 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6669 ;; is another way to set the prompt in /bin/bash, it must be
6670 ;; discarded as well.
6671 (tramp-send-command
6673 (format
6674 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6675 (shell-quote-argument tramp-end-of-output)
6676 (tramp-get-method-parameter
6677 (tramp-file-name-method vec) 'tramp-remote-sh))
6680 ;; Disable echo.
6681 (tramp-message vec 5 "Setting up remote shell environment")
6682 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6683 ;; Check whether the echo has really been disabled. Some
6684 ;; implementations, like busybox of embedded GNU/Linux, don't
6685 ;; support disabling.
6686 (tramp-send-command vec "echo foo" t)
6687 (with-current-buffer (process-buffer proc)
6688 (goto-char (point-min))
6689 (when (looking-at "echo foo")
6690 (tramp-set-connection-property proc "remote-echo" t)
6691 (tramp-message vec 5 "Remote echo still on. Ok.")
6692 ;; Make sure backspaces and their echo are enabled and no line
6693 ;; width magic interferes with them.
6694 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6696 (tramp-message vec 5 "Setting shell prompt")
6697 (tramp-send-command
6698 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6699 (tramp-send-command vec "PS2=''" t)
6700 (tramp-send-command vec "PS3=''" t)
6701 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6703 ;; Try to set up the coding system correctly.
6704 ;; CCC this can't be the right way to do it. Hm.
6705 (tramp-message vec 5 "Determining coding system")
6706 (tramp-send-command vec "echo foo ; echo bar" t)
6707 (with-current-buffer (process-buffer proc)
6708 (goto-char (point-min))
6709 (if (featurep 'mule)
6710 ;; Use MULE to select the right EOL convention for communicating
6711 ;; with the process.
6712 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
6713 (cons 'undecided 'undecided)))
6714 cs-decode cs-encode)
6715 (when (symbolp cs) (setq cs (cons cs cs)))
6716 (setq cs-decode (car cs))
6717 (setq cs-encode (cdr cs))
6718 (unless cs-decode (setq cs-decode 'undecided))
6719 (unless cs-encode (setq cs-encode 'undecided))
6720 (setq cs-encode (tramp-coding-system-change-eol-conversion
6721 cs-encode 'unix))
6722 (when (search-forward "\r" nil t)
6723 (setq cs-decode (tramp-coding-system-change-eol-conversion
6724 cs-decode 'dos)))
6725 (funcall (symbol-function 'set-buffer-process-coding-system)
6726 cs-decode cs-encode)
6727 (tramp-message
6728 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6729 ;; Look for ^M and do something useful if found.
6730 (when (search-forward "\r" nil t)
6731 ;; We have found a ^M but cannot frob the process coding system
6732 ;; because we're running on a non-MULE Emacs. Let's try
6733 ;; stty, instead.
6734 (tramp-send-command vec "stty -onlcr" t))))
6735 (tramp-send-command vec "set +o vi +o emacs" t)
6737 ;; Check whether the output of "uname -sr" has been changed. If
6738 ;; yes, this is a strong indication that we must expire all
6739 ;; connection properties. We start again with
6740 ;; `tramp-maybe-open-connection', it will be catched there.
6741 (tramp-message vec 5 "Checking system information")
6742 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6743 (new-uname
6744 (tramp-set-connection-property
6745 vec "uname"
6746 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6747 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
6748 (with-current-buffer (tramp-get-debug-buffer vec)
6749 ;; Keep the debug buffer
6750 (rename-buffer
6751 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
6752 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6753 (if (= (point-min) (point-max))
6754 (kill-buffer nil)
6755 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6756 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6757 (tramp-get-buffer vec)
6758 (tramp-message
6759 vec 3
6760 "Connection reset, because remote host changed from `%s' to `%s'"
6761 old-uname new-uname)
6762 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
6764 ;; Check whether the remote host suffers from buggy
6765 ;; `send-process-string'. This is known for FreeBSD (see comment in
6766 ;; `send_process', file process.c). I've tested sending 624 bytes
6767 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6768 ;; this host type is detected locally. It cannot handle remote
6769 ;; hosts, though.
6770 (with-connection-property proc "chunksize"
6771 (cond
6772 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6773 tramp-chunksize)
6775 (tramp-message
6776 vec 5 "Checking remote host type for `send-process-string' bug")
6777 (if (string-match
6778 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
6779 500 0))))
6781 ;; Set remote PATH variable.
6782 (tramp-set-remote-path vec)
6784 ;; Search for a good shell before searching for a command which
6785 ;; checks if a file exists. This is done because Tramp wants to use
6786 ;; "test foo; echo $?" to check if various conditions hold, and
6787 ;; there are buggy /bin/sh implementations which don't execute the
6788 ;; "echo $?" part if the "test" part has an error. In particular,
6789 ;; the Solaris /bin/sh is a problem. I'm betting that all systems
6790 ;; with buggy /bin/sh implementations will have a working bash or
6791 ;; ksh. Whee...
6792 (tramp-find-shell vec)
6794 ;; Disable unexpected output.
6795 (tramp-send-command vec "mesg n; biff n" t)
6797 ;; Set the environment.
6798 (tramp-message vec 5 "Setting default environment")
6800 ;; On OpenSolaris, there is a bug when HISTFILE is changed in place
6801 ;; <http://bugs.opensolaris.org/view_bug.do?bug_id=6834184>. We
6802 ;; apply the workaround.
6803 (if (string-equal (tramp-get-connection-property vec "uname" "") "SunOS 5.11")
6804 (tramp-send-command vec "unset HISTFILE"))
6806 (let ((env (copy-sequence tramp-remote-process-environment))
6807 unset item)
6808 (while env
6809 (setq item (tramp-compat-split-string (car env) "="))
6810 (if (and (stringp (cadr item)) (not (string-equal (cadr item) "")))
6811 (tramp-send-command
6812 vec (format "%s=%s; export %s" (car item) (cadr item) (car item)) t)
6813 (push (car item) unset))
6814 (setq env (cdr env)))
6815 (when unset
6816 (tramp-send-command
6817 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
6819 ;; CCC: We should either implement a Perl version of base64 encoding
6820 ;; and decoding. Then we just use that in the last item. The other
6821 ;; alternative is to use the Perl version of UU encoding. But then
6822 ;; we need a Lisp version of uuencode.
6824 ;; Old text from documentation of tramp-methods:
6825 ;; Using a uuencode/uudecode inline method is discouraged, please use one
6826 ;; of the base64 methods instead since base64 encoding is much more
6827 ;; reliable and the commands are more standardized between the different
6828 ;; Unix versions. But if you can't use base64 for some reason, please
6829 ;; note that the default uudecode command does not work well for some
6830 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
6831 ;; the following command for uudecode:
6833 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6835 ;; For Irix, no solution is known yet.
6837 (defconst tramp-local-coding-commands
6838 '((b64 base64-encode-region base64-decode-region)
6839 (uu tramp-uuencode-region uudecode-decode-region)
6840 (pack
6841 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6842 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6843 "List of local coding commands for inline transfer.
6844 Each item is a list that looks like this:
6846 \(FORMAT ENCODING DECODING)
6848 FORMAT is symbol describing the encoding/decoding format. It can be
6849 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6851 ENCODING and DECODING can be strings, giving commands, or symbols,
6852 giving functions. If they are strings, then they can contain
6853 the \"%s\" format specifier. If that specifier is present, the input
6854 filename will be put into the command line at that spot. If the
6855 specifier is not present, the input should be read from standard
6856 input.
6858 If they are functions, they will be called with two arguments, start
6859 and end of region, and are expected to replace the region contents
6860 with the encoded or decoded results, respectively.")
6862 (defconst tramp-remote-coding-commands
6863 '((b64 "base64" "base64 -d")
6864 (b64 "mimencode -b" "mimencode -u -b")
6865 (b64 "mmencode -b" "mmencode -u -b")
6866 (b64 "recode data..base64" "recode base64..data")
6867 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6868 (b64 tramp-perl-encode tramp-perl-decode)
6869 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6870 (uu "uuencode xxx" "uudecode -o -")
6871 (uu "uuencode xxx" "uudecode -p")
6872 (uu "uuencode xxx" tramp-uudecode)
6873 (pack
6874 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6875 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6876 "List of remote coding commands for inline transfer.
6877 Each item is a list that looks like this:
6879 \(FORMAT ENCODING DECODING)
6881 FORMAT is symbol describing the encoding/decoding format. It can be
6882 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6884 ENCODING and DECODING can be strings, giving commands, or symbols,
6885 giving variables. If they are strings, then they can contain
6886 the \"%s\" format specifier. If that specifier is present, the input
6887 filename will be put into the command line at that spot. If the
6888 specifier is not present, the input should be read from standard
6889 input.
6891 If they are variables, this variable is a string containing a Perl
6892 implementation for this functionality. This Perl program will be transferred
6893 to the remote host, and it is available as shell function with the same name.")
6895 (defun tramp-find-inline-encoding (vec)
6896 "Find an inline transfer encoding that works.
6897 Goes through the list `tramp-local-coding-commands' and
6898 `tramp-remote-coding-commands'."
6899 (save-excursion
6900 (let ((local-commands tramp-local-coding-commands)
6901 (magic "xyzzy")
6902 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6903 (while (and local-commands (not found))
6904 (setq litem (pop local-commands))
6905 (catch 'wont-work-local
6906 (let ((format (nth 0 litem))
6907 (remote-commands tramp-remote-coding-commands))
6908 (setq loc-enc (nth 1 litem))
6909 (setq loc-dec (nth 2 litem))
6910 ;; If the local encoder or decoder is a string, the
6911 ;; corresponding command has to work locally.
6912 (if (not (stringp loc-enc))
6913 (tramp-message
6914 vec 5 "Checking local encoding function `%s'" loc-enc)
6915 (tramp-message
6916 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6917 (unless (zerop (tramp-call-local-coding-command
6918 loc-enc nil nil))
6919 (throw 'wont-work-local nil)))
6920 (if (not (stringp loc-dec))
6921 (tramp-message
6922 vec 5 "Checking local decoding function `%s'" loc-dec)
6923 (tramp-message
6924 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
6925 (unless (zerop (tramp-call-local-coding-command
6926 loc-dec nil nil))
6927 (throw 'wont-work-local nil)))
6928 ;; Search for remote coding commands with the same format
6929 (while (and remote-commands (not found))
6930 (setq ritem (pop remote-commands))
6931 (catch 'wont-work-remote
6932 (when (equal format (nth 0 ritem))
6933 (setq rem-enc (nth 1 ritem))
6934 (setq rem-dec (nth 2 ritem))
6935 ;; Check if remote encoding and decoding commands can be
6936 ;; called remotely with null input and output. This makes
6937 ;; sure there are no syntax errors and the command is really
6938 ;; found. Note that we do not redirect stdout to /dev/null,
6939 ;; for two reasons: when checking the decoding command, we
6940 ;; actually check the output it gives. And also, when
6941 ;; redirecting "mimencode" output to /dev/null, then as root
6942 ;; it might change the permissions of /dev/null!
6943 (when (not (stringp rem-enc))
6944 (let ((name (symbol-name rem-enc)))
6945 (while (string-match (regexp-quote "-") name)
6946 (setq name (replace-match "_" nil t name)))
6947 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
6948 (setq rem-enc name)))
6949 (tramp-message
6950 vec 5
6951 "Checking remote encoding command `%s' for sanity" rem-enc)
6952 (unless (zerop (tramp-send-command-and-check
6953 vec (format "%s </dev/null" rem-enc) t))
6954 (throw 'wont-work-remote nil))
6956 (when (not (stringp rem-dec))
6957 (let ((name (symbol-name rem-dec)))
6958 (while (string-match (regexp-quote "-") name)
6959 (setq name (replace-match "_" nil t name)))
6960 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
6961 (setq rem-dec name)))
6962 (tramp-message
6963 vec 5
6964 "Checking remote decoding command `%s' for sanity" rem-dec)
6965 (unless (zerop (tramp-send-command-and-check
6967 (format "echo %s | %s | %s"
6968 magic rem-enc rem-dec)
6970 (throw 'wont-work-remote nil))
6972 (with-current-buffer (tramp-get-buffer vec)
6973 (goto-char (point-min))
6974 (unless (looking-at (regexp-quote magic))
6975 (throw 'wont-work-remote nil)))
6977 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
6978 (setq rem-enc (nth 1 ritem))
6979 (setq rem-dec (nth 2 ritem))
6980 (setq found t)))))))
6982 ;; Did we find something?
6983 (unless found
6984 (tramp-message vec 2 "Couldn't find an inline transfer encoding"))
6986 ;; Set connection properties.
6987 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
6988 (tramp-set-connection-property vec "local-encoding" loc-enc)
6989 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
6990 (tramp-set-connection-property vec "local-decoding" loc-dec)
6991 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
6992 (tramp-set-connection-property vec "remote-encoding" rem-enc)
6993 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
6994 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
6996 (defun tramp-call-local-coding-command (cmd input output)
6997 "Call the local encoding or decoding command.
6998 If CMD contains \"%s\", provide input file INPUT there in command.
6999 Otherwise, INPUT is passed via standard input.
7000 INPUT can also be nil which means `/dev/null'.
7001 OUTPUT can be a string (which specifies a filename), or t (which
7002 means standard output and thus the current buffer), or nil (which
7003 means discard it)."
7004 (tramp-local-call-process
7005 tramp-encoding-shell
7006 (when (and input (not (string-match "%s" cmd))) input)
7007 (if (eq output t) t nil)
7009 tramp-encoding-command-switch
7010 (concat
7011 (if (string-match "%s" cmd) (format cmd input) cmd)
7012 (if (stringp output) (concat "> " output) ""))))
7014 (defun tramp-compute-multi-hops (vec)
7015 "Expands VEC according to `tramp-default-proxies-alist'.
7016 Gateway hops are already opened."
7017 (let ((target-alist `(,vec))
7018 (choices tramp-default-proxies-alist)
7019 item proxy)
7021 ;; Look for proxy hosts to be passed.
7022 (while choices
7023 (setq item (pop choices)
7024 proxy (eval (nth 2 item)))
7025 (when (and
7026 ;; host
7027 (string-match (or (eval (nth 0 item)) "")
7028 (or (tramp-file-name-host (car target-alist)) ""))
7029 ;; user
7030 (string-match (or (eval (nth 1 item)) "")
7031 (or (tramp-file-name-user (car target-alist)) "")))
7032 (if (null proxy)
7033 ;; No more hops needed.
7034 (setq choices nil)
7035 ;; Replace placeholders.
7036 (setq proxy
7037 (format-spec
7038 proxy
7039 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
7040 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
7041 (with-parsed-tramp-file-name proxy l
7042 ;; Add the hop.
7043 (add-to-list 'target-alist l)
7044 ;; Start next search.
7045 (setq choices tramp-default-proxies-alist)))))
7047 ;; Handle gateways.
7048 (when (and (boundp 'tramp-gw-tunnel-method)
7049 (string-match (format
7050 "^\\(%s\\|%s\\)$"
7051 (symbol-value 'tramp-gw-tunnel-method)
7052 (symbol-value 'tramp-gw-socks-method))
7053 (tramp-file-name-method (car target-alist))))
7054 (let ((gw (pop target-alist))
7055 (hop (pop target-alist)))
7056 ;; Is the method prepared for gateways?
7057 (unless (tramp-get-method-parameter
7058 (tramp-file-name-method hop) 'tramp-default-port)
7059 (tramp-error
7060 vec 'file-error
7061 "Method `%s' is not supported for gateway access."
7062 (tramp-file-name-method hop)))
7063 ;; Add default port if needed.
7064 (unless
7065 (string-match
7066 tramp-host-with-port-regexp (tramp-file-name-host hop))
7067 (aset hop 2
7068 (concat
7069 (tramp-file-name-host hop) tramp-prefix-port-format
7070 (number-to-string
7071 (tramp-get-method-parameter
7072 (tramp-file-name-method hop) 'tramp-default-port)))))
7073 ;; Open the gateway connection.
7074 (add-to-list
7075 'target-alist
7076 (vector
7077 (tramp-file-name-method hop) (tramp-file-name-user hop)
7078 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
7079 ;; For the password prompt, we need the correct values.
7080 ;; Therefore, we must remember the gateway vector. But we
7081 ;; cannot do it as connection property, because it shouldn't
7082 ;; be persistent. And we have no started process yet either.
7083 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7085 ;; Foreign and out-of-band methods are not supported for multi-hops.
7086 (when (cdr target-alist)
7087 (setq choices target-alist)
7088 (while choices
7089 (setq item (pop choices))
7090 (when
7092 (not
7093 (tramp-get-method-parameter
7094 (tramp-file-name-method item) 'tramp-login-program))
7095 (tramp-get-method-parameter
7096 (tramp-file-name-method item) 'tramp-copy-program))
7097 (tramp-error
7098 vec 'file-error
7099 "Method `%s' is not supported for multi-hops."
7100 (tramp-file-name-method item)))))
7102 ;; In case the host name is not used for the remote shell
7103 ;; command, the user could be misguided by applying a random
7104 ;; hostname.
7105 (let* ((v (car target-alist))
7106 (method (tramp-file-name-method v))
7107 (host (tramp-file-name-host v)))
7108 (unless
7110 ;; There are multi-hops.
7111 (cdr target-alist)
7112 ;; The host name is used for the remote shell command.
7113 (member
7114 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7115 ;; The host is local. We cannot use `tramp-local-host-p'
7116 ;; here, because it opens a connection as well.
7117 (string-match tramp-local-host-regexp host))
7118 (tramp-error
7119 v 'file-error
7120 "Host `%s' looks like a remote host, `%s' can only use the local host"
7121 host method)))
7123 ;; Result.
7124 target-alist))
7126 (defun tramp-maybe-open-connection (vec)
7127 "Maybe open a connection VEC.
7128 Does not do anything if a connection is already open, but re-opens the
7129 connection if a previous connection has died for some reason."
7130 (catch 'uname-changed
7131 (let ((p (tramp-get-connection-process vec))
7132 (process-environment (copy-sequence process-environment)))
7134 ;; If too much time has passed since last command was sent, look
7135 ;; whether process is still alive. If it isn't, kill it. When
7136 ;; using ssh, it can sometimes happen that the remote end has
7137 ;; hung up but the local ssh client doesn't recognize this until
7138 ;; it tries to send some data to the remote end. So that's why
7139 ;; we try to send a command from time to time, then look again
7140 ;; whether the process is really alive.
7141 (condition-case nil
7142 (when (and (> (tramp-time-diff
7143 (current-time)
7144 (tramp-get-connection-property
7145 p "last-cmd-time" '(0 0 0)))
7147 p (processp p) (memq (process-status p) '(run open)))
7148 (tramp-send-command vec "echo are you awake" t t)
7149 (unless (and (memq (process-status p) '(run open))
7150 (tramp-wait-for-output p 10))
7151 ;; The error will be catched locally.
7152 (tramp-error vec 'file-error "Awake did fail")))
7153 (file-error
7154 (tramp-flush-connection-property vec)
7155 (tramp-flush-connection-property p)
7156 (delete-process p)
7157 (setq p nil)))
7159 ;; New connection must be opened.
7160 (unless (and p (processp p) (memq (process-status p) '(run open)))
7162 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7163 ;; messages from the beginning.
7164 (tramp-get-buffer vec)
7165 (if (zerop (length (tramp-file-name-user vec)))
7166 (tramp-message
7167 vec 3 "Opening connection for %s using %s..."
7168 (tramp-file-name-host vec)
7169 (tramp-file-name-method vec))
7170 (tramp-message
7171 vec 3 "Opening connection for %s@%s using %s..."
7172 (tramp-file-name-user vec)
7173 (tramp-file-name-host vec)
7174 (tramp-file-name-method vec)))
7176 ;; Start new process.
7177 (when (and p (processp p))
7178 (delete-process p))
7179 (setenv "TERM" tramp-terminal-type)
7180 (setenv "LC_ALL" "C")
7181 (setenv "PROMPT_COMMAND")
7182 (setenv "PS1" tramp-initial-end-of-output)
7183 (let* ((target-alist (tramp-compute-multi-hops vec))
7184 (process-connection-type tramp-process-connection-type)
7185 (process-adaptive-read-buffering nil)
7186 (coding-system-for-read nil)
7187 ;; This must be done in order to avoid our file name handler.
7188 (p (let ((default-directory
7189 (tramp-compat-temporary-file-directory)))
7190 (start-process
7191 (or (tramp-get-connection-property vec "process-name" nil)
7192 (tramp-buffer-name vec))
7193 (tramp-get-connection-buffer vec)
7194 tramp-encoding-shell))))
7196 (tramp-message
7197 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7199 ;; Check whether process is alive.
7200 (tramp-set-process-query-on-exit-flag p nil)
7201 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
7202 (tramp-barf-if-no-shell-prompt
7203 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7205 ;; Now do all the connections as specified.
7206 (while target-alist
7207 (let* ((hop (car target-alist))
7208 (l-method (tramp-file-name-method hop))
7209 (l-user (tramp-file-name-user hop))
7210 (l-host (tramp-file-name-host hop))
7211 (l-port nil)
7212 (login-program
7213 (tramp-get-method-parameter l-method 'tramp-login-program))
7214 (login-args
7215 (tramp-get-method-parameter l-method 'tramp-login-args))
7216 (gw-args
7217 (tramp-get-method-parameter l-method 'tramp-gw-args))
7218 (gw (tramp-get-file-property hop "" "gateway" nil))
7219 (g-method (and gw (tramp-file-name-method gw)))
7220 (g-user (and gw (tramp-file-name-user gw)))
7221 (g-host (and gw (tramp-file-name-host gw)))
7222 (command login-program)
7223 ;; We don't create the temporary file. In fact, it
7224 ;; is just a prefix for the ControlPath option of
7225 ;; ssh; the real temporary file has another name, and
7226 ;; it is created and protected by ssh. It is also
7227 ;; removed by ssh, when the connection is closed.
7228 (tmpfile
7229 (tramp-set-connection-property
7230 p "temp-file"
7231 (make-temp-name
7232 (expand-file-name
7233 tramp-temp-name-prefix
7234 (tramp-compat-temporary-file-directory)))))
7235 spec)
7237 ;; Add gateway arguments if necessary.
7238 (when (and gw gw-args)
7239 (setq login-args (append login-args gw-args)))
7241 ;; Check for port number. Until now, there's no need
7242 ;; for handling like method, user, host.
7243 (when (string-match tramp-host-with-port-regexp l-host)
7244 (setq l-port (match-string 2 l-host)
7245 l-host (match-string 1 l-host)))
7247 ;; Set variables for computing the prompt for reading
7248 ;; password. They can also be derived from a gateway.
7249 (setq tramp-current-method (or g-method l-method)
7250 tramp-current-user (or g-user l-user)
7251 tramp-current-host (or g-host l-host))
7253 ;; Replace login-args place holders.
7254 (setq
7255 l-host (or l-host "")
7256 l-user (or l-user "")
7257 l-port (or l-port "")
7258 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
7259 (?t . ,tmpfile))
7260 command
7261 (concat
7262 ;; We do not want to see the trailing local prompt in
7263 ;; `start-file-process'.
7264 (unless (memq system-type '(windows-nt)) "exec ")
7265 command " "
7266 (mapconcat
7267 (lambda (x)
7268 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7269 (unless (member "" x) (mapconcat 'identity x " ")))
7270 login-args " ")
7271 ;; Local shell could be a Windows COMSPEC. It doesn't
7272 ;; know the ";" syntax, but we must exit always for
7273 ;; `start-file-process'. "exec" does not work either.
7274 (if (memq system-type '(windows-nt)) " && exit || exit")))
7276 ;; Send the command.
7277 (tramp-message vec 3 "Sending command `%s'" command)
7278 (tramp-send-command vec command t t)
7279 (tramp-process-actions p vec tramp-actions-before-shell 60)
7280 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
7281 ;; Next hop.
7282 (setq target-alist (cdr target-alist)))
7284 ;; Make initial shell settings.
7285 (tramp-open-connection-setup-interactive-shell p vec))))))
7287 (defun tramp-send-command (vec command &optional neveropen nooutput)
7288 "Send the COMMAND to connection VEC.
7289 Erases temporary buffer before sending the command. If optional
7290 arg NEVEROPEN is non-nil, never try to open the connection. This
7291 is meant to be used from `tramp-maybe-open-connection' only. The
7292 function waits for output unless NOOUTPUT is set."
7293 (unless neveropen (tramp-maybe-open-connection vec))
7294 (let ((p (tramp-get-connection-process vec)))
7295 (when (tramp-get-connection-property p "remote-echo" nil)
7296 ;; We mark the command string that it can be erased in the output buffer.
7297 (tramp-set-connection-property p "check-remote-echo" t)
7298 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7299 (tramp-message vec 6 "%s" command)
7300 (tramp-send-string vec command)
7301 (unless nooutput (tramp-wait-for-output p))))
7303 (defun tramp-wait-for-output (proc &optional timeout)
7304 "Wait for output from remote rsh command."
7305 (with-current-buffer (process-buffer proc)
7306 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7307 ;; be leading escape sequences, which must be ignored.
7308 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7309 ;; Sometimes, the commands do not return a newline but a
7310 ;; null byte before the shell prompt, for example "git
7311 ;; ls-files -c -z ...".
7312 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7313 (found (tramp-wait-for-regexp proc timeout regexp1)))
7314 (if found
7315 (let (buffer-read-only)
7316 (goto-char (point-max))
7317 (re-search-backward regexp nil t)
7318 (delete-region (point) (point-max)))
7319 (if timeout
7320 (tramp-error
7321 proc 'file-error
7322 "[[Remote prompt `%s' not found in %d secs]]"
7323 tramp-end-of-output timeout)
7324 (tramp-error
7325 proc 'file-error
7326 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7327 ;; Return value is whether end-of-output sentinel was found.
7328 found)))
7330 (defun tramp-send-command-and-check
7331 (vec command &optional subshell dont-suppress-err)
7332 "Run COMMAND and check its exit status.
7333 Sends `echo $?' along with the COMMAND for checking the exit status. If
7334 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7336 If the optional argument SUBSHELL is non-nil, the command is
7337 executed in a subshell, ie surrounded by parentheses. If
7338 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7339 (tramp-send-command
7341 (concat (if subshell "( " "")
7342 command
7343 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7344 "echo tramp_exit_status $?"
7345 (if subshell " )" "")))
7346 (with-current-buffer (tramp-get-connection-buffer vec)
7347 (goto-char (point-max))
7348 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7349 (tramp-error
7350 vec 'file-error "Couldn't find exit status of `%s'" command))
7351 (skip-chars-forward "^ ")
7352 (prog1
7353 (read (current-buffer))
7354 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7356 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7357 "Run COMMAND, check exit status, throw error if exit status not okay.
7358 Similar to `tramp-send-command-and-check' but accepts two more arguments
7359 FMT and ARGS which are passed to `error'."
7360 (unless (zerop (tramp-send-command-and-check vec command))
7361 (apply 'tramp-error vec 'file-error fmt args)))
7363 (defun tramp-send-command-and-read (vec command)
7364 "Run COMMAND and return the output, which must be a Lisp expression.
7365 In case there is no valid Lisp expression, it raises an error"
7366 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7367 (with-current-buffer (tramp-get-connection-buffer vec)
7368 ;; Read the expression.
7369 (goto-char (point-min))
7370 (condition-case nil
7371 (prog1 (read (current-buffer))
7372 ;; Error handling.
7373 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7374 (error nil)))
7375 (error (tramp-error
7376 vec 'file-error
7377 "`%s' does not return a valid Lisp expression: `%s'"
7378 command (buffer-string))))))
7380 ;; It seems that Tru64 Unix does not like it if long strings are sent
7381 ;; to it in one go. (This happens when sending the Perl
7382 ;; `file-attributes' implementation, for instance.) Therefore, we
7383 ;; have this function which sends the string in chunks.
7384 (defun tramp-send-string (vec string)
7385 "Send the STRING via connection VEC.
7387 The STRING is expected to use Unix line-endings, but the lines sent to
7388 the remote host use line-endings as defined in the variable
7389 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7390 (let* ((p (tramp-get-connection-process vec))
7391 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7392 (unless p
7393 (tramp-error
7394 vec 'file-error "Can't send string to remote host -- not logged in"))
7395 (tramp-set-connection-property p "last-cmd-time" (current-time))
7396 (tramp-message vec 10 "%s" string)
7397 (with-current-buffer (tramp-get-connection-buffer vec)
7398 ;; Clean up the buffer. We cannot call `erase-buffer' because
7399 ;; narrowing might be in effect.
7400 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7401 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7402 (setq string
7403 (mapconcat 'identity
7404 (tramp-compat-split-string string "\n")
7405 tramp-rsh-end-of-line))
7406 (unless (or (string= string "")
7407 (string-equal (substring string -1) tramp-rsh-end-of-line))
7408 (setq string (concat string tramp-rsh-end-of-line)))
7409 ;; Send the string.
7410 (if (and chunksize (not (zerop chunksize)))
7411 (let ((pos 0)
7412 (end (length string)))
7413 (while (< pos end)
7414 (tramp-message
7415 vec 10 "Sending chunk from %s to %s"
7416 pos (min (+ pos chunksize) end))
7417 (process-send-string
7418 p (substring string pos (min (+ pos chunksize) end)))
7419 (setq pos (+ pos chunksize))))
7420 (process-send-string p string)))))
7422 (defun tramp-mode-string-to-int (mode-string)
7423 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7424 (let* (case-fold-search
7425 (mode-chars (string-to-vector mode-string))
7426 (owner-read (aref mode-chars 1))
7427 (owner-write (aref mode-chars 2))
7428 (owner-execute-or-setid (aref mode-chars 3))
7429 (group-read (aref mode-chars 4))
7430 (group-write (aref mode-chars 5))
7431 (group-execute-or-setid (aref mode-chars 6))
7432 (other-read (aref mode-chars 7))
7433 (other-write (aref mode-chars 8))
7434 (other-execute-or-sticky (aref mode-chars 9)))
7435 (save-match-data
7436 (logior
7437 (cond
7438 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7439 ((char-equal owner-read ?-) 0)
7440 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7441 (cond
7442 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7443 ((char-equal owner-write ?-) 0)
7444 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7445 (cond
7446 ((char-equal owner-execute-or-setid ?x)
7447 (tramp-octal-to-decimal "00100"))
7448 ((char-equal owner-execute-or-setid ?S)
7449 (tramp-octal-to-decimal "04000"))
7450 ((char-equal owner-execute-or-setid ?s)
7451 (tramp-octal-to-decimal "04100"))
7452 ((char-equal owner-execute-or-setid ?-) 0)
7453 (t (error "Fourth char `%c' must be one of `xsS-'"
7454 owner-execute-or-setid)))
7455 (cond
7456 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7457 ((char-equal group-read ?-) 0)
7458 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7459 (cond
7460 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7461 ((char-equal group-write ?-) 0)
7462 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7463 (cond
7464 ((char-equal group-execute-or-setid ?x)
7465 (tramp-octal-to-decimal "00010"))
7466 ((char-equal group-execute-or-setid ?S)
7467 (tramp-octal-to-decimal "02000"))
7468 ((char-equal group-execute-or-setid ?s)
7469 (tramp-octal-to-decimal "02010"))
7470 ((char-equal group-execute-or-setid ?-) 0)
7471 (t (error "Seventh char `%c' must be one of `xsS-'"
7472 group-execute-or-setid)))
7473 (cond
7474 ((char-equal other-read ?r)
7475 (tramp-octal-to-decimal "00004"))
7476 ((char-equal other-read ?-) 0)
7477 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7478 (cond
7479 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7480 ((char-equal other-write ?-) 0)
7481 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7482 (cond
7483 ((char-equal other-execute-or-sticky ?x)
7484 (tramp-octal-to-decimal "00001"))
7485 ((char-equal other-execute-or-sticky ?T)
7486 (tramp-octal-to-decimal "01000"))
7487 ((char-equal other-execute-or-sticky ?t)
7488 (tramp-octal-to-decimal "01001"))
7489 ((char-equal other-execute-or-sticky ?-) 0)
7490 (t (error "Tenth char `%c' must be one of `xtT-'"
7491 other-execute-or-sticky)))))))
7493 (defun tramp-convert-file-attributes (vec attr)
7494 "Convert file-attributes ATTR generated by perl script, stat or ls.
7495 Convert file mode bits to string and set virtual device number.
7496 Return ATTR."
7497 (when attr
7498 ;; Convert last access time.
7499 (unless (listp (nth 4 attr))
7500 (setcar (nthcdr 4 attr)
7501 (list (floor (nth 4 attr) 65536)
7502 (floor (mod (nth 4 attr) 65536)))))
7503 ;; Convert last modification time.
7504 (unless (listp (nth 5 attr))
7505 (setcar (nthcdr 5 attr)
7506 (list (floor (nth 5 attr) 65536)
7507 (floor (mod (nth 5 attr) 65536)))))
7508 ;; Convert last status change time.
7509 (unless (listp (nth 6 attr))
7510 (setcar (nthcdr 6 attr)
7511 (list (floor (nth 6 attr) 65536)
7512 (floor (mod (nth 6 attr) 65536)))))
7513 ;; Convert file size.
7514 (when (< (nth 7 attr) 0)
7515 (setcar (nthcdr 7 attr) -1))
7516 (when (and (floatp (nth 7 attr))
7517 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7518 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7519 ;; Convert file mode bits to string.
7520 (unless (stringp (nth 8 attr))
7521 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7522 (when (stringp (car attr))
7523 (aset (nth 8 attr) 0 ?l)))
7524 ;; Convert directory indication bit.
7525 (when (string-match "^d" (nth 8 attr))
7526 (setcar attr t))
7527 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7528 (when (consp (car attr))
7529 (if (and (stringp (caar attr))
7530 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7531 (setcar attr (match-string 1 (caar attr)))
7532 (setcar attr nil)))
7533 ;; Set file's gid change bit.
7534 (setcar (nthcdr 9 attr)
7535 (if (numberp (nth 3 attr))
7536 (not (= (nth 3 attr)
7537 (tramp-get-remote-gid vec 'integer)))
7538 (not (string-equal
7539 (nth 3 attr)
7540 (tramp-get-remote-gid vec 'string)))))
7541 ;; Convert inode.
7542 (unless (listp (nth 10 attr))
7543 (setcar (nthcdr 10 attr)
7544 (condition-case nil
7545 (cons (floor (nth 10 attr) 65536)
7546 (floor (mod (nth 10 attr) 65536)))
7547 ;; Inodes can be incredible huge. We must hide this.
7548 (error (tramp-get-inode vec)))))
7549 ;; Set virtual device number.
7550 (setcar (nthcdr 11 attr)
7551 (tramp-get-device vec))
7552 attr))
7554 (defun tramp-check-cached-permissions (vec access)
7555 "Check `file-attributes' caches for VEC.
7556 Return t if according to the cache access type ACCESS is known to
7557 be granted."
7558 (let ((result nil)
7559 (offset (cond
7560 ((eq ?r access) 1)
7561 ((eq ?w access) 2)
7562 ((eq ?x access) 3))))
7563 (dolist (suffix '("string" "integer") result)
7564 (setq
7565 result
7567 result
7568 (let ((file-attr
7569 (tramp-get-file-property
7570 vec (tramp-file-name-localname vec)
7571 (concat "file-attributes-" suffix) nil))
7572 (remote-uid
7573 (tramp-get-connection-property
7574 vec (concat "uid-" suffix) nil))
7575 (remote-gid
7576 (tramp-get-connection-property
7577 vec (concat "gid-" suffix) nil)))
7578 (and
7579 file-attr
7581 ;; Not a symlink
7582 (eq t (car file-attr))
7583 (null (car file-attr)))
7585 ;; World accessible.
7586 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7587 ;; User accessible and owned by user.
7588 (and
7589 (eq access (aref (nth 8 file-attr) offset))
7590 (equal remote-uid (nth 2 file-attr)))
7591 ;; Group accessible and owned by user's
7592 ;; principal group.
7593 (and
7594 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7595 (equal remote-gid (nth 3 file-attr)))))))))))
7597 (defun tramp-get-inode (vec)
7598 "Returns the virtual inode number.
7599 If it doesn't exist, generate a new one."
7600 (let ((string (tramp-make-tramp-file-name
7601 (tramp-file-name-method vec)
7602 (tramp-file-name-user vec)
7603 (tramp-file-name-host vec)
7604 "")))
7605 (unless (assoc string tramp-inodes)
7606 (add-to-list 'tramp-inodes
7607 (list string (length tramp-inodes))))
7608 (nth 1 (assoc string tramp-inodes))))
7610 (defun tramp-get-device (vec)
7611 "Returns the virtual device number.
7612 If it doesn't exist, generate a new one."
7613 (let ((string (tramp-make-tramp-file-name
7614 (tramp-file-name-method vec)
7615 (tramp-file-name-user vec)
7616 (tramp-file-name-host vec)
7617 "")))
7618 (unless (assoc string tramp-devices)
7619 (add-to-list 'tramp-devices
7620 (list string (length tramp-devices))))
7621 (cons -1 (nth 1 (assoc string tramp-devices)))))
7623 (defun tramp-file-mode-from-int (mode)
7624 "Turn an integer representing a file mode into an ls(1)-like string."
7625 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7626 (user (logand (lsh mode -6) 7))
7627 (group (logand (lsh mode -3) 7))
7628 (other (logand (lsh mode -0) 7))
7629 (suid (> (logand (lsh mode -9) 4) 0))
7630 (sgid (> (logand (lsh mode -9) 2) 0))
7631 (sticky (> (logand (lsh mode -9) 1) 0)))
7632 (setq user (tramp-file-mode-permissions user suid "s"))
7633 (setq group (tramp-file-mode-permissions group sgid "s"))
7634 (setq other (tramp-file-mode-permissions other sticky "t"))
7635 (concat type user group other)))
7637 (defun tramp-file-mode-permissions (perm suid suid-text)
7638 "Convert a permission bitset into a string.
7639 This is used internally by `tramp-file-mode-from-int'."
7640 (let ((r (> (logand perm 4) 0))
7641 (w (> (logand perm 2) 0))
7642 (x (> (logand perm 1) 0)))
7643 (concat (or (and r "r") "-")
7644 (or (and w "w") "-")
7645 (or (and suid x suid-text) ; suid, execute
7646 (and suid (upcase suid-text)) ; suid, !execute
7647 (and x "x") "-")))) ; !suid
7649 (defun tramp-decimal-to-octal (i)
7650 "Return a string consisting of the octal digits of I.
7651 Not actually used. Use `(format \"%o\" i)' instead?"
7652 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7653 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7654 ((zerop i) "0")
7655 (t (concat (tramp-decimal-to-octal (/ i 8))
7656 (number-to-string (% i 8))))))
7658 ;; Kudos to Gerd Moellmann for this suggestion.
7659 (defun tramp-octal-to-decimal (ostr)
7660 "Given a string of octal digits, return a decimal number."
7661 (let ((x (or ostr "")))
7662 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7663 (unless (string-match "\\`[0-7]*\\'" x)
7664 (error "Non-octal junk in string `%s'" x))
7665 (string-to-number ostr 8)))
7667 (defun tramp-shell-case-fold (string)
7668 "Converts STRING to shell glob pattern which ignores case."
7669 (mapconcat
7670 (lambda (c)
7671 (if (equal (downcase c) (upcase c))
7672 (vector c)
7673 (format "[%c%c]" (downcase c) (upcase c))))
7674 string
7675 ""))
7678 ;; ------------------------------------------------------------
7679 ;; -- Tramp file names --
7680 ;; ------------------------------------------------------------
7681 ;; Conversion functions between external representation and
7682 ;; internal data structure. Convenience functions for internal
7683 ;; data structure.
7685 (defun tramp-file-name-p (vec)
7686 "Check whether VEC is a Tramp object."
7687 (and (vectorp vec) (= 4 (length vec))))
7689 (defun tramp-file-name-method (vec)
7690 "Return method component of VEC."
7691 (and (tramp-file-name-p vec) (aref vec 0)))
7693 (defun tramp-file-name-user (vec)
7694 "Return user component of VEC."
7695 (and (tramp-file-name-p vec) (aref vec 1)))
7697 (defun tramp-file-name-host (vec)
7698 "Return host component of VEC."
7699 (and (tramp-file-name-p vec) (aref vec 2)))
7701 (defun tramp-file-name-localname (vec)
7702 "Return localname component of VEC."
7703 (and (tramp-file-name-p vec) (aref vec 3)))
7705 ;; The user part of a Tramp file name vector can be of kind
7706 ;; "user%domain". Sometimes, we must extract these parts.
7707 (defun tramp-file-name-real-user (vec)
7708 "Return the user name of VEC without domain."
7709 (save-match-data
7710 (let ((user (tramp-file-name-user vec)))
7711 (if (and (stringp user)
7712 (string-match tramp-user-with-domain-regexp user))
7713 (match-string 1 user)
7714 user))))
7716 (defun tramp-file-name-domain (vec)
7717 "Return the domain name of VEC."
7718 (save-match-data
7719 (let ((user (tramp-file-name-user vec)))
7720 (and (stringp user)
7721 (string-match tramp-user-with-domain-regexp user)
7722 (match-string 2 user)))))
7724 ;; The host part of a Tramp file name vector can be of kind
7725 ;; "host#port". Sometimes, we must extract these parts.
7726 (defun tramp-file-name-real-host (vec)
7727 "Return the host name of VEC without port."
7728 (save-match-data
7729 (let ((host (tramp-file-name-host vec)))
7730 (if (and (stringp host)
7731 (string-match tramp-host-with-port-regexp host))
7732 (match-string 1 host)
7733 host))))
7735 (defun tramp-file-name-port (vec)
7736 "Return the port number of VEC."
7737 (save-match-data
7738 (let ((host (tramp-file-name-host vec)))
7739 (and (stringp host)
7740 (string-match tramp-host-with-port-regexp host)
7741 (string-to-number (match-string 2 host))))))
7743 (defun tramp-tramp-file-p (name)
7744 "Return t if NAME is a string with Tramp file name syntax."
7745 (save-match-data
7746 (and (stringp name) (string-match tramp-file-name-regexp name))))
7748 (defun tramp-find-method (method user host)
7749 "Return the right method string to use.
7750 This is METHOD, if non-nil. Otherwise, do a lookup in
7751 `tramp-default-method-alist'."
7752 (or method
7753 (let ((choices tramp-default-method-alist)
7754 lmethod item)
7755 (while choices
7756 (setq item (pop choices))
7757 (when (and (string-match (or (nth 0 item) "") (or host ""))
7758 (string-match (or (nth 1 item) "") (or user "")))
7759 (setq lmethod (nth 2 item))
7760 (setq choices nil)))
7761 lmethod)
7762 tramp-default-method))
7764 (defun tramp-find-user (method user host)
7765 "Return the right user string to use.
7766 This is USER, if non-nil. Otherwise, do a lookup in
7767 `tramp-default-user-alist'."
7768 (or user
7769 (let ((choices tramp-default-user-alist)
7770 luser item)
7771 (while choices
7772 (setq item (pop choices))
7773 (when (and (string-match (or (nth 0 item) "") (or method ""))
7774 (string-match (or (nth 1 item) "") (or host "")))
7775 (setq luser (nth 2 item))
7776 (setq choices nil)))
7777 luser)
7778 tramp-default-user))
7780 (defun tramp-find-host (method user host)
7781 "Return the right host string to use.
7782 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7783 (or (and (> (length host) 0) host)
7784 tramp-default-host))
7786 (defun tramp-dissect-file-name (name &optional nodefault)
7787 "Return a `tramp-file-name' structure.
7788 The structure consists of remote method, remote user, remote host
7789 and localname (file name on remote host). If NODEFAULT is
7790 non-nil, the file name parts are not expanded to their default
7791 values."
7792 (save-match-data
7793 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
7794 (unless match (error "Not a Tramp file name: %s" name))
7795 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7796 (user (match-string (nth 2 tramp-file-name-structure) name))
7797 (host (match-string (nth 3 tramp-file-name-structure) name))
7798 (localname (match-string (nth 4 tramp-file-name-structure) name)))
7799 (when (member method '("multi" "multiu"))
7800 (error
7801 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7802 method))
7803 (when host
7804 (when (string-match tramp-prefix-ipv6-regexp host)
7805 (setq host (replace-match "" nil t host)))
7806 (when (string-match tramp-postfix-ipv6-regexp host)
7807 (setq host (replace-match "" nil t host))))
7808 (if nodefault
7809 (vector method user host localname)
7810 (vector
7811 (tramp-find-method method user host)
7812 (tramp-find-user method user host)
7813 (tramp-find-host method user host)
7814 localname))))))
7816 (defun tramp-equal-remote (file1 file2)
7817 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7818 The check depends on method, user and host name of the files. If
7819 one of the components is missing, the default values are used.
7820 The local file name parts of FILE1 and FILE2 are not taken into
7821 account.
7823 Example:
7825 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7827 would yield `t'. On the other hand, the following check results in nil:
7829 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
7830 (and (stringp (file-remote-p file1))
7831 (stringp (file-remote-p file2))
7832 (string-equal (file-remote-p file1) (file-remote-p file2))))
7834 (defun tramp-make-tramp-file-name (method user host localname)
7835 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7836 (concat tramp-prefix-format
7837 (when (not (zerop (length method)))
7838 (concat method tramp-postfix-method-format))
7839 (when (not (zerop (length user)))
7840 (concat user tramp-postfix-user-format))
7841 (when host
7842 (if (string-match tramp-ipv6-regexp host)
7843 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7844 host))
7845 tramp-postfix-host-format
7846 (when localname localname)))
7848 (defun tramp-completion-make-tramp-file-name (method user host localname)
7849 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7850 It must not be a complete Tramp file name, but as long as there are
7851 necessary only. This function will be used in file name completion."
7852 (concat tramp-prefix-format
7853 (when (not (zerop (length method)))
7854 (concat method tramp-postfix-method-format))
7855 (when (not (zerop (length user)))
7856 (concat user tramp-postfix-user-format))
7857 (when (not (zerop (length host)))
7858 (concat
7859 (if (string-match tramp-ipv6-regexp host)
7860 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7861 host)
7862 tramp-postfix-host-format))
7863 (when localname localname)))
7865 (defun tramp-make-copy-program-file-name (vec)
7866 "Create a file name suitable to be passed to `rcp' and workalikes."
7867 (let ((user (tramp-file-name-user vec))
7868 (host (tramp-file-name-real-host vec))
7869 (localname (tramp-shell-quote-argument
7870 (tramp-file-name-localname vec))))
7871 (if (not (zerop (length user)))
7872 (format "%s@%s:%s" user host localname)
7873 (format "%s:%s" host localname))))
7875 (defun tramp-method-out-of-band-p (vec size)
7876 "Return t if this is an out-of-band method, nil otherwise."
7877 (and
7878 ;; It shall be an out-of-band method.
7879 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7880 ;; Either the file size is large enough, or (in rare cases) there
7881 ;; does not exist a remote encoding.
7882 (or (> size tramp-copy-size-limit)
7883 (null (tramp-get-remote-coding vec "remote-encoding")))))
7885 (defun tramp-local-host-p (vec)
7886 "Return t if this points to the local host, nil otherwise."
7887 ;; We cannot use `tramp-file-name-real-host'. A port is an
7888 ;; indication for an ssh tunnel or alike.
7889 (let ((host (tramp-file-name-host vec)))
7890 (and
7891 (stringp host)
7892 (string-match tramp-local-host-regexp host)
7893 ;; The method shall be applied to one of the shell file name
7894 ;; handler. `tramp-local-host-p' is also called for "smb" and
7895 ;; alike, where it must fail.
7896 (tramp-get-method-parameter
7897 (tramp-file-name-method vec) 'tramp-login-program)
7898 ;; The local temp directory must be writable for the other user.
7899 (file-writable-p
7900 (tramp-make-tramp-file-name
7901 (tramp-file-name-method vec)
7902 (tramp-file-name-user vec)
7903 host
7904 (tramp-compat-temporary-file-directory)))
7905 ;; On some systems, chown runs only for root.
7906 (or (zerop (user-uid))
7907 (zerop (tramp-get-remote-uid vec 'integer))))))
7909 ;; Variables local to connection.
7911 (defun tramp-get-remote-path (vec)
7912 (with-connection-property
7913 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
7914 ;; cache the result for the session only. Otherwise, the result
7915 ;; is cached persistently.
7916 (if (memq 'tramp-own-remote-path tramp-remote-path)
7917 (tramp-get-connection-process vec)
7918 vec)
7919 "remote-path"
7920 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
7921 (elt1 (memq 'tramp-default-remote-path remote-path))
7922 (elt2 (memq 'tramp-own-remote-path remote-path))
7923 (default-remote-path
7924 (when elt1
7925 (condition-case nil
7926 (tramp-send-command-and-read
7927 vec "echo \\\"`getconf PATH`\\\"")
7928 ;; Default if "getconf" is not available.
7929 (error
7930 (tramp-message
7931 vec 3
7932 "`getconf PATH' not successful, using default value \"%s\"."
7933 "/bin:/usr/bin")
7934 "/bin:/usr/bin"))))
7935 (own-remote-path
7936 (when elt2
7937 (condition-case nil
7938 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
7939 ;; Default if "getconf" is not available.
7940 (error
7941 (tramp-message
7942 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
7943 nil)))))
7945 ;; Replace place holder `tramp-default-remote-path'.
7946 (when elt1
7947 (setcdr elt1
7948 (append
7949 (tramp-compat-split-string default-remote-path ":")
7950 (cdr elt1)))
7951 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
7953 ;; Replace place holder `tramp-own-remote-path'.
7954 (when elt2
7955 (setcdr elt2
7956 (append
7957 (tramp-compat-split-string own-remote-path ":")
7958 (cdr elt2)))
7959 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
7961 ;; Remove double entries.
7962 (setq elt1 remote-path)
7963 (while (consp elt1)
7964 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
7965 (setcar elt2 nil))
7966 (setq elt1 (cdr elt1)))
7968 ;; Remove non-existing directories.
7969 (delq
7971 (mapcar
7972 (lambda (x)
7973 (and
7974 (stringp x)
7975 (file-directory-p
7976 (tramp-make-tramp-file-name
7977 (tramp-file-name-method vec)
7978 (tramp-file-name-user vec)
7979 (tramp-file-name-host vec)
7982 remote-path)))))
7984 (defun tramp-get-remote-tmpdir (vec)
7985 (with-connection-property vec "tmp-directory"
7986 (let ((dir (tramp-shell-quote-argument "/tmp")))
7987 (if (and (zerop
7988 (tramp-send-command-and-check
7989 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
7990 (zerop
7991 (tramp-send-command-and-check
7992 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
7994 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
7996 (defun tramp-get-ls-command (vec)
7997 (with-connection-property vec "ls"
7998 (tramp-message vec 5 "Finding a suitable `ls' command")
8000 (catch 'ls-found
8001 (dolist (cmd '("ls" "gnuls" "gls"))
8002 (let ((dl (tramp-get-remote-path vec))
8003 result)
8004 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8005 ;; Check parameter.
8006 (when (zerop (tramp-send-command-and-check
8007 vec (format "%s -lnd /" result)))
8008 (throw 'ls-found result))
8009 (setq dl (cdr dl))))))
8010 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8012 (defun tramp-get-ls-command-with-dired (vec)
8013 (save-match-data
8014 (with-connection-property vec "ls-dired"
8015 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8016 (zerop (tramp-send-command-and-check
8017 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8019 (defun tramp-get-test-command (vec)
8020 (with-connection-property vec "test"
8021 (tramp-message vec 5 "Finding a suitable `test' command")
8022 (if (zerop (tramp-send-command-and-check vec "test 0"))
8023 "test"
8024 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8026 (defun tramp-get-test-nt-command (vec)
8027 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8028 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8029 ;; for otherwise the shell crashes.
8030 (with-connection-property vec "test-nt"
8032 (progn
8033 (tramp-send-command
8034 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8035 (with-current-buffer (tramp-get-buffer vec)
8036 (goto-char (point-min))
8037 (when (looking-at (regexp-quote tramp-end-of-output))
8038 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8039 (progn
8040 (tramp-send-command
8042 (format
8043 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8044 (tramp-get-test-command vec)))
8045 "tramp_test_nt %s %s"))))
8047 (defun tramp-get-file-exists-command (vec)
8048 (with-connection-property vec "file-exists"
8049 (tramp-message vec 5 "Finding command to check if file exists")
8050 (tramp-find-file-exists-command vec)))
8052 (defun tramp-get-remote-ln (vec)
8053 (with-connection-property vec "ln"
8054 (tramp-message vec 5 "Finding a suitable `ln' command")
8055 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8057 (defun tramp-get-remote-perl (vec)
8058 (with-connection-property vec "perl"
8059 (tramp-message vec 5 "Finding a suitable `perl' command")
8060 (let ((result
8061 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8062 (tramp-find-executable
8063 vec "perl" (tramp-get-remote-path vec)))))
8064 ;; We must check also for some Perl modules.
8065 (when result
8066 (with-connection-property vec "perl-file-spec"
8067 (zerop
8068 (tramp-send-command-and-check
8069 vec (format "%s -e 'use File::Spec;'" result))))
8070 (with-connection-property vec "perl-cwd-realpath"
8071 (zerop
8072 (tramp-send-command-and-check
8073 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8074 result)))
8076 (defun tramp-get-remote-stat (vec)
8077 (with-connection-property vec "stat"
8078 (tramp-message vec 5 "Finding a suitable `stat' command")
8079 (let ((result (tramp-find-executable
8080 vec "stat" (tramp-get-remote-path vec)))
8081 tmp)
8082 ;; Check whether stat(1) returns usable syntax. %s does not
8083 ;; work on older AIX systems.
8084 (when result
8085 (setq tmp
8086 ;; We don't want to display an error message.
8087 (with-temp-message (or (current-message) "")
8088 (condition-case nil
8089 (tramp-send-command-and-read
8090 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8091 (error nil))))
8092 (unless (and (listp tmp) (stringp (car tmp))
8093 (string-match "^./.$" (car tmp))
8094 (integerp (cadr tmp)))
8095 (setq result nil)))
8096 result)))
8098 (defun tramp-get-remote-readlink (vec)
8099 (with-connection-property vec "readlink"
8100 (tramp-message vec 5 "Finding a suitable `readlink' command")
8101 (let ((result (tramp-find-executable
8102 vec "readlink" (tramp-get-remote-path vec))))
8103 (when (and result
8104 ;; We don't want to display an error message.
8105 (with-temp-message (or (current-message) "")
8106 (condition-case nil
8107 (zerop
8108 (tramp-send-command-and-check
8109 vec (format "%s --canonicalize-missing /" result)))
8110 (error nil))))
8111 result))))
8113 (defun tramp-get-remote-id (vec)
8114 (with-connection-property vec "id"
8115 (tramp-message vec 5 "Finding POSIX `id' command")
8117 (catch 'id-found
8118 (let ((dl (tramp-get-remote-path vec))
8119 result)
8120 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8121 ;; Check POSIX parameter.
8122 (when (zerop (tramp-send-command-and-check
8123 vec (format "%s -u" result)))
8124 (throw 'id-found result))
8125 (setq dl (cdr dl)))))
8126 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8128 (defun tramp-get-remote-uid (vec id-format)
8129 (with-connection-property vec (format "uid-%s" id-format)
8130 (let ((res (tramp-send-command-and-read
8132 (format "%s -u%s %s"
8133 (tramp-get-remote-id vec)
8134 (if (equal id-format 'integer) "" "n")
8135 (if (equal id-format 'integer)
8136 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8137 ;; The command might not always return a number.
8138 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8140 (defun tramp-get-remote-gid (vec id-format)
8141 (with-connection-property vec (format "gid-%s" id-format)
8142 (let ((res (tramp-send-command-and-read
8144 (format "%s -g%s %s"
8145 (tramp-get-remote-id vec)
8146 (if (equal id-format 'integer) "" "n")
8147 (if (equal id-format 'integer)
8148 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8149 ;; The command might not always return a number.
8150 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8152 (defun tramp-get-local-uid (id-format)
8153 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8155 (defun tramp-get-local-gid (id-format)
8156 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8158 ;; Some predefined connection properties.
8159 (defun tramp-get-remote-coding (vec prop)
8160 ;; Local coding handles properties like remote coding. So we could
8161 ;; call it without pain.
8162 (let ((ret (tramp-get-local-coding vec prop)))
8163 ;; The connection property might have been cached. So we must send
8164 ;; the script - maybe.
8165 (when (and ret (symbolp ret))
8166 (let ((name (symbol-name ret)))
8167 (while (string-match (regexp-quote "-") name)
8168 (setq name (replace-match "_" nil t name)))
8169 (tramp-maybe-send-script vec (symbol-value ret) name)
8170 (setq ret name)))
8171 ;; Return the value.
8172 ret))
8174 (defun tramp-get-local-coding (vec prop)
8176 (tramp-get-connection-property vec prop nil)
8177 (progn
8178 (tramp-find-inline-encoding vec)
8179 (tramp-get-connection-property vec prop nil))))
8181 (defun tramp-get-method-parameter (method param)
8182 "Return the method parameter PARAM.
8183 If the `tramp-methods' entry does not exist, return NIL."
8184 (let ((entry (assoc param (assoc method tramp-methods))))
8185 (when entry (cadr entry))))
8187 ;; Auto saving to a special directory.
8189 (defun tramp-exists-file-name-handler (operation &rest args)
8190 "Checks whether OPERATION runs a file name handler."
8191 ;; The file name handler is determined on base of either an
8192 ;; argument, `buffer-file-name', or `default-directory'.
8193 (condition-case nil
8194 (let* ((buffer-file-name "/")
8195 (default-directory "/")
8196 (fnha file-name-handler-alist)
8197 (check-file-name-operation operation)
8198 (file-name-handler-alist
8199 (list
8200 (cons "/"
8201 (lambda (operation &rest args)
8202 "Returns OPERATION if it is the one to be checked."
8203 (if (equal check-file-name-operation operation)
8204 operation
8205 (let ((file-name-handler-alist fnha))
8206 (apply operation args))))))))
8207 (equal (apply operation args) operation))
8208 (error nil)))
8210 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8211 (defadvice make-auto-save-file-name
8212 (around tramp-advice-make-auto-save-file-name () activate)
8213 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8214 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
8215 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8216 ;; directly, because this would bypass the locking mechanism.
8217 (setq ad-return-value
8218 (tramp-file-name-handler 'make-auto-save-file-name))
8219 ad-do-it))
8220 (add-hook
8221 'tramp-unload-hook
8222 (lambda ()
8223 (ad-remove-advice
8224 'make-auto-save-file-name
8225 'around 'tramp-advice-make-auto-save-file-name)
8226 (ad-activate 'make-auto-save-file-name))))
8228 ;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
8229 ;; permission 0666 minus umask. This is a security threat.
8231 (defun tramp-set-auto-save-file-modes ()
8232 "Set permissions of autosaved remote files to the original permissions."
8233 (let ((bfn (buffer-file-name)))
8234 (when (and (stringp bfn)
8235 (tramp-tramp-file-p bfn)
8236 (buffer-modified-p)
8237 (stringp buffer-auto-save-file-name)
8238 (not (equal bfn buffer-auto-save-file-name)))
8239 (unless (file-exists-p buffer-auto-save-file-name)
8240 (write-region "" nil buffer-auto-save-file-name))
8241 ;; Permissions should be set always, because there might be an old
8242 ;; auto-saved file belonging to another original file. This could
8243 ;; be a security threat.
8244 (set-file-modes buffer-auto-save-file-name
8245 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8247 (unless (or (> emacs-major-version 21)
8248 (and (featurep 'xemacs)
8249 (= emacs-major-version 21)
8250 (> emacs-minor-version 4)))
8251 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8252 (add-hook 'tramp-unload-hook
8253 (lambda ()
8254 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8256 (defun tramp-subst-strs-in-string (alist string)
8257 "Replace all occurrences of the string FROM with TO in STRING.
8258 ALIST is of the form ((FROM . TO) ...)."
8259 (save-match-data
8260 (while alist
8261 (let* ((pr (car alist))
8262 (from (car pr))
8263 (to (cdr pr)))
8264 (while (string-match (regexp-quote from) string)
8265 (setq string (replace-match to t t string)))
8266 (setq alist (cdr alist))))
8267 string))
8269 ;; ------------------------------------------------------------
8270 ;; -- Compatibility functions section --
8271 ;; ------------------------------------------------------------
8273 (defun tramp-read-passwd (proc &optional prompt)
8274 "Read a password from user (compat function).
8275 Consults the auth-source package.
8276 Invokes `password-read' if available, `read-passwd' else."
8277 (let* ((key (tramp-make-tramp-file-name
8278 tramp-current-method tramp-current-user
8279 tramp-current-host ""))
8280 (pw-prompt
8281 (or prompt
8282 (with-current-buffer (process-buffer proc)
8283 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8284 (format "%s for %s " (capitalize (match-string 1)) key)))))
8285 (prog1
8287 ;; See if auth-sources contains something useful, if it's bound.
8288 (and (boundp 'auth-sources)
8289 (tramp-get-connection-property proc "first-password-request" nil)
8290 ;; Try with Tramp's current method.
8291 (funcall (symbol-function 'auth-source-user-or-password)
8292 "password" tramp-current-host tramp-current-method))
8293 ;; Try the password cache.
8294 (when (functionp 'password-read)
8295 (unless (tramp-get-connection-property
8296 proc "first-password-request" nil)
8297 (funcall (symbol-function 'password-cache-remove) key))
8298 (let ((password
8299 (funcall (symbol-function 'password-read) pw-prompt key)))
8300 (funcall (symbol-function 'password-cache-add) key password)
8301 password))
8302 ;; Else, get the password interactively.
8303 (read-passwd pw-prompt))
8304 (tramp-set-connection-property proc "first-password-request" nil))))
8306 (defun tramp-clear-passwd (vec)
8307 "Clear password cache for connection related to VEC."
8308 (when (functionp 'password-cache-remove)
8309 (funcall
8310 (symbol-function 'password-cache-remove)
8311 (tramp-make-tramp-file-name
8312 (tramp-file-name-method vec)
8313 (tramp-file-name-user vec)
8314 (tramp-file-name-host vec)
8315 ""))))
8317 ;; Snarfed code from time-date.el and parse-time.el
8319 (defconst tramp-half-a-year '(241 17024)
8320 "Evaluated by \"(days-to-time 183)\".")
8322 (defconst tramp-parse-time-months
8323 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8324 ("apr" . 4) ("may" . 5) ("jun" . 6)
8325 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8326 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8327 "Alist mapping month names to integers.")
8329 (defun tramp-time-less-p (t1 t2)
8330 "Say whether time value T1 is less than time value T2."
8331 (unless t1 (setq t1 '(0 0)))
8332 (unless t2 (setq t2 '(0 0)))
8333 (or (< (car t1) (car t2))
8334 (and (= (car t1) (car t2))
8335 (< (nth 1 t1) (nth 1 t2)))))
8337 (defun tramp-time-subtract (t1 t2)
8338 "Subtract two time values.
8339 Return the difference in the format of a time value."
8340 (unless t1 (setq t1 '(0 0)))
8341 (unless t2 (setq t2 '(0 0)))
8342 (let ((borrow (< (cadr t1) (cadr t2))))
8343 (list (- (car t1) (car t2) (if borrow 1 0))
8344 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8346 (defun tramp-time-diff (t1 t2)
8347 "Return the difference between the two times, in seconds.
8348 T1 and T2 are time values (as returned by `current-time' for example)."
8349 ;; Pacify byte-compiler with `symbol-function'.
8350 (cond ((and (fboundp 'subtract-time)
8351 (fboundp 'float-time))
8352 (funcall (symbol-function 'float-time)
8353 (funcall (symbol-function 'subtract-time) t1 t2)))
8354 ((and (fboundp 'subtract-time)
8355 (fboundp 'time-to-seconds))
8356 (funcall (symbol-function 'time-to-seconds)
8357 (funcall (symbol-function 'subtract-time) t1 t2)))
8358 ((fboundp 'itimer-time-difference)
8359 (funcall (symbol-function 'itimer-time-difference)
8360 (if (< (length t1) 3) (append t1 '(0)) t1)
8361 (if (< (length t2) 3) (append t2 '(0)) t2)))
8363 (let ((time (tramp-time-subtract t1 t2)))
8364 (+ (* (car time) 65536.0)
8365 (cadr time)
8366 (/ (or (nth 2 time) 0) 1000000.0))))))
8368 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8369 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8370 EOL-TYPE can be one of `dos', `unix', or `mac'."
8371 (cond ((fboundp 'coding-system-change-eol-conversion)
8372 (funcall (symbol-function 'coding-system-change-eol-conversion)
8373 coding-system eol-type))
8374 ((fboundp 'subsidiary-coding-system)
8375 (funcall (symbol-function 'subsidiary-coding-system)
8376 coding-system
8377 (cond ((eq eol-type 'dos) 'crlf)
8378 ((eq eol-type 'unix) 'lf)
8379 ((eq eol-type 'mac) 'cr)
8381 (error "Unknown EOL-TYPE `%s', must be %s"
8382 eol-type
8383 "`dos', `unix', or `mac'")))))
8384 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8386 (defun tramp-set-process-query-on-exit-flag (process flag)
8387 "Specify if query is needed for process when Emacs is exited.
8388 If the second argument flag is non-nil, Emacs will query the user before
8389 exiting if process is running."
8390 (if (fboundp 'set-process-query-on-exit-flag)
8391 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
8392 (funcall (symbol-function 'process-kill-without-query) process flag)))
8395 ;; ------------------------------------------------------------
8396 ;; -- Kludges section --
8397 ;; ------------------------------------------------------------
8399 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8400 ;; does not deal well with newline characters. Newline is replaced by
8401 ;; backslash newline. But if, say, the string `a backslash newline b'
8402 ;; is passed to a shell, the shell will expand this into "ab",
8403 ;; completely omitting the newline. This is not what was intended.
8404 ;; It does not appear to be possible to make the function
8405 ;; `shell-quote-argument' work with newlines without making it
8406 ;; dependent on the shell used. But within this package, we know that
8407 ;; we will always use a Bourne-like shell, so we use an approach which
8408 ;; groks newlines.
8410 ;; The approach is simple: we call `shell-quote-argument', then
8411 ;; massage the newline part of the result.
8413 ;; This function should produce a string which is grokked by a Unix
8414 ;; shell, even if the Emacs is running on Windows. Since this is the
8415 ;; kludges section, we bind `system-type' in such a way that
8416 ;; `shell-quote-arguments' behaves as if on Unix.
8418 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8419 ;; function to work with Bourne-like shells.
8421 ;; CCC: This function should be rewritten so that
8422 ;; `shell-quote-argument' is not used. This way, we are safe from
8423 ;; changes in `shell-quote-argument'.
8424 (defun tramp-shell-quote-argument (s)
8425 "Similar to `shell-quote-argument', but groks newlines.
8426 Only works for Bourne-like shells."
8427 (let ((system-type 'not-windows))
8428 (save-match-data
8429 (let ((result (shell-quote-argument s))
8430 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8431 (when (and (>= (length result) 2)
8432 (string= (substring result 0 2) "\\~"))
8433 (setq result (substring result 1)))
8434 (while (string-match nl result)
8435 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8436 t t result)))
8437 result))))
8439 ;; Checklist for `tramp-unload-hook'
8440 ;; - Unload all `tramp-*' packages
8441 ;; - Reset `file-name-handler-alist'
8442 ;; - Cleanup hooks where Tramp functions are in
8443 ;; - Cleanup advised functions
8444 ;; - Cleanup autoloads
8445 ;;;###autoload
8446 (defun tramp-unload-tramp ()
8447 "Discard Tramp from loading remote files."
8448 (interactive)
8449 ;; When Tramp is not loaded yet, its autoloads are still active.
8450 (tramp-unload-file-name-handlers)
8451 ;; ange-ftp settings must be enabled.
8452 (when (functionp 'tramp-ftp-enable-ange-ftp)
8453 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
8454 ;; Maybe its not loaded yet.
8455 (condition-case nil
8456 (unload-feature 'tramp 'force)
8457 (error nil)))
8459 (when (and load-in-progress
8460 (string-match "Loading tramp..." (or (current-message) "")))
8461 (message "Loading tramp...done"))
8463 (provide 'tramp)
8465 ;;; TODO:
8467 ;; * Handle nonlocal exits such as C-g.
8468 ;; * But it would probably be better to use with-local-quit at the
8469 ;; place where it's actually needed: around any potentially
8470 ;; indefinitely blocking piece of code. In this case it would be
8471 ;; within Tramp around one of its calls to accept-process-output (or
8472 ;; around one of the loops that calls accept-process-output)
8473 ;; (Stefan Monnier).
8474 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8475 ;; `shell-quote-argument'.
8476 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8477 ;; by the files in that directory. Add this here.
8478 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8479 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8480 ;; * Case-insensitive filename completion. (Norbert Goevert.)
8481 ;; * Don't use globbing for directories with many files, as this is
8482 ;; likely to produce long command lines, and some shells choke on
8483 ;; long command lines.
8484 ;; * `vc-directory' does not work. It never displays any files, even
8485 ;; if it does show files when run locally.
8486 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8487 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8488 ;; * abbreviate-file-name
8489 ;; * Better error checking. At least whenever we see something
8490 ;; strange when doing zerop, we should kill the process and start
8491 ;; again. (Greg Stark)
8492 ;; * Remove unneeded parameters from methods.
8493 ;; * Make it work for different encodings, and for different file name
8494 ;; encodings, too. (Daniel Pittman)
8495 ;; * Progress reports while copying files. (Michael Kifer)
8496 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8497 ;; then look if it's the right version (with `perl -v').
8498 ;; * When editing a remote CVS controlled file as a different user, VC
8499 ;; gets confused about the file locking status. Try to find out why
8500 ;; the workaround doesn't work.
8501 ;; * Username and hostname completion.
8502 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8503 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8504 ;; Code is nearly identical.
8505 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8506 ;; until the last but one hop via `start-file-process'. Apply it
8507 ;; also for ftp and smb.
8508 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8509 ;; some shell with root priviledges, it would be nice if I could
8510 ;; just call
8511 ;; trampclient filename.c
8512 ;; as an editor, and the _current_ shell would connect to an Emacs
8513 ;; server and would be used in an existing non-priviledged Emacs
8514 ;; session for doing the editing in question.
8515 ;; That way, I need not tell Emacs my password again and be afraid
8516 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8517 ;; once display a just typed password in the context of a keyboard
8518 ;; sequence prompt for a question immediately following in a shell
8519 ;; script run within Emacs -- nasty).
8520 ;; And if I have some ssh session running to a different computer,
8521 ;; having the possibility of passing a local file there to a local
8522 ;; Emacs session (in case I can arrange for a connection back) would
8523 ;; be nice.
8524 ;; Likely the corresponding Tramp server should not allow the
8525 ;; equivalent of the emacsclient -eval option in order to make this
8526 ;; reasonably unproblematic. And maybe trampclient should have some
8527 ;; way of passing credentials, like by using an SSL socket or
8528 ;; something. (David Kastrup)
8529 ;; * Reconnect directly to a compliant shell without first going
8530 ;; through the user's default shell. (Pete Forman)
8531 ;; * Make `tramp-default-user' obsolete.
8532 ;; * Tramp shall reconnect automatically to its ssh connection when it
8533 ;; detects that the process "has died". (David Reitter)
8534 ;; * How can I interrupt the remote process with a signal
8535 ;; (interrupt-process seems not to work)? (Markus Triska)
8536 ;; * Avoid the local shell entirely for starting remote processes. If
8537 ;; so, I think even a signal, when delivered directly to the local
8538 ;; SSH instance, would correctly be propagated to the remote process
8539 ;; automatically; possibly SSH would have to be started with
8540 ;; "-t". (Markus Triska)
8541 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8542 ;; isn't on the remote host. (Mark A. Hershberger)
8543 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8544 ;; * Implement a general server-local-variable mechanism, as there are
8545 ;; probably other variables that need different values for different
8546 ;; servers too. The user could then configure a variable (such as
8547 ;; tramp-server-local-variable-alist) to define any such variables
8548 ;; that they need to, which would then be let bound as appropriate
8549 ;; in tramp functions. (Jason Rumney)
8550 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8551 ;; rsync).
8552 ;; * Keep a second connection open for out-of-band methods like scp or
8553 ;; rsync.
8554 ;; * Support ptys in `tramp-handle-start-file-process'.
8556 ;; Functions for file-name-handler-alist:
8557 ;; diff-latest-backup-file -- in diff.el
8559 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8560 ;;; tramp.el ends here
8562 ;; Local Variables:
8563 ;; mode: Emacs-Lisp
8564 ;; coding: utf-8
8565 ;; End: