10-09-13
[emacs/old-mirror.git] / lisp / net / tramp.el
blob86ece233fa6a4337d73d2dbc37a7a1247a1a2115
1 (setq tramp-version 24)
2 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
4 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
5 ;; 2005, 2006, 2007, 2008, 2009, 2010 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
12 ;; Package: tramp
14 ;; This file is part of GNU Emacs.
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <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 22.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 ;; Also see the todo list at the bottom of this file.
47 ;; The current version of Tramp can be retrieved from the following URL:
48 ;; http://ftp.gnu.org/gnu/tramp/
50 ;; There's a mailing list for this, as well. Its name is:
51 ;; tramp-devel@gnu.org
52 ;; You can use the Web to subscribe, under the following URL:
53 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
55 ;; For the adventurous, the current development sources are available
56 ;; via CVS. You can find instructions about this at the following URL:
57 ;; http://savannah.gnu.org/projects/tramp/
58 ;; Click on "CVS" in the navigation bar near the top.
60 ;; Don't forget to put on your asbestos longjohns, first!
62 ;;; Code:
64 ;; Since Emacs 23.1, loading messages have been disabled during
65 ;; autoload. However, loading Tramp takes a while, and it could
66 ;; happen while typing a filename in the minibuffer. Therefore, Tramp
67 ;; shall inform about.
68 (when (and load-in-progress (null (current-message)))
69 (message "Loading tramp..."))
71 (require 'tramp-compat)
73 (require 'format-spec)
74 ;; As long as password.el is not part of (X)Emacs, it shouldn't
75 ;; be mandatory
76 (if (featurep 'xemacs)
77 (load "password" 'noerror)
78 (or (require 'password-cache nil 'noerror)
79 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
81 (require 'shell)
82 (require 'advice)
84 (eval-and-compile
85 (if (featurep 'xemacs)
86 (load "auth-source" 'noerror)
87 (require 'auth-source nil 'noerror)))
89 (autoload 'uudecode-decode-region "uudecode")
91 ;;; User Customizable Internal Variables:
93 (defgroup tramp nil
94 "Edit remote files with a combination of rsh and rcp or similar programs."
95 :group 'files
96 :group 'comm
97 :version "22.1")
99 ;; Maybe we need once a real Tramp mode, with key bindings etc.
100 ;;;###autoload
101 (defcustom tramp-mode t
102 "*Whether Tramp is enabled.
103 If it is set to nil, all remote file names are used literally."
104 :group 'tramp
105 :type 'boolean)
107 (defcustom tramp-verbose 3
108 "*Verbosity level for Tramp messages.
109 Any level x includes messages for all levels 1 .. x-1. The levels are
111 0 silent (no tramp messages at all)
112 1 errors
113 2 warnings
114 3 connection to remote hosts (default level)
115 4 activities
116 5 internal
117 6 sent and received strings
118 7 file caching
119 8 connection properties
120 9 test commands
121 10 traces (huge)."
122 :group 'tramp
123 :type 'integer)
125 ;; Emacs case.
126 (eval-and-compile
127 (when (boundp 'backup-directory-alist)
128 (defcustom tramp-backup-directory-alist nil
129 "Alist of filename patterns and backup directory names.
130 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
131 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
132 is a local file name, the backup directory is prepended with Tramp file
133 name prefix \(method, user, host\) of file.
135 \(setq tramp-backup-directory-alist backup-directory-alist\)
137 gives the same backup policy for Tramp files on their hosts like the
138 policy for local files."
139 :group 'tramp
140 :type '(repeat (cons (regexp :tag "Regexp matching filename")
141 (directory :tag "Backup directory name"))))))
143 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
144 ;; the package "backup-dir" might not be loaded yet.
145 (eval-and-compile
146 (when (featurep 'xemacs)
147 (defcustom tramp-bkup-backup-directory-info nil
148 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
149 It has the same meaning like `bkup-backup-directory-info' from package
150 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
151 file name, the backup directory is prepended with Tramp file name prefix
152 \(method, user, host\) of file.
154 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
156 gives the same backup policy for Tramp files on their hosts like the
157 policy for local files."
158 :type '(repeat
159 (list (regexp :tag "File regexp")
160 (string :tag "Backup Dir")
161 (set :inline t
162 (const ok-create)
163 (const full-path)
164 (const prepend-name)
165 (const search-upward))))
166 :group 'tramp)))
168 (defcustom tramp-auto-save-directory nil
169 "*Put auto-save files in this directory, if set.
170 The idea is to use a local directory so that auto-saving is faster."
171 :group 'tramp
172 :type '(choice (const nil) string))
174 (defcustom tramp-encoding-shell
175 (if (memq system-type '(windows-nt))
176 (getenv "COMSPEC")
177 "/bin/sh")
178 "*Use this program for encoding and decoding commands on the local host.
179 This shell is used to execute the encoding and decoding command on the
180 local host, so if you want to use `~' in those commands, you should
181 choose a shell here which groks tilde expansion. `/bin/sh' normally
182 does not understand tilde expansion.
184 For encoding and deocding, commands like the following are executed:
186 /bin/sh -c COMMAND < INPUT > OUTPUT
188 This variable can be used to change the \"/bin/sh\" part. See the
189 variable `tramp-encoding-command-switch' for the \"-c\" part.
191 Note that this variable is not used for remote commands. There are
192 mechanisms in tramp.el which automatically determine the right shell to
193 use for the remote host."
194 :group 'tramp
195 :type '(file :must-match t))
197 (defcustom tramp-encoding-command-switch
198 (if (string-match "cmd\\.exe" tramp-encoding-shell)
199 "/c"
200 "-c")
201 "*Use this switch together with `tramp-encoding-shell' for local commands.
202 See the variable `tramp-encoding-shell' for more information."
203 :group 'tramp
204 :type 'string)
206 (defcustom tramp-inline-compress-start-size 4096
207 "*The minimum size of compressing where inline transfer.
208 When inline transfer, compress transfered data of file
209 whose size is this value or above (up to `tramp-copy-size-limit').
210 If it is nil, no compression at all will be applied."
211 :group 'tramp
212 :type '(choice (const nil) integer))
214 (defcustom tramp-copy-size-limit 10240
215 "*The maximum file size where inline copying is preferred over an out-of-the-band copy.
216 If it is nil, inline out-of-the-band copy will be used without a check."
217 :group 'tramp
218 :type '(choice (const nil) integer))
220 ;;;###tramp-autoload
221 (defcustom tramp-terminal-type "dumb"
222 "*Value of TERM environment variable for logging in to remote host.
223 Because Tramp wants to parse the output of the remote shell, it is easily
224 confused by ANSI color escape sequences and suchlike. Often, shell init
225 files conditionalize this setup based on the TERM environment variable."
226 :group 'tramp
227 :type 'string)
229 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
230 ;; root users. It uses the `$' character for other users. In order
231 ;; to guarantee a proper prompt, we use "#$" for the prompt.
233 (defvar tramp-end-of-output
234 (format
235 "///%s#$"
236 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
237 "String used to recognize end of output.
238 The '$' character at the end is quoted; the string cannot be
239 detected as prompt when being sent on echoing hosts, therefore.")
241 ;;;###tramp-autoload
242 (defconst tramp-initial-end-of-output "#$ "
243 "Prompt when establishing a connection.")
245 ;;;###tramp-autoload
246 (defvar tramp-methods
247 `(("rcp" (tramp-login-program "rsh")
248 (tramp-login-args (("%h") ("-l" "%u")))
249 (tramp-remote-sh "/bin/sh")
250 (tramp-copy-program "rcp")
251 (tramp-copy-args (("-p" "%k") ("-r")))
252 (tramp-copy-keep-date t)
253 (tramp-copy-recursive t)
254 (tramp-password-end-of-line nil))
255 ("scp" (tramp-login-program "ssh")
256 (tramp-login-args (("-l" "%u") ("-p" "%p")
257 ("-e" "none") ("%h")))
258 (tramp-async-args (("-q")))
259 (tramp-remote-sh "/bin/sh")
260 (tramp-copy-program "scp")
261 (tramp-copy-args (("-P" "%p") ("-p" "%k")
262 ("-q") ("-r")))
263 (tramp-copy-keep-date t)
264 (tramp-copy-recursive t)
265 (tramp-password-end-of-line nil)
266 (tramp-gw-args (("-o"
267 "GlobalKnownHostsFile=/dev/null")
268 ("-o" "UserKnownHostsFile=/dev/null")
269 ("-o" "StrictHostKeyChecking=no")))
270 (tramp-default-port 22))
271 ("scp1" (tramp-login-program "ssh")
272 (tramp-login-args (("-l" "%u") ("-p" "%p")
273 ("-1") ("-e" "none") ("%h")))
274 (tramp-async-args (("-q")))
275 (tramp-remote-sh "/bin/sh")
276 (tramp-copy-program "scp")
277 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
278 ("-q") ("-r")))
279 (tramp-copy-keep-date t)
280 (tramp-copy-recursive t)
281 (tramp-password-end-of-line nil)
282 (tramp-gw-args (("-o"
283 "GlobalKnownHostsFile=/dev/null")
284 ("-o" "UserKnownHostsFile=/dev/null")
285 ("-o" "StrictHostKeyChecking=no")))
286 (tramp-default-port 22))
287 ("scp2" (tramp-login-program "ssh")
288 (tramp-login-args (("-l" "%u") ("-p" "%p")
289 ("-2") ("-e" "none") ("%h")))
290 (tramp-async-args (("-q")))
291 (tramp-remote-sh "/bin/sh")
292 (tramp-copy-program "scp")
293 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
294 ("-q") ("-r")))
295 (tramp-copy-keep-date t)
296 (tramp-copy-recursive t)
297 (tramp-password-end-of-line nil)
298 (tramp-gw-args (("-o"
299 "GlobalKnownHostsFile=/dev/null")
300 ("-o" "UserKnownHostsFile=/dev/null")
301 ("-o" "StrictHostKeyChecking=no")))
302 (tramp-default-port 22))
303 ("scp1_old"
304 (tramp-login-program "ssh1")
305 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
306 ("-e" "none")))
307 (tramp-remote-sh "/bin/sh")
308 (tramp-copy-program "scp1")
309 (tramp-copy-args (("-p" "%k") ("-r")))
310 (tramp-copy-keep-date t)
311 (tramp-copy-recursive t)
312 (tramp-password-end-of-line nil))
313 ("scp2_old"
314 (tramp-login-program "ssh2")
315 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
316 ("-e" "none")))
317 (tramp-remote-sh "/bin/sh")
318 (tramp-copy-program "scp2")
319 (tramp-copy-args (("-p" "%k") ("-r")))
320 (tramp-copy-keep-date t)
321 (tramp-copy-recursive t)
322 (tramp-password-end-of-line nil))
323 ("sftp" (tramp-login-program "ssh")
324 (tramp-login-args (("-l" "%u") ("-p" "%p")
325 ("-e" "none") ("%h")))
326 (tramp-async-args (("-q")))
327 (tramp-remote-sh "/bin/sh")
328 (tramp-copy-program "sftp")
329 (tramp-copy-args nil)
330 (tramp-copy-keep-date nil)
331 (tramp-password-end-of-line nil))
332 ("rsync" (tramp-login-program "ssh")
333 (tramp-login-args (("-l" "%u") ("-p" "%p")
334 ("-e" "none") ("%h")))
335 (tramp-async-args (("-q")))
336 (tramp-remote-sh "/bin/sh")
337 (tramp-copy-program "rsync")
338 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
339 (tramp-copy-keep-date t)
340 (tramp-copy-keep-tmpfile t)
341 (tramp-copy-recursive t)
342 (tramp-password-end-of-line nil))
343 ("rsyncc"
344 (tramp-login-program "ssh")
345 (tramp-login-args (("-l" "%u") ("-p" "%p")
346 ("-o" "ControlPath=%t.%%r@%%h:%%p")
347 ("-o" "ControlMaster=yes")
348 ("-e" "none") ("%h")))
349 (tramp-async-args (("-q")))
350 (tramp-remote-sh "/bin/sh")
351 (tramp-copy-program "rsync")
352 (tramp-copy-args (("-t" "%k") ("-r")))
353 (tramp-copy-env (("RSYNC_RSH")
354 (,(concat
355 "ssh"
356 " -o ControlPath=%t.%%r@%%h:%%p"
357 " -o ControlMaster=auto"))))
358 (tramp-copy-keep-date t)
359 (tramp-copy-keep-tmpfile t)
360 (tramp-copy-recursive t)
361 (tramp-password-end-of-line nil))
362 ("remcp" (tramp-login-program "remsh")
363 (tramp-login-args (("%h") ("-l" "%u")))
364 (tramp-remote-sh "/bin/sh")
365 (tramp-copy-program "rcp")
366 (tramp-copy-args (("-p" "%k")))
367 (tramp-copy-keep-date t)
368 (tramp-password-end-of-line nil))
369 ("rsh" (tramp-login-program "rsh")
370 (tramp-login-args (("%h") ("-l" "%u")))
371 (tramp-remote-sh "/bin/sh")
372 (tramp-copy-program nil)
373 (tramp-copy-args nil)
374 (tramp-copy-keep-date nil)
375 (tramp-password-end-of-line nil))
376 ("ssh" (tramp-login-program "ssh")
377 (tramp-login-args (("-l" "%u") ("-p" "%p")
378 ("-e" "none") ("%h")))
379 (tramp-async-args (("-q")))
380 (tramp-remote-sh "/bin/sh")
381 (tramp-copy-program nil)
382 (tramp-copy-args nil)
383 (tramp-copy-keep-date nil)
384 (tramp-password-end-of-line nil)
385 (tramp-gw-args (("-o"
386 "GlobalKnownHostsFile=/dev/null")
387 ("-o" "UserKnownHostsFile=/dev/null")
388 ("-o" "StrictHostKeyChecking=no")))
389 (tramp-default-port 22))
390 ("ssh1" (tramp-login-program "ssh")
391 (tramp-login-args (("-l" "%u") ("-p" "%p")
392 ("-1") ("-e" "none") ("%h")))
393 (tramp-async-args (("-q")))
394 (tramp-remote-sh "/bin/sh")
395 (tramp-copy-program nil)
396 (tramp-copy-args nil)
397 (tramp-copy-keep-date nil)
398 (tramp-password-end-of-line nil)
399 (tramp-gw-args (("-o"
400 "GlobalKnownHostsFile=/dev/null")
401 ("-o" "UserKnownHostsFile=/dev/null")
402 ("-o" "StrictHostKeyChecking=no")))
403 (tramp-default-port 22))
404 ("ssh2" (tramp-login-program "ssh")
405 (tramp-login-args (("-l" "%u") ("-p" "%p")
406 ("-2") ("-e" "none") ("%h")))
407 (tramp-async-args (("-q")))
408 (tramp-remote-sh "/bin/sh")
409 (tramp-copy-program nil)
410 (tramp-copy-args nil)
411 (tramp-copy-keep-date nil)
412 (tramp-password-end-of-line nil)
413 (tramp-gw-args (("-o"
414 "GlobalKnownHostsFile=/dev/null")
415 ("-o" "UserKnownHostsFile=/dev/null")
416 ("-o" "StrictHostKeyChecking=no")))
417 (tramp-default-port 22))
418 ("ssh1_old"
419 (tramp-login-program "ssh1")
420 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
421 ("-e" "none")))
422 (tramp-async-args (("-q")))
423 (tramp-remote-sh "/bin/sh")
424 (tramp-copy-program nil)
425 (tramp-copy-args nil)
426 (tramp-copy-keep-date nil)
427 (tramp-password-end-of-line nil))
428 ("ssh2_old"
429 (tramp-login-program "ssh2")
430 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
431 ("-e" "none")))
432 (tramp-remote-sh "/bin/sh")
433 (tramp-copy-program nil)
434 (tramp-copy-args nil)
435 (tramp-copy-keep-date nil)
436 (tramp-password-end-of-line nil))
437 ("remsh" (tramp-login-program "remsh")
438 (tramp-login-args (("%h") ("-l" "%u")))
439 (tramp-remote-sh "/bin/sh")
440 (tramp-copy-program nil)
441 (tramp-copy-args nil)
442 (tramp-copy-keep-date nil)
443 (tramp-password-end-of-line nil))
444 ("telnet"
445 (tramp-login-program "telnet")
446 (tramp-login-args (("%h") ("%p")))
447 (tramp-remote-sh "/bin/sh")
448 (tramp-copy-program nil)
449 (tramp-copy-args nil)
450 (tramp-copy-keep-date nil)
451 (tramp-password-end-of-line nil)
452 (tramp-default-port 23))
453 ("su" (tramp-login-program "su")
454 (tramp-login-args (("-") ("%u")))
455 (tramp-remote-sh "/bin/sh")
456 (tramp-copy-program nil)
457 (tramp-copy-args nil)
458 (tramp-copy-keep-date nil)
459 (tramp-password-end-of-line nil))
460 ("sudo" (tramp-login-program "sudo")
461 (tramp-login-args (("-u" "%u")
462 ("-s") ("-H") ("-p" "Password:")))
463 (tramp-remote-sh "/bin/sh")
464 (tramp-copy-program nil)
465 (tramp-copy-args nil)
466 (tramp-copy-keep-date nil)
467 (tramp-password-end-of-line nil))
468 ("scpc" (tramp-login-program "ssh")
469 (tramp-login-args (("-l" "%u") ("-p" "%p")
470 ("-o" "ControlPath=%t.%%r@%%h:%%p")
471 ("-o" "ControlMaster=yes")
472 ("-e" "none") ("%h")))
473 (tramp-async-args (("-q")))
474 (tramp-remote-sh "/bin/sh")
475 (tramp-copy-program "scp")
476 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
477 ("-o" "ControlPath=%t.%%r@%%h:%%p")
478 ("-o" "ControlMaster=auto")))
479 (tramp-copy-keep-date t)
480 (tramp-password-end-of-line nil)
481 (tramp-gw-args (("-o"
482 "GlobalKnownHostsFile=/dev/null")
483 ("-o" "UserKnownHostsFile=/dev/null")
484 ("-o" "StrictHostKeyChecking=no")))
485 (tramp-default-port 22))
486 ("scpx" (tramp-login-program "ssh")
487 (tramp-login-args (("-l" "%u") ("-p" "%p")
488 ("-e" "none") ("-t" "-t")
489 ("%h") ("/bin/sh")))
490 (tramp-async-args (("-q")))
491 (tramp-remote-sh "/bin/sh")
492 (tramp-copy-program "scp")
493 (tramp-copy-args (("-p" "%k")))
494 (tramp-copy-keep-date t)
495 (tramp-password-end-of-line nil)
496 (tramp-gw-args (("-o"
497 "GlobalKnownHostsFile=/dev/null")
498 ("-o" "UserKnownHostsFile=/dev/null")
499 ("-o" "StrictHostKeyChecking=no")))
500 (tramp-default-port 22))
501 ("sshx" (tramp-login-program "ssh")
502 (tramp-login-args (("-l" "%u") ("-p" "%p")
503 ("-e" "none") ("-t" "-t")
504 ("%h") ("/bin/sh")))
505 (tramp-async-args (("-q")))
506 (tramp-remote-sh "/bin/sh")
507 (tramp-copy-program nil)
508 (tramp-copy-args nil)
509 (tramp-copy-keep-date nil)
510 (tramp-password-end-of-line nil)
511 (tramp-gw-args (("-o"
512 "GlobalKnownHostsFile=/dev/null")
513 ("-o" "UserKnownHostsFile=/dev/null")
514 ("-o" "StrictHostKeyChecking=no")))
515 (tramp-default-port 22))
516 ("krlogin"
517 (tramp-login-program "krlogin")
518 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
519 (tramp-remote-sh "/bin/sh")
520 (tramp-copy-program nil)
521 (tramp-copy-args nil)
522 (tramp-copy-keep-date nil)
523 (tramp-password-end-of-line nil))
524 ("plink" (tramp-login-program "plink")
525 (tramp-login-args (("-l" "%u") ("-P" "%p")
526 ("-ssh") ("%h")))
527 (tramp-remote-sh "/bin/sh")
528 (tramp-copy-program nil)
529 (tramp-copy-args nil)
530 (tramp-copy-keep-date nil)
531 (tramp-password-end-of-line "xy") ;see docstring for "xy"
532 (tramp-default-port 22))
533 ("plink1"
534 (tramp-login-program "plink")
535 (tramp-login-args (("-l" "%u") ("-P" "%p")
536 ("-1" "-ssh") ("%h")))
537 (tramp-remote-sh "/bin/sh")
538 (tramp-copy-program nil)
539 (tramp-copy-args nil)
540 (tramp-copy-keep-date nil)
541 (tramp-password-end-of-line "xy") ;see docstring for "xy"
542 (tramp-default-port 22))
543 ("plinkx"
544 (tramp-login-program "plink")
545 ;; ("%h") must be a single element, see
546 ;; `tramp-compute-multi-hops'.
547 (tramp-login-args (("-load") ("%h") ("-t")
548 (,(format
549 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
550 tramp-terminal-type
551 tramp-initial-end-of-output))
552 ("/bin/sh")))
553 (tramp-remote-sh "/bin/sh")
554 (tramp-copy-program nil)
555 (tramp-copy-args nil)
556 (tramp-copy-keep-date nil)
557 (tramp-password-end-of-line nil))
558 ("pscp" (tramp-login-program "plink")
559 (tramp-login-args (("-l" "%u") ("-P" "%p")
560 ("-ssh") ("%h")))
561 (tramp-remote-sh "/bin/sh")
562 (tramp-copy-program "pscp")
563 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
564 (tramp-copy-keep-date t)
565 (tramp-password-end-of-line "xy") ;see docstring for "xy"
566 (tramp-default-port 22))
567 ("psftp" (tramp-login-program "plink")
568 (tramp-login-args (("-l" "%u") ("-P" "%p")
569 ("-ssh") ("%h")))
570 (tramp-remote-sh "/bin/sh")
571 (tramp-copy-program "pscp")
572 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
573 (tramp-copy-keep-date t)
574 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
575 ("fcp" (tramp-login-program "fsh")
576 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
577 (tramp-remote-sh "/bin/sh -i")
578 (tramp-copy-program "fcp")
579 (tramp-copy-args (("-p" "%k")))
580 (tramp-copy-keep-date t)
581 (tramp-password-end-of-line nil)))
582 "*Alist of methods for remote files.
583 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
584 Each NAME stands for a remote access method. Each PARAM is a
585 pair of the form (KEY VALUE). The following KEYs are defined:
586 * `tramp-remote-sh'
587 This specifies the Bourne shell to use on the remote host. This
588 MUST be a Bourne-like shell. It is normally not necessary to set
589 this to any value other than \"/bin/sh\": Tramp wants to use a shell
590 which groks tilde expansion, but it can search for it. Also note
591 that \"/bin/sh\" exists on all Unixen, this might not be true for
592 the value that you decide to use. You Have Been Warned.
593 * `tramp-login-program'
594 This specifies the name of the program to use for logging in to the
595 remote host. This may be the name of rsh or a workalike program,
596 or the name of telnet or a workalike, or the name of su or a workalike.
597 * `tramp-login-args'
598 This specifies the list of arguments to pass to the above
599 mentioned program. Please note that this is a list of list of arguments,
600 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
601 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
602 There are some patterns: \"%h\" in this list is replaced by the host
603 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
604 port number, and \"%%\" can be used to obtain a literal percent character.
605 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
606 expansion (i.e. no host or no user specified), this list is not used as
607 argument. By this, arguments like (\"-l\" \"%u\") are optional.
608 \"%t\" is replaced by the temporary file name produced with
609 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
610 parameter of a program, if exists.
611 * `tramp-async-args'
612 When an asynchronous process is started, we know already that
613 the connection works. Therefore, we can pass additional
614 parameters to suppress diagnostic messages, in order not to
615 tamper the process output.
616 * `tramp-copy-program'
617 This specifies the name of the program to use for remotely copying
618 the file; this might be the absolute filename of rcp or the name of
619 a workalike program.
620 * `tramp-copy-args'
621 This specifies the list of parameters to pass to the above mentioned
622 program, the hints for `tramp-login-args' also apply here.
623 * `tramp-copy-keep-date'
624 This specifies whether the copying program when the preserves the
625 timestamp of the original file.
626 * `tramp-copy-keep-tmpfile'
627 This specifies whether a temporary local file shall be kept
628 for optimization reasons (useful for \"rsync\" methods).
629 * `tramp-copy-recursive'
630 Whether the operation copies directories recursively.
631 * `tramp-default-port'
632 The default port of a method is needed in case of gateway connections.
633 Additionally, it is used as indication which method is prepared for
634 passing gateways.
635 * `tramp-gw-args'
636 As the attribute name says, additional arguments are specified here
637 when a method is applied via a gateway.
638 * `tramp-password-end-of-line'
639 This specifies the string to use for terminating the line after
640 submitting the password. If this method parameter is nil, then the
641 value of the normal variable `tramp-default-password-end-of-line'
642 is used. This parameter is necessary because the \"plink\" program
643 requires any two characters after sending the password. These do
644 not have to be newline or carriage return characters. Other login
645 programs are happy with just one character, the newline character.
646 We use \"xy\" as the value for methods using \"plink\".
648 What does all this mean? Well, you should specify `tramp-login-program'
649 for all methods; this program is used to log in to the remote site. Then,
650 there are two ways to actually transfer the files between the local and the
651 remote side. One way is using an additional rcp-like program. If you want
652 to do this, set `tramp-copy-program' in the method.
654 Another possibility for file transfer is inline transfer, i.e. the
655 file is passed through the same buffer used by `tramp-login-program'. In
656 this case, the file contents need to be protected since the
657 `tramp-login-program' might use escape codes or the connection might not
658 be eight-bit clean. Therefore, file contents are encoded for transit.
659 See the variables `tramp-local-coding-commands' and
660 `tramp-remote-coding-commands' for details.
662 So, to summarize: if the method is an out-of-band method, then you
663 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
664 inline method, then these two parameters should be nil. Methods which
665 are fit for gateways must have `tramp-default-port' at least.
667 Notes:
669 When using `su' or `sudo' the phrase `open connection to a remote
670 host' sounds strange, but it is used nevertheless, for consistency.
671 No connection is opened to a remote host, but `su' or `sudo' is
672 started on the local host. You should specify a remote host
673 `localhost' or the name of the local host. Another host name is
674 useful only in combination with `tramp-default-proxies-alist'.")
676 (defun tramp-detect-ssh-controlmaster ()
677 "Call ssh to detect whether it supports the ControlMaster argument.
678 This function may return nil when the argument is supported, but
679 shouldn't return t when it isn't."
680 (ignore-errors
681 (with-temp-buffer
682 (call-process "ssh" nil t nil "-o" "ControlMaster")
683 (goto-char (point-min))
684 (search-forward-regexp "Missing ControlMaster argument" nil t))))
686 (defcustom tramp-default-method
687 ;; An external copy method seems to be preferred, because it is much
688 ;; more performant for large files, and it hasn't too serious delays
689 ;; for small files. But it must be ensured that there aren't
690 ;; permanent password queries. Either a password agent like
691 ;; "ssh-agent" or "Pageant" shall run, or the optional
692 ;; password-cache.el or auth-sources.el packages shall be active for
693 ;; password caching. "scpc" is chosen if we detect that the user is
694 ;; running OpenSSH 4.0 or newer.
695 (cond
696 ;; PuTTY is installed.
697 ((executable-find "pscp")
698 (if (or (fboundp 'password-read)
699 (fboundp 'auth-source-user-or-password)
700 ;; Pageant is running.
701 (tramp-compat-process-running-p "Pageant"))
702 "pscp"
703 "plink"))
704 ;; There is an ssh installation.
705 ((executable-find "scp")
706 (cond
707 ((tramp-detect-ssh-controlmaster) "scpc")
708 ((or (fboundp 'password-read)
709 (fboundp 'auth-source-user-or-password)
710 ;; ssh-agent is running.
711 (getenv "SSH_AUTH_SOCK")
712 (getenv "SSH_AGENT_PID"))
713 "scp")
714 (t "ssh")))
715 ;; Fallback.
716 (t "ftp"))
717 "*Default method to use for transferring files.
718 See `tramp-methods' for possibilities.
719 Also see `tramp-default-method-alist'."
720 :group 'tramp
721 :type 'string)
723 (defcustom tramp-default-method-alist
724 '(("\\`localhost\\'" "\\`root\\'" "su"))
725 "*Default method to use for specific host/user pairs.
726 This is an alist of items (HOST USER METHOD). The first matching item
727 specifies the method to use for a file name which does not specify a
728 method. HOST and USER are regular expressions or nil, which is
729 interpreted as a regular expression which always matches. If no entry
730 matches, the variable `tramp-default-method' takes effect.
732 If the file name does not specify the user, lookup is done using the
733 empty string for the user name.
735 See `tramp-methods' for a list of possibilities for METHOD."
736 :group 'tramp
737 :type '(repeat (list (regexp :tag "Host regexp")
738 (regexp :tag "User regexp")
739 (string :tag "Method"))))
741 (defcustom tramp-default-user
743 "*Default user to use for transferring files.
744 It is nil by default; otherwise settings in configuration files like
745 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
747 This variable is regarded as obsolete, and will be removed soon."
748 :group 'tramp
749 :type '(choice (const nil) string))
751 (defcustom tramp-default-user-alist
752 `(("\\`su\\(do\\)?\\'" nil "root")
753 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
754 nil ,(user-login-name)))
755 "*Default user to use for specific method/host pairs.
756 This is an alist of items (METHOD HOST USER). The first matching item
757 specifies the user to use for a file name which does not specify a
758 user. METHOD and USER are regular expressions or nil, which is
759 interpreted as a regular expression which always matches. If no entry
760 matches, the variable `tramp-default-user' takes effect.
762 If the file name does not specify the method, lookup is done using the
763 empty string for the method name."
764 :group 'tramp
765 :type '(repeat (list (regexp :tag "Method regexp")
766 (regexp :tag "Host regexp")
767 (string :tag "User"))))
769 (defcustom tramp-default-host
770 (system-name)
771 "*Default host to use for transferring files.
772 Useful for su and sudo methods mostly."
773 :group 'tramp
774 :type 'string)
776 (defcustom tramp-default-proxies-alist nil
777 "*Route to be followed for specific host/user pairs.
778 This is an alist of items (HOST USER PROXY). The first matching
779 item specifies the proxy to be passed for a file name located on
780 a remote target matching USER@HOST. HOST and USER are regular
781 expressions. PROXY must be a Tramp filename without a localname
782 part. Method and user name on PROXY are optional, which is
783 interpreted with the default values. PROXY can contain the
784 patterns %h and %u, which are replaced by the strings matching
785 HOST or USER, respectively.
787 HOST, USER or PROXY could also be Lisp forms, which will be
788 evaluated. The result must be a string or nil, which is
789 interpreted as a regular expression which always matches."
790 :group 'tramp
791 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
792 (choice :tag "User regexp" regexp sexp)
793 (choice :tag "Proxy remote name" string (const nil)))))
795 (defconst tramp-local-host-regexp
796 (concat
797 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
798 "*Host names which are regarded as local host.")
800 (defconst tramp-completion-function-alist-rsh
801 '((tramp-parse-rhosts "/etc/hosts.equiv")
802 (tramp-parse-rhosts "~/.rhosts"))
803 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
805 (defconst tramp-completion-function-alist-ssh
806 '((tramp-parse-rhosts "/etc/hosts.equiv")
807 (tramp-parse-rhosts "/etc/shosts.equiv")
808 (tramp-parse-shosts "/etc/ssh_known_hosts")
809 (tramp-parse-sconfig "/etc/ssh_config")
810 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
811 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
812 (tramp-parse-rhosts "~/.rhosts")
813 (tramp-parse-rhosts "~/.shosts")
814 (tramp-parse-shosts "~/.ssh/known_hosts")
815 (tramp-parse-sconfig "~/.ssh/config")
816 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
817 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
818 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
820 (defconst tramp-completion-function-alist-telnet
821 '((tramp-parse-hosts "/etc/hosts"))
822 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
824 (defconst tramp-completion-function-alist-su
825 '((tramp-parse-passwd "/etc/passwd"))
826 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
828 (defconst tramp-completion-function-alist-putty
829 '((tramp-parse-putty
830 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
831 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
833 (defvar tramp-completion-function-alist nil
834 "*Alist of methods for remote files.
835 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
836 Each NAME stands for a remote access method. Each PAIR is of the form
837 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
838 names from FILE for completion. The following predefined FUNCTIONs exists:
840 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
841 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
842 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
843 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
844 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
845 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
846 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
847 * `tramp-parse-netrc' for \"~/.netrc\" like files.
848 * `tramp-parse-putty' for PuTTY registry keys.
850 FUNCTION can also be a customer defined function. For more details see
851 the info pages.")
853 (eval-after-load "tramp"
854 '(progn
855 (tramp-set-completion-function
856 "rcp" tramp-completion-function-alist-rsh)
857 (tramp-set-completion-function
858 "scp" tramp-completion-function-alist-ssh)
859 (tramp-set-completion-function
860 "scp1" tramp-completion-function-alist-ssh)
861 (tramp-set-completion-function
862 "scp2" tramp-completion-function-alist-ssh)
863 (tramp-set-completion-function
864 "scp1_old" tramp-completion-function-alist-ssh)
865 (tramp-set-completion-function
866 "scp2_old" tramp-completion-function-alist-ssh)
867 (tramp-set-completion-function
868 "rsync" tramp-completion-function-alist-ssh)
869 (tramp-set-completion-function
870 "rsyncc" tramp-completion-function-alist-ssh)
871 (tramp-set-completion-function
872 "remcp" tramp-completion-function-alist-rsh)
873 (tramp-set-completion-function
874 "rsh" tramp-completion-function-alist-rsh)
875 (tramp-set-completion-function
876 "ssh" tramp-completion-function-alist-ssh)
877 (tramp-set-completion-function
878 "ssh1" tramp-completion-function-alist-ssh)
879 (tramp-set-completion-function
880 "ssh2" tramp-completion-function-alist-ssh)
881 (tramp-set-completion-function
882 "ssh1_old" tramp-completion-function-alist-ssh)
883 (tramp-set-completion-function
884 "ssh2_old" tramp-completion-function-alist-ssh)
885 (tramp-set-completion-function
886 "remsh" tramp-completion-function-alist-rsh)
887 (tramp-set-completion-function
888 "telnet" tramp-completion-function-alist-telnet)
889 (tramp-set-completion-function
890 "su" tramp-completion-function-alist-su)
891 (tramp-set-completion-function
892 "sudo" tramp-completion-function-alist-su)
893 (tramp-set-completion-function
894 "scpx" tramp-completion-function-alist-ssh)
895 (tramp-set-completion-function
896 "sshx" tramp-completion-function-alist-ssh)
897 (tramp-set-completion-function
898 "krlogin" tramp-completion-function-alist-rsh)
899 (tramp-set-completion-function
900 "plink" tramp-completion-function-alist-ssh)
901 (tramp-set-completion-function
902 "plink1" tramp-completion-function-alist-ssh)
903 (tramp-set-completion-function
904 "plinkx" tramp-completion-function-alist-putty)
905 (tramp-set-completion-function
906 "pscp" tramp-completion-function-alist-ssh)
907 (tramp-set-completion-function
908 "fcp" tramp-completion-function-alist-ssh)))
910 (defconst tramp-echo-mark-marker "_echo"
911 "String marker to surround echoed commands.")
913 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
914 "String length of `tramp-echo-mark-marker'.")
916 (defconst tramp-echo-mark
917 (concat tramp-echo-mark-marker
918 (make-string tramp-echo-mark-marker-length ?\b))
919 "String mark to be transmitted around shell commands.
920 Used to separate their echo from the output they produce. This
921 will only be used if we cannot disable remote echo via stty.
922 This string must have no effect on the remote shell except for
923 producing some echo which can later be detected by
924 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
925 followed by an equal number of backspaces to erase them will
926 usually suffice.")
928 (defconst tramp-echoed-echo-mark-regexp
929 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
930 tramp-echo-mark-marker tramp-echo-mark-marker-length)
931 "Regexp which matches `tramp-echo-mark' as it gets echoed by
932 the remote shell.")
934 (defcustom tramp-rsh-end-of-line "\n"
935 "*String used for end of line in rsh connections.
936 I don't think this ever needs to be changed, so please tell me about it
937 if you need to change this.
938 Also see the method parameter `tramp-password-end-of-line' and the normal
939 variable `tramp-default-password-end-of-line'."
940 :group 'tramp
941 :type 'string)
943 (defcustom tramp-default-password-end-of-line
944 tramp-rsh-end-of-line
945 "*String used for end of line after sending a password.
946 This variable provides the default value for the method parameter
947 `tramp-password-end-of-line', see `tramp-methods' for more details.
949 It seems that people using plink under Windows need to send
950 \"\\r\\n\" (carriage-return, then newline) after a password, but just
951 \"\\n\" after all other lines. This variable can be used for the
952 password, see `tramp-rsh-end-of-line' for the other cases.
954 The default value is to use the same value as `tramp-rsh-end-of-line'."
955 :group 'tramp
956 :type 'string)
958 ;; "getconf PATH" yields:
959 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
960 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
961 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
962 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
963 ;; IRIX64: /usr/bin
964 (defcustom tramp-remote-path
965 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
966 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
967 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
968 "*List of directories to search for executables on remote host.
969 For every remote host, this variable will be set buffer local,
970 keeping the list of existing directories on that host.
972 You can use `~' in this list, but when searching for a shell which groks
973 tilde expansion, all directory names starting with `~' will be ignored.
975 `Default Directories' represent the list of directories given by
976 the command \"getconf PATH\". It is recommended to use this
977 entry on top of this list, because these are the default
978 directories for POSIX compatible commands.
980 `Private Directories' are the settings of the $PATH environment,
981 as given in your `~/.profile'."
982 :group 'tramp
983 :type '(repeat (choice
984 (const :tag "Default Directories" tramp-default-remote-path)
985 (const :tag "Private Directories" tramp-own-remote-path)
986 (string :tag "Directory"))))
988 (defcustom tramp-remote-process-environment
989 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
990 ,(format "TERM=%s" tramp-terminal-type)
991 "EMACS=t" ;; Deprecated.
992 ,(format "INSIDE_EMACS='%s,tramp:%s'" emacs-version tramp-version)
993 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
994 "autocorrect=" "correct=")
996 "*List of environment variables to be set on the remote host.
998 Each element should be a string of the form ENVVARNAME=VALUE. An
999 entry ENVVARNAME= diables the corresponding environment variable,
1000 which might have been set in the init files like ~/.profile.
1002 Special handling is applied to the PATH environment, which should
1003 not be set here. Instead of, it should be set via `tramp-remote-path'."
1004 :group 'tramp
1005 :type '(repeat string))
1007 (defcustom tramp-login-prompt-regexp
1008 ".*ogin\\( .*\\)?: *"
1009 "*Regexp matching login-like prompts.
1010 The regexp should match at end of buffer.
1012 Sometimes the prompt is reported to look like \"login as:\"."
1013 :group 'tramp
1014 :type 'regexp)
1016 (defcustom tramp-shell-prompt-pattern
1017 ;; Allow a prompt to start right after a ^M since it indeed would be
1018 ;; displayed at the beginning of the line (and Zsh uses it). This
1019 ;; regexp works only for GNU Emacs.
1020 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
1021 "[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
1022 "Regexp to match prompts from remote shell.
1023 Normally, Tramp expects you to configure `shell-prompt-pattern'
1024 correctly, but sometimes it happens that you are connecting to a
1025 remote host which sends a different kind of shell prompt. Therefore,
1026 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1027 and also things matched by this variable. The default value of this
1028 variable is similar to the default value of `shell-prompt-pattern',
1029 which should work well in many cases.
1031 This regexp must match both `tramp-initial-end-of-output' and
1032 `tramp-end-of-output'."
1033 :group 'tramp
1034 :type 'regexp)
1036 (defcustom tramp-password-prompt-regexp
1037 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1038 "*Regexp matching password-like prompts.
1039 The regexp should match at end of buffer.
1041 The `sudo' program appears to insert a `^@' character into the prompt."
1042 :group 'tramp
1043 :type 'regexp)
1045 (defcustom tramp-wrong-passwd-regexp
1046 (concat "^.*"
1047 ;; These strings should be on the last line
1048 (regexp-opt '("Permission denied"
1049 "Login incorrect"
1050 "Login Incorrect"
1051 "Connection refused"
1052 "Connection closed"
1053 "Timeout, server not responding."
1054 "Sorry, try again."
1055 "Name or service not known"
1056 "Host key verification failed."
1057 "No supported authentication methods left to try!") t)
1058 ".*"
1059 "\\|"
1060 "^.*\\("
1061 ;; Here comes a list of regexes, separated by \\|
1062 "Received signal [0-9]+"
1063 "\\).*")
1064 "*Regexp matching a `login failed' message.
1065 The regexp should match at end of buffer."
1066 :group 'tramp
1067 :type 'regexp)
1069 (defcustom tramp-yesno-prompt-regexp
1070 (concat
1071 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1072 "\\s-*")
1073 "Regular expression matching all yes/no queries which need to be confirmed.
1074 The confirmation should be done with yes or no.
1075 The regexp should match at end of buffer.
1076 See also `tramp-yn-prompt-regexp'."
1077 :group 'tramp
1078 :type 'regexp)
1080 (defcustom tramp-yn-prompt-regexp
1081 (concat
1082 (regexp-opt '("Store key in cache? (y/n)"
1083 "Update cached key? (y/n, Return cancels connection)") t)
1084 "\\s-*")
1085 "Regular expression matching all y/n queries which need to be confirmed.
1086 The confirmation should be done with y or n.
1087 The regexp should match at end of buffer.
1088 See also `tramp-yesno-prompt-regexp'."
1089 :group 'tramp
1090 :type 'regexp)
1092 (defcustom tramp-terminal-prompt-regexp
1093 (concat "\\("
1094 "TERM = (.*)"
1095 "\\|"
1096 "Terminal type\\? \\[.*\\]"
1097 "\\)\\s-*")
1098 "Regular expression matching all terminal setting prompts.
1099 The regexp should match at end of buffer.
1100 The answer will be provided by `tramp-action-terminal', which see."
1101 :group 'tramp
1102 :type 'regexp)
1104 (defcustom tramp-operation-not-permitted-regexp
1105 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1106 (regexp-opt '("Operation not permitted") t))
1107 "Regular expression matching keep-date problems in (s)cp operations.
1108 Copying has been performed successfully already, so this message can
1109 be ignored safely."
1110 :group 'tramp
1111 :type 'regexp)
1113 (defcustom tramp-copy-failed-regexp
1114 (concat "\\(.+: "
1115 (regexp-opt '("Permission denied"
1116 "not a regular file"
1117 "is a directory"
1118 "No such file or directory") t)
1119 "\\)\\s-*")
1120 "Regular expression matching copy problems in (s)cp operations."
1121 :group 'tramp
1122 :type 'regexp)
1124 (defcustom tramp-process-alive-regexp
1126 "Regular expression indicating a process has finished.
1127 In fact this expression is empty by intention, it will be used only to
1128 check regularly the status of the associated process.
1129 The answer will be provided by `tramp-action-process-alive',
1130 `tramp-action-out-of-band', which see."
1131 :group 'tramp
1132 :type 'regexp)
1134 (defcustom tramp-temp-name-prefix "tramp."
1135 "*Prefix to use for temporary files.
1136 If this is a relative file name (such as \"tramp.\"), it is considered
1137 relative to the directory name returned by the function
1138 `tramp-compat-temporary-file-directory' (which see). It may also be an
1139 absolute file name; don't forget to include a prefix for the filename
1140 part, though."
1141 :group 'tramp
1142 :type 'string)
1144 (defconst tramp-temp-buffer-name " *tramp temp*"
1145 "Buffer name for a temporary buffer.
1146 It shall be used in combination with `generate-new-buffer-name'.")
1148 (defvar tramp-temp-buffer-file-name nil
1149 "File name of a persistent local temporary file.
1150 Useful for \"rsync\" like methods.")
1151 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1153 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1154 "*Alist specifying extra arguments to pass to the remote shell.
1155 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1156 matching the shell file name and ARGS is a string specifying the
1157 arguments.
1159 This variable is only used when Tramp needs to start up another shell
1160 for tilde expansion. The extra arguments should typically prevent the
1161 shell from reading its init file."
1162 :group 'tramp
1163 ;; This might be the wrong way to test whether the widget type
1164 ;; `alist' is available. Who knows the right way to test it?
1165 :type (if (get 'alist 'widget-type)
1166 '(alist :key-type string :value-type string)
1167 '(repeat (cons string string))))
1169 ;; XEmacs is distributed with few Lisp packages. Further packages are
1170 ;; installed using EFS. If we use a unified filename format, then
1171 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1172 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1173 ;; just like before.) Another reason for using a separate filename
1174 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1175 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1176 ;; the other places.
1178 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1179 ;;;###autoload
1180 (defcustom tramp-syntax
1181 (if (featurep 'xemacs) 'sep 'ftp)
1182 "Tramp filename syntax to be used.
1184 It can have the following values:
1186 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1187 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1188 'url -- URL-like syntax."
1189 :group 'tramp
1190 :type (if (featurep 'xemacs)
1191 '(choice (const :tag "EFS" ftp)
1192 (const :tag "XEmacs" sep)
1193 (const :tag "URL" url))
1194 '(choice (const :tag "Ange-FTP" ftp)
1195 (const :tag "URL" url))))
1197 (defconst tramp-prefix-format
1198 (cond ((equal tramp-syntax 'ftp) "/")
1199 ((equal tramp-syntax 'sep) "/[")
1200 ((equal tramp-syntax 'url) "/")
1201 (t (error "Wrong `tramp-syntax' defined")))
1202 "*String matching the very beginning of Tramp file names.
1203 Used in `tramp-make-tramp-file-name'.")
1205 (defconst tramp-prefix-regexp
1206 (concat "^" (regexp-quote tramp-prefix-format))
1207 "*Regexp matching the very beginning of Tramp file names.
1208 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1210 (defconst tramp-method-regexp
1211 "[a-zA-Z_0-9-]+"
1212 "*Regexp matching methods identifiers.")
1214 (defconst tramp-postfix-method-format
1215 (cond ((equal tramp-syntax 'ftp) ":")
1216 ((equal tramp-syntax 'sep) "/")
1217 ((equal tramp-syntax 'url) "://")
1218 (t (error "Wrong `tramp-syntax' defined")))
1219 "*String matching delimeter between method and user or host names.
1220 Used in `tramp-make-tramp-file-name'.")
1222 (defconst tramp-postfix-method-regexp
1223 (regexp-quote tramp-postfix-method-format)
1224 "*Regexp matching delimeter between method and user or host names.
1225 Derived from `tramp-postfix-method-format'.")
1227 (defconst tramp-user-regexp
1228 "[^:/ \t]+"
1229 "*Regexp matching user names.")
1231 (defconst tramp-prefix-domain-format "%"
1232 "*String matching delimeter between user and domain names.")
1234 (defconst tramp-prefix-domain-regexp
1235 (regexp-quote tramp-prefix-domain-format)
1236 "*Regexp matching delimeter between user and domain names.
1237 Derived from `tramp-prefix-domain-format'.")
1239 (defconst tramp-domain-regexp
1240 "[-a-zA-Z0-9_.]+"
1241 "*Regexp matching domain names.")
1243 (defconst tramp-user-with-domain-regexp
1244 (concat "\\(" tramp-user-regexp "\\)"
1245 tramp-prefix-domain-regexp
1246 "\\(" tramp-domain-regexp "\\)")
1247 "*Regexp matching user names with domain names.")
1249 (defconst tramp-postfix-user-format
1251 "*String matching delimeter between user and host names.
1252 Used in `tramp-make-tramp-file-name'.")
1254 (defconst tramp-postfix-user-regexp
1255 (regexp-quote tramp-postfix-user-format)
1256 "*Regexp matching delimeter between user and host names.
1257 Derived from `tramp-postfix-user-format'.")
1259 (defconst tramp-host-regexp
1260 "[a-zA-Z0-9_.-]+"
1261 "*Regexp matching host names.")
1263 (defconst tramp-prefix-ipv6-format
1264 (cond ((equal tramp-syntax 'ftp) "[")
1265 ((equal tramp-syntax 'sep) "")
1266 ((equal tramp-syntax 'url) "[")
1267 (t (error "Wrong `tramp-syntax' defined")))
1268 "*String matching left hand side of IPv6 addresses.
1269 Used in `tramp-make-tramp-file-name'.")
1271 (defconst tramp-prefix-ipv6-regexp
1272 (regexp-quote tramp-prefix-ipv6-format)
1273 "*Regexp matching left hand side of IPv6 addresses.
1274 Derived from `tramp-prefix-ipv6-format'.")
1276 ;; The following regexp is a bit sloppy. But it shall serve our
1277 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1278 ;; "::ffff:192.168.0.1".
1279 (defconst tramp-ipv6-regexp
1280 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1281 "*Regexp matching IPv6 addresses.")
1283 (defconst tramp-postfix-ipv6-format
1284 (cond ((equal tramp-syntax 'ftp) "]")
1285 ((equal tramp-syntax 'sep) "")
1286 ((equal tramp-syntax 'url) "]")
1287 (t (error "Wrong `tramp-syntax' defined")))
1288 "*String matching right hand side of IPv6 addresses.
1289 Used in `tramp-make-tramp-file-name'.")
1291 (defconst tramp-postfix-ipv6-regexp
1292 (regexp-quote tramp-postfix-ipv6-format)
1293 "*Regexp matching right hand side of IPv6 addresses.
1294 Derived from `tramp-postfix-ipv6-format'.")
1296 (defconst tramp-prefix-port-format
1297 (cond ((equal tramp-syntax 'ftp) "#")
1298 ((equal tramp-syntax 'sep) "#")
1299 ((equal tramp-syntax 'url) ":")
1300 (t (error "Wrong `tramp-syntax' defined")))
1301 "*String matching delimeter between host names and port numbers.")
1303 (defconst tramp-prefix-port-regexp
1304 (regexp-quote tramp-prefix-port-format)
1305 "*Regexp matching delimeter between host names and port numbers.
1306 Derived from `tramp-prefix-port-format'.")
1308 (defconst tramp-port-regexp
1309 "[0-9]+"
1310 "*Regexp matching port numbers.")
1312 (defconst tramp-host-with-port-regexp
1313 (concat "\\(" tramp-host-regexp "\\)"
1314 tramp-prefix-port-regexp
1315 "\\(" tramp-port-regexp "\\)")
1316 "*Regexp matching host names with port numbers.")
1318 (defconst tramp-postfix-host-format
1319 (cond ((equal tramp-syntax 'ftp) ":")
1320 ((equal tramp-syntax 'sep) "]")
1321 ((equal tramp-syntax 'url) "")
1322 (t (error "Wrong `tramp-syntax' defined")))
1323 "*String matching delimeter between host names and localnames.
1324 Used in `tramp-make-tramp-file-name'.")
1326 (defconst tramp-postfix-host-regexp
1327 (regexp-quote tramp-postfix-host-format)
1328 "*Regexp matching delimeter between host names and localnames.
1329 Derived from `tramp-postfix-host-format'.")
1331 (defconst tramp-localname-regexp
1332 ".*$"
1333 "*Regexp matching localnames.")
1335 ;; File name format.
1337 (defconst tramp-file-name-structure
1338 (list
1339 (concat
1340 tramp-prefix-regexp
1341 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1342 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1343 "\\(" "\\(" tramp-host-regexp
1344 "\\|"
1345 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1346 tramp-postfix-ipv6-regexp "\\)"
1347 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1348 tramp-postfix-host-regexp
1349 "\\(" tramp-localname-regexp "\\)")
1350 2 4 5 8)
1352 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1353 the Tramp file name structure.
1355 The first element REGEXP is a regular expression matching a Tramp file
1356 name. The regex should contain parentheses around the method name,
1357 the user name, the host name, and the file name parts.
1359 The second element METHOD is a number, saying which pair of
1360 parentheses matches the method name. The third element USER is
1361 similar, but for the user name. The fourth element HOST is similar,
1362 but for the host name. The fifth element FILE is for the file name.
1363 These numbers are passed directly to `match-string', which see. That
1364 means the opening parentheses are counted to identify the pair.
1366 See also `tramp-file-name-regexp'.")
1368 ;;;###autoload
1369 (defconst tramp-file-name-regexp-unified
1370 (if (memq system-type '(cygwin windows-nt))
1371 "\\`/\\([^[/:]\\{2,\\}\\|[^/]\\{2,\\}]\\):"
1372 "\\`/\\([^[/:]+\\|[^/]+]\\):")
1373 "Value for `tramp-file-name-regexp' for unified remoting.
1374 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1375 Tramp. See `tramp-file-name-structure' for more explanations.
1377 On W32 systems, the volume letter must be ignored.")
1379 ;;;###autoload
1380 (defconst tramp-file-name-regexp-separate
1381 "\\`/\\[.*\\]"
1382 "Value for `tramp-file-name-regexp' for separate remoting.
1383 XEmacs uses a separate filename syntax for Tramp and EFS.
1384 See `tramp-file-name-structure' for more explanations.")
1386 ;;;###autoload
1387 (defconst tramp-file-name-regexp-url
1388 "\\`/[^/:]+://"
1389 "Value for `tramp-file-name-regexp' for URL-like remoting.
1390 See `tramp-file-name-structure' for more explanations.")
1392 ;;;###autoload
1393 (defconst tramp-file-name-regexp
1394 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1395 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1396 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1397 (t (error "Wrong `tramp-syntax' defined")))
1398 "*Regular expression matching file names handled by Tramp.
1399 This regexp should match Tramp file names but no other file names.
1400 When tramp.el is loaded, this regular expression is prepended to
1401 `file-name-handler-alist', and that is searched sequentially. Thus,
1402 if the Tramp entry appears rather early in the `file-name-handler-alist'
1403 and is a bit too general, then some files might be considered Tramp
1404 files which are not really Tramp files.
1406 Please note that the entry in `file-name-handler-alist' is made when
1407 this file \(tramp.el\) is loaded. This means that this variable must be set
1408 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1409 updated after changing this variable.
1411 Also see `tramp-file-name-structure'.")
1413 ;;;###autoload
1414 (defconst tramp-root-regexp
1415 (if (memq system-type '(cygwin windows-nt))
1416 "\\`\\([a-zA-Z]:\\)?/"
1417 "\\`/")
1418 "Beginning of an incomplete Tramp file name.
1419 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1420 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1422 ;;;###autoload
1423 (defconst tramp-completion-file-name-regexp-unified
1424 (if (memq system-type '(cygwin windows-nt))
1425 (concat tramp-root-regexp "[^/]\\{2,\\}\\'")
1426 (concat tramp-root-regexp "[^/]*\\'"))
1427 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1428 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1429 See `tramp-file-name-structure' for more explanations.
1431 On W32 systems, the volume letter must be ignored.")
1433 ;;;###autoload
1434 (defconst tramp-completion-file-name-regexp-separate
1435 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1436 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1437 XEmacs uses a separate filename syntax for Tramp and EFS.
1438 See `tramp-file-name-structure' for more explanations.")
1440 ;;;###autoload
1441 (defconst tramp-completion-file-name-regexp-url
1442 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1443 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1444 See `tramp-file-name-structure' for more explanations.")
1446 ;;;###autoload
1447 (defconst tramp-completion-file-name-regexp
1448 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1449 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1450 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1451 (t (error "Wrong `tramp-syntax' defined")))
1452 "*Regular expression matching file names handled by Tramp completion.
1453 This regexp should match partial Tramp file names only.
1455 Please note that the entry in `file-name-handler-alist' is made when
1456 this file (tramp.el) is loaded. This means that this variable must be set
1457 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1458 updated after changing this variable.
1460 Also see `tramp-file-name-structure'.")
1462 (defconst tramp-actions-before-shell
1463 '((tramp-login-prompt-regexp tramp-action-login)
1464 (tramp-password-prompt-regexp tramp-action-password)
1465 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1466 (shell-prompt-pattern tramp-action-succeed)
1467 (tramp-shell-prompt-pattern tramp-action-succeed)
1468 (tramp-yesno-prompt-regexp tramp-action-yesno)
1469 (tramp-yn-prompt-regexp tramp-action-yn)
1470 (tramp-terminal-prompt-regexp tramp-action-terminal)
1471 (tramp-process-alive-regexp tramp-action-process-alive))
1472 "List of pattern/action pairs.
1473 Whenever a pattern matches, the corresponding action is performed.
1474 Each item looks like (PATTERN ACTION).
1476 The PATTERN should be a symbol, a variable. The value of this
1477 variable gives the regular expression to search for. Note that the
1478 regexp must match at the end of the buffer, \"\\'\" is implicitly
1479 appended to it.
1481 The ACTION should also be a symbol, but a function. When the
1482 corresponding PATTERN matches, the ACTION function is called.")
1484 (defconst tramp-actions-copy-out-of-band
1485 '((tramp-password-prompt-regexp tramp-action-password)
1486 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1487 (tramp-copy-failed-regexp tramp-action-permission-denied)
1488 (tramp-process-alive-regexp tramp-action-out-of-band))
1489 "List of pattern/action pairs.
1490 This list is used for copying/renaming with out-of-band methods.
1492 See `tramp-actions-before-shell' for more info.")
1494 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1495 ;; known to have a bug in `process-send-string'; some ssh connections appear
1496 ;; to drop bytes when data is sent too quickly. There is also a connection
1497 ;; buffer local variable, which is computed depending on remote host properties
1498 ;; when `tramp-chunksize' is zero or nil.
1499 (defcustom tramp-chunksize
1500 (when (and (not (featurep 'xemacs))
1501 (memq system-type '(hpux)))
1502 500)
1503 ;; Parentheses in docstring starting at beginning of line are escaped.
1504 ;; Fontification is messed up when
1505 ;; `open-paren-in-column-0-is-defun-start' set to t.
1506 "*If non-nil, chunksize for sending input to local process.
1507 It is necessary only on systems which have a buggy `process-send-string'
1508 implementation. The necessity, whether this variable must be set, can be
1509 checked via the following code:
1511 (with-temp-buffer
1512 (let* ((user \"xxx\") (host \"yyy\")
1513 (init 0) (step 50)
1514 (sent init) (received init))
1515 (while (= sent received)
1516 (setq sent (+ sent step))
1517 (erase-buffer)
1518 (let ((proc (start-process (buffer-name) (current-buffer)
1519 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1520 (when (memq (process-status proc) '(run open))
1521 (process-send-string proc (make-string sent ?\\ ))
1522 (process-send-eof proc)
1523 (process-send-eof proc))
1524 (while (not (progn (goto-char (point-min))
1525 (re-search-forward \"\\\\w+\" (point-max) t)))
1526 (accept-process-output proc 1))
1527 (when (memq (process-status proc) '(run open))
1528 (setq received (string-to-number (match-string 0)))
1529 (delete-process proc)
1530 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1531 (sit-for 0))))
1532 (if (> sent (+ init step))
1533 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1534 (- sent step))
1535 (message \"Test does not work\")
1536 (display-buffer (current-buffer))
1537 (sit-for 30))))
1539 In the Emacs normally running Tramp, evaluate the above code
1540 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1541 respectively\). You can do this, for example, by pasting it into
1542 the `*scratch*' buffer and then hitting C-j with the cursor after the
1543 last closing parenthesis. Note that it works only if you have configured
1544 \"ssh\" to run without password query, see ssh-agent\(1\).
1546 You will see the number of bytes sent successfully to the remote host.
1547 If that number exceeds 1000, you can stop the execution by hitting
1548 C-g, because your Emacs is likely clean.
1550 When it is necessary to set `tramp-chunksize', you might consider to
1551 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1552 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
1553 performance.
1555 If your Emacs is buggy, the code stops and gives you an indication
1556 about the value `tramp-chunksize' should be set. Maybe you could just
1557 experiment a bit, e.g. changing the values of `init' and `step'
1558 in the third line of the code.
1560 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1561 this variable to be set as well."
1562 :group 'tramp
1563 :type '(choice (const nil) integer))
1565 ;; Logging in to a remote host normally requires obtaining a pty. But
1566 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1567 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1568 ;; for an override of the system default.
1569 (defcustom tramp-process-connection-type t
1570 "Overrides `process-connection-type' for connections from Tramp.
1571 Tramp binds process-connection-type to the value given here before
1572 opening a connection to a remote host."
1573 :group 'tramp
1574 :type '(choice (const nil) (const t) (const pty)))
1576 (defcustom tramp-completion-reread-directory-timeout 10
1577 "Defines seconds since last remote command before rereading a directory.
1578 A remote directory might have changed its contents. In order to
1579 make it visible during file name completion in the minibuffer,
1580 Tramp flushes its cache and rereads the directory contents when
1581 more than `tramp-completion-reread-directory-timeout' seconds
1582 have been gone since last remote command execution. A value of 0
1583 would require an immediate reread during filename completion, nil
1584 means to use always cached values for the directory contents."
1585 :group 'tramp
1586 :type '(choice (const nil) integer))
1588 ;;; Internal Variables:
1590 (defvar tramp-current-method nil
1591 "Connection method for this *tramp* buffer.")
1593 (defvar tramp-current-user nil
1594 "Remote login name for this *tramp* buffer.")
1596 (defvar tramp-current-host nil
1597 "Remote host for this *tramp* buffer.")
1599 (defconst tramp-uudecode
1600 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1601 cat /tmp/tramp.$$
1602 rm -f /tmp/tramp.$$"
1603 "Shell function to implement `uudecode' to standard output.
1604 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1605 for this or `uudecode -p', but some systems don't, and for them
1606 we have this shell function.")
1608 (defconst tramp-perl-file-truename
1609 "%s -e '
1610 use File::Spec;
1611 use Cwd \"realpath\";
1613 sub recursive {
1614 my ($volume, @dirs) = @_;
1615 my $real = realpath(File::Spec->catpath(
1616 $volume, File::Spec->catdir(@dirs), \"\"));
1617 if ($real) {
1618 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1619 return ($vol, File::Spec->splitdir($dir));
1621 else {
1622 my $last = pop(@dirs);
1623 ($volume, @dirs) = recursive($volume, @dirs);
1624 push(@dirs, $last);
1625 return ($volume, @dirs);
1629 $result = realpath($ARGV[0]);
1630 if (!$result) {
1631 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1632 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1634 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1637 if ($ARGV[0] =~ /\\/$/) {
1638 $result = $result . \"/\";
1641 print \"\\\"$result\\\"\\n\";
1642 ' \"$1\" 2>/dev/null"
1643 "Perl script to produce output suitable for use with `file-truename'
1644 on the remote file system.
1645 Escape sequence %s is replaced with name of Perl binary.
1646 This string is passed to `format', so percent characters need to be doubled.")
1648 (defconst tramp-perl-file-name-all-completions
1649 "%s -e 'sub case {
1650 my $str = shift;
1651 if ($ARGV[2]) {
1652 return lc($str);
1654 else {
1655 return $str;
1658 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1659 @files = readdir(d); closedir(d);
1660 foreach $f (@files) {
1661 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1662 if (-d \"$ARGV[0]/$f\") {
1663 print \"$f/\\n\";
1665 else {
1666 print \"$f\\n\";
1670 print \"ok\\n\"
1671 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1672 "Perl script to produce output suitable for use with
1673 `file-name-all-completions' on the remote file system. Escape
1674 sequence %s is replaced with name of Perl binary. This string is
1675 passed to `format', so percent characters need to be doubled.")
1677 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1678 ;; output. If you are hacking on this, note that you get *no* output
1679 ;; unless this spits out a complete line, including the '\n' at the
1680 ;; end.
1681 ;; The device number is returned as "-1", because there will be a virtual
1682 ;; device number set in `tramp-handle-file-attributes'.
1683 (defconst tramp-perl-file-attributes
1684 "%s -e '
1685 @stat = lstat($ARGV[0]);
1686 if (!@stat) {
1687 print \"nil\\n\";
1688 exit 0;
1690 if (($stat[2] & 0170000) == 0120000)
1692 $type = readlink($ARGV[0]);
1693 $type = \"\\\"$type\\\"\";
1695 elsif (($stat[2] & 0170000) == 040000)
1697 $type = \"t\";
1699 else
1701 $type = \"nil\"
1703 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1704 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1705 printf(
1706 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1707 $type,
1708 $stat[3],
1709 $uid,
1710 $gid,
1711 $stat[8] >> 16 & 0xffff,
1712 $stat[8] & 0xffff,
1713 $stat[9] >> 16 & 0xffff,
1714 $stat[9] & 0xffff,
1715 $stat[10] >> 16 & 0xffff,
1716 $stat[10] & 0xffff,
1717 $stat[7],
1718 $stat[2],
1719 $stat[1] >> 16 & 0xffff,
1720 $stat[1] & 0xffff
1721 );' \"$1\" \"$2\" 2>/dev/null"
1722 "Perl script to produce output suitable for use with `file-attributes'
1723 on the remote file system.
1724 Escape sequence %s is replaced with name of Perl binary.
1725 This string is passed to `format', so percent characters need to be doubled.")
1727 (defconst tramp-perl-directory-files-and-attributes
1728 "%s -e '
1729 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1730 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1731 @list = readdir(DIR);
1732 closedir(DIR);
1733 $n = scalar(@list);
1734 printf(\"(\\n\");
1735 for($i = 0; $i < $n; $i++)
1737 $filename = $list[$i];
1738 @stat = lstat($filename);
1739 if (($stat[2] & 0170000) == 0120000)
1741 $type = readlink($filename);
1742 $type = \"\\\"$type\\\"\";
1744 elsif (($stat[2] & 0170000) == 040000)
1746 $type = \"t\";
1748 else
1750 $type = \"nil\"
1752 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1753 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1754 printf(
1755 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1756 $filename,
1757 $type,
1758 $stat[3],
1759 $uid,
1760 $gid,
1761 $stat[8] >> 16 & 0xffff,
1762 $stat[8] & 0xffff,
1763 $stat[9] >> 16 & 0xffff,
1764 $stat[9] & 0xffff,
1765 $stat[10] >> 16 & 0xffff,
1766 $stat[10] & 0xffff,
1767 $stat[7],
1768 $stat[2],
1769 $stat[1] >> 16 & 0xffff,
1770 $stat[1] & 0xffff,
1771 $stat[0] >> 16 & 0xffff,
1772 $stat[0] & 0xffff);
1774 printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
1775 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1776 output.
1777 Escape sequence %s is replaced with name of Perl binary.
1778 This string is passed to `format', so percent characters need to be doubled.")
1780 ;; ;; These two use uu encoding.
1781 ;; (defvar tramp-perl-encode "%s -e'\
1782 ;; print qq(begin 644 xxx\n);
1783 ;; my $s = q();
1784 ;; my $res = q();
1785 ;; while (read(STDIN, $s, 45)) {
1786 ;; print pack(q(u), $s);
1787 ;; }
1788 ;; print qq(`\n);
1789 ;; print qq(end\n);
1790 ;; '"
1791 ;; "Perl program to use for encoding a file.
1792 ;; Escape sequence %s is replaced with name of Perl binary.")
1794 ;; (defvar tramp-perl-decode "%s -ne '
1795 ;; print unpack q(u), $_;
1796 ;; '"
1797 ;; "Perl program to use for decoding a file.
1798 ;; Escape sequence %s is replaced with name of Perl binary.")
1800 ;; These two use base64 encoding.
1801 (defconst tramp-perl-encode-with-module
1802 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1803 "Perl program to use for encoding a file.
1804 Escape sequence %s is replaced with name of Perl binary.
1805 This string is passed to `format', so percent characters need to be doubled.
1806 This implementation requires the MIME::Base64 Perl module to be installed
1807 on the remote host.")
1809 (defconst tramp-perl-decode-with-module
1810 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1811 "Perl program to use for decoding a file.
1812 Escape sequence %s is replaced with name of Perl binary.
1813 This string is passed to `format', so percent characters need to be doubled.
1814 This implementation requires the MIME::Base64 Perl module to be installed
1815 on the remote host.")
1817 (defconst tramp-perl-encode
1818 "%s -e '
1819 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1820 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1821 # Free Software Foundation, Inc.
1822 use strict;
1824 my %%trans = do {
1825 my $i = 0;
1826 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1827 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1830 binmode(\\*STDIN);
1832 # We read in chunks of 54 bytes, to generate output lines
1833 # of 72 chars (plus end of line)
1834 $/ = \\54;
1836 while (my $data = <STDIN>) {
1837 my $pad = q();
1839 # Only for the last chunk, and only if did not fill the last three-byte packet
1840 if (eof) {
1841 my $mod = length($data) %% 3;
1842 $pad = q(=) x (3 - $mod) if $mod;
1845 # Not the fastest method, but it is simple: unpack to binary string, split
1846 # by groups of 6 bits and convert back from binary to byte; then map into
1847 # the translation table
1848 print
1849 join q(),
1850 map($trans{$_},
1851 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1852 $pad,
1853 qq(\\n);
1854 }' 2>/dev/null"
1855 "Perl program to use for encoding a file.
1856 Escape sequence %s is replaced with name of Perl binary.
1857 This string is passed to `format', so percent characters need to be doubled.")
1859 (defconst tramp-perl-decode
1860 "%s -e '
1861 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1862 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1863 # Free Software Foundation, Inc.
1864 use strict;
1866 my %%trans = do {
1867 my $i = 0;
1868 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1869 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1872 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1874 binmode(\\*STDOUT);
1876 # We are going to accumulate into $pending to accept any line length
1877 # (we do not check they are <= 76 chars as the RFC says)
1878 my $pending = q();
1880 while (my $data = <STDIN>) {
1881 chomp $data;
1883 # If we find one or two =, we have reached the end and
1884 # any following data is to be discarded
1885 my $finished = $data =~ s/(==?).*/$1/;
1886 $pending .= $data;
1888 my $len = length($pending);
1889 my $chunk = substr($pending, 0, $len & ~3);
1890 $pending = substr($pending, $len & ~3 + 1);
1892 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1893 # split in 8-bit chunks and convert back to char.
1894 print join q(),
1895 map $bytes{$_},
1896 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1898 last if $finished;
1899 }' 2>/dev/null"
1900 "Perl program to use for decoding a file.
1901 Escape sequence %s is replaced with name of Perl binary.
1902 This string is passed to `format', so percent characters need to be doubled.")
1904 (defconst tramp-vc-registered-read-file-names
1905 "echo \"(\"
1906 while read file; do
1907 if %s \"$file\"; then
1908 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1909 else
1910 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1912 if %s \"$file\"; then
1913 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1914 else
1915 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1917 done
1918 echo \")\""
1919 "Script to check existence of VC related files.
1920 It must be send formatted with two strings; the tests for file
1921 existence, and file readability. Input shall be read via
1922 here-document, otherwise the command could exceed maximum length
1923 of command line.")
1925 (defconst tramp-file-mode-type-map
1926 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1927 (1 . "p") ; fifo
1928 (2 . "c") ; character device
1929 (3 . "m") ; multiplexed character device (v7)
1930 (4 . "d") ; directory
1931 (5 . "?") ; Named special file (XENIX)
1932 (6 . "b") ; block device
1933 (7 . "?") ; multiplexed block device (v7)
1934 (8 . "-") ; regular file
1935 (9 . "n") ; network special file (HP-UX)
1936 (10 . "l") ; symlink
1937 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1938 (12 . "s") ; socket
1939 (13 . "D") ; door special (Solaris)
1940 (14 . "w")) ; whiteout (BSD)
1941 "A list of file types returned from the `stat' system call.
1942 This is used to map a mode number to a permission string.")
1944 ;; New handlers should be added here. The following operations can be
1945 ;; handled using the normal primitives: file-name-sans-versions,
1946 ;; get-file-buffer.
1947 (defconst tramp-file-name-handler-alist
1948 '((load . tramp-handle-load)
1949 (make-symbolic-link . tramp-handle-make-symbolic-link)
1950 (file-name-as-directory . tramp-handle-file-name-as-directory)
1951 (file-name-directory . tramp-handle-file-name-directory)
1952 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1953 (file-truename . tramp-handle-file-truename)
1954 (file-exists-p . tramp-handle-file-exists-p)
1955 (file-directory-p . tramp-handle-file-directory-p)
1956 (file-executable-p . tramp-handle-file-executable-p)
1957 (file-readable-p . tramp-handle-file-readable-p)
1958 (file-regular-p . tramp-handle-file-regular-p)
1959 (file-symlink-p . tramp-handle-file-symlink-p)
1960 (file-writable-p . tramp-handle-file-writable-p)
1961 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1962 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1963 (file-attributes . tramp-handle-file-attributes)
1964 (file-modes . tramp-handle-file-modes)
1965 (directory-files . tramp-handle-directory-files)
1966 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1967 (file-name-all-completions . tramp-handle-file-name-all-completions)
1968 (file-name-completion . tramp-handle-file-name-completion)
1969 (add-name-to-file . tramp-handle-add-name-to-file)
1970 (copy-file . tramp-handle-copy-file)
1971 (copy-directory . tramp-handle-copy-directory)
1972 (rename-file . tramp-handle-rename-file)
1973 (set-file-modes . tramp-handle-set-file-modes)
1974 (set-file-times . tramp-handle-set-file-times)
1975 (make-directory . tramp-handle-make-directory)
1976 (delete-directory . tramp-handle-delete-directory)
1977 (delete-file . tramp-handle-delete-file)
1978 (directory-file-name . tramp-handle-directory-file-name)
1979 ;; `executable-find' is not official yet.
1980 (executable-find . tramp-handle-executable-find)
1981 (start-file-process . tramp-handle-start-file-process)
1982 (process-file . tramp-handle-process-file)
1983 (shell-command . tramp-handle-shell-command)
1984 (insert-directory . tramp-handle-insert-directory)
1985 (expand-file-name . tramp-handle-expand-file-name)
1986 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
1987 (file-local-copy . tramp-handle-file-local-copy)
1988 (file-remote-p . tramp-handle-file-remote-p)
1989 (insert-file-contents . tramp-handle-insert-file-contents)
1990 (insert-file-contents-literally
1991 . tramp-handle-insert-file-contents-literally)
1992 (write-region . tramp-handle-write-region)
1993 (find-backup-file-name . tramp-handle-find-backup-file-name)
1994 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
1995 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
1996 (dired-compress-file . tramp-handle-dired-compress-file)
1997 (dired-recursive-delete-directory
1998 . tramp-handle-dired-recursive-delete-directory)
1999 (dired-uncache . tramp-handle-dired-uncache)
2000 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2001 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2002 (file-selinux-context . tramp-handle-file-selinux-context)
2003 (set-file-selinux-context . tramp-handle-set-file-selinux-context)
2004 (vc-registered . tramp-handle-vc-registered))
2005 "Alist of handler functions.
2006 Operations not mentioned here will be handled by the normal Emacs functions.")
2008 ;; Handlers for partial Tramp file names. For Emacs just
2009 ;; `file-name-all-completions' is needed.
2010 ;;;###autoload
2011 (defconst tramp-completion-file-name-handler-alist
2012 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2013 (file-name-completion . tramp-completion-handle-file-name-completion))
2014 "Alist of completion handler functions.
2015 Used for file names matching `tramp-file-name-regexp'. Operations not
2016 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2017 normal Emacs functions.")
2019 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2020 ;;;###tramp-autoload
2021 (defvar tramp-foreign-file-name-handler-alist
2022 ;; (identity . tramp-sh-file-name-handler) should always be the last
2023 ;; entry, because `identity' always matches.
2024 '((identity . tramp-sh-file-name-handler))
2025 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2026 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2027 calling HANDLER.")
2029 ;;; Internal functions which must come first:
2032 ;; ------------------------------------------------------------
2033 ;; -- Tramp file names --
2034 ;; ------------------------------------------------------------
2035 ;; Conversion functions between external representation and
2036 ;; internal data structure. Convenience functions for internal
2037 ;; data structure.
2039 (defun tramp-file-name-p (vec)
2040 "Check, whether VEC is a Tramp object."
2041 (and (vectorp vec) (= 4 (length vec))))
2043 (defun tramp-file-name-method (vec)
2044 "Return method component of VEC."
2045 (and (tramp-file-name-p vec) (aref vec 0)))
2047 (defun tramp-file-name-user (vec)
2048 "Return user component of VEC."
2049 (and (tramp-file-name-p vec) (aref vec 1)))
2051 (defun tramp-file-name-host (vec)
2052 "Return host component of VEC."
2053 (and (tramp-file-name-p vec) (aref vec 2)))
2055 (defun tramp-file-name-localname (vec)
2056 "Return localname component of VEC."
2057 (and (tramp-file-name-p vec) (aref vec 3)))
2059 ;; The user part of a Tramp file name vector can be of kind
2060 ;; "user%domain". Sometimes, we must extract these parts.
2061 (defun tramp-file-name-real-user (vec)
2062 "Return the user name of VEC without domain."
2063 (save-match-data
2064 (let ((user (tramp-file-name-user vec)))
2065 (if (and (stringp user)
2066 (string-match tramp-user-with-domain-regexp user))
2067 (match-string 1 user)
2068 user))))
2070 (defun tramp-file-name-domain (vec)
2071 "Return the domain name of VEC."
2072 (save-match-data
2073 (let ((user (tramp-file-name-user vec)))
2074 (and (stringp user)
2075 (string-match tramp-user-with-domain-regexp user)
2076 (match-string 2 user)))))
2078 ;; The host part of a Tramp file name vector can be of kind
2079 ;; "host#port". Sometimes, we must extract these parts.
2080 (defun tramp-file-name-real-host (vec)
2081 "Return the host name of VEC without port."
2082 (save-match-data
2083 (let ((host (tramp-file-name-host vec)))
2084 (if (and (stringp host)
2085 (string-match tramp-host-with-port-regexp host))
2086 (match-string 1 host)
2087 host))))
2089 (defun tramp-file-name-port (vec)
2090 "Return the port number of VEC."
2091 (save-match-data
2092 (let ((host (tramp-file-name-host vec)))
2093 (and (stringp host)
2094 (string-match tramp-host-with-port-regexp host)
2095 (string-to-number (match-string 2 host))))))
2097 ;;;###tramp-autoload
2098 (defun tramp-tramp-file-p (name)
2099 "Return t if NAME is a string with Tramp file name syntax."
2100 (save-match-data
2101 (and (stringp name) (string-match tramp-file-name-regexp name))))
2103 (defun tramp-find-method (method user host)
2104 "Return the right method string to use.
2105 This is METHOD, if non-nil. Otherwise, do a lookup in
2106 `tramp-default-method-alist'."
2107 (or method
2108 (let ((choices tramp-default-method-alist)
2109 lmethod item)
2110 (while choices
2111 (setq item (pop choices))
2112 (when (and (string-match (or (nth 0 item) "") (or host ""))
2113 (string-match (or (nth 1 item) "") (or user "")))
2114 (setq lmethod (nth 2 item))
2115 (setq choices nil)))
2116 lmethod)
2117 tramp-default-method))
2119 (defun tramp-find-user (method user host)
2120 "Return the right user string to use.
2121 This is USER, if non-nil. Otherwise, do a lookup in
2122 `tramp-default-user-alist'."
2123 (or user
2124 (let ((choices tramp-default-user-alist)
2125 luser item)
2126 (while choices
2127 (setq item (pop choices))
2128 (when (and (string-match (or (nth 0 item) "") (or method ""))
2129 (string-match (or (nth 1 item) "") (or host "")))
2130 (setq luser (nth 2 item))
2131 (setq choices nil)))
2132 luser)
2133 tramp-default-user))
2135 (defun tramp-find-host (method user host)
2136 "Return the right host string to use.
2137 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
2138 (or (and (> (length host) 0) host)
2139 tramp-default-host))
2141 (defun tramp-dissect-file-name (name &optional nodefault)
2142 "Return a `tramp-file-name' structure.
2143 The structure consists of remote method, remote user, remote host
2144 and localname (file name on remote host). If NODEFAULT is
2145 non-nil, the file name parts are not expanded to their default
2146 values."
2147 (save-match-data
2148 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
2149 (unless match (error "Not a Tramp file name: %s" name))
2150 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
2151 (user (match-string (nth 2 tramp-file-name-structure) name))
2152 (host (match-string (nth 3 tramp-file-name-structure) name))
2153 (localname (match-string (nth 4 tramp-file-name-structure) name)))
2154 (when (member method '("multi" "multiu"))
2155 (error
2156 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
2157 method))
2158 (when host
2159 (when (string-match tramp-prefix-ipv6-regexp host)
2160 (setq host (replace-match "" nil t host)))
2161 (when (string-match tramp-postfix-ipv6-regexp host)
2162 (setq host (replace-match "" nil t host))))
2163 (if nodefault
2164 (vector method user host localname)
2165 (vector
2166 (tramp-find-method method user host)
2167 (tramp-find-user method user host)
2168 (tramp-find-host method user host)
2169 localname))))))
2171 (defun tramp-buffer-name (vec)
2172 "A name for the connection buffer VEC."
2173 ;; We must use `tramp-file-name-real-host', because for gateway
2174 ;; methods the default port will be expanded later on, which would
2175 ;; tamper the name.
2176 (let ((method (tramp-file-name-method vec))
2177 (user (tramp-file-name-user vec))
2178 (host (tramp-file-name-real-host vec)))
2179 (if (not (zerop (length user)))
2180 (format "*tramp/%s %s@%s*" method user host)
2181 (format "*tramp/%s %s*" method host))))
2183 (defun tramp-make-tramp-file-name (method user host localname)
2184 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
2185 (concat tramp-prefix-format
2186 (when (not (zerop (length method)))
2187 (concat method tramp-postfix-method-format))
2188 (when (not (zerop (length user)))
2189 (concat user tramp-postfix-user-format))
2190 (when host
2191 (if (string-match tramp-ipv6-regexp host)
2192 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
2193 host))
2194 tramp-postfix-host-format
2195 (when localname localname)))
2197 (defun tramp-completion-make-tramp-file-name (method user host localname)
2198 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
2199 It must not be a complete Tramp file name, but as long as there are
2200 necessary only. This function will be used in file name completion."
2201 (concat tramp-prefix-format
2202 (when (not (zerop (length method)))
2203 (concat method tramp-postfix-method-format))
2204 (when (not (zerop (length user)))
2205 (concat user tramp-postfix-user-format))
2206 (when (not (zerop (length host)))
2207 (concat
2208 (if (string-match tramp-ipv6-regexp host)
2209 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
2210 host)
2211 tramp-postfix-host-format))
2212 (when localname localname)))
2214 (defun tramp-get-buffer (vec)
2215 "Get the connection buffer to be used for VEC."
2216 (or (get-buffer (tramp-buffer-name vec))
2217 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
2218 (setq buffer-undo-list t)
2219 (setq default-directory
2220 (tramp-make-tramp-file-name
2221 (tramp-file-name-method vec)
2222 (tramp-file-name-user vec)
2223 (tramp-file-name-host vec)
2224 "/"))
2225 (current-buffer))))
2227 (defun tramp-get-connection-buffer (vec)
2228 "Get the connection buffer to be used for VEC.
2229 In case a second asynchronous communication has been started, it is different
2230 from `tramp-get-buffer'."
2231 (or (tramp-get-connection-property vec "process-buffer" nil)
2232 (tramp-get-buffer vec)))
2234 (defun tramp-get-connection-process (vec)
2235 "Get the connection process to be used for VEC.
2236 In case a second asynchronous communication has been started, it is different
2237 from the default one."
2238 (get-process
2239 (or (tramp-get-connection-property vec "process-name" nil)
2240 (tramp-buffer-name vec))))
2242 (defun tramp-debug-buffer-name (vec)
2243 "A name for the debug buffer for VEC."
2244 ;; We must use `tramp-file-name-real-host', because for gateway
2245 ;; methods the default port will be expanded later on, which would
2246 ;; tamper the name.
2247 (let ((method (tramp-file-name-method vec))
2248 (user (tramp-file-name-user vec))
2249 (host (tramp-file-name-real-host vec)))
2250 (if (not (zerop (length user)))
2251 (format "*debug tramp/%s %s@%s*" method user host)
2252 (format "*debug tramp/%s %s*" method host))))
2254 (defconst tramp-debug-outline-regexp
2255 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
2257 (defun tramp-get-debug-buffer (vec)
2258 "Get the debug buffer for VEC."
2259 (with-current-buffer
2260 (get-buffer-create (tramp-debug-buffer-name vec))
2261 (when (bobp)
2262 (setq buffer-undo-list t)
2263 ;; Activate `outline-mode'. This runs `text-mode-hook' and
2264 ;; `outline-mode-hook'. We must prevent that local processes
2265 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
2266 ;; Furthermore, `outline-regexp' must have the correct value
2267 ;; already, because it is used by `font-lock-compile-keywords'.
2268 (let ((default-directory (tramp-compat-temporary-file-directory))
2269 (outline-regexp tramp-debug-outline-regexp))
2270 (outline-mode))
2271 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
2272 (set (make-local-variable 'outline-level) 'tramp-outline-level))
2273 (current-buffer)))
2275 (defun tramp-outline-level ()
2276 "Return the depth to which a statement is nested in the outline.
2277 Point must be at the beginning of a header line.
2279 The outline level is equal to the verbosity of the Tramp message."
2280 (1+ (string-to-number (match-string 1))))
2282 (defsubst tramp-debug-message (vec fmt-string &rest args)
2283 "Append message to debug buffer.
2284 Message is formatted with FMT-STRING as control string and the remaining
2285 ARGS to actually emit the message (if applicable)."
2286 (when (get-buffer (tramp-buffer-name vec))
2287 (with-current-buffer (tramp-get-debug-buffer vec)
2288 (goto-char (point-max))
2289 ;; Headline.
2290 (when (bobp)
2291 (insert
2292 (format
2293 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2294 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2295 emacs-version tramp-version)))
2296 (unless (bolp)
2297 (insert "\n"))
2298 ;; Timestamp.
2299 (let ((now (current-time)))
2300 (insert (format-time-string "%T." now))
2301 (insert (format "%06d " (nth 2 now))))
2302 ;; Calling function.
2303 (let ((btn 1) btf fn)
2304 (while (not fn)
2305 (setq btf (nth 1 (backtrace-frame btn)))
2306 (if (not btf)
2307 (setq fn "")
2308 (when (symbolp btf)
2309 (setq fn (symbol-name btf))
2310 (unless (and (string-match "^tramp" fn)
2311 (not (string-match
2312 "^tramp\\(-debug\\)?\\(-message\\|-error\\|-compat-funcall\\)$"
2313 fn)))
2314 (setq fn nil)))
2315 (setq btn (1+ btn))))
2316 ;; The following code inserts filename and line number.
2317 ;; Should be deactivated by default, because it is time
2318 ;; consuming.
2319 ; (let ((ffn (find-function-noselect (intern fn))))
2320 ; (insert
2321 ; (format
2322 ; "%s:%d: "
2323 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2324 ; (with-current-buffer (car ffn)
2325 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2326 (insert (format "%s " fn)))
2327 ;; The message.
2328 (insert (apply 'format fmt-string args)))))
2330 (defvar tramp-message-show-message t
2331 "Show Tramp message in the minibuffer.
2332 This variable is used to disable messages from `tramp-error'.
2333 The messages are visible anyway, because an error is raised.")
2335 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2336 "Emit a message depending on verbosity level.
2337 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2338 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2339 less than LEVEL. The message is emitted only if `tramp-verbose' is
2340 greater than or equal to LEVEL.
2342 The message is also logged into the debug buffer when `tramp-verbose'
2343 is greater than or equal 4.
2345 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2346 control string and the remaining ARGS to actually emit the message (if
2347 applicable)."
2348 (condition-case nil
2349 (when (<= level tramp-verbose)
2350 ;; Match data must be preserved!
2351 (save-match-data
2352 ;; Display only when there is a minimum level.
2353 (when (and tramp-message-show-message (<= level 3))
2354 (apply 'message
2355 (concat
2356 (cond
2357 ((= level 0) "")
2358 ((= level 1) "")
2359 ((= level 2) "Warning: ")
2360 (t "Tramp: "))
2361 fmt-string)
2362 args))
2363 ;; Log only when there is a minimum level.
2364 (when (>= tramp-verbose 4)
2365 (when (and vec-or-proc
2366 (processp vec-or-proc)
2367 (buffer-name (process-buffer vec-or-proc)))
2368 (with-current-buffer (process-buffer vec-or-proc)
2369 ;; Translate proc to vec.
2370 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2371 (when (and vec-or-proc (vectorp vec-or-proc))
2372 (apply 'tramp-debug-message
2373 vec-or-proc
2374 (concat (format "(%d) # " level) fmt-string)
2375 args)))))
2376 ;; Suppress all errors.
2377 (error nil)))
2379 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2380 "Emit an error.
2381 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2382 signal identifier to be raised, remaining args passed to
2383 `tramp-message'. Finally, signal SIGNAL is raised."
2384 (let (tramp-message-show-message)
2385 (tramp-message
2386 vec-or-proc 1 "%s"
2387 (error-message-string
2388 (list signal
2389 (get signal 'error-message)
2390 (apply 'format fmt-string args))))
2391 (signal signal (list (apply 'format fmt-string args)))))
2393 (defsubst tramp-error-with-buffer
2394 (buffer vec-or-proc signal fmt-string &rest args)
2395 "Emit an error, and show BUFFER.
2396 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2397 an input event arrives. The other arguments are passed to `tramp-error'."
2398 (save-window-excursion
2399 (unwind-protect
2400 (apply 'tramp-error vec-or-proc signal fmt-string args)
2401 (when (and vec-or-proc
2402 (not (zerop tramp-verbose))
2403 (not (tramp-completion-mode-p)))
2404 (let ((enable-recursive-minibuffers t))
2405 (pop-to-buffer
2406 (or (and (bufferp buffer) buffer)
2407 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2408 (tramp-get-buffer vec-or-proc)))
2409 (sit-for 30))))))
2411 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2412 "Parse a Tramp filename and make components available in the body.
2414 First arg FILENAME is evaluated and dissected into its components.
2415 Second arg VAR is a symbol. It is used as a variable name to hold
2416 the filename structure. It is also used as a prefix for the variables
2417 holding the components. For example, if VAR is the symbol `foo', then
2418 `foo' will be bound to the whole structure, `foo-method' will be bound to
2419 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2421 Remaining args are Lisp expressions to be evaluated (inside an implicit
2422 `progn').
2424 If VAR is nil, then we bind `v' to the structure and `method', `user',
2425 `host', `localname' to the components."
2426 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2427 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2428 (tramp-file-name-method ,(or var 'v)))
2429 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2430 (tramp-file-name-user ,(or var 'v)))
2431 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2432 (tramp-file-name-host ,(or var 'v)))
2433 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2434 (tramp-file-name-localname ,(or var 'v))))
2435 ,@body))
2437 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2438 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2439 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2441 (defun tramp-progress-reporter-update (reporter &optional value)
2442 (let* ((parameters (cdr reporter))
2443 (message (aref parameters 3)))
2444 (when (string-match message (or (current-message) ""))
2445 (funcall 'progress-reporter-update reporter value))))
2447 (defmacro with-progress-reporter (vec level message &rest body)
2448 "Executes BODY, spinning a progress reporter with MESSAGE.
2449 If LEVEL does not fit for visible messages, or if this is a
2450 nested call of the macro, there are only traces without a visible
2451 progress reporter."
2452 `(let (pr tm)
2453 (tramp-message ,vec ,level "%s..." ,message)
2454 ;; We start a pulsing progress reporter after 3 seconds. Feature
2455 ;; introduced in Emacs 24.1.
2456 (when (and tramp-message-show-message
2457 ;; Display only when there is a minimum level.
2458 (<= ,level (min tramp-verbose 3)))
2459 (condition-case nil
2460 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
2461 tm (when pr
2462 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))
2463 (error nil)))
2464 (unwind-protect
2465 ;; Execute the body. Unset `tramp-message-show-message' when
2466 ;; the timer object is created, in order to suppress
2467 ;; concurrent timers.
2468 (let ((tramp-message-show-message
2469 (and tramp-message-show-message (not tm))))
2470 ,@body)
2471 ;; Stop progress reporter.
2472 (if tm (tramp-compat-funcall 'cancel-timer tm))
2473 (tramp-message ,vec ,level "%s...done" ,message))))
2475 (put 'with-progress-reporter 'lisp-indent-function 3)
2476 (put 'with-progress-reporter 'edebug-form-spec t)
2477 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
2479 (eval-and-compile ;; Silence compiler.
2480 (if (memq system-type '(cygwin windows-nt))
2481 (defun tramp-drop-volume-letter (name)
2482 "Cut off unnecessary drive letter from file NAME.
2483 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2484 locally on a remote file name. When the local system is a W32 system
2485 but the remote system is Unix, this introduces a superfluous drive
2486 letter into the file name. This function removes it."
2487 (save-match-data
2488 (if (string-match tramp-root-regexp name)
2489 (replace-match "/" nil t name)
2490 name)))
2492 (defalias 'tramp-drop-volume-letter 'identity)))
2494 (defsubst tramp-make-tramp-temp-file (vec)
2495 "Create a temporary file on the remote host identified by VEC.
2496 Return the local name of the temporary file."
2497 (let ((prefix
2498 (tramp-make-tramp-file-name
2499 (tramp-file-name-method vec)
2500 (tramp-file-name-user vec)
2501 (tramp-file-name-host vec)
2502 (tramp-drop-volume-letter
2503 (expand-file-name
2504 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2505 result)
2506 (while (not result)
2507 ;; `make-temp-file' would be the natural choice for
2508 ;; implementation. But it calls `write-region' internally,
2509 ;; which also needs a temporary file - we would end in an
2510 ;; infinite loop.
2511 (setq result (make-temp-name prefix))
2512 (if (file-exists-p result)
2513 (setq result nil)
2514 ;; This creates the file by side effect.
2515 (set-file-times result)
2516 (set-file-modes result (tramp-compat-octal-to-decimal "0700"))))
2518 ;; Return the local part.
2519 (with-parsed-tramp-file-name result nil localname)))
2522 ;;; Config Manipulation Functions:
2524 (defun tramp-set-completion-function (method function-list)
2525 "Sets the list of completion functions for METHOD.
2526 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2527 The FUNCTION is intended to parse FILE according its syntax.
2528 It might be a predefined FUNCTION, or a user defined FUNCTION.
2529 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2530 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2531 and `tramp-parse-netrc'.
2533 Example:
2535 (tramp-set-completion-function
2536 \"ssh\"
2537 '((tramp-parse-sconfig \"/etc/ssh_config\")
2538 (tramp-parse-sconfig \"~/.ssh/config\")))"
2540 (let ((r function-list)
2541 (v function-list))
2542 (setq tramp-completion-function-alist
2543 (delete (assoc method tramp-completion-function-alist)
2544 tramp-completion-function-alist))
2546 (while v
2547 ;; Remove double entries.
2548 (when (member (car v) (cdr v))
2549 (setcdr v (delete (car v) (cdr v))))
2550 ;; Check for function and file or registry key.
2551 (unless (and (functionp (nth 0 (car v)))
2552 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2553 ;; Windows registry.
2554 (and (memq system-type '(cygwin windows-nt))
2555 (zerop
2556 (tramp-compat-call-process
2557 "reg" nil nil nil "query" (nth 1 (car v)))))
2558 ;; Configuration file.
2559 (file-exists-p (nth 1 (car v)))))
2560 (setq r (delete (car v) r)))
2561 (setq v (cdr v)))
2563 (when r
2564 (add-to-list 'tramp-completion-function-alist
2565 (cons method r)))))
2567 (defun tramp-get-completion-function (method)
2568 "Returns a list of completion functions for METHOD.
2569 For definition of that list see `tramp-set-completion-function'."
2570 (cons
2571 ;; Hosts visited once shall be remembered.
2572 `(tramp-parse-connection-properties ,method)
2573 ;; The method related defaults.
2574 (cdr (assoc method tramp-completion-function-alist))))
2577 ;;; Fontification of `read-file-name':
2579 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2580 (defvar tramp-rfn-eshadow-overlay)
2581 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2583 (defun tramp-rfn-eshadow-setup-minibuffer ()
2584 "Set up a minibuffer for `file-name-shadow-mode'.
2585 Adds another overlay hiding filename parts according to Tramp's
2586 special handling of `substitute-in-file-name'."
2587 (when (symbol-value 'minibuffer-completing-file-name)
2588 (setq tramp-rfn-eshadow-overlay
2589 (tramp-compat-funcall
2590 'make-overlay
2591 (tramp-compat-funcall 'minibuffer-prompt-end)
2592 (tramp-compat-funcall 'minibuffer-prompt-end)))
2593 ;; Copy rfn-eshadow-overlay properties.
2594 (let ((props (tramp-compat-funcall
2595 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
2596 (while props
2597 (tramp-compat-funcall
2598 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2600 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2601 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2602 'tramp-rfn-eshadow-setup-minibuffer)
2603 (add-hook 'tramp-unload-hook
2604 (lambda ()
2605 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2606 'tramp-rfn-eshadow-setup-minibuffer))))
2608 (defconst tramp-rfn-eshadow-update-overlay-regexp
2609 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2611 (defun tramp-rfn-eshadow-update-overlay ()
2612 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2613 This is intended to be used as a minibuffer `post-command-hook' for
2614 `file-name-shadow-mode'; the minibuffer should have already
2615 been set up by `rfn-eshadow-setup-minibuffer'."
2616 ;; In remote files name, there is a shadowing just for the local part.
2617 (let ((end (or (tramp-compat-funcall
2618 'overlay-end (symbol-value 'rfn-eshadow-overlay))
2619 (tramp-compat-funcall 'minibuffer-prompt-end))))
2620 (when
2621 (file-remote-p
2622 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
2623 (save-excursion
2624 (save-restriction
2625 (narrow-to-region
2626 (1+ (or (string-match
2627 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2628 end))
2629 (point-max))
2630 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2631 (rfn-eshadow-update-overlay-hook nil))
2632 (tramp-compat-funcall
2633 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
2634 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
2636 (when (boundp 'rfn-eshadow-update-overlay-hook)
2637 (add-hook 'rfn-eshadow-update-overlay-hook
2638 'tramp-rfn-eshadow-update-overlay)
2639 (add-hook 'tramp-unload-hook
2640 (lambda ()
2641 (remove-hook 'rfn-eshadow-update-overlay-hook
2642 'tramp-rfn-eshadow-update-overlay))))
2645 ;;; Integration of eshell.el:
2647 (eval-when-compile
2648 (defvar eshell-path-env))
2650 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2651 ;; when `default-directory' points to another host.
2652 (defun tramp-eshell-directory-change ()
2653 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2654 (setq eshell-path-env
2655 (if (file-remote-p default-directory)
2656 (with-parsed-tramp-file-name default-directory nil
2657 (mapconcat
2658 'identity
2659 (tramp-get-remote-path v)
2660 ":"))
2661 (getenv "PATH"))))
2663 (eval-after-load "esh-util"
2664 '(progn
2665 (tramp-eshell-directory-change)
2666 (add-hook 'eshell-directory-change-hook
2667 'tramp-eshell-directory-change)
2668 (add-hook 'tramp-unload-hook
2669 (lambda ()
2670 (remove-hook 'eshell-directory-change-hook
2671 'tramp-eshell-directory-change)))))
2674 ;;; File Name Handler Functions:
2676 (defun tramp-handle-make-symbolic-link
2677 (filename linkname &optional ok-if-already-exists)
2678 "Like `make-symbolic-link' for Tramp files.
2679 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2680 the symlink. If LINKNAME is a Tramp file, only the localname component is
2681 used as the target of the symlink.
2683 If LINKNAME is a Tramp file and the localname component is relative, then
2684 it is expanded first, before the localname component is taken. Note that
2685 this can give surprising results if the user/host for the source and
2686 target of the symlink differ."
2687 (with-parsed-tramp-file-name linkname l
2688 (let ((ln (tramp-get-remote-ln l))
2689 (cwd (tramp-run-real-handler
2690 'file-name-directory (list l-localname))))
2691 (unless ln
2692 (tramp-error
2693 l 'file-error
2694 "Making a symbolic link. ln(1) does not exist on the remote host."))
2696 ;; Do the 'confirm if exists' thing.
2697 (when (file-exists-p linkname)
2698 ;; What to do?
2699 (if (or (null ok-if-already-exists) ; not allowed to exist
2700 (and (numberp ok-if-already-exists)
2701 (not (yes-or-no-p
2702 (format
2703 "File %s already exists; make it a link anyway? "
2704 l-localname)))))
2705 (tramp-error
2706 l 'file-already-exists "File %s already exists" l-localname)
2707 (delete-file linkname)))
2709 ;; If FILENAME is a Tramp name, use just the localname component.
2710 (when (tramp-tramp-file-p filename)
2711 (setq filename
2712 (tramp-file-name-localname
2713 (tramp-dissect-file-name (expand-file-name filename)))))
2715 (tramp-flush-file-property l (file-name-directory l-localname))
2716 (tramp-flush-file-property l l-localname)
2718 ;; Right, they are on the same host, regardless of user, method, etc.
2719 ;; We now make the link on the remote machine. This will occur as the user
2720 ;; that FILENAME belongs to.
2721 (zerop
2722 (tramp-send-command-and-check
2724 (format
2725 "cd %s && %s -sf %s %s"
2726 (tramp-shell-quote-argument cwd)
2728 (tramp-shell-quote-argument filename)
2729 (tramp-shell-quote-argument l-localname))
2730 t)))))
2732 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2733 "Like `load' for Tramp files."
2734 (with-parsed-tramp-file-name (expand-file-name file) nil
2735 (unless nosuffix
2736 (cond ((file-exists-p (concat file ".elc"))
2737 (setq file (concat file ".elc")))
2738 ((file-exists-p (concat file ".el"))
2739 (setq file (concat file ".el")))))
2740 (when must-suffix
2741 ;; The first condition is always true for absolute file names.
2742 ;; Included for safety's sake.
2743 (unless (or (file-name-directory file)
2744 (string-match "\\.elc?\\'" file))
2745 (tramp-error
2746 v 'file-error
2747 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2748 (unless noerror
2749 (when (not (file-exists-p file))
2750 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2751 (if (not (file-exists-p file))
2753 (let ((tramp-message-show-message (not nomessage)))
2754 (with-progress-reporter v 0 (format "Loading %s" file)
2755 (let ((local-copy (file-local-copy file)))
2756 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2757 (unwind-protect
2758 (load local-copy noerror t t)
2759 (delete-file local-copy)))))
2760 t)))
2762 ;; Localname manipulation functions that grok Tramp localnames...
2763 (defun tramp-handle-file-name-as-directory (file)
2764 "Like `file-name-as-directory' but aware of Tramp files."
2765 ;; `file-name-as-directory' would be sufficient except localname is
2766 ;; the empty string.
2767 (let ((v (tramp-dissect-file-name file t)))
2768 ;; Run the command on the localname portion only.
2769 (tramp-make-tramp-file-name
2770 (tramp-file-name-method v)
2771 (tramp-file-name-user v)
2772 (tramp-file-name-host v)
2773 (tramp-run-real-handler
2774 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2776 (defun tramp-handle-file-name-directory (file)
2777 "Like `file-name-directory' but aware of Tramp files."
2778 ;; Everything except the last filename thing is the directory. We
2779 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2780 ;; the remote file name parts. This is a problem when we are in
2781 ;; file name completion.
2782 (let ((v (tramp-dissect-file-name file t)))
2783 ;; Run the command on the localname portion only.
2784 (tramp-make-tramp-file-name
2785 (tramp-file-name-method v)
2786 (tramp-file-name-user v)
2787 (tramp-file-name-host v)
2788 (tramp-run-real-handler
2789 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2791 (defun tramp-handle-file-name-nondirectory (file)
2792 "Like `file-name-nondirectory' but aware of Tramp files."
2793 (with-parsed-tramp-file-name file nil
2794 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2796 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2797 "Like `file-truename' for Tramp files."
2798 (with-parsed-tramp-file-name (expand-file-name filename) nil
2799 (with-file-property v localname "file-truename"
2800 (let ((result nil)) ; result steps in reverse order
2801 (tramp-message v 4 "Finding true name for `%s'" filename)
2802 (cond
2803 ;; Use GNU readlink --canonicalize-missing where available.
2804 ((tramp-get-remote-readlink v)
2805 (setq result
2806 (tramp-send-command-and-read
2808 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2809 (tramp-get-remote-readlink v)
2810 (tramp-shell-quote-argument localname)))))
2812 ;; Use Perl implementation.
2813 ((and (tramp-get-remote-perl v)
2814 (tramp-get-connection-property v "perl-file-spec" nil)
2815 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2816 (tramp-maybe-send-script
2817 v tramp-perl-file-truename "tramp_perl_file_truename")
2818 (setq result
2819 (tramp-send-command-and-read
2821 (format "tramp_perl_file_truename %s"
2822 (tramp-shell-quote-argument localname)))))
2824 ;; Do it yourself. We bind `directory-sep-char' here for
2825 ;; XEmacs on Windows, which would otherwise use backslash.
2826 (t (let* ((directory-sep-char ?/)
2827 (steps (tramp-compat-split-string localname "/"))
2828 (localnamedir (tramp-run-real-handler
2829 'file-name-as-directory (list localname)))
2830 (is-dir (string= localname localnamedir))
2831 (thisstep nil)
2832 (numchase 0)
2833 ;; Don't make the following value larger than
2834 ;; necessary. People expect an error message in a
2835 ;; timely fashion when something is wrong;
2836 ;; otherwise they might think that Emacs is hung.
2837 ;; Of course, correctness has to come first.
2838 (numchase-limit 20)
2839 symlink-target)
2840 (while (and steps (< numchase numchase-limit))
2841 (setq thisstep (pop steps))
2842 (tramp-message
2843 v 5 "Check %s"
2844 (mapconcat 'identity
2845 (append '("") (reverse result) (list thisstep))
2846 "/"))
2847 (setq symlink-target
2848 (nth 0 (file-attributes
2849 (tramp-make-tramp-file-name
2850 method user host
2851 (mapconcat 'identity
2852 (append '("")
2853 (reverse result)
2854 (list thisstep))
2855 "/")))))
2856 (cond ((string= "." thisstep)
2857 (tramp-message v 5 "Ignoring step `.'"))
2858 ((string= ".." thisstep)
2859 (tramp-message v 5 "Processing step `..'")
2860 (pop result))
2861 ((stringp symlink-target)
2862 ;; It's a symlink, follow it.
2863 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2864 (setq numchase (1+ numchase))
2865 (when (file-name-absolute-p symlink-target)
2866 (setq result nil))
2867 ;; If the symlink was absolute, we'll get a string like
2868 ;; "/user@host:/some/target"; extract the
2869 ;; "/some/target" part from it.
2870 (when (tramp-tramp-file-p symlink-target)
2871 (unless (tramp-equal-remote filename symlink-target)
2872 (tramp-error
2873 v 'file-error
2874 "Symlink target `%s' on wrong host" symlink-target))
2875 (setq symlink-target localname))
2876 (setq steps
2877 (append (tramp-compat-split-string
2878 symlink-target "/")
2879 steps)))
2881 ;; It's a file.
2882 (setq result (cons thisstep result)))))
2883 (when (>= numchase numchase-limit)
2884 (tramp-error
2885 v 'file-error
2886 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2887 (setq result (reverse result))
2888 ;; Combine list to form string.
2889 (setq result
2890 (if result
2891 (mapconcat 'identity (cons "" result) "/")
2892 "/"))
2893 (when (and is-dir (or (string= "" result)
2894 (not (string= (substring result -1) "/"))))
2895 (setq result (concat result "/"))))))
2897 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2898 (tramp-make-tramp-file-name method user host result)))))
2900 ;; Basic functions.
2902 (defun tramp-handle-file-exists-p (filename)
2903 "Like `file-exists-p' for Tramp files."
2904 (with-parsed-tramp-file-name filename nil
2905 (with-file-property v localname "file-exists-p"
2906 (or (not (null (tramp-get-file-property
2907 v localname "file-attributes-integer" nil)))
2908 (not (null (tramp-get-file-property
2909 v localname "file-attributes-string" nil)))
2910 (zerop (tramp-send-command-and-check
2912 (format
2913 "%s %s"
2914 (tramp-get-file-exists-command v)
2915 (tramp-shell-quote-argument localname))))))))
2917 ;; Inodes don't exist for some file systems. Therefore we must
2918 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2919 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2920 ;; performance isn't the major issue given that file transfer will
2921 ;; take time.
2922 (defvar tramp-inodes nil
2923 "Keeps virtual inodes numbers.")
2925 ;; Devices must distinguish physical file systems. The device numbers
2926 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2927 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2928 ;; EFS use device number "-1". In order to be different, we use device number
2929 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2930 (defvar tramp-devices nil
2931 "Keeps virtual device numbers.")
2933 ;; CCC: This should check for an error condition and signal failure
2934 ;; when something goes wrong.
2935 ;; Daniel Pittman <daniel@danann.net>
2936 (defun tramp-handle-file-attributes (filename &optional id-format)
2937 "Like `file-attributes' for Tramp files."
2938 (unless id-format (setq id-format 'integer))
2939 ;; Don't modify `last-coding-system-used' by accident.
2940 (let ((last-coding-system-used last-coding-system-used))
2941 (with-parsed-tramp-file-name (expand-file-name filename) nil
2942 (with-file-property v localname (format "file-attributes-%s" id-format)
2943 (save-excursion
2944 (tramp-convert-file-attributes
2946 (cond
2947 ((tramp-get-remote-stat v)
2948 (tramp-do-file-attributes-with-stat v localname id-format))
2949 ((tramp-get-remote-perl v)
2950 (tramp-do-file-attributes-with-perl v localname id-format))
2952 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2954 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2955 "Implement `file-attributes' for Tramp files using the ls(1) command."
2956 (let (symlinkp dirp
2957 res-inode res-filemodes res-numlinks
2958 res-uid res-gid res-size res-symlink-target)
2959 (tramp-message vec 5 "file attributes with ls: %s" localname)
2960 (tramp-send-command
2962 (format "(%s %s || %s -h %s) && %s %s %s"
2963 (tramp-get-file-exists-command vec)
2964 (tramp-shell-quote-argument localname)
2965 (tramp-get-test-command vec)
2966 (tramp-shell-quote-argument localname)
2967 (tramp-get-ls-command vec)
2968 (if (eq id-format 'integer) "-ildn" "-ild")
2969 (tramp-shell-quote-argument localname)))
2970 ;; parse `ls -l' output ...
2971 (with-current-buffer (tramp-get-buffer vec)
2972 (when (> (buffer-size) 0)
2973 (goto-char (point-min))
2974 ;; ... inode
2975 (setq res-inode
2976 (condition-case err
2977 (read (current-buffer))
2978 (invalid-read-syntax
2979 (when (and (equal (cadr err)
2980 "Integer constant overflow in reader")
2981 (string-match
2982 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2983 (car (cddr err))))
2984 (let* ((big (read (substring (car (cddr err)) 0
2985 (match-beginning 1))))
2986 (small (read (match-string 1 (car (cddr err)))))
2987 (twiddle (/ small 65536)))
2988 (cons (+ big twiddle)
2989 (- small (* twiddle 65536))))))))
2990 ;; ... file mode flags
2991 (setq res-filemodes (symbol-name (read (current-buffer))))
2992 ;; ... number links
2993 (setq res-numlinks (read (current-buffer)))
2994 ;; ... uid and gid
2995 (setq res-uid (read (current-buffer)))
2996 (setq res-gid (read (current-buffer)))
2997 (if (eq id-format 'integer)
2998 (progn
2999 (unless (numberp res-uid) (setq res-uid -1))
3000 (unless (numberp res-gid) (setq res-gid -1)))
3001 (progn
3002 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
3003 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
3004 ;; ... size
3005 (setq res-size (read (current-buffer)))
3006 ;; From the file modes, figure out other stuff.
3007 (setq symlinkp (eq ?l (aref res-filemodes 0)))
3008 (setq dirp (eq ?d (aref res-filemodes 0)))
3009 ;; if symlink, find out file name pointed to
3010 (when symlinkp
3011 (search-forward "-> ")
3012 (setq res-symlink-target
3013 (buffer-substring (point) (tramp-compat-line-end-position))))
3014 ;; return data gathered
3015 (list
3016 ;; 0. t for directory, string (name linked to) for symbolic
3017 ;; link, or nil.
3018 (or dirp res-symlink-target)
3019 ;; 1. Number of links to file.
3020 res-numlinks
3021 ;; 2. File uid.
3022 res-uid
3023 ;; 3. File gid.
3024 res-gid
3025 ;; 4. Last access time, as a list of two integers. First
3026 ;; integer has high-order 16 bits of time, second has low 16
3027 ;; bits.
3028 ;; 5. Last modification time, likewise.
3029 ;; 6. Last status change time, likewise.
3030 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
3031 ;; 7. Size in bytes (-1, if number is out of range).
3032 res-size
3033 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
3034 res-filemodes
3035 ;; 9. t if file's gid would change if file were deleted and
3036 ;; recreated. Will be set in `tramp-convert-file-attributes'
3038 ;; 10. inode number.
3039 res-inode
3040 ;; 11. Device number. Will be replaced by a virtual device number.
3042 )))))
3044 (defun tramp-do-file-attributes-with-perl
3045 (vec localname &optional id-format)
3046 "Implement `file-attributes' for Tramp files using a Perl script."
3047 (tramp-message vec 5 "file attributes with perl: %s" localname)
3048 (tramp-maybe-send-script
3049 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
3050 (tramp-send-command-and-read
3052 (format "tramp_perl_file_attributes %s %s"
3053 (tramp-shell-quote-argument localname) id-format)))
3055 (defun tramp-do-file-attributes-with-stat
3056 (vec localname &optional id-format)
3057 "Implement `file-attributes' for Tramp files using stat(1) command."
3058 (tramp-message vec 5 "file attributes with stat: %s" localname)
3059 (tramp-send-command-and-read
3061 (format
3062 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
3063 ;; parse correctly the sequence "((". Therefore, we add a space.
3064 "( (%s %s || %s -h %s) && %s -c '( (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s || echo nil)"
3065 (tramp-get-file-exists-command vec)
3066 (tramp-shell-quote-argument localname)
3067 (tramp-get-test-command vec)
3068 (tramp-shell-quote-argument localname)
3069 (tramp-get-remote-stat vec)
3070 (if (eq id-format 'integer) "%u" "\"%U\"")
3071 (if (eq id-format 'integer) "%g" "\"%G\"")
3072 (tramp-shell-quote-argument localname))))
3074 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
3075 "Like `set-visited-file-modtime' for Tramp files."
3076 (unless (buffer-file-name)
3077 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
3078 (buffer-name)))
3079 (if time-list
3080 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
3081 (let ((f (buffer-file-name))
3082 coding-system-used)
3083 (with-parsed-tramp-file-name f nil
3084 (let* ((attr (file-attributes f))
3085 ;; '(-1 65535) means file doesn't exists yet.
3086 (modtime (or (nth 5 attr) '(-1 65535))))
3087 (when (boundp 'last-coding-system-used)
3088 (setq coding-system-used (symbol-value 'last-coding-system-used)))
3089 ;; We use '(0 0) as a don't-know value. See also
3090 ;; `tramp-do-file-attributes-with-ls'.
3091 (if (not (equal modtime '(0 0)))
3092 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
3093 (progn
3094 (tramp-send-command
3096 (format "%s -ild %s"
3097 (tramp-get-ls-command v)
3098 (tramp-shell-quote-argument localname)))
3099 (setq attr (buffer-substring (point)
3100 (progn (end-of-line) (point)))))
3101 (tramp-set-file-property
3102 v localname "visited-file-modtime-ild" attr))
3103 (when (boundp 'last-coding-system-used)
3104 (set 'last-coding-system-used coding-system-used))
3105 nil)))))
3107 ;; This function makes the same assumption as
3108 ;; `tramp-handle-set-visited-file-modtime'.
3109 (defun tramp-handle-verify-visited-file-modtime (buf)
3110 "Like `verify-visited-file-modtime' for Tramp files.
3111 At the time `verify-visited-file-modtime' calls this function, we
3112 already know that the buffer is visiting a file and that
3113 `visited-file-modtime' does not return 0. Do not call this
3114 function directly, unless those two cases are already taken care
3115 of."
3116 (with-current-buffer buf
3117 (let ((f (buffer-file-name)))
3118 ;; There is no file visiting the buffer, or the buffer has no
3119 ;; recorded last modification time, or there is no established
3120 ;; connection.
3121 (if (or (not f)
3122 (eq (visited-file-modtime) 0)
3123 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
3125 (with-parsed-tramp-file-name f nil
3126 (tramp-flush-file-property v localname)
3127 (let* ((attr (file-attributes f))
3128 (modtime (nth 5 attr))
3129 (mt (visited-file-modtime)))
3131 (cond
3132 ;; File exists, and has a known modtime.
3133 ((and attr (not (equal modtime '(0 0))))
3134 (< (abs (tramp-time-diff
3135 modtime
3136 ;; For compatibility, deal with both the old
3137 ;; (HIGH . LOW) and the new (HIGH LOW) return
3138 ;; values of `visited-file-modtime'.
3139 (if (atom (cdr mt))
3140 (list (car mt) (cdr mt))
3141 mt)))
3143 ;; Modtime has the don't know value.
3144 (attr
3145 (tramp-send-command
3147 (format "%s -ild %s"
3148 (tramp-get-ls-command v)
3149 (tramp-shell-quote-argument localname)))
3150 (with-current-buffer (tramp-get-buffer v)
3151 (setq attr (buffer-substring
3152 (point) (progn (end-of-line) (point)))))
3153 (equal
3154 attr
3155 (tramp-get-file-property
3156 v localname "visited-file-modtime-ild" "")))
3157 ;; If file does not exist, say it is not modified if and
3158 ;; only if that agrees with the buffer's record.
3159 (t (equal mt '(-1 65535))))))))))
3161 (defun tramp-handle-set-file-modes (filename mode)
3162 "Like `set-file-modes' for Tramp files."
3163 (with-parsed-tramp-file-name filename nil
3164 (tramp-flush-file-property v localname)
3165 (unless (zerop (tramp-send-command-and-check
3167 (format "chmod %s %s"
3168 (tramp-compat-decimal-to-octal mode)
3169 (tramp-shell-quote-argument localname))))
3170 ;; FIXME: extract the proper text from chmod's stderr.
3171 (tramp-error
3172 v 'file-error "Error while changing file's mode %s" filename))))
3174 (defun tramp-handle-set-file-times (filename &optional time)
3175 "Like `set-file-times' for Tramp files."
3176 (zerop
3177 (if (file-remote-p filename)
3178 (with-parsed-tramp-file-name filename nil
3179 (tramp-flush-file-property v localname)
3180 (let ((time (if (or (null time) (equal time '(0 0)))
3181 (current-time)
3182 time))
3183 ;; With GNU Emacs, `format-time-string' has an optional
3184 ;; parameter UNIVERSAL. This is preferred, because we
3185 ;; could handle the case when the remote host is
3186 ;; located in a different time zone as the local host.
3187 (utc (not (featurep 'xemacs))))
3188 (tramp-send-command-and-check
3189 v (format "%s touch -t %s %s"
3190 (if utc "TZ=UTC; export TZ;" "")
3191 (if utc
3192 (format-time-string "%Y%m%d%H%M.%S" time t)
3193 (format-time-string "%Y%m%d%H%M.%S" time))
3194 (tramp-shell-quote-argument localname)))))
3196 ;; We handle also the local part, because in older Emacsen,
3197 ;; without `set-file-times', this function is an alias for this.
3198 ;; We are local, so we don't need the UTC settings.
3199 (tramp-compat-call-process
3200 "touch" nil nil nil "-t"
3201 (format-time-string "%Y%m%d%H%M.%S" time)
3202 (tramp-shell-quote-argument filename)))))
3204 (defun tramp-set-file-uid-gid (filename &optional uid gid)
3205 "Set the ownership for FILENAME.
3206 If UID and GID are provided, these values are used; otherwise uid
3207 and gid of the corresponding user is taken. Both parameters must be integers."
3208 ;; Modern Unices allow chown only for root. So we might need
3209 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
3210 ;; working with su(do)? when it is needed, so it shall succeed in
3211 ;; the majority of cases.
3212 ;; Don't modify `last-coding-system-used' by accident.
3213 (let ((last-coding-system-used last-coding-system-used))
3214 (if (file-remote-p filename)
3215 (with-parsed-tramp-file-name filename nil
3216 (if (and (zerop (user-uid)) (tramp-local-host-p v))
3217 ;; If we are root on the local host, we can do it directly.
3218 (tramp-set-file-uid-gid localname uid gid)
3219 (let ((uid (or (and (integerp uid) uid)
3220 (tramp-get-remote-uid v 'integer)))
3221 (gid (or (and (integerp gid) gid)
3222 (tramp-get-remote-gid v 'integer))))
3223 (tramp-send-command
3224 v (format
3225 "chown %d:%d %s" uid gid
3226 (tramp-shell-quote-argument localname))))))
3228 ;; We handle also the local part, because there doesn't exist
3229 ;; `set-file-uid-gid'. On W32 "chown" might not work.
3230 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
3231 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
3232 (tramp-compat-call-process
3233 "chown" nil nil nil
3234 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
3236 (defun tramp-remote-selinux-p (vec)
3237 "Check, whether SELINUX is enabled on the remote host."
3238 (with-connection-property (tramp-get-connection-process vec) "selinux-p"
3239 (let ((result (tramp-find-executable
3240 vec "getenforce" (tramp-get-remote-path vec) t t)))
3241 (and result
3242 (string-equal
3243 (tramp-send-command-and-read
3244 vec (format "echo \\\"`%S`\\\"" result))
3245 "Enforcing")))))
3247 (defun tramp-handle-file-selinux-context (filename)
3248 "Like `file-selinux-context' for Tramp files."
3249 (with-parsed-tramp-file-name filename nil
3250 (with-file-property v localname "file-selinux-context"
3251 (let ((context '(nil nil nil nil))
3252 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
3253 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
3254 (when (and (tramp-remote-selinux-p v)
3255 (zerop (tramp-send-command-and-check
3256 v (format
3257 "%s -d -Z %s"
3258 (tramp-get-ls-command v)
3259 (tramp-shell-quote-argument localname)))))
3260 (with-current-buffer (tramp-get-connection-buffer v)
3261 (goto-char (point-min))
3262 (when (re-search-forward regexp (tramp-compat-line-end-position) t)
3263 (setq context (list (match-string 1) (match-string 2)
3264 (match-string 3) (match-string 4))))))
3265 ;; Return the context.
3266 context))))
3268 (defun tramp-handle-set-file-selinux-context (filename context)
3269 "Like `set-file-selinux-context' for Tramp files."
3270 (with-parsed-tramp-file-name filename nil
3271 (if (and (consp context)
3272 (tramp-remote-selinux-p v)
3273 (zerop (tramp-send-command-and-check
3274 v (format "chcon %s %s %s %s %s"
3275 (if (stringp (nth 0 context))
3276 (format "--user=%s" (nth 0 context)) "")
3277 (if (stringp (nth 1 context))
3278 (format "--role=%s" (nth 1 context)) "")
3279 (if (stringp (nth 2 context))
3280 (format "--type=%s" (nth 2 context)) "")
3281 (if (stringp (nth 3 context))
3282 (format "--range=%s" (nth 3 context)) "")
3283 (tramp-shell-quote-argument localname)))))
3284 (tramp-set-file-property v localname "file-selinux-context" context)
3285 (tramp-set-file-property v localname "file-selinux-context" 'undef)))
3286 ;; We always return nil.
3287 nil)
3289 ;; Simple functions using the `test' command.
3291 (defun tramp-handle-file-executable-p (filename)
3292 "Like `file-executable-p' for Tramp files."
3293 (with-parsed-tramp-file-name filename nil
3294 (with-file-property v localname "file-executable-p"
3295 ;; Examine `file-attributes' cache to see if request can be
3296 ;; satisfied without remote operation.
3297 (or (tramp-check-cached-permissions v ?x)
3298 (zerop (tramp-run-test "-x" filename))))))
3300 (defun tramp-handle-file-readable-p (filename)
3301 "Like `file-readable-p' for Tramp files."
3302 (with-parsed-tramp-file-name filename nil
3303 (with-file-property v localname "file-readable-p"
3304 ;; Examine `file-attributes' cache to see if request can be
3305 ;; satisfied without remote operation.
3306 (or (tramp-check-cached-permissions v ?r)
3307 (zerop (tramp-run-test "-r" filename))))))
3309 ;; When the remote shell is started, it looks for a shell which groks
3310 ;; tilde expansion. Here, we assume that all shells which grok tilde
3311 ;; expansion will also provide a `test' command which groks `-nt' (for
3312 ;; newer than). If this breaks, tell me about it and I'll try to do
3313 ;; something smarter about it.
3314 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3315 "Like `file-newer-than-file-p' for Tramp files."
3316 (cond ((not (file-exists-p file1))
3317 nil)
3318 ((not (file-exists-p file2))
3320 ;; We are sure both files exist at this point.
3322 (save-excursion
3323 ;; We try to get the mtime of both files. If they are not
3324 ;; equal to the "dont-know" value, then we subtract the times
3325 ;; and obtain the result.
3326 (let ((fa1 (file-attributes file1))
3327 (fa2 (file-attributes file2)))
3328 (if (and (not (equal (nth 5 fa1) '(0 0)))
3329 (not (equal (nth 5 fa2) '(0 0))))
3330 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3331 ;; If one of them is the dont-know value, then we can
3332 ;; still try to run a shell command on the remote host.
3333 ;; However, this only works if both files are Tramp
3334 ;; files and both have the same method, same user, same
3335 ;; host.
3336 (unless (tramp-equal-remote file1 file2)
3337 (with-parsed-tramp-file-name
3338 (if (tramp-tramp-file-p file1) file1 file2) nil
3339 (tramp-error
3340 v 'file-error
3341 "Files %s and %s must have same method, user, host"
3342 file1 file2)))
3343 (with-parsed-tramp-file-name file1 nil
3344 (zerop (tramp-run-test2
3345 (tramp-get-test-nt-command v) file1 file2)))))))))
3347 ;; Functions implemented using the basic functions above.
3349 (defun tramp-handle-file-modes (filename)
3350 "Like `file-modes' for Tramp files."
3351 (let ((truename (or (file-truename filename) filename)))
3352 (when (file-exists-p truename)
3353 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3355 (defun tramp-default-file-modes (filename)
3356 "Return file modes of FILENAME as integer.
3357 If the file modes of FILENAME cannot be determined, return the
3358 value of `default-file-modes', without execute permissions."
3359 (or (file-modes filename)
3360 (logand (default-file-modes) (tramp-compat-octal-to-decimal "0666"))))
3362 (defun tramp-handle-file-directory-p (filename)
3363 "Like `file-directory-p' for Tramp files."
3364 ;; Care must be taken that this function returns `t' for symlinks
3365 ;; pointing to directories. Surely the most obvious implementation
3366 ;; would be `test -d', but that returns false for such symlinks.
3367 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3368 ;; I now think he's right. So we could be using `test -d', couldn't
3369 ;; we?
3371 ;; Alternatives: `cd %s', `test -d %s'
3372 (with-parsed-tramp-file-name filename nil
3373 (with-file-property v localname "file-directory-p"
3374 (zerop (tramp-run-test "-d" filename)))))
3376 (defun tramp-handle-file-regular-p (filename)
3377 "Like `file-regular-p' for Tramp files."
3378 (and (file-exists-p filename)
3379 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3381 (defun tramp-handle-file-symlink-p (filename)
3382 "Like `file-symlink-p' for Tramp files."
3383 (with-parsed-tramp-file-name filename nil
3384 (let ((x (car (file-attributes filename))))
3385 (when (stringp x)
3386 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3387 ;; might do weird things.
3388 (if (file-name-absolute-p x)
3389 (tramp-make-tramp-file-name method user host x)
3390 x)))))
3392 (defun tramp-handle-file-writable-p (filename)
3393 "Like `file-writable-p' for Tramp files."
3394 (with-parsed-tramp-file-name filename nil
3395 (with-file-property v localname "file-writable-p"
3396 (if (file-exists-p filename)
3397 ;; Examine `file-attributes' cache to see if request can be
3398 ;; satisfied without remote operation.
3399 (or (tramp-check-cached-permissions v ?w)
3400 (zerop (tramp-run-test "-w" filename)))
3401 ;; If file doesn't exist, check if directory is writable.
3402 (and (zerop (tramp-run-test
3403 "-d" (file-name-directory filename)))
3404 (zerop (tramp-run-test
3405 "-w" (file-name-directory filename))))))))
3407 (defun tramp-handle-file-ownership-preserved-p (filename)
3408 "Like `file-ownership-preserved-p' for Tramp files."
3409 (with-parsed-tramp-file-name filename nil
3410 (with-file-property v localname "file-ownership-preserved-p"
3411 (let ((attributes (file-attributes filename)))
3412 ;; Return t if the file doesn't exist, since it's true that no
3413 ;; information would be lost by an (attempted) delete and create.
3414 (or (null attributes)
3415 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3417 ;; Other file name ops.
3419 (defun tramp-handle-directory-file-name (directory)
3420 "Like `directory-file-name' for Tramp files."
3421 ;; If localname component of filename is "/", leave it unchanged.
3422 ;; Otherwise, remove any trailing slash from localname component.
3423 ;; Method, host, etc, are unchanged. Does it make sense to try
3424 ;; to avoid parsing the filename?
3425 (with-parsed-tramp-file-name directory nil
3426 (if (and (not (zerop (length localname)))
3427 (eq (aref localname (1- (length localname))) ?/)
3428 (not (string= localname "/")))
3429 (substring directory 0 -1)
3430 directory)))
3432 ;; Directory listings.
3434 (defun tramp-handle-directory-files
3435 (directory &optional full match nosort files-only)
3436 "Like `directory-files' for Tramp files."
3437 ;; FILES-ONLY is valid for XEmacs only.
3438 (when (file-directory-p directory)
3439 (setq directory (file-name-as-directory (expand-file-name directory)))
3440 (let ((temp (nreverse (file-name-all-completions "" directory)))
3441 result item)
3443 (while temp
3444 (setq item (directory-file-name (pop temp)))
3445 (when (and (or (null match) (string-match match item))
3446 (or (null files-only)
3447 ;; Files only.
3448 (and (equal files-only t) (file-regular-p item))
3449 ;; Directories only.
3450 (file-directory-p item)))
3451 (push (if full (concat directory item) item)
3452 result)))
3453 (if nosort result (sort result 'string<)))))
3455 (defun tramp-handle-directory-files-and-attributes
3456 (directory &optional full match nosort id-format)
3457 "Like `directory-files-and-attributes' for Tramp files."
3458 (unless id-format (setq id-format 'integer))
3459 (when (file-directory-p directory)
3460 (setq directory (expand-file-name directory))
3461 (let* ((temp
3462 (copy-tree
3463 (with-parsed-tramp-file-name directory nil
3464 (with-file-property
3465 v localname
3466 (format "directory-files-and-attributes-%s" id-format)
3467 (save-excursion
3468 (mapcar
3469 (lambda (x)
3470 (cons (car x)
3471 (tramp-convert-file-attributes v (cdr x))))
3472 (cond
3473 ((tramp-get-remote-stat v)
3474 (tramp-do-directory-files-and-attributes-with-stat
3475 v localname id-format))
3476 ((tramp-get-remote-perl v)
3477 (tramp-do-directory-files-and-attributes-with-perl
3478 v localname id-format)))))))))
3479 result item)
3481 (while temp
3482 (setq item (pop temp))
3483 (when (or (null match) (string-match match (car item)))
3484 (when full
3485 (setcar item (expand-file-name (car item) directory)))
3486 (push item result)))
3488 (if nosort
3489 result
3490 (sort result (lambda (x y) (string< (car x) (car y))))))))
3492 (defun tramp-do-directory-files-and-attributes-with-perl
3493 (vec localname &optional id-format)
3494 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3495 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3496 (tramp-maybe-send-script
3497 vec tramp-perl-directory-files-and-attributes
3498 "tramp_perl_directory_files_and_attributes")
3499 (let ((object
3500 (tramp-send-command-and-read
3502 (format "tramp_perl_directory_files_and_attributes %s %s"
3503 (tramp-shell-quote-argument localname) id-format))))
3504 (when (stringp object) (tramp-error vec 'file-error object))
3505 object))
3507 (defun tramp-do-directory-files-and-attributes-with-stat
3508 (vec localname &optional id-format)
3509 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3510 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3511 (tramp-send-command-and-read
3513 (format
3514 (concat
3515 ;; We must care about filenames with spaces, or starting with
3516 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3517 ;; but it does not work on all remote systems. Therefore, we
3518 ;; quote the filenames via sed.
3519 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3520 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3521 "echo \")\"")
3522 (tramp-shell-quote-argument localname)
3523 (tramp-get-ls-command vec)
3524 (tramp-get-remote-stat vec)
3525 (if (eq id-format 'integer) "%u" "\"%U\"")
3526 (if (eq id-format 'integer) "%g" "\"%G\""))))
3528 ;; This function should return "foo/" for directories and "bar" for
3529 ;; files.
3530 (defun tramp-handle-file-name-all-completions (filename directory)
3531 "Like `file-name-all-completions' for Tramp files."
3532 (unless (save-match-data (string-match "/" filename))
3533 (with-parsed-tramp-file-name (expand-file-name directory) nil
3535 (all-completions
3536 filename
3537 (mapcar
3538 'list
3540 ;; Try cache first
3541 (and
3542 ;; Ignore if expired
3543 (or (not (integerp tramp-completion-reread-directory-timeout))
3544 (<= (tramp-time-diff
3545 (current-time)
3546 (tramp-get-file-property
3547 v localname "last-completion" '(0 0 0)))
3548 tramp-completion-reread-directory-timeout))
3550 ;; Try cache entries for filename, filename with last
3551 ;; character removed, filename with last two characters
3552 ;; removed, ..., and finally the empty string - all
3553 ;; concatenated to the local directory name
3555 ;; This is inefficient for very long filenames, pity
3556 ;; `reduce' is not available...
3557 (car
3558 (apply
3559 'append
3560 (mapcar
3561 (lambda (x)
3562 (let ((cache-hit
3563 (tramp-get-file-property
3565 (concat localname (substring filename 0 x))
3566 "file-name-all-completions"
3567 nil)))
3568 (when cache-hit (list cache-hit))))
3569 (tramp-compat-number-sequence (length filename) 0 -1)))))
3571 ;; Cache expired or no matching cache entry found so we need
3572 ;; to perform a remote operation
3573 (let (result)
3574 ;; Get a list of directories and files, including reliably
3575 ;; tagging the directories with a trailing '/'. Because I
3576 ;; rock. --daniel@danann.net
3578 ;; Changed to perform `cd' in the same remote op and only
3579 ;; get entries starting with `filename'. Capture any `cd'
3580 ;; error messages. Ensure any `cd' and `echo' aliases are
3581 ;; ignored.
3582 (tramp-send-command
3584 (if (tramp-get-remote-perl v)
3585 (progn
3586 (tramp-maybe-send-script
3587 v tramp-perl-file-name-all-completions
3588 "tramp_perl_file_name_all_completions")
3589 (format "tramp_perl_file_name_all_completions %s %s %d"
3590 (tramp-shell-quote-argument localname)
3591 (tramp-shell-quote-argument filename)
3592 (if (symbol-value
3593 ;; `read-file-name-completion-ignore-case'
3594 ;; is introduced with Emacs 22.1.
3595 (if (boundp
3596 'read-file-name-completion-ignore-case)
3597 'read-file-name-completion-ignore-case
3598 'completion-ignore-case))
3599 1 0)))
3601 (format (concat
3602 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3603 ;; `ls' with wildcard might fail with `Argument
3604 ;; list too long' error in some corner cases; if
3605 ;; `ls' fails after `cd' succeeded, chances are
3606 ;; that's the case, so let's retry without
3607 ;; wildcard. This will return "too many" entries
3608 ;; but that isn't harmful.
3609 " || %s -a 2>/dev/null)"
3610 " | while read f; do"
3611 " if %s -d \"$f\" 2>/dev/null;"
3612 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3613 " && \\echo ok) || \\echo fail")
3614 (tramp-shell-quote-argument localname)
3615 (tramp-get-ls-command v)
3616 ;; When `filename' is empty, just `ls' without
3617 ;; filename argument is more efficient than `ls *'
3618 ;; for very large directories and might avoid the
3619 ;; `Argument list too long' error.
3621 ;; With and only with wildcard, we need to add
3622 ;; `-d' to prevent `ls' from descending into
3623 ;; sub-directories.
3624 (if (zerop (length filename))
3626 (concat (tramp-shell-quote-argument filename) "* -d"))
3627 (tramp-get-ls-command v)
3628 (tramp-get-test-command v))))
3630 ;; Now grab the output.
3631 (with-current-buffer (tramp-get-buffer v)
3632 (goto-char (point-max))
3634 ;; Check result code, found in last line of output
3635 (forward-line -1)
3636 (if (looking-at "^fail$")
3637 (progn
3638 ;; Grab error message from line before last line
3639 ;; (it was put there by `cd 2>&1')
3640 (forward-line -1)
3641 (tramp-error
3642 v 'file-error
3643 "tramp-handle-file-name-all-completions: %s"
3644 (buffer-substring
3645 (point) (tramp-compat-line-end-position))))
3646 ;; For peace of mind, if buffer doesn't end in `fail'
3647 ;; then it should end in `ok'. If neither are in the
3648 ;; buffer something went seriously wrong on the remote
3649 ;; side.
3650 (unless (looking-at "^ok$")
3651 (tramp-error
3652 v 'file-error
3654 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3655 (tramp-shell-quote-argument localname) (buffer-string))))
3657 (while (zerop (forward-line -1))
3658 (push (buffer-substring
3659 (point) (tramp-compat-line-end-position))
3660 result)))
3662 ;; Because the remote op went through OK we know the
3663 ;; directory we `cd'-ed to exists
3664 (tramp-set-file-property
3665 v localname "file-exists-p" t)
3667 ;; Because the remote op went through OK we know every
3668 ;; file listed by `ls' exists.
3669 (mapc (lambda (entry)
3670 (tramp-set-file-property
3671 v (concat localname entry) "file-exists-p" t))
3672 result)
3674 (tramp-set-file-property
3675 v localname "last-completion" (current-time))
3677 ;; Store result in the cache
3678 (tramp-set-file-property
3679 v (concat localname filename)
3680 "file-name-all-completions"
3681 result))))))))
3683 (defun tramp-handle-file-name-completion
3684 (filename directory &optional predicate)
3685 "Like `file-name-completion' for Tramp files."
3686 (unless (tramp-tramp-file-p directory)
3687 (error
3688 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3689 directory))
3690 (try-completion
3691 filename
3692 (mapcar 'list (file-name-all-completions filename directory))
3693 (when predicate
3694 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3696 ;; cp, mv and ln
3698 (defun tramp-handle-add-name-to-file
3699 (filename newname &optional ok-if-already-exists)
3700 "Like `add-name-to-file' for Tramp files."
3701 (unless (tramp-equal-remote filename newname)
3702 (with-parsed-tramp-file-name
3703 (if (tramp-tramp-file-p filename) filename newname) nil
3704 (tramp-error
3705 v 'file-error
3706 "add-name-to-file: %s"
3707 "only implemented for same method, same user, same host")))
3708 (with-parsed-tramp-file-name filename v1
3709 (with-parsed-tramp-file-name newname v2
3710 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3711 (when (and (not ok-if-already-exists)
3712 (file-exists-p newname)
3713 (not (numberp ok-if-already-exists))
3714 (y-or-n-p
3715 (format
3716 "File %s already exists; make it a new name anyway? "
3717 newname)))
3718 (tramp-error
3719 v2 'file-error
3720 "add-name-to-file: file %s already exists" newname))
3721 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3722 (tramp-flush-file-property v2 v2-localname)
3723 (tramp-barf-unless-okay
3725 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3726 (tramp-shell-quote-argument v2-localname))
3727 "error with add-name-to-file, see buffer `%s' for details"
3728 (buffer-name))))))
3730 (defun tramp-handle-copy-file
3731 (filename newname &optional ok-if-already-exists keep-date
3732 preserve-uid-gid preserve-selinux-context)
3733 "Like `copy-file' for Tramp files."
3734 (setq filename (expand-file-name filename))
3735 (setq newname (expand-file-name newname))
3736 (cond
3737 ;; At least one file a Tramp file?
3738 ((or (tramp-tramp-file-p filename)
3739 (tramp-tramp-file-p newname))
3740 (tramp-do-copy-or-rename-file
3741 'copy filename newname ok-if-already-exists keep-date
3742 preserve-uid-gid preserve-selinux-context))
3743 ;; Compat section.
3744 (preserve-selinux-context
3745 (tramp-run-real-handler
3746 'copy-file
3747 (list filename newname ok-if-already-exists keep-date
3748 preserve-uid-gid preserve-selinux-context)))
3749 (preserve-uid-gid
3750 (tramp-run-real-handler
3751 'copy-file
3752 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3754 (tramp-run-real-handler
3755 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3757 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3758 "Like `copy-directory' for Tramp files."
3759 (let ((t1 (tramp-tramp-file-p dirname))
3760 (t2 (tramp-tramp-file-p newname)))
3761 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3762 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3763 ;; When DIRNAME and NEWNAME are remote, they must have
3764 ;; the same method.
3765 (or (null t1) (null t2)
3766 (string-equal
3767 (tramp-file-name-method (tramp-dissect-file-name dirname))
3768 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3769 ;; scp or rsync DTRT.
3770 (progn
3771 (setq dirname (directory-file-name (expand-file-name dirname))
3772 newname (directory-file-name (expand-file-name newname)))
3773 (if (and (file-directory-p newname)
3774 (not (string-equal (file-name-nondirectory dirname)
3775 (file-name-nondirectory newname))))
3776 (setq newname
3777 (expand-file-name
3778 (file-name-nondirectory dirname) newname)))
3779 (if (not (file-directory-p (file-name-directory newname)))
3780 (make-directory (file-name-directory newname) parents))
3781 (tramp-do-copy-or-rename-file-out-of-band
3782 'copy dirname newname keep-date))
3783 ;; We must do it file-wise.
3784 (tramp-run-real-handler
3785 'copy-directory (list dirname newname keep-date parents)))
3787 ;; When newname did exist, we have wrong cached values.
3788 (when t2
3789 (with-parsed-tramp-file-name newname nil
3790 (tramp-flush-file-property v (file-name-directory localname))
3791 (tramp-flush-file-property v localname))))))
3793 (defun tramp-handle-rename-file
3794 (filename newname &optional ok-if-already-exists)
3795 "Like `rename-file' for Tramp files."
3796 ;; Check if both files are local -- invoke normal rename-file.
3797 ;; Otherwise, use Tramp from local system.
3798 (setq filename (expand-file-name filename))
3799 (setq newname (expand-file-name newname))
3800 ;; At least one file a Tramp file?
3801 (if (or (tramp-tramp-file-p filename)
3802 (tramp-tramp-file-p newname))
3803 (tramp-do-copy-or-rename-file
3804 'rename filename newname ok-if-already-exists t t)
3805 (tramp-run-real-handler
3806 'rename-file (list filename newname ok-if-already-exists))))
3808 (defun tramp-do-copy-or-rename-file
3809 (op filename newname &optional ok-if-already-exists keep-date
3810 preserve-uid-gid preserve-selinux-context)
3811 "Copy or rename a remote file.
3812 OP must be `copy' or `rename' and indicates the operation to perform.
3813 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3814 the new file (for copy) or the new name of the file (for rename).
3815 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3816 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3817 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3818 the uid and gid if both files are on the same host.
3819 PRESERVE-SELINUX-CONTEXT activates selinux commands.
3821 This function is invoked by `tramp-handle-copy-file' and
3822 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3823 and `rename'. FILENAME and NEWNAME must be absolute file names."
3824 (unless (memq op '(copy rename))
3825 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3826 (let ((t1 (tramp-tramp-file-p filename))
3827 (t2 (tramp-tramp-file-p newname))
3828 (context (and preserve-selinux-context
3829 (apply 'file-selinux-context (list filename))))
3830 pr tm)
3832 (with-parsed-tramp-file-name (if t1 filename newname) nil
3833 (when (and (not ok-if-already-exists) (file-exists-p newname))
3834 (tramp-error
3835 v 'file-already-exists "File %s already exists" newname))
3837 (with-progress-reporter
3838 v 0 (format "%s %s to %s"
3839 (if (eq op 'copy) "Copying" "Renaming")
3840 filename newname)
3842 (cond
3843 ;; Both are Tramp files.
3844 ((and t1 t2)
3845 (with-parsed-tramp-file-name filename v1
3846 (with-parsed-tramp-file-name newname v2
3847 (cond
3848 ;; Shortcut: if method, host, user are the same for
3849 ;; both files, we invoke `cp' or `mv' on the remote
3850 ;; host directly.
3851 ((tramp-equal-remote filename newname)
3852 (tramp-do-copy-or-rename-file-directly
3853 op filename newname
3854 ok-if-already-exists keep-date preserve-uid-gid))
3856 ;; Try out-of-band operation.
3857 ((tramp-method-out-of-band-p
3858 v1 (nth 7 (file-attributes filename)))
3859 (tramp-do-copy-or-rename-file-out-of-band
3860 op filename newname keep-date))
3862 ;; No shortcut was possible. So we copy the file
3863 ;; first. If the operation was `rename', we go back
3864 ;; and delete the original file (if the copy was
3865 ;; successful). The approach is simple-minded: we
3866 ;; create a new buffer, insert the contents of the
3867 ;; source file into it, then write out the buffer to
3868 ;; the target file. The advantage is that it doesn't
3869 ;; matter which filename handlers are used for the
3870 ;; source and target file.
3872 (tramp-do-copy-or-rename-file-via-buffer
3873 op filename newname keep-date))))))
3875 ;; One file is a Tramp file, the other one is local.
3876 ((or t1 t2)
3877 (cond
3878 ;; Fast track on local machine.
3879 ((tramp-local-host-p v)
3880 (tramp-do-copy-or-rename-file-directly
3881 op filename newname
3882 ok-if-already-exists keep-date preserve-uid-gid))
3884 ;; If the Tramp file has an out-of-band method, the
3885 ;; corresponding copy-program can be invoked.
3886 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3887 (tramp-do-copy-or-rename-file-out-of-band
3888 op filename newname keep-date))
3890 ;; Use the inline method via a Tramp buffer.
3891 (t (tramp-do-copy-or-rename-file-via-buffer
3892 op filename newname keep-date))))
3895 ;; One of them must be a Tramp file.
3896 (error "Tramp implementation says this cannot happen")))
3898 ;; Handle `preserve-selinux-context'.
3899 (when context (apply 'set-file-selinux-context (list newname context)))
3901 ;; In case of `rename', we must flush the cache of the source file.
3902 (when (and t1 (eq op 'rename))
3903 (with-parsed-tramp-file-name filename v1
3904 (tramp-flush-file-property v1 (file-name-directory localname))
3905 (tramp-flush-file-property v1 localname)))
3907 ;; When newname did exist, we have wrong cached values.
3908 (when t2
3909 (with-parsed-tramp-file-name newname v2
3910 (tramp-flush-file-property v2 (file-name-directory localname))
3911 (tramp-flush-file-property v2 localname)))))))
3913 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3914 "Use an Emacs buffer to copy or rename a file.
3915 First arg OP is either `copy' or `rename' and indicates the operation.
3916 FILENAME is the source file, NEWNAME the target file.
3917 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3918 (with-temp-buffer
3919 ;; We must disable multibyte, because binary data shall not be
3920 ;; converted.
3921 (set-buffer-multibyte nil)
3922 (let ((coding-system-for-read 'binary)
3923 (jka-compr-inhibit t))
3924 (insert-file-contents-literally filename))
3925 ;; We don't want the target file to be compressed, so we let-bind
3926 ;; `jka-compr-inhibit' to t.
3927 (let ((coding-system-for-write 'binary)
3928 (jka-compr-inhibit t))
3929 (write-region (point-min) (point-max) newname)))
3930 ;; KEEP-DATE handling.
3931 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3932 ;; Set the mode.
3933 (set-file-modes newname (tramp-default-file-modes filename))
3934 ;; If the operation was `rename', delete the original file.
3935 (unless (eq op 'copy) (delete-file filename)))
3937 (defun tramp-do-copy-or-rename-file-directly
3938 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3939 "Invokes `cp' or `mv' on the remote system.
3940 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3941 respectively. FILENAME specifies the file to copy or rename,
3942 NEWNAME is the name of the new file (for copy) or the new name of
3943 the file (for rename). Both files must reside on the same host.
3944 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3945 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3946 the uid and gid from FILENAME."
3947 (let ((t1 (tramp-tramp-file-p filename))
3948 (t2 (tramp-tramp-file-p newname))
3949 (file-times (nth 5 (file-attributes filename)))
3950 (file-modes (tramp-default-file-modes filename)))
3951 (with-parsed-tramp-file-name (if t1 filename newname) nil
3952 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3953 ((eq op 'copy) "cp -f")
3954 ((eq op 'rename) "mv -f")
3955 (t (tramp-error
3956 v 'file-error
3957 "Unknown operation `%s', must be `copy' or `rename'"
3958 op))))
3959 (localname1
3960 (if t1
3961 (tramp-file-name-handler 'file-remote-p filename 'localname)
3962 filename))
3963 (localname2
3964 (if t2
3965 (tramp-file-name-handler 'file-remote-p newname 'localname)
3966 newname))
3967 (prefix (file-remote-p (if t1 filename newname)))
3968 cmd-result)
3970 (cond
3971 ;; Both files are on a remote host, with same user.
3972 ((and t1 t2)
3973 (setq cmd-result
3974 (tramp-send-command-and-check
3976 (format "%s %s %s" cmd
3977 (tramp-shell-quote-argument localname1)
3978 (tramp-shell-quote-argument localname2))))
3979 (with-current-buffer (tramp-get-buffer v)
3980 (goto-char (point-min))
3981 (unless
3983 (and keep-date
3984 ;; Mask cp -f error.
3985 (re-search-forward
3986 tramp-operation-not-permitted-regexp nil t))
3987 (zerop cmd-result))
3988 (tramp-error-with-buffer
3989 nil v 'file-error
3990 "Copying directly failed, see buffer `%s' for details."
3991 (buffer-name)))))
3993 ;; We are on the local host.
3994 ((or t1 t2)
3995 (cond
3996 ;; We can do it directly.
3997 ((let (file-name-handler-alist)
3998 (and (file-readable-p localname1)
3999 (file-writable-p (file-name-directory localname2))
4000 (or (file-directory-p localname2)
4001 (file-writable-p localname2))))
4002 (if (eq op 'copy)
4003 (tramp-compat-copy-file
4004 localname1 localname2 ok-if-already-exists
4005 keep-date preserve-uid-gid)
4006 (tramp-run-real-handler
4007 'rename-file (list localname1 localname2 ok-if-already-exists))))
4009 ;; We can do it directly with `tramp-send-command'
4010 ((and (file-readable-p (concat prefix localname1))
4011 (file-writable-p
4012 (file-name-directory (concat prefix localname2)))
4013 (or (file-directory-p (concat prefix localname2))
4014 (file-writable-p (concat prefix localname2))))
4015 (tramp-do-copy-or-rename-file-directly
4016 op (concat prefix localname1) (concat prefix localname2)
4017 ok-if-already-exists keep-date t)
4018 ;; We must change the ownership to the local user.
4019 (tramp-set-file-uid-gid
4020 (concat prefix localname2)
4021 (tramp-get-local-uid 'integer)
4022 (tramp-get-local-gid 'integer)))
4024 ;; We need a temporary file in between.
4026 ;; Create the temporary file.
4027 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
4028 (unwind-protect
4029 (progn
4030 (cond
4033 (zerop
4034 (tramp-send-command-and-check
4035 v (format
4036 "%s %s %s" cmd
4037 (tramp-shell-quote-argument localname1)
4038 (tramp-shell-quote-argument tmpfile))))
4039 (tramp-error-with-buffer
4040 nil v 'file-error
4041 "Copying directly failed, see buffer `%s' for details."
4042 (tramp-get-buffer v)))
4043 ;; We must change the ownership as remote user.
4044 ;; Since this does not work reliable, we also
4045 ;; give read permissions.
4046 (set-file-modes
4047 (concat prefix tmpfile)
4048 (tramp-compat-octal-to-decimal "0777"))
4049 (tramp-set-file-uid-gid
4050 (concat prefix tmpfile)
4051 (tramp-get-local-uid 'integer)
4052 (tramp-get-local-gid 'integer)))
4054 (if (eq op 'copy)
4055 (tramp-compat-copy-file
4056 localname1 tmpfile t
4057 keep-date preserve-uid-gid)
4058 (tramp-run-real-handler
4059 'rename-file
4060 (list localname1 tmpfile t)))
4061 ;; We must change the ownership as local user.
4062 ;; Since this does not work reliable, we also
4063 ;; give read permissions.
4064 (set-file-modes
4065 tmpfile (tramp-compat-octal-to-decimal "0777"))
4066 (tramp-set-file-uid-gid
4067 tmpfile
4068 (tramp-get-remote-uid v 'integer)
4069 (tramp-get-remote-gid v 'integer))))
4071 ;; Move the temporary file to its destination.
4072 (cond
4075 (zerop
4076 (tramp-send-command-and-check
4077 v (format
4078 "cp -f -p %s %s"
4079 (tramp-shell-quote-argument tmpfile)
4080 (tramp-shell-quote-argument localname2))))
4081 (tramp-error-with-buffer
4082 nil v 'file-error
4083 "Copying directly failed, see buffer `%s' for details."
4084 (tramp-get-buffer v))))
4086 (tramp-run-real-handler
4087 'rename-file
4088 (list tmpfile localname2 ok-if-already-exists)))))
4090 ;; Save exit.
4091 (condition-case nil
4092 (delete-file tmpfile)
4093 (error)))))))))
4095 ;; Set the time and mode. Mask possible errors.
4096 (condition-case nil
4097 (when keep-date
4098 (set-file-times newname file-times)
4099 (set-file-modes newname file-modes))
4100 (error)))))
4102 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
4103 "Invoke rcp program to copy.
4104 The method used must be an out-of-band method."
4105 (let ((t1 (tramp-tramp-file-p filename))
4106 (t2 (tramp-tramp-file-p newname))
4107 copy-program copy-args copy-env copy-keep-date port spec
4108 source target)
4110 (with-parsed-tramp-file-name (if t1 filename newname) nil
4111 (if (and t1 t2)
4113 ;; Both are Tramp files. We shall optimize it, when the
4114 ;; methods for filename and newname are the same.
4115 (let* ((dir-flag (file-directory-p filename))
4116 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
4117 (if dir-flag
4118 (setq tmpfile
4119 (expand-file-name
4120 (file-name-nondirectory newname) tmpfile)))
4121 (unwind-protect
4122 (progn
4123 (tramp-do-copy-or-rename-file-out-of-band
4124 op filename tmpfile keep-date)
4125 (tramp-do-copy-or-rename-file-out-of-band
4126 'rename tmpfile newname keep-date))
4127 ;; Save exit.
4128 (condition-case nil
4129 (if dir-flag
4130 (tramp-compat-delete-directory
4131 (expand-file-name ".." tmpfile) 'recursive)
4132 (delete-file tmpfile))
4133 (error))))
4135 ;; Expand hops. Might be necessary for gateway methods.
4136 (setq v (car (tramp-compute-multi-hops v)))
4137 (aset v 3 localname)
4139 ;; Check which ones of source and target are Tramp files.
4140 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
4141 target (funcall
4142 (if (and (file-directory-p filename)
4143 (string-equal
4144 (file-name-nondirectory filename)
4145 (file-name-nondirectory newname)))
4146 'file-name-directory
4147 'identity)
4148 (if t2 (tramp-make-copy-program-file-name v) newname)))
4150 ;; Check for port number. Until now, there's no need for handling
4151 ;; like method, user, host.
4152 (setq host (tramp-file-name-real-host v)
4153 port (tramp-file-name-port v)
4154 port (or (and port (number-to-string port)) ""))
4156 ;; Compose copy command.
4157 (setq spec (format-spec-make
4158 ?h host ?u user ?p port
4159 ?t (tramp-get-connection-property
4160 (tramp-get-connection-process v) "temp-file" "")
4161 ?k (if keep-date " " ""))
4162 copy-program (tramp-get-method-parameter
4163 method 'tramp-copy-program)
4164 copy-keep-date (tramp-get-method-parameter
4165 method 'tramp-copy-keep-date)
4166 copy-args
4167 (delq
4169 (mapcar
4170 (lambda (x)
4171 (setq
4173 ;; " " is indication for keep-date argument.
4174 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
4175 (unless (member "" x) (mapconcat 'identity x " ")))
4176 (tramp-get-method-parameter method 'tramp-copy-args)))
4177 copy-env
4178 (delq
4180 (mapcar
4181 (lambda (x)
4182 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4183 (unless (member "" x) (mapconcat 'identity x " ")))
4184 (tramp-get-method-parameter method 'tramp-copy-env))))
4186 ;; Check for program.
4187 (when (and (fboundp 'executable-find)
4188 (not (let ((default-directory
4189 (tramp-compat-temporary-file-directory)))
4190 (executable-find copy-program))))
4191 (tramp-error
4192 v 'file-error "Cannot find copy program: %s" copy-program))
4194 ;; Set variables for computing the prompt for reading
4195 ;; password.
4196 (setq tramp-current-method (tramp-file-name-method v)
4197 tramp-current-user (tramp-file-name-user v)
4198 tramp-current-host (tramp-file-name-host v))
4200 (unwind-protect
4201 (with-temp-buffer
4202 ;; The default directory must be remote.
4203 (let ((default-directory
4204 (file-name-directory (if t1 filename newname)))
4205 (process-environment (copy-sequence process-environment)))
4206 ;; Set the transfer process properties.
4207 (tramp-set-connection-property
4208 v "process-name" (buffer-name (current-buffer)))
4209 (tramp-set-connection-property
4210 v "process-buffer" (current-buffer))
4211 (while copy-env
4212 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
4213 (setenv (pop copy-env) (pop copy-env)))
4215 ;; Use an asynchronous process. By this, password can
4216 ;; be handled. The default directory must be local, in
4217 ;; order to apply the correct `copy-program'. We don't
4218 ;; set a timeout, because the copying of large files can
4219 ;; last longer than 60 secs.
4220 (let ((p (let ((default-directory
4221 (tramp-compat-temporary-file-directory)))
4222 (apply 'start-process
4223 (tramp-get-connection-property
4224 v "process-name" nil)
4225 (tramp-get-connection-property
4226 v "process-buffer" nil)
4227 copy-program
4228 (append copy-args (list source target))))))
4229 (tramp-message
4230 v 6 "%s" (mapconcat 'identity (process-command p) " "))
4231 (tramp-set-process-query-on-exit-flag p nil)
4232 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
4234 ;; Reset the transfer process properties.
4235 (tramp-set-connection-property v "process-name" nil)
4236 (tramp-set-connection-property v "process-buffer" nil))
4238 ;; Handle KEEP-DATE argument.
4239 (when (and keep-date (not copy-keep-date))
4240 (set-file-times newname (nth 5 (file-attributes filename))))
4242 ;; Set the mode.
4243 (unless (and keep-date copy-keep-date)
4244 (ignore-errors
4245 (set-file-modes newname (tramp-default-file-modes filename)))))
4247 ;; If the operation was `rename', delete the original file.
4248 (unless (eq op 'copy)
4249 (if (file-regular-p filename)
4250 (delete-file filename)
4251 (tramp-compat-delete-directory filename 'recursive))))))
4253 (defun tramp-handle-make-directory (dir &optional parents)
4254 "Like `make-directory' for Tramp files."
4255 (setq dir (expand-file-name dir))
4256 (with-parsed-tramp-file-name dir nil
4257 (tramp-flush-directory-property v (file-name-directory localname))
4258 (save-excursion
4259 (tramp-barf-unless-okay
4261 (format "%s %s"
4262 (if parents "mkdir -p" "mkdir")
4263 (tramp-shell-quote-argument localname))
4264 "Couldn't make directory %s" dir))))
4266 (defun tramp-handle-delete-directory (directory &optional recursive)
4267 "Like `delete-directory' for Tramp files."
4268 (setq directory (expand-file-name directory))
4269 (with-parsed-tramp-file-name directory nil
4270 (tramp-flush-file-property v (file-name-directory localname))
4271 (tramp-flush-directory-property v localname)
4272 (unless (zerop (tramp-send-command-and-check
4274 (format
4275 "%s %s"
4276 (if recursive "rm -rf" "rmdir")
4277 (tramp-shell-quote-argument localname))))
4278 (tramp-error v 'file-error "Couldn't delete %s" directory))))
4280 (defun tramp-handle-delete-file (filename &optional trash)
4281 "Like `delete-file' for Tramp files."
4282 (setq filename (expand-file-name filename))
4283 (with-parsed-tramp-file-name filename nil
4284 (tramp-flush-file-property v (file-name-directory localname))
4285 (tramp-flush-file-property v localname)
4286 (unless
4287 (zerop
4288 (tramp-send-command-and-check
4289 v (format "%s %s"
4290 (or (and trash (tramp-get-remote-trash v)) "rm -f")
4291 (tramp-shell-quote-argument localname))))
4292 (tramp-error v 'file-error "Couldn't delete %s" filename))))
4294 ;; Dired.
4296 ;; CCC: This does not seem to be enough. Something dies when
4297 ;; we try and delete two directories under Tramp :/
4298 (defun tramp-handle-dired-recursive-delete-directory (filename)
4299 "Recursively delete the directory given.
4300 This is like `dired-recursive-delete-directory' for Tramp files."
4301 (with-parsed-tramp-file-name filename nil
4302 ;; Run a shell command 'rm -r <localname>'
4303 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
4304 (unless (file-exists-p filename)
4305 (tramp-error v 'file-error "No such directory: %s" filename))
4306 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
4307 (tramp-send-command
4309 (format "rm -rf %s" (tramp-shell-quote-argument localname))
4310 ;; Don't read the output, do it explicitely.
4311 nil t)
4312 ;; Wait for the remote system to return to us...
4313 ;; This might take a while, allow it plenty of time.
4314 (tramp-wait-for-output (tramp-get-connection-process v) 120)
4315 ;; Make sure that it worked...
4316 (tramp-flush-file-property v (file-name-directory localname))
4317 (tramp-flush-directory-property v localname)
4318 (and (file-exists-p filename)
4319 (tramp-error
4320 v 'file-error "Failed to recursively delete %s" filename))))
4322 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4323 "Like `dired-compress-file' for Tramp files."
4324 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4325 ;; Code stolen mainly from dired-aux.el.
4326 (with-parsed-tramp-file-name file nil
4327 (tramp-flush-file-property v localname)
4328 (save-excursion
4329 (let ((suffixes
4330 (if (not (featurep 'xemacs))
4331 ;; Emacs case
4332 (symbol-value 'dired-compress-file-suffixes)
4333 ;; XEmacs has `dired-compression-method-alist', which is
4334 ;; transformed into `dired-compress-file-suffixes' structure.
4335 (mapcar
4336 (lambda (x)
4337 (list (concat (regexp-quote (nth 1 x)) "\\'")
4339 (mapconcat 'identity (nth 3 x) " ")))
4340 (symbol-value 'dired-compression-method-alist))))
4341 suffix)
4342 ;; See if any suffix rule matches this file name.
4343 (while suffixes
4344 (let (case-fold-search)
4345 (if (string-match (car (car suffixes)) localname)
4346 (setq suffix (car suffixes) suffixes nil))
4347 (setq suffixes (cdr suffixes))))
4349 (cond ((file-symlink-p file)
4350 nil)
4351 ((and suffix (nth 2 suffix))
4352 ;; We found an uncompression rule.
4353 (with-progress-reporter v 0 (format "Uncompressing %s" file)
4354 (when (zerop
4355 (tramp-send-command-and-check
4356 v (concat (nth 2 suffix) " "
4357 (tramp-shell-quote-argument localname))))
4358 ;; `dired-remove-file' is not defined in XEmacs.
4359 (tramp-compat-funcall 'dired-remove-file file)
4360 (string-match (car suffix) file)
4361 (concat (substring file 0 (match-beginning 0))))))
4363 ;; We don't recognize the file as compressed, so compress it.
4364 ;; Try gzip.
4365 (with-progress-reporter v 0 (format "Compressing %s" file)
4366 (when (zerop
4367 (tramp-send-command-and-check
4368 v (concat "gzip -f "
4369 (tramp-shell-quote-argument localname))))
4370 ;; `dired-remove-file' is not defined in XEmacs.
4371 (tramp-compat-funcall 'dired-remove-file file)
4372 (cond ((file-exists-p (concat file ".gz"))
4373 (concat file ".gz"))
4374 ((file-exists-p (concat file ".z"))
4375 (concat file ".z"))
4376 (t nil))))))))))
4378 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4379 "Like `dired-uncache' for Tramp files."
4380 ;; DIR-P is valid for XEmacs only.
4381 (with-parsed-tramp-file-name
4382 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4383 (tramp-flush-directory-property v localname)))
4385 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4386 ;; not sure at all that this is the right way to do it, but let's hope
4387 ;; it works for now, and wait for a guru to point out the Right Way to
4388 ;; achieve this.
4389 ;;(eval-when-compile
4390 ;; (unless (fboundp 'dired-insert-set-properties)
4391 ;; (fset 'dired-insert-set-properties 'ignore)))
4392 ;; Gerd suggests this:
4393 (eval-when-compile (require 'dired))
4394 ;; Note that dired is required at run-time, too, when it is needed.
4395 ;; It is only needed on XEmacs for the function
4396 ;; `dired-insert-set-properties'.
4398 (defun tramp-handle-insert-directory
4399 (filename switches &optional wildcard full-directory-p)
4400 "Like `insert-directory' for Tramp files."
4401 (setq filename (expand-file-name filename))
4402 (with-parsed-tramp-file-name filename nil
4403 (if (and (featurep 'ls-lisp)
4404 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4405 (tramp-run-real-handler
4406 'insert-directory (list filename switches wildcard full-directory-p))
4407 (when (stringp switches)
4408 (setq switches (split-string switches)))
4409 (when (and (member "--dired" switches)
4410 (not (tramp-get-ls-command-with-dired v)))
4411 (setq switches (delete "--dired" switches)))
4412 (when wildcard
4413 (setq wildcard (tramp-run-real-handler
4414 'file-name-nondirectory (list localname)))
4415 (setq localname (tramp-run-real-handler
4416 'file-name-directory (list localname))))
4417 (unless full-directory-p
4418 (setq switches (add-to-list 'switches "-d" 'append)))
4419 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4420 (when wildcard
4421 (setq switches (concat switches " " wildcard)))
4422 (tramp-message
4423 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4424 switches filename (if wildcard "yes" "no")
4425 (if full-directory-p "yes" "no"))
4426 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4427 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4428 (if full-directory-p
4429 (tramp-send-command
4431 (format "%s %s %s 2>/dev/null"
4432 (tramp-get-ls-command v)
4433 switches
4434 (if wildcard
4435 localname
4436 (tramp-shell-quote-argument (concat localname ".")))))
4437 (tramp-barf-unless-okay
4439 (format "cd %s" (tramp-shell-quote-argument
4440 (tramp-run-real-handler
4441 'file-name-directory (list localname))))
4442 "Couldn't `cd %s'"
4443 (tramp-shell-quote-argument
4444 (tramp-run-real-handler 'file-name-directory (list localname))))
4445 (tramp-send-command
4447 (format "%s %s %s"
4448 (tramp-get-ls-command v)
4449 switches
4450 (if (or wildcard
4451 (zerop (length
4452 (tramp-run-real-handler
4453 'file-name-nondirectory (list localname)))))
4455 (tramp-shell-quote-argument
4456 (tramp-run-real-handler
4457 'file-name-nondirectory (list localname)))))))
4458 (let ((beg (point)))
4459 ;; We cannot use `insert-buffer-substring' because the Tramp
4460 ;; buffer changes its contents before insertion due to calling
4461 ;; `expand-file' and alike.
4462 (insert
4463 (with-current-buffer (tramp-get-buffer v)
4464 (buffer-string)))
4466 ;; Check for "--dired" output.
4467 (forward-line -2)
4468 (when (looking-at "//SUBDIRED//")
4469 (forward-line -1))
4470 (when (looking-at "//DIRED//\\s-+")
4471 (let ((databeg (match-end 0))
4472 (end (tramp-compat-line-end-position)))
4473 ;; Now read the numeric positions of file names.
4474 (goto-char databeg)
4475 (while (< (point) end)
4476 (let ((start (+ beg (read (current-buffer))))
4477 (end (+ beg (read (current-buffer)))))
4478 (if (memq (char-after end) '(?\n ?\ ))
4479 ;; End is followed by \n or by " -> ".
4480 (put-text-property start end 'dired-filename t))))))
4481 ;; Remove trailing lines.
4482 (goto-char (tramp-compat-line-beginning-position))
4483 (while (looking-at "//")
4484 (forward-line 1)
4485 (delete-region (match-beginning 0) (point)))
4487 ;; The inserted file could be from somewhere else.
4488 (when (and (not wildcard) (not full-directory-p))
4489 (goto-char (point-max))
4490 (when (file-symlink-p filename)
4491 (goto-char (search-backward "->" beg 'noerror)))
4492 (search-backward
4493 (if (zerop (length (file-name-nondirectory filename)))
4495 (file-name-nondirectory filename))
4496 beg 'noerror)
4497 (replace-match (file-relative-name filename) t))
4499 (goto-char (point-max))))))
4501 (defun tramp-handle-unhandled-file-name-directory (filename)
4502 "Like `unhandled-file-name-directory' for Tramp files."
4503 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4504 ;; for backward compatibility.
4505 (expand-file-name "~/"))
4507 ;; Canonicalization of file names.
4509 (defun tramp-handle-expand-file-name (name &optional dir)
4510 "Like `expand-file-name' for Tramp files.
4511 If the localname part of the given filename starts with \"/../\" then
4512 the result will be a local, non-Tramp, filename."
4513 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4514 (setq dir (or dir default-directory "/"))
4515 ;; Unless NAME is absolute, concat DIR and NAME.
4516 (unless (file-name-absolute-p name)
4517 (setq name (concat (file-name-as-directory dir) name)))
4518 ;; If NAME is not a Tramp file, run the real handler.
4519 (if (not (tramp-connectable-p name))
4520 (tramp-run-real-handler 'expand-file-name (list name nil))
4521 ;; Dissect NAME.
4522 (with-parsed-tramp-file-name name nil
4523 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4524 (setq localname (concat "~/" localname)))
4525 ;; Tilde expansion if necessary. This needs a shell which
4526 ;; groks tilde expansion! The function `tramp-find-shell' is
4527 ;; supposed to find such a shell on the remote host. Please
4528 ;; tell me about it when this doesn't work on your system.
4529 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4530 (let ((uname (match-string 1 localname))
4531 (fname (match-string 2 localname)))
4532 ;; We cannot simply apply "~/", because under sudo "~/" is
4533 ;; expanded to the local user home directory but to the
4534 ;; root home directory. On the other hand, using always
4535 ;; the default user name for tilde expansion is not
4536 ;; appropriate either, because ssh and companions might
4537 ;; use a user name from the config file.
4538 (when (and (string-equal uname "~")
4539 (string-match "\\`su\\(do\\)?\\'" method))
4540 (setq uname (concat uname user)))
4541 (setq uname
4542 (with-connection-property v uname
4543 (tramp-send-command
4544 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4545 (with-current-buffer (tramp-get-buffer v)
4546 (goto-char (point-min))
4547 (buffer-substring
4548 (point) (tramp-compat-line-end-position)))))
4549 (setq localname (concat uname fname))))
4550 ;; There might be a double slash, for example when "~/"
4551 ;; expands to "/". Remove this.
4552 (while (string-match "//" localname)
4553 (setq localname (replace-match "/" t t localname)))
4554 ;; No tilde characters in file name, do normal
4555 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4556 ;; `directory-sep-char' here for XEmacs on Windows, which would
4557 ;; otherwise use backslash. `default-directory' is bound,
4558 ;; because on Windows there would be problems with UNC shares or
4559 ;; Cygwin mounts.
4560 (let ((directory-sep-char ?/)
4561 (default-directory (tramp-compat-temporary-file-directory)))
4562 (tramp-make-tramp-file-name
4563 method user host
4564 (tramp-drop-volume-letter
4565 (tramp-run-real-handler
4566 'expand-file-name (list localname))))))))
4568 (defun tramp-replace-environment-variables (filename)
4569 "Replace environment variables in FILENAME.
4570 Return the string with the replaced variables."
4571 (save-match-data
4572 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4573 ;; `$' is coded as `$$'.
4574 (when (and idx
4575 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4576 (getenv (match-string 1 filename)))
4577 (setq filename
4578 (replace-match
4579 (substitute-in-file-name (match-string 0 filename))
4580 t nil filename)))
4581 filename)))
4583 (defun tramp-handle-substitute-in-file-name (filename)
4584 "Like `substitute-in-file-name' for Tramp files.
4585 \"//\" and \"/~\" substitute only in the local filename part.
4586 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4587 beginning of local filename are not substituted."
4588 ;; First, we must replace environment variables.
4589 (setq filename (tramp-replace-environment-variables filename))
4590 (with-parsed-tramp-file-name filename nil
4591 (if (equal tramp-syntax 'url)
4592 ;; We need to check localname only. The other parts cannot contain
4593 ;; "//" or "/~".
4594 (if (and (> (length localname) 1)
4595 (or (string-match "//" localname)
4596 (string-match "/~" localname 1)))
4597 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4598 (tramp-make-tramp-file-name
4599 (when method (substitute-in-file-name method))
4600 (when user (substitute-in-file-name user))
4601 (when host (substitute-in-file-name host))
4602 (when localname
4603 (tramp-run-real-handler
4604 'substitute-in-file-name (list localname)))))
4605 ;; Ignore in LOCALNAME everything before "//" or "/~".
4606 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4607 (setq filename
4608 (concat (file-remote-p filename)
4609 (replace-match "\\1" nil nil localname)))
4610 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4611 (when (string-match "~$" filename)
4612 (setq filename (concat filename "/"))))
4613 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4615 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4616 ;; which calls corresponding functions (see minibuf.el).
4617 (when (fboundp 'minibuffer-electric-separator)
4618 (mapc
4619 (lambda (x)
4620 (eval
4621 `(defadvice ,x
4622 (around ,(intern (format "tramp-advice-%s" x)) activate)
4623 "Invoke `substitute-in-file-name' for Tramp files."
4624 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4625 (tramp-tramp-file-p (buffer-substring)))
4626 ;; We don't need to handle `last-input-event', because
4627 ;; due to the key map we know it must be ?/ or ?~.
4628 (let ((s (concat (buffer-substring (point-min) (point))
4629 (string last-command-char))))
4630 (delete-region (point-min) (point))
4631 (insert (substitute-in-file-name s))
4632 (setq ad-return-value last-command-char))
4633 ad-do-it)))
4634 (eval
4635 `(add-hook
4636 'tramp-unload-hook
4637 (lambda ()
4638 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4639 (ad-activate ',x)))))
4641 '(minibuffer-electric-separator
4642 minibuffer-electric-tilde)))
4645 ;;; Remote commands:
4647 (defun tramp-handle-executable-find (command)
4648 "Like `executable-find' for Tramp files."
4649 (with-parsed-tramp-file-name default-directory nil
4650 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4652 (defun tramp-process-sentinel (proc event)
4653 "Flush file caches."
4654 (unless (memq (process-status proc) '(run open))
4655 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4656 (when vec
4657 (tramp-message vec 5 "Sentinel called: `%s' `%s'" proc event)
4658 (tramp-flush-directory-property vec "")))))
4660 ;; We use BUFFER also as connection buffer during setup. Because of
4661 ;; this, its original contents must be saved, and restored once
4662 ;; connection has been setup.
4663 (defun tramp-handle-start-file-process (name buffer program &rest args)
4664 "Like `start-file-process' for Tramp files."
4665 (with-parsed-tramp-file-name default-directory nil
4666 (unwind-protect
4667 ;; When PROGRAM is nil, we just provide a tty.
4668 (let ((command
4669 (when (stringp program)
4670 (format "cd %s; exec %s"
4671 (tramp-shell-quote-argument localname)
4672 (mapconcat 'tramp-shell-quote-argument
4673 (cons program args) " "))))
4674 (tramp-process-connection-type
4675 (or (null program) tramp-process-connection-type))
4676 (name1 name)
4677 (i 0))
4678 (unless buffer
4679 ;; BUFFER can be nil. We use a temporary buffer.
4680 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4681 (while (get-process name1)
4682 ;; NAME must be unique as process name.
4683 (setq i (1+ i)
4684 name1 (format "%s<%d>" name i)))
4685 (setq name name1)
4686 ;; Set the new process properties.
4687 (tramp-set-connection-property v "process-name" name)
4688 (tramp-set-connection-property v "process-buffer" buffer)
4689 ;; Activate narrowing in order to save BUFFER contents.
4690 ;; Clear also the modification time; otherwise we might be
4691 ;; interrupted by `verify-visited-file-modtime'.
4692 (with-current-buffer (tramp-get-connection-buffer v)
4693 (clear-visited-file-modtime)
4694 (narrow-to-region (point-max) (point-max)))
4695 (if command
4696 ;; Send the command.
4697 (tramp-send-command v command nil t) ; nooutput
4698 ;; Check, whether a pty is associated.
4699 (tramp-maybe-open-connection v)
4700 (unless (process-get (tramp-get-connection-process v) 'remote-tty)
4701 (tramp-error
4702 v 'file-error "pty association is not supported for `%s'" name)))
4703 (let ((p (tramp-get-connection-process v)))
4704 ;; Set sentinel and query flag for this process.
4705 (tramp-set-connection-property p "vector" v)
4706 (set-process-sentinel p 'tramp-process-sentinel)
4707 (tramp-set-process-query-on-exit-flag p t)
4708 ;; Return process.
4710 ;; Save exit.
4711 (with-current-buffer (tramp-get-connection-buffer v)
4712 (if (string-match tramp-temp-buffer-name (buffer-name))
4713 (progn
4714 (set-process-buffer (tramp-get-connection-process v) nil)
4715 (kill-buffer (current-buffer)))
4716 (widen)
4717 (goto-char (point-max))))
4718 (tramp-set-connection-property v "process-name" nil)
4719 (tramp-set-connection-property v "process-buffer" nil))))
4721 (defun tramp-handle-process-file
4722 (program &optional infile destination display &rest args)
4723 "Like `process-file' for Tramp files."
4724 ;; The implementation is not complete yet.
4725 (when (and (numberp destination) (zerop destination))
4726 (error "Implementation does not handle immediate return"))
4728 (with-parsed-tramp-file-name default-directory nil
4729 (let (command input tmpinput stderr tmpstderr outbuf ret)
4730 ;; Compute command.
4731 (setq command (mapconcat 'tramp-shell-quote-argument
4732 (cons program args) " "))
4733 ;; Determine input.
4734 (if (null infile)
4735 (setq input "/dev/null")
4736 (setq infile (expand-file-name infile))
4737 (if (tramp-equal-remote default-directory infile)
4738 ;; INFILE is on the same remote host.
4739 (setq input (with-parsed-tramp-file-name infile nil localname))
4740 ;; INFILE must be copied to remote host.
4741 (setq input (tramp-make-tramp-temp-file v)
4742 tmpinput (tramp-make-tramp-file-name method user host input))
4743 (copy-file infile tmpinput t)))
4744 (when input (setq command (format "%s <%s" command input)))
4746 ;; Determine output.
4747 (cond
4748 ;; Just a buffer.
4749 ((bufferp destination)
4750 (setq outbuf destination))
4751 ;; A buffer name.
4752 ((stringp destination)
4753 (setq outbuf (get-buffer-create destination)))
4754 ;; (REAL-DESTINATION ERROR-DESTINATION)
4755 ((consp destination)
4756 ;; output.
4757 (cond
4758 ((bufferp (car destination))
4759 (setq outbuf (car destination)))
4760 ((stringp (car destination))
4761 (setq outbuf (get-buffer-create (car destination))))
4762 ((car destination)
4763 (setq outbuf (current-buffer))))
4764 ;; stderr.
4765 (cond
4766 ((stringp (cadr destination))
4767 (setcar (cdr destination) (expand-file-name (cadr destination)))
4768 (if (tramp-equal-remote default-directory (cadr destination))
4769 ;; stderr is on the same remote host.
4770 (setq stderr (with-parsed-tramp-file-name
4771 (cadr destination) nil localname))
4772 ;; stderr must be copied to remote host. The temporary
4773 ;; file must be deleted after execution.
4774 (setq stderr (tramp-make-tramp-temp-file v)
4775 tmpstderr (tramp-make-tramp-file-name
4776 method user host stderr))))
4777 ;; stderr to be discarded.
4778 ((null (cadr destination))
4779 (setq stderr "/dev/null"))))
4780 ;; 't
4781 (destination
4782 (setq outbuf (current-buffer))))
4783 (when stderr (setq command (format "%s 2>%s" command stderr)))
4785 ;; Send the command. It might not return in time, so we protect
4786 ;; it. Call it in a subshell, in order to preserve working
4787 ;; directory.
4788 (condition-case nil
4789 (unwind-protect
4790 (setq ret
4791 (tramp-send-command-and-check
4792 v (format "\\cd %s; %s"
4793 (tramp-shell-quote-argument localname)
4794 command)
4795 t t))
4796 ;; We should show the output anyway.
4797 (when outbuf
4798 (with-current-buffer outbuf
4799 (insert
4800 (with-current-buffer (tramp-get-connection-buffer v)
4801 (buffer-string))))
4802 (when display (display-buffer outbuf))))
4803 ;; When the user did interrupt, we should do it also. We use
4804 ;; return code -1 as marker.
4805 (quit
4806 (kill-buffer (tramp-get-connection-buffer v))
4807 (setq ret -1))
4808 ;; Handle errors.
4809 (error
4810 (kill-buffer (tramp-get-connection-buffer v))
4811 (setq ret 1)))
4813 ;; Provide error file.
4814 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4816 ;; Cleanup. We remove all file cache values for the connection,
4817 ;; because the remote process could have changed them.
4818 (when tmpinput (delete-file tmpinput))
4820 ;; `process-file-side-effects' has been introduced with GNU
4821 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4822 ;; by `program'. If it doesn't exist, we assume its default
4823 ;; value 't'.
4824 (unless (and (boundp 'process-file-side-effects)
4825 (not (symbol-value 'process-file-side-effects)))
4826 (tramp-flush-directory-property v ""))
4828 ;; Return exit status.
4829 (if (equal ret -1)
4830 (keyboard-quit)
4831 ret))))
4833 (defun tramp-handle-call-process-region
4834 (start end program &optional delete buffer display &rest args)
4835 "Like `call-process-region' for Tramp files."
4836 (let ((tmpfile (tramp-compat-make-temp-file "")))
4837 (write-region start end tmpfile)
4838 (when delete (delete-region start end))
4839 (unwind-protect
4840 (apply 'call-process program tmpfile buffer display args)
4841 (delete-file tmpfile))))
4843 (defun tramp-handle-shell-command
4844 (command &optional output-buffer error-buffer)
4845 "Like `shell-command' for Tramp files."
4846 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4847 ;; We cannot use `shell-file-name' and `shell-command-switch',
4848 ;; they are variables of the local host.
4849 (args (list
4850 (tramp-get-method-parameter
4851 (tramp-file-name-method
4852 (tramp-dissect-file-name default-directory))
4853 'tramp-remote-sh)
4854 "-c" (substring command 0 asynchronous)))
4855 current-buffer-p
4856 (output-buffer
4857 (cond
4858 ((bufferp output-buffer) output-buffer)
4859 ((stringp output-buffer) (get-buffer-create output-buffer))
4860 (output-buffer
4861 (setq current-buffer-p t)
4862 (current-buffer))
4863 (t (get-buffer-create
4864 (if asynchronous
4865 "*Async Shell Command*"
4866 "*Shell Command Output*")))))
4867 (error-buffer
4868 (cond
4869 ((bufferp error-buffer) error-buffer)
4870 ((stringp error-buffer) (get-buffer-create error-buffer))))
4871 (buffer
4872 (if (and (not asynchronous) error-buffer)
4873 (with-parsed-tramp-file-name default-directory nil
4874 (list output-buffer (tramp-make-tramp-temp-file v)))
4875 output-buffer))
4876 (p (get-buffer-process output-buffer)))
4878 ;; Check whether there is another process running. Tramp does not
4879 ;; support 2 (asynchronous) processes in parallel.
4880 (when p
4881 (if (yes-or-no-p "A command is running. Kill it? ")
4882 (condition-case nil
4883 (kill-process p)
4884 (error nil))
4885 (error "Shell command in progress")))
4887 (if current-buffer-p
4888 (progn
4889 (barf-if-buffer-read-only)
4890 (push-mark nil t))
4891 (with-current-buffer output-buffer
4892 (setq buffer-read-only nil)
4893 (erase-buffer)))
4895 (if (and (not current-buffer-p) (integerp asynchronous))
4896 (prog1
4897 ;; Run the process.
4898 (apply 'start-file-process "*Async Shell*" buffer args)
4899 ;; Display output.
4900 (pop-to-buffer output-buffer)
4901 (setq mode-line-process '(":%s"))
4902 (shell-mode))
4904 (prog1
4905 ;; Run the process.
4906 (apply 'process-file (car args) nil buffer nil (cdr args))
4907 ;; Insert error messages if they were separated.
4908 (when (listp buffer)
4909 (with-current-buffer error-buffer
4910 (insert-file-contents (cadr buffer)))
4911 (delete-file (cadr buffer)))
4912 (if current-buffer-p
4913 ;; This is like exchange-point-and-mark, but doesn't
4914 ;; activate the mark. It is cleaner to avoid activation,
4915 ;; even though the command loop would deactivate the mark
4916 ;; because we inserted text.
4917 (goto-char (prog1 (mark t)
4918 (set-marker (mark-marker) (point)
4919 (current-buffer))))
4920 ;; There's some output, display it.
4921 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4922 (if (functionp 'display-message-or-buffer)
4923 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
4924 (pop-to-buffer output-buffer))))))))
4926 ;; File Editing.
4928 (defvar tramp-handle-file-local-copy-hook nil
4929 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4931 (defun tramp-handle-file-local-copy (filename)
4932 "Like `file-local-copy' for Tramp files."
4934 (with-parsed-tramp-file-name filename nil
4935 (unless (file-exists-p filename)
4936 (tramp-error
4937 v 'file-error
4938 "Cannot make local copy of non-existing file `%s'" filename))
4940 (let* ((size (nth 7 (file-attributes filename)))
4941 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
4942 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
4943 (tmpfile (tramp-compat-make-temp-file filename)))
4945 (condition-case err
4946 (cond
4947 ;; `copy-file' handles direct copy and out-of-band methods.
4948 ((or (tramp-local-host-p v)
4949 (tramp-method-out-of-band-p v size))
4950 (copy-file filename tmpfile t t))
4952 ;; Use inline encoding for file transfer.
4953 (rem-enc
4954 (save-excursion
4955 (with-progress-reporter
4956 v 3 (format "Encoding remote file %s" filename)
4957 (tramp-barf-unless-okay
4958 v (format rem-enc (tramp-shell-quote-argument localname))
4959 "Encoding remote file failed"))
4961 (if (functionp loc-dec)
4962 ;; If local decoding is a function, we call it. We
4963 ;; must disable multibyte, because
4964 ;; `uudecode-decode-region' doesn't handle it
4965 ;; correctly.
4966 (with-temp-buffer
4967 (set-buffer-multibyte nil)
4968 (insert-buffer-substring (tramp-get-buffer v))
4969 (with-progress-reporter
4970 v 3 (format "Decoding remote file %s with function %s"
4971 filename loc-dec)
4972 (funcall loc-dec (point-min) (point-max))
4973 ;; Unset `file-name-handler-alist'. Otherwise,
4974 ;; epa-file gets confused.
4975 (let (file-name-handler-alist
4976 (coding-system-for-write 'binary))
4977 (write-region (point-min) (point-max) tmpfile))))
4979 ;; If tramp-decoding-function is not defined for this
4980 ;; method, we invoke tramp-decoding-command instead.
4981 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4982 ;; Unset `file-name-handler-alist'. Otherwise,
4983 ;; epa-file gets confused.
4984 (let (file-name-handler-alist
4985 (coding-system-for-write 'binary))
4986 (write-region (point-min) (point-max) tmpfile2))
4987 (with-progress-reporter
4988 v 3 (format "Decoding remote file %s with command %s"
4989 filename loc-dec)
4990 (unwind-protect
4991 (tramp-call-local-coding-command
4992 loc-dec tmpfile2 tmpfile)
4993 (delete-file tmpfile2)))))
4995 ;; Set proper permissions.
4996 (set-file-modes tmpfile (tramp-default-file-modes filename))
4997 ;; Set local user ownership.
4998 (tramp-set-file-uid-gid tmpfile)))
5000 ;; Oops, I don't know what to do.
5001 (t (tramp-error
5002 v 'file-error "Wrong method specification for `%s'" method)))
5004 ;; Error handling.
5005 ((error quit)
5006 (delete-file tmpfile)
5007 (signal (car err) (cdr err))))
5009 (run-hooks 'tramp-handle-file-local-copy-hook)
5010 tmpfile)))
5012 (defun tramp-handle-file-remote-p (filename &optional identification connected)
5013 "Like `file-remote-p' for Tramp files."
5014 (let ((tramp-verbose 3))
5015 (when (tramp-tramp-file-p filename)
5016 (let* ((v (tramp-dissect-file-name filename))
5017 (p (tramp-get-connection-process v))
5018 (c (and p (processp p) (memq (process-status p) '(run open)))))
5019 ;; We expand the file name only, if there is already a connection.
5020 (with-parsed-tramp-file-name
5021 (if c (expand-file-name filename) filename) nil
5022 (and (or (not connected) c)
5023 (cond
5024 ((eq identification 'method) method)
5025 ((eq identification 'user) user)
5026 ((eq identification 'host) host)
5027 ((eq identification 'localname) localname)
5028 (t (tramp-make-tramp-file-name method user host "")))))))))
5030 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
5031 "Like `find-operation-coding-system' for Tramp filenames.
5032 Tramp's `insert-file-contents' and `write-region' work over
5033 temporary file names. If `file-coding-system-alist' contains an
5034 expression, which matches more than the file name suffix, the
5035 coding system might not be determined. This function repairs it."
5036 (let (result)
5037 (dolist (elt file-coding-system-alist result)
5038 (when (and (consp elt) (string-match (car elt) filename))
5039 ;; We found a matching entry in `file-coding-system-alist'.
5040 ;; So we add a similar entry, but with the temporary file name
5041 ;; as regexp.
5042 (add-to-list
5043 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
5045 (defun tramp-handle-insert-file-contents
5046 (filename &optional visit beg end replace)
5047 "Like `insert-file-contents' for Tramp files."
5048 (barf-if-buffer-read-only)
5049 (setq filename (expand-file-name filename))
5050 (let (result local-copy remote-copy)
5051 (with-parsed-tramp-file-name filename nil
5052 (unwind-protect
5053 (if (not (file-exists-p filename))
5054 ;; We don't raise a Tramp error, because it might be
5055 ;; suppressed, like in `find-file-noselect-1'.
5056 (signal 'file-error
5057 (list "File not found on remote host" filename))
5059 (if (and (tramp-local-host-p v)
5060 (let (file-name-handler-alist)
5061 (file-readable-p localname)))
5062 ;; Short track: if we are on the local host, we can
5063 ;; run directly.
5064 (setq result
5065 (tramp-run-real-handler
5066 'insert-file-contents
5067 (list localname visit beg end replace)))
5069 ;; When we shall insert only a part of the file, we copy
5070 ;; this part.
5071 (when (or beg end)
5072 (setq remote-copy (tramp-make-tramp-temp-file v))
5073 (tramp-send-command
5075 (cond
5076 ((and beg end)
5077 (format "tail -c +%d %s | head -c +%d >%s"
5078 (1+ beg) (tramp-shell-quote-argument localname)
5079 (- end beg) remote-copy))
5080 (beg
5081 (format "tail -c +%d %s >%s"
5082 (1+ beg) (tramp-shell-quote-argument localname)
5083 remote-copy))
5084 (end
5085 (format "head -c +%d %s >%s"
5086 (1+ end) (tramp-shell-quote-argument localname)
5087 remote-copy)))))
5089 ;; `insert-file-contents-literally' takes care to avoid
5090 ;; calling jka-compr. By let-binding
5091 ;; `inhibit-file-name-operation', we propagate that care
5092 ;; to the `file-local-copy' operation.
5093 (setq local-copy
5094 (let ((inhibit-file-name-operation
5095 (when (eq inhibit-file-name-operation
5096 'insert-file-contents)
5097 'file-local-copy)))
5098 (cond
5099 ((stringp remote-copy)
5100 (file-local-copy
5101 (tramp-make-tramp-file-name
5102 method user host remote-copy)))
5103 ((stringp tramp-temp-buffer-file-name)
5104 (copy-file filename tramp-temp-buffer-file-name 'ok)
5105 tramp-temp-buffer-file-name)
5106 (t (file-local-copy filename)))))
5108 ;; When the file is not readable for the owner, it
5109 ;; cannot be inserted, even it is redable for the group
5110 ;; or for everybody.
5111 (set-file-modes local-copy (tramp-compat-octal-to-decimal "0600"))
5113 (when (and (null remote-copy)
5114 (tramp-get-method-parameter
5115 method 'tramp-copy-keep-tmpfile))
5116 ;; We keep the local file for performance reasons,
5117 ;; useful for "rsync".
5118 (setq tramp-temp-buffer-file-name local-copy)
5119 (put 'tramp-temp-buffer-file-name 'permanent-local t))
5121 (with-progress-reporter
5122 v 3 (format "Inserting local temp file `%s'" local-copy)
5123 ;; We must ensure that `file-coding-system-alist'
5124 ;; matches `local-copy'.
5125 (let ((file-coding-system-alist
5126 (tramp-find-file-name-coding-system-alist
5127 filename local-copy)))
5128 (setq result
5129 (insert-file-contents
5130 local-copy nil nil nil replace))))))
5132 ;; Save exit.
5133 (progn
5134 (when visit
5135 (setq buffer-file-name filename)
5136 (setq buffer-read-only (not (file-writable-p filename)))
5137 (set-visited-file-modtime)
5138 (set-buffer-modified-p nil))
5139 (when (and (stringp local-copy)
5140 (or remote-copy (null tramp-temp-buffer-file-name)))
5141 (delete-file local-copy))
5142 (when (stringp remote-copy)
5143 (delete-file
5144 (tramp-make-tramp-file-name method user host remote-copy))))))
5146 ;; Result.
5147 (list (expand-file-name filename)
5148 (cadr result))))
5150 ;; This is needed for XEmacs only. Code stolen from files.el.
5151 (defun tramp-handle-insert-file-contents-literally
5152 (filename &optional visit beg end replace)
5153 "Like `insert-file-contents-literally' for Tramp files."
5154 (let ((format-alist nil)
5155 (after-insert-file-functions nil)
5156 (coding-system-for-read 'no-conversion)
5157 (coding-system-for-write 'no-conversion)
5158 (find-buffer-file-type-function
5159 (if (fboundp 'find-buffer-file-type)
5160 (symbol-function 'find-buffer-file-type)
5161 nil))
5162 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
5163 (inhibit-file-name-operation 'insert-file-contents))
5164 (unwind-protect
5165 (progn
5166 (fset 'find-buffer-file-type (lambda (filename) t))
5167 (insert-file-contents filename visit beg end replace))
5168 ;; Save exit.
5169 (if find-buffer-file-type-function
5170 (fset 'find-buffer-file-type find-buffer-file-type-function)
5171 (fmakunbound 'find-buffer-file-type)))))
5173 (defun tramp-handle-find-backup-file-name (filename)
5174 "Like `find-backup-file-name' for Tramp files."
5175 (with-parsed-tramp-file-name filename nil
5176 ;; We set both variables. It doesn't matter whether it is
5177 ;; Emacs or XEmacs.
5178 (let ((backup-directory-alist
5179 ;; Emacs case.
5180 (when (boundp 'backup-directory-alist)
5181 (if (symbol-value 'tramp-backup-directory-alist)
5182 (mapcar
5183 (lambda (x)
5184 (cons
5185 (car x)
5186 (if (and (stringp (cdr x))
5187 (file-name-absolute-p (cdr x))
5188 (not (tramp-file-name-p (cdr x))))
5189 (tramp-make-tramp-file-name method user host (cdr x))
5190 (cdr x))))
5191 (symbol-value 'tramp-backup-directory-alist))
5192 (symbol-value 'backup-directory-alist))))
5194 (bkup-backup-directory-info
5195 ;; XEmacs case.
5196 (when (boundp 'bkup-backup-directory-info)
5197 (if (symbol-value 'tramp-bkup-backup-directory-info)
5198 (mapcar
5199 (lambda (x)
5200 (nconc
5201 (list (car x))
5202 (list
5203 (if (and (stringp (car (cdr x)))
5204 (file-name-absolute-p (car (cdr x)))
5205 (not (tramp-file-name-p (car (cdr x)))))
5206 (tramp-make-tramp-file-name
5207 method user host (car (cdr x)))
5208 (car (cdr x))))
5209 (cdr (cdr x))))
5210 (symbol-value 'tramp-bkup-backup-directory-info))
5211 (symbol-value 'bkup-backup-directory-info)))))
5213 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
5215 (defun tramp-handle-make-auto-save-file-name ()
5216 "Like `make-auto-save-file-name' for Tramp files.
5217 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
5218 (let ((tramp-auto-save-directory tramp-auto-save-directory)
5219 (buffer-file-name
5220 (tramp-subst-strs-in-string
5221 '(("_" . "|")
5222 ("/" . "_a")
5223 (":" . "_b")
5224 ("|" . "__")
5225 ("[" . "_l")
5226 ("]" . "_r"))
5227 (buffer-file-name))))
5228 ;; File name must be unique. This is ensured with Emacs 22 (see
5229 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
5230 ;; all other cases we must do it ourselves.
5231 (when (boundp 'auto-save-file-name-transforms)
5232 (mapc
5233 (lambda (x)
5234 (when (and (string-match (car x) buffer-file-name)
5235 (not (car (cddr x))))
5236 (setq tramp-auto-save-directory
5237 (or tramp-auto-save-directory
5238 (tramp-compat-temporary-file-directory)))))
5239 (symbol-value 'auto-save-file-name-transforms)))
5240 ;; Create directory.
5241 (when tramp-auto-save-directory
5242 (setq buffer-file-name
5243 (expand-file-name buffer-file-name tramp-auto-save-directory))
5244 (unless (file-exists-p tramp-auto-save-directory)
5245 (make-directory tramp-auto-save-directory t)))
5246 ;; Run plain `make-auto-save-file-name'. There might be an advice when
5247 ;; it is not a magic file name operation (since Emacs 22).
5248 ;; We must deactivate it temporarily.
5249 (if (not (ad-is-active 'make-auto-save-file-name))
5250 (tramp-run-real-handler 'make-auto-save-file-name nil)
5251 ;; else
5252 (ad-deactivate 'make-auto-save-file-name)
5253 (prog1
5254 (tramp-run-real-handler 'make-auto-save-file-name nil)
5255 (ad-activate 'make-auto-save-file-name)))))
5257 (defvar tramp-handle-write-region-hook nil
5258 "Normal hook to be run at the end of `tramp-handle-write-region'.")
5260 ;; CCC grok LOCKNAME
5261 (defun tramp-handle-write-region
5262 (start end filename &optional append visit lockname confirm)
5263 "Like `write-region' for Tramp files."
5264 (setq filename (expand-file-name filename))
5265 (with-parsed-tramp-file-name filename nil
5266 ;; Following part commented out because we don't know what to do about
5267 ;; file locking, and it does not appear to be a problem to ignore it.
5268 ;; Ange-ftp ignores it, too.
5269 ;; (when (and lockname (stringp lockname))
5270 ;; (setq lockname (expand-file-name lockname)))
5271 ;; (unless (or (eq lockname nil)
5272 ;; (string= lockname filename))
5273 ;; (error
5274 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
5276 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
5277 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
5278 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
5279 (tramp-error v 'file-error "File not overwritten")))
5281 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
5282 (tramp-get-remote-uid v 'integer)))
5283 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
5284 (tramp-get-remote-gid v 'integer))))
5286 (if (and (tramp-local-host-p v)
5287 ;; `file-writable-p' calls `file-expand-file-name'. We
5288 ;; cannot use `tramp-run-real-handler' therefore.
5289 (let (file-name-handler-alist)
5290 (and
5291 (file-writable-p (file-name-directory localname))
5292 (or (file-directory-p localname)
5293 (file-writable-p localname)))))
5294 ;; Short track: if we are on the local host, we can run directly.
5295 (tramp-run-real-handler
5296 'write-region
5297 (list start end localname append 'no-message lockname confirm))
5299 (let ((modes (save-excursion (tramp-default-file-modes filename)))
5300 ;; We use this to save the value of
5301 ;; `last-coding-system-used' after writing the tmp
5302 ;; file. At the end of the function, we set
5303 ;; `last-coding-system-used' to this saved value. This
5304 ;; way, any intermediary coding systems used while
5305 ;; talking to the remote shell or suchlike won't hose
5306 ;; this variable. This approach was snarfed from
5307 ;; ange-ftp.el.
5308 coding-system-used
5309 ;; Write region into a tmp file. This isn't really
5310 ;; needed if we use an encoding function, but currently
5311 ;; we use it always because this makes the logic
5312 ;; simpler.
5313 (tmpfile (or tramp-temp-buffer-file-name
5314 (tramp-compat-make-temp-file filename))))
5316 ;; If `append' is non-nil, we copy the file locally, and let
5317 ;; the native `write-region' implementation do the job.
5318 (when append (copy-file filename tmpfile 'ok))
5320 ;; We say `no-message' here because we don't want the
5321 ;; visited file modtime data to be clobbered from the temp
5322 ;; file. We call `set-visited-file-modtime' ourselves later
5323 ;; on. We must ensure that `file-coding-system-alist'
5324 ;; matches `tmpfile'.
5325 (let (file-name-handler-alist
5326 (file-coding-system-alist
5327 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5328 (condition-case err
5329 (tramp-run-real-handler
5330 'write-region
5331 (list start end tmpfile append 'no-message lockname confirm))
5332 ((error quit)
5333 (setq tramp-temp-buffer-file-name nil)
5334 (delete-file tmpfile)
5335 (signal (car err) (cdr err))))
5337 ;; Now, `last-coding-system-used' has the right value. Remember it.
5338 (when (boundp 'last-coding-system-used)
5339 (setq coding-system-used
5340 (symbol-value 'last-coding-system-used))))
5342 ;; The permissions of the temporary file should be set. If
5343 ;; filename does not exist (eq modes nil) it has been
5344 ;; renamed to the backup file. This case `save-buffer'
5345 ;; handles permissions.
5346 ;; Ensure, that it is still readable.
5347 (when modes
5348 (set-file-modes
5349 tmpfile
5350 (logior (or modes 0) (tramp-compat-octal-to-decimal "0400"))))
5352 ;; This is a bit lengthy due to the different methods
5353 ;; possible for file transfer. First, we check whether the
5354 ;; method uses an rcp program. If so, we call it.
5355 ;; Otherwise, both encoding and decoding command must be
5356 ;; specified. However, if the method _also_ specifies an
5357 ;; encoding function, then that is used for encoding the
5358 ;; contents of the tmp file.
5359 (let* ((size (nth 7 (file-attributes tmpfile)))
5360 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
5361 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
5362 (cond
5363 ;; `copy-file' handles direct copy and out-of-band methods.
5364 ((or (tramp-local-host-p v)
5365 (tramp-method-out-of-band-p v size))
5366 (if (and (not (stringp start))
5367 (= (or end (point-max)) (point-max))
5368 (= (or start (point-min)) (point-min))
5369 (tramp-get-method-parameter
5370 method 'tramp-copy-keep-tmpfile))
5371 (progn
5372 (setq tramp-temp-buffer-file-name tmpfile)
5373 (condition-case err
5374 ;; We keep the local file for performance
5375 ;; reasons, useful for "rsync".
5376 (copy-file tmpfile filename t)
5377 ((error quit)
5378 (setq tramp-temp-buffer-file-name nil)
5379 (delete-file tmpfile)
5380 (signal (car err) (cdr err)))))
5381 (setq tramp-temp-buffer-file-name nil)
5382 ;; Don't rename, in order to keep context in SELinux.
5383 (unwind-protect
5384 (copy-file tmpfile filename t)
5385 (delete-file tmpfile))))
5387 ;; Use inline file transfer.
5388 (rem-dec
5389 ;; Encode tmpfile.
5390 (unwind-protect
5391 (with-temp-buffer
5392 (set-buffer-multibyte nil)
5393 ;; Use encoding function or command.
5394 (if (functionp loc-enc)
5395 (with-progress-reporter
5396 v 3 (format "Encoding region using function `%s'"
5397 loc-enc)
5398 (let ((coding-system-for-read 'binary))
5399 (insert-file-contents-literally tmpfile))
5400 ;; The following `let' is a workaround for the
5401 ;; base64.el that comes with pgnus-0.84. If
5402 ;; both of the following conditions are
5403 ;; satisfied, it tries to write to a local
5404 ;; file in default-directory, but at this
5405 ;; point, default-directory is remote.
5406 ;; (`call-process-region' can't write to
5407 ;; remote files, it seems.) The file in
5408 ;; question is a tmp file anyway.
5409 (let ((default-directory
5410 (tramp-compat-temporary-file-directory)))
5411 (funcall loc-enc (point-min) (point-max))))
5413 (with-progress-reporter
5414 v 3 (format "Encoding region using command `%s'"
5415 loc-enc)
5416 (unless (zerop (tramp-call-local-coding-command
5417 loc-enc tmpfile t))
5418 (tramp-error
5419 v 'file-error
5420 (concat "Cannot write to `%s', "
5421 "local encoding command `%s' failed")
5422 filename loc-enc))))
5424 ;; Send buffer into remote decoding command which
5425 ;; writes to remote file. Because this happens on
5426 ;; the remote host, we cannot use the function.
5427 (with-progress-reporter
5429 (format "Decoding region into remote file %s" filename)
5430 (goto-char (point-max))
5431 (unless (bolp) (newline))
5432 (tramp-send-command
5434 (format
5435 (concat rem-dec " <<'EOF'\n%sEOF")
5436 (tramp-shell-quote-argument localname)
5437 (buffer-string)))
5438 (tramp-barf-unless-okay
5439 v nil
5440 "Couldn't write region to `%s', decode using `%s' failed"
5441 filename rem-dec)
5442 ;; When `file-precious-flag' is set, the region is
5443 ;; written to a temporary file. Check that the
5444 ;; checksum is equal to that from the local tmpfile.
5445 (when file-precious-flag
5446 (erase-buffer)
5447 (and
5448 ;; cksum runs locally, if possible.
5449 (zerop (tramp-compat-call-process "cksum" tmpfile t))
5450 ;; cksum runs remotely.
5451 (zerop
5452 (tramp-send-command-and-check
5454 (format
5455 "cksum <%s"
5456 (tramp-shell-quote-argument localname))))
5457 ;; ... they are different.
5458 (not
5459 (string-equal
5460 (buffer-string)
5461 (with-current-buffer (tramp-get-buffer v)
5462 (buffer-string))))
5463 (tramp-error
5464 v 'file-error
5465 (concat "Couldn't write region to `%s',"
5466 " decode using `%s' failed")
5467 filename rem-dec)))))
5469 ;; Save exit.
5470 (delete-file tmpfile)))
5472 ;; That's not expected.
5474 (tramp-error
5475 v 'file-error
5476 (concat "Method `%s' should specify both encoding and "
5477 "decoding command or an rcp program")
5478 method))))
5480 ;; Make `last-coding-system-used' have the right value.
5481 (when coding-system-used
5482 (set 'last-coding-system-used coding-system-used))))
5484 (tramp-flush-file-property v (file-name-directory localname))
5485 (tramp-flush-file-property v localname)
5487 ;; We must protect `last-coding-system-used', now we have set it
5488 ;; to its correct value.
5489 (let (last-coding-system-used (need-chown t))
5490 ;; Set file modification time.
5491 (when (or (eq visit t) (stringp visit))
5492 (let ((file-attr (file-attributes filename)))
5493 (set-visited-file-modtime
5494 ;; We must pass modtime explicitely, because filename can
5495 ;; be different from (buffer-file-name), f.e. if
5496 ;; `file-precious-flag' is set.
5497 (nth 5 file-attr))
5498 (when (and (eq (nth 2 file-attr) uid)
5499 (eq (nth 3 file-attr) gid))
5500 (setq need-chown nil))))
5502 ;; Set the ownership.
5503 (when need-chown
5504 (tramp-set-file-uid-gid filename uid gid))
5505 (when (or (eq visit t) (null visit) (stringp visit))
5506 (tramp-message v 0 "Wrote %s" filename))
5507 (run-hooks 'tramp-handle-write-region-hook)))))
5509 (defvar tramp-vc-registered-file-names nil
5510 "List used to collect file names, which are checked during `vc-registered'.")
5512 ;; VC backends check for the existence of various different special
5513 ;; files. This is very time consuming, because every single check
5514 ;; requires a remote command (the file cache must be invalidated).
5515 ;; Therefore, we apply a kind of optimization. We install the file
5516 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5517 ;; remembers all file names for which `file-exists-p' or
5518 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5519 ;; is performed. Afterwards, a script is applied for all collected
5520 ;; file names, using just one remote command. The result of this
5521 ;; script is used to fill the file cache with actual values. Now we
5522 ;; can reset the file name handlers, and we make a second run of
5523 ;; `vc-registered', which returns the expected result without sending
5524 ;; any other remote command.
5525 (defun tramp-handle-vc-registered (file)
5526 "Like `vc-registered' for Tramp files."
5527 (with-temp-message ""
5528 (with-parsed-tramp-file-name file nil
5529 (with-progress-reporter
5530 v 3 (format "Checking `vc-registered' for %s" file)
5532 ;; There could be new files, created by the vc backend. We
5533 ;; cannot reuse the old cache entries, therefore.
5534 (let (tramp-vc-registered-file-names
5535 (tramp-cache-inhibit-cache (current-time))
5536 (file-name-handler-alist
5537 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5539 ;; Here we collect only file names, which need an operation.
5540 (tramp-run-real-handler 'vc-registered (list file))
5541 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5543 ;; Send just one command, in order to fill the cache.
5544 (when tramp-vc-registered-file-names
5545 (tramp-maybe-send-script
5547 (format tramp-vc-registered-read-file-names
5548 (tramp-get-file-exists-command v)
5549 (format "%s -r" (tramp-get-test-command v)))
5550 "tramp_vc_registered_read_file_names")
5552 (dolist
5553 (elt
5554 (tramp-send-command-and-read
5556 (format
5557 "tramp_vc_registered_read_file_names <<'EOF'\n%s\nEOF\n"
5558 (mapconcat 'tramp-shell-quote-argument
5559 tramp-vc-registered-file-names
5560 "\n"))))
5562 (tramp-set-file-property
5563 v (car elt) (cadr elt) (cadr (cdr elt))))))
5565 ;; Second run. Now all `file-exists-p' or `file-readable-p'
5566 ;; calls shall be answered from the file cache. We unset
5567 ;; `process-file-side-effects' in order to keep the cache when
5568 ;; `process-file' calls appear.
5569 (let (process-file-side-effects)
5570 (tramp-run-real-handler 'vc-registered (list file)))))))
5572 ;;;###autoload
5573 (progn (defun tramp-run-real-handler (operation args)
5574 "Invoke normal file name handler for OPERATION.
5575 First arg specifies the OPERATION, second arg is a list of arguments to
5576 pass to the OPERATION."
5577 (let* ((inhibit-file-name-handlers
5578 `(tramp-file-name-handler
5579 tramp-vc-file-name-handler
5580 tramp-completion-file-name-handler
5581 cygwin-mount-name-hook-function
5582 cygwin-mount-map-drive-hook-function
5584 ,(and (eq inhibit-file-name-operation operation)
5585 inhibit-file-name-handlers)))
5586 (inhibit-file-name-operation operation))
5587 (apply operation args))))
5589 ;;;###autoload
5590 (progn (defun tramp-completion-run-real-handler (operation args)
5591 "Invoke `tramp-file-name-handler' for OPERATION.
5592 First arg specifies the OPERATION, second arg is a list of arguments to
5593 pass to the OPERATION."
5594 (let* ((inhibit-file-name-handlers
5595 `(tramp-completion-file-name-handler
5596 cygwin-mount-name-hook-function
5597 cygwin-mount-map-drive-hook-function
5599 ,(and (eq inhibit-file-name-operation operation)
5600 inhibit-file-name-handlers)))
5601 (inhibit-file-name-operation operation))
5602 (apply operation args))))
5604 ;; We handle here all file primitives. Most of them have the file
5605 ;; name as first parameter; nevertheless we check for them explicitly
5606 ;; in order to be signaled if a new primitive appears. This
5607 ;; scenario is needed because there isn't a way to decide by
5608 ;; syntactical means whether a foreign method must be called. It would
5609 ;; ease the life if `file-name-handler-alist' would support a decision
5610 ;; function as well but regexp only.
5611 (defun tramp-file-name-for-operation (operation &rest args)
5612 "Return file name related to OPERATION file primitive.
5613 ARGS are the arguments OPERATION has been called with."
5614 (cond
5615 ;; FILE resp DIRECTORY.
5616 ((member operation
5617 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5618 'delete-file 'diff-latest-backup-file 'directory-file-name
5619 'directory-files 'directory-files-and-attributes
5620 'dired-compress-file 'dired-uncache
5621 'file-accessible-directory-p 'file-attributes
5622 'file-directory-p 'file-executable-p 'file-exists-p
5623 'file-local-copy 'file-remote-p 'file-modes
5624 'file-name-as-directory 'file-name-directory
5625 'file-name-nondirectory 'file-name-sans-versions
5626 'file-ownership-preserved-p 'file-readable-p
5627 'file-regular-p 'file-symlink-p 'file-truename
5628 'file-writable-p 'find-backup-file-name 'find-file-noselect
5629 'get-file-buffer 'insert-directory 'insert-file-contents
5630 'load 'make-directory 'make-directory-internal
5631 'set-file-modes 'substitute-in-file-name
5632 'unhandled-file-name-directory 'vc-registered
5633 ;; Emacs 22+ only.
5634 'set-file-times
5635 ;; Emacs 24+ only.
5636 'file-selinux-context 'set-file-selinux-context
5637 ;; XEmacs only.
5638 'abbreviate-file-name 'create-file-buffer
5639 'dired-file-modtime 'dired-make-compressed-filename
5640 'dired-recursive-delete-directory 'dired-set-file-modtime
5641 'dired-shell-unhandle-file-name 'dired-uucode-file
5642 'insert-file-contents-literally 'make-temp-name 'recover-file
5643 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5644 (if (file-name-absolute-p (nth 0 args))
5645 (nth 0 args)
5646 (expand-file-name (nth 0 args))))
5647 ;; FILE DIRECTORY resp FILE1 FILE2.
5648 ((member operation
5649 (list 'add-name-to-file 'copy-file 'expand-file-name
5650 'file-name-all-completions 'file-name-completion
5651 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5652 ;; Emacs 23+ only.
5653 'copy-directory
5654 ;; XEmacs only.
5655 'dired-make-relative-symlink
5656 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5657 (save-match-data
5658 (cond
5659 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5660 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5661 (t (buffer-file-name (current-buffer))))))
5662 ;; START END FILE.
5663 ((eq operation 'write-region)
5664 (nth 2 args))
5665 ;; BUFFER.
5666 ((member operation
5667 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5668 ;; Emacs 22+ only.
5669 'make-auto-save-file-name
5670 ;; XEmacs only.
5671 'backup-buffer))
5672 (buffer-file-name
5673 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5674 ;; COMMAND.
5675 ((member operation
5676 (list ;; not in Emacs 23+.
5677 'dired-call-process
5678 ;; Emacs only.
5679 'shell-command
5680 ;; Emacs 22+ only.
5681 'process-file
5682 ;; Emacs 23+ only.
5683 'start-file-process
5684 ;; XEmacs only.
5685 'dired-print-file 'dired-shell-call-process
5686 ;; nowhere yet.
5687 'executable-find 'start-process
5688 'call-process 'call-process-region))
5689 default-directory)
5690 ;; Unknown file primitive.
5691 (t (error "unknown file I/O primitive: %s" operation))))
5693 (defun tramp-find-foreign-file-name-handler (filename)
5694 "Return foreign file name handler if exists."
5695 (when (tramp-tramp-file-p filename)
5696 (let ((v (tramp-dissect-file-name filename t))
5697 (handler tramp-foreign-file-name-handler-alist)
5698 elt res)
5699 ;; When we are not fully sure that filename completion is safe,
5700 ;; we should not return a handler.
5701 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5702 (and (tramp-file-name-host v)
5703 (not (member (tramp-file-name-host v)
5704 (mapcar 'car tramp-methods))))
5705 (not (tramp-completion-mode-p)))
5706 (while handler
5707 (setq elt (car handler)
5708 handler (cdr handler))
5709 (when (funcall (car elt) filename)
5710 (setq handler nil
5711 res (cdr elt))))
5712 res))))
5714 ;; Main function.
5715 ;;;###autoload
5716 (defun tramp-file-name-handler (operation &rest args)
5717 "Invoke Tramp file name handler.
5718 Falls back to normal file name handler if no Tramp file name handler exists."
5719 (if tramp-mode
5720 (save-match-data
5721 (let* ((filename
5722 (tramp-replace-environment-variables
5723 (apply 'tramp-file-name-for-operation operation args)))
5724 (completion (tramp-completion-mode-p))
5725 (foreign (tramp-find-foreign-file-name-handler filename)))
5726 (with-parsed-tramp-file-name filename nil
5727 ;; Call the backend function.
5728 (if foreign
5729 (condition-case err
5730 (apply foreign operation args)
5732 ;; Trace that somebody has interrupted the
5733 ;; operation.
5734 (quit
5735 (let (tramp-message-show-message)
5736 (tramp-message
5737 v 1 "Interrupt received in operation %s"
5738 (append (list operation) args)))
5739 ;; Propagate the quit signal.
5740 (signal (car err) (cdr err)))
5742 ;; When we are in completion mode, some failed
5743 ;; operations shall return at least a default value
5744 ;; in order to give the user a chance to correct the
5745 ;; file name in the minibuffer.
5746 (error
5747 (cond
5748 ((and completion (zerop (length localname))
5749 (memq operation '(file-exists-p file-directory-p)))
5751 ((and completion (zerop (length localname))
5752 (memq operation
5753 '(expand-file-name file-name-as-directory)))
5754 filename)
5755 ;; Propagate the error.
5756 (t (signal (car err) (cdr err))))))
5758 ;; Nothing to do for us.
5759 (tramp-run-real-handler operation args)))))
5761 ;; When `tramp-mode' is not enabled, we don't do anything.
5762 (tramp-run-real-handler operation args)))
5764 ;; In Emacs, there is some concurrency due to timers. If a timer
5765 ;; interrupts Tramp and wishes to use the same connection buffer as
5766 ;; the "main" Emacs, then garbage might occur in the connection
5767 ;; buffer. Therefore, we need to make sure that a timer does not use
5768 ;; the same connection buffer as the "main" Emacs. We implement a
5769 ;; cheap global lock, instead of locking each connection buffer
5770 ;; separately. The global lock is based on two variables,
5771 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5772 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5773 ;; processing of a single file operation, so we need to allow
5774 ;; recursive calls. That's where the `tramp-locker' variable comes in
5775 ;; -- it is let-bound to t during the execution of the current
5776 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5777 ;; then we should just proceed because we have been called
5778 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5779 ;; interrupting the "main" Emacs, and then we signal an error.
5781 (defvar tramp-locked nil
5782 "If non-nil, then Tramp is currently busy.
5783 Together with `tramp-locker', this implements a locking mechanism
5784 preventing reentrant calls of Tramp.")
5786 (defvar tramp-locker nil
5787 "If non-nil, then a caller has locked Tramp.
5788 Together with `tramp-locked', this implements a locking mechanism
5789 preventing reentrant calls of Tramp.")
5791 (defun tramp-sh-file-name-handler (operation &rest args)
5792 "Invoke remote-shell Tramp file name handler.
5793 Fall back to normal file name handler if no Tramp handler exists."
5794 (when (and tramp-locked (not tramp-locker))
5795 (setq tramp-locked nil)
5796 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5797 (let ((tl tramp-locked))
5798 (unwind-protect
5799 (progn
5800 (setq tramp-locked t)
5801 (let ((tramp-locker t))
5802 (save-match-data
5803 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5804 (if fn
5805 (apply (cdr fn) args)
5806 (tramp-run-real-handler operation args))))))
5807 (setq tramp-locked tl))))
5809 (defun tramp-vc-file-name-handler (operation &rest args)
5810 "Invoke special file name handler, which collects files to be handled."
5811 (save-match-data
5812 (let ((filename
5813 (tramp-replace-environment-variables
5814 (apply 'tramp-file-name-for-operation operation args)))
5815 (fn (assoc operation tramp-file-name-handler-alist)))
5816 (with-parsed-tramp-file-name filename nil
5817 (cond
5818 ;; That's what we want: file names, for which checks are
5819 ;; applied. We assume, that VC uses only `file-exists-p' and
5820 ;; `file-readable-p' checks; otherwise we must extend the
5821 ;; list. We do not perform any action, but return nil, in
5822 ;; order to keep `vc-registered' running.
5823 ((and fn (memq operation '(file-exists-p file-readable-p)))
5824 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5825 nil)
5826 ;; Tramp file name handlers like `expand-file-name'. They
5827 ;; must still work.
5829 (save-match-data (apply (cdr fn) args)))
5830 ;; Default file name handlers, we don't care.
5831 (t (tramp-run-real-handler operation args)))))))
5833 ;;;###autoload
5834 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5835 "Invoke Tramp file name completion handler.
5836 Falls back to normal file name handler if no Tramp file name handler exists."
5837 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5838 ;; would otherwise use backslash.
5839 (let ((directory-sep-char ?/)
5840 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5841 (if (and
5842 ;; When `tramp-mode' is not enabled, we don't do anything.
5843 fn tramp-mode
5844 ;; For other syntaxes than `sep', the regexp matches many common
5845 ;; situations where the user doesn't actually want to use Tramp.
5846 ;; So to avoid autoloading Tramp after typing just "/s", we
5847 ;; disable this part of the completion, unless the user implicitly
5848 ;; indicated his interest in using a fancier completion system.
5849 (or (eq tramp-syntax 'sep)
5850 (featurep 'tramp) ;; If it's loaded, we may as well use it.
5851 ;; `partial-completion-mode' does not exist in XEmacs.
5852 ;; It is obsoleted with Emacs 24.1.
5853 (and (boundp 'partial-completion-mode)
5854 (symbol-value 'partial-completion-mode))
5855 ;; FIXME: These may have been loaded even if the user never
5856 ;; intended to use them.
5857 (featurep 'ido)
5858 (featurep 'icicles)))
5859 (save-match-data (apply (cdr fn) args))
5860 (tramp-completion-run-real-handler operation args)))))
5862 ;;;###autoload
5863 (progn (defun tramp-register-file-name-handlers ()
5864 "Add Tramp file name handlers to `file-name-handler-alist'."
5865 ;; Remove autoloaded handlers from file name handler alist. Useful,
5866 ;; if `tramp-syntax' has been changed.
5867 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5868 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5869 (let ((a1 (rassq
5870 'tramp-completion-file-name-handler file-name-handler-alist)))
5871 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5872 ;; Add the handlers.
5873 (add-to-list 'file-name-handler-alist
5874 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5875 (put 'tramp-file-name-handler 'safe-magic t)
5876 (add-to-list 'file-name-handler-alist
5877 (cons tramp-completion-file-name-regexp
5878 'tramp-completion-file-name-handler))
5879 (put 'tramp-completion-file-name-handler 'safe-magic t)
5880 ;; If jka-compr or epa-file are already loaded, move them to the
5881 ;; front of `file-name-handler-alist'.
5882 (dolist (fnh '(epa-file-handler jka-compr-handler))
5883 (let ((entry (rassoc fnh file-name-handler-alist)))
5884 (when entry
5885 (setq file-name-handler-alist
5886 (cons entry (delete entry file-name-handler-alist))))))))
5888 ;; `tramp-file-name-handler' must be registered before evaluation of
5889 ;; site-start and init files, because there might exist remote files
5890 ;; already, f.e. files kept via recentf-mode.
5891 ;;;###autoload(tramp-register-file-name-handlers)
5892 (tramp-register-file-name-handlers)
5894 ;;;###autoload
5895 (defun tramp-unload-file-name-handlers ()
5896 (setq file-name-handler-alist
5897 (delete (rassoc 'tramp-file-name-handler
5898 file-name-handler-alist)
5899 (delete (rassoc 'tramp-completion-file-name-handler
5900 file-name-handler-alist)
5901 file-name-handler-alist))))
5903 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5905 ;;; File name handler functions for completion mode:
5907 (defvar tramp-completion-mode nil
5908 "If non-nil, external packages signal that they are in file name completion.
5910 This is necessary, because Tramp uses a heuristic depending on last
5911 input event. This fails when external packages use other characters
5912 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5913 should never be set globally, the intention is to let-bind it.")
5915 ;; Necessary because `tramp-file-name-regexp-unified' and
5916 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5917 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5918 ;; to `tramp-file-name-handler'). Otherwise, it takes
5919 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5920 ;; risky, because completing a file might require loading other files,
5921 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5922 ;; variable. On the other hand, those files shouldn't have partial
5923 ;; Tramp file name syntax. Maybe another variable should be introduced
5924 ;; overwriting this check in such cases. Or we change Tramp file name
5925 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5926 ;;;###tramp-autoload
5927 (defun tramp-completion-mode-p ()
5928 "Check, whether method / user name / host name completion is active."
5930 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5931 (and (boundp 'non-essential) (symbol-value 'non-essential))
5932 tramp-completion-mode
5933 ;; Emacs.
5934 (equal last-input-event 'tab)
5935 (and (natnump last-input-event)
5937 ;; ?\t has event-modifier 'control.
5938 (equal last-input-event ?\t)
5939 (and (not (event-modifiers last-input-event))
5940 (or (equal last-input-event ?\?)
5941 (equal last-input-event ?\ )))))
5942 ;; XEmacs.
5943 (and (featurep 'xemacs)
5944 ;; `last-input-event' might be nil.
5945 (not (null last-input-event))
5946 ;; `last-input-event' may have no character approximation.
5947 (tramp-compat-funcall 'event-to-character last-input-event)
5949 ;; ?\t has event-modifier 'control.
5950 (equal
5951 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
5952 (and (not (event-modifiers last-input-event))
5953 (or (equal
5954 (tramp-compat-funcall 'event-to-character last-input-event)
5955 ?\?)
5956 (equal
5957 (tramp-compat-funcall 'event-to-character last-input-event)
5958 ?\ )))))))
5960 (defun tramp-connectable-p (filename)
5961 "Check, whether it is possible to connect the remote host w/o side-effects.
5962 This is true, if either the remote host is already connected, or if we are
5963 not in completion mode."
5964 (and (tramp-tramp-file-p filename)
5965 (with-parsed-tramp-file-name filename nil
5966 (or (get-buffer (tramp-buffer-name v))
5967 (not (tramp-completion-mode-p))))))
5969 ;; Method, host name and user name completion.
5970 ;; `tramp-completion-dissect-file-name' returns a list of
5971 ;; tramp-file-name structures. For all of them we return possible completions.
5972 ;;;###autoload
5973 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5974 "Like `file-name-all-completions' for partial Tramp files."
5976 (let* ((fullname (tramp-drop-volume-letter
5977 (expand-file-name filename directory)))
5978 ;; Possible completion structures.
5979 (v (tramp-completion-dissect-file-name fullname))
5980 result result1)
5982 (while v
5983 (let* ((car (car v))
5984 (method (tramp-file-name-method car))
5985 (user (tramp-file-name-user car))
5986 (host (tramp-file-name-host car))
5987 (localname (tramp-file-name-localname car))
5988 (m (tramp-find-method method user host))
5989 (tramp-current-user user) ; see `tramp-parse-passwd'
5990 all-user-hosts)
5992 (unless localname ;; Nothing to complete.
5994 (if (or user host)
5996 ;; Method dependent user / host combinations.
5997 (progn
5998 (mapc
5999 (lambda (x)
6000 (setq all-user-hosts
6001 (append all-user-hosts
6002 (funcall (nth 0 x) (nth 1 x)))))
6003 (tramp-get-completion-function m))
6005 (setq result
6006 (append result
6007 (mapcar
6008 (lambda (x)
6009 (tramp-get-completion-user-host
6010 method user host (nth 0 x) (nth 1 x)))
6011 (delq nil all-user-hosts)))))
6013 ;; Possible methods.
6014 (setq result
6015 (append result (tramp-get-completion-methods m)))))
6017 (setq v (cdr v))))
6019 ;; Unify list, remove nil elements.
6020 (while result
6021 (let ((car (car result)))
6022 (when car
6023 (add-to-list
6024 'result1
6025 (substring car (length (tramp-drop-volume-letter directory)))))
6026 (setq result (cdr result))))
6028 ;; Complete local parts.
6029 (append
6030 result1
6031 (condition-case nil
6032 (apply (if (tramp-connectable-p fullname)
6033 'tramp-completion-run-real-handler
6034 'tramp-run-real-handler)
6035 'file-name-all-completions (list (list filename directory)))
6036 (error nil)))))
6038 ;; Method, host name and user name completion for a file.
6039 ;;;###autoload
6040 (defun tramp-completion-handle-file-name-completion
6041 (filename directory &optional predicate)
6042 "Like `file-name-completion' for Tramp files."
6043 (try-completion
6044 filename
6045 (mapcar 'list (file-name-all-completions filename directory))
6046 (when (and predicate
6047 (tramp-connectable-p (expand-file-name filename directory)))
6048 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
6050 ;; I misuse a little bit the tramp-file-name structure in order to handle
6051 ;; completion possibilities for partial methods / user names / host names.
6052 ;; Return value is a list of tramp-file-name structures according to possible
6053 ;; completions. If "localname" is non-nil it means there
6054 ;; shouldn't be a completion anymore.
6056 ;; Expected results:
6058 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
6059 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
6060 ;; [nil "x" nil nil]
6061 ;; ["x" nil nil nil]
6063 ;; "/x:" "/x:y" "/x:y:"
6064 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
6065 ;; "/[x/" "/[x/y"
6066 ;; ["x" nil "" nil] ["x" nil "y" nil]
6067 ;; ["x" "" nil nil] ["x" "y" nil nil]
6069 ;; "/x:y@" "/x:y@z" "/x:y@z:"
6070 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
6071 ;; "/[x/y@" "/[x/y@z"
6072 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
6073 (defun tramp-completion-dissect-file-name (name)
6074 "Returns a list of `tramp-file-name' structures.
6075 They are collected by `tramp-completion-dissect-file-name1'."
6077 (let* ((result)
6078 (x-nil "\\|\\(\\)")
6079 (tramp-completion-ipv6-regexp
6080 (format
6081 "[^%s]*"
6082 (if (zerop (length tramp-postfix-ipv6-format))
6083 tramp-postfix-host-format
6084 tramp-postfix-ipv6-format)))
6085 ;; "/method" "/[method"
6086 (tramp-completion-file-name-structure1
6087 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
6088 1 nil nil nil))
6089 ;; "/user" "/[user"
6090 (tramp-completion-file-name-structure2
6091 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
6092 nil 1 nil nil))
6093 ;; "/host" "/[host"
6094 (tramp-completion-file-name-structure3
6095 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
6096 nil nil 1 nil))
6097 ;; "/[ipv6" "/[ipv6"
6098 (tramp-completion-file-name-structure4
6099 (list (concat tramp-prefix-regexp
6100 tramp-prefix-ipv6-regexp
6101 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6102 nil nil 1 nil))
6103 ;; "/user@host" "/[user@host"
6104 (tramp-completion-file-name-structure5
6105 (list (concat tramp-prefix-regexp
6106 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6107 "\\(" tramp-host-regexp x-nil "\\)$")
6108 nil 1 2 nil))
6109 ;; "/user@[ipv6" "/[user@ipv6"
6110 (tramp-completion-file-name-structure6
6111 (list (concat tramp-prefix-regexp
6112 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6113 tramp-prefix-ipv6-regexp
6114 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6115 nil 1 2 nil))
6116 ;; "/method:user" "/[method/user" "/method://user"
6117 (tramp-completion-file-name-structure7
6118 (list (concat tramp-prefix-regexp
6119 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6120 "\\(" tramp-user-regexp x-nil "\\)$")
6121 1 2 nil nil))
6122 ;; "/method:host" "/[method/host" "/method://host"
6123 (tramp-completion-file-name-structure8
6124 (list (concat tramp-prefix-regexp
6125 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6126 "\\(" tramp-host-regexp x-nil "\\)$")
6127 1 nil 2 nil))
6128 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
6129 (tramp-completion-file-name-structure9
6130 (list (concat tramp-prefix-regexp
6131 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6132 tramp-prefix-ipv6-regexp
6133 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6134 1 nil 2 nil))
6135 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
6136 (tramp-completion-file-name-structure10
6137 (list (concat tramp-prefix-regexp
6138 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6139 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6140 "\\(" tramp-host-regexp x-nil "\\)$")
6141 1 2 3 nil))
6142 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
6143 (tramp-completion-file-name-structure11
6144 (list (concat tramp-prefix-regexp
6145 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6146 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6147 tramp-prefix-ipv6-regexp
6148 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6149 1 2 3 nil))
6150 ;; "/method: "/method:/"
6151 (tramp-completion-file-name-structure12
6152 (list
6153 (if (equal tramp-syntax 'url)
6154 (concat tramp-prefix-regexp
6155 "\\(" tramp-method-regexp "\\)"
6156 "\\(" (substring tramp-postfix-method-regexp 0 1)
6157 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6158 "\\(" "\\)$")
6159 ;; Should not match if not URL syntax.
6160 (concat tramp-prefix-regexp "/$"))
6161 1 3 nil nil))
6162 ;; "/method: "/method:/"
6163 (tramp-completion-file-name-structure13
6164 (list
6165 (if (equal tramp-syntax 'url)
6166 (concat tramp-prefix-regexp
6167 "\\(" tramp-method-regexp "\\)"
6168 "\\(" (substring tramp-postfix-method-regexp 0 1)
6169 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6170 "\\(" "\\)$")
6171 ;; Should not match if not URL syntax.
6172 (concat tramp-prefix-regexp "/$"))
6173 1 nil 3 nil)))
6175 (mapc (lambda (regexp)
6176 (add-to-list 'result
6177 (tramp-completion-dissect-file-name1 regexp name)))
6178 (list
6179 tramp-completion-file-name-structure1
6180 tramp-completion-file-name-structure2
6181 tramp-completion-file-name-structure3
6182 tramp-completion-file-name-structure4
6183 tramp-completion-file-name-structure5
6184 tramp-completion-file-name-structure6
6185 tramp-completion-file-name-structure7
6186 tramp-completion-file-name-structure8
6187 tramp-completion-file-name-structure9
6188 tramp-completion-file-name-structure10
6189 tramp-completion-file-name-structure11
6190 tramp-completion-file-name-structure12
6191 tramp-completion-file-name-structure13
6192 tramp-file-name-structure))
6194 (delq nil result)))
6196 (defun tramp-completion-dissect-file-name1 (structure name)
6197 "Returns a `tramp-file-name' structure matching STRUCTURE.
6198 The structure consists of remote method, remote user,
6199 remote host and localname (filename on remote host)."
6201 (save-match-data
6202 (when (string-match (nth 0 structure) name)
6203 (let ((method (and (nth 1 structure)
6204 (match-string (nth 1 structure) name)))
6205 (user (and (nth 2 structure)
6206 (match-string (nth 2 structure) name)))
6207 (host (and (nth 3 structure)
6208 (match-string (nth 3 structure) name)))
6209 (localname (and (nth 4 structure)
6210 (match-string (nth 4 structure) name))))
6211 (vector method user host localname)))))
6213 ;; This function returns all possible method completions, adding the
6214 ;; trailing method delimeter.
6215 (defun tramp-get-completion-methods (partial-method)
6216 "Returns all method completions for PARTIAL-METHOD."
6217 (mapcar
6218 (lambda (method)
6219 (and method
6220 (string-match (concat "^" (regexp-quote partial-method)) method)
6221 (tramp-completion-make-tramp-file-name method nil nil nil)))
6222 (mapcar 'car tramp-methods)))
6224 ;; Compares partial user and host names with possible completions.
6225 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
6226 "Returns the most expanded string for user and host name completion.
6227 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
6228 (cond
6230 ((and partial-user partial-host)
6231 (if (and host
6232 (string-match (concat "^" (regexp-quote partial-host)) host)
6233 (string-equal partial-user (or user partial-user)))
6234 (setq user partial-user)
6235 (setq user nil
6236 host nil)))
6238 (partial-user
6239 (setq host nil)
6240 (unless
6241 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
6242 (setq user nil)))
6244 (partial-host
6245 (setq user nil)
6246 (unless
6247 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
6248 (setq host nil)))
6250 (t (setq user nil
6251 host nil)))
6253 (unless (zerop (+ (length user) (length host)))
6254 (tramp-completion-make-tramp-file-name method user host nil)))
6256 (defun tramp-parse-rhosts (filename)
6257 "Return a list of (user host) tuples allowed to access.
6258 Either user or host may be nil."
6259 ;; On Windows, there are problems in completion when
6260 ;; `default-directory' is remote.
6261 (let ((default-directory (tramp-compat-temporary-file-directory))
6262 res)
6263 (when (file-readable-p filename)
6264 (with-temp-buffer
6265 (insert-file-contents filename)
6266 (goto-char (point-min))
6267 (while (not (eobp))
6268 (push (tramp-parse-rhosts-group) res))))
6269 res))
6271 (defun tramp-parse-rhosts-group ()
6272 "Return a (user host) tuple allowed to access.
6273 Either user or host may be nil."
6274 (let ((result)
6275 (regexp
6276 (concat
6277 "^\\(" tramp-host-regexp "\\)"
6278 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6279 (narrow-to-region (point) (tramp-compat-line-end-position))
6280 (when (re-search-forward regexp nil t)
6281 (setq result (append (list (match-string 3) (match-string 1)))))
6282 (widen)
6283 (forward-line 1)
6284 result))
6286 (defun tramp-parse-shosts (filename)
6287 "Return a list of (user host) tuples allowed to access.
6288 User is always nil."
6289 ;; On Windows, there are problems in completion when
6290 ;; `default-directory' is remote.
6291 (let ((default-directory (tramp-compat-temporary-file-directory))
6292 res)
6293 (when (file-readable-p filename)
6294 (with-temp-buffer
6295 (insert-file-contents filename)
6296 (goto-char (point-min))
6297 (while (not (eobp))
6298 (push (tramp-parse-shosts-group) res))))
6299 res))
6301 (defun tramp-parse-shosts-group ()
6302 "Return a (user host) tuple allowed to access.
6303 User is always nil."
6304 (let ((result)
6305 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
6306 (narrow-to-region (point) (tramp-compat-line-end-position))
6307 (when (re-search-forward regexp nil t)
6308 (setq result (list nil (match-string 1))))
6309 (widen)
6311 (> (skip-chars-forward ",") 0)
6312 (forward-line 1))
6313 result))
6315 (defun tramp-parse-sconfig (filename)
6316 "Return a list of (user host) tuples allowed to access.
6317 User is always nil."
6318 ;; On Windows, there are problems in completion when
6319 ;; `default-directory' is remote.
6320 (let ((default-directory (tramp-compat-temporary-file-directory))
6321 res)
6322 (when (file-readable-p filename)
6323 (with-temp-buffer
6324 (insert-file-contents filename)
6325 (goto-char (point-min))
6326 (while (not (eobp))
6327 (push (tramp-parse-sconfig-group) res))))
6328 res))
6330 (defun tramp-parse-sconfig-group ()
6331 "Return a (user host) tuple allowed to access.
6332 User is always nil."
6333 (let ((result)
6334 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
6335 (narrow-to-region (point) (tramp-compat-line-end-position))
6336 (when (re-search-forward regexp nil t)
6337 (setq result (list nil (match-string 1))))
6338 (widen)
6340 (> (skip-chars-forward ",") 0)
6341 (forward-line 1))
6342 result))
6344 (defun tramp-parse-shostkeys (dirname)
6345 "Return a list of (user host) tuples allowed to access.
6346 User is always nil."
6347 ;; On Windows, there are problems in completion when
6348 ;; `default-directory' is remote.
6349 (let* ((default-directory (tramp-compat-temporary-file-directory))
6350 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6351 (files (when (file-directory-p dirname) (directory-files dirname)))
6352 result)
6353 (while files
6354 (when (string-match regexp (car files))
6355 (push (list nil (match-string 1 (car files))) result))
6356 (setq files (cdr files)))
6357 result))
6359 (defun tramp-parse-sknownhosts (dirname)
6360 "Return a list of (user host) tuples allowed to access.
6361 User is always nil."
6362 ;; On Windows, there are problems in completion when
6363 ;; `default-directory' is remote.
6364 (let* ((default-directory (tramp-compat-temporary-file-directory))
6365 (regexp (concat "^\\(" tramp-host-regexp
6366 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6367 (files (when (file-directory-p dirname) (directory-files dirname)))
6368 result)
6369 (while files
6370 (when (string-match regexp (car files))
6371 (push (list nil (match-string 1 (car files))) result))
6372 (setq files (cdr files)))
6373 result))
6375 (defun tramp-parse-hosts (filename)
6376 "Return a list of (user host) tuples allowed to access.
6377 User is always nil."
6378 ;; On Windows, there are problems in completion when
6379 ;; `default-directory' is remote.
6380 (let ((default-directory (tramp-compat-temporary-file-directory))
6381 res)
6382 (when (file-readable-p filename)
6383 (with-temp-buffer
6384 (insert-file-contents filename)
6385 (goto-char (point-min))
6386 (while (not (eobp))
6387 (push (tramp-parse-hosts-group) res))))
6388 res))
6390 (defun tramp-parse-hosts-group ()
6391 "Return a (user host) tuple allowed to access.
6392 User is always nil."
6393 (let ((result)
6394 (regexp
6395 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6396 (narrow-to-region (point) (tramp-compat-line-end-position))
6397 (when (re-search-forward regexp nil t)
6398 (setq result (list nil (match-string 1))))
6399 (widen)
6401 (> (skip-chars-forward " \t") 0)
6402 (forward-line 1))
6403 result))
6405 ;; For su-alike methods it would be desirable to return "root@localhost"
6406 ;; as default. Unfortunately, we have no information whether any user name
6407 ;; has been typed already. So we use `tramp-current-user' as indication,
6408 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6409 (defun tramp-parse-passwd (filename)
6410 "Return a list of (user host) tuples allowed to access.
6411 Host is always \"localhost\"."
6412 ;; On Windows, there are problems in completion when
6413 ;; `default-directory' is remote.
6414 (let ((default-directory (tramp-compat-temporary-file-directory))
6415 res)
6416 (if (zerop (length tramp-current-user))
6417 '(("root" nil))
6418 (when (file-readable-p filename)
6419 (with-temp-buffer
6420 (insert-file-contents filename)
6421 (goto-char (point-min))
6422 (while (not (eobp))
6423 (push (tramp-parse-passwd-group) res))))
6424 res)))
6426 (defun tramp-parse-passwd-group ()
6427 "Return a (user host) tuple allowed to access.
6428 Host is always \"localhost\"."
6429 (let ((result)
6430 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6431 (narrow-to-region (point) (tramp-compat-line-end-position))
6432 (when (re-search-forward regexp nil t)
6433 (setq result (list (match-string 1) "localhost")))
6434 (widen)
6435 (forward-line 1)
6436 result))
6438 (defun tramp-parse-netrc (filename)
6439 "Return a list of (user host) tuples allowed to access.
6440 User may be nil."
6441 ;; On Windows, there are problems in completion when
6442 ;; `default-directory' is remote.
6443 (let ((default-directory (tramp-compat-temporary-file-directory))
6444 res)
6445 (when (file-readable-p filename)
6446 (with-temp-buffer
6447 (insert-file-contents filename)
6448 (goto-char (point-min))
6449 (while (not (eobp))
6450 (push (tramp-parse-netrc-group) res))))
6451 res))
6453 (defun tramp-parse-netrc-group ()
6454 "Return a (user host) tuple allowed to access.
6455 User may be nil."
6456 (let ((result)
6457 (regexp
6458 (concat
6459 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6460 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6461 (narrow-to-region (point) (tramp-compat-line-end-position))
6462 (when (re-search-forward regexp nil t)
6463 (setq result (list (match-string 3) (match-string 1))))
6464 (widen)
6465 (forward-line 1)
6466 result))
6468 (defun tramp-parse-putty (registry)
6469 "Return a list of (user host) tuples allowed to access.
6470 User is always nil."
6471 ;; On Windows, there are problems in completion when
6472 ;; `default-directory' is remote.
6473 (let ((default-directory (tramp-compat-temporary-file-directory))
6474 res)
6475 (with-temp-buffer
6476 (when (zerop (tramp-compat-call-process "reg" nil t nil "query" registry))
6477 (goto-char (point-min))
6478 (while (not (eobp))
6479 (push (tramp-parse-putty-group registry) res))))
6480 res))
6482 (defun tramp-parse-putty-group (registry)
6483 "Return a (user host) tuple allowed to access.
6484 User is always nil."
6485 (let ((result)
6486 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6487 (narrow-to-region (point) (tramp-compat-line-end-position))
6488 (when (re-search-forward regexp nil t)
6489 (setq result (list nil (match-string 1))))
6490 (widen)
6491 (forward-line 1)
6492 result))
6494 ;;; Internal Functions:
6496 (defun tramp-maybe-send-script (vec script name)
6497 "Define in remote shell function NAME implemented as SCRIPT.
6498 Only send the definition if it has not already been done."
6499 (let* ((p (tramp-get-connection-process vec))
6500 (scripts (tramp-get-connection-property p "scripts" nil)))
6501 (unless (member name scripts)
6502 (with-progress-reporter vec 5 (format "Sending script `%s'" name)
6503 ;; The script could contain a call of Perl. This is masked with `%s'.
6504 (tramp-send-command-and-check
6506 (format "%s () {\n%s\n}" name
6507 (format script (tramp-get-remote-perl vec))))
6508 (tramp-set-connection-property p "scripts" (cons name scripts))))))
6510 (defun tramp-set-auto-save ()
6511 (when (and ;; ange-ftp has its own auto-save mechanism
6512 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6513 'tramp-sh-file-name-handler)
6514 auto-save-default)
6515 (auto-save-mode 1)))
6516 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6517 (add-hook 'tramp-unload-hook
6518 (lambda ()
6519 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6521 (defun tramp-run-test (switch filename)
6522 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6523 Returns the exit code of the `test' program."
6524 (with-parsed-tramp-file-name filename nil
6525 (tramp-send-command-and-check
6527 (format
6528 "%s %s %s"
6529 (tramp-get-test-command v)
6530 switch
6531 (tramp-shell-quote-argument localname)))))
6533 (defun tramp-run-test2 (format-string file1 file2)
6534 "Run `test'-like program on the remote system, given FILE1, FILE2.
6535 FORMAT-STRING contains the program name, switches, and place holders.
6536 Returns the exit code of the `test' program. Barfs if the methods,
6537 hosts, or files, disagree."
6538 (unless (tramp-equal-remote file1 file2)
6539 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6540 (tramp-error
6541 v 'file-error
6542 "tramp-run-test2 only implemented for same method, user, host")))
6543 (with-parsed-tramp-file-name file1 v1
6544 (with-parsed-tramp-file-name file1 v2
6545 (tramp-send-command-and-check
6547 (format format-string
6548 (tramp-shell-quote-argument v1-localname)
6549 (tramp-shell-quote-argument v2-localname))))))
6551 (defun tramp-delete-temp-file-function ()
6552 "Remove temporary files related to current buffer."
6553 (when (stringp tramp-temp-buffer-file-name)
6554 (condition-case nil
6555 (delete-file tramp-temp-buffer-file-name)
6556 (error nil))))
6558 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6559 (add-hook 'tramp-cache-unload-hook
6560 (lambda ()
6561 (remove-hook 'kill-buffer-hook
6562 'tramp-delete-temp-file-function)))
6564 (defun tramp-find-executable
6565 (vec progname dirlist &optional ignore-tilde ignore-path)
6566 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6567 First arg VEC specifies the connection, PROGNAME is the program
6568 to search for, and DIRLIST gives the list of directories to
6569 search. If IGNORE-TILDE is non-nil, directory names starting
6570 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6571 only in DIRLIST.
6573 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6575 This function expects to be in the right *tramp* buffer."
6576 (with-current-buffer (tramp-get-connection-buffer vec)
6577 (let (result)
6578 ;; Check whether the executable is in $PATH. "which(1)" does not
6579 ;; report always a correct error code; therefore we check the
6580 ;; number of words it returns.
6581 (unless ignore-path
6582 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6583 (goto-char (point-min))
6584 (if (looking-at "^\\s-*1$")
6585 (setq result (concat "\\" progname))))
6586 (unless result
6587 (when ignore-tilde
6588 ;; Remove all ~/foo directories from dirlist. In XEmacs,
6589 ;; `remove' is in CL, and we want to avoid CL dependencies.
6590 (let (newdl d)
6591 (while dirlist
6592 (setq d (car dirlist))
6593 (setq dirlist (cdr dirlist))
6594 (unless (char-equal ?~ (aref d 0))
6595 (setq newdl (cons d newdl))))
6596 (setq dirlist (nreverse newdl))))
6597 (tramp-send-command
6599 (format (concat "while read d; "
6600 "do if test -x $d/%s -a -f $d/%s; "
6601 "then echo tramp_executable $d/%s; "
6602 "break; fi; done <<'EOF'\n"
6603 "%s\nEOF")
6604 progname progname progname (mapconcat 'identity dirlist "\n")))
6605 (goto-char (point-max))
6606 (when (search-backward "tramp_executable " nil t)
6607 (skip-chars-forward "^ ")
6608 (skip-chars-forward " ")
6609 (setq result (buffer-substring
6610 (point) (tramp-compat-line-end-position)))))
6611 result)))
6613 (defun tramp-set-remote-path (vec)
6614 "Sets the remote environment PATH to existing directories.
6615 I.e., for each directory in `tramp-remote-path', it is tested
6616 whether it exists and if so, it is added to the environment
6617 variable PATH."
6618 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6619 (tramp-send-command
6620 vec (format "PATH=%s; export PATH"
6621 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6623 ;; ------------------------------------------------------------
6624 ;; -- Communication with external shell --
6625 ;; ------------------------------------------------------------
6627 (defun tramp-find-file-exists-command (vec)
6628 "Find a command on the remote host for checking if a file exists.
6629 Here, we are looking for a command which has zero exit status if the
6630 file exists and nonzero exit status otherwise."
6631 (let ((existing "/")
6632 (nonexisting
6633 (tramp-shell-quote-argument "/ this file does not exist "))
6634 result)
6635 ;; The algorithm is as follows: we try a list of several commands.
6636 ;; For each command, we first run `$cmd /' -- this should return
6637 ;; true, as the root directory always exists. And then we run
6638 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6639 ;; does not exist. This should return false. We use the first
6640 ;; command we find that seems to work.
6641 ;; The list of commands to try is as follows:
6642 ;; `ls -d' This works on most systems, but NetBSD 1.4
6643 ;; has a bug: `ls' always returns zero exit
6644 ;; status, even for files which don't exist.
6645 ;; `test -e' Some Bourne shells have a `test' builtin
6646 ;; which does not know the `-e' option.
6647 ;; `/bin/test -e' For those, the `test' binary on disk normally
6648 ;; provides the option. Alas, the binary
6649 ;; is sometimes `/bin/test' and sometimes it's
6650 ;; `/usr/bin/test'.
6651 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6652 (unless (or
6653 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6654 (zerop (tramp-send-command-and-check
6655 vec (format "%s %s" result existing)))
6656 (not (zerop (tramp-send-command-and-check
6657 vec (format "%s %s" result nonexisting)))))
6658 (and (setq result "/bin/test -e")
6659 (zerop (tramp-send-command-and-check
6660 vec (format "%s %s" result existing)))
6661 (not (zerop (tramp-send-command-and-check
6662 vec (format "%s %s" result nonexisting)))))
6663 (and (setq result "/usr/bin/test -e")
6664 (zerop (tramp-send-command-and-check
6665 vec (format "%s %s" result existing)))
6666 (not (zerop (tramp-send-command-and-check
6667 vec (format "%s %s" result nonexisting)))))
6668 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6669 (zerop (tramp-send-command-and-check
6670 vec (format "%s %s" result existing)))
6671 (not (zerop (tramp-send-command-and-check
6672 vec (format "%s %s" result nonexisting))))))
6673 (tramp-error
6674 vec 'file-error "Couldn't find command to check if file exists"))
6675 result))
6677 (defun tramp-open-shell (vec shell)
6678 "Opens shell SHELL."
6679 (with-progress-reporter vec 5 (format "Opening remote shell `%s'" shell)
6680 ;; Find arguments for this shell.
6681 (let ((tramp-end-of-output tramp-initial-end-of-output)
6682 (alist tramp-sh-extra-args)
6683 item extra-args)
6684 (while (and alist (null extra-args))
6685 (setq item (pop alist))
6686 (when (string-match (car item) shell)
6687 (setq extra-args (cdr item))))
6688 (when extra-args (setq shell (concat shell " " extra-args)))
6689 (tramp-send-command
6690 vec (format "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6691 (shell-quote-argument tramp-end-of-output) shell)
6693 ;; Setting prompts.
6694 (tramp-send-command
6695 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6696 (tramp-send-command vec "PS2=''" t)
6697 (tramp-send-command vec "PS3=''" t)
6698 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
6700 (defun tramp-find-shell (vec)
6701 "Opens a shell on the remote host which groks tilde expansion."
6702 (unless (tramp-get-connection-property vec "remote-shell" nil)
6703 (let (shell)
6704 (with-current-buffer (tramp-get-buffer vec)
6705 (tramp-send-command vec "echo ~root" t)
6706 (cond
6707 ((or (string-match "^~root$" (buffer-string))
6708 ;; The default shell (ksh93) of OpenSolaris is buggy.
6709 (string-equal (tramp-get-connection-property vec "uname" "")
6710 "SunOS 5.11"))
6711 (setq shell
6712 (or (tramp-find-executable
6713 vec "bash" (tramp-get-remote-path vec) t t)
6714 (tramp-find-executable
6715 vec "ksh" (tramp-get-remote-path vec) t t)))
6716 (unless shell
6717 (tramp-error
6718 vec 'file-error
6719 "Couldn't find a shell which groks tilde expansion"))
6720 (tramp-message
6721 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
6722 (tramp-open-shell vec shell))
6724 (t (tramp-message
6725 vec 5 "Remote `%s' groks tilde expansion, good"
6726 (tramp-set-connection-property
6727 vec "remote-shell"
6728 (tramp-get-method-parameter
6729 (tramp-file-name-method vec) 'tramp-remote-sh)))))))))
6731 ;; ------------------------------------------------------------
6732 ;; -- Functions for establishing connection --
6733 ;; ------------------------------------------------------------
6735 ;; The following functions are actions to be taken when seeing certain
6736 ;; prompts from the remote host. See the variable
6737 ;; `tramp-actions-before-shell' for usage of these functions.
6739 (defun tramp-action-login (proc vec)
6740 "Send the login name."
6741 (when (not (stringp tramp-current-user))
6742 (save-window-excursion
6743 (let ((enable-recursive-minibuffers t))
6744 (pop-to-buffer (tramp-get-connection-buffer vec))
6745 (setq tramp-current-user (read-string (match-string 0))))))
6746 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6747 (with-current-buffer (tramp-get-connection-buffer vec)
6748 (tramp-message vec 6 "\n%s" (buffer-string)))
6749 (tramp-send-string vec tramp-current-user))
6751 (defun tramp-action-password (proc vec)
6752 "Query the user for a password."
6753 (with-current-buffer (process-buffer proc)
6754 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6755 (tramp-message vec 3 "Sending %s" (match-string 1))
6756 (tramp-enter-password proc)
6757 ;; Hide password prompt.
6758 (narrow-to-region (point-max) (point-max))))
6760 (defun tramp-action-succeed (proc vec)
6761 "Signal success in finding shell prompt."
6762 (throw 'tramp-action 'ok))
6764 (defun tramp-action-permission-denied (proc vec)
6765 "Signal permission denied."
6766 (kill-process proc)
6767 (throw 'tramp-action 'permission-denied))
6769 (defun tramp-action-yesno (proc vec)
6770 "Ask the user for confirmation using `yes-or-no-p'.
6771 Send \"yes\" to remote process on confirmation, abort otherwise.
6772 See also `tramp-action-yn'."
6773 (save-window-excursion
6774 (let ((enable-recursive-minibuffers t))
6775 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6776 (unless (yes-or-no-p (match-string 0))
6777 (kill-process proc)
6778 (throw 'tramp-action 'permission-denied))
6779 (with-current-buffer (tramp-get-connection-buffer vec)
6780 (tramp-message vec 6 "\n%s" (buffer-string)))
6781 (tramp-send-string vec "yes"))))
6783 (defun tramp-action-yn (proc vec)
6784 "Ask the user for confirmation using `y-or-n-p'.
6785 Send \"y\" to remote process on confirmation, abort otherwise.
6786 See also `tramp-action-yesno'."
6787 (save-window-excursion
6788 (let ((enable-recursive-minibuffers t))
6789 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6790 (unless (y-or-n-p (match-string 0))
6791 (kill-process proc)
6792 (throw 'tramp-action 'permission-denied))
6793 (with-current-buffer (tramp-get-connection-buffer vec)
6794 (tramp-message vec 6 "\n%s" (buffer-string)))
6795 (tramp-send-string vec "y"))))
6797 (defun tramp-action-terminal (proc vec)
6798 "Tell the remote host which terminal type to use.
6799 The terminal type can be configured with `tramp-terminal-type'."
6800 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6801 (with-current-buffer (tramp-get-connection-buffer vec)
6802 (tramp-message vec 6 "\n%s" (buffer-string)))
6803 (tramp-send-string vec tramp-terminal-type))
6805 (defun tramp-action-process-alive (proc vec)
6806 "Check, whether a process has finished."
6807 (unless (memq (process-status proc) '(run open))
6808 (throw 'tramp-action 'process-died)))
6810 (defun tramp-action-out-of-band (proc vec)
6811 "Check, whether an out-of-band copy has finished."
6812 (cond ((and (memq (process-status proc) '(stop exit))
6813 (zerop (process-exit-status proc)))
6814 (tramp-message vec 3 "Process has finished.")
6815 (throw 'tramp-action 'ok))
6816 ((or (and (memq (process-status proc) '(stop exit))
6817 (not (zerop (process-exit-status proc))))
6818 (memq (process-status proc) '(signal)))
6819 ;; `scp' could have copied correctly, but set modes could have failed.
6820 ;; This can be ignored.
6821 (with-current-buffer (process-buffer proc)
6822 (goto-char (point-min))
6823 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6824 (progn
6825 (tramp-message vec 5 "'set mode' error ignored.")
6826 (tramp-message vec 3 "Process has finished.")
6827 (throw 'tramp-action 'ok))
6828 (tramp-message vec 3 "Process has died.")
6829 (throw 'tramp-action 'process-died))))
6830 (t nil)))
6832 ;; Functions for processing the actions.
6834 (defun tramp-process-one-action (proc vec actions)
6835 "Wait for output from the shell and perform one action."
6836 (let (found todo item pattern action)
6837 (while (not found)
6838 ;; Reread output once all actions have been performed.
6839 ;; Obviously, the output was not complete.
6840 (tramp-accept-process-output proc 1)
6841 (setq todo actions)
6842 (while todo
6843 (setq item (pop todo))
6844 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6845 (setq action (nth 1 item))
6846 (tramp-message
6847 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6848 (when (tramp-check-for-regexp proc pattern)
6849 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6850 (setq found (funcall action proc vec)))))
6851 found))
6853 (defun tramp-process-actions (proc vec actions &optional timeout)
6854 "Perform actions until success or TIMEOUT."
6855 ;; Preserve message for `progress-reporter'.
6856 (with-temp-message ""
6857 ;; Enable auth-source and password-cache.
6858 (tramp-set-connection-property vec "first-password-request" t)
6859 (let (exit)
6860 (while (not exit)
6861 (tramp-message proc 3 "Waiting for prompts from remote shell")
6862 (setq exit
6863 (catch 'tramp-action
6864 (if timeout
6865 (with-timeout (timeout)
6866 (tramp-process-one-action proc vec actions))
6867 (tramp-process-one-action proc vec actions)))))
6868 (with-current-buffer (tramp-get-connection-buffer vec)
6869 (widen)
6870 (tramp-message vec 6 "\n%s" (buffer-string)))
6871 (unless (eq exit 'ok)
6872 (tramp-clear-passwd vec)
6873 (tramp-error-with-buffer
6874 nil vec 'file-error
6875 (cond
6876 ((eq exit 'permission-denied) "Permission denied")
6877 ((eq exit 'process-died) "Process died")
6878 (t "Login failed")))))))
6880 ;; Utility functions.
6882 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6883 "Like `accept-process-output' for Tramp processes.
6884 This is needed in order to hide `last-coding-system-used', which is set
6885 for process communication also."
6886 (with-current-buffer (process-buffer proc)
6887 (tramp-message proc 10 "%s %s" proc (process-status proc))
6888 (let (buffer-read-only last-coding-system-used)
6889 ;; Under Windows XP, accept-process-output doesn't return
6890 ;; sometimes. So we add an additional timeout.
6891 (with-timeout ((or timeout 1))
6892 (accept-process-output proc timeout timeout-msecs)))
6893 (tramp-message proc 10 "\n%s" (buffer-string))))
6895 (defun tramp-check-for-regexp (proc regexp)
6896 "Check, whether REGEXP is contained in process buffer of PROC.
6897 Erase echoed commands if exists."
6898 (with-current-buffer (process-buffer proc)
6899 (goto-char (point-min))
6901 ;; Check whether we need to remove echo output.
6902 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6903 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6904 (let ((begin (match-beginning 0)))
6905 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6906 ;; Discard echo from remote output.
6907 (tramp-set-connection-property proc "check-remote-echo" nil)
6908 (tramp-message proc 5 "echo-mark found")
6909 (forward-line 1)
6910 (delete-region begin (point))
6911 (goto-char (point-min)))))
6913 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6914 ;; Sometimes, the echo string is suppressed on the remote side.
6915 (not (string-equal
6916 (tramp-compat-funcall
6917 'substring-no-properties tramp-echo-mark-marker
6918 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6919 (tramp-compat-funcall
6920 'buffer-substring-no-properties
6921 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6922 ;; No echo to be handled, now we can look for the regexp.
6923 (goto-char (point-min))
6924 (re-search-forward regexp nil t))))
6926 (defun tramp-wait-for-regexp (proc timeout regexp)
6927 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6928 Expects the output of PROC to be sent to the current buffer. Returns
6929 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6930 nil."
6931 (with-current-buffer (process-buffer proc)
6932 (let ((found (tramp-check-for-regexp proc regexp))
6933 (start-time (current-time)))
6934 (cond (timeout
6935 ;; Work around a bug in XEmacs 21, where the timeout
6936 ;; expires faster than it should. This degenerates
6937 ;; to polling for buggy XEmacsen, but oh, well.
6938 (while (and (not found)
6939 (< (tramp-time-diff (current-time) start-time)
6940 timeout))
6941 (with-timeout (timeout)
6942 (while (not found)
6943 (tramp-accept-process-output proc 1)
6944 (unless (memq (process-status proc) '(run open))
6945 (tramp-error-with-buffer
6946 nil proc 'file-error "Process has died"))
6947 (setq found (tramp-check-for-regexp proc regexp))))))
6949 (while (not found)
6950 (tramp-accept-process-output proc 1)
6951 (unless (memq (process-status proc) '(run open))
6952 (tramp-error-with-buffer
6953 nil proc 'file-error "Process has died"))
6954 (setq found (tramp-check-for-regexp proc regexp)))))
6955 (tramp-message proc 6 "\n%s" (buffer-string))
6956 (when (not found)
6957 (if timeout
6958 (tramp-error
6959 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6960 regexp timeout)
6961 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6962 found)))
6964 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6965 "Wait for shell prompt and barf if none appears.
6966 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6967 seconds. If not, it produces an error message with the given ERROR-ARGS."
6968 (unless
6969 (tramp-wait-for-regexp
6970 proc timeout
6971 (format
6972 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6973 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6975 ;; We don't call `tramp-send-string' in order to hide the password
6976 ;; from the debug buffer, and because end-of-line handling of the
6977 ;; string.
6978 (defun tramp-enter-password (proc)
6979 "Prompt for a password and send it to the remote end."
6980 (process-send-string
6981 proc (concat (tramp-read-passwd proc)
6982 (or (tramp-get-method-parameter
6983 tramp-current-method
6984 'tramp-password-end-of-line)
6985 tramp-default-password-end-of-line))))
6987 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6988 "Set up an interactive shell.
6989 Mainly sets the prompt and the echo correctly. PROC is the shell
6990 process to set up. VEC specifies the connection."
6991 (let ((tramp-end-of-output tramp-initial-end-of-output))
6992 ;; It is useful to set the prompt in the following command because
6993 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6994 ;; about and thus /bin/sh will display a strange prompt. For
6995 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6996 ;; display the current working directory but /bin/sh will display
6997 ;; a dollar sign. The following command line sets $PS1 to a sane
6998 ;; value, and works under Bourne-ish shells as well as csh-like
6999 ;; shells. Daniel Pittman reports that the unusual positioning of
7000 ;; the single quotes makes it work under `rc', too. We also unset
7001 ;; the variable $ENV because that is read by some sh
7002 ;; implementations (eg, bash when called as sh) on startup; this
7003 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
7004 ;; is another way to set the prompt in /bin/bash, it must be
7005 ;; discarded as well.
7006 (tramp-open-shell
7008 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-remote-sh))
7010 ;; Disable echo.
7011 (tramp-message vec 5 "Setting up remote shell environment")
7012 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
7013 ;; Check whether the echo has really been disabled. Some
7014 ;; implementations, like busybox of embedded GNU/Linux, don't
7015 ;; support disabling.
7016 (tramp-send-command vec "echo foo" t)
7017 (with-current-buffer (process-buffer proc)
7018 (goto-char (point-min))
7019 (when (looking-at "echo foo")
7020 (tramp-set-connection-property proc "remote-echo" t)
7021 (tramp-message vec 5 "Remote echo still on. Ok.")
7022 ;; Make sure backspaces and their echo are enabled and no line
7023 ;; width magic interferes with them.
7024 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
7026 (tramp-message vec 5 "Setting shell prompt")
7027 (tramp-send-command
7028 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
7029 (tramp-send-command vec "PS2=''" t)
7030 (tramp-send-command vec "PS3=''" t)
7031 (tramp-send-command vec "PROMPT_COMMAND=''" t)
7033 ;; Try to set up the coding system correctly.
7034 ;; CCC this can't be the right way to do it. Hm.
7035 (tramp-message vec 5 "Determining coding system")
7036 (tramp-send-command vec "echo foo ; echo bar" t)
7037 (with-current-buffer (process-buffer proc)
7038 (goto-char (point-min))
7039 (if (featurep 'mule)
7040 ;; Use MULE to select the right EOL convention for communicating
7041 ;; with the process.
7042 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
7043 (cons 'undecided 'undecided)))
7044 cs-decode cs-encode)
7045 (when (symbolp cs) (setq cs (cons cs cs)))
7046 (setq cs-decode (car cs))
7047 (setq cs-encode (cdr cs))
7048 (unless cs-decode (setq cs-decode 'undecided))
7049 (unless cs-encode (setq cs-encode 'undecided))
7050 (setq cs-encode (tramp-coding-system-change-eol-conversion
7051 cs-encode 'unix))
7052 (when (search-forward "\r" nil t)
7053 (setq cs-decode (tramp-coding-system-change-eol-conversion
7054 cs-decode 'dos)))
7055 (tramp-compat-funcall
7056 'set-buffer-process-coding-system cs-decode cs-encode)
7057 (tramp-message
7058 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
7059 ;; Look for ^M and do something useful if found.
7060 (when (search-forward "\r" nil t)
7061 ;; We have found a ^M but cannot frob the process coding system
7062 ;; because we're running on a non-MULE Emacs. Let's try
7063 ;; stty, instead.
7064 (tramp-send-command vec "stty -onlcr" t))))
7065 ;; Dump stty settings in the traces.
7066 (when (>= tramp-verbose 9)
7067 (tramp-send-command vec "stty -a" t))
7068 (tramp-send-command vec "set +o vi +o emacs" t)
7070 ;; Check whether the output of "uname -sr" has been changed. If
7071 ;; yes, this is a strong indication that we must expire all
7072 ;; connection properties. We start again with
7073 ;; `tramp-maybe-open-connection', it will be catched there.
7074 (tramp-message vec 5 "Checking system information")
7075 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
7076 (new-uname
7077 (tramp-set-connection-property
7078 vec "uname"
7079 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
7080 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
7081 (with-current-buffer (tramp-get-debug-buffer vec)
7082 ;; Keep the debug buffer.
7083 (rename-buffer
7084 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
7085 (tramp-compat-funcall 'tramp-cleanup-connection vec)
7086 (if (= (point-min) (point-max))
7087 (kill-buffer nil)
7088 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
7089 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
7090 (tramp-get-buffer vec)
7091 (tramp-message
7092 vec 3
7093 "Connection reset, because remote host changed from `%s' to `%s'"
7094 old-uname new-uname)
7095 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
7097 ;; Check whether the remote host suffers from buggy
7098 ;; `send-process-string'. This is known for FreeBSD (see comment in
7099 ;; `send_process', file process.c). I've tested sending 624 bytes
7100 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
7101 ;; this host type is detected locally. It cannot handle remote
7102 ;; hosts, though.
7103 (with-connection-property proc "chunksize"
7104 (cond
7105 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
7106 tramp-chunksize)
7108 (tramp-message
7109 vec 5 "Checking remote host type for `send-process-string' bug")
7110 (if (string-match
7111 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
7112 500 0))))
7114 ;; Set remote PATH variable.
7115 (tramp-set-remote-path vec)
7117 ;; Search for a good shell before searching for a command which
7118 ;; checks if a file exists. This is done because Tramp wants to use
7119 ;; "test foo; echo $?" to check if various conditions hold, and
7120 ;; there are buggy /bin/sh implementations which don't execute the
7121 ;; "echo $?" part if the "test" part has an error. In particular,
7122 ;; the OpenSolaris /bin/sh is a problem. There are also other
7123 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
7124 ;; in function declarations, or changing HISTFILE in place.
7125 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
7126 ;; detected.
7127 (tramp-find-shell vec)
7129 ;; Disable unexpected output.
7130 (tramp-send-command vec "mesg n; biff n" t)
7132 ;; IRIX64 bash expands "!" even when in single quotes. This
7133 ;; destroys our shell functions, we must disable it. See
7134 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
7135 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
7136 (tramp-send-command vec "set +H" t))
7138 ;; Set `remote-tty' process property.
7139 (ignore-errors
7140 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"")))
7141 (unless (zerop (length tty)) (process-put proc 'remote-tty tty))))
7143 ;; Set the environment.
7144 (tramp-message vec 5 "Setting default environment")
7146 (let ((env (copy-sequence tramp-remote-process-environment))
7147 unset item)
7148 (while env
7149 (setq item (tramp-compat-split-string (car env) "="))
7150 (setcdr item (mapconcat 'identity (cdr item) "="))
7151 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
7152 (tramp-send-command
7153 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
7154 (push (car item) unset))
7155 (setq env (cdr env)))
7156 (when unset
7157 (tramp-send-command
7158 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
7160 ;; CCC: We should either implement a Perl version of base64 encoding
7161 ;; and decoding. Then we just use that in the last item. The other
7162 ;; alternative is to use the Perl version of UU encoding. But then
7163 ;; we need a Lisp version of uuencode.
7165 ;; Old text from documentation of tramp-methods:
7166 ;; Using a uuencode/uudecode inline method is discouraged, please use one
7167 ;; of the base64 methods instead since base64 encoding is much more
7168 ;; reliable and the commands are more standardized between the different
7169 ;; Unix versions. But if you can't use base64 for some reason, please
7170 ;; note that the default uudecode command does not work well for some
7171 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
7172 ;; the following command for uudecode:
7174 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
7176 ;; For Irix, no solution is known yet.
7178 (defconst tramp-local-coding-commands
7179 '((b64 base64-encode-region base64-decode-region)
7180 (uu tramp-uuencode-region uudecode-decode-region)
7181 (pack
7182 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7183 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7184 "List of local coding commands for inline transfer.
7185 Each item is a list that looks like this:
7187 \(FORMAT ENCODING DECODING\)
7189 FORMAT is symbol describing the encoding/decoding format. It can be
7190 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7192 ENCODING and DECODING can be strings, giving commands, or symbols,
7193 giving functions. If they are strings, then they can contain
7194 the \"%s\" format specifier. If that specifier is present, the input
7195 filename will be put into the command line at that spot. If the
7196 specifier is not present, the input should be read from standard
7197 input.
7199 If they are functions, they will be called with two arguments, start
7200 and end of region, and are expected to replace the region contents
7201 with the encoded or decoded results, respectively.")
7203 (defconst tramp-remote-coding-commands
7204 '((b64 "base64" "base64 -d")
7205 (b64 "mimencode -b" "mimencode -u -b")
7206 (b64 "mmencode -b" "mmencode -u -b")
7207 (b64 "recode data..base64" "recode base64..data")
7208 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
7209 (b64 tramp-perl-encode tramp-perl-decode)
7210 (uu "uuencode xxx" "uudecode -o /dev/stdout")
7211 (uu "uuencode xxx" "uudecode -o -")
7212 (uu "uuencode xxx" "uudecode -p")
7213 (uu "uuencode xxx" tramp-uudecode)
7214 (pack
7215 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7216 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7217 "List of remote coding commands for inline transfer.
7218 Each item is a list that looks like this:
7220 \(FORMAT ENCODING DECODING\)
7222 FORMAT is symbol describing the encoding/decoding format. It can be
7223 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7225 ENCODING and DECODING can be strings, giving commands, or symbols,
7226 giving variables. If they are strings, then they can contain
7227 the \"%s\" format specifier. If that specifier is present, the input
7228 filename will be put into the command line at that spot. If the
7229 specifier is not present, the input should be read from standard
7230 input.
7232 If they are variables, this variable is a string containing a Perl
7233 implementation for this functionality. This Perl program will be transferred
7234 to the remote host, and it is available as shell function with the same name.")
7236 (defun tramp-find-inline-encoding (vec)
7237 "Find an inline transfer encoding that works.
7238 Goes through the list `tramp-local-coding-commands' and
7239 `tramp-remote-coding-commands'."
7240 (save-excursion
7241 (let ((local-commands tramp-local-coding-commands)
7242 (magic "xyzzy")
7243 loc-enc loc-dec rem-enc rem-dec litem ritem found)
7244 (while (and local-commands (not found))
7245 (setq litem (pop local-commands))
7246 (catch 'wont-work-local
7247 (let ((format (nth 0 litem))
7248 (remote-commands tramp-remote-coding-commands))
7249 (setq loc-enc (nth 1 litem))
7250 (setq loc-dec (nth 2 litem))
7251 ;; If the local encoder or decoder is a string, the
7252 ;; corresponding command has to work locally.
7253 (if (not (stringp loc-enc))
7254 (tramp-message
7255 vec 5 "Checking local encoding function `%s'" loc-enc)
7256 (tramp-message
7257 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
7258 (unless (zerop (tramp-call-local-coding-command
7259 loc-enc nil nil))
7260 (throw 'wont-work-local nil)))
7261 (if (not (stringp loc-dec))
7262 (tramp-message
7263 vec 5 "Checking local decoding function `%s'" loc-dec)
7264 (tramp-message
7265 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7266 (unless (zerop (tramp-call-local-coding-command
7267 loc-dec nil nil))
7268 (throw 'wont-work-local nil)))
7269 ;; Search for remote coding commands with the same format
7270 (while (and remote-commands (not found))
7271 (setq ritem (pop remote-commands))
7272 (catch 'wont-work-remote
7273 (when (equal format (nth 0 ritem))
7274 (setq rem-enc (nth 1 ritem))
7275 (setq rem-dec (nth 2 ritem))
7276 ;; Check if remote encoding and decoding commands can be
7277 ;; called remotely with null input and output. This makes
7278 ;; sure there are no syntax errors and the command is really
7279 ;; found. Note that we do not redirect stdout to /dev/null,
7280 ;; for two reasons: when checking the decoding command, we
7281 ;; actually check the output it gives. And also, when
7282 ;; redirecting "mimencode" output to /dev/null, then as root
7283 ;; it might change the permissions of /dev/null!
7284 (when (not (stringp rem-enc))
7285 (let ((name (symbol-name rem-enc)))
7286 (while (string-match (regexp-quote "-") name)
7287 (setq name (replace-match "_" nil t name)))
7288 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7289 (setq rem-enc name)))
7290 (tramp-message
7291 vec 5
7292 "Checking remote encoding command `%s' for sanity" rem-enc)
7293 (unless (zerop (tramp-send-command-and-check
7294 vec (format "%s </dev/null" rem-enc) t))
7295 (throw 'wont-work-remote nil))
7297 (when (not (stringp rem-dec))
7298 (let ((name (symbol-name rem-dec)))
7299 (while (string-match (regexp-quote "-") name)
7300 (setq name (replace-match "_" nil t name)))
7301 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7302 (setq rem-dec name)))
7303 (tramp-message
7304 vec 5
7305 "Checking remote decoding command `%s' for sanity" rem-dec)
7306 (unless (zerop (tramp-send-command-and-check
7308 (format "echo %s | %s | %s"
7309 magic rem-enc rem-dec)
7311 (throw 'wont-work-remote nil))
7313 (with-current-buffer (tramp-get-buffer vec)
7314 (goto-char (point-min))
7315 (unless (looking-at (regexp-quote magic))
7316 (throw 'wont-work-remote nil)))
7318 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7319 (setq rem-enc (nth 1 ritem))
7320 (setq rem-dec (nth 2 ritem))
7321 (setq found t)))))))
7323 ;; Did we find something?
7324 (unless found
7325 (tramp-error
7326 vec 'file-error "Couldn't find an inline transfer encoding"))
7328 ;; Set connection properties.
7329 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7330 (tramp-set-connection-property vec "local-encoding" loc-enc)
7331 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7332 (tramp-set-connection-property vec "local-decoding" loc-dec)
7333 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7334 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7335 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7336 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7338 (defun tramp-call-local-coding-command (cmd input output)
7339 "Call the local encoding or decoding command.
7340 If CMD contains \"%s\", provide input file INPUT there in command.
7341 Otherwise, INPUT is passed via standard input.
7342 INPUT can also be nil which means `/dev/null'.
7343 OUTPUT can be a string (which specifies a filename), or t (which
7344 means standard output and thus the current buffer), or nil (which
7345 means discard it)."
7346 (tramp-compat-call-process
7347 tramp-encoding-shell
7348 (when (and input (not (string-match "%s" cmd))) input)
7349 (if (eq output t) t nil)
7351 tramp-encoding-command-switch
7352 (concat
7353 (if (string-match "%s" cmd) (format cmd input) cmd)
7354 (if (stringp output) (concat "> " output) ""))))
7356 (defconst tramp-inline-compress-commands
7357 '(("gzip" "gzip -d")
7358 ("bzip2" "bzip2 -d")
7359 ("compress" "compress -d"))
7360 "List of compress and decompress commands for inline transfer.
7361 Each item is a list that looks like this:
7363 \(COMPRESS DECOMPRESS\)
7365 COMPRESS or DECOMPRESS are strings with the respective commands.")
7367 (defun tramp-find-inline-compress (vec)
7368 "Find an inline transfer compress command that works.
7369 Goes through the list `tramp-inline-compress-commands'."
7370 (save-excursion
7371 (let ((commands tramp-inline-compress-commands)
7372 (magic "xyzzy")
7373 item compress decompress
7374 found)
7375 (while (and commands (not found))
7376 (catch 'next
7377 (setq item (pop commands)
7378 compress (nth 0 item)
7379 decompress (nth 1 item))
7380 (tramp-message
7381 vec 5
7382 "Checking local compress command `%s', `%s' for sanity"
7383 compress decompress)
7384 (unless (zerop (tramp-call-local-coding-command
7385 (format "echo %s | %s | %s"
7386 magic compress decompress) nil nil))
7387 (throw 'next nil))
7388 (tramp-message
7389 vec 5
7390 "Checking remote compress command `%s', `%s' for sanity"
7391 compress decompress)
7392 (unless (zerop (tramp-send-command-and-check
7393 vec (format "echo %s | %s | %s"
7394 magic compress decompress) t))
7395 (throw 'next nil))
7396 (setq found t)))
7398 ;; Did we find something?
7399 (if found
7400 (progn
7401 ;; Set connection properties.
7402 (tramp-message
7403 vec 5 "Using inline transfer compress command `%s'" compress)
7404 (tramp-set-connection-property vec "inline-compress" compress)
7405 (tramp-message
7406 vec 5 "Using inline transfer decompress command `%s'" decompress)
7407 (tramp-set-connection-property vec "inline-decompress" decompress))
7409 (tramp-set-connection-property vec "inline-compress" nil)
7410 (tramp-set-connection-property vec "inline-decompress" nil)
7411 (tramp-message
7412 vec 2 "Couldn't find an inline transfer compress command")))))
7414 (defun tramp-compute-multi-hops (vec)
7415 "Expands VEC according to `tramp-default-proxies-alist'.
7416 Gateway hops are already opened."
7417 (let ((target-alist `(,vec))
7418 (choices tramp-default-proxies-alist)
7419 item proxy)
7421 ;; Look for proxy hosts to be passed.
7422 (while choices
7423 (setq item (pop choices)
7424 proxy (eval (nth 2 item)))
7425 (when (and
7426 ;; host
7427 (string-match (or (eval (nth 0 item)) "")
7428 (or (tramp-file-name-host (car target-alist)) ""))
7429 ;; user
7430 (string-match (or (eval (nth 1 item)) "")
7431 (or (tramp-file-name-user (car target-alist)) "")))
7432 (if (null proxy)
7433 ;; No more hops needed.
7434 (setq choices nil)
7435 ;; Replace placeholders.
7436 (setq proxy
7437 (format-spec
7438 proxy
7439 (format-spec-make
7440 ?u (or (tramp-file-name-user (car target-alist)) "")
7441 ?h (or (tramp-file-name-host (car target-alist)) ""))))
7442 (with-parsed-tramp-file-name proxy l
7443 ;; Add the hop.
7444 (add-to-list 'target-alist l)
7445 ;; Start next search.
7446 (setq choices tramp-default-proxies-alist)))))
7448 ;; Handle gateways.
7449 (when (string-match
7450 (format
7451 "^\\(%s\\|%s\\)$" tramp-gw-tunnel-method tramp-gw-socks-method)
7452 (tramp-file-name-method (car target-alist)))
7453 (let ((gw (pop target-alist))
7454 (hop (pop target-alist)))
7455 ;; Is the method prepared for gateways?
7456 (unless (tramp-get-method-parameter
7457 (tramp-file-name-method hop) 'tramp-default-port)
7458 (tramp-error
7459 vec 'file-error
7460 "Method `%s' is not supported for gateway access."
7461 (tramp-file-name-method hop)))
7462 ;; Add default port if needed.
7463 (unless
7464 (string-match
7465 tramp-host-with-port-regexp (tramp-file-name-host hop))
7466 (aset hop 2
7467 (concat
7468 (tramp-file-name-host hop) tramp-prefix-port-format
7469 (number-to-string
7470 (tramp-get-method-parameter
7471 (tramp-file-name-method hop) 'tramp-default-port)))))
7472 ;; Open the gateway connection.
7473 (add-to-list
7474 'target-alist
7475 (vector
7476 (tramp-file-name-method hop) (tramp-file-name-user hop)
7477 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil))
7478 ;; For the password prompt, we need the correct values.
7479 ;; Therefore, we must remember the gateway vector. But we
7480 ;; cannot do it as connection property, because it shouldn't
7481 ;; be persistent. And we have no started process yet either.
7482 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7484 ;; Foreign and out-of-band methods are not supported for multi-hops.
7485 (when (cdr target-alist)
7486 (setq choices target-alist)
7487 (while choices
7488 (setq item (pop choices))
7489 (when
7491 (not
7492 (tramp-get-method-parameter
7493 (tramp-file-name-method item) 'tramp-login-program))
7494 (tramp-get-method-parameter
7495 (tramp-file-name-method item) 'tramp-copy-program))
7496 (tramp-error
7497 vec 'file-error
7498 "Method `%s' is not supported for multi-hops."
7499 (tramp-file-name-method item)))))
7501 ;; In case the host name is not used for the remote shell
7502 ;; command, the user could be misguided by applying a random
7503 ;; hostname.
7504 (let* ((v (car target-alist))
7505 (method (tramp-file-name-method v))
7506 (host (tramp-file-name-host v)))
7507 (unless
7509 ;; There are multi-hops.
7510 (cdr target-alist)
7511 ;; The host name is used for the remote shell command.
7512 (member
7513 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7514 ;; The host is local. We cannot use `tramp-local-host-p'
7515 ;; here, because it opens a connection as well.
7516 (string-match tramp-local-host-regexp host))
7517 (tramp-error
7518 v 'file-error
7519 "Host `%s' looks like a remote host, `%s' can only use the local host"
7520 host method)))
7522 ;; Result.
7523 target-alist))
7525 (defun tramp-maybe-open-connection (vec)
7526 "Maybe open a connection VEC.
7527 Does not do anything if a connection is already open, but re-opens the
7528 connection if a previous connection has died for some reason."
7529 (catch 'uname-changed
7530 (let ((p (tramp-get-connection-process vec))
7531 (process-name (tramp-get-connection-property vec "process-name" nil))
7532 (process-environment (copy-sequence process-environment)))
7534 ;; If too much time has passed since last command was sent, look
7535 ;; whether process is still alive. If it isn't, kill it. When
7536 ;; using ssh, it can sometimes happen that the remote end has
7537 ;; hung up but the local ssh client doesn't recognize this until
7538 ;; it tries to send some data to the remote end. So that's why
7539 ;; we try to send a command from time to time, then look again
7540 ;; whether the process is really alive.
7541 (condition-case nil
7542 (when (and (> (tramp-time-diff
7543 (current-time)
7544 (tramp-get-connection-property
7545 p "last-cmd-time" '(0 0 0)))
7547 p (processp p) (memq (process-status p) '(run open)))
7548 (tramp-send-command vec "echo are you awake" t t)
7549 (unless (and (memq (process-status p) '(run open))
7550 (tramp-wait-for-output p 10))
7551 ;; The error will be catched locally.
7552 (tramp-error vec 'file-error "Awake did fail")))
7553 (file-error
7554 (tramp-flush-connection-property vec)
7555 (tramp-flush-connection-property p)
7556 (delete-process p)
7557 (setq p nil)))
7559 ;; New connection must be opened.
7560 (unless (and p (processp p) (memq (process-status p) '(run open)))
7562 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7563 ;; messages from the beginning.
7564 (tramp-get-buffer vec)
7565 (with-progress-reporter
7566 vec 3
7567 (if (zerop (length (tramp-file-name-user vec)))
7568 (format "Opening connection for %s using %s"
7569 (tramp-file-name-host vec)
7570 (tramp-file-name-method vec))
7571 (format "Opening connection for %s@%s using %s"
7572 (tramp-file-name-user vec)
7573 (tramp-file-name-host vec)
7574 (tramp-file-name-method vec)))
7576 ;; Start new process.
7577 (when (and p (processp p))
7578 (delete-process p))
7579 (setenv "TERM" tramp-terminal-type)
7580 (setenv "LC_ALL" "C")
7581 (setenv "PROMPT_COMMAND")
7582 (setenv "PS1" tramp-initial-end-of-output)
7583 (let* ((target-alist (tramp-compute-multi-hops vec))
7584 (process-connection-type tramp-process-connection-type)
7585 (process-adaptive-read-buffering nil)
7586 (coding-system-for-read nil)
7587 ;; This must be done in order to avoid our file name handler.
7588 (p (let ((default-directory
7589 (tramp-compat-temporary-file-directory)))
7590 (start-process
7591 (or process-name (tramp-buffer-name vec))
7592 (tramp-get-connection-buffer vec)
7593 tramp-encoding-shell))))
7595 (tramp-message
7596 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7598 ;; Check whether process is alive.
7599 (tramp-set-process-query-on-exit-flag p nil)
7600 (tramp-barf-if-no-shell-prompt
7601 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7603 ;; Now do all the connections as specified.
7604 (while target-alist
7605 (let* ((hop (car target-alist))
7606 (l-method (tramp-file-name-method hop))
7607 (l-user (tramp-file-name-user hop))
7608 (l-host (tramp-file-name-host hop))
7609 (l-port nil)
7610 (login-program
7611 (tramp-get-method-parameter
7612 l-method 'tramp-login-program))
7613 (login-args
7614 (tramp-get-method-parameter l-method 'tramp-login-args))
7615 (async-args
7616 (tramp-get-method-parameter l-method 'tramp-async-args))
7617 (gw-args
7618 (tramp-get-method-parameter l-method 'tramp-gw-args))
7619 (gw (tramp-get-file-property hop "" "gateway" nil))
7620 (g-method (and gw (tramp-file-name-method gw)))
7621 (g-user (and gw (tramp-file-name-user gw)))
7622 (g-host (and gw (tramp-file-name-host gw)))
7623 (command login-program)
7624 ;; We don't create the temporary file. In fact,
7625 ;; it is just a prefix for the ControlPath option
7626 ;; of ssh; the real temporary file has another
7627 ;; name, and it is created and protected by ssh.
7628 ;; It is also removed by ssh, when the connection
7629 ;; is closed.
7630 (tmpfile
7631 (tramp-set-connection-property
7632 p "temp-file"
7633 (make-temp-name
7634 (expand-file-name
7635 tramp-temp-name-prefix
7636 (tramp-compat-temporary-file-directory)))))
7637 spec)
7639 ;; Add arguments for asynchrononous processes.
7640 (when (and process-name async-args)
7641 (setq login-args (append async-args login-args)))
7643 ;; Add gateway arguments if necessary.
7644 (when (and gw gw-args)
7645 (setq login-args (append gw-args login-args)))
7647 ;; Check for port number. Until now, there's no need
7648 ;; for handling like method, user, host.
7649 (when (string-match tramp-host-with-port-regexp l-host)
7650 (setq l-port (match-string 2 l-host)
7651 l-host (match-string 1 l-host)))
7653 ;; Set variables for computing the prompt for reading
7654 ;; password. They can also be derived from a gateway.
7655 (setq tramp-current-method (or g-method l-method)
7656 tramp-current-user (or g-user l-user)
7657 tramp-current-host (or g-host l-host))
7659 ;; Replace login-args place holders.
7660 (setq
7661 l-host (or l-host "")
7662 l-user (or l-user "")
7663 l-port (or l-port "")
7664 spec (format-spec-make
7665 ?h l-host ?u l-user ?p l-port ?t tmpfile)
7666 command
7667 (concat
7668 ;; We do not want to see the trailing local prompt in
7669 ;; `start-file-process'.
7670 (unless (memq system-type '(windows-nt)) "exec ")
7671 command " "
7672 (mapconcat
7673 (lambda (x)
7674 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7675 (unless (member "" x) (mapconcat 'identity x " ")))
7676 login-args " ")
7677 ;; Local shell could be a Windows COMSPEC. It
7678 ;; doesn't know the ";" syntax, but we must exit
7679 ;; always for `start-file-process'. "exec" does not
7680 ;; work either.
7681 (if (memq system-type '(windows-nt)) " && exit || exit")))
7683 ;; Send the command.
7684 (tramp-message vec 3 "Sending command `%s'" command)
7685 (tramp-send-command vec command t t)
7686 (tramp-process-actions p vec tramp-actions-before-shell 60)
7687 (tramp-message
7688 vec 3 "Found remote shell prompt on `%s'" l-host))
7689 ;; Next hop.
7690 (setq target-alist (cdr target-alist)))
7692 ;; Make initial shell settings.
7693 (tramp-open-connection-setup-interactive-shell p vec)))))))
7695 (defun tramp-send-command (vec command &optional neveropen nooutput)
7696 "Send the COMMAND to connection VEC.
7697 Erases temporary buffer before sending the command. If optional
7698 arg NEVEROPEN is non-nil, never try to open the connection. This
7699 is meant to be used from `tramp-maybe-open-connection' only. The
7700 function waits for output unless NOOUTPUT is set."
7701 (unless neveropen (tramp-maybe-open-connection vec))
7702 (let ((p (tramp-get-connection-process vec)))
7703 (when (tramp-get-connection-property p "remote-echo" nil)
7704 ;; We mark the command string that it can be erased in the output buffer.
7705 (tramp-set-connection-property p "check-remote-echo" t)
7706 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7707 (tramp-message vec 6 "%s" command)
7708 (tramp-send-string vec command)
7709 (unless nooutput (tramp-wait-for-output p))))
7711 (defun tramp-wait-for-output (proc &optional timeout)
7712 "Wait for output from remote command."
7713 (unless (buffer-live-p (process-buffer proc))
7714 (delete-process proc)
7715 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7716 (with-current-buffer (process-buffer proc)
7717 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7718 ;; be leading escape sequences, which must be ignored.
7719 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7720 ;; Sometimes, the commands do not return a newline but a
7721 ;; null byte before the shell prompt, for example "git
7722 ;; ls-files -c -z ...".
7723 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7724 (found (tramp-wait-for-regexp proc timeout regexp1)))
7725 (if found
7726 (let (buffer-read-only)
7727 ;; A simple-minded busybox has sent " ^H" sequences.
7728 ;; Delete them.
7729 (goto-char (point-min))
7730 (when (re-search-forward
7731 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7732 (forward-line 1)
7733 (delete-region (point-min) (point)))
7734 ;; Delete the prompt.
7735 (goto-char (point-max))
7736 (re-search-backward regexp nil t)
7737 (delete-region (point) (point-max)))
7738 (if timeout
7739 (tramp-error
7740 proc 'file-error
7741 "[[Remote prompt `%s' not found in %d secs]]"
7742 tramp-end-of-output timeout)
7743 (tramp-error
7744 proc 'file-error
7745 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7746 ;; Return value is whether end-of-output sentinel was found.
7747 found)))
7749 ;;;###tramp-autoload
7750 (defun tramp-send-command-and-check
7751 (vec command &optional subshell dont-suppress-err)
7752 "Run COMMAND and check its exit status.
7753 Sends `echo $?' along with the COMMAND for checking the exit status. If
7754 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7756 If the optional argument SUBSHELL is non-nil, the command is
7757 executed in a subshell, ie surrounded by parentheses. If
7758 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7759 (tramp-send-command
7761 (concat (if subshell "( " "")
7762 command
7763 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7764 "echo tramp_exit_status $?"
7765 (if subshell " )" "")))
7766 (with-current-buffer (tramp-get-connection-buffer vec)
7767 (goto-char (point-max))
7768 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7769 (tramp-error
7770 vec 'file-error "Couldn't find exit status of `%s'" command))
7771 (skip-chars-forward "^ ")
7772 (prog1
7773 (read (current-buffer))
7774 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7776 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7777 "Run COMMAND, check exit status, throw error if exit status not okay.
7778 Similar to `tramp-send-command-and-check' but accepts two more arguments
7779 FMT and ARGS which are passed to `error'."
7780 (unless (zerop (tramp-send-command-and-check vec command))
7781 (apply 'tramp-error vec 'file-error fmt args)))
7783 (defun tramp-send-command-and-read (vec command)
7784 "Run COMMAND and return the output, which must be a Lisp expression.
7785 In case there is no valid Lisp expression, it raises an error"
7786 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7787 (with-current-buffer (tramp-get-connection-buffer vec)
7788 ;; Read the expression.
7789 (goto-char (point-min))
7790 (condition-case nil
7791 (prog1 (read (current-buffer))
7792 ;; Error handling.
7793 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7794 (error nil)))
7795 (error (tramp-error
7796 vec 'file-error
7797 "`%s' does not return a valid Lisp expression: `%s'"
7798 command (buffer-string))))))
7800 ;; It seems that Tru64 Unix does not like it if long strings are sent
7801 ;; to it in one go. (This happens when sending the Perl
7802 ;; `file-attributes' implementation, for instance.) Therefore, we
7803 ;; have this function which sends the string in chunks.
7804 (defun tramp-send-string (vec string)
7805 "Send the STRING via connection VEC.
7807 The STRING is expected to use Unix line-endings, but the lines sent to
7808 the remote host use line-endings as defined in the variable
7809 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7810 (let* ((p (tramp-get-connection-process vec))
7811 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7812 (unless p
7813 (tramp-error
7814 vec 'file-error "Can't send string to remote host -- not logged in"))
7815 (tramp-set-connection-property p "last-cmd-time" (current-time))
7816 (tramp-message vec 10 "%s" string)
7817 (with-current-buffer (tramp-get-connection-buffer vec)
7818 ;; Clean up the buffer. We cannot call `erase-buffer' because
7819 ;; narrowing might be in effect.
7820 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7821 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7822 (setq string
7823 (mapconcat 'identity
7824 (tramp-compat-split-string string "\n")
7825 tramp-rsh-end-of-line))
7826 (unless (or (string= string "")
7827 (string-equal (substring string -1) tramp-rsh-end-of-line))
7828 (setq string (concat string tramp-rsh-end-of-line)))
7829 ;; Send the string.
7830 (if (and chunksize (not (zerop chunksize)))
7831 (let ((pos 0)
7832 (end (length string)))
7833 (while (< pos end)
7834 (tramp-message
7835 vec 10 "Sending chunk from %s to %s"
7836 pos (min (+ pos chunksize) end))
7837 (process-send-string
7838 p (substring string pos (min (+ pos chunksize) end)))
7839 (setq pos (+ pos chunksize))))
7840 (process-send-string p string)))))
7842 (defun tramp-mode-string-to-int (mode-string)
7843 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7844 (let* (case-fold-search
7845 (mode-chars (string-to-vector mode-string))
7846 (owner-read (aref mode-chars 1))
7847 (owner-write (aref mode-chars 2))
7848 (owner-execute-or-setid (aref mode-chars 3))
7849 (group-read (aref mode-chars 4))
7850 (group-write (aref mode-chars 5))
7851 (group-execute-or-setid (aref mode-chars 6))
7852 (other-read (aref mode-chars 7))
7853 (other-write (aref mode-chars 8))
7854 (other-execute-or-sticky (aref mode-chars 9)))
7855 (save-match-data
7856 (logior
7857 (cond
7858 ((char-equal owner-read ?r) (tramp-compat-octal-to-decimal "00400"))
7859 ((char-equal owner-read ?-) 0)
7860 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7861 (cond
7862 ((char-equal owner-write ?w) (tramp-compat-octal-to-decimal "00200"))
7863 ((char-equal owner-write ?-) 0)
7864 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7865 (cond
7866 ((char-equal owner-execute-or-setid ?x)
7867 (tramp-compat-octal-to-decimal "00100"))
7868 ((char-equal owner-execute-or-setid ?S)
7869 (tramp-compat-octal-to-decimal "04000"))
7870 ((char-equal owner-execute-or-setid ?s)
7871 (tramp-compat-octal-to-decimal "04100"))
7872 ((char-equal owner-execute-or-setid ?-) 0)
7873 (t (error "Fourth char `%c' must be one of `xsS-'"
7874 owner-execute-or-setid)))
7875 (cond
7876 ((char-equal group-read ?r) (tramp-compat-octal-to-decimal "00040"))
7877 ((char-equal group-read ?-) 0)
7878 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7879 (cond
7880 ((char-equal group-write ?w) (tramp-compat-octal-to-decimal "00020"))
7881 ((char-equal group-write ?-) 0)
7882 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7883 (cond
7884 ((char-equal group-execute-or-setid ?x)
7885 (tramp-compat-octal-to-decimal "00010"))
7886 ((char-equal group-execute-or-setid ?S)
7887 (tramp-compat-octal-to-decimal "02000"))
7888 ((char-equal group-execute-or-setid ?s)
7889 (tramp-compat-octal-to-decimal "02010"))
7890 ((char-equal group-execute-or-setid ?-) 0)
7891 (t (error "Seventh char `%c' must be one of `xsS-'"
7892 group-execute-or-setid)))
7893 (cond
7894 ((char-equal other-read ?r)
7895 (tramp-compat-octal-to-decimal "00004"))
7896 ((char-equal other-read ?-) 0)
7897 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7898 (cond
7899 ((char-equal other-write ?w) (tramp-compat-octal-to-decimal "00002"))
7900 ((char-equal other-write ?-) 0)
7901 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7902 (cond
7903 ((char-equal other-execute-or-sticky ?x)
7904 (tramp-compat-octal-to-decimal "00001"))
7905 ((char-equal other-execute-or-sticky ?T)
7906 (tramp-compat-octal-to-decimal "01000"))
7907 ((char-equal other-execute-or-sticky ?t)
7908 (tramp-compat-octal-to-decimal "01001"))
7909 ((char-equal other-execute-or-sticky ?-) 0)
7910 (t (error "Tenth char `%c' must be one of `xtT-'"
7911 other-execute-or-sticky)))))))
7913 (defun tramp-convert-file-attributes (vec attr)
7914 "Convert file-attributes ATTR generated by perl script, stat or ls.
7915 Convert file mode bits to string and set virtual device number.
7916 Return ATTR."
7917 (when attr
7918 ;; Convert last access time.
7919 (unless (listp (nth 4 attr))
7920 (setcar (nthcdr 4 attr)
7921 (list (floor (nth 4 attr) 65536)
7922 (floor (mod (nth 4 attr) 65536)))))
7923 ;; Convert last modification time.
7924 (unless (listp (nth 5 attr))
7925 (setcar (nthcdr 5 attr)
7926 (list (floor (nth 5 attr) 65536)
7927 (floor (mod (nth 5 attr) 65536)))))
7928 ;; Convert last status change time.
7929 (unless (listp (nth 6 attr))
7930 (setcar (nthcdr 6 attr)
7931 (list (floor (nth 6 attr) 65536)
7932 (floor (mod (nth 6 attr) 65536)))))
7933 ;; Convert file size.
7934 (when (< (nth 7 attr) 0)
7935 (setcar (nthcdr 7 attr) -1))
7936 (when (and (floatp (nth 7 attr))
7937 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7938 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7939 ;; Convert file mode bits to string.
7940 (unless (stringp (nth 8 attr))
7941 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7942 (when (stringp (car attr))
7943 (aset (nth 8 attr) 0 ?l)))
7944 ;; Convert directory indication bit.
7945 (when (string-match "^d" (nth 8 attr))
7946 (setcar attr t))
7947 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7948 (when (consp (car attr))
7949 (if (and (stringp (caar attr))
7950 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7951 (setcar attr (match-string 1 (caar attr)))
7952 (setcar attr nil)))
7953 ;; Set file's gid change bit.
7954 (setcar (nthcdr 9 attr)
7955 (if (numberp (nth 3 attr))
7956 (not (= (nth 3 attr)
7957 (tramp-get-remote-gid vec 'integer)))
7958 (not (string-equal
7959 (nth 3 attr)
7960 (tramp-get-remote-gid vec 'string)))))
7961 ;; Convert inode.
7962 (unless (listp (nth 10 attr))
7963 (setcar (nthcdr 10 attr)
7964 (condition-case nil
7965 (cons (floor (nth 10 attr) 65536)
7966 (floor (mod (nth 10 attr) 65536)))
7967 ;; Inodes can be incredible huge. We must hide this.
7968 (error (tramp-get-inode vec)))))
7969 ;; Set virtual device number.
7970 (setcar (nthcdr 11 attr)
7971 (tramp-get-device vec))
7972 attr))
7974 (defun tramp-check-cached-permissions (vec access)
7975 "Check `file-attributes' caches for VEC.
7976 Return t if according to the cache access type ACCESS is known to
7977 be granted."
7978 (let ((result nil)
7979 (offset (cond
7980 ((eq ?r access) 1)
7981 ((eq ?w access) 2)
7982 ((eq ?x access) 3))))
7983 (dolist (suffix '("string" "integer") result)
7984 (setq
7985 result
7987 result
7988 (let ((file-attr
7989 (tramp-get-file-property
7990 vec (tramp-file-name-localname vec)
7991 (concat "file-attributes-" suffix) nil))
7992 (remote-uid
7993 (tramp-get-connection-property
7994 vec (concat "uid-" suffix) nil))
7995 (remote-gid
7996 (tramp-get-connection-property
7997 vec (concat "gid-" suffix) nil)))
7998 (and
7999 file-attr
8001 ;; Not a symlink
8002 (eq t (car file-attr))
8003 (null (car file-attr)))
8005 ;; World accessible.
8006 (eq access (aref (nth 8 file-attr) (+ offset 6)))
8007 ;; User accessible and owned by user.
8008 (and
8009 (eq access (aref (nth 8 file-attr) offset))
8010 (equal remote-uid (nth 2 file-attr)))
8011 ;; Group accessible and owned by user's
8012 ;; principal group.
8013 (and
8014 (eq access (aref (nth 8 file-attr) (+ offset 3)))
8015 (equal remote-gid (nth 3 file-attr)))))))))))
8017 (defun tramp-get-inode (vec)
8018 "Returns the virtual inode number.
8019 If it doesn't exist, generate a new one."
8020 (let ((string (tramp-make-tramp-file-name
8021 (tramp-file-name-method vec)
8022 (tramp-file-name-user vec)
8023 (tramp-file-name-host vec)
8024 "")))
8025 (unless (assoc string tramp-inodes)
8026 (add-to-list 'tramp-inodes
8027 (list string (length tramp-inodes))))
8028 (nth 1 (assoc string tramp-inodes))))
8030 (defun tramp-get-device (vec)
8031 "Returns the virtual device number.
8032 If it doesn't exist, generate a new one."
8033 (let ((string (tramp-make-tramp-file-name
8034 (tramp-file-name-method vec)
8035 (tramp-file-name-user vec)
8036 (tramp-file-name-host vec)
8037 "")))
8038 (unless (assoc string tramp-devices)
8039 (add-to-list 'tramp-devices
8040 (list string (length tramp-devices))))
8041 (cons -1 (nth 1 (assoc string tramp-devices)))))
8043 (defun tramp-file-mode-from-int (mode)
8044 "Turn an integer representing a file mode into an ls(1)-like string."
8045 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
8046 (user (logand (lsh mode -6) 7))
8047 (group (logand (lsh mode -3) 7))
8048 (other (logand (lsh mode -0) 7))
8049 (suid (> (logand (lsh mode -9) 4) 0))
8050 (sgid (> (logand (lsh mode -9) 2) 0))
8051 (sticky (> (logand (lsh mode -9) 1) 0)))
8052 (setq user (tramp-file-mode-permissions user suid "s"))
8053 (setq group (tramp-file-mode-permissions group sgid "s"))
8054 (setq other (tramp-file-mode-permissions other sticky "t"))
8055 (concat type user group other)))
8057 (defun tramp-file-mode-permissions (perm suid suid-text)
8058 "Convert a permission bitset into a string.
8059 This is used internally by `tramp-file-mode-from-int'."
8060 (let ((r (> (logand perm 4) 0))
8061 (w (> (logand perm 2) 0))
8062 (x (> (logand perm 1) 0)))
8063 (concat (or (and r "r") "-")
8064 (or (and w "w") "-")
8065 (or (and suid x suid-text) ; suid, execute
8066 (and suid (upcase suid-text)) ; suid, !execute
8067 (and x "x") "-")))) ; !suid
8069 (defun tramp-shell-case-fold (string)
8070 "Converts STRING to shell glob pattern which ignores case."
8071 (mapconcat
8072 (lambda (c)
8073 (if (equal (downcase c) (upcase c))
8074 (vector c)
8075 (format "[%c%c]" (downcase c) (upcase c))))
8076 string
8077 ""))
8079 (defun tramp-equal-remote (file1 file2)
8080 "Check, whether the remote parts of FILE1 and FILE2 are identical.
8081 The check depends on method, user and host name of the files. If
8082 one of the components is missing, the default values are used.
8083 The local file name parts of FILE1 and FILE2 are not taken into
8084 account.
8086 Example:
8088 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
8090 would yield `t'. On the other hand, the following check results in nil:
8092 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
8093 (and (stringp (file-remote-p file1))
8094 (stringp (file-remote-p file2))
8095 (string-equal (file-remote-p file1) (file-remote-p file2))))
8097 (defun tramp-make-copy-program-file-name (vec)
8098 "Create a file name suitable to be passed to `rcp' and workalikes."
8099 (let ((user (tramp-file-name-user vec))
8100 (host (tramp-file-name-real-host vec))
8101 (localname (tramp-shell-quote-argument
8102 (tramp-file-name-localname vec))))
8103 (if (not (zerop (length user)))
8104 (format "%s@%s:%s" user host localname)
8105 (format "%s:%s" host localname))))
8107 (defun tramp-method-out-of-band-p (vec size)
8108 "Return t if this is an out-of-band method, nil otherwise."
8109 (and
8110 ;; It shall be an out-of-band method.
8111 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
8112 ;; Either the file size is large enough, or (in rare cases) there
8113 ;; does not exist a remote encoding.
8114 (or (null tramp-copy-size-limit)
8115 (> size tramp-copy-size-limit)
8116 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
8118 (defun tramp-local-host-p (vec)
8119 "Return t if this points to the local host, nil otherwise."
8120 ;; We cannot use `tramp-file-name-real-host'. A port is an
8121 ;; indication for an ssh tunnel or alike.
8122 (let ((host (tramp-file-name-host vec)))
8123 (and
8124 (stringp host)
8125 (string-match tramp-local-host-regexp host)
8126 ;; The method shall be applied to one of the shell file name
8127 ;; handler. `tramp-local-host-p' is also called for "smb" and
8128 ;; alike, where it must fail.
8129 (tramp-get-method-parameter
8130 (tramp-file-name-method vec) 'tramp-login-program)
8131 ;; The local temp directory must be writable for the other user.
8132 (file-writable-p
8133 (tramp-make-tramp-file-name
8134 (tramp-file-name-method vec)
8135 (tramp-file-name-user vec)
8136 host
8137 (tramp-compat-temporary-file-directory)))
8138 ;; On some systems, chown runs only for root.
8139 (or (zerop (user-uid))
8140 (zerop (tramp-get-remote-uid vec 'integer))))))
8142 ;; Variables local to connection.
8144 ;;;###tramp-autoload
8145 (defun tramp-get-remote-path (vec)
8146 (with-connection-property
8147 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8148 ;; cache the result for the session only. Otherwise, the result
8149 ;; is cached persistently.
8150 (if (memq 'tramp-own-remote-path tramp-remote-path)
8151 (tramp-get-connection-process vec)
8152 vec)
8153 "remote-path"
8154 (let* ((remote-path (copy-tree tramp-remote-path))
8155 (elt1 (memq 'tramp-default-remote-path remote-path))
8156 (elt2 (memq 'tramp-own-remote-path remote-path))
8157 (default-remote-path
8158 (when elt1
8159 (condition-case nil
8160 (tramp-send-command-and-read
8161 vec "echo \\\"`getconf PATH`\\\"")
8162 ;; Default if "getconf" is not available.
8163 (error
8164 (tramp-message
8165 vec 3
8166 "`getconf PATH' not successful, using default value \"%s\"."
8167 "/bin:/usr/bin")
8168 "/bin:/usr/bin"))))
8169 (own-remote-path
8170 (when elt2
8171 (condition-case nil
8172 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8173 ;; Default if "getconf" is not available.
8174 (error
8175 (tramp-message
8176 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8177 nil)))))
8179 ;; Replace place holder `tramp-default-remote-path'.
8180 (when elt1
8181 (setcdr elt1
8182 (append
8183 (tramp-compat-split-string default-remote-path ":")
8184 (cdr elt1)))
8185 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8187 ;; Replace place holder `tramp-own-remote-path'.
8188 (when elt2
8189 (setcdr elt2
8190 (append
8191 (tramp-compat-split-string own-remote-path ":")
8192 (cdr elt2)))
8193 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8195 ;; Remove double entries.
8196 (setq elt1 remote-path)
8197 (while (consp elt1)
8198 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8199 (setcar elt2 nil))
8200 (setq elt1 (cdr elt1)))
8202 ;; Remove non-existing directories.
8203 (delq
8205 (mapcar
8206 (lambda (x)
8207 (and
8208 (stringp x)
8209 (file-directory-p
8210 (tramp-make-tramp-file-name
8211 (tramp-file-name-method vec)
8212 (tramp-file-name-user vec)
8213 (tramp-file-name-host vec)
8216 remote-path)))))
8218 ;;;###tramp-autoload
8219 (defun tramp-get-remote-tmpdir (vec)
8220 (with-connection-property vec "tmp-directory"
8221 (let ((dir (tramp-shell-quote-argument "/tmp")))
8222 (if (and (zerop
8223 (tramp-send-command-and-check
8224 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8225 (zerop
8226 (tramp-send-command-and-check
8227 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8229 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8231 (defun tramp-get-ls-command (vec)
8232 (with-connection-property vec "ls"
8233 (tramp-message vec 5 "Finding a suitable `ls' command")
8235 (catch 'ls-found
8236 (dolist (cmd '("ls" "gnuls" "gls"))
8237 (let ((dl (tramp-get-remote-path vec))
8238 result)
8239 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8240 ;; Check parameters. On busybox, "ls" output coloring is
8241 ;; enabled by default sometimes. So we try to disable it
8242 ;; when possible. $LS_COLORING is not supported there.
8243 ;; Some "ls" versions are sensible wrt the order of
8244 ;; arguments, they fail when "-al" is after the
8245 ;; "--color=never" argument (for example on FreeBSD).
8246 (when (zerop (tramp-send-command-and-check
8247 vec (format "%s -lnd /" result)))
8248 (when (zerop (tramp-send-command-and-check
8249 vec (format
8250 "%s --color=never -al /dev/null" result)))
8251 (setq result (concat result " --color=never")))
8252 (throw 'ls-found result))
8253 (setq dl (cdr dl))))))
8254 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8256 (defun tramp-get-ls-command-with-dired (vec)
8257 (save-match-data
8258 (with-connection-property vec "ls-dired"
8259 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8260 ;; Some "ls" versions are sensible wrt the order of arguments,
8261 ;; they fail when "-al" is after the "--dired" argument (for
8262 ;; example on FreeBSD).
8263 (zerop (tramp-send-command-and-check
8264 vec (format "%s --dired -al /dev/null"
8265 (tramp-get-ls-command vec)))))))
8267 (defun tramp-get-test-command (vec)
8268 (with-connection-property vec "test"
8269 (tramp-message vec 5 "Finding a suitable `test' command")
8270 (if (zerop (tramp-send-command-and-check vec "test 0"))
8271 "test"
8272 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8274 (defun tramp-get-test-nt-command (vec)
8275 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8276 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8277 ;; for otherwise the shell crashes.
8278 (with-connection-property vec "test-nt"
8280 (progn
8281 (tramp-send-command
8282 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8283 (with-current-buffer (tramp-get-buffer vec)
8284 (goto-char (point-min))
8285 (when (looking-at (regexp-quote tramp-end-of-output))
8286 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8287 (progn
8288 (tramp-send-command
8290 (format
8291 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8292 (tramp-get-test-command vec)))
8293 "tramp_test_nt %s %s"))))
8295 (defun tramp-get-file-exists-command (vec)
8296 (with-connection-property vec "file-exists"
8297 (tramp-message vec 5 "Finding command to check if file exists")
8298 (tramp-find-file-exists-command vec)))
8300 ;;;###tramp-autoload
8301 (defun tramp-get-remote-ln (vec)
8302 (with-connection-property vec "ln"
8303 (tramp-message vec 5 "Finding a suitable `ln' command")
8304 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8306 (defun tramp-get-remote-perl (vec)
8307 (with-connection-property vec "perl"
8308 (tramp-message vec 5 "Finding a suitable `perl' command")
8309 (let ((result
8310 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8311 (tramp-find-executable
8312 vec "perl" (tramp-get-remote-path vec)))))
8313 ;; We must check also for some Perl modules.
8314 (when result
8315 (with-connection-property vec "perl-file-spec"
8316 (zerop
8317 (tramp-send-command-and-check
8318 vec (format "%s -e 'use File::Spec;'" result))))
8319 (with-connection-property vec "perl-cwd-realpath"
8320 (zerop
8321 (tramp-send-command-and-check
8322 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8323 result)))
8325 (defun tramp-get-remote-stat (vec)
8326 (with-connection-property vec "stat"
8327 (tramp-message vec 5 "Finding a suitable `stat' command")
8328 (let ((result (tramp-find-executable
8329 vec "stat" (tramp-get-remote-path vec)))
8330 tmp)
8331 ;; Check whether stat(1) returns usable syntax. %s does not
8332 ;; work on older AIX systems.
8333 (when result
8334 (setq tmp
8335 ;; We don't want to display an error message.
8336 (with-temp-message (or (current-message) "")
8337 (condition-case nil
8338 (tramp-send-command-and-read
8339 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8340 (error nil))))
8341 (unless (and (listp tmp) (stringp (car tmp))
8342 (string-match "^./.$" (car tmp))
8343 (integerp (cadr tmp)))
8344 (setq result nil)))
8345 result)))
8347 (defun tramp-get-remote-readlink (vec)
8348 (with-connection-property vec "readlink"
8349 (tramp-message vec 5 "Finding a suitable `readlink' command")
8350 (let ((result (tramp-find-executable
8351 vec "readlink" (tramp-get-remote-path vec))))
8352 (when (and result
8353 ;; We don't want to display an error message.
8354 (with-temp-message (or (current-message) "")
8355 (condition-case nil
8356 (zerop
8357 (tramp-send-command-and-check
8358 vec (format "%s --canonicalize-missing /" result)))
8359 (error nil))))
8360 result))))
8362 (defun tramp-get-remote-trash (vec)
8363 (with-connection-property vec "trash"
8364 (tramp-message vec 5 "Finding a suitable `trash' command")
8365 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
8367 (defun tramp-get-remote-id (vec)
8368 (with-connection-property vec "id"
8369 (tramp-message vec 5 "Finding POSIX `id' command")
8371 (catch 'id-found
8372 (let ((dl (tramp-get-remote-path vec))
8373 result)
8374 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8375 ;; Check POSIX parameter.
8376 (when (zerop (tramp-send-command-and-check
8377 vec (format "%s -u" result)))
8378 (throw 'id-found result))
8379 (setq dl (cdr dl)))))
8380 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8382 (defun tramp-get-remote-uid (vec id-format)
8383 (with-connection-property vec (format "uid-%s" id-format)
8384 (let ((res (tramp-send-command-and-read
8386 (format "%s -u%s %s"
8387 (tramp-get-remote-id vec)
8388 (if (equal id-format 'integer) "" "n")
8389 (if (equal id-format 'integer)
8390 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8391 ;; The command might not always return a number.
8392 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8394 (defun tramp-get-remote-gid (vec id-format)
8395 (with-connection-property vec (format "gid-%s" id-format)
8396 (let ((res (tramp-send-command-and-read
8398 (format "%s -g%s %s"
8399 (tramp-get-remote-id vec)
8400 (if (equal id-format 'integer) "" "n")
8401 (if (equal id-format 'integer)
8402 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8403 ;; The command might not always return a number.
8404 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8406 (defun tramp-get-local-uid (id-format)
8407 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8409 (defun tramp-get-local-gid (id-format)
8410 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8412 ;; Some predefined connection properties.
8413 (defun tramp-get-inline-compress (vec prop size)
8414 "Return the compress command related to PROP.
8415 PROP is either `inline-compress' or `inline-decompress'. SIZE is
8416 the length of the file to be compressed.
8418 If no corresponding command is found, nil is returned."
8419 (when (and (integerp tramp-inline-compress-start-size)
8420 (> size tramp-inline-compress-start-size))
8421 (with-connection-property vec prop
8422 (tramp-find-inline-compress vec)
8423 (tramp-get-connection-property vec prop nil))))
8425 (defun tramp-get-inline-coding (vec prop size)
8426 "Return the coding command related to PROP.
8427 PROP is either `remote-encoding', `remode-decoding',
8428 `local-encoding' or `local-decoding'.
8430 SIZE is the length of the file to be coded. Depending on SIZE,
8431 compression might be applied.
8433 If no corresponding command is found, nil is returned.
8434 Otherwise, either a string is returned which contains a `%s' mark
8435 to be used for the respective input or output file; or a Lisp
8436 function cell is returned to be applied on a buffer."
8437 (let ((coding
8438 (with-connection-property vec prop
8439 (tramp-find-inline-encoding vec)
8440 (tramp-get-connection-property vec prop nil)))
8441 (prop1 (if (string-match "encoding" prop)
8442 "inline-compress" "inline-decompress"))
8443 compress)
8444 ;; The connection property might have been cached. So we must send
8445 ;; the script to the remote side - maybe.
8446 (when (and coding (symbolp coding) (string-match "remote" prop))
8447 (let ((name (symbol-name coding)))
8448 (while (string-match (regexp-quote "-") name)
8449 (setq name (replace-match "_" nil t name)))
8450 (tramp-maybe-send-script vec (symbol-value coding) name)
8451 (setq coding name)))
8452 (when coding
8453 ;; Check for the `compress' command.
8454 (setq compress (tramp-get-inline-compress vec prop1 size))
8455 ;; Return the value.
8456 (cond
8457 ((and compress (symbolp coding))
8458 (if (string-match "decompress" prop1)
8459 `(lambda (beg end)
8460 (,coding beg end)
8461 (let ((coding-system-for-write 'binary)
8462 (coding-system-for-read 'binary))
8463 (apply
8464 'call-process-region (point-min) (point-max)
8465 (car (split-string ,compress)) t t nil
8466 (cdr (split-string ,compress)))))
8467 `(lambda (beg end)
8468 (let ((coding-system-for-write 'binary)
8469 (coding-system-for-read 'binary))
8470 (apply
8471 'call-process-region beg end
8472 (car (split-string ,compress)) t t nil
8473 (cdr (split-string ,compress))))
8474 (,coding (point-min) (point-max)))))
8475 ((symbolp coding)
8476 coding)
8477 ((and compress (string-match "decoding" prop))
8478 (format "(%s | %s >%%s)" coding compress))
8479 (compress
8480 (format "(%s <%%s | %s)" compress coding))
8481 ((string-match "decoding" prop)
8482 (format "%s >%%s" coding))
8484 (format "%s <%%s" coding))))))
8486 (defun tramp-get-method-parameter (method param)
8487 "Return the method parameter PARAM.
8488 If the `tramp-methods' entry does not exist, return nil."
8489 (let ((entry (assoc param (assoc method tramp-methods))))
8490 (when entry (cadr entry))))
8492 ;; Auto saving to a special directory.
8494 (defun tramp-exists-file-name-handler (operation &rest args)
8495 "Check, whether OPERATION runs a file name handler."
8496 ;; The file name handler is determined on base of either an
8497 ;; argument, `buffer-file-name', or `default-directory'.
8498 (condition-case nil
8499 (let* ((buffer-file-name "/")
8500 (default-directory "/")
8501 (fnha file-name-handler-alist)
8502 (check-file-name-operation operation)
8503 (file-name-handler-alist
8504 (list
8505 (cons "/"
8506 (lambda (operation &rest args)
8507 "Returns OPERATION if it is the one to be checked."
8508 (if (equal check-file-name-operation operation)
8509 operation
8510 (let ((file-name-handler-alist fnha))
8511 (apply operation args))))))))
8512 (equal (apply operation args) operation))
8513 (error nil)))
8515 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8516 (defadvice make-auto-save-file-name
8517 (around tramp-advice-make-auto-save-file-name () activate)
8518 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8519 (if (tramp-tramp-file-p (buffer-file-name))
8520 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8521 ;; directly, because this would bypass the locking mechanism.
8522 (setq ad-return-value
8523 (tramp-file-name-handler 'make-auto-save-file-name))
8524 ad-do-it))
8525 (add-hook
8526 'tramp-unload-hook
8527 (lambda ()
8528 (ad-remove-advice
8529 'make-auto-save-file-name
8530 'around 'tramp-advice-make-auto-save-file-name)
8531 (ad-activate 'make-auto-save-file-name))))
8533 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8534 ;; umask. This is a security threat.
8536 (defun tramp-set-auto-save-file-modes ()
8537 "Set permissions of autosaved remote files to the original permissions."
8538 (let ((bfn (buffer-file-name)))
8539 (when (and (tramp-tramp-file-p bfn)
8540 (buffer-modified-p)
8541 (stringp buffer-auto-save-file-name)
8542 (not (equal bfn buffer-auto-save-file-name)))
8543 (unless (file-exists-p buffer-auto-save-file-name)
8544 (write-region "" nil buffer-auto-save-file-name))
8545 ;; Permissions should be set always, because there might be an old
8546 ;; auto-saved file belonging to another original file. This could
8547 ;; be a security threat.
8548 (set-file-modes
8549 buffer-auto-save-file-name
8550 (or (file-modes bfn) (tramp-compat-octal-to-decimal "0600"))))))
8552 (unless (and (featurep 'xemacs)
8553 (= emacs-major-version 21)
8554 (> emacs-minor-version 4))
8555 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8556 (add-hook 'tramp-unload-hook
8557 (lambda ()
8558 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8560 (defun tramp-subst-strs-in-string (alist string)
8561 "Replace all occurrences of the string FROM with TO in STRING.
8562 ALIST is of the form ((FROM . TO) ...)."
8563 (save-match-data
8564 (while alist
8565 (let* ((pr (car alist))
8566 (from (car pr))
8567 (to (cdr pr)))
8568 (while (string-match (regexp-quote from) string)
8569 (setq string (replace-match to t t string)))
8570 (setq alist (cdr alist))))
8571 string))
8573 ;; ------------------------------------------------------------
8574 ;; -- Compatibility functions section --
8575 ;; ------------------------------------------------------------
8577 (defun tramp-read-passwd (proc &optional prompt)
8578 "Read a password from user (compat function).
8579 Consults the auth-source package.
8580 Invokes `password-read' if available, `read-passwd' else."
8581 (let* ((key (tramp-make-tramp-file-name
8582 tramp-current-method tramp-current-user
8583 tramp-current-host ""))
8584 (pw-prompt
8585 (or prompt
8586 (with-current-buffer (process-buffer proc)
8587 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8588 (format "%s for %s " (capitalize (match-string 1)) key)))))
8589 (with-parsed-tramp-file-name key nil
8590 (prog1
8592 ;; See if auth-sources contains something useful, if it's bound.
8593 (and (boundp 'auth-sources)
8594 (tramp-get-connection-property v "first-password-request" nil)
8595 ;; Try with Tramp's current method.
8596 (tramp-compat-funcall
8597 'auth-source-user-or-password
8598 "password" tramp-current-host tramp-current-method))
8599 ;; Try the password cache.
8600 (when (functionp 'password-read)
8601 (unless (tramp-get-connection-property
8602 v "first-password-request" nil)
8603 (tramp-compat-funcall 'password-cache-remove key))
8604 (let ((password
8605 (tramp-compat-funcall 'password-read pw-prompt key)))
8606 (tramp-compat-funcall 'password-cache-add key password)
8607 password))
8608 ;; Else, get the password interactively.
8609 (read-passwd pw-prompt))
8610 (tramp-set-connection-property v "first-password-request" nil)))))
8612 (defun tramp-clear-passwd (vec)
8613 "Clear password cache for connection related to VEC."
8614 (tramp-compat-funcall
8615 'password-cache-remove
8616 (tramp-make-tramp-file-name
8617 (tramp-file-name-method vec)
8618 (tramp-file-name-user vec)
8619 (tramp-file-name-host vec)
8620 "")))
8622 ;; Snarfed code from time-date.el and parse-time.el
8624 (defconst tramp-half-a-year '(241 17024)
8625 "Evaluated by \"(days-to-time 183)\".")
8627 (defconst tramp-parse-time-months
8628 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8629 ("apr" . 4) ("may" . 5) ("jun" . 6)
8630 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8631 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8632 "Alist mapping month names to integers.")
8634 (defun tramp-time-less-p (t1 t2)
8635 "Say whether time value T1 is less than time value T2."
8636 (unless t1 (setq t1 '(0 0)))
8637 (unless t2 (setq t2 '(0 0)))
8638 (or (< (car t1) (car t2))
8639 (and (= (car t1) (car t2))
8640 (< (nth 1 t1) (nth 1 t2)))))
8642 (defun tramp-time-subtract (t1 t2)
8643 "Subtract two time values.
8644 Return the difference in the format of a time value."
8645 (unless t1 (setq t1 '(0 0)))
8646 (unless t2 (setq t2 '(0 0)))
8647 (let ((borrow (< (cadr t1) (cadr t2))))
8648 (list (- (car t1) (car t2) (if borrow 1 0))
8649 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8651 (defun tramp-time-diff (t1 t2)
8652 "Return the difference between the two times, in seconds.
8653 T1 and T2 are time values (as returned by `current-time' for example)."
8654 (cond ((and (fboundp 'subtract-time)
8655 (fboundp 'float-time))
8656 (tramp-compat-funcall
8657 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
8658 ((and (fboundp 'subtract-time)
8659 (fboundp 'time-to-seconds))
8660 (tramp-compat-funcall
8661 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
8662 ((fboundp 'itimer-time-difference)
8663 (tramp-compat-funcall
8664 'itimer-time-difference
8665 (if (< (length t1) 3) (append t1 '(0)) t1)
8666 (if (< (length t2) 3) (append t2 '(0)) t2)))
8668 (let ((time (tramp-time-subtract t1 t2)))
8669 (+ (* (car time) 65536.0)
8670 (cadr time)
8671 (/ (or (nth 2 time) 0) 1000000.0))))))
8673 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8674 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8675 EOL-TYPE can be one of `dos', `unix', or `mac'."
8676 (cond ((fboundp 'coding-system-change-eol-conversion)
8677 (tramp-compat-funcall
8678 'coding-system-change-eol-conversion coding-system eol-type))
8679 ((fboundp 'subsidiary-coding-system)
8680 (tramp-compat-funcall
8681 'subsidiary-coding-system coding-system
8682 (cond ((eq eol-type 'dos) 'crlf)
8683 ((eq eol-type 'unix) 'lf)
8684 ((eq eol-type 'mac) 'cr)
8686 (error "Unknown EOL-TYPE `%s', must be %s"
8687 eol-type
8688 "`dos', `unix', or `mac'")))))
8689 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8691 (defun tramp-set-process-query-on-exit-flag (process flag)
8692 "Specify if query is needed for process when Emacs is exited.
8693 If the second argument flag is non-nil, Emacs will query the user before
8694 exiting if process is running."
8695 (if (fboundp 'set-process-query-on-exit-flag)
8696 (tramp-compat-funcall 'set-process-query-on-exit-flag process flag)
8697 (tramp-compat-funcall 'process-kill-without-query process flag)))
8700 ;; ------------------------------------------------------------
8701 ;; -- Kludges section --
8702 ;; ------------------------------------------------------------
8704 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8705 ;; does not deal well with newline characters. Newline is replaced by
8706 ;; backslash newline. But if, say, the string `a backslash newline b'
8707 ;; is passed to a shell, the shell will expand this into "ab",
8708 ;; completely omitting the newline. This is not what was intended.
8709 ;; It does not appear to be possible to make the function
8710 ;; `shell-quote-argument' work with newlines without making it
8711 ;; dependent on the shell used. But within this package, we know that
8712 ;; we will always use a Bourne-like shell, so we use an approach which
8713 ;; groks newlines.
8715 ;; The approach is simple: we call `shell-quote-argument', then
8716 ;; massage the newline part of the result.
8718 ;; This function should produce a string which is grokked by a Unix
8719 ;; shell, even if the Emacs is running on Windows. Since this is the
8720 ;; kludges section, we bind `system-type' in such a way that
8721 ;; `shell-quote-arguments' behaves as if on Unix.
8723 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8724 ;; function to work with Bourne-like shells.
8726 ;; CCC: This function should be rewritten so that
8727 ;; `shell-quote-argument' is not used. This way, we are safe from
8728 ;; changes in `shell-quote-argument'.
8729 ;;;###tramp-autoload
8730 (defun tramp-shell-quote-argument (s)
8731 "Similar to `shell-quote-argument', but groks newlines.
8732 Only works for Bourne-like shells."
8733 (let ((system-type 'not-windows))
8734 (save-match-data
8735 (let ((result (shell-quote-argument s))
8736 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8737 (when (and (>= (length result) 2)
8738 (string= (substring result 0 2) "\\~"))
8739 (setq result (substring result 1)))
8740 (while (string-match nl result)
8741 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8742 t t result)))
8743 result))))
8745 ;; Checklist for `tramp-unload-hook'
8746 ;; - Unload all `tramp-*' packages
8747 ;; - Reset `file-name-handler-alist'
8748 ;; - Cleanup hooks where Tramp functions are in
8749 ;; - Cleanup advised functions
8750 ;; - Cleanup autoloads
8751 ;;;###autoload
8752 (defun tramp-unload-tramp ()
8753 "Discard Tramp from loading remote files."
8754 (interactive)
8755 ;; ange-ftp settings must be enabled.
8756 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
8757 ;; Maybe it's not loaded yet.
8758 (condition-case nil
8759 (unload-feature 'tramp 'force)
8760 (error nil)))
8762 (when (and load-in-progress
8763 (string-match "Loading tramp..." (or (current-message) "")))
8764 (message "Loading tramp...done"))
8766 (provide 'tramp)
8768 ;;; TODO:
8770 ;; * Handle nonlocal exits such as C-g.
8771 ;; * But it would probably be better to use with-local-quit at the
8772 ;; place where it's actually needed: around any potentially
8773 ;; indefinitely blocking piece of code. In this case it would be
8774 ;; within Tramp around one of its calls to accept-process-output (or
8775 ;; around one of the loops that calls accept-process-output)
8776 ;; (Stefan Monnier).
8777 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8778 ;; `shell-quote-argument'.
8779 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8780 ;; by the files in that directory. Add this here.
8781 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8782 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8783 ;; * Don't use globbing for directories with many files, as this is
8784 ;; likely to produce long command lines, and some shells choke on
8785 ;; long command lines.
8786 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8787 ;; * abbreviate-file-name
8788 ;; * Better error checking. At least whenever we see something
8789 ;; strange when doing zerop, we should kill the process and start
8790 ;; again. (Greg Stark)
8791 ;; * Remove unneeded parameters from methods.
8792 ;; * Make it work for different encodings, and for different file name
8793 ;; encodings, too. (Daniel Pittman)
8794 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8795 ;; then look if it's the right version (with `perl -v').
8796 ;; * When editing a remote CVS controlled file as a different user, VC
8797 ;; gets confused about the file locking status. Try to find out why
8798 ;; the workaround doesn't work.
8799 ;; * Username and hostname completion.
8800 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8801 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8802 ;; Code is nearly identical.
8803 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8804 ;; until the last but one hop via `start-file-process'. Apply it
8805 ;; also for ftp and smb.
8806 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8807 ;; some shell with root priviledges, it would be nice if I could
8808 ;; just call
8809 ;; trampclient filename.c
8810 ;; as an editor, and the _current_ shell would connect to an Emacs
8811 ;; server and would be used in an existing non-priviledged Emacs
8812 ;; session for doing the editing in question.
8813 ;; That way, I need not tell Emacs my password again and be afraid
8814 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8815 ;; once display a just typed password in the context of a keyboard
8816 ;; sequence prompt for a question immediately following in a shell
8817 ;; script run within Emacs -- nasty).
8818 ;; And if I have some ssh session running to a different computer,
8819 ;; having the possibility of passing a local file there to a local
8820 ;; Emacs session (in case I can arrange for a connection back) would
8821 ;; be nice.
8822 ;; Likely the corresponding Tramp server should not allow the
8823 ;; equivalent of the emacsclient -eval option in order to make this
8824 ;; reasonably unproblematic. And maybe trampclient should have some
8825 ;; way of passing credentials, like by using an SSL socket or
8826 ;; something. (David Kastrup)
8827 ;; * Reconnect directly to a compliant shell without first going
8828 ;; through the user's default shell. (Pete Forman)
8829 ;; * Make `tramp-default-user' obsolete.
8830 ;; * How can I interrupt the remote process with a signal
8831 ;; (interrupt-process seems not to work)? (Markus Triska)
8832 ;; * Avoid the local shell entirely for starting remote processes. If
8833 ;; so, I think even a signal, when delivered directly to the local
8834 ;; SSH instance, would correctly be propagated to the remote process
8835 ;; automatically; possibly SSH would have to be started with
8836 ;; "-t". (Markus Triska)
8837 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8838 ;; isn't on the remote host. (Mark A. Hershberger)
8839 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8840 ;; * Implement a general server-local-variable mechanism, as there are
8841 ;; probably other variables that need different values for different
8842 ;; servers too. The user could then configure a variable (such as
8843 ;; tramp-server-local-variable-alist) to define any such variables
8844 ;; that they need to, which would then be let bound as appropriate
8845 ;; in tramp functions. (Jason Rumney)
8846 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8847 ;; rsync).
8848 ;; * Keep a second connection open for out-of-band methods like scp or
8849 ;; rsync.
8850 ;; * IMHO, it's a drawback that currently Tramp doesn't support
8851 ;; Unicode in Dired file names by default. Is it possible to
8852 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8853 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
8854 ;; expects only English messages? (Juri Linkov)
8855 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8856 ;; * Try telnet+curl as new method. It might be useful for busybox,
8857 ;; without built-in uuencode/uudecode.
8858 ;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
8859 ;; * I was wondering it it would be possible to use tramp even if I'm
8860 ;; actually using sshfs. But when I launch a command I would like
8861 ;; to get it executed on the remote machine where the files really
8862 ;; are. (Andrea Crotti)
8863 ;; * Run emerge on two remote files. Bug is described here:
8864 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
8865 ;; (Bug#6850)
8867 ;; Functions for file-name-handler-alist:
8868 ;; diff-latest-backup-file -- in diff.el
8870 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8871 ;;; tramp.el ends here
8873 ;; Local Variables:
8874 ;; mode: Emacs-Lisp
8875 ;; coding: utf-8
8876 ;; End: