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