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