(tramp-drop-volume-letter): Move definition before use.
[emacs.git] / lisp / net / tramp.el
blob439636dcf2cc92dcf3f8150d4861beebf4da3d2e
1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 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, or (at your option)
17 ;; 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; see the file COPYING. If not, see
26 ;; <http://www.gnu.org/licenses/>.
28 ;;; Commentary:
30 ;; This package provides remote file editing, similar to ange-ftp.
31 ;; The difference is that ange-ftp uses FTP to transfer files between
32 ;; the local and the remote host, whereas tramp.el uses a combination
33 ;; of rsh and rcp or other work-alike programs, such as ssh/scp.
35 ;; For more detailed instructions, please see the info file.
37 ;; Notes:
38 ;; -----
40 ;; This package only works for Emacs 21.1 and higher, and for XEmacs 21.4
41 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
42 ;; the `with-timeout' macro.)
44 ;; This version might not work with pre-Emacs 21 VC unless VC is
45 ;; loaded before tramp.el. Could you please test this and tell me about
46 ;; the result? Thanks.
48 ;; Also see the todo list at the bottom of this file.
50 ;; The current version of Tramp can be retrieved from the following URL:
51 ;; http://ftp.gnu.org/gnu/tramp/
53 ;; There's a mailing list for this, as well. Its name is:
54 ;; tramp-devel@gnu.org
55 ;; You can use the Web to subscribe, under the following URL:
56 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
58 ;; For the adventurous, the current development sources are available
59 ;; via CVS. You can find instructions about this at the following URL:
60 ;; http://savannah.gnu.org/projects/tramp/
61 ;; Click on "CVS" in the navigation bar near the top.
63 ;; Don't forget to put on your asbestos longjohns, first!
65 ;;; Code:
67 ;; The Tramp version number and bug report address, as prepared by configure.
68 (require 'trampver)
69 (add-hook 'tramp-unload-hook
70 '(lambda ()
71 (when (featurep 'trampver)
72 (unload-feature 'trampver 'force))))
74 (require 'tramp-compat)
75 (add-hook 'tramp-unload-hook
76 '(lambda ()
77 (when (featurep 'tramp-compat)
78 (unload-feature 'tramp-compat 'force))))
80 (require 'format-spec) ; from Gnus 5.8, also in tar ball
81 ;; As long as password.el is not part of (X)Emacs, it shouldn't
82 ;; be mandatory
83 (if (featurep 'xemacs)
84 (load "password" 'noerror)
85 (or (require 'password-cache nil 'noerror)
86 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
88 (require 'shell)
89 (require 'advice)
91 ;; Requiring 'tramp-cache results in an endless loop.
92 (autoload 'tramp-get-file-property "tramp-cache")
93 (autoload 'tramp-set-file-property "tramp-cache")
94 (autoload 'tramp-flush-file-property "tramp-cache")
95 (autoload 'tramp-flush-directory-property "tramp-cache")
96 (autoload 'tramp-get-connection-property "tramp-cache")
97 (autoload 'tramp-set-connection-property "tramp-cache")
98 (autoload 'tramp-flush-connection-property "tramp-cache")
99 (autoload 'tramp-parse-connection-properties "tramp-cache")
100 (add-hook 'tramp-unload-hook
101 '(lambda ()
102 (when (featurep 'tramp-cache)
103 (unload-feature 'tramp-cache 'force))))
105 (autoload 'tramp-uuencode-region "tramp-uu"
106 "Implementation of `uuencode' in Lisp.")
107 (add-hook 'tramp-unload-hook
108 '(lambda ()
109 (when (featurep 'tramp-uu)
110 (unload-feature 'tramp-uu 'force))))
112 (autoload 'uudecode-decode-region "uudecode")
114 ;; The following Tramp packages must be loaded after tramp.el, because
115 ;; they require it as well.
116 (eval-after-load "tramp"
117 '(dolist
118 (feature
119 (list
121 ;; Tramp interactive commands.
122 'tramp-cmds
124 ;; Load foreign FTP method.
125 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
127 ;; tramp-smb uses "smbclient" from Samba. Not available
128 ;; under Cygwin and Windows, because they don't offer
129 ;; "smbclient". And even not necessary there, because Emacs
130 ;; supports UNC file names like "//host/share/localname".
131 (unless (memq system-type '(cygwin windows-nt)) 'tramp-smb)
133 ;; Load foreign FISH method.
134 'tramp-fish
136 ;; Load gateways. It needs `make-network-process' from Emacs 22.
137 (when (functionp 'make-network-process) 'tramp-gw)))
139 (when feature
140 (require feature)
141 (add-hook 'tramp-unload-hook
142 `(lambda ()
143 (when (featurep ,feature)
144 (unload-feature ,feature 'force)))))))
146 ;;; User Customizable Internal Variables:
148 (defgroup tramp nil
149 "Edit remote files with a combination of rsh and rcp or similar programs."
150 :group 'files
151 :version "22.1")
153 (defcustom tramp-verbose 3
154 "*Verbosity level for Tramp.
155 Any level x includes messages for all levels 1 .. x-1. The levels are
157 0 silent (no tramp messages at all)
158 1 errors
159 2 warnings
160 3 connection to remote hosts (default level)
161 4 activities
162 5 internal
163 6 sent and received strings
164 7 file caching
165 8 connection properties
166 10 traces (huge)."
167 :group 'tramp
168 :type 'integer)
170 ;; Emacs case
171 (eval-and-compile
172 (when (boundp 'backup-directory-alist)
173 (defcustom tramp-backup-directory-alist nil
174 "Alist of filename patterns and backup directory names.
175 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
176 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
177 is a local file name, the backup directory is prepended with Tramp file
178 name prefix \(method, user, host\) of file.
180 \(setq tramp-backup-directory-alist backup-directory-alist\)
182 gives the same backup policy for Tramp files on their hosts like the
183 policy for local files."
184 :group 'tramp
185 :type '(repeat (cons (regexp :tag "Regexp matching filename")
186 (directory :tag "Backup directory name"))))))
188 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
189 ;; the package "backup-dir" might not be loaded yet.
190 (eval-and-compile
191 (when (featurep 'xemacs)
192 (defcustom tramp-bkup-backup-directory-info nil
193 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
194 It has the same meaning like `bkup-backup-directory-info' from package
195 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
196 file name, the backup directory is prepended with Tramp file name prefix
197 \(method, user, host\) of file.
199 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
201 gives the same backup policy for Tramp files on their hosts like the
202 policy for local files."
203 :type '(repeat
204 (list (regexp :tag "File regexp")
205 (string :tag "Backup Dir")
206 (set :inline t
207 (const ok-create)
208 (const full-path)
209 (const prepend-name)
210 (const search-upward))))
211 :group 'tramp)))
213 (defcustom tramp-auto-save-directory nil
214 "*Put auto-save files in this directory, if set.
215 The idea is to use a local directory so that auto-saving is faster."
216 :group 'tramp
217 :type '(choice (const nil) string))
219 (defcustom tramp-encoding-shell
220 (if (memq system-type '(windows-nt))
221 (getenv "COMSPEC")
222 "/bin/sh")
223 "*Use this program for encoding and decoding commands on the local host.
224 This shell is used to execute the encoding and decoding command on the
225 local host, so if you want to use `~' in those commands, you should
226 choose a shell here which groks tilde expansion. `/bin/sh' normally
227 does not understand tilde expansion.
229 For encoding and deocding, commands like the following are executed:
231 /bin/sh -c COMMAND < INPUT > OUTPUT
233 This variable can be used to change the \"/bin/sh\" part. See the
234 variable `tramp-encoding-command-switch' for the \"-c\" part.
236 Note that this variable is not used for remote commands. There are
237 mechanisms in tramp.el which automatically determine the right shell to
238 use for the remote host."
239 :group 'tramp
240 :type '(file :must-match t))
242 (defcustom tramp-encoding-command-switch
243 (if (string-match "cmd\\.exe" tramp-encoding-shell)
244 "/c"
245 "-c")
246 "*Use this switch together with `tramp-encoding-shell' for local commands.
247 See the variable `tramp-encoding-shell' for more information."
248 :group 'tramp
249 :type 'string)
251 (defcustom tramp-copy-size-limit 10240
252 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
253 :group 'tramp
254 :type 'integer)
256 (defcustom tramp-terminal-type "dumb"
257 "*Value of TERM environment variable for logging in to remote host.
258 Because Tramp wants to parse the output of the remote shell, it is easily
259 confused by ANSI color escape sequences and suchlike. Often, shell init
260 files conditionalize this setup based on the TERM environment variable."
261 :group 'tramp
262 :type 'string)
264 (defvar tramp-methods
265 `(("rcp" (tramp-login-program "rsh")
266 (tramp-login-args (("%h") ("-l" "%u")))
267 (tramp-remote-sh "/bin/sh")
268 (tramp-copy-program "rcp")
269 (tramp-copy-args (("-p" "%k")))
270 (tramp-copy-keep-date t)
271 (tramp-password-end-of-line nil))
272 ("scp" (tramp-login-program "ssh")
273 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
274 ("-e" "none")))
275 (tramp-remote-sh "/bin/sh")
276 (tramp-copy-program "scp")
277 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")))
278 (tramp-copy-keep-date t)
279 (tramp-password-end-of-line nil)
280 (tramp-gw-args (("-o"
281 "GlobalKnownHostsFile=/dev/null")
282 ("-o" "UserKnownHostsFile=/dev/null")
283 ("-o" "StrictHostKeyChecking=no")))
284 (tramp-default-port 22))
285 ("scp1" (tramp-login-program "ssh")
286 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
287 ("-1" "-e" "none")))
288 (tramp-remote-sh "/bin/sh")
289 (tramp-copy-program "scp")
290 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
291 ("-q")))
292 (tramp-copy-keep-date t)
293 (tramp-password-end-of-line nil)
294 (tramp-gw-args (("-o"
295 "GlobalKnownHostsFile=/dev/null")
296 ("-o" "UserKnownHostsFile=/dev/null")
297 ("-o" "StrictHostKeyChecking=no")))
298 (tramp-default-port 22))
299 ("scp2" (tramp-login-program "ssh")
300 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
301 ("-2" "-e" "none")))
302 (tramp-remote-sh "/bin/sh")
303 (tramp-copy-program "scp")
304 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
305 ("-q")))
306 (tramp-copy-keep-date t)
307 (tramp-password-end-of-line nil)
308 (tramp-gw-args (("-o"
309 "GlobalKnownHostsFile=/dev/null")
310 ("-o" "UserKnownHostsFile=/dev/null")
311 ("-o" "StrictHostKeyChecking=no")))
312 (tramp-default-port 22))
313 ("scp1_old"
314 (tramp-login-program "ssh1")
315 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
316 ("-e" "none")))
317 (tramp-remote-sh "/bin/sh")
318 (tramp-copy-program "scp1")
319 (tramp-copy-args (("-p" "%k")))
320 (tramp-copy-keep-date t)
321 (tramp-password-end-of-line nil))
322 ("scp2_old"
323 (tramp-login-program "ssh2")
324 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
325 ("-e" "none")))
326 (tramp-remote-sh "/bin/sh")
327 (tramp-copy-program "scp2")
328 (tramp-copy-args (("-p" "%k")))
329 (tramp-copy-keep-date t)
330 (tramp-password-end-of-line nil))
331 ("sftp" (tramp-login-program "ssh")
332 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
333 ("-e" "none")))
334 (tramp-remote-sh "/bin/sh")
335 (tramp-copy-program "sftp")
336 (tramp-copy-args nil)
337 (tramp-copy-keep-date nil)
338 (tramp-password-end-of-line nil))
339 ("rsync" (tramp-login-program "ssh")
340 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
341 ("-e" "none")))
342 (tramp-remote-sh "/bin/sh")
343 (tramp-copy-program "rsync")
344 (tramp-copy-args (("-e" "ssh") ("-t" "%k")))
345 (tramp-copy-keep-date t)
346 (tramp-password-end-of-line nil))
347 ("remcp" (tramp-login-program "remsh")
348 (tramp-login-args (("%h") ("-l" "%u")))
349 (tramp-remote-sh "/bin/sh")
350 (tramp-copy-program "rcp")
351 (tramp-copy-args (("-p" "%k")))
352 (tramp-copy-keep-date t)
353 (tramp-password-end-of-line nil))
354 ("rsh" (tramp-login-program "rsh")
355 (tramp-login-args (("%h") ("-l" "%u")))
356 (tramp-remote-sh "/bin/sh")
357 (tramp-copy-program nil)
358 (tramp-copy-args nil)
359 (tramp-copy-keep-date nil)
360 (tramp-password-end-of-line nil))
361 ("ssh" (tramp-login-program "ssh")
362 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
363 ("-e" "none")))
364 (tramp-remote-sh "/bin/sh")
365 (tramp-copy-program nil)
366 (tramp-copy-args nil)
367 (tramp-copy-keep-date nil)
368 (tramp-password-end-of-line nil)
369 (tramp-gw-args (("-o"
370 "GlobalKnownHostsFile=/dev/null")
371 ("-o" "UserKnownHostsFile=/dev/null")
372 ("-o" "StrictHostKeyChecking=no")))
373 (tramp-default-port 22))
374 ("ssh1" (tramp-login-program "ssh")
375 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
376 ("-1" "-e" "none")))
377 (tramp-remote-sh "/bin/sh")
378 (tramp-copy-program nil)
379 (tramp-copy-args nil)
380 (tramp-copy-keep-date nil)
381 (tramp-password-end-of-line nil)
382 (tramp-gw-args (("-o"
383 "GlobalKnownHostsFile=/dev/null")
384 ("-o" "UserKnownHostsFile=/dev/null")
385 ("-o" "StrictHostKeyChecking=no")))
386 (tramp-default-port 22))
387 ("ssh2" (tramp-login-program "ssh")
388 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
389 ("-2" "-e" "none")))
390 (tramp-remote-sh "/bin/sh")
391 (tramp-copy-program nil)
392 (tramp-copy-args nil)
393 (tramp-copy-keep-date nil)
394 (tramp-password-end-of-line nil)
395 (tramp-gw-args (("-o"
396 "GlobalKnownHostsFile=/dev/null")
397 ("-o" "UserKnownHostsFile=/dev/null")
398 ("-o" "StrictHostKeyChecking=no")))
399 (tramp-default-port 22))
400 ("ssh1_old"
401 (tramp-login-program "ssh1")
402 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
403 ("-e" "none")))
404 (tramp-remote-sh "/bin/sh")
405 (tramp-copy-program nil)
406 (tramp-copy-args nil)
407 (tramp-copy-keep-date nil)
408 (tramp-password-end-of-line nil))
409 ("ssh2_old"
410 (tramp-login-program "ssh2")
411 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
412 ("-e" "none")))
413 (tramp-remote-sh "/bin/sh")
414 (tramp-copy-program nil)
415 (tramp-copy-args nil)
416 (tramp-copy-keep-date nil)
417 (tramp-password-end-of-line nil))
418 ("remsh" (tramp-login-program "remsh")
419 (tramp-login-args (("%h") ("-l" "%u")))
420 (tramp-remote-sh "/bin/sh")
421 (tramp-copy-program nil)
422 (tramp-copy-args nil)
423 (tramp-copy-keep-date nil)
424 (tramp-password-end-of-line nil))
425 ("telnet"
426 (tramp-login-program "telnet")
427 (tramp-login-args (("%h") ("%p")))
428 (tramp-remote-sh "/bin/sh")
429 (tramp-copy-program nil)
430 (tramp-copy-args nil)
431 (tramp-copy-keep-date nil)
432 (tramp-password-end-of-line nil)
433 (tramp-default-port 23))
434 ("su" (tramp-login-program "su")
435 (tramp-login-args (("-") ("%u")))
436 (tramp-remote-sh "/bin/sh")
437 (tramp-copy-program nil)
438 (tramp-copy-args nil)
439 (tramp-copy-keep-date nil)
440 (tramp-password-end-of-line nil))
441 ("sudo" (tramp-login-program "sudo")
442 (tramp-login-args (("-u" "%u")
443 ("-s") ("-H") ("-p" "Password:")))
444 (tramp-remote-sh "/bin/sh")
445 (tramp-copy-program nil)
446 (tramp-copy-args nil)
447 (tramp-copy-keep-date nil)
448 (tramp-password-end-of-line nil))
449 ("scpc" (tramp-login-program "ssh")
450 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
451 ("-o" "ControlPath=%t.%%r@%%h:%%p")
452 ("-o" "ControlMaster=yes")
453 ("-e" "none")))
454 (tramp-remote-sh "/bin/sh")
455 (tramp-copy-program "scp")
456 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
457 ("-o" "ControlPath=%t.%%r@%%h:%%p")
458 ("-o" "ControlMaster=auto")))
459 (tramp-copy-keep-date t)
460 (tramp-password-end-of-line nil)
461 (tramp-gw-args (("-o"
462 "GlobalKnownHostsFile=/dev/null")
463 ("-o" "UserKnownHostsFile=/dev/null")
464 ("-o" "StrictHostKeyChecking=no")))
465 (tramp-default-port 22))
466 ("scpx" (tramp-login-program "ssh")
467 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
468 ("-e" "none" "-t" "-t" "/bin/sh")))
469 (tramp-remote-sh "/bin/sh")
470 (tramp-copy-program "scp")
471 (tramp-copy-args (("-p" "%k")))
472 (tramp-copy-keep-date t)
473 (tramp-password-end-of-line nil)
474 (tramp-gw-args (("-o"
475 "GlobalKnownHostsFile=/dev/null")
476 ("-o" "UserKnownHostsFile=/dev/null")
477 ("-o" "StrictHostKeyChecking=no")))
478 (tramp-default-port 22))
479 ("sshx" (tramp-login-program "ssh")
480 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
481 ("-e" "none" "-t" "-t" "/bin/sh")))
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 (tramp-gw-args (("-o"
488 "GlobalKnownHostsFile=/dev/null")
489 ("-o" "UserKnownHostsFile=/dev/null")
490 ("-o" "StrictHostKeyChecking=no")))
491 (tramp-default-port 22))
492 ("krlogin"
493 (tramp-login-program "krlogin")
494 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
495 (tramp-remote-sh "/bin/sh")
496 (tramp-copy-program nil)
497 (tramp-copy-args nil)
498 (tramp-copy-keep-date nil)
499 (tramp-password-end-of-line nil))
500 ("plink" (tramp-login-program "plink")
501 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
502 ("-ssh")))
503 (tramp-remote-sh "/bin/sh")
504 (tramp-copy-program nil)
505 (tramp-copy-args nil)
506 (tramp-copy-keep-date nil)
507 (tramp-password-end-of-line "xy") ;see docstring for "xy"
508 (tramp-default-port 22))
509 ("plink1"
510 (tramp-login-program "plink")
511 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
512 ("-1" "-ssh")))
513 (tramp-remote-sh "/bin/sh")
514 (tramp-copy-program nil)
515 (tramp-copy-args nil)
516 (tramp-copy-keep-date nil)
517 (tramp-password-end-of-line "xy") ;see docstring for "xy"
518 (tramp-default-port 22))
519 ("plinkx"
520 (tramp-login-program "plink")
521 ;; ("%h") must be a single element, see
522 ;; `tramp-compute-multi-hops'.
523 (tramp-login-args (("-load") ("%h") ("-t")
524 (,(format
525 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=$ '"
526 tramp-terminal-type))
527 ("/bin/sh")))
528 (tramp-remote-sh "/bin/sh")
529 (tramp-copy-program nil)
530 (tramp-copy-args nil)
531 (tramp-copy-keep-date nil)
532 (tramp-password-end-of-line nil))
533 ("pscp" (tramp-login-program "plink")
534 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
535 ("-ssh")))
536 (tramp-remote-sh "/bin/sh")
537 (tramp-copy-program "pscp")
538 (tramp-copy-args (("-P") ("%p") ("-scp") ("-p" "%k")))
539 (tramp-copy-keep-date t)
540 (tramp-password-end-of-line "xy") ;see docstring for "xy"
541 (tramp-default-port 22))
542 ("psftp" (tramp-login-program "plink")
543 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
544 ("-ssh")))
545 (tramp-remote-sh "/bin/sh")
546 (tramp-copy-program "pscp")
547 (tramp-copy-args (("-P") ("%p") ("-sftp") ("-p" "%k")))
548 (tramp-copy-keep-date t)
549 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
550 ("fcp" (tramp-login-program "fsh")
551 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
552 (tramp-remote-sh "/bin/sh -i")
553 (tramp-copy-program "fcp")
554 (tramp-copy-args (("-p" "%k")))
555 (tramp-copy-keep-date t)
556 (tramp-password-end-of-line nil)))
557 "*Alist of methods for remote files.
558 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
559 Each NAME stands for a remote access method. Each PARAM is a
560 pair of the form (KEY VALUE). The following KEYs are defined:
561 * `tramp-remote-sh'
562 This specifies the Bourne shell to use on the remote host. This
563 MUST be a Bourne-like shell. It is normally not necessary to set
564 this to any value other than \"/bin/sh\": Tramp wants to use a shell
565 which groks tilde expansion, but it can search for it. Also note
566 that \"/bin/sh\" exists on all Unixen, this might not be true for
567 the value that you decide to use. You Have Been Warned.
568 * `tramp-login-program'
569 This specifies the name of the program to use for logging in to the
570 remote host. This may be the name of rsh or a workalike program,
571 or the name of telnet or a workalike, or the name of su or a workalike.
572 * `tramp-login-args'
573 This specifies the list of arguments to pass to the above
574 mentioned program. Please note that this is a list of list of arguments,
575 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
576 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
577 There are some patterns: \"%h\" in this list is replaced by the host
578 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
579 port number, and \"%%\" can be used to obtain a literal percent character.
580 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
581 expansion (i.e. no host or no user specified), this list is not used as
582 argument. By this, arguments like (\"-l\" \"%u\") are optional.
583 \"%t\" is replaced by the temporary file name produced with
584 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
585 parameter of a program, if exists.
586 * `tramp-copy-program'
587 This specifies the name of the program to use for remotely copying
588 the file; this might be the absolute filename of rcp or the name of
589 a workalike program.
590 * `tramp-copy-args'
591 This specifies the list of parameters to pass to the above mentioned
592 program, the hints for `tramp-login-args' also apply here.
593 * `tramp-copy-keep-date'
594 This specifies whether the copying program when the preserves the
595 timestamp of the original file.
596 * `tramp-default-port'
597 The default port of a method is needed in case of gateway connections.
598 Additionally, it is used as indication which method is prepared for
599 passing gateways.
600 * `tramp-gw-args'
601 As the attribute name says, additional arguments are specified here
602 when a method is applied via a gateway.
603 * `tramp-password-end-of-line'
604 This specifies the string to use for terminating the line after
605 submitting the password. If this method parameter is nil, then the
606 value of the normal variable `tramp-default-password-end-of-line'
607 is used. This parameter is necessary because the \"plink\" program
608 requires any two characters after sending the password. These do
609 not have to be newline or carriage return characters. Other login
610 programs are happy with just one character, the newline character.
611 We use \"xy\" as the value for methods using \"plink\".
613 What does all this mean? Well, you should specify `tramp-login-program'
614 for all methods; this program is used to log in to the remote site. Then,
615 there are two ways to actually transfer the files between the local and the
616 remote side. One way is using an additional rcp-like program. If you want
617 to do this, set `tramp-copy-program' in the method.
619 Another possibility for file transfer is inline transfer, i.e. the
620 file is passed through the same buffer used by `tramp-login-program'. In
621 this case, the file contents need to be protected since the
622 `tramp-login-program' might use escape codes or the connection might not
623 be eight-bit clean. Therefore, file contents are encoded for transit.
624 See the variables `tramp-local-coding-commands' and
625 `tramp-remote-coding-commands' for details.
627 So, to summarize: if the method is an out-of-band method, then you
628 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
629 inline method, then these two parameters should be nil. Methods which
630 are fit for gateways must have `tramp-default-port' at least.
632 Notes:
634 When using `su' or `sudo' the phrase `open connection to a remote
635 host' sounds strange, but it is used nevertheless, for consistency.
636 No connection is opened to a remote host, but `su' or `sudo' is
637 started on the local host. You should specify a remote host
638 `localhost' or the name of the local host. Another host name is
639 useful only in combination with `tramp-default-proxies-alist'.")
641 (defcustom tramp-default-method
642 ;; An external copy method seems to be preferred, because it is much
643 ;; more performant for large files, and it hasn't too serious delays
644 ;; for small files. But it must be ensured that there aren't
645 ;; permanent password queries. Either a password agent like
646 ;; "ssh-agent" or "Pageant" shall run, or the optional password.el
647 ;; package shall be active for password caching. "scpc" would be
648 ;; another good choice because of the "ControlMaster" option, but
649 ;; this is a more modern alternative in OpenSSH 4, which cannot be
650 ;; taken as default.
651 (cond
652 ;; PuTTY is installed.
653 ((executable-find "pscp")
654 (if (or (fboundp 'password-read)
655 ;; Pageant is running.
656 (and (fboundp 'w32-window-exists-p)
657 (funcall (symbol-function 'w32-window-exists-p)
658 "Pageant" "Pageant")))
659 "pscp"
660 "plink"))
661 ;; There is an ssh installation.
662 ((executable-find "scp")
663 (if (or (fboundp 'password-read)
664 ;; ssh-agent is running.
665 (getenv "SSH_AUTH_SOCK")
666 (getenv "SSH_AGENT_PID"))
667 "scp"
668 "ssh"))
669 ;; Fallback.
670 (t "ftp"))
671 "*Default method to use for transferring files.
672 See `tramp-methods' for possibilities.
673 Also see `tramp-default-method-alist'."
674 :group 'tramp
675 :type 'string)
677 (defcustom tramp-default-method-alist
678 '(("\\`localhost\\'" "\\`root\\'" "su"))
679 "*Default method to use for specific host/user pairs.
680 This is an alist of items (HOST USER METHOD). The first matching item
681 specifies the method to use for a file name which does not specify a
682 method. HOST and USER are regular expressions or nil, which is
683 interpreted as a regular expression which always matches. If no entry
684 matches, the variable `tramp-default-method' takes effect.
686 If the file name does not specify the user, lookup is done using the
687 empty string for the user name.
689 See `tramp-methods' for a list of possibilities for METHOD."
690 :group 'tramp
691 :type '(repeat (list (regexp :tag "Host regexp")
692 (regexp :tag "User regexp")
693 (string :tag "Method"))))
695 (defcustom tramp-default-user
697 "*Default user to use for transferring files.
698 It is nil by default; otherwise settings in configuration files like
699 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
701 This variable is regarded as obsolete, and will be removed soon."
702 :group 'tramp
703 :type '(choice (const nil) string))
705 (defcustom tramp-default-user-alist
706 `(("\\`su\\(do\\)?\\'" nil "root")
707 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
708 nil ,(user-login-name)))
709 "*Default user to use for specific method/host pairs.
710 This is an alist of items (METHOD HOST USER). The first matching item
711 specifies the user to use for a file name which does not specify a
712 user. METHOD and USER are regular expressions or nil, which is
713 interpreted as a regular expression which always matches. If no entry
714 matches, the variable `tramp-default-user' takes effect.
716 If the file name does not specify the method, lookup is done using the
717 empty string for the method name."
718 :group 'tramp
719 :type '(repeat (list (regexp :tag "Method regexp")
720 (regexp :tag "Host regexp")
721 (string :tag "User"))))
723 (defcustom tramp-default-host
724 (system-name)
725 "*Default host to use for transferring files.
726 Useful for su and sudo methods mostly."
727 :group 'tramp
728 :type 'string)
730 (defcustom tramp-default-proxies-alist nil
731 "*Route to be followed for specific host/user pairs.
732 This is an alist of items (HOST USER PROXY). The first matching
733 item specifies the proxy to be passed for a file name located on
734 a remote target matching USER@HOST. HOST and USER are regular
735 expressions or nil, which is interpreted as a regular expression
736 which always matches. PROXY must be a Tramp filename without a
737 localname part. Method and user name on PROXY are optional,
738 which is interpreted with the default values. PROXY can contain
739 the patterns %h and %u, which are replaced by the strings
740 matching HOST or USER, respectively."
741 :group 'tramp
742 :type '(repeat (list (regexp :tag "Host regexp")
743 (regexp :tag "User regexp")
744 (string :tag "Proxy remote name"))))
746 (defconst tramp-completion-function-alist-rsh
747 '((tramp-parse-rhosts "/etc/hosts.equiv")
748 (tramp-parse-rhosts "~/.rhosts"))
749 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
751 (defconst tramp-completion-function-alist-ssh
752 '((tramp-parse-rhosts "/etc/hosts.equiv")
753 (tramp-parse-rhosts "/etc/shosts.equiv")
754 (tramp-parse-shosts "/etc/ssh_known_hosts")
755 (tramp-parse-sconfig "/etc/ssh_config")
756 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
757 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
758 (tramp-parse-rhosts "~/.rhosts")
759 (tramp-parse-rhosts "~/.shosts")
760 (tramp-parse-shosts "~/.ssh/known_hosts")
761 (tramp-parse-sconfig "~/.ssh/config")
762 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
763 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
764 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
766 (defconst tramp-completion-function-alist-telnet
767 '((tramp-parse-hosts "/etc/hosts"))
768 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
770 (defconst tramp-completion-function-alist-su
771 '((tramp-parse-passwd "/etc/passwd"))
772 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
774 (defconst tramp-completion-function-alist-putty
775 '((tramp-parse-putty
776 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
777 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
779 (defvar tramp-completion-function-alist nil
780 "*Alist of methods for remote files.
781 This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
782 Each NAME stands for a remote access method. Each PAIR is of the form
783 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
784 names from FILE for completion. The following predefined FUNCTIONs exists:
786 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
787 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
788 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
789 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
790 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
791 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
792 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
793 * `tramp-parse-netrc' for \"~/.netrc\" like files.
794 * `tramp-parse-putty' for PuTTY registry keys.
796 FUNCTION can also be a customer defined function. For more details see
797 the info pages.")
799 (eval-after-load "tramp"
800 '(progn
801 (tramp-set-completion-function
802 "rcp" tramp-completion-function-alist-rsh)
803 (tramp-set-completion-function
804 "scp" tramp-completion-function-alist-ssh)
805 (tramp-set-completion-function
806 "scp1" tramp-completion-function-alist-ssh)
807 (tramp-set-completion-function
808 "scp2" tramp-completion-function-alist-ssh)
809 (tramp-set-completion-function
810 "scp1_old" tramp-completion-function-alist-ssh)
811 (tramp-set-completion-function
812 "scp2_old" tramp-completion-function-alist-ssh)
813 (tramp-set-completion-function
814 "rsync" tramp-completion-function-alist-rsh)
815 (tramp-set-completion-function
816 "remcp" tramp-completion-function-alist-rsh)
817 (tramp-set-completion-function
818 "rsh" tramp-completion-function-alist-rsh)
819 (tramp-set-completion-function
820 "ssh" tramp-completion-function-alist-ssh)
821 (tramp-set-completion-function
822 "ssh1" tramp-completion-function-alist-ssh)
823 (tramp-set-completion-function
824 "ssh2" tramp-completion-function-alist-ssh)
825 (tramp-set-completion-function
826 "ssh1_old" tramp-completion-function-alist-ssh)
827 (tramp-set-completion-function
828 "ssh2_old" tramp-completion-function-alist-ssh)
829 (tramp-set-completion-function
830 "remsh" tramp-completion-function-alist-rsh)
831 (tramp-set-completion-function
832 "telnet" tramp-completion-function-alist-telnet)
833 (tramp-set-completion-function
834 "su" tramp-completion-function-alist-su)
835 (tramp-set-completion-function
836 "sudo" tramp-completion-function-alist-su)
837 (tramp-set-completion-function
838 "scpx" tramp-completion-function-alist-ssh)
839 (tramp-set-completion-function
840 "sshx" tramp-completion-function-alist-ssh)
841 (tramp-set-completion-function
842 "krlogin" tramp-completion-function-alist-rsh)
843 (tramp-set-completion-function
844 "plink" tramp-completion-function-alist-ssh)
845 (tramp-set-completion-function
846 "plink1" tramp-completion-function-alist-ssh)
847 (tramp-set-completion-function
848 "plinkx" tramp-completion-function-alist-putty)
849 (tramp-set-completion-function
850 "pscp" tramp-completion-function-alist-ssh)
851 (tramp-set-completion-function
852 "fcp" tramp-completion-function-alist-ssh)))
854 (defconst tramp-echo-mark "_echo\b\b\b\b\b"
855 "String mark to be transmitted around shell commands.
856 Used to separate their echo from the output they produce. This
857 will only be used if we cannot disable remote echo via stty.
858 This string must have no effect on the remote shell except for
859 producing some echo which can later be detected by
860 `tramp-echoed-echo-mark-regexp'. Using some characters followed
861 by an equal number of backspaces to erase them will usually
862 suffice.")
864 (defconst tramp-echoed-echo-mark-regexp "_echo\\(\b\\( \b\\)?\\)\\{5\\}"
865 "Regexp which matches `tramp-echo-mark' as it gets echoed by
866 the remote shell.")
868 (defcustom tramp-rsh-end-of-line "\n"
869 "*String used for end of line in rsh connections.
870 I don't think this ever needs to be changed, so please tell me about it
871 if you need to change this.
872 Also see the method parameter `tramp-password-end-of-line' and the normal
873 variable `tramp-default-password-end-of-line'."
874 :group 'tramp
875 :type 'string)
877 (defcustom tramp-default-password-end-of-line
878 tramp-rsh-end-of-line
879 "*String used for end of line after sending a password.
880 This variable provides the default value for the method parameter
881 `tramp-password-end-of-line', see `tramp-methods' for more details.
883 It seems that people using plink under Windows need to send
884 \"\\r\\n\" (carriage-return, then newline) after a password, but just
885 \"\\n\" after all other lines. This variable can be used for the
886 password, see `tramp-rsh-end-of-line' for the other cases.
888 The default value is to use the same value as `tramp-rsh-end-of-line'."
889 :group 'tramp
890 :type 'string)
892 ;; "getconf PATH" yields:
893 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
894 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
895 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
896 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
897 (defcustom tramp-remote-path
898 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
899 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
900 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
901 "*List of directories to search for executables on remote host.
902 For every remote host, this variable will be set buffer local,
903 keeping the list of existing directories on that host.
905 You can use `~' in this list, but when searching for a shell which groks
906 tilde expansion, all directory names starting with `~' will be ignored.
908 `Default Directories' represent the list of directories given by
909 the command \"getconf PATH\". It is recommended to use this
910 entry on top of this list, because these are the default
911 directories for POSIX compatible commands."
912 :group 'tramp
913 :type '(repeat (choice
914 (const :tag "Default Directories" tramp-default-remote-path)
915 (string :tag "Directory"))))
917 (defcustom tramp-remote-process-environment
918 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
919 ,(concat "TERM=" tramp-terminal-type)
920 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
921 "autocorrect=" "correct=")
923 "*List of environment variables to be set on the remote host.
925 Each element should be a string of the form ENVVARNAME=VALUE. An
926 entry ENVVARNAME= diables the corresponding environment variable,
927 which might have been set in the init files like ~/.profile.
929 Special handling is applied to the PATH environment, which should
930 not be set here. Instead of, it should be set via `tramp-remote-path'."
931 :group 'tramp
932 :type '(repeat string))
934 (defcustom tramp-login-prompt-regexp
935 ".*ogin\\( .*\\)?: *"
936 "*Regexp matching login-like prompts.
937 The regexp should match at end of buffer.
939 Sometimes the prompt is reported to look like \"login as:\"."
940 :group 'tramp
941 :type 'regexp)
943 (defcustom tramp-shell-prompt-pattern
944 "^[^#$%>\n]*[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
945 "Regexp to match prompts from remote shell.
946 Normally, Tramp expects you to configure `shell-prompt-pattern'
947 correctly, but sometimes it happens that you are connecting to a
948 remote host which sends a different kind of shell prompt. Therefore,
949 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
950 and also things matched by this variable. The default value of this
951 variable is similar to the default value of `shell-prompt-pattern',
952 which should work well in many cases."
953 :group 'tramp
954 :type 'regexp)
956 (defcustom tramp-password-prompt-regexp
957 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
958 "*Regexp matching password-like prompts.
959 The regexp should match at end of buffer.
961 The `sudo' program appears to insert a `^@' character into the prompt."
962 :group 'tramp
963 :type 'regexp)
965 (defcustom tramp-wrong-passwd-regexp
966 (concat "^.*"
967 ;; These strings should be on the last line
968 (regexp-opt '("Permission denied"
969 "Login incorrect"
970 "Login Incorrect"
971 "Connection refused"
972 "Connection closed"
973 "Sorry, try again."
974 "Name or service not known"
975 "Host key verification failed."
976 "No supported authentication methods left to try!"
977 "Tramp connection closed") t)
978 ".*"
979 "\\|"
980 "^.*\\("
981 ;; Here comes a list of regexes, separated by \\|
982 "Received signal [0-9]+"
983 "\\).*")
984 "*Regexp matching a `login failed' message.
985 The regexp should match at end of buffer."
986 :group 'tramp
987 :type 'regexp)
989 (defcustom tramp-yesno-prompt-regexp
990 (concat
991 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
992 "\\s-*")
993 "Regular expression matching all yes/no queries which need to be confirmed.
994 The confirmation should be done with yes or no.
995 The regexp should match at end of buffer.
996 See also `tramp-yn-prompt-regexp'."
997 :group 'tramp
998 :type 'regexp)
1000 (defcustom tramp-yn-prompt-regexp
1001 (concat
1002 (regexp-opt '("Store key in cache? (y/n)"
1003 "Update cached key? (y/n, Return cancels connection)") t)
1004 "\\s-*")
1005 "Regular expression matching all y/n queries which need to be confirmed.
1006 The confirmation should be done with y or n.
1007 The regexp should match at end of buffer.
1008 See also `tramp-yesno-prompt-regexp'."
1009 :group 'tramp
1010 :type 'regexp)
1012 (defcustom tramp-terminal-prompt-regexp
1013 (concat "\\("
1014 "TERM = (.*)"
1015 "\\|"
1016 "Terminal type\\? \\[.*\\]"
1017 "\\)\\s-*")
1018 "Regular expression matching all terminal setting prompts.
1019 The regexp should match at end of buffer.
1020 The answer will be provided by `tramp-action-terminal', which see."
1021 :group 'tramp
1022 :type 'regexp)
1024 (defcustom tramp-operation-not-permitted-regexp
1025 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1026 (regexp-opt '("Operation not permitted") t))
1027 "Regular expression matching keep-date problems in (s)cp operations.
1028 Copying has been performed successfully already, so this message can
1029 be ignored safely."
1030 :group 'tramp
1031 :type 'regexp)
1033 (defcustom tramp-copy-failed-regexp
1034 (concat "\\(.+: "
1035 (regexp-opt '("Permission denied"
1036 "not a regular file"
1037 "is a directory"
1038 "No such file or directory") t)
1039 "\\)\\s-*")
1040 "Regular expression matching copy problems in (s)cp operations."
1041 :group 'tramp
1042 :type 'regexp)
1044 (defcustom tramp-process-alive-regexp
1046 "Regular expression indicating a process has finished.
1047 In fact this expression is empty by intention, it will be used only to
1048 check regularly the status of the associated process.
1049 The answer will be provided by `tramp-action-process-alive',
1050 `tramp-action-out-of-band', which see."
1051 :group 'tramp
1052 :type 'regexp)
1054 (defcustom tramp-temp-name-prefix "tramp."
1055 "*Prefix to use for temporary files.
1056 If this is a relative file name (such as \"tramp.\"), it is considered
1057 relative to the directory name returned by the function
1058 `tramp-compat-temporary-file-directory' (which see). It may also be an
1059 absolute file name; don't forget to include a prefix for the filename
1060 part, though."
1061 :group 'tramp
1062 :type 'string)
1064 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1065 "*Alist specifying extra arguments to pass to the remote shell.
1066 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1067 matching the shell file name and ARGS is a string specifying the
1068 arguments.
1070 This variable is only used when Tramp needs to start up another shell
1071 for tilde expansion. The extra arguments should typically prevent the
1072 shell from reading its init file."
1073 :group 'tramp
1074 ;; This might be the wrong way to test whether the widget type
1075 ;; `alist' is available. Who knows the right way to test it?
1076 :type (if (get 'alist 'widget-type)
1077 '(alist :key-type string :value-type string)
1078 '(repeat (cons string string))))
1080 ;; XEmacs is distributed with few Lisp packages. Further packages are
1081 ;; installed using EFS. If we use a unified filename format, then
1082 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1083 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1084 ;; just like before.) Another reason for using a separate filename
1085 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1086 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1087 ;; the other places.
1089 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1090 ;;;###autoload
1091 (defcustom tramp-syntax
1092 (if (featurep 'xemacs) 'sep 'ftp)
1093 "Tramp filename syntax to be used.
1095 It can have the following values:
1097 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1098 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1099 'url -- URL-like syntax."
1100 :group 'tramp
1101 :type (if (featurep 'xemacs)
1102 '(choice (const :tag "EFS" ftp)
1103 (const :tag "XEmacs" sep)
1104 (const :tag "URL" url))
1105 '(choice (const :tag "Ange-FTP" ftp)
1106 (const :tag "URL" url))))
1108 (defconst tramp-prefix-format
1109 (cond ((equal tramp-syntax 'ftp) "/")
1110 ((equal tramp-syntax 'sep) "/[")
1111 ((equal tramp-syntax 'url) "/")
1112 (t (error "Wrong `tramp-syntax' defined")))
1113 "*String matching the very beginning of Tramp file names.
1114 Used in `tramp-make-tramp-file-name'.")
1116 (defconst tramp-prefix-regexp
1117 (concat "^" (regexp-quote tramp-prefix-format))
1118 "*Regexp matching the very beginning of Tramp file names.
1119 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1121 (defconst tramp-method-regexp
1122 "[a-zA-Z_0-9-]+"
1123 "*Regexp matching methods identifiers.")
1125 (defconst tramp-postfix-method-format
1126 (cond ((equal tramp-syntax 'ftp) ":")
1127 ((equal tramp-syntax 'sep) "/")
1128 ((equal tramp-syntax 'url) "://")
1129 (t (error "Wrong `tramp-syntax' defined")))
1130 "*String matching delimeter between method and user or host names.
1131 Used in `tramp-make-tramp-file-name'.")
1133 (defconst tramp-postfix-method-regexp
1134 (regexp-quote tramp-postfix-method-format)
1135 "*Regexp matching delimeter between method and user or host names.
1136 Derived from `tramp-postfix-method-format'.")
1138 (defconst tramp-user-regexp
1139 "[^:/ \t]+"
1140 "*Regexp matching user names.")
1142 (defconst tramp-postfix-user-format
1144 "*String matching delimeter between user and host names.
1145 Used in `tramp-make-tramp-file-name'.")
1147 (defconst tramp-postfix-user-regexp
1148 (regexp-quote tramp-postfix-user-format)
1149 "*Regexp matching delimeter between user and host names.
1150 Derived from `tramp-postfix-user-format'.")
1152 (defconst tramp-host-regexp
1153 "[a-zA-Z0-9_.-]+"
1154 "*Regexp matching host names.")
1156 (defconst tramp-prefix-port-format
1157 (cond ((equal tramp-syntax 'ftp) "#")
1158 ((equal tramp-syntax 'sep) "#")
1159 ((equal tramp-syntax 'url) ":")
1160 (t (error "Wrong `tramp-syntax' defined")))
1161 "*String matching delimeter between host names and port numbers.")
1163 (defconst tramp-prefix-port-regexp
1164 (regexp-quote tramp-prefix-port-format)
1165 "*Regexp matching delimeter between host names and port numbers.
1166 Derived from `tramp-prefix-port-format'.")
1168 (defconst tramp-port-regexp
1169 "[0-9]+"
1170 "*Regexp matching port numbers.")
1172 (defconst tramp-host-with-port-regexp
1173 (concat "\\(" tramp-host-regexp "\\)"
1174 tramp-prefix-port-regexp
1175 "\\(" tramp-port-regexp "\\)")
1176 "*Regexp matching host names with port numbers.")
1178 (defconst tramp-postfix-host-format
1179 (cond ((equal tramp-syntax 'ftp) ":")
1180 ((equal tramp-syntax 'sep) "]")
1181 ((equal tramp-syntax 'url) "")
1182 (t (error "Wrong `tramp-syntax' defined")))
1183 "*String matching delimeter between host names and localnames.
1184 Used in `tramp-make-tramp-file-name'.")
1186 (defconst tramp-postfix-host-regexp
1187 (regexp-quote tramp-postfix-host-format)
1188 "*Regexp matching delimeter between host names and localnames.
1189 Derived from `tramp-postfix-host-format'.")
1191 (defconst tramp-localname-regexp
1192 ".*$"
1193 "*Regexp matching localnames.")
1195 ;; File name format.
1197 (defconst tramp-file-name-structure
1198 (list
1199 (concat
1200 tramp-prefix-regexp
1201 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1202 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1203 "\\(" tramp-host-regexp
1204 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1205 tramp-postfix-host-regexp
1206 "\\(" tramp-localname-regexp "\\)")
1207 2 4 5 7)
1209 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1210 the Tramp file name structure.
1212 The first element REGEXP is a regular expression matching a Tramp file
1213 name. The regex should contain parentheses around the method name,
1214 the user name, the host name, and the file name parts.
1216 The second element METHOD is a number, saying which pair of
1217 parentheses matches the method name. The third element USER is
1218 similar, but for the user name. The fourth element HOST is similar,
1219 but for the host name. The fifth element FILE is for the file name.
1220 These numbers are passed directly to `match-string', which see. That
1221 means the opening parentheses are counted to identify the pair.
1223 See also `tramp-file-name-regexp'.")
1225 ;;;###autoload
1226 (defconst tramp-file-name-regexp-unified
1227 "\\`/[^/:]+:"
1228 "Value for `tramp-file-name-regexp' for unified remoting.
1229 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1230 Tramp. See `tramp-file-name-structure' for more explanations.")
1232 ;;;###autoload
1233 (defconst tramp-file-name-regexp-separate
1234 "\\`/\\[.*\\]"
1235 "Value for `tramp-file-name-regexp' for separate remoting.
1236 XEmacs uses a separate filename syntax for Tramp and EFS.
1237 See `tramp-file-name-structure' for more explanations.")
1239 ;;;###autoload
1240 (defconst tramp-file-name-regexp-url
1241 "\\`/[^/:]+://"
1242 "Value for `tramp-file-name-regexp' for URL-like remoting.
1243 See `tramp-file-name-structure' for more explanations.")
1245 ;;;###autoload
1246 (defconst tramp-file-name-regexp
1247 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1248 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1249 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1250 (t (error "Wrong `tramp-syntax' defined")))
1251 "*Regular expression matching file names handled by Tramp.
1252 This regexp should match Tramp file names but no other file names.
1253 \(When tramp.el is loaded, this regular expression is prepended to
1254 `file-name-handler-alist', and that is searched sequentially. Thus,
1255 if the Tramp entry appears rather early in the `file-name-handler-alist'
1256 and is a bit too general, then some files might be considered Tramp
1257 files which are not really Tramp files.
1259 Please note that the entry in `file-name-handler-alist' is made when
1260 this file (tramp.el) is loaded. This means that this variable must be set
1261 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1262 updated after changing this variable.
1264 Also see `tramp-file-name-structure'.")
1266 ;;;###autoload
1267 (defconst tramp-root-regexp
1268 (if (memq system-type '(cygwin windows-nt))
1269 "^\\([a-zA-Z]:\\)?/"
1270 "^/")
1271 "Beginning of an incomplete Tramp file name.
1272 Usually, it is just \"^/\". On W32 systems, there might be a
1273 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1275 ;;;###autoload
1276 (defconst tramp-completion-file-name-regexp-unified
1277 (concat tramp-root-regexp "[^/]*$")
1278 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1279 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1280 See `tramp-file-name-structure' for more explanations.")
1282 ;;;###autoload
1283 (defconst tramp-completion-file-name-regexp-separate
1284 (concat tramp-root-regexp "\\([[][^]]*\\)?$")
1285 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1286 XEmacs uses a separate filename syntax for Tramp and EFS.
1287 See `tramp-file-name-structure' for more explanations.")
1289 ;;;###autoload
1290 (defconst tramp-completion-file-name-regexp-url
1291 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?$")
1292 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1293 See `tramp-file-name-structure' for more explanations.")
1295 ;;;###autoload
1296 (defconst tramp-completion-file-name-regexp
1297 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1298 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1299 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1300 (t (error "Wrong `tramp-syntax' defined")))
1301 "*Regular expression matching file names handled by Tramp completion.
1302 This regexp should match partial Tramp file names only.
1304 Please note that the entry in `file-name-handler-alist' is made when
1305 this file (tramp.el) is loaded. This means that this variable must be set
1306 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1307 updated after changing this variable.
1309 Also see `tramp-file-name-structure'.")
1311 (defconst tramp-actions-before-shell
1312 '((tramp-login-prompt-regexp tramp-action-login)
1313 (tramp-password-prompt-regexp tramp-action-password)
1314 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1315 (shell-prompt-pattern tramp-action-succeed)
1316 (tramp-shell-prompt-pattern tramp-action-succeed)
1317 (tramp-yesno-prompt-regexp tramp-action-yesno)
1318 (tramp-yn-prompt-regexp tramp-action-yn)
1319 (tramp-terminal-prompt-regexp tramp-action-terminal)
1320 (tramp-process-alive-regexp tramp-action-process-alive))
1321 "List of pattern/action pairs.
1322 Whenever a pattern matches, the corresponding action is performed.
1323 Each item looks like (PATTERN ACTION).
1325 The PATTERN should be a symbol, a variable. The value of this
1326 variable gives the regular expression to search for. Note that the
1327 regexp must match at the end of the buffer, \"\\'\" is implicitly
1328 appended to it.
1330 The ACTION should also be a symbol, but a function. When the
1331 corresponding PATTERN matches, the ACTION function is called.")
1333 (defconst tramp-actions-copy-out-of-band
1334 '((tramp-password-prompt-regexp tramp-action-password)
1335 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1336 (tramp-copy-failed-regexp tramp-action-permission-denied)
1337 (tramp-process-alive-regexp tramp-action-out-of-band))
1338 "List of pattern/action pairs.
1339 This list is used for copying/renaming with out-of-band methods.
1341 See `tramp-actions-before-shell' for more info.")
1343 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1344 ;; known to have a bug in `process-send-string'; some ssh connections appear
1345 ;; to drop bytes when data is sent too quickly. There is also a connection
1346 ;; buffer local variable, which is computed depending on remote host properties
1347 ;; when `tramp-chunksize' is zero or nil.
1348 (defcustom tramp-chunksize
1349 (when (and (not (featurep 'xemacs))
1350 (memq system-type '(hpux)))
1351 500)
1352 ;; Parentheses in docstring starting at beginning of line are escaped.
1353 ;; Fontification is messed up when
1354 ;; `open-paren-in-column-0-is-defun-start' set to t.
1355 "*If non-nil, chunksize for sending input to local process.
1356 It is necessary only on systems which have a buggy `process-send-string'
1357 implementation. The necessity, whether this variable must be set, can be
1358 checked via the following code:
1360 (with-temp-buffer
1361 (let* ((user \"xxx\") (host \"yyy\")
1362 (init 0) (step 50)
1363 (sent init) (received init))
1364 (while (= sent received)
1365 (setq sent (+ sent step))
1366 (erase-buffer)
1367 (let ((proc (start-process (buffer-name) (current-buffer)
1368 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1369 (when (memq (process-status proc) '(run open))
1370 (process-send-string proc (make-string sent ?\\ ))
1371 (process-send-eof proc)
1372 (process-send-eof proc))
1373 (while (not (progn (goto-char (point-min))
1374 (re-search-forward \"\\\\w+\" (point-max) t)))
1375 (accept-process-output proc 1))
1376 (when (memq (process-status proc) '(run open))
1377 (setq received (string-to-number (match-string 0)))
1378 (delete-process proc)
1379 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1380 (sit-for 0))))
1381 (if (> sent (+ init step))
1382 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1383 (- sent step))
1384 (message \"Test does not work\")
1385 (display-buffer (current-buffer))
1386 (sit-for 30))))
1388 In the Emacs normally running Tramp, evaluate the above code
1389 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1390 respectively). You can do this, for example, by pasting it into
1391 the `*scratch*' buffer and then hitting C-j with the cursor after the
1392 last closing parenthesis. Note that it works only if you have configured
1393 \"ssh\" to run without password query, see ssh-agent(1).
1395 You will see the number of bytes sent successfully to the remote host.
1396 If that number exceeds 1000, you can stop the execution by hitting
1397 C-g, because your Emacs is likely clean.
1399 When it is necessary to set `tramp-chunksize', you might consider to
1400 use an out-of-the-band method (like \"scp\") instead of an internal one
1401 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
1402 performance.
1404 If your Emacs is buggy, the code stops and gives you an indication
1405 about the value `tramp-chunksize' should be set. Maybe you could just
1406 experiment a bit, e.g. changing the values of `init' and `step'
1407 in the third line of the code.
1409 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1410 this variable to be set as well."
1411 :group 'tramp
1412 :type '(choice (const nil) integer))
1414 ;; Logging in to a remote host normally requires obtaining a pty. But
1415 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1416 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1417 ;; for an override of the system default.
1418 (defcustom tramp-process-connection-type t
1419 "Overrides `process-connection-type' for connections from Tramp.
1420 Tramp binds process-connection-type to the value given here before
1421 opening a connection to a remote host."
1422 :group 'tramp
1423 :type '(choice (const nil) (const t) (const pty)))
1425 (defcustom tramp-completion-reread-directory-timeout 10
1426 "Defines seconds since last remote command before rereading a directory.
1427 A remote directory might have changed its contents. In order to
1428 make it visible during file name completion in the minibuffer,
1429 Tramp flushes its cache and rereads the directory contents when
1430 more than `tramp-completion-reread-directory-timeout' seconds
1431 have been gone since last remote command execution. A value of 0
1432 would require an immediate reread during filename completion, nil
1433 means to use always cached values for the directory contents."
1434 :group 'tramp
1435 :type '(choice (const nil) integer))
1437 ;;; Internal Variables:
1439 (defvar tramp-end-of-output
1440 (format
1441 "%s///%s%s"
1442 tramp-rsh-end-of-line
1443 (md5 (concat (prin1-to-string process-environment) (current-time-string)))
1444 tramp-rsh-end-of-line)
1445 "String used to recognize end of output.")
1447 (defvar tramp-current-method nil
1448 "Connection method for this *tramp* buffer.")
1450 (defvar tramp-current-user nil
1451 "Remote login name for this *tramp* buffer.")
1453 (defvar tramp-current-host nil
1454 "Remote host for this *tramp* buffer.")
1456 (defconst tramp-uudecode
1457 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1458 cat /tmp/tramp.$$
1459 rm -f /tmp/tramp.$$"
1460 "Shell function to implement `uudecode' to standard output.
1461 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1462 for this or `uudecode -p', but some systems don't, and for them
1463 we have this shell function.")
1465 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1466 ;; output. If you are hacking on this, note that you get *no* output
1467 ;; unless this spits out a complete line, including the '\n' at the
1468 ;; end.
1469 ;; The device number is returned as "-1", because there will be a virtual
1470 ;; device number set in `tramp-handle-file-attributes'
1471 (defconst tramp-perl-file-attributes
1472 "%s -e '
1473 @stat = lstat($ARGV[0]);
1474 if (($stat[2] & 0170000) == 0120000)
1476 $type = readlink($ARGV[0]);
1477 $type = \"\\\"$type\\\"\";
1479 elsif (($stat[2] & 0170000) == 040000)
1481 $type = \"t\";
1483 else
1485 $type = \"nil\"
1487 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1488 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1489 printf(
1490 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1491 $type,
1492 $stat[3],
1493 $uid,
1494 $gid,
1495 $stat[8] >> 16 & 0xffff,
1496 $stat[8] & 0xffff,
1497 $stat[9] >> 16 & 0xffff,
1498 $stat[9] & 0xffff,
1499 $stat[10] >> 16 & 0xffff,
1500 $stat[10] & 0xffff,
1501 $stat[7],
1502 $stat[2],
1503 $stat[1] >> 16 & 0xffff,
1504 $stat[1] & 0xffff
1505 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1506 "Perl script to produce output suitable for use with `file-attributes'
1507 on the remote file system.
1508 Escape sequence %s is replaced with name of Perl binary.
1509 This string is passed to `format', so percent characters need to be doubled.")
1511 (defconst tramp-perl-directory-files-and-attributes
1512 "%s -e '
1513 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1514 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1515 @list = readdir(DIR);
1516 closedir(DIR);
1517 $n = scalar(@list);
1518 printf(\"(\\n\");
1519 for($i = 0; $i < $n; $i++)
1521 $filename = $list[$i];
1522 @stat = lstat($filename);
1523 if (($stat[2] & 0170000) == 0120000)
1525 $type = readlink($filename);
1526 $type = \"\\\"$type\\\"\";
1528 elsif (($stat[2] & 0170000) == 040000)
1530 $type = \"t\";
1532 else
1534 $type = \"nil\"
1536 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1537 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1538 printf(
1539 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u %%u))\\n\",
1540 $filename,
1541 $type,
1542 $stat[3],
1543 $uid,
1544 $gid,
1545 $stat[8] >> 16 & 0xffff,
1546 $stat[8] & 0xffff,
1547 $stat[9] >> 16 & 0xffff,
1548 $stat[9] & 0xffff,
1549 $stat[10] >> 16 & 0xffff,
1550 $stat[10] & 0xffff,
1551 $stat[7],
1552 $stat[2],
1553 $stat[1] >> 16 & 0xffff,
1554 $stat[1] & 0xffff,
1555 $stat[0] >> 16 & 0xffff,
1556 $stat[0] & 0xffff);
1558 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1559 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1560 output.
1561 Escape sequence %s is replaced with name of Perl binary.
1562 This string is passed to `format', so percent characters need to be doubled.")
1564 ;; ;; These two use uu encoding.
1565 ;; (defvar tramp-perl-encode "%s -e'\
1566 ;; print qq(begin 644 xxx\n);
1567 ;; my $s = q();
1568 ;; my $res = q();
1569 ;; while (read(STDIN, $s, 45)) {
1570 ;; print pack(q(u), $s);
1571 ;; }
1572 ;; print qq(`\n);
1573 ;; print qq(end\n);
1574 ;; '"
1575 ;; "Perl program to use for encoding a file.
1576 ;; Escape sequence %s is replaced with name of Perl binary.")
1578 ;; (defvar tramp-perl-decode "%s -ne '
1579 ;; print unpack q(u), $_;
1580 ;; '"
1581 ;; "Perl program to use for decoding a file.
1582 ;; Escape sequence %s is replaced with name of Perl binary.")
1584 ;; These two use base64 encoding.
1585 (defconst tramp-perl-encode-with-module
1586 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1587 "Perl program to use for encoding a file.
1588 Escape sequence %s is replaced with name of Perl binary.
1589 This string is passed to `format', so percent characters need to be doubled.
1590 This implementation requires the MIME::Base64 Perl module to be installed
1591 on the remote host.")
1593 (defconst tramp-perl-decode-with-module
1594 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1595 "Perl program to use for decoding a file.
1596 Escape sequence %s is replaced with name of Perl binary.
1597 This string is passed to `format', so percent characters need to be doubled.
1598 This implementation requires the MIME::Base64 Perl module to be installed
1599 on the remote host.")
1601 (defconst tramp-perl-encode
1602 "%s -e '
1603 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1604 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
1605 # Free Software Foundation, Inc.
1606 use strict;
1608 my %%trans = do {
1609 my $i = 0;
1610 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1611 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1614 binmode(\\*STDIN);
1616 # We read in chunks of 54 bytes, to generate output lines
1617 # of 72 chars (plus end of line)
1618 $/ = \\54;
1620 while (my $data = <STDIN>) {
1621 my $pad = q();
1623 # Only for the last chunk, and only if did not fill the last three-byte packet
1624 if (eof) {
1625 my $mod = length($data) %% 3;
1626 $pad = q(=) x (3 - $mod) if $mod;
1629 # Not the fastest method, but it is simple: unpack to binary string, split
1630 # by groups of 6 bits and convert back from binary to byte; then map into
1631 # the translation table
1632 print
1633 join q(),
1634 map($trans{$_},
1635 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1636 $pad,
1637 qq(\\n);
1638 }' 2>/dev/null"
1639 "Perl program to use for encoding a file.
1640 Escape sequence %s is replaced with name of Perl binary.
1641 This string is passed to `format', so percent characters need to be doubled.")
1643 (defconst tramp-perl-decode
1644 "%s -e '
1645 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1646 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
1647 # Free Software Foundation, Inc.
1648 use strict;
1650 my %%trans = do {
1651 my $i = 0;
1652 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1653 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1656 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1658 binmode(\\*STDOUT);
1660 # We are going to accumulate into $pending to accept any line length
1661 # (we do not check they are <= 76 chars as the RFC says)
1662 my $pending = q();
1664 while (my $data = <STDIN>) {
1665 chomp $data;
1667 # If we find one or two =, we have reached the end and
1668 # any following data is to be discarded
1669 my $finished = $data =~ s/(==?).*/$1/;
1670 $pending .= $data;
1672 my $len = length($pending);
1673 my $chunk = substr($pending, 0, $len & ~3);
1674 $pending = substr($pending, $len & ~3 + 1);
1676 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1677 # split in 8-bit chunks and convert back to char.
1678 print join q(),
1679 map $bytes{$_},
1680 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1682 last if $finished;
1683 }' 2>/dev/null"
1684 "Perl program to use for decoding a file.
1685 Escape sequence %s is replaced with name of Perl binary.
1686 This string is passed to `format', so percent characters need to be doubled.")
1688 (defconst tramp-file-mode-type-map
1689 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1690 (1 . "p") ; fifo
1691 (2 . "c") ; character device
1692 (3 . "m") ; multiplexed character device (v7)
1693 (4 . "d") ; directory
1694 (5 . "?") ; Named special file (XENIX)
1695 (6 . "b") ; block device
1696 (7 . "?") ; multiplexed block device (v7)
1697 (8 . "-") ; regular file
1698 (9 . "n") ; network special file (HP-UX)
1699 (10 . "l") ; symlink
1700 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1701 (12 . "s") ; socket
1702 (13 . "D") ; door special (Solaris)
1703 (14 . "w")) ; whiteout (BSD)
1704 "A list of file types returned from the `stat' system call.
1705 This is used to map a mode number to a permission string.")
1707 ;; New handlers should be added here. The following operations can be
1708 ;; handled using the normal primitives: file-name-as-directory,
1709 ;; file-name-sans-versions, get-file-buffer.
1710 (defconst tramp-file-name-handler-alist
1711 '((load . tramp-handle-load)
1712 (make-symbolic-link . tramp-handle-make-symbolic-link)
1713 (file-name-directory . tramp-handle-file-name-directory)
1714 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1715 (file-truename . tramp-handle-file-truename)
1716 (file-exists-p . tramp-handle-file-exists-p)
1717 (file-directory-p . tramp-handle-file-directory-p)
1718 (file-executable-p . tramp-handle-file-executable-p)
1719 (file-readable-p . tramp-handle-file-readable-p)
1720 (file-regular-p . tramp-handle-file-regular-p)
1721 (file-symlink-p . tramp-handle-file-symlink-p)
1722 (file-writable-p . tramp-handle-file-writable-p)
1723 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1724 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1725 (file-attributes . tramp-handle-file-attributes)
1726 (file-modes . tramp-handle-file-modes)
1727 (directory-files . tramp-handle-directory-files)
1728 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1729 (file-name-all-completions . tramp-handle-file-name-all-completions)
1730 (file-name-completion . tramp-handle-file-name-completion)
1731 (add-name-to-file . tramp-handle-add-name-to-file)
1732 (copy-file . tramp-handle-copy-file)
1733 (rename-file . tramp-handle-rename-file)
1734 (set-file-modes . tramp-handle-set-file-modes)
1735 (set-file-times . tramp-handle-set-file-times)
1736 (make-directory . tramp-handle-make-directory)
1737 (delete-directory . tramp-handle-delete-directory)
1738 (delete-file . tramp-handle-delete-file)
1739 (directory-file-name . tramp-handle-directory-file-name)
1740 ;; `executable-find' is not official yet.
1741 (executable-find . tramp-handle-executable-find)
1742 (start-file-process . tramp-handle-start-file-process)
1743 (process-file . tramp-handle-process-file)
1744 (shell-command . tramp-handle-shell-command)
1745 (insert-directory . tramp-handle-insert-directory)
1746 (expand-file-name . tramp-handle-expand-file-name)
1747 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
1748 (file-local-copy . tramp-handle-file-local-copy)
1749 (file-remote-p . tramp-handle-file-remote-p)
1750 (insert-file-contents . tramp-handle-insert-file-contents)
1751 (insert-file-contents-literally
1752 . tramp-handle-insert-file-contents-literally)
1753 (write-region . tramp-handle-write-region)
1754 (find-backup-file-name . tramp-handle-find-backup-file-name)
1755 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
1756 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
1757 (dired-compress-file . tramp-handle-dired-compress-file)
1758 (dired-recursive-delete-directory
1759 . tramp-handle-dired-recursive-delete-directory)
1760 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
1761 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime))
1762 "Alist of handler functions.
1763 Operations not mentioned here will be handled by the normal Emacs functions.")
1765 ;; Handlers for partial Tramp file names. For Emacs just
1766 ;; `file-name-all-completions' is needed.
1767 ;;;###autoload
1768 (defconst tramp-completion-file-name-handler-alist
1769 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
1770 (file-name-completion . tramp-completion-handle-file-name-completion))
1771 "Alist of completion handler functions.
1772 Used for file names matching `tramp-file-name-regexp'. Operations not
1773 mentioned here will be handled by `tramp-file-name-handler-alist' or the
1774 normal Emacs functions.")
1776 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1777 (defvar tramp-foreign-file-name-handler-alist
1778 ;; (identity . tramp-sh-file-name-handler) should always be the last
1779 ;; entry, since `identity' always matches.
1780 '((identity . tramp-sh-file-name-handler))
1781 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1782 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1783 calling HANDLER.")
1785 ;;; Internal functions which must come first:
1787 (defsubst tramp-debug-message (vec fmt-string &rest args)
1788 "Append message to debug buffer.
1789 Message is formatted with FMT-STRING as control string and the remaining
1790 ARGS to actually emit the message (if applicable)."
1791 (when (get-buffer (tramp-buffer-name vec))
1792 (with-current-buffer (tramp-get-debug-buffer vec)
1793 (goto-char (point-max))
1794 (unless (bolp)
1795 (insert "\n"))
1796 ;; Timestamp
1797 (insert (format-time-string "%T "))
1798 ;; Calling function
1799 (let ((btn 1) btf fn)
1800 (while (not fn)
1801 (setq btf (nth 1 (backtrace-frame btn)))
1802 (if (not btf)
1803 (setq fn "")
1804 (when (symbolp btf)
1805 (setq fn (symbol-name btf))
1806 (unless (and (string-match "^tramp" fn)
1807 (not (string-match
1808 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
1809 fn)))
1810 (setq fn nil)))
1811 (setq btn (1+ btn))))
1812 ;; The following code inserts filename and line number.
1813 ;; Should be deactivated by default, because it is time
1814 ;; consuming.
1815 ; (let ((ffn (find-function-noselect (intern fn))))
1816 ; (insert
1817 ; (format
1818 ; "%s:%d: "
1819 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1820 ; (with-current-buffer (car ffn)
1821 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1822 (insert (format "%s " fn)))
1823 ;; The message
1824 (insert (apply 'format fmt-string args)))))
1826 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
1827 "Emit a message depending on verbosity level.
1828 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1829 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1830 less than LEVEL. The message is emitted only if `tramp-verbose' is
1831 greater than or equal to LEVEL.
1833 The message is also logged into the debug buffer when `tramp-verbose'
1834 is greater than or equal 4.
1836 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1837 control string and the remaining ARGS to actually emit the message (if
1838 applicable)."
1839 (condition-case nil
1840 (when (<= level tramp-verbose)
1841 ;; Match data must be preserved!
1842 (save-match-data
1843 ;; Display only when there is a minimum level.
1844 (when (<= level 3)
1845 (apply 'message
1846 (concat
1847 (cond
1848 ((= level 0) "")
1849 ((= level 1) "")
1850 ((= level 2) "Warning: ")
1851 (t "Tramp: "))
1852 fmt-string)
1853 args))
1854 ;; Log only when there is a minimum level.
1855 (when (>= tramp-verbose 4)
1856 (when (and vec-or-proc
1857 (processp vec-or-proc)
1858 (buffer-name (process-buffer vec-or-proc)))
1859 (with-current-buffer (process-buffer vec-or-proc)
1860 ;; Translate proc to vec.
1861 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
1862 (when (and vec-or-proc (vectorp vec-or-proc))
1863 (apply 'tramp-debug-message
1864 vec-or-proc
1865 (concat (format "(%d) # " level) fmt-string)
1866 args)))))
1867 ;; Suppress all errors.
1868 (error nil)))
1870 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
1871 "Emit an error.
1872 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1873 signal identifier to be raised, remaining args passed to
1874 `tramp-message'. Finally, signal SIGNAL is raised."
1875 (tramp-message
1876 vec-or-proc 1 "%s"
1877 (error-message-string
1878 (list signal (get signal 'error-message) (apply 'format fmt-string args))))
1879 (signal signal (list (apply 'format fmt-string args))))
1881 (defsubst tramp-error-with-buffer
1882 (buffer vec-or-proc signal fmt-string &rest args)
1883 "Emit an error, and show BUFFER.
1884 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
1885 an input event arrives. The other arguments are passed to `tramp-error'."
1886 (save-window-excursion
1887 (unwind-protect
1888 (apply 'tramp-error vec-or-proc signal fmt-string args)
1889 (when (and vec-or-proc (not (zerop tramp-verbose)))
1890 (let ((enable-recursive-minibuffers t))
1891 (pop-to-buffer
1892 (or (and (bufferp buffer) buffer)
1893 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1894 (tramp-get-buffer vec-or-proc)))
1895 (sit-for 30))))))
1897 (defmacro with-parsed-tramp-file-name (filename var &rest body)
1898 "Parse a Tramp filename and make components available in the body.
1900 First arg FILENAME is evaluated and dissected into its components.
1901 Second arg VAR is a symbol. It is used as a variable name to hold
1902 the filename structure. It is also used as a prefix for the variables
1903 holding the components. For example, if VAR is the symbol `foo', then
1904 `foo' will be bound to the whole structure, `foo-method' will be bound to
1905 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
1907 Remaining args are Lisp expressions to be evaluated (inside an implicit
1908 `progn').
1910 If VAR is nil, then we bind `v' to the structure and `method', `user',
1911 `host', `localname' to the components."
1912 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
1913 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
1914 (tramp-file-name-method ,(or var 'v)))
1915 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
1916 (tramp-file-name-user ,(or var 'v)))
1917 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
1918 (tramp-file-name-host ,(or var 'v)))
1919 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
1920 (tramp-file-name-localname ,(or var 'v))))
1921 ,@body))
1923 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
1924 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
1925 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
1927 (defmacro with-file-property (vec file property &rest body)
1928 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
1929 FILE must be a local file name on a connection identified via VEC."
1930 `(if (file-name-absolute-p ,file)
1931 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
1932 (when (eq value 'undef)
1933 ;; We cannot pass @body as parameter to
1934 ;; `tramp-set-file-property' because it mangles our
1935 ;; debug messages.
1936 (setq value (progn ,@body))
1937 (tramp-set-file-property ,vec ,file ,property value))
1938 value)
1939 ,@body))
1941 (put 'with-file-property 'lisp-indent-function 3)
1942 (put 'with-file-property 'edebug-form-spec t)
1943 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
1945 (defmacro with-connection-property (key property &rest body)
1946 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
1947 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
1948 (when (eq value 'undef)
1949 ;; We cannot pass ,@body as parameter to
1950 ;; `tramp-set-connection-property' because it mangles our debug
1951 ;; messages.
1952 (setq value (progn ,@body))
1953 (tramp-set-connection-property ,key ,property value))
1954 value))
1956 (put 'with-connection-property 'lisp-indent-function 2)
1957 (put 'with-connection-property 'edebug-form-spec t)
1958 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
1960 (eval-and-compile ; silence compiler
1961 (if (memq system-type '(cygwin windows-nt))
1962 (defun tramp-drop-volume-letter (name)
1963 "Cut off unnecessary drive letter from file NAME.
1964 The function `tramp-handle-expand-file-name' calls `expand-file-name'
1965 locally on a remote file name. When the local system is a W32 system
1966 but the remote system is Unix, this introduces a superfluous drive
1967 letter into the file name. This function removes it."
1968 (save-match-data
1969 (if (string-match tramp-root-regexp name)
1970 (replace-match "/" nil t name)
1971 name)))
1973 (defalias 'tramp-drop-volume-letter 'identity)))
1975 (defsubst tramp-make-tramp-temp-file (vec)
1976 "Create a temporary file on the remote host identified by VEC.
1977 Return the local name of the temporary file."
1978 (let ((prefix
1979 (tramp-make-tramp-file-name
1980 (tramp-file-name-method vec)
1981 (tramp-file-name-user vec)
1982 (tramp-file-name-host vec)
1983 (tramp-drop-volume-letter
1984 (expand-file-name
1985 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
1986 result)
1987 (while (not result)
1988 ;; `make-temp-file' would be the natural choice for
1989 ;; implementation. But it calls `write-region' internally,
1990 ;; which also needs a temporary file - we would end in an
1991 ;; infinite loop.
1992 (setq result (make-temp-name prefix))
1993 (if (file-exists-p result)
1994 (setq result nil)
1995 ;; This creates the file by side effect.
1996 (set-file-times result)
1997 (set-file-modes result (tramp-octal-to-decimal "0700"))))
1999 ;; Return the local part.
2000 (with-parsed-tramp-file-name result nil localname)))
2003 ;;; Config Manipulation Functions:
2005 (defun tramp-set-completion-function (method function-list)
2006 "Sets the list of completion functions for METHOD.
2007 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2008 The FUNCTION is intended to parse FILE according its syntax.
2009 It might be a predefined FUNCTION, or a user defined FUNCTION.
2010 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2011 `tramp-parse-sconfig',`tramp-parse-hosts', `tramp-parse-passwd',
2012 and `tramp-parse-netrc'.
2014 Example:
2016 (tramp-set-completion-function
2017 \"ssh\"
2018 '((tramp-parse-sconfig \"/etc/ssh_config\")
2019 (tramp-parse-sconfig \"~/.ssh/config\")))"
2021 (let ((r function-list)
2022 (v function-list))
2023 (setq tramp-completion-function-alist
2024 (delete (assoc method tramp-completion-function-alist)
2025 tramp-completion-function-alist))
2027 (while v
2028 ;; Remove double entries.
2029 (when (member (car v) (cdr v))
2030 (setcdr v (delete (car v) (cdr v))))
2031 ;; Check for function and file or registry key.
2032 (unless (and (functionp (nth 0 (car v)))
2033 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2034 ;; Windows registry.
2035 (and (memq system-type '(cygwin windows-nt))
2036 (zerop
2037 (tramp-local-call-process
2038 "reg" nil nil nil "query" (nth 1 (car v)))))
2039 ;; Configuration file.
2040 (file-exists-p (nth 1 (car v)))))
2041 (setq r (delete (car v) r)))
2042 (setq v (cdr v)))
2044 (when r
2045 (add-to-list 'tramp-completion-function-alist
2046 (cons method r)))))
2048 (defun tramp-get-completion-function (method)
2049 "Returns a list of completion functions for METHOD.
2050 For definition of that list see `tramp-set-completion-function'."
2051 (cons
2052 ;; Hosts visited once shall be remembered.
2053 `(tramp-parse-connection-properties ,method)
2054 ;; The method related defaults.
2055 (cdr (assoc method tramp-completion-function-alist))))
2058 ;;; Fontification of `read-file-name':
2060 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2061 (defvar tramp-rfn-eshadow-overlay)
2062 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2064 (defun tramp-rfn-eshadow-setup-minibuffer ()
2065 "Set up a minibuffer for `file-name-shadow-mode'.
2066 Adds another overlay hiding filename parts according to Tramp's
2067 special handling of `substitute-in-file-name'."
2068 (when (symbol-value 'minibuffer-completing-file-name)
2069 (setq tramp-rfn-eshadow-overlay
2070 (funcall (symbol-function 'make-overlay)
2071 (funcall (symbol-function 'minibuffer-prompt-end))
2072 (funcall (symbol-function 'minibuffer-prompt-end))))
2073 ;; Copy rfn-eshadow-overlay properties.
2074 (let ((props (funcall (symbol-function 'overlay-properties)
2075 (symbol-value 'rfn-eshadow-overlay))))
2076 (while props
2077 (funcall (symbol-function 'overlay-put)
2078 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2080 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2081 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2082 'tramp-rfn-eshadow-setup-minibuffer))
2084 (defun tramp-rfn-eshadow-update-overlay ()
2085 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2086 This is intended to be used as a minibuffer `post-command-hook' for
2087 `file-name-shadow-mode'; the minibuffer should have already
2088 been set up by `rfn-eshadow-setup-minibuffer'."
2089 ;; In remote files name, there is a shadowing just for the local part.
2090 (let ((end (or (funcall (symbol-function 'overlay-end)
2091 (symbol-value 'rfn-eshadow-overlay))
2092 (funcall (symbol-function 'minibuffer-prompt-end)))))
2093 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
2094 (save-excursion
2095 (save-restriction
2096 (narrow-to-region
2097 (1+ (or (string-match "/" (buffer-string) end) end)) (point-max))
2098 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2099 (rfn-eshadow-update-overlay-hook nil))
2100 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
2102 (when (boundp 'rfn-eshadow-update-overlay-hook)
2103 (add-hook 'rfn-eshadow-update-overlay-hook
2104 'tramp-rfn-eshadow-update-overlay))
2107 ;;; File Name Handler Functions:
2109 (defun tramp-handle-make-symbolic-link
2110 (filename linkname &optional ok-if-already-exists)
2111 "Like `make-symbolic-link' for Tramp files.
2112 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2113 the symlink. If LINKNAME is a Tramp file, only the localname component is
2114 used as the target of the symlink.
2116 If LINKNAME is a Tramp file and the localname component is relative, then
2117 it is expanded first, before the localname component is taken. Note that
2118 this can give surprising results if the user/host for the source and
2119 target of the symlink differ."
2120 (with-parsed-tramp-file-name linkname l
2121 (let ((ln (tramp-get-remote-ln l))
2122 (cwd (file-name-directory l-localname)))
2123 (unless ln
2124 (tramp-error
2125 l 'file-error
2126 "Making a symbolic link. ln(1) does not exist on the remote host."))
2128 ;; Do the 'confirm if exists' thing.
2129 (when (file-exists-p linkname)
2130 ;; What to do?
2131 (if (or (null ok-if-already-exists) ; not allowed to exist
2132 (and (numberp ok-if-already-exists)
2133 (not (yes-or-no-p
2134 (format
2135 "File %s already exists; make it a link anyway? "
2136 l-localname)))))
2137 (tramp-error
2138 l 'file-already-exists "File %s already exists" l-localname)
2139 (delete-file linkname)))
2141 ;; If FILENAME is a Tramp name, use just the localname component.
2142 (when (tramp-tramp-file-p filename)
2143 (setq filename
2144 (tramp-file-name-localname
2145 (tramp-dissect-file-name (expand-file-name filename)))))
2147 ;; Right, they are on the same host, regardless of user, method, etc.
2148 ;; We now make the link on the remote machine. This will occur as the user
2149 ;; that FILENAME belongs to.
2150 (zerop
2151 (tramp-send-command-and-check
2152 l (format "cd %s && %s -sf %s %s" cwd ln filename l-localname) t)))))
2155 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2156 "Like `load' for Tramp files."
2157 (with-parsed-tramp-file-name (expand-file-name file) nil
2158 (unless nosuffix
2159 (cond ((file-exists-p (concat file ".elc"))
2160 (setq file (concat file ".elc")))
2161 ((file-exists-p (concat file ".el"))
2162 (setq file (concat file ".el")))))
2163 (when must-suffix
2164 ;; The first condition is always true for absolute file names.
2165 ;; Included for safety's sake.
2166 (unless (or (file-name-directory file)
2167 (string-match "\\.elc?\\'" file))
2168 (tramp-error
2169 v 'file-error
2170 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2171 (unless noerror
2172 (when (not (file-exists-p file))
2173 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2174 (if (not (file-exists-p file))
2176 (unless nomessage (tramp-message v 0 "Loading %s..." file))
2177 (let ((local-copy (file-local-copy file)))
2178 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2179 (load local-copy noerror t t)
2180 (delete-file local-copy))
2181 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
2182 t)))
2184 ;; Localname manipulation functions that grok Tramp localnames...
2185 (defun tramp-handle-file-name-directory (file)
2186 "Like `file-name-directory' but aware of Tramp files."
2187 ;; Everything except the last filename thing is the directory. We
2188 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2189 ;; the remote file name parts. This is a problem when we are in
2190 ;; file name completion.
2191 (let ((v (tramp-dissect-file-name file t)))
2192 ;; Run the command on the localname portion only.
2193 (tramp-make-tramp-file-name
2194 (tramp-file-name-method v)
2195 (tramp-file-name-user v)
2196 (tramp-file-name-host v)
2197 (file-name-directory (or (tramp-file-name-localname v) "")))))
2199 (defun tramp-handle-file-name-nondirectory (file)
2200 "Like `file-name-nondirectory' but aware of Tramp files."
2201 (with-parsed-tramp-file-name file nil
2202 (file-name-nondirectory localname)))
2204 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2205 "Like `file-truename' for Tramp files."
2206 (with-parsed-tramp-file-name (expand-file-name filename) nil
2207 (with-file-property v localname "file-truename"
2208 (let* ((directory-sep-char ?/) ; for XEmacs
2209 (steps (tramp-split-string localname "/"))
2210 (localnamedir (file-name-as-directory localname))
2211 (is-dir (string= localname localnamedir))
2212 (thisstep nil)
2213 (numchase 0)
2214 ;; Don't make the following value larger than necessary.
2215 ;; People expect an error message in a timely fashion when
2216 ;; something is wrong; otherwise they might think that Emacs
2217 ;; is hung. Of course, correctness has to come first.
2218 (numchase-limit 20)
2219 (result nil) ;result steps in reverse order
2220 symlink-target)
2221 (tramp-message v 4 "Finding true name for `%s'" filename)
2222 (while (and steps (< numchase numchase-limit))
2223 (setq thisstep (pop steps))
2224 (tramp-message
2225 v 5 "Check %s"
2226 (mapconcat 'identity
2227 (append '("") (reverse result) (list thisstep))
2228 "/"))
2229 (setq symlink-target
2230 (nth 0 (file-attributes
2231 (tramp-make-tramp-file-name
2232 method user host
2233 (mapconcat 'identity
2234 (append '("")
2235 (reverse result)
2236 (list thisstep))
2237 "/")))))
2238 (cond ((string= "." thisstep)
2239 (tramp-message v 5 "Ignoring step `.'"))
2240 ((string= ".." thisstep)
2241 (tramp-message v 5 "Processing step `..'")
2242 (pop result))
2243 ((stringp symlink-target)
2244 ;; It's a symlink, follow it.
2245 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2246 (setq numchase (1+ numchase))
2247 (when (file-name-absolute-p symlink-target)
2248 (setq result nil))
2249 ;; If the symlink was absolute, we'll get a string like
2250 ;; "/user@host:/some/target"; extract the
2251 ;; "/some/target" part from it.
2252 (when (tramp-tramp-file-p symlink-target)
2253 (unless (tramp-equal-remote filename symlink-target)
2254 (tramp-error
2255 v 'file-error
2256 "Symlink target `%s' on wrong host" symlink-target))
2257 (setq symlink-target localname))
2258 (setq steps
2259 (append (tramp-split-string symlink-target "/")
2260 steps)))
2262 ;; It's a file.
2263 (setq result (cons thisstep result)))))
2264 (when (>= numchase numchase-limit)
2265 (tramp-error
2266 v 'file-error
2267 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2268 (setq result (reverse result))
2269 ;; Combine list to form string.
2270 (setq result
2271 (if result
2272 (mapconcat 'identity (cons "" result) "/")
2273 "/"))
2274 (when (and is-dir (or (string= "" result)
2275 (not (string= (substring result -1) "/"))))
2276 (setq result (concat result "/")))
2277 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2278 (tramp-make-tramp-file-name method user host result)))))
2280 ;; Basic functions.
2282 (defun tramp-handle-file-exists-p (filename)
2283 "Like `file-exists-p' for Tramp files."
2284 (with-parsed-tramp-file-name filename nil
2285 (with-file-property v localname "file-exists-p"
2286 (zerop (tramp-send-command-and-check
2288 (format
2289 "%s %s"
2290 (tramp-get-file-exists-command v)
2291 (tramp-shell-quote-argument localname)))))))
2293 ;; Inodes don't exist for some file systems. Therefore we must
2294 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2295 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2296 ;; performance isn't the major issue given that file transfer will
2297 ;; take time.
2298 (defvar tramp-inodes nil
2299 "Keeps virtual inodes numbers.")
2301 ;; Devices must distinguish physical file systems. The device numbers
2302 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2303 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2304 ;; EFS use device number "-1". In order to be different, we use device number
2305 ;; (-1 x), whereby "x" is unique for a given (method user host).
2306 (defvar tramp-devices nil
2307 "Keeps virtual device numbers.")
2309 ;; CCC: This should check for an error condition and signal failure
2310 ;; when something goes wrong.
2311 ;; Daniel Pittman <daniel@danann.net>
2312 (defun tramp-handle-file-attributes (filename &optional id-format)
2313 "Like `file-attributes' for Tramp files."
2314 (unless id-format (setq id-format 'integer))
2315 (with-parsed-tramp-file-name (expand-file-name filename) nil
2316 (with-file-property v localname (format "file-attributes-%s" id-format)
2317 (when (file-exists-p filename)
2318 ;; file exists, find out stuff
2319 (save-excursion
2320 (tramp-convert-file-attributes
2322 (if (tramp-get-remote-stat v)
2323 (tramp-handle-file-attributes-with-stat v localname id-format)
2324 (if (tramp-get-remote-perl v)
2325 (tramp-handle-file-attributes-with-perl v localname id-format)
2326 (tramp-handle-file-attributes-with-ls
2327 v localname id-format)))))))))
2329 (defun tramp-handle-file-attributes-with-ls (vec localname &optional id-format)
2330 "Implement `file-attributes' for Tramp files using the ls(1) command."
2331 (let (symlinkp dirp
2332 res-inode res-filemodes res-numlinks
2333 res-uid res-gid res-size res-symlink-target)
2334 (tramp-message vec 5 "file attributes with ls: %s" localname)
2335 (tramp-send-command
2337 (format "%s %s %s"
2338 (tramp-get-ls-command vec)
2339 (if (eq id-format 'integer) "-ildn" "-ild")
2340 (tramp-shell-quote-argument localname)))
2341 ;; parse `ls -l' output ...
2342 (with-current-buffer (tramp-get-buffer vec)
2343 (goto-char (point-min))
2344 ;; ... inode
2345 (setq res-inode
2346 (condition-case err
2347 (read (current-buffer))
2348 (invalid-read-syntax
2349 (when (and (equal (cadr err)
2350 "Integer constant overflow in reader")
2351 (string-match
2352 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2353 (car (cddr err))))
2354 (let* ((big (read (substring (car (cddr err)) 0
2355 (match-beginning 1))))
2356 (small (read (match-string 1 (car (cddr err)))))
2357 (twiddle (/ small 65536)))
2358 (cons (+ big twiddle)
2359 (- small (* twiddle 65536))))))))
2360 ;; ... file mode flags
2361 (setq res-filemodes (symbol-name (read (current-buffer))))
2362 ;; ... number links
2363 (setq res-numlinks (read (current-buffer)))
2364 ;; ... uid and gid
2365 (setq res-uid (read (current-buffer)))
2366 (setq res-gid (read (current-buffer)))
2367 (if (eq id-format 'integer)
2368 (progn
2369 (unless (numberp res-uid) (setq res-uid -1))
2370 (unless (numberp res-gid) (setq res-gid -1)))
2371 (progn
2372 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2373 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2374 ;; ... size
2375 (setq res-size (read (current-buffer)))
2376 ;; From the file modes, figure out other stuff.
2377 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2378 (setq dirp (eq ?d (aref res-filemodes 0)))
2379 ;; if symlink, find out file name pointed to
2380 (when symlinkp
2381 (search-forward "-> ")
2382 (setq res-symlink-target
2383 (buffer-substring (point) (tramp-compat-line-end-position))))
2384 ;; return data gathered
2385 (list
2386 ;; 0. t for directory, string (name linked to) for symbolic
2387 ;; link, or nil.
2388 (or dirp res-symlink-target)
2389 ;; 1. Number of links to file.
2390 res-numlinks
2391 ;; 2. File uid.
2392 res-uid
2393 ;; 3. File gid.
2394 res-gid
2395 ;; 4. Last access time, as a list of two integers. First
2396 ;; integer has high-order 16 bits of time, second has low 16
2397 ;; bits.
2398 ;; 5. Last modification time, likewise.
2399 ;; 6. Last status change time, likewise.
2400 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2401 ;; 7. Size in bytes (-1, if number is out of range).
2402 res-size
2403 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2404 res-filemodes
2405 ;; 9. t if file's gid would change if file were deleted and
2406 ;; recreated. Will be set in `tramp-convert-file-attributes'
2408 ;; 10. inode number.
2409 res-inode
2410 ;; 11. Device number. Will be replaced by a virtual device number.
2412 ))))
2414 (defun tramp-handle-file-attributes-with-perl
2415 (vec localname &optional id-format)
2416 "Implement `file-attributes' for Tramp files using a Perl script."
2417 (tramp-message vec 5 "file attributes with perl: %s" localname)
2418 (tramp-maybe-send-script
2419 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2420 (tramp-send-command-and-read
2422 (format "tramp_perl_file_attributes %s %s"
2423 (tramp-shell-quote-argument localname) id-format)))
2425 (defun tramp-handle-file-attributes-with-stat
2426 (vec localname &optional id-format)
2427 "Implement `file-attributes' for Tramp files using stat(1) command."
2428 (tramp-message vec 5 "file attributes with stat: %s" localname)
2429 (tramp-send-command-and-read
2431 (format
2432 "%s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s"
2433 (tramp-get-remote-stat vec)
2434 (if (eq id-format 'integer) "%u" "\"%U\"")
2435 (if (eq id-format 'integer) "%g" "\"%G\"")
2436 (tramp-shell-quote-argument localname))))
2438 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2439 "Like `set-visited-file-modtime' for Tramp files."
2440 (unless (buffer-file-name)
2441 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2442 (buffer-name)))
2443 (if time-list
2444 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2445 (let ((f (buffer-file-name))
2446 coding-system-used)
2447 (with-parsed-tramp-file-name f nil
2448 (let* ((attr (file-attributes f))
2449 ;; '(-1 65535) means file doesn't exists yet.
2450 (modtime (or (nth 5 attr) '(-1 65535))))
2451 (when (boundp 'last-coding-system-used)
2452 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2453 ;; We use '(0 0) as a don't-know value. See also
2454 ;; `tramp-handle-file-attributes-with-ls'.
2455 (if (not (equal modtime '(0 0)))
2456 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2457 (progn
2458 (tramp-send-command
2460 (format "%s -ild %s"
2461 (tramp-get-ls-command v)
2462 (tramp-shell-quote-argument localname)))
2463 (setq attr (buffer-substring (point)
2464 (progn (end-of-line) (point)))))
2465 (tramp-set-file-property
2466 v localname "visited-file-modtime-ild" attr))
2467 (when (boundp 'last-coding-system-used)
2468 (set 'last-coding-system-used coding-system-used))
2469 nil)))))
2471 ;; CCC continue here
2473 ;; This function makes the same assumption as
2474 ;; `tramp-handle-set-visited-file-modtime'.
2475 (defun tramp-handle-verify-visited-file-modtime (buf)
2476 "Like `verify-visited-file-modtime' for Tramp files.
2477 At the time `verify-visited-file-modtime' calls this function, we
2478 already know that the buffer is visiting a file and that
2479 `visited-file-modtime' does not return 0. Do not call this
2480 function directly, unless those two cases are already taken care
2481 of."
2482 (with-current-buffer buf
2483 ;; There is no file visiting the buffer, or the buffer has no
2484 ;; recorded last modification time.
2485 (if (or (not (buffer-file-name))
2486 (eq (visited-file-modtime) 0))
2488 (let ((f (buffer-file-name)))
2489 (with-parsed-tramp-file-name f nil
2490 (tramp-flush-file-property v localname)
2491 (let* ((attr (file-attributes f))
2492 (modtime (nth 5 attr))
2493 (mt (visited-file-modtime)))
2495 (cond
2496 ;; file exists, and has a known modtime.
2497 ((and attr (not (equal modtime '(0 0))))
2498 (< (abs (tramp-time-diff
2499 modtime
2500 ;; For compatibility, deal with both the old
2501 ;; (HIGH . LOW) and the new (HIGH LOW)
2502 ;; return values of `visited-file-modtime'.
2503 (if (atom (cdr mt))
2504 (list (car mt) (cdr mt))
2505 mt)))
2507 ;; modtime has the don't know value.
2508 (attr
2509 (tramp-send-command
2511 (format "%s -ild %s"
2512 (tramp-get-ls-command v)
2513 (tramp-shell-quote-argument localname)))
2514 (with-current-buffer (tramp-get-buffer v)
2515 (setq attr (buffer-substring
2516 (point) (progn (end-of-line) (point)))))
2517 (equal
2518 attr
2519 (tramp-get-file-property
2520 v localname "visited-file-modtime-ild" "")))
2521 ;; If file does not exist, say it is not modified
2522 ;; if and only if that agrees with the buffer's record.
2523 (t (equal mt '(-1 65535))))))))))
2525 (defun tramp-handle-set-file-modes (filename mode)
2526 "Like `set-file-modes' for Tramp files."
2527 (with-parsed-tramp-file-name filename nil
2528 (tramp-flush-file-property v localname)
2529 (unless (zerop (tramp-send-command-and-check
2531 (format "chmod %s %s"
2532 (tramp-decimal-to-octal mode)
2533 (tramp-shell-quote-argument localname))))
2534 ;; FIXME: extract the proper text from chmod's stderr.
2535 (tramp-error
2536 v 'file-error "Error while changing file's mode %s" filename))))
2538 (defun tramp-handle-set-file-times (filename &optional time)
2539 "Like `set-file-times' for Tramp files."
2540 (zerop
2541 (if (file-remote-p filename)
2542 (with-parsed-tramp-file-name filename nil
2543 (tramp-flush-file-property v localname)
2544 (let ((time (if (or (null time) (equal time '(0 0)))
2545 (current-time)
2546 time))
2547 (utc
2548 ;; With GNU Emacs, `format-time-string' has an
2549 ;; optional parameter UNIVERSAL. This is preferred,
2550 ;; because we could handle the case when the remote
2551 ;; host is located in a different time zone as the
2552 ;; local host.
2553 (and (functionp 'subr-arity)
2554 (subrp (symbol-function 'format-time-string))
2555 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2556 (symbol-function
2557 'format-time-string)))))))
2558 (tramp-send-command-and-check
2559 v (format "%s touch -t %s %s"
2560 (if utc "TZ=UTC; export TZ;" "")
2561 (if utc
2562 (format-time-string "%Y%m%d%H%M.%S" time t)
2563 (format-time-string "%Y%m%d%H%M.%S" time))
2564 (tramp-shell-quote-argument localname)))))
2566 ;; We handle also the local part, because in older Emacsen,
2567 ;; without `set-file-times', this function is an alias for this.
2568 ;; We are local, so we don't need the UTC settings.
2569 (tramp-local-call-process
2570 "touch" nil nil nil "-t"
2571 (format-time-string "%Y%m%d%H%M.%S" time)
2572 (tramp-shell-quote-argument filename)))))
2574 (defun tramp-set-file-uid-gid (filename &optional uid gid)
2575 "Set the ownership for FILENAME.
2576 If UID and GID are provided, these values are used; otherwise uid
2577 and gid of the corresponding user is taken. Both parameters must be integers."
2578 ;; CCC: Modern Unices allow chown only for root. So we might need
2579 ;; another implementation, see `dired-do-chown'. OTOH, it is
2580 ;; mostly working with su(do)? when it is needed, so it shall
2581 ;; succeed in the majority of cases.
2582 (if (file-remote-p filename)
2583 (with-parsed-tramp-file-name filename nil
2584 (let ((uid (or (and (integerp uid) uid)
2585 (tramp-get-remote-uid v 'integer)))
2586 (gid (or (and (integerp gid) gid)
2587 (tramp-get-remote-gid v 'integer))))
2588 (tramp-send-command
2589 v (format
2590 "chown %d:%d %s" uid gid
2591 (tramp-shell-quote-argument localname)))))
2593 ;; We handle also the local part, because there doesn't exist
2594 ;; `set-file-uid-gid'. On Win32 "chown" might not work.
2595 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2596 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2597 (tramp-local-call-process
2598 "chown" nil nil nil
2599 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename)))))
2601 ;; Simple functions using the `test' command.
2603 (defun tramp-handle-file-executable-p (filename)
2604 "Like `file-executable-p' for Tramp files."
2605 (with-parsed-tramp-file-name filename nil
2606 (with-file-property v localname "file-executable-p"
2607 (zerop (tramp-run-test "-x" filename)))))
2609 (defun tramp-handle-file-readable-p (filename)
2610 "Like `file-readable-p' for Tramp files."
2611 (with-parsed-tramp-file-name filename nil
2612 (with-file-property v localname "file-readable-p"
2613 (zerop (tramp-run-test "-r" filename)))))
2615 ;; When the remote shell is started, it looks for a shell which groks
2616 ;; tilde expansion. Here, we assume that all shells which grok tilde
2617 ;; expansion will also provide a `test' command which groks `-nt' (for
2618 ;; newer than). If this breaks, tell me about it and I'll try to do
2619 ;; something smarter about it.
2620 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2621 "Like `file-newer-than-file-p' for Tramp files."
2622 (cond ((not (file-exists-p file1))
2623 nil)
2624 ((not (file-exists-p file2))
2626 ;; We are sure both files exist at this point.
2628 (save-excursion
2629 ;; We try to get the mtime of both files. If they are not
2630 ;; equal to the "dont-know" value, then we subtract the times
2631 ;; and obtain the result.
2632 (let ((fa1 (file-attributes file1))
2633 (fa2 (file-attributes file2)))
2634 (if (and (not (equal (nth 5 fa1) '(0 0)))
2635 (not (equal (nth 5 fa2) '(0 0))))
2636 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
2637 ;; If one of them is the dont-know value, then we can
2638 ;; still try to run a shell command on the remote host.
2639 ;; However, this only works if both files are Tramp
2640 ;; files and both have the same method, same user, same
2641 ;; host.
2642 (unless (tramp-equal-remote file1 file2)
2643 (with-parsed-tramp-file-name
2644 (if (tramp-tramp-file-p file1) file1 file2) nil
2645 (tramp-error
2646 v 'file-error
2647 "Files %s and %s must have same method, user, host"
2648 file1 file2)))
2649 (with-parsed-tramp-file-name file1 nil
2650 (zerop (tramp-run-test2
2651 (tramp-get-test-nt-command v) file1 file2)))))))))
2653 ;; Functions implemented using the basic functions above.
2655 (defun tramp-handle-file-modes (filename)
2656 "Like `file-modes' for Tramp files."
2657 (when (file-exists-p filename)
2658 (tramp-mode-string-to-int
2659 (nth 8 (file-attributes filename)))))
2661 (defun tramp-handle-file-directory-p (filename)
2662 "Like `file-directory-p' for Tramp files."
2663 ;; Care must be taken that this function returns `t' for symlinks
2664 ;; pointing to directories. Surely the most obvious implementation
2665 ;; would be `test -d', but that returns false for such symlinks.
2666 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
2667 ;; I now think he's right. So we could be using `test -d', couldn't
2668 ;; we?
2670 ;; Alternatives: `cd %s', `test -d %s'
2671 (with-parsed-tramp-file-name filename nil
2672 (with-file-property v localname "file-directory-p"
2673 (zerop (tramp-run-test "-d" filename)))))
2675 (defun tramp-handle-file-regular-p (filename)
2676 "Like `file-regular-p' for Tramp files."
2677 (and (file-exists-p filename)
2678 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
2680 (defun tramp-handle-file-symlink-p (filename)
2681 "Like `file-symlink-p' for Tramp files."
2682 (with-parsed-tramp-file-name filename nil
2683 (let ((x (car (file-attributes filename))))
2684 (when (stringp x)
2685 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2686 ;; might do weird things.
2687 (if (file-name-absolute-p x)
2688 (tramp-make-tramp-file-name method user host x)
2689 x)))))
2691 (defun tramp-handle-file-writable-p (filename)
2692 "Like `file-writable-p' for Tramp files."
2693 (with-parsed-tramp-file-name filename nil
2694 (with-file-property v localname "file-writable-p"
2695 (if (file-exists-p filename)
2696 ;; Existing files must be writable.
2697 (zerop (tramp-run-test "-w" filename))
2698 ;; If file doesn't exist, check if directory is writable.
2699 (and (zerop (tramp-run-test
2700 "-d" (file-name-directory filename)))
2701 (zerop (tramp-run-test
2702 "-w" (file-name-directory filename))))))))
2704 (defun tramp-handle-file-ownership-preserved-p (filename)
2705 "Like `file-ownership-preserved-p' for Tramp files."
2706 (with-parsed-tramp-file-name filename nil
2707 (with-file-property v localname "file-ownership-preserved-p"
2708 (let ((attributes (file-attributes filename)))
2709 ;; Return t if the file doesn't exist, since it's true that no
2710 ;; information would be lost by an (attempted) delete and create.
2711 (or (null attributes)
2712 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
2714 ;; Other file name ops.
2716 (defun tramp-handle-directory-file-name (directory)
2717 "Like `directory-file-name' for Tramp files."
2718 ;; If localname component of filename is "/", leave it unchanged.
2719 ;; Otherwise, remove any trailing slash from localname component.
2720 ;; Method, host, etc, are unchanged. Does it make sense to try
2721 ;; to avoid parsing the filename?
2722 (with-parsed-tramp-file-name directory nil
2723 (if (and (not (zerop (length localname)))
2724 (eq (aref localname (1- (length localname))) ?/)
2725 (not (string= localname "/")))
2726 (substring directory 0 -1)
2727 directory)))
2729 ;; Directory listings.
2731 (defun tramp-handle-directory-files
2732 (directory &optional full match nosort files-only)
2733 "Like `directory-files' for Tramp files."
2734 ;; FILES-ONLY is valid for XEmacs only.
2735 (when (file-directory-p directory)
2736 (setq directory (expand-file-name directory))
2737 (let ((temp (nreverse (file-name-all-completions "" directory)))
2738 result item)
2740 (while temp
2741 (setq item (directory-file-name (pop temp)))
2742 (when (and (or (null match) (string-match match item))
2743 (or (null files-only)
2744 ;; files only
2745 (and (equal files-only t) (file-regular-p item))
2746 ;; directories only
2747 (file-directory-p item)))
2748 (push (if full (expand-file-name item directory) item)
2749 result)))
2750 result)))
2752 (defun tramp-handle-directory-files-and-attributes
2753 (directory &optional full match nosort id-format)
2754 "Like `directory-files-and-attributes' for Tramp files."
2755 (unless id-format (setq id-format 'integer))
2756 (when (file-directory-p directory)
2757 (setq directory (expand-file-name directory))
2758 (let* ((temp
2759 (tramp-compat-copy-tree
2760 (with-parsed-tramp-file-name directory nil
2761 (with-file-property
2762 v localname
2763 (format "directory-files-and-attributes-%s" id-format)
2764 (save-excursion
2765 (mapcar
2766 '(lambda (x)
2767 (cons (car x)
2768 (tramp-convert-file-attributes v (cdr x))))
2769 (if (tramp-get-remote-stat v)
2770 (tramp-handle-directory-files-and-attributes-with-stat
2771 v localname id-format)
2772 (if (tramp-get-remote-perl v)
2773 (tramp-handle-directory-files-and-attributes-with-perl
2774 v localname id-format)))))))))
2775 result item)
2777 (while temp
2778 (setq item (pop temp))
2779 (when (or (null match) (string-match match (car item)))
2780 (when full
2781 (setcar item (expand-file-name (car item) directory)))
2782 (push item result)))
2784 (if nosort
2785 result
2786 (sort result (lambda (x y) (string< (car x) (car y))))))))
2788 (defun tramp-handle-directory-files-and-attributes-with-perl
2789 (vec localname &optional id-format)
2790 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
2791 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
2792 (tramp-maybe-send-script
2793 vec tramp-perl-directory-files-and-attributes
2794 "tramp_perl_directory_files_and_attributes")
2795 (let ((object
2796 (tramp-send-command-and-read
2798 (format "tramp_perl_directory_files_and_attributes %s %s"
2799 (tramp-shell-quote-argument localname) id-format))))
2800 (when (stringp object) (tramp-error vec 'file-error object))
2801 object))
2803 (defun tramp-handle-directory-files-and-attributes-with-stat
2804 (vec localname &optional id-format)
2805 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
2806 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
2807 (tramp-send-command-and-read
2809 (format
2810 (concat
2811 "cd %s; echo \"(\"; (%s -ab | xargs "
2812 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
2813 "echo \")\"")
2814 (tramp-shell-quote-argument localname)
2815 (tramp-get-ls-command vec)
2816 (tramp-get-remote-stat vec)
2817 (if (eq id-format 'integer) "%u" "\"%U\"")
2818 (if (eq id-format 'integer) "%g" "\"%G\""))))
2820 ;; This function should return "foo/" for directories and "bar" for
2821 ;; files.
2822 (defun tramp-handle-file-name-all-completions (filename directory)
2823 "Like `file-name-all-completions' for Tramp files."
2824 (unless (save-match-data (string-match "/" filename))
2825 (with-parsed-tramp-file-name (expand-file-name directory) nil
2826 ;; Flush the directory cache. There could be changed directory
2827 ;; contents.
2828 (when (and (integerp tramp-completion-reread-directory-timeout)
2829 (> (tramp-time-diff
2830 (current-time)
2831 (tramp-get-file-property
2832 v localname "last-completion" '(0 0 0)))
2833 tramp-completion-reread-directory-timeout))
2834 (tramp-flush-file-property v localname))
2836 (all-completions
2837 filename
2838 (mapcar
2839 'list
2840 (with-file-property v localname "file-name-all-completions"
2841 (let (result)
2842 (tramp-barf-unless-okay
2844 (format "cd %s" (tramp-shell-quote-argument localname))
2845 "tramp-handle-file-name-all-completions: Couldn't `cd %s'"
2846 (tramp-shell-quote-argument localname))
2848 ;; Get a list of directories and files, including reliably
2849 ;; tagging the directories with a trailing '/'. Because I
2850 ;; rock. --daniel@danann.net
2851 (tramp-send-command
2853 (format (concat "%s -ab 2>/dev/null | while read f; do "
2854 "if %s -d \"$f\" 2>/dev/null; "
2855 "then echo \"$f/\"; else echo \"$f\"; fi; done")
2856 (tramp-get-ls-command v)
2857 (tramp-get-test-command v)))
2859 ;; Now grab the output.
2860 (with-current-buffer (tramp-get-buffer v)
2861 (goto-char (point-max))
2862 (while (zerop (forward-line -1))
2863 (push (buffer-substring
2864 (point) (tramp-compat-line-end-position))
2865 result)))
2867 (tramp-set-file-property
2868 v localname "last-completion" (current-time))
2869 result)))))))
2871 ;; The following isn't needed for Emacs 20 but for 19.34?
2872 (defun tramp-handle-file-name-completion
2873 (filename directory &optional predicate)
2874 "Like `file-name-completion' for Tramp files."
2875 (unless (tramp-tramp-file-p directory)
2876 (error
2877 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2878 directory))
2879 (try-completion
2880 filename
2881 (mapcar 'list (file-name-all-completions filename directory))
2882 (when predicate
2883 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2885 ;; cp, mv and ln
2887 (defun tramp-handle-add-name-to-file
2888 (filename newname &optional ok-if-already-exists)
2889 "Like `add-name-to-file' for Tramp files."
2890 (unless (tramp-equal-remote filename newname)
2891 (with-parsed-tramp-file-name
2892 (if (tramp-tramp-file-p filename) filename newname) nil
2893 (tramp-error
2894 v 'file-error
2895 "add-name-to-file: %s"
2896 "only implemented for same method, same user, same host")))
2897 (with-parsed-tramp-file-name filename v1
2898 (with-parsed-tramp-file-name newname v2
2899 (let ((ln (when v1 (tramp-get-remote-ln v1))))
2900 (when (and (not ok-if-already-exists)
2901 (file-exists-p newname)
2902 (not (numberp ok-if-already-exists))
2903 (y-or-n-p
2904 (format
2905 "File %s already exists; make it a new name anyway? "
2906 newname)))
2907 (tramp-error
2908 v2 'file-error
2909 "add-name-to-file: file %s already exists" newname))
2910 (tramp-flush-file-property v2 v2-localname)
2911 (tramp-barf-unless-okay
2913 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
2914 (tramp-shell-quote-argument v2-localname))
2915 "error with add-name-to-file, see buffer `%s' for details"
2916 (buffer-name))))))
2918 (defun tramp-handle-copy-file
2919 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
2920 "Like `copy-file' for Tramp files."
2921 ;; Check if both files are local -- invoke normal copy-file.
2922 ;; Otherwise, use Tramp from local system.
2923 (setq filename (expand-file-name filename))
2924 (setq newname (expand-file-name newname))
2925 (cond
2926 ;; At least one file a Tramp file?
2927 ((or (tramp-tramp-file-p filename)
2928 (tramp-tramp-file-p newname))
2929 (tramp-do-copy-or-rename-file
2930 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
2931 ;; Compat section.
2932 (preserve-uid-gid
2933 (tramp-run-real-handler
2934 'copy-file
2935 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
2937 (tramp-run-real-handler
2938 'copy-file (list filename newname ok-if-already-exists keep-date)))))
2940 (defun tramp-handle-rename-file
2941 (filename newname &optional ok-if-already-exists)
2942 "Like `rename-file' for Tramp files."
2943 ;; Check if both files are local -- invoke normal rename-file.
2944 ;; Otherwise, use Tramp from local system.
2945 (setq filename (expand-file-name filename))
2946 (setq newname (expand-file-name newname))
2947 ;; At least one file a Tramp file?
2948 (if (or (tramp-tramp-file-p filename)
2949 (tramp-tramp-file-p newname))
2950 (tramp-do-copy-or-rename-file
2951 'rename filename newname ok-if-already-exists t t)
2952 (tramp-run-real-handler
2953 'rename-file (list filename newname ok-if-already-exists))))
2955 (defun tramp-do-copy-or-rename-file
2956 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
2957 "Copy or rename a remote file.
2958 OP must be `copy' or `rename' and indicates the operation to perform.
2959 FILENAME specifies the file to copy or rename, NEWNAME is the name of
2960 the new file (for copy) or the new name of the file (for rename).
2961 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
2962 KEEP-DATE means to make sure that NEWNAME has the same timestamp
2963 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
2964 the uid and gid if both files are on the same host.
2966 This function is invoked by `tramp-handle-copy-file' and
2967 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
2968 and `rename'. FILENAME and NEWNAME must be absolute file names."
2969 (unless (memq op '(copy rename))
2970 (error "Unknown operation `%s', must be `copy' or `rename'" op))
2971 (let ((t1 (tramp-tramp-file-p filename))
2972 (t2 (tramp-tramp-file-p newname)))
2974 (when (and (not ok-if-already-exists) (file-exists-p newname))
2975 (with-parsed-tramp-file-name (if t1 filename newname) nil
2976 (tramp-error
2977 v 'file-already-exists "File %s already exists" newname)))
2979 (prog1
2980 (cond
2981 ;; Both are Tramp files.
2982 ((and t1 t2)
2983 (with-parsed-tramp-file-name filename v1
2984 (with-parsed-tramp-file-name newname v2
2985 (cond
2986 ;; Shortcut: if method, host, user are the same for both
2987 ;; files, we invoke `cp' or `mv' on the remote host
2988 ;; directly.
2989 ((tramp-equal-remote filename newname)
2990 (tramp-do-copy-or-rename-file-directly
2991 op filename newname
2992 ok-if-already-exists keep-date preserve-uid-gid))
2994 ;; If both source and target are Tramp files,
2995 ;; both are using the same copy-program, then we
2996 ;; can invoke rcp directly. Note that
2997 ;; default-directory should point to a local
2998 ;; directory if we want to invoke rcp.
2999 ((and (equal v1-method v2-method)
3000 (tramp-method-out-of-band-p v1)
3001 (> (nth 7 (file-attributes filename))
3002 tramp-copy-size-limit))
3003 (tramp-do-copy-or-rename-file-out-of-band
3004 op filename newname keep-date))
3006 ;; No shortcut was possible. So we copy the
3007 ;; file first. If the operation was `rename', we go
3008 ;; back and delete the original file (if the copy was
3009 ;; successful). The approach is simple-minded: we
3010 ;; create a new buffer, insert the contents of the
3011 ;; source file into it, then write out the buffer to
3012 ;; the target file. The advantage is that it doesn't
3013 ;; matter which filename handlers are used for the
3014 ;; source and target file.
3016 (tramp-do-copy-or-rename-file-via-buffer
3017 op filename newname keep-date))))))
3019 ;; One file is a Tramp file, the other one is local.
3020 ((or t1 t2)
3021 (with-parsed-tramp-file-name (if t1 filename newname) nil
3022 (cond
3023 ;; Fast track on local machine.
3024 ((tramp-local-host-p v)
3025 (tramp-do-copy-or-rename-file-directly
3026 op filename newname
3027 ok-if-already-exists keep-date preserve-uid-gid))
3029 ;; If the Tramp file has an out-of-band method, the corresponding
3030 ;; copy-program can be invoked.
3031 ((and (tramp-method-out-of-band-p v)
3032 (> (nth 7 (file-attributes filename))
3033 tramp-copy-size-limit))
3034 (tramp-do-copy-or-rename-file-out-of-band
3035 op filename newname keep-date))
3037 ;; Use the inline method via a Tramp buffer.
3038 (t (tramp-do-copy-or-rename-file-via-buffer
3039 op filename newname keep-date)))))
3042 ;; One of them must be a Tramp file.
3043 (error "Tramp implementation says this cannot happen")))
3045 ;; In case of `rename', we must flush the cache of the source file.
3046 (when (and t1 (eq op 'rename))
3047 (with-parsed-tramp-file-name filename nil
3048 (tramp-flush-file-property v localname)))
3050 ;; When newname did exist, we have wrong cached values.
3051 (when t2
3052 (with-parsed-tramp-file-name newname nil
3053 (tramp-flush-file-property v localname))))))
3055 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3056 "Use an Emacs buffer to copy or rename a file.
3057 First arg OP is either `copy' or `rename' and indicates the operation.
3058 FILENAME is the source file, NEWNAME the target file.
3059 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3060 (with-temp-buffer
3061 ;; We must disable multibyte, because binary data shall not be
3062 ;; converted.
3063 (set-buffer-multibyte nil)
3064 (let ((coding-system-for-read 'binary)
3065 (jka-compr-inhibit t))
3066 (insert-file-contents-literally filename))
3067 ;; We don't want the target file to be compressed, so we let-bind
3068 ;; `jka-compr-inhibit' to t.
3069 (let ((coding-system-for-write 'binary)
3070 (jka-compr-inhibit t))
3071 (write-region (point-min) (point-max) newname)))
3072 ;; KEEP-DATE handling.
3073 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3074 ;; Set the mode.
3075 (set-file-modes newname (file-modes filename))
3076 ;; If the operation was `rename', delete the original file.
3077 (unless (eq op 'copy) (delete-file filename)))
3079 (defun tramp-do-copy-or-rename-file-directly
3080 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3081 "Invokes `cp' or `mv' on the remote system.
3082 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3083 respectively. FILENAME specifies the file to copy or rename,
3084 NEWNAME is the name of the new file (for copy) or the new name of
3085 the file (for rename). Both files must reside on the same host.
3086 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3087 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3088 the uid and gid from FILENAME."
3089 (let ((t1 (tramp-tramp-file-p filename))
3090 (t2 (tramp-tramp-file-p newname)))
3091 (with-parsed-tramp-file-name (if t1 filename newname) nil
3092 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3093 ((eq op 'copy) "cp -f")
3094 ((eq op 'rename) "mv -f")
3095 (t (tramp-error
3096 v 'file-error
3097 "Unknown operation `%s', must be `copy' or `rename'"
3098 op))))
3099 (localname1
3100 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3101 (localname2
3102 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
3103 (prefix (file-remote-p (if t1 filename newname))))
3105 (cond
3106 ;; Both files are on a remote host, with same user.
3107 ((and t1 t2)
3108 (tramp-send-command
3110 (format "%s %s %s" cmd
3111 (tramp-shell-quote-argument localname1)
3112 (tramp-shell-quote-argument localname2)))
3113 (with-current-buffer (tramp-get-buffer v)
3114 (goto-char (point-min))
3115 (unless
3117 (and keep-date
3118 ;; Mask cp -f error.
3119 (re-search-forward
3120 tramp-operation-not-permitted-regexp nil t))
3121 (zerop (tramp-send-command-and-check v nil)))
3122 (tramp-error-with-buffer
3123 nil v 'file-error
3124 "Copying directly failed, see buffer `%s' for details."
3125 (buffer-name)))))
3127 ;; We are on the local host.
3128 ((or t1 t2)
3129 (cond
3130 ;; We can do it directly.
3131 ((and (file-readable-p localname1)
3132 (file-writable-p (file-name-directory localname2))
3133 (or (file-directory-p localname2)
3134 (file-writable-p localname2)))
3135 (if (eq op 'copy)
3136 (tramp-compat-copy-file
3137 localname1 localname2 ok-if-already-exists
3138 keep-date preserve-uid-gid)
3139 (rename-file localname1 localname2 ok-if-already-exists)))
3141 ;; We can do it directly with `tramp-send-command'
3142 ((and (file-readable-p (concat prefix localname1))
3143 (file-writable-p
3144 (file-name-directory (concat prefix localname2))))
3145 (tramp-do-copy-or-rename-file-directly
3146 op (concat prefix localname1) (concat prefix localname2)
3147 ok-if-already-exists keep-date t)
3148 ;; We must change the ownership to the local user.
3149 (tramp-set-file-uid-gid
3150 (concat prefix localname2)
3151 (tramp-get-local-uid 'integer)
3152 (tramp-get-local-gid 'integer)))
3154 ;; We need a temporary file in between.
3156 ;; Create the temporary file.
3157 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3158 (cond
3160 (tramp-send-command
3161 v (format
3162 "%s %s %s" cmd
3163 (tramp-shell-quote-argument localname1)
3164 (tramp-shell-quote-argument tmpfile)))
3165 ;; We must change the ownership as remote user.
3166 (tramp-set-file-uid-gid
3167 (concat prefix tmpfile)
3168 (tramp-get-local-uid 'integer)
3169 (tramp-get-local-gid 'integer)))
3171 (if (eq op 'copy)
3172 (tramp-compat-copy-file
3173 localname1 tmpfile ok-if-already-exists
3174 keep-date preserve-uid-gid)
3175 (rename-file localname1 tmpfile ok-if-already-exists))
3176 ;; We must change the ownership as local user.
3177 (tramp-set-file-uid-gid
3178 tmpfile
3179 (tramp-get-remote-uid v 'integer)
3180 (tramp-get-remote-gid v 'integer))))
3182 ;; Move the temporary file to its destination.
3183 (cond
3185 (tramp-send-command
3186 v (format
3187 "mv -f %s %s"
3188 (tramp-shell-quote-argument tmpfile)
3189 (tramp-shell-quote-argument localname2))))
3191 (rename-file tmpfile localname2 ok-if-already-exists)))))))))
3193 ;; Set the time and mode. Mask possible errors.
3194 ;; Won't be applied for 'rename.
3195 (condition-case nil
3196 (when (and keep-date (not preserve-uid-gid))
3197 (set-file-times newname (nth 5 (file-attributes filename)))
3198 (set-file-modes newname (file-modes filename)))
3199 (error)))))
3202 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3203 "Invoke rcp program to copy.
3204 One of FILENAME and NEWNAME must be a Tramp name, the other must
3205 be a local filename. The method used must be an out-of-band method."
3206 (let ((t1 (tramp-tramp-file-p filename))
3207 (t2 (tramp-tramp-file-p newname))
3208 copy-program copy-args copy-keep-date port spec
3209 source target)
3211 (with-parsed-tramp-file-name (if t1 filename newname) nil
3213 ;; Expand hops. Might be necessary for gateway methods.
3214 (setq v (car (tramp-compute-multi-hops v)))
3215 (aset v 3 localname)
3217 ;; Check which ones of source and target are Tramp files.
3218 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3219 target (if t2 (tramp-make-copy-program-file-name v) newname))
3221 ;; Check for port number. Until now, there's no need for handling
3222 ;; like method, user, host.
3223 (setq host (tramp-file-name-real-host v)
3224 port (tramp-file-name-port v)
3225 port (or (and port (number-to-string port)) ""))
3227 ;; Compose copy command.
3228 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3229 (?t . ,(tramp-get-connection-property
3230 (tramp-get-connection-process v) "temp-file" ""))
3231 (?k . ,(if keep-date " " "")))
3232 copy-program (tramp-get-method-parameter
3233 method 'tramp-copy-program)
3234 copy-keep-date (tramp-get-method-parameter
3235 method 'tramp-copy-keep-date)
3236 copy-args
3237 (delq
3239 (mapcar
3240 '(lambda (x)
3241 (setq
3242 ;; " " is indication for keep-date argument.
3243 x (delete " " (mapcar '(lambda (y) (format-spec y spec)) x)))
3244 (unless (member "" x) (mapconcat 'identity x " ")))
3245 (tramp-get-method-parameter method 'tramp-copy-args))))
3247 ;; Check for program.
3248 (when (and (fboundp 'executable-find)
3249 (not (let ((default-directory
3250 (tramp-compat-temporary-file-directory)))
3251 (executable-find copy-program))))
3252 (tramp-error
3253 v 'file-error "Cannot find copy program: %s" copy-program))
3255 (tramp-message v 0 "Transferring %s to %s..." filename newname)
3257 (unwind-protect
3258 (with-temp-buffer
3259 ;; The default directory must be remote.
3260 (let ((default-directory
3261 (file-name-directory (if t1 filename newname))))
3262 ;; Set the transfer process properties.
3263 (tramp-set-connection-property
3264 v "process-name" (buffer-name (current-buffer)))
3265 (tramp-set-connection-property
3266 v "process-buffer" (current-buffer))
3268 ;; Use an asynchronous process. By this, password can
3269 ;; be handled. The default directory must be local, in
3270 ;; order to apply the correct `copy-program'. We don't
3271 ;; set a timeout, because the copying of large files can
3272 ;; last longer than 60 secs.
3273 (let ((p (let ((default-directory
3274 (tramp-compat-temporary-file-directory)))
3275 (apply 'start-process
3276 (tramp-get-connection-property
3277 v "process-name" nil)
3278 (tramp-get-connection-property
3279 v "process-buffer" nil)
3280 copy-program
3281 (append copy-args (list source target))))))
3282 (tramp-message
3283 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3284 (set-process-sentinel p 'tramp-process-sentinel)
3285 (tramp-set-process-query-on-exit-flag p nil)
3286 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
3288 ;; Reset the transfer process properties.
3289 (tramp-set-connection-property v "process-name" nil)
3290 (tramp-set-connection-property v "process-buffer" nil))
3292 (tramp-message v 0 "Transferring %s to %s...done" filename newname)
3294 ;; Handle KEEP-DATE argument.
3295 (when (and keep-date (not copy-keep-date))
3296 (set-file-times newname (nth 5 (file-attributes filename))))
3298 ;; Set the mode.
3299 (unless (and keep-date copy-keep-date)
3300 (set-file-modes newname (file-modes filename))))
3302 ;; If the operation was `rename', delete the original file.
3303 (unless (eq op 'copy)
3304 (delete-file filename))))
3306 (defun tramp-handle-make-directory (dir &optional parents)
3307 "Like `make-directory' for Tramp files."
3308 (setq dir (expand-file-name dir))
3309 (with-parsed-tramp-file-name dir nil
3310 (save-excursion
3311 (tramp-barf-unless-okay
3313 (format "%s %s"
3314 (if parents "mkdir -p" "mkdir")
3315 (tramp-shell-quote-argument localname))
3316 "Couldn't make directory %s" dir))))
3318 (defun tramp-handle-delete-directory (directory)
3319 "Like `delete-directory' for Tramp files."
3320 (setq directory (expand-file-name directory))
3321 (with-parsed-tramp-file-name directory nil
3322 (tramp-flush-directory-property v localname)
3323 (unless (zerop (tramp-send-command-and-check
3325 (format "rmdir %s" (tramp-shell-quote-argument localname))))
3326 (tramp-error v 'file-error "Couldn't delete %s" directory))))
3328 (defun tramp-handle-delete-file (filename)
3329 "Like `delete-file' for Tramp files."
3330 (setq filename (expand-file-name filename))
3331 (with-parsed-tramp-file-name filename nil
3332 (tramp-flush-file-property v localname)
3333 (unless (zerop (tramp-send-command-and-check
3335 (format "rm -f %s"
3336 (tramp-shell-quote-argument localname))))
3337 (tramp-error v 'file-error "Couldn't delete %s" filename))))
3339 ;; Dired.
3341 ;; CCC: This does not seem to be enough. Something dies when
3342 ;; we try and delete two directories under Tramp :/
3343 (defun tramp-handle-dired-recursive-delete-directory (filename)
3344 "Recursively delete the directory given.
3345 This is like `dired-recursive-delete-directory' for Tramp files."
3346 (with-parsed-tramp-file-name filename nil
3347 (tramp-flush-directory-property v filename)
3348 ;; Run a shell command 'rm -r <localname>'
3349 ;; Code shamelessly stolen for the dired implementation and, um, hacked :)
3350 (unless (file-exists-p filename)
3351 (tramp-error v 'file-error "No such directory: %s" filename))
3352 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
3353 (tramp-send-command
3355 (format "rm -rf %s" (tramp-shell-quote-argument localname))
3356 ;; Don't read the output, do it explicitely.
3357 nil t)
3358 ;; Wait for the remote system to return to us...
3359 ;; This might take a while, allow it plenty of time.
3360 (tramp-wait-for-output (tramp-get-connection-process v) 120)
3361 ;; Make sure that it worked...
3362 (and (file-exists-p filename)
3363 (tramp-error
3364 v 'file-error "Failed to recursively delete %s" filename))))
3366 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
3367 "Like `dired-compress-file' for Tramp files."
3368 ;; OK-FLAG is valid for XEmacs only, but not implemented.
3369 ;; Code stolen mainly from dired-aux.el.
3370 (with-parsed-tramp-file-name file nil
3371 (tramp-flush-file-property v localname)
3372 (save-excursion
3373 (let ((suffixes
3374 (if (not (featurep 'xemacs))
3375 ;; Emacs case
3376 (symbol-value 'dired-compress-file-suffixes)
3377 ;; XEmacs has `dired-compression-method-alist', which is
3378 ;; transformed into `dired-compress-file-suffixes' structure.
3379 (mapcar
3380 '(lambda (x)
3381 (list (concat (regexp-quote (nth 1 x)) "\\'")
3383 (mapconcat 'identity (nth 3 x) " ")))
3384 (symbol-value 'dired-compression-method-alist))))
3385 suffix)
3386 ;; See if any suffix rule matches this file name.
3387 (while suffixes
3388 (let (case-fold-search)
3389 (if (string-match (car (car suffixes)) localname)
3390 (setq suffix (car suffixes) suffixes nil))
3391 (setq suffixes (cdr suffixes))))
3393 (cond ((file-symlink-p file)
3394 nil)
3395 ((and suffix (nth 2 suffix))
3396 ;; We found an uncompression rule.
3397 (tramp-message v 0 "Uncompressing %s..." file)
3398 (when (zerop (tramp-send-command-and-check
3399 v (concat (nth 2 suffix) " " localname)))
3400 (tramp-message v 0 "Uncompressing %s...done" file)
3401 ;; `dired-remove-file' is not defined in XEmacs
3402 (funcall (symbol-function 'dired-remove-file) file)
3403 (string-match (car suffix) file)
3404 (concat (substring file 0 (match-beginning 0)))))
3406 ;; We don't recognize the file as compressed, so compress it.
3407 ;; Try gzip.
3408 (tramp-message v 0 "Compressing %s..." file)
3409 (when (zerop (tramp-send-command-and-check
3410 v (concat "gzip -f " localname)))
3411 (tramp-message v 0 "Compressing %s...done" file)
3412 ;; `dired-remove-file' is not defined in XEmacs
3413 (funcall (symbol-function 'dired-remove-file) file)
3414 (cond ((file-exists-p (concat file ".gz"))
3415 (concat file ".gz"))
3416 ((file-exists-p (concat file ".z"))
3417 (concat file ".z"))
3418 (t nil)))))))))
3420 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
3421 ;; not sure at all that this is the right way to do it, but let's hope
3422 ;; it works for now, and wait for a guru to point out the Right Way to
3423 ;; achieve this.
3424 ;;(eval-when-compile
3425 ;; (unless (fboundp 'dired-insert-set-properties)
3426 ;; (fset 'dired-insert-set-properties 'ignore)))
3427 ;; Gerd suggests this:
3428 (eval-when-compile (require 'dired))
3429 ;; Note that dired is required at run-time, too, when it is needed.
3430 ;; It is only needed on XEmacs for the function
3431 ;; `dired-insert-set-properties'.
3433 (defun tramp-handle-insert-directory
3434 (filename switches &optional wildcard full-directory-p)
3435 "Like `insert-directory' for Tramp files."
3436 (setq filename (expand-file-name filename))
3437 (with-parsed-tramp-file-name filename nil
3438 (tramp-flush-file-property v localname)
3439 (if (and (featurep 'ls-lisp)
3440 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
3441 (tramp-run-real-handler
3442 'insert-directory (list filename switches wildcard full-directory-p))
3443 ;; For the moment, we assume that the remote "ls" program does not
3444 ;; grok "--dired". In the future, we should detect this on
3445 ;; connection setup.
3446 (when (string-match "^--dired\\s-+" switches)
3447 (setq switches (replace-match "" nil t switches)))
3448 (tramp-message
3449 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
3450 switches filename (if wildcard "yes" "no")
3451 (if full-directory-p "yes" "no"))
3452 (when wildcard
3453 (setq wildcard (file-name-nondirectory localname))
3454 (setq localname (file-name-directory localname)))
3455 (when (listp switches)
3456 (setq switches (mapconcat 'identity switches " ")))
3457 (unless full-directory-p
3458 (setq switches (concat "-d " switches)))
3459 (when wildcard
3460 (setq switches (concat switches " " wildcard)))
3461 ;; If `full-directory-p', we just say `ls -l FILENAME'.
3462 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
3463 (if full-directory-p
3464 (tramp-send-command
3466 (format "%s %s %s"
3467 (tramp-get-ls-command v)
3468 switches
3469 (if wildcard
3470 localname
3471 (tramp-shell-quote-argument (concat localname ".")))))
3472 (tramp-barf-unless-okay
3474 (format "cd %s" (tramp-shell-quote-argument
3475 (file-name-directory localname)))
3476 "Couldn't `cd %s'"
3477 (tramp-shell-quote-argument (file-name-directory localname)))
3478 (tramp-send-command
3480 (format "%s %s %s"
3481 (tramp-get-ls-command v)
3482 switches
3483 (if (or wildcard
3484 (zerop (length (file-name-nondirectory localname))))
3486 (tramp-shell-quote-argument
3487 (file-name-nondirectory localname))))))
3488 ;; We cannot use `insert-buffer-substring' because the Tramp buffer
3489 ;; changes its contents before insertion due to calling
3490 ;; `expand-file' and alike.
3491 (insert
3492 (with-current-buffer (tramp-get-buffer v)
3493 (buffer-string))))))
3495 (defun tramp-handle-unhandled-file-name-directory (filename)
3496 "Like `unhandled-file-name-directory' for Tramp files."
3497 ;; With Emacs 23, we could simply return `nil'. But we must keep it
3498 ;; for backward compatibility.
3499 (expand-file-name "~/"))
3501 ;; Canonicalization of file names.
3503 (defun tramp-handle-expand-file-name (name &optional dir)
3504 "Like `expand-file-name' for Tramp files.
3505 If the localname part of the given filename starts with \"/../\" then
3506 the result will be a local, non-Tramp, filename."
3507 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
3508 (setq dir (or dir default-directory "/"))
3509 ;; Unless NAME is absolute, concat DIR and NAME.
3510 (unless (file-name-absolute-p name)
3511 (setq name (concat (file-name-as-directory dir) name)))
3512 ;; If NAME is not a Tramp file, run the real handler.
3513 (if (not (tramp-tramp-file-p name))
3514 (tramp-run-real-handler 'expand-file-name (list name nil))
3515 ;; Dissect NAME.
3516 (with-parsed-tramp-file-name name nil
3517 (unless (file-name-absolute-p localname)
3518 (setq localname (concat "~/" localname)))
3519 ;; Tilde expansion if necessary. This needs a shell which
3520 ;; groks tilde expansion! The function `tramp-find-shell' is
3521 ;; supposed to find such a shell on the remote host. Please
3522 ;; tell me about it when this doesn't work on your system.
3523 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
3524 (let ((uname (match-string 1 localname))
3525 (fname (match-string 2 localname)))
3526 ;; We cannot simply apply "~/", because under sudo "~/" is
3527 ;; expanded to the local user home directory but to the
3528 ;; root home directory. On the other hand, using always
3529 ;; the default user name for tilde expansion is not
3530 ;; appropriate either, because ssh and companions might
3531 ;; use a user name from the config file.
3532 (when (and (string-equal uname "~")
3533 (string-match "\\`su\\(do\\)?\\'" method))
3534 (setq uname (concat uname user)))
3535 (setq uname
3536 (with-connection-property v uname
3537 (tramp-send-command v (format "cd %s; pwd" uname))
3538 (with-current-buffer (tramp-get-buffer v)
3539 (goto-char (point-min))
3540 (buffer-substring (point) (tramp-compat-line-end-position)))))
3541 (setq localname (concat uname fname))))
3542 ;; There might be a double slash, for example when "~/"
3543 ;; expands to "/". Remove this.
3544 (while (string-match "//" localname)
3545 (setq localname (replace-match "/" t t localname)))
3546 ;; No tilde characters in file name, do normal
3547 ;; expand-file-name (this does "/./" and "/../"). We bind
3548 ;; `directory-sep-char' here for XEmacs on Windows, which
3549 ;; would otherwise use backslash. `default-directory' is
3550 ;; bound, because on Windows there would be problems with UNC
3551 ;; shares or Cygwin mounts.
3552 (let ((directory-sep-char ?/)
3553 (default-directory (tramp-compat-temporary-file-directory)))
3554 (tramp-make-tramp-file-name
3555 method user host
3556 (tramp-drop-volume-letter
3557 (tramp-run-real-handler 'expand-file-name
3558 (list localname))))))))
3560 (defun tramp-handle-substitute-in-file-name (filename)
3561 "Like `substitute-in-file-name' for Tramp files.
3562 \"//\" and \"/~\" substitute only in the local filename part.
3563 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
3564 beginning of local filename are not substituted."
3565 (with-parsed-tramp-file-name filename nil
3566 (if (equal tramp-syntax 'url)
3567 ;; We need to check localname only. The other parts cannot contain
3568 ;; "//" or "/~".
3569 (if (and (> (length localname) 1)
3570 (or (string-match "//" localname)
3571 (string-match "/~" localname 1)))
3572 (tramp-run-real-handler 'substitute-in-file-name (list filename))
3573 (tramp-make-tramp-file-name
3574 (when method (substitute-in-file-name method))
3575 (when user (substitute-in-file-name user))
3576 (when host (substitute-in-file-name host))
3577 (when localname (substitute-in-file-name localname))))
3578 ;; Ignore in LOCALNAME everything before "//" or "/~".
3579 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3580 (setq filename
3581 (concat (file-remote-p filename)
3582 (replace-match "\\1" nil nil localname)))
3583 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3584 (when (string-match "~$" filename)
3585 (setq filename (concat filename "/"))))
3586 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
3588 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
3589 ;; which calls corresponding functions (see minibuf.el).
3590 (when (fboundp 'minibuffer-electric-separator)
3591 (mapc
3592 '(lambda (x)
3593 (eval
3594 `(defadvice ,x
3595 (around ,(intern (format "tramp-advice-%s" x)) activate)
3596 "Invoke `substitute-in-file-name' for Tramp files."
3597 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
3598 (tramp-tramp-file-p (buffer-substring)))
3599 ;; We don't need to handle `last-input-event', because
3600 ;; due to the key map we know it must be ?/ or ?~.
3601 (let ((s (concat (buffer-substring (point-min) (point))
3602 (string last-command-char))))
3603 (delete-region (point-min) (point))
3604 (insert (substitute-in-file-name s))
3605 (setq ad-return-value last-command-char))
3606 ad-do-it))))
3608 '(minibuffer-electric-separator
3609 minibuffer-electric-tilde)))
3612 ;;; Remote commands:
3614 (defun tramp-handle-executable-find (command)
3615 "Like `executable-find' for Tramp files."
3616 (with-parsed-tramp-file-name default-directory nil
3617 (tramp-find-executable v command (tramp-get-remote-path v) t)))
3619 ;; We use BUFFER also as connection buffer during setup. Because of
3620 ;; this, its original contents must be saved, and restored once
3621 ;; connection has been setup.
3622 (defun tramp-handle-start-file-process (name buffer program &rest args)
3623 "Like `start-file-process' for Tramp files."
3624 (with-parsed-tramp-file-name default-directory nil
3625 (unwind-protect
3626 (progn
3627 ;; Set the new process properties.
3628 (tramp-set-connection-property v "process-name" name)
3629 (tramp-set-connection-property
3630 v "process-buffer"
3631 ;; BUFFER can be nil.
3632 (get-buffer-create (or buffer (current-buffer))))
3633 ;; Activate narrowing in order to save BUFFER contents.
3634 (with-current-buffer (tramp-get-connection-buffer v)
3635 (narrow-to-region (point-max) (point-max)))
3636 ;; Goto working directory. `tramp-send-command' opens a new
3637 ;; connection.
3638 (tramp-send-command
3639 v (format "cd %s" (tramp-shell-quote-argument localname)))
3640 ;; Send the command.
3641 (tramp-send-command
3643 (format "%s; echo %s; exit"
3644 (mapconcat 'tramp-shell-quote-argument
3645 (cons program args) " ")
3646 (tramp-shell-quote-argument tramp-end-of-output))
3647 nil t) ; nooutput
3648 ;; Return process.
3649 (tramp-get-connection-process v))
3650 ;; Save exit.
3651 (with-current-buffer (tramp-get-connection-buffer v)
3652 (widen)
3653 (goto-char (point-max)))
3654 (tramp-set-connection-property v "process-name" nil)
3655 (tramp-set-connection-property v "process-buffer" nil))))
3657 (defun tramp-handle-process-file
3658 (program &optional infile destination display &rest args)
3659 "Like `process-file' for Tramp files."
3660 ;; The implementation is not complete yet.
3661 (when (and (numberp destination) (zerop destination))
3662 (error "Implementation does not handle immediate return"))
3664 (with-parsed-tramp-file-name default-directory nil
3665 (let (command input tmpinput stderr tmpstderr outbuf ret)
3666 ;; Compute command.
3667 (setq command (mapconcat 'tramp-shell-quote-argument
3668 (cons program args) " "))
3669 ;; Determine input.
3670 (if (null infile)
3671 (setq input "/dev/null")
3672 (setq infile (expand-file-name infile))
3673 (if (tramp-equal-remote default-directory infile)
3674 ;; INFILE is on the same remote host.
3675 (setq input (with-parsed-tramp-file-name infile nil localname))
3676 ;; INFILE must be copied to remote host.
3677 (setq input (tramp-make-tramp-temp-file v)
3678 tmpinput (tramp-make-tramp-file-name method user host input))
3679 (copy-file infile tmpinput t)))
3680 (when input (setq command (format "%s <%s" command input)))
3682 ;; Determine output.
3683 (cond
3684 ;; Just a buffer
3685 ((bufferp destination)
3686 (setq outbuf destination))
3687 ;; A buffer name
3688 ((stringp destination)
3689 (setq outbuf (get-buffer-create destination)))
3690 ;; (REAL-DESTINATION ERROR-DESTINATION)
3691 ((consp destination)
3692 ;; output
3693 (cond
3694 ((bufferp (car destination))
3695 (setq outbuf (car destination)))
3696 ((stringp (car destination))
3697 (setq outbuf (get-buffer-create (car destination))))
3698 ((car destination)
3699 (setq outbuf (current-buffer))))
3700 ;; stderr
3701 (cond
3702 ((stringp (cadr destination))
3703 (setcar (cdr destination) (expand-file-name (cadr destination)))
3704 (if (tramp-equal-remote default-directory (cadr destination))
3705 ;; stderr is on the same remote host.
3706 (setq stderr (with-parsed-tramp-file-name
3707 (cadr destination) nil localname))
3708 ;; stderr must be copied to remote host. The temporary
3709 ;; file must be deleted after execution.
3710 (setq stderr (tramp-make-tramp-temp-file v)
3711 tmpstderr (tramp-make-tramp-file-name
3712 method user host stderr))))
3713 ;; stderr to be discarded
3714 ((null (cadr destination))
3715 (setq stderr "/dev/null"))))
3716 ;; 't
3717 (destination
3718 (setq outbuf (current-buffer))))
3719 (when stderr (setq command (format "%s 2>%s" command stderr)))
3721 ;; Goto working directory.
3722 (tramp-send-command
3723 v (format "cd %s" (tramp-shell-quote-argument localname)))
3724 ;; Send the command. It might not return in time, so we protect it.
3725 (condition-case nil
3726 (unwind-protect
3727 (tramp-send-command v command)
3728 ;; We should show the output anyway.
3729 (when outbuf
3730 (let ((output-string
3731 (with-current-buffer (tramp-get-connection-buffer v)
3732 (buffer-substring (point-min) (point-max)))))
3733 (with-current-buffer outbuf
3734 (insert output-string)))
3735 (when display (display-buffer outbuf))))
3736 ;; When the user did interrupt, we should do it also.
3737 (error
3738 (kill-buffer (tramp-get-connection-buffer v))
3739 (setq ret 1)))
3741 ;; Check return code.
3742 (unless ret (setq ret (tramp-send-command-and-check v nil)))
3743 ;; Provide error file.
3744 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
3745 ;; Cleanup.
3746 (when tmpinput (delete-file tmpinput))
3747 ;; Return exit status.
3748 ret)))
3750 (defun tramp-local-call-process
3751 (program &optional infile destination display &rest args)
3752 "Calls `call-process' on the local host.
3753 This is needed because for some Emacs flavors Tramp has
3754 defadviced `call-process' to behave like `process-file'. The
3755 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
3756 (let ((default-directory
3757 (if (file-remote-p default-directory)
3758 (tramp-compat-temporary-file-directory)
3759 default-directory)))
3760 (if (executable-find program)
3761 (apply 'call-process program infile destination display args)
3762 1)))
3764 (defun tramp-handle-call-process-region
3765 (start end program &optional delete buffer display &rest args)
3766 "Like `call-process-region' for Tramp files."
3767 (let ((tmpfile (tramp-compat-make-temp-file "")))
3768 (write-region start end tmpfile)
3769 (when delete (delete-region start end))
3770 (unwind-protect
3771 (apply 'call-process program tmpfile buffer display args)
3772 (delete-file tmpfile))))
3774 (defun tramp-handle-shell-command
3775 (command &optional output-buffer error-buffer)
3776 "Like `shell-command' for Tramp files."
3777 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
3778 ;; We cannot use `shell-file-name' and `shell-command-switch',
3779 ;; they are variables of the local host.
3780 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
3781 (output-buffer
3782 (cond
3783 ((bufferp output-buffer) output-buffer)
3784 ((stringp output-buffer) (get-buffer-create output-buffer))
3785 (output-buffer (current-buffer))
3786 (t (get-buffer-create
3787 (if asynchronous
3788 "*Async Shell Command*"
3789 "*Shell Command Output*")))))
3790 (error-buffer
3791 (cond
3792 ((bufferp error-buffer) error-buffer)
3793 ((stringp error-buffer) (get-buffer-create error-buffer))))
3794 (buffer
3795 (if (and (not asynchronous) error-buffer)
3796 (with-parsed-tramp-file-name default-directory nil
3797 (list output-buffer (tramp-make-tramp-temp-file v)))
3798 output-buffer))
3799 (p (get-buffer-process output-buffer)))
3801 ;; Check whether there is another process running. Tramp does not
3802 ;; support 2 (asynchronous) processes in parallel.
3803 (when p
3804 (if (yes-or-no-p "A command is running. Kill it? ")
3805 (condition-case nil
3806 (kill-process p)
3807 (error nil))
3808 (error "Shell command in progress")))
3810 (with-current-buffer output-buffer
3811 (setq buffer-read-only nil
3812 buffer-undo-list t)
3813 (erase-buffer))
3815 (if (integerp asynchronous)
3816 (prog1
3817 ;; Run the process.
3818 (apply 'start-file-process "*Async Shell*" buffer args)
3819 ;; Display output.
3820 (pop-to-buffer output-buffer)
3821 (setq mode-line-process '(":%s"))
3822 (require 'shell) (shell-mode))
3824 (prog1
3825 ;; Run the process.
3826 (apply 'process-file (car args) nil buffer nil (cdr args))
3827 ;; Insert error messages if they were separated.
3828 (when (listp buffer)
3829 (with-current-buffer error-buffer
3830 (insert-file-contents (cadr buffer)))
3831 (delete-file (cadr buffer)))
3832 ;; There's some output, display it.
3833 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
3834 (if (functionp 'display-message-or-buffer)
3835 (funcall (symbol-function 'display-message-or-buffer)
3836 output-buffer)
3837 (pop-to-buffer output-buffer)))))))
3839 ;; File Editing.
3841 (defvar tramp-handle-file-local-copy-hook nil
3842 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
3844 (defun tramp-handle-file-local-copy (filename)
3845 "Like `file-local-copy' for Tramp files."
3847 (with-parsed-tramp-file-name filename nil
3848 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
3849 (loc-dec (tramp-get-local-coding v "local-decoding"))
3850 (tmpfile (tramp-compat-make-temp-file filename)))
3851 (unless (file-exists-p filename)
3852 (tramp-error
3853 v 'file-error
3854 "Cannot make local copy of non-existing file `%s'" filename))
3856 (cond
3857 ;; `copy-file' handles direct copy and out-of-band methods.
3858 ((or (tramp-local-host-p v)
3859 (and (tramp-method-out-of-band-p v)
3860 (> (nth 7 (file-attributes filename)) tramp-copy-size-limit)))
3861 (copy-file filename tmpfile t t))
3863 ;; Use inline encoding for file transfer.
3864 (rem-enc
3865 (save-excursion
3866 (tramp-message v 5 "Encoding remote file %s..." filename)
3867 (tramp-barf-unless-okay
3868 v (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
3869 "Encoding remote file failed")
3870 (tramp-message v 5 "Encoding remote file %s...done" filename)
3872 (tramp-message v 5 "Decoding remote file %s..." filename)
3873 (if (and (symbolp loc-dec) (fboundp loc-dec))
3874 ;; If local decoding is a function, we call it. We must
3875 ;; disable multibyte, because `uudecode-decode-region'
3876 ;; doesn't handle it correctly.
3877 (unwind-protect
3878 (with-temp-buffer
3879 (set-buffer-multibyte nil)
3880 (insert-buffer-substring (tramp-get-buffer v))
3881 (tramp-message
3882 v 5 "Decoding remote file %s with function %s..."
3883 filename loc-dec)
3884 (funcall loc-dec (point-min) (point-max))
3885 (let ((coding-system-for-write 'binary))
3886 (write-region (point-min) (point-max) tmpfile))))
3887 ;; If tramp-decoding-function is not defined for this
3888 ;; method, we invoke tramp-decoding-command instead.
3889 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
3890 (let ((coding-system-for-write 'binary))
3891 (write-region (point-min) (point-max) tmpfile2))
3892 (tramp-message
3893 v 5 "Decoding remote file %s with command %s..."
3894 filename loc-dec)
3895 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
3896 (delete-file tmpfile2)))
3897 (tramp-message v 5 "Decoding remote file %s...done" filename)
3898 ;; Set proper permissions.
3899 (set-file-modes tmpfile (file-modes filename))
3900 ;; Set local user ownership.
3901 (tramp-set-file-uid-gid tmpfile)))
3903 ;; Oops, I don't know what to do.
3904 (t (tramp-error
3905 v 'file-error "Wrong method specification for `%s'" method)))
3907 (run-hooks 'tramp-handle-file-local-copy-hook)
3908 tmpfile)))
3910 (defun tramp-handle-file-remote-p (filename &optional identification connected)
3911 "Like `file-remote-p' for Tramp files."
3912 (when (tramp-tramp-file-p filename)
3913 (with-parsed-tramp-file-name filename nil
3914 (and (or (not connected)
3915 (let ((p (tramp-get-connection-process v)))
3916 (and p (processp p) (memq (process-status p) '(run open)))))
3917 (cond
3918 ((eq identification 'method) method)
3919 ((eq identification 'user) user)
3920 ((eq identification 'host) host)
3921 ((eq identification 'localname) localname)
3922 (t (tramp-make-tramp-file-name method user host "")))))))
3924 (defun tramp-handle-insert-file-contents
3925 (filename &optional visit beg end replace)
3926 "Like `insert-file-contents' for Tramp files."
3927 (barf-if-buffer-read-only)
3928 (setq filename (expand-file-name filename))
3929 (let (coding-system-used result)
3930 (with-parsed-tramp-file-name filename nil
3932 (if (not (file-exists-p filename))
3933 (progn
3934 (when visit
3935 (setq buffer-file-name filename)
3936 (set-visited-file-modtime)
3937 (set-buffer-modified-p nil))
3938 ;; We don't raise a Tramp error, because it might be
3939 ;; suppressed, like in `find-file-noselect-1'.
3940 (signal 'file-error (list "File not found on remote host" filename))
3941 (list (expand-file-name filename) 0))
3943 (if (and (tramp-local-host-p v)
3944 (file-readable-p localname))
3945 ;; Short track: if we are on the local host, we can run directly.
3946 (setq result (insert-file-contents localname visit beg end replace))
3948 ;; `insert-file-contents-literally' takes care to avoid calling
3949 ;; jka-compr. By let-binding inhibit-file-name-operation, we
3950 ;; propagate that care to the file-local-copy operation.
3951 (let ((local-copy
3952 (let ((inhibit-file-name-operation
3953 (when (eq inhibit-file-name-operation
3954 'insert-file-contents)
3955 'file-local-copy)))
3956 (file-local-copy filename))))
3957 (tramp-message v 4 "Inserting local temp file `%s'..." local-copy)
3958 (setq result (insert-file-contents local-copy nil beg end replace))
3959 ;; Now `last-coding-system-used' has right value. Remember it.
3960 (when (boundp 'last-coding-system-used)
3961 (setq coding-system-used (symbol-value 'last-coding-system-used)))
3962 (tramp-message v 4 "Inserting local temp file `%s'...done" local-copy)
3963 (delete-file local-copy)
3964 (when (boundp 'last-coding-system-used)
3965 (set 'last-coding-system-used coding-system-used))))
3967 (when visit
3968 (setq buffer-read-only (file-writable-p filename))
3969 (setq buffer-file-name filename)
3970 (set-visited-file-modtime)
3971 (set-buffer-modified-p nil))
3972 (list (expand-file-name filename)
3973 (cadr result))))))
3975 ;; This is needed for XEmacs only. Code stolen from files.el.
3976 (defun tramp-handle-insert-file-contents-literally
3977 (filename &optional visit beg end replace)
3978 "Like `insert-file-contents-literally' for Tramp files."
3979 (let ((format-alist nil)
3980 (after-insert-file-functions nil)
3981 (coding-system-for-read 'no-conversion)
3982 (coding-system-for-write 'no-conversion)
3983 (find-buffer-file-type-function
3984 (if (fboundp 'find-buffer-file-type)
3985 (symbol-function 'find-buffer-file-type)
3986 nil))
3987 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
3988 (inhibit-file-name-operation 'insert-file-contents))
3989 (unwind-protect
3990 (progn
3991 (fset 'find-buffer-file-type (lambda (filename) t))
3992 (insert-file-contents filename visit beg end replace))
3993 (if find-buffer-file-type-function
3994 (fset 'find-buffer-file-type find-buffer-file-type-function)
3995 (fmakunbound 'find-buffer-file-type)))))
3997 (defun tramp-handle-find-backup-file-name (filename)
3998 "Like `find-backup-file-name' for Tramp files."
3999 (with-parsed-tramp-file-name filename nil
4000 ;; We set both variables. It doesn't matter whether it is
4001 ;; Emacs or XEmacs
4002 (let ((backup-directory-alist
4003 ;; Emacs case
4004 (when (boundp 'backup-directory-alist)
4005 (if (boundp 'tramp-backup-directory-alist)
4006 (mapcar
4007 '(lambda (x)
4008 (cons
4009 (car x)
4010 (if (and (stringp (cdr x))
4011 (file-name-absolute-p (cdr x))
4012 (not (tramp-file-name-p (cdr x))))
4013 (tramp-make-tramp-file-name method user host (cdr x))
4014 (cdr x))))
4015 (symbol-value 'tramp-backup-directory-alist))
4016 (symbol-value 'backup-directory-alist))))
4018 (bkup-backup-directory-info
4019 ;; XEmacs case
4020 (when (boundp 'bkup-backup-directory-info)
4021 (if (boundp 'tramp-bkup-backup-directory-info)
4022 (mapcar
4023 '(lambda (x)
4024 (nconc
4025 (list (car x))
4026 (list
4027 (if (and (stringp (car (cdr x)))
4028 (file-name-absolute-p (car (cdr x)))
4029 (not (tramp-file-name-p (car (cdr x)))))
4030 (tramp-make-tramp-file-name
4031 method user host (car (cdr x)))
4032 (car (cdr x))))
4033 (cdr (cdr x))))
4034 (symbol-value 'tramp-bkup-backup-directory-info))
4035 (symbol-value 'bkup-backup-directory-info)))))
4037 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
4039 (defun tramp-handle-make-auto-save-file-name ()
4040 "Like `make-auto-save-file-name' for Tramp files.
4041 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
4042 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4043 (buffer-file-name
4044 (tramp-subst-strs-in-string
4045 '(("_" . "|")
4046 ("/" . "_a")
4047 (":" . "_b")
4048 ("|" . "__")
4049 ("[" . "_l")
4050 ("]" . "_r"))
4051 (buffer-file-name))))
4052 ;; File name must be unique. This is ensured with Emacs 22 (see
4053 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4054 ;; all other cases we must do it ourselves.
4055 (when (boundp 'auto-save-file-name-transforms)
4056 (mapc
4057 '(lambda (x)
4058 (when (and (string-match (car x) buffer-file-name)
4059 (not (car (cddr x))))
4060 (setq tramp-auto-save-directory
4061 (or tramp-auto-save-directory
4062 (tramp-compat-temporary-file-directory)))))
4063 (symbol-value 'auto-save-file-name-transforms)))
4064 ;; Create directory.
4065 (when tramp-auto-save-directory
4066 (setq buffer-file-name
4067 (expand-file-name buffer-file-name tramp-auto-save-directory))
4068 (unless (file-exists-p tramp-auto-save-directory)
4069 (make-directory tramp-auto-save-directory t)))
4070 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4071 ;; it is not a magic file name operation (since Emacs 22).
4072 ;; We must deactivate it temporarily.
4073 (if (not (ad-is-active 'make-auto-save-file-name))
4074 (tramp-run-real-handler 'make-auto-save-file-name nil)
4075 ;; else
4076 (ad-deactivate 'make-auto-save-file-name)
4077 (prog1
4078 (tramp-run-real-handler 'make-auto-save-file-name nil)
4079 (ad-activate 'make-auto-save-file-name)))))
4081 (defvar tramp-handle-write-region-hook nil
4082 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4084 ;; CCC grok APPEND, LOCKNAME
4085 (defun tramp-handle-write-region
4086 (start end filename &optional append visit lockname confirm)
4087 "Like `write-region' for Tramp files."
4088 (setq filename (expand-file-name filename))
4089 (with-parsed-tramp-file-name filename nil
4090 (unless (null append)
4091 (tramp-error
4092 v 'file-error "Cannot append to file using Tramp (`%s')" filename))
4093 ;; Following part commented out because we don't know what to do about
4094 ;; file locking, and it does not appear to be a problem to ignore it.
4095 ;; Ange-ftp ignores it, too.
4096 ;; (when (and lockname (stringp lockname))
4097 ;; (setq lockname (expand-file-name lockname)))
4098 ;; (unless (or (eq lockname nil)
4099 ;; (string= lockname filename))
4100 ;; (error
4101 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
4103 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
4104 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4105 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4106 (tramp-error v 'file-error "File not overwritten")))
4108 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
4109 (tramp-get-remote-uid v 'integer)))
4110 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
4111 (tramp-get-remote-gid v 'integer))))
4113 (if (and (tramp-local-host-p v)
4114 (file-writable-p (file-name-directory localname))
4115 (or (file-directory-p localname)
4116 (file-writable-p localname)))
4117 ;; Short track: if we are on the local host, we can run directly.
4118 (write-region start end localname append 'no-message lockname confirm)
4120 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4121 (loc-enc (tramp-get-local-coding v "local-encoding"))
4122 (modes (save-excursion (file-modes filename)))
4123 ;; We use this to save the value of
4124 ;; `last-coding-system-used' after writing the tmp file.
4125 ;; At the end of the function, we set
4126 ;; `last-coding-system-used' to this saved value. This
4127 ;; way, any intermediary coding systems used while
4128 ;; talking to the remote shell or suchlike won't hose
4129 ;; this variable. This approach was snarfed from
4130 ;; ange-ftp.el.
4131 coding-system-used
4132 ;; Write region into a tmp file. This isn't really
4133 ;; needed if we use an encoding function, but currently
4134 ;; we use it always because this makes the logic
4135 ;; simpler.
4136 (tmpfile (tramp-compat-make-temp-file filename)))
4138 ;; We say `no-message' here because we don't want the
4139 ;; visited file modtime data to be clobbered from the temp
4140 ;; file. We call `set-visited-file-modtime' ourselves later
4141 ;; on.
4142 (tramp-run-real-handler
4143 'write-region
4144 (list start end tmpfile append 'no-message lockname confirm))
4145 ;; Now, `last-coding-system-used' has the right value. Remember it.
4146 (when (boundp 'last-coding-system-used)
4147 (setq coding-system-used (symbol-value 'last-coding-system-used)))
4148 ;; The permissions of the temporary file should be set. If
4149 ;; filename does not exist (eq modes nil) it has been
4150 ;; renamed to the backup file. This case `save-buffer'
4151 ;; handles permissions.
4152 (when modes (set-file-modes tmpfile modes))
4154 ;; This is a bit lengthy due to the different methods
4155 ;; possible for file transfer. First, we check whether the
4156 ;; method uses an rcp program. If so, we call it.
4157 ;; Otherwise, both encoding and decoding command must be
4158 ;; specified. However, if the method _also_ specifies an
4159 ;; encoding function, then that is used for encoding the
4160 ;; contents of the tmp file.
4161 (cond
4162 ;; `rename-file' handles direct copy and out-of-band methods.
4163 ((or (tramp-local-host-p v)
4164 (and (tramp-method-out-of-band-p v)
4165 (integerp start)
4166 (> (- end start) tramp-copy-size-limit)))
4167 (rename-file tmpfile filename t))
4169 ;; Use inline file transfer
4170 (rem-dec
4171 ;; Encode tmpfile
4172 (tramp-message v 5 "Encoding region...")
4173 (unwind-protect
4174 (with-temp-buffer
4175 ;; Use encoding function or command.
4176 (if (and (symbolp loc-enc) (fboundp loc-enc))
4177 (progn
4178 (tramp-message
4179 v 5 "Encoding region using function `%s'..."
4180 (symbol-name loc-enc))
4181 (let ((coding-system-for-read 'binary))
4182 (insert-file-contents-literally tmpfile))
4183 ;; CCC. The following `let' is a workaround
4184 ;; for the base64.el that comes with
4185 ;; pgnus-0.84. If both of the following
4186 ;; conditions are satisfied, it tries to write
4187 ;; to a local file in default-directory, but
4188 ;; at this point, default-directory is remote.
4189 ;; (`call-process-region' can't write to remote
4190 ;; files, it seems.) The file in question is
4191 ;; a tmp file anyway.
4192 (let ((default-directory
4193 (tramp-compat-temporary-file-directory)))
4194 (funcall loc-enc (point-min) (point-max))))
4196 (tramp-message
4197 v 5 "Encoding region using command `%s'..." loc-enc)
4198 (unless (equal 0 (tramp-call-local-coding-command
4199 loc-enc tmpfile t))
4200 (tramp-error
4201 v 'file-error
4202 "Cannot write to `%s', local encoding command `%s' failed"
4203 filename loc-enc)))
4205 ;; Send buffer into remote decoding command which
4206 ;; writes to remote file. Because this happens on
4207 ;; the remote host, we cannot use the function.
4208 (goto-char (point-max))
4209 (unless (bolp) (newline))
4210 (tramp-message
4211 v 5 "Decoding region into remote file %s..." filename)
4212 (tramp-send-command
4214 (format
4215 "%s >%s <<'EOF'\n%sEOF"
4216 rem-dec
4217 (tramp-shell-quote-argument localname)
4218 (buffer-string)))
4219 (tramp-barf-unless-okay
4220 v nil
4221 "Couldn't write region to `%s', decode using `%s' failed"
4222 filename rem-dec)
4223 ;; When `file-precious-flag' is set, the region is
4224 ;; written to a temporary file. Check that the
4225 ;; checksum is equal to that from the local tmpfile.
4226 (when file-precious-flag
4227 (erase-buffer)
4228 (and
4229 ;; cksum runs locally, if possible.
4230 (zerop (tramp-local-call-process "cksum" tmpfile t))
4231 ;; cksum runs remotely.
4232 (zerop
4233 (tramp-send-command-and-check
4235 (format
4236 "cksum <%s" (tramp-shell-quote-argument localname))))
4237 ;; ... they are different.
4238 (not
4239 (string-equal
4240 (buffer-string)
4241 (with-current-buffer (tramp-get-buffer v)
4242 (buffer-string))))
4243 (tramp-error
4244 v 'file-error
4245 (concat "Couldn't write region to `%s',"
4246 " decode using `%s' failed")
4247 filename rem-dec)))
4248 (tramp-message
4249 v 5 "Decoding region into remote file %s...done" filename)
4250 (tramp-flush-file-property v localname))
4252 ;; Save exit.
4253 (delete-file tmpfile)))
4255 ;; That's not expected.
4257 (tramp-error
4258 v 'file-error
4259 (concat "Method `%s' should specify both encoding and "
4260 "decoding command or an rcp program")
4261 method)))
4263 ;; Make `last-coding-system-used' have the right value.
4264 (when coding-system-used
4265 (set 'last-coding-system-used coding-system-used))))
4267 ;; We must protect `last-coding-system-used', now we have set it
4268 ;; to its correct value.
4269 (let (last-coding-system-used)
4270 ;; Set file modification time.
4271 (when (or (eq visit t) (stringp visit))
4272 (set-visited-file-modtime
4273 ;; We must pass modtime explicitely, because filename can
4274 ;; be different from (buffer-file-name), f.e. if
4275 ;; `file-precious-flag' is set.
4276 (nth 5 (file-attributes filename))))
4278 ;; Set the ownership.
4279 (tramp-set-file-uid-gid filename uid gid)
4280 (when (or (eq visit t) (null visit) (stringp visit))
4281 (tramp-message v 0 "Wrote %s" filename))
4282 (run-hooks 'tramp-handle-write-region-hook)))))
4284 ;;;###autoload
4285 (progn (defun tramp-run-real-handler (operation args)
4286 "Invoke normal file name handler for OPERATION.
4287 First arg specifies the OPERATION, second arg is a list of arguments to
4288 pass to the OPERATION."
4289 (let* ((inhibit-file-name-handlers
4290 `(tramp-file-name-handler
4291 tramp-completion-file-name-handler
4292 cygwin-mount-name-hook-function
4293 cygwin-mount-map-drive-hook-function
4295 ,(and (eq inhibit-file-name-operation operation)
4296 inhibit-file-name-handlers)))
4297 (inhibit-file-name-operation operation))
4298 (apply operation args))))
4300 ;;;###autoload
4301 (progn (defun tramp-completion-run-real-handler (operation args)
4302 "Invoke `tramp-file-name-handler' for OPERATION.
4303 First arg specifies the OPERATION, second arg is a list of arguments to
4304 pass to the OPERATION."
4305 (let* ((inhibit-file-name-handlers
4306 `(tramp-completion-file-name-handler
4307 cygwin-mount-name-hook-function
4308 cygwin-mount-map-drive-hook-function
4310 ,(and (eq inhibit-file-name-operation operation)
4311 inhibit-file-name-handlers)))
4312 (inhibit-file-name-operation operation))
4313 (apply operation args))))
4315 ;; We handle here all file primitives. Most of them have the file
4316 ;; name as first parameter; nevertheless we check for them explicitly
4317 ;; in order to be signalled if a new primitive appears. This
4318 ;; scenario is needed because there isn't a way to decide by
4319 ;; syntactical means whether a foreign method must be called. It would
4320 ;; ease the life if `file-name-handler-alist' would support a decision
4321 ;; function as well but regexp only.
4322 (defun tramp-file-name-for-operation (operation &rest args)
4323 "Return file name related to OPERATION file primitive.
4324 ARGS are the arguments OPERATION has been called with."
4325 (cond
4326 ; FILE resp DIRECTORY
4327 ((member operation
4328 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
4329 'delete-file 'diff-latest-backup-file 'directory-file-name
4330 'directory-files 'directory-files-and-attributes
4331 'dired-compress-file 'dired-uncache
4332 'file-accessible-directory-p 'file-attributes
4333 'file-directory-p 'file-executable-p 'file-exists-p
4334 'file-local-copy 'file-remote-p 'file-modes
4335 'file-name-as-directory 'file-name-directory
4336 'file-name-nondirectory 'file-name-sans-versions
4337 'file-ownership-preserved-p 'file-readable-p
4338 'file-regular-p 'file-symlink-p 'file-truename
4339 'file-writable-p 'find-backup-file-name 'find-file-noselect
4340 'get-file-buffer 'insert-directory 'insert-file-contents
4341 'load 'make-directory 'make-directory-internal
4342 'set-file-modes 'substitute-in-file-name
4343 'unhandled-file-name-directory 'vc-registered
4344 ; Emacs 22 only
4345 'set-file-times
4346 ; XEmacs only
4347 'abbreviate-file-name 'create-file-buffer
4348 'dired-file-modtime 'dired-make-compressed-filename
4349 'dired-recursive-delete-directory 'dired-set-file-modtime
4350 'dired-shell-unhandle-file-name 'dired-uucode-file
4351 'insert-file-contents-literally 'recover-file
4352 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
4353 (if (file-name-absolute-p (nth 0 args))
4354 (nth 0 args)
4355 (expand-file-name (nth 0 args))))
4356 ; FILE DIRECTORY resp FILE1 FILE2
4357 ((member operation
4358 (list 'add-name-to-file 'copy-file 'expand-file-name
4359 'file-name-all-completions 'file-name-completion
4360 'file-newer-than-file-p 'make-symbolic-link 'rename-file
4361 ; XEmacs only
4362 'dired-make-relative-symlink
4363 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
4364 (save-match-data
4365 (cond
4366 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
4367 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
4368 (t (buffer-file-name (current-buffer))))))
4369 ; START END FILE
4370 ((eq operation 'write-region)
4371 (nth 2 args))
4372 ; BUF
4373 ((member operation
4374 (list 'set-visited-file-modtime 'verify-visited-file-modtime
4375 ; since Emacs 22 only
4376 'make-auto-save-file-name
4377 ; XEmacs only
4378 'backup-buffer))
4379 (buffer-file-name
4380 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
4381 ; COMMAND
4382 ((member operation
4383 (list ; not in Emacs 23
4384 'dired-call-process
4385 ; Emacs only
4386 'shell-command
4387 ; since Emacs 22 only
4388 'process-file
4389 ; since Emacs 23 only
4390 'start-file-process
4391 ; XEmacs only
4392 'dired-print-file 'dired-shell-call-process
4393 ; nowhere yet
4394 'executable-find 'start-process 'call-process))
4395 default-directory)
4396 ; unknown file primitive
4397 (t (error "unknown file I/O primitive: %s" operation))))
4399 (defun tramp-find-foreign-file-name-handler (filename)
4400 "Return foreign file name handler if exists."
4401 (when (and (stringp filename) (tramp-tramp-file-p filename))
4402 (let ((v (tramp-dissect-file-name filename t))
4403 (handler tramp-foreign-file-name-handler-alist)
4404 elt res)
4405 ;; When we are not fully sure that filename completion is safe,
4406 ;; we should not return a handler.
4407 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
4408 (and (tramp-file-name-host v)
4409 (not (member (tramp-file-name-host v)
4410 (mapcar 'car tramp-methods))))
4411 (not (tramp-completion-mode-p)))
4412 (while handler
4413 (setq elt (car handler)
4414 handler (cdr handler))
4415 (when (funcall (car elt) filename)
4416 (setq handler nil
4417 res (cdr elt))))
4418 res))))
4420 ;; Main function.
4421 ;;;###autoload
4422 (defun tramp-file-name-handler (operation &rest args)
4423 "Invoke Tramp file name handler.
4424 Falls back to normal file name handler if no Tramp file name handler exists."
4425 (save-match-data
4426 (let* ((filename (apply 'tramp-file-name-for-operation operation args))
4427 (completion (tramp-completion-mode-p))
4428 (foreign (tramp-find-foreign-file-name-handler filename)))
4429 (with-parsed-tramp-file-name filename nil
4430 (cond
4431 ;; When we are in completion mode, some operations shouldn't be
4432 ;; handled by backend.
4433 ((and completion (zerop (length localname))
4434 (memq operation '(file-exists-p file-directory-p)))
4436 ((and completion (zerop (length localname))
4437 (memq operation '(file-name-as-directory)))
4438 filename)
4439 ;; Call the backend function.
4440 (foreign (apply foreign operation args))
4441 ;; Nothing to do for us.
4442 (t (tramp-run-real-handler operation args)))))))
4444 ;; In Emacs, there is some concurrency due to timers. If a timer
4445 ;; interrupts Tramp and wishes to use the same connection buffer as
4446 ;; the "main" Emacs, then garbage might occur in the connection
4447 ;; buffer. Therefore, we need to make sure that a timer does not use
4448 ;; the same connection buffer as the "main" Emacs. We implement a
4449 ;; cheap global lock, instead of locking each connection buffer
4450 ;; separately. The global lock is based on two variables,
4451 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
4452 ;; (with setq) to indicate a lock. But Tramp also calls itself during
4453 ;; processing of a single file operation, so we need to allow
4454 ;; recursive calls. That's where the `tramp-locker' variable comes in
4455 ;; -- it is let-bound to t during the execution of the current
4456 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
4457 ;; then we should just proceed because we have been called
4458 ;; recursively. But if `tramp-locker' is nil, then we are a timer
4459 ;; interrupting the "main" Emacs, and then we signal an error.
4461 (defvar tramp-locked nil
4462 "If non-nil, then Tramp is currently busy.
4463 Together with `tramp-locker', this implements a locking mechanism
4464 preventing reentrant calls of Tramp.")
4466 (defvar tramp-locker nil
4467 "If non-nil, then a caller has locked Tramp.
4468 Together with `tramp-locked', this implements a locking mechanism
4469 preventing reentrant calls of Tramp.")
4471 (defun tramp-sh-file-name-handler (operation &rest args)
4472 "Invoke remote-shell Tramp file name handler.
4473 Fall back to normal file name handler if no Tramp handler exists."
4474 (when (and tramp-locked (not tramp-locker))
4475 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
4476 (let ((tl tramp-locked))
4477 (unwind-protect
4478 (progn
4479 (setq tramp-locked t)
4480 (let ((tramp-locker t))
4481 (save-match-data
4482 (let ((fn (assoc operation tramp-file-name-handler-alist)))
4483 (if fn
4484 (apply (cdr fn) args)
4485 (tramp-run-real-handler operation args))))))
4486 (setq tramp-locked tl))))
4488 ;;;###autoload
4489 (progn (defun tramp-completion-file-name-handler (operation &rest args)
4490 "Invoke Tramp file name completion handler.
4491 Falls back to normal file name handler if no Tramp file name handler exists."
4492 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
4493 ;; would otherwise use backslash.
4494 (let ((directory-sep-char ?/)
4495 (fn (assoc operation tramp-completion-file-name-handler-alist)))
4496 (if fn
4497 (save-match-data (apply (cdr fn) args))
4498 (tramp-completion-run-real-handler operation args)))))
4500 ;;;###autoload
4501 (defsubst tramp-register-file-name-handler ()
4502 "Add Tramp file name handler to `file-name-handler-alist'."
4503 ;; Remove autoloaded handler from file name handler alist. Useful,
4504 ;; if `tramp-syntax' has been changed.
4505 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
4506 (setq file-name-handler-alist (delete a1 file-name-handler-alist)))
4507 ;; Add the handler.
4508 (add-to-list 'file-name-handler-alist
4509 (cons tramp-file-name-regexp 'tramp-file-name-handler))
4510 ;; If jka-compr is already loaded, move it to the front of
4511 ;; `file-name-handler-alist'.
4512 (let ((jka (rassoc 'jka-compr-handler file-name-handler-alist)))
4513 (when jka
4514 (setq file-name-handler-alist
4515 (cons jka (delete jka file-name-handler-alist))))))
4517 ;; `tramp-file-name-handler' must be registered before evaluation of
4518 ;; site-start and init files, because there might exist remote files
4519 ;; already, f.e. files kept via recentf-mode.
4520 ;;;###autoload(tramp-register-file-name-handler)
4521 (tramp-register-file-name-handler)
4523 ;;;###autoload
4524 (defsubst tramp-register-completion-file-name-handler ()
4525 "Add Tramp completion file name handler to `file-name-handler-alist'."
4526 ;; Remove autoloaded handler from file name handler alist. Useful,
4527 ;; if `tramp-syntax' has been changed.
4528 (let ((a1 (rassq
4529 'tramp-completion-file-name-handler file-name-handler-alist)))
4530 (setq file-name-handler-alist (delete a1 file-name-handler-alist)))
4531 ;; `partial-completion-mode' is unknown in XEmacs. So we should
4532 ;; load it unconditionally there. In the GNU Emacs case, method/
4533 ;; user/host name completion shall be bound to `partial-completion-mode'.
4534 ;; `ido-mode' and `icy-mode' are other packages which extend file
4535 ;; name completion.
4536 (when (or (not (boundp 'partial-completion-mode))
4537 (symbol-value 'partial-completion-mode)
4538 (featurep 'ido)
4539 (featurep 'icicles))
4540 (add-to-list 'file-name-handler-alist
4541 (cons tramp-completion-file-name-regexp
4542 'tramp-completion-file-name-handler))
4543 (put 'tramp-completion-file-name-handler 'safe-magic t))
4544 ;; If jka-compr is already loaded, move it to the front of
4545 ;; `file-name-handler-alist'.
4546 (let ((jka (rassoc 'jka-compr-handler file-name-handler-alist)))
4547 (when jka
4548 (setq file-name-handler-alist
4549 (cons jka (delete jka file-name-handler-alist))))))
4551 ;; During autoload, it shall be checked whether
4552 ;; `partial-completion-mode' is active. Therefore registering of
4553 ;; `tramp-completion-file-name-handler' will be delayed.
4554 ;;;###autoload(add-hook
4555 ;;;###autoload 'after-init-hook
4556 ;;;###autoload '(lambda () (tramp-register-completion-file-name-handler)))
4557 (tramp-register-completion-file-name-handler)
4559 ;;;###autoload
4560 (defun tramp-unload-file-name-handlers ()
4561 (setq file-name-handler-alist
4562 (delete (rassoc 'tramp-file-name-handler
4563 file-name-handler-alist)
4564 (delete (rassoc 'tramp-completion-file-name-handler
4565 file-name-handler-alist)
4566 file-name-handler-alist))))
4568 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
4570 ;;; File name handler functions for completion mode:
4572 (defvar tramp-completion-mode nil
4573 "If non-nil, external packages signal that they are in file name completion.
4575 This is necessary, because Tramp uses a heuristic depending on last
4576 input event. This fails when external packages use other characters
4577 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
4578 should never be set globally, the intention is to let-bind it.")
4580 ;; Necessary because `tramp-file-name-regexp-unified' and
4581 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
4582 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
4583 ;; to `tramp-file-name-handler'). Otherwise, it takes
4584 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
4585 ;; risky, because completing a file might require loading other files,
4586 ;; like "~/.netrc", and for them it shouldn't be decided based on that
4587 ;; variable. On the other hand, those files shouldn't have partial
4588 ;; Tramp file name syntax. Maybe another variable should be introduced
4589 ;; overwriting this check in such cases. Or we change Tramp file name
4590 ;; syntax in order to avoid ambiguities, like in XEmacs ...
4591 (defun tramp-completion-mode-p ()
4592 "Checks whether method / user name / host name completion is active."
4594 ;; Signal from outside.
4595 tramp-completion-mode
4596 ;; Emacs.
4597 (equal last-input-event 'tab)
4598 (and (natnump last-input-event)
4600 ;; ?\t has event-modifier 'control.
4601 (equal last-input-event ?\t)
4602 (and (not (event-modifiers last-input-event))
4603 (or (equal last-input-event ?\?)
4604 (equal last-input-event ?\ )))))
4605 ;; XEmacs.
4606 (and (featurep 'xemacs)
4607 ;; `last-input-event' might be nil.
4608 (not (null last-input-event))
4609 ;; `last-input-event' may have no character approximation.
4610 (funcall (symbol-function 'event-to-character) last-input-event)
4612 ;; ?\t has event-modifier 'control.
4613 (equal
4614 (funcall (symbol-function 'event-to-character)
4615 last-input-event) ?\t)
4616 (and (not (event-modifiers last-input-event))
4617 (or (equal
4618 (funcall (symbol-function 'event-to-character)
4619 last-input-event) ?\?)
4620 (equal
4621 (funcall (symbol-function 'event-to-character)
4622 last-input-event) ?\ )))))))
4624 ;; Method, host name and user name completion.
4625 ;; `tramp-completion-dissect-file-name' returns a list of
4626 ;; tramp-file-name structures. For all of them we return possible completions.
4627 ;;;###autoload
4628 (defun tramp-completion-handle-file-name-all-completions (filename directory)
4629 "Like `file-name-all-completions' for partial Tramp files."
4631 (let* ((fullname (tramp-drop-volume-letter
4632 (expand-file-name filename directory)))
4633 ;; Possible completion structures.
4634 (v (tramp-completion-dissect-file-name fullname))
4635 result result1)
4637 (while v
4638 (let* ((car (car v))
4639 (method (tramp-file-name-method car))
4640 (user (tramp-file-name-user car))
4641 (host (tramp-file-name-host car))
4642 (localname (tramp-file-name-localname car))
4643 (m (tramp-find-method method user host))
4644 (tramp-current-user user) ; see `tramp-parse-passwd'
4645 all-user-hosts)
4647 (unless localname ;; Nothing to complete.
4649 (if (or user host)
4651 ;; Method dependent user / host combinations.
4652 (progn
4653 (mapc
4654 (lambda (x)
4655 (setq all-user-hosts
4656 (append all-user-hosts
4657 (funcall (nth 0 x) (nth 1 x)))))
4658 (tramp-get-completion-function m))
4660 (setq result
4661 (append result
4662 (mapcar
4663 (lambda (x)
4664 (tramp-get-completion-user-host
4665 method user host (nth 0 x) (nth 1 x)))
4666 (delq nil all-user-hosts)))))
4668 ;; Possible methods.
4669 (setq result
4670 (append result (tramp-get-completion-methods m)))))
4672 (setq v (cdr v))))
4674 ;; Unify list, remove nil elements.
4675 (while result
4676 (let ((car (car result)))
4677 (when car
4678 (add-to-list
4679 'result1
4680 (substring car (length (tramp-drop-volume-letter directory)))))
4681 (setq result (cdr result))))
4683 ;; Complete local parts.
4684 (append
4685 result1
4686 (condition-case nil
4687 (tramp-completion-run-real-handler
4688 'file-name-all-completions (list filename directory))
4689 (error nil)))))
4691 ;; Method, host name and user name completion for a file.
4692 ;;;###autoload
4693 (defun tramp-completion-handle-file-name-completion
4694 (filename directory &optional predicate)
4695 "Like `file-name-completion' for Tramp files."
4696 (try-completion
4697 filename
4698 (mapcar 'list (file-name-all-completions filename directory))
4699 (when predicate
4700 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
4702 ;; I misuse a little bit the tramp-file-name structure in order to handle
4703 ;; completion possibilities for partial methods / user names / host names.
4704 ;; Return value is a list of tramp-file-name structures according to possible
4705 ;; completions. If "localname" is non-nil it means there
4706 ;; shouldn't be a completion anymore.
4708 ;; Expected results:
4710 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
4711 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
4712 ;; [nil "x" nil nil]
4713 ;; ["x" nil nil nil]
4715 ;; "/x:" "/x:y" "/x:y:"
4716 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
4717 ;; "/[x/" "/[x/y"
4718 ;; ["x" nil "" nil] ["x" nil "y" nil]
4719 ;; ["x" "" nil nil] ["x" "y" nil nil]
4721 ;; "/x:y@" "/x:y@z" "/x:y@z:"
4722 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
4723 ;; "/[x/y@" "/[x/y@z"
4724 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
4725 (defun tramp-completion-dissect-file-name (name)
4726 "Returns a list of `tramp-file-name' structures.
4727 They are collected by `tramp-completion-dissect-file-name1'."
4729 (let* ((result)
4730 (x-nil "\\|\\(\\)")
4731 ;; "/method" "/[method"
4732 (tramp-completion-file-name-structure1
4733 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
4734 1 nil nil nil))
4735 ;; "/user" "/[user"
4736 (tramp-completion-file-name-structure2
4737 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
4738 nil 1 nil nil))
4739 ;; "/host" "/[host"
4740 (tramp-completion-file-name-structure3
4741 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
4742 nil nil 1 nil))
4743 ;; "/user@host" "/[user@host"
4744 (tramp-completion-file-name-structure4
4745 (list (concat tramp-prefix-regexp
4746 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
4747 "\\(" tramp-host-regexp x-nil "\\)$")
4748 nil 1 2 nil))
4749 ;; "/method:user" "/[method/user" "/method://user"
4750 (tramp-completion-file-name-structure5
4751 (list (concat tramp-prefix-regexp
4752 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4753 "\\(" tramp-user-regexp x-nil "\\)$")
4754 1 2 nil nil))
4755 ;; "/method:host" "/[method/host" "/method://host"
4756 (tramp-completion-file-name-structure6
4757 (list (concat tramp-prefix-regexp
4758 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4759 "\\(" tramp-host-regexp x-nil "\\)$")
4760 1 nil 2 nil))
4761 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
4762 (tramp-completion-file-name-structure7
4763 (list (concat tramp-prefix-regexp
4764 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
4765 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
4766 "\\(" tramp-host-regexp x-nil "\\)$")
4767 1 2 3 nil))
4768 ;; "/method: "/method:/"
4769 (tramp-completion-file-name-structure8
4770 (list
4771 (if (equal tramp-syntax 'url)
4772 (concat tramp-prefix-regexp
4773 "\\(" tramp-method-regexp "\\)"
4774 "\\(" (substring tramp-postfix-method-regexp 0 1)
4775 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
4776 "\\(" "\\)$")
4777 ;; Should not match if not URL syntax.
4778 (concat tramp-prefix-regexp "/$"))
4779 1 3 nil nil))
4780 ;; "/method: "/method:/"
4781 (tramp-completion-file-name-structure9
4782 (list
4783 (if (equal tramp-syntax 'url)
4784 (concat tramp-prefix-regexp
4785 "\\(" tramp-method-regexp "\\)"
4786 "\\(" (substring tramp-postfix-method-regexp 0 1)
4787 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
4788 "\\(" "\\)$")
4789 ;; Should not match if not URL syntax.
4790 (concat tramp-prefix-regexp "/$"))
4791 1 nil 3 nil)))
4793 (mapc (lambda (regexp)
4794 (add-to-list 'result
4795 (tramp-completion-dissect-file-name1 regexp name)))
4796 (list
4797 tramp-completion-file-name-structure1
4798 tramp-completion-file-name-structure2
4799 tramp-completion-file-name-structure3
4800 tramp-completion-file-name-structure4
4801 tramp-completion-file-name-structure5
4802 tramp-completion-file-name-structure6
4803 tramp-completion-file-name-structure7
4804 tramp-completion-file-name-structure8
4805 tramp-completion-file-name-structure9
4806 tramp-file-name-structure))
4808 (delq nil result)))
4810 (defun tramp-completion-dissect-file-name1 (structure name)
4811 "Returns a `tramp-file-name' structure matching STRUCTURE.
4812 The structure consists of remote method, remote user,
4813 remote host and localname (filename on remote host)."
4815 (save-match-data
4816 (when (string-match (nth 0 structure) name)
4817 (let ((method (and (nth 1 structure)
4818 (match-string (nth 1 structure) name)))
4819 (user (and (nth 2 structure)
4820 (match-string (nth 2 structure) name)))
4821 (host (and (nth 3 structure)
4822 (match-string (nth 3 structure) name)))
4823 (localname (and (nth 4 structure)
4824 (match-string (nth 4 structure) name))))
4825 (vector method user host localname)))))
4827 ;; This function returns all possible method completions, adding the
4828 ;; trailing method delimeter.
4829 (defun tramp-get-completion-methods (partial-method)
4830 "Returns all method completions for PARTIAL-METHOD."
4831 (mapcar
4832 (lambda (method)
4833 (and method
4834 (string-match (concat "^" (regexp-quote partial-method)) method)
4835 (tramp-completion-make-tramp-file-name method nil nil nil)))
4836 (mapcar 'car tramp-methods)))
4838 ;; Compares partial user and host names with possible completions.
4839 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
4840 "Returns the most expanded string for user and host name completion.
4841 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
4842 (cond
4844 ((and partial-user partial-host)
4845 (if (and host
4846 (string-match (concat "^" (regexp-quote partial-host)) host)
4847 (string-equal partial-user (or user partial-user)))
4848 (setq user partial-user)
4849 (setq user nil
4850 host nil)))
4852 (partial-user
4853 (setq host nil)
4854 (unless
4855 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
4856 (setq user nil)))
4858 (partial-host
4859 (setq user nil)
4860 (unless
4861 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
4862 (setq host nil)))
4864 (t (setq user nil
4865 host nil)))
4867 (unless (zerop (+ (length user) (length host)))
4868 (tramp-completion-make-tramp-file-name method user host nil)))
4870 (defun tramp-parse-rhosts (filename)
4871 "Return a list of (user host) tuples allowed to access.
4872 Either user or host may be nil."
4873 ;; On Windows, there are problems in completion when
4874 ;; `default-directory' is remote.
4875 (let ((default-directory (tramp-compat-temporary-file-directory))
4876 res)
4877 (when (file-readable-p filename)
4878 (with-temp-buffer
4879 (insert-file-contents filename)
4880 (goto-char (point-min))
4881 (while (not (eobp))
4882 (push (tramp-parse-rhosts-group) res))))
4883 res))
4885 (defun tramp-parse-rhosts-group ()
4886 "Return a (user host) tuple allowed to access.
4887 Either user or host may be nil."
4888 (let ((result)
4889 (regexp
4890 (concat
4891 "^\\(" tramp-host-regexp "\\)"
4892 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
4893 (narrow-to-region (point) (tramp-compat-line-end-position))
4894 (when (re-search-forward regexp nil t)
4895 (setq result (append (list (match-string 3) (match-string 1)))))
4896 (widen)
4897 (forward-line 1)
4898 result))
4900 (defun tramp-parse-shosts (filename)
4901 "Return a list of (user host) tuples allowed to access.
4902 User is always nil."
4903 ;; On Windows, there are problems in completion when
4904 ;; `default-directory' is remote.
4905 (let ((default-directory (tramp-compat-temporary-file-directory))
4906 res)
4907 (when (file-readable-p filename)
4908 (with-temp-buffer
4909 (insert-file-contents filename)
4910 (goto-char (point-min))
4911 (while (not (eobp))
4912 (push (tramp-parse-shosts-group) res))))
4913 res))
4915 (defun tramp-parse-shosts-group ()
4916 "Return a (user host) tuple allowed to access.
4917 User is always nil."
4918 (let ((result)
4919 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
4920 (narrow-to-region (point) (tramp-compat-line-end-position))
4921 (when (re-search-forward regexp nil t)
4922 (setq result (list nil (match-string 1))))
4923 (widen)
4925 (> (skip-chars-forward ",") 0)
4926 (forward-line 1))
4927 result))
4929 (defun tramp-parse-sconfig (filename)
4930 "Return a list of (user host) tuples allowed to access.
4931 User is always nil."
4932 ;; On Windows, there are problems in completion when
4933 ;; `default-directory' is remote.
4934 (let ((default-directory (tramp-compat-temporary-file-directory))
4935 res)
4936 (when (file-readable-p filename)
4937 (with-temp-buffer
4938 (insert-file-contents filename)
4939 (goto-char (point-min))
4940 (while (not (eobp))
4941 (push (tramp-parse-sconfig-group) res))))
4942 res))
4944 (defun tramp-parse-sconfig-group ()
4945 "Return a (user host) tuple allowed to access.
4946 User is always nil."
4947 (let ((result)
4948 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
4949 (narrow-to-region (point) (tramp-compat-line-end-position))
4950 (when (re-search-forward regexp nil t)
4951 (setq result (list nil (match-string 1))))
4952 (widen)
4954 (> (skip-chars-forward ",") 0)
4955 (forward-line 1))
4956 result))
4958 (defun tramp-parse-shostkeys (dirname)
4959 "Return a list of (user host) tuples allowed to access.
4960 User is always nil."
4961 ;; On Windows, there are problems in completion when
4962 ;; `default-directory' is remote.
4963 (let* ((default-directory (tramp-compat-temporary-file-directory))
4964 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
4965 (files (when (file-directory-p dirname) (directory-files dirname)))
4966 result)
4967 (while files
4968 (when (string-match regexp (car files))
4969 (push (list nil (match-string 1 (car files))) result))
4970 (setq files (cdr files)))
4971 result))
4973 (defun tramp-parse-sknownhosts (dirname)
4974 "Return a list of (user host) tuples allowed to access.
4975 User is always nil."
4976 ;; On Windows, there are problems in completion when
4977 ;; `default-directory' is remote.
4978 (let* ((default-directory (tramp-compat-temporary-file-directory))
4979 (regexp (concat "^\\(" tramp-host-regexp
4980 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
4981 (files (when (file-directory-p dirname) (directory-files dirname)))
4982 result)
4983 (while files
4984 (when (string-match regexp (car files))
4985 (push (list nil (match-string 1 (car files))) result))
4986 (setq files (cdr files)))
4987 result))
4989 (defun tramp-parse-hosts (filename)
4990 "Return a list of (user host) tuples allowed to access.
4991 User is always nil."
4992 ;; On Windows, there are problems in completion when
4993 ;; `default-directory' is remote.
4994 (let ((default-directory (tramp-compat-temporary-file-directory))
4995 res)
4996 (when (file-readable-p filename)
4997 (with-temp-buffer
4998 (insert-file-contents filename)
4999 (goto-char (point-min))
5000 (while (not (eobp))
5001 (push (tramp-parse-hosts-group) res))))
5002 res))
5004 (defun tramp-parse-hosts-group ()
5005 "Return a (user host) tuple allowed to access.
5006 User is always nil."
5007 (let ((result)
5008 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
5009 (narrow-to-region (point) (tramp-compat-line-end-position))
5010 (when (re-search-forward regexp nil t)
5011 (unless (char-equal (or (char-after) ?\n) ?:) ; no IPv6
5012 (setq result (list nil (match-string 1)))))
5013 (widen)
5015 (> (skip-chars-forward " \t") 0)
5016 (forward-line 1))
5017 result))
5019 ;; For su-alike methods it would be desirable to return "root@localhost"
5020 ;; as default. Unfortunately, we have no information whether any user name
5021 ;; has been typed already. So we use `tramp-current-user' as indication,
5022 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
5023 (defun tramp-parse-passwd (filename)
5024 "Return a list of (user host) tuples allowed to access.
5025 Host is always \"localhost\"."
5026 ;; On Windows, there are problems in completion when
5027 ;; `default-directory' is remote.
5028 (let ((default-directory (tramp-compat-temporary-file-directory))
5029 res)
5030 (if (zerop (length tramp-current-user))
5031 '(("root" nil))
5032 (when (file-readable-p filename)
5033 (with-temp-buffer
5034 (insert-file-contents filename)
5035 (goto-char (point-min))
5036 (while (not (eobp))
5037 (push (tramp-parse-passwd-group) res))))
5038 res)))
5040 (defun tramp-parse-passwd-group ()
5041 "Return a (user host) tuple allowed to access.
5042 Host is always \"localhost\"."
5043 (let ((result)
5044 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
5045 (narrow-to-region (point) (tramp-compat-line-end-position))
5046 (when (re-search-forward regexp nil t)
5047 (setq result (list (match-string 1) "localhost")))
5048 (widen)
5049 (forward-line 1)
5050 result))
5052 (defun tramp-parse-netrc (filename)
5053 "Return a list of (user host) tuples allowed to access.
5054 User may be nil."
5055 ;; On Windows, there are problems in completion when
5056 ;; `default-directory' is remote.
5057 (let ((default-directory (tramp-compat-temporary-file-directory))
5058 res)
5059 (when (file-readable-p filename)
5060 (with-temp-buffer
5061 (insert-file-contents filename)
5062 (goto-char (point-min))
5063 (while (not (eobp))
5064 (push (tramp-parse-netrc-group) res))))
5065 res))
5067 (defun tramp-parse-netrc-group ()
5068 "Return a (user host) tuple allowed to access.
5069 User may be nil."
5070 (let ((result)
5071 (regexp
5072 (concat
5073 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
5074 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5075 (narrow-to-region (point) (tramp-compat-line-end-position))
5076 (when (re-search-forward regexp nil t)
5077 (setq result (list (match-string 3) (match-string 1))))
5078 (widen)
5079 (forward-line 1)
5080 result))
5082 (defun tramp-parse-putty (registry)
5083 "Return a list of (user host) tuples allowed to access.
5084 User is always nil."
5085 ;; On Windows, there are problems in completion when
5086 ;; `default-directory' is remote.
5087 (let ((default-directory (tramp-compat-temporary-file-directory))
5088 res)
5089 (with-temp-buffer
5090 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
5091 (goto-char (point-min))
5092 (while (not (eobp))
5093 (push (tramp-parse-putty-group registry) res))))
5094 res))
5096 (defun tramp-parse-putty-group (registry)
5097 "Return a (user host) tuple allowed to access.
5098 User is always nil."
5099 (let ((result)
5100 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
5101 (narrow-to-region (point) (tramp-compat-line-end-position))
5102 (when (re-search-forward regexp nil t)
5103 (setq result (list nil (match-string 1))))
5104 (widen)
5105 (forward-line 1)
5106 result))
5108 ;;; Internal Functions:
5110 (defun tramp-maybe-send-script (vec script name)
5111 "Define in remote shell function NAME implemented as SCRIPT.
5112 Only send the definition if it has not already been done."
5113 (let* ((p (tramp-get-connection-process vec))
5114 (scripts (tramp-get-connection-property p "scripts" nil)))
5115 (unless (member name scripts)
5116 (tramp-message vec 5 "Sending script `%s'..." name)
5117 ;; The script could contain a call of Perl. This is masked with `%s'.
5118 (tramp-send-command-and-check
5120 (format "%s () {\n%s\n}" name
5121 (format script (tramp-get-remote-perl vec))))
5122 (tramp-set-connection-property p "scripts" (cons name scripts))
5123 (tramp-message vec 5 "Sending script `%s'...done." name))))
5125 (defun tramp-set-auto-save ()
5126 (when (and ;; ange-ftp has its own auto-save mechanism
5127 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
5128 'tramp-sh-file-name-handler)
5129 auto-save-default)
5130 (auto-save-mode 1)))
5131 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
5132 (add-hook 'tramp-unload-hook
5133 '(lambda ()
5134 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
5136 (defun tramp-run-test (switch filename)
5137 "Run `test' on the remote system, given a SWITCH and a FILENAME.
5138 Returns the exit code of the `test' program."
5139 (with-parsed-tramp-file-name filename nil
5140 (tramp-send-command-and-check
5142 (format
5143 "%s %s %s"
5144 (tramp-get-test-command v)
5145 switch
5146 (tramp-shell-quote-argument localname)))))
5148 (defun tramp-run-test2 (format-string file1 file2)
5149 "Run `test'-like program on the remote system, given FILE1, FILE2.
5150 FORMAT-STRING contains the program name, switches, and place holders.
5151 Returns the exit code of the `test' program. Barfs if the methods,
5152 hosts, or files, disagree."
5153 (unless (tramp-equal-remote file1 file2)
5154 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
5155 (tramp-error
5156 v 'file-error
5157 "tramp-run-test2 only implemented for same method, user, host")))
5158 (with-parsed-tramp-file-name file1 v1
5159 (with-parsed-tramp-file-name file1 v2
5160 (tramp-send-command-and-check
5162 (format format-string
5163 (tramp-shell-quote-argument v1-localname)
5164 (tramp-shell-quote-argument v2-localname))))))
5166 (defun tramp-buffer-name (vec)
5167 "A name for the connection buffer VEC."
5168 ;; We must use `tramp-file-name-real-host', because for gateway
5169 ;; methods the default port will be expanded later on, which would
5170 ;; tamper the name.
5171 (let ((method (tramp-file-name-method vec))
5172 (user (tramp-file-name-user vec))
5173 (host (tramp-file-name-real-host vec)))
5174 (if (not (zerop (length user)))
5175 (format "*tramp/%s %s@%s*" method user host)
5176 (format "*tramp/%s %s*" method host))))
5178 (defun tramp-get-buffer (vec)
5179 "Get the connection buffer to be used for VEC."
5180 (or (get-buffer (tramp-buffer-name vec))
5181 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
5182 (setq buffer-undo-list t)
5183 (setq default-directory
5184 (tramp-make-tramp-file-name
5185 (tramp-file-name-method vec)
5186 (tramp-file-name-user vec)
5187 (tramp-file-name-host vec)
5188 "/"))
5189 (current-buffer))))
5191 (defun tramp-get-connection-buffer (vec)
5192 "Get the connection buffer to be used for VEC.
5193 In case a second asynchronous communication has been started, it is different
5194 from `tramp-get-buffer'."
5195 (or (tramp-get-connection-property vec "process-buffer" nil)
5196 (tramp-get-buffer vec)))
5198 (defun tramp-get-connection-process (vec)
5199 "Get the connection process to be used for VEC.
5200 In case a second asynchronous communication has been started, it is different
5201 from the default one."
5202 (get-process
5203 (or (tramp-get-connection-property vec "process-name" nil)
5204 (tramp-buffer-name vec))))
5206 (defun tramp-debug-buffer-name (vec)
5207 "A name for the debug buffer for VEC."
5208 ;; We must use `tramp-file-name-real-host', because for gateway
5209 ;; methods the default port will be expanded later on, which would
5210 ;; tamper the name.
5211 (let ((method (tramp-file-name-method vec))
5212 (user (tramp-file-name-user vec))
5213 (host (tramp-file-name-real-host vec)))
5214 (if (not (zerop (length user)))
5215 (format "*debug tramp/%s %s@%s*" method user host)
5216 (format "*debug tramp/%s %s*" method host))))
5218 (defun tramp-get-debug-buffer (vec)
5219 "Get the debug buffer for VEC."
5220 (with-current-buffer
5221 (get-buffer-create (tramp-debug-buffer-name vec))
5222 (when (bobp)
5223 (setq buffer-undo-list t)
5224 ;; Activate outline-mode. This runs `text-mode-hook' and
5225 ;; `outline-mode-hook'. We must prevent that local processes
5226 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
5227 ;; ...
5228 (let ((default-directory (tramp-compat-temporary-file-directory)))
5229 (outline-mode))
5230 (set (make-local-variable 'outline-regexp)
5231 "[0-9]+:[0-9]+:[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
5232 ; (set (make-local-variable 'outline-regexp)
5233 ; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
5234 (set (make-local-variable 'outline-level) 'tramp-outline-level))
5235 (current-buffer)))
5237 (defun tramp-outline-level ()
5238 "Return the depth to which a statement is nested in the outline.
5239 Point must be at the beginning of a header line.
5241 The outline level is equal to the verbosity of the Tramp message."
5242 (1+ (string-to-number (match-string 1))))
5244 (defun tramp-find-executable
5245 (vec progname dirlist &optional ignore-tilde ignore-path)
5246 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
5247 First arg VEC specifies the connection, PROGNAME is the program
5248 to search for, and DIRLIST gives the list of directories to
5249 search. If IGNORE-TILDE is non-nil, directory names starting
5250 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
5251 only in DIRLIST.
5253 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
5255 This function expects to be in the right *tramp* buffer."
5256 (with-current-buffer (tramp-get-buffer vec)
5257 (let (result)
5258 ;; Check whether the executable is in $PATH. "which(1)" does not
5259 ;; report always a correct error code; therefore we check the
5260 ;; number of words it returns.
5261 (unless ignore-path
5262 (tramp-send-command vec (format "which \\%s | wc -w" progname))
5263 (goto-char (point-min))
5264 (if (looking-at "^1$")
5265 (setq result (concat "\\" progname))))
5266 (unless result
5267 (when ignore-tilde
5268 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
5269 ;; `remove' is in CL, and we want to avoid CL dependencies.
5270 (let (newdl d)
5271 (while dirlist
5272 (setq d (car dirlist))
5273 (setq dirlist (cdr dirlist))
5274 (unless (char-equal ?~ (aref d 0))
5275 (setq newdl (cons d newdl))))
5276 (setq dirlist (nreverse newdl))))
5277 (tramp-send-command
5279 (format (concat "while read d; "
5280 "do if test -x $d/%s -a -f $d/%s; "
5281 "then echo tramp_executable $d/%s; "
5282 "break; fi; done <<'EOF'\n"
5283 "%s\nEOF")
5284 progname progname progname (mapconcat 'identity dirlist "\n")))
5285 (goto-char (point-max))
5286 (when (search-backward "tramp_executable " nil t)
5287 (skip-chars-forward "^ ")
5288 (skip-chars-forward " ")
5289 (setq result (buffer-substring
5290 (point) (tramp-compat-line-end-position)))))
5291 result)))
5293 (defun tramp-set-remote-path (vec)
5294 "Sets the remote environment PATH to existing directories.
5295 I.e., for each directory in `tramp-remote-path', it is tested
5296 whether it exists and if so, it is added to the environment
5297 variable PATH."
5298 (tramp-message vec 5 (format "Setting $PATH environment variable"))
5299 (tramp-send-command
5300 vec (format "PATH=%s; export PATH"
5301 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
5303 ;; ------------------------------------------------------------
5304 ;; -- Communication with external shell --
5305 ;; ------------------------------------------------------------
5307 (defun tramp-find-file-exists-command (vec)
5308 "Find a command on the remote host for checking if a file exists.
5309 Here, we are looking for a command which has zero exit status if the
5310 file exists and nonzero exit status otherwise."
5311 (let ((existing "/")
5312 (nonexisting
5313 (tramp-shell-quote-argument "/ this file does not exist "))
5314 result)
5315 ;; The algorithm is as follows: we try a list of several commands.
5316 ;; For each command, we first run `$cmd /' -- this should return
5317 ;; true, as the root directory always exists. And then we run
5318 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
5319 ;; does not exist. This should return false. We use the first
5320 ;; command we find that seems to work.
5321 ;; The list of commands to try is as follows:
5322 ;; `ls -d' This works on most systems, but NetBSD 1.4
5323 ;; has a bug: `ls' always returns zero exit
5324 ;; status, even for files which don't exist.
5325 ;; `test -e' Some Bourne shells have a `test' builtin
5326 ;; which does not know the `-e' option.
5327 ;; `/bin/test -e' For those, the `test' binary on disk normally
5328 ;; provides the option. Alas, the binary
5329 ;; is sometimes `/bin/test' and sometimes it's
5330 ;; `/usr/bin/test'.
5331 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
5332 (unless (or
5333 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
5334 (zerop (tramp-send-command-and-check
5335 vec (format "%s %s" result existing)))
5336 (not (zerop (tramp-send-command-and-check
5337 vec (format "%s %s" result nonexisting)))))
5338 (and (setq result "/bin/test -e")
5339 (zerop (tramp-send-command-and-check
5340 vec (format "%s %s" result existing)))
5341 (not (zerop (tramp-send-command-and-check
5342 vec (format "%s %s" result nonexisting)))))
5343 (and (setq result "/usr/bin/test -e")
5344 (zerop (tramp-send-command-and-check
5345 vec (format "%s %s" result existing)))
5346 (not (zerop (tramp-send-command-and-check
5347 vec (format "%s %s" result nonexisting)))))
5348 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
5349 (zerop (tramp-send-command-and-check
5350 vec (format "%s %s" result existing)))
5351 (not (zerop (tramp-send-command-and-check
5352 vec (format "%s %s" result nonexisting))))))
5353 (tramp-error
5354 vec 'file-error "Couldn't find command to check if file exists"))
5355 result))
5357 ;; CCC test ksh or bash found for tilde expansion?
5358 (defun tramp-find-shell (vec)
5359 "Opens a shell on the remote host which groks tilde expansion."
5360 (unless (tramp-get-connection-property vec "remote-shell" nil)
5361 (let (shell)
5362 (with-current-buffer (tramp-get-buffer vec)
5363 (tramp-send-command vec "echo ~root" t)
5364 (cond
5365 ((string-match "^~root$" (buffer-string))
5366 (setq shell
5367 (or (tramp-find-executable
5368 vec "bash" (tramp-get-remote-path vec) t)
5369 (tramp-find-executable
5370 vec "ksh" (tramp-get-remote-path vec) t)))
5371 (unless shell
5372 (tramp-error
5373 vec 'file-error
5374 "Couldn't find a shell which groks tilde expansion"))
5375 ;; Find arguments for this shell.
5376 (let ((alist tramp-sh-extra-args)
5377 item extra-args)
5378 (while (and alist (null extra-args))
5379 (setq item (pop alist))
5380 (when (string-match (car item) shell)
5381 (setq extra-args (cdr item))))
5382 (when extra-args (setq shell (concat shell " " extra-args))))
5383 (tramp-message
5384 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
5385 (let ((tramp-end-of-output "$ "))
5386 (tramp-send-command
5388 (format "PROMPT_COMMAND='' PS1='$ ' PS2='' PS3='' exec %s" shell)
5390 ;; Setting prompts.
5391 (tramp-message vec 5 "Setting remote shell prompt...")
5392 (tramp-send-command vec (format "PS1='%s'" tramp-end-of-output) t)
5393 (tramp-send-command vec "PS2=''" t)
5394 (tramp-send-command vec "PS3=''" t)
5395 (tramp-send-command vec "PROMPT_COMMAND=''" t)
5396 (tramp-message vec 5 "Setting remote shell prompt...done"))
5398 (t (tramp-message
5399 vec 5 "Remote `%s' groks tilde expansion, good"
5400 (tramp-get-method-parameter
5401 (tramp-file-name-method vec) 'tramp-remote-sh))
5402 (tramp-set-connection-property
5403 vec "remote-shell"
5404 (tramp-get-method-parameter
5405 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
5407 ;; ------------------------------------------------------------
5408 ;; -- Functions for establishing connection --
5409 ;; ------------------------------------------------------------
5411 ;; The following functions are actions to be taken when seeing certain
5412 ;; prompts from the remote host. See the variable
5413 ;; `tramp-actions-before-shell' for usage of these functions.
5415 (defun tramp-action-login (proc vec)
5416 "Send the login name."
5417 (when (not (stringp tramp-current-user))
5418 (save-window-excursion
5419 (let ((enable-recursive-minibuffers t))
5420 (pop-to-buffer (tramp-get-connection-buffer vec))
5421 (setq tramp-current-user (read-string (match-string 0))))))
5422 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
5423 (with-current-buffer (tramp-get-connection-buffer vec)
5424 (tramp-message vec 6 "\n%s" (buffer-string)))
5425 (tramp-send-string vec tramp-current-user))
5427 (defun tramp-action-password (proc vec)
5428 "Query the user for a password."
5429 (tramp-message vec 3 "Sending password")
5430 (tramp-enter-password proc))
5432 (defun tramp-action-succeed (proc vec)
5433 "Signal success in finding shell prompt."
5434 (throw 'tramp-action 'ok))
5436 (defun tramp-action-permission-denied (proc vec)
5437 "Signal permission denied."
5438 (kill-process proc)
5439 (throw 'tramp-action 'permission-denied))
5441 (defun tramp-action-yesno (proc vec)
5442 "Ask the user for confirmation using `yes-or-no-p'.
5443 Send \"yes\" to remote process on confirmation, abort otherwise.
5444 See also `tramp-action-yn'."
5445 (save-window-excursion
5446 (let ((enable-recursive-minibuffers t))
5447 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
5448 (unless (yes-or-no-p (match-string 0))
5449 (kill-process proc)
5450 (throw 'tramp-action 'permission-denied))
5451 (with-current-buffer (tramp-get-connection-buffer vec)
5452 (tramp-message vec 6 "\n%s" (buffer-string)))
5453 (tramp-send-string vec "yes"))))
5455 (defun tramp-action-yn (proc vec)
5456 "Ask the user for confirmation using `y-or-n-p'.
5457 Send \"y\" to remote process on confirmation, abort otherwise.
5458 See also `tramp-action-yesno'."
5459 (save-window-excursion
5460 (let ((enable-recursive-minibuffers t))
5461 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
5462 (unless (y-or-n-p (match-string 0))
5463 (kill-process proc)
5464 (throw 'tramp-action 'permission-denied))
5465 (with-current-buffer (tramp-get-connection-buffer vec)
5466 (tramp-message vec 6 "\n%s" (buffer-string)))
5467 (tramp-send-string vec "y"))))
5469 (defun tramp-action-terminal (proc vec)
5470 "Tell the remote host which terminal type to use.
5471 The terminal type can be configured with `tramp-terminal-type'."
5472 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
5473 (with-current-buffer (tramp-get-connection-buffer vec)
5474 (tramp-message vec 6 "\n%s" (buffer-string)))
5475 (tramp-send-string vec tramp-terminal-type))
5477 (defun tramp-action-process-alive (proc vec)
5478 "Check whether a process has finished."
5479 (unless (memq (process-status proc) '(run open))
5480 (throw 'tramp-action 'process-died)))
5482 (defun tramp-action-out-of-band (proc vec)
5483 "Check whether an out-of-band copy has finished."
5484 (cond ((and (memq (process-status proc) '(stop exit))
5485 (zerop (process-exit-status proc)))
5486 (tramp-message vec 3 "Process has finished.")
5487 (throw 'tramp-action 'ok))
5488 ((or (and (memq (process-status proc) '(stop exit))
5489 (not (zerop (process-exit-status proc))))
5490 (memq (process-status proc) '(signal)))
5491 ;; `scp' could have copied correctly, but set modes could have failed.
5492 ;; This can be ignored.
5493 (with-current-buffer (process-buffer proc)
5494 (goto-char (point-min))
5495 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
5496 (progn
5497 (tramp-message vec 5 "'set mode' error ignored.")
5498 (tramp-message vec 3 "Process has finished.")
5499 (throw 'tramp-action 'ok))
5500 (tramp-message vec 3 "Process has died.")
5501 (throw 'tramp-action 'process-died))))
5502 (t nil)))
5504 ;; Functions for processing the actions.
5506 (defun tramp-process-one-action (proc vec actions)
5507 "Wait for output from the shell and perform one action."
5508 (let (found todo item pattern action)
5509 (while (not found)
5510 ;; Reread output once all actions have been performed.
5511 ;; Obviously, the output was not complete.
5512 (tramp-accept-process-output proc 1)
5513 (setq todo actions)
5514 (while todo
5515 (setq item (pop todo))
5516 (setq pattern (concat (symbol-value (nth 0 item)) "\\'"))
5517 (setq action (nth 1 item))
5518 (tramp-message
5519 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
5520 (when (tramp-check-for-regexp proc pattern)
5521 (tramp-message vec 5 "Call `%s'" (symbol-name action))
5522 (setq found (funcall action proc vec)))))
5523 found))
5525 (defun tramp-process-actions (proc vec actions &optional timeout)
5526 "Perform actions until success or TIMEOUT."
5527 (let (exit)
5528 (while (not exit)
5529 (tramp-message proc 3 "Waiting for prompts from remote shell")
5530 (setq exit
5531 (catch 'tramp-action
5532 (if timeout
5533 (with-timeout (timeout)
5534 (tramp-process-one-action proc vec actions))
5535 (tramp-process-one-action proc vec actions)))))
5536 (with-current-buffer (tramp-get-connection-buffer vec)
5537 (tramp-message vec 6 "\n%s" (buffer-string)))
5538 (unless (eq exit 'ok)
5539 (tramp-clear-passwd vec)
5540 (tramp-error-with-buffer
5541 nil vec 'file-error
5542 (cond
5543 ((eq exit 'permission-denied) "Permission denied")
5544 ((eq exit 'process-died) "Process died")
5545 (t "Login failed"))))))
5547 ;; Utility functions.
5549 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
5550 "Like `accept-process-output' for Tramp processes.
5551 This is needed in order to hide `last-coding-system-used', which is set
5552 for process communication also."
5553 (with-current-buffer (process-buffer proc)
5554 (tramp-message proc 10 "%s %s" proc (process-status proc))
5555 (let (buffer-read-only last-coding-system-used)
5556 ;; Under Windows XP, accept-process-output doesn't return
5557 ;; sometimes. So we add an additional timeout.
5558 (with-timeout ((or timeout 1))
5559 (accept-process-output proc timeout timeout-msecs)))
5560 (tramp-message proc 10 "\n%s" (buffer-string))))
5562 (defun tramp-check-for-regexp (proc regexp)
5563 "Check whether REGEXP is contained in process buffer of PROC.
5564 Erase echoed commands if exists."
5565 (with-current-buffer (process-buffer proc)
5566 (goto-char (point-min))
5567 ;; Check whether we need to remove echo output.
5568 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
5569 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
5570 (let ((begin (match-beginning 0)))
5571 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
5572 ;; Discard echo from remote output.
5573 (tramp-set-connection-property proc "check-remote-echo" nil)
5574 (tramp-message proc 5 "echo-mark found")
5575 (forward-line)
5576 (delete-region begin (point))
5577 (goto-char (point-min)))))
5578 ;; No echo to be handled, now we can look for the regexp.
5579 (when (not (tramp-get-connection-property proc "check-remote-echo" nil))
5580 (re-search-forward regexp nil t))))
5582 (defun tramp-wait-for-regexp (proc timeout regexp)
5583 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
5584 Expects the output of PROC to be sent to the current buffer. Returns
5585 the string that matched, or nil. Waits indefinitely if TIMEOUT is
5586 nil."
5587 (with-current-buffer (process-buffer proc)
5588 (let ((found (tramp-check-for-regexp proc regexp))
5589 (start-time (current-time)))
5590 (cond (timeout
5591 ;; Work around a bug in XEmacs 21, where the timeout
5592 ;; expires faster than it should. This degenerates
5593 ;; to polling for buggy XEmacsen, but oh, well.
5594 (while (and (not found)
5595 (< (tramp-time-diff (current-time) start-time)
5596 timeout))
5597 (with-timeout (timeout)
5598 (while (not found)
5599 (tramp-accept-process-output proc 1)
5600 (unless (memq (process-status proc) '(run open))
5601 (tramp-error-with-buffer
5602 nil proc 'file-error "Process has died"))
5603 (setq found (tramp-check-for-regexp proc regexp))))))
5605 (while (not found)
5606 (tramp-accept-process-output proc 1)
5607 (unless (memq (process-status proc) '(run open))
5608 (tramp-error-with-buffer
5609 nil proc 'file-error "Process has died"))
5610 (setq found (tramp-check-for-regexp proc regexp)))))
5611 (tramp-message proc 6 "\n%s" (buffer-string))
5612 (when (not found)
5613 (if timeout
5614 (tramp-error
5615 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
5616 regexp timeout)
5617 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
5618 found)))
5620 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
5621 "Wait for shell prompt and barf if none appears.
5622 Looks at process PROC to see if a shell prompt appears in TIMEOUT
5623 seconds. If not, it produces an error message with the given ERROR-ARGS."
5624 (unless
5625 (tramp-wait-for-regexp
5626 proc timeout
5627 (format
5628 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
5629 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
5631 ;; We don't call `tramp-send-string' in order to hide the password
5632 ;; from the debug buffer, and because end-of-line handling of the
5633 ;; string.
5634 (defun tramp-enter-password (proc)
5635 "Prompt for a password and send it to the remote end."
5636 (process-send-string
5637 proc (concat (tramp-read-passwd proc)
5638 (or (tramp-get-method-parameter
5639 tramp-current-method
5640 'tramp-password-end-of-line)
5641 tramp-default-password-end-of-line))))
5643 (defun tramp-process-sentinel (proc event)
5644 "Process sentinel for Tramp processes."
5645 (when (memq (process-status proc) '(stop exit signal))
5646 (tramp-flush-connection-property proc)
5647 ;; The "Connection closed" and "exit" messages disturb the output
5648 ;; for asynchronous processes. That's why we have echoed the
5649 ;; Tramp prompt at the end. Trailing messages can be removed.
5650 (let ((buf (process-buffer proc)))
5651 (when (buffer-live-p buf)
5652 (with-current-buffer buf
5653 (goto-char (point-max))
5654 (re-search-backward
5655 (mapconcat 'identity (split-string tramp-end-of-output "\n")
5656 "\r?\n")
5657 (line-beginning-position -8) t)
5658 (delete-region (point) (point-max)))))))
5660 (defun tramp-open-connection-setup-interactive-shell (proc vec)
5661 "Set up an interactive shell.
5662 Mainly sets the prompt and the echo correctly. PROC is the shell
5663 process to set up. VEC specifies the connection."
5664 (let ((tramp-end-of-output "$ "))
5665 ;; It is useful to set the prompt in the following command because
5666 ;; some people have a setting for $PS1 which /bin/sh doesn't know
5667 ;; about and thus /bin/sh will display a strange prompt. For
5668 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
5669 ;; display the current working directory but /bin/sh will display
5670 ;; a dollar sign. The following command line sets $PS1 to a sane
5671 ;; value, and works under Bourne-ish shells as well as csh-like
5672 ;; shells. Daniel Pittman reports that the unusual positioning of
5673 ;; the single quotes makes it work under `rc', too. We also unset
5674 ;; the variable $ENV because that is read by some sh
5675 ;; implementations (eg, bash when called as sh) on startup; this
5676 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
5677 ;; is another way to set the prompt in /bin/bash, it must be
5678 ;; discarded as well.
5679 (tramp-send-command
5681 (format
5682 "exec env ENV='' PROMPT_COMMAND='' PS1='$ ' PS2='' PS3='' %s"
5683 (tramp-get-method-parameter
5684 (tramp-file-name-method vec) 'tramp-remote-sh))
5687 ;; Disable echo.
5688 (tramp-message vec 5 "Setting up remote shell environment")
5689 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
5690 ;; Check whether the echo has really been disabled. Some
5691 ;; implementations, like busybox of embedded GNU/Linux, don't
5692 ;; support disabling.
5693 (tramp-send-command vec "echo foo" t)
5694 (with-current-buffer (process-buffer proc)
5695 (goto-char (point-min))
5696 (when (looking-at "echo foo")
5697 (tramp-set-connection-property proc "remote-echo" t)
5698 (tramp-message vec 5 "Remote echo still on. Ok.")
5699 ;; Make sure backspaces and their echo are enabled and no line
5700 ;; width magic interferes with them.
5701 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
5703 (tramp-message vec 5 "Setting shell prompt")
5704 ;; We can set $PS1 to `tramp-end-of-output' only when the echo has
5705 ;; been disabled. Otherwise, the echo of the command would be
5706 ;; regarded as prompt already.
5707 (tramp-send-command vec (format "PS1='%s'" tramp-end-of-output) t)
5708 (tramp-send-command vec "PS2=''" t)
5709 (tramp-send-command vec "PS3=''" t)
5710 (tramp-send-command vec "PROMPT_COMMAND=''" t)
5712 ;; Try to set up the coding system correctly.
5713 ;; CCC this can't be the right way to do it. Hm.
5714 (tramp-message vec 5 "Determining coding system")
5715 (tramp-send-command vec "echo foo ; echo bar" t)
5716 (with-current-buffer (process-buffer proc)
5717 (goto-char (point-min))
5718 (if (featurep 'mule)
5719 ;; Use MULE to select the right EOL convention for communicating
5720 ;; with the process.
5721 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
5722 (cons 'undecided 'undecided)))
5723 cs-decode cs-encode)
5724 (when (symbolp cs) (setq cs (cons cs cs)))
5725 (setq cs-decode (car cs))
5726 (setq cs-encode (cdr cs))
5727 (unless cs-decode (setq cs-decode 'undecided))
5728 (unless cs-encode (setq cs-encode 'undecided))
5729 (setq cs-encode (tramp-coding-system-change-eol-conversion
5730 cs-encode 'unix))
5731 (when (search-forward "\r" nil t)
5732 (setq cs-decode (tramp-coding-system-change-eol-conversion
5733 cs-decode 'dos)))
5734 (funcall (symbol-function 'set-buffer-process-coding-system)
5735 cs-decode cs-encode))
5736 ;; Look for ^M and do something useful if found.
5737 (when (search-forward "\r" nil t)
5738 ;; We have found a ^M but cannot frob the process coding system
5739 ;; because we're running on a non-MULE Emacs. Let's try
5740 ;; stty, instead.
5741 (tramp-send-command vec "stty -onlcr" t))))
5742 (tramp-send-command vec "set +o vi +o emacs" t)
5744 ;; Check whether the output of "uname -sr" has been changed. If
5745 ;; yes, this is a strong indication that we must expire all
5746 ;; connection properties.
5747 (tramp-message vec 5 "Checking system information")
5748 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
5749 (new-uname
5750 (tramp-set-connection-property
5751 vec "uname"
5752 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
5753 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
5754 (funcall (symbol-function 'tramp-cleanup-connection) vec)
5755 (signal
5756 'quit
5757 (list (format
5758 "Connection reset, because remote host changed from `%s' to `%s'"
5759 old-uname new-uname)))))
5761 ;; Check whether the remote host suffers from buggy
5762 ;; `send-process-string'. This is known for FreeBSD (see comment in
5763 ;; `send_process', file process.c). I've tested sending 624 bytes
5764 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
5765 ;; this host type is detected locally. It cannot handle remote
5766 ;; hosts, though.
5767 (with-connection-property proc "chunksize"
5768 (cond
5769 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
5770 tramp-chunksize)
5772 (tramp-message
5773 vec 5 "Checking remote host type for `send-process-string' bug")
5774 (if (string-match
5775 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
5776 500 0))))
5778 ;; Set remote PATH variable.
5779 (tramp-set-remote-path vec)
5781 ;; Search for a good shell before searching for a command which
5782 ;; checks if a file exists. This is done because Tramp wants to use
5783 ;; "test foo; echo $?" to check if various conditions hold, and
5784 ;; there are buggy /bin/sh implementations which don't execute the
5785 ;; "echo $?" part if the "test" part has an error. In particular,
5786 ;; the Solaris /bin/sh is a problem. I'm betting that all systems
5787 ;; with buggy /bin/sh implementations will have a working bash or
5788 ;; ksh. Whee...
5789 (tramp-find-shell vec)
5791 ;; Disable unexpected output.
5792 (tramp-send-command vec "mesg n; biff n" t)
5794 ;; Set the environment.
5795 (tramp-message vec 5 "Setting default environment")
5796 (let ((env (copy-sequence tramp-remote-process-environment))
5797 unset item)
5798 (while env
5799 (setq item (split-string (car env) "="))
5800 (if (and (stringp (cadr item)) (not (string-equal (cadr item) "")))
5801 (tramp-send-command
5802 vec (format "%s=%s; export %s" (car item) (cadr item) (car item)) t)
5803 (push (car item) unset))
5804 (setq env (cdr env)))
5805 (when unset
5806 (tramp-send-command
5807 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
5809 ;; CCC: We should either implement a Perl version of base64 encoding
5810 ;; and decoding. Then we just use that in the last item. The other
5811 ;; alternative is to use the Perl version of UU encoding. But then
5812 ;; we need a Lisp version of uuencode.
5814 ;; Old text from documentation of tramp-methods:
5815 ;; Using a uuencode/uudecode inline method is discouraged, please use one
5816 ;; of the base64 methods instead since base64 encoding is much more
5817 ;; reliable and the commands are more standardized between the different
5818 ;; Unix versions. But if you can't use base64 for some reason, please
5819 ;; note that the default uudecode command does not work well for some
5820 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
5821 ;; the following command for uudecode:
5823 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
5825 ;; For Irix, no solution is known yet.
5827 (defconst tramp-local-coding-commands
5828 '((b64 base64-encode-region base64-decode-region)
5829 (uu tramp-uuencode-region uudecode-decode-region)
5830 (pack
5831 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
5832 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
5833 "List of local coding commands for inline transfer.
5834 Each item is a list that looks like this:
5836 \(FORMAT ENCODING DECODING)
5838 FORMAT is symbol describing the encoding/decoding format. It can be
5839 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
5841 ENCODING and DECODING can be strings, giving commands, or symbols,
5842 giving functions. If they are strings, then they can contain
5843 the \"%s\" format specifier. If that specifier is present, the input
5844 filename will be put into the command line at that spot. If the
5845 specifier is not present, the input should be read from standard
5846 input.
5848 If they are functions, they will be called with two arguments, start
5849 and end of region, and are expected to replace the region contents
5850 with the encoded or decoded results, respectively.")
5852 (defconst tramp-remote-coding-commands
5853 '((b64 "mimencode -b" "mimencode -u -b")
5854 (b64 "mmencode -b" "mmencode -u -b")
5855 (b64 "recode data..base64" "recode base64..data")
5856 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
5857 (b64 tramp-perl-encode tramp-perl-decode)
5858 (uu "uuencode xxx" "uudecode -o /dev/stdout")
5859 (uu "uuencode xxx" "uudecode -o -")
5860 (uu "uuencode xxx" "uudecode -p")
5861 (uu "uuencode xxx" tramp-uudecode)
5862 (pack
5863 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
5864 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
5865 "List of remote coding commands for inline transfer.
5866 Each item is a list that looks like this:
5868 \(FORMAT ENCODING DECODING)
5870 FORMAT is symbol describing the encoding/decoding format. It can be
5871 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
5873 ENCODING and DECODING can be strings, giving commands, or symbols,
5874 giving variables. If they are strings, then they can contain
5875 the \"%s\" format specifier. If that specifier is present, the input
5876 filename will be put into the command line at that spot. If the
5877 specifier is not present, the input should be read from standard
5878 input.
5880 If they are variables, this variable is a string containing a Perl
5881 implementation for this functionality. This Perl program will be transferred
5882 to the remote host, and it is avalible as shell function with the same name.")
5884 (defun tramp-find-inline-encoding (vec)
5885 "Find an inline transfer encoding that works.
5886 Goes through the list `tramp-local-coding-commands' and
5887 `tramp-remote-coding-commands'."
5888 (save-excursion
5889 (let ((local-commands tramp-local-coding-commands)
5890 (magic "xyzzy")
5891 loc-enc loc-dec rem-enc rem-dec litem ritem found)
5892 (while (and local-commands (not found))
5893 (setq litem (pop local-commands))
5894 (catch 'wont-work-local
5895 (let ((format (nth 0 litem))
5896 (remote-commands tramp-remote-coding-commands))
5897 (setq loc-enc (nth 1 litem))
5898 (setq loc-dec (nth 2 litem))
5899 ;; If the local encoder or decoder is a string, the
5900 ;; corresponding command has to work locally.
5901 (if (not (stringp loc-enc))
5902 (tramp-message
5903 vec 5 "Checking local encoding function `%s'" loc-enc)
5904 (tramp-message
5905 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
5906 (unless (zerop (tramp-call-local-coding-command
5907 loc-enc nil nil))
5908 (throw 'wont-work-local nil)))
5909 (if (not (stringp loc-dec))
5910 (tramp-message
5911 vec 5 "Checking local decoding function `%s'" loc-dec)
5912 (tramp-message
5913 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
5914 (unless (zerop (tramp-call-local-coding-command
5915 loc-dec nil nil))
5916 (throw 'wont-work-local nil)))
5917 ;; Search for remote coding commands with the same format
5918 (while (and remote-commands (not found))
5919 (setq ritem (pop remote-commands))
5920 (catch 'wont-work-remote
5921 (when (equal format (nth 0 ritem))
5922 (setq rem-enc (nth 1 ritem))
5923 (setq rem-dec (nth 2 ritem))
5924 ;; Check if remote encoding and decoding commands can be
5925 ;; called remotely with null input and output. This makes
5926 ;; sure there are no syntax errors and the command is really
5927 ;; found. Note that we do not redirect stdout to /dev/null,
5928 ;; for two reasons: when checking the decoding command, we
5929 ;; actually check the output it gives. And also, when
5930 ;; redirecting "mimencode" output to /dev/null, then as root
5931 ;; it might change the permissions of /dev/null!
5932 (when (not (stringp rem-enc))
5933 (let ((name (symbol-name rem-enc)))
5934 (while (string-match (regexp-quote "-") name)
5935 (setq name (replace-match "_" nil t name)))
5936 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
5937 (setq rem-enc name)))
5938 (tramp-message
5939 vec 5
5940 "Checking remote encoding command `%s' for sanity" rem-enc)
5941 (unless (zerop (tramp-send-command-and-check
5942 vec (format "%s </dev/null" rem-enc) t))
5943 (throw 'wont-work-remote nil))
5945 (when (not (stringp rem-dec))
5946 (let ((name (symbol-name rem-dec)))
5947 (while (string-match (regexp-quote "-") name)
5948 (setq name (replace-match "_" nil t name)))
5949 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
5950 (setq rem-dec name)))
5951 (tramp-message
5952 vec 5
5953 "Checking remote decoding command `%s' for sanity" rem-dec)
5954 (unless (zerop (tramp-send-command-and-check
5956 (format "echo %s | %s | %s"
5957 magic rem-enc rem-dec) t))
5958 (throw 'wont-work-remote nil))
5960 (with-current-buffer (tramp-get-buffer vec)
5961 (goto-char (point-min))
5962 (unless (looking-at (regexp-quote magic))
5963 (throw 'wont-work-remote nil)))
5965 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
5966 (setq rem-enc (nth 1 ritem))
5967 (setq rem-dec (nth 2 ritem))
5968 (setq found t)))))))
5970 ;; Did we find something? If not, issue an error.
5971 (unless found
5972 (kill-process (tramp-get-connection-process vec))
5973 (tramp-error
5974 vec 'file-error "Couldn't find an inline transfer encoding"))
5976 ;; Set connection properties.
5977 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
5978 (tramp-set-connection-property vec "local-encoding" loc-enc)
5979 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
5980 (tramp-set-connection-property vec "local-decoding" loc-dec)
5981 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
5982 (tramp-set-connection-property vec "remote-encoding" rem-enc)
5983 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
5984 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
5986 (defun tramp-call-local-coding-command (cmd input output)
5987 "Call the local encoding or decoding command.
5988 If CMD contains \"%s\", provide input file INPUT there in command.
5989 Otherwise, INPUT is passed via standard input.
5990 INPUT can also be nil which means `/dev/null'.
5991 OUTPUT can be a string (which specifies a filename), or t (which
5992 means standard output and thus the current buffer), or nil (which
5993 means discard it)."
5994 (tramp-local-call-process
5995 tramp-encoding-shell
5996 (when (and input (not (string-match "%s" cmd))) input)
5997 (if (eq output t) t nil)
5999 tramp-encoding-command-switch
6000 (concat
6001 (if (string-match "%s" cmd) (format cmd input) cmd)
6002 (if (stringp output) (concat "> " output) ""))))
6004 (defun tramp-compute-multi-hops (vec)
6005 "Expands VEC according to `tramp-default-proxies-alist'.
6006 Gateway hops are already opened."
6007 (let ((target-alist `(,vec))
6008 (choices tramp-default-proxies-alist)
6009 item proxy)
6011 ;; Look for proxy hosts to be passed.
6012 (while choices
6013 (setq item (pop choices)
6014 proxy (nth 2 item))
6015 (when (and
6016 ;; host
6017 (string-match (or (nth 0 item) "")
6018 (or (tramp-file-name-host (car target-alist)) ""))
6019 ;; user
6020 (string-match (or (nth 1 item) "")
6021 (or (tramp-file-name-user (car target-alist)) "")))
6022 (if (null proxy)
6023 ;; No more hops needed.
6024 (setq choices nil)
6025 ;; Replace placeholders.
6026 (setq proxy
6027 (format-spec
6028 proxy
6029 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
6030 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
6031 (with-parsed-tramp-file-name proxy l
6032 ;; Add the hop.
6033 (add-to-list 'target-alist l)
6034 ;; Start next search.
6035 (setq choices tramp-default-proxies-alist)))))
6037 ;; Handle gateways.
6038 (when (and (boundp 'tramp-gw-tunnel-method)
6039 (string-match (format
6040 "^\\(%s\\|%s\\)$"
6041 (symbol-value 'tramp-gw-tunnel-method)
6042 (symbol-value 'tramp-gw-socks-method))
6043 (tramp-file-name-method (car target-alist))))
6044 (let ((gw (pop target-alist))
6045 (hop (pop target-alist)))
6046 ;; Is the method prepared for gateways?
6047 (unless (tramp-get-method-parameter
6048 (tramp-file-name-method hop) 'tramp-default-port)
6049 (tramp-error
6050 vec 'file-error
6051 "Method `%s' is not supported for gateway access."
6052 (tramp-file-name-method hop)))
6053 ;; Add default port if needed.
6054 (unless
6055 (string-match
6056 tramp-host-with-port-regexp (tramp-file-name-host hop))
6057 (aset hop 2
6058 (concat
6059 (tramp-file-name-host hop) tramp-prefix-port-format
6060 (number-to-string
6061 (tramp-get-method-parameter
6062 (tramp-file-name-method hop) 'tramp-default-port)))))
6063 ;; Open the gateway connection.
6064 (add-to-list
6065 'target-alist
6066 (vector
6067 (tramp-file-name-method hop) (tramp-file-name-user hop)
6068 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
6069 ;; For the password prompt, we need the correct values.
6070 ;; Therefore, we must remember the gateway vector. But we
6071 ;; cannot do it as connection property, because it shouldn't
6072 ;; be persistent. And we have no started process yet either.
6073 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
6075 ;; Foreign and out-of-band methods are not supported for multi-hops.
6076 (when (cdr target-alist)
6077 (setq choices target-alist)
6078 (while choices
6079 (setq item (pop choices))
6080 (when
6082 (not
6083 (tramp-get-method-parameter
6084 (tramp-file-name-method item) 'tramp-login-program))
6085 (tramp-get-method-parameter
6086 (tramp-file-name-method item) 'tramp-copy-program))
6087 (tramp-error
6088 vec 'file-error
6089 "Method `%s' is not supported for multi-hops."
6090 (tramp-file-name-method item)))))
6092 ;; In case the host name is not used for the remote shell
6093 ;; command, the user could be misguided by applying a random
6094 ;; hostname.
6095 (let* ((v (car target-alist))
6096 (method (tramp-file-name-method v))
6097 (host (tramp-file-name-host v)))
6098 (unless
6100 ;; There are multi-hops.
6101 (cdr target-alist)
6102 ;; The host name is used for the remote shell command.
6103 (member
6104 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
6105 ;; The host is local. We cannot use `tramp-local-host-p'
6106 ;; here, because it opens a connection as well.
6107 (string-match
6108 (concat "^" (regexp-opt (list "localhost" (system-name)) t) "$")
6109 host))
6110 (tramp-error
6111 v 'file-error
6112 "Host `%s' looks like a remote host, `%s' can only use the local host"
6113 host method)))
6115 ;; Result.
6116 target-alist))
6118 (defun tramp-maybe-open-connection (vec)
6119 "Maybe open a connection VEC.
6120 Does not do anything if a connection is already open, but re-opens the
6121 connection if a previous connection has died for some reason."
6122 (let ((p (tramp-get-connection-process vec))
6123 (process-environment (copy-sequence process-environment)))
6125 ;; If too much time has passed since last command was sent, look
6126 ;; whether process is still alive. If it isn't, kill it. When
6127 ;; using ssh, it can sometimes happen that the remote end has hung
6128 ;; up but the local ssh client doesn't recognize this until it
6129 ;; tries to send some data to the remote end. So that's why we
6130 ;; try to send a command from time to time, then look again
6131 ;; whether the process is really alive.
6132 (condition-case nil
6133 (when (and (> (tramp-time-diff
6134 (current-time)
6135 (tramp-get-connection-property
6136 p "last-cmd-time" '(0 0 0)))
6138 p (processp p) (memq (process-status p) '(run open)))
6139 (tramp-send-command vec "echo are you awake" t t)
6140 (unless (and (memq (process-status p) '(run open))
6141 (tramp-wait-for-output p 10))
6142 ;; The error will be catched locally.
6143 (tramp-error vec 'file-error "Awake did fail")))
6144 (file-error
6145 (tramp-flush-connection-property vec)
6146 (tramp-flush-connection-property p)
6147 (delete-process p)
6148 (setq p nil)))
6150 ;; New connection must be opened.
6151 (unless (and p (processp p) (memq (process-status p) '(run open)))
6153 ;; We call `tramp-get-buffer' in order to get a debug buffer for
6154 ;; messages from the beginning.
6155 (tramp-get-buffer vec)
6156 (if (zerop (length (tramp-file-name-user vec)))
6157 (tramp-message
6158 vec 3 "Opening connection for %s using %s..."
6159 (tramp-file-name-host vec)
6160 (tramp-file-name-method vec))
6161 (tramp-message
6162 vec 3 "Opening connection for %s@%s using %s..."
6163 (tramp-file-name-user vec)
6164 (tramp-file-name-host vec)
6165 (tramp-file-name-method vec)))
6167 ;; Start new process.
6168 (when (and p (processp p))
6169 (delete-process p))
6170 (setenv "TERM" tramp-terminal-type)
6171 (setenv "LC_ALL" "C")
6172 (setenv "PROMPT_COMMAND")
6173 (setenv "PS1" "$ ")
6174 (let* ((target-alist (tramp-compute-multi-hops vec))
6175 (process-connection-type tramp-process-connection-type)
6176 (process-adaptive-read-buffering nil)
6177 (coding-system-for-read nil)
6178 ;; This must be done in order to avoid our file name handler.
6179 (p (let ((default-directory
6180 (tramp-compat-temporary-file-directory)))
6181 (start-process
6182 (or (tramp-get-connection-property vec "process-name" nil)
6183 (tramp-buffer-name vec))
6184 (tramp-get-connection-buffer vec)
6185 tramp-encoding-shell)))
6186 (first-hop t))
6188 (tramp-message
6189 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
6191 ;; Check whether process is alive.
6192 (set-process-sentinel p 'tramp-process-sentinel)
6193 (tramp-set-process-query-on-exit-flag p nil)
6194 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
6195 (tramp-barf-if-no-shell-prompt
6196 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
6198 ;; Now do all the connections as specified.
6199 (while target-alist
6200 (let* ((hop (car target-alist))
6201 (l-method (tramp-file-name-method hop))
6202 (l-user (tramp-file-name-user hop))
6203 (l-host (tramp-file-name-host hop))
6204 (l-port nil)
6205 (login-program
6206 (tramp-get-method-parameter l-method 'tramp-login-program))
6207 (login-args
6208 (tramp-get-method-parameter l-method 'tramp-login-args))
6209 (gw-args
6210 (tramp-get-method-parameter l-method 'tramp-gw-args))
6211 (gw (tramp-get-file-property hop "" "gateway" nil))
6212 (g-method (and gw (tramp-file-name-method gw)))
6213 (g-user (and gw (tramp-file-name-user gw)))
6214 (g-host (and gw (tramp-file-name-host gw)))
6215 (command login-program)
6216 ;; We don't create the temporary file. In fact, it
6217 ;; is just a prefix for the ControlPath option of
6218 ;; ssh; the real temporary file has another name, and
6219 ;; it is created and protected by ssh. It is also
6220 ;; removed by ssh, when the connection is closed.
6221 (tmpfile
6222 (tramp-set-connection-property
6223 p "temp-file"
6224 (make-temp-name
6225 (expand-file-name
6226 tramp-temp-name-prefix
6227 (tramp-compat-temporary-file-directory)))))
6228 spec)
6230 ;; Add gateway arguments if necessary.
6231 (when (and gw gw-args)
6232 (setq login-args (append login-args gw-args)))
6234 ;; Check for port number. Until now, there's no need for handling
6235 ;; like method, user, host.
6236 (when (string-match tramp-host-with-port-regexp l-host)
6237 (setq l-port (match-string 2 l-host)
6238 l-host (match-string 1 l-host)))
6240 ;; Set variables for computing the prompt for reading password.
6241 ;; They can also be derived from a gatewy.
6242 (setq tramp-current-method (or g-method l-method)
6243 tramp-current-user (or g-user l-user)
6244 tramp-current-host (or g-host l-host))
6246 ;; Replace login-args place holders.
6247 (setq
6248 l-host (or l-host "")
6249 l-user (or l-user "")
6250 l-port (or l-port "")
6251 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
6252 (?t . ,tmpfile))
6253 command
6254 (concat
6255 command " "
6256 (mapconcat
6257 '(lambda (x)
6258 (setq x (mapcar '(lambda (y) (format-spec y spec)) x))
6259 (unless (member "" x) (mapconcat 'identity x " ")))
6260 login-args " ")
6261 ;; String to detect failed connection. Every single word must
6262 ;; be enclosed with '\"'; otherwise it is detected
6263 ;; during connection setup.
6264 ;; Local shell could be a Windows COMSPEC. It doesn't know
6265 ;; the ";" syntax, but we must exit always for `start-process'.
6266 ;; "exec" does not work either.
6267 (if first-hop
6268 " && exit || exit"
6269 "; echo \"Tramp\" \"connection\" \"closed\"; sleep 1"))
6270 ;; We don't reach a Windows shell. Could be initial only.
6271 first-hop nil)
6273 ;; Send the command.
6274 (tramp-message vec 3 "Sending command `%s'" command)
6275 (tramp-send-command vec command t t)
6276 (tramp-process-actions p vec tramp-actions-before-shell 60)
6277 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
6278 ;; Next hop.
6279 (setq target-alist (cdr target-alist)))
6281 ;; Make initial shell settings.
6282 (tramp-open-connection-setup-interactive-shell p vec)))))
6284 (defun tramp-send-command (vec command &optional neveropen nooutput)
6285 "Send the COMMAND to connection VEC.
6286 Erases temporary buffer before sending the command. If optional
6287 arg NEVEROPEN is non-nil, never try to open the connection. This
6288 is meant to be used from `tramp-maybe-open-connection' only. The
6289 function waits for output unless NOOUTPUT is set."
6290 (unless neveropen (tramp-maybe-open-connection vec))
6291 (let ((p (tramp-get-connection-process vec)))
6292 (when (tramp-get-connection-property p "remote-echo" nil)
6293 ;; We mark the command string that it can be erased in the output buffer.
6294 (tramp-set-connection-property p "check-remote-echo" t)
6295 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
6296 (tramp-message vec 6 "%s" command)
6297 (tramp-send-string vec command)
6298 (unless nooutput (tramp-wait-for-output p))))
6300 (defun tramp-wait-for-output (proc &optional timeout)
6301 "Wait for output from remote rsh command."
6302 (with-current-buffer (process-buffer proc)
6303 ;; Initially, `tramp-end-of-output' is "$ ". There might be
6304 ;; leading escape sequences, which must be ignored.
6305 (let* ((regexp
6306 (if (string-match (regexp-quote "\n") tramp-end-of-output)
6307 (mapconcat
6308 'identity (split-string tramp-end-of-output "\n") "\r?\n")
6309 (format "^[^$\n]*%s\r?$" (regexp-quote tramp-end-of-output))))
6310 (found (tramp-wait-for-regexp proc timeout regexp)))
6311 (if found
6312 (let (buffer-read-only)
6313 (goto-char (point-max))
6314 (re-search-backward regexp nil t)
6315 (delete-region (point) (point-max)))
6316 (if timeout
6317 (tramp-error
6318 proc 'file-error
6319 "[[Remote prompt `%s' not found in %d secs]]"
6320 tramp-end-of-output timeout)
6321 (tramp-error
6322 proc 'file-error
6323 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
6324 ;; Return value is whether end-of-output sentinel was found.
6325 found)))
6327 (defun tramp-send-command-and-check (vec command &optional subshell)
6328 "Run COMMAND and check its exit status.
6329 Sends `echo $?' along with the COMMAND for checking the exit status. If
6330 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
6332 If the optional argument SUBSHELL is non-nil, the command is executed in
6333 a subshell, ie surrounded by parentheses."
6334 (tramp-send-command
6336 (concat (if subshell "( " "")
6337 command
6338 (if command " 2>/dev/null; " "")
6339 "echo tramp_exit_status $?"
6340 (if subshell " )" " ")))
6341 (with-current-buffer (tramp-get-connection-buffer vec)
6342 (goto-char (point-max))
6343 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
6344 (tramp-error
6345 vec 'file-error "Couldn't find exit status of `%s'" command))
6346 (skip-chars-forward "^ ")
6347 (prog1
6348 (read (current-buffer))
6349 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
6351 (defun tramp-barf-unless-okay (vec command fmt &rest args)
6352 "Run COMMAND, check exit status, throw error if exit status not okay.
6353 Similar to `tramp-send-command-and-check' but accepts two more arguments
6354 FMT and ARGS which are passed to `error'."
6355 (unless (zerop (tramp-send-command-and-check vec command))
6356 (apply 'tramp-error vec 'file-error fmt args)))
6358 (defun tramp-send-command-and-read (vec command)
6359 "Run COMMAND and return the output, which must be a Lisp expression.
6360 In case there is no valid Lisp expression, it raises an error"
6361 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
6362 (with-current-buffer (tramp-get-connection-buffer vec)
6363 ;; Read the expression.
6364 (goto-char (point-min))
6365 (condition-case nil
6366 (prog1 (read (current-buffer))
6367 ;; Error handling.
6368 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
6369 (error nil)))
6370 (error (tramp-error
6371 vec 'file-error
6372 "`%s' does not return a valid Lisp expression: `%s'"
6373 command (buffer-string))))))
6375 ;; It seems that Tru64 Unix does not like it if long strings are sent
6376 ;; to it in one go. (This happens when sending the Perl
6377 ;; `file-attributes' implementation, for instance.) Therefore, we
6378 ;; have this function which sends the string in chunks.
6379 (defun tramp-send-string (vec string)
6380 "Send the STRING via connection VEC.
6382 The STRING is expected to use Unix line-endings, but the lines sent to
6383 the remote host use line-endings as defined in the variable
6384 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
6385 (let* ((p (tramp-get-connection-process vec))
6386 (chunksize (tramp-get-connection-property p "chunksize" nil)))
6387 (unless p
6388 (tramp-error
6389 vec 'file-error "Can't send string to remote host -- not logged in"))
6390 (tramp-set-connection-property p "last-cmd-time" (current-time))
6391 (tramp-message vec 10 "%s" string)
6392 (with-current-buffer (tramp-get-connection-buffer vec)
6393 ;; Clean up the buffer. We cannot call `erase-buffer' because
6394 ;; narrowing might be in effect.
6395 (let (buffer-read-only) (delete-region (point-min) (point-max)))
6396 ;; Replace "\n" by `tramp-rsh-end-of-line'.
6397 (setq string
6398 (mapconcat 'identity
6399 (split-string string "\n")
6400 tramp-rsh-end-of-line))
6401 (unless (or (string= string "")
6402 (string-equal (substring string -1) tramp-rsh-end-of-line))
6403 (setq string (concat string tramp-rsh-end-of-line)))
6404 ;; Send the string.
6405 (if (and chunksize (not (zerop chunksize)))
6406 (let ((pos 0)
6407 (end (length string)))
6408 (while (< pos end)
6409 (tramp-message
6410 vec 10 "Sending chunk from %s to %s"
6411 pos (min (+ pos chunksize) end))
6412 (process-send-string
6413 p (substring string pos (min (+ pos chunksize) end)))
6414 (setq pos (+ pos chunksize))))
6415 (process-send-string p string)))))
6417 (defun tramp-mode-string-to-int (mode-string)
6418 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
6419 (let* (case-fold-search
6420 (mode-chars (string-to-vector mode-string))
6421 (owner-read (aref mode-chars 1))
6422 (owner-write (aref mode-chars 2))
6423 (owner-execute-or-setid (aref mode-chars 3))
6424 (group-read (aref mode-chars 4))
6425 (group-write (aref mode-chars 5))
6426 (group-execute-or-setid (aref mode-chars 6))
6427 (other-read (aref mode-chars 7))
6428 (other-write (aref mode-chars 8))
6429 (other-execute-or-sticky (aref mode-chars 9)))
6430 (save-match-data
6431 (logior
6432 (cond
6433 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
6434 ((char-equal owner-read ?-) 0)
6435 (t (error "Second char `%c' must be one of `r-'" owner-read)))
6436 (cond
6437 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
6438 ((char-equal owner-write ?-) 0)
6439 (t (error "Third char `%c' must be one of `w-'" owner-write)))
6440 (cond
6441 ((char-equal owner-execute-or-setid ?x)
6442 (tramp-octal-to-decimal "00100"))
6443 ((char-equal owner-execute-or-setid ?S)
6444 (tramp-octal-to-decimal "04000"))
6445 ((char-equal owner-execute-or-setid ?s)
6446 (tramp-octal-to-decimal "04100"))
6447 ((char-equal owner-execute-or-setid ?-) 0)
6448 (t (error "Fourth char `%c' must be one of `xsS-'"
6449 owner-execute-or-setid)))
6450 (cond
6451 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
6452 ((char-equal group-read ?-) 0)
6453 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
6454 (cond
6455 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
6456 ((char-equal group-write ?-) 0)
6457 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
6458 (cond
6459 ((char-equal group-execute-or-setid ?x)
6460 (tramp-octal-to-decimal "00010"))
6461 ((char-equal group-execute-or-setid ?S)
6462 (tramp-octal-to-decimal "02000"))
6463 ((char-equal group-execute-or-setid ?s)
6464 (tramp-octal-to-decimal "02010"))
6465 ((char-equal group-execute-or-setid ?-) 0)
6466 (t (error "Seventh char `%c' must be one of `xsS-'"
6467 group-execute-or-setid)))
6468 (cond
6469 ((char-equal other-read ?r)
6470 (tramp-octal-to-decimal "00004"))
6471 ((char-equal other-read ?-) 0)
6472 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
6473 (cond
6474 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
6475 ((char-equal other-write ?-) 0)
6476 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
6477 (cond
6478 ((char-equal other-execute-or-sticky ?x)
6479 (tramp-octal-to-decimal "00001"))
6480 ((char-equal other-execute-or-sticky ?T)
6481 (tramp-octal-to-decimal "01000"))
6482 ((char-equal other-execute-or-sticky ?t)
6483 (tramp-octal-to-decimal "01001"))
6484 ((char-equal other-execute-or-sticky ?-) 0)
6485 (t (error "Tenth char `%c' must be one of `xtT-'"
6486 other-execute-or-sticky)))))))
6488 (defun tramp-convert-file-attributes (vec attr)
6489 "Convert file-attributes ATTR generated by perl script, stat or ls.
6490 Convert file mode bits to string and set virtual device number.
6491 Return ATTR."
6492 ;; Convert last access time.
6493 (unless (listp (nth 4 attr))
6494 (setcar (nthcdr 4 attr)
6495 (list (floor (nth 4 attr) 65536)
6496 (floor (mod (nth 4 attr) 65536)))))
6497 ;; Convert last modification time.
6498 (unless (listp (nth 5 attr))
6499 (setcar (nthcdr 5 attr)
6500 (list (floor (nth 5 attr) 65536)
6501 (floor (mod (nth 5 attr) 65536)))))
6502 ;; Convert last status change time.
6503 (unless (listp (nth 6 attr))
6504 (setcar (nthcdr 6 attr)
6505 (list (floor (nth 6 attr) 65536)
6506 (floor (mod (nth 6 attr) 65536)))))
6507 ;; Convert file size.
6508 (when (< (nth 7 attr) 0)
6509 (setcar (nthcdr 7 attr) -1))
6510 (when (and (floatp (nth 7 attr))
6511 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
6512 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
6513 ;; Convert file mode bits to string.
6514 (unless (stringp (nth 8 attr))
6515 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr))))
6516 ;; Convert directory indication bit.
6517 (if (string-match "^d" (nth 8 attr))
6518 (setcar attr t)
6519 (if (and (listp (car attr)) (stringp (caar attr))
6520 (string-match ".+ -> .\\(.+\\)." (caar attr)))
6521 (setcar attr (match-string 1 (caar attr)))
6522 (setcar attr nil)))
6523 ;; Set file's gid change bit.
6524 (setcar (nthcdr 9 attr)
6525 (if (numberp (nth 3 attr))
6526 (not (= (nth 3 attr)
6527 (tramp-get-remote-gid vec 'integer)))
6528 (not (string-equal
6529 (nth 3 attr)
6530 (tramp-get-remote-gid vec 'string)))))
6531 ;; Convert inode.
6532 (unless (listp (nth 10 attr))
6533 (setcar (nthcdr 10 attr)
6534 (condition-case nil
6535 (list (floor (nth 10 attr) 65536)
6536 (floor (mod (nth 10 attr) 65536)))
6537 ;; Inodes can be incredible huge. We must hide this.
6538 (error (tramp-get-inode vec)))))
6539 ;; Set virtual device number.
6540 (setcar (nthcdr 11 attr)
6541 (tramp-get-device vec))
6542 attr)
6544 (defun tramp-get-inode (vec)
6545 "Returns the virtual inode number.
6546 If it doesn't exist, generate a new one."
6547 (let ((string (tramp-make-tramp-file-name
6548 (tramp-file-name-method vec)
6549 (tramp-file-name-user vec)
6550 (tramp-file-name-host vec)
6551 "")))
6552 (unless (assoc string tramp-inodes)
6553 (add-to-list 'tramp-inodes
6554 (list string (length tramp-inodes))))
6555 (nth 1 (assoc string tramp-inodes))))
6557 (defun tramp-get-device (vec)
6558 "Returns the virtual device number.
6559 If it doesn't exist, generate a new one."
6560 (let ((string (tramp-make-tramp-file-name
6561 (tramp-file-name-method vec)
6562 (tramp-file-name-user vec)
6563 (tramp-file-name-host vec)
6564 "")))
6565 (unless (assoc string tramp-devices)
6566 (add-to-list 'tramp-devices
6567 (list string (length tramp-devices))))
6568 (list -1 (nth 1 (assoc string tramp-devices)))))
6570 (defun tramp-file-mode-from-int (mode)
6571 "Turn an integer representing a file mode into an ls(1)-like string."
6572 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
6573 (user (logand (lsh mode -6) 7))
6574 (group (logand (lsh mode -3) 7))
6575 (other (logand (lsh mode -0) 7))
6576 (suid (> (logand (lsh mode -9) 4) 0))
6577 (sgid (> (logand (lsh mode -9) 2) 0))
6578 (sticky (> (logand (lsh mode -9) 1) 0)))
6579 (setq user (tramp-file-mode-permissions user suid "s"))
6580 (setq group (tramp-file-mode-permissions group sgid "s"))
6581 (setq other (tramp-file-mode-permissions other sticky "t"))
6582 (concat type user group other)))
6584 (defun tramp-file-mode-permissions (perm suid suid-text)
6585 "Convert a permission bitset into a string.
6586 This is used internally by `tramp-file-mode-from-int'."
6587 (let ((r (> (logand perm 4) 0))
6588 (w (> (logand perm 2) 0))
6589 (x (> (logand perm 1) 0)))
6590 (concat (or (and r "r") "-")
6591 (or (and w "w") "-")
6592 (or (and suid x suid-text) ; suid, execute
6593 (and suid (upcase suid-text)) ; suid, !execute
6594 (and x "x") "-")))) ; !suid
6596 (defun tramp-decimal-to-octal (i)
6597 "Return a string consisting of the octal digits of I.
6598 Not actually used. Use `(format \"%o\" i)' instead?"
6599 (cond ((< i 0) (error "Cannot convert negative number to octal"))
6600 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
6601 ((zerop i) "0")
6602 (t (concat (tramp-decimal-to-octal (/ i 8))
6603 (number-to-string (% i 8))))))
6606 ;; Kudos to Gerd Moellmann for this suggestion.
6607 (defun tramp-octal-to-decimal (ostr)
6608 "Given a string of octal digits, return a decimal number."
6609 (let ((x (or ostr "")))
6610 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
6611 (unless (string-match "\\`[0-7]*\\'" x)
6612 (error "Non-octal junk in string `%s'" x))
6613 (string-to-number ostr 8)))
6615 (defun tramp-shell-case-fold (string)
6616 "Converts STRING to shell glob pattern which ignores case."
6617 (mapconcat
6618 (lambda (c)
6619 (if (equal (downcase c) (upcase c))
6620 (vector c)
6621 (format "[%c%c]" (downcase c) (upcase c))))
6622 string
6623 ""))
6626 ;; ------------------------------------------------------------
6627 ;; -- Tramp file names --
6628 ;; ------------------------------------------------------------
6629 ;; Conversion functions between external representation and
6630 ;; internal data structure. Convenience functions for internal
6631 ;; data structure.
6633 (defun tramp-file-name-p (vec)
6634 "Check whether VEC is a Tramp object."
6635 (and (vectorp vec) (= 4 (length vec))))
6637 (defun tramp-file-name-method (vec)
6638 "Return method component of VEC."
6639 (and (tramp-file-name-p vec) (aref vec 0)))
6641 (defun tramp-file-name-user (vec)
6642 "Return user component of VEC."
6643 (and (tramp-file-name-p vec) (aref vec 1)))
6645 (defun tramp-file-name-host (vec)
6646 "Return host component of VEC."
6647 (and (tramp-file-name-p vec) (aref vec 2)))
6649 (defun tramp-file-name-localname (vec)
6650 "Return localname component of VEC."
6651 (and (tramp-file-name-p vec) (aref vec 3)))
6653 ;; The host part of a Tramp file name vector can be of kind
6654 ;; "host#port". Sometimes, we must extract these parts.
6655 (defun tramp-file-name-real-host (vec)
6656 "Return the host name of VEC without port."
6657 (let ((host (tramp-file-name-host vec)))
6658 (if (and (stringp host)
6659 (string-match tramp-host-with-port-regexp host))
6660 (match-string 1 host)
6661 host)))
6663 (defun tramp-file-name-port (vec)
6664 "Return the port number of VEC."
6665 (let ((host (tramp-file-name-host vec)))
6666 (and (stringp host)
6667 (string-match tramp-host-with-port-regexp host)
6668 (string-to-number (match-string 2 host)))))
6670 (defun tramp-tramp-file-p (name)
6671 "Return t if NAME is a Tramp file."
6672 (save-match-data
6673 (string-match tramp-file-name-regexp name)))
6675 (defun tramp-find-method (method user host)
6676 "Return the right method string to use.
6677 This is METHOD, if non-nil. Otherwise, do a lookup in
6678 `tramp-default-method-alist'."
6679 (or method
6680 (let ((choices tramp-default-method-alist)
6681 lmethod item)
6682 (while choices
6683 (setq item (pop choices))
6684 (when (and (string-match (or (nth 0 item) "") (or host ""))
6685 (string-match (or (nth 1 item) "") (or user "")))
6686 (setq lmethod (nth 2 item))
6687 (setq choices nil)))
6688 lmethod)
6689 tramp-default-method))
6691 (defun tramp-find-user (method user host)
6692 "Return the right user string to use.
6693 This is USER, if non-nil. Otherwise, do a lookup in
6694 `tramp-default-user-alist'."
6695 (or user
6696 (let ((choices tramp-default-user-alist)
6697 luser item)
6698 (while choices
6699 (setq item (pop choices))
6700 (when (and (string-match (or (nth 0 item) "") (or method ""))
6701 (string-match (or (nth 1 item) "") (or host "")))
6702 (setq luser (nth 2 item))
6703 (setq choices nil)))
6704 luser)
6705 tramp-default-user))
6707 (defun tramp-find-host (method user host)
6708 "Return the right host string to use.
6709 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
6710 (or (and (> (length host) 0) host)
6711 tramp-default-host))
6713 (defun tramp-dissect-file-name (name &optional nodefault)
6714 "Return a `tramp-file-name' structure.
6715 The structure consists of remote method, remote user, remote host
6716 and localname (file name on remote host). If NODEFAULT is
6717 non-nil, the file name parts are not expanded to their default
6718 values."
6719 (save-match-data
6720 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
6721 (unless match (error "Not a Tramp file name: %s" name))
6722 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
6723 (user (match-string (nth 2 tramp-file-name-structure) name))
6724 (host (match-string (nth 3 tramp-file-name-structure) name))
6725 (localname (match-string (nth 4 tramp-file-name-structure) name)))
6726 (when (member method '("multi" "multiu"))
6727 (error
6728 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
6729 method))
6730 (if nodefault
6731 (vector method user host localname)
6732 (vector
6733 (tramp-find-method method user host)
6734 (tramp-find-user method user host)
6735 (tramp-find-host method user host)
6736 localname))))))
6738 (defun tramp-equal-remote (file1 file2)
6739 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
6740 The check depends on method, user and host name of the files. If
6741 one of the components is missing, the default values are used.
6742 The local file name parts of FILE1 and FILE2 are not taken into
6743 account.
6745 Example:
6747 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
6749 would yield `t'. On the other hand, the following check results in nil:
6751 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
6752 (and (stringp (file-remote-p file1))
6753 (stringp (file-remote-p file2))
6754 (string-equal (file-remote-p file1) (file-remote-p file2))))
6756 (defun tramp-make-tramp-file-name (method user host localname)
6757 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
6758 (concat tramp-prefix-format
6759 (when (not (zerop (length method)))
6760 (concat method tramp-postfix-method-format))
6761 (when (not (zerop (length user)))
6762 (concat user tramp-postfix-user-format))
6763 (when host host) tramp-postfix-host-format
6764 (when localname localname)))
6766 (defun tramp-completion-make-tramp-file-name (method user host localname)
6767 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
6768 It must not be a complete Tramp file name, but as long as there are
6769 necessary only. This function will be used in file name completion."
6770 (concat tramp-prefix-format
6771 (when (not (zerop (length method)))
6772 (concat method tramp-postfix-method-format))
6773 (when (not (zerop (length user)))
6774 (concat user tramp-postfix-user-format))
6775 (when (not (zerop (length host)))
6776 (concat host tramp-postfix-host-format))
6777 (when localname localname)))
6779 (defun tramp-make-copy-program-file-name (vec)
6780 "Create a file name suitable to be passed to `rcp' and workalikes."
6781 (let ((user (tramp-file-name-user vec))
6782 (host (tramp-file-name-real-host vec))
6783 (localname (tramp-shell-quote-argument
6784 (tramp-file-name-localname vec))))
6785 (if (not (zerop (length user)))
6786 (format "%s@%s:%s" user host localname)
6787 (format "%s:%s" host localname))))
6789 (defun tramp-method-out-of-band-p (vec)
6790 "Return t if this is an out-of-band method, nil otherwise."
6791 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program))
6793 (defun tramp-local-host-p (vec)
6794 "Return t if this points to the local host, nil otherwise."
6795 ;; We cannot use `tramp-file-name-real-host'. A port is an
6796 ;; indication for an ssh tunnel or alike.
6797 (let ((host (tramp-file-name-host vec)))
6798 (and
6799 (stringp host)
6800 (string-match
6801 (concat "^" (regexp-opt (list "localhost" (system-name)) t) "$") host)
6802 ;; The local temp directory must be writable for the other user.
6803 (file-writable-p
6804 (tramp-make-tramp-file-name
6805 (tramp-file-name-method vec)
6806 (tramp-file-name-user vec)
6807 host
6808 (tramp-compat-temporary-file-directory))))))
6810 ;; Variables local to connection.
6812 (defun tramp-get-remote-path (vec)
6813 (with-connection-property vec "remote-path"
6814 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
6815 (elt (memq 'tramp-default-remote-path remote-path))
6816 (default-remote-path
6817 (when elt
6818 (condition-case nil
6819 (symbol-name
6820 (tramp-send-command-and-read vec "getconf PATH"))
6821 ;; Default if "getconf" is not available.
6822 (error
6823 (tramp-message
6824 vec 3
6825 "`getconf PATH' not successful, using default value \"%s\"."
6826 "/bin:/usr/bin")
6827 "/bin:/usr/bin")))))
6828 (when elt
6829 ;; Replace place holder `tramp-default-remote-path'.
6830 (setcdr elt
6831 (append
6832 (tramp-split-string default-remote-path ":")
6833 (cdr elt)))
6834 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
6836 ;; Remove non-existing directories.
6837 (delq
6839 (mapcar
6840 (lambda (x)
6841 (and
6842 (with-connection-property vec x
6843 (file-directory-p
6844 (tramp-make-tramp-file-name
6845 (tramp-file-name-method vec)
6846 (tramp-file-name-user vec)
6847 (tramp-file-name-host vec)
6848 x)))
6850 remote-path)))))
6852 (defun tramp-get-remote-tmpdir (vec)
6853 (with-connection-property vec "tmp-directory"
6854 (let ((dir (tramp-shell-quote-argument "/tmp")))
6855 (if (and (zerop
6856 (tramp-send-command-and-check
6857 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
6858 (zerop
6859 (tramp-send-command-and-check
6860 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
6862 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
6864 (defun tramp-get-ls-command (vec)
6865 (with-connection-property vec "ls"
6866 (with-current-buffer (tramp-get-buffer vec)
6867 (tramp-message vec 5 "Finding a suitable `ls' command")
6869 (catch 'ls-found
6870 (dolist (cmd '("ls" "gnuls" "gls"))
6871 (let ((dl (tramp-get-remote-path vec))
6872 result)
6873 (while
6874 (and
6876 (setq result
6877 (tramp-find-executable vec cmd dl t t)))
6878 ;; Check parameter.
6879 (when (zerop (tramp-send-command-and-check
6880 vec (format "%s -lnd /" result)))
6881 (throw 'ls-found result))
6882 (setq dl (cdr dl))))))
6883 (tramp-error vec 'file-error "Couldn't find a proper `ls' command")))))
6885 (defun tramp-get-test-command (vec)
6886 (with-connection-property vec "test"
6887 (with-current-buffer (tramp-get-buffer vec)
6888 (tramp-message vec 5 "Finding a suitable `test' command")
6889 (if (zerop (tramp-send-command-and-check vec "test 0"))
6890 "test"
6891 (tramp-find-executable vec "test" (tramp-get-remote-path vec))))))
6893 (defun tramp-get-test-nt-command (vec)
6894 ;; Does `test A -nt B' work? Use abominable `find' construct if it
6895 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
6896 ;; for otherwise the shell crashes.
6897 (with-connection-property vec "test-nt"
6899 (progn
6900 (tramp-send-command
6901 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
6902 (with-current-buffer (tramp-get-buffer vec)
6903 (goto-char (point-min))
6904 (when (looking-at (regexp-quote tramp-end-of-output))
6905 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
6906 (progn
6907 (tramp-send-command
6909 (format
6910 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
6911 (tramp-get-test-command vec)))
6912 "tramp_test_nt %s %s"))))
6914 (defun tramp-get-file-exists-command (vec)
6915 (with-connection-property vec "file-exists"
6916 (with-current-buffer (tramp-get-buffer vec)
6917 (tramp-message vec 5 "Finding command to check if file exists")
6918 (tramp-find-file-exists-command vec))))
6920 (defun tramp-get-remote-ln (vec)
6921 (with-connection-property vec "ln"
6922 (with-current-buffer (tramp-get-buffer vec)
6923 (tramp-message vec 5 "Finding a suitable `ln' command")
6924 (tramp-find-executable vec "ln" (tramp-get-remote-path vec)))))
6926 (defun tramp-get-remote-perl (vec)
6927 (with-connection-property vec "perl"
6928 (with-current-buffer (tramp-get-buffer vec)
6929 (tramp-message vec 5 "Finding a suitable `perl' command")
6930 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
6931 (tramp-find-executable vec "perl" (tramp-get-remote-path vec))))))
6933 (defun tramp-get-remote-stat (vec)
6934 (with-connection-property vec "stat"
6935 (with-current-buffer (tramp-get-buffer vec)
6936 (tramp-message vec 5 "Finding a suitable `stat' command")
6937 (let ((result (tramp-find-executable
6938 vec "stat" (tramp-get-remote-path vec)))
6939 tmp)
6940 ;; Check whether stat(1) returns usable syntax.
6941 (when result
6942 (setq tmp
6943 ;; We don't want to display an error message.
6944 (with-temp-message (or (current-message) "")
6945 (condition-case nil
6946 (tramp-send-command-and-read
6947 vec (format "%s -c '(\"%%N\")' /" result))
6948 (error nil))))
6949 (unless (and (listp tmp) (stringp (car tmp))
6950 (string-match "^./.$" (car tmp)))
6951 (setq result nil)))
6952 result))))
6954 (defun tramp-get-remote-id (vec)
6955 (with-connection-property vec "id"
6956 (with-current-buffer (tramp-get-buffer vec)
6957 (tramp-message vec 5 "Finding POSIX `id' command")
6959 (catch 'id-found
6960 (let ((dl (tramp-get-remote-path vec))
6961 result)
6962 (while
6963 (and
6965 (setq result
6966 (tramp-find-executable vec "id" dl t t)))
6967 ;; Check POSIX parameter.
6968 (when (zerop (tramp-send-command-and-check
6969 vec (format "%s -u" result)))
6970 (throw 'id-found result))
6971 (setq dl (cdr dl)))))
6972 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command")))))
6974 (defun tramp-get-remote-uid (vec id-format)
6975 (with-connection-property vec (format "uid-%s" id-format)
6976 (let ((res (tramp-send-command-and-read
6978 (format "%s -u%s %s"
6979 (tramp-get-remote-id vec)
6980 (if (equal id-format 'integer) "" "n")
6981 (if (equal id-format 'integer)
6982 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
6983 ;; The command might not always return a number.
6984 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
6986 (defun tramp-get-remote-gid (vec id-format)
6987 (with-connection-property vec (format "gid-%s" id-format)
6988 (let ((res (tramp-send-command-and-read
6990 (format "%s -g%s %s"
6991 (tramp-get-remote-id vec)
6992 (if (equal id-format 'integer) "" "n")
6993 (if (equal id-format 'integer)
6994 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
6995 ;; The command might not always return a number.
6996 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
6998 (defun tramp-get-local-uid (id-format)
6999 (if (equal id-format 'integer) (user-uid) (user-login-name)))
7001 (defun tramp-get-local-gid (id-format)
7002 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
7004 ;; Some predefined connection properties.
7005 (defun tramp-get-remote-coding (vec prop)
7006 ;; Local coding handles properties like remote coding. So we could
7007 ;; call it without pain.
7008 (let ((ret (tramp-get-local-coding vec prop)))
7009 ;; The connection property might have been cached. So we must send
7010 ;; the script - maybe.
7011 (when (not (stringp ret))
7012 (let ((name (symbol-name ret)))
7013 (while (string-match (regexp-quote "-") name)
7014 (setq name (replace-match "_" nil t name)))
7015 (tramp-maybe-send-script vec (symbol-value ret) name)
7016 (setq ret name)))
7017 ;; Return the value.
7018 ret))
7020 (defun tramp-get-local-coding (vec prop)
7022 (tramp-get-connection-property vec prop nil)
7023 (progn
7024 (tramp-find-inline-encoding vec)
7025 (tramp-get-connection-property vec prop nil))))
7027 (defun tramp-get-method-parameter (method param)
7028 "Return the method parameter PARAM.
7029 If the `tramp-methods' entry does not exist, return NIL."
7030 (let ((entry (assoc param (assoc method tramp-methods))))
7031 (when entry (cadr entry))))
7033 ;; Auto saving to a special directory.
7035 (defun tramp-exists-file-name-handler (operation &rest args)
7036 "Checks whether OPERATION runs a file name handler."
7037 ;; The file name handler is determined on base of either an
7038 ;; argument, `buffer-file-name', or `default-directory'.
7039 (condition-case nil
7040 (let* ((buffer-file-name "/")
7041 (default-directory "/")
7042 (fnha file-name-handler-alist)
7043 (check-file-name-operation operation)
7044 (file-name-handler-alist
7045 (list
7046 (cons "/"
7047 '(lambda (operation &rest args)
7048 "Returns OPERATION if it is the one to be checked."
7049 (if (equal check-file-name-operation operation)
7050 operation
7051 (let ((file-name-handler-alist fnha))
7052 (apply operation args))))))))
7053 (equal (apply operation args) operation))
7054 (error nil)))
7056 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
7057 (defadvice make-auto-save-file-name
7058 (around tramp-advice-make-auto-save-file-name () activate)
7059 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
7060 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
7061 (setq ad-return-value (tramp-handle-make-auto-save-file-name))
7062 ad-do-it))
7063 (add-hook 'tramp-unload-hook
7064 '(lambda () (ad-unadvise 'make-auto-save-file-name))))
7066 ;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
7067 ;; permission 0666 minus umask. This is a security threat.
7069 (defun tramp-set-auto-save-file-modes ()
7070 "Set permissions of autosaved remote files to the original permissions."
7071 (let ((bfn (buffer-file-name)))
7072 (when (and (stringp bfn)
7073 (tramp-tramp-file-p bfn)
7074 (buffer-modified-p)
7075 (stringp buffer-auto-save-file-name)
7076 (not (equal bfn buffer-auto-save-file-name)))
7077 (unless (file-exists-p buffer-auto-save-file-name)
7078 (write-region "" nil buffer-auto-save-file-name))
7079 ;; Permissions should be set always, because there might be an old
7080 ;; auto-saved file belonging to another original file. This could
7081 ;; be a security threat.
7082 (set-file-modes buffer-auto-save-file-name
7083 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
7085 (unless (or (> emacs-major-version 21)
7086 (and (featurep 'xemacs)
7087 (= emacs-major-version 21)
7088 (> emacs-minor-version 4)))
7089 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
7090 (add-hook 'tramp-unload-hook
7091 '(lambda ()
7092 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
7094 (defun tramp-subst-strs-in-string (alist string)
7095 "Replace all occurrences of the string FROM with TO in STRING.
7096 ALIST is of the form ((FROM . TO) ...)."
7097 (save-match-data
7098 (while alist
7099 (let* ((pr (car alist))
7100 (from (car pr))
7101 (to (cdr pr)))
7102 (while (string-match (regexp-quote from) string)
7103 (setq string (replace-match to t t string)))
7104 (setq alist (cdr alist))))
7105 string))
7107 ;; ------------------------------------------------------------
7108 ;; -- Compatibility functions section --
7109 ;; ------------------------------------------------------------
7111 (defun tramp-read-passwd (proc &optional prompt)
7112 "Read a password from user (compat function).
7113 Invokes `password-read' if available, `read-passwd' else."
7114 (let* ((key (tramp-make-tramp-file-name
7115 tramp-current-method tramp-current-user
7116 tramp-current-host ""))
7117 (pw-prompt
7118 (or prompt
7119 (with-current-buffer (process-buffer proc)
7120 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
7121 (format "%s for %s " (capitalize (match-string 1)) key)))))
7122 (if (functionp 'password-read)
7123 (let ((password (funcall (symbol-function 'password-read)
7124 pw-prompt key)))
7125 (funcall (symbol-function 'password-cache-add) key password)
7126 password)
7127 (read-passwd pw-prompt))))
7129 (defun tramp-clear-passwd (vec)
7130 "Clear password cache for connection related to VEC."
7131 (when (functionp 'password-cache-remove)
7132 (funcall
7133 (symbol-function 'password-cache-remove)
7134 (tramp-make-tramp-file-name
7135 (tramp-file-name-method vec)
7136 (tramp-file-name-user vec)
7137 (tramp-file-name-host vec)
7138 ""))))
7140 ;; Snarfed code from time-date.el and parse-time.el
7142 (defconst tramp-half-a-year '(241 17024)
7143 "Evaluated by \"(days-to-time 183)\".")
7145 (defconst tramp-parse-time-months
7146 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
7147 ("apr" . 4) ("may" . 5) ("jun" . 6)
7148 ("jul" . 7) ("aug" . 8) ("sep" . 9)
7149 ("oct" . 10) ("nov" . 11) ("dec" . 12))
7150 "Alist mapping month names to integers.")
7152 (defun tramp-time-less-p (t1 t2)
7153 "Say whether time value T1 is less than time value T2."
7154 (unless t1 (setq t1 '(0 0)))
7155 (unless t2 (setq t2 '(0 0)))
7156 (or (< (car t1) (car t2))
7157 (and (= (car t1) (car t2))
7158 (< (nth 1 t1) (nth 1 t2)))))
7160 (defun tramp-time-subtract (t1 t2)
7161 "Subtract two time values.
7162 Return the difference in the format of a time value."
7163 (unless t1 (setq t1 '(0 0)))
7164 (unless t2 (setq t2 '(0 0)))
7165 (let ((borrow (< (cadr t1) (cadr t2))))
7166 (list (- (car t1) (car t2) (if borrow 1 0))
7167 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
7169 (defun tramp-time-diff (t1 t2)
7170 "Return the difference between the two times, in seconds.
7171 T1 and T2 are time values (as returned by `current-time' for example)."
7172 ;; Pacify byte-compiler with `symbol-function'.
7173 (cond ((and (fboundp 'subtract-time)
7174 (fboundp 'float-time))
7175 (funcall (symbol-function 'float-time)
7176 (funcall (symbol-function 'subtract-time) t1 t2)))
7177 ((and (fboundp 'subtract-time)
7178 (fboundp 'time-to-seconds))
7179 (funcall (symbol-function 'time-to-seconds)
7180 (funcall (symbol-function 'subtract-time) t1 t2)))
7181 ((fboundp 'itimer-time-difference)
7182 (funcall (symbol-function 'itimer-time-difference)
7183 (if (< (length t1) 3) (append t1 '(0)) t1)
7184 (if (< (length t2) 3) (append t2 '(0)) t2)))
7186 (let ((time (tramp-time-subtract t1 t2)))
7187 (+ (* (car time) 65536.0)
7188 (cadr time)
7189 (/ (or (nth 2 time) 0) 1000000.0))))))
7191 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
7192 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
7193 EOL-TYPE can be one of `dos', `unix', or `mac'."
7194 (cond ((fboundp 'coding-system-change-eol-conversion)
7195 (funcall (symbol-function 'coding-system-change-eol-conversion)
7196 coding-system eol-type))
7197 ((fboundp 'subsidiary-coding-system)
7198 (funcall (symbol-function 'subsidiary-coding-system)
7199 coding-system
7200 (cond ((eq eol-type 'dos) 'crlf)
7201 ((eq eol-type 'unix) 'lf)
7202 ((eq eol-type 'mac) 'cr)
7204 (error "Unknown EOL-TYPE `%s', must be %s"
7205 eol-type
7206 "`dos', `unix', or `mac'")))))
7207 (t (error "Can't change EOL conversion -- is MULE missing?"))))
7209 (defun tramp-split-string (string pattern)
7210 "Like `split-string' but omit empty strings.
7211 In Emacs, (split-string \"/foo/bar\" \"/\") returns (\"foo\" \"bar\").
7212 This is, the first, empty, element is omitted. In XEmacs, the first
7213 element is not omitted.
7215 Note: this function has been written for `tramp-handle-file-truename'.
7216 If you want to use it for something else, you'll have to check whether
7217 it does the right thing."
7218 (delete "" (split-string string pattern)))
7220 (defun tramp-set-process-query-on-exit-flag (process flag)
7221 "Specify if query is needed for process when Emacs is exited.
7222 If the second argument flag is non-nil, Emacs will query the user before
7223 exiting if process is running."
7224 (if (fboundp 'set-process-query-on-exit-flag)
7225 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
7226 (funcall (symbol-function 'process-kill-without-query) process flag)))
7229 ;; ------------------------------------------------------------
7230 ;; -- Kludges section --
7231 ;; ------------------------------------------------------------
7233 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
7234 ;; does not deal well with newline characters. Newline is replaced by
7235 ;; backslash newline. But if, say, the string `a backslash newline b'
7236 ;; is passed to a shell, the shell will expand this into "ab",
7237 ;; completely omitting the newline. This is not what was intended.
7238 ;; It does not appear to be possible to make the function
7239 ;; `shell-quote-argument' work with newlines without making it
7240 ;; dependent on the shell used. But within this package, we know that
7241 ;; we will always use a Bourne-like shell, so we use an approach which
7242 ;; groks newlines.
7244 ;; The approach is simple: we call `shell-quote-argument', then
7245 ;; massage the newline part of the result.
7247 ;; This function should produce a string which is grokked by a Unix
7248 ;; shell, even if the Emacs is running on Windows. Since this is the
7249 ;; kludges section, we bind `system-type' in such a way that
7250 ;; `shell-quote-arguments' behaves as if on Unix.
7252 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
7253 ;; function to work with Bourne-like shells.
7255 ;; CCC: This function should be rewritten so that
7256 ;; `shell-quote-argument' is not used. This way, we are safe from
7257 ;; changes in `shell-quote-argument'.
7258 (defun tramp-shell-quote-argument (s)
7259 "Similar to `shell-quote-argument', but groks newlines.
7260 Only works for Bourne-like shells."
7261 (let ((system-type 'not-windows))
7262 (save-match-data
7263 (let ((result (shell-quote-argument s))
7264 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
7265 (when (and (>= (length result) 2)
7266 (string= (substring result 0 2) "\\~"))
7267 (setq result (substring result 1)))
7268 (while (string-match nl result)
7269 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
7270 t t result)))
7271 result))))
7273 ;; We currently (sometimes) use "[" and "]" in the filename format.
7274 ;; This means that Emacs wants to expand wildcards if
7275 ;; `find-file-wildcards' is non-nil, and then barfs because no
7276 ;; expansion could be found. We detect this situation and do
7277 ;; something really awful: we have `file-expand-wildcards' return the
7278 ;; original filename if it can't expand anything. Let's just hope
7279 ;; that this doesn't break anything else.
7280 ;; CCC: This check is now also really awful; we should search all
7281 ;; of the filename format, not just the prefix.
7282 (when (string-match "\\[" tramp-prefix-format)
7283 (defadvice file-expand-wildcards
7284 (around tramp-advice-file-expand-wildcards activate)
7285 (let ((name (ad-get-arg 0)))
7286 (if (tramp-tramp-file-p name)
7287 ;; If it's a Tramp file, dissect it and look if wildcards
7288 ;; need to be expanded at all.
7289 (if (string-match
7290 "[[*?]"
7291 (tramp-file-name-localname (tramp-dissect-file-name name)))
7292 (setq ad-return-value (or ad-do-it (list name)))
7293 (setq ad-return-value (list name)))
7294 ;; If it is not a Tramp file, just run the original function.
7295 (setq ad-return-value (or ad-do-it (list name))))))
7296 (add-hook 'tramp-unload-hook
7297 '(lambda () (ad-unadvise 'file-expand-wildcards))))
7299 ;; Checklist for `tramp-unload-hook'
7300 ;; - Unload all `tramp-*' packages
7301 ;; - Reset `file-name-handler-alist'
7302 ;; - Cleanup hooks where Tramp functions are in
7303 ;; - Cleanup advised functions
7304 ;; - Cleanup autoloads
7305 ;;;###autoload
7306 (defun tramp-unload-tramp ()
7307 "Discard Tramp from loading remote files."
7308 (interactive)
7309 ;; When Tramp is not loaded yet, its autoloads are still active.
7310 (tramp-unload-file-name-handlers)
7311 ;; ange-ftp settings must be enabled.
7312 (when (functionp 'tramp-ftp-enable-ange-ftp)
7313 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
7314 ;; Maybe its not loaded yet.
7315 (condition-case nil
7316 (unload-feature 'tramp 'force)
7317 (error nil)))
7319 (provide 'tramp)
7321 ;;; TODO:
7323 ;; * Allow putting passwords in the filename.
7324 ;; This should be implemented via a general mechanism to add
7325 ;; parameters in filenames. There is currently a kludge for
7326 ;; putting the port number into the filename for ssh and ftp
7327 ;; files. This could be subsumed by the new mechanism as well.
7328 ;; Another approach is to read a netrc file like ~/.authinfo
7329 ;; from Gnus.
7330 ;; * Handle nonlocal exits such as C-g.
7331 ;; * But it would probably be better to use with-local-quit at the
7332 ;; place where it's actually needed: around any potentially
7333 ;; indefinitely blocking piece of code. In this case it would be
7334 ;; within Tramp around one of its calls to accept-process-output (or
7335 ;; around one of the loops that calls accept-process-output)
7336 ;; (Stefan Monnier).
7337 ;; * Autodetect if remote `ls' groks the "--dired" switch.
7338 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
7339 ;; `shell-quote-argument'.
7340 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
7341 ;; by the files in that directory. Add this here.
7342 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
7343 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
7344 ;; * When logging in, keep looking for questions according to an alist
7345 ;; and then invoke the right function.
7346 ;; * Case-insensitive filename completion. (Norbert Goevert.)
7347 ;; * Don't use globbing for directories with many files, as this is
7348 ;; likely to produce long command lines, and some shells choke on
7349 ;; long command lines.
7350 ;; * `vc-directory' does not work. It never displays any files, even
7351 ;; if it does show files when run locally.
7352 ;; * Allow correction of passwords, if the remote end allows this.
7353 ;; (Mark Hershberger)
7354 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
7355 ;; * Grok `append' parameter for `write-region'.
7356 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
7357 ;; * abbreviate-file-name
7358 ;; * better error checking. At least whenever we see something
7359 ;; strange when doing zerop, we should kill the process and start
7360 ;; again. (Greg Stark)
7361 ;; * Provide a local cache of old versions of remote files for the rsync
7362 ;; transfer method to use. (Greg Stark)
7363 ;; * Remove unneeded parameters from methods.
7364 ;; * Invoke rsync once for copying a whole directory hierarchy.
7365 ;; (Francesco Potortì)
7366 ;; * Make it work for different encodings, and for different file name
7367 ;; encodings, too. (Daniel Pittman)
7368 ;; * Progress reports while copying files. (Michael Kifer)
7369 ;; * Don't search for perl5 and perl. Instead, only search for perl and
7370 ;; then look if it's the right version (with `perl -v').
7371 ;; * When editing a remote CVS controlled file as a different user, VC
7372 ;; gets confused about the file locking status. Try to find out why
7373 ;; the workaround doesn't work.
7374 ;; * Username and hostname completion.
7375 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
7376 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
7377 ;; Code is nearly identical.
7378 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
7379 ;; until the last but one hop via `start-file-process'. Apply it
7380 ;; also for ftp and smb.
7381 ;; * WIBNI if we had a command "trampclient"? If I was editing in
7382 ;; some shell with root priviledges, it would be nice if I could
7383 ;; just call
7384 ;; trampclient filename.c
7385 ;; as an editor, and the _current_ shell would connect to an Emacs
7386 ;; server and would be used in an existing non-priviledged Emacs
7387 ;; session for doing the editing in question.
7388 ;; That way, I need not tell Emacs my password again and be afraid
7389 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
7390 ;; once display a just typed password in the context of a keyboard
7391 ;; sequence prompt for a question immediately following in a shell
7392 ;; script run within Emacs -- nasty).
7393 ;; And if I have some ssh session running to a different computer,
7394 ;; having the possibility of passing a local file there to a local
7395 ;; Emacs session (in case I can arrange for a connection back) would
7396 ;; be nice.
7397 ;; Likely the corresponding Tramp server should not allow the
7398 ;; equivalent of the emacsclient -eval option in order to make this
7399 ;; reasonably unproblematic. And maybe trampclient should have some
7400 ;; way of passing credentials, like by using an SSL socket or
7401 ;; something. (David Kastrup)
7402 ;; * Could Tramp reasonably look for a prompt after ^M rather than
7403 ;; only after ^J ? (Stefan Monnier)
7404 ;; * Reconnect directly to a compliant shell without first going
7405 ;; through the user's default shell. (Pete Forman)
7406 ;; * Make `tramp-default-user' obsolete.
7407 ;; * Tramp shall reconnect automatically to its ssh connection when it
7408 ;; detects that the process "has died". (David Reitter)
7410 ;; Functions for file-name-handler-alist:
7411 ;; diff-latest-backup-file -- in diff.el
7412 ;; dired-uncache -- this will be needed when we do insert-directory caching
7413 ;; file-name-as-directory -- use primitive?
7414 ;; file-name-sans-versions -- use primitive?
7415 ;; get-file-buffer -- use primitive
7416 ;; vc-registered
7418 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
7419 ;;; tramp.el ends here
7421 ;; Local Variables:
7422 ;; mode: Emacs-Lisp
7423 ;; coding: utf-8
7424 ;; End: