Fix some stuff that didn't compile.
[bpt/emacs.git] / 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, 2010 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 22.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)
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 (tramp-compat-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 :group 'comm
180 :version "22.1")
181
182 ;; Maybe we need once a real Tramp mode, with key bindings etc.
183 ;;;###autoload
184 (defcustom tramp-mode t
185 "*Whether Tramp is enabled.
186 If it is set to nil, all remote file names are used literally."
187 :group 'tramp
188 :type 'boolean)
189
190 (defcustom tramp-verbose 3
191 "*Verbosity level for Tramp messages.
192 Any level x includes messages for all levels 1 .. x-1. The levels are
193
194 0 silent (no tramp messages at all)
195 1 errors
196 2 warnings
197 3 connection to remote hosts (default level)
198 4 activities
199 5 internal
200 6 sent and received strings
201 7 file caching
202 8 connection properties
203 9 test commands
204 10 traces (huge)."
205 :group 'tramp
206 :type 'integer)
207
208 ;; Emacs case.
209 (eval-and-compile
210 (when (boundp 'backup-directory-alist)
211 (defcustom tramp-backup-directory-alist nil
212 "Alist of filename patterns and backup directory names.
213 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
214 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
215 is a local file name, the backup directory is prepended with Tramp file
216 name prefix \(method, user, host\) of file.
217
218 \(setq tramp-backup-directory-alist backup-directory-alist\)
219
220 gives the same backup policy for Tramp files on their hosts like the
221 policy for local files."
222 :group 'tramp
223 :type '(repeat (cons (regexp :tag "Regexp matching filename")
224 (directory :tag "Backup directory name"))))))
225
226 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
227 ;; the package "backup-dir" might not be loaded yet.
228 (eval-and-compile
229 (when (featurep 'xemacs)
230 (defcustom tramp-bkup-backup-directory-info nil
231 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
232 It has the same meaning like `bkup-backup-directory-info' from package
233 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
234 file name, the backup directory is prepended with Tramp file name prefix
235 \(method, user, host\) of file.
236
237 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
238
239 gives the same backup policy for Tramp files on their hosts like the
240 policy for local files."
241 :type '(repeat
242 (list (regexp :tag "File regexp")
243 (string :tag "Backup Dir")
244 (set :inline t
245 (const ok-create)
246 (const full-path)
247 (const prepend-name)
248 (const search-upward))))
249 :group 'tramp)))
250
251 (defcustom tramp-auto-save-directory nil
252 "*Put auto-save files in this directory, if set.
253 The idea is to use a local directory so that auto-saving is faster."
254 :group 'tramp
255 :type '(choice (const nil) string))
256
257 (defcustom tramp-encoding-shell
258 (if (memq system-type '(windows-nt))
259 (getenv "COMSPEC")
260 "/bin/sh")
261 "*Use this program for encoding and decoding commands on the local host.
262 This shell is used to execute the encoding and decoding command on the
263 local host, so if you want to use `~' in those commands, you should
264 choose a shell here which groks tilde expansion. `/bin/sh' normally
265 does not understand tilde expansion.
266
267 For encoding and deocding, commands like the following are executed:
268
269 /bin/sh -c COMMAND < INPUT > OUTPUT
270
271 This variable can be used to change the \"/bin/sh\" part. See the
272 variable `tramp-encoding-command-switch' for the \"-c\" part.
273
274 Note that this variable is not used for remote commands. There are
275 mechanisms in tramp.el which automatically determine the right shell to
276 use for the remote host."
277 :group 'tramp
278 :type '(file :must-match t))
279
280 (defcustom tramp-encoding-command-switch
281 (if (string-match "cmd\\.exe" tramp-encoding-shell)
282 "/c"
283 "-c")
284 "*Use this switch together with `tramp-encoding-shell' for local commands.
285 See the variable `tramp-encoding-shell' for more information."
286 :group 'tramp
287 :type 'string)
288
289 (defcustom tramp-inline-compress-start-size 4096
290 "*The minimum size of compressing where inline transfer.
291 When inline transfer, compress transfered data of file
292 whose size is this value or above (up to `tramp-copy-size-limit').
293 If it is nil, no compression at all will be applied."
294 :group 'tramp
295 :type '(choice (const nil) integer))
296
297 (defcustom tramp-copy-size-limit 10240
298 "*The maximum file size where inline copying is preferred over an out-of-the-band copy.
299 If it is nil, inline out-of-the-band copy will be used without a check."
300 :group 'tramp
301 :type '(choice (const nil) integer))
302
303 (defcustom tramp-terminal-type "dumb"
304 "*Value of TERM environment variable for logging in to remote host.
305 Because Tramp wants to parse the output of the remote shell, it is easily
306 confused by ANSI color escape sequences and suchlike. Often, shell init
307 files conditionalize this setup based on the TERM environment variable."
308 :group 'tramp
309 :type 'string)
310
311 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
312 ;; root users. It uses the `$' character for other users. In order
313 ;; to guarantee a proper prompt, we use "#$" for the prompt.
314
315 (defvar tramp-end-of-output
316 (format
317 "///%s#$"
318 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
319 "String used to recognize end of output.
320 The '$' character at the end is quoted; the string cannot be
321 detected as prompt when being sent on echoing hosts, therefore.")
322
323 (defconst tramp-initial-end-of-output "#$ "
324 "Prompt when establishing a connection.")
325
326 (defvar tramp-methods
327 `(("rcp" (tramp-login-program "rsh")
328 (tramp-login-args (("%h") ("-l" "%u")))
329 (tramp-remote-sh "/bin/sh")
330 (tramp-copy-program "rcp")
331 (tramp-copy-args (("-p" "%k") ("-r")))
332 (tramp-copy-keep-date t)
333 (tramp-copy-recursive t)
334 (tramp-password-end-of-line nil))
335 ("scp" (tramp-login-program "ssh")
336 (tramp-login-args (("-l" "%u") ("-p" "%p")
337 ("-e" "none") ("%h")))
338 (tramp-async-args (("-q")))
339 (tramp-remote-sh "/bin/sh")
340 (tramp-copy-program "scp")
341 (tramp-copy-args (("-P" "%p") ("-p" "%k")
342 ("-q") ("-r")))
343 (tramp-copy-keep-date t)
344 (tramp-copy-recursive t)
345 (tramp-password-end-of-line nil)
346 (tramp-gw-args (("-o"
347 "GlobalKnownHostsFile=/dev/null")
348 ("-o" "UserKnownHostsFile=/dev/null")
349 ("-o" "StrictHostKeyChecking=no")))
350 (tramp-default-port 22))
351 ("scp1" (tramp-login-program "ssh")
352 (tramp-login-args (("-l" "%u") ("-p" "%p")
353 ("-1") ("-e" "none") ("%h")))
354 (tramp-async-args (("-q")))
355 (tramp-remote-sh "/bin/sh")
356 (tramp-copy-program "scp")
357 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
358 ("-q") ("-r")))
359 (tramp-copy-keep-date t)
360 (tramp-copy-recursive t)
361 (tramp-password-end-of-line nil)
362 (tramp-gw-args (("-o"
363 "GlobalKnownHostsFile=/dev/null")
364 ("-o" "UserKnownHostsFile=/dev/null")
365 ("-o" "StrictHostKeyChecking=no")))
366 (tramp-default-port 22))
367 ("scp2" (tramp-login-program "ssh")
368 (tramp-login-args (("-l" "%u") ("-p" "%p")
369 ("-2") ("-e" "none") ("%h")))
370 (tramp-async-args (("-q")))
371 (tramp-remote-sh "/bin/sh")
372 (tramp-copy-program "scp")
373 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
374 ("-q") ("-r")))
375 (tramp-copy-keep-date t)
376 (tramp-copy-recursive t)
377 (tramp-password-end-of-line nil)
378 (tramp-gw-args (("-o"
379 "GlobalKnownHostsFile=/dev/null")
380 ("-o" "UserKnownHostsFile=/dev/null")
381 ("-o" "StrictHostKeyChecking=no")))
382 (tramp-default-port 22))
383 ("scp1_old"
384 (tramp-login-program "ssh1")
385 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
386 ("-e" "none")))
387 (tramp-remote-sh "/bin/sh")
388 (tramp-copy-program "scp1")
389 (tramp-copy-args (("-p" "%k") ("-r")))
390 (tramp-copy-keep-date t)
391 (tramp-copy-recursive t)
392 (tramp-password-end-of-line nil))
393 ("scp2_old"
394 (tramp-login-program "ssh2")
395 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
396 ("-e" "none")))
397 (tramp-remote-sh "/bin/sh")
398 (tramp-copy-program "scp2")
399 (tramp-copy-args (("-p" "%k") ("-r")))
400 (tramp-copy-keep-date t)
401 (tramp-copy-recursive t)
402 (tramp-password-end-of-line nil))
403 ("sftp" (tramp-login-program "ssh")
404 (tramp-login-args (("-l" "%u") ("-p" "%p")
405 ("-e" "none") ("%h")))
406 (tramp-async-args (("-q")))
407 (tramp-remote-sh "/bin/sh")
408 (tramp-copy-program "sftp")
409 (tramp-copy-args nil)
410 (tramp-copy-keep-date nil)
411 (tramp-password-end-of-line nil))
412 ("rsync" (tramp-login-program "ssh")
413 (tramp-login-args (("-l" "%u") ("-p" "%p")
414 ("-e" "none") ("%h")))
415 (tramp-async-args (("-q")))
416 (tramp-remote-sh "/bin/sh")
417 (tramp-copy-program "rsync")
418 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
419 (tramp-copy-keep-date t)
420 (tramp-copy-keep-tmpfile t)
421 (tramp-copy-recursive t)
422 (tramp-password-end-of-line nil))
423 ("rsyncc"
424 (tramp-login-program "ssh")
425 (tramp-login-args (("-l" "%u") ("-p" "%p")
426 ("-o" "ControlPath=%t.%%r@%%h:%%p")
427 ("-o" "ControlMaster=yes")
428 ("-e" "none") ("%h")))
429 (tramp-async-args (("-q")))
430 (tramp-remote-sh "/bin/sh")
431 (tramp-copy-program "rsync")
432 (tramp-copy-args (("-t" "%k") ("-r")))
433 (tramp-copy-env (("RSYNC_RSH")
434 (,(concat
435 "ssh"
436 " -o ControlPath=%t.%%r@%%h:%%p"
437 " -o ControlMaster=auto"))))
438 (tramp-copy-keep-date t)
439 (tramp-copy-keep-tmpfile t)
440 (tramp-copy-recursive t)
441 (tramp-password-end-of-line nil))
442 ("remcp" (tramp-login-program "remsh")
443 (tramp-login-args (("%h") ("-l" "%u")))
444 (tramp-remote-sh "/bin/sh")
445 (tramp-copy-program "rcp")
446 (tramp-copy-args (("-p" "%k")))
447 (tramp-copy-keep-date t)
448 (tramp-password-end-of-line nil))
449 ("rsh" (tramp-login-program "rsh")
450 (tramp-login-args (("%h") ("-l" "%u")))
451 (tramp-remote-sh "/bin/sh")
452 (tramp-copy-program nil)
453 (tramp-copy-args nil)
454 (tramp-copy-keep-date nil)
455 (tramp-password-end-of-line nil))
456 ("ssh" (tramp-login-program "ssh")
457 (tramp-login-args (("-l" "%u") ("-p" "%p")
458 ("-e" "none") ("%h")))
459 (tramp-async-args (("-q")))
460 (tramp-remote-sh "/bin/sh")
461 (tramp-copy-program nil)
462 (tramp-copy-args nil)
463 (tramp-copy-keep-date nil)
464 (tramp-password-end-of-line nil)
465 (tramp-gw-args (("-o"
466 "GlobalKnownHostsFile=/dev/null")
467 ("-o" "UserKnownHostsFile=/dev/null")
468 ("-o" "StrictHostKeyChecking=no")))
469 (tramp-default-port 22))
470 ("ssh1" (tramp-login-program "ssh")
471 (tramp-login-args (("-l" "%u") ("-p" "%p")
472 ("-1") ("-e" "none") ("%h")))
473 (tramp-async-args (("-q")))
474 (tramp-remote-sh "/bin/sh")
475 (tramp-copy-program nil)
476 (tramp-copy-args nil)
477 (tramp-copy-keep-date nil)
478 (tramp-password-end-of-line nil)
479 (tramp-gw-args (("-o"
480 "GlobalKnownHostsFile=/dev/null")
481 ("-o" "UserKnownHostsFile=/dev/null")
482 ("-o" "StrictHostKeyChecking=no")))
483 (tramp-default-port 22))
484 ("ssh2" (tramp-login-program "ssh")
485 (tramp-login-args (("-l" "%u") ("-p" "%p")
486 ("-2") ("-e" "none") ("%h")))
487 (tramp-async-args (("-q")))
488 (tramp-remote-sh "/bin/sh")
489 (tramp-copy-program nil)
490 (tramp-copy-args nil)
491 (tramp-copy-keep-date nil)
492 (tramp-password-end-of-line nil)
493 (tramp-gw-args (("-o"
494 "GlobalKnownHostsFile=/dev/null")
495 ("-o" "UserKnownHostsFile=/dev/null")
496 ("-o" "StrictHostKeyChecking=no")))
497 (tramp-default-port 22))
498 ("ssh1_old"
499 (tramp-login-program "ssh1")
500 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
501 ("-e" "none")))
502 (tramp-async-args (("-q")))
503 (tramp-remote-sh "/bin/sh")
504 (tramp-copy-program nil)
505 (tramp-copy-args nil)
506 (tramp-copy-keep-date nil)
507 (tramp-password-end-of-line nil))
508 ("ssh2_old"
509 (tramp-login-program "ssh2")
510 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
511 ("-e" "none")))
512 (tramp-remote-sh "/bin/sh")
513 (tramp-copy-program nil)
514 (tramp-copy-args nil)
515 (tramp-copy-keep-date nil)
516 (tramp-password-end-of-line nil))
517 ("remsh" (tramp-login-program "remsh")
518 (tramp-login-args (("%h") ("-l" "%u")))
519 (tramp-remote-sh "/bin/sh")
520 (tramp-copy-program nil)
521 (tramp-copy-args nil)
522 (tramp-copy-keep-date nil)
523 (tramp-password-end-of-line nil))
524 ("telnet"
525 (tramp-login-program "telnet")
526 (tramp-login-args (("%h") ("%p")))
527 (tramp-remote-sh "/bin/sh")
528 (tramp-copy-program nil)
529 (tramp-copy-args nil)
530 (tramp-copy-keep-date nil)
531 (tramp-password-end-of-line nil)
532 (tramp-default-port 23))
533 ("su" (tramp-login-program "su")
534 (tramp-login-args (("-") ("%u")))
535 (tramp-remote-sh "/bin/sh")
536 (tramp-copy-program nil)
537 (tramp-copy-args nil)
538 (tramp-copy-keep-date nil)
539 (tramp-password-end-of-line nil))
540 ("sudo" (tramp-login-program "sudo")
541 (tramp-login-args (("-u" "%u")
542 ("-s") ("-H") ("-p" "Password:")))
543 (tramp-remote-sh "/bin/sh")
544 (tramp-copy-program nil)
545 (tramp-copy-args nil)
546 (tramp-copy-keep-date nil)
547 (tramp-password-end-of-line nil))
548 ("scpc" (tramp-login-program "ssh")
549 (tramp-login-args (("-l" "%u") ("-p" "%p")
550 ("-o" "ControlPath=%t.%%r@%%h:%%p")
551 ("-o" "ControlMaster=yes")
552 ("-e" "none") ("%h")))
553 (tramp-async-args (("-q")))
554 (tramp-remote-sh "/bin/sh")
555 (tramp-copy-program "scp")
556 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
557 ("-o" "ControlPath=%t.%%r@%%h:%%p")
558 ("-o" "ControlMaster=auto")))
559 (tramp-copy-keep-date t)
560 (tramp-password-end-of-line nil)
561 (tramp-gw-args (("-o"
562 "GlobalKnownHostsFile=/dev/null")
563 ("-o" "UserKnownHostsFile=/dev/null")
564 ("-o" "StrictHostKeyChecking=no")))
565 (tramp-default-port 22))
566 ("scpx" (tramp-login-program "ssh")
567 (tramp-login-args (("-l" "%u") ("-p" "%p")
568 ("-e" "none") ("-t" "-t")
569 ("%h") ("/bin/sh")))
570 (tramp-async-args (("-q")))
571 (tramp-remote-sh "/bin/sh")
572 (tramp-copy-program "scp")
573 (tramp-copy-args (("-p" "%k")))
574 (tramp-copy-keep-date t)
575 (tramp-password-end-of-line nil)
576 (tramp-gw-args (("-o"
577 "GlobalKnownHostsFile=/dev/null")
578 ("-o" "UserKnownHostsFile=/dev/null")
579 ("-o" "StrictHostKeyChecking=no")))
580 (tramp-default-port 22))
581 ("sshx" (tramp-login-program "ssh")
582 (tramp-login-args (("-l" "%u") ("-p" "%p")
583 ("-e" "none") ("-t" "-t")
584 ("%h") ("/bin/sh")))
585 (tramp-async-args (("-q")))
586 (tramp-remote-sh "/bin/sh")
587 (tramp-copy-program nil)
588 (tramp-copy-args nil)
589 (tramp-copy-keep-date nil)
590 (tramp-password-end-of-line nil)
591 (tramp-gw-args (("-o"
592 "GlobalKnownHostsFile=/dev/null")
593 ("-o" "UserKnownHostsFile=/dev/null")
594 ("-o" "StrictHostKeyChecking=no")))
595 (tramp-default-port 22))
596 ("krlogin"
597 (tramp-login-program "krlogin")
598 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
599 (tramp-remote-sh "/bin/sh")
600 (tramp-copy-program nil)
601 (tramp-copy-args nil)
602 (tramp-copy-keep-date nil)
603 (tramp-password-end-of-line nil))
604 ("plink" (tramp-login-program "plink")
605 (tramp-login-args (("-l" "%u") ("-P" "%p")
606 ("-ssh") ("%h")))
607 (tramp-remote-sh "/bin/sh")
608 (tramp-copy-program nil)
609 (tramp-copy-args nil)
610 (tramp-copy-keep-date nil)
611 (tramp-password-end-of-line "xy") ;see docstring for "xy"
612 (tramp-default-port 22))
613 ("plink1"
614 (tramp-login-program "plink")
615 (tramp-login-args (("-l" "%u") ("-P" "%p")
616 ("-1" "-ssh") ("%h")))
617 (tramp-remote-sh "/bin/sh")
618 (tramp-copy-program nil)
619 (tramp-copy-args nil)
620 (tramp-copy-keep-date nil)
621 (tramp-password-end-of-line "xy") ;see docstring for "xy"
622 (tramp-default-port 22))
623 ("plinkx"
624 (tramp-login-program "plink")
625 ;; ("%h") must be a single element, see
626 ;; `tramp-compute-multi-hops'.
627 (tramp-login-args (("-load") ("%h") ("-t")
628 (,(format
629 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
630 tramp-terminal-type
631 tramp-initial-end-of-output))
632 ("/bin/sh")))
633 (tramp-remote-sh "/bin/sh")
634 (tramp-copy-program nil)
635 (tramp-copy-args nil)
636 (tramp-copy-keep-date nil)
637 (tramp-password-end-of-line nil))
638 ("pscp" (tramp-login-program "plink")
639 (tramp-login-args (("-l" "%u") ("-P" "%p")
640 ("-ssh") ("%h")))
641 (tramp-remote-sh "/bin/sh")
642 (tramp-copy-program "pscp")
643 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
644 (tramp-copy-keep-date t)
645 (tramp-password-end-of-line "xy") ;see docstring for "xy"
646 (tramp-default-port 22))
647 ("psftp" (tramp-login-program "plink")
648 (tramp-login-args (("-l" "%u") ("-P" "%p")
649 ("-ssh") ("%h")))
650 (tramp-remote-sh "/bin/sh")
651 (tramp-copy-program "pscp")
652 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
653 (tramp-copy-keep-date t)
654 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
655 ("fcp" (tramp-login-program "fsh")
656 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
657 (tramp-remote-sh "/bin/sh -i")
658 (tramp-copy-program "fcp")
659 (tramp-copy-args (("-p" "%k")))
660 (tramp-copy-keep-date t)
661 (tramp-password-end-of-line nil)))
662 "*Alist of methods for remote files.
663 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
664 Each NAME stands for a remote access method. Each PARAM is a
665 pair of the form (KEY VALUE). The following KEYs are defined:
666 * `tramp-remote-sh'
667 This specifies the Bourne shell to use on the remote host. This
668 MUST be a Bourne-like shell. It is normally not necessary to set
669 this to any value other than \"/bin/sh\": Tramp wants to use a shell
670 which groks tilde expansion, but it can search for it. Also note
671 that \"/bin/sh\" exists on all Unixen, this might not be true for
672 the value that you decide to use. You Have Been Warned.
673 * `tramp-login-program'
674 This specifies the name of the program to use for logging in to the
675 remote host. This may be the name of rsh or a workalike program,
676 or the name of telnet or a workalike, or the name of su or a workalike.
677 * `tramp-login-args'
678 This specifies the list of arguments to pass to the above
679 mentioned program. Please note that this is a list of list of arguments,
680 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
681 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
682 There are some patterns: \"%h\" in this list is replaced by the host
683 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
684 port number, and \"%%\" can be used to obtain a literal percent character.
685 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
686 expansion (i.e. no host or no user specified), this list is not used as
687 argument. By this, arguments like (\"-l\" \"%u\") are optional.
688 \"%t\" is replaced by the temporary file name produced with
689 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
690 parameter of a program, if exists.
691 * `tramp-async-args'
692 When an asynchronous process is started, we know already that
693 the connection works. Therefore, we can pass additional
694 parameters to suppress diagnostic messages, in order not to
695 tamper the process output.
696 * `tramp-copy-program'
697 This specifies the name of the program to use for remotely copying
698 the file; this might be the absolute filename of rcp or the name of
699 a workalike program.
700 * `tramp-copy-args'
701 This specifies the list of parameters to pass to the above mentioned
702 program, the hints for `tramp-login-args' also apply here.
703 * `tramp-copy-keep-date'
704 This specifies whether the copying program when the preserves the
705 timestamp of the original file.
706 * `tramp-copy-keep-tmpfile'
707 This specifies whether a temporary local file shall be kept
708 for optimization reasons (useful for \"rsync\" methods).
709 * `tramp-copy-recursive'
710 Whether the operation copies directories recursively.
711 * `tramp-default-port'
712 The default port of a method is needed in case of gateway connections.
713 Additionally, it is used as indication which method is prepared for
714 passing gateways.
715 * `tramp-gw-args'
716 As the attribute name says, additional arguments are specified here
717 when a method is applied via a gateway.
718 * `tramp-password-end-of-line'
719 This specifies the string to use for terminating the line after
720 submitting the password. If this method parameter is nil, then the
721 value of the normal variable `tramp-default-password-end-of-line'
722 is used. This parameter is necessary because the \"plink\" program
723 requires any two characters after sending the password. These do
724 not have to be newline or carriage return characters. Other login
725 programs are happy with just one character, the newline character.
726 We use \"xy\" as the value for methods using \"plink\".
727
728 What does all this mean? Well, you should specify `tramp-login-program'
729 for all methods; this program is used to log in to the remote site. Then,
730 there are two ways to actually transfer the files between the local and the
731 remote side. One way is using an additional rcp-like program. If you want
732 to do this, set `tramp-copy-program' in the method.
733
734 Another possibility for file transfer is inline transfer, i.e. the
735 file is passed through the same buffer used by `tramp-login-program'. In
736 this case, the file contents need to be protected since the
737 `tramp-login-program' might use escape codes or the connection might not
738 be eight-bit clean. Therefore, file contents are encoded for transit.
739 See the variables `tramp-local-coding-commands' and
740 `tramp-remote-coding-commands' for details.
741
742 So, to summarize: if the method is an out-of-band method, then you
743 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
744 inline method, then these two parameters should be nil. Methods which
745 are fit for gateways must have `tramp-default-port' at least.
746
747 Notes:
748
749 When using `su' or `sudo' the phrase `open connection to a remote
750 host' sounds strange, but it is used nevertheless, for consistency.
751 No connection is opened to a remote host, but `su' or `sudo' is
752 started on the local host. You should specify a remote host
753 `localhost' or the name of the local host. Another host name is
754 useful only in combination with `tramp-default-proxies-alist'.")
755
756 (defun tramp-detect-ssh-controlmaster ()
757 "Call ssh to detect whether it supports the ControlMaster argument.
758 This function may return nil when the argument is supported, but
759 shouldn't return t when it isn't."
760 (ignore-errors
761 (with-temp-buffer
762 (call-process "ssh" nil t nil "-o" "ControlMaster")
763 (goto-char (point-min))
764 (search-forward-regexp "Missing ControlMaster argument" nil t))))
765
766 (defcustom tramp-default-method
767 ;; An external copy method seems to be preferred, because it is much
768 ;; more performant for large files, and it hasn't too serious delays
769 ;; for small files. But it must be ensured that there aren't
770 ;; permanent password queries. Either a password agent like
771 ;; "ssh-agent" or "Pageant" shall run, or the optional
772 ;; password-cache.el or auth-sources.el packages shall be active for
773 ;; password caching. "scpc" is chosen if we detect that the user is
774 ;; running OpenSSH 4.0 or newer.
775 (cond
776 ;; PuTTY is installed.
777 ((executable-find "pscp")
778 (if (or (fboundp 'password-read)
779 (fboundp 'auth-source-user-or-password)
780 ;; Pageant is running.
781 (tramp-compat-process-running-p "Pageant"))
782 "pscp"
783 "plink"))
784 ;; There is an ssh installation.
785 ((executable-find "scp")
786 (cond
787 ((tramp-detect-ssh-controlmaster) "scpc")
788 ((or (fboundp 'password-read)
789 (fboundp 'auth-source-user-or-password)
790 ;; ssh-agent is running.
791 (getenv "SSH_AUTH_SOCK")
792 (getenv "SSH_AGENT_PID"))
793 "scp")
794 (t "ssh")))
795 ;; Fallback.
796 (t "ftp"))
797 "*Default method to use for transferring files.
798 See `tramp-methods' for possibilities.
799 Also see `tramp-default-method-alist'."
800 :group 'tramp
801 :type 'string)
802
803 (defcustom tramp-default-method-alist
804 '(("\\`localhost\\'" "\\`root\\'" "su"))
805 "*Default method to use for specific host/user pairs.
806 This is an alist of items (HOST USER METHOD). The first matching item
807 specifies the method to use for a file name which does not specify a
808 method. HOST and USER are regular expressions or nil, which is
809 interpreted as a regular expression which always matches. If no entry
810 matches, the variable `tramp-default-method' takes effect.
811
812 If the file name does not specify the user, lookup is done using the
813 empty string for the user name.
814
815 See `tramp-methods' for a list of possibilities for METHOD."
816 :group 'tramp
817 :type '(repeat (list (regexp :tag "Host regexp")
818 (regexp :tag "User regexp")
819 (string :tag "Method"))))
820
821 (defcustom tramp-default-user
822 nil
823 "*Default user to use for transferring files.
824 It is nil by default; otherwise settings in configuration files like
825 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
826
827 This variable is regarded as obsolete, and will be removed soon."
828 :group 'tramp
829 :type '(choice (const nil) string))
830
831 (defcustom tramp-default-user-alist
832 `(("\\`su\\(do\\)?\\'" nil "root")
833 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
834 nil ,(user-login-name)))
835 "*Default user to use for specific method/host pairs.
836 This is an alist of items (METHOD HOST USER). The first matching item
837 specifies the user to use for a file name which does not specify a
838 user. METHOD and USER are regular expressions or nil, which is
839 interpreted as a regular expression which always matches. If no entry
840 matches, the variable `tramp-default-user' takes effect.
841
842 If the file name does not specify the method, lookup is done using the
843 empty string for the method name."
844 :group 'tramp
845 :type '(repeat (list (regexp :tag "Method regexp")
846 (regexp :tag "Host regexp")
847 (string :tag "User"))))
848
849 (defcustom tramp-default-host
850 (system-name)
851 "*Default host to use for transferring files.
852 Useful for su and sudo methods mostly."
853 :group 'tramp
854 :type 'string)
855
856 (defcustom tramp-default-proxies-alist nil
857 "*Route to be followed for specific host/user pairs.
858 This is an alist of items (HOST USER PROXY). The first matching
859 item specifies the proxy to be passed for a file name located on
860 a remote target matching USER@HOST. HOST and USER are regular
861 expressions. PROXY must be a Tramp filename without a localname
862 part. Method and user name on PROXY are optional, which is
863 interpreted with the default values. PROXY can contain the
864 patterns %h and %u, which are replaced by the strings matching
865 HOST or USER, respectively.
866
867 HOST, USER or PROXY could also be Lisp forms, which will be
868 evaluated. The result must be a string or nil, which is
869 interpreted as a regular expression which always matches."
870 :group 'tramp
871 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
872 (choice :tag "User regexp" regexp sexp)
873 (choice :tag "Proxy remote name" string (const nil)))))
874
875 (defconst tramp-local-host-regexp
876 (concat
877 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
878 "*Host names which are regarded as local host.")
879
880 (defconst tramp-completion-function-alist-rsh
881 '((tramp-parse-rhosts "/etc/hosts.equiv")
882 (tramp-parse-rhosts "~/.rhosts"))
883 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
884
885 (defconst tramp-completion-function-alist-ssh
886 '((tramp-parse-rhosts "/etc/hosts.equiv")
887 (tramp-parse-rhosts "/etc/shosts.equiv")
888 (tramp-parse-shosts "/etc/ssh_known_hosts")
889 (tramp-parse-sconfig "/etc/ssh_config")
890 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
891 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
892 (tramp-parse-rhosts "~/.rhosts")
893 (tramp-parse-rhosts "~/.shosts")
894 (tramp-parse-shosts "~/.ssh/known_hosts")
895 (tramp-parse-sconfig "~/.ssh/config")
896 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
897 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
898 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
899
900 (defconst tramp-completion-function-alist-telnet
901 '((tramp-parse-hosts "/etc/hosts"))
902 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
903
904 (defconst tramp-completion-function-alist-su
905 '((tramp-parse-passwd "/etc/passwd"))
906 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
907
908 (defconst tramp-completion-function-alist-putty
909 '((tramp-parse-putty
910 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
911 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
912
913 (defvar tramp-completion-function-alist nil
914 "*Alist of methods for remote files.
915 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
916 Each NAME stands for a remote access method. Each PAIR is of the form
917 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
918 names from FILE for completion. The following predefined FUNCTIONs exists:
919
920 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
921 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
922 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
923 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
924 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
925 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
926 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
927 * `tramp-parse-netrc' for \"~/.netrc\" like files.
928 * `tramp-parse-putty' for PuTTY registry keys.
929
930 FUNCTION can also be a customer defined function. For more details see
931 the info pages.")
932
933 (eval-after-load "tramp"
934 '(progn
935 (tramp-set-completion-function
936 "rcp" tramp-completion-function-alist-rsh)
937 (tramp-set-completion-function
938 "scp" tramp-completion-function-alist-ssh)
939 (tramp-set-completion-function
940 "scp1" tramp-completion-function-alist-ssh)
941 (tramp-set-completion-function
942 "scp2" tramp-completion-function-alist-ssh)
943 (tramp-set-completion-function
944 "scp1_old" tramp-completion-function-alist-ssh)
945 (tramp-set-completion-function
946 "scp2_old" tramp-completion-function-alist-ssh)
947 (tramp-set-completion-function
948 "rsync" tramp-completion-function-alist-ssh)
949 (tramp-set-completion-function
950 "rsyncc" tramp-completion-function-alist-ssh)
951 (tramp-set-completion-function
952 "remcp" tramp-completion-function-alist-rsh)
953 (tramp-set-completion-function
954 "rsh" tramp-completion-function-alist-rsh)
955 (tramp-set-completion-function
956 "ssh" tramp-completion-function-alist-ssh)
957 (tramp-set-completion-function
958 "ssh1" tramp-completion-function-alist-ssh)
959 (tramp-set-completion-function
960 "ssh2" tramp-completion-function-alist-ssh)
961 (tramp-set-completion-function
962 "ssh1_old" tramp-completion-function-alist-ssh)
963 (tramp-set-completion-function
964 "ssh2_old" tramp-completion-function-alist-ssh)
965 (tramp-set-completion-function
966 "remsh" tramp-completion-function-alist-rsh)
967 (tramp-set-completion-function
968 "telnet" tramp-completion-function-alist-telnet)
969 (tramp-set-completion-function
970 "su" tramp-completion-function-alist-su)
971 (tramp-set-completion-function
972 "sudo" tramp-completion-function-alist-su)
973 (tramp-set-completion-function
974 "scpx" tramp-completion-function-alist-ssh)
975 (tramp-set-completion-function
976 "sshx" tramp-completion-function-alist-ssh)
977 (tramp-set-completion-function
978 "krlogin" tramp-completion-function-alist-rsh)
979 (tramp-set-completion-function
980 "plink" tramp-completion-function-alist-ssh)
981 (tramp-set-completion-function
982 "plink1" tramp-completion-function-alist-ssh)
983 (tramp-set-completion-function
984 "plinkx" tramp-completion-function-alist-putty)
985 (tramp-set-completion-function
986 "pscp" tramp-completion-function-alist-ssh)
987 (tramp-set-completion-function
988 "fcp" tramp-completion-function-alist-ssh)))
989
990 (defconst tramp-echo-mark-marker "_echo"
991 "String marker to surround echoed commands.")
992
993 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
994 "String length of `tramp-echo-mark-marker'.")
995
996 (defconst tramp-echo-mark
997 (concat tramp-echo-mark-marker
998 (make-string tramp-echo-mark-marker-length ?\b))
999 "String mark to be transmitted around shell commands.
1000 Used to separate their echo from the output they produce. This
1001 will only be used if we cannot disable remote echo via stty.
1002 This string must have no effect on the remote shell except for
1003 producing some echo which can later be detected by
1004 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
1005 followed by an equal number of backspaces to erase them will
1006 usually suffice.")
1007
1008 (defconst tramp-echoed-echo-mark-regexp
1009 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
1010 tramp-echo-mark-marker tramp-echo-mark-marker-length)
1011 "Regexp which matches `tramp-echo-mark' as it gets echoed by
1012 the remote shell.")
1013
1014 (defcustom tramp-rsh-end-of-line "\n"
1015 "*String used for end of line in rsh connections.
1016 I don't think this ever needs to be changed, so please tell me about it
1017 if you need to change this.
1018 Also see the method parameter `tramp-password-end-of-line' and the normal
1019 variable `tramp-default-password-end-of-line'."
1020 :group 'tramp
1021 :type 'string)
1022
1023 (defcustom tramp-default-password-end-of-line
1024 tramp-rsh-end-of-line
1025 "*String used for end of line after sending a password.
1026 This variable provides the default value for the method parameter
1027 `tramp-password-end-of-line', see `tramp-methods' for more details.
1028
1029 It seems that people using plink under Windows need to send
1030 \"\\r\\n\" (carriage-return, then newline) after a password, but just
1031 \"\\n\" after all other lines. This variable can be used for the
1032 password, see `tramp-rsh-end-of-line' for the other cases.
1033
1034 The default value is to use the same value as `tramp-rsh-end-of-line'."
1035 :group 'tramp
1036 :type 'string)
1037
1038 ;; "getconf PATH" yields:
1039 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
1040 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
1041 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1042 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1043 ;; IRIX64: /usr/bin
1044 (defcustom tramp-remote-path
1045 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1046 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1047 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1048 "*List of directories to search for executables on remote host.
1049 For every remote host, this variable will be set buffer local,
1050 keeping the list of existing directories on that host.
1051
1052 You can use `~' in this list, but when searching for a shell which groks
1053 tilde expansion, all directory names starting with `~' will be ignored.
1054
1055 `Default Directories' represent the list of directories given by
1056 the command \"getconf PATH\". It is recommended to use this
1057 entry on top of this list, because these are the default
1058 directories for POSIX compatible commands.
1059
1060 `Private Directories' are the settings of the $PATH environment,
1061 as given in your `~/.profile'."
1062 :group 'tramp
1063 :type '(repeat (choice
1064 (const :tag "Default Directories" tramp-default-remote-path)
1065 (const :tag "Private Directories" tramp-own-remote-path)
1066 (string :tag "Directory"))))
1067
1068 (defcustom tramp-remote-process-environment
1069 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1070 ,(format "TERM=%s" tramp-terminal-type)
1071 "EMACS=t" ;; Deprecated.
1072 ,(format "INSIDE_EMACS='%s,tramp:%s'" emacs-version tramp-version)
1073 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1074 "autocorrect=" "correct=")
1075
1076 "*List of environment variables to be set on the remote host.
1077
1078 Each element should be a string of the form ENVVARNAME=VALUE. An
1079 entry ENVVARNAME= diables the corresponding environment variable,
1080 which might have been set in the init files like ~/.profile.
1081
1082 Special handling is applied to the PATH environment, which should
1083 not be set here. Instead of, it should be set via `tramp-remote-path'."
1084 :group 'tramp
1085 :type '(repeat string))
1086
1087 (defcustom tramp-login-prompt-regexp
1088 ".*ogin\\( .*\\)?: *"
1089 "*Regexp matching login-like prompts.
1090 The regexp should match at end of buffer.
1091
1092 Sometimes the prompt is reported to look like \"login as:\"."
1093 :group 'tramp
1094 :type 'regexp)
1095
1096 (defcustom tramp-shell-prompt-pattern
1097 ;; Allow a prompt to start right after a ^M since it indeed would be
1098 ;; displayed at the beginning of the line (and Zsh uses it). This
1099 ;; regexp works only for GNU Emacs.
1100 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
1101 "[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
1102 "Regexp to match prompts from remote shell.
1103 Normally, Tramp expects you to configure `shell-prompt-pattern'
1104 correctly, but sometimes it happens that you are connecting to a
1105 remote host which sends a different kind of shell prompt. Therefore,
1106 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1107 and also things matched by this variable. The default value of this
1108 variable is similar to the default value of `shell-prompt-pattern',
1109 which should work well in many cases.
1110
1111 This regexp must match both `tramp-initial-end-of-output' and
1112 `tramp-end-of-output'."
1113 :group 'tramp
1114 :type 'regexp)
1115
1116 (defcustom tramp-password-prompt-regexp
1117 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1118 "*Regexp matching password-like prompts.
1119 The regexp should match at end of buffer.
1120
1121 The `sudo' program appears to insert a `^@' character into the prompt."
1122 :group 'tramp
1123 :type 'regexp)
1124
1125 (defcustom tramp-wrong-passwd-regexp
1126 (concat "^.*"
1127 ;; These strings should be on the last line
1128 (regexp-opt '("Permission denied"
1129 "Login incorrect"
1130 "Login Incorrect"
1131 "Connection refused"
1132 "Connection closed"
1133 "Timeout, server not responding."
1134 "Sorry, try again."
1135 "Name or service not known"
1136 "Host key verification failed."
1137 "No supported authentication methods left to try!") t)
1138 ".*"
1139 "\\|"
1140 "^.*\\("
1141 ;; Here comes a list of regexes, separated by \\|
1142 "Received signal [0-9]+"
1143 "\\).*")
1144 "*Regexp matching a `login failed' message.
1145 The regexp should match at end of buffer."
1146 :group 'tramp
1147 :type 'regexp)
1148
1149 (defcustom tramp-yesno-prompt-regexp
1150 (concat
1151 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1152 "\\s-*")
1153 "Regular expression matching all yes/no queries which need to be confirmed.
1154 The confirmation should be done with yes or no.
1155 The regexp should match at end of buffer.
1156 See also `tramp-yn-prompt-regexp'."
1157 :group 'tramp
1158 :type 'regexp)
1159
1160 (defcustom tramp-yn-prompt-regexp
1161 (concat
1162 (regexp-opt '("Store key in cache? (y/n)"
1163 "Update cached key? (y/n, Return cancels connection)") t)
1164 "\\s-*")
1165 "Regular expression matching all y/n queries which need to be confirmed.
1166 The confirmation should be done with y or n.
1167 The regexp should match at end of buffer.
1168 See also `tramp-yesno-prompt-regexp'."
1169 :group 'tramp
1170 :type 'regexp)
1171
1172 (defcustom tramp-terminal-prompt-regexp
1173 (concat "\\("
1174 "TERM = (.*)"
1175 "\\|"
1176 "Terminal type\\? \\[.*\\]"
1177 "\\)\\s-*")
1178 "Regular expression matching all terminal setting prompts.
1179 The regexp should match at end of buffer.
1180 The answer will be provided by `tramp-action-terminal', which see."
1181 :group 'tramp
1182 :type 'regexp)
1183
1184 (defcustom tramp-operation-not-permitted-regexp
1185 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1186 (regexp-opt '("Operation not permitted") t))
1187 "Regular expression matching keep-date problems in (s)cp operations.
1188 Copying has been performed successfully already, so this message can
1189 be ignored safely."
1190 :group 'tramp
1191 :type 'regexp)
1192
1193 (defcustom tramp-copy-failed-regexp
1194 (concat "\\(.+: "
1195 (regexp-opt '("Permission denied"
1196 "not a regular file"
1197 "is a directory"
1198 "No such file or directory") t)
1199 "\\)\\s-*")
1200 "Regular expression matching copy problems in (s)cp operations."
1201 :group 'tramp
1202 :type 'regexp)
1203
1204 (defcustom tramp-process-alive-regexp
1205 ""
1206 "Regular expression indicating a process has finished.
1207 In fact this expression is empty by intention, it will be used only to
1208 check regularly the status of the associated process.
1209 The answer will be provided by `tramp-action-process-alive',
1210 `tramp-action-out-of-band', which see."
1211 :group 'tramp
1212 :type 'regexp)
1213
1214 (defcustom tramp-temp-name-prefix "tramp."
1215 "*Prefix to use for temporary files.
1216 If this is a relative file name (such as \"tramp.\"), it is considered
1217 relative to the directory name returned by the function
1218 `tramp-compat-temporary-file-directory' (which see). It may also be an
1219 absolute file name; don't forget to include a prefix for the filename
1220 part, though."
1221 :group 'tramp
1222 :type 'string)
1223
1224 (defconst tramp-temp-buffer-name " *tramp temp*"
1225 "Buffer name for a temporary buffer.
1226 It shall be used in combination with `generate-new-buffer-name'.")
1227
1228 (defvar tramp-temp-buffer-file-name nil
1229 "File name of a persistent local temporary file.
1230 Useful for \"rsync\" like methods.")
1231 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1232
1233 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1234 "*Alist specifying extra arguments to pass to the remote shell.
1235 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1236 matching the shell file name and ARGS is a string specifying the
1237 arguments.
1238
1239 This variable is only used when Tramp needs to start up another shell
1240 for tilde expansion. The extra arguments should typically prevent the
1241 shell from reading its init file."
1242 :group 'tramp
1243 ;; This might be the wrong way to test whether the widget type
1244 ;; `alist' is available. Who knows the right way to test it?
1245 :type (if (get 'alist 'widget-type)
1246 '(alist :key-type string :value-type string)
1247 '(repeat (cons string string))))
1248
1249 ;; XEmacs is distributed with few Lisp packages. Further packages are
1250 ;; installed using EFS. If we use a unified filename format, then
1251 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1252 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1253 ;; just like before.) Another reason for using a separate filename
1254 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1255 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1256 ;; the other places.
1257
1258 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1259 ;;;###autoload
1260 (defcustom tramp-syntax
1261 (if (featurep 'xemacs) 'sep 'ftp)
1262 "Tramp filename syntax to be used.
1263
1264 It can have the following values:
1265
1266 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1267 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1268 'url -- URL-like syntax."
1269 :group 'tramp
1270 :type (if (featurep 'xemacs)
1271 '(choice (const :tag "EFS" ftp)
1272 (const :tag "XEmacs" sep)
1273 (const :tag "URL" url))
1274 '(choice (const :tag "Ange-FTP" ftp)
1275 (const :tag "URL" url))))
1276
1277 (defconst tramp-prefix-format
1278 (cond ((equal tramp-syntax 'ftp) "/")
1279 ((equal tramp-syntax 'sep) "/[")
1280 ((equal tramp-syntax 'url) "/")
1281 (t (error "Wrong `tramp-syntax' defined")))
1282 "*String matching the very beginning of Tramp file names.
1283 Used in `tramp-make-tramp-file-name'.")
1284
1285 (defconst tramp-prefix-regexp
1286 (concat "^" (regexp-quote tramp-prefix-format))
1287 "*Regexp matching the very beginning of Tramp file names.
1288 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1289
1290 (defconst tramp-method-regexp
1291 "[a-zA-Z_0-9-]+"
1292 "*Regexp matching methods identifiers.")
1293
1294 (defconst tramp-postfix-method-format
1295 (cond ((equal tramp-syntax 'ftp) ":")
1296 ((equal tramp-syntax 'sep) "/")
1297 ((equal tramp-syntax 'url) "://")
1298 (t (error "Wrong `tramp-syntax' defined")))
1299 "*String matching delimeter between method and user or host names.
1300 Used in `tramp-make-tramp-file-name'.")
1301
1302 (defconst tramp-postfix-method-regexp
1303 (regexp-quote tramp-postfix-method-format)
1304 "*Regexp matching delimeter between method and user or host names.
1305 Derived from `tramp-postfix-method-format'.")
1306
1307 (defconst tramp-user-regexp
1308 "[^:/ \t]+"
1309 "*Regexp matching user names.")
1310
1311 (defconst tramp-prefix-domain-format "%"
1312 "*String matching delimeter between user and domain names.")
1313
1314 (defconst tramp-prefix-domain-regexp
1315 (regexp-quote tramp-prefix-domain-format)
1316 "*Regexp matching delimeter between user and domain names.
1317 Derived from `tramp-prefix-domain-format'.")
1318
1319 (defconst tramp-domain-regexp
1320 "[-a-zA-Z0-9_.]+"
1321 "*Regexp matching domain names.")
1322
1323 (defconst tramp-user-with-domain-regexp
1324 (concat "\\(" tramp-user-regexp "\\)"
1325 tramp-prefix-domain-regexp
1326 "\\(" tramp-domain-regexp "\\)")
1327 "*Regexp matching user names with domain names.")
1328
1329 (defconst tramp-postfix-user-format
1330 "@"
1331 "*String matching delimeter between user and host names.
1332 Used in `tramp-make-tramp-file-name'.")
1333
1334 (defconst tramp-postfix-user-regexp
1335 (regexp-quote tramp-postfix-user-format)
1336 "*Regexp matching delimeter between user and host names.
1337 Derived from `tramp-postfix-user-format'.")
1338
1339 (defconst tramp-host-regexp
1340 "[a-zA-Z0-9_.-]+"
1341 "*Regexp matching host names.")
1342
1343 (defconst tramp-prefix-ipv6-format
1344 (cond ((equal tramp-syntax 'ftp) "[")
1345 ((equal tramp-syntax 'sep) "")
1346 ((equal tramp-syntax 'url) "[")
1347 (t (error "Wrong `tramp-syntax' defined")))
1348 "*String matching left hand side of IPv6 addresses.
1349 Used in `tramp-make-tramp-file-name'.")
1350
1351 (defconst tramp-prefix-ipv6-regexp
1352 (regexp-quote tramp-prefix-ipv6-format)
1353 "*Regexp matching left hand side of IPv6 addresses.
1354 Derived from `tramp-prefix-ipv6-format'.")
1355
1356 ;; The following regexp is a bit sloppy. But it shall serve our
1357 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1358 ;; "::ffff:192.168.0.1".
1359 (defconst tramp-ipv6-regexp
1360 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1361 "*Regexp matching IPv6 addresses.")
1362
1363 (defconst tramp-postfix-ipv6-format
1364 (cond ((equal tramp-syntax 'ftp) "]")
1365 ((equal tramp-syntax 'sep) "")
1366 ((equal tramp-syntax 'url) "]")
1367 (t (error "Wrong `tramp-syntax' defined")))
1368 "*String matching right hand side of IPv6 addresses.
1369 Used in `tramp-make-tramp-file-name'.")
1370
1371 (defconst tramp-postfix-ipv6-regexp
1372 (regexp-quote tramp-postfix-ipv6-format)
1373 "*Regexp matching right hand side of IPv6 addresses.
1374 Derived from `tramp-postfix-ipv6-format'.")
1375
1376 (defconst tramp-prefix-port-format
1377 (cond ((equal tramp-syntax 'ftp) "#")
1378 ((equal tramp-syntax 'sep) "#")
1379 ((equal tramp-syntax 'url) ":")
1380 (t (error "Wrong `tramp-syntax' defined")))
1381 "*String matching delimeter between host names and port numbers.")
1382
1383 (defconst tramp-prefix-port-regexp
1384 (regexp-quote tramp-prefix-port-format)
1385 "*Regexp matching delimeter between host names and port numbers.
1386 Derived from `tramp-prefix-port-format'.")
1387
1388 (defconst tramp-port-regexp
1389 "[0-9]+"
1390 "*Regexp matching port numbers.")
1391
1392 (defconst tramp-host-with-port-regexp
1393 (concat "\\(" tramp-host-regexp "\\)"
1394 tramp-prefix-port-regexp
1395 "\\(" tramp-port-regexp "\\)")
1396 "*Regexp matching host names with port numbers.")
1397
1398 (defconst tramp-postfix-host-format
1399 (cond ((equal tramp-syntax 'ftp) ":")
1400 ((equal tramp-syntax 'sep) "]")
1401 ((equal tramp-syntax 'url) "")
1402 (t (error "Wrong `tramp-syntax' defined")))
1403 "*String matching delimeter between host names and localnames.
1404 Used in `tramp-make-tramp-file-name'.")
1405
1406 (defconst tramp-postfix-host-regexp
1407 (regexp-quote tramp-postfix-host-format)
1408 "*Regexp matching delimeter between host names and localnames.
1409 Derived from `tramp-postfix-host-format'.")
1410
1411 (defconst tramp-localname-regexp
1412 ".*$"
1413 "*Regexp matching localnames.")
1414
1415 ;; File name format.
1416
1417 (defconst tramp-file-name-structure
1418 (list
1419 (concat
1420 tramp-prefix-regexp
1421 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1422 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1423 "\\(" "\\(" tramp-host-regexp
1424 "\\|"
1425 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1426 tramp-postfix-ipv6-regexp "\\)"
1427 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1428 tramp-postfix-host-regexp
1429 "\\(" tramp-localname-regexp "\\)")
1430 2 4 5 8)
1431
1432 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1433 the Tramp file name structure.
1434
1435 The first element REGEXP is a regular expression matching a Tramp file
1436 name. The regex should contain parentheses around the method name,
1437 the user name, the host name, and the file name parts.
1438
1439 The second element METHOD is a number, saying which pair of
1440 parentheses matches the method name. The third element USER is
1441 similar, but for the user name. The fourth element HOST is similar,
1442 but for the host name. The fifth element FILE is for the file name.
1443 These numbers are passed directly to `match-string', which see. That
1444 means the opening parentheses are counted to identify the pair.
1445
1446 See also `tramp-file-name-regexp'.")
1447
1448 ;;;###autoload
1449 (defconst tramp-file-name-regexp-unified
1450 (if (memq system-type '(cygwin windows-nt))
1451 "\\`/\\([^[/:]\\{2,\\}\\|[^/]\\{2,\\}]\\):"
1452 "\\`/\\([^[/:]+\\|[^/]+]\\):")
1453 "Value for `tramp-file-name-regexp' for unified remoting.
1454 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1455 Tramp. See `tramp-file-name-structure' for more explanations.
1456
1457 On W32 systems, the volume letter must be ignored.")
1458
1459 ;;;###autoload
1460 (defconst tramp-file-name-regexp-separate
1461 "\\`/\\[.*\\]"
1462 "Value for `tramp-file-name-regexp' for separate remoting.
1463 XEmacs uses a separate filename syntax for Tramp and EFS.
1464 See `tramp-file-name-structure' for more explanations.")
1465
1466 ;;;###autoload
1467 (defconst tramp-file-name-regexp-url
1468 "\\`/[^/:]+://"
1469 "Value for `tramp-file-name-regexp' for URL-like remoting.
1470 See `tramp-file-name-structure' for more explanations.")
1471
1472 ;;;###autoload
1473 (defconst tramp-file-name-regexp
1474 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1475 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1476 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1477 (t (error "Wrong `tramp-syntax' defined")))
1478 "*Regular expression matching file names handled by Tramp.
1479 This regexp should match Tramp file names but no other file names.
1480 When tramp.el is loaded, this regular expression is prepended to
1481 `file-name-handler-alist', and that is searched sequentially. Thus,
1482 if the Tramp entry appears rather early in the `file-name-handler-alist'
1483 and is a bit too general, then some files might be considered Tramp
1484 files which are not really Tramp files.
1485
1486 Please note that the entry in `file-name-handler-alist' is made when
1487 this file \(tramp.el\) is loaded. This means that this variable must be set
1488 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1489 updated after changing this variable.
1490
1491 Also see `tramp-file-name-structure'.")
1492
1493 ;;;###autoload
1494 (defconst tramp-root-regexp
1495 (if (memq system-type '(cygwin windows-nt))
1496 "\\`\\([a-zA-Z]:\\)?/"
1497 "\\`/")
1498 "Beginning of an incomplete Tramp file name.
1499 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1500 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1501
1502 ;;;###autoload
1503 (defconst tramp-completion-file-name-regexp-unified
1504 (if (memq system-type '(cygwin windows-nt))
1505 (concat tramp-root-regexp "[^/]\\{2,\\}\\'")
1506 (concat tramp-root-regexp "[^/]*\\'"))
1507 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1508 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1509 See `tramp-file-name-structure' for more explanations.
1510
1511 On W32 systems, the volume letter must be ignored.")
1512
1513 ;;;###autoload
1514 (defconst tramp-completion-file-name-regexp-separate
1515 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1516 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1517 XEmacs uses a separate filename syntax for Tramp and EFS.
1518 See `tramp-file-name-structure' for more explanations.")
1519
1520 ;;;###autoload
1521 (defconst tramp-completion-file-name-regexp-url
1522 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1523 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1524 See `tramp-file-name-structure' for more explanations.")
1525
1526 ;;;###autoload
1527 (defconst tramp-completion-file-name-regexp
1528 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1529 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1530 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1531 (t (error "Wrong `tramp-syntax' defined")))
1532 "*Regular expression matching file names handled by Tramp completion.
1533 This regexp should match partial Tramp file names only.
1534
1535 Please note that the entry in `file-name-handler-alist' is made when
1536 this file (tramp.el) is loaded. This means that this variable must be set
1537 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1538 updated after changing this variable.
1539
1540 Also see `tramp-file-name-structure'.")
1541
1542 (defconst tramp-actions-before-shell
1543 '((tramp-login-prompt-regexp tramp-action-login)
1544 (tramp-password-prompt-regexp tramp-action-password)
1545 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1546 (shell-prompt-pattern tramp-action-succeed)
1547 (tramp-shell-prompt-pattern tramp-action-succeed)
1548 (tramp-yesno-prompt-regexp tramp-action-yesno)
1549 (tramp-yn-prompt-regexp tramp-action-yn)
1550 (tramp-terminal-prompt-regexp tramp-action-terminal)
1551 (tramp-process-alive-regexp tramp-action-process-alive))
1552 "List of pattern/action pairs.
1553 Whenever a pattern matches, the corresponding action is performed.
1554 Each item looks like (PATTERN ACTION).
1555
1556 The PATTERN should be a symbol, a variable. The value of this
1557 variable gives the regular expression to search for. Note that the
1558 regexp must match at the end of the buffer, \"\\'\" is implicitly
1559 appended to it.
1560
1561 The ACTION should also be a symbol, but a function. When the
1562 corresponding PATTERN matches, the ACTION function is called.")
1563
1564 (defconst tramp-actions-copy-out-of-band
1565 '((tramp-password-prompt-regexp tramp-action-password)
1566 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1567 (tramp-copy-failed-regexp tramp-action-permission-denied)
1568 (tramp-process-alive-regexp tramp-action-out-of-band))
1569 "List of pattern/action pairs.
1570 This list is used for copying/renaming with out-of-band methods.
1571
1572 See `tramp-actions-before-shell' for more info.")
1573
1574 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1575 ;; known to have a bug in `process-send-string'; some ssh connections appear
1576 ;; to drop bytes when data is sent too quickly. There is also a connection
1577 ;; buffer local variable, which is computed depending on remote host properties
1578 ;; when `tramp-chunksize' is zero or nil.
1579 (defcustom tramp-chunksize
1580 (when (and (not (featurep 'xemacs))
1581 (memq system-type '(hpux)))
1582 500)
1583 ;; Parentheses in docstring starting at beginning of line are escaped.
1584 ;; Fontification is messed up when
1585 ;; `open-paren-in-column-0-is-defun-start' set to t.
1586 "*If non-nil, chunksize for sending input to local process.
1587 It is necessary only on systems which have a buggy `process-send-string'
1588 implementation. The necessity, whether this variable must be set, can be
1589 checked via the following code:
1590
1591 (with-temp-buffer
1592 (let* ((user \"xxx\") (host \"yyy\")
1593 (init 0) (step 50)
1594 (sent init) (received init))
1595 (while (= sent received)
1596 (setq sent (+ sent step))
1597 (erase-buffer)
1598 (let ((proc (start-process (buffer-name) (current-buffer)
1599 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1600 (when (memq (process-status proc) '(run open))
1601 (process-send-string proc (make-string sent ?\\ ))
1602 (process-send-eof proc)
1603 (process-send-eof proc))
1604 (while (not (progn (goto-char (point-min))
1605 (re-search-forward \"\\\\w+\" (point-max) t)))
1606 (accept-process-output proc 1))
1607 (when (memq (process-status proc) '(run open))
1608 (setq received (string-to-number (match-string 0)))
1609 (delete-process proc)
1610 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1611 (sit-for 0))))
1612 (if (> sent (+ init step))
1613 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1614 (- sent step))
1615 (message \"Test does not work\")
1616 (display-buffer (current-buffer))
1617 (sit-for 30))))
1618
1619 In the Emacs normally running Tramp, evaluate the above code
1620 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1621 respectively\). You can do this, for example, by pasting it into
1622 the `*scratch*' buffer and then hitting C-j with the cursor after the
1623 last closing parenthesis. Note that it works only if you have configured
1624 \"ssh\" to run without password query, see ssh-agent\(1\).
1625
1626 You will see the number of bytes sent successfully to the remote host.
1627 If that number exceeds 1000, you can stop the execution by hitting
1628 C-g, because your Emacs is likely clean.
1629
1630 When it is necessary to set `tramp-chunksize', you might consider to
1631 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1632 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
1633 performance.
1634
1635 If your Emacs is buggy, the code stops and gives you an indication
1636 about the value `tramp-chunksize' should be set. Maybe you could just
1637 experiment a bit, e.g. changing the values of `init' and `step'
1638 in the third line of the code.
1639
1640 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1641 this variable to be set as well."
1642 :group 'tramp
1643 :type '(choice (const nil) integer))
1644
1645 ;; Logging in to a remote host normally requires obtaining a pty. But
1646 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1647 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1648 ;; for an override of the system default.
1649 (defcustom tramp-process-connection-type t
1650 "Overrides `process-connection-type' for connections from Tramp.
1651 Tramp binds process-connection-type to the value given here before
1652 opening a connection to a remote host."
1653 :group 'tramp
1654 :type '(choice (const nil) (const t) (const pty)))
1655
1656 (defcustom tramp-completion-reread-directory-timeout 10
1657 "Defines seconds since last remote command before rereading a directory.
1658 A remote directory might have changed its contents. In order to
1659 make it visible during file name completion in the minibuffer,
1660 Tramp flushes its cache and rereads the directory contents when
1661 more than `tramp-completion-reread-directory-timeout' seconds
1662 have been gone since last remote command execution. A value of 0
1663 would require an immediate reread during filename completion, nil
1664 means to use always cached values for the directory contents."
1665 :group 'tramp
1666 :type '(choice (const nil) integer))
1667
1668 ;;; Internal Variables:
1669
1670 (defvar tramp-current-method nil
1671 "Connection method for this *tramp* buffer.")
1672
1673 (defvar tramp-current-user nil
1674 "Remote login name for this *tramp* buffer.")
1675
1676 (defvar tramp-current-host nil
1677 "Remote host for this *tramp* buffer.")
1678
1679 (defconst tramp-uudecode
1680 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1681 cat /tmp/tramp.$$
1682 rm -f /tmp/tramp.$$"
1683 "Shell function to implement `uudecode' to standard output.
1684 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1685 for this or `uudecode -p', but some systems don't, and for them
1686 we have this shell function.")
1687
1688 (defconst tramp-perl-file-truename
1689 "%s -e '
1690 use File::Spec;
1691 use Cwd \"realpath\";
1692
1693 sub recursive {
1694 my ($volume, @dirs) = @_;
1695 my $real = realpath(File::Spec->catpath(
1696 $volume, File::Spec->catdir(@dirs), \"\"));
1697 if ($real) {
1698 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1699 return ($vol, File::Spec->splitdir($dir));
1700 }
1701 else {
1702 my $last = pop(@dirs);
1703 ($volume, @dirs) = recursive($volume, @dirs);
1704 push(@dirs, $last);
1705 return ($volume, @dirs);
1706 }
1707 }
1708
1709 $result = realpath($ARGV[0]);
1710 if (!$result) {
1711 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1712 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1713
1714 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1715 }
1716
1717 if ($ARGV[0] =~ /\\/$/) {
1718 $result = $result . \"/\";
1719 }
1720
1721 print \"\\\"$result\\\"\\n\";
1722 ' \"$1\" 2>/dev/null"
1723 "Perl script to produce output suitable for use with `file-truename'
1724 on the remote file system.
1725 Escape sequence %s is replaced with name of Perl binary.
1726 This string is passed to `format', so percent characters need to be doubled.")
1727
1728 (defconst tramp-perl-file-name-all-completions
1729 "%s -e 'sub case {
1730 my $str = shift;
1731 if ($ARGV[2]) {
1732 return lc($str);
1733 }
1734 else {
1735 return $str;
1736 }
1737 }
1738 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1739 @files = readdir(d); closedir(d);
1740 foreach $f (@files) {
1741 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1742 if (-d \"$ARGV[0]/$f\") {
1743 print \"$f/\\n\";
1744 }
1745 else {
1746 print \"$f\\n\";
1747 }
1748 }
1749 }
1750 print \"ok\\n\"
1751 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1752 "Perl script to produce output suitable for use with
1753 `file-name-all-completions' on the remote file system. Escape
1754 sequence %s is replaced with name of Perl binary. This string is
1755 passed to `format', so percent characters need to be doubled.")
1756
1757 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1758 ;; output. If you are hacking on this, note that you get *no* output
1759 ;; unless this spits out a complete line, including the '\n' at the
1760 ;; end.
1761 ;; The device number is returned as "-1", because there will be a virtual
1762 ;; device number set in `tramp-handle-file-attributes'.
1763 (defconst tramp-perl-file-attributes
1764 "%s -e '
1765 @stat = lstat($ARGV[0]);
1766 if (!@stat) {
1767 print \"nil\\n\";
1768 exit 0;
1769 }
1770 if (($stat[2] & 0170000) == 0120000)
1771 {
1772 $type = readlink($ARGV[0]);
1773 $type = \"\\\"$type\\\"\";
1774 }
1775 elsif (($stat[2] & 0170000) == 040000)
1776 {
1777 $type = \"t\";
1778 }
1779 else
1780 {
1781 $type = \"nil\"
1782 };
1783 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1784 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1785 printf(
1786 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1787 $type,
1788 $stat[3],
1789 $uid,
1790 $gid,
1791 $stat[8] >> 16 & 0xffff,
1792 $stat[8] & 0xffff,
1793 $stat[9] >> 16 & 0xffff,
1794 $stat[9] & 0xffff,
1795 $stat[10] >> 16 & 0xffff,
1796 $stat[10] & 0xffff,
1797 $stat[7],
1798 $stat[2],
1799 $stat[1] >> 16 & 0xffff,
1800 $stat[1] & 0xffff
1801 );' \"$1\" \"$2\" 2>/dev/null"
1802 "Perl script to produce output suitable for use with `file-attributes'
1803 on the remote file system.
1804 Escape sequence %s is replaced with name of Perl binary.
1805 This string is passed to `format', so percent characters need to be doubled.")
1806
1807 (defconst tramp-perl-directory-files-and-attributes
1808 "%s -e '
1809 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1810 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1811 @list = readdir(DIR);
1812 closedir(DIR);
1813 $n = scalar(@list);
1814 printf(\"(\\n\");
1815 for($i = 0; $i < $n; $i++)
1816 {
1817 $filename = $list[$i];
1818 @stat = lstat($filename);
1819 if (($stat[2] & 0170000) == 0120000)
1820 {
1821 $type = readlink($filename);
1822 $type = \"\\\"$type\\\"\";
1823 }
1824 elsif (($stat[2] & 0170000) == 040000)
1825 {
1826 $type = \"t\";
1827 }
1828 else
1829 {
1830 $type = \"nil\"
1831 };
1832 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1833 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1834 printf(
1835 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1836 $filename,
1837 $type,
1838 $stat[3],
1839 $uid,
1840 $gid,
1841 $stat[8] >> 16 & 0xffff,
1842 $stat[8] & 0xffff,
1843 $stat[9] >> 16 & 0xffff,
1844 $stat[9] & 0xffff,
1845 $stat[10] >> 16 & 0xffff,
1846 $stat[10] & 0xffff,
1847 $stat[7],
1848 $stat[2],
1849 $stat[1] >> 16 & 0xffff,
1850 $stat[1] & 0xffff,
1851 $stat[0] >> 16 & 0xffff,
1852 $stat[0] & 0xffff);
1853 }
1854 printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
1855 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1856 output.
1857 Escape sequence %s is replaced with name of Perl binary.
1858 This string is passed to `format', so percent characters need to be doubled.")
1859
1860 ;; ;; These two use uu encoding.
1861 ;; (defvar tramp-perl-encode "%s -e'\
1862 ;; print qq(begin 644 xxx\n);
1863 ;; my $s = q();
1864 ;; my $res = q();
1865 ;; while (read(STDIN, $s, 45)) {
1866 ;; print pack(q(u), $s);
1867 ;; }
1868 ;; print qq(`\n);
1869 ;; print qq(end\n);
1870 ;; '"
1871 ;; "Perl program to use for encoding a file.
1872 ;; Escape sequence %s is replaced with name of Perl binary.")
1873
1874 ;; (defvar tramp-perl-decode "%s -ne '
1875 ;; print unpack q(u), $_;
1876 ;; '"
1877 ;; "Perl program to use for decoding a file.
1878 ;; Escape sequence %s is replaced with name of Perl binary.")
1879
1880 ;; These two use base64 encoding.
1881 (defconst tramp-perl-encode-with-module
1882 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1883 "Perl program to use for encoding a file.
1884 Escape sequence %s is replaced with name of Perl binary.
1885 This string is passed to `format', so percent characters need to be doubled.
1886 This implementation requires the MIME::Base64 Perl module to be installed
1887 on the remote host.")
1888
1889 (defconst tramp-perl-decode-with-module
1890 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1891 "Perl program to use for decoding a file.
1892 Escape sequence %s is replaced with name of Perl binary.
1893 This string is passed to `format', so percent characters need to be doubled.
1894 This implementation requires the MIME::Base64 Perl module to be installed
1895 on the remote host.")
1896
1897 (defconst tramp-perl-encode
1898 "%s -e '
1899 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1900 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1901 # Free Software Foundation, Inc.
1902 use strict;
1903
1904 my %%trans = do {
1905 my $i = 0;
1906 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1907 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1908 };
1909
1910 binmode(\\*STDIN);
1911
1912 # We read in chunks of 54 bytes, to generate output lines
1913 # of 72 chars (plus end of line)
1914 $/ = \\54;
1915
1916 while (my $data = <STDIN>) {
1917 my $pad = q();
1918
1919 # Only for the last chunk, and only if did not fill the last three-byte packet
1920 if (eof) {
1921 my $mod = length($data) %% 3;
1922 $pad = q(=) x (3 - $mod) if $mod;
1923 }
1924
1925 # Not the fastest method, but it is simple: unpack to binary string, split
1926 # by groups of 6 bits and convert back from binary to byte; then map into
1927 # the translation table
1928 print
1929 join q(),
1930 map($trans{$_},
1931 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1932 $pad,
1933 qq(\\n);
1934 }' 2>/dev/null"
1935 "Perl program to use for encoding a file.
1936 Escape sequence %s is replaced with name of Perl binary.
1937 This string is passed to `format', so percent characters need to be doubled.")
1938
1939 (defconst tramp-perl-decode
1940 "%s -e '
1941 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1942 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1943 # Free Software Foundation, Inc.
1944 use strict;
1945
1946 my %%trans = do {
1947 my $i = 0;
1948 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1949 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1950 };
1951
1952 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1953
1954 binmode(\\*STDOUT);
1955
1956 # We are going to accumulate into $pending to accept any line length
1957 # (we do not check they are <= 76 chars as the RFC says)
1958 my $pending = q();
1959
1960 while (my $data = <STDIN>) {
1961 chomp $data;
1962
1963 # If we find one or two =, we have reached the end and
1964 # any following data is to be discarded
1965 my $finished = $data =~ s/(==?).*/$1/;
1966 $pending .= $data;
1967
1968 my $len = length($pending);
1969 my $chunk = substr($pending, 0, $len & ~3);
1970 $pending = substr($pending, $len & ~3 + 1);
1971
1972 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1973 # split in 8-bit chunks and convert back to char.
1974 print join q(),
1975 map $bytes{$_},
1976 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1977
1978 last if $finished;
1979 }' 2>/dev/null"
1980 "Perl program to use for decoding a file.
1981 Escape sequence %s is replaced with name of Perl binary.
1982 This string is passed to `format', so percent characters need to be doubled.")
1983
1984 (defconst tramp-vc-registered-read-file-names
1985 "echo \"(\"
1986 for file in \"$@\"; do
1987 if %s $file; then
1988 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1989 else
1990 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1991 fi
1992 if %s $file; then
1993 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1994 else
1995 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1996 fi
1997 done
1998 echo \")\""
1999 "Script to check existence of VC related files.
2000 It must be send formatted with two strings; the tests for file
2001 existence, and file readability.")
2002
2003 (defconst tramp-file-mode-type-map
2004 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
2005 (1 . "p") ; fifo
2006 (2 . "c") ; character device
2007 (3 . "m") ; multiplexed character device (v7)
2008 (4 . "d") ; directory
2009 (5 . "?") ; Named special file (XENIX)
2010 (6 . "b") ; block device
2011 (7 . "?") ; multiplexed block device (v7)
2012 (8 . "-") ; regular file
2013 (9 . "n") ; network special file (HP-UX)
2014 (10 . "l") ; symlink
2015 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
2016 (12 . "s") ; socket
2017 (13 . "D") ; door special (Solaris)
2018 (14 . "w")) ; whiteout (BSD)
2019 "A list of file types returned from the `stat' system call.
2020 This is used to map a mode number to a permission string.")
2021
2022 ;; New handlers should be added here. The following operations can be
2023 ;; handled using the normal primitives: file-name-sans-versions,
2024 ;; get-file-buffer.
2025 (defconst tramp-file-name-handler-alist
2026 '((load . tramp-handle-load)
2027 (make-symbolic-link . tramp-handle-make-symbolic-link)
2028 (file-name-as-directory . tramp-handle-file-name-as-directory)
2029 (file-name-directory . tramp-handle-file-name-directory)
2030 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
2031 (file-truename . tramp-handle-file-truename)
2032 (file-exists-p . tramp-handle-file-exists-p)
2033 (file-directory-p . tramp-handle-file-directory-p)
2034 (file-executable-p . tramp-handle-file-executable-p)
2035 (file-readable-p . tramp-handle-file-readable-p)
2036 (file-regular-p . tramp-handle-file-regular-p)
2037 (file-symlink-p . tramp-handle-file-symlink-p)
2038 (file-writable-p . tramp-handle-file-writable-p)
2039 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
2040 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
2041 (file-attributes . tramp-handle-file-attributes)
2042 (file-modes . tramp-handle-file-modes)
2043 (directory-files . tramp-handle-directory-files)
2044 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
2045 (file-name-all-completions . tramp-handle-file-name-all-completions)
2046 (file-name-completion . tramp-handle-file-name-completion)
2047 (add-name-to-file . tramp-handle-add-name-to-file)
2048 (copy-file . tramp-handle-copy-file)
2049 (copy-directory . tramp-handle-copy-directory)
2050 (rename-file . tramp-handle-rename-file)
2051 (set-file-modes . tramp-handle-set-file-modes)
2052 (set-file-times . tramp-handle-set-file-times)
2053 (make-directory . tramp-handle-make-directory)
2054 (delete-directory . tramp-handle-delete-directory)
2055 (delete-file . tramp-handle-delete-file)
2056 (directory-file-name . tramp-handle-directory-file-name)
2057 ;; `executable-find' is not official yet.
2058 (executable-find . tramp-handle-executable-find)
2059 (start-file-process . tramp-handle-start-file-process)
2060 (process-file . tramp-handle-process-file)
2061 (shell-command . tramp-handle-shell-command)
2062 (insert-directory . tramp-handle-insert-directory)
2063 (expand-file-name . tramp-handle-expand-file-name)
2064 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2065 (file-local-copy . tramp-handle-file-local-copy)
2066 (file-remote-p . tramp-handle-file-remote-p)
2067 (insert-file-contents . tramp-handle-insert-file-contents)
2068 (insert-file-contents-literally
2069 . tramp-handle-insert-file-contents-literally)
2070 (write-region . tramp-handle-write-region)
2071 (find-backup-file-name . tramp-handle-find-backup-file-name)
2072 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2073 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2074 (dired-compress-file . tramp-handle-dired-compress-file)
2075 (dired-recursive-delete-directory
2076 . tramp-handle-dired-recursive-delete-directory)
2077 (dired-uncache . tramp-handle-dired-uncache)
2078 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2079 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2080 (file-selinux-context . tramp-handle-file-selinux-context)
2081 (set-file-selinux-context . tramp-handle-set-file-selinux-context)
2082 (vc-registered . tramp-handle-vc-registered))
2083 "Alist of handler functions.
2084 Operations not mentioned here will be handled by the normal Emacs functions.")
2085
2086 ;; Handlers for partial Tramp file names. For Emacs just
2087 ;; `file-name-all-completions' is needed.
2088 ;;;###autoload
2089 (defconst tramp-completion-file-name-handler-alist
2090 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2091 (file-name-completion . tramp-completion-handle-file-name-completion))
2092 "Alist of completion handler functions.
2093 Used for file names matching `tramp-file-name-regexp'. Operations not
2094 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2095 normal Emacs functions.")
2096
2097 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2098 (defvar tramp-foreign-file-name-handler-alist
2099 ;; (identity . tramp-sh-file-name-handler) should always be the last
2100 ;; entry, because `identity' always matches.
2101 '((identity . tramp-sh-file-name-handler))
2102 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2103 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2104 calling HANDLER.")
2105
2106 ;;; Internal functions which must come first:
2107
2108 (defsubst tramp-debug-message (vec fmt-string &rest args)
2109 "Append message to debug buffer.
2110 Message is formatted with FMT-STRING as control string and the remaining
2111 ARGS to actually emit the message (if applicable)."
2112 (when (get-buffer (tramp-buffer-name vec))
2113 (with-current-buffer (tramp-get-debug-buffer vec)
2114 (goto-char (point-max))
2115 ;; Headline.
2116 (when (bobp)
2117 (insert
2118 (format
2119 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2120 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2121 emacs-version tramp-version)))
2122 (unless (bolp)
2123 (insert "\n"))
2124 ;; Timestamp.
2125 (let ((now (current-time)))
2126 (insert (format-time-string "%T." now))
2127 (insert (format "%06d " (nth 2 now))))
2128 ;; Calling function.
2129 (let ((btn 1) btf fn)
2130 (while (not fn)
2131 (setq btf (nth 1 (backtrace-frame btn)))
2132 (if (not btf)
2133 (setq fn "")
2134 (when (symbolp btf)
2135 (setq fn (symbol-name btf))
2136 (unless (and (string-match "^tramp" fn)
2137 (not (string-match
2138 "^tramp\\(-debug\\)?\\(-message\\|-error\\|-compat-funcall\\)$"
2139 fn)))
2140 (setq fn nil)))
2141 (setq btn (1+ btn))))
2142 ;; The following code inserts filename and line number.
2143 ;; Should be deactivated by default, because it is time
2144 ;; consuming.
2145 ; (let ((ffn (find-function-noselect (intern fn))))
2146 ; (insert
2147 ; (format
2148 ; "%s:%d: "
2149 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2150 ; (with-current-buffer (car ffn)
2151 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2152 (insert (format "%s " fn)))
2153 ;; The message.
2154 (insert (apply 'format fmt-string args)))))
2155
2156 (defvar tramp-message-show-message t
2157 "Show Tramp message in the minibuffer.
2158 This variable is used to disable messages from `tramp-error'.
2159 The messages are visible anyway, because an error is raised.")
2160
2161 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2162 "Emit a message depending on verbosity level.
2163 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2164 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2165 less than LEVEL. The message is emitted only if `tramp-verbose' is
2166 greater than or equal to LEVEL.
2167
2168 The message is also logged into the debug buffer when `tramp-verbose'
2169 is greater than or equal 4.
2170
2171 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2172 control string and the remaining ARGS to actually emit the message (if
2173 applicable)."
2174 (condition-case nil
2175 (when (<= level tramp-verbose)
2176 ;; Match data must be preserved!
2177 (save-match-data
2178 ;; Display only when there is a minimum level.
2179 (when (and tramp-message-show-message (<= level 3))
2180 (apply 'message
2181 (concat
2182 (cond
2183 ((= level 0) "")
2184 ((= level 1) "")
2185 ((= level 2) "Warning: ")
2186 (t "Tramp: "))
2187 fmt-string)
2188 args))
2189 ;; Log only when there is a minimum level.
2190 (when (>= tramp-verbose 4)
2191 (when (and vec-or-proc
2192 (processp vec-or-proc)
2193 (buffer-name (process-buffer vec-or-proc)))
2194 (with-current-buffer (process-buffer vec-or-proc)
2195 ;; Translate proc to vec.
2196 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2197 (when (and vec-or-proc (vectorp vec-or-proc))
2198 (apply 'tramp-debug-message
2199 vec-or-proc
2200 (concat (format "(%d) # " level) fmt-string)
2201 args)))))
2202 ;; Suppress all errors.
2203 (error nil)))
2204
2205 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2206 "Emit an error.
2207 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2208 signal identifier to be raised, remaining args passed to
2209 `tramp-message'. Finally, signal SIGNAL is raised."
2210 (let (tramp-message-show-message)
2211 (tramp-message
2212 vec-or-proc 1 "%s"
2213 (error-message-string
2214 (list signal
2215 (get signal 'error-message)
2216 (apply 'format fmt-string args))))
2217 (signal signal (list (apply 'format fmt-string args)))))
2218
2219 (defsubst tramp-error-with-buffer
2220 (buffer vec-or-proc signal fmt-string &rest args)
2221 "Emit an error, and show BUFFER.
2222 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2223 an input event arrives. The other arguments are passed to `tramp-error'."
2224 (save-window-excursion
2225 (unwind-protect
2226 (apply 'tramp-error vec-or-proc signal fmt-string args)
2227 (when (and vec-or-proc
2228 (not (zerop tramp-verbose))
2229 (not (tramp-completion-mode-p)))
2230 (let ((enable-recursive-minibuffers t))
2231 (pop-to-buffer
2232 (or (and (bufferp buffer) buffer)
2233 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2234 (tramp-get-buffer vec-or-proc)))
2235 (sit-for 30))))))
2236
2237 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2238 "Parse a Tramp filename and make components available in the body.
2239
2240 First arg FILENAME is evaluated and dissected into its components.
2241 Second arg VAR is a symbol. It is used as a variable name to hold
2242 the filename structure. It is also used as a prefix for the variables
2243 holding the components. For example, if VAR is the symbol `foo', then
2244 `foo' will be bound to the whole structure, `foo-method' will be bound to
2245 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2246
2247 Remaining args are Lisp expressions to be evaluated (inside an implicit
2248 `progn').
2249
2250 If VAR is nil, then we bind `v' to the structure and `method', `user',
2251 `host', `localname' to the components."
2252 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2253 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2254 (tramp-file-name-method ,(or var 'v)))
2255 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2256 (tramp-file-name-user ,(or var 'v)))
2257 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2258 (tramp-file-name-host ,(or var 'v)))
2259 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2260 (tramp-file-name-localname ,(or var 'v))))
2261 ,@body))
2262
2263 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2264 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2265 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2266
2267 (defmacro with-file-property (vec file property &rest body)
2268 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2269 FILE must be a local file name on a connection identified via VEC."
2270 `(if (file-name-absolute-p ,file)
2271 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2272 (when (eq value 'undef)
2273 ;; We cannot pass @body as parameter to
2274 ;; `tramp-set-file-property' because it mangles our
2275 ;; debug messages.
2276 (setq value (progn ,@body))
2277 (tramp-set-file-property ,vec ,file ,property value))
2278 value)
2279 ,@body))
2280
2281 (put 'with-file-property 'lisp-indent-function 3)
2282 (put 'with-file-property 'edebug-form-spec t)
2283 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2284
2285 (defmacro with-connection-property (key property &rest body)
2286 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
2287 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2288 (when (eq value 'undef)
2289 ;; We cannot pass ,@body as parameter to
2290 ;; `tramp-set-connection-property' because it mangles our debug
2291 ;; messages.
2292 (setq value (progn ,@body))
2293 (tramp-set-connection-property ,key ,property value))
2294 value))
2295
2296 (put 'with-connection-property 'lisp-indent-function 2)
2297 (put 'with-connection-property 'edebug-form-spec t)
2298 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2299
2300 (defun tramp-progress-reporter-update (reporter &optional value)
2301 (let* ((parameters (cdr reporter))
2302 (message (aref parameters 3)))
2303 (when (string-match message (or (current-message) ""))
2304 (funcall 'progress-reporter-update reporter value))))
2305
2306 (defmacro with-progress-reporter (vec level message &rest body)
2307 "Executes BODY, spinning a progress reporter with MESSAGE.
2308 If LEVEL does not fit for visible messages, or if this is a
2309 nested call of the macro, there are only traces without a visible
2310 progress reporter."
2311 `(let (pr tm)
2312 (tramp-message ,vec ,level "%s..." ,message)
2313 ;; We start a pulsing progress reporter after 3 seconds. Feature
2314 ;; introduced in Emacs 24.1.
2315 (when (and tramp-message-show-message
2316 ;; Display only when there is a minimum level.
2317 (<= ,level (min tramp-verbose 3)))
2318 (condition-case nil
2319 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
2320 tm (when pr
2321 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))
2322 (error nil)))
2323 (unwind-protect
2324 ;; Execute the body. Unset `tramp-message-show-message' when
2325 ;; the timer object is created, in order to suppress
2326 ;; concurrent timers.
2327 (let ((tramp-message-show-message
2328 (and tramp-message-show-message (not tm))))
2329 ,@body)
2330 ;; Stop progress reporter.
2331 (if tm (tramp-compat-funcall 'cancel-timer tm))
2332 (tramp-message ,vec ,level "%s...done" ,message))))
2333
2334 (put 'with-progress-reporter 'lisp-indent-function 3)
2335 (put 'with-progress-reporter 'edebug-form-spec t)
2336 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
2337
2338 (eval-and-compile ;; Silence compiler.
2339 (if (memq system-type '(cygwin windows-nt))
2340 (defun tramp-drop-volume-letter (name)
2341 "Cut off unnecessary drive letter from file NAME.
2342 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2343 locally on a remote file name. When the local system is a W32 system
2344 but the remote system is Unix, this introduces a superfluous drive
2345 letter into the file name. This function removes it."
2346 (save-match-data
2347 (if (string-match tramp-root-regexp name)
2348 (replace-match "/" nil t name)
2349 name)))
2350
2351 (defalias 'tramp-drop-volume-letter 'identity)))
2352
2353 (defsubst tramp-make-tramp-temp-file (vec)
2354 "Create a temporary file on the remote host identified by VEC.
2355 Return the local name of the temporary file."
2356 (let ((prefix
2357 (tramp-make-tramp-file-name
2358 (tramp-file-name-method vec)
2359 (tramp-file-name-user vec)
2360 (tramp-file-name-host vec)
2361 (tramp-drop-volume-letter
2362 (expand-file-name
2363 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2364 result)
2365 (while (not result)
2366 ;; `make-temp-file' would be the natural choice for
2367 ;; implementation. But it calls `write-region' internally,
2368 ;; which also needs a temporary file - we would end in an
2369 ;; infinite loop.
2370 (setq result (make-temp-name prefix))
2371 (if (file-exists-p result)
2372 (setq result nil)
2373 ;; This creates the file by side effect.
2374 (set-file-times result)
2375 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2376
2377 ;; Return the local part.
2378 (with-parsed-tramp-file-name result nil localname)))
2379
2380
2381 ;;; Config Manipulation Functions:
2382
2383 (defun tramp-set-completion-function (method function-list)
2384 "Sets the list of completion functions for METHOD.
2385 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2386 The FUNCTION is intended to parse FILE according its syntax.
2387 It might be a predefined FUNCTION, or a user defined FUNCTION.
2388 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2389 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2390 and `tramp-parse-netrc'.
2391
2392 Example:
2393
2394 (tramp-set-completion-function
2395 \"ssh\"
2396 '((tramp-parse-sconfig \"/etc/ssh_config\")
2397 (tramp-parse-sconfig \"~/.ssh/config\")))"
2398
2399 (let ((r function-list)
2400 (v function-list))
2401 (setq tramp-completion-function-alist
2402 (delete (assoc method tramp-completion-function-alist)
2403 tramp-completion-function-alist))
2404
2405 (while v
2406 ;; Remove double entries.
2407 (when (member (car v) (cdr v))
2408 (setcdr v (delete (car v) (cdr v))))
2409 ;; Check for function and file or registry key.
2410 (unless (and (functionp (nth 0 (car v)))
2411 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2412 ;; Windows registry.
2413 (and (memq system-type '(cygwin windows-nt))
2414 (zerop
2415 (tramp-local-call-process
2416 "reg" nil nil nil "query" (nth 1 (car v)))))
2417 ;; Configuration file.
2418 (file-exists-p (nth 1 (car v)))))
2419 (setq r (delete (car v) r)))
2420 (setq v (cdr v)))
2421
2422 (when r
2423 (add-to-list 'tramp-completion-function-alist
2424 (cons method r)))))
2425
2426 (defun tramp-get-completion-function (method)
2427 "Returns a list of completion functions for METHOD.
2428 For definition of that list see `tramp-set-completion-function'."
2429 (cons
2430 ;; Hosts visited once shall be remembered.
2431 `(tramp-parse-connection-properties ,method)
2432 ;; The method related defaults.
2433 (cdr (assoc method tramp-completion-function-alist))))
2434
2435
2436 ;;; Fontification of `read-file-name':
2437
2438 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2439 (defvar tramp-rfn-eshadow-overlay)
2440 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2441
2442 (defun tramp-rfn-eshadow-setup-minibuffer ()
2443 "Set up a minibuffer for `file-name-shadow-mode'.
2444 Adds another overlay hiding filename parts according to Tramp's
2445 special handling of `substitute-in-file-name'."
2446 (when (symbol-value 'minibuffer-completing-file-name)
2447 (setq tramp-rfn-eshadow-overlay
2448 (tramp-compat-funcall
2449 'make-overlay
2450 (tramp-compat-funcall 'minibuffer-prompt-end)
2451 (tramp-compat-funcall 'minibuffer-prompt-end)))
2452 ;; Copy rfn-eshadow-overlay properties.
2453 (let ((props (tramp-compat-funcall
2454 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
2455 (while props
2456 (tramp-compat-funcall
2457 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2458
2459 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2460 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2461 'tramp-rfn-eshadow-setup-minibuffer)
2462 (add-hook 'tramp-unload-hook
2463 (lambda ()
2464 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2465 'tramp-rfn-eshadow-setup-minibuffer))))
2466
2467 (defconst tramp-rfn-eshadow-update-overlay-regexp
2468 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2469
2470 (defun tramp-rfn-eshadow-update-overlay ()
2471 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2472 This is intended to be used as a minibuffer `post-command-hook' for
2473 `file-name-shadow-mode'; the minibuffer should have already
2474 been set up by `rfn-eshadow-setup-minibuffer'."
2475 ;; In remote files name, there is a shadowing just for the local part.
2476 (let ((end (or (tramp-compat-funcall
2477 'overlay-end (symbol-value 'rfn-eshadow-overlay))
2478 (tramp-compat-funcall 'minibuffer-prompt-end))))
2479 (when
2480 (file-remote-p
2481 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
2482 (save-excursion
2483 (save-restriction
2484 (narrow-to-region
2485 (1+ (or (string-match
2486 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2487 end))
2488 (point-max))
2489 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2490 (rfn-eshadow-update-overlay-hook nil))
2491 (tramp-compat-funcall
2492 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
2493 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
2494
2495 (when (boundp 'rfn-eshadow-update-overlay-hook)
2496 (add-hook 'rfn-eshadow-update-overlay-hook
2497 'tramp-rfn-eshadow-update-overlay)
2498 (add-hook 'tramp-unload-hook
2499 (lambda ()
2500 (remove-hook 'rfn-eshadow-update-overlay-hook
2501 'tramp-rfn-eshadow-update-overlay))))
2502
2503
2504 ;;; Integration of eshell.el:
2505
2506 (eval-when-compile
2507 (defvar eshell-path-env))
2508
2509 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2510 ;; when `default-directory' points to another host.
2511 (defun tramp-eshell-directory-change ()
2512 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2513 (setq eshell-path-env
2514 (if (file-remote-p default-directory)
2515 (with-parsed-tramp-file-name default-directory nil
2516 (mapconcat
2517 'identity
2518 (tramp-get-remote-path v)
2519 ":"))
2520 (getenv "PATH"))))
2521
2522 (eval-after-load "esh-util"
2523 '(progn
2524 (tramp-eshell-directory-change)
2525 (add-hook 'eshell-directory-change-hook
2526 'tramp-eshell-directory-change)
2527 (add-hook 'tramp-unload-hook
2528 (lambda ()
2529 (remove-hook 'eshell-directory-change-hook
2530 'tramp-eshell-directory-change)))))
2531
2532
2533 ;;; File Name Handler Functions:
2534
2535 (defun tramp-handle-make-symbolic-link
2536 (filename linkname &optional ok-if-already-exists)
2537 "Like `make-symbolic-link' for Tramp files.
2538 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2539 the symlink. If LINKNAME is a Tramp file, only the localname component is
2540 used as the target of the symlink.
2541
2542 If LINKNAME is a Tramp file and the localname component is relative, then
2543 it is expanded first, before the localname component is taken. Note that
2544 this can give surprising results if the user/host for the source and
2545 target of the symlink differ."
2546 (with-parsed-tramp-file-name linkname l
2547 (let ((ln (tramp-get-remote-ln l))
2548 (cwd (tramp-run-real-handler
2549 'file-name-directory (list l-localname))))
2550 (unless ln
2551 (tramp-error
2552 l 'file-error
2553 "Making a symbolic link. ln(1) does not exist on the remote host."))
2554
2555 ;; Do the 'confirm if exists' thing.
2556 (when (file-exists-p linkname)
2557 ;; What to do?
2558 (if (or (null ok-if-already-exists) ; not allowed to exist
2559 (and (numberp ok-if-already-exists)
2560 (not (yes-or-no-p
2561 (format
2562 "File %s already exists; make it a link anyway? "
2563 l-localname)))))
2564 (tramp-error
2565 l 'file-already-exists "File %s already exists" l-localname)
2566 (delete-file linkname)))
2567
2568 ;; If FILENAME is a Tramp name, use just the localname component.
2569 (when (tramp-tramp-file-p filename)
2570 (setq filename
2571 (tramp-file-name-localname
2572 (tramp-dissect-file-name (expand-file-name filename)))))
2573
2574 ;; Right, they are on the same host, regardless of user, method, etc.
2575 ;; We now make the link on the remote machine. This will occur as the user
2576 ;; that FILENAME belongs to.
2577 (zerop
2578 (tramp-send-command-and-check
2579 l
2580 (format
2581 "cd %s && %s -sf %s %s"
2582 (tramp-shell-quote-argument cwd)
2583 ln
2584 (tramp-shell-quote-argument filename)
2585 (tramp-shell-quote-argument l-localname))
2586 t)))))
2587
2588 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2589 "Like `load' for Tramp files."
2590 (with-parsed-tramp-file-name (expand-file-name file) nil
2591 (unless nosuffix
2592 (cond ((file-exists-p (concat file ".elc"))
2593 (setq file (concat file ".elc")))
2594 ((file-exists-p (concat file ".el"))
2595 (setq file (concat file ".el")))))
2596 (when must-suffix
2597 ;; The first condition is always true for absolute file names.
2598 ;; Included for safety's sake.
2599 (unless (or (file-name-directory file)
2600 (string-match "\\.elc?\\'" file))
2601 (tramp-error
2602 v 'file-error
2603 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2604 (unless noerror
2605 (when (not (file-exists-p file))
2606 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2607 (if (not (file-exists-p file))
2608 nil
2609 (let ((tramp-message-show-message (not nomessage)))
2610 (with-progress-reporter v 0 (format "Loading %s" file)
2611 (let ((local-copy (file-local-copy file)))
2612 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2613 (unwind-protect
2614 (load local-copy noerror t t)
2615 (delete-file local-copy)))))
2616 t)))
2617
2618 ;; Localname manipulation functions that grok Tramp localnames...
2619 (defun tramp-handle-file-name-as-directory (file)
2620 "Like `file-name-as-directory' but aware of Tramp files."
2621 ;; `file-name-as-directory' would be sufficient except localname is
2622 ;; the empty string.
2623 (let ((v (tramp-dissect-file-name file t)))
2624 ;; Run the command on the localname portion only.
2625 (tramp-make-tramp-file-name
2626 (tramp-file-name-method v)
2627 (tramp-file-name-user v)
2628 (tramp-file-name-host v)
2629 (tramp-run-real-handler
2630 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2631
2632 (defun tramp-handle-file-name-directory (file)
2633 "Like `file-name-directory' but aware of Tramp files."
2634 ;; Everything except the last filename thing is the directory. We
2635 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2636 ;; the remote file name parts. This is a problem when we are in
2637 ;; file name completion.
2638 (let ((v (tramp-dissect-file-name file t)))
2639 ;; Run the command on the localname portion only.
2640 (tramp-make-tramp-file-name
2641 (tramp-file-name-method v)
2642 (tramp-file-name-user v)
2643 (tramp-file-name-host v)
2644 (tramp-run-real-handler
2645 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2646
2647 (defun tramp-handle-file-name-nondirectory (file)
2648 "Like `file-name-nondirectory' but aware of Tramp files."
2649 (with-parsed-tramp-file-name file nil
2650 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2651
2652 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2653 "Like `file-truename' for Tramp files."
2654 (with-parsed-tramp-file-name (expand-file-name filename) nil
2655 (with-file-property v localname "file-truename"
2656 (let ((result nil)) ; result steps in reverse order
2657 (tramp-message v 4 "Finding true name for `%s'" filename)
2658 (cond
2659 ;; Use GNU readlink --canonicalize-missing where available.
2660 ((tramp-get-remote-readlink v)
2661 (setq result
2662 (tramp-send-command-and-read
2663 v
2664 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2665 (tramp-get-remote-readlink v)
2666 (tramp-shell-quote-argument localname)))))
2667
2668 ;; Use Perl implementation.
2669 ((and (tramp-get-remote-perl v)
2670 (tramp-get-connection-property v "perl-file-spec" nil)
2671 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2672 (tramp-maybe-send-script
2673 v tramp-perl-file-truename "tramp_perl_file_truename")
2674 (setq result
2675 (tramp-send-command-and-read
2676 v
2677 (format "tramp_perl_file_truename %s"
2678 (tramp-shell-quote-argument localname)))))
2679
2680 ;; Do it yourself. We bind `directory-sep-char' here for
2681 ;; XEmacs on Windows, which would otherwise use backslash.
2682 (t (let* ((directory-sep-char ?/)
2683 (steps (tramp-compat-split-string localname "/"))
2684 (localnamedir (tramp-run-real-handler
2685 'file-name-as-directory (list localname)))
2686 (is-dir (string= localname localnamedir))
2687 (thisstep nil)
2688 (numchase 0)
2689 ;; Don't make the following value larger than
2690 ;; necessary. People expect an error message in a
2691 ;; timely fashion when something is wrong;
2692 ;; otherwise they might think that Emacs is hung.
2693 ;; Of course, correctness has to come first.
2694 (numchase-limit 20)
2695 symlink-target)
2696 (while (and steps (< numchase numchase-limit))
2697 (setq thisstep (pop steps))
2698 (tramp-message
2699 v 5 "Check %s"
2700 (mapconcat 'identity
2701 (append '("") (reverse result) (list thisstep))
2702 "/"))
2703 (setq symlink-target
2704 (nth 0 (file-attributes
2705 (tramp-make-tramp-file-name
2706 method user host
2707 (mapconcat 'identity
2708 (append '("")
2709 (reverse result)
2710 (list thisstep))
2711 "/")))))
2712 (cond ((string= "." thisstep)
2713 (tramp-message v 5 "Ignoring step `.'"))
2714 ((string= ".." thisstep)
2715 (tramp-message v 5 "Processing step `..'")
2716 (pop result))
2717 ((stringp symlink-target)
2718 ;; It's a symlink, follow it.
2719 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2720 (setq numchase (1+ numchase))
2721 (when (file-name-absolute-p symlink-target)
2722 (setq result nil))
2723 ;; If the symlink was absolute, we'll get a string like
2724 ;; "/user@host:/some/target"; extract the
2725 ;; "/some/target" part from it.
2726 (when (tramp-tramp-file-p symlink-target)
2727 (unless (tramp-equal-remote filename symlink-target)
2728 (tramp-error
2729 v 'file-error
2730 "Symlink target `%s' on wrong host" symlink-target))
2731 (setq symlink-target localname))
2732 (setq steps
2733 (append (tramp-compat-split-string
2734 symlink-target "/")
2735 steps)))
2736 (t
2737 ;; It's a file.
2738 (setq result (cons thisstep result)))))
2739 (when (>= numchase numchase-limit)
2740 (tramp-error
2741 v 'file-error
2742 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2743 (setq result (reverse result))
2744 ;; Combine list to form string.
2745 (setq result
2746 (if result
2747 (mapconcat 'identity (cons "" result) "/")
2748 "/"))
2749 (when (and is-dir (or (string= "" result)
2750 (not (string= (substring result -1) "/"))))
2751 (setq result (concat result "/"))))))
2752
2753 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2754 (tramp-make-tramp-file-name method user host result)))))
2755
2756 ;; Basic functions.
2757
2758 (defun tramp-handle-file-exists-p (filename)
2759 "Like `file-exists-p' for Tramp files."
2760 (with-parsed-tramp-file-name filename nil
2761 (with-file-property v localname "file-exists-p"
2762 (or (not (null (tramp-get-file-property
2763 v localname "file-attributes-integer" nil)))
2764 (not (null (tramp-get-file-property
2765 v localname "file-attributes-string" nil)))
2766 (zerop (tramp-send-command-and-check
2767 v
2768 (format
2769 "%s %s"
2770 (tramp-get-file-exists-command v)
2771 (tramp-shell-quote-argument localname))))))))
2772
2773 ;; Inodes don't exist for some file systems. Therefore we must
2774 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2775 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2776 ;; performance isn't the major issue given that file transfer will
2777 ;; take time.
2778 (defvar tramp-inodes nil
2779 "Keeps virtual inodes numbers.")
2780
2781 ;; Devices must distinguish physical file systems. The device numbers
2782 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2783 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2784 ;; EFS use device number "-1". In order to be different, we use device number
2785 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2786 (defvar tramp-devices nil
2787 "Keeps virtual device numbers.")
2788
2789 ;; CCC: This should check for an error condition and signal failure
2790 ;; when something goes wrong.
2791 ;; Daniel Pittman <daniel@danann.net>
2792 (defun tramp-handle-file-attributes (filename &optional id-format)
2793 "Like `file-attributes' for Tramp files."
2794 (unless id-format (setq id-format 'integer))
2795 ;; Don't modify `last-coding-system-used' by accident.
2796 (let ((last-coding-system-used last-coding-system-used))
2797 (with-parsed-tramp-file-name (expand-file-name filename) nil
2798 (with-file-property v localname (format "file-attributes-%s" id-format)
2799 (save-excursion
2800 (tramp-convert-file-attributes
2801 v
2802 (cond
2803 ((tramp-get-remote-stat v)
2804 (tramp-do-file-attributes-with-stat v localname id-format))
2805 ((tramp-get-remote-perl v)
2806 (tramp-do-file-attributes-with-perl v localname id-format))
2807 (t
2808 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2809
2810 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2811 "Implement `file-attributes' for Tramp files using the ls(1) command."
2812 (let (symlinkp dirp
2813 res-inode res-filemodes res-numlinks
2814 res-uid res-gid res-size res-symlink-target)
2815 (tramp-message vec 5 "file attributes with ls: %s" localname)
2816 (tramp-send-command
2817 vec
2818 (format "(%s %s || %s -h %s) && %s %s %s"
2819 (tramp-get-file-exists-command vec)
2820 (tramp-shell-quote-argument localname)
2821 (tramp-get-test-command vec)
2822 (tramp-shell-quote-argument localname)
2823 (tramp-get-ls-command vec)
2824 (if (eq id-format 'integer) "-ildn" "-ild")
2825 (tramp-shell-quote-argument localname)))
2826 ;; parse `ls -l' output ...
2827 (with-current-buffer (tramp-get-buffer vec)
2828 (when (> (buffer-size) 0)
2829 (goto-char (point-min))
2830 ;; ... inode
2831 (setq res-inode
2832 (condition-case err
2833 (read (current-buffer))
2834 (invalid-read-syntax
2835 (when (and (equal (cadr err)
2836 "Integer constant overflow in reader")
2837 (string-match
2838 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2839 (car (cddr err))))
2840 (let* ((big (read (substring (car (cddr err)) 0
2841 (match-beginning 1))))
2842 (small (read (match-string 1 (car (cddr err)))))
2843 (twiddle (/ small 65536)))
2844 (cons (+ big twiddle)
2845 (- small (* twiddle 65536))))))))
2846 ;; ... file mode flags
2847 (setq res-filemodes (symbol-name (read (current-buffer))))
2848 ;; ... number links
2849 (setq res-numlinks (read (current-buffer)))
2850 ;; ... uid and gid
2851 (setq res-uid (read (current-buffer)))
2852 (setq res-gid (read (current-buffer)))
2853 (if (eq id-format 'integer)
2854 (progn
2855 (unless (numberp res-uid) (setq res-uid -1))
2856 (unless (numberp res-gid) (setq res-gid -1)))
2857 (progn
2858 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2859 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2860 ;; ... size
2861 (setq res-size (read (current-buffer)))
2862 ;; From the file modes, figure out other stuff.
2863 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2864 (setq dirp (eq ?d (aref res-filemodes 0)))
2865 ;; if symlink, find out file name pointed to
2866 (when symlinkp
2867 (search-forward "-> ")
2868 (setq res-symlink-target
2869 (buffer-substring (point) (tramp-compat-line-end-position))))
2870 ;; return data gathered
2871 (list
2872 ;; 0. t for directory, string (name linked to) for symbolic
2873 ;; link, or nil.
2874 (or dirp res-symlink-target)
2875 ;; 1. Number of links to file.
2876 res-numlinks
2877 ;; 2. File uid.
2878 res-uid
2879 ;; 3. File gid.
2880 res-gid
2881 ;; 4. Last access time, as a list of two integers. First
2882 ;; integer has high-order 16 bits of time, second has low 16
2883 ;; bits.
2884 ;; 5. Last modification time, likewise.
2885 ;; 6. Last status change time, likewise.
2886 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2887 ;; 7. Size in bytes (-1, if number is out of range).
2888 res-size
2889 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2890 res-filemodes
2891 ;; 9. t if file's gid would change if file were deleted and
2892 ;; recreated. Will be set in `tramp-convert-file-attributes'
2893 t
2894 ;; 10. inode number.
2895 res-inode
2896 ;; 11. Device number. Will be replaced by a virtual device number.
2897 -1
2898 )))))
2899
2900 (defun tramp-do-file-attributes-with-perl
2901 (vec localname &optional id-format)
2902 "Implement `file-attributes' for Tramp files using a Perl script."
2903 (tramp-message vec 5 "file attributes with perl: %s" localname)
2904 (tramp-maybe-send-script
2905 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2906 (tramp-send-command-and-read
2907 vec
2908 (format "tramp_perl_file_attributes %s %s"
2909 (tramp-shell-quote-argument localname) id-format)))
2910
2911 (defun tramp-do-file-attributes-with-stat
2912 (vec localname &optional id-format)
2913 "Implement `file-attributes' for Tramp files using stat(1) command."
2914 (tramp-message vec 5 "file attributes with stat: %s" localname)
2915 (tramp-send-command-and-read
2916 vec
2917 (format
2918 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
2919 ;; parse correctly the sequence "((". Therefore, we add a space.
2920 "( (%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)"
2921 (tramp-get-file-exists-command vec)
2922 (tramp-shell-quote-argument localname)
2923 (tramp-get-test-command vec)
2924 (tramp-shell-quote-argument localname)
2925 (tramp-get-remote-stat vec)
2926 (if (eq id-format 'integer) "%u" "\"%U\"")
2927 (if (eq id-format 'integer) "%g" "\"%G\"")
2928 (tramp-shell-quote-argument localname))))
2929
2930 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2931 "Like `set-visited-file-modtime' for Tramp files."
2932 (unless (buffer-file-name)
2933 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2934 (buffer-name)))
2935 (if time-list
2936 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2937 (let ((f (buffer-file-name))
2938 coding-system-used)
2939 (with-parsed-tramp-file-name f nil
2940 (let* ((attr (file-attributes f))
2941 ;; '(-1 65535) means file doesn't exists yet.
2942 (modtime (or (nth 5 attr) '(-1 65535))))
2943 (when (boundp 'last-coding-system-used)
2944 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2945 ;; We use '(0 0) as a don't-know value. See also
2946 ;; `tramp-do-file-attributes-with-ls'.
2947 (if (not (equal modtime '(0 0)))
2948 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2949 (progn
2950 (tramp-send-command
2951 v
2952 (format "%s -ild %s"
2953 (tramp-get-ls-command v)
2954 (tramp-shell-quote-argument localname)))
2955 (setq attr (buffer-substring (point)
2956 (progn (end-of-line) (point)))))
2957 (tramp-set-file-property
2958 v localname "visited-file-modtime-ild" attr))
2959 (when (boundp 'last-coding-system-used)
2960 (set 'last-coding-system-used coding-system-used))
2961 nil)))))
2962
2963 ;; This function makes the same assumption as
2964 ;; `tramp-handle-set-visited-file-modtime'.
2965 (defun tramp-handle-verify-visited-file-modtime (buf)
2966 "Like `verify-visited-file-modtime' for Tramp files.
2967 At the time `verify-visited-file-modtime' calls this function, we
2968 already know that the buffer is visiting a file and that
2969 `visited-file-modtime' does not return 0. Do not call this
2970 function directly, unless those two cases are already taken care
2971 of."
2972 (with-current-buffer buf
2973 (let ((f (buffer-file-name)))
2974 ;; There is no file visiting the buffer, or the buffer has no
2975 ;; recorded last modification time, or there is no established
2976 ;; connection.
2977 (if (or (not f)
2978 (eq (visited-file-modtime) 0)
2979 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
2980 t
2981 (with-parsed-tramp-file-name f nil
2982 (tramp-flush-file-property v localname)
2983 (let* ((attr (file-attributes f))
2984 (modtime (nth 5 attr))
2985 (mt (visited-file-modtime)))
2986
2987 (cond
2988 ;; File exists, and has a known modtime.
2989 ((and attr (not (equal modtime '(0 0))))
2990 (< (abs (tramp-time-diff
2991 modtime
2992 ;; For compatibility, deal with both the old
2993 ;; (HIGH . LOW) and the new (HIGH LOW) return
2994 ;; values of `visited-file-modtime'.
2995 (if (atom (cdr mt))
2996 (list (car mt) (cdr mt))
2997 mt)))
2998 2))
2999 ;; Modtime has the don't know value.
3000 (attr
3001 (tramp-send-command
3002 v
3003 (format "%s -ild %s"
3004 (tramp-get-ls-command v)
3005 (tramp-shell-quote-argument localname)))
3006 (with-current-buffer (tramp-get-buffer v)
3007 (setq attr (buffer-substring
3008 (point) (progn (end-of-line) (point)))))
3009 (equal
3010 attr
3011 (tramp-get-file-property
3012 v localname "visited-file-modtime-ild" "")))
3013 ;; If file does not exist, say it is not modified if and
3014 ;; only if that agrees with the buffer's record.
3015 (t (equal mt '(-1 65535))))))))))
3016
3017 (defun tramp-handle-set-file-modes (filename mode)
3018 "Like `set-file-modes' for Tramp files."
3019 (with-parsed-tramp-file-name filename nil
3020 (tramp-flush-file-property v localname)
3021 (unless (zerop (tramp-send-command-and-check
3022 v
3023 (format "chmod %s %s"
3024 (tramp-decimal-to-octal mode)
3025 (tramp-shell-quote-argument localname))))
3026 ;; FIXME: extract the proper text from chmod's stderr.
3027 (tramp-error
3028 v 'file-error "Error while changing file's mode %s" filename))))
3029
3030 (defun tramp-handle-set-file-times (filename &optional time)
3031 "Like `set-file-times' for Tramp files."
3032 (zerop
3033 (if (file-remote-p filename)
3034 (with-parsed-tramp-file-name filename nil
3035 (tramp-flush-file-property v localname)
3036 (let ((time (if (or (null time) (equal time '(0 0)))
3037 (current-time)
3038 time))
3039 ;; With GNU Emacs, `format-time-string' has an optional
3040 ;; parameter UNIVERSAL. This is preferred, because we
3041 ;; could handle the case when the remote host is
3042 ;; located in a different time zone as the local host.
3043 (utc (not (featurep 'xemacs))))
3044 (tramp-send-command-and-check
3045 v (format "%s touch -t %s %s"
3046 (if utc "TZ=UTC; export TZ;" "")
3047 (if utc
3048 (format-time-string "%Y%m%d%H%M.%S" time t)
3049 (format-time-string "%Y%m%d%H%M.%S" time))
3050 (tramp-shell-quote-argument localname)))))
3051
3052 ;; We handle also the local part, because in older Emacsen,
3053 ;; without `set-file-times', this function is an alias for this.
3054 ;; We are local, so we don't need the UTC settings.
3055 (tramp-local-call-process
3056 "touch" nil nil nil "-t"
3057 (format-time-string "%Y%m%d%H%M.%S" time)
3058 (tramp-shell-quote-argument filename)))))
3059
3060 (defun tramp-set-file-uid-gid (filename &optional uid gid)
3061 "Set the ownership for FILENAME.
3062 If UID and GID are provided, these values are used; otherwise uid
3063 and gid of the corresponding user is taken. Both parameters must be integers."
3064 ;; Modern Unices allow chown only for root. So we might need
3065 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
3066 ;; working with su(do)? when it is needed, so it shall succeed in
3067 ;; the majority of cases.
3068 ;; Don't modify `last-coding-system-used' by accident.
3069 (let ((last-coding-system-used last-coding-system-used))
3070 (if (file-remote-p filename)
3071 (with-parsed-tramp-file-name filename nil
3072 (if (and (zerop (user-uid)) (tramp-local-host-p v))
3073 ;; If we are root on the local host, we can do it directly.
3074 (tramp-set-file-uid-gid localname uid gid)
3075 (let ((uid (or (and (integerp uid) uid)
3076 (tramp-get-remote-uid v 'integer)))
3077 (gid (or (and (integerp gid) gid)
3078 (tramp-get-remote-gid v 'integer))))
3079 (tramp-send-command
3080 v (format
3081 "chown %d:%d %s" uid gid
3082 (tramp-shell-quote-argument localname))))))
3083
3084 ;; We handle also the local part, because there doesn't exist
3085 ;; `set-file-uid-gid'. On W32 "chown" might not work.
3086 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
3087 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
3088 (tramp-local-call-process
3089 "chown" nil nil nil
3090 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
3091
3092 (defun tramp-remote-selinux-p (vec)
3093 "Check, whether SELINUX is enabled on the remote host."
3094 (with-connection-property (tramp-get-connection-process vec) "selinux-p"
3095 (let ((result (tramp-find-executable
3096 vec "getenforce" (tramp-get-remote-path vec) t t)))
3097 (and result
3098 (string-equal
3099 (tramp-send-command-and-read
3100 vec (format "echo \\\"`%S`\\\"" result))
3101 "Enforcing")))))
3102
3103 (defun tramp-handle-file-selinux-context (filename)
3104 "Like `file-selinux-context' for Tramp files."
3105 (with-parsed-tramp-file-name filename nil
3106 (with-file-property v localname "file-selinux-context"
3107 (let ((context '(nil nil nil nil))
3108 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
3109 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
3110 (when (and (tramp-remote-selinux-p v)
3111 (zerop (tramp-send-command-and-check
3112 v (format
3113 "%s -d -Z %s"
3114 (tramp-get-ls-command v)
3115 (tramp-shell-quote-argument localname)))))
3116 (with-current-buffer (tramp-get-connection-buffer v)
3117 (goto-char (point-min))
3118 (when (re-search-forward regexp (tramp-compat-line-end-position) t)
3119 (setq context (list (match-string 1) (match-string 2)
3120 (match-string 3) (match-string 4))))))
3121 ;; Return the context.
3122 context))))
3123
3124 (defun tramp-handle-set-file-selinux-context (filename context)
3125 "Like `set-file-selinux-context' for Tramp files."
3126 (with-parsed-tramp-file-name filename nil
3127 (if (and (consp context)
3128 (tramp-remote-selinux-p v)
3129 (zerop (tramp-send-command-and-check
3130 v (format "chcon %s %s %s %s %s"
3131 (if (stringp (nth 0 context))
3132 (format "--user=%s" (nth 0 context)) "")
3133 (if (stringp (nth 1 context))
3134 (format "--role=%s" (nth 1 context)) "")
3135 (if (stringp (nth 2 context))
3136 (format "--type=%s" (nth 2 context)) "")
3137 (if (stringp (nth 3 context))
3138 (format "--range=%s" (nth 3 context)) "")
3139 (tramp-shell-quote-argument localname)))))
3140 (tramp-set-file-property v localname "file-selinux-context" context)
3141 (tramp-set-file-property v localname "file-selinux-context" 'undef)))
3142 ;; We always return nil.
3143 nil)
3144
3145 ;; Simple functions using the `test' command.
3146
3147 (defun tramp-handle-file-executable-p (filename)
3148 "Like `file-executable-p' for Tramp files."
3149 (with-parsed-tramp-file-name filename nil
3150 (with-file-property v localname "file-executable-p"
3151 ;; Examine `file-attributes' cache to see if request can be
3152 ;; satisfied without remote operation.
3153 (or (tramp-check-cached-permissions v ?x)
3154 (zerop (tramp-run-test "-x" filename))))))
3155
3156 (defun tramp-handle-file-readable-p (filename)
3157 "Like `file-readable-p' for Tramp files."
3158 (with-parsed-tramp-file-name filename nil
3159 (with-file-property v localname "file-readable-p"
3160 ;; Examine `file-attributes' cache to see if request can be
3161 ;; satisfied without remote operation.
3162 (or (tramp-check-cached-permissions v ?r)
3163 (zerop (tramp-run-test "-r" filename))))))
3164
3165 ;; When the remote shell is started, it looks for a shell which groks
3166 ;; tilde expansion. Here, we assume that all shells which grok tilde
3167 ;; expansion will also provide a `test' command which groks `-nt' (for
3168 ;; newer than). If this breaks, tell me about it and I'll try to do
3169 ;; something smarter about it.
3170 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3171 "Like `file-newer-than-file-p' for Tramp files."
3172 (cond ((not (file-exists-p file1))
3173 nil)
3174 ((not (file-exists-p file2))
3175 t)
3176 ;; We are sure both files exist at this point.
3177 (t
3178 (save-excursion
3179 ;; We try to get the mtime of both files. If they are not
3180 ;; equal to the "dont-know" value, then we subtract the times
3181 ;; and obtain the result.
3182 (let ((fa1 (file-attributes file1))
3183 (fa2 (file-attributes file2)))
3184 (if (and (not (equal (nth 5 fa1) '(0 0)))
3185 (not (equal (nth 5 fa2) '(0 0))))
3186 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3187 ;; If one of them is the dont-know value, then we can
3188 ;; still try to run a shell command on the remote host.
3189 ;; However, this only works if both files are Tramp
3190 ;; files and both have the same method, same user, same
3191 ;; host.
3192 (unless (tramp-equal-remote file1 file2)
3193 (with-parsed-tramp-file-name
3194 (if (tramp-tramp-file-p file1) file1 file2) nil
3195 (tramp-error
3196 v 'file-error
3197 "Files %s and %s must have same method, user, host"
3198 file1 file2)))
3199 (with-parsed-tramp-file-name file1 nil
3200 (zerop (tramp-run-test2
3201 (tramp-get-test-nt-command v) file1 file2)))))))))
3202
3203 ;; Functions implemented using the basic functions above.
3204
3205 (defun tramp-handle-file-modes (filename)
3206 "Like `file-modes' for Tramp files."
3207 (let ((truename (or (file-truename filename) filename)))
3208 (when (file-exists-p truename)
3209 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3210
3211 (defun tramp-default-file-modes (filename)
3212 "Return file modes of FILENAME as integer.
3213 If the file modes of FILENAME cannot be determined, return the
3214 value of `default-file-modes', without execute permissions."
3215 (or (file-modes filename)
3216 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3217
3218 (defun tramp-handle-file-directory-p (filename)
3219 "Like `file-directory-p' for Tramp files."
3220 ;; Care must be taken that this function returns `t' for symlinks
3221 ;; pointing to directories. Surely the most obvious implementation
3222 ;; would be `test -d', but that returns false for such symlinks.
3223 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3224 ;; I now think he's right. So we could be using `test -d', couldn't
3225 ;; we?
3226 ;;
3227 ;; Alternatives: `cd %s', `test -d %s'
3228 (with-parsed-tramp-file-name filename nil
3229 (with-file-property v localname "file-directory-p"
3230 (zerop (tramp-run-test "-d" filename)))))
3231
3232 (defun tramp-handle-file-regular-p (filename)
3233 "Like `file-regular-p' for Tramp files."
3234 (and (file-exists-p filename)
3235 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3236
3237 (defun tramp-handle-file-symlink-p (filename)
3238 "Like `file-symlink-p' for Tramp files."
3239 (with-parsed-tramp-file-name filename nil
3240 (let ((x (car (file-attributes filename))))
3241 (when (stringp x)
3242 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3243 ;; might do weird things.
3244 (if (file-name-absolute-p x)
3245 (tramp-make-tramp-file-name method user host x)
3246 x)))))
3247
3248 (defun tramp-handle-file-writable-p (filename)
3249 "Like `file-writable-p' for Tramp files."
3250 (with-parsed-tramp-file-name filename nil
3251 (with-file-property v localname "file-writable-p"
3252 (if (file-exists-p filename)
3253 ;; Examine `file-attributes' cache to see if request can be
3254 ;; satisfied without remote operation.
3255 (or (tramp-check-cached-permissions v ?w)
3256 (zerop (tramp-run-test "-w" filename)))
3257 ;; If file doesn't exist, check if directory is writable.
3258 (and (zerop (tramp-run-test
3259 "-d" (file-name-directory filename)))
3260 (zerop (tramp-run-test
3261 "-w" (file-name-directory filename))))))))
3262
3263 (defun tramp-handle-file-ownership-preserved-p (filename)
3264 "Like `file-ownership-preserved-p' for Tramp files."
3265 (with-parsed-tramp-file-name filename nil
3266 (with-file-property v localname "file-ownership-preserved-p"
3267 (let ((attributes (file-attributes filename)))
3268 ;; Return t if the file doesn't exist, since it's true that no
3269 ;; information would be lost by an (attempted) delete and create.
3270 (or (null attributes)
3271 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3272
3273 ;; Other file name ops.
3274
3275 (defun tramp-handle-directory-file-name (directory)
3276 "Like `directory-file-name' for Tramp files."
3277 ;; If localname component of filename is "/", leave it unchanged.
3278 ;; Otherwise, remove any trailing slash from localname component.
3279 ;; Method, host, etc, are unchanged. Does it make sense to try
3280 ;; to avoid parsing the filename?
3281 (with-parsed-tramp-file-name directory nil
3282 (if (and (not (zerop (length localname)))
3283 (eq (aref localname (1- (length localname))) ?/)
3284 (not (string= localname "/")))
3285 (substring directory 0 -1)
3286 directory)))
3287
3288 ;; Directory listings.
3289
3290 (defun tramp-handle-directory-files
3291 (directory &optional full match nosort files-only)
3292 "Like `directory-files' for Tramp files."
3293 ;; FILES-ONLY is valid for XEmacs only.
3294 (when (file-directory-p directory)
3295 (setq directory (file-name-as-directory (expand-file-name directory)))
3296 (let ((temp (nreverse (file-name-all-completions "" directory)))
3297 result item)
3298
3299 (while temp
3300 (setq item (directory-file-name (pop temp)))
3301 (when (and (or (null match) (string-match match item))
3302 (or (null files-only)
3303 ;; Files only.
3304 (and (equal files-only t) (file-regular-p item))
3305 ;; Directories only.
3306 (file-directory-p item)))
3307 (push (if full (concat directory item) item)
3308 result)))
3309 (if nosort result (sort result 'string<)))))
3310
3311 (defun tramp-handle-directory-files-and-attributes
3312 (directory &optional full match nosort id-format)
3313 "Like `directory-files-and-attributes' for Tramp files."
3314 (unless id-format (setq id-format 'integer))
3315 (when (file-directory-p directory)
3316 (setq directory (expand-file-name directory))
3317 (let* ((temp
3318 (copy-tree
3319 (with-parsed-tramp-file-name directory nil
3320 (with-file-property
3321 v localname
3322 (format "directory-files-and-attributes-%s" id-format)
3323 (save-excursion
3324 (mapcar
3325 (lambda (x)
3326 (cons (car x)
3327 (tramp-convert-file-attributes v (cdr x))))
3328 (cond
3329 ((tramp-get-remote-stat v)
3330 (tramp-do-directory-files-and-attributes-with-stat
3331 v localname id-format))
3332 ((tramp-get-remote-perl v)
3333 (tramp-do-directory-files-and-attributes-with-perl
3334 v localname id-format)))))))))
3335 result item)
3336
3337 (while temp
3338 (setq item (pop temp))
3339 (when (or (null match) (string-match match (car item)))
3340 (when full
3341 (setcar item (expand-file-name (car item) directory)))
3342 (push item result)))
3343
3344 (if nosort
3345 result
3346 (sort result (lambda (x y) (string< (car x) (car y))))))))
3347
3348 (defun tramp-do-directory-files-and-attributes-with-perl
3349 (vec localname &optional id-format)
3350 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3351 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3352 (tramp-maybe-send-script
3353 vec tramp-perl-directory-files-and-attributes
3354 "tramp_perl_directory_files_and_attributes")
3355 (let ((object
3356 (tramp-send-command-and-read
3357 vec
3358 (format "tramp_perl_directory_files_and_attributes %s %s"
3359 (tramp-shell-quote-argument localname) id-format))))
3360 (when (stringp object) (tramp-error vec 'file-error object))
3361 object))
3362
3363 (defun tramp-do-directory-files-and-attributes-with-stat
3364 (vec localname &optional id-format)
3365 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3366 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3367 (tramp-send-command-and-read
3368 vec
3369 (format
3370 (concat
3371 ;; We must care about filenames with spaces, or starting with
3372 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3373 ;; but it does not work on all remote systems. Therefore, we
3374 ;; quote the filenames via sed.
3375 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3376 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3377 "echo \")\"")
3378 (tramp-shell-quote-argument localname)
3379 (tramp-get-ls-command vec)
3380 (tramp-get-remote-stat vec)
3381 (if (eq id-format 'integer) "%u" "\"%U\"")
3382 (if (eq id-format 'integer) "%g" "\"%G\""))))
3383
3384 ;; This function should return "foo/" for directories and "bar" for
3385 ;; files.
3386 (defun tramp-handle-file-name-all-completions (filename directory)
3387 "Like `file-name-all-completions' for Tramp files."
3388 (unless (save-match-data (string-match "/" filename))
3389 (with-parsed-tramp-file-name (expand-file-name directory) nil
3390
3391 (all-completions
3392 filename
3393 (mapcar
3394 'list
3395 (or
3396 ;; Try cache first
3397 (and
3398 ;; Ignore if expired
3399 (or (not (integerp tramp-completion-reread-directory-timeout))
3400 (<= (tramp-time-diff
3401 (current-time)
3402 (tramp-get-file-property
3403 v localname "last-completion" '(0 0 0)))
3404 tramp-completion-reread-directory-timeout))
3405
3406 ;; Try cache entries for filename, filename with last
3407 ;; character removed, filename with last two characters
3408 ;; removed, ..., and finally the empty string - all
3409 ;; concatenated to the local directory name
3410
3411 ;; This is inefficient for very long filenames, pity
3412 ;; `reduce' is not available...
3413 (car
3414 (apply
3415 'append
3416 (mapcar
3417 (lambda (x)
3418 (let ((cache-hit
3419 (tramp-get-file-property
3420 v
3421 (concat localname (substring filename 0 x))
3422 "file-name-all-completions"
3423 nil)))
3424 (when cache-hit (list cache-hit))))
3425 (tramp-compat-number-sequence (length filename) 0 -1)))))
3426
3427 ;; Cache expired or no matching cache entry found so we need
3428 ;; to perform a remote operation
3429 (let (result)
3430 ;; Get a list of directories and files, including reliably
3431 ;; tagging the directories with a trailing '/'. Because I
3432 ;; rock. --daniel@danann.net
3433
3434 ;; Changed to perform `cd' in the same remote op and only
3435 ;; get entries starting with `filename'. Capture any `cd'
3436 ;; error messages. Ensure any `cd' and `echo' aliases are
3437 ;; ignored.
3438 (tramp-send-command
3439 v
3440 (if (tramp-get-remote-perl v)
3441 (progn
3442 (tramp-maybe-send-script
3443 v tramp-perl-file-name-all-completions
3444 "tramp_perl_file_name_all_completions")
3445 (format "tramp_perl_file_name_all_completions %s %s %d"
3446 (tramp-shell-quote-argument localname)
3447 (tramp-shell-quote-argument filename)
3448 (if (symbol-value
3449 ;; `read-file-name-completion-ignore-case'
3450 ;; is introduced with Emacs 22.1.
3451 (if (boundp
3452 'read-file-name-completion-ignore-case)
3453 'read-file-name-completion-ignore-case
3454 'completion-ignore-case))
3455 1 0)))
3456
3457 (format (concat
3458 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3459 ;; `ls' with wildcard might fail with `Argument
3460 ;; list too long' error in some corner cases; if
3461 ;; `ls' fails after `cd' succeeded, chances are
3462 ;; that's the case, so let's retry without
3463 ;; wildcard. This will return "too many" entries
3464 ;; but that isn't harmful.
3465 " || %s -a 2>/dev/null)"
3466 " | while read f; do"
3467 " if %s -d \"$f\" 2>/dev/null;"
3468 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3469 " && \\echo ok) || \\echo fail")
3470 (tramp-shell-quote-argument localname)
3471 (tramp-get-ls-command v)
3472 ;; When `filename' is empty, just `ls' without
3473 ;; filename argument is more efficient than `ls *'
3474 ;; for very large directories and might avoid the
3475 ;; `Argument list too long' error.
3476 ;;
3477 ;; With and only with wildcard, we need to add
3478 ;; `-d' to prevent `ls' from descending into
3479 ;; sub-directories.
3480 (if (zerop (length filename))
3481 "."
3482 (concat (tramp-shell-quote-argument filename) "* -d"))
3483 (tramp-get-ls-command v)
3484 (tramp-get-test-command v))))
3485
3486 ;; Now grab the output.
3487 (with-current-buffer (tramp-get-buffer v)
3488 (goto-char (point-max))
3489
3490 ;; Check result code, found in last line of output
3491 (forward-line -1)
3492 (if (looking-at "^fail$")
3493 (progn
3494 ;; Grab error message from line before last line
3495 ;; (it was put there by `cd 2>&1')
3496 (forward-line -1)
3497 (tramp-error
3498 v 'file-error
3499 "tramp-handle-file-name-all-completions: %s"
3500 (buffer-substring
3501 (point) (tramp-compat-line-end-position))))
3502 ;; For peace of mind, if buffer doesn't end in `fail'
3503 ;; then it should end in `ok'. If neither are in the
3504 ;; buffer something went seriously wrong on the remote
3505 ;; side.
3506 (unless (looking-at "^ok$")
3507 (tramp-error
3508 v 'file-error
3509 "\
3510 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3511 (tramp-shell-quote-argument localname) (buffer-string))))
3512
3513 (while (zerop (forward-line -1))
3514 (push (buffer-substring
3515 (point) (tramp-compat-line-end-position))
3516 result)))
3517
3518 ;; Because the remote op went through OK we know the
3519 ;; directory we `cd'-ed to exists
3520 (tramp-set-file-property
3521 v localname "file-exists-p" t)
3522
3523 ;; Because the remote op went through OK we know every
3524 ;; file listed by `ls' exists.
3525 (mapc (lambda (entry)
3526 (tramp-set-file-property
3527 v (concat localname entry) "file-exists-p" t))
3528 result)
3529
3530 (tramp-set-file-property
3531 v localname "last-completion" (current-time))
3532
3533 ;; Store result in the cache
3534 (tramp-set-file-property
3535 v (concat localname filename)
3536 "file-name-all-completions"
3537 result))))))))
3538
3539 (defun tramp-handle-file-name-completion
3540 (filename directory &optional predicate)
3541 "Like `file-name-completion' for Tramp files."
3542 (unless (tramp-tramp-file-p directory)
3543 (error
3544 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3545 directory))
3546 (try-completion
3547 filename
3548 (mapcar 'list (file-name-all-completions filename directory))
3549 (when predicate
3550 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3551
3552 ;; cp, mv and ln
3553
3554 (defun tramp-handle-add-name-to-file
3555 (filename newname &optional ok-if-already-exists)
3556 "Like `add-name-to-file' for Tramp files."
3557 (unless (tramp-equal-remote filename newname)
3558 (with-parsed-tramp-file-name
3559 (if (tramp-tramp-file-p filename) filename newname) nil
3560 (tramp-error
3561 v 'file-error
3562 "add-name-to-file: %s"
3563 "only implemented for same method, same user, same host")))
3564 (with-parsed-tramp-file-name filename v1
3565 (with-parsed-tramp-file-name newname v2
3566 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3567 (when (and (not ok-if-already-exists)
3568 (file-exists-p newname)
3569 (not (numberp ok-if-already-exists))
3570 (y-or-n-p
3571 (format
3572 "File %s already exists; make it a new name anyway? "
3573 newname)))
3574 (tramp-error
3575 v2 'file-error
3576 "add-name-to-file: file %s already exists" newname))
3577 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3578 (tramp-flush-file-property v2 v2-localname)
3579 (tramp-barf-unless-okay
3580 v1
3581 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3582 (tramp-shell-quote-argument v2-localname))
3583 "error with add-name-to-file, see buffer `%s' for details"
3584 (buffer-name))))))
3585
3586 (defun tramp-handle-copy-file
3587 (filename newname &optional ok-if-already-exists keep-date
3588 preserve-uid-gid preserve-selinux-context)
3589 "Like `copy-file' for Tramp files."
3590 (setq filename (expand-file-name filename))
3591 (setq newname (expand-file-name newname))
3592 (cond
3593 ;; At least one file a Tramp file?
3594 ((or (tramp-tramp-file-p filename)
3595 (tramp-tramp-file-p newname))
3596 (tramp-do-copy-or-rename-file
3597 'copy filename newname ok-if-already-exists keep-date
3598 preserve-uid-gid preserve-selinux-context))
3599 ;; Compat section.
3600 (preserve-selinux-context
3601 (tramp-run-real-handler
3602 'copy-file
3603 (list filename newname ok-if-already-exists keep-date
3604 preserve-uid-gid preserve-selinux-context)))
3605 (preserve-uid-gid
3606 (tramp-run-real-handler
3607 'copy-file
3608 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3609 (t
3610 (tramp-run-real-handler
3611 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3612
3613 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3614 "Like `copy-directory' for Tramp files."
3615 (let ((t1 (tramp-tramp-file-p dirname))
3616 (t2 (tramp-tramp-file-p newname)))
3617 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3618 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3619 ;; When DIRNAME and NEWNAME are remote, they must have
3620 ;; the same method.
3621 (or (null t1) (null t2)
3622 (string-equal
3623 (tramp-file-name-method (tramp-dissect-file-name dirname))
3624 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3625 ;; scp or rsync DTRT.
3626 (progn
3627 (setq dirname (directory-file-name (expand-file-name dirname))
3628 newname (directory-file-name (expand-file-name newname)))
3629 (if (and (file-directory-p newname)
3630 (not (string-equal (file-name-nondirectory dirname)
3631 (file-name-nondirectory newname))))
3632 (setq newname
3633 (expand-file-name
3634 (file-name-nondirectory dirname) newname)))
3635 (if (not (file-directory-p (file-name-directory newname)))
3636 (make-directory (file-name-directory newname) parents))
3637 (tramp-do-copy-or-rename-file-out-of-band
3638 'copy dirname newname keep-date))
3639 ;; We must do it file-wise.
3640 (tramp-run-real-handler
3641 'copy-directory (list dirname newname keep-date parents)))
3642
3643 ;; When newname did exist, we have wrong cached values.
3644 (when t2
3645 (with-parsed-tramp-file-name newname nil
3646 (tramp-flush-file-property v (file-name-directory localname))
3647 (tramp-flush-file-property v localname))))))
3648
3649 (defun tramp-handle-rename-file
3650 (filename newname &optional ok-if-already-exists)
3651 "Like `rename-file' for Tramp files."
3652 ;; Check if both files are local -- invoke normal rename-file.
3653 ;; Otherwise, use Tramp from local system.
3654 (setq filename (expand-file-name filename))
3655 (setq newname (expand-file-name newname))
3656 ;; At least one file a Tramp file?
3657 (if (or (tramp-tramp-file-p filename)
3658 (tramp-tramp-file-p newname))
3659 (tramp-do-copy-or-rename-file
3660 'rename filename newname ok-if-already-exists t t)
3661 (tramp-run-real-handler
3662 'rename-file (list filename newname ok-if-already-exists))))
3663
3664 (defun tramp-do-copy-or-rename-file
3665 (op filename newname &optional ok-if-already-exists keep-date
3666 preserve-uid-gid preserve-selinux-context)
3667 "Copy or rename a remote file.
3668 OP must be `copy' or `rename' and indicates the operation to perform.
3669 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3670 the new file (for copy) or the new name of the file (for rename).
3671 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3672 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3673 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3674 the uid and gid if both files are on the same host.
3675 PRESERVE-SELINUX-CONTEXT activates selinux commands.
3676
3677 This function is invoked by `tramp-handle-copy-file' and
3678 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3679 and `rename'. FILENAME and NEWNAME must be absolute file names."
3680 (unless (memq op '(copy rename))
3681 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3682 (let ((t1 (tramp-tramp-file-p filename))
3683 (t2 (tramp-tramp-file-p newname))
3684 (context (and preserve-selinux-context
3685 (apply 'file-selinux-context (list filename))))
3686 pr tm)
3687
3688 (with-parsed-tramp-file-name (if t1 filename newname) nil
3689 (when (and (not ok-if-already-exists) (file-exists-p newname))
3690 (tramp-error
3691 v 'file-already-exists "File %s already exists" newname))
3692
3693 (with-progress-reporter
3694 v 0 (format "%s %s to %s"
3695 (if (eq op 'copy) "Copying" "Renaming")
3696 filename newname)
3697
3698 (cond
3699 ;; Both are Tramp files.
3700 ((and t1 t2)
3701 (with-parsed-tramp-file-name filename v1
3702 (with-parsed-tramp-file-name newname v2
3703 (cond
3704 ;; Shortcut: if method, host, user are the same for
3705 ;; both files, we invoke `cp' or `mv' on the remote
3706 ;; host directly.
3707 ((tramp-equal-remote filename newname)
3708 (tramp-do-copy-or-rename-file-directly
3709 op filename newname
3710 ok-if-already-exists keep-date preserve-uid-gid))
3711
3712 ;; Try out-of-band operation.
3713 ((tramp-method-out-of-band-p
3714 v1 (nth 7 (file-attributes filename)))
3715 (tramp-do-copy-or-rename-file-out-of-band
3716 op filename newname keep-date))
3717
3718 ;; No shortcut was possible. So we copy the file
3719 ;; first. If the operation was `rename', we go back
3720 ;; and delete the original file (if the copy was
3721 ;; successful). The approach is simple-minded: we
3722 ;; create a new buffer, insert the contents of the
3723 ;; source file into it, then write out the buffer to
3724 ;; the target file. The advantage is that it doesn't
3725 ;; matter which filename handlers are used for the
3726 ;; source and target file.
3727 (t
3728 (tramp-do-copy-or-rename-file-via-buffer
3729 op filename newname keep-date))))))
3730
3731 ;; One file is a Tramp file, the other one is local.
3732 ((or t1 t2)
3733 (cond
3734 ;; Fast track on local machine.
3735 ((tramp-local-host-p v)
3736 (tramp-do-copy-or-rename-file-directly
3737 op filename newname
3738 ok-if-already-exists keep-date preserve-uid-gid))
3739
3740 ;; If the Tramp file has an out-of-band method, the
3741 ;; corresponding copy-program can be invoked.
3742 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3743 (tramp-do-copy-or-rename-file-out-of-band
3744 op filename newname keep-date))
3745
3746 ;; Use the inline method via a Tramp buffer.
3747 (t (tramp-do-copy-or-rename-file-via-buffer
3748 op filename newname keep-date))))
3749
3750 (t
3751 ;; One of them must be a Tramp file.
3752 (error "Tramp implementation says this cannot happen")))
3753
3754 ;; Handle `preserve-selinux-context'.
3755 (when context (apply 'set-file-selinux-context (list newname context)))
3756
3757 ;; In case of `rename', we must flush the cache of the source file.
3758 (when (and t1 (eq op 'rename))
3759 (with-parsed-tramp-file-name filename v1
3760 (tramp-flush-file-property v1 (file-name-directory localname))
3761 (tramp-flush-file-property v1 localname)))
3762
3763 ;; When newname did exist, we have wrong cached values.
3764 (when t2
3765 (with-parsed-tramp-file-name newname v2
3766 (tramp-flush-file-property v2 (file-name-directory localname))
3767 (tramp-flush-file-property v2 localname)))))))
3768
3769 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3770 "Use an Emacs buffer to copy or rename a file.
3771 First arg OP is either `copy' or `rename' and indicates the operation.
3772 FILENAME is the source file, NEWNAME the target file.
3773 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3774 (with-temp-buffer
3775 ;; We must disable multibyte, because binary data shall not be
3776 ;; converted.
3777 (set-buffer-multibyte nil)
3778 (let ((coding-system-for-read 'binary)
3779 (jka-compr-inhibit t))
3780 (insert-file-contents-literally filename))
3781 ;; We don't want the target file to be compressed, so we let-bind
3782 ;; `jka-compr-inhibit' to t.
3783 (let ((coding-system-for-write 'binary)
3784 (jka-compr-inhibit t))
3785 (write-region (point-min) (point-max) newname)))
3786 ;; KEEP-DATE handling.
3787 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3788 ;; Set the mode.
3789 (set-file-modes newname (tramp-default-file-modes filename))
3790 ;; If the operation was `rename', delete the original file.
3791 (unless (eq op 'copy) (delete-file filename)))
3792
3793 (defun tramp-do-copy-or-rename-file-directly
3794 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3795 "Invokes `cp' or `mv' on the remote system.
3796 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3797 respectively. FILENAME specifies the file to copy or rename,
3798 NEWNAME is the name of the new file (for copy) or the new name of
3799 the file (for rename). Both files must reside on the same host.
3800 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3801 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3802 the uid and gid from FILENAME."
3803 (let ((t1 (tramp-tramp-file-p filename))
3804 (t2 (tramp-tramp-file-p newname))
3805 (file-times (nth 5 (file-attributes filename)))
3806 (file-modes (tramp-default-file-modes filename)))
3807 (with-parsed-tramp-file-name (if t1 filename newname) nil
3808 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3809 ((eq op 'copy) "cp -f")
3810 ((eq op 'rename) "mv -f")
3811 (t (tramp-error
3812 v 'file-error
3813 "Unknown operation `%s', must be `copy' or `rename'"
3814 op))))
3815 (localname1
3816 (if t1
3817 (tramp-file-name-handler 'file-remote-p filename 'localname)
3818 filename))
3819 (localname2
3820 (if t2
3821 (tramp-file-name-handler 'file-remote-p newname 'localname)
3822 newname))
3823 (prefix (file-remote-p (if t1 filename newname)))
3824 cmd-result)
3825
3826 (cond
3827 ;; Both files are on a remote host, with same user.
3828 ((and t1 t2)
3829 (setq cmd-result
3830 (tramp-send-command-and-check
3831 v
3832 (format "%s %s %s" cmd
3833 (tramp-shell-quote-argument localname1)
3834 (tramp-shell-quote-argument localname2))))
3835 (with-current-buffer (tramp-get-buffer v)
3836 (goto-char (point-min))
3837 (unless
3838 (or
3839 (and keep-date
3840 ;; Mask cp -f error.
3841 (re-search-forward
3842 tramp-operation-not-permitted-regexp nil t))
3843 (zerop cmd-result))
3844 (tramp-error-with-buffer
3845 nil v 'file-error
3846 "Copying directly failed, see buffer `%s' for details."
3847 (buffer-name)))))
3848
3849 ;; We are on the local host.
3850 ((or t1 t2)
3851 (cond
3852 ;; We can do it directly.
3853 ((let (file-name-handler-alist)
3854 (and (file-readable-p localname1)
3855 (file-writable-p (file-name-directory localname2))
3856 (or (file-directory-p localname2)
3857 (file-writable-p localname2))))
3858 (if (eq op 'copy)
3859 (tramp-compat-copy-file
3860 localname1 localname2 ok-if-already-exists
3861 keep-date preserve-uid-gid)
3862 (tramp-run-real-handler
3863 'rename-file (list localname1 localname2 ok-if-already-exists))))
3864
3865 ;; We can do it directly with `tramp-send-command'
3866 ((and (file-readable-p (concat prefix localname1))
3867 (file-writable-p
3868 (file-name-directory (concat prefix localname2)))
3869 (or (file-directory-p (concat prefix localname2))
3870 (file-writable-p (concat prefix localname2))))
3871 (tramp-do-copy-or-rename-file-directly
3872 op (concat prefix localname1) (concat prefix localname2)
3873 ok-if-already-exists keep-date t)
3874 ;; We must change the ownership to the local user.
3875 (tramp-set-file-uid-gid
3876 (concat prefix localname2)
3877 (tramp-get-local-uid 'integer)
3878 (tramp-get-local-gid 'integer)))
3879
3880 ;; We need a temporary file in between.
3881 (t
3882 ;; Create the temporary file.
3883 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3884 (unwind-protect
3885 (progn
3886 (cond
3887 (t1
3888 (or
3889 (zerop
3890 (tramp-send-command-and-check
3891 v (format
3892 "%s %s %s" cmd
3893 (tramp-shell-quote-argument localname1)
3894 (tramp-shell-quote-argument tmpfile))))
3895 (tramp-error-with-buffer
3896 nil v 'file-error
3897 "Copying directly failed, see buffer `%s' for details."
3898 (tramp-get-buffer v)))
3899 ;; We must change the ownership as remote user.
3900 ;; Since this does not work reliable, we also
3901 ;; give read permissions.
3902 (set-file-modes
3903 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3904 (tramp-set-file-uid-gid
3905 (concat prefix tmpfile)
3906 (tramp-get-local-uid 'integer)
3907 (tramp-get-local-gid 'integer)))
3908 (t2
3909 (if (eq op 'copy)
3910 (tramp-compat-copy-file
3911 localname1 tmpfile t
3912 keep-date preserve-uid-gid)
3913 (tramp-run-real-handler
3914 'rename-file
3915 (list localname1 tmpfile t)))
3916 ;; We must change the ownership as local user.
3917 ;; Since this does not work reliable, we also
3918 ;; give read permissions.
3919 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3920 (tramp-set-file-uid-gid
3921 tmpfile
3922 (tramp-get-remote-uid v 'integer)
3923 (tramp-get-remote-gid v 'integer))))
3924
3925 ;; Move the temporary file to its destination.
3926 (cond
3927 (t2
3928 (or
3929 (zerop
3930 (tramp-send-command-and-check
3931 v (format
3932 "cp -f -p %s %s"
3933 (tramp-shell-quote-argument tmpfile)
3934 (tramp-shell-quote-argument localname2))))
3935 (tramp-error-with-buffer
3936 nil v 'file-error
3937 "Copying directly failed, see buffer `%s' for details."
3938 (tramp-get-buffer v))))
3939 (t1
3940 (tramp-run-real-handler
3941 'rename-file
3942 (list tmpfile localname2 ok-if-already-exists)))))
3943
3944 ;; Save exit.
3945 (condition-case nil
3946 (delete-file tmpfile)
3947 (error)))))))))
3948
3949 ;; Set the time and mode. Mask possible errors.
3950 (condition-case nil
3951 (when keep-date
3952 (set-file-times newname file-times)
3953 (set-file-modes newname file-modes))
3954 (error)))))
3955
3956 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3957 "Invoke rcp program to copy.
3958 The method used must be an out-of-band method."
3959 (let ((t1 (tramp-tramp-file-p filename))
3960 (t2 (tramp-tramp-file-p newname))
3961 copy-program copy-args copy-env copy-keep-date port spec
3962 source target)
3963
3964 (with-parsed-tramp-file-name (if t1 filename newname) nil
3965 (if (and t1 t2)
3966
3967 ;; Both are Tramp files. We shall optimize it, when the
3968 ;; methods for filename and newname are the same.
3969 (let* ((dir-flag (file-directory-p filename))
3970 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3971 (if dir-flag
3972 (setq tmpfile
3973 (expand-file-name
3974 (file-name-nondirectory newname) tmpfile)))
3975 (unwind-protect
3976 (progn
3977 (tramp-do-copy-or-rename-file-out-of-band
3978 op filename tmpfile keep-date)
3979 (tramp-do-copy-or-rename-file-out-of-band
3980 'rename tmpfile newname keep-date))
3981 ;; Save exit.
3982 (condition-case nil
3983 (if dir-flag
3984 (tramp-compat-delete-directory
3985 (expand-file-name ".." tmpfile) 'recursive)
3986 (delete-file tmpfile))
3987 (error))))
3988
3989 ;; Expand hops. Might be necessary for gateway methods.
3990 (setq v (car (tramp-compute-multi-hops v)))
3991 (aset v 3 localname)
3992
3993 ;; Check which ones of source and target are Tramp files.
3994 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3995 target (funcall
3996 (if (and (file-directory-p filename)
3997 (string-equal
3998 (file-name-nondirectory filename)
3999 (file-name-nondirectory newname)))
4000 'file-name-directory
4001 'identity)
4002 (if t2 (tramp-make-copy-program-file-name v) newname)))
4003
4004 ;; Check for port number. Until now, there's no need for handling
4005 ;; like method, user, host.
4006 (setq host (tramp-file-name-real-host v)
4007 port (tramp-file-name-port v)
4008 port (or (and port (number-to-string port)) ""))
4009
4010 ;; Compose copy command.
4011 (setq spec (format-spec-make
4012 ?h host ?u user ?p port
4013 ?t (tramp-get-connection-property
4014 (tramp-get-connection-process v) "temp-file" "")
4015 ?k (if keep-date " " ""))
4016 copy-program (tramp-get-method-parameter
4017 method 'tramp-copy-program)
4018 copy-keep-date (tramp-get-method-parameter
4019 method 'tramp-copy-keep-date)
4020 copy-args
4021 (delq
4022 nil
4023 (mapcar
4024 (lambda (x)
4025 (setq
4026 x
4027 ;; " " is indication for keep-date argument.
4028 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
4029 (unless (member "" x) (mapconcat 'identity x " ")))
4030 (tramp-get-method-parameter method 'tramp-copy-args)))
4031 copy-env
4032 (delq
4033 nil
4034 (mapcar
4035 (lambda (x)
4036 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4037 (unless (member "" x) (mapconcat 'identity x " ")))
4038 (tramp-get-method-parameter method 'tramp-copy-env))))
4039
4040 ;; Check for program.
4041 (when (and (fboundp 'executable-find)
4042 (not (let ((default-directory
4043 (tramp-compat-temporary-file-directory)))
4044 (executable-find copy-program))))
4045 (tramp-error
4046 v 'file-error "Cannot find copy program: %s" copy-program))
4047
4048 ;; Set variables for computing the prompt for reading
4049 ;; password.
4050 (setq tramp-current-method (tramp-file-name-method v)
4051 tramp-current-user (tramp-file-name-user v)
4052 tramp-current-host (tramp-file-name-host v))
4053
4054 (unwind-protect
4055 (with-temp-buffer
4056 ;; The default directory must be remote.
4057 (let ((default-directory
4058 (file-name-directory (if t1 filename newname)))
4059 (process-environment (copy-sequence process-environment)))
4060 ;; Set the transfer process properties.
4061 (tramp-set-connection-property
4062 v "process-name" (buffer-name (current-buffer)))
4063 (tramp-set-connection-property
4064 v "process-buffer" (current-buffer))
4065 (while copy-env
4066 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
4067 (setenv (pop copy-env) (pop copy-env)))
4068
4069 ;; Use an asynchronous process. By this, password can
4070 ;; be handled. The default directory must be local, in
4071 ;; order to apply the correct `copy-program'. We don't
4072 ;; set a timeout, because the copying of large files can
4073 ;; last longer than 60 secs.
4074 (let ((p (let ((default-directory
4075 (tramp-compat-temporary-file-directory)))
4076 (apply 'start-process
4077 (tramp-get-connection-property
4078 v "process-name" nil)
4079 (tramp-get-connection-property
4080 v "process-buffer" nil)
4081 copy-program
4082 (append copy-args (list source target))))))
4083 (tramp-message
4084 v 6 "%s" (mapconcat 'identity (process-command p) " "))
4085 (tramp-set-process-query-on-exit-flag p nil)
4086 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
4087
4088 ;; Reset the transfer process properties.
4089 (tramp-set-connection-property v "process-name" nil)
4090 (tramp-set-connection-property v "process-buffer" nil))
4091
4092 ;; Handle KEEP-DATE argument.
4093 (when (and keep-date (not copy-keep-date))
4094 (set-file-times newname (nth 5 (file-attributes filename))))
4095
4096 ;; Set the mode.
4097 (unless (and keep-date copy-keep-date)
4098 (ignore-errors
4099 (set-file-modes newname (tramp-default-file-modes filename)))))
4100
4101 ;; If the operation was `rename', delete the original file.
4102 (unless (eq op 'copy)
4103 (if (file-regular-p filename)
4104 (delete-file filename)
4105 (tramp-compat-delete-directory filename 'recursive))))))
4106
4107 (defun tramp-handle-make-directory (dir &optional parents)
4108 "Like `make-directory' for Tramp files."
4109 (setq dir (expand-file-name dir))
4110 (with-parsed-tramp-file-name dir nil
4111 (tramp-flush-directory-property v (file-name-directory localname))
4112 (save-excursion
4113 (tramp-barf-unless-okay
4114 v
4115 (format "%s %s"
4116 (if parents "mkdir -p" "mkdir")
4117 (tramp-shell-quote-argument localname))
4118 "Couldn't make directory %s" dir))))
4119
4120 (defun tramp-handle-delete-directory (directory &optional recursive)
4121 "Like `delete-directory' for Tramp files."
4122 (setq directory (expand-file-name directory))
4123 (with-parsed-tramp-file-name directory nil
4124 (tramp-flush-file-property v (file-name-directory localname))
4125 (tramp-flush-directory-property v localname)
4126 (unless (zerop (tramp-send-command-and-check
4127 v
4128 (format
4129 "%s %s"
4130 (if recursive "rm -rf" "rmdir")
4131 (tramp-shell-quote-argument localname))))
4132 (tramp-error v 'file-error "Couldn't delete %s" directory))))
4133
4134 (defun tramp-handle-delete-file (filename &optional trash)
4135 "Like `delete-file' for Tramp files."
4136 (setq filename (expand-file-name filename))
4137 (with-parsed-tramp-file-name filename nil
4138 (tramp-flush-file-property v (file-name-directory localname))
4139 (tramp-flush-file-property v localname)
4140 (unless
4141 (zerop
4142 (tramp-send-command-and-check
4143 v (format "%s %s"
4144 (or (and trash (tramp-get-remote-trash v)) "rm -f")
4145 (tramp-shell-quote-argument localname))))
4146 (tramp-error v 'file-error "Couldn't delete %s" filename))))
4147
4148 ;; Dired.
4149
4150 ;; CCC: This does not seem to be enough. Something dies when
4151 ;; we try and delete two directories under Tramp :/
4152 (defun tramp-handle-dired-recursive-delete-directory (filename)
4153 "Recursively delete the directory given.
4154 This is like `dired-recursive-delete-directory' for Tramp files."
4155 (with-parsed-tramp-file-name filename nil
4156 ;; Run a shell command 'rm -r <localname>'
4157 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
4158 (unless (file-exists-p filename)
4159 (tramp-error v 'file-error "No such directory: %s" filename))
4160 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
4161 (tramp-send-command
4162 v
4163 (format "rm -rf %s" (tramp-shell-quote-argument localname))
4164 ;; Don't read the output, do it explicitely.
4165 nil t)
4166 ;; Wait for the remote system to return to us...
4167 ;; This might take a while, allow it plenty of time.
4168 (tramp-wait-for-output (tramp-get-connection-process v) 120)
4169 ;; Make sure that it worked...
4170 (tramp-flush-file-property v (file-name-directory localname))
4171 (tramp-flush-directory-property v localname)
4172 (and (file-exists-p filename)
4173 (tramp-error
4174 v 'file-error "Failed to recursively delete %s" filename))))
4175
4176 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4177 "Like `dired-compress-file' for Tramp files."
4178 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4179 ;; Code stolen mainly from dired-aux.el.
4180 (with-parsed-tramp-file-name file nil
4181 (tramp-flush-file-property v localname)
4182 (save-excursion
4183 (let ((suffixes
4184 (if (not (featurep 'xemacs))
4185 ;; Emacs case
4186 (symbol-value 'dired-compress-file-suffixes)
4187 ;; XEmacs has `dired-compression-method-alist', which is
4188 ;; transformed into `dired-compress-file-suffixes' structure.
4189 (mapcar
4190 (lambda (x)
4191 (list (concat (regexp-quote (nth 1 x)) "\\'")
4192 nil
4193 (mapconcat 'identity (nth 3 x) " ")))
4194 (symbol-value 'dired-compression-method-alist))))
4195 suffix)
4196 ;; See if any suffix rule matches this file name.
4197 (while suffixes
4198 (let (case-fold-search)
4199 (if (string-match (car (car suffixes)) localname)
4200 (setq suffix (car suffixes) suffixes nil))
4201 (setq suffixes (cdr suffixes))))
4202
4203 (cond ((file-symlink-p file)
4204 nil)
4205 ((and suffix (nth 2 suffix))
4206 ;; We found an uncompression rule.
4207 (with-progress-reporter v 0 (format "Uncompressing %s" file)
4208 (when (zerop
4209 (tramp-send-command-and-check
4210 v (concat (nth 2 suffix) " "
4211 (tramp-shell-quote-argument localname))))
4212 ;; `dired-remove-file' is not defined in XEmacs.
4213 (tramp-compat-funcall 'dired-remove-file file)
4214 (string-match (car suffix) file)
4215 (concat (substring file 0 (match-beginning 0))))))
4216 (t
4217 ;; We don't recognize the file as compressed, so compress it.
4218 ;; Try gzip.
4219 (with-progress-reporter v 0 (format "Compressing %s" file)
4220 (when (zerop
4221 (tramp-send-command-and-check
4222 v (concat "gzip -f "
4223 (tramp-shell-quote-argument localname))))
4224 ;; `dired-remove-file' is not defined in XEmacs.
4225 (tramp-compat-funcall 'dired-remove-file file)
4226 (cond ((file-exists-p (concat file ".gz"))
4227 (concat file ".gz"))
4228 ((file-exists-p (concat file ".z"))
4229 (concat file ".z"))
4230 (t nil))))))))))
4231
4232 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4233 "Like `dired-uncache' for Tramp files."
4234 ;; DIR-P is valid for XEmacs only.
4235 (with-parsed-tramp-file-name
4236 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4237 (tramp-flush-file-property v localname)))
4238
4239 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4240 ;; not sure at all that this is the right way to do it, but let's hope
4241 ;; it works for now, and wait for a guru to point out the Right Way to
4242 ;; achieve this.
4243 ;;(eval-when-compile
4244 ;; (unless (fboundp 'dired-insert-set-properties)
4245 ;; (fset 'dired-insert-set-properties 'ignore)))
4246 ;; Gerd suggests this:
4247 (eval-when-compile (require 'dired))
4248 ;; Note that dired is required at run-time, too, when it is needed.
4249 ;; It is only needed on XEmacs for the function
4250 ;; `dired-insert-set-properties'.
4251
4252 (defun tramp-handle-insert-directory
4253 (filename switches &optional wildcard full-directory-p)
4254 "Like `insert-directory' for Tramp files."
4255 (setq filename (expand-file-name filename))
4256 (with-parsed-tramp-file-name filename nil
4257 (if (and (featurep 'ls-lisp)
4258 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4259 (tramp-run-real-handler
4260 'insert-directory (list filename switches wildcard full-directory-p))
4261 (when (stringp switches)
4262 (setq switches (split-string switches)))
4263 (when (and (member "--dired" switches)
4264 (not (tramp-get-ls-command-with-dired v)))
4265 (setq switches (delete "--dired" switches)))
4266 (when wildcard
4267 (setq wildcard (tramp-run-real-handler
4268 'file-name-nondirectory (list localname)))
4269 (setq localname (tramp-run-real-handler
4270 'file-name-directory (list localname))))
4271 (unless full-directory-p
4272 (setq switches (add-to-list 'switches "-d" 'append)))
4273 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4274 (when wildcard
4275 (setq switches (concat switches " " wildcard)))
4276 (tramp-message
4277 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4278 switches filename (if wildcard "yes" "no")
4279 (if full-directory-p "yes" "no"))
4280 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4281 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4282 (if full-directory-p
4283 (tramp-send-command
4284 v
4285 (format "%s %s %s 2>/dev/null"
4286 (tramp-get-ls-command v)
4287 switches
4288 (if wildcard
4289 localname
4290 (tramp-shell-quote-argument (concat localname ".")))))
4291 (tramp-barf-unless-okay
4292 v
4293 (format "cd %s" (tramp-shell-quote-argument
4294 (tramp-run-real-handler
4295 'file-name-directory (list localname))))
4296 "Couldn't `cd %s'"
4297 (tramp-shell-quote-argument
4298 (tramp-run-real-handler 'file-name-directory (list localname))))
4299 (tramp-send-command
4300 v
4301 (format "%s %s %s"
4302 (tramp-get-ls-command v)
4303 switches
4304 (if (or wildcard
4305 (zerop (length
4306 (tramp-run-real-handler
4307 'file-name-nondirectory (list localname)))))
4308 ""
4309 (tramp-shell-quote-argument
4310 (tramp-run-real-handler
4311 'file-name-nondirectory (list localname)))))))
4312 (let ((beg (point)))
4313 ;; We cannot use `insert-buffer-substring' because the Tramp
4314 ;; buffer changes its contents before insertion due to calling
4315 ;; `expand-file' and alike.
4316 (insert
4317 (with-current-buffer (tramp-get-buffer v)
4318 (buffer-string)))
4319
4320 ;; Check for "--dired" output.
4321 (forward-line -2)
4322 (when (looking-at "//SUBDIRED//")
4323 (forward-line -1))
4324 (when (looking-at "//DIRED//\\s-+")
4325 (let ((databeg (match-end 0))
4326 (end (tramp-compat-line-end-position)))
4327 ;; Now read the numeric positions of file names.
4328 (goto-char databeg)
4329 (while (< (point) end)
4330 (let ((start (+ beg (read (current-buffer))))
4331 (end (+ beg (read (current-buffer)))))
4332 (if (memq (char-after end) '(?\n ?\ ))
4333 ;; End is followed by \n or by " -> ".
4334 (put-text-property start end 'dired-filename t))))))
4335 ;; Remove trailing lines.
4336 (goto-char (tramp-compat-line-beginning-position))
4337 (while (looking-at "//")
4338 (forward-line 1)
4339 (delete-region (match-beginning 0) (point)))
4340
4341 ;; The inserted file could be from somewhere else.
4342 (when (and (not wildcard) (not full-directory-p))
4343 (goto-char (point-max))
4344 (when (file-symlink-p filename)
4345 (goto-char (search-backward "->" beg 'noerror)))
4346 (search-backward
4347 (if (zerop (length (file-name-nondirectory filename)))
4348 "."
4349 (file-name-nondirectory filename))
4350 beg 'noerror)
4351 (replace-match (file-relative-name filename) t))
4352
4353 (goto-char (point-max))))))
4354
4355 (defun tramp-handle-unhandled-file-name-directory (filename)
4356 "Like `unhandled-file-name-directory' for Tramp files."
4357 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4358 ;; for backward compatibility.
4359 (expand-file-name "~/"))
4360
4361 ;; Canonicalization of file names.
4362
4363 (defun tramp-handle-expand-file-name (name &optional dir)
4364 "Like `expand-file-name' for Tramp files.
4365 If the localname part of the given filename starts with \"/../\" then
4366 the result will be a local, non-Tramp, filename."
4367 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4368 (setq dir (or dir default-directory "/"))
4369 ;; Unless NAME is absolute, concat DIR and NAME.
4370 (unless (file-name-absolute-p name)
4371 (setq name (concat (file-name-as-directory dir) name)))
4372 ;; If NAME is not a Tramp file, run the real handler.
4373 (if (not (tramp-connectable-p name))
4374 (tramp-run-real-handler 'expand-file-name (list name nil))
4375 ;; Dissect NAME.
4376 (with-parsed-tramp-file-name name nil
4377 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4378 (setq localname (concat "~/" localname)))
4379 ;; Tilde expansion if necessary. This needs a shell which
4380 ;; groks tilde expansion! The function `tramp-find-shell' is
4381 ;; supposed to find such a shell on the remote host. Please
4382 ;; tell me about it when this doesn't work on your system.
4383 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4384 (let ((uname (match-string 1 localname))
4385 (fname (match-string 2 localname)))
4386 ;; We cannot simply apply "~/", because under sudo "~/" is
4387 ;; expanded to the local user home directory but to the
4388 ;; root home directory. On the other hand, using always
4389 ;; the default user name for tilde expansion is not
4390 ;; appropriate either, because ssh and companions might
4391 ;; use a user name from the config file.
4392 (when (and (string-equal uname "~")
4393 (string-match "\\`su\\(do\\)?\\'" method))
4394 (setq uname (concat uname user)))
4395 (setq uname
4396 (with-connection-property v uname
4397 (tramp-send-command
4398 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4399 (with-current-buffer (tramp-get-buffer v)
4400 (goto-char (point-min))
4401 (buffer-substring
4402 (point) (tramp-compat-line-end-position)))))
4403 (setq localname (concat uname fname))))
4404 ;; There might be a double slash, for example when "~/"
4405 ;; expands to "/". Remove this.
4406 (while (string-match "//" localname)
4407 (setq localname (replace-match "/" t t localname)))
4408 ;; No tilde characters in file name, do normal
4409 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4410 ;; `directory-sep-char' here for XEmacs on Windows, which would
4411 ;; otherwise use backslash. `default-directory' is bound,
4412 ;; because on Windows there would be problems with UNC shares or
4413 ;; Cygwin mounts.
4414 (let ((directory-sep-char ?/)
4415 (default-directory (tramp-compat-temporary-file-directory)))
4416 (tramp-make-tramp-file-name
4417 method user host
4418 (tramp-drop-volume-letter
4419 (tramp-run-real-handler
4420 'expand-file-name (list localname))))))))
4421
4422 (defun tramp-replace-environment-variables (filename)
4423 "Replace environment variables in FILENAME.
4424 Return the string with the replaced variables."
4425 (save-match-data
4426 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4427 ;; `$' is coded as `$$'.
4428 (when (and idx
4429 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4430 (getenv (match-string 1 filename)))
4431 (setq filename
4432 (replace-match
4433 (substitute-in-file-name (match-string 0 filename))
4434 t nil filename)))
4435 filename)))
4436
4437 (defun tramp-handle-substitute-in-file-name (filename)
4438 "Like `substitute-in-file-name' for Tramp files.
4439 \"//\" and \"/~\" substitute only in the local filename part.
4440 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4441 beginning of local filename are not substituted."
4442 ;; First, we must replace environment variables.
4443 (setq filename (tramp-replace-environment-variables filename))
4444 (with-parsed-tramp-file-name filename nil
4445 (if (equal tramp-syntax 'url)
4446 ;; We need to check localname only. The other parts cannot contain
4447 ;; "//" or "/~".
4448 (if (and (> (length localname) 1)
4449 (or (string-match "//" localname)
4450 (string-match "/~" localname 1)))
4451 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4452 (tramp-make-tramp-file-name
4453 (when method (substitute-in-file-name method))
4454 (when user (substitute-in-file-name user))
4455 (when host (substitute-in-file-name host))
4456 (when localname
4457 (tramp-run-real-handler
4458 'substitute-in-file-name (list localname)))))
4459 ;; Ignore in LOCALNAME everything before "//" or "/~".
4460 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4461 (setq filename
4462 (concat (file-remote-p filename)
4463 (replace-match "\\1" nil nil localname)))
4464 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4465 (when (string-match "~$" filename)
4466 (setq filename (concat filename "/"))))
4467 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4468
4469 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4470 ;; which calls corresponding functions (see minibuf.el).
4471 (when (fboundp 'minibuffer-electric-separator)
4472 (mapc
4473 (lambda (x)
4474 (eval
4475 `(defadvice ,x
4476 (around ,(intern (format "tramp-advice-%s" x)) activate)
4477 "Invoke `substitute-in-file-name' for Tramp files."
4478 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4479 (tramp-tramp-file-p (buffer-substring)))
4480 ;; We don't need to handle `last-input-event', because
4481 ;; due to the key map we know it must be ?/ or ?~.
4482 (let ((s (concat (buffer-substring (point-min) (point))
4483 (string last-command-char))))
4484 (delete-region (point-min) (point))
4485 (insert (substitute-in-file-name s))
4486 (setq ad-return-value last-command-char))
4487 ad-do-it)))
4488 (eval
4489 `(add-hook
4490 'tramp-unload-hook
4491 (lambda ()
4492 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4493 (ad-activate ',x)))))
4494
4495 '(minibuffer-electric-separator
4496 minibuffer-electric-tilde)))
4497
4498
4499 ;;; Remote commands:
4500
4501 (defun tramp-handle-executable-find (command)
4502 "Like `executable-find' for Tramp files."
4503 (with-parsed-tramp-file-name default-directory nil
4504 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4505
4506 ;; We use BUFFER also as connection buffer during setup. Because of
4507 ;; this, its original contents must be saved, and restored once
4508 ;; connection has been setup.
4509 (defun tramp-handle-start-file-process (name buffer program &rest args)
4510 "Like `start-file-process' for Tramp files."
4511 (with-parsed-tramp-file-name default-directory nil
4512 (unwind-protect
4513 ;; When PROGRAM is nil, we just provide a tty.
4514 (let ((command
4515 (when (stringp program)
4516 (format "cd %s; exec %s"
4517 (tramp-shell-quote-argument localname)
4518 (mapconcat 'tramp-shell-quote-argument
4519 (cons program args) " "))))
4520 (tramp-process-connection-type
4521 (or (null program) tramp-process-connection-type))
4522 (name1 name)
4523 (i 0))
4524 (unless buffer
4525 ;; BUFFER can be nil. We use a temporary buffer.
4526 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4527 (while (get-process name1)
4528 ;; NAME must be unique as process name.
4529 (setq i (1+ i)
4530 name1 (format "%s<%d>" name i)))
4531 (setq name name1)
4532 ;; Set the new process properties.
4533 (tramp-set-connection-property v "process-name" name)
4534 (tramp-set-connection-property v "process-buffer" buffer)
4535 ;; Activate narrowing in order to save BUFFER contents.
4536 ;; Clear also the modification time; otherwise we might be
4537 ;; interrupted by `verify-visited-file-modtime'.
4538 (with-current-buffer (tramp-get-connection-buffer v)
4539 (clear-visited-file-modtime)
4540 (narrow-to-region (point-max) (point-max)))
4541 (if (stringp program)
4542 ;; Send the command. `tramp-send-command' opens a new
4543 ;; connection.
4544 (tramp-send-command v command nil t) ; nooutput
4545 ;; Check, whether a pty is associated, and set it as
4546 ;; process property.
4547 (condition-case nil
4548 (tramp-send-command-and-read v "echo \\\"`tty`\\\"")
4549 (tramp-error
4550 v 'file-error "pty association is not supported for `%s'" name)))
4551 ;; Set query flag for this process.
4552 (tramp-set-process-query-on-exit-flag
4553 (tramp-get-connection-process v) t)
4554 ;; Return process.
4555 (tramp-get-connection-process v))
4556 ;; Save exit.
4557 (with-current-buffer (tramp-get-connection-buffer v)
4558 (if (string-match tramp-temp-buffer-name (buffer-name))
4559 (progn
4560 (set-process-buffer (tramp-get-connection-process v) nil)
4561 (kill-buffer (current-buffer)))
4562 (widen)
4563 (goto-char (point-max))))
4564 (tramp-set-connection-property v "process-name" nil)
4565 (tramp-set-connection-property v "process-buffer" nil))))
4566
4567 (defun tramp-handle-process-file
4568 (program &optional infile destination display &rest args)
4569 "Like `process-file' for Tramp files."
4570 ;; The implementation is not complete yet.
4571 (when (and (numberp destination) (zerop destination))
4572 (error "Implementation does not handle immediate return"))
4573
4574 (with-parsed-tramp-file-name default-directory nil
4575 (let (command input tmpinput stderr tmpstderr outbuf ret)
4576 ;; Compute command.
4577 (setq command (mapconcat 'tramp-shell-quote-argument
4578 (cons program args) " "))
4579 ;; Determine input.
4580 (if (null infile)
4581 (setq input "/dev/null")
4582 (setq infile (expand-file-name infile))
4583 (if (tramp-equal-remote default-directory infile)
4584 ;; INFILE is on the same remote host.
4585 (setq input (with-parsed-tramp-file-name infile nil localname))
4586 ;; INFILE must be copied to remote host.
4587 (setq input (tramp-make-tramp-temp-file v)
4588 tmpinput (tramp-make-tramp-file-name method user host input))
4589 (copy-file infile tmpinput t)))
4590 (when input (setq command (format "%s <%s" command input)))
4591
4592 ;; Determine output.
4593 (cond
4594 ;; Just a buffer.
4595 ((bufferp destination)
4596 (setq outbuf destination))
4597 ;; A buffer name.
4598 ((stringp destination)
4599 (setq outbuf (get-buffer-create destination)))
4600 ;; (REAL-DESTINATION ERROR-DESTINATION)
4601 ((consp destination)
4602 ;; output.
4603 (cond
4604 ((bufferp (car destination))
4605 (setq outbuf (car destination)))
4606 ((stringp (car destination))
4607 (setq outbuf (get-buffer-create (car destination))))
4608 ((car destination)
4609 (setq outbuf (current-buffer))))
4610 ;; stderr.
4611 (cond
4612 ((stringp (cadr destination))
4613 (setcar (cdr destination) (expand-file-name (cadr destination)))
4614 (if (tramp-equal-remote default-directory (cadr destination))
4615 ;; stderr is on the same remote host.
4616 (setq stderr (with-parsed-tramp-file-name
4617 (cadr destination) nil localname))
4618 ;; stderr must be copied to remote host. The temporary
4619 ;; file must be deleted after execution.
4620 (setq stderr (tramp-make-tramp-temp-file v)
4621 tmpstderr (tramp-make-tramp-file-name
4622 method user host stderr))))
4623 ;; stderr to be discarded.
4624 ((null (cadr destination))
4625 (setq stderr "/dev/null"))))
4626 ;; 't
4627 (destination
4628 (setq outbuf (current-buffer))))
4629 (when stderr (setq command (format "%s 2>%s" command stderr)))
4630
4631 ;; Send the command. It might not return in time, so we protect it.
4632 (condition-case nil
4633 (unwind-protect
4634 (setq ret
4635 (tramp-send-command-and-check
4636 v (format "\\cd %s; %s"
4637 (tramp-shell-quote-argument localname)
4638 command)
4639 nil t))
4640 ;; We should show the output anyway.
4641 (when outbuf
4642 (with-current-buffer outbuf
4643 (insert
4644 (with-current-buffer (tramp-get-connection-buffer v)
4645 (buffer-string))))
4646 (when display (display-buffer outbuf))))
4647 ;; When the user did interrupt, we should do it also. We use
4648 ;; return code -1 as marker.
4649 (quit
4650 (kill-buffer (tramp-get-connection-buffer v))
4651 (setq ret -1))
4652 ;; Handle errors.
4653 (error
4654 (kill-buffer (tramp-get-connection-buffer v))
4655 (setq ret 1)))
4656
4657 ;; Provide error file.
4658 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4659
4660 ;; Cleanup. We remove all file cache values for the connection,
4661 ;; because the remote process could have changed them.
4662 (when tmpinput (delete-file tmpinput))
4663
4664 ;; `process-file-side-effects' has been introduced with GNU
4665 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4666 ;; by `program'. If it doesn't exist, we assume its default
4667 ;; value 't'.
4668 (unless (and (boundp 'process-file-side-effects)
4669 (not (symbol-value 'process-file-side-effects)))
4670 (tramp-flush-directory-property v ""))
4671
4672 ;; Return exit status.
4673 (if (equal ret -1)
4674 (keyboard-quit)
4675 ret))))
4676
4677 (defun tramp-local-call-process
4678 (program &optional infile destination display &rest args)
4679 "Calls `call-process' on the local host.
4680 This is needed because for some Emacs flavors Tramp has
4681 defadviced `call-process' to behave like `process-file'. The
4682 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4683 (let ((default-directory
4684 (if (file-remote-p default-directory)
4685 (tramp-compat-temporary-file-directory)
4686 default-directory)))
4687 (if (executable-find program)
4688 (apply 'call-process program infile destination display args)
4689 1)))
4690
4691 (defun tramp-handle-call-process-region
4692 (start end program &optional delete buffer display &rest args)
4693 "Like `call-process-region' for Tramp files."
4694 (let ((tmpfile (tramp-compat-make-temp-file "")))
4695 (write-region start end tmpfile)
4696 (when delete (delete-region start end))
4697 (unwind-protect
4698 (apply 'call-process program tmpfile buffer display args)
4699 (delete-file tmpfile))))
4700
4701 (defun tramp-handle-shell-command
4702 (command &optional output-buffer error-buffer)
4703 "Like `shell-command' for Tramp files."
4704 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4705 ;; We cannot use `shell-file-name' and `shell-command-switch',
4706 ;; they are variables of the local host.
4707 (args (list
4708 (tramp-get-method-parameter
4709 (tramp-file-name-method
4710 (tramp-dissect-file-name default-directory))
4711 'tramp-remote-sh)
4712 "-c" (substring command 0 asynchronous)))
4713 current-buffer-p
4714 (output-buffer
4715 (cond
4716 ((bufferp output-buffer) output-buffer)
4717 ((stringp output-buffer) (get-buffer-create output-buffer))
4718 (output-buffer
4719 (setq current-buffer-p t)
4720 (current-buffer))
4721 (t (get-buffer-create
4722 (if asynchronous
4723 "*Async Shell Command*"
4724 "*Shell Command Output*")))))
4725 (error-buffer
4726 (cond
4727 ((bufferp error-buffer) error-buffer)
4728 ((stringp error-buffer) (get-buffer-create error-buffer))))
4729 (buffer
4730 (if (and (not asynchronous) error-buffer)
4731 (with-parsed-tramp-file-name default-directory nil
4732 (list output-buffer (tramp-make-tramp-temp-file v)))
4733 output-buffer))
4734 (p (get-buffer-process output-buffer)))
4735
4736 ;; Check whether there is another process running. Tramp does not
4737 ;; support 2 (asynchronous) processes in parallel.
4738 (when p
4739 (if (yes-or-no-p "A command is running. Kill it? ")
4740 (condition-case nil
4741 (kill-process p)
4742 (error nil))
4743 (error "Shell command in progress")))
4744
4745 (if current-buffer-p
4746 (progn
4747 (barf-if-buffer-read-only)
4748 (push-mark nil t))
4749 (with-current-buffer output-buffer
4750 (setq buffer-read-only nil)
4751 (erase-buffer)))
4752
4753 (if (and (not current-buffer-p) (integerp asynchronous))
4754 (prog1
4755 ;; Run the process.
4756 (apply 'start-file-process "*Async Shell*" buffer args)
4757 ;; Display output.
4758 (pop-to-buffer output-buffer)
4759 (setq mode-line-process '(":%s"))
4760 (require 'shell) (shell-mode))
4761
4762 (prog1
4763 ;; Run the process.
4764 (apply 'process-file (car args) nil buffer nil (cdr args))
4765 ;; Insert error messages if they were separated.
4766 (when (listp buffer)
4767 (with-current-buffer error-buffer
4768 (insert-file-contents (cadr buffer)))
4769 (delete-file (cadr buffer)))
4770 (if current-buffer-p
4771 ;; This is like exchange-point-and-mark, but doesn't
4772 ;; activate the mark. It is cleaner to avoid activation,
4773 ;; even though the command loop would deactivate the mark
4774 ;; because we inserted text.
4775 (goto-char (prog1 (mark t)
4776 (set-marker (mark-marker) (point)
4777 (current-buffer))))
4778 ;; There's some output, display it.
4779 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4780 (if (functionp 'display-message-or-buffer)
4781 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
4782 (pop-to-buffer output-buffer))))))))
4783
4784 ;; File Editing.
4785
4786 (defvar tramp-handle-file-local-copy-hook nil
4787 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4788
4789 (defun tramp-handle-file-local-copy (filename)
4790 "Like `file-local-copy' for Tramp files."
4791
4792 (with-parsed-tramp-file-name filename nil
4793 (unless (file-exists-p filename)
4794 (tramp-error
4795 v 'file-error
4796 "Cannot make local copy of non-existing file `%s'" filename))
4797
4798 (let* ((size (nth 7 (file-attributes filename)))
4799 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
4800 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
4801 (tmpfile (tramp-compat-make-temp-file filename)))
4802
4803 (condition-case err
4804 (cond
4805 ;; `copy-file' handles direct copy and out-of-band methods.
4806 ((or (tramp-local-host-p v)
4807 (tramp-method-out-of-band-p v size))
4808 (copy-file filename tmpfile t t))
4809
4810 ;; Use inline encoding for file transfer.
4811 (rem-enc
4812 (save-excursion
4813 (with-progress-reporter
4814 v 3 (format "Encoding remote file %s" filename)
4815 (tramp-barf-unless-okay
4816 v (format rem-enc (tramp-shell-quote-argument localname))
4817 "Encoding remote file failed"))
4818
4819 (if (functionp loc-dec)
4820 ;; If local decoding is a function, we call it. We
4821 ;; must disable multibyte, because
4822 ;; `uudecode-decode-region' doesn't handle it
4823 ;; correctly.
4824 (with-temp-buffer
4825 (set-buffer-multibyte nil)
4826 (insert-buffer-substring (tramp-get-buffer v))
4827 (with-progress-reporter
4828 v 3 (format "Decoding remote file %s with function %s"
4829 filename loc-dec)
4830 (funcall loc-dec (point-min) (point-max))
4831 ;; Unset `file-name-handler-alist'. Otherwise,
4832 ;; epa-file gets confused.
4833 (let (file-name-handler-alist
4834 (coding-system-for-write 'binary))
4835 (write-region (point-min) (point-max) tmpfile))))
4836
4837 ;; If tramp-decoding-function is not defined for this
4838 ;; method, we invoke tramp-decoding-command instead.
4839 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4840 ;; Unset `file-name-handler-alist'. Otherwise,
4841 ;; epa-file gets confused.
4842 (let (file-name-handler-alist
4843 (coding-system-for-write 'binary))
4844 (write-region (point-min) (point-max) tmpfile2))
4845 (with-progress-reporter
4846 v 3 (format "Decoding remote file %s with command %s"
4847 filename loc-dec)
4848 (unwind-protect
4849 (tramp-call-local-coding-command
4850 loc-dec tmpfile2 tmpfile)
4851 (delete-file tmpfile2)))))
4852
4853 ;; Set proper permissions.
4854 (set-file-modes tmpfile (tramp-default-file-modes filename))
4855 ;; Set local user ownership.
4856 (tramp-set-file-uid-gid tmpfile)))
4857
4858 ;; Oops, I don't know what to do.
4859 (t (tramp-error
4860 v 'file-error "Wrong method specification for `%s'" method)))
4861
4862 ;; Error handling.
4863 ((error quit)
4864 (delete-file tmpfile)
4865 (signal (car err) (cdr err))))
4866
4867 (run-hooks 'tramp-handle-file-local-copy-hook)
4868 tmpfile)))
4869
4870 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4871 "Like `file-remote-p' for Tramp files."
4872 (let ((tramp-verbose 3))
4873 (when (tramp-tramp-file-p filename)
4874 (let* ((v (tramp-dissect-file-name filename))
4875 (p (tramp-get-connection-process v))
4876 (c (and p (processp p) (memq (process-status p) '(run open)))))
4877 ;; We expand the file name only, if there is already a connection.
4878 (with-parsed-tramp-file-name
4879 (if c (expand-file-name filename) filename) nil
4880 (and (or (not connected) c)
4881 (cond
4882 ((eq identification 'method) method)
4883 ((eq identification 'user) user)
4884 ((eq identification 'host) host)
4885 ((eq identification 'localname) localname)
4886 (t (tramp-make-tramp-file-name method user host "")))))))))
4887
4888 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4889 "Like `find-operation-coding-system' for Tramp filenames.
4890 Tramp's `insert-file-contents' and `write-region' work over
4891 temporary file names. If `file-coding-system-alist' contains an
4892 expression, which matches more than the file name suffix, the
4893 coding system might not be determined. This function repairs it."
4894 (let (result)
4895 (dolist (elt file-coding-system-alist result)
4896 (when (and (consp elt) (string-match (car elt) filename))
4897 ;; We found a matching entry in `file-coding-system-alist'.
4898 ;; So we add a similar entry, but with the temporary file name
4899 ;; as regexp.
4900 (add-to-list
4901 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4902
4903 (defun tramp-handle-insert-file-contents
4904 (filename &optional visit beg end replace)
4905 "Like `insert-file-contents' for Tramp files."
4906 (barf-if-buffer-read-only)
4907 (setq filename (expand-file-name filename))
4908 (let (result local-copy remote-copy)
4909 (with-parsed-tramp-file-name filename nil
4910 (unwind-protect
4911 (if (not (file-exists-p filename))
4912 ;; We don't raise a Tramp error, because it might be
4913 ;; suppressed, like in `find-file-noselect-1'.
4914 (signal 'file-error
4915 (list "File not found on remote host" filename))
4916
4917 (if (and (tramp-local-host-p v)
4918 (let (file-name-handler-alist)
4919 (file-readable-p localname)))
4920 ;; Short track: if we are on the local host, we can
4921 ;; run directly.
4922 (setq result
4923 (tramp-run-real-handler
4924 'insert-file-contents
4925 (list localname visit beg end replace)))
4926
4927 ;; When we shall insert only a part of the file, we copy
4928 ;; this part.
4929 (when (or beg end)
4930 (setq remote-copy (tramp-make-tramp-temp-file v))
4931 (tramp-send-command
4932 v
4933 (cond
4934 ((and beg end)
4935 (format "tail -c +%d %s | head -c +%d >%s"
4936 (1+ beg) (tramp-shell-quote-argument localname)
4937 (- end beg) remote-copy))
4938 (beg
4939 (format "tail -c +%d %s >%s"
4940 (1+ beg) (tramp-shell-quote-argument localname)
4941 remote-copy))
4942 (end
4943 (format "head -c +%d %s >%s"
4944 (1+ end) (tramp-shell-quote-argument localname)
4945 remote-copy)))))
4946
4947 ;; `insert-file-contents-literally' takes care to avoid
4948 ;; calling jka-compr. By let-binding
4949 ;; `inhibit-file-name-operation', we propagate that care
4950 ;; to the `file-local-copy' operation.
4951 (setq local-copy
4952 (let ((inhibit-file-name-operation
4953 (when (eq inhibit-file-name-operation
4954 'insert-file-contents)
4955 'file-local-copy)))
4956 (cond
4957 ((stringp remote-copy)
4958 (file-local-copy
4959 (tramp-make-tramp-file-name
4960 method user host remote-copy)))
4961 ((stringp tramp-temp-buffer-file-name)
4962 (copy-file filename tramp-temp-buffer-file-name 'ok)
4963 tramp-temp-buffer-file-name)
4964 (t (file-local-copy filename)))))
4965
4966 ;; When the file is not readable for the owner, it
4967 ;; cannot be inserted, even it is redable for the group
4968 ;; or for everybody.
4969 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4970
4971 (when (and (null remote-copy)
4972 (tramp-get-method-parameter
4973 method 'tramp-copy-keep-tmpfile))
4974 ;; We keep the local file for performance reasons,
4975 ;; useful for "rsync".
4976 (setq tramp-temp-buffer-file-name local-copy)
4977 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4978
4979 (with-progress-reporter
4980 v 3 (format "Inserting local temp file `%s'" local-copy)
4981 ;; We must ensure that `file-coding-system-alist'
4982 ;; matches `local-copy'.
4983 (let ((file-coding-system-alist
4984 (tramp-find-file-name-coding-system-alist
4985 filename local-copy)))
4986 (setq result
4987 (insert-file-contents
4988 local-copy nil nil nil replace))))))
4989
4990 ;; Save exit.
4991 (progn
4992 (when visit
4993 (setq buffer-file-name filename)
4994 (setq buffer-read-only (not (file-writable-p filename)))
4995 (set-visited-file-modtime)
4996 (set-buffer-modified-p nil))
4997 (when (and (stringp local-copy)
4998 (or remote-copy (null tramp-temp-buffer-file-name)))
4999 (delete-file local-copy))
5000 (when (stringp remote-copy)
5001 (delete-file
5002 (tramp-make-tramp-file-name method user host remote-copy))))))
5003
5004 ;; Result.
5005 (list (expand-file-name filename)
5006 (cadr result))))
5007
5008 ;; This is needed for XEmacs only. Code stolen from files.el.
5009 (defun tramp-handle-insert-file-contents-literally
5010 (filename &optional visit beg end replace)
5011 "Like `insert-file-contents-literally' for Tramp files."
5012 (let ((format-alist nil)
5013 (after-insert-file-functions nil)
5014 (coding-system-for-read 'no-conversion)
5015 (coding-system-for-write 'no-conversion)
5016 (find-buffer-file-type-function
5017 (if (fboundp 'find-buffer-file-type)
5018 (symbol-function 'find-buffer-file-type)
5019 nil))
5020 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
5021 (inhibit-file-name-operation 'insert-file-contents))
5022 (unwind-protect
5023 (progn
5024 (fset 'find-buffer-file-type (lambda (filename) t))
5025 (insert-file-contents filename visit beg end replace))
5026 ;; Save exit.
5027 (if find-buffer-file-type-function
5028 (fset 'find-buffer-file-type find-buffer-file-type-function)
5029 (fmakunbound 'find-buffer-file-type)))))
5030
5031 (defun tramp-handle-find-backup-file-name (filename)
5032 "Like `find-backup-file-name' for Tramp files."
5033 (with-parsed-tramp-file-name filename nil
5034 ;; We set both variables. It doesn't matter whether it is
5035 ;; Emacs or XEmacs.
5036 (let ((backup-directory-alist
5037 ;; Emacs case.
5038 (when (boundp 'backup-directory-alist)
5039 (if (symbol-value 'tramp-backup-directory-alist)
5040 (mapcar
5041 (lambda (x)
5042 (cons
5043 (car x)
5044 (if (and (stringp (cdr x))
5045 (file-name-absolute-p (cdr x))
5046 (not (tramp-file-name-p (cdr x))))
5047 (tramp-make-tramp-file-name method user host (cdr x))
5048 (cdr x))))
5049 (symbol-value 'tramp-backup-directory-alist))
5050 (symbol-value 'backup-directory-alist))))
5051
5052 (bkup-backup-directory-info
5053 ;; XEmacs case.
5054 (when (boundp 'bkup-backup-directory-info)
5055 (if (symbol-value 'tramp-bkup-backup-directory-info)
5056 (mapcar
5057 (lambda (x)
5058 (nconc
5059 (list (car x))
5060 (list
5061 (if (and (stringp (car (cdr x)))
5062 (file-name-absolute-p (car (cdr x)))
5063 (not (tramp-file-name-p (car (cdr x)))))
5064 (tramp-make-tramp-file-name
5065 method user host (car (cdr x)))
5066 (car (cdr x))))
5067 (cdr (cdr x))))
5068 (symbol-value 'tramp-bkup-backup-directory-info))
5069 (symbol-value 'bkup-backup-directory-info)))))
5070
5071 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
5072
5073 (defun tramp-handle-make-auto-save-file-name ()
5074 "Like `make-auto-save-file-name' for Tramp files.
5075 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
5076 (let ((tramp-auto-save-directory tramp-auto-save-directory)
5077 (buffer-file-name
5078 (tramp-subst-strs-in-string
5079 '(("_" . "|")
5080 ("/" . "_a")
5081 (":" . "_b")
5082 ("|" . "__")
5083 ("[" . "_l")
5084 ("]" . "_r"))
5085 (buffer-file-name))))
5086 ;; File name must be unique. This is ensured with Emacs 22 (see
5087 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
5088 ;; all other cases we must do it ourselves.
5089 (when (boundp 'auto-save-file-name-transforms)
5090 (mapc
5091 (lambda (x)
5092 (when (and (string-match (car x) buffer-file-name)
5093 (not (car (cddr x))))
5094 (setq tramp-auto-save-directory
5095 (or tramp-auto-save-directory
5096 (tramp-compat-temporary-file-directory)))))
5097 (symbol-value 'auto-save-file-name-transforms)))
5098 ;; Create directory.
5099 (when tramp-auto-save-directory
5100 (setq buffer-file-name
5101 (expand-file-name buffer-file-name tramp-auto-save-directory))
5102 (unless (file-exists-p tramp-auto-save-directory)
5103 (make-directory tramp-auto-save-directory t)))
5104 ;; Run plain `make-auto-save-file-name'. There might be an advice when
5105 ;; it is not a magic file name operation (since Emacs 22).
5106 ;; We must deactivate it temporarily.
5107 (if (not (ad-is-active 'make-auto-save-file-name))
5108 (tramp-run-real-handler 'make-auto-save-file-name nil)
5109 ;; else
5110 (ad-deactivate 'make-auto-save-file-name)
5111 (prog1
5112 (tramp-run-real-handler 'make-auto-save-file-name nil)
5113 (ad-activate 'make-auto-save-file-name)))))
5114
5115 (defvar tramp-handle-write-region-hook nil
5116 "Normal hook to be run at the end of `tramp-handle-write-region'.")
5117
5118 ;; CCC grok LOCKNAME
5119 (defun tramp-handle-write-region
5120 (start end filename &optional append visit lockname confirm)
5121 "Like `write-region' for Tramp files."
5122 (setq filename (expand-file-name filename))
5123 (with-parsed-tramp-file-name filename nil
5124 ;; Following part commented out because we don't know what to do about
5125 ;; file locking, and it does not appear to be a problem to ignore it.
5126 ;; Ange-ftp ignores it, too.
5127 ;; (when (and lockname (stringp lockname))
5128 ;; (setq lockname (expand-file-name lockname)))
5129 ;; (unless (or (eq lockname nil)
5130 ;; (string= lockname filename))
5131 ;; (error
5132 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
5133
5134 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
5135 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
5136 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
5137 (tramp-error v 'file-error "File not overwritten")))
5138
5139 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
5140 (tramp-get-remote-uid v 'integer)))
5141 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
5142 (tramp-get-remote-gid v 'integer))))
5143
5144 (if (and (tramp-local-host-p v)
5145 ;; `file-writable-p' calls `file-expand-file-name'. We
5146 ;; cannot use `tramp-run-real-handler' therefore.
5147 (let (file-name-handler-alist)
5148 (and
5149 (file-writable-p (file-name-directory localname))
5150 (or (file-directory-p localname)
5151 (file-writable-p localname)))))
5152 ;; Short track: if we are on the local host, we can run directly.
5153 (tramp-run-real-handler
5154 'write-region
5155 (list start end localname append 'no-message lockname confirm))
5156
5157 (let ((modes (save-excursion (tramp-default-file-modes filename)))
5158 ;; We use this to save the value of
5159 ;; `last-coding-system-used' after writing the tmp
5160 ;; file. At the end of the function, we set
5161 ;; `last-coding-system-used' to this saved value. This
5162 ;; way, any intermediary coding systems used while
5163 ;; talking to the remote shell or suchlike won't hose
5164 ;; this variable. This approach was snarfed from
5165 ;; ange-ftp.el.
5166 coding-system-used
5167 ;; Write region into a tmp file. This isn't really
5168 ;; needed if we use an encoding function, but currently
5169 ;; we use it always because this makes the logic
5170 ;; simpler.
5171 (tmpfile (or tramp-temp-buffer-file-name
5172 (tramp-compat-make-temp-file filename))))
5173
5174 ;; If `append' is non-nil, we copy the file locally, and let
5175 ;; the native `write-region' implementation do the job.
5176 (when append (copy-file filename tmpfile 'ok))
5177
5178 ;; We say `no-message' here because we don't want the
5179 ;; visited file modtime data to be clobbered from the temp
5180 ;; file. We call `set-visited-file-modtime' ourselves later
5181 ;; on. We must ensure that `file-coding-system-alist'
5182 ;; matches `tmpfile'.
5183 (let (file-name-handler-alist
5184 (file-coding-system-alist
5185 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5186 (condition-case err
5187 (tramp-run-real-handler
5188 'write-region
5189 (list start end tmpfile append 'no-message lockname confirm))
5190 ((error quit)
5191 (setq tramp-temp-buffer-file-name nil)
5192 (delete-file tmpfile)
5193 (signal (car err) (cdr err))))
5194
5195 ;; Now, `last-coding-system-used' has the right value. Remember it.
5196 (when (boundp 'last-coding-system-used)
5197 (setq coding-system-used
5198 (symbol-value 'last-coding-system-used))))
5199
5200 ;; The permissions of the temporary file should be set. If
5201 ;; filename does not exist (eq modes nil) it has been
5202 ;; renamed to the backup file. This case `save-buffer'
5203 ;; handles permissions.
5204 ;; Ensure, that it is still readable.
5205 (when modes
5206 (set-file-modes
5207 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
5208
5209 ;; This is a bit lengthy due to the different methods
5210 ;; possible for file transfer. First, we check whether the
5211 ;; method uses an rcp program. If so, we call it.
5212 ;; Otherwise, both encoding and decoding command must be
5213 ;; specified. However, if the method _also_ specifies an
5214 ;; encoding function, then that is used for encoding the
5215 ;; contents of the tmp file.
5216 (let* ((size (nth 7 (file-attributes tmpfile)))
5217 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
5218 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
5219 (cond
5220 ;; `copy-file' handles direct copy and out-of-band methods.
5221 ((or (tramp-local-host-p v)
5222 (tramp-method-out-of-band-p v size))
5223 (if (and (not (stringp start))
5224 (= (or end (point-max)) (point-max))
5225 (= (or start (point-min)) (point-min))
5226 (tramp-get-method-parameter
5227 method 'tramp-copy-keep-tmpfile))
5228 (progn
5229 (setq tramp-temp-buffer-file-name tmpfile)
5230 (condition-case err
5231 ;; We keep the local file for performance
5232 ;; reasons, useful for "rsync".
5233 (copy-file tmpfile filename t)
5234 ((error quit)
5235 (setq tramp-temp-buffer-file-name nil)
5236 (delete-file tmpfile)
5237 (signal (car err) (cdr err)))))
5238 (setq tramp-temp-buffer-file-name nil)
5239 ;; Don't rename, in order to keep context in SELinux.
5240 (unwind-protect
5241 (copy-file tmpfile filename t)
5242 (delete-file tmpfile))))
5243
5244 ;; Use inline file transfer.
5245 (rem-dec
5246 ;; Encode tmpfile.
5247 (unwind-protect
5248 (with-temp-buffer
5249 (set-buffer-multibyte nil)
5250 ;; Use encoding function or command.
5251 (if (functionp loc-enc)
5252 (with-progress-reporter
5253 v 3 (format "Encoding region using function `%s'"
5254 loc-enc)
5255 (let ((coding-system-for-read 'binary))
5256 (insert-file-contents-literally tmpfile))
5257 ;; The following `let' is a workaround for the
5258 ;; base64.el that comes with pgnus-0.84. If
5259 ;; both of the following conditions are
5260 ;; satisfied, it tries to write to a local
5261 ;; file in default-directory, but at this
5262 ;; point, default-directory is remote.
5263 ;; (`call-process-region' can't write to
5264 ;; remote files, it seems.) The file in
5265 ;; question is a tmp file anyway.
5266 (let ((default-directory
5267 (tramp-compat-temporary-file-directory)))
5268 (funcall loc-enc (point-min) (point-max))))
5269
5270 (with-progress-reporter
5271 v 3 (format "Encoding region using command `%s'"
5272 loc-enc)
5273 (unless (zerop (tramp-call-local-coding-command
5274 loc-enc tmpfile t))
5275 (tramp-error
5276 v 'file-error
5277 (concat "Cannot write to `%s', "
5278 "local encoding command `%s' failed")
5279 filename loc-enc))))
5280
5281 ;; Send buffer into remote decoding command which
5282 ;; writes to remote file. Because this happens on
5283 ;; the remote host, we cannot use the function.
5284 (with-progress-reporter
5285 v 3
5286 (format "Decoding region into remote file %s" filename)
5287 (goto-char (point-max))
5288 (unless (bolp) (newline))
5289 (tramp-send-command
5290 v
5291 (format
5292 (concat rem-dec " <<'EOF'\n%sEOF")
5293 (tramp-shell-quote-argument localname)
5294 (buffer-string)))
5295 (tramp-barf-unless-okay
5296 v nil
5297 "Couldn't write region to `%s', decode using `%s' failed"
5298 filename rem-dec)
5299 ;; When `file-precious-flag' is set, the region is
5300 ;; written to a temporary file. Check that the
5301 ;; checksum is equal to that from the local tmpfile.
5302 (when file-precious-flag
5303 (erase-buffer)
5304 (and
5305 ;; cksum runs locally, if possible.
5306 (zerop (tramp-local-call-process "cksum" tmpfile t))
5307 ;; cksum runs remotely.
5308 (zerop
5309 (tramp-send-command-and-check
5310 v
5311 (format
5312 "cksum <%s"
5313 (tramp-shell-quote-argument localname))))
5314 ;; ... they are different.
5315 (not
5316 (string-equal
5317 (buffer-string)
5318 (with-current-buffer (tramp-get-buffer v)
5319 (buffer-string))))
5320 (tramp-error
5321 v 'file-error
5322 (concat "Couldn't write region to `%s',"
5323 " decode using `%s' failed")
5324 filename rem-dec)))))
5325
5326 ;; Save exit.
5327 (delete-file tmpfile)))
5328
5329 ;; That's not expected.
5330 (t
5331 (tramp-error
5332 v 'file-error
5333 (concat "Method `%s' should specify both encoding and "
5334 "decoding command or an rcp program")
5335 method))))
5336
5337 ;; Make `last-coding-system-used' have the right value.
5338 (when coding-system-used
5339 (set 'last-coding-system-used coding-system-used))))
5340
5341 (tramp-flush-file-property v (file-name-directory localname))
5342 (tramp-flush-file-property v localname)
5343
5344 ;; We must protect `last-coding-system-used', now we have set it
5345 ;; to its correct value.
5346 (let (last-coding-system-used (need-chown t))
5347 ;; Set file modification time.
5348 (when (or (eq visit t) (stringp visit))
5349 (let ((file-attr (file-attributes filename)))
5350 (set-visited-file-modtime
5351 ;; We must pass modtime explicitely, because filename can
5352 ;; be different from (buffer-file-name), f.e. if
5353 ;; `file-precious-flag' is set.
5354 (nth 5 file-attr))
5355 (when (and (eq (nth 2 file-attr) uid)
5356 (eq (nth 3 file-attr) gid))
5357 (setq need-chown nil))))
5358
5359 ;; Set the ownership.
5360 (when need-chown
5361 (tramp-set-file-uid-gid filename uid gid))
5362 (when (or (eq visit t) (null visit) (stringp visit))
5363 (tramp-message v 0 "Wrote %s" filename))
5364 (run-hooks 'tramp-handle-write-region-hook)))))
5365
5366 (defvar tramp-vc-registered-file-names nil
5367 "List used to collect file names, which are checked during `vc-registered'.")
5368
5369 ;; VC backends check for the existence of various different special
5370 ;; files. This is very time consuming, because every single check
5371 ;; requires a remote command (the file cache must be invalidated).
5372 ;; Therefore, we apply a kind of optimization. We install the file
5373 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5374 ;; remembers all file names for which `file-exists-p' or
5375 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5376 ;; is performed. Afterwards, a script is applied for all collected
5377 ;; file names, using just one remote command. The result of this
5378 ;; script is used to fill the file cache with actual values. Now we
5379 ;; can reset the file name handlers, and we make a second run of
5380 ;; `vc-registered', which returns the expected result without sending
5381 ;; any other remote command.
5382 (defun tramp-handle-vc-registered (file)
5383 "Like `vc-registered' for Tramp files."
5384 (with-temp-message ""
5385 (with-parsed-tramp-file-name file nil
5386 (with-progress-reporter
5387 v 3 (format "Checking `vc-registered' for %s" file)
5388
5389 ;; There could be new files, created by the vc backend. We
5390 ;; cannot reuse the old cache entries, therefore.
5391 (let (tramp-vc-registered-file-names
5392 (tramp-cache-inhibit-cache (current-time))
5393 (file-name-handler-alist
5394 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5395
5396 ;; Here we collect only file names, which need an operation.
5397 (tramp-run-real-handler 'vc-registered (list file))
5398 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5399
5400 ;; Send just one command, in order to fill the cache.
5401 (when tramp-vc-registered-file-names
5402 (tramp-maybe-send-script
5403 v
5404 (format tramp-vc-registered-read-file-names
5405 (tramp-get-file-exists-command v)
5406 (format "%s -r" (tramp-get-test-command v)))
5407 "tramp_vc_registered_read_file_names")
5408
5409 (dolist
5410 (elt
5411 (tramp-send-command-and-read
5412 v
5413 (format
5414 "tramp_vc_registered_read_file_names %s"
5415 (mapconcat 'tramp-shell-quote-argument
5416 tramp-vc-registered-file-names
5417 " "))))
5418
5419 (tramp-set-file-property
5420 v (car elt) (cadr elt) (cadr (cdr elt))))))
5421
5422 ;; Second run. Now all `file-exists-p' or `file-readable-p'
5423 ;; calls shall be answered from the file cache. We unset
5424 ;; `process-file-side-effects' in order to keep the cache when
5425 ;; `process-file' calls appear.
5426 (let (process-file-side-effects)
5427 (tramp-run-real-handler 'vc-registered (list file)))))))
5428
5429 ;;;###autoload
5430 (progn (defun tramp-run-real-handler (operation args)
5431 "Invoke normal file name handler for OPERATION.
5432 First arg specifies the OPERATION, second arg is a list of arguments to
5433 pass to the OPERATION."
5434 (let* ((inhibit-file-name-handlers
5435 `(tramp-file-name-handler
5436 tramp-vc-file-name-handler
5437 tramp-completion-file-name-handler
5438 cygwin-mount-name-hook-function
5439 cygwin-mount-map-drive-hook-function
5440 .
5441 ,(and (eq inhibit-file-name-operation operation)
5442 inhibit-file-name-handlers)))
5443 (inhibit-file-name-operation operation))
5444 (apply operation args))))
5445
5446 ;;;###autoload
5447 (progn (defun tramp-completion-run-real-handler (operation args)
5448 "Invoke `tramp-file-name-handler' for OPERATION.
5449 First arg specifies the OPERATION, second arg is a list of arguments to
5450 pass to the OPERATION."
5451 (let* ((inhibit-file-name-handlers
5452 `(tramp-completion-file-name-handler
5453 cygwin-mount-name-hook-function
5454 cygwin-mount-map-drive-hook-function
5455 .
5456 ,(and (eq inhibit-file-name-operation operation)
5457 inhibit-file-name-handlers)))
5458 (inhibit-file-name-operation operation))
5459 (apply operation args))))
5460
5461 ;; We handle here all file primitives. Most of them have the file
5462 ;; name as first parameter; nevertheless we check for them explicitly
5463 ;; in order to be signaled if a new primitive appears. This
5464 ;; scenario is needed because there isn't a way to decide by
5465 ;; syntactical means whether a foreign method must be called. It would
5466 ;; ease the life if `file-name-handler-alist' would support a decision
5467 ;; function as well but regexp only.
5468 (defun tramp-file-name-for-operation (operation &rest args)
5469 "Return file name related to OPERATION file primitive.
5470 ARGS are the arguments OPERATION has been called with."
5471 (cond
5472 ;; FILE resp DIRECTORY.
5473 ((member operation
5474 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5475 'delete-file 'diff-latest-backup-file 'directory-file-name
5476 'directory-files 'directory-files-and-attributes
5477 'dired-compress-file 'dired-uncache
5478 'file-accessible-directory-p 'file-attributes
5479 'file-directory-p 'file-executable-p 'file-exists-p
5480 'file-local-copy 'file-remote-p 'file-modes
5481 'file-name-as-directory 'file-name-directory
5482 'file-name-nondirectory 'file-name-sans-versions
5483 'file-ownership-preserved-p 'file-readable-p
5484 'file-regular-p 'file-symlink-p 'file-truename
5485 'file-writable-p 'find-backup-file-name 'find-file-noselect
5486 'get-file-buffer 'insert-directory 'insert-file-contents
5487 'load 'make-directory 'make-directory-internal
5488 'set-file-modes 'substitute-in-file-name
5489 'unhandled-file-name-directory 'vc-registered
5490 ;; Emacs 22+ only.
5491 'set-file-times
5492 ;; Emacs 24+ only.
5493 'file-selinux-context 'set-file-selinux-context
5494 ;; XEmacs only.
5495 'abbreviate-file-name 'create-file-buffer
5496 'dired-file-modtime 'dired-make-compressed-filename
5497 'dired-recursive-delete-directory 'dired-set-file-modtime
5498 'dired-shell-unhandle-file-name 'dired-uucode-file
5499 'insert-file-contents-literally 'make-temp-name 'recover-file
5500 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5501 (if (file-name-absolute-p (nth 0 args))
5502 (nth 0 args)
5503 (expand-file-name (nth 0 args))))
5504 ;; FILE DIRECTORY resp FILE1 FILE2.
5505 ((member operation
5506 (list 'add-name-to-file 'copy-file 'expand-file-name
5507 'file-name-all-completions 'file-name-completion
5508 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5509 ;; Emacs 23+ only.
5510 'copy-directory
5511 ;; XEmacs only.
5512 'dired-make-relative-symlink
5513 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5514 (save-match-data
5515 (cond
5516 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5517 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5518 (t (buffer-file-name (current-buffer))))))
5519 ;; START END FILE.
5520 ((eq operation 'write-region)
5521 (nth 2 args))
5522 ;; BUFFER.
5523 ((member operation
5524 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5525 ;; Emacs 22+ only.
5526 'make-auto-save-file-name
5527 ;; XEmacs only.
5528 'backup-buffer))
5529 (buffer-file-name
5530 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5531 ;; COMMAND.
5532 ((member operation
5533 (list ;; not in Emacs 23+.
5534 'dired-call-process
5535 ;; Emacs only.
5536 'shell-command
5537 ;; Emacs 22+ only.
5538 'process-file
5539 ;; Emacs 23+ only.
5540 'start-file-process
5541 ;; XEmacs only.
5542 'dired-print-file 'dired-shell-call-process
5543 ;; nowhere yet.
5544 'executable-find 'start-process
5545 'call-process 'call-process-region))
5546 default-directory)
5547 ;; Unknown file primitive.
5548 (t (error "unknown file I/O primitive: %s" operation))))
5549
5550 (defun tramp-find-foreign-file-name-handler (filename)
5551 "Return foreign file name handler if exists."
5552 (when (tramp-tramp-file-p filename)
5553 (let ((v (tramp-dissect-file-name filename t))
5554 (handler tramp-foreign-file-name-handler-alist)
5555 elt res)
5556 ;; When we are not fully sure that filename completion is safe,
5557 ;; we should not return a handler.
5558 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5559 (and (tramp-file-name-host v)
5560 (not (member (tramp-file-name-host v)
5561 (mapcar 'car tramp-methods))))
5562 (not (tramp-completion-mode-p)))
5563 (while handler
5564 (setq elt (car handler)
5565 handler (cdr handler))
5566 (when (funcall (car elt) filename)
5567 (setq handler nil
5568 res (cdr elt))))
5569 res))))
5570
5571 ;; Main function.
5572 ;;;###autoload
5573 (defun tramp-file-name-handler (operation &rest args)
5574 "Invoke Tramp file name handler.
5575 Falls back to normal file name handler if no Tramp file name handler exists."
5576 (if tramp-mode
5577 (save-match-data
5578 (let* ((filename
5579 (tramp-replace-environment-variables
5580 (apply 'tramp-file-name-for-operation operation args)))
5581 (completion (tramp-completion-mode-p))
5582 (foreign (tramp-find-foreign-file-name-handler filename)))
5583 (with-parsed-tramp-file-name filename nil
5584 ;; Call the backend function.
5585 (if foreign
5586 (condition-case err
5587 (apply foreign operation args)
5588
5589 ;; Trace that somebody has interrupted the
5590 ;; operation.
5591 (quit
5592 (let (tramp-message-show-message)
5593 (tramp-message
5594 v 1 "Interrupt received in operation %s"
5595 (append (list operation) args)))
5596 ;; Propagate the quit signal.
5597 (signal (car err) (cdr err)))
5598
5599 ;; When we are in completion mode, some failed
5600 ;; operations shall return at least a default value
5601 ;; in order to give the user a chance to correct the
5602 ;; file name in the minibuffer.
5603 (error
5604 (cond
5605 ((and completion (zerop (length localname))
5606 (memq operation '(file-exists-p file-directory-p)))
5607 t)
5608 ((and completion (zerop (length localname))
5609 (memq operation
5610 '(expand-file-name file-name-as-directory)))
5611 filename)
5612 ;; Propagate the error.
5613 (t (signal (car err) (cdr err))))))
5614
5615 ;; Nothing to do for us.
5616 (tramp-run-real-handler operation args)))))
5617
5618 ;; When `tramp-mode' is not enabled, we don't do anything.
5619 (tramp-run-real-handler operation args)))
5620
5621 ;; In Emacs, there is some concurrency due to timers. If a timer
5622 ;; interrupts Tramp and wishes to use the same connection buffer as
5623 ;; the "main" Emacs, then garbage might occur in the connection
5624 ;; buffer. Therefore, we need to make sure that a timer does not use
5625 ;; the same connection buffer as the "main" Emacs. We implement a
5626 ;; cheap global lock, instead of locking each connection buffer
5627 ;; separately. The global lock is based on two variables,
5628 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5629 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5630 ;; processing of a single file operation, so we need to allow
5631 ;; recursive calls. That's where the `tramp-locker' variable comes in
5632 ;; -- it is let-bound to t during the execution of the current
5633 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5634 ;; then we should just proceed because we have been called
5635 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5636 ;; interrupting the "main" Emacs, and then we signal an error.
5637
5638 (defvar tramp-locked nil
5639 "If non-nil, then Tramp is currently busy.
5640 Together with `tramp-locker', this implements a locking mechanism
5641 preventing reentrant calls of Tramp.")
5642
5643 (defvar tramp-locker nil
5644 "If non-nil, then a caller has locked Tramp.
5645 Together with `tramp-locked', this implements a locking mechanism
5646 preventing reentrant calls of Tramp.")
5647
5648 (defun tramp-sh-file-name-handler (operation &rest args)
5649 "Invoke remote-shell Tramp file name handler.
5650 Fall back to normal file name handler if no Tramp handler exists."
5651 (when (and tramp-locked (not tramp-locker))
5652 (setq tramp-locked nil)
5653 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5654 (let ((tl tramp-locked))
5655 (unwind-protect
5656 (progn
5657 (setq tramp-locked t)
5658 (let ((tramp-locker t))
5659 (save-match-data
5660 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5661 (if fn
5662 (apply (cdr fn) args)
5663 (tramp-run-real-handler operation args))))))
5664 (setq tramp-locked tl))))
5665
5666 (defun tramp-vc-file-name-handler (operation &rest args)
5667 "Invoke special file name handler, which collects files to be handled."
5668 (save-match-data
5669 (let ((filename
5670 (tramp-replace-environment-variables
5671 (apply 'tramp-file-name-for-operation operation args)))
5672 (fn (assoc operation tramp-file-name-handler-alist)))
5673 (with-parsed-tramp-file-name filename nil
5674 (cond
5675 ;; That's what we want: file names, for which checks are
5676 ;; applied. We assume, that VC uses only `file-exists-p' and
5677 ;; `file-readable-p' checks; otherwise we must extend the
5678 ;; list. We do not perform any action, but return nil, in
5679 ;; order to keep `vc-registered' running.
5680 ((and fn (memq operation '(file-exists-p file-readable-p)))
5681 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5682 nil)
5683 ;; Tramp file name handlers like `expand-file-name'. They
5684 ;; must still work.
5685 (fn
5686 (save-match-data (apply (cdr fn) args)))
5687 ;; Default file name handlers, we don't care.
5688 (t (tramp-run-real-handler operation args)))))))
5689
5690 ;;;###autoload
5691 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5692 "Invoke Tramp file name completion handler.
5693 Falls back to normal file name handler if no Tramp file name handler exists."
5694 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5695 ;; would otherwise use backslash.
5696 (let ((directory-sep-char ?/)
5697 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5698 (if (and
5699 ;; When `tramp-mode' is not enabled, we don't do anything.
5700 fn tramp-mode
5701 ;; For other syntaxes than `sep', the regexp matches many common
5702 ;; situations where the user doesn't actually want to use Tramp.
5703 ;; So to avoid autoloading Tramp after typing just "/s", we
5704 ;; disable this part of the completion, unless the user implicitly
5705 ;; indicated his interest in using a fancier completion system.
5706 (or (eq tramp-syntax 'sep)
5707 (featurep 'tramp) ;; If it's loaded, we may as well use it.
5708 ;; `partial-completion-mode' does not exist in XEmacs.
5709 ;; It is obsoleted with Emacs 24.1.
5710 (and (boundp 'partial-completion-mode)
5711 (symbol-value 'partial-completion-mode))
5712 ;; FIXME: These may have been loaded even if the user never
5713 ;; intended to use them.
5714 (featurep 'ido)
5715 (featurep 'icicles)))
5716 (save-match-data (apply (cdr fn) args))
5717 (tramp-completion-run-real-handler operation args)))))
5718
5719 ;;;###autoload
5720 (progn (defun tramp-register-file-name-handlers ()
5721 "Add Tramp file name handlers to `file-name-handler-alist'."
5722 ;; Remove autoloaded handlers from file name handler alist. Useful,
5723 ;; if `tramp-syntax' has been changed.
5724 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5725 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5726 (let ((a1 (rassq
5727 'tramp-completion-file-name-handler file-name-handler-alist)))
5728 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5729 ;; Add the handlers.
5730 (add-to-list 'file-name-handler-alist
5731 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5732 (put 'tramp-file-name-handler 'safe-magic t)
5733 (add-to-list 'file-name-handler-alist
5734 (cons tramp-completion-file-name-regexp
5735 'tramp-completion-file-name-handler))
5736 (put 'tramp-completion-file-name-handler 'safe-magic t)
5737 ;; If jka-compr or epa-file are already loaded, move them to the
5738 ;; front of `file-name-handler-alist'.
5739 (dolist (fnh '(epa-file-handler jka-compr-handler))
5740 (let ((entry (rassoc fnh file-name-handler-alist)))
5741 (when entry
5742 (setq file-name-handler-alist
5743 (cons entry (delete entry file-name-handler-alist))))))))
5744
5745 ;; `tramp-file-name-handler' must be registered before evaluation of
5746 ;; site-start and init files, because there might exist remote files
5747 ;; already, f.e. files kept via recentf-mode.
5748 ;;;###autoload(tramp-register-file-name-handlers)
5749 (tramp-register-file-name-handlers)
5750
5751 ;;;###autoload
5752 (defun tramp-unload-file-name-handlers ()
5753 (setq file-name-handler-alist
5754 (delete (rassoc 'tramp-file-name-handler
5755 file-name-handler-alist)
5756 (delete (rassoc 'tramp-completion-file-name-handler
5757 file-name-handler-alist)
5758 file-name-handler-alist))))
5759
5760 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5761
5762 ;;; File name handler functions for completion mode:
5763
5764 (defvar tramp-completion-mode nil
5765 "If non-nil, external packages signal that they are in file name completion.
5766
5767 This is necessary, because Tramp uses a heuristic depending on last
5768 input event. This fails when external packages use other characters
5769 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5770 should never be set globally, the intention is to let-bind it.")
5771
5772 ;; Necessary because `tramp-file-name-regexp-unified' and
5773 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5774 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5775 ;; to `tramp-file-name-handler'). Otherwise, it takes
5776 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5777 ;; risky, because completing a file might require loading other files,
5778 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5779 ;; variable. On the other hand, those files shouldn't have partial
5780 ;; Tramp file name syntax. Maybe another variable should be introduced
5781 ;; overwriting this check in such cases. Or we change Tramp file name
5782 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5783 (defun tramp-completion-mode-p ()
5784 "Check, whether method / user name / host name completion is active."
5785 (or
5786 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5787 (and (boundp 'non-essential) (symbol-value 'non-essential))
5788 tramp-completion-mode
5789 ;; Emacs.
5790 (equal last-input-event 'tab)
5791 (and (natnump last-input-event)
5792 (or
5793 ;; ?\t has event-modifier 'control.
5794 (equal last-input-event ?\t)
5795 (and (not (event-modifiers last-input-event))
5796 (or (equal last-input-event ?\?)
5797 (equal last-input-event ?\ )))))
5798 ;; XEmacs.
5799 (and (featurep 'xemacs)
5800 ;; `last-input-event' might be nil.
5801 (not (null last-input-event))
5802 ;; `last-input-event' may have no character approximation.
5803 (tramp-compat-funcall 'event-to-character last-input-event)
5804 (or
5805 ;; ?\t has event-modifier 'control.
5806 (equal
5807 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
5808 (and (not (event-modifiers last-input-event))
5809 (or (equal
5810 (tramp-compat-funcall 'event-to-character last-input-event)
5811 ?\?)
5812 (equal
5813 (tramp-compat-funcall 'event-to-character last-input-event)
5814 ?\ )))))))
5815
5816 (defun tramp-connectable-p (filename)
5817 "Check, whether it is possible to connect the remote host w/o side-effects.
5818 This is true, if either the remote host is already connected, or if we are
5819 not in completion mode."
5820 (and (tramp-tramp-file-p filename)
5821 (with-parsed-tramp-file-name filename nil
5822 (or (get-buffer (tramp-buffer-name v))
5823 (not (tramp-completion-mode-p))))))
5824
5825 ;; Method, host name and user name completion.
5826 ;; `tramp-completion-dissect-file-name' returns a list of
5827 ;; tramp-file-name structures. For all of them we return possible completions.
5828 ;;;###autoload
5829 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5830 "Like `file-name-all-completions' for partial Tramp files."
5831
5832 (let* ((fullname (tramp-drop-volume-letter
5833 (expand-file-name filename directory)))
5834 ;; Possible completion structures.
5835 (v (tramp-completion-dissect-file-name fullname))
5836 result result1)
5837
5838 (while v
5839 (let* ((car (car v))
5840 (method (tramp-file-name-method car))
5841 (user (tramp-file-name-user car))
5842 (host (tramp-file-name-host car))
5843 (localname (tramp-file-name-localname car))
5844 (m (tramp-find-method method user host))
5845 (tramp-current-user user) ; see `tramp-parse-passwd'
5846 all-user-hosts)
5847
5848 (unless localname ;; Nothing to complete.
5849
5850 (if (or user host)
5851
5852 ;; Method dependent user / host combinations.
5853 (progn
5854 (mapc
5855 (lambda (x)
5856 (setq all-user-hosts
5857 (append all-user-hosts
5858 (funcall (nth 0 x) (nth 1 x)))))
5859 (tramp-get-completion-function m))
5860
5861 (setq result
5862 (append result
5863 (mapcar
5864 (lambda (x)
5865 (tramp-get-completion-user-host
5866 method user host (nth 0 x) (nth 1 x)))
5867 (delq nil all-user-hosts)))))
5868
5869 ;; Possible methods.
5870 (setq result
5871 (append result (tramp-get-completion-methods m)))))
5872
5873 (setq v (cdr v))))
5874
5875 ;; Unify list, remove nil elements.
5876 (while result
5877 (let ((car (car result)))
5878 (when car
5879 (add-to-list
5880 'result1
5881 (substring car (length (tramp-drop-volume-letter directory)))))
5882 (setq result (cdr result))))
5883
5884 ;; Complete local parts.
5885 (append
5886 result1
5887 (condition-case nil
5888 (apply (if (tramp-connectable-p fullname)
5889 'tramp-completion-run-real-handler
5890 'tramp-run-real-handler)
5891 'file-name-all-completions (list (list filename directory)))
5892 (error nil)))))
5893
5894 ;; Method, host name and user name completion for a file.
5895 ;;;###autoload
5896 (defun tramp-completion-handle-file-name-completion
5897 (filename directory &optional predicate)
5898 "Like `file-name-completion' for Tramp files."
5899 (try-completion
5900 filename
5901 (mapcar 'list (file-name-all-completions filename directory))
5902 (when (and predicate
5903 (tramp-connectable-p (expand-file-name filename directory)))
5904 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5905
5906 ;; I misuse a little bit the tramp-file-name structure in order to handle
5907 ;; completion possibilities for partial methods / user names / host names.
5908 ;; Return value is a list of tramp-file-name structures according to possible
5909 ;; completions. If "localname" is non-nil it means there
5910 ;; shouldn't be a completion anymore.
5911
5912 ;; Expected results:
5913
5914 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5915 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5916 ;; [nil "x" nil nil]
5917 ;; ["x" nil nil nil]
5918
5919 ;; "/x:" "/x:y" "/x:y:"
5920 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5921 ;; "/[x/" "/[x/y"
5922 ;; ["x" nil "" nil] ["x" nil "y" nil]
5923 ;; ["x" "" nil nil] ["x" "y" nil nil]
5924
5925 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5926 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5927 ;; "/[x/y@" "/[x/y@z"
5928 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5929 (defun tramp-completion-dissect-file-name (name)
5930 "Returns a list of `tramp-file-name' structures.
5931 They are collected by `tramp-completion-dissect-file-name1'."
5932
5933 (let* ((result)
5934 (x-nil "\\|\\(\\)")
5935 (tramp-completion-ipv6-regexp
5936 (format
5937 "[^%s]*"
5938 (if (zerop (length tramp-postfix-ipv6-format))
5939 tramp-postfix-host-format
5940 tramp-postfix-ipv6-format)))
5941 ;; "/method" "/[method"
5942 (tramp-completion-file-name-structure1
5943 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5944 1 nil nil nil))
5945 ;; "/user" "/[user"
5946 (tramp-completion-file-name-structure2
5947 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5948 nil 1 nil nil))
5949 ;; "/host" "/[host"
5950 (tramp-completion-file-name-structure3
5951 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5952 nil nil 1 nil))
5953 ;; "/[ipv6" "/[ipv6"
5954 (tramp-completion-file-name-structure4
5955 (list (concat tramp-prefix-regexp
5956 tramp-prefix-ipv6-regexp
5957 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5958 nil nil 1 nil))
5959 ;; "/user@host" "/[user@host"
5960 (tramp-completion-file-name-structure5
5961 (list (concat tramp-prefix-regexp
5962 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5963 "\\(" tramp-host-regexp x-nil "\\)$")
5964 nil 1 2 nil))
5965 ;; "/user@[ipv6" "/[user@ipv6"
5966 (tramp-completion-file-name-structure6
5967 (list (concat tramp-prefix-regexp
5968 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5969 tramp-prefix-ipv6-regexp
5970 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5971 nil 1 2 nil))
5972 ;; "/method:user" "/[method/user" "/method://user"
5973 (tramp-completion-file-name-structure7
5974 (list (concat tramp-prefix-regexp
5975 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5976 "\\(" tramp-user-regexp x-nil "\\)$")
5977 1 2 nil nil))
5978 ;; "/method:host" "/[method/host" "/method://host"
5979 (tramp-completion-file-name-structure8
5980 (list (concat tramp-prefix-regexp
5981 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5982 "\\(" tramp-host-regexp x-nil "\\)$")
5983 1 nil 2 nil))
5984 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5985 (tramp-completion-file-name-structure9
5986 (list (concat tramp-prefix-regexp
5987 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5988 tramp-prefix-ipv6-regexp
5989 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5990 1 nil 2 nil))
5991 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5992 (tramp-completion-file-name-structure10
5993 (list (concat tramp-prefix-regexp
5994 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5995 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5996 "\\(" tramp-host-regexp x-nil "\\)$")
5997 1 2 3 nil))
5998 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5999 (tramp-completion-file-name-structure11
6000 (list (concat tramp-prefix-regexp
6001 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6002 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6003 tramp-prefix-ipv6-regexp
6004 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6005 1 2 3 nil))
6006 ;; "/method: "/method:/"
6007 (tramp-completion-file-name-structure12
6008 (list
6009 (if (equal tramp-syntax 'url)
6010 (concat tramp-prefix-regexp
6011 "\\(" tramp-method-regexp "\\)"
6012 "\\(" (substring tramp-postfix-method-regexp 0 1)
6013 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6014 "\\(" "\\)$")
6015 ;; Should not match if not URL syntax.
6016 (concat tramp-prefix-regexp "/$"))
6017 1 3 nil nil))
6018 ;; "/method: "/method:/"
6019 (tramp-completion-file-name-structure13
6020 (list
6021 (if (equal tramp-syntax 'url)
6022 (concat tramp-prefix-regexp
6023 "\\(" tramp-method-regexp "\\)"
6024 "\\(" (substring tramp-postfix-method-regexp 0 1)
6025 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6026 "\\(" "\\)$")
6027 ;; Should not match if not URL syntax.
6028 (concat tramp-prefix-regexp "/$"))
6029 1 nil 3 nil)))
6030
6031 (mapc (lambda (regexp)
6032 (add-to-list 'result
6033 (tramp-completion-dissect-file-name1 regexp name)))
6034 (list
6035 tramp-completion-file-name-structure1
6036 tramp-completion-file-name-structure2
6037 tramp-completion-file-name-structure3
6038 tramp-completion-file-name-structure4
6039 tramp-completion-file-name-structure5
6040 tramp-completion-file-name-structure6
6041 tramp-completion-file-name-structure7
6042 tramp-completion-file-name-structure8
6043 tramp-completion-file-name-structure9
6044 tramp-completion-file-name-structure10
6045 tramp-completion-file-name-structure11
6046 tramp-completion-file-name-structure12
6047 tramp-completion-file-name-structure13
6048 tramp-file-name-structure))
6049
6050 (delq nil result)))
6051
6052 (defun tramp-completion-dissect-file-name1 (structure name)
6053 "Returns a `tramp-file-name' structure matching STRUCTURE.
6054 The structure consists of remote method, remote user,
6055 remote host and localname (filename on remote host)."
6056
6057 (save-match-data
6058 (when (string-match (nth 0 structure) name)
6059 (let ((method (and (nth 1 structure)
6060 (match-string (nth 1 structure) name)))
6061 (user (and (nth 2 structure)
6062 (match-string (nth 2 structure) name)))
6063 (host (and (nth 3 structure)
6064 (match-string (nth 3 structure) name)))
6065 (localname (and (nth 4 structure)
6066 (match-string (nth 4 structure) name))))
6067 (vector method user host localname)))))
6068
6069 ;; This function returns all possible method completions, adding the
6070 ;; trailing method delimeter.
6071 (defun tramp-get-completion-methods (partial-method)
6072 "Returns all method completions for PARTIAL-METHOD."
6073 (mapcar
6074 (lambda (method)
6075 (and method
6076 (string-match (concat "^" (regexp-quote partial-method)) method)
6077 (tramp-completion-make-tramp-file-name method nil nil nil)))
6078 (mapcar 'car tramp-methods)))
6079
6080 ;; Compares partial user and host names with possible completions.
6081 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
6082 "Returns the most expanded string for user and host name completion.
6083 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
6084 (cond
6085
6086 ((and partial-user partial-host)
6087 (if (and host
6088 (string-match (concat "^" (regexp-quote partial-host)) host)
6089 (string-equal partial-user (or user partial-user)))
6090 (setq user partial-user)
6091 (setq user nil
6092 host nil)))
6093
6094 (partial-user
6095 (setq host nil)
6096 (unless
6097 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
6098 (setq user nil)))
6099
6100 (partial-host
6101 (setq user nil)
6102 (unless
6103 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
6104 (setq host nil)))
6105
6106 (t (setq user nil
6107 host nil)))
6108
6109 (unless (zerop (+ (length user) (length host)))
6110 (tramp-completion-make-tramp-file-name method user host nil)))
6111
6112 (defun tramp-parse-rhosts (filename)
6113 "Return a list of (user host) tuples allowed to access.
6114 Either user or host may be nil."
6115 ;; On Windows, there are problems in completion when
6116 ;; `default-directory' is remote.
6117 (let ((default-directory (tramp-compat-temporary-file-directory))
6118 res)
6119 (when (file-readable-p filename)
6120 (with-temp-buffer
6121 (insert-file-contents filename)
6122 (goto-char (point-min))
6123 (while (not (eobp))
6124 (push (tramp-parse-rhosts-group) res))))
6125 res))
6126
6127 (defun tramp-parse-rhosts-group ()
6128 "Return a (user host) tuple allowed to access.
6129 Either user or host may be nil."
6130 (let ((result)
6131 (regexp
6132 (concat
6133 "^\\(" tramp-host-regexp "\\)"
6134 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6135 (narrow-to-region (point) (tramp-compat-line-end-position))
6136 (when (re-search-forward regexp nil t)
6137 (setq result (append (list (match-string 3) (match-string 1)))))
6138 (widen)
6139 (forward-line 1)
6140 result))
6141
6142 (defun tramp-parse-shosts (filename)
6143 "Return a list of (user host) tuples allowed to access.
6144 User is always nil."
6145 ;; On Windows, there are problems in completion when
6146 ;; `default-directory' is remote.
6147 (let ((default-directory (tramp-compat-temporary-file-directory))
6148 res)
6149 (when (file-readable-p filename)
6150 (with-temp-buffer
6151 (insert-file-contents filename)
6152 (goto-char (point-min))
6153 (while (not (eobp))
6154 (push (tramp-parse-shosts-group) res))))
6155 res))
6156
6157 (defun tramp-parse-shosts-group ()
6158 "Return a (user host) tuple allowed to access.
6159 User is always nil."
6160 (let ((result)
6161 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
6162 (narrow-to-region (point) (tramp-compat-line-end-position))
6163 (when (re-search-forward regexp nil t)
6164 (setq result (list nil (match-string 1))))
6165 (widen)
6166 (or
6167 (> (skip-chars-forward ",") 0)
6168 (forward-line 1))
6169 result))
6170
6171 (defun tramp-parse-sconfig (filename)
6172 "Return a list of (user host) tuples allowed to access.
6173 User is always nil."
6174 ;; On Windows, there are problems in completion when
6175 ;; `default-directory' is remote.
6176 (let ((default-directory (tramp-compat-temporary-file-directory))
6177 res)
6178 (when (file-readable-p filename)
6179 (with-temp-buffer
6180 (insert-file-contents filename)
6181 (goto-char (point-min))
6182 (while (not (eobp))
6183 (push (tramp-parse-sconfig-group) res))))
6184 res))
6185
6186 (defun tramp-parse-sconfig-group ()
6187 "Return a (user host) tuple allowed to access.
6188 User is always nil."
6189 (let ((result)
6190 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
6191 (narrow-to-region (point) (tramp-compat-line-end-position))
6192 (when (re-search-forward regexp nil t)
6193 (setq result (list nil (match-string 1))))
6194 (widen)
6195 (or
6196 (> (skip-chars-forward ",") 0)
6197 (forward-line 1))
6198 result))
6199
6200 (defun tramp-parse-shostkeys (dirname)
6201 "Return a list of (user host) tuples allowed to access.
6202 User is always nil."
6203 ;; On Windows, there are problems in completion when
6204 ;; `default-directory' is remote.
6205 (let* ((default-directory (tramp-compat-temporary-file-directory))
6206 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6207 (files (when (file-directory-p dirname) (directory-files dirname)))
6208 result)
6209 (while files
6210 (when (string-match regexp (car files))
6211 (push (list nil (match-string 1 (car files))) result))
6212 (setq files (cdr files)))
6213 result))
6214
6215 (defun tramp-parse-sknownhosts (dirname)
6216 "Return a list of (user host) tuples allowed to access.
6217 User is always nil."
6218 ;; On Windows, there are problems in completion when
6219 ;; `default-directory' is remote.
6220 (let* ((default-directory (tramp-compat-temporary-file-directory))
6221 (regexp (concat "^\\(" tramp-host-regexp
6222 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6223 (files (when (file-directory-p dirname) (directory-files dirname)))
6224 result)
6225 (while files
6226 (when (string-match regexp (car files))
6227 (push (list nil (match-string 1 (car files))) result))
6228 (setq files (cdr files)))
6229 result))
6230
6231 (defun tramp-parse-hosts (filename)
6232 "Return a list of (user host) tuples allowed to access.
6233 User is always nil."
6234 ;; On Windows, there are problems in completion when
6235 ;; `default-directory' is remote.
6236 (let ((default-directory (tramp-compat-temporary-file-directory))
6237 res)
6238 (when (file-readable-p filename)
6239 (with-temp-buffer
6240 (insert-file-contents filename)
6241 (goto-char (point-min))
6242 (while (not (eobp))
6243 (push (tramp-parse-hosts-group) res))))
6244 res))
6245
6246 (defun tramp-parse-hosts-group ()
6247 "Return a (user host) tuple allowed to access.
6248 User is always nil."
6249 (let ((result)
6250 (regexp
6251 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6252 (narrow-to-region (point) (tramp-compat-line-end-position))
6253 (when (re-search-forward regexp nil t)
6254 (setq result (list nil (match-string 1))))
6255 (widen)
6256 (or
6257 (> (skip-chars-forward " \t") 0)
6258 (forward-line 1))
6259 result))
6260
6261 ;; For su-alike methods it would be desirable to return "root@localhost"
6262 ;; as default. Unfortunately, we have no information whether any user name
6263 ;; has been typed already. So we use `tramp-current-user' as indication,
6264 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6265 (defun tramp-parse-passwd (filename)
6266 "Return a list of (user host) tuples allowed to access.
6267 Host is always \"localhost\"."
6268 ;; On Windows, there are problems in completion when
6269 ;; `default-directory' is remote.
6270 (let ((default-directory (tramp-compat-temporary-file-directory))
6271 res)
6272 (if (zerop (length tramp-current-user))
6273 '(("root" nil))
6274 (when (file-readable-p filename)
6275 (with-temp-buffer
6276 (insert-file-contents filename)
6277 (goto-char (point-min))
6278 (while (not (eobp))
6279 (push (tramp-parse-passwd-group) res))))
6280 res)))
6281
6282 (defun tramp-parse-passwd-group ()
6283 "Return a (user host) tuple allowed to access.
6284 Host is always \"localhost\"."
6285 (let ((result)
6286 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6287 (narrow-to-region (point) (tramp-compat-line-end-position))
6288 (when (re-search-forward regexp nil t)
6289 (setq result (list (match-string 1) "localhost")))
6290 (widen)
6291 (forward-line 1)
6292 result))
6293
6294 (defun tramp-parse-netrc (filename)
6295 "Return a list of (user host) tuples allowed to access.
6296 User may be nil."
6297 ;; On Windows, there are problems in completion when
6298 ;; `default-directory' is remote.
6299 (let ((default-directory (tramp-compat-temporary-file-directory))
6300 res)
6301 (when (file-readable-p filename)
6302 (with-temp-buffer
6303 (insert-file-contents filename)
6304 (goto-char (point-min))
6305 (while (not (eobp))
6306 (push (tramp-parse-netrc-group) res))))
6307 res))
6308
6309 (defun tramp-parse-netrc-group ()
6310 "Return a (user host) tuple allowed to access.
6311 User may be nil."
6312 (let ((result)
6313 (regexp
6314 (concat
6315 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6316 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6317 (narrow-to-region (point) (tramp-compat-line-end-position))
6318 (when (re-search-forward regexp nil t)
6319 (setq result (list (match-string 3) (match-string 1))))
6320 (widen)
6321 (forward-line 1)
6322 result))
6323
6324 (defun tramp-parse-putty (registry)
6325 "Return a list of (user host) tuples allowed to access.
6326 User is always nil."
6327 ;; On Windows, there are problems in completion when
6328 ;; `default-directory' is remote.
6329 (let ((default-directory (tramp-compat-temporary-file-directory))
6330 res)
6331 (with-temp-buffer
6332 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6333 (goto-char (point-min))
6334 (while (not (eobp))
6335 (push (tramp-parse-putty-group registry) res))))
6336 res))
6337
6338 (defun tramp-parse-putty-group (registry)
6339 "Return a (user host) tuple allowed to access.
6340 User is always nil."
6341 (let ((result)
6342 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6343 (narrow-to-region (point) (tramp-compat-line-end-position))
6344 (when (re-search-forward regexp nil t)
6345 (setq result (list nil (match-string 1))))
6346 (widen)
6347 (forward-line 1)
6348 result))
6349
6350 ;;; Internal Functions:
6351
6352 (defun tramp-maybe-send-script (vec script name)
6353 "Define in remote shell function NAME implemented as SCRIPT.
6354 Only send the definition if it has not already been done."
6355 (let* ((p (tramp-get-connection-process vec))
6356 (scripts (tramp-get-connection-property p "scripts" nil)))
6357 (unless (member name scripts)
6358 (with-progress-reporter vec 5 (format "Sending script `%s'" name)
6359 ;; The script could contain a call of Perl. This is masked with `%s'.
6360 (tramp-send-command-and-check
6361 vec
6362 (format "%s () {\n%s\n}" name
6363 (format script (tramp-get-remote-perl vec))))
6364 (tramp-set-connection-property p "scripts" (cons name scripts))))))
6365
6366 (defun tramp-set-auto-save ()
6367 (when (and ;; ange-ftp has its own auto-save mechanism
6368 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6369 'tramp-sh-file-name-handler)
6370 auto-save-default)
6371 (auto-save-mode 1)))
6372 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6373 (add-hook 'tramp-unload-hook
6374 (lambda ()
6375 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6376
6377 (defun tramp-run-test (switch filename)
6378 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6379 Returns the exit code of the `test' program."
6380 (with-parsed-tramp-file-name filename nil
6381 (tramp-send-command-and-check
6382 v
6383 (format
6384 "%s %s %s"
6385 (tramp-get-test-command v)
6386 switch
6387 (tramp-shell-quote-argument localname)))))
6388
6389 (defun tramp-run-test2 (format-string file1 file2)
6390 "Run `test'-like program on the remote system, given FILE1, FILE2.
6391 FORMAT-STRING contains the program name, switches, and place holders.
6392 Returns the exit code of the `test' program. Barfs if the methods,
6393 hosts, or files, disagree."
6394 (unless (tramp-equal-remote file1 file2)
6395 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6396 (tramp-error
6397 v 'file-error
6398 "tramp-run-test2 only implemented for same method, user, host")))
6399 (with-parsed-tramp-file-name file1 v1
6400 (with-parsed-tramp-file-name file1 v2
6401 (tramp-send-command-and-check
6402 v1
6403 (format format-string
6404 (tramp-shell-quote-argument v1-localname)
6405 (tramp-shell-quote-argument v2-localname))))))
6406
6407 (defun tramp-buffer-name (vec)
6408 "A name for the connection buffer VEC."
6409 ;; We must use `tramp-file-name-real-host', because for gateway
6410 ;; methods the default port will be expanded later on, which would
6411 ;; tamper the name.
6412 (let ((method (tramp-file-name-method vec))
6413 (user (tramp-file-name-user vec))
6414 (host (tramp-file-name-real-host vec)))
6415 (if (not (zerop (length user)))
6416 (format "*tramp/%s %s@%s*" method user host)
6417 (format "*tramp/%s %s*" method host))))
6418
6419 (defun tramp-delete-temp-file-function ()
6420 "Remove temporary files related to current buffer."
6421 (when (stringp tramp-temp-buffer-file-name)
6422 (condition-case nil
6423 (delete-file tramp-temp-buffer-file-name)
6424 (error nil))))
6425
6426 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6427 (add-hook 'tramp-cache-unload-hook
6428 (lambda ()
6429 (remove-hook 'kill-buffer-hook
6430 'tramp-delete-temp-file-function)))
6431
6432 (defun tramp-get-buffer (vec)
6433 "Get the connection buffer to be used for VEC."
6434 (or (get-buffer (tramp-buffer-name vec))
6435 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6436 (setq buffer-undo-list t)
6437 (setq default-directory
6438 (tramp-make-tramp-file-name
6439 (tramp-file-name-method vec)
6440 (tramp-file-name-user vec)
6441 (tramp-file-name-host vec)
6442 "/"))
6443 (current-buffer))))
6444
6445 (defun tramp-get-connection-buffer (vec)
6446 "Get the connection buffer to be used for VEC.
6447 In case a second asynchronous communication has been started, it is different
6448 from `tramp-get-buffer'."
6449 (or (tramp-get-connection-property vec "process-buffer" nil)
6450 (tramp-get-buffer vec)))
6451
6452 (defun tramp-get-connection-process (vec)
6453 "Get the connection process to be used for VEC.
6454 In case a second asynchronous communication has been started, it is different
6455 from the default one."
6456 (get-process
6457 (or (tramp-get-connection-property vec "process-name" nil)
6458 (tramp-buffer-name vec))))
6459
6460 (defun tramp-debug-buffer-name (vec)
6461 "A name for the debug buffer for VEC."
6462 ;; We must use `tramp-file-name-real-host', because for gateway
6463 ;; methods the default port will be expanded later on, which would
6464 ;; tamper the name.
6465 (let ((method (tramp-file-name-method vec))
6466 (user (tramp-file-name-user vec))
6467 (host (tramp-file-name-real-host vec)))
6468 (if (not (zerop (length user)))
6469 (format "*debug tramp/%s %s@%s*" method user host)
6470 (format "*debug tramp/%s %s*" method host))))
6471
6472 (defconst tramp-debug-outline-regexp
6473 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6474
6475 (defun tramp-get-debug-buffer (vec)
6476 "Get the debug buffer for VEC."
6477 (with-current-buffer
6478 (get-buffer-create (tramp-debug-buffer-name vec))
6479 (when (bobp)
6480 (setq buffer-undo-list t)
6481 ;; Activate `outline-mode'. This runs `text-mode-hook' and
6482 ;; `outline-mode-hook'. We must prevent that local processes
6483 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6484 ;; Furthermore, `outline-regexp' must have the correct value
6485 ;; already, because it is used by `font-lock-compile-keywords'.
6486 (let ((default-directory (tramp-compat-temporary-file-directory))
6487 (outline-regexp tramp-debug-outline-regexp))
6488 (outline-mode))
6489 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
6490 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6491 (current-buffer)))
6492
6493 (defun tramp-outline-level ()
6494 "Return the depth to which a statement is nested in the outline.
6495 Point must be at the beginning of a header line.
6496
6497 The outline level is equal to the verbosity of the Tramp message."
6498 (1+ (string-to-number (match-string 1))))
6499
6500 (defun tramp-find-executable
6501 (vec progname dirlist &optional ignore-tilde ignore-path)
6502 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6503 First arg VEC specifies the connection, PROGNAME is the program
6504 to search for, and DIRLIST gives the list of directories to
6505 search. If IGNORE-TILDE is non-nil, directory names starting
6506 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6507 only in DIRLIST.
6508
6509 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6510
6511 This function expects to be in the right *tramp* buffer."
6512 (with-current-buffer (tramp-get-connection-buffer vec)
6513 (let (result)
6514 ;; Check whether the executable is in $PATH. "which(1)" does not
6515 ;; report always a correct error code; therefore we check the
6516 ;; number of words it returns.
6517 (unless ignore-path
6518 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6519 (goto-char (point-min))
6520 (if (looking-at "^\\s-*1$")
6521 (setq result (concat "\\" progname))))
6522 (unless result
6523 (when ignore-tilde
6524 ;; Remove all ~/foo directories from dirlist. In XEmacs,
6525 ;; `remove' is in CL, and we want to avoid CL dependencies.
6526 (let (newdl d)
6527 (while dirlist
6528 (setq d (car dirlist))
6529 (setq dirlist (cdr dirlist))
6530 (unless (char-equal ?~ (aref d 0))
6531 (setq newdl (cons d newdl))))
6532 (setq dirlist (nreverse newdl))))
6533 (tramp-send-command
6534 vec
6535 (format (concat "while read d; "
6536 "do if test -x $d/%s -a -f $d/%s; "
6537 "then echo tramp_executable $d/%s; "
6538 "break; fi; done <<'EOF'\n"
6539 "%s\nEOF")
6540 progname progname progname (mapconcat 'identity dirlist "\n")))
6541 (goto-char (point-max))
6542 (when (search-backward "tramp_executable " nil t)
6543 (skip-chars-forward "^ ")
6544 (skip-chars-forward " ")
6545 (setq result (buffer-substring
6546 (point) (tramp-compat-line-end-position)))))
6547 result)))
6548
6549 (defun tramp-set-remote-path (vec)
6550 "Sets the remote environment PATH to existing directories.
6551 I.e., for each directory in `tramp-remote-path', it is tested
6552 whether it exists and if so, it is added to the environment
6553 variable PATH."
6554 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6555 (tramp-send-command
6556 vec (format "PATH=%s; export PATH"
6557 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6558
6559 ;; ------------------------------------------------------------
6560 ;; -- Communication with external shell --
6561 ;; ------------------------------------------------------------
6562
6563 (defun tramp-find-file-exists-command (vec)
6564 "Find a command on the remote host for checking if a file exists.
6565 Here, we are looking for a command which has zero exit status if the
6566 file exists and nonzero exit status otherwise."
6567 (let ((existing "/")
6568 (nonexisting
6569 (tramp-shell-quote-argument "/ this file does not exist "))
6570 result)
6571 ;; The algorithm is as follows: we try a list of several commands.
6572 ;; For each command, we first run `$cmd /' -- this should return
6573 ;; true, as the root directory always exists. And then we run
6574 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6575 ;; does not exist. This should return false. We use the first
6576 ;; command we find that seems to work.
6577 ;; The list of commands to try is as follows:
6578 ;; `ls -d' This works on most systems, but NetBSD 1.4
6579 ;; has a bug: `ls' always returns zero exit
6580 ;; status, even for files which don't exist.
6581 ;; `test -e' Some Bourne shells have a `test' builtin
6582 ;; which does not know the `-e' option.
6583 ;; `/bin/test -e' For those, the `test' binary on disk normally
6584 ;; provides the option. Alas, the binary
6585 ;; is sometimes `/bin/test' and sometimes it's
6586 ;; `/usr/bin/test'.
6587 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6588 (unless (or
6589 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6590 (zerop (tramp-send-command-and-check
6591 vec (format "%s %s" result existing)))
6592 (not (zerop (tramp-send-command-and-check
6593 vec (format "%s %s" result nonexisting)))))
6594 (and (setq result "/bin/test -e")
6595 (zerop (tramp-send-command-and-check
6596 vec (format "%s %s" result existing)))
6597 (not (zerop (tramp-send-command-and-check
6598 vec (format "%s %s" result nonexisting)))))
6599 (and (setq result "/usr/bin/test -e")
6600 (zerop (tramp-send-command-and-check
6601 vec (format "%s %s" result existing)))
6602 (not (zerop (tramp-send-command-and-check
6603 vec (format "%s %s" result nonexisting)))))
6604 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6605 (zerop (tramp-send-command-and-check
6606 vec (format "%s %s" result existing)))
6607 (not (zerop (tramp-send-command-and-check
6608 vec (format "%s %s" result nonexisting))))))
6609 (tramp-error
6610 vec 'file-error "Couldn't find command to check if file exists"))
6611 result))
6612
6613 (defun tramp-open-shell (vec shell)
6614 "Opens shell SHELL."
6615 (with-progress-reporter vec 5 (format "Opening remote shell `%s'" shell)
6616 ;; Find arguments for this shell.
6617 (let ((tramp-end-of-output tramp-initial-end-of-output)
6618 (alist tramp-sh-extra-args)
6619 item extra-args)
6620 (while (and alist (null extra-args))
6621 (setq item (pop alist))
6622 (when (string-match (car item) shell)
6623 (setq extra-args (cdr item))))
6624 (when extra-args (setq shell (concat shell " " extra-args)))
6625 (tramp-send-command
6626 vec (format "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6627 (shell-quote-argument tramp-end-of-output) shell)
6628 t))
6629 ;; Setting prompts.
6630 (tramp-send-command
6631 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6632 (tramp-send-command vec "PS2=''" t)
6633 (tramp-send-command vec "PS3=''" t)
6634 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6635 ;; Dump tty in the traces.
6636 (when (>= tramp-verbose 9)
6637 (tramp-send-command vec "tty" t))))
6638
6639 (defun tramp-find-shell (vec)
6640 "Opens a shell on the remote host which groks tilde expansion."
6641 (unless (tramp-get-connection-property vec "remote-shell" nil)
6642 (let (shell)
6643 (with-current-buffer (tramp-get-buffer vec)
6644 (tramp-send-command vec "echo ~root" t)
6645 (cond
6646 ((or (string-match "^~root$" (buffer-string))
6647 ;; The default shell (ksh93) of OpenSolaris is buggy.
6648 (string-equal (tramp-get-connection-property vec "uname" "")
6649 "SunOS 5.11"))
6650 (setq shell
6651 (or (tramp-find-executable
6652 vec "bash" (tramp-get-remote-path vec) t t)
6653 (tramp-find-executable
6654 vec "ksh" (tramp-get-remote-path vec) t t)))
6655 (unless shell
6656 (tramp-error
6657 vec 'file-error
6658 "Couldn't find a shell which groks tilde expansion"))
6659 (tramp-message
6660 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
6661 (tramp-open-shell vec shell))
6662
6663 (t (tramp-message
6664 vec 5 "Remote `%s' groks tilde expansion, good"
6665 (tramp-set-connection-property
6666 vec "remote-shell"
6667 (tramp-get-method-parameter
6668 (tramp-file-name-method vec) 'tramp-remote-sh)))))))))
6669
6670 ;; ------------------------------------------------------------
6671 ;; -- Functions for establishing connection --
6672 ;; ------------------------------------------------------------
6673
6674 ;; The following functions are actions to be taken when seeing certain
6675 ;; prompts from the remote host. See the variable
6676 ;; `tramp-actions-before-shell' for usage of these functions.
6677
6678 (defun tramp-action-login (proc vec)
6679 "Send the login name."
6680 (when (not (stringp tramp-current-user))
6681 (save-window-excursion
6682 (let ((enable-recursive-minibuffers t))
6683 (pop-to-buffer (tramp-get-connection-buffer vec))
6684 (setq tramp-current-user (read-string (match-string 0))))))
6685 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6686 (with-current-buffer (tramp-get-connection-buffer vec)
6687 (tramp-message vec 6 "\n%s" (buffer-string)))
6688 (tramp-send-string vec tramp-current-user))
6689
6690 (defun tramp-action-password (proc vec)
6691 "Query the user for a password."
6692 (with-current-buffer (process-buffer proc)
6693 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6694 (tramp-message vec 3 "Sending %s" (match-string 1)))
6695 (tramp-enter-password proc))
6696
6697 (defun tramp-action-succeed (proc vec)
6698 "Signal success in finding shell prompt."
6699 (throw 'tramp-action 'ok))
6700
6701 (defun tramp-action-permission-denied (proc vec)
6702 "Signal permission denied."
6703 (kill-process proc)
6704 (throw 'tramp-action 'permission-denied))
6705
6706 (defun tramp-action-yesno (proc vec)
6707 "Ask the user for confirmation using `yes-or-no-p'.
6708 Send \"yes\" to remote process on confirmation, abort otherwise.
6709 See also `tramp-action-yn'."
6710 (save-window-excursion
6711 (let ((enable-recursive-minibuffers t))
6712 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6713 (unless (yes-or-no-p (match-string 0))
6714 (kill-process proc)
6715 (throw 'tramp-action 'permission-denied))
6716 (with-current-buffer (tramp-get-connection-buffer vec)
6717 (tramp-message vec 6 "\n%s" (buffer-string)))
6718 (tramp-send-string vec "yes"))))
6719
6720 (defun tramp-action-yn (proc vec)
6721 "Ask the user for confirmation using `y-or-n-p'.
6722 Send \"y\" to remote process on confirmation, abort otherwise.
6723 See also `tramp-action-yesno'."
6724 (save-window-excursion
6725 (let ((enable-recursive-minibuffers t))
6726 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6727 (unless (y-or-n-p (match-string 0))
6728 (kill-process proc)
6729 (throw 'tramp-action 'permission-denied))
6730 (with-current-buffer (tramp-get-connection-buffer vec)
6731 (tramp-message vec 6 "\n%s" (buffer-string)))
6732 (tramp-send-string vec "y"))))
6733
6734 (defun tramp-action-terminal (proc vec)
6735 "Tell the remote host which terminal type to use.
6736 The terminal type can be configured with `tramp-terminal-type'."
6737 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6738 (with-current-buffer (tramp-get-connection-buffer vec)
6739 (tramp-message vec 6 "\n%s" (buffer-string)))
6740 (tramp-send-string vec tramp-terminal-type))
6741
6742 (defun tramp-action-process-alive (proc vec)
6743 "Check, whether a process has finished."
6744 (unless (memq (process-status proc) '(run open))
6745 (throw 'tramp-action 'process-died)))
6746
6747 (defun tramp-action-out-of-band (proc vec)
6748 "Check, whether an out-of-band copy has finished."
6749 (cond ((and (memq (process-status proc) '(stop exit))
6750 (zerop (process-exit-status proc)))
6751 (tramp-message vec 3 "Process has finished.")
6752 (throw 'tramp-action 'ok))
6753 ((or (and (memq (process-status proc) '(stop exit))
6754 (not (zerop (process-exit-status proc))))
6755 (memq (process-status proc) '(signal)))
6756 ;; `scp' could have copied correctly, but set modes could have failed.
6757 ;; This can be ignored.
6758 (with-current-buffer (process-buffer proc)
6759 (goto-char (point-min))
6760 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6761 (progn
6762 (tramp-message vec 5 "'set mode' error ignored.")
6763 (tramp-message vec 3 "Process has finished.")
6764 (throw 'tramp-action 'ok))
6765 (tramp-message vec 3 "Process has died.")
6766 (throw 'tramp-action 'process-died))))
6767 (t nil)))
6768
6769 ;; Functions for processing the actions.
6770
6771 (defun tramp-process-one-action (proc vec actions)
6772 "Wait for output from the shell and perform one action."
6773 (let (found todo item pattern action)
6774 (while (not found)
6775 ;; Reread output once all actions have been performed.
6776 ;; Obviously, the output was not complete.
6777 (tramp-accept-process-output proc 1)
6778 (setq todo actions)
6779 (while todo
6780 (setq item (pop todo))
6781 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6782 (setq action (nth 1 item))
6783 (tramp-message
6784 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6785 (when (tramp-check-for-regexp proc pattern)
6786 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6787 (setq found (funcall action proc vec)))))
6788 found))
6789
6790 (defun tramp-process-actions (proc vec actions &optional timeout)
6791 "Perform actions until success or TIMEOUT."
6792 ;; Preserve message for `progress-reporter'.
6793 (with-temp-message ""
6794 ;; Enable auth-source and password-cache.
6795 (tramp-set-connection-property vec "first-password-request" t)
6796 (let (exit)
6797 (while (not exit)
6798 (tramp-message proc 3 "Waiting for prompts from remote shell")
6799 (setq exit
6800 (catch 'tramp-action
6801 (if timeout
6802 (with-timeout (timeout)
6803 (tramp-process-one-action proc vec actions))
6804 (tramp-process-one-action proc vec actions)))))
6805 (with-current-buffer (tramp-get-connection-buffer vec)
6806 (tramp-message vec 6 "\n%s" (buffer-string)))
6807 (unless (eq exit 'ok)
6808 (tramp-clear-passwd vec)
6809 (tramp-error-with-buffer
6810 nil vec 'file-error
6811 (cond
6812 ((eq exit 'permission-denied) "Permission denied")
6813 ((eq exit 'process-died) "Process died")
6814 (t "Login failed")))))))
6815
6816 ;; Utility functions.
6817
6818 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6819 "Like `accept-process-output' for Tramp processes.
6820 This is needed in order to hide `last-coding-system-used', which is set
6821 for process communication also."
6822 (with-current-buffer (process-buffer proc)
6823 (tramp-message proc 10 "%s %s" proc (process-status proc))
6824 (let (buffer-read-only last-coding-system-used)
6825 ;; Under Windows XP, accept-process-output doesn't return
6826 ;; sometimes. So we add an additional timeout.
6827 (with-timeout ((or timeout 1))
6828 (accept-process-output proc timeout timeout-msecs)))
6829 (tramp-message proc 10 "\n%s" (buffer-string))))
6830
6831 (defun tramp-check-for-regexp (proc regexp)
6832 "Check, whether REGEXP is contained in process buffer of PROC.
6833 Erase echoed commands if exists."
6834 (with-current-buffer (process-buffer proc)
6835 (goto-char (point-min))
6836
6837 ;; Check whether we need to remove echo output.
6838 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6839 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6840 (let ((begin (match-beginning 0)))
6841 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6842 ;; Discard echo from remote output.
6843 (tramp-set-connection-property proc "check-remote-echo" nil)
6844 (tramp-message proc 5 "echo-mark found")
6845 (forward-line 1)
6846 (delete-region begin (point))
6847 (goto-char (point-min)))))
6848
6849 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6850 ;; Sometimes, the echo string is suppressed on the remote side.
6851 (not (string-equal
6852 (tramp-compat-funcall
6853 'substring-no-properties tramp-echo-mark-marker
6854 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6855 (tramp-compat-funcall
6856 'buffer-substring-no-properties
6857 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6858 ;; No echo to be handled, now we can look for the regexp.
6859 (goto-char (point-min))
6860 (re-search-forward regexp nil t))))
6861
6862 (defun tramp-wait-for-regexp (proc timeout regexp)
6863 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6864 Expects the output of PROC to be sent to the current buffer. Returns
6865 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6866 nil."
6867 (with-current-buffer (process-buffer proc)
6868 (let ((found (tramp-check-for-regexp proc regexp))
6869 (start-time (current-time)))
6870 (cond (timeout
6871 ;; Work around a bug in XEmacs 21, where the timeout
6872 ;; expires faster than it should. This degenerates
6873 ;; to polling for buggy XEmacsen, but oh, well.
6874 (while (and (not found)
6875 (< (tramp-time-diff (current-time) start-time)
6876 timeout))
6877 (with-timeout (timeout)
6878 (while (not found)
6879 (tramp-accept-process-output proc 1)
6880 (unless (memq (process-status proc) '(run open))
6881 (tramp-error-with-buffer
6882 nil proc 'file-error "Process has died"))
6883 (setq found (tramp-check-for-regexp proc regexp))))))
6884 (t
6885 (while (not found)
6886 (tramp-accept-process-output proc 1)
6887 (unless (memq (process-status proc) '(run open))
6888 (tramp-error-with-buffer
6889 nil proc 'file-error "Process has died"))
6890 (setq found (tramp-check-for-regexp proc regexp)))))
6891 (tramp-message proc 6 "\n%s" (buffer-string))
6892 (when (not found)
6893 (if timeout
6894 (tramp-error
6895 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6896 regexp timeout)
6897 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6898 found)))
6899
6900 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6901 "Wait for shell prompt and barf if none appears.
6902 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6903 seconds. If not, it produces an error message with the given ERROR-ARGS."
6904 (unless
6905 (tramp-wait-for-regexp
6906 proc timeout
6907 (format
6908 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6909 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6910
6911 ;; We don't call `tramp-send-string' in order to hide the password
6912 ;; from the debug buffer, and because end-of-line handling of the
6913 ;; string.
6914 (defun tramp-enter-password (proc)
6915 "Prompt for a password and send it to the remote end."
6916 (process-send-string
6917 proc (concat (tramp-read-passwd proc)
6918 (or (tramp-get-method-parameter
6919 tramp-current-method
6920 'tramp-password-end-of-line)
6921 tramp-default-password-end-of-line))))
6922
6923 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6924 "Set up an interactive shell.
6925 Mainly sets the prompt and the echo correctly. PROC is the shell
6926 process to set up. VEC specifies the connection."
6927 (let ((tramp-end-of-output tramp-initial-end-of-output))
6928 ;; It is useful to set the prompt in the following command because
6929 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6930 ;; about and thus /bin/sh will display a strange prompt. For
6931 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6932 ;; display the current working directory but /bin/sh will display
6933 ;; a dollar sign. The following command line sets $PS1 to a sane
6934 ;; value, and works under Bourne-ish shells as well as csh-like
6935 ;; shells. Daniel Pittman reports that the unusual positioning of
6936 ;; the single quotes makes it work under `rc', too. We also unset
6937 ;; the variable $ENV because that is read by some sh
6938 ;; implementations (eg, bash when called as sh) on startup; this
6939 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6940 ;; is another way to set the prompt in /bin/bash, it must be
6941 ;; discarded as well.
6942 (tramp-open-shell
6943 vec
6944 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-remote-sh))
6945
6946 ;; Disable echo.
6947 (tramp-message vec 5 "Setting up remote shell environment")
6948 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6949 ;; Check whether the echo has really been disabled. Some
6950 ;; implementations, like busybox of embedded GNU/Linux, don't
6951 ;; support disabling.
6952 (tramp-send-command vec "echo foo" t)
6953 (with-current-buffer (process-buffer proc)
6954 (goto-char (point-min))
6955 (when (looking-at "echo foo")
6956 (tramp-set-connection-property proc "remote-echo" t)
6957 (tramp-message vec 5 "Remote echo still on. Ok.")
6958 ;; Make sure backspaces and their echo are enabled and no line
6959 ;; width magic interferes with them.
6960 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6961
6962 (tramp-message vec 5 "Setting shell prompt")
6963 (tramp-send-command
6964 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6965 (tramp-send-command vec "PS2=''" t)
6966 (tramp-send-command vec "PS3=''" t)
6967 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6968
6969 ;; Try to set up the coding system correctly.
6970 ;; CCC this can't be the right way to do it. Hm.
6971 (tramp-message vec 5 "Determining coding system")
6972 (tramp-send-command vec "echo foo ; echo bar" t)
6973 (with-current-buffer (process-buffer proc)
6974 (goto-char (point-min))
6975 (if (featurep 'mule)
6976 ;; Use MULE to select the right EOL convention for communicating
6977 ;; with the process.
6978 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
6979 (cons 'undecided 'undecided)))
6980 cs-decode cs-encode)
6981 (when (symbolp cs) (setq cs (cons cs cs)))
6982 (setq cs-decode (car cs))
6983 (setq cs-encode (cdr cs))
6984 (unless cs-decode (setq cs-decode 'undecided))
6985 (unless cs-encode (setq cs-encode 'undecided))
6986 (setq cs-encode (tramp-coding-system-change-eol-conversion
6987 cs-encode 'unix))
6988 (when (search-forward "\r" nil t)
6989 (setq cs-decode (tramp-coding-system-change-eol-conversion
6990 cs-decode 'dos)))
6991 (tramp-compat-funcall
6992 'set-buffer-process-coding-system cs-decode cs-encode)
6993 (tramp-message
6994 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6995 ;; Look for ^M and do something useful if found.
6996 (when (search-forward "\r" nil t)
6997 ;; We have found a ^M but cannot frob the process coding system
6998 ;; because we're running on a non-MULE Emacs. Let's try
6999 ;; stty, instead.
7000 (tramp-send-command vec "stty -onlcr" t))))
7001 ;; Dump stty settings in the traces.
7002 (when (>= tramp-verbose 9)
7003 (tramp-send-command vec "stty -a" t))
7004 (tramp-send-command vec "set +o vi +o emacs" t)
7005
7006 ;; Check whether the output of "uname -sr" has been changed. If
7007 ;; yes, this is a strong indication that we must expire all
7008 ;; connection properties. We start again with
7009 ;; `tramp-maybe-open-connection', it will be catched there.
7010 (tramp-message vec 5 "Checking system information")
7011 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
7012 (new-uname
7013 (tramp-set-connection-property
7014 vec "uname"
7015 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
7016 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
7017 (with-current-buffer (tramp-get-debug-buffer vec)
7018 ;; Keep the debug buffer.
7019 (rename-buffer
7020 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
7021 (tramp-compat-funcall 'tramp-cleanup-connection vec)
7022 (if (= (point-min) (point-max))
7023 (kill-buffer nil)
7024 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
7025 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
7026 (tramp-get-buffer vec)
7027 (tramp-message
7028 vec 3
7029 "Connection reset, because remote host changed from `%s' to `%s'"
7030 old-uname new-uname)
7031 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
7032
7033 ;; Check whether the remote host suffers from buggy
7034 ;; `send-process-string'. This is known for FreeBSD (see comment in
7035 ;; `send_process', file process.c). I've tested sending 624 bytes
7036 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
7037 ;; this host type is detected locally. It cannot handle remote
7038 ;; hosts, though.
7039 (with-connection-property proc "chunksize"
7040 (cond
7041 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
7042 tramp-chunksize)
7043 (t
7044 (tramp-message
7045 vec 5 "Checking remote host type for `send-process-string' bug")
7046 (if (string-match
7047 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
7048 500 0))))
7049
7050 ;; Set remote PATH variable.
7051 (tramp-set-remote-path vec)
7052
7053 ;; Search for a good shell before searching for a command which
7054 ;; checks if a file exists. This is done because Tramp wants to use
7055 ;; "test foo; echo $?" to check if various conditions hold, and
7056 ;; there are buggy /bin/sh implementations which don't execute the
7057 ;; "echo $?" part if the "test" part has an error. In particular,
7058 ;; the OpenSolaris /bin/sh is a problem. There are also other
7059 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
7060 ;; in function declarations, or changing HISTFILE in place.
7061 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
7062 ;; detected.
7063 (tramp-find-shell vec)
7064
7065 ;; Disable unexpected output.
7066 (tramp-send-command vec "mesg n; biff n" t)
7067
7068 ;; IRIX64 bash expands "!" even when in single quotes. This
7069 ;; destroys our shell functions, we must disable it. See
7070 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
7071 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
7072 (tramp-send-command vec "set +H" t))
7073
7074 ;; Set the environment.
7075 (tramp-message vec 5 "Setting default environment")
7076
7077 (let ((env (copy-sequence tramp-remote-process-environment))
7078 unset item)
7079 (while env
7080 (setq item (tramp-compat-split-string (car env) "="))
7081 (setcdr item (mapconcat 'identity (cdr item) "="))
7082 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
7083 (tramp-send-command
7084 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
7085 (push (car item) unset))
7086 (setq env (cdr env)))
7087 (when unset
7088 (tramp-send-command
7089 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
7090
7091 ;; CCC: We should either implement a Perl version of base64 encoding
7092 ;; and decoding. Then we just use that in the last item. The other
7093 ;; alternative is to use the Perl version of UU encoding. But then
7094 ;; we need a Lisp version of uuencode.
7095 ;;
7096 ;; Old text from documentation of tramp-methods:
7097 ;; Using a uuencode/uudecode inline method is discouraged, please use one
7098 ;; of the base64 methods instead since base64 encoding is much more
7099 ;; reliable and the commands are more standardized between the different
7100 ;; Unix versions. But if you can't use base64 for some reason, please
7101 ;; note that the default uudecode command does not work well for some
7102 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
7103 ;; the following command for uudecode:
7104 ;;
7105 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
7106 ;;
7107 ;; For Irix, no solution is known yet.
7108
7109 (defconst tramp-local-coding-commands
7110 '((b64 base64-encode-region base64-decode-region)
7111 (uu tramp-uuencode-region uudecode-decode-region)
7112 (pack
7113 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7114 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7115 "List of local coding commands for inline transfer.
7116 Each item is a list that looks like this:
7117
7118 \(FORMAT ENCODING DECODING\)
7119
7120 FORMAT is symbol describing the encoding/decoding format. It can be
7121 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7122
7123 ENCODING and DECODING can be strings, giving commands, or symbols,
7124 giving functions. If they are strings, then they can contain
7125 the \"%s\" format specifier. If that specifier is present, the input
7126 filename will be put into the command line at that spot. If the
7127 specifier is not present, the input should be read from standard
7128 input.
7129
7130 If they are functions, they will be called with two arguments, start
7131 and end of region, and are expected to replace the region contents
7132 with the encoded or decoded results, respectively.")
7133
7134 (defconst tramp-remote-coding-commands
7135 '((b64 "base64" "base64 -d")
7136 (b64 "mimencode -b" "mimencode -u -b")
7137 (b64 "mmencode -b" "mmencode -u -b")
7138 (b64 "recode data..base64" "recode base64..data")
7139 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
7140 (b64 tramp-perl-encode tramp-perl-decode)
7141 (uu "uuencode xxx" "uudecode -o /dev/stdout")
7142 (uu "uuencode xxx" "uudecode -o -")
7143 (uu "uuencode xxx" "uudecode -p")
7144 (uu "uuencode xxx" tramp-uudecode)
7145 (pack
7146 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7147 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7148 "List of remote coding commands for inline transfer.
7149 Each item is a list that looks like this:
7150
7151 \(FORMAT ENCODING DECODING\)
7152
7153 FORMAT is symbol describing the encoding/decoding format. It can be
7154 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7155
7156 ENCODING and DECODING can be strings, giving commands, or symbols,
7157 giving variables. If they are strings, then they can contain
7158 the \"%s\" format specifier. If that specifier is present, the input
7159 filename will be put into the command line at that spot. If the
7160 specifier is not present, the input should be read from standard
7161 input.
7162
7163 If they are variables, this variable is a string containing a Perl
7164 implementation for this functionality. This Perl program will be transferred
7165 to the remote host, and it is available as shell function with the same name.")
7166
7167 (defun tramp-find-inline-encoding (vec)
7168 "Find an inline transfer encoding that works.
7169 Goes through the list `tramp-local-coding-commands' and
7170 `tramp-remote-coding-commands'."
7171 (save-excursion
7172 (let ((local-commands tramp-local-coding-commands)
7173 (magic "xyzzy")
7174 loc-enc loc-dec rem-enc rem-dec litem ritem found)
7175 (while (and local-commands (not found))
7176 (setq litem (pop local-commands))
7177 (catch 'wont-work-local
7178 (let ((format (nth 0 litem))
7179 (remote-commands tramp-remote-coding-commands))
7180 (setq loc-enc (nth 1 litem))
7181 (setq loc-dec (nth 2 litem))
7182 ;; If the local encoder or decoder is a string, the
7183 ;; corresponding command has to work locally.
7184 (if (not (stringp loc-enc))
7185 (tramp-message
7186 vec 5 "Checking local encoding function `%s'" loc-enc)
7187 (tramp-message
7188 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
7189 (unless (zerop (tramp-call-local-coding-command
7190 loc-enc nil nil))
7191 (throw 'wont-work-local nil)))
7192 (if (not (stringp loc-dec))
7193 (tramp-message
7194 vec 5 "Checking local decoding function `%s'" loc-dec)
7195 (tramp-message
7196 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7197 (unless (zerop (tramp-call-local-coding-command
7198 loc-dec nil nil))
7199 (throw 'wont-work-local nil)))
7200 ;; Search for remote coding commands with the same format
7201 (while (and remote-commands (not found))
7202 (setq ritem (pop remote-commands))
7203 (catch 'wont-work-remote
7204 (when (equal format (nth 0 ritem))
7205 (setq rem-enc (nth 1 ritem))
7206 (setq rem-dec (nth 2 ritem))
7207 ;; Check if remote encoding and decoding commands can be
7208 ;; called remotely with null input and output. This makes
7209 ;; sure there are no syntax errors and the command is really
7210 ;; found. Note that we do not redirect stdout to /dev/null,
7211 ;; for two reasons: when checking the decoding command, we
7212 ;; actually check the output it gives. And also, when
7213 ;; redirecting "mimencode" output to /dev/null, then as root
7214 ;; it might change the permissions of /dev/null!
7215 (when (not (stringp rem-enc))
7216 (let ((name (symbol-name rem-enc)))
7217 (while (string-match (regexp-quote "-") name)
7218 (setq name (replace-match "_" nil t name)))
7219 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7220 (setq rem-enc name)))
7221 (tramp-message
7222 vec 5
7223 "Checking remote encoding command `%s' for sanity" rem-enc)
7224 (unless (zerop (tramp-send-command-and-check
7225 vec (format "%s </dev/null" rem-enc) t))
7226 (throw 'wont-work-remote nil))
7227
7228 (when (not (stringp rem-dec))
7229 (let ((name (symbol-name rem-dec)))
7230 (while (string-match (regexp-quote "-") name)
7231 (setq name (replace-match "_" nil t name)))
7232 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7233 (setq rem-dec name)))
7234 (tramp-message
7235 vec 5
7236 "Checking remote decoding command `%s' for sanity" rem-dec)
7237 (unless (zerop (tramp-send-command-and-check
7238 vec
7239 (format "echo %s | %s | %s"
7240 magic rem-enc rem-dec)
7241 t))
7242 (throw 'wont-work-remote nil))
7243
7244 (with-current-buffer (tramp-get-buffer vec)
7245 (goto-char (point-min))
7246 (unless (looking-at (regexp-quote magic))
7247 (throw 'wont-work-remote nil)))
7248
7249 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7250 (setq rem-enc (nth 1 ritem))
7251 (setq rem-dec (nth 2 ritem))
7252 (setq found t)))))))
7253
7254 ;; Did we find something?
7255 (unless found
7256 (tramp-error
7257 vec 'file-error "Couldn't find an inline transfer encoding"))
7258
7259 ;; Set connection properties.
7260 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7261 (tramp-set-connection-property vec "local-encoding" loc-enc)
7262 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7263 (tramp-set-connection-property vec "local-decoding" loc-dec)
7264 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7265 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7266 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7267 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7268
7269 (defun tramp-call-local-coding-command (cmd input output)
7270 "Call the local encoding or decoding command.
7271 If CMD contains \"%s\", provide input file INPUT there in command.
7272 Otherwise, INPUT is passed via standard input.
7273 INPUT can also be nil which means `/dev/null'.
7274 OUTPUT can be a string (which specifies a filename), or t (which
7275 means standard output and thus the current buffer), or nil (which
7276 means discard it)."
7277 (tramp-local-call-process
7278 tramp-encoding-shell
7279 (when (and input (not (string-match "%s" cmd))) input)
7280 (if (eq output t) t nil)
7281 nil
7282 tramp-encoding-command-switch
7283 (concat
7284 (if (string-match "%s" cmd) (format cmd input) cmd)
7285 (if (stringp output) (concat "> " output) ""))))
7286
7287 (defconst tramp-inline-compress-commands
7288 '(("gzip" "gzip -d")
7289 ("bzip2" "bzip2 -d")
7290 ("compress" "compress -d"))
7291 "List of compress and decompress commands for inline transfer.
7292 Each item is a list that looks like this:
7293
7294 \(COMPRESS DECOMPRESS\)
7295
7296 COMPRESS or DECOMPRESS are strings with the respective commands.")
7297
7298 (defun tramp-find-inline-compress (vec)
7299 "Find an inline transfer compress command that works.
7300 Goes through the list `tramp-inline-compress-commands'."
7301 (save-excursion
7302 (let ((commands tramp-inline-compress-commands)
7303 (magic "xyzzy")
7304 item compress decompress
7305 found)
7306 (while (and commands (not found))
7307 (catch 'next
7308 (setq item (pop commands)
7309 compress (nth 0 item)
7310 decompress (nth 1 item))
7311 (tramp-message
7312 vec 5
7313 "Checking local compress command `%s', `%s' for sanity"
7314 compress decompress)
7315 (unless (zerop (tramp-call-local-coding-command
7316 (format "echo %s | %s | %s"
7317 magic compress decompress) nil nil))
7318 (throw 'next nil))
7319 (tramp-message
7320 vec 5
7321 "Checking remote compress command `%s', `%s' for sanity"
7322 compress decompress)
7323 (unless (zerop (tramp-send-command-and-check
7324 vec (format "echo %s | %s | %s"
7325 magic compress decompress) t))
7326 (throw 'next nil))
7327 (setq found t)))
7328
7329 ;; Did we find something?
7330 (if found
7331 (progn
7332 ;; Set connection properties.
7333 (tramp-message
7334 vec 5 "Using inline transfer compress command `%s'" compress)
7335 (tramp-set-connection-property vec "inline-compress" compress)
7336 (tramp-message
7337 vec 5 "Using inline transfer decompress command `%s'" decompress)
7338 (tramp-set-connection-property vec "inline-decompress" decompress))
7339
7340 (tramp-set-connection-property vec "inline-compress" nil)
7341 (tramp-set-connection-property vec "inline-decompress" nil)
7342 (tramp-message
7343 vec 2 "Couldn't find an inline transfer compress command")))))
7344
7345 (defun tramp-compute-multi-hops (vec)
7346 "Expands VEC according to `tramp-default-proxies-alist'.
7347 Gateway hops are already opened."
7348 (let ((target-alist `(,vec))
7349 (choices tramp-default-proxies-alist)
7350 item proxy)
7351
7352 ;; Look for proxy hosts to be passed.
7353 (while choices
7354 (setq item (pop choices)
7355 proxy (eval (nth 2 item)))
7356 (when (and
7357 ;; host
7358 (string-match (or (eval (nth 0 item)) "")
7359 (or (tramp-file-name-host (car target-alist)) ""))
7360 ;; user
7361 (string-match (or (eval (nth 1 item)) "")
7362 (or (tramp-file-name-user (car target-alist)) "")))
7363 (if (null proxy)
7364 ;; No more hops needed.
7365 (setq choices nil)
7366 ;; Replace placeholders.
7367 (setq proxy
7368 (format-spec
7369 proxy
7370 (format-spec-make
7371 ?u (or (tramp-file-name-user (car target-alist)) "")
7372 ?h (or (tramp-file-name-host (car target-alist)) ""))))
7373 (with-parsed-tramp-file-name proxy l
7374 ;; Add the hop.
7375 (add-to-list 'target-alist l)
7376 ;; Start next search.
7377 (setq choices tramp-default-proxies-alist)))))
7378
7379 ;; Handle gateways.
7380 (when (and (boundp 'tramp-gw-tunnel-method)
7381 (string-match (format
7382 "^\\(%s\\|%s\\)$"
7383 (symbol-value 'tramp-gw-tunnel-method)
7384 (symbol-value 'tramp-gw-socks-method))
7385 (tramp-file-name-method (car target-alist))))
7386 (let ((gw (pop target-alist))
7387 (hop (pop target-alist)))
7388 ;; Is the method prepared for gateways?
7389 (unless (tramp-get-method-parameter
7390 (tramp-file-name-method hop) 'tramp-default-port)
7391 (tramp-error
7392 vec 'file-error
7393 "Method `%s' is not supported for gateway access."
7394 (tramp-file-name-method hop)))
7395 ;; Add default port if needed.
7396 (unless
7397 (string-match
7398 tramp-host-with-port-regexp (tramp-file-name-host hop))
7399 (aset hop 2
7400 (concat
7401 (tramp-file-name-host hop) tramp-prefix-port-format
7402 (number-to-string
7403 (tramp-get-method-parameter
7404 (tramp-file-name-method hop) 'tramp-default-port)))))
7405 ;; Open the gateway connection.
7406 (add-to-list
7407 'target-alist
7408 (vector
7409 (tramp-file-name-method hop) (tramp-file-name-user hop)
7410 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil))
7411 ;; For the password prompt, we need the correct values.
7412 ;; Therefore, we must remember the gateway vector. But we
7413 ;; cannot do it as connection property, because it shouldn't
7414 ;; be persistent. And we have no started process yet either.
7415 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7416
7417 ;; Foreign and out-of-band methods are not supported for multi-hops.
7418 (when (cdr target-alist)
7419 (setq choices target-alist)
7420 (while choices
7421 (setq item (pop choices))
7422 (when
7423 (or
7424 (not
7425 (tramp-get-method-parameter
7426 (tramp-file-name-method item) 'tramp-login-program))
7427 (tramp-get-method-parameter
7428 (tramp-file-name-method item) 'tramp-copy-program))
7429 (tramp-error
7430 vec 'file-error
7431 "Method `%s' is not supported for multi-hops."
7432 (tramp-file-name-method item)))))
7433
7434 ;; In case the host name is not used for the remote shell
7435 ;; command, the user could be misguided by applying a random
7436 ;; hostname.
7437 (let* ((v (car target-alist))
7438 (method (tramp-file-name-method v))
7439 (host (tramp-file-name-host v)))
7440 (unless
7441 (or
7442 ;; There are multi-hops.
7443 (cdr target-alist)
7444 ;; The host name is used for the remote shell command.
7445 (member
7446 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7447 ;; The host is local. We cannot use `tramp-local-host-p'
7448 ;; here, because it opens a connection as well.
7449 (string-match tramp-local-host-regexp host))
7450 (tramp-error
7451 v 'file-error
7452 "Host `%s' looks like a remote host, `%s' can only use the local host"
7453 host method)))
7454
7455 ;; Result.
7456 target-alist))
7457
7458 (defun tramp-maybe-open-connection (vec)
7459 "Maybe open a connection VEC.
7460 Does not do anything if a connection is already open, but re-opens the
7461 connection if a previous connection has died for some reason."
7462 (catch 'uname-changed
7463 (let ((p (tramp-get-connection-process vec))
7464 (process-name (tramp-get-connection-property vec "process-name" nil))
7465 (process-environment (copy-sequence process-environment)))
7466
7467 ;; If too much time has passed since last command was sent, look
7468 ;; whether process is still alive. If it isn't, kill it. When
7469 ;; using ssh, it can sometimes happen that the remote end has
7470 ;; hung up but the local ssh client doesn't recognize this until
7471 ;; it tries to send some data to the remote end. So that's why
7472 ;; we try to send a command from time to time, then look again
7473 ;; whether the process is really alive.
7474 (condition-case nil
7475 (when (and (> (tramp-time-diff
7476 (current-time)
7477 (tramp-get-connection-property
7478 p "last-cmd-time" '(0 0 0)))
7479 60)
7480 p (processp p) (memq (process-status p) '(run open)))
7481 (tramp-send-command vec "echo are you awake" t t)
7482 (unless (and (memq (process-status p) '(run open))
7483 (tramp-wait-for-output p 10))
7484 ;; The error will be catched locally.
7485 (tramp-error vec 'file-error "Awake did fail")))
7486 (file-error
7487 (tramp-flush-connection-property vec)
7488 (tramp-flush-connection-property p)
7489 (delete-process p)
7490 (setq p nil)))
7491
7492 ;; New connection must be opened.
7493 (unless (and p (processp p) (memq (process-status p) '(run open)))
7494
7495 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7496 ;; messages from the beginning.
7497 (tramp-get-buffer vec)
7498 (with-progress-reporter
7499 vec 3
7500 (if (zerop (length (tramp-file-name-user vec)))
7501 (format "Opening connection for %s using %s"
7502 (tramp-file-name-host vec)
7503 (tramp-file-name-method vec))
7504 (format "Opening connection for %s@%s using %s"
7505 (tramp-file-name-user vec)
7506 (tramp-file-name-host vec)
7507 (tramp-file-name-method vec)))
7508
7509 ;; Start new process.
7510 (when (and p (processp p))
7511 (delete-process p))
7512 (setenv "TERM" tramp-terminal-type)
7513 (setenv "LC_ALL" "C")
7514 (setenv "PROMPT_COMMAND")
7515 (setenv "PS1" tramp-initial-end-of-output)
7516 (let* ((target-alist (tramp-compute-multi-hops vec))
7517 (process-connection-type tramp-process-connection-type)
7518 (process-adaptive-read-buffering nil)
7519 (coding-system-for-read nil)
7520 ;; This must be done in order to avoid our file name handler.
7521 (p (let ((default-directory
7522 (tramp-compat-temporary-file-directory)))
7523 (start-process
7524 (or process-name (tramp-buffer-name vec))
7525 (tramp-get-connection-buffer vec)
7526 tramp-encoding-shell))))
7527
7528 (tramp-message
7529 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7530
7531 ;; Check whether process is alive.
7532 (tramp-set-process-query-on-exit-flag p nil)
7533 (tramp-barf-if-no-shell-prompt
7534 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7535
7536 ;; Now do all the connections as specified.
7537 (while target-alist
7538 (let* ((hop (car target-alist))
7539 (l-method (tramp-file-name-method hop))
7540 (l-user (tramp-file-name-user hop))
7541 (l-host (tramp-file-name-host hop))
7542 (l-port nil)
7543 (login-program
7544 (tramp-get-method-parameter
7545 l-method 'tramp-login-program))
7546 (login-args
7547 (tramp-get-method-parameter l-method 'tramp-login-args))
7548 (async-args
7549 (tramp-get-method-parameter l-method 'tramp-async-args))
7550 (gw-args
7551 (tramp-get-method-parameter l-method 'tramp-gw-args))
7552 (gw (tramp-get-file-property hop "" "gateway" nil))
7553 (g-method (and gw (tramp-file-name-method gw)))
7554 (g-user (and gw (tramp-file-name-user gw)))
7555 (g-host (and gw (tramp-file-name-host gw)))
7556 (command login-program)
7557 ;; We don't create the temporary file. In fact,
7558 ;; it is just a prefix for the ControlPath option
7559 ;; of ssh; the real temporary file has another
7560 ;; name, and it is created and protected by ssh.
7561 ;; It is also removed by ssh, when the connection
7562 ;; is closed.
7563 (tmpfile
7564 (tramp-set-connection-property
7565 p "temp-file"
7566 (make-temp-name
7567 (expand-file-name
7568 tramp-temp-name-prefix
7569 (tramp-compat-temporary-file-directory)))))
7570 spec)
7571
7572 ;; Add arguments for asynchrononous processes.
7573 (when (and process-name async-args)
7574 (setq login-args (append async-args login-args)))
7575
7576 ;; Add gateway arguments if necessary.
7577 (when (and gw gw-args)
7578 (setq login-args (append gw-args login-args)))
7579
7580 ;; Check for port number. Until now, there's no need
7581 ;; for handling like method, user, host.
7582 (when (string-match tramp-host-with-port-regexp l-host)
7583 (setq l-port (match-string 2 l-host)
7584 l-host (match-string 1 l-host)))
7585
7586 ;; Set variables for computing the prompt for reading
7587 ;; password. They can also be derived from a gateway.
7588 (setq tramp-current-method (or g-method l-method)
7589 tramp-current-user (or g-user l-user)
7590 tramp-current-host (or g-host l-host))
7591
7592 ;; Replace login-args place holders.
7593 (setq
7594 l-host (or l-host "")
7595 l-user (or l-user "")
7596 l-port (or l-port "")
7597 spec (format-spec-make
7598 ?h l-host ?u l-user ?p l-port ?t tmpfile)
7599 command
7600 (concat
7601 ;; We do not want to see the trailing local prompt in
7602 ;; `start-file-process'.
7603 (unless (memq system-type '(windows-nt)) "exec ")
7604 command " "
7605 (mapconcat
7606 (lambda (x)
7607 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7608 (unless (member "" x) (mapconcat 'identity x " ")))
7609 login-args " ")
7610 ;; Local shell could be a Windows COMSPEC. It
7611 ;; doesn't know the ";" syntax, but we must exit
7612 ;; always for `start-file-process'. "exec" does not
7613 ;; work either.
7614 (if (memq system-type '(windows-nt)) " && exit || exit")))
7615
7616 ;; Send the command.
7617 (tramp-message vec 3 "Sending command `%s'" command)
7618 (tramp-send-command vec command t t)
7619 (tramp-process-actions p vec tramp-actions-before-shell 60)
7620 (tramp-message
7621 vec 3 "Found remote shell prompt on `%s'" l-host))
7622 ;; Next hop.
7623 (setq target-alist (cdr target-alist)))
7624
7625 ;; Make initial shell settings.
7626 (tramp-open-connection-setup-interactive-shell p vec)))))))
7627
7628 (defun tramp-send-command (vec command &optional neveropen nooutput)
7629 "Send the COMMAND to connection VEC.
7630 Erases temporary buffer before sending the command. If optional
7631 arg NEVEROPEN is non-nil, never try to open the connection. This
7632 is meant to be used from `tramp-maybe-open-connection' only. The
7633 function waits for output unless NOOUTPUT is set."
7634 (unless neveropen (tramp-maybe-open-connection vec))
7635 (let ((p (tramp-get-connection-process vec)))
7636 (when (tramp-get-connection-property p "remote-echo" nil)
7637 ;; We mark the command string that it can be erased in the output buffer.
7638 (tramp-set-connection-property p "check-remote-echo" t)
7639 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7640 (tramp-message vec 6 "%s" command)
7641 (tramp-send-string vec command)
7642 (unless nooutput (tramp-wait-for-output p))))
7643
7644 (defun tramp-wait-for-output (proc &optional timeout)
7645 "Wait for output from remote command."
7646 (unless (buffer-live-p (process-buffer proc))
7647 (delete-process proc)
7648 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7649 (with-current-buffer (process-buffer proc)
7650 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7651 ;; be leading escape sequences, which must be ignored.
7652 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7653 ;; Sometimes, the commands do not return a newline but a
7654 ;; null byte before the shell prompt, for example "git
7655 ;; ls-files -c -z ...".
7656 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7657 (found (tramp-wait-for-regexp proc timeout regexp1)))
7658 (if found
7659 (let (buffer-read-only)
7660 ;; A simple-minded busybox has sent " ^H" sequences.
7661 ;; Delete them.
7662 (goto-char (point-min))
7663 (when (re-search-forward
7664 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7665 (forward-line 1)
7666 (delete-region (point-min) (point)))
7667 ;; Delete the prompt.
7668 (goto-char (point-max))
7669 (re-search-backward regexp nil t)
7670 (delete-region (point) (point-max)))
7671 (if timeout
7672 (tramp-error
7673 proc 'file-error
7674 "[[Remote prompt `%s' not found in %d secs]]"
7675 tramp-end-of-output timeout)
7676 (tramp-error
7677 proc 'file-error
7678 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7679 ;; Return value is whether end-of-output sentinel was found.
7680 found)))
7681
7682 (defun tramp-send-command-and-check
7683 (vec command &optional subshell dont-suppress-err)
7684 "Run COMMAND and check its exit status.
7685 Sends `echo $?' along with the COMMAND for checking the exit status. If
7686 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7687
7688 If the optional argument SUBSHELL is non-nil, the command is
7689 executed in a subshell, ie surrounded by parentheses. If
7690 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7691 (tramp-send-command
7692 vec
7693 (concat (if subshell "( " "")
7694 command
7695 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7696 "echo tramp_exit_status $?"
7697 (if subshell " )" "")))
7698 (with-current-buffer (tramp-get-connection-buffer vec)
7699 (goto-char (point-max))
7700 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7701 (tramp-error
7702 vec 'file-error "Couldn't find exit status of `%s'" command))
7703 (skip-chars-forward "^ ")
7704 (prog1
7705 (read (current-buffer))
7706 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7707
7708 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7709 "Run COMMAND, check exit status, throw error if exit status not okay.
7710 Similar to `tramp-send-command-and-check' but accepts two more arguments
7711 FMT and ARGS which are passed to `error'."
7712 (unless (zerop (tramp-send-command-and-check vec command))
7713 (apply 'tramp-error vec 'file-error fmt args)))
7714
7715 (defun tramp-send-command-and-read (vec command)
7716 "Run COMMAND and return the output, which must be a Lisp expression.
7717 In case there is no valid Lisp expression, it raises an error"
7718 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7719 (with-current-buffer (tramp-get-connection-buffer vec)
7720 ;; Read the expression.
7721 (goto-char (point-min))
7722 (condition-case nil
7723 (prog1 (read (current-buffer))
7724 ;; Error handling.
7725 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7726 (error nil)))
7727 (error (tramp-error
7728 vec 'file-error
7729 "`%s' does not return a valid Lisp expression: `%s'"
7730 command (buffer-string))))))
7731
7732 ;; It seems that Tru64 Unix does not like it if long strings are sent
7733 ;; to it in one go. (This happens when sending the Perl
7734 ;; `file-attributes' implementation, for instance.) Therefore, we
7735 ;; have this function which sends the string in chunks.
7736 (defun tramp-send-string (vec string)
7737 "Send the STRING via connection VEC.
7738
7739 The STRING is expected to use Unix line-endings, but the lines sent to
7740 the remote host use line-endings as defined in the variable
7741 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7742 (let* ((p (tramp-get-connection-process vec))
7743 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7744 (unless p
7745 (tramp-error
7746 vec 'file-error "Can't send string to remote host -- not logged in"))
7747 (tramp-set-connection-property p "last-cmd-time" (current-time))
7748 (tramp-message vec 10 "%s" string)
7749 (with-current-buffer (tramp-get-connection-buffer vec)
7750 ;; Clean up the buffer. We cannot call `erase-buffer' because
7751 ;; narrowing might be in effect.
7752 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7753 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7754 (setq string
7755 (mapconcat 'identity
7756 (tramp-compat-split-string string "\n")
7757 tramp-rsh-end-of-line))
7758 (unless (or (string= string "")
7759 (string-equal (substring string -1) tramp-rsh-end-of-line))
7760 (setq string (concat string tramp-rsh-end-of-line)))
7761 ;; Send the string.
7762 (if (and chunksize (not (zerop chunksize)))
7763 (let ((pos 0)
7764 (end (length string)))
7765 (while (< pos end)
7766 (tramp-message
7767 vec 10 "Sending chunk from %s to %s"
7768 pos (min (+ pos chunksize) end))
7769 (process-send-string
7770 p (substring string pos (min (+ pos chunksize) end)))
7771 (setq pos (+ pos chunksize))))
7772 (process-send-string p string)))))
7773
7774 (defun tramp-mode-string-to-int (mode-string)
7775 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7776 (let* (case-fold-search
7777 (mode-chars (string-to-vector mode-string))
7778 (owner-read (aref mode-chars 1))
7779 (owner-write (aref mode-chars 2))
7780 (owner-execute-or-setid (aref mode-chars 3))
7781 (group-read (aref mode-chars 4))
7782 (group-write (aref mode-chars 5))
7783 (group-execute-or-setid (aref mode-chars 6))
7784 (other-read (aref mode-chars 7))
7785 (other-write (aref mode-chars 8))
7786 (other-execute-or-sticky (aref mode-chars 9)))
7787 (save-match-data
7788 (logior
7789 (cond
7790 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7791 ((char-equal owner-read ?-) 0)
7792 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7793 (cond
7794 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7795 ((char-equal owner-write ?-) 0)
7796 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7797 (cond
7798 ((char-equal owner-execute-or-setid ?x)
7799 (tramp-octal-to-decimal "00100"))
7800 ((char-equal owner-execute-or-setid ?S)
7801 (tramp-octal-to-decimal "04000"))
7802 ((char-equal owner-execute-or-setid ?s)
7803 (tramp-octal-to-decimal "04100"))
7804 ((char-equal owner-execute-or-setid ?-) 0)
7805 (t (error "Fourth char `%c' must be one of `xsS-'"
7806 owner-execute-or-setid)))
7807 (cond
7808 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7809 ((char-equal group-read ?-) 0)
7810 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7811 (cond
7812 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7813 ((char-equal group-write ?-) 0)
7814 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7815 (cond
7816 ((char-equal group-execute-or-setid ?x)
7817 (tramp-octal-to-decimal "00010"))
7818 ((char-equal group-execute-or-setid ?S)
7819 (tramp-octal-to-decimal "02000"))
7820 ((char-equal group-execute-or-setid ?s)
7821 (tramp-octal-to-decimal "02010"))
7822 ((char-equal group-execute-or-setid ?-) 0)
7823 (t (error "Seventh char `%c' must be one of `xsS-'"
7824 group-execute-or-setid)))
7825 (cond
7826 ((char-equal other-read ?r)
7827 (tramp-octal-to-decimal "00004"))
7828 ((char-equal other-read ?-) 0)
7829 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7830 (cond
7831 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7832 ((char-equal other-write ?-) 0)
7833 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7834 (cond
7835 ((char-equal other-execute-or-sticky ?x)
7836 (tramp-octal-to-decimal "00001"))
7837 ((char-equal other-execute-or-sticky ?T)
7838 (tramp-octal-to-decimal "01000"))
7839 ((char-equal other-execute-or-sticky ?t)
7840 (tramp-octal-to-decimal "01001"))
7841 ((char-equal other-execute-or-sticky ?-) 0)
7842 (t (error "Tenth char `%c' must be one of `xtT-'"
7843 other-execute-or-sticky)))))))
7844
7845 (defun tramp-convert-file-attributes (vec attr)
7846 "Convert file-attributes ATTR generated by perl script, stat or ls.
7847 Convert file mode bits to string and set virtual device number.
7848 Return ATTR."
7849 (when attr
7850 ;; Convert last access time.
7851 (unless (listp (nth 4 attr))
7852 (setcar (nthcdr 4 attr)
7853 (list (floor (nth 4 attr) 65536)
7854 (floor (mod (nth 4 attr) 65536)))))
7855 ;; Convert last modification time.
7856 (unless (listp (nth 5 attr))
7857 (setcar (nthcdr 5 attr)
7858 (list (floor (nth 5 attr) 65536)
7859 (floor (mod (nth 5 attr) 65536)))))
7860 ;; Convert last status change time.
7861 (unless (listp (nth 6 attr))
7862 (setcar (nthcdr 6 attr)
7863 (list (floor (nth 6 attr) 65536)
7864 (floor (mod (nth 6 attr) 65536)))))
7865 ;; Convert file size.
7866 (when (< (nth 7 attr) 0)
7867 (setcar (nthcdr 7 attr) -1))
7868 (when (and (floatp (nth 7 attr))
7869 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7870 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7871 ;; Convert file mode bits to string.
7872 (unless (stringp (nth 8 attr))
7873 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7874 (when (stringp (car attr))
7875 (aset (nth 8 attr) 0 ?l)))
7876 ;; Convert directory indication bit.
7877 (when (string-match "^d" (nth 8 attr))
7878 (setcar attr t))
7879 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7880 (when (consp (car attr))
7881 (if (and (stringp (caar attr))
7882 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7883 (setcar attr (match-string 1 (caar attr)))
7884 (setcar attr nil)))
7885 ;; Set file's gid change bit.
7886 (setcar (nthcdr 9 attr)
7887 (if (numberp (nth 3 attr))
7888 (not (= (nth 3 attr)
7889 (tramp-get-remote-gid vec 'integer)))
7890 (not (string-equal
7891 (nth 3 attr)
7892 (tramp-get-remote-gid vec 'string)))))
7893 ;; Convert inode.
7894 (unless (listp (nth 10 attr))
7895 (setcar (nthcdr 10 attr)
7896 (condition-case nil
7897 (cons (floor (nth 10 attr) 65536)
7898 (floor (mod (nth 10 attr) 65536)))
7899 ;; Inodes can be incredible huge. We must hide this.
7900 (error (tramp-get-inode vec)))))
7901 ;; Set virtual device number.
7902 (setcar (nthcdr 11 attr)
7903 (tramp-get-device vec))
7904 attr))
7905
7906 (defun tramp-check-cached-permissions (vec access)
7907 "Check `file-attributes' caches for VEC.
7908 Return t if according to the cache access type ACCESS is known to
7909 be granted."
7910 (let ((result nil)
7911 (offset (cond
7912 ((eq ?r access) 1)
7913 ((eq ?w access) 2)
7914 ((eq ?x access) 3))))
7915 (dolist (suffix '("string" "integer") result)
7916 (setq
7917 result
7918 (or
7919 result
7920 (let ((file-attr
7921 (tramp-get-file-property
7922 vec (tramp-file-name-localname vec)
7923 (concat "file-attributes-" suffix) nil))
7924 (remote-uid
7925 (tramp-get-connection-property
7926 vec (concat "uid-" suffix) nil))
7927 (remote-gid
7928 (tramp-get-connection-property
7929 vec (concat "gid-" suffix) nil)))
7930 (and
7931 file-attr
7932 (or
7933 ;; Not a symlink
7934 (eq t (car file-attr))
7935 (null (car file-attr)))
7936 (or
7937 ;; World accessible.
7938 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7939 ;; User accessible and owned by user.
7940 (and
7941 (eq access (aref (nth 8 file-attr) offset))
7942 (equal remote-uid (nth 2 file-attr)))
7943 ;; Group accessible and owned by user's
7944 ;; principal group.
7945 (and
7946 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7947 (equal remote-gid (nth 3 file-attr)))))))))))
7948
7949 (defun tramp-get-inode (vec)
7950 "Returns the virtual inode number.
7951 If it doesn't exist, generate a new one."
7952 (let ((string (tramp-make-tramp-file-name
7953 (tramp-file-name-method vec)
7954 (tramp-file-name-user vec)
7955 (tramp-file-name-host vec)
7956 "")))
7957 (unless (assoc string tramp-inodes)
7958 (add-to-list 'tramp-inodes
7959 (list string (length tramp-inodes))))
7960 (nth 1 (assoc string tramp-inodes))))
7961
7962 (defun tramp-get-device (vec)
7963 "Returns the virtual device number.
7964 If it doesn't exist, generate a new one."
7965 (let ((string (tramp-make-tramp-file-name
7966 (tramp-file-name-method vec)
7967 (tramp-file-name-user vec)
7968 (tramp-file-name-host vec)
7969 "")))
7970 (unless (assoc string tramp-devices)
7971 (add-to-list 'tramp-devices
7972 (list string (length tramp-devices))))
7973 (cons -1 (nth 1 (assoc string tramp-devices)))))
7974
7975 (defun tramp-file-mode-from-int (mode)
7976 "Turn an integer representing a file mode into an ls(1)-like string."
7977 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7978 (user (logand (lsh mode -6) 7))
7979 (group (logand (lsh mode -3) 7))
7980 (other (logand (lsh mode -0) 7))
7981 (suid (> (logand (lsh mode -9) 4) 0))
7982 (sgid (> (logand (lsh mode -9) 2) 0))
7983 (sticky (> (logand (lsh mode -9) 1) 0)))
7984 (setq user (tramp-file-mode-permissions user suid "s"))
7985 (setq group (tramp-file-mode-permissions group sgid "s"))
7986 (setq other (tramp-file-mode-permissions other sticky "t"))
7987 (concat type user group other)))
7988
7989 (defun tramp-file-mode-permissions (perm suid suid-text)
7990 "Convert a permission bitset into a string.
7991 This is used internally by `tramp-file-mode-from-int'."
7992 (let ((r (> (logand perm 4) 0))
7993 (w (> (logand perm 2) 0))
7994 (x (> (logand perm 1) 0)))
7995 (concat (or (and r "r") "-")
7996 (or (and w "w") "-")
7997 (or (and suid x suid-text) ; suid, execute
7998 (and suid (upcase suid-text)) ; suid, !execute
7999 (and x "x") "-")))) ; !suid
8000
8001 (defun tramp-decimal-to-octal (i)
8002 "Return a string consisting of the octal digits of I.
8003 Not actually used. Use `(format \"%o\" i)' instead?"
8004 (cond ((< i 0) (error "Cannot convert negative number to octal"))
8005 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
8006 ((zerop i) "0")
8007 (t (concat (tramp-decimal-to-octal (/ i 8))
8008 (number-to-string (% i 8))))))
8009
8010 ;; Kudos to Gerd Moellmann for this suggestion.
8011 (defun tramp-octal-to-decimal (ostr)
8012 "Given a string of octal digits, return a decimal number."
8013 (let ((x (or ostr "")))
8014 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
8015 (unless (string-match "\\`[0-7]*\\'" x)
8016 (error "Non-octal junk in string `%s'" x))
8017 (string-to-number ostr 8)))
8018
8019 (defun tramp-shell-case-fold (string)
8020 "Converts STRING to shell glob pattern which ignores case."
8021 (mapconcat
8022 (lambda (c)
8023 (if (equal (downcase c) (upcase c))
8024 (vector c)
8025 (format "[%c%c]" (downcase c) (upcase c))))
8026 string
8027 ""))
8028
8029
8030 ;; ------------------------------------------------------------
8031 ;; -- Tramp file names --
8032 ;; ------------------------------------------------------------
8033 ;; Conversion functions between external representation and
8034 ;; internal data structure. Convenience functions for internal
8035 ;; data structure.
8036
8037 (defun tramp-file-name-p (vec)
8038 "Check, whether VEC is a Tramp object."
8039 (and (vectorp vec) (= 4 (length vec))))
8040
8041 (defun tramp-file-name-method (vec)
8042 "Return method component of VEC."
8043 (and (tramp-file-name-p vec) (aref vec 0)))
8044
8045 (defun tramp-file-name-user (vec)
8046 "Return user component of VEC."
8047 (and (tramp-file-name-p vec) (aref vec 1)))
8048
8049 (defun tramp-file-name-host (vec)
8050 "Return host component of VEC."
8051 (and (tramp-file-name-p vec) (aref vec 2)))
8052
8053 (defun tramp-file-name-localname (vec)
8054 "Return localname component of VEC."
8055 (and (tramp-file-name-p vec) (aref vec 3)))
8056
8057 ;; The user part of a Tramp file name vector can be of kind
8058 ;; "user%domain". Sometimes, we must extract these parts.
8059 (defun tramp-file-name-real-user (vec)
8060 "Return the user name of VEC without domain."
8061 (save-match-data
8062 (let ((user (tramp-file-name-user vec)))
8063 (if (and (stringp user)
8064 (string-match tramp-user-with-domain-regexp user))
8065 (match-string 1 user)
8066 user))))
8067
8068 (defun tramp-file-name-domain (vec)
8069 "Return the domain name of VEC."
8070 (save-match-data
8071 (let ((user (tramp-file-name-user vec)))
8072 (and (stringp user)
8073 (string-match tramp-user-with-domain-regexp user)
8074 (match-string 2 user)))))
8075
8076 ;; The host part of a Tramp file name vector can be of kind
8077 ;; "host#port". Sometimes, we must extract these parts.
8078 (defun tramp-file-name-real-host (vec)
8079 "Return the host name of VEC without port."
8080 (save-match-data
8081 (let ((host (tramp-file-name-host vec)))
8082 (if (and (stringp host)
8083 (string-match tramp-host-with-port-regexp host))
8084 (match-string 1 host)
8085 host))))
8086
8087 (defun tramp-file-name-port (vec)
8088 "Return the port number of VEC."
8089 (save-match-data
8090 (let ((host (tramp-file-name-host vec)))
8091 (and (stringp host)
8092 (string-match tramp-host-with-port-regexp host)
8093 (string-to-number (match-string 2 host))))))
8094
8095 (defun tramp-tramp-file-p (name)
8096 "Return t if NAME is a string with Tramp file name syntax."
8097 (save-match-data
8098 (and (stringp name) (string-match tramp-file-name-regexp name))))
8099
8100 (defun tramp-find-method (method user host)
8101 "Return the right method string to use.
8102 This is METHOD, if non-nil. Otherwise, do a lookup in
8103 `tramp-default-method-alist'."
8104 (or method
8105 (let ((choices tramp-default-method-alist)
8106 lmethod item)
8107 (while choices
8108 (setq item (pop choices))
8109 (when (and (string-match (or (nth 0 item) "") (or host ""))
8110 (string-match (or (nth 1 item) "") (or user "")))
8111 (setq lmethod (nth 2 item))
8112 (setq choices nil)))
8113 lmethod)
8114 tramp-default-method))
8115
8116 (defun tramp-find-user (method user host)
8117 "Return the right user string to use.
8118 This is USER, if non-nil. Otherwise, do a lookup in
8119 `tramp-default-user-alist'."
8120 (or user
8121 (let ((choices tramp-default-user-alist)
8122 luser item)
8123 (while choices
8124 (setq item (pop choices))
8125 (when (and (string-match (or (nth 0 item) "") (or method ""))
8126 (string-match (or (nth 1 item) "") (or host "")))
8127 (setq luser (nth 2 item))
8128 (setq choices nil)))
8129 luser)
8130 tramp-default-user))
8131
8132 (defun tramp-find-host (method user host)
8133 "Return the right host string to use.
8134 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
8135 (or (and (> (length host) 0) host)
8136 tramp-default-host))
8137
8138 (defun tramp-dissect-file-name (name &optional nodefault)
8139 "Return a `tramp-file-name' structure.
8140 The structure consists of remote method, remote user, remote host
8141 and localname (file name on remote host). If NODEFAULT is
8142 non-nil, the file name parts are not expanded to their default
8143 values."
8144 (save-match-data
8145 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
8146 (unless match (error "Not a Tramp file name: %s" name))
8147 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
8148 (user (match-string (nth 2 tramp-file-name-structure) name))
8149 (host (match-string (nth 3 tramp-file-name-structure) name))
8150 (localname (match-string (nth 4 tramp-file-name-structure) name)))
8151 (when (member method '("multi" "multiu"))
8152 (error
8153 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
8154 method))
8155 (when host
8156 (when (string-match tramp-prefix-ipv6-regexp host)
8157 (setq host (replace-match "" nil t host)))
8158 (when (string-match tramp-postfix-ipv6-regexp host)
8159 (setq host (replace-match "" nil t host))))
8160 (if nodefault
8161 (vector method user host localname)
8162 (vector
8163 (tramp-find-method method user host)
8164 (tramp-find-user method user host)
8165 (tramp-find-host method user host)
8166 localname))))))
8167
8168 (defun tramp-equal-remote (file1 file2)
8169 "Check, whether the remote parts of FILE1 and FILE2 are identical.
8170 The check depends on method, user and host name of the files. If
8171 one of the components is missing, the default values are used.
8172 The local file name parts of FILE1 and FILE2 are not taken into
8173 account.
8174
8175 Example:
8176
8177 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
8178
8179 would yield `t'. On the other hand, the following check results in nil:
8180
8181 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
8182 (and (stringp (file-remote-p file1))
8183 (stringp (file-remote-p file2))
8184 (string-equal (file-remote-p file1) (file-remote-p file2))))
8185
8186 (defun tramp-make-tramp-file-name (method user host localname)
8187 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
8188 (concat tramp-prefix-format
8189 (when (not (zerop (length method)))
8190 (concat method tramp-postfix-method-format))
8191 (when (not (zerop (length user)))
8192 (concat user tramp-postfix-user-format))
8193 (when host
8194 (if (string-match tramp-ipv6-regexp host)
8195 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8196 host))
8197 tramp-postfix-host-format
8198 (when localname localname)))
8199
8200 (defun tramp-completion-make-tramp-file-name (method user host localname)
8201 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
8202 It must not be a complete Tramp file name, but as long as there are
8203 necessary only. This function will be used in file name completion."
8204 (concat tramp-prefix-format
8205 (when (not (zerop (length method)))
8206 (concat method tramp-postfix-method-format))
8207 (when (not (zerop (length user)))
8208 (concat user tramp-postfix-user-format))
8209 (when (not (zerop (length host)))
8210 (concat
8211 (if (string-match tramp-ipv6-regexp host)
8212 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8213 host)
8214 tramp-postfix-host-format))
8215 (when localname localname)))
8216
8217 (defun tramp-make-copy-program-file-name (vec)
8218 "Create a file name suitable to be passed to `rcp' and workalikes."
8219 (let ((user (tramp-file-name-user vec))
8220 (host (tramp-file-name-real-host vec))
8221 (localname (tramp-shell-quote-argument
8222 (tramp-file-name-localname vec))))
8223 (if (not (zerop (length user)))
8224 (format "%s@%s:%s" user host localname)
8225 (format "%s:%s" host localname))))
8226
8227 (defun tramp-method-out-of-band-p (vec size)
8228 "Return t if this is an out-of-band method, nil otherwise."
8229 (and
8230 ;; It shall be an out-of-band method.
8231 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
8232 ;; Either the file size is large enough, or (in rare cases) there
8233 ;; does not exist a remote encoding.
8234 (or (null tramp-copy-size-limit)
8235 (> size tramp-copy-size-limit)
8236 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
8237
8238 (defun tramp-local-host-p (vec)
8239 "Return t if this points to the local host, nil otherwise."
8240 ;; We cannot use `tramp-file-name-real-host'. A port is an
8241 ;; indication for an ssh tunnel or alike.
8242 (let ((host (tramp-file-name-host vec)))
8243 (and
8244 (stringp host)
8245 (string-match tramp-local-host-regexp host)
8246 ;; The method shall be applied to one of the shell file name
8247 ;; handler. `tramp-local-host-p' is also called for "smb" and
8248 ;; alike, where it must fail.
8249 (tramp-get-method-parameter
8250 (tramp-file-name-method vec) 'tramp-login-program)
8251 ;; The local temp directory must be writable for the other user.
8252 (file-writable-p
8253 (tramp-make-tramp-file-name
8254 (tramp-file-name-method vec)
8255 (tramp-file-name-user vec)
8256 host
8257 (tramp-compat-temporary-file-directory)))
8258 ;; On some systems, chown runs only for root.
8259 (or (zerop (user-uid))
8260 (zerop (tramp-get-remote-uid vec 'integer))))))
8261
8262 ;; Variables local to connection.
8263
8264 (defun tramp-get-remote-path (vec)
8265 (with-connection-property
8266 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8267 ;; cache the result for the session only. Otherwise, the result
8268 ;; is cached persistently.
8269 (if (memq 'tramp-own-remote-path tramp-remote-path)
8270 (tramp-get-connection-process vec)
8271 vec)
8272 "remote-path"
8273 (let* ((remote-path (copy-tree tramp-remote-path))
8274 (elt1 (memq 'tramp-default-remote-path remote-path))
8275 (elt2 (memq 'tramp-own-remote-path remote-path))
8276 (default-remote-path
8277 (when elt1
8278 (condition-case nil
8279 (tramp-send-command-and-read
8280 vec "echo \\\"`getconf PATH`\\\"")
8281 ;; Default if "getconf" is not available.
8282 (error
8283 (tramp-message
8284 vec 3
8285 "`getconf PATH' not successful, using default value \"%s\"."
8286 "/bin:/usr/bin")
8287 "/bin:/usr/bin"))))
8288 (own-remote-path
8289 (when elt2
8290 (condition-case nil
8291 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8292 ;; Default if "getconf" is not available.
8293 (error
8294 (tramp-message
8295 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8296 nil)))))
8297
8298 ;; Replace place holder `tramp-default-remote-path'.
8299 (when elt1
8300 (setcdr elt1
8301 (append
8302 (tramp-compat-split-string default-remote-path ":")
8303 (cdr elt1)))
8304 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8305
8306 ;; Replace place holder `tramp-own-remote-path'.
8307 (when elt2
8308 (setcdr elt2
8309 (append
8310 (tramp-compat-split-string own-remote-path ":")
8311 (cdr elt2)))
8312 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8313
8314 ;; Remove double entries.
8315 (setq elt1 remote-path)
8316 (while (consp elt1)
8317 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8318 (setcar elt2 nil))
8319 (setq elt1 (cdr elt1)))
8320
8321 ;; Remove non-existing directories.
8322 (delq
8323 nil
8324 (mapcar
8325 (lambda (x)
8326 (and
8327 (stringp x)
8328 (file-directory-p
8329 (tramp-make-tramp-file-name
8330 (tramp-file-name-method vec)
8331 (tramp-file-name-user vec)
8332 (tramp-file-name-host vec)
8333 x))
8334 x))
8335 remote-path)))))
8336
8337 (defun tramp-get-remote-tmpdir (vec)
8338 (with-connection-property vec "tmp-directory"
8339 (let ((dir (tramp-shell-quote-argument "/tmp")))
8340 (if (and (zerop
8341 (tramp-send-command-and-check
8342 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8343 (zerop
8344 (tramp-send-command-and-check
8345 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8346 dir
8347 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8348
8349 (defun tramp-get-ls-command (vec)
8350 (with-connection-property vec "ls"
8351 (tramp-message vec 5 "Finding a suitable `ls' command")
8352 (or
8353 (catch 'ls-found
8354 (dolist (cmd '("ls" "gnuls" "gls"))
8355 (let ((dl (tramp-get-remote-path vec))
8356 result)
8357 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8358 ;; Check parameters. On busybox, "ls" output coloring is
8359 ;; enabled by default sometimes. So we try to disable it
8360 ;; when possible. $LS_COLORING is not supported there.
8361 ;; Some "ls" versions are sensible wrt the order of
8362 ;; arguments, they fail when "-al" is after the
8363 ;; "--color=never" argument (for example on FreeBSD).
8364 (when (zerop (tramp-send-command-and-check
8365 vec (format "%s -lnd /" result)))
8366 (when (zerop (tramp-send-command-and-check
8367 vec (format
8368 "%s --color=never -al /dev/null" result)))
8369 (setq result (concat result " --color=never")))
8370 (throw 'ls-found result))
8371 (setq dl (cdr dl))))))
8372 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8373
8374 (defun tramp-get-ls-command-with-dired (vec)
8375 (save-match-data
8376 (with-connection-property vec "ls-dired"
8377 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8378 ;; Some "ls" versions are sensible wrt the order of arguments,
8379 ;; they fail when "-al" is after the "--dired" argument (for
8380 ;; example on FreeBSD).
8381 (zerop (tramp-send-command-and-check
8382 vec (format "%s --dired -al /dev/null"
8383 (tramp-get-ls-command vec)))))))
8384
8385 (defun tramp-get-test-command (vec)
8386 (with-connection-property vec "test"
8387 (tramp-message vec 5 "Finding a suitable `test' command")
8388 (if (zerop (tramp-send-command-and-check vec "test 0"))
8389 "test"
8390 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8391
8392 (defun tramp-get-test-nt-command (vec)
8393 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8394 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8395 ;; for otherwise the shell crashes.
8396 (with-connection-property vec "test-nt"
8397 (or
8398 (progn
8399 (tramp-send-command
8400 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8401 (with-current-buffer (tramp-get-buffer vec)
8402 (goto-char (point-min))
8403 (when (looking-at (regexp-quote tramp-end-of-output))
8404 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8405 (progn
8406 (tramp-send-command
8407 vec
8408 (format
8409 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8410 (tramp-get-test-command vec)))
8411 "tramp_test_nt %s %s"))))
8412
8413 (defun tramp-get-file-exists-command (vec)
8414 (with-connection-property vec "file-exists"
8415 (tramp-message vec 5 "Finding command to check if file exists")
8416 (tramp-find-file-exists-command vec)))
8417
8418 (defun tramp-get-remote-ln (vec)
8419 (with-connection-property vec "ln"
8420 (tramp-message vec 5 "Finding a suitable `ln' command")
8421 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8422
8423 (defun tramp-get-remote-perl (vec)
8424 (with-connection-property vec "perl"
8425 (tramp-message vec 5 "Finding a suitable `perl' command")
8426 (let ((result
8427 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8428 (tramp-find-executable
8429 vec "perl" (tramp-get-remote-path vec)))))
8430 ;; We must check also for some Perl modules.
8431 (when result
8432 (with-connection-property vec "perl-file-spec"
8433 (zerop
8434 (tramp-send-command-and-check
8435 vec (format "%s -e 'use File::Spec;'" result))))
8436 (with-connection-property vec "perl-cwd-realpath"
8437 (zerop
8438 (tramp-send-command-and-check
8439 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8440 result)))
8441
8442 (defun tramp-get-remote-stat (vec)
8443 (with-connection-property vec "stat"
8444 (tramp-message vec 5 "Finding a suitable `stat' command")
8445 (let ((result (tramp-find-executable
8446 vec "stat" (tramp-get-remote-path vec)))
8447 tmp)
8448 ;; Check whether stat(1) returns usable syntax. %s does not
8449 ;; work on older AIX systems.
8450 (when result
8451 (setq tmp
8452 ;; We don't want to display an error message.
8453 (with-temp-message (or (current-message) "")
8454 (condition-case nil
8455 (tramp-send-command-and-read
8456 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8457 (error nil))))
8458 (unless (and (listp tmp) (stringp (car tmp))
8459 (string-match "^./.$" (car tmp))
8460 (integerp (cadr tmp)))
8461 (setq result nil)))
8462 result)))
8463
8464 (defun tramp-get-remote-readlink (vec)
8465 (with-connection-property vec "readlink"
8466 (tramp-message vec 5 "Finding a suitable `readlink' command")
8467 (let ((result (tramp-find-executable
8468 vec "readlink" (tramp-get-remote-path vec))))
8469 (when (and result
8470 ;; We don't want to display an error message.
8471 (with-temp-message (or (current-message) "")
8472 (condition-case nil
8473 (zerop
8474 (tramp-send-command-and-check
8475 vec (format "%s --canonicalize-missing /" result)))
8476 (error nil))))
8477 result))))
8478
8479 (defun tramp-get-remote-trash (vec)
8480 (with-connection-property vec "trash"
8481 (tramp-message vec 5 "Finding a suitable `trash' command")
8482 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
8483
8484 (defun tramp-get-remote-id (vec)
8485 (with-connection-property vec "id"
8486 (tramp-message vec 5 "Finding POSIX `id' command")
8487 (or
8488 (catch 'id-found
8489 (let ((dl (tramp-get-remote-path vec))
8490 result)
8491 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8492 ;; Check POSIX parameter.
8493 (when (zerop (tramp-send-command-and-check
8494 vec (format "%s -u" result)))
8495 (throw 'id-found result))
8496 (setq dl (cdr dl)))))
8497 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8498
8499 (defun tramp-get-remote-uid (vec id-format)
8500 (with-connection-property vec (format "uid-%s" id-format)
8501 (let ((res (tramp-send-command-and-read
8502 vec
8503 (format "%s -u%s %s"
8504 (tramp-get-remote-id vec)
8505 (if (equal id-format 'integer) "" "n")
8506 (if (equal id-format 'integer)
8507 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8508 ;; The command might not always return a number.
8509 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8510
8511 (defun tramp-get-remote-gid (vec id-format)
8512 (with-connection-property vec (format "gid-%s" id-format)
8513 (let ((res (tramp-send-command-and-read
8514 vec
8515 (format "%s -g%s %s"
8516 (tramp-get-remote-id vec)
8517 (if (equal id-format 'integer) "" "n")
8518 (if (equal id-format 'integer)
8519 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8520 ;; The command might not always return a number.
8521 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8522
8523 (defun tramp-get-local-uid (id-format)
8524 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8525
8526 (defun tramp-get-local-gid (id-format)
8527 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8528
8529 ;; Some predefined connection properties.
8530 (defun tramp-get-inline-compress (vec prop size)
8531 "Return the compress command related to PROP.
8532 PROP is either `inline-compress' or `inline-decompress'. SIZE is
8533 the length of the file to be compressed.
8534
8535 If no corresponding command is found, nil is returned."
8536 (when (and (integerp tramp-inline-compress-start-size)
8537 (> size tramp-inline-compress-start-size))
8538 (with-connection-property vec prop
8539 (tramp-find-inline-compress vec)
8540 (tramp-get-connection-property vec prop nil))))
8541
8542 (defun tramp-get-inline-coding (vec prop size)
8543 "Return the coding command related to PROP.
8544 PROP is either `remote-encoding', `remode-decoding',
8545 `local-encoding' or `local-decoding'.
8546
8547 SIZE is the length of the file to be coded. Depending on SIZE,
8548 compression might be applied.
8549
8550 If no corresponding command is found, nil is returned.
8551 Otherwise, either a string is returned which contains a `%s' mark
8552 to be used for the respective input or output file; or a Lisp
8553 function cell is returned to be applied on a buffer."
8554 (let ((coding
8555 (with-connection-property vec prop
8556 (tramp-find-inline-encoding vec)
8557 (tramp-get-connection-property vec prop nil)))
8558 (prop1 (if (string-match "encoding" prop)
8559 "inline-compress" "inline-decompress"))
8560 compress)
8561 ;; The connection property might have been cached. So we must send
8562 ;; the script to the remote side - maybe.
8563 (when (and coding (symbolp coding) (string-match "remote" prop))
8564 (let ((name (symbol-name coding)))
8565 (while (string-match (regexp-quote "-") name)
8566 (setq name (replace-match "_" nil t name)))
8567 (tramp-maybe-send-script vec (symbol-value coding) name)
8568 (setq coding name)))
8569 (when coding
8570 ;; Check for the `compress' command.
8571 (setq compress (tramp-get-inline-compress vec prop1 size))
8572 ;; Return the value.
8573 (cond
8574 ((and compress (symbolp coding))
8575 (if (string-match "decompress" prop1)
8576 `(lambda (beg end)
8577 (,coding beg end)
8578 (let ((coding-system-for-write 'binary)
8579 (coding-system-for-read 'binary))
8580 (apply
8581 'call-process-region (point-min) (point-max)
8582 (car (split-string ,compress)) t t nil
8583 (cdr (split-string ,compress)))))
8584 `(lambda (beg end)
8585 (let ((coding-system-for-write 'binary)
8586 (coding-system-for-read 'binary))
8587 (apply
8588 'call-process-region beg end
8589 (car (split-string ,compress)) t t nil
8590 (cdr (split-string ,compress))))
8591 (,coding (point-min) (point-max)))))
8592 ((symbolp coding)
8593 coding)
8594 ((and compress (string-match "decoding" prop))
8595 (format "(%s | %s >%%s)" coding compress))
8596 (compress
8597 (format "(%s <%%s | %s)" compress coding))
8598 ((string-match "decoding" prop)
8599 (format "%s >%%s" coding))
8600 (t
8601 (format "%s <%%s" coding))))))
8602
8603 (defun tramp-get-method-parameter (method param)
8604 "Return the method parameter PARAM.
8605 If the `tramp-methods' entry does not exist, return nil."
8606 (let ((entry (assoc param (assoc method tramp-methods))))
8607 (when entry (cadr entry))))
8608
8609 ;; Auto saving to a special directory.
8610
8611 (defun tramp-exists-file-name-handler (operation &rest args)
8612 "Check, whether OPERATION runs a file name handler."
8613 ;; The file name handler is determined on base of either an
8614 ;; argument, `buffer-file-name', or `default-directory'.
8615 (condition-case nil
8616 (let* ((buffer-file-name "/")
8617 (default-directory "/")
8618 (fnha file-name-handler-alist)
8619 (check-file-name-operation operation)
8620 (file-name-handler-alist
8621 (list
8622 (cons "/"
8623 (lambda (operation &rest args)
8624 "Returns OPERATION if it is the one to be checked."
8625 (if (equal check-file-name-operation operation)
8626 operation
8627 (let ((file-name-handler-alist fnha))
8628 (apply operation args))))))))
8629 (equal (apply operation args) operation))
8630 (error nil)))
8631
8632 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8633 (defadvice make-auto-save-file-name
8634 (around tramp-advice-make-auto-save-file-name () activate)
8635 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8636 (if (tramp-tramp-file-p (buffer-file-name))
8637 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8638 ;; directly, because this would bypass the locking mechanism.
8639 (setq ad-return-value
8640 (tramp-file-name-handler 'make-auto-save-file-name))
8641 ad-do-it))
8642 (add-hook
8643 'tramp-unload-hook
8644 (lambda ()
8645 (ad-remove-advice
8646 'make-auto-save-file-name
8647 'around 'tramp-advice-make-auto-save-file-name)
8648 (ad-activate 'make-auto-save-file-name))))
8649
8650 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8651 ;; umask. This is a security threat.
8652
8653 (defun tramp-set-auto-save-file-modes ()
8654 "Set permissions of autosaved remote files to the original permissions."
8655 (let ((bfn (buffer-file-name)))
8656 (when (and (tramp-tramp-file-p bfn)
8657 (buffer-modified-p)
8658 (stringp buffer-auto-save-file-name)
8659 (not (equal bfn buffer-auto-save-file-name)))
8660 (unless (file-exists-p buffer-auto-save-file-name)
8661 (write-region "" nil buffer-auto-save-file-name))
8662 ;; Permissions should be set always, because there might be an old
8663 ;; auto-saved file belonging to another original file. This could
8664 ;; be a security threat.
8665 (set-file-modes buffer-auto-save-file-name
8666 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8667
8668 (unless (and (featurep 'xemacs)
8669 (= emacs-major-version 21)
8670 (> emacs-minor-version 4))
8671 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8672 (add-hook 'tramp-unload-hook
8673 (lambda ()
8674 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8675
8676 (defun tramp-subst-strs-in-string (alist string)
8677 "Replace all occurrences of the string FROM with TO in STRING.
8678 ALIST is of the form ((FROM . TO) ...)."
8679 (save-match-data
8680 (while alist
8681 (let* ((pr (car alist))
8682 (from (car pr))
8683 (to (cdr pr)))
8684 (while (string-match (regexp-quote from) string)
8685 (setq string (replace-match to t t string)))
8686 (setq alist (cdr alist))))
8687 string))
8688
8689 ;; ------------------------------------------------------------
8690 ;; -- Compatibility functions section --
8691 ;; ------------------------------------------------------------
8692
8693 (defun tramp-read-passwd (proc &optional prompt)
8694 "Read a password from user (compat function).
8695 Consults the auth-source package.
8696 Invokes `password-read' if available, `read-passwd' else."
8697 (let* ((key (tramp-make-tramp-file-name
8698 tramp-current-method tramp-current-user
8699 tramp-current-host ""))
8700 (pw-prompt
8701 (or prompt
8702 (with-current-buffer (process-buffer proc)
8703 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8704 (format "%s for %s " (capitalize (match-string 1)) key)))))
8705 (with-parsed-tramp-file-name key nil
8706 (prog1
8707 (or
8708 ;; See if auth-sources contains something useful, if it's bound.
8709 (and (boundp 'auth-sources)
8710 (tramp-get-connection-property v "first-password-request" nil)
8711 ;; Try with Tramp's current method.
8712 (tramp-compat-funcall
8713 'auth-source-user-or-password
8714 "password" tramp-current-host tramp-current-method))
8715 ;; Try the password cache.
8716 (when (functionp 'password-read)
8717 (unless (tramp-get-connection-property
8718 v "first-password-request" nil)
8719 (tramp-compat-funcall 'password-cache-remove key))
8720 (let ((password
8721 (tramp-compat-funcall 'password-read pw-prompt key)))
8722 (tramp-compat-funcall 'password-cache-add key password)
8723 password))
8724 ;; Else, get the password interactively.
8725 (read-passwd pw-prompt))
8726 (tramp-set-connection-property v "first-password-request" nil)))))
8727
8728 (defun tramp-clear-passwd (vec)
8729 "Clear password cache for connection related to VEC."
8730 (tramp-compat-funcall
8731 'password-cache-remove
8732 (tramp-make-tramp-file-name
8733 (tramp-file-name-method vec)
8734 (tramp-file-name-user vec)
8735 (tramp-file-name-host vec)
8736 "")))
8737
8738 ;; Snarfed code from time-date.el and parse-time.el
8739
8740 (defconst tramp-half-a-year '(241 17024)
8741 "Evaluated by \"(days-to-time 183)\".")
8742
8743 (defconst tramp-parse-time-months
8744 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8745 ("apr" . 4) ("may" . 5) ("jun" . 6)
8746 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8747 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8748 "Alist mapping month names to integers.")
8749
8750 (defun tramp-time-less-p (t1 t2)
8751 "Say whether time value T1 is less than time value T2."
8752 (unless t1 (setq t1 '(0 0)))
8753 (unless t2 (setq t2 '(0 0)))
8754 (or (< (car t1) (car t2))
8755 (and (= (car t1) (car t2))
8756 (< (nth 1 t1) (nth 1 t2)))))
8757
8758 (defun tramp-time-subtract (t1 t2)
8759 "Subtract two time values.
8760 Return the difference in the format of a time value."
8761 (unless t1 (setq t1 '(0 0)))
8762 (unless t2 (setq t2 '(0 0)))
8763 (let ((borrow (< (cadr t1) (cadr t2))))
8764 (list (- (car t1) (car t2) (if borrow 1 0))
8765 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8766
8767 (defun tramp-time-diff (t1 t2)
8768 "Return the difference between the two times, in seconds.
8769 T1 and T2 are time values (as returned by `current-time' for example)."
8770 ;; Pacify byte-compiler with `symbol-function'.
8771 (cond ((and (fboundp 'subtract-time)
8772 (fboundp 'float-time))
8773 (tramp-compat-funcall
8774 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
8775 ((and (fboundp 'subtract-time)
8776 (fboundp 'time-to-seconds))
8777 (tramp-compat-funcall
8778 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
8779 ((fboundp 'itimer-time-difference)
8780 (tramp-compat-funcall
8781 'itimer-time-difference
8782 (if (< (length t1) 3) (append t1 '(0)) t1)
8783 (if (< (length t2) 3) (append t2 '(0)) t2)))
8784 (t
8785 (let ((time (tramp-time-subtract t1 t2)))
8786 (+ (* (car time) 65536.0)
8787 (cadr time)
8788 (/ (or (nth 2 time) 0) 1000000.0))))))
8789
8790 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8791 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8792 EOL-TYPE can be one of `dos', `unix', or `mac'."
8793 (cond ((fboundp 'coding-system-change-eol-conversion)
8794 (tramp-compat-funcall
8795 'coding-system-change-eol-conversion coding-system eol-type))
8796 ((fboundp 'subsidiary-coding-system)
8797 (tramp-compat-funcall
8798 'subsidiary-coding-system coding-system
8799 (cond ((eq eol-type 'dos) 'crlf)
8800 ((eq eol-type 'unix) 'lf)
8801 ((eq eol-type 'mac) 'cr)
8802 (t
8803 (error "Unknown EOL-TYPE `%s', must be %s"
8804 eol-type
8805 "`dos', `unix', or `mac'")))))
8806 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8807
8808 (defun tramp-set-process-query-on-exit-flag (process flag)
8809 "Specify if query is needed for process when Emacs is exited.
8810 If the second argument flag is non-nil, Emacs will query the user before
8811 exiting if process is running."
8812 (if (fboundp 'set-process-query-on-exit-flag)
8813 (tramp-compat-funcall 'set-process-query-on-exit-flag process flag)
8814 (tramp-compat-funcall 'process-kill-without-query process flag)))
8815
8816
8817 ;; ------------------------------------------------------------
8818 ;; -- Kludges section --
8819 ;; ------------------------------------------------------------
8820
8821 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8822 ;; does not deal well with newline characters. Newline is replaced by
8823 ;; backslash newline. But if, say, the string `a backslash newline b'
8824 ;; is passed to a shell, the shell will expand this into "ab",
8825 ;; completely omitting the newline. This is not what was intended.
8826 ;; It does not appear to be possible to make the function
8827 ;; `shell-quote-argument' work with newlines without making it
8828 ;; dependent on the shell used. But within this package, we know that
8829 ;; we will always use a Bourne-like shell, so we use an approach which
8830 ;; groks newlines.
8831 ;;
8832 ;; The approach is simple: we call `shell-quote-argument', then
8833 ;; massage the newline part of the result.
8834 ;;
8835 ;; This function should produce a string which is grokked by a Unix
8836 ;; shell, even if the Emacs is running on Windows. Since this is the
8837 ;; kludges section, we bind `system-type' in such a way that
8838 ;; `shell-quote-arguments' behaves as if on Unix.
8839 ;;
8840 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8841 ;; function to work with Bourne-like shells.
8842 ;;
8843 ;; CCC: This function should be rewritten so that
8844 ;; `shell-quote-argument' is not used. This way, we are safe from
8845 ;; changes in `shell-quote-argument'.
8846 (defun tramp-shell-quote-argument (s)
8847 "Similar to `shell-quote-argument', but groks newlines.
8848 Only works for Bourne-like shells."
8849 (let ((system-type 'not-windows))
8850 (save-match-data
8851 (let ((result (shell-quote-argument s))
8852 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8853 (when (and (>= (length result) 2)
8854 (string= (substring result 0 2) "\\~"))
8855 (setq result (substring result 1)))
8856 (while (string-match nl result)
8857 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8858 t t result)))
8859 result))))
8860
8861 ;; Checklist for `tramp-unload-hook'
8862 ;; - Unload all `tramp-*' packages
8863 ;; - Reset `file-name-handler-alist'
8864 ;; - Cleanup hooks where Tramp functions are in
8865 ;; - Cleanup advised functions
8866 ;; - Cleanup autoloads
8867 ;;;###autoload
8868 (defun tramp-unload-tramp ()
8869 "Discard Tramp from loading remote files."
8870 (interactive)
8871 ;; When Tramp is not loaded yet, its autoloads are still active.
8872 (tramp-unload-file-name-handlers)
8873 ;; ange-ftp settings must be enabled.
8874 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
8875 ;; Maybe its not loaded yet.
8876 (condition-case nil
8877 (unload-feature 'tramp 'force)
8878 (error nil)))
8879
8880 (when (and load-in-progress
8881 (string-match "Loading tramp..." (or (current-message) "")))
8882 (message "Loading tramp...done"))
8883
8884 (provide 'tramp)
8885
8886 ;;; TODO:
8887
8888 ;; * Handle nonlocal exits such as C-g.
8889 ;; * But it would probably be better to use with-local-quit at the
8890 ;; place where it's actually needed: around any potentially
8891 ;; indefinitely blocking piece of code. In this case it would be
8892 ;; within Tramp around one of its calls to accept-process-output (or
8893 ;; around one of the loops that calls accept-process-output)
8894 ;; (Stefan Monnier).
8895 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8896 ;; `shell-quote-argument'.
8897 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8898 ;; by the files in that directory. Add this here.
8899 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8900 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8901 ;; * Don't use globbing for directories with many files, as this is
8902 ;; likely to produce long command lines, and some shells choke on
8903 ;; long command lines.
8904 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8905 ;; * abbreviate-file-name
8906 ;; * Better error checking. At least whenever we see something
8907 ;; strange when doing zerop, we should kill the process and start
8908 ;; again. (Greg Stark)
8909 ;; * Remove unneeded parameters from methods.
8910 ;; * Make it work for different encodings, and for different file name
8911 ;; encodings, too. (Daniel Pittman)
8912 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8913 ;; then look if it's the right version (with `perl -v').
8914 ;; * When editing a remote CVS controlled file as a different user, VC
8915 ;; gets confused about the file locking status. Try to find out why
8916 ;; the workaround doesn't work.
8917 ;; * Username and hostname completion.
8918 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8919 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8920 ;; Code is nearly identical.
8921 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8922 ;; until the last but one hop via `start-file-process'. Apply it
8923 ;; also for ftp and smb.
8924 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8925 ;; some shell with root priviledges, it would be nice if I could
8926 ;; just call
8927 ;; trampclient filename.c
8928 ;; as an editor, and the _current_ shell would connect to an Emacs
8929 ;; server and would be used in an existing non-priviledged Emacs
8930 ;; session for doing the editing in question.
8931 ;; That way, I need not tell Emacs my password again and be afraid
8932 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8933 ;; once display a just typed password in the context of a keyboard
8934 ;; sequence prompt for a question immediately following in a shell
8935 ;; script run within Emacs -- nasty).
8936 ;; And if I have some ssh session running to a different computer,
8937 ;; having the possibility of passing a local file there to a local
8938 ;; Emacs session (in case I can arrange for a connection back) would
8939 ;; be nice.
8940 ;; Likely the corresponding Tramp server should not allow the
8941 ;; equivalent of the emacsclient -eval option in order to make this
8942 ;; reasonably unproblematic. And maybe trampclient should have some
8943 ;; way of passing credentials, like by using an SSL socket or
8944 ;; something. (David Kastrup)
8945 ;; * Reconnect directly to a compliant shell without first going
8946 ;; through the user's default shell. (Pete Forman)
8947 ;; * Make `tramp-default-user' obsolete.
8948 ;; * How can I interrupt the remote process with a signal
8949 ;; (interrupt-process seems not to work)? (Markus Triska)
8950 ;; * Avoid the local shell entirely for starting remote processes. If
8951 ;; so, I think even a signal, when delivered directly to the local
8952 ;; SSH instance, would correctly be propagated to the remote process
8953 ;; automatically; possibly SSH would have to be started with
8954 ;; "-t". (Markus Triska)
8955 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8956 ;; isn't on the remote host. (Mark A. Hershberger)
8957 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8958 ;; * Implement a general server-local-variable mechanism, as there are
8959 ;; probably other variables that need different values for different
8960 ;; servers too. The user could then configure a variable (such as
8961 ;; tramp-server-local-variable-alist) to define any such variables
8962 ;; that they need to, which would then be let bound as appropriate
8963 ;; in tramp functions. (Jason Rumney)
8964 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8965 ;; rsync).
8966 ;; * Keep a second connection open for out-of-band methods like scp or
8967 ;; rsync.
8968 ;; * IMHO, it's a drawback that currently Tramp doesn't support
8969 ;; Unicode in Dired file names by default. Is it possible to
8970 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8971 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
8972 ;; expects only English messages? (Juri Linkov)
8973 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8974 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
8975 ;; * Try telnet+curl as new method. It might be useful for busybox,
8976 ;; without built-in uuencode/uudecode.
8977 ;; * Let `shell-dynamic-complete-*' and `comint-dynamic-complete' work
8978 ;; on remote hosts.
8979 ;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
8980
8981 ;; Functions for file-name-handler-alist:
8982 ;; diff-latest-backup-file -- in diff.el
8983
8984 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8985 ;;; tramp.el ends here
8986
8987 ;; Local Variables:
8988 ;; mode: Emacs-Lisp
8989 ;; coding: utf-8
8990 ;; End: