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