]> code.delx.au - gnu-emacs/blob - lisp/net/tramp.el
Merge from trunk
[gnu-emacs] / lisp / net / tramp.el
1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 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 while read file; 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. Input shall be read via
2002 here-document, otherwise the command could exceed maximum length
2003 of command line.")
2004
2005 (defconst tramp-file-mode-type-map
2006 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
2007 (1 . "p") ; fifo
2008 (2 . "c") ; character device
2009 (3 . "m") ; multiplexed character device (v7)
2010 (4 . "d") ; directory
2011 (5 . "?") ; Named special file (XENIX)
2012 (6 . "b") ; block device
2013 (7 . "?") ; multiplexed block device (v7)
2014 (8 . "-") ; regular file
2015 (9 . "n") ; network special file (HP-UX)
2016 (10 . "l") ; symlink
2017 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
2018 (12 . "s") ; socket
2019 (13 . "D") ; door special (Solaris)
2020 (14 . "w")) ; whiteout (BSD)
2021 "A list of file types returned from the `stat' system call.
2022 This is used to map a mode number to a permission string.")
2023
2024 ;; New handlers should be added here. The following operations can be
2025 ;; handled using the normal primitives: file-name-sans-versions,
2026 ;; get-file-buffer.
2027 (defconst tramp-file-name-handler-alist
2028 '((load . tramp-handle-load)
2029 (make-symbolic-link . tramp-handle-make-symbolic-link)
2030 (file-name-as-directory . tramp-handle-file-name-as-directory)
2031 (file-name-directory . tramp-handle-file-name-directory)
2032 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
2033 (file-truename . tramp-handle-file-truename)
2034 (file-exists-p . tramp-handle-file-exists-p)
2035 (file-directory-p . tramp-handle-file-directory-p)
2036 (file-executable-p . tramp-handle-file-executable-p)
2037 (file-readable-p . tramp-handle-file-readable-p)
2038 (file-regular-p . tramp-handle-file-regular-p)
2039 (file-symlink-p . tramp-handle-file-symlink-p)
2040 (file-writable-p . tramp-handle-file-writable-p)
2041 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
2042 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
2043 (file-attributes . tramp-handle-file-attributes)
2044 (file-modes . tramp-handle-file-modes)
2045 (directory-files . tramp-handle-directory-files)
2046 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
2047 (file-name-all-completions . tramp-handle-file-name-all-completions)
2048 (file-name-completion . tramp-handle-file-name-completion)
2049 (add-name-to-file . tramp-handle-add-name-to-file)
2050 (copy-file . tramp-handle-copy-file)
2051 (copy-directory . tramp-handle-copy-directory)
2052 (rename-file . tramp-handle-rename-file)
2053 (set-file-modes . tramp-handle-set-file-modes)
2054 (set-file-times . tramp-handle-set-file-times)
2055 (make-directory . tramp-handle-make-directory)
2056 (delete-directory . tramp-handle-delete-directory)
2057 (delete-file . tramp-handle-delete-file)
2058 (directory-file-name . tramp-handle-directory-file-name)
2059 ;; `executable-find' is not official yet.
2060 (executable-find . tramp-handle-executable-find)
2061 (start-file-process . tramp-handle-start-file-process)
2062 (process-file . tramp-handle-process-file)
2063 (shell-command . tramp-handle-shell-command)
2064 (insert-directory . tramp-handle-insert-directory)
2065 (expand-file-name . tramp-handle-expand-file-name)
2066 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2067 (file-local-copy . tramp-handle-file-local-copy)
2068 (file-remote-p . tramp-handle-file-remote-p)
2069 (insert-file-contents . tramp-handle-insert-file-contents)
2070 (insert-file-contents-literally
2071 . tramp-handle-insert-file-contents-literally)
2072 (write-region . tramp-handle-write-region)
2073 (find-backup-file-name . tramp-handle-find-backup-file-name)
2074 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2075 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2076 (dired-compress-file . tramp-handle-dired-compress-file)
2077 (dired-recursive-delete-directory
2078 . tramp-handle-dired-recursive-delete-directory)
2079 (dired-uncache . tramp-handle-dired-uncache)
2080 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2081 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2082 (file-selinux-context . tramp-handle-file-selinux-context)
2083 (set-file-selinux-context . tramp-handle-set-file-selinux-context)
2084 (vc-registered . tramp-handle-vc-registered))
2085 "Alist of handler functions.
2086 Operations not mentioned here will be handled by the normal Emacs functions.")
2087
2088 ;; Handlers for partial Tramp file names. For Emacs just
2089 ;; `file-name-all-completions' is needed.
2090 ;;;###autoload
2091 (defconst tramp-completion-file-name-handler-alist
2092 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2093 (file-name-completion . tramp-completion-handle-file-name-completion))
2094 "Alist of completion handler functions.
2095 Used for file names matching `tramp-file-name-regexp'. Operations not
2096 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2097 normal Emacs functions.")
2098
2099 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2100 (defvar tramp-foreign-file-name-handler-alist
2101 ;; (identity . tramp-sh-file-name-handler) should always be the last
2102 ;; entry, because `identity' always matches.
2103 '((identity . tramp-sh-file-name-handler))
2104 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2105 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2106 calling HANDLER.")
2107
2108 ;;; Internal functions which must come first:
2109
2110 (defsubst tramp-debug-message (vec fmt-string &rest args)
2111 "Append message to debug buffer.
2112 Message is formatted with FMT-STRING as control string and the remaining
2113 ARGS to actually emit the message (if applicable)."
2114 (when (get-buffer (tramp-buffer-name vec))
2115 (with-current-buffer (tramp-get-debug-buffer vec)
2116 (goto-char (point-max))
2117 ;; Headline.
2118 (when (bobp)
2119 (insert
2120 (format
2121 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2122 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2123 emacs-version tramp-version)))
2124 (unless (bolp)
2125 (insert "\n"))
2126 ;; Timestamp.
2127 (let ((now (current-time)))
2128 (insert (format-time-string "%T." now))
2129 (insert (format "%06d " (nth 2 now))))
2130 ;; Calling function.
2131 (let ((btn 1) btf fn)
2132 (while (not fn)
2133 (setq btf (nth 1 (backtrace-frame btn)))
2134 (if (not btf)
2135 (setq fn "")
2136 (when (symbolp btf)
2137 (setq fn (symbol-name btf))
2138 (unless (and (string-match "^tramp" fn)
2139 (not (string-match
2140 "^tramp\\(-debug\\)?\\(-message\\|-error\\|-compat-funcall\\)$"
2141 fn)))
2142 (setq fn nil)))
2143 (setq btn (1+ btn))))
2144 ;; The following code inserts filename and line number.
2145 ;; Should be deactivated by default, because it is time
2146 ;; consuming.
2147 ; (let ((ffn (find-function-noselect (intern fn))))
2148 ; (insert
2149 ; (format
2150 ; "%s:%d: "
2151 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2152 ; (with-current-buffer (car ffn)
2153 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2154 (insert (format "%s " fn)))
2155 ;; The message.
2156 (insert (apply 'format fmt-string args)))))
2157
2158 (defvar tramp-message-show-message t
2159 "Show Tramp message in the minibuffer.
2160 This variable is used to disable messages from `tramp-error'.
2161 The messages are visible anyway, because an error is raised.")
2162
2163 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2164 "Emit a message depending on verbosity level.
2165 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2166 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2167 less than LEVEL. The message is emitted only if `tramp-verbose' is
2168 greater than or equal to LEVEL.
2169
2170 The message is also logged into the debug buffer when `tramp-verbose'
2171 is greater than or equal 4.
2172
2173 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2174 control string and the remaining ARGS to actually emit the message (if
2175 applicable)."
2176 (condition-case nil
2177 (when (<= level tramp-verbose)
2178 ;; Match data must be preserved!
2179 (save-match-data
2180 ;; Display only when there is a minimum level.
2181 (when (and tramp-message-show-message (<= level 3))
2182 (apply 'message
2183 (concat
2184 (cond
2185 ((= level 0) "")
2186 ((= level 1) "")
2187 ((= level 2) "Warning: ")
2188 (t "Tramp: "))
2189 fmt-string)
2190 args))
2191 ;; Log only when there is a minimum level.
2192 (when (>= tramp-verbose 4)
2193 (when (and vec-or-proc
2194 (processp vec-or-proc)
2195 (buffer-name (process-buffer vec-or-proc)))
2196 (with-current-buffer (process-buffer vec-or-proc)
2197 ;; Translate proc to vec.
2198 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2199 (when (and vec-or-proc (vectorp vec-or-proc))
2200 (apply 'tramp-debug-message
2201 vec-or-proc
2202 (concat (format "(%d) # " level) fmt-string)
2203 args)))))
2204 ;; Suppress all errors.
2205 (error nil)))
2206
2207 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2208 "Emit an error.
2209 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2210 signal identifier to be raised, remaining args passed to
2211 `tramp-message'. Finally, signal SIGNAL is raised."
2212 (let (tramp-message-show-message)
2213 (tramp-message
2214 vec-or-proc 1 "%s"
2215 (error-message-string
2216 (list signal
2217 (get signal 'error-message)
2218 (apply 'format fmt-string args))))
2219 (signal signal (list (apply 'format fmt-string args)))))
2220
2221 (defsubst tramp-error-with-buffer
2222 (buffer vec-or-proc signal fmt-string &rest args)
2223 "Emit an error, and show BUFFER.
2224 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2225 an input event arrives. The other arguments are passed to `tramp-error'."
2226 (save-window-excursion
2227 (unwind-protect
2228 (apply 'tramp-error vec-or-proc signal fmt-string args)
2229 (when (and vec-or-proc
2230 (not (zerop tramp-verbose))
2231 (not (tramp-completion-mode-p)))
2232 (let ((enable-recursive-minibuffers t))
2233 (pop-to-buffer
2234 (or (and (bufferp buffer) buffer)
2235 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2236 (tramp-get-buffer vec-or-proc)))
2237 (sit-for 30))))))
2238
2239 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2240 "Parse a Tramp filename and make components available in the body.
2241
2242 First arg FILENAME is evaluated and dissected into its components.
2243 Second arg VAR is a symbol. It is used as a variable name to hold
2244 the filename structure. It is also used as a prefix for the variables
2245 holding the components. For example, if VAR is the symbol `foo', then
2246 `foo' will be bound to the whole structure, `foo-method' will be bound to
2247 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2248
2249 Remaining args are Lisp expressions to be evaluated (inside an implicit
2250 `progn').
2251
2252 If VAR is nil, then we bind `v' to the structure and `method', `user',
2253 `host', `localname' to the components."
2254 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2255 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2256 (tramp-file-name-method ,(or var 'v)))
2257 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2258 (tramp-file-name-user ,(or var 'v)))
2259 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2260 (tramp-file-name-host ,(or var 'v)))
2261 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2262 (tramp-file-name-localname ,(or var 'v))))
2263 ,@body))
2264
2265 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2266 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2267 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2268
2269 (defmacro with-file-property (vec file property &rest body)
2270 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2271 FILE must be a local file name on a connection identified via VEC."
2272 `(if (file-name-absolute-p ,file)
2273 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2274 (when (eq value 'undef)
2275 ;; We cannot pass @body as parameter to
2276 ;; `tramp-set-file-property' because it mangles our
2277 ;; debug messages.
2278 (setq value (progn ,@body))
2279 (tramp-set-file-property ,vec ,file ,property value))
2280 value)
2281 ,@body))
2282
2283 (put 'with-file-property 'lisp-indent-function 3)
2284 (put 'with-file-property 'edebug-form-spec t)
2285 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2286
2287 (defmacro with-connection-property (key property &rest body)
2288 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
2289 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2290 (when (eq value 'undef)
2291 ;; We cannot pass ,@body as parameter to
2292 ;; `tramp-set-connection-property' because it mangles our debug
2293 ;; messages.
2294 (setq value (progn ,@body))
2295 (tramp-set-connection-property ,key ,property value))
2296 value))
2297
2298 (put 'with-connection-property 'lisp-indent-function 2)
2299 (put 'with-connection-property 'edebug-form-spec t)
2300 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2301
2302 (defun tramp-progress-reporter-update (reporter &optional value)
2303 (let* ((parameters (cdr reporter))
2304 (message (aref parameters 3)))
2305 (when (string-match message (or (current-message) ""))
2306 (funcall 'progress-reporter-update reporter value))))
2307
2308 (defmacro with-progress-reporter (vec level message &rest body)
2309 "Executes BODY, spinning a progress reporter with MESSAGE.
2310 If LEVEL does not fit for visible messages, or if this is a
2311 nested call of the macro, there are only traces without a visible
2312 progress reporter."
2313 `(let (pr tm)
2314 (tramp-message ,vec ,level "%s..." ,message)
2315 ;; We start a pulsing progress reporter after 3 seconds. Feature
2316 ;; introduced in Emacs 24.1.
2317 (when (and tramp-message-show-message
2318 ;; Display only when there is a minimum level.
2319 (<= ,level (min tramp-verbose 3)))
2320 (condition-case nil
2321 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
2322 tm (when pr
2323 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))
2324 (error nil)))
2325 (unwind-protect
2326 ;; Execute the body. Unset `tramp-message-show-message' when
2327 ;; the timer object is created, in order to suppress
2328 ;; concurrent timers.
2329 (let ((tramp-message-show-message
2330 (and tramp-message-show-message (not tm))))
2331 ,@body)
2332 ;; Stop progress reporter.
2333 (if tm (tramp-compat-funcall 'cancel-timer tm))
2334 (tramp-message ,vec ,level "%s...done" ,message))))
2335
2336 (put 'with-progress-reporter 'lisp-indent-function 3)
2337 (put 'with-progress-reporter 'edebug-form-spec t)
2338 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
2339
2340 (eval-and-compile ;; Silence compiler.
2341 (if (memq system-type '(cygwin windows-nt))
2342 (defun tramp-drop-volume-letter (name)
2343 "Cut off unnecessary drive letter from file NAME.
2344 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2345 locally on a remote file name. When the local system is a W32 system
2346 but the remote system is Unix, this introduces a superfluous drive
2347 letter into the file name. This function removes it."
2348 (save-match-data
2349 (if (string-match tramp-root-regexp name)
2350 (replace-match "/" nil t name)
2351 name)))
2352
2353 (defalias 'tramp-drop-volume-letter 'identity)))
2354
2355 (defsubst tramp-make-tramp-temp-file (vec)
2356 "Create a temporary file on the remote host identified by VEC.
2357 Return the local name of the temporary file."
2358 (let ((prefix
2359 (tramp-make-tramp-file-name
2360 (tramp-file-name-method vec)
2361 (tramp-file-name-user vec)
2362 (tramp-file-name-host vec)
2363 (tramp-drop-volume-letter
2364 (expand-file-name
2365 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2366 result)
2367 (while (not result)
2368 ;; `make-temp-file' would be the natural choice for
2369 ;; implementation. But it calls `write-region' internally,
2370 ;; which also needs a temporary file - we would end in an
2371 ;; infinite loop.
2372 (setq result (make-temp-name prefix))
2373 (if (file-exists-p result)
2374 (setq result nil)
2375 ;; This creates the file by side effect.
2376 (set-file-times result)
2377 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2378
2379 ;; Return the local part.
2380 (with-parsed-tramp-file-name result nil localname)))
2381
2382
2383 ;;; Config Manipulation Functions:
2384
2385 (defun tramp-set-completion-function (method function-list)
2386 "Sets the list of completion functions for METHOD.
2387 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2388 The FUNCTION is intended to parse FILE according its syntax.
2389 It might be a predefined FUNCTION, or a user defined FUNCTION.
2390 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2391 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2392 and `tramp-parse-netrc'.
2393
2394 Example:
2395
2396 (tramp-set-completion-function
2397 \"ssh\"
2398 '((tramp-parse-sconfig \"/etc/ssh_config\")
2399 (tramp-parse-sconfig \"~/.ssh/config\")))"
2400
2401 (let ((r function-list)
2402 (v function-list))
2403 (setq tramp-completion-function-alist
2404 (delete (assoc method tramp-completion-function-alist)
2405 tramp-completion-function-alist))
2406
2407 (while v
2408 ;; Remove double entries.
2409 (when (member (car v) (cdr v))
2410 (setcdr v (delete (car v) (cdr v))))
2411 ;; Check for function and file or registry key.
2412 (unless (and (functionp (nth 0 (car v)))
2413 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2414 ;; Windows registry.
2415 (and (memq system-type '(cygwin windows-nt))
2416 (zerop
2417 (tramp-local-call-process
2418 "reg" nil nil nil "query" (nth 1 (car v)))))
2419 ;; Configuration file.
2420 (file-exists-p (nth 1 (car v)))))
2421 (setq r (delete (car v) r)))
2422 (setq v (cdr v)))
2423
2424 (when r
2425 (add-to-list 'tramp-completion-function-alist
2426 (cons method r)))))
2427
2428 (defun tramp-get-completion-function (method)
2429 "Returns a list of completion functions for METHOD.
2430 For definition of that list see `tramp-set-completion-function'."
2431 (cons
2432 ;; Hosts visited once shall be remembered.
2433 `(tramp-parse-connection-properties ,method)
2434 ;; The method related defaults.
2435 (cdr (assoc method tramp-completion-function-alist))))
2436
2437
2438 ;;; Fontification of `read-file-name':
2439
2440 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2441 (defvar tramp-rfn-eshadow-overlay)
2442 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2443
2444 (defun tramp-rfn-eshadow-setup-minibuffer ()
2445 "Set up a minibuffer for `file-name-shadow-mode'.
2446 Adds another overlay hiding filename parts according to Tramp's
2447 special handling of `substitute-in-file-name'."
2448 (when (symbol-value 'minibuffer-completing-file-name)
2449 (setq tramp-rfn-eshadow-overlay
2450 (tramp-compat-funcall
2451 'make-overlay
2452 (tramp-compat-funcall 'minibuffer-prompt-end)
2453 (tramp-compat-funcall 'minibuffer-prompt-end)))
2454 ;; Copy rfn-eshadow-overlay properties.
2455 (let ((props (tramp-compat-funcall
2456 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
2457 (while props
2458 (tramp-compat-funcall
2459 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2460
2461 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2462 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2463 'tramp-rfn-eshadow-setup-minibuffer)
2464 (add-hook 'tramp-unload-hook
2465 (lambda ()
2466 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2467 'tramp-rfn-eshadow-setup-minibuffer))))
2468
2469 (defconst tramp-rfn-eshadow-update-overlay-regexp
2470 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2471
2472 (defun tramp-rfn-eshadow-update-overlay ()
2473 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2474 This is intended to be used as a minibuffer `post-command-hook' for
2475 `file-name-shadow-mode'; the minibuffer should have already
2476 been set up by `rfn-eshadow-setup-minibuffer'."
2477 ;; In remote files name, there is a shadowing just for the local part.
2478 (let ((end (or (tramp-compat-funcall
2479 'overlay-end (symbol-value 'rfn-eshadow-overlay))
2480 (tramp-compat-funcall 'minibuffer-prompt-end))))
2481 (when
2482 (file-remote-p
2483 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
2484 (save-excursion
2485 (save-restriction
2486 (narrow-to-region
2487 (1+ (or (string-match
2488 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2489 end))
2490 (point-max))
2491 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2492 (rfn-eshadow-update-overlay-hook nil))
2493 (tramp-compat-funcall
2494 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
2495 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
2496
2497 (when (boundp 'rfn-eshadow-update-overlay-hook)
2498 (add-hook 'rfn-eshadow-update-overlay-hook
2499 'tramp-rfn-eshadow-update-overlay)
2500 (add-hook 'tramp-unload-hook
2501 (lambda ()
2502 (remove-hook 'rfn-eshadow-update-overlay-hook
2503 'tramp-rfn-eshadow-update-overlay))))
2504
2505
2506 ;;; Integration of eshell.el:
2507
2508 (eval-when-compile
2509 (defvar eshell-path-env))
2510
2511 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2512 ;; when `default-directory' points to another host.
2513 (defun tramp-eshell-directory-change ()
2514 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2515 (setq eshell-path-env
2516 (if (file-remote-p default-directory)
2517 (with-parsed-tramp-file-name default-directory nil
2518 (mapconcat
2519 'identity
2520 (tramp-get-remote-path v)
2521 ":"))
2522 (getenv "PATH"))))
2523
2524 (eval-after-load "esh-util"
2525 '(progn
2526 (tramp-eshell-directory-change)
2527 (add-hook 'eshell-directory-change-hook
2528 'tramp-eshell-directory-change)
2529 (add-hook 'tramp-unload-hook
2530 (lambda ()
2531 (remove-hook 'eshell-directory-change-hook
2532 'tramp-eshell-directory-change)))))
2533
2534
2535 ;;; File Name Handler Functions:
2536
2537 (defun tramp-handle-make-symbolic-link
2538 (filename linkname &optional ok-if-already-exists)
2539 "Like `make-symbolic-link' for Tramp files.
2540 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2541 the symlink. If LINKNAME is a Tramp file, only the localname component is
2542 used as the target of the symlink.
2543
2544 If LINKNAME is a Tramp file and the localname component is relative, then
2545 it is expanded first, before the localname component is taken. Note that
2546 this can give surprising results if the user/host for the source and
2547 target of the symlink differ."
2548 (with-parsed-tramp-file-name linkname l
2549 (let ((ln (tramp-get-remote-ln l))
2550 (cwd (tramp-run-real-handler
2551 'file-name-directory (list l-localname))))
2552 (unless ln
2553 (tramp-error
2554 l 'file-error
2555 "Making a symbolic link. ln(1) does not exist on the remote host."))
2556
2557 ;; Do the 'confirm if exists' thing.
2558 (when (file-exists-p linkname)
2559 ;; What to do?
2560 (if (or (null ok-if-already-exists) ; not allowed to exist
2561 (and (numberp ok-if-already-exists)
2562 (not (yes-or-no-p
2563 (format
2564 "File %s already exists; make it a link anyway? "
2565 l-localname)))))
2566 (tramp-error
2567 l 'file-already-exists "File %s already exists" l-localname)
2568 (delete-file linkname)))
2569
2570 ;; If FILENAME is a Tramp name, use just the localname component.
2571 (when (tramp-tramp-file-p filename)
2572 (setq filename
2573 (tramp-file-name-localname
2574 (tramp-dissect-file-name (expand-file-name filename)))))
2575
2576 ;; Right, they are on the same host, regardless of user, method, etc.
2577 ;; We now make the link on the remote machine. This will occur as the user
2578 ;; that FILENAME belongs to.
2579 (zerop
2580 (tramp-send-command-and-check
2581 l
2582 (format
2583 "cd %s && %s -sf %s %s"
2584 (tramp-shell-quote-argument cwd)
2585 ln
2586 (tramp-shell-quote-argument filename)
2587 (tramp-shell-quote-argument l-localname))
2588 t)))))
2589
2590 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2591 "Like `load' for Tramp files."
2592 (with-parsed-tramp-file-name (expand-file-name file) nil
2593 (unless nosuffix
2594 (cond ((file-exists-p (concat file ".elc"))
2595 (setq file (concat file ".elc")))
2596 ((file-exists-p (concat file ".el"))
2597 (setq file (concat file ".el")))))
2598 (when must-suffix
2599 ;; The first condition is always true for absolute file names.
2600 ;; Included for safety's sake.
2601 (unless (or (file-name-directory file)
2602 (string-match "\\.elc?\\'" file))
2603 (tramp-error
2604 v 'file-error
2605 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2606 (unless noerror
2607 (when (not (file-exists-p file))
2608 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2609 (if (not (file-exists-p file))
2610 nil
2611 (let ((tramp-message-show-message (not nomessage)))
2612 (with-progress-reporter v 0 (format "Loading %s" file)
2613 (let ((local-copy (file-local-copy file)))
2614 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2615 (unwind-protect
2616 (load local-copy noerror t t)
2617 (delete-file local-copy)))))
2618 t)))
2619
2620 ;; Localname manipulation functions that grok Tramp localnames...
2621 (defun tramp-handle-file-name-as-directory (file)
2622 "Like `file-name-as-directory' but aware of Tramp files."
2623 ;; `file-name-as-directory' would be sufficient except localname is
2624 ;; the empty string.
2625 (let ((v (tramp-dissect-file-name file t)))
2626 ;; Run the command on the localname portion only.
2627 (tramp-make-tramp-file-name
2628 (tramp-file-name-method v)
2629 (tramp-file-name-user v)
2630 (tramp-file-name-host v)
2631 (tramp-run-real-handler
2632 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2633
2634 (defun tramp-handle-file-name-directory (file)
2635 "Like `file-name-directory' but aware of Tramp files."
2636 ;; Everything except the last filename thing is the directory. We
2637 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2638 ;; the remote file name parts. This is a problem when we are in
2639 ;; file name completion.
2640 (let ((v (tramp-dissect-file-name file t)))
2641 ;; Run the command on the localname portion only.
2642 (tramp-make-tramp-file-name
2643 (tramp-file-name-method v)
2644 (tramp-file-name-user v)
2645 (tramp-file-name-host v)
2646 (tramp-run-real-handler
2647 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2648
2649 (defun tramp-handle-file-name-nondirectory (file)
2650 "Like `file-name-nondirectory' but aware of Tramp files."
2651 (with-parsed-tramp-file-name file nil
2652 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2653
2654 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2655 "Like `file-truename' for Tramp files."
2656 (with-parsed-tramp-file-name (expand-file-name filename) nil
2657 (with-file-property v localname "file-truename"
2658 (let ((result nil)) ; result steps in reverse order
2659 (tramp-message v 4 "Finding true name for `%s'" filename)
2660 (cond
2661 ;; Use GNU readlink --canonicalize-missing where available.
2662 ((tramp-get-remote-readlink v)
2663 (setq result
2664 (tramp-send-command-and-read
2665 v
2666 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2667 (tramp-get-remote-readlink v)
2668 (tramp-shell-quote-argument localname)))))
2669
2670 ;; Use Perl implementation.
2671 ((and (tramp-get-remote-perl v)
2672 (tramp-get-connection-property v "perl-file-spec" nil)
2673 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2674 (tramp-maybe-send-script
2675 v tramp-perl-file-truename "tramp_perl_file_truename")
2676 (setq result
2677 (tramp-send-command-and-read
2678 v
2679 (format "tramp_perl_file_truename %s"
2680 (tramp-shell-quote-argument localname)))))
2681
2682 ;; Do it yourself. We bind `directory-sep-char' here for
2683 ;; XEmacs on Windows, which would otherwise use backslash.
2684 (t (let* ((directory-sep-char ?/)
2685 (steps (tramp-compat-split-string localname "/"))
2686 (localnamedir (tramp-run-real-handler
2687 'file-name-as-directory (list localname)))
2688 (is-dir (string= localname localnamedir))
2689 (thisstep nil)
2690 (numchase 0)
2691 ;; Don't make the following value larger than
2692 ;; necessary. People expect an error message in a
2693 ;; timely fashion when something is wrong;
2694 ;; otherwise they might think that Emacs is hung.
2695 ;; Of course, correctness has to come first.
2696 (numchase-limit 20)
2697 symlink-target)
2698 (while (and steps (< numchase numchase-limit))
2699 (setq thisstep (pop steps))
2700 (tramp-message
2701 v 5 "Check %s"
2702 (mapconcat 'identity
2703 (append '("") (reverse result) (list thisstep))
2704 "/"))
2705 (setq symlink-target
2706 (nth 0 (file-attributes
2707 (tramp-make-tramp-file-name
2708 method user host
2709 (mapconcat 'identity
2710 (append '("")
2711 (reverse result)
2712 (list thisstep))
2713 "/")))))
2714 (cond ((string= "." thisstep)
2715 (tramp-message v 5 "Ignoring step `.'"))
2716 ((string= ".." thisstep)
2717 (tramp-message v 5 "Processing step `..'")
2718 (pop result))
2719 ((stringp symlink-target)
2720 ;; It's a symlink, follow it.
2721 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2722 (setq numchase (1+ numchase))
2723 (when (file-name-absolute-p symlink-target)
2724 (setq result nil))
2725 ;; If the symlink was absolute, we'll get a string like
2726 ;; "/user@host:/some/target"; extract the
2727 ;; "/some/target" part from it.
2728 (when (tramp-tramp-file-p symlink-target)
2729 (unless (tramp-equal-remote filename symlink-target)
2730 (tramp-error
2731 v 'file-error
2732 "Symlink target `%s' on wrong host" symlink-target))
2733 (setq symlink-target localname))
2734 (setq steps
2735 (append (tramp-compat-split-string
2736 symlink-target "/")
2737 steps)))
2738 (t
2739 ;; It's a file.
2740 (setq result (cons thisstep result)))))
2741 (when (>= numchase numchase-limit)
2742 (tramp-error
2743 v 'file-error
2744 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2745 (setq result (reverse result))
2746 ;; Combine list to form string.
2747 (setq result
2748 (if result
2749 (mapconcat 'identity (cons "" result) "/")
2750 "/"))
2751 (when (and is-dir (or (string= "" result)
2752 (not (string= (substring result -1) "/"))))
2753 (setq result (concat result "/"))))))
2754
2755 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2756 (tramp-make-tramp-file-name method user host result)))))
2757
2758 ;; Basic functions.
2759
2760 (defun tramp-handle-file-exists-p (filename)
2761 "Like `file-exists-p' for Tramp files."
2762 (with-parsed-tramp-file-name filename nil
2763 (with-file-property v localname "file-exists-p"
2764 (or (not (null (tramp-get-file-property
2765 v localname "file-attributes-integer" nil)))
2766 (not (null (tramp-get-file-property
2767 v localname "file-attributes-string" nil)))
2768 (zerop (tramp-send-command-and-check
2769 v
2770 (format
2771 "%s %s"
2772 (tramp-get-file-exists-command v)
2773 (tramp-shell-quote-argument localname))))))))
2774
2775 ;; Inodes don't exist for some file systems. Therefore we must
2776 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2777 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2778 ;; performance isn't the major issue given that file transfer will
2779 ;; take time.
2780 (defvar tramp-inodes nil
2781 "Keeps virtual inodes numbers.")
2782
2783 ;; Devices must distinguish physical file systems. The device numbers
2784 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2785 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2786 ;; EFS use device number "-1". In order to be different, we use device number
2787 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2788 (defvar tramp-devices nil
2789 "Keeps virtual device numbers.")
2790
2791 ;; CCC: This should check for an error condition and signal failure
2792 ;; when something goes wrong.
2793 ;; Daniel Pittman <daniel@danann.net>
2794 (defun tramp-handle-file-attributes (filename &optional id-format)
2795 "Like `file-attributes' for Tramp files."
2796 (unless id-format (setq id-format 'integer))
2797 ;; Don't modify `last-coding-system-used' by accident.
2798 (let ((last-coding-system-used last-coding-system-used))
2799 (with-parsed-tramp-file-name (expand-file-name filename) nil
2800 (with-file-property v localname (format "file-attributes-%s" id-format)
2801 (save-excursion
2802 (tramp-convert-file-attributes
2803 v
2804 (cond
2805 ((tramp-get-remote-stat v)
2806 (tramp-do-file-attributes-with-stat v localname id-format))
2807 ((tramp-get-remote-perl v)
2808 (tramp-do-file-attributes-with-perl v localname id-format))
2809 (t
2810 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2811
2812 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2813 "Implement `file-attributes' for Tramp files using the ls(1) command."
2814 (let (symlinkp dirp
2815 res-inode res-filemodes res-numlinks
2816 res-uid res-gid res-size res-symlink-target)
2817 (tramp-message vec 5 "file attributes with ls: %s" localname)
2818 (tramp-send-command
2819 vec
2820 (format "(%s %s || %s -h %s) && %s %s %s"
2821 (tramp-get-file-exists-command vec)
2822 (tramp-shell-quote-argument localname)
2823 (tramp-get-test-command vec)
2824 (tramp-shell-quote-argument localname)
2825 (tramp-get-ls-command vec)
2826 (if (eq id-format 'integer) "-ildn" "-ild")
2827 (tramp-shell-quote-argument localname)))
2828 ;; parse `ls -l' output ...
2829 (with-current-buffer (tramp-get-buffer vec)
2830 (when (> (buffer-size) 0)
2831 (goto-char (point-min))
2832 ;; ... inode
2833 (setq res-inode
2834 (condition-case err
2835 (read (current-buffer))
2836 (invalid-read-syntax
2837 (when (and (equal (cadr err)
2838 "Integer constant overflow in reader")
2839 (string-match
2840 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2841 (car (cddr err))))
2842 (let* ((big (read (substring (car (cddr err)) 0
2843 (match-beginning 1))))
2844 (small (read (match-string 1 (car (cddr err)))))
2845 (twiddle (/ small 65536)))
2846 (cons (+ big twiddle)
2847 (- small (* twiddle 65536))))))))
2848 ;; ... file mode flags
2849 (setq res-filemodes (symbol-name (read (current-buffer))))
2850 ;; ... number links
2851 (setq res-numlinks (read (current-buffer)))
2852 ;; ... uid and gid
2853 (setq res-uid (read (current-buffer)))
2854 (setq res-gid (read (current-buffer)))
2855 (if (eq id-format 'integer)
2856 (progn
2857 (unless (numberp res-uid) (setq res-uid -1))
2858 (unless (numberp res-gid) (setq res-gid -1)))
2859 (progn
2860 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2861 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2862 ;; ... size
2863 (setq res-size (read (current-buffer)))
2864 ;; From the file modes, figure out other stuff.
2865 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2866 (setq dirp (eq ?d (aref res-filemodes 0)))
2867 ;; if symlink, find out file name pointed to
2868 (when symlinkp
2869 (search-forward "-> ")
2870 (setq res-symlink-target
2871 (buffer-substring (point) (tramp-compat-line-end-position))))
2872 ;; return data gathered
2873 (list
2874 ;; 0. t for directory, string (name linked to) for symbolic
2875 ;; link, or nil.
2876 (or dirp res-symlink-target)
2877 ;; 1. Number of links to file.
2878 res-numlinks
2879 ;; 2. File uid.
2880 res-uid
2881 ;; 3. File gid.
2882 res-gid
2883 ;; 4. Last access time, as a list of two integers. First
2884 ;; integer has high-order 16 bits of time, second has low 16
2885 ;; bits.
2886 ;; 5. Last modification time, likewise.
2887 ;; 6. Last status change time, likewise.
2888 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2889 ;; 7. Size in bytes (-1, if number is out of range).
2890 res-size
2891 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2892 res-filemodes
2893 ;; 9. t if file's gid would change if file were deleted and
2894 ;; recreated. Will be set in `tramp-convert-file-attributes'
2895 t
2896 ;; 10. inode number.
2897 res-inode
2898 ;; 11. Device number. Will be replaced by a virtual device number.
2899 -1
2900 )))))
2901
2902 (defun tramp-do-file-attributes-with-perl
2903 (vec localname &optional id-format)
2904 "Implement `file-attributes' for Tramp files using a Perl script."
2905 (tramp-message vec 5 "file attributes with perl: %s" localname)
2906 (tramp-maybe-send-script
2907 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2908 (tramp-send-command-and-read
2909 vec
2910 (format "tramp_perl_file_attributes %s %s"
2911 (tramp-shell-quote-argument localname) id-format)))
2912
2913 (defun tramp-do-file-attributes-with-stat
2914 (vec localname &optional id-format)
2915 "Implement `file-attributes' for Tramp files using stat(1) command."
2916 (tramp-message vec 5 "file attributes with stat: %s" localname)
2917 (tramp-send-command-and-read
2918 vec
2919 (format
2920 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
2921 ;; parse correctly the sequence "((". Therefore, we add a space.
2922 "( (%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)"
2923 (tramp-get-file-exists-command vec)
2924 (tramp-shell-quote-argument localname)
2925 (tramp-get-test-command vec)
2926 (tramp-shell-quote-argument localname)
2927 (tramp-get-remote-stat vec)
2928 (if (eq id-format 'integer) "%u" "\"%U\"")
2929 (if (eq id-format 'integer) "%g" "\"%G\"")
2930 (tramp-shell-quote-argument localname))))
2931
2932 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2933 "Like `set-visited-file-modtime' for Tramp files."
2934 (unless (buffer-file-name)
2935 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2936 (buffer-name)))
2937 (if time-list
2938 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2939 (let ((f (buffer-file-name))
2940 coding-system-used)
2941 (with-parsed-tramp-file-name f nil
2942 (let* ((attr (file-attributes f))
2943 ;; '(-1 65535) means file doesn't exists yet.
2944 (modtime (or (nth 5 attr) '(-1 65535))))
2945 (when (boundp 'last-coding-system-used)
2946 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2947 ;; We use '(0 0) as a don't-know value. See also
2948 ;; `tramp-do-file-attributes-with-ls'.
2949 (if (not (equal modtime '(0 0)))
2950 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2951 (progn
2952 (tramp-send-command
2953 v
2954 (format "%s -ild %s"
2955 (tramp-get-ls-command v)
2956 (tramp-shell-quote-argument localname)))
2957 (setq attr (buffer-substring (point)
2958 (progn (end-of-line) (point)))))
2959 (tramp-set-file-property
2960 v localname "visited-file-modtime-ild" attr))
2961 (when (boundp 'last-coding-system-used)
2962 (set 'last-coding-system-used coding-system-used))
2963 nil)))))
2964
2965 ;; This function makes the same assumption as
2966 ;; `tramp-handle-set-visited-file-modtime'.
2967 (defun tramp-handle-verify-visited-file-modtime (buf)
2968 "Like `verify-visited-file-modtime' for Tramp files.
2969 At the time `verify-visited-file-modtime' calls this function, we
2970 already know that the buffer is visiting a file and that
2971 `visited-file-modtime' does not return 0. Do not call this
2972 function directly, unless those two cases are already taken care
2973 of."
2974 (with-current-buffer buf
2975 (let ((f (buffer-file-name)))
2976 ;; There is no file visiting the buffer, or the buffer has no
2977 ;; recorded last modification time, or there is no established
2978 ;; connection.
2979 (if (or (not f)
2980 (eq (visited-file-modtime) 0)
2981 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
2982 t
2983 (with-parsed-tramp-file-name f nil
2984 (tramp-flush-file-property v localname)
2985 (let* ((attr (file-attributes f))
2986 (modtime (nth 5 attr))
2987 (mt (visited-file-modtime)))
2988
2989 (cond
2990 ;; File exists, and has a known modtime.
2991 ((and attr (not (equal modtime '(0 0))))
2992 (< (abs (tramp-time-diff
2993 modtime
2994 ;; For compatibility, deal with both the old
2995 ;; (HIGH . LOW) and the new (HIGH LOW) return
2996 ;; values of `visited-file-modtime'.
2997 (if (atom (cdr mt))
2998 (list (car mt) (cdr mt))
2999 mt)))
3000 2))
3001 ;; Modtime has the don't know value.
3002 (attr
3003 (tramp-send-command
3004 v
3005 (format "%s -ild %s"
3006 (tramp-get-ls-command v)
3007 (tramp-shell-quote-argument localname)))
3008 (with-current-buffer (tramp-get-buffer v)
3009 (setq attr (buffer-substring
3010 (point) (progn (end-of-line) (point)))))
3011 (equal
3012 attr
3013 (tramp-get-file-property
3014 v localname "visited-file-modtime-ild" "")))
3015 ;; If file does not exist, say it is not modified if and
3016 ;; only if that agrees with the buffer's record.
3017 (t (equal mt '(-1 65535))))))))))
3018
3019 (defun tramp-handle-set-file-modes (filename mode)
3020 "Like `set-file-modes' for Tramp files."
3021 (with-parsed-tramp-file-name filename nil
3022 (tramp-flush-file-property v localname)
3023 (unless (zerop (tramp-send-command-and-check
3024 v
3025 (format "chmod %s %s"
3026 (tramp-decimal-to-octal mode)
3027 (tramp-shell-quote-argument localname))))
3028 ;; FIXME: extract the proper text from chmod's stderr.
3029 (tramp-error
3030 v 'file-error "Error while changing file's mode %s" filename))))
3031
3032 (defun tramp-handle-set-file-times (filename &optional time)
3033 "Like `set-file-times' for Tramp files."
3034 (zerop
3035 (if (file-remote-p filename)
3036 (with-parsed-tramp-file-name filename nil
3037 (tramp-flush-file-property v localname)
3038 (let ((time (if (or (null time) (equal time '(0 0)))
3039 (current-time)
3040 time))
3041 ;; With GNU Emacs, `format-time-string' has an optional
3042 ;; parameter UNIVERSAL. This is preferred, because we
3043 ;; could handle the case when the remote host is
3044 ;; located in a different time zone as the local host.
3045 (utc (not (featurep 'xemacs))))
3046 (tramp-send-command-and-check
3047 v (format "%s touch -t %s %s"
3048 (if utc "TZ=UTC; export TZ;" "")
3049 (if utc
3050 (format-time-string "%Y%m%d%H%M.%S" time t)
3051 (format-time-string "%Y%m%d%H%M.%S" time))
3052 (tramp-shell-quote-argument localname)))))
3053
3054 ;; We handle also the local part, because in older Emacsen,
3055 ;; without `set-file-times', this function is an alias for this.
3056 ;; We are local, so we don't need the UTC settings.
3057 (tramp-local-call-process
3058 "touch" nil nil nil "-t"
3059 (format-time-string "%Y%m%d%H%M.%S" time)
3060 (tramp-shell-quote-argument filename)))))
3061
3062 (defun tramp-set-file-uid-gid (filename &optional uid gid)
3063 "Set the ownership for FILENAME.
3064 If UID and GID are provided, these values are used; otherwise uid
3065 and gid of the corresponding user is taken. Both parameters must be integers."
3066 ;; Modern Unices allow chown only for root. So we might need
3067 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
3068 ;; working with su(do)? when it is needed, so it shall succeed in
3069 ;; the majority of cases.
3070 ;; Don't modify `last-coding-system-used' by accident.
3071 (let ((last-coding-system-used last-coding-system-used))
3072 (if (file-remote-p filename)
3073 (with-parsed-tramp-file-name filename nil
3074 (if (and (zerop (user-uid)) (tramp-local-host-p v))
3075 ;; If we are root on the local host, we can do it directly.
3076 (tramp-set-file-uid-gid localname uid gid)
3077 (let ((uid (or (and (integerp uid) uid)
3078 (tramp-get-remote-uid v 'integer)))
3079 (gid (or (and (integerp gid) gid)
3080 (tramp-get-remote-gid v 'integer))))
3081 (tramp-send-command
3082 v (format
3083 "chown %d:%d %s" uid gid
3084 (tramp-shell-quote-argument localname))))))
3085
3086 ;; We handle also the local part, because there doesn't exist
3087 ;; `set-file-uid-gid'. On W32 "chown" might not work.
3088 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
3089 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
3090 (tramp-local-call-process
3091 "chown" nil nil nil
3092 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
3093
3094 (defun tramp-remote-selinux-p (vec)
3095 "Check, whether SELINUX is enabled on the remote host."
3096 (with-connection-property (tramp-get-connection-process vec) "selinux-p"
3097 (let ((result (tramp-find-executable
3098 vec "getenforce" (tramp-get-remote-path vec) t t)))
3099 (and result
3100 (string-equal
3101 (tramp-send-command-and-read
3102 vec (format "echo \\\"`%S`\\\"" result))
3103 "Enforcing")))))
3104
3105 (defun tramp-handle-file-selinux-context (filename)
3106 "Like `file-selinux-context' for Tramp files."
3107 (with-parsed-tramp-file-name filename nil
3108 (with-file-property v localname "file-selinux-context"
3109 (let ((context '(nil nil nil nil))
3110 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
3111 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
3112 (when (and (tramp-remote-selinux-p v)
3113 (zerop (tramp-send-command-and-check
3114 v (format
3115 "%s -d -Z %s"
3116 (tramp-get-ls-command v)
3117 (tramp-shell-quote-argument localname)))))
3118 (with-current-buffer (tramp-get-connection-buffer v)
3119 (goto-char (point-min))
3120 (when (re-search-forward regexp (tramp-compat-line-end-position) t)
3121 (setq context (list (match-string 1) (match-string 2)
3122 (match-string 3) (match-string 4))))))
3123 ;; Return the context.
3124 context))))
3125
3126 (defun tramp-handle-set-file-selinux-context (filename context)
3127 "Like `set-file-selinux-context' for Tramp files."
3128 (with-parsed-tramp-file-name filename nil
3129 (if (and (consp context)
3130 (tramp-remote-selinux-p v)
3131 (zerop (tramp-send-command-and-check
3132 v (format "chcon %s %s %s %s %s"
3133 (if (stringp (nth 0 context))
3134 (format "--user=%s" (nth 0 context)) "")
3135 (if (stringp (nth 1 context))
3136 (format "--role=%s" (nth 1 context)) "")
3137 (if (stringp (nth 2 context))
3138 (format "--type=%s" (nth 2 context)) "")
3139 (if (stringp (nth 3 context))
3140 (format "--range=%s" (nth 3 context)) "")
3141 (tramp-shell-quote-argument localname)))))
3142 (tramp-set-file-property v localname "file-selinux-context" context)
3143 (tramp-set-file-property v localname "file-selinux-context" 'undef)))
3144 ;; We always return nil.
3145 nil)
3146
3147 ;; Simple functions using the `test' command.
3148
3149 (defun tramp-handle-file-executable-p (filename)
3150 "Like `file-executable-p' for Tramp files."
3151 (with-parsed-tramp-file-name filename nil
3152 (with-file-property v localname "file-executable-p"
3153 ;; Examine `file-attributes' cache to see if request can be
3154 ;; satisfied without remote operation.
3155 (or (tramp-check-cached-permissions v ?x)
3156 (zerop (tramp-run-test "-x" filename))))))
3157
3158 (defun tramp-handle-file-readable-p (filename)
3159 "Like `file-readable-p' for Tramp files."
3160 (with-parsed-tramp-file-name filename nil
3161 (with-file-property v localname "file-readable-p"
3162 ;; Examine `file-attributes' cache to see if request can be
3163 ;; satisfied without remote operation.
3164 (or (tramp-check-cached-permissions v ?r)
3165 (zerop (tramp-run-test "-r" filename))))))
3166
3167 ;; When the remote shell is started, it looks for a shell which groks
3168 ;; tilde expansion. Here, we assume that all shells which grok tilde
3169 ;; expansion will also provide a `test' command which groks `-nt' (for
3170 ;; newer than). If this breaks, tell me about it and I'll try to do
3171 ;; something smarter about it.
3172 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3173 "Like `file-newer-than-file-p' for Tramp files."
3174 (cond ((not (file-exists-p file1))
3175 nil)
3176 ((not (file-exists-p file2))
3177 t)
3178 ;; We are sure both files exist at this point.
3179 (t
3180 (save-excursion
3181 ;; We try to get the mtime of both files. If they are not
3182 ;; equal to the "dont-know" value, then we subtract the times
3183 ;; and obtain the result.
3184 (let ((fa1 (file-attributes file1))
3185 (fa2 (file-attributes file2)))
3186 (if (and (not (equal (nth 5 fa1) '(0 0)))
3187 (not (equal (nth 5 fa2) '(0 0))))
3188 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3189 ;; If one of them is the dont-know value, then we can
3190 ;; still try to run a shell command on the remote host.
3191 ;; However, this only works if both files are Tramp
3192 ;; files and both have the same method, same user, same
3193 ;; host.
3194 (unless (tramp-equal-remote file1 file2)
3195 (with-parsed-tramp-file-name
3196 (if (tramp-tramp-file-p file1) file1 file2) nil
3197 (tramp-error
3198 v 'file-error
3199 "Files %s and %s must have same method, user, host"
3200 file1 file2)))
3201 (with-parsed-tramp-file-name file1 nil
3202 (zerop (tramp-run-test2
3203 (tramp-get-test-nt-command v) file1 file2)))))))))
3204
3205 ;; Functions implemented using the basic functions above.
3206
3207 (defun tramp-handle-file-modes (filename)
3208 "Like `file-modes' for Tramp files."
3209 (let ((truename (or (file-truename filename) filename)))
3210 (when (file-exists-p truename)
3211 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3212
3213 (defun tramp-default-file-modes (filename)
3214 "Return file modes of FILENAME as integer.
3215 If the file modes of FILENAME cannot be determined, return the
3216 value of `default-file-modes', without execute permissions."
3217 (or (file-modes filename)
3218 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3219
3220 (defun tramp-handle-file-directory-p (filename)
3221 "Like `file-directory-p' for Tramp files."
3222 ;; Care must be taken that this function returns `t' for symlinks
3223 ;; pointing to directories. Surely the most obvious implementation
3224 ;; would be `test -d', but that returns false for such symlinks.
3225 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3226 ;; I now think he's right. So we could be using `test -d', couldn't
3227 ;; we?
3228 ;;
3229 ;; Alternatives: `cd %s', `test -d %s'
3230 (with-parsed-tramp-file-name filename nil
3231 (with-file-property v localname "file-directory-p"
3232 (zerop (tramp-run-test "-d" filename)))))
3233
3234 (defun tramp-handle-file-regular-p (filename)
3235 "Like `file-regular-p' for Tramp files."
3236 (and (file-exists-p filename)
3237 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3238
3239 (defun tramp-handle-file-symlink-p (filename)
3240 "Like `file-symlink-p' for Tramp files."
3241 (with-parsed-tramp-file-name filename nil
3242 (let ((x (car (file-attributes filename))))
3243 (when (stringp x)
3244 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3245 ;; might do weird things.
3246 (if (file-name-absolute-p x)
3247 (tramp-make-tramp-file-name method user host x)
3248 x)))))
3249
3250 (defun tramp-handle-file-writable-p (filename)
3251 "Like `file-writable-p' for Tramp files."
3252 (with-parsed-tramp-file-name filename nil
3253 (with-file-property v localname "file-writable-p"
3254 (if (file-exists-p filename)
3255 ;; Examine `file-attributes' cache to see if request can be
3256 ;; satisfied without remote operation.
3257 (or (tramp-check-cached-permissions v ?w)
3258 (zerop (tramp-run-test "-w" filename)))
3259 ;; If file doesn't exist, check if directory is writable.
3260 (and (zerop (tramp-run-test
3261 "-d" (file-name-directory filename)))
3262 (zerop (tramp-run-test
3263 "-w" (file-name-directory filename))))))))
3264
3265 (defun tramp-handle-file-ownership-preserved-p (filename)
3266 "Like `file-ownership-preserved-p' for Tramp files."
3267 (with-parsed-tramp-file-name filename nil
3268 (with-file-property v localname "file-ownership-preserved-p"
3269 (let ((attributes (file-attributes filename)))
3270 ;; Return t if the file doesn't exist, since it's true that no
3271 ;; information would be lost by an (attempted) delete and create.
3272 (or (null attributes)
3273 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3274
3275 ;; Other file name ops.
3276
3277 (defun tramp-handle-directory-file-name (directory)
3278 "Like `directory-file-name' for Tramp files."
3279 ;; If localname component of filename is "/", leave it unchanged.
3280 ;; Otherwise, remove any trailing slash from localname component.
3281 ;; Method, host, etc, are unchanged. Does it make sense to try
3282 ;; to avoid parsing the filename?
3283 (with-parsed-tramp-file-name directory nil
3284 (if (and (not (zerop (length localname)))
3285 (eq (aref localname (1- (length localname))) ?/)
3286 (not (string= localname "/")))
3287 (substring directory 0 -1)
3288 directory)))
3289
3290 ;; Directory listings.
3291
3292 (defun tramp-handle-directory-files
3293 (directory &optional full match nosort files-only)
3294 "Like `directory-files' for Tramp files."
3295 ;; FILES-ONLY is valid for XEmacs only.
3296 (when (file-directory-p directory)
3297 (setq directory (file-name-as-directory (expand-file-name directory)))
3298 (let ((temp (nreverse (file-name-all-completions "" directory)))
3299 result item)
3300
3301 (while temp
3302 (setq item (directory-file-name (pop temp)))
3303 (when (and (or (null match) (string-match match item))
3304 (or (null files-only)
3305 ;; Files only.
3306 (and (equal files-only t) (file-regular-p item))
3307 ;; Directories only.
3308 (file-directory-p item)))
3309 (push (if full (concat directory item) item)
3310 result)))
3311 (if nosort result (sort result 'string<)))))
3312
3313 (defun tramp-handle-directory-files-and-attributes
3314 (directory &optional full match nosort id-format)
3315 "Like `directory-files-and-attributes' for Tramp files."
3316 (unless id-format (setq id-format 'integer))
3317 (when (file-directory-p directory)
3318 (setq directory (expand-file-name directory))
3319 (let* ((temp
3320 (copy-tree
3321 (with-parsed-tramp-file-name directory nil
3322 (with-file-property
3323 v localname
3324 (format "directory-files-and-attributes-%s" id-format)
3325 (save-excursion
3326 (mapcar
3327 (lambda (x)
3328 (cons (car x)
3329 (tramp-convert-file-attributes v (cdr x))))
3330 (cond
3331 ((tramp-get-remote-stat v)
3332 (tramp-do-directory-files-and-attributes-with-stat
3333 v localname id-format))
3334 ((tramp-get-remote-perl v)
3335 (tramp-do-directory-files-and-attributes-with-perl
3336 v localname id-format)))))))))
3337 result item)
3338
3339 (while temp
3340 (setq item (pop temp))
3341 (when (or (null match) (string-match match (car item)))
3342 (when full
3343 (setcar item (expand-file-name (car item) directory)))
3344 (push item result)))
3345
3346 (if nosort
3347 result
3348 (sort result (lambda (x y) (string< (car x) (car y))))))))
3349
3350 (defun tramp-do-directory-files-and-attributes-with-perl
3351 (vec localname &optional id-format)
3352 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3353 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3354 (tramp-maybe-send-script
3355 vec tramp-perl-directory-files-and-attributes
3356 "tramp_perl_directory_files_and_attributes")
3357 (let ((object
3358 (tramp-send-command-and-read
3359 vec
3360 (format "tramp_perl_directory_files_and_attributes %s %s"
3361 (tramp-shell-quote-argument localname) id-format))))
3362 (when (stringp object) (tramp-error vec 'file-error object))
3363 object))
3364
3365 (defun tramp-do-directory-files-and-attributes-with-stat
3366 (vec localname &optional id-format)
3367 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3368 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3369 (tramp-send-command-and-read
3370 vec
3371 (format
3372 (concat
3373 ;; We must care about filenames with spaces, or starting with
3374 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3375 ;; but it does not work on all remote systems. Therefore, we
3376 ;; quote the filenames via sed.
3377 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3378 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3379 "echo \")\"")
3380 (tramp-shell-quote-argument localname)
3381 (tramp-get-ls-command vec)
3382 (tramp-get-remote-stat vec)
3383 (if (eq id-format 'integer) "%u" "\"%U\"")
3384 (if (eq id-format 'integer) "%g" "\"%G\""))))
3385
3386 ;; This function should return "foo/" for directories and "bar" for
3387 ;; files.
3388 (defun tramp-handle-file-name-all-completions (filename directory)
3389 "Like `file-name-all-completions' for Tramp files."
3390 (unless (save-match-data (string-match "/" filename))
3391 (with-parsed-tramp-file-name (expand-file-name directory) nil
3392
3393 (all-completions
3394 filename
3395 (mapcar
3396 'list
3397 (or
3398 ;; Try cache first
3399 (and
3400 ;; Ignore if expired
3401 (or (not (integerp tramp-completion-reread-directory-timeout))
3402 (<= (tramp-time-diff
3403 (current-time)
3404 (tramp-get-file-property
3405 v localname "last-completion" '(0 0 0)))
3406 tramp-completion-reread-directory-timeout))
3407
3408 ;; Try cache entries for filename, filename with last
3409 ;; character removed, filename with last two characters
3410 ;; removed, ..., and finally the empty string - all
3411 ;; concatenated to the local directory name
3412
3413 ;; This is inefficient for very long filenames, pity
3414 ;; `reduce' is not available...
3415 (car
3416 (apply
3417 'append
3418 (mapcar
3419 (lambda (x)
3420 (let ((cache-hit
3421 (tramp-get-file-property
3422 v
3423 (concat localname (substring filename 0 x))
3424 "file-name-all-completions"
3425 nil)))
3426 (when cache-hit (list cache-hit))))
3427 (tramp-compat-number-sequence (length filename) 0 -1)))))
3428
3429 ;; Cache expired or no matching cache entry found so we need
3430 ;; to perform a remote operation
3431 (let (result)
3432 ;; Get a list of directories and files, including reliably
3433 ;; tagging the directories with a trailing '/'. Because I
3434 ;; rock. --daniel@danann.net
3435
3436 ;; Changed to perform `cd' in the same remote op and only
3437 ;; get entries starting with `filename'. Capture any `cd'
3438 ;; error messages. Ensure any `cd' and `echo' aliases are
3439 ;; ignored.
3440 (tramp-send-command
3441 v
3442 (if (tramp-get-remote-perl v)
3443 (progn
3444 (tramp-maybe-send-script
3445 v tramp-perl-file-name-all-completions
3446 "tramp_perl_file_name_all_completions")
3447 (format "tramp_perl_file_name_all_completions %s %s %d"
3448 (tramp-shell-quote-argument localname)
3449 (tramp-shell-quote-argument filename)
3450 (if (symbol-value
3451 ;; `read-file-name-completion-ignore-case'
3452 ;; is introduced with Emacs 22.1.
3453 (if (boundp
3454 'read-file-name-completion-ignore-case)
3455 'read-file-name-completion-ignore-case
3456 'completion-ignore-case))
3457 1 0)))
3458
3459 (format (concat
3460 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3461 ;; `ls' with wildcard might fail with `Argument
3462 ;; list too long' error in some corner cases; if
3463 ;; `ls' fails after `cd' succeeded, chances are
3464 ;; that's the case, so let's retry without
3465 ;; wildcard. This will return "too many" entries
3466 ;; but that isn't harmful.
3467 " || %s -a 2>/dev/null)"
3468 " | while read f; do"
3469 " if %s -d \"$f\" 2>/dev/null;"
3470 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3471 " && \\echo ok) || \\echo fail")
3472 (tramp-shell-quote-argument localname)
3473 (tramp-get-ls-command v)
3474 ;; When `filename' is empty, just `ls' without
3475 ;; filename argument is more efficient than `ls *'
3476 ;; for very large directories and might avoid the
3477 ;; `Argument list too long' error.
3478 ;;
3479 ;; With and only with wildcard, we need to add
3480 ;; `-d' to prevent `ls' from descending into
3481 ;; sub-directories.
3482 (if (zerop (length filename))
3483 "."
3484 (concat (tramp-shell-quote-argument filename) "* -d"))
3485 (tramp-get-ls-command v)
3486 (tramp-get-test-command v))))
3487
3488 ;; Now grab the output.
3489 (with-current-buffer (tramp-get-buffer v)
3490 (goto-char (point-max))
3491
3492 ;; Check result code, found in last line of output
3493 (forward-line -1)
3494 (if (looking-at "^fail$")
3495 (progn
3496 ;; Grab error message from line before last line
3497 ;; (it was put there by `cd 2>&1')
3498 (forward-line -1)
3499 (tramp-error
3500 v 'file-error
3501 "tramp-handle-file-name-all-completions: %s"
3502 (buffer-substring
3503 (point) (tramp-compat-line-end-position))))
3504 ;; For peace of mind, if buffer doesn't end in `fail'
3505 ;; then it should end in `ok'. If neither are in the
3506 ;; buffer something went seriously wrong on the remote
3507 ;; side.
3508 (unless (looking-at "^ok$")
3509 (tramp-error
3510 v 'file-error
3511 "\
3512 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3513 (tramp-shell-quote-argument localname) (buffer-string))))
3514
3515 (while (zerop (forward-line -1))
3516 (push (buffer-substring
3517 (point) (tramp-compat-line-end-position))
3518 result)))
3519
3520 ;; Because the remote op went through OK we know the
3521 ;; directory we `cd'-ed to exists
3522 (tramp-set-file-property
3523 v localname "file-exists-p" t)
3524
3525 ;; Because the remote op went through OK we know every
3526 ;; file listed by `ls' exists.
3527 (mapc (lambda (entry)
3528 (tramp-set-file-property
3529 v (concat localname entry) "file-exists-p" t))
3530 result)
3531
3532 (tramp-set-file-property
3533 v localname "last-completion" (current-time))
3534
3535 ;; Store result in the cache
3536 (tramp-set-file-property
3537 v (concat localname filename)
3538 "file-name-all-completions"
3539 result))))))))
3540
3541 (defun tramp-handle-file-name-completion
3542 (filename directory &optional predicate)
3543 "Like `file-name-completion' for Tramp files."
3544 (unless (tramp-tramp-file-p directory)
3545 (error
3546 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3547 directory))
3548 (try-completion
3549 filename
3550 (mapcar 'list (file-name-all-completions filename directory))
3551 (when predicate
3552 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3553
3554 ;; cp, mv and ln
3555
3556 (defun tramp-handle-add-name-to-file
3557 (filename newname &optional ok-if-already-exists)
3558 "Like `add-name-to-file' for Tramp files."
3559 (unless (tramp-equal-remote filename newname)
3560 (with-parsed-tramp-file-name
3561 (if (tramp-tramp-file-p filename) filename newname) nil
3562 (tramp-error
3563 v 'file-error
3564 "add-name-to-file: %s"
3565 "only implemented for same method, same user, same host")))
3566 (with-parsed-tramp-file-name filename v1
3567 (with-parsed-tramp-file-name newname v2
3568 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3569 (when (and (not ok-if-already-exists)
3570 (file-exists-p newname)
3571 (not (numberp ok-if-already-exists))
3572 (y-or-n-p
3573 (format
3574 "File %s already exists; make it a new name anyway? "
3575 newname)))
3576 (tramp-error
3577 v2 'file-error
3578 "add-name-to-file: file %s already exists" newname))
3579 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3580 (tramp-flush-file-property v2 v2-localname)
3581 (tramp-barf-unless-okay
3582 v1
3583 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3584 (tramp-shell-quote-argument v2-localname))
3585 "error with add-name-to-file, see buffer `%s' for details"
3586 (buffer-name))))))
3587
3588 (defun tramp-handle-copy-file
3589 (filename newname &optional ok-if-already-exists keep-date
3590 preserve-uid-gid preserve-selinux-context)
3591 "Like `copy-file' for Tramp files."
3592 (setq filename (expand-file-name filename))
3593 (setq newname (expand-file-name newname))
3594 (cond
3595 ;; At least one file a Tramp file?
3596 ((or (tramp-tramp-file-p filename)
3597 (tramp-tramp-file-p newname))
3598 (tramp-do-copy-or-rename-file
3599 'copy filename newname ok-if-already-exists keep-date
3600 preserve-uid-gid preserve-selinux-context))
3601 ;; Compat section.
3602 (preserve-selinux-context
3603 (tramp-run-real-handler
3604 'copy-file
3605 (list filename newname ok-if-already-exists keep-date
3606 preserve-uid-gid preserve-selinux-context)))
3607 (preserve-uid-gid
3608 (tramp-run-real-handler
3609 'copy-file
3610 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3611 (t
3612 (tramp-run-real-handler
3613 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3614
3615 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3616 "Like `copy-directory' for Tramp files."
3617 (let ((t1 (tramp-tramp-file-p dirname))
3618 (t2 (tramp-tramp-file-p newname)))
3619 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3620 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3621 ;; When DIRNAME and NEWNAME are remote, they must have
3622 ;; the same method.
3623 (or (null t1) (null t2)
3624 (string-equal
3625 (tramp-file-name-method (tramp-dissect-file-name dirname))
3626 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3627 ;; scp or rsync DTRT.
3628 (progn
3629 (setq dirname (directory-file-name (expand-file-name dirname))
3630 newname (directory-file-name (expand-file-name newname)))
3631 (if (and (file-directory-p newname)
3632 (not (string-equal (file-name-nondirectory dirname)
3633 (file-name-nondirectory newname))))
3634 (setq newname
3635 (expand-file-name
3636 (file-name-nondirectory dirname) newname)))
3637 (if (not (file-directory-p (file-name-directory newname)))
3638 (make-directory (file-name-directory newname) parents))
3639 (tramp-do-copy-or-rename-file-out-of-band
3640 'copy dirname newname keep-date))
3641 ;; We must do it file-wise.
3642 (tramp-run-real-handler
3643 'copy-directory (list dirname newname keep-date parents)))
3644
3645 ;; When newname did exist, we have wrong cached values.
3646 (when t2
3647 (with-parsed-tramp-file-name newname nil
3648 (tramp-flush-file-property v (file-name-directory localname))
3649 (tramp-flush-file-property v localname))))))
3650
3651 (defun tramp-handle-rename-file
3652 (filename newname &optional ok-if-already-exists)
3653 "Like `rename-file' for Tramp files."
3654 ;; Check if both files are local -- invoke normal rename-file.
3655 ;; Otherwise, use Tramp from local system.
3656 (setq filename (expand-file-name filename))
3657 (setq newname (expand-file-name newname))
3658 ;; At least one file a Tramp file?
3659 (if (or (tramp-tramp-file-p filename)
3660 (tramp-tramp-file-p newname))
3661 (tramp-do-copy-or-rename-file
3662 'rename filename newname ok-if-already-exists t t)
3663 (tramp-run-real-handler
3664 'rename-file (list filename newname ok-if-already-exists))))
3665
3666 (defun tramp-do-copy-or-rename-file
3667 (op filename newname &optional ok-if-already-exists keep-date
3668 preserve-uid-gid preserve-selinux-context)
3669 "Copy or rename a remote file.
3670 OP must be `copy' or `rename' and indicates the operation to perform.
3671 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3672 the new file (for copy) or the new name of the file (for rename).
3673 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3674 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3675 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3676 the uid and gid if both files are on the same host.
3677 PRESERVE-SELINUX-CONTEXT activates selinux commands.
3678
3679 This function is invoked by `tramp-handle-copy-file' and
3680 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3681 and `rename'. FILENAME and NEWNAME must be absolute file names."
3682 (unless (memq op '(copy rename))
3683 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3684 (let ((t1 (tramp-tramp-file-p filename))
3685 (t2 (tramp-tramp-file-p newname))
3686 (context (and preserve-selinux-context
3687 (apply 'file-selinux-context (list filename))))
3688 pr tm)
3689
3690 (with-parsed-tramp-file-name (if t1 filename newname) nil
3691 (when (and (not ok-if-already-exists) (file-exists-p newname))
3692 (tramp-error
3693 v 'file-already-exists "File %s already exists" newname))
3694
3695 (with-progress-reporter
3696 v 0 (format "%s %s to %s"
3697 (if (eq op 'copy) "Copying" "Renaming")
3698 filename newname)
3699
3700 (cond
3701 ;; Both are Tramp files.
3702 ((and t1 t2)
3703 (with-parsed-tramp-file-name filename v1
3704 (with-parsed-tramp-file-name newname v2
3705 (cond
3706 ;; Shortcut: if method, host, user are the same for
3707 ;; both files, we invoke `cp' or `mv' on the remote
3708 ;; host directly.
3709 ((tramp-equal-remote filename newname)
3710 (tramp-do-copy-or-rename-file-directly
3711 op filename newname
3712 ok-if-already-exists keep-date preserve-uid-gid))
3713
3714 ;; Try out-of-band operation.
3715 ((tramp-method-out-of-band-p
3716 v1 (nth 7 (file-attributes filename)))
3717 (tramp-do-copy-or-rename-file-out-of-band
3718 op filename newname keep-date))
3719
3720 ;; No shortcut was possible. So we copy the file
3721 ;; first. If the operation was `rename', we go back
3722 ;; and delete the original file (if the copy was
3723 ;; successful). The approach is simple-minded: we
3724 ;; create a new buffer, insert the contents of the
3725 ;; source file into it, then write out the buffer to
3726 ;; the target file. The advantage is that it doesn't
3727 ;; matter which filename handlers are used for the
3728 ;; source and target file.
3729 (t
3730 (tramp-do-copy-or-rename-file-via-buffer
3731 op filename newname keep-date))))))
3732
3733 ;; One file is a Tramp file, the other one is local.
3734 ((or t1 t2)
3735 (cond
3736 ;; Fast track on local machine.
3737 ((tramp-local-host-p v)
3738 (tramp-do-copy-or-rename-file-directly
3739 op filename newname
3740 ok-if-already-exists keep-date preserve-uid-gid))
3741
3742 ;; If the Tramp file has an out-of-band method, the
3743 ;; corresponding copy-program can be invoked.
3744 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3745 (tramp-do-copy-or-rename-file-out-of-band
3746 op filename newname keep-date))
3747
3748 ;; Use the inline method via a Tramp buffer.
3749 (t (tramp-do-copy-or-rename-file-via-buffer
3750 op filename newname keep-date))))
3751
3752 (t
3753 ;; One of them must be a Tramp file.
3754 (error "Tramp implementation says this cannot happen")))
3755
3756 ;; Handle `preserve-selinux-context'.
3757 (when context (apply 'set-file-selinux-context (list newname context)))
3758
3759 ;; In case of `rename', we must flush the cache of the source file.
3760 (when (and t1 (eq op 'rename))
3761 (with-parsed-tramp-file-name filename v1
3762 (tramp-flush-file-property v1 (file-name-directory localname))
3763 (tramp-flush-file-property v1 localname)))
3764
3765 ;; When newname did exist, we have wrong cached values.
3766 (when t2
3767 (with-parsed-tramp-file-name newname v2
3768 (tramp-flush-file-property v2 (file-name-directory localname))
3769 (tramp-flush-file-property v2 localname)))))))
3770
3771 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3772 "Use an Emacs buffer to copy or rename a file.
3773 First arg OP is either `copy' or `rename' and indicates the operation.
3774 FILENAME is the source file, NEWNAME the target file.
3775 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3776 (with-temp-buffer
3777 ;; We must disable multibyte, because binary data shall not be
3778 ;; converted.
3779 (set-buffer-multibyte nil)
3780 (let ((coding-system-for-read 'binary)
3781 (jka-compr-inhibit t))
3782 (insert-file-contents-literally filename))
3783 ;; We don't want the target file to be compressed, so we let-bind
3784 ;; `jka-compr-inhibit' to t.
3785 (let ((coding-system-for-write 'binary)
3786 (jka-compr-inhibit t))
3787 (write-region (point-min) (point-max) newname)))
3788 ;; KEEP-DATE handling.
3789 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3790 ;; Set the mode.
3791 (set-file-modes newname (tramp-default-file-modes filename))
3792 ;; If the operation was `rename', delete the original file.
3793 (unless (eq op 'copy) (delete-file filename)))
3794
3795 (defun tramp-do-copy-or-rename-file-directly
3796 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3797 "Invokes `cp' or `mv' on the remote system.
3798 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3799 respectively. FILENAME specifies the file to copy or rename,
3800 NEWNAME is the name of the new file (for copy) or the new name of
3801 the file (for rename). Both files must reside on the same host.
3802 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3803 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3804 the uid and gid from FILENAME."
3805 (let ((t1 (tramp-tramp-file-p filename))
3806 (t2 (tramp-tramp-file-p newname))
3807 (file-times (nth 5 (file-attributes filename)))
3808 (file-modes (tramp-default-file-modes filename)))
3809 (with-parsed-tramp-file-name (if t1 filename newname) nil
3810 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3811 ((eq op 'copy) "cp -f")
3812 ((eq op 'rename) "mv -f")
3813 (t (tramp-error
3814 v 'file-error
3815 "Unknown operation `%s', must be `copy' or `rename'"
3816 op))))
3817 (localname1
3818 (if t1
3819 (tramp-file-name-handler 'file-remote-p filename 'localname)
3820 filename))
3821 (localname2
3822 (if t2
3823 (tramp-file-name-handler 'file-remote-p newname 'localname)
3824 newname))
3825 (prefix (file-remote-p (if t1 filename newname)))
3826 cmd-result)
3827
3828 (cond
3829 ;; Both files are on a remote host, with same user.
3830 ((and t1 t2)
3831 (setq cmd-result
3832 (tramp-send-command-and-check
3833 v
3834 (format "%s %s %s" cmd
3835 (tramp-shell-quote-argument localname1)
3836 (tramp-shell-quote-argument localname2))))
3837 (with-current-buffer (tramp-get-buffer v)
3838 (goto-char (point-min))
3839 (unless
3840 (or
3841 (and keep-date
3842 ;; Mask cp -f error.
3843 (re-search-forward
3844 tramp-operation-not-permitted-regexp nil t))
3845 (zerop cmd-result))
3846 (tramp-error-with-buffer
3847 nil v 'file-error
3848 "Copying directly failed, see buffer `%s' for details."
3849 (buffer-name)))))
3850
3851 ;; We are on the local host.
3852 ((or t1 t2)
3853 (cond
3854 ;; We can do it directly.
3855 ((let (file-name-handler-alist)
3856 (and (file-readable-p localname1)
3857 (file-writable-p (file-name-directory localname2))
3858 (or (file-directory-p localname2)
3859 (file-writable-p localname2))))
3860 (if (eq op 'copy)
3861 (tramp-compat-copy-file
3862 localname1 localname2 ok-if-already-exists
3863 keep-date preserve-uid-gid)
3864 (tramp-run-real-handler
3865 'rename-file (list localname1 localname2 ok-if-already-exists))))
3866
3867 ;; We can do it directly with `tramp-send-command'
3868 ((and (file-readable-p (concat prefix localname1))
3869 (file-writable-p
3870 (file-name-directory (concat prefix localname2)))
3871 (or (file-directory-p (concat prefix localname2))
3872 (file-writable-p (concat prefix localname2))))
3873 (tramp-do-copy-or-rename-file-directly
3874 op (concat prefix localname1) (concat prefix localname2)
3875 ok-if-already-exists keep-date t)
3876 ;; We must change the ownership to the local user.
3877 (tramp-set-file-uid-gid
3878 (concat prefix localname2)
3879 (tramp-get-local-uid 'integer)
3880 (tramp-get-local-gid 'integer)))
3881
3882 ;; We need a temporary file in between.
3883 (t
3884 ;; Create the temporary file.
3885 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3886 (unwind-protect
3887 (progn
3888 (cond
3889 (t1
3890 (or
3891 (zerop
3892 (tramp-send-command-and-check
3893 v (format
3894 "%s %s %s" cmd
3895 (tramp-shell-quote-argument localname1)
3896 (tramp-shell-quote-argument tmpfile))))
3897 (tramp-error-with-buffer
3898 nil v 'file-error
3899 "Copying directly failed, see buffer `%s' for details."
3900 (tramp-get-buffer v)))
3901 ;; We must change the ownership as remote user.
3902 ;; Since this does not work reliable, we also
3903 ;; give read permissions.
3904 (set-file-modes
3905 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3906 (tramp-set-file-uid-gid
3907 (concat prefix tmpfile)
3908 (tramp-get-local-uid 'integer)
3909 (tramp-get-local-gid 'integer)))
3910 (t2
3911 (if (eq op 'copy)
3912 (tramp-compat-copy-file
3913 localname1 tmpfile t
3914 keep-date preserve-uid-gid)
3915 (tramp-run-real-handler
3916 'rename-file
3917 (list localname1 tmpfile t)))
3918 ;; We must change the ownership as local user.
3919 ;; Since this does not work reliable, we also
3920 ;; give read permissions.
3921 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3922 (tramp-set-file-uid-gid
3923 tmpfile
3924 (tramp-get-remote-uid v 'integer)
3925 (tramp-get-remote-gid v 'integer))))
3926
3927 ;; Move the temporary file to its destination.
3928 (cond
3929 (t2
3930 (or
3931 (zerop
3932 (tramp-send-command-and-check
3933 v (format
3934 "cp -f -p %s %s"
3935 (tramp-shell-quote-argument tmpfile)
3936 (tramp-shell-quote-argument localname2))))
3937 (tramp-error-with-buffer
3938 nil v 'file-error
3939 "Copying directly failed, see buffer `%s' for details."
3940 (tramp-get-buffer v))))
3941 (t1
3942 (tramp-run-real-handler
3943 'rename-file
3944 (list tmpfile localname2 ok-if-already-exists)))))
3945
3946 ;; Save exit.
3947 (condition-case nil
3948 (delete-file tmpfile)
3949 (error)))))))))
3950
3951 ;; Set the time and mode. Mask possible errors.
3952 (condition-case nil
3953 (when keep-date
3954 (set-file-times newname file-times)
3955 (set-file-modes newname file-modes))
3956 (error)))))
3957
3958 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3959 "Invoke rcp program to copy.
3960 The method used must be an out-of-band method."
3961 (let ((t1 (tramp-tramp-file-p filename))
3962 (t2 (tramp-tramp-file-p newname))
3963 copy-program copy-args copy-env copy-keep-date port spec
3964 source target)
3965
3966 (with-parsed-tramp-file-name (if t1 filename newname) nil
3967 (if (and t1 t2)
3968
3969 ;; Both are Tramp files. We shall optimize it, when the
3970 ;; methods for filename and newname are the same.
3971 (let* ((dir-flag (file-directory-p filename))
3972 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3973 (if dir-flag
3974 (setq tmpfile
3975 (expand-file-name
3976 (file-name-nondirectory newname) tmpfile)))
3977 (unwind-protect
3978 (progn
3979 (tramp-do-copy-or-rename-file-out-of-band
3980 op filename tmpfile keep-date)
3981 (tramp-do-copy-or-rename-file-out-of-band
3982 'rename tmpfile newname keep-date))
3983 ;; Save exit.
3984 (condition-case nil
3985 (if dir-flag
3986 (tramp-compat-delete-directory
3987 (expand-file-name ".." tmpfile) 'recursive)
3988 (delete-file tmpfile))
3989 (error))))
3990
3991 ;; Expand hops. Might be necessary for gateway methods.
3992 (setq v (car (tramp-compute-multi-hops v)))
3993 (aset v 3 localname)
3994
3995 ;; Check which ones of source and target are Tramp files.
3996 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3997 target (funcall
3998 (if (and (file-directory-p filename)
3999 (string-equal
4000 (file-name-nondirectory filename)
4001 (file-name-nondirectory newname)))
4002 'file-name-directory
4003 'identity)
4004 (if t2 (tramp-make-copy-program-file-name v) newname)))
4005
4006 ;; Check for port number. Until now, there's no need for handling
4007 ;; like method, user, host.
4008 (setq host (tramp-file-name-real-host v)
4009 port (tramp-file-name-port v)
4010 port (or (and port (number-to-string port)) ""))
4011
4012 ;; Compose copy command.
4013 (setq spec (format-spec-make
4014 ?h host ?u user ?p port
4015 ?t (tramp-get-connection-property
4016 (tramp-get-connection-process v) "temp-file" "")
4017 ?k (if keep-date " " ""))
4018 copy-program (tramp-get-method-parameter
4019 method 'tramp-copy-program)
4020 copy-keep-date (tramp-get-method-parameter
4021 method 'tramp-copy-keep-date)
4022 copy-args
4023 (delq
4024 nil
4025 (mapcar
4026 (lambda (x)
4027 (setq
4028 x
4029 ;; " " is indication for keep-date argument.
4030 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
4031 (unless (member "" x) (mapconcat 'identity x " ")))
4032 (tramp-get-method-parameter method 'tramp-copy-args)))
4033 copy-env
4034 (delq
4035 nil
4036 (mapcar
4037 (lambda (x)
4038 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4039 (unless (member "" x) (mapconcat 'identity x " ")))
4040 (tramp-get-method-parameter method 'tramp-copy-env))))
4041
4042 ;; Check for program.
4043 (when (and (fboundp 'executable-find)
4044 (not (let ((default-directory
4045 (tramp-compat-temporary-file-directory)))
4046 (executable-find copy-program))))
4047 (tramp-error
4048 v 'file-error "Cannot find copy program: %s" copy-program))
4049
4050 ;; Set variables for computing the prompt for reading
4051 ;; password.
4052 (setq tramp-current-method (tramp-file-name-method v)
4053 tramp-current-user (tramp-file-name-user v)
4054 tramp-current-host (tramp-file-name-host v))
4055
4056 (unwind-protect
4057 (with-temp-buffer
4058 ;; The default directory must be remote.
4059 (let ((default-directory
4060 (file-name-directory (if t1 filename newname)))
4061 (process-environment (copy-sequence process-environment)))
4062 ;; Set the transfer process properties.
4063 (tramp-set-connection-property
4064 v "process-name" (buffer-name (current-buffer)))
4065 (tramp-set-connection-property
4066 v "process-buffer" (current-buffer))
4067 (while copy-env
4068 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
4069 (setenv (pop copy-env) (pop copy-env)))
4070
4071 ;; Use an asynchronous process. By this, password can
4072 ;; be handled. The default directory must be local, in
4073 ;; order to apply the correct `copy-program'. We don't
4074 ;; set a timeout, because the copying of large files can
4075 ;; last longer than 60 secs.
4076 (let ((p (let ((default-directory
4077 (tramp-compat-temporary-file-directory)))
4078 (apply 'start-process
4079 (tramp-get-connection-property
4080 v "process-name" nil)
4081 (tramp-get-connection-property
4082 v "process-buffer" nil)
4083 copy-program
4084 (append copy-args (list source target))))))
4085 (tramp-message
4086 v 6 "%s" (mapconcat 'identity (process-command p) " "))
4087 (tramp-set-process-query-on-exit-flag p nil)
4088 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
4089
4090 ;; Reset the transfer process properties.
4091 (tramp-set-connection-property v "process-name" nil)
4092 (tramp-set-connection-property v "process-buffer" nil))
4093
4094 ;; Handle KEEP-DATE argument.
4095 (when (and keep-date (not copy-keep-date))
4096 (set-file-times newname (nth 5 (file-attributes filename))))
4097
4098 ;; Set the mode.
4099 (unless (and keep-date copy-keep-date)
4100 (ignore-errors
4101 (set-file-modes newname (tramp-default-file-modes filename)))))
4102
4103 ;; If the operation was `rename', delete the original file.
4104 (unless (eq op 'copy)
4105 (if (file-regular-p filename)
4106 (delete-file filename)
4107 (tramp-compat-delete-directory filename 'recursive))))))
4108
4109 (defun tramp-handle-make-directory (dir &optional parents)
4110 "Like `make-directory' for Tramp files."
4111 (setq dir (expand-file-name dir))
4112 (with-parsed-tramp-file-name dir nil
4113 (tramp-flush-directory-property v (file-name-directory localname))
4114 (save-excursion
4115 (tramp-barf-unless-okay
4116 v
4117 (format "%s %s"
4118 (if parents "mkdir -p" "mkdir")
4119 (tramp-shell-quote-argument localname))
4120 "Couldn't make directory %s" dir))))
4121
4122 (defun tramp-handle-delete-directory (directory &optional recursive)
4123 "Like `delete-directory' for Tramp files."
4124 (setq directory (expand-file-name directory))
4125 (with-parsed-tramp-file-name directory nil
4126 (tramp-flush-file-property v (file-name-directory localname))
4127 (tramp-flush-directory-property v localname)
4128 (unless (zerop (tramp-send-command-and-check
4129 v
4130 (format
4131 "%s %s"
4132 (if recursive "rm -rf" "rmdir")
4133 (tramp-shell-quote-argument localname))))
4134 (tramp-error v 'file-error "Couldn't delete %s" directory))))
4135
4136 (defun tramp-handle-delete-file (filename &optional trash)
4137 "Like `delete-file' for Tramp files."
4138 (setq filename (expand-file-name filename))
4139 (with-parsed-tramp-file-name filename nil
4140 (tramp-flush-file-property v (file-name-directory localname))
4141 (tramp-flush-file-property v localname)
4142 (unless
4143 (zerop
4144 (tramp-send-command-and-check
4145 v (format "%s %s"
4146 (or (and trash (tramp-get-remote-trash v)) "rm -f")
4147 (tramp-shell-quote-argument localname))))
4148 (tramp-error v 'file-error "Couldn't delete %s" filename))))
4149
4150 ;; Dired.
4151
4152 ;; CCC: This does not seem to be enough. Something dies when
4153 ;; we try and delete two directories under Tramp :/
4154 (defun tramp-handle-dired-recursive-delete-directory (filename)
4155 "Recursively delete the directory given.
4156 This is like `dired-recursive-delete-directory' for Tramp files."
4157 (with-parsed-tramp-file-name filename nil
4158 ;; Run a shell command 'rm -r <localname>'
4159 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
4160 (unless (file-exists-p filename)
4161 (tramp-error v 'file-error "No such directory: %s" filename))
4162 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
4163 (tramp-send-command
4164 v
4165 (format "rm -rf %s" (tramp-shell-quote-argument localname))
4166 ;; Don't read the output, do it explicitely.
4167 nil t)
4168 ;; Wait for the remote system to return to us...
4169 ;; This might take a while, allow it plenty of time.
4170 (tramp-wait-for-output (tramp-get-connection-process v) 120)
4171 ;; Make sure that it worked...
4172 (tramp-flush-file-property v (file-name-directory localname))
4173 (tramp-flush-directory-property v localname)
4174 (and (file-exists-p filename)
4175 (tramp-error
4176 v 'file-error "Failed to recursively delete %s" filename))))
4177
4178 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4179 "Like `dired-compress-file' for Tramp files."
4180 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4181 ;; Code stolen mainly from dired-aux.el.
4182 (with-parsed-tramp-file-name file nil
4183 (tramp-flush-file-property v localname)
4184 (save-excursion
4185 (let ((suffixes
4186 (if (not (featurep 'xemacs))
4187 ;; Emacs case
4188 (symbol-value 'dired-compress-file-suffixes)
4189 ;; XEmacs has `dired-compression-method-alist', which is
4190 ;; transformed into `dired-compress-file-suffixes' structure.
4191 (mapcar
4192 (lambda (x)
4193 (list (concat (regexp-quote (nth 1 x)) "\\'")
4194 nil
4195 (mapconcat 'identity (nth 3 x) " ")))
4196 (symbol-value 'dired-compression-method-alist))))
4197 suffix)
4198 ;; See if any suffix rule matches this file name.
4199 (while suffixes
4200 (let (case-fold-search)
4201 (if (string-match (car (car suffixes)) localname)
4202 (setq suffix (car suffixes) suffixes nil))
4203 (setq suffixes (cdr suffixes))))
4204
4205 (cond ((file-symlink-p file)
4206 nil)
4207 ((and suffix (nth 2 suffix))
4208 ;; We found an uncompression rule.
4209 (with-progress-reporter v 0 (format "Uncompressing %s" file)
4210 (when (zerop
4211 (tramp-send-command-and-check
4212 v (concat (nth 2 suffix) " "
4213 (tramp-shell-quote-argument localname))))
4214 ;; `dired-remove-file' is not defined in XEmacs.
4215 (tramp-compat-funcall 'dired-remove-file file)
4216 (string-match (car suffix) file)
4217 (concat (substring file 0 (match-beginning 0))))))
4218 (t
4219 ;; We don't recognize the file as compressed, so compress it.
4220 ;; Try gzip.
4221 (with-progress-reporter v 0 (format "Compressing %s" file)
4222 (when (zerop
4223 (tramp-send-command-and-check
4224 v (concat "gzip -f "
4225 (tramp-shell-quote-argument localname))))
4226 ;; `dired-remove-file' is not defined in XEmacs.
4227 (tramp-compat-funcall 'dired-remove-file file)
4228 (cond ((file-exists-p (concat file ".gz"))
4229 (concat file ".gz"))
4230 ((file-exists-p (concat file ".z"))
4231 (concat file ".z"))
4232 (t nil))))))))))
4233
4234 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4235 "Like `dired-uncache' for Tramp files."
4236 ;; DIR-P is valid for XEmacs only.
4237 (with-parsed-tramp-file-name
4238 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4239 (tramp-flush-directory-property v localname)))
4240
4241 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4242 ;; not sure at all that this is the right way to do it, but let's hope
4243 ;; it works for now, and wait for a guru to point out the Right Way to
4244 ;; achieve this.
4245 ;;(eval-when-compile
4246 ;; (unless (fboundp 'dired-insert-set-properties)
4247 ;; (fset 'dired-insert-set-properties 'ignore)))
4248 ;; Gerd suggests this:
4249 (eval-when-compile (require 'dired))
4250 ;; Note that dired is required at run-time, too, when it is needed.
4251 ;; It is only needed on XEmacs for the function
4252 ;; `dired-insert-set-properties'.
4253
4254 (defun tramp-handle-insert-directory
4255 (filename switches &optional wildcard full-directory-p)
4256 "Like `insert-directory' for Tramp files."
4257 (setq filename (expand-file-name filename))
4258 (with-parsed-tramp-file-name filename nil
4259 (if (and (featurep 'ls-lisp)
4260 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4261 (tramp-run-real-handler
4262 'insert-directory (list filename switches wildcard full-directory-p))
4263 (when (stringp switches)
4264 (setq switches (split-string switches)))
4265 (when (and (member "--dired" switches)
4266 (not (tramp-get-ls-command-with-dired v)))
4267 (setq switches (delete "--dired" switches)))
4268 (when wildcard
4269 (setq wildcard (tramp-run-real-handler
4270 'file-name-nondirectory (list localname)))
4271 (setq localname (tramp-run-real-handler
4272 'file-name-directory (list localname))))
4273 (unless full-directory-p
4274 (setq switches (add-to-list 'switches "-d" 'append)))
4275 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4276 (when wildcard
4277 (setq switches (concat switches " " wildcard)))
4278 (tramp-message
4279 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4280 switches filename (if wildcard "yes" "no")
4281 (if full-directory-p "yes" "no"))
4282 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4283 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4284 (if full-directory-p
4285 (tramp-send-command
4286 v
4287 (format "%s %s %s 2>/dev/null"
4288 (tramp-get-ls-command v)
4289 switches
4290 (if wildcard
4291 localname
4292 (tramp-shell-quote-argument (concat localname ".")))))
4293 (tramp-barf-unless-okay
4294 v
4295 (format "cd %s" (tramp-shell-quote-argument
4296 (tramp-run-real-handler
4297 'file-name-directory (list localname))))
4298 "Couldn't `cd %s'"
4299 (tramp-shell-quote-argument
4300 (tramp-run-real-handler 'file-name-directory (list localname))))
4301 (tramp-send-command
4302 v
4303 (format "%s %s %s"
4304 (tramp-get-ls-command v)
4305 switches
4306 (if (or wildcard
4307 (zerop (length
4308 (tramp-run-real-handler
4309 'file-name-nondirectory (list localname)))))
4310 ""
4311 (tramp-shell-quote-argument
4312 (tramp-run-real-handler
4313 'file-name-nondirectory (list localname)))))))
4314 (let ((beg (point)))
4315 ;; We cannot use `insert-buffer-substring' because the Tramp
4316 ;; buffer changes its contents before insertion due to calling
4317 ;; `expand-file' and alike.
4318 (insert
4319 (with-current-buffer (tramp-get-buffer v)
4320 (buffer-string)))
4321
4322 ;; Check for "--dired" output.
4323 (forward-line -2)
4324 (when (looking-at "//SUBDIRED//")
4325 (forward-line -1))
4326 (when (looking-at "//DIRED//\\s-+")
4327 (let ((databeg (match-end 0))
4328 (end (tramp-compat-line-end-position)))
4329 ;; Now read the numeric positions of file names.
4330 (goto-char databeg)
4331 (while (< (point) end)
4332 (let ((start (+ beg (read (current-buffer))))
4333 (end (+ beg (read (current-buffer)))))
4334 (if (memq (char-after end) '(?\n ?\ ))
4335 ;; End is followed by \n or by " -> ".
4336 (put-text-property start end 'dired-filename t))))))
4337 ;; Remove trailing lines.
4338 (goto-char (tramp-compat-line-beginning-position))
4339 (while (looking-at "//")
4340 (forward-line 1)
4341 (delete-region (match-beginning 0) (point)))
4342
4343 ;; The inserted file could be from somewhere else.
4344 (when (and (not wildcard) (not full-directory-p))
4345 (goto-char (point-max))
4346 (when (file-symlink-p filename)
4347 (goto-char (search-backward "->" beg 'noerror)))
4348 (search-backward
4349 (if (zerop (length (file-name-nondirectory filename)))
4350 "."
4351 (file-name-nondirectory filename))
4352 beg 'noerror)
4353 (replace-match (file-relative-name filename) t))
4354
4355 (goto-char (point-max))))))
4356
4357 (defun tramp-handle-unhandled-file-name-directory (filename)
4358 "Like `unhandled-file-name-directory' for Tramp files."
4359 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4360 ;; for backward compatibility.
4361 (expand-file-name "~/"))
4362
4363 ;; Canonicalization of file names.
4364
4365 (defun tramp-handle-expand-file-name (name &optional dir)
4366 "Like `expand-file-name' for Tramp files.
4367 If the localname part of the given filename starts with \"/../\" then
4368 the result will be a local, non-Tramp, filename."
4369 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4370 (setq dir (or dir default-directory "/"))
4371 ;; Unless NAME is absolute, concat DIR and NAME.
4372 (unless (file-name-absolute-p name)
4373 (setq name (concat (file-name-as-directory dir) name)))
4374 ;; If NAME is not a Tramp file, run the real handler.
4375 (if (not (tramp-connectable-p name))
4376 (tramp-run-real-handler 'expand-file-name (list name nil))
4377 ;; Dissect NAME.
4378 (with-parsed-tramp-file-name name nil
4379 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4380 (setq localname (concat "~/" localname)))
4381 ;; Tilde expansion if necessary. This needs a shell which
4382 ;; groks tilde expansion! The function `tramp-find-shell' is
4383 ;; supposed to find such a shell on the remote host. Please
4384 ;; tell me about it when this doesn't work on your system.
4385 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4386 (let ((uname (match-string 1 localname))
4387 (fname (match-string 2 localname)))
4388 ;; We cannot simply apply "~/", because under sudo "~/" is
4389 ;; expanded to the local user home directory but to the
4390 ;; root home directory. On the other hand, using always
4391 ;; the default user name for tilde expansion is not
4392 ;; appropriate either, because ssh and companions might
4393 ;; use a user name from the config file.
4394 (when (and (string-equal uname "~")
4395 (string-match "\\`su\\(do\\)?\\'" method))
4396 (setq uname (concat uname user)))
4397 (setq uname
4398 (with-connection-property v uname
4399 (tramp-send-command
4400 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4401 (with-current-buffer (tramp-get-buffer v)
4402 (goto-char (point-min))
4403 (buffer-substring
4404 (point) (tramp-compat-line-end-position)))))
4405 (setq localname (concat uname fname))))
4406 ;; There might be a double slash, for example when "~/"
4407 ;; expands to "/". Remove this.
4408 (while (string-match "//" localname)
4409 (setq localname (replace-match "/" t t localname)))
4410 ;; No tilde characters in file name, do normal
4411 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4412 ;; `directory-sep-char' here for XEmacs on Windows, which would
4413 ;; otherwise use backslash. `default-directory' is bound,
4414 ;; because on Windows there would be problems with UNC shares or
4415 ;; Cygwin mounts.
4416 (let ((directory-sep-char ?/)
4417 (default-directory (tramp-compat-temporary-file-directory)))
4418 (tramp-make-tramp-file-name
4419 method user host
4420 (tramp-drop-volume-letter
4421 (tramp-run-real-handler
4422 'expand-file-name (list localname))))))))
4423
4424 (defun tramp-replace-environment-variables (filename)
4425 "Replace environment variables in FILENAME.
4426 Return the string with the replaced variables."
4427 (save-match-data
4428 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4429 ;; `$' is coded as `$$'.
4430 (when (and idx
4431 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4432 (getenv (match-string 1 filename)))
4433 (setq filename
4434 (replace-match
4435 (substitute-in-file-name (match-string 0 filename))
4436 t nil filename)))
4437 filename)))
4438
4439 (defun tramp-handle-substitute-in-file-name (filename)
4440 "Like `substitute-in-file-name' for Tramp files.
4441 \"//\" and \"/~\" substitute only in the local filename part.
4442 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4443 beginning of local filename are not substituted."
4444 ;; First, we must replace environment variables.
4445 (setq filename (tramp-replace-environment-variables filename))
4446 (with-parsed-tramp-file-name filename nil
4447 (if (equal tramp-syntax 'url)
4448 ;; We need to check localname only. The other parts cannot contain
4449 ;; "//" or "/~".
4450 (if (and (> (length localname) 1)
4451 (or (string-match "//" localname)
4452 (string-match "/~" localname 1)))
4453 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4454 (tramp-make-tramp-file-name
4455 (when method (substitute-in-file-name method))
4456 (when user (substitute-in-file-name user))
4457 (when host (substitute-in-file-name host))
4458 (when localname
4459 (tramp-run-real-handler
4460 'substitute-in-file-name (list localname)))))
4461 ;; Ignore in LOCALNAME everything before "//" or "/~".
4462 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4463 (setq filename
4464 (concat (file-remote-p filename)
4465 (replace-match "\\1" nil nil localname)))
4466 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4467 (when (string-match "~$" filename)
4468 (setq filename (concat filename "/"))))
4469 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4470
4471 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4472 ;; which calls corresponding functions (see minibuf.el).
4473 (when (fboundp 'minibuffer-electric-separator)
4474 (mapc
4475 (lambda (x)
4476 (eval
4477 `(defadvice ,x
4478 (around ,(intern (format "tramp-advice-%s" x)) activate)
4479 "Invoke `substitute-in-file-name' for Tramp files."
4480 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4481 (tramp-tramp-file-p (buffer-substring)))
4482 ;; We don't need to handle `last-input-event', because
4483 ;; due to the key map we know it must be ?/ or ?~.
4484 (let ((s (concat (buffer-substring (point-min) (point))
4485 (string last-command-char))))
4486 (delete-region (point-min) (point))
4487 (insert (substitute-in-file-name s))
4488 (setq ad-return-value last-command-char))
4489 ad-do-it)))
4490 (eval
4491 `(add-hook
4492 'tramp-unload-hook
4493 (lambda ()
4494 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4495 (ad-activate ',x)))))
4496
4497 '(minibuffer-electric-separator
4498 minibuffer-electric-tilde)))
4499
4500
4501 ;;; Remote commands:
4502
4503 (defun tramp-handle-executable-find (command)
4504 "Like `executable-find' for Tramp files."
4505 (with-parsed-tramp-file-name default-directory nil
4506 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4507
4508 (defun tramp-process-sentinel (proc event)
4509 "Flush file caches."
4510 (unless (memq (process-status proc) '(run open))
4511 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4512 (when vec
4513 (tramp-message vec 5 "Sentinel called: `%s' `%s'" proc event)
4514 (tramp-flush-directory-property vec "")))))
4515
4516 ;; We use BUFFER also as connection buffer during setup. Because of
4517 ;; this, its original contents must be saved, and restored once
4518 ;; connection has been setup.
4519 (defun tramp-handle-start-file-process (name buffer program &rest args)
4520 "Like `start-file-process' for Tramp files."
4521 (with-parsed-tramp-file-name default-directory nil
4522 (unwind-protect
4523 ;; When PROGRAM is nil, we just provide a tty.
4524 (let ((command
4525 (when (stringp program)
4526 (format "cd %s; exec %s"
4527 (tramp-shell-quote-argument localname)
4528 (mapconcat 'tramp-shell-quote-argument
4529 (cons program args) " "))))
4530 (tramp-process-connection-type
4531 (or (null program) tramp-process-connection-type))
4532 (name1 name)
4533 (i 0))
4534 (unless buffer
4535 ;; BUFFER can be nil. We use a temporary buffer.
4536 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4537 (while (get-process name1)
4538 ;; NAME must be unique as process name.
4539 (setq i (1+ i)
4540 name1 (format "%s<%d>" name i)))
4541 (setq name name1)
4542 ;; Set the new process properties.
4543 (tramp-set-connection-property v "process-name" name)
4544 (tramp-set-connection-property v "process-buffer" buffer)
4545 ;; Activate narrowing in order to save BUFFER contents.
4546 ;; Clear also the modification time; otherwise we might be
4547 ;; interrupted by `verify-visited-file-modtime'.
4548 (with-current-buffer (tramp-get-connection-buffer v)
4549 (clear-visited-file-modtime)
4550 (narrow-to-region (point-max) (point-max)))
4551 (if command
4552 ;; Send the command.
4553 (tramp-send-command v command nil t) ; nooutput
4554 ;; Check, whether a pty is associated.
4555 (tramp-maybe-open-connection v)
4556 (unless (process-get (tramp-get-connection-process v) 'remote-tty)
4557 (tramp-error
4558 v 'file-error "pty association is not supported for `%s'" name)))
4559 (let ((p (tramp-get-connection-process v)))
4560 ;; Set sentinel and query flag for this process.
4561 (tramp-set-connection-property p "vector" v)
4562 (set-process-sentinel p 'tramp-process-sentinel)
4563 (tramp-set-process-query-on-exit-flag p t)
4564 ;; Return process.
4565 p))
4566 ;; Save exit.
4567 (with-current-buffer (tramp-get-connection-buffer v)
4568 (if (string-match tramp-temp-buffer-name (buffer-name))
4569 (progn
4570 (set-process-buffer (tramp-get-connection-process v) nil)
4571 (kill-buffer (current-buffer)))
4572 (widen)
4573 (goto-char (point-max))))
4574 (tramp-set-connection-property v "process-name" nil)
4575 (tramp-set-connection-property v "process-buffer" nil))))
4576
4577 (defun tramp-handle-process-file
4578 (program &optional infile destination display &rest args)
4579 "Like `process-file' for Tramp files."
4580 ;; The implementation is not complete yet.
4581 (when (and (numberp destination) (zerop destination))
4582 (error "Implementation does not handle immediate return"))
4583
4584 (with-parsed-tramp-file-name default-directory nil
4585 (let (command input tmpinput stderr tmpstderr outbuf ret)
4586 ;; Compute command.
4587 (setq command (mapconcat 'tramp-shell-quote-argument
4588 (cons program args) " "))
4589 ;; Determine input.
4590 (if (null infile)
4591 (setq input "/dev/null")
4592 (setq infile (expand-file-name infile))
4593 (if (tramp-equal-remote default-directory infile)
4594 ;; INFILE is on the same remote host.
4595 (setq input (with-parsed-tramp-file-name infile nil localname))
4596 ;; INFILE must be copied to remote host.
4597 (setq input (tramp-make-tramp-temp-file v)
4598 tmpinput (tramp-make-tramp-file-name method user host input))
4599 (copy-file infile tmpinput t)))
4600 (when input (setq command (format "%s <%s" command input)))
4601
4602 ;; Determine output.
4603 (cond
4604 ;; Just a buffer.
4605 ((bufferp destination)
4606 (setq outbuf destination))
4607 ;; A buffer name.
4608 ((stringp destination)
4609 (setq outbuf (get-buffer-create destination)))
4610 ;; (REAL-DESTINATION ERROR-DESTINATION)
4611 ((consp destination)
4612 ;; output.
4613 (cond
4614 ((bufferp (car destination))
4615 (setq outbuf (car destination)))
4616 ((stringp (car destination))
4617 (setq outbuf (get-buffer-create (car destination))))
4618 ((car destination)
4619 (setq outbuf (current-buffer))))
4620 ;; stderr.
4621 (cond
4622 ((stringp (cadr destination))
4623 (setcar (cdr destination) (expand-file-name (cadr destination)))
4624 (if (tramp-equal-remote default-directory (cadr destination))
4625 ;; stderr is on the same remote host.
4626 (setq stderr (with-parsed-tramp-file-name
4627 (cadr destination) nil localname))
4628 ;; stderr must be copied to remote host. The temporary
4629 ;; file must be deleted after execution.
4630 (setq stderr (tramp-make-tramp-temp-file v)
4631 tmpstderr (tramp-make-tramp-file-name
4632 method user host stderr))))
4633 ;; stderr to be discarded.
4634 ((null (cadr destination))
4635 (setq stderr "/dev/null"))))
4636 ;; 't
4637 (destination
4638 (setq outbuf (current-buffer))))
4639 (when stderr (setq command (format "%s 2>%s" command stderr)))
4640
4641 ;; Send the command. It might not return in time, so we protect it.
4642 (condition-case nil
4643 (unwind-protect
4644 (setq ret
4645 (tramp-send-command-and-check
4646 v (format "\\cd %s; %s"
4647 (tramp-shell-quote-argument localname)
4648 command)
4649 nil t))
4650 ;; We should show the output anyway.
4651 (when outbuf
4652 (with-current-buffer outbuf
4653 (insert
4654 (with-current-buffer (tramp-get-connection-buffer v)
4655 (buffer-string))))
4656 (when display (display-buffer outbuf))))
4657 ;; When the user did interrupt, we should do it also. We use
4658 ;; return code -1 as marker.
4659 (quit
4660 (kill-buffer (tramp-get-connection-buffer v))
4661 (setq ret -1))
4662 ;; Handle errors.
4663 (error
4664 (kill-buffer (tramp-get-connection-buffer v))
4665 (setq ret 1)))
4666
4667 ;; Provide error file.
4668 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4669
4670 ;; Cleanup. We remove all file cache values for the connection,
4671 ;; because the remote process could have changed them.
4672 (when tmpinput (delete-file tmpinput))
4673
4674 ;; `process-file-side-effects' has been introduced with GNU
4675 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4676 ;; by `program'. If it doesn't exist, we assume its default
4677 ;; value 't'.
4678 (unless (and (boundp 'process-file-side-effects)
4679 (not (symbol-value 'process-file-side-effects)))
4680 (tramp-flush-directory-property v ""))
4681
4682 ;; Return exit status.
4683 (if (equal ret -1)
4684 (keyboard-quit)
4685 ret))))
4686
4687 (defun tramp-local-call-process
4688 (program &optional infile destination display &rest args)
4689 "Calls `call-process' on the local host.
4690 This is needed because for some Emacs flavors Tramp has
4691 defadviced `call-process' to behave like `process-file'. The
4692 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4693 (let ((default-directory
4694 (if (file-remote-p default-directory)
4695 (tramp-compat-temporary-file-directory)
4696 default-directory)))
4697 (if (executable-find program)
4698 (apply 'call-process program infile destination display args)
4699 1)))
4700
4701 (defun tramp-handle-call-process-region
4702 (start end program &optional delete buffer display &rest args)
4703 "Like `call-process-region' for Tramp files."
4704 (let ((tmpfile (tramp-compat-make-temp-file "")))
4705 (write-region start end tmpfile)
4706 (when delete (delete-region start end))
4707 (unwind-protect
4708 (apply 'call-process program tmpfile buffer display args)
4709 (delete-file tmpfile))))
4710
4711 (defun tramp-handle-shell-command
4712 (command &optional output-buffer error-buffer)
4713 "Like `shell-command' for Tramp files."
4714 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4715 ;; We cannot use `shell-file-name' and `shell-command-switch',
4716 ;; they are variables of the local host.
4717 (args (list
4718 (tramp-get-method-parameter
4719 (tramp-file-name-method
4720 (tramp-dissect-file-name default-directory))
4721 'tramp-remote-sh)
4722 "-c" (substring command 0 asynchronous)))
4723 current-buffer-p
4724 (output-buffer
4725 (cond
4726 ((bufferp output-buffer) output-buffer)
4727 ((stringp output-buffer) (get-buffer-create output-buffer))
4728 (output-buffer
4729 (setq current-buffer-p t)
4730 (current-buffer))
4731 (t (get-buffer-create
4732 (if asynchronous
4733 "*Async Shell Command*"
4734 "*Shell Command Output*")))))
4735 (error-buffer
4736 (cond
4737 ((bufferp error-buffer) error-buffer)
4738 ((stringp error-buffer) (get-buffer-create error-buffer))))
4739 (buffer
4740 (if (and (not asynchronous) error-buffer)
4741 (with-parsed-tramp-file-name default-directory nil
4742 (list output-buffer (tramp-make-tramp-temp-file v)))
4743 output-buffer))
4744 (p (get-buffer-process output-buffer)))
4745
4746 ;; Check whether there is another process running. Tramp does not
4747 ;; support 2 (asynchronous) processes in parallel.
4748 (when p
4749 (if (yes-or-no-p "A command is running. Kill it? ")
4750 (condition-case nil
4751 (kill-process p)
4752 (error nil))
4753 (error "Shell command in progress")))
4754
4755 (if current-buffer-p
4756 (progn
4757 (barf-if-buffer-read-only)
4758 (push-mark nil t))
4759 (with-current-buffer output-buffer
4760 (setq buffer-read-only nil)
4761 (erase-buffer)))
4762
4763 (if (and (not current-buffer-p) (integerp asynchronous))
4764 (prog1
4765 ;; Run the process.
4766 (apply 'start-file-process "*Async Shell*" buffer args)
4767 ;; Display output.
4768 (pop-to-buffer output-buffer)
4769 (setq mode-line-process '(":%s"))
4770 (require 'shell) (shell-mode))
4771
4772 (prog1
4773 ;; Run the process.
4774 (apply 'process-file (car args) nil buffer nil (cdr args))
4775 ;; Insert error messages if they were separated.
4776 (when (listp buffer)
4777 (with-current-buffer error-buffer
4778 (insert-file-contents (cadr buffer)))
4779 (delete-file (cadr buffer)))
4780 (if current-buffer-p
4781 ;; This is like exchange-point-and-mark, but doesn't
4782 ;; activate the mark. It is cleaner to avoid activation,
4783 ;; even though the command loop would deactivate the mark
4784 ;; because we inserted text.
4785 (goto-char (prog1 (mark t)
4786 (set-marker (mark-marker) (point)
4787 (current-buffer))))
4788 ;; There's some output, display it.
4789 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4790 (if (functionp 'display-message-or-buffer)
4791 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
4792 (pop-to-buffer output-buffer))))))))
4793
4794 ;; File Editing.
4795
4796 (defvar tramp-handle-file-local-copy-hook nil
4797 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4798
4799 (defun tramp-handle-file-local-copy (filename)
4800 "Like `file-local-copy' for Tramp files."
4801
4802 (with-parsed-tramp-file-name filename nil
4803 (unless (file-exists-p filename)
4804 (tramp-error
4805 v 'file-error
4806 "Cannot make local copy of non-existing file `%s'" filename))
4807
4808 (let* ((size (nth 7 (file-attributes filename)))
4809 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
4810 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
4811 (tmpfile (tramp-compat-make-temp-file filename)))
4812
4813 (condition-case err
4814 (cond
4815 ;; `copy-file' handles direct copy and out-of-band methods.
4816 ((or (tramp-local-host-p v)
4817 (tramp-method-out-of-band-p v size))
4818 (copy-file filename tmpfile t t))
4819
4820 ;; Use inline encoding for file transfer.
4821 (rem-enc
4822 (save-excursion
4823 (with-progress-reporter
4824 v 3 (format "Encoding remote file %s" filename)
4825 (tramp-barf-unless-okay
4826 v (format rem-enc (tramp-shell-quote-argument localname))
4827 "Encoding remote file failed"))
4828
4829 (if (functionp loc-dec)
4830 ;; If local decoding is a function, we call it. We
4831 ;; must disable multibyte, because
4832 ;; `uudecode-decode-region' doesn't handle it
4833 ;; correctly.
4834 (with-temp-buffer
4835 (set-buffer-multibyte nil)
4836 (insert-buffer-substring (tramp-get-buffer v))
4837 (with-progress-reporter
4838 v 3 (format "Decoding remote file %s with function %s"
4839 filename loc-dec)
4840 (funcall loc-dec (point-min) (point-max))
4841 ;; Unset `file-name-handler-alist'. Otherwise,
4842 ;; epa-file gets confused.
4843 (let (file-name-handler-alist
4844 (coding-system-for-write 'binary))
4845 (write-region (point-min) (point-max) tmpfile))))
4846
4847 ;; If tramp-decoding-function is not defined for this
4848 ;; method, we invoke tramp-decoding-command instead.
4849 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4850 ;; Unset `file-name-handler-alist'. Otherwise,
4851 ;; epa-file gets confused.
4852 (let (file-name-handler-alist
4853 (coding-system-for-write 'binary))
4854 (write-region (point-min) (point-max) tmpfile2))
4855 (with-progress-reporter
4856 v 3 (format "Decoding remote file %s with command %s"
4857 filename loc-dec)
4858 (unwind-protect
4859 (tramp-call-local-coding-command
4860 loc-dec tmpfile2 tmpfile)
4861 (delete-file tmpfile2)))))
4862
4863 ;; Set proper permissions.
4864 (set-file-modes tmpfile (tramp-default-file-modes filename))
4865 ;; Set local user ownership.
4866 (tramp-set-file-uid-gid tmpfile)))
4867
4868 ;; Oops, I don't know what to do.
4869 (t (tramp-error
4870 v 'file-error "Wrong method specification for `%s'" method)))
4871
4872 ;; Error handling.
4873 ((error quit)
4874 (delete-file tmpfile)
4875 (signal (car err) (cdr err))))
4876
4877 (run-hooks 'tramp-handle-file-local-copy-hook)
4878 tmpfile)))
4879
4880 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4881 "Like `file-remote-p' for Tramp files."
4882 (let ((tramp-verbose 3))
4883 (when (tramp-tramp-file-p filename)
4884 (let* ((v (tramp-dissect-file-name filename))
4885 (p (tramp-get-connection-process v))
4886 (c (and p (processp p) (memq (process-status p) '(run open)))))
4887 ;; We expand the file name only, if there is already a connection.
4888 (with-parsed-tramp-file-name
4889 (if c (expand-file-name filename) filename) nil
4890 (and (or (not connected) c)
4891 (cond
4892 ((eq identification 'method) method)
4893 ((eq identification 'user) user)
4894 ((eq identification 'host) host)
4895 ((eq identification 'localname) localname)
4896 (t (tramp-make-tramp-file-name method user host "")))))))))
4897
4898 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4899 "Like `find-operation-coding-system' for Tramp filenames.
4900 Tramp's `insert-file-contents' and `write-region' work over
4901 temporary file names. If `file-coding-system-alist' contains an
4902 expression, which matches more than the file name suffix, the
4903 coding system might not be determined. This function repairs it."
4904 (let (result)
4905 (dolist (elt file-coding-system-alist result)
4906 (when (and (consp elt) (string-match (car elt) filename))
4907 ;; We found a matching entry in `file-coding-system-alist'.
4908 ;; So we add a similar entry, but with the temporary file name
4909 ;; as regexp.
4910 (add-to-list
4911 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4912
4913 (defun tramp-handle-insert-file-contents
4914 (filename &optional visit beg end replace)
4915 "Like `insert-file-contents' for Tramp files."
4916 (barf-if-buffer-read-only)
4917 (setq filename (expand-file-name filename))
4918 (let (result local-copy remote-copy)
4919 (with-parsed-tramp-file-name filename nil
4920 (unwind-protect
4921 (if (not (file-exists-p filename))
4922 ;; We don't raise a Tramp error, because it might be
4923 ;; suppressed, like in `find-file-noselect-1'.
4924 (signal 'file-error
4925 (list "File not found on remote host" filename))
4926
4927 (if (and (tramp-local-host-p v)
4928 (let (file-name-handler-alist)
4929 (file-readable-p localname)))
4930 ;; Short track: if we are on the local host, we can
4931 ;; run directly.
4932 (setq result
4933 (tramp-run-real-handler
4934 'insert-file-contents
4935 (list localname visit beg end replace)))
4936
4937 ;; When we shall insert only a part of the file, we copy
4938 ;; this part.
4939 (when (or beg end)
4940 (setq remote-copy (tramp-make-tramp-temp-file v))
4941 (tramp-send-command
4942 v
4943 (cond
4944 ((and beg end)
4945 (format "tail -c +%d %s | head -c +%d >%s"
4946 (1+ beg) (tramp-shell-quote-argument localname)
4947 (- end beg) remote-copy))
4948 (beg
4949 (format "tail -c +%d %s >%s"
4950 (1+ beg) (tramp-shell-quote-argument localname)
4951 remote-copy))
4952 (end
4953 (format "head -c +%d %s >%s"
4954 (1+ end) (tramp-shell-quote-argument localname)
4955 remote-copy)))))
4956
4957 ;; `insert-file-contents-literally' takes care to avoid
4958 ;; calling jka-compr. By let-binding
4959 ;; `inhibit-file-name-operation', we propagate that care
4960 ;; to the `file-local-copy' operation.
4961 (setq local-copy
4962 (let ((inhibit-file-name-operation
4963 (when (eq inhibit-file-name-operation
4964 'insert-file-contents)
4965 'file-local-copy)))
4966 (cond
4967 ((stringp remote-copy)
4968 (file-local-copy
4969 (tramp-make-tramp-file-name
4970 method user host remote-copy)))
4971 ((stringp tramp-temp-buffer-file-name)
4972 (copy-file filename tramp-temp-buffer-file-name 'ok)
4973 tramp-temp-buffer-file-name)
4974 (t (file-local-copy filename)))))
4975
4976 ;; When the file is not readable for the owner, it
4977 ;; cannot be inserted, even it is redable for the group
4978 ;; or for everybody.
4979 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4980
4981 (when (and (null remote-copy)
4982 (tramp-get-method-parameter
4983 method 'tramp-copy-keep-tmpfile))
4984 ;; We keep the local file for performance reasons,
4985 ;; useful for "rsync".
4986 (setq tramp-temp-buffer-file-name local-copy)
4987 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4988
4989 (with-progress-reporter
4990 v 3 (format "Inserting local temp file `%s'" local-copy)
4991 ;; We must ensure that `file-coding-system-alist'
4992 ;; matches `local-copy'.
4993 (let ((file-coding-system-alist
4994 (tramp-find-file-name-coding-system-alist
4995 filename local-copy)))
4996 (setq result
4997 (insert-file-contents
4998 local-copy nil nil nil replace))))))
4999
5000 ;; Save exit.
5001 (progn
5002 (when visit
5003 (setq buffer-file-name filename)
5004 (setq buffer-read-only (not (file-writable-p filename)))
5005 (set-visited-file-modtime)
5006 (set-buffer-modified-p nil))
5007 (when (and (stringp local-copy)
5008 (or remote-copy (null tramp-temp-buffer-file-name)))
5009 (delete-file local-copy))
5010 (when (stringp remote-copy)
5011 (delete-file
5012 (tramp-make-tramp-file-name method user host remote-copy))))))
5013
5014 ;; Result.
5015 (list (expand-file-name filename)
5016 (cadr result))))
5017
5018 ;; This is needed for XEmacs only. Code stolen from files.el.
5019 (defun tramp-handle-insert-file-contents-literally
5020 (filename &optional visit beg end replace)
5021 "Like `insert-file-contents-literally' for Tramp files."
5022 (let ((format-alist nil)
5023 (after-insert-file-functions nil)
5024 (coding-system-for-read 'no-conversion)
5025 (coding-system-for-write 'no-conversion)
5026 (find-buffer-file-type-function
5027 (if (fboundp 'find-buffer-file-type)
5028 (symbol-function 'find-buffer-file-type)
5029 nil))
5030 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
5031 (inhibit-file-name-operation 'insert-file-contents))
5032 (unwind-protect
5033 (progn
5034 (fset 'find-buffer-file-type (lambda (filename) t))
5035 (insert-file-contents filename visit beg end replace))
5036 ;; Save exit.
5037 (if find-buffer-file-type-function
5038 (fset 'find-buffer-file-type find-buffer-file-type-function)
5039 (fmakunbound 'find-buffer-file-type)))))
5040
5041 (defun tramp-handle-find-backup-file-name (filename)
5042 "Like `find-backup-file-name' for Tramp files."
5043 (with-parsed-tramp-file-name filename nil
5044 ;; We set both variables. It doesn't matter whether it is
5045 ;; Emacs or XEmacs.
5046 (let ((backup-directory-alist
5047 ;; Emacs case.
5048 (when (boundp 'backup-directory-alist)
5049 (if (symbol-value 'tramp-backup-directory-alist)
5050 (mapcar
5051 (lambda (x)
5052 (cons
5053 (car x)
5054 (if (and (stringp (cdr x))
5055 (file-name-absolute-p (cdr x))
5056 (not (tramp-file-name-p (cdr x))))
5057 (tramp-make-tramp-file-name method user host (cdr x))
5058 (cdr x))))
5059 (symbol-value 'tramp-backup-directory-alist))
5060 (symbol-value 'backup-directory-alist))))
5061
5062 (bkup-backup-directory-info
5063 ;; XEmacs case.
5064 (when (boundp 'bkup-backup-directory-info)
5065 (if (symbol-value 'tramp-bkup-backup-directory-info)
5066 (mapcar
5067 (lambda (x)
5068 (nconc
5069 (list (car x))
5070 (list
5071 (if (and (stringp (car (cdr x)))
5072 (file-name-absolute-p (car (cdr x)))
5073 (not (tramp-file-name-p (car (cdr x)))))
5074 (tramp-make-tramp-file-name
5075 method user host (car (cdr x)))
5076 (car (cdr x))))
5077 (cdr (cdr x))))
5078 (symbol-value 'tramp-bkup-backup-directory-info))
5079 (symbol-value 'bkup-backup-directory-info)))))
5080
5081 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
5082
5083 (defun tramp-handle-make-auto-save-file-name ()
5084 "Like `make-auto-save-file-name' for Tramp files.
5085 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
5086 (let ((tramp-auto-save-directory tramp-auto-save-directory)
5087 (buffer-file-name
5088 (tramp-subst-strs-in-string
5089 '(("_" . "|")
5090 ("/" . "_a")
5091 (":" . "_b")
5092 ("|" . "__")
5093 ("[" . "_l")
5094 ("]" . "_r"))
5095 (buffer-file-name))))
5096 ;; File name must be unique. This is ensured with Emacs 22 (see
5097 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
5098 ;; all other cases we must do it ourselves.
5099 (when (boundp 'auto-save-file-name-transforms)
5100 (mapc
5101 (lambda (x)
5102 (when (and (string-match (car x) buffer-file-name)
5103 (not (car (cddr x))))
5104 (setq tramp-auto-save-directory
5105 (or tramp-auto-save-directory
5106 (tramp-compat-temporary-file-directory)))))
5107 (symbol-value 'auto-save-file-name-transforms)))
5108 ;; Create directory.
5109 (when tramp-auto-save-directory
5110 (setq buffer-file-name
5111 (expand-file-name buffer-file-name tramp-auto-save-directory))
5112 (unless (file-exists-p tramp-auto-save-directory)
5113 (make-directory tramp-auto-save-directory t)))
5114 ;; Run plain `make-auto-save-file-name'. There might be an advice when
5115 ;; it is not a magic file name operation (since Emacs 22).
5116 ;; We must deactivate it temporarily.
5117 (if (not (ad-is-active 'make-auto-save-file-name))
5118 (tramp-run-real-handler 'make-auto-save-file-name nil)
5119 ;; else
5120 (ad-deactivate 'make-auto-save-file-name)
5121 (prog1
5122 (tramp-run-real-handler 'make-auto-save-file-name nil)
5123 (ad-activate 'make-auto-save-file-name)))))
5124
5125 (defvar tramp-handle-write-region-hook nil
5126 "Normal hook to be run at the end of `tramp-handle-write-region'.")
5127
5128 ;; CCC grok LOCKNAME
5129 (defun tramp-handle-write-region
5130 (start end filename &optional append visit lockname confirm)
5131 "Like `write-region' for Tramp files."
5132 (setq filename (expand-file-name filename))
5133 (with-parsed-tramp-file-name filename nil
5134 ;; Following part commented out because we don't know what to do about
5135 ;; file locking, and it does not appear to be a problem to ignore it.
5136 ;; Ange-ftp ignores it, too.
5137 ;; (when (and lockname (stringp lockname))
5138 ;; (setq lockname (expand-file-name lockname)))
5139 ;; (unless (or (eq lockname nil)
5140 ;; (string= lockname filename))
5141 ;; (error
5142 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
5143
5144 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
5145 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
5146 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
5147 (tramp-error v 'file-error "File not overwritten")))
5148
5149 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
5150 (tramp-get-remote-uid v 'integer)))
5151 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
5152 (tramp-get-remote-gid v 'integer))))
5153
5154 (if (and (tramp-local-host-p v)
5155 ;; `file-writable-p' calls `file-expand-file-name'. We
5156 ;; cannot use `tramp-run-real-handler' therefore.
5157 (let (file-name-handler-alist)
5158 (and
5159 (file-writable-p (file-name-directory localname))
5160 (or (file-directory-p localname)
5161 (file-writable-p localname)))))
5162 ;; Short track: if we are on the local host, we can run directly.
5163 (tramp-run-real-handler
5164 'write-region
5165 (list start end localname append 'no-message lockname confirm))
5166
5167 (let ((modes (save-excursion (tramp-default-file-modes filename)))
5168 ;; We use this to save the value of
5169 ;; `last-coding-system-used' after writing the tmp
5170 ;; file. At the end of the function, we set
5171 ;; `last-coding-system-used' to this saved value. This
5172 ;; way, any intermediary coding systems used while
5173 ;; talking to the remote shell or suchlike won't hose
5174 ;; this variable. This approach was snarfed from
5175 ;; ange-ftp.el.
5176 coding-system-used
5177 ;; Write region into a tmp file. This isn't really
5178 ;; needed if we use an encoding function, but currently
5179 ;; we use it always because this makes the logic
5180 ;; simpler.
5181 (tmpfile (or tramp-temp-buffer-file-name
5182 (tramp-compat-make-temp-file filename))))
5183
5184 ;; If `append' is non-nil, we copy the file locally, and let
5185 ;; the native `write-region' implementation do the job.
5186 (when append (copy-file filename tmpfile 'ok))
5187
5188 ;; We say `no-message' here because we don't want the
5189 ;; visited file modtime data to be clobbered from the temp
5190 ;; file. We call `set-visited-file-modtime' ourselves later
5191 ;; on. We must ensure that `file-coding-system-alist'
5192 ;; matches `tmpfile'.
5193 (let (file-name-handler-alist
5194 (file-coding-system-alist
5195 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5196 (condition-case err
5197 (tramp-run-real-handler
5198 'write-region
5199 (list start end tmpfile append 'no-message lockname confirm))
5200 ((error quit)
5201 (setq tramp-temp-buffer-file-name nil)
5202 (delete-file tmpfile)
5203 (signal (car err) (cdr err))))
5204
5205 ;; Now, `last-coding-system-used' has the right value. Remember it.
5206 (when (boundp 'last-coding-system-used)
5207 (setq coding-system-used
5208 (symbol-value 'last-coding-system-used))))
5209
5210 ;; The permissions of the temporary file should be set. If
5211 ;; filename does not exist (eq modes nil) it has been
5212 ;; renamed to the backup file. This case `save-buffer'
5213 ;; handles permissions.
5214 ;; Ensure, that it is still readable.
5215 (when modes
5216 (set-file-modes
5217 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
5218
5219 ;; This is a bit lengthy due to the different methods
5220 ;; possible for file transfer. First, we check whether the
5221 ;; method uses an rcp program. If so, we call it.
5222 ;; Otherwise, both encoding and decoding command must be
5223 ;; specified. However, if the method _also_ specifies an
5224 ;; encoding function, then that is used for encoding the
5225 ;; contents of the tmp file.
5226 (let* ((size (nth 7 (file-attributes tmpfile)))
5227 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
5228 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
5229 (cond
5230 ;; `copy-file' handles direct copy and out-of-band methods.
5231 ((or (tramp-local-host-p v)
5232 (tramp-method-out-of-band-p v size))
5233 (if (and (not (stringp start))
5234 (= (or end (point-max)) (point-max))
5235 (= (or start (point-min)) (point-min))
5236 (tramp-get-method-parameter
5237 method 'tramp-copy-keep-tmpfile))
5238 (progn
5239 (setq tramp-temp-buffer-file-name tmpfile)
5240 (condition-case err
5241 ;; We keep the local file for performance
5242 ;; reasons, useful for "rsync".
5243 (copy-file tmpfile filename t)
5244 ((error quit)
5245 (setq tramp-temp-buffer-file-name nil)
5246 (delete-file tmpfile)
5247 (signal (car err) (cdr err)))))
5248 (setq tramp-temp-buffer-file-name nil)
5249 ;; Don't rename, in order to keep context in SELinux.
5250 (unwind-protect
5251 (copy-file tmpfile filename t)
5252 (delete-file tmpfile))))
5253
5254 ;; Use inline file transfer.
5255 (rem-dec
5256 ;; Encode tmpfile.
5257 (unwind-protect
5258 (with-temp-buffer
5259 (set-buffer-multibyte nil)
5260 ;; Use encoding function or command.
5261 (if (functionp loc-enc)
5262 (with-progress-reporter
5263 v 3 (format "Encoding region using function `%s'"
5264 loc-enc)
5265 (let ((coding-system-for-read 'binary))
5266 (insert-file-contents-literally tmpfile))
5267 ;; The following `let' is a workaround for the
5268 ;; base64.el that comes with pgnus-0.84. If
5269 ;; both of the following conditions are
5270 ;; satisfied, it tries to write to a local
5271 ;; file in default-directory, but at this
5272 ;; point, default-directory is remote.
5273 ;; (`call-process-region' can't write to
5274 ;; remote files, it seems.) The file in
5275 ;; question is a tmp file anyway.
5276 (let ((default-directory
5277 (tramp-compat-temporary-file-directory)))
5278 (funcall loc-enc (point-min) (point-max))))
5279
5280 (with-progress-reporter
5281 v 3 (format "Encoding region using command `%s'"
5282 loc-enc)
5283 (unless (zerop (tramp-call-local-coding-command
5284 loc-enc tmpfile t))
5285 (tramp-error
5286 v 'file-error
5287 (concat "Cannot write to `%s', "
5288 "local encoding command `%s' failed")
5289 filename loc-enc))))
5290
5291 ;; Send buffer into remote decoding command which
5292 ;; writes to remote file. Because this happens on
5293 ;; the remote host, we cannot use the function.
5294 (with-progress-reporter
5295 v 3
5296 (format "Decoding region into remote file %s" filename)
5297 (goto-char (point-max))
5298 (unless (bolp) (newline))
5299 (tramp-send-command
5300 v
5301 (format
5302 (concat rem-dec " <<'EOF'\n%sEOF")
5303 (tramp-shell-quote-argument localname)
5304 (buffer-string)))
5305 (tramp-barf-unless-okay
5306 v nil
5307 "Couldn't write region to `%s', decode using `%s' failed"
5308 filename rem-dec)
5309 ;; When `file-precious-flag' is set, the region is
5310 ;; written to a temporary file. Check that the
5311 ;; checksum is equal to that from the local tmpfile.
5312 (when file-precious-flag
5313 (erase-buffer)
5314 (and
5315 ;; cksum runs locally, if possible.
5316 (zerop (tramp-local-call-process "cksum" tmpfile t))
5317 ;; cksum runs remotely.
5318 (zerop
5319 (tramp-send-command-and-check
5320 v
5321 (format
5322 "cksum <%s"
5323 (tramp-shell-quote-argument localname))))
5324 ;; ... they are different.
5325 (not
5326 (string-equal
5327 (buffer-string)
5328 (with-current-buffer (tramp-get-buffer v)
5329 (buffer-string))))
5330 (tramp-error
5331 v 'file-error
5332 (concat "Couldn't write region to `%s',"
5333 " decode using `%s' failed")
5334 filename rem-dec)))))
5335
5336 ;; Save exit.
5337 (delete-file tmpfile)))
5338
5339 ;; That's not expected.
5340 (t
5341 (tramp-error
5342 v 'file-error
5343 (concat "Method `%s' should specify both encoding and "
5344 "decoding command or an rcp program")
5345 method))))
5346
5347 ;; Make `last-coding-system-used' have the right value.
5348 (when coding-system-used
5349 (set 'last-coding-system-used coding-system-used))))
5350
5351 (tramp-flush-file-property v (file-name-directory localname))
5352 (tramp-flush-file-property v localname)
5353
5354 ;; We must protect `last-coding-system-used', now we have set it
5355 ;; to its correct value.
5356 (let (last-coding-system-used (need-chown t))
5357 ;; Set file modification time.
5358 (when (or (eq visit t) (stringp visit))
5359 (let ((file-attr (file-attributes filename)))
5360 (set-visited-file-modtime
5361 ;; We must pass modtime explicitely, because filename can
5362 ;; be different from (buffer-file-name), f.e. if
5363 ;; `file-precious-flag' is set.
5364 (nth 5 file-attr))
5365 (when (and (eq (nth 2 file-attr) uid)
5366 (eq (nth 3 file-attr) gid))
5367 (setq need-chown nil))))
5368
5369 ;; Set the ownership.
5370 (when need-chown
5371 (tramp-set-file-uid-gid filename uid gid))
5372 (when (or (eq visit t) (null visit) (stringp visit))
5373 (tramp-message v 0 "Wrote %s" filename))
5374 (run-hooks 'tramp-handle-write-region-hook)))))
5375
5376 (defvar tramp-vc-registered-file-names nil
5377 "List used to collect file names, which are checked during `vc-registered'.")
5378
5379 ;; VC backends check for the existence of various different special
5380 ;; files. This is very time consuming, because every single check
5381 ;; requires a remote command (the file cache must be invalidated).
5382 ;; Therefore, we apply a kind of optimization. We install the file
5383 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5384 ;; remembers all file names for which `file-exists-p' or
5385 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5386 ;; is performed. Afterwards, a script is applied for all collected
5387 ;; file names, using just one remote command. The result of this
5388 ;; script is used to fill the file cache with actual values. Now we
5389 ;; can reset the file name handlers, and we make a second run of
5390 ;; `vc-registered', which returns the expected result without sending
5391 ;; any other remote command.
5392 (defun tramp-handle-vc-registered (file)
5393 "Like `vc-registered' for Tramp files."
5394 (with-temp-message ""
5395 (with-parsed-tramp-file-name file nil
5396 (with-progress-reporter
5397 v 3 (format "Checking `vc-registered' for %s" file)
5398
5399 ;; There could be new files, created by the vc backend. We
5400 ;; cannot reuse the old cache entries, therefore.
5401 (let (tramp-vc-registered-file-names
5402 (tramp-cache-inhibit-cache (current-time))
5403 (file-name-handler-alist
5404 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5405
5406 ;; Here we collect only file names, which need an operation.
5407 (tramp-run-real-handler 'vc-registered (list file))
5408 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5409
5410 ;; Send just one command, in order to fill the cache.
5411 (when tramp-vc-registered-file-names
5412 (tramp-maybe-send-script
5413 v
5414 (format tramp-vc-registered-read-file-names
5415 (tramp-get-file-exists-command v)
5416 (format "%s -r" (tramp-get-test-command v)))
5417 "tramp_vc_registered_read_file_names")
5418
5419 (dolist
5420 (elt
5421 (tramp-send-command-and-read
5422 v
5423 (format
5424 "tramp_vc_registered_read_file_names <<'EOF'\n%s\nEOF\n"
5425 (mapconcat 'tramp-shell-quote-argument
5426 tramp-vc-registered-file-names
5427 "\n"))))
5428
5429 (tramp-set-file-property
5430 v (car elt) (cadr elt) (cadr (cdr elt))))))
5431
5432 ;; Second run. Now all `file-exists-p' or `file-readable-p'
5433 ;; calls shall be answered from the file cache. We unset
5434 ;; `process-file-side-effects' in order to keep the cache when
5435 ;; `process-file' calls appear.
5436 (let (process-file-side-effects)
5437 (tramp-run-real-handler 'vc-registered (list file)))))))
5438
5439 ;;;###autoload
5440 (progn (defun tramp-run-real-handler (operation args)
5441 "Invoke normal file name handler for OPERATION.
5442 First arg specifies the OPERATION, second arg is a list of arguments to
5443 pass to the OPERATION."
5444 (let* ((inhibit-file-name-handlers
5445 `(tramp-file-name-handler
5446 tramp-vc-file-name-handler
5447 tramp-completion-file-name-handler
5448 cygwin-mount-name-hook-function
5449 cygwin-mount-map-drive-hook-function
5450 .
5451 ,(and (eq inhibit-file-name-operation operation)
5452 inhibit-file-name-handlers)))
5453 (inhibit-file-name-operation operation))
5454 (apply operation args))))
5455
5456 ;;;###autoload
5457 (progn (defun tramp-completion-run-real-handler (operation args)
5458 "Invoke `tramp-file-name-handler' for OPERATION.
5459 First arg specifies the OPERATION, second arg is a list of arguments to
5460 pass to the OPERATION."
5461 (let* ((inhibit-file-name-handlers
5462 `(tramp-completion-file-name-handler
5463 cygwin-mount-name-hook-function
5464 cygwin-mount-map-drive-hook-function
5465 .
5466 ,(and (eq inhibit-file-name-operation operation)
5467 inhibit-file-name-handlers)))
5468 (inhibit-file-name-operation operation))
5469 (apply operation args))))
5470
5471 ;; We handle here all file primitives. Most of them have the file
5472 ;; name as first parameter; nevertheless we check for them explicitly
5473 ;; in order to be signaled if a new primitive appears. This
5474 ;; scenario is needed because there isn't a way to decide by
5475 ;; syntactical means whether a foreign method must be called. It would
5476 ;; ease the life if `file-name-handler-alist' would support a decision
5477 ;; function as well but regexp only.
5478 (defun tramp-file-name-for-operation (operation &rest args)
5479 "Return file name related to OPERATION file primitive.
5480 ARGS are the arguments OPERATION has been called with."
5481 (cond
5482 ;; FILE resp DIRECTORY.
5483 ((member operation
5484 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5485 'delete-file 'diff-latest-backup-file 'directory-file-name
5486 'directory-files 'directory-files-and-attributes
5487 'dired-compress-file 'dired-uncache
5488 'file-accessible-directory-p 'file-attributes
5489 'file-directory-p 'file-executable-p 'file-exists-p
5490 'file-local-copy 'file-remote-p 'file-modes
5491 'file-name-as-directory 'file-name-directory
5492 'file-name-nondirectory 'file-name-sans-versions
5493 'file-ownership-preserved-p 'file-readable-p
5494 'file-regular-p 'file-symlink-p 'file-truename
5495 'file-writable-p 'find-backup-file-name 'find-file-noselect
5496 'get-file-buffer 'insert-directory 'insert-file-contents
5497 'load 'make-directory 'make-directory-internal
5498 'set-file-modes 'substitute-in-file-name
5499 'unhandled-file-name-directory 'vc-registered
5500 ;; Emacs 22+ only.
5501 'set-file-times
5502 ;; Emacs 24+ only.
5503 'file-selinux-context 'set-file-selinux-context
5504 ;; XEmacs only.
5505 'abbreviate-file-name 'create-file-buffer
5506 'dired-file-modtime 'dired-make-compressed-filename
5507 'dired-recursive-delete-directory 'dired-set-file-modtime
5508 'dired-shell-unhandle-file-name 'dired-uucode-file
5509 'insert-file-contents-literally 'make-temp-name 'recover-file
5510 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5511 (if (file-name-absolute-p (nth 0 args))
5512 (nth 0 args)
5513 (expand-file-name (nth 0 args))))
5514 ;; FILE DIRECTORY resp FILE1 FILE2.
5515 ((member operation
5516 (list 'add-name-to-file 'copy-file 'expand-file-name
5517 'file-name-all-completions 'file-name-completion
5518 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5519 ;; Emacs 23+ only.
5520 'copy-directory
5521 ;; XEmacs only.
5522 'dired-make-relative-symlink
5523 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5524 (save-match-data
5525 (cond
5526 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5527 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5528 (t (buffer-file-name (current-buffer))))))
5529 ;; START END FILE.
5530 ((eq operation 'write-region)
5531 (nth 2 args))
5532 ;; BUFFER.
5533 ((member operation
5534 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5535 ;; Emacs 22+ only.
5536 'make-auto-save-file-name
5537 ;; XEmacs only.
5538 'backup-buffer))
5539 (buffer-file-name
5540 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5541 ;; COMMAND.
5542 ((member operation
5543 (list ;; not in Emacs 23+.
5544 'dired-call-process
5545 ;; Emacs only.
5546 'shell-command
5547 ;; Emacs 22+ only.
5548 'process-file
5549 ;; Emacs 23+ only.
5550 'start-file-process
5551 ;; XEmacs only.
5552 'dired-print-file 'dired-shell-call-process
5553 ;; nowhere yet.
5554 'executable-find 'start-process
5555 'call-process 'call-process-region))
5556 default-directory)
5557 ;; Unknown file primitive.
5558 (t (error "unknown file I/O primitive: %s" operation))))
5559
5560 (defun tramp-find-foreign-file-name-handler (filename)
5561 "Return foreign file name handler if exists."
5562 (when (tramp-tramp-file-p filename)
5563 (let ((v (tramp-dissect-file-name filename t))
5564 (handler tramp-foreign-file-name-handler-alist)
5565 elt res)
5566 ;; When we are not fully sure that filename completion is safe,
5567 ;; we should not return a handler.
5568 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5569 (and (tramp-file-name-host v)
5570 (not (member (tramp-file-name-host v)
5571 (mapcar 'car tramp-methods))))
5572 (not (tramp-completion-mode-p)))
5573 (while handler
5574 (setq elt (car handler)
5575 handler (cdr handler))
5576 (when (funcall (car elt) filename)
5577 (setq handler nil
5578 res (cdr elt))))
5579 res))))
5580
5581 ;; Main function.
5582 ;;;###autoload
5583 (defun tramp-file-name-handler (operation &rest args)
5584 "Invoke Tramp file name handler.
5585 Falls back to normal file name handler if no Tramp file name handler exists."
5586 (if tramp-mode
5587 (save-match-data
5588 (let* ((filename
5589 (tramp-replace-environment-variables
5590 (apply 'tramp-file-name-for-operation operation args)))
5591 (completion (tramp-completion-mode-p))
5592 (foreign (tramp-find-foreign-file-name-handler filename)))
5593 (with-parsed-tramp-file-name filename nil
5594 ;; Call the backend function.
5595 (if foreign
5596 (condition-case err
5597 (apply foreign operation args)
5598
5599 ;; Trace that somebody has interrupted the
5600 ;; operation.
5601 (quit
5602 (let (tramp-message-show-message)
5603 (tramp-message
5604 v 1 "Interrupt received in operation %s"
5605 (append (list operation) args)))
5606 ;; Propagate the quit signal.
5607 (signal (car err) (cdr err)))
5608
5609 ;; When we are in completion mode, some failed
5610 ;; operations shall return at least a default value
5611 ;; in order to give the user a chance to correct the
5612 ;; file name in the minibuffer.
5613 (error
5614 (cond
5615 ((and completion (zerop (length localname))
5616 (memq operation '(file-exists-p file-directory-p)))
5617 t)
5618 ((and completion (zerop (length localname))
5619 (memq operation
5620 '(expand-file-name file-name-as-directory)))
5621 filename)
5622 ;; Propagate the error.
5623 (t (signal (car err) (cdr err))))))
5624
5625 ;; Nothing to do for us.
5626 (tramp-run-real-handler operation args)))))
5627
5628 ;; When `tramp-mode' is not enabled, we don't do anything.
5629 (tramp-run-real-handler operation args)))
5630
5631 ;; In Emacs, there is some concurrency due to timers. If a timer
5632 ;; interrupts Tramp and wishes to use the same connection buffer as
5633 ;; the "main" Emacs, then garbage might occur in the connection
5634 ;; buffer. Therefore, we need to make sure that a timer does not use
5635 ;; the same connection buffer as the "main" Emacs. We implement a
5636 ;; cheap global lock, instead of locking each connection buffer
5637 ;; separately. The global lock is based on two variables,
5638 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5639 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5640 ;; processing of a single file operation, so we need to allow
5641 ;; recursive calls. That's where the `tramp-locker' variable comes in
5642 ;; -- it is let-bound to t during the execution of the current
5643 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5644 ;; then we should just proceed because we have been called
5645 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5646 ;; interrupting the "main" Emacs, and then we signal an error.
5647
5648 (defvar tramp-locked nil
5649 "If non-nil, then Tramp is currently busy.
5650 Together with `tramp-locker', this implements a locking mechanism
5651 preventing reentrant calls of Tramp.")
5652
5653 (defvar tramp-locker nil
5654 "If non-nil, then a caller has locked Tramp.
5655 Together with `tramp-locked', this implements a locking mechanism
5656 preventing reentrant calls of Tramp.")
5657
5658 (defun tramp-sh-file-name-handler (operation &rest args)
5659 "Invoke remote-shell Tramp file name handler.
5660 Fall back to normal file name handler if no Tramp handler exists."
5661 (when (and tramp-locked (not tramp-locker))
5662 (setq tramp-locked nil)
5663 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5664 (let ((tl tramp-locked))
5665 (unwind-protect
5666 (progn
5667 (setq tramp-locked t)
5668 (let ((tramp-locker t))
5669 (save-match-data
5670 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5671 (if fn
5672 (apply (cdr fn) args)
5673 (tramp-run-real-handler operation args))))))
5674 (setq tramp-locked tl))))
5675
5676 (defun tramp-vc-file-name-handler (operation &rest args)
5677 "Invoke special file name handler, which collects files to be handled."
5678 (save-match-data
5679 (let ((filename
5680 (tramp-replace-environment-variables
5681 (apply 'tramp-file-name-for-operation operation args)))
5682 (fn (assoc operation tramp-file-name-handler-alist)))
5683 (with-parsed-tramp-file-name filename nil
5684 (cond
5685 ;; That's what we want: file names, for which checks are
5686 ;; applied. We assume, that VC uses only `file-exists-p' and
5687 ;; `file-readable-p' checks; otherwise we must extend the
5688 ;; list. We do not perform any action, but return nil, in
5689 ;; order to keep `vc-registered' running.
5690 ((and fn (memq operation '(file-exists-p file-readable-p)))
5691 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5692 nil)
5693 ;; Tramp file name handlers like `expand-file-name'. They
5694 ;; must still work.
5695 (fn
5696 (save-match-data (apply (cdr fn) args)))
5697 ;; Default file name handlers, we don't care.
5698 (t (tramp-run-real-handler operation args)))))))
5699
5700 ;;;###autoload
5701 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5702 "Invoke Tramp file name completion handler.
5703 Falls back to normal file name handler if no Tramp file name handler exists."
5704 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5705 ;; would otherwise use backslash.
5706 (let ((directory-sep-char ?/)
5707 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5708 (if (and
5709 ;; When `tramp-mode' is not enabled, we don't do anything.
5710 fn tramp-mode
5711 ;; For other syntaxes than `sep', the regexp matches many common
5712 ;; situations where the user doesn't actually want to use Tramp.
5713 ;; So to avoid autoloading Tramp after typing just "/s", we
5714 ;; disable this part of the completion, unless the user implicitly
5715 ;; indicated his interest in using a fancier completion system.
5716 (or (eq tramp-syntax 'sep)
5717 (featurep 'tramp) ;; If it's loaded, we may as well use it.
5718 ;; `partial-completion-mode' does not exist in XEmacs.
5719 ;; It is obsoleted with Emacs 24.1.
5720 (and (boundp 'partial-completion-mode)
5721 (symbol-value 'partial-completion-mode))
5722 ;; FIXME: These may have been loaded even if the user never
5723 ;; intended to use them.
5724 (featurep 'ido)
5725 (featurep 'icicles)))
5726 (save-match-data (apply (cdr fn) args))
5727 (tramp-completion-run-real-handler operation args)))))
5728
5729 ;;;###autoload
5730 (progn (defun tramp-register-file-name-handlers ()
5731 "Add Tramp file name handlers to `file-name-handler-alist'."
5732 ;; Remove autoloaded handlers from file name handler alist. Useful,
5733 ;; if `tramp-syntax' has been changed.
5734 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5735 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5736 (let ((a1 (rassq
5737 'tramp-completion-file-name-handler file-name-handler-alist)))
5738 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5739 ;; Add the handlers.
5740 (add-to-list 'file-name-handler-alist
5741 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5742 (put 'tramp-file-name-handler 'safe-magic t)
5743 (add-to-list 'file-name-handler-alist
5744 (cons tramp-completion-file-name-regexp
5745 'tramp-completion-file-name-handler))
5746 (put 'tramp-completion-file-name-handler 'safe-magic t)
5747 ;; If jka-compr or epa-file are already loaded, move them to the
5748 ;; front of `file-name-handler-alist'.
5749 (dolist (fnh '(epa-file-handler jka-compr-handler))
5750 (let ((entry (rassoc fnh file-name-handler-alist)))
5751 (when entry
5752 (setq file-name-handler-alist
5753 (cons entry (delete entry file-name-handler-alist))))))))
5754
5755 ;; `tramp-file-name-handler' must be registered before evaluation of
5756 ;; site-start and init files, because there might exist remote files
5757 ;; already, f.e. files kept via recentf-mode.
5758 ;;;###autoload(tramp-register-file-name-handlers)
5759 (tramp-register-file-name-handlers)
5760
5761 ;;;###autoload
5762 (defun tramp-unload-file-name-handlers ()
5763 (setq file-name-handler-alist
5764 (delete (rassoc 'tramp-file-name-handler
5765 file-name-handler-alist)
5766 (delete (rassoc 'tramp-completion-file-name-handler
5767 file-name-handler-alist)
5768 file-name-handler-alist))))
5769
5770 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5771
5772 ;;; File name handler functions for completion mode:
5773
5774 (defvar tramp-completion-mode nil
5775 "If non-nil, external packages signal that they are in file name completion.
5776
5777 This is necessary, because Tramp uses a heuristic depending on last
5778 input event. This fails when external packages use other characters
5779 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5780 should never be set globally, the intention is to let-bind it.")
5781
5782 ;; Necessary because `tramp-file-name-regexp-unified' and
5783 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5784 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5785 ;; to `tramp-file-name-handler'). Otherwise, it takes
5786 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5787 ;; risky, because completing a file might require loading other files,
5788 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5789 ;; variable. On the other hand, those files shouldn't have partial
5790 ;; Tramp file name syntax. Maybe another variable should be introduced
5791 ;; overwriting this check in such cases. Or we change Tramp file name
5792 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5793 (defun tramp-completion-mode-p ()
5794 "Check, whether method / user name / host name completion is active."
5795 (or
5796 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5797 (and (boundp 'non-essential) (symbol-value 'non-essential))
5798 tramp-completion-mode
5799 ;; Emacs.
5800 (equal last-input-event 'tab)
5801 (and (natnump last-input-event)
5802 (or
5803 ;; ?\t has event-modifier 'control.
5804 (equal last-input-event ?\t)
5805 (and (not (event-modifiers last-input-event))
5806 (or (equal last-input-event ?\?)
5807 (equal last-input-event ?\ )))))
5808 ;; XEmacs.
5809 (and (featurep 'xemacs)
5810 ;; `last-input-event' might be nil.
5811 (not (null last-input-event))
5812 ;; `last-input-event' may have no character approximation.
5813 (tramp-compat-funcall 'event-to-character last-input-event)
5814 (or
5815 ;; ?\t has event-modifier 'control.
5816 (equal
5817 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
5818 (and (not (event-modifiers last-input-event))
5819 (or (equal
5820 (tramp-compat-funcall 'event-to-character last-input-event)
5821 ?\?)
5822 (equal
5823 (tramp-compat-funcall 'event-to-character last-input-event)
5824 ?\ )))))))
5825
5826 (defun tramp-connectable-p (filename)
5827 "Check, whether it is possible to connect the remote host w/o side-effects.
5828 This is true, if either the remote host is already connected, or if we are
5829 not in completion mode."
5830 (and (tramp-tramp-file-p filename)
5831 (with-parsed-tramp-file-name filename nil
5832 (or (get-buffer (tramp-buffer-name v))
5833 (not (tramp-completion-mode-p))))))
5834
5835 ;; Method, host name and user name completion.
5836 ;; `tramp-completion-dissect-file-name' returns a list of
5837 ;; tramp-file-name structures. For all of them we return possible completions.
5838 ;;;###autoload
5839 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5840 "Like `file-name-all-completions' for partial Tramp files."
5841
5842 (let* ((fullname (tramp-drop-volume-letter
5843 (expand-file-name filename directory)))
5844 ;; Possible completion structures.
5845 (v (tramp-completion-dissect-file-name fullname))
5846 result result1)
5847
5848 (while v
5849 (let* ((car (car v))
5850 (method (tramp-file-name-method car))
5851 (user (tramp-file-name-user car))
5852 (host (tramp-file-name-host car))
5853 (localname (tramp-file-name-localname car))
5854 (m (tramp-find-method method user host))
5855 (tramp-current-user user) ; see `tramp-parse-passwd'
5856 all-user-hosts)
5857
5858 (unless localname ;; Nothing to complete.
5859
5860 (if (or user host)
5861
5862 ;; Method dependent user / host combinations.
5863 (progn
5864 (mapc
5865 (lambda (x)
5866 (setq all-user-hosts
5867 (append all-user-hosts
5868 (funcall (nth 0 x) (nth 1 x)))))
5869 (tramp-get-completion-function m))
5870
5871 (setq result
5872 (append result
5873 (mapcar
5874 (lambda (x)
5875 (tramp-get-completion-user-host
5876 method user host (nth 0 x) (nth 1 x)))
5877 (delq nil all-user-hosts)))))
5878
5879 ;; Possible methods.
5880 (setq result
5881 (append result (tramp-get-completion-methods m)))))
5882
5883 (setq v (cdr v))))
5884
5885 ;; Unify list, remove nil elements.
5886 (while result
5887 (let ((car (car result)))
5888 (when car
5889 (add-to-list
5890 'result1
5891 (substring car (length (tramp-drop-volume-letter directory)))))
5892 (setq result (cdr result))))
5893
5894 ;; Complete local parts.
5895 (append
5896 result1
5897 (condition-case nil
5898 (apply (if (tramp-connectable-p fullname)
5899 'tramp-completion-run-real-handler
5900 'tramp-run-real-handler)
5901 'file-name-all-completions (list (list filename directory)))
5902 (error nil)))))
5903
5904 ;; Method, host name and user name completion for a file.
5905 ;;;###autoload
5906 (defun tramp-completion-handle-file-name-completion
5907 (filename directory &optional predicate)
5908 "Like `file-name-completion' for Tramp files."
5909 (try-completion
5910 filename
5911 (mapcar 'list (file-name-all-completions filename directory))
5912 (when (and predicate
5913 (tramp-connectable-p (expand-file-name filename directory)))
5914 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5915
5916 ;; I misuse a little bit the tramp-file-name structure in order to handle
5917 ;; completion possibilities for partial methods / user names / host names.
5918 ;; Return value is a list of tramp-file-name structures according to possible
5919 ;; completions. If "localname" is non-nil it means there
5920 ;; shouldn't be a completion anymore.
5921
5922 ;; Expected results:
5923
5924 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5925 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5926 ;; [nil "x" nil nil]
5927 ;; ["x" nil nil nil]
5928
5929 ;; "/x:" "/x:y" "/x:y:"
5930 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5931 ;; "/[x/" "/[x/y"
5932 ;; ["x" nil "" nil] ["x" nil "y" nil]
5933 ;; ["x" "" nil nil] ["x" "y" nil nil]
5934
5935 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5936 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5937 ;; "/[x/y@" "/[x/y@z"
5938 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5939 (defun tramp-completion-dissect-file-name (name)
5940 "Returns a list of `tramp-file-name' structures.
5941 They are collected by `tramp-completion-dissect-file-name1'."
5942
5943 (let* ((result)
5944 (x-nil "\\|\\(\\)")
5945 (tramp-completion-ipv6-regexp
5946 (format
5947 "[^%s]*"
5948 (if (zerop (length tramp-postfix-ipv6-format))
5949 tramp-postfix-host-format
5950 tramp-postfix-ipv6-format)))
5951 ;; "/method" "/[method"
5952 (tramp-completion-file-name-structure1
5953 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5954 1 nil nil nil))
5955 ;; "/user" "/[user"
5956 (tramp-completion-file-name-structure2
5957 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5958 nil 1 nil nil))
5959 ;; "/host" "/[host"
5960 (tramp-completion-file-name-structure3
5961 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5962 nil nil 1 nil))
5963 ;; "/[ipv6" "/[ipv6"
5964 (tramp-completion-file-name-structure4
5965 (list (concat tramp-prefix-regexp
5966 tramp-prefix-ipv6-regexp
5967 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5968 nil nil 1 nil))
5969 ;; "/user@host" "/[user@host"
5970 (tramp-completion-file-name-structure5
5971 (list (concat tramp-prefix-regexp
5972 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5973 "\\(" tramp-host-regexp x-nil "\\)$")
5974 nil 1 2 nil))
5975 ;; "/user@[ipv6" "/[user@ipv6"
5976 (tramp-completion-file-name-structure6
5977 (list (concat tramp-prefix-regexp
5978 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5979 tramp-prefix-ipv6-regexp
5980 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5981 nil 1 2 nil))
5982 ;; "/method:user" "/[method/user" "/method://user"
5983 (tramp-completion-file-name-structure7
5984 (list (concat tramp-prefix-regexp
5985 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5986 "\\(" tramp-user-regexp x-nil "\\)$")
5987 1 2 nil nil))
5988 ;; "/method:host" "/[method/host" "/method://host"
5989 (tramp-completion-file-name-structure8
5990 (list (concat tramp-prefix-regexp
5991 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5992 "\\(" tramp-host-regexp x-nil "\\)$")
5993 1 nil 2 nil))
5994 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5995 (tramp-completion-file-name-structure9
5996 (list (concat tramp-prefix-regexp
5997 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5998 tramp-prefix-ipv6-regexp
5999 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6000 1 nil 2 nil))
6001 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
6002 (tramp-completion-file-name-structure10
6003 (list (concat tramp-prefix-regexp
6004 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6005 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6006 "\\(" tramp-host-regexp x-nil "\\)$")
6007 1 2 3 nil))
6008 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
6009 (tramp-completion-file-name-structure11
6010 (list (concat tramp-prefix-regexp
6011 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6012 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6013 tramp-prefix-ipv6-regexp
6014 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6015 1 2 3 nil))
6016 ;; "/method: "/method:/"
6017 (tramp-completion-file-name-structure12
6018 (list
6019 (if (equal tramp-syntax 'url)
6020 (concat tramp-prefix-regexp
6021 "\\(" tramp-method-regexp "\\)"
6022 "\\(" (substring tramp-postfix-method-regexp 0 1)
6023 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6024 "\\(" "\\)$")
6025 ;; Should not match if not URL syntax.
6026 (concat tramp-prefix-regexp "/$"))
6027 1 3 nil nil))
6028 ;; "/method: "/method:/"
6029 (tramp-completion-file-name-structure13
6030 (list
6031 (if (equal tramp-syntax 'url)
6032 (concat tramp-prefix-regexp
6033 "\\(" tramp-method-regexp "\\)"
6034 "\\(" (substring tramp-postfix-method-regexp 0 1)
6035 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6036 "\\(" "\\)$")
6037 ;; Should not match if not URL syntax.
6038 (concat tramp-prefix-regexp "/$"))
6039 1 nil 3 nil)))
6040
6041 (mapc (lambda (regexp)
6042 (add-to-list 'result
6043 (tramp-completion-dissect-file-name1 regexp name)))
6044 (list
6045 tramp-completion-file-name-structure1
6046 tramp-completion-file-name-structure2
6047 tramp-completion-file-name-structure3
6048 tramp-completion-file-name-structure4
6049 tramp-completion-file-name-structure5
6050 tramp-completion-file-name-structure6
6051 tramp-completion-file-name-structure7
6052 tramp-completion-file-name-structure8
6053 tramp-completion-file-name-structure9
6054 tramp-completion-file-name-structure10
6055 tramp-completion-file-name-structure11
6056 tramp-completion-file-name-structure12
6057 tramp-completion-file-name-structure13
6058 tramp-file-name-structure))
6059
6060 (delq nil result)))
6061
6062 (defun tramp-completion-dissect-file-name1 (structure name)
6063 "Returns a `tramp-file-name' structure matching STRUCTURE.
6064 The structure consists of remote method, remote user,
6065 remote host and localname (filename on remote host)."
6066
6067 (save-match-data
6068 (when (string-match (nth 0 structure) name)
6069 (let ((method (and (nth 1 structure)
6070 (match-string (nth 1 structure) name)))
6071 (user (and (nth 2 structure)
6072 (match-string (nth 2 structure) name)))
6073 (host (and (nth 3 structure)
6074 (match-string (nth 3 structure) name)))
6075 (localname (and (nth 4 structure)
6076 (match-string (nth 4 structure) name))))
6077 (vector method user host localname)))))
6078
6079 ;; This function returns all possible method completions, adding the
6080 ;; trailing method delimeter.
6081 (defun tramp-get-completion-methods (partial-method)
6082 "Returns all method completions for PARTIAL-METHOD."
6083 (mapcar
6084 (lambda (method)
6085 (and method
6086 (string-match (concat "^" (regexp-quote partial-method)) method)
6087 (tramp-completion-make-tramp-file-name method nil nil nil)))
6088 (mapcar 'car tramp-methods)))
6089
6090 ;; Compares partial user and host names with possible completions.
6091 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
6092 "Returns the most expanded string for user and host name completion.
6093 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
6094 (cond
6095
6096 ((and partial-user partial-host)
6097 (if (and host
6098 (string-match (concat "^" (regexp-quote partial-host)) host)
6099 (string-equal partial-user (or user partial-user)))
6100 (setq user partial-user)
6101 (setq user nil
6102 host nil)))
6103
6104 (partial-user
6105 (setq host nil)
6106 (unless
6107 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
6108 (setq user nil)))
6109
6110 (partial-host
6111 (setq user nil)
6112 (unless
6113 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
6114 (setq host nil)))
6115
6116 (t (setq user nil
6117 host nil)))
6118
6119 (unless (zerop (+ (length user) (length host)))
6120 (tramp-completion-make-tramp-file-name method user host nil)))
6121
6122 (defun tramp-parse-rhosts (filename)
6123 "Return a list of (user host) tuples allowed to access.
6124 Either user or host may be nil."
6125 ;; On Windows, there are problems in completion when
6126 ;; `default-directory' is remote.
6127 (let ((default-directory (tramp-compat-temporary-file-directory))
6128 res)
6129 (when (file-readable-p filename)
6130 (with-temp-buffer
6131 (insert-file-contents filename)
6132 (goto-char (point-min))
6133 (while (not (eobp))
6134 (push (tramp-parse-rhosts-group) res))))
6135 res))
6136
6137 (defun tramp-parse-rhosts-group ()
6138 "Return a (user host) tuple allowed to access.
6139 Either user or host may be nil."
6140 (let ((result)
6141 (regexp
6142 (concat
6143 "^\\(" tramp-host-regexp "\\)"
6144 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6145 (narrow-to-region (point) (tramp-compat-line-end-position))
6146 (when (re-search-forward regexp nil t)
6147 (setq result (append (list (match-string 3) (match-string 1)))))
6148 (widen)
6149 (forward-line 1)
6150 result))
6151
6152 (defun tramp-parse-shosts (filename)
6153 "Return a list of (user host) tuples allowed to access.
6154 User is always nil."
6155 ;; On Windows, there are problems in completion when
6156 ;; `default-directory' is remote.
6157 (let ((default-directory (tramp-compat-temporary-file-directory))
6158 res)
6159 (when (file-readable-p filename)
6160 (with-temp-buffer
6161 (insert-file-contents filename)
6162 (goto-char (point-min))
6163 (while (not (eobp))
6164 (push (tramp-parse-shosts-group) res))))
6165 res))
6166
6167 (defun tramp-parse-shosts-group ()
6168 "Return a (user host) tuple allowed to access.
6169 User is always nil."
6170 (let ((result)
6171 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
6172 (narrow-to-region (point) (tramp-compat-line-end-position))
6173 (when (re-search-forward regexp nil t)
6174 (setq result (list nil (match-string 1))))
6175 (widen)
6176 (or
6177 (> (skip-chars-forward ",") 0)
6178 (forward-line 1))
6179 result))
6180
6181 (defun tramp-parse-sconfig (filename)
6182 "Return a list of (user host) tuples allowed to access.
6183 User is always nil."
6184 ;; On Windows, there are problems in completion when
6185 ;; `default-directory' is remote.
6186 (let ((default-directory (tramp-compat-temporary-file-directory))
6187 res)
6188 (when (file-readable-p filename)
6189 (with-temp-buffer
6190 (insert-file-contents filename)
6191 (goto-char (point-min))
6192 (while (not (eobp))
6193 (push (tramp-parse-sconfig-group) res))))
6194 res))
6195
6196 (defun tramp-parse-sconfig-group ()
6197 "Return a (user host) tuple allowed to access.
6198 User is always nil."
6199 (let ((result)
6200 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
6201 (narrow-to-region (point) (tramp-compat-line-end-position))
6202 (when (re-search-forward regexp nil t)
6203 (setq result (list nil (match-string 1))))
6204 (widen)
6205 (or
6206 (> (skip-chars-forward ",") 0)
6207 (forward-line 1))
6208 result))
6209
6210 (defun tramp-parse-shostkeys (dirname)
6211 "Return a list of (user host) tuples allowed to access.
6212 User is always nil."
6213 ;; On Windows, there are problems in completion when
6214 ;; `default-directory' is remote.
6215 (let* ((default-directory (tramp-compat-temporary-file-directory))
6216 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6217 (files (when (file-directory-p dirname) (directory-files dirname)))
6218 result)
6219 (while files
6220 (when (string-match regexp (car files))
6221 (push (list nil (match-string 1 (car files))) result))
6222 (setq files (cdr files)))
6223 result))
6224
6225 (defun tramp-parse-sknownhosts (dirname)
6226 "Return a list of (user host) tuples allowed to access.
6227 User is always nil."
6228 ;; On Windows, there are problems in completion when
6229 ;; `default-directory' is remote.
6230 (let* ((default-directory (tramp-compat-temporary-file-directory))
6231 (regexp (concat "^\\(" tramp-host-regexp
6232 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6233 (files (when (file-directory-p dirname) (directory-files dirname)))
6234 result)
6235 (while files
6236 (when (string-match regexp (car files))
6237 (push (list nil (match-string 1 (car files))) result))
6238 (setq files (cdr files)))
6239 result))
6240
6241 (defun tramp-parse-hosts (filename)
6242 "Return a list of (user host) tuples allowed to access.
6243 User is always nil."
6244 ;; On Windows, there are problems in completion when
6245 ;; `default-directory' is remote.
6246 (let ((default-directory (tramp-compat-temporary-file-directory))
6247 res)
6248 (when (file-readable-p filename)
6249 (with-temp-buffer
6250 (insert-file-contents filename)
6251 (goto-char (point-min))
6252 (while (not (eobp))
6253 (push (tramp-parse-hosts-group) res))))
6254 res))
6255
6256 (defun tramp-parse-hosts-group ()
6257 "Return a (user host) tuple allowed to access.
6258 User is always nil."
6259 (let ((result)
6260 (regexp
6261 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6262 (narrow-to-region (point) (tramp-compat-line-end-position))
6263 (when (re-search-forward regexp nil t)
6264 (setq result (list nil (match-string 1))))
6265 (widen)
6266 (or
6267 (> (skip-chars-forward " \t") 0)
6268 (forward-line 1))
6269 result))
6270
6271 ;; For su-alike methods it would be desirable to return "root@localhost"
6272 ;; as default. Unfortunately, we have no information whether any user name
6273 ;; has been typed already. So we use `tramp-current-user' as indication,
6274 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6275 (defun tramp-parse-passwd (filename)
6276 "Return a list of (user host) tuples allowed to access.
6277 Host is always \"localhost\"."
6278 ;; On Windows, there are problems in completion when
6279 ;; `default-directory' is remote.
6280 (let ((default-directory (tramp-compat-temporary-file-directory))
6281 res)
6282 (if (zerop (length tramp-current-user))
6283 '(("root" nil))
6284 (when (file-readable-p filename)
6285 (with-temp-buffer
6286 (insert-file-contents filename)
6287 (goto-char (point-min))
6288 (while (not (eobp))
6289 (push (tramp-parse-passwd-group) res))))
6290 res)))
6291
6292 (defun tramp-parse-passwd-group ()
6293 "Return a (user host) tuple allowed to access.
6294 Host is always \"localhost\"."
6295 (let ((result)
6296 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6297 (narrow-to-region (point) (tramp-compat-line-end-position))
6298 (when (re-search-forward regexp nil t)
6299 (setq result (list (match-string 1) "localhost")))
6300 (widen)
6301 (forward-line 1)
6302 result))
6303
6304 (defun tramp-parse-netrc (filename)
6305 "Return a list of (user host) tuples allowed to access.
6306 User may be nil."
6307 ;; On Windows, there are problems in completion when
6308 ;; `default-directory' is remote.
6309 (let ((default-directory (tramp-compat-temporary-file-directory))
6310 res)
6311 (when (file-readable-p filename)
6312 (with-temp-buffer
6313 (insert-file-contents filename)
6314 (goto-char (point-min))
6315 (while (not (eobp))
6316 (push (tramp-parse-netrc-group) res))))
6317 res))
6318
6319 (defun tramp-parse-netrc-group ()
6320 "Return a (user host) tuple allowed to access.
6321 User may be nil."
6322 (let ((result)
6323 (regexp
6324 (concat
6325 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6326 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6327 (narrow-to-region (point) (tramp-compat-line-end-position))
6328 (when (re-search-forward regexp nil t)
6329 (setq result (list (match-string 3) (match-string 1))))
6330 (widen)
6331 (forward-line 1)
6332 result))
6333
6334 (defun tramp-parse-putty (registry)
6335 "Return a list of (user host) tuples allowed to access.
6336 User is always nil."
6337 ;; On Windows, there are problems in completion when
6338 ;; `default-directory' is remote.
6339 (let ((default-directory (tramp-compat-temporary-file-directory))
6340 res)
6341 (with-temp-buffer
6342 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6343 (goto-char (point-min))
6344 (while (not (eobp))
6345 (push (tramp-parse-putty-group registry) res))))
6346 res))
6347
6348 (defun tramp-parse-putty-group (registry)
6349 "Return a (user host) tuple allowed to access.
6350 User is always nil."
6351 (let ((result)
6352 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6353 (narrow-to-region (point) (tramp-compat-line-end-position))
6354 (when (re-search-forward regexp nil t)
6355 (setq result (list nil (match-string 1))))
6356 (widen)
6357 (forward-line 1)
6358 result))
6359
6360 ;;; Internal Functions:
6361
6362 (defun tramp-maybe-send-script (vec script name)
6363 "Define in remote shell function NAME implemented as SCRIPT.
6364 Only send the definition if it has not already been done."
6365 (let* ((p (tramp-get-connection-process vec))
6366 (scripts (tramp-get-connection-property p "scripts" nil)))
6367 (unless (member name scripts)
6368 (with-progress-reporter vec 5 (format "Sending script `%s'" name)
6369 ;; The script could contain a call of Perl. This is masked with `%s'.
6370 (tramp-send-command-and-check
6371 vec
6372 (format "%s () {\n%s\n}" name
6373 (format script (tramp-get-remote-perl vec))))
6374 (tramp-set-connection-property p "scripts" (cons name scripts))))))
6375
6376 (defun tramp-set-auto-save ()
6377 (when (and ;; ange-ftp has its own auto-save mechanism
6378 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6379 'tramp-sh-file-name-handler)
6380 auto-save-default)
6381 (auto-save-mode 1)))
6382 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6383 (add-hook 'tramp-unload-hook
6384 (lambda ()
6385 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6386
6387 (defun tramp-run-test (switch filename)
6388 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6389 Returns the exit code of the `test' program."
6390 (with-parsed-tramp-file-name filename nil
6391 (tramp-send-command-and-check
6392 v
6393 (format
6394 "%s %s %s"
6395 (tramp-get-test-command v)
6396 switch
6397 (tramp-shell-quote-argument localname)))))
6398
6399 (defun tramp-run-test2 (format-string file1 file2)
6400 "Run `test'-like program on the remote system, given FILE1, FILE2.
6401 FORMAT-STRING contains the program name, switches, and place holders.
6402 Returns the exit code of the `test' program. Barfs if the methods,
6403 hosts, or files, disagree."
6404 (unless (tramp-equal-remote file1 file2)
6405 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6406 (tramp-error
6407 v 'file-error
6408 "tramp-run-test2 only implemented for same method, user, host")))
6409 (with-parsed-tramp-file-name file1 v1
6410 (with-parsed-tramp-file-name file1 v2
6411 (tramp-send-command-and-check
6412 v1
6413 (format format-string
6414 (tramp-shell-quote-argument v1-localname)
6415 (tramp-shell-quote-argument v2-localname))))))
6416
6417 (defun tramp-buffer-name (vec)
6418 "A name for the connection buffer VEC."
6419 ;; We must use `tramp-file-name-real-host', because for gateway
6420 ;; methods the default port will be expanded later on, which would
6421 ;; tamper the name.
6422 (let ((method (tramp-file-name-method vec))
6423 (user (tramp-file-name-user vec))
6424 (host (tramp-file-name-real-host vec)))
6425 (if (not (zerop (length user)))
6426 (format "*tramp/%s %s@%s*" method user host)
6427 (format "*tramp/%s %s*" method host))))
6428
6429 (defun tramp-delete-temp-file-function ()
6430 "Remove temporary files related to current buffer."
6431 (when (stringp tramp-temp-buffer-file-name)
6432 (condition-case nil
6433 (delete-file tramp-temp-buffer-file-name)
6434 (error nil))))
6435
6436 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6437 (add-hook 'tramp-cache-unload-hook
6438 (lambda ()
6439 (remove-hook 'kill-buffer-hook
6440 'tramp-delete-temp-file-function)))
6441
6442 (defun tramp-get-buffer (vec)
6443 "Get the connection buffer to be used for VEC."
6444 (or (get-buffer (tramp-buffer-name vec))
6445 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6446 (setq buffer-undo-list t)
6447 (setq default-directory
6448 (tramp-make-tramp-file-name
6449 (tramp-file-name-method vec)
6450 (tramp-file-name-user vec)
6451 (tramp-file-name-host vec)
6452 "/"))
6453 (current-buffer))))
6454
6455 (defun tramp-get-connection-buffer (vec)
6456 "Get the connection buffer to be used for VEC.
6457 In case a second asynchronous communication has been started, it is different
6458 from `tramp-get-buffer'."
6459 (or (tramp-get-connection-property vec "process-buffer" nil)
6460 (tramp-get-buffer vec)))
6461
6462 (defun tramp-get-connection-process (vec)
6463 "Get the connection process to be used for VEC.
6464 In case a second asynchronous communication has been started, it is different
6465 from the default one."
6466 (get-process
6467 (or (tramp-get-connection-property vec "process-name" nil)
6468 (tramp-buffer-name vec))))
6469
6470 (defun tramp-debug-buffer-name (vec)
6471 "A name for the debug buffer for VEC."
6472 ;; We must use `tramp-file-name-real-host', because for gateway
6473 ;; methods the default port will be expanded later on, which would
6474 ;; tamper the name.
6475 (let ((method (tramp-file-name-method vec))
6476 (user (tramp-file-name-user vec))
6477 (host (tramp-file-name-real-host vec)))
6478 (if (not (zerop (length user)))
6479 (format "*debug tramp/%s %s@%s*" method user host)
6480 (format "*debug tramp/%s %s*" method host))))
6481
6482 (defconst tramp-debug-outline-regexp
6483 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6484
6485 (defun tramp-get-debug-buffer (vec)
6486 "Get the debug buffer for VEC."
6487 (with-current-buffer
6488 (get-buffer-create (tramp-debug-buffer-name vec))
6489 (when (bobp)
6490 (setq buffer-undo-list t)
6491 ;; Activate `outline-mode'. This runs `text-mode-hook' and
6492 ;; `outline-mode-hook'. We must prevent that local processes
6493 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6494 ;; Furthermore, `outline-regexp' must have the correct value
6495 ;; already, because it is used by `font-lock-compile-keywords'.
6496 (let ((default-directory (tramp-compat-temporary-file-directory))
6497 (outline-regexp tramp-debug-outline-regexp))
6498 (outline-mode))
6499 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
6500 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6501 (current-buffer)))
6502
6503 (defun tramp-outline-level ()
6504 "Return the depth to which a statement is nested in the outline.
6505 Point must be at the beginning of a header line.
6506
6507 The outline level is equal to the verbosity of the Tramp message."
6508 (1+ (string-to-number (match-string 1))))
6509
6510 (defun tramp-find-executable
6511 (vec progname dirlist &optional ignore-tilde ignore-path)
6512 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6513 First arg VEC specifies the connection, PROGNAME is the program
6514 to search for, and DIRLIST gives the list of directories to
6515 search. If IGNORE-TILDE is non-nil, directory names starting
6516 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6517 only in DIRLIST.
6518
6519 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6520
6521 This function expects to be in the right *tramp* buffer."
6522 (with-current-buffer (tramp-get-connection-buffer vec)
6523 (let (result)
6524 ;; Check whether the executable is in $PATH. "which(1)" does not
6525 ;; report always a correct error code; therefore we check the
6526 ;; number of words it returns.
6527 (unless ignore-path
6528 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6529 (goto-char (point-min))
6530 (if (looking-at "^\\s-*1$")
6531 (setq result (concat "\\" progname))))
6532 (unless result
6533 (when ignore-tilde
6534 ;; Remove all ~/foo directories from dirlist. In XEmacs,
6535 ;; `remove' is in CL, and we want to avoid CL dependencies.
6536 (let (newdl d)
6537 (while dirlist
6538 (setq d (car dirlist))
6539 (setq dirlist (cdr dirlist))
6540 (unless (char-equal ?~ (aref d 0))
6541 (setq newdl (cons d newdl))))
6542 (setq dirlist (nreverse newdl))))
6543 (tramp-send-command
6544 vec
6545 (format (concat "while read d; "
6546 "do if test -x $d/%s -a -f $d/%s; "
6547 "then echo tramp_executable $d/%s; "
6548 "break; fi; done <<'EOF'\n"
6549 "%s\nEOF")
6550 progname progname progname (mapconcat 'identity dirlist "\n")))
6551 (goto-char (point-max))
6552 (when (search-backward "tramp_executable " nil t)
6553 (skip-chars-forward "^ ")
6554 (skip-chars-forward " ")
6555 (setq result (buffer-substring
6556 (point) (tramp-compat-line-end-position)))))
6557 result)))
6558
6559 (defun tramp-set-remote-path (vec)
6560 "Sets the remote environment PATH to existing directories.
6561 I.e., for each directory in `tramp-remote-path', it is tested
6562 whether it exists and if so, it is added to the environment
6563 variable PATH."
6564 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6565 (tramp-send-command
6566 vec (format "PATH=%s; export PATH"
6567 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6568
6569 ;; ------------------------------------------------------------
6570 ;; -- Communication with external shell --
6571 ;; ------------------------------------------------------------
6572
6573 (defun tramp-find-file-exists-command (vec)
6574 "Find a command on the remote host for checking if a file exists.
6575 Here, we are looking for a command which has zero exit status if the
6576 file exists and nonzero exit status otherwise."
6577 (let ((existing "/")
6578 (nonexisting
6579 (tramp-shell-quote-argument "/ this file does not exist "))
6580 result)
6581 ;; The algorithm is as follows: we try a list of several commands.
6582 ;; For each command, we first run `$cmd /' -- this should return
6583 ;; true, as the root directory always exists. And then we run
6584 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6585 ;; does not exist. This should return false. We use the first
6586 ;; command we find that seems to work.
6587 ;; The list of commands to try is as follows:
6588 ;; `ls -d' This works on most systems, but NetBSD 1.4
6589 ;; has a bug: `ls' always returns zero exit
6590 ;; status, even for files which don't exist.
6591 ;; `test -e' Some Bourne shells have a `test' builtin
6592 ;; which does not know the `-e' option.
6593 ;; `/bin/test -e' For those, the `test' binary on disk normally
6594 ;; provides the option. Alas, the binary
6595 ;; is sometimes `/bin/test' and sometimes it's
6596 ;; `/usr/bin/test'.
6597 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6598 (unless (or
6599 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
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 "/bin/test -e")
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 (and (setq result "/usr/bin/test -e")
6610 (zerop (tramp-send-command-and-check
6611 vec (format "%s %s" result existing)))
6612 (not (zerop (tramp-send-command-and-check
6613 vec (format "%s %s" result nonexisting)))))
6614 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6615 (zerop (tramp-send-command-and-check
6616 vec (format "%s %s" result existing)))
6617 (not (zerop (tramp-send-command-and-check
6618 vec (format "%s %s" result nonexisting))))))
6619 (tramp-error
6620 vec 'file-error "Couldn't find command to check if file exists"))
6621 result))
6622
6623 (defun tramp-open-shell (vec shell)
6624 "Opens shell SHELL."
6625 (with-progress-reporter vec 5 (format "Opening remote shell `%s'" shell)
6626 ;; Find arguments for this shell.
6627 (let ((tramp-end-of-output tramp-initial-end-of-output)
6628 (alist tramp-sh-extra-args)
6629 item extra-args)
6630 (while (and alist (null extra-args))
6631 (setq item (pop alist))
6632 (when (string-match (car item) shell)
6633 (setq extra-args (cdr item))))
6634 (when extra-args (setq shell (concat shell " " extra-args)))
6635 (tramp-send-command
6636 vec (format "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6637 (shell-quote-argument tramp-end-of-output) shell)
6638 t))
6639 ;; Setting prompts.
6640 (tramp-send-command
6641 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6642 (tramp-send-command vec "PS2=''" t)
6643 (tramp-send-command vec "PS3=''" t)
6644 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
6645
6646 (defun tramp-find-shell (vec)
6647 "Opens a shell on the remote host which groks tilde expansion."
6648 (unless (tramp-get-connection-property vec "remote-shell" nil)
6649 (let (shell)
6650 (with-current-buffer (tramp-get-buffer vec)
6651 (tramp-send-command vec "echo ~root" t)
6652 (cond
6653 ((or (string-match "^~root$" (buffer-string))
6654 ;; The default shell (ksh93) of OpenSolaris is buggy.
6655 (string-equal (tramp-get-connection-property vec "uname" "")
6656 "SunOS 5.11"))
6657 (setq shell
6658 (or (tramp-find-executable
6659 vec "bash" (tramp-get-remote-path vec) t t)
6660 (tramp-find-executable
6661 vec "ksh" (tramp-get-remote-path vec) t t)))
6662 (unless shell
6663 (tramp-error
6664 vec 'file-error
6665 "Couldn't find a shell which groks tilde expansion"))
6666 (tramp-message
6667 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
6668 (tramp-open-shell vec shell))
6669
6670 (t (tramp-message
6671 vec 5 "Remote `%s' groks tilde expansion, good"
6672 (tramp-set-connection-property
6673 vec "remote-shell"
6674 (tramp-get-method-parameter
6675 (tramp-file-name-method vec) 'tramp-remote-sh)))))))))
6676
6677 ;; ------------------------------------------------------------
6678 ;; -- Functions for establishing connection --
6679 ;; ------------------------------------------------------------
6680
6681 ;; The following functions are actions to be taken when seeing certain
6682 ;; prompts from the remote host. See the variable
6683 ;; `tramp-actions-before-shell' for usage of these functions.
6684
6685 (defun tramp-action-login (proc vec)
6686 "Send the login name."
6687 (when (not (stringp tramp-current-user))
6688 (save-window-excursion
6689 (let ((enable-recursive-minibuffers t))
6690 (pop-to-buffer (tramp-get-connection-buffer vec))
6691 (setq tramp-current-user (read-string (match-string 0))))))
6692 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6693 (with-current-buffer (tramp-get-connection-buffer vec)
6694 (tramp-message vec 6 "\n%s" (buffer-string)))
6695 (tramp-send-string vec tramp-current-user))
6696
6697 (defun tramp-action-password (proc vec)
6698 "Query the user for a password."
6699 (with-current-buffer (process-buffer proc)
6700 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6701 (tramp-message vec 3 "Sending %s" (match-string 1)))
6702 (tramp-enter-password proc))
6703
6704 (defun tramp-action-succeed (proc vec)
6705 "Signal success in finding shell prompt."
6706 (throw 'tramp-action 'ok))
6707
6708 (defun tramp-action-permission-denied (proc vec)
6709 "Signal permission denied."
6710 (kill-process proc)
6711 (throw 'tramp-action 'permission-denied))
6712
6713 (defun tramp-action-yesno (proc vec)
6714 "Ask the user for confirmation using `yes-or-no-p'.
6715 Send \"yes\" to remote process on confirmation, abort otherwise.
6716 See also `tramp-action-yn'."
6717 (save-window-excursion
6718 (let ((enable-recursive-minibuffers t))
6719 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6720 (unless (yes-or-no-p (match-string 0))
6721 (kill-process proc)
6722 (throw 'tramp-action 'permission-denied))
6723 (with-current-buffer (tramp-get-connection-buffer vec)
6724 (tramp-message vec 6 "\n%s" (buffer-string)))
6725 (tramp-send-string vec "yes"))))
6726
6727 (defun tramp-action-yn (proc vec)
6728 "Ask the user for confirmation using `y-or-n-p'.
6729 Send \"y\" to remote process on confirmation, abort otherwise.
6730 See also `tramp-action-yesno'."
6731 (save-window-excursion
6732 (let ((enable-recursive-minibuffers t))
6733 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6734 (unless (y-or-n-p (match-string 0))
6735 (kill-process proc)
6736 (throw 'tramp-action 'permission-denied))
6737 (with-current-buffer (tramp-get-connection-buffer vec)
6738 (tramp-message vec 6 "\n%s" (buffer-string)))
6739 (tramp-send-string vec "y"))))
6740
6741 (defun tramp-action-terminal (proc vec)
6742 "Tell the remote host which terminal type to use.
6743 The terminal type can be configured with `tramp-terminal-type'."
6744 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6745 (with-current-buffer (tramp-get-connection-buffer vec)
6746 (tramp-message vec 6 "\n%s" (buffer-string)))
6747 (tramp-send-string vec tramp-terminal-type))
6748
6749 (defun tramp-action-process-alive (proc vec)
6750 "Check, whether a process has finished."
6751 (unless (memq (process-status proc) '(run open))
6752 (throw 'tramp-action 'process-died)))
6753
6754 (defun tramp-action-out-of-band (proc vec)
6755 "Check, whether an out-of-band copy has finished."
6756 (cond ((and (memq (process-status proc) '(stop exit))
6757 (zerop (process-exit-status proc)))
6758 (tramp-message vec 3 "Process has finished.")
6759 (throw 'tramp-action 'ok))
6760 ((or (and (memq (process-status proc) '(stop exit))
6761 (not (zerop (process-exit-status proc))))
6762 (memq (process-status proc) '(signal)))
6763 ;; `scp' could have copied correctly, but set modes could have failed.
6764 ;; This can be ignored.
6765 (with-current-buffer (process-buffer proc)
6766 (goto-char (point-min))
6767 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6768 (progn
6769 (tramp-message vec 5 "'set mode' error ignored.")
6770 (tramp-message vec 3 "Process has finished.")
6771 (throw 'tramp-action 'ok))
6772 (tramp-message vec 3 "Process has died.")
6773 (throw 'tramp-action 'process-died))))
6774 (t nil)))
6775
6776 ;; Functions for processing the actions.
6777
6778 (defun tramp-process-one-action (proc vec actions)
6779 "Wait for output from the shell and perform one action."
6780 (let (found todo item pattern action)
6781 (while (not found)
6782 ;; Reread output once all actions have been performed.
6783 ;; Obviously, the output was not complete.
6784 (tramp-accept-process-output proc 1)
6785 (setq todo actions)
6786 (while todo
6787 (setq item (pop todo))
6788 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6789 (setq action (nth 1 item))
6790 (tramp-message
6791 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6792 (when (tramp-check-for-regexp proc pattern)
6793 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6794 (setq found (funcall action proc vec)))))
6795 found))
6796
6797 (defun tramp-process-actions (proc vec actions &optional timeout)
6798 "Perform actions until success or TIMEOUT."
6799 ;; Preserve message for `progress-reporter'.
6800 (with-temp-message ""
6801 ;; Enable auth-source and password-cache.
6802 (tramp-set-connection-property vec "first-password-request" t)
6803 (let (exit)
6804 (while (not exit)
6805 (tramp-message proc 3 "Waiting for prompts from remote shell")
6806 (setq exit
6807 (catch 'tramp-action
6808 (if timeout
6809 (with-timeout (timeout)
6810 (tramp-process-one-action proc vec actions))
6811 (tramp-process-one-action proc vec actions)))))
6812 (with-current-buffer (tramp-get-connection-buffer vec)
6813 (tramp-message vec 6 "\n%s" (buffer-string)))
6814 (unless (eq exit 'ok)
6815 (tramp-clear-passwd vec)
6816 (tramp-error-with-buffer
6817 nil vec 'file-error
6818 (cond
6819 ((eq exit 'permission-denied) "Permission denied")
6820 ((eq exit 'process-died) "Process died")
6821 (t "Login failed")))))))
6822
6823 ;; Utility functions.
6824
6825 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6826 "Like `accept-process-output' for Tramp processes.
6827 This is needed in order to hide `last-coding-system-used', which is set
6828 for process communication also."
6829 (with-current-buffer (process-buffer proc)
6830 (tramp-message proc 10 "%s %s" proc (process-status proc))
6831 (let (buffer-read-only last-coding-system-used)
6832 ;; Under Windows XP, accept-process-output doesn't return
6833 ;; sometimes. So we add an additional timeout.
6834 (with-timeout ((or timeout 1))
6835 (accept-process-output proc timeout timeout-msecs)))
6836 (tramp-message proc 10 "\n%s" (buffer-string))))
6837
6838 (defun tramp-check-for-regexp (proc regexp)
6839 "Check, whether REGEXP is contained in process buffer of PROC.
6840 Erase echoed commands if exists."
6841 (with-current-buffer (process-buffer proc)
6842 (goto-char (point-min))
6843
6844 ;; Check whether we need to remove echo output.
6845 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6846 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6847 (let ((begin (match-beginning 0)))
6848 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6849 ;; Discard echo from remote output.
6850 (tramp-set-connection-property proc "check-remote-echo" nil)
6851 (tramp-message proc 5 "echo-mark found")
6852 (forward-line 1)
6853 (delete-region begin (point))
6854 (goto-char (point-min)))))
6855
6856 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6857 ;; Sometimes, the echo string is suppressed on the remote side.
6858 (not (string-equal
6859 (tramp-compat-funcall
6860 'substring-no-properties tramp-echo-mark-marker
6861 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6862 (tramp-compat-funcall
6863 'buffer-substring-no-properties
6864 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6865 ;; No echo to be handled, now we can look for the regexp.
6866 (goto-char (point-min))
6867 (re-search-forward regexp nil t))))
6868
6869 (defun tramp-wait-for-regexp (proc timeout regexp)
6870 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6871 Expects the output of PROC to be sent to the current buffer. Returns
6872 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6873 nil."
6874 (with-current-buffer (process-buffer proc)
6875 (let ((found (tramp-check-for-regexp proc regexp))
6876 (start-time (current-time)))
6877 (cond (timeout
6878 ;; Work around a bug in XEmacs 21, where the timeout
6879 ;; expires faster than it should. This degenerates
6880 ;; to polling for buggy XEmacsen, but oh, well.
6881 (while (and (not found)
6882 (< (tramp-time-diff (current-time) start-time)
6883 timeout))
6884 (with-timeout (timeout)
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 (t
6892 (while (not found)
6893 (tramp-accept-process-output proc 1)
6894 (unless (memq (process-status proc) '(run open))
6895 (tramp-error-with-buffer
6896 nil proc 'file-error "Process has died"))
6897 (setq found (tramp-check-for-regexp proc regexp)))))
6898 (tramp-message proc 6 "\n%s" (buffer-string))
6899 (when (not found)
6900 (if timeout
6901 (tramp-error
6902 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6903 regexp timeout)
6904 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6905 found)))
6906
6907 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6908 "Wait for shell prompt and barf if none appears.
6909 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6910 seconds. If not, it produces an error message with the given ERROR-ARGS."
6911 (unless
6912 (tramp-wait-for-regexp
6913 proc timeout
6914 (format
6915 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6916 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6917
6918 ;; We don't call `tramp-send-string' in order to hide the password
6919 ;; from the debug buffer, and because end-of-line handling of the
6920 ;; string.
6921 (defun tramp-enter-password (proc)
6922 "Prompt for a password and send it to the remote end."
6923 (process-send-string
6924 proc (concat (tramp-read-passwd proc)
6925 (or (tramp-get-method-parameter
6926 tramp-current-method
6927 'tramp-password-end-of-line)
6928 tramp-default-password-end-of-line))))
6929
6930 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6931 "Set up an interactive shell.
6932 Mainly sets the prompt and the echo correctly. PROC is the shell
6933 process to set up. VEC specifies the connection."
6934 (let ((tramp-end-of-output tramp-initial-end-of-output))
6935 ;; It is useful to set the prompt in the following command because
6936 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6937 ;; about and thus /bin/sh will display a strange prompt. For
6938 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6939 ;; display the current working directory but /bin/sh will display
6940 ;; a dollar sign. The following command line sets $PS1 to a sane
6941 ;; value, and works under Bourne-ish shells as well as csh-like
6942 ;; shells. Daniel Pittman reports that the unusual positioning of
6943 ;; the single quotes makes it work under `rc', too. We also unset
6944 ;; the variable $ENV because that is read by some sh
6945 ;; implementations (eg, bash when called as sh) on startup; this
6946 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6947 ;; is another way to set the prompt in /bin/bash, it must be
6948 ;; discarded as well.
6949 (tramp-open-shell
6950 vec
6951 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-remote-sh))
6952
6953 ;; Disable echo.
6954 (tramp-message vec 5 "Setting up remote shell environment")
6955 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6956 ;; Check whether the echo has really been disabled. Some
6957 ;; implementations, like busybox of embedded GNU/Linux, don't
6958 ;; support disabling.
6959 (tramp-send-command vec "echo foo" t)
6960 (with-current-buffer (process-buffer proc)
6961 (goto-char (point-min))
6962 (when (looking-at "echo foo")
6963 (tramp-set-connection-property proc "remote-echo" t)
6964 (tramp-message vec 5 "Remote echo still on. Ok.")
6965 ;; Make sure backspaces and their echo are enabled and no line
6966 ;; width magic interferes with them.
6967 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6968
6969 (tramp-message vec 5 "Setting shell prompt")
6970 (tramp-send-command
6971 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6972 (tramp-send-command vec "PS2=''" t)
6973 (tramp-send-command vec "PS3=''" t)
6974 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6975
6976 ;; Try to set up the coding system correctly.
6977 ;; CCC this can't be the right way to do it. Hm.
6978 (tramp-message vec 5 "Determining coding system")
6979 (tramp-send-command vec "echo foo ; echo bar" t)
6980 (with-current-buffer (process-buffer proc)
6981 (goto-char (point-min))
6982 (if (featurep 'mule)
6983 ;; Use MULE to select the right EOL convention for communicating
6984 ;; with the process.
6985 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
6986 (cons 'undecided 'undecided)))
6987 cs-decode cs-encode)
6988 (when (symbolp cs) (setq cs (cons cs cs)))
6989 (setq cs-decode (car cs))
6990 (setq cs-encode (cdr cs))
6991 (unless cs-decode (setq cs-decode 'undecided))
6992 (unless cs-encode (setq cs-encode 'undecided))
6993 (setq cs-encode (tramp-coding-system-change-eol-conversion
6994 cs-encode 'unix))
6995 (when (search-forward "\r" nil t)
6996 (setq cs-decode (tramp-coding-system-change-eol-conversion
6997 cs-decode 'dos)))
6998 (tramp-compat-funcall
6999 'set-buffer-process-coding-system cs-decode cs-encode)
7000 (tramp-message
7001 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
7002 ;; Look for ^M and do something useful if found.
7003 (when (search-forward "\r" nil t)
7004 ;; We have found a ^M but cannot frob the process coding system
7005 ;; because we're running on a non-MULE Emacs. Let's try
7006 ;; stty, instead.
7007 (tramp-send-command vec "stty -onlcr" t))))
7008 ;; Dump stty settings in the traces.
7009 (when (>= tramp-verbose 9)
7010 (tramp-send-command vec "stty -a" t))
7011 (tramp-send-command vec "set +o vi +o emacs" t)
7012
7013 ;; Check whether the output of "uname -sr" has been changed. If
7014 ;; yes, this is a strong indication that we must expire all
7015 ;; connection properties. We start again with
7016 ;; `tramp-maybe-open-connection', it will be catched there.
7017 (tramp-message vec 5 "Checking system information")
7018 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
7019 (new-uname
7020 (tramp-set-connection-property
7021 vec "uname"
7022 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
7023 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
7024 (with-current-buffer (tramp-get-debug-buffer vec)
7025 ;; Keep the debug buffer.
7026 (rename-buffer
7027 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
7028 (tramp-compat-funcall 'tramp-cleanup-connection vec)
7029 (if (= (point-min) (point-max))
7030 (kill-buffer nil)
7031 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
7032 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
7033 (tramp-get-buffer vec)
7034 (tramp-message
7035 vec 3
7036 "Connection reset, because remote host changed from `%s' to `%s'"
7037 old-uname new-uname)
7038 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
7039
7040 ;; Check whether the remote host suffers from buggy
7041 ;; `send-process-string'. This is known for FreeBSD (see comment in
7042 ;; `send_process', file process.c). I've tested sending 624 bytes
7043 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
7044 ;; this host type is detected locally. It cannot handle remote
7045 ;; hosts, though.
7046 (with-connection-property proc "chunksize"
7047 (cond
7048 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
7049 tramp-chunksize)
7050 (t
7051 (tramp-message
7052 vec 5 "Checking remote host type for `send-process-string' bug")
7053 (if (string-match
7054 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
7055 500 0))))
7056
7057 ;; Set remote PATH variable.
7058 (tramp-set-remote-path vec)
7059
7060 ;; Search for a good shell before searching for a command which
7061 ;; checks if a file exists. This is done because Tramp wants to use
7062 ;; "test foo; echo $?" to check if various conditions hold, and
7063 ;; there are buggy /bin/sh implementations which don't execute the
7064 ;; "echo $?" part if the "test" part has an error. In particular,
7065 ;; the OpenSolaris /bin/sh is a problem. There are also other
7066 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
7067 ;; in function declarations, or changing HISTFILE in place.
7068 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
7069 ;; detected.
7070 (tramp-find-shell vec)
7071
7072 ;; Disable unexpected output.
7073 (tramp-send-command vec "mesg n; biff n" t)
7074
7075 ;; IRIX64 bash expands "!" even when in single quotes. This
7076 ;; destroys our shell functions, we must disable it. See
7077 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
7078 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
7079 (tramp-send-command vec "set +H" t))
7080
7081 ;; Set `remote-tty' process property.
7082 (ignore-errors
7083 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"")))
7084 (unless (zerop (length tty)) (process-put proc 'remote-tty tty))))
7085
7086 ;; Set the environment.
7087 (tramp-message vec 5 "Setting default environment")
7088
7089 (let ((env (copy-sequence tramp-remote-process-environment))
7090 unset item)
7091 (while env
7092 (setq item (tramp-compat-split-string (car env) "="))
7093 (setcdr item (mapconcat 'identity (cdr item) "="))
7094 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
7095 (tramp-send-command
7096 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
7097 (push (car item) unset))
7098 (setq env (cdr env)))
7099 (when unset
7100 (tramp-send-command
7101 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
7102
7103 ;; CCC: We should either implement a Perl version of base64 encoding
7104 ;; and decoding. Then we just use that in the last item. The other
7105 ;; alternative is to use the Perl version of UU encoding. But then
7106 ;; we need a Lisp version of uuencode.
7107 ;;
7108 ;; Old text from documentation of tramp-methods:
7109 ;; Using a uuencode/uudecode inline method is discouraged, please use one
7110 ;; of the base64 methods instead since base64 encoding is much more
7111 ;; reliable and the commands are more standardized between the different
7112 ;; Unix versions. But if you can't use base64 for some reason, please
7113 ;; note that the default uudecode command does not work well for some
7114 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
7115 ;; the following command for uudecode:
7116 ;;
7117 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
7118 ;;
7119 ;; For Irix, no solution is known yet.
7120
7121 (defconst tramp-local-coding-commands
7122 '((b64 base64-encode-region base64-decode-region)
7123 (uu tramp-uuencode-region uudecode-decode-region)
7124 (pack
7125 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7126 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7127 "List of local coding commands for inline transfer.
7128 Each item is a list that looks like this:
7129
7130 \(FORMAT ENCODING DECODING\)
7131
7132 FORMAT is symbol describing the encoding/decoding format. It can be
7133 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7134
7135 ENCODING and DECODING can be strings, giving commands, or symbols,
7136 giving functions. If they are strings, then they can contain
7137 the \"%s\" format specifier. If that specifier is present, the input
7138 filename will be put into the command line at that spot. If the
7139 specifier is not present, the input should be read from standard
7140 input.
7141
7142 If they are functions, they will be called with two arguments, start
7143 and end of region, and are expected to replace the region contents
7144 with the encoded or decoded results, respectively.")
7145
7146 (defconst tramp-remote-coding-commands
7147 '((b64 "base64" "base64 -d")
7148 (b64 "mimencode -b" "mimencode -u -b")
7149 (b64 "mmencode -b" "mmencode -u -b")
7150 (b64 "recode data..base64" "recode base64..data")
7151 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
7152 (b64 tramp-perl-encode tramp-perl-decode)
7153 (uu "uuencode xxx" "uudecode -o /dev/stdout")
7154 (uu "uuencode xxx" "uudecode -o -")
7155 (uu "uuencode xxx" "uudecode -p")
7156 (uu "uuencode xxx" tramp-uudecode)
7157 (pack
7158 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7159 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7160 "List of remote coding commands for inline transfer.
7161 Each item is a list that looks like this:
7162
7163 \(FORMAT ENCODING DECODING\)
7164
7165 FORMAT is symbol describing the encoding/decoding format. It can be
7166 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7167
7168 ENCODING and DECODING can be strings, giving commands, or symbols,
7169 giving variables. If they are strings, then they can contain
7170 the \"%s\" format specifier. If that specifier is present, the input
7171 filename will be put into the command line at that spot. If the
7172 specifier is not present, the input should be read from standard
7173 input.
7174
7175 If they are variables, this variable is a string containing a Perl
7176 implementation for this functionality. This Perl program will be transferred
7177 to the remote host, and it is available as shell function with the same name.")
7178
7179 (defun tramp-find-inline-encoding (vec)
7180 "Find an inline transfer encoding that works.
7181 Goes through the list `tramp-local-coding-commands' and
7182 `tramp-remote-coding-commands'."
7183 (save-excursion
7184 (let ((local-commands tramp-local-coding-commands)
7185 (magic "xyzzy")
7186 loc-enc loc-dec rem-enc rem-dec litem ritem found)
7187 (while (and local-commands (not found))
7188 (setq litem (pop local-commands))
7189 (catch 'wont-work-local
7190 (let ((format (nth 0 litem))
7191 (remote-commands tramp-remote-coding-commands))
7192 (setq loc-enc (nth 1 litem))
7193 (setq loc-dec (nth 2 litem))
7194 ;; If the local encoder or decoder is a string, the
7195 ;; corresponding command has to work locally.
7196 (if (not (stringp loc-enc))
7197 (tramp-message
7198 vec 5 "Checking local encoding function `%s'" loc-enc)
7199 (tramp-message
7200 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
7201 (unless (zerop (tramp-call-local-coding-command
7202 loc-enc nil nil))
7203 (throw 'wont-work-local nil)))
7204 (if (not (stringp loc-dec))
7205 (tramp-message
7206 vec 5 "Checking local decoding function `%s'" loc-dec)
7207 (tramp-message
7208 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7209 (unless (zerop (tramp-call-local-coding-command
7210 loc-dec nil nil))
7211 (throw 'wont-work-local nil)))
7212 ;; Search for remote coding commands with the same format
7213 (while (and remote-commands (not found))
7214 (setq ritem (pop remote-commands))
7215 (catch 'wont-work-remote
7216 (when (equal format (nth 0 ritem))
7217 (setq rem-enc (nth 1 ritem))
7218 (setq rem-dec (nth 2 ritem))
7219 ;; Check if remote encoding and decoding commands can be
7220 ;; called remotely with null input and output. This makes
7221 ;; sure there are no syntax errors and the command is really
7222 ;; found. Note that we do not redirect stdout to /dev/null,
7223 ;; for two reasons: when checking the decoding command, we
7224 ;; actually check the output it gives. And also, when
7225 ;; redirecting "mimencode" output to /dev/null, then as root
7226 ;; it might change the permissions of /dev/null!
7227 (when (not (stringp rem-enc))
7228 (let ((name (symbol-name rem-enc)))
7229 (while (string-match (regexp-quote "-") name)
7230 (setq name (replace-match "_" nil t name)))
7231 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7232 (setq rem-enc name)))
7233 (tramp-message
7234 vec 5
7235 "Checking remote encoding command `%s' for sanity" rem-enc)
7236 (unless (zerop (tramp-send-command-and-check
7237 vec (format "%s </dev/null" rem-enc) t))
7238 (throw 'wont-work-remote nil))
7239
7240 (when (not (stringp rem-dec))
7241 (let ((name (symbol-name rem-dec)))
7242 (while (string-match (regexp-quote "-") name)
7243 (setq name (replace-match "_" nil t name)))
7244 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7245 (setq rem-dec name)))
7246 (tramp-message
7247 vec 5
7248 "Checking remote decoding command `%s' for sanity" rem-dec)
7249 (unless (zerop (tramp-send-command-and-check
7250 vec
7251 (format "echo %s | %s | %s"
7252 magic rem-enc rem-dec)
7253 t))
7254 (throw 'wont-work-remote nil))
7255
7256 (with-current-buffer (tramp-get-buffer vec)
7257 (goto-char (point-min))
7258 (unless (looking-at (regexp-quote magic))
7259 (throw 'wont-work-remote nil)))
7260
7261 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7262 (setq rem-enc (nth 1 ritem))
7263 (setq rem-dec (nth 2 ritem))
7264 (setq found t)))))))
7265
7266 ;; Did we find something?
7267 (unless found
7268 (tramp-error
7269 vec 'file-error "Couldn't find an inline transfer encoding"))
7270
7271 ;; Set connection properties.
7272 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7273 (tramp-set-connection-property vec "local-encoding" loc-enc)
7274 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7275 (tramp-set-connection-property vec "local-decoding" loc-dec)
7276 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7277 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7278 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7279 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7280
7281 (defun tramp-call-local-coding-command (cmd input output)
7282 "Call the local encoding or decoding command.
7283 If CMD contains \"%s\", provide input file INPUT there in command.
7284 Otherwise, INPUT is passed via standard input.
7285 INPUT can also be nil which means `/dev/null'.
7286 OUTPUT can be a string (which specifies a filename), or t (which
7287 means standard output and thus the current buffer), or nil (which
7288 means discard it)."
7289 (tramp-local-call-process
7290 tramp-encoding-shell
7291 (when (and input (not (string-match "%s" cmd))) input)
7292 (if (eq output t) t nil)
7293 nil
7294 tramp-encoding-command-switch
7295 (concat
7296 (if (string-match "%s" cmd) (format cmd input) cmd)
7297 (if (stringp output) (concat "> " output) ""))))
7298
7299 (defconst tramp-inline-compress-commands
7300 '(("gzip" "gzip -d")
7301 ("bzip2" "bzip2 -d")
7302 ("compress" "compress -d"))
7303 "List of compress and decompress commands for inline transfer.
7304 Each item is a list that looks like this:
7305
7306 \(COMPRESS DECOMPRESS\)
7307
7308 COMPRESS or DECOMPRESS are strings with the respective commands.")
7309
7310 (defun tramp-find-inline-compress (vec)
7311 "Find an inline transfer compress command that works.
7312 Goes through the list `tramp-inline-compress-commands'."
7313 (save-excursion
7314 (let ((commands tramp-inline-compress-commands)
7315 (magic "xyzzy")
7316 item compress decompress
7317 found)
7318 (while (and commands (not found))
7319 (catch 'next
7320 (setq item (pop commands)
7321 compress (nth 0 item)
7322 decompress (nth 1 item))
7323 (tramp-message
7324 vec 5
7325 "Checking local compress command `%s', `%s' for sanity"
7326 compress decompress)
7327 (unless (zerop (tramp-call-local-coding-command
7328 (format "echo %s | %s | %s"
7329 magic compress decompress) nil nil))
7330 (throw 'next nil))
7331 (tramp-message
7332 vec 5
7333 "Checking remote compress command `%s', `%s' for sanity"
7334 compress decompress)
7335 (unless (zerop (tramp-send-command-and-check
7336 vec (format "echo %s | %s | %s"
7337 magic compress decompress) t))
7338 (throw 'next nil))
7339 (setq found t)))
7340
7341 ;; Did we find something?
7342 (if found
7343 (progn
7344 ;; Set connection properties.
7345 (tramp-message
7346 vec 5 "Using inline transfer compress command `%s'" compress)
7347 (tramp-set-connection-property vec "inline-compress" compress)
7348 (tramp-message
7349 vec 5 "Using inline transfer decompress command `%s'" decompress)
7350 (tramp-set-connection-property vec "inline-decompress" decompress))
7351
7352 (tramp-set-connection-property vec "inline-compress" nil)
7353 (tramp-set-connection-property vec "inline-decompress" nil)
7354 (tramp-message
7355 vec 2 "Couldn't find an inline transfer compress command")))))
7356
7357 (defun tramp-compute-multi-hops (vec)
7358 "Expands VEC according to `tramp-default-proxies-alist'.
7359 Gateway hops are already opened."
7360 (let ((target-alist `(,vec))
7361 (choices tramp-default-proxies-alist)
7362 item proxy)
7363
7364 ;; Look for proxy hosts to be passed.
7365 (while choices
7366 (setq item (pop choices)
7367 proxy (eval (nth 2 item)))
7368 (when (and
7369 ;; host
7370 (string-match (or (eval (nth 0 item)) "")
7371 (or (tramp-file-name-host (car target-alist)) ""))
7372 ;; user
7373 (string-match (or (eval (nth 1 item)) "")
7374 (or (tramp-file-name-user (car target-alist)) "")))
7375 (if (null proxy)
7376 ;; No more hops needed.
7377 (setq choices nil)
7378 ;; Replace placeholders.
7379 (setq proxy
7380 (format-spec
7381 proxy
7382 (format-spec-make
7383 ?u (or (tramp-file-name-user (car target-alist)) "")
7384 ?h (or (tramp-file-name-host (car target-alist)) ""))))
7385 (with-parsed-tramp-file-name proxy l
7386 ;; Add the hop.
7387 (add-to-list 'target-alist l)
7388 ;; Start next search.
7389 (setq choices tramp-default-proxies-alist)))))
7390
7391 ;; Handle gateways.
7392 (when (and (boundp 'tramp-gw-tunnel-method)
7393 (string-match (format
7394 "^\\(%s\\|%s\\)$"
7395 (symbol-value 'tramp-gw-tunnel-method)
7396 (symbol-value 'tramp-gw-socks-method))
7397 (tramp-file-name-method (car target-alist))))
7398 (let ((gw (pop target-alist))
7399 (hop (pop target-alist)))
7400 ;; Is the method prepared for gateways?
7401 (unless (tramp-get-method-parameter
7402 (tramp-file-name-method hop) 'tramp-default-port)
7403 (tramp-error
7404 vec 'file-error
7405 "Method `%s' is not supported for gateway access."
7406 (tramp-file-name-method hop)))
7407 ;; Add default port if needed.
7408 (unless
7409 (string-match
7410 tramp-host-with-port-regexp (tramp-file-name-host hop))
7411 (aset hop 2
7412 (concat
7413 (tramp-file-name-host hop) tramp-prefix-port-format
7414 (number-to-string
7415 (tramp-get-method-parameter
7416 (tramp-file-name-method hop) 'tramp-default-port)))))
7417 ;; Open the gateway connection.
7418 (add-to-list
7419 'target-alist
7420 (vector
7421 (tramp-file-name-method hop) (tramp-file-name-user hop)
7422 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil))
7423 ;; For the password prompt, we need the correct values.
7424 ;; Therefore, we must remember the gateway vector. But we
7425 ;; cannot do it as connection property, because it shouldn't
7426 ;; be persistent. And we have no started process yet either.
7427 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7428
7429 ;; Foreign and out-of-band methods are not supported for multi-hops.
7430 (when (cdr target-alist)
7431 (setq choices target-alist)
7432 (while choices
7433 (setq item (pop choices))
7434 (when
7435 (or
7436 (not
7437 (tramp-get-method-parameter
7438 (tramp-file-name-method item) 'tramp-login-program))
7439 (tramp-get-method-parameter
7440 (tramp-file-name-method item) 'tramp-copy-program))
7441 (tramp-error
7442 vec 'file-error
7443 "Method `%s' is not supported for multi-hops."
7444 (tramp-file-name-method item)))))
7445
7446 ;; In case the host name is not used for the remote shell
7447 ;; command, the user could be misguided by applying a random
7448 ;; hostname.
7449 (let* ((v (car target-alist))
7450 (method (tramp-file-name-method v))
7451 (host (tramp-file-name-host v)))
7452 (unless
7453 (or
7454 ;; There are multi-hops.
7455 (cdr target-alist)
7456 ;; The host name is used for the remote shell command.
7457 (member
7458 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7459 ;; The host is local. We cannot use `tramp-local-host-p'
7460 ;; here, because it opens a connection as well.
7461 (string-match tramp-local-host-regexp host))
7462 (tramp-error
7463 v 'file-error
7464 "Host `%s' looks like a remote host, `%s' can only use the local host"
7465 host method)))
7466
7467 ;; Result.
7468 target-alist))
7469
7470 (defun tramp-maybe-open-connection (vec)
7471 "Maybe open a connection VEC.
7472 Does not do anything if a connection is already open, but re-opens the
7473 connection if a previous connection has died for some reason."
7474 (catch 'uname-changed
7475 (let ((p (tramp-get-connection-process vec))
7476 (process-name (tramp-get-connection-property vec "process-name" nil))
7477 (process-environment (copy-sequence process-environment)))
7478
7479 ;; If too much time has passed since last command was sent, look
7480 ;; whether process is still alive. If it isn't, kill it. When
7481 ;; using ssh, it can sometimes happen that the remote end has
7482 ;; hung up but the local ssh client doesn't recognize this until
7483 ;; it tries to send some data to the remote end. So that's why
7484 ;; we try to send a command from time to time, then look again
7485 ;; whether the process is really alive.
7486 (condition-case nil
7487 (when (and (> (tramp-time-diff
7488 (current-time)
7489 (tramp-get-connection-property
7490 p "last-cmd-time" '(0 0 0)))
7491 60)
7492 p (processp p) (memq (process-status p) '(run open)))
7493 (tramp-send-command vec "echo are you awake" t t)
7494 (unless (and (memq (process-status p) '(run open))
7495 (tramp-wait-for-output p 10))
7496 ;; The error will be catched locally.
7497 (tramp-error vec 'file-error "Awake did fail")))
7498 (file-error
7499 (tramp-flush-connection-property vec)
7500 (tramp-flush-connection-property p)
7501 (delete-process p)
7502 (setq p nil)))
7503
7504 ;; New connection must be opened.
7505 (unless (and p (processp p) (memq (process-status p) '(run open)))
7506
7507 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7508 ;; messages from the beginning.
7509 (tramp-get-buffer vec)
7510 (with-progress-reporter
7511 vec 3
7512 (if (zerop (length (tramp-file-name-user vec)))
7513 (format "Opening connection for %s using %s"
7514 (tramp-file-name-host vec)
7515 (tramp-file-name-method vec))
7516 (format "Opening connection for %s@%s using %s"
7517 (tramp-file-name-user vec)
7518 (tramp-file-name-host vec)
7519 (tramp-file-name-method vec)))
7520
7521 ;; Start new process.
7522 (when (and p (processp p))
7523 (delete-process p))
7524 (setenv "TERM" tramp-terminal-type)
7525 (setenv "LC_ALL" "C")
7526 (setenv "PROMPT_COMMAND")
7527 (setenv "PS1" tramp-initial-end-of-output)
7528 (let* ((target-alist (tramp-compute-multi-hops vec))
7529 (process-connection-type tramp-process-connection-type)
7530 (process-adaptive-read-buffering nil)
7531 (coding-system-for-read nil)
7532 ;; This must be done in order to avoid our file name handler.
7533 (p (let ((default-directory
7534 (tramp-compat-temporary-file-directory)))
7535 (start-process
7536 (or process-name (tramp-buffer-name vec))
7537 (tramp-get-connection-buffer vec)
7538 tramp-encoding-shell))))
7539
7540 (tramp-message
7541 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7542
7543 ;; Check whether process is alive.
7544 (tramp-set-process-query-on-exit-flag p nil)
7545 (tramp-barf-if-no-shell-prompt
7546 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7547
7548 ;; Now do all the connections as specified.
7549 (while target-alist
7550 (let* ((hop (car target-alist))
7551 (l-method (tramp-file-name-method hop))
7552 (l-user (tramp-file-name-user hop))
7553 (l-host (tramp-file-name-host hop))
7554 (l-port nil)
7555 (login-program
7556 (tramp-get-method-parameter
7557 l-method 'tramp-login-program))
7558 (login-args
7559 (tramp-get-method-parameter l-method 'tramp-login-args))
7560 (async-args
7561 (tramp-get-method-parameter l-method 'tramp-async-args))
7562 (gw-args
7563 (tramp-get-method-parameter l-method 'tramp-gw-args))
7564 (gw (tramp-get-file-property hop "" "gateway" nil))
7565 (g-method (and gw (tramp-file-name-method gw)))
7566 (g-user (and gw (tramp-file-name-user gw)))
7567 (g-host (and gw (tramp-file-name-host gw)))
7568 (command login-program)
7569 ;; We don't create the temporary file. In fact,
7570 ;; it is just a prefix for the ControlPath option
7571 ;; of ssh; the real temporary file has another
7572 ;; name, and it is created and protected by ssh.
7573 ;; It is also removed by ssh, when the connection
7574 ;; is closed.
7575 (tmpfile
7576 (tramp-set-connection-property
7577 p "temp-file"
7578 (make-temp-name
7579 (expand-file-name
7580 tramp-temp-name-prefix
7581 (tramp-compat-temporary-file-directory)))))
7582 spec)
7583
7584 ;; Add arguments for asynchrononous processes.
7585 (when (and process-name async-args)
7586 (setq login-args (append async-args login-args)))
7587
7588 ;; Add gateway arguments if necessary.
7589 (when (and gw gw-args)
7590 (setq login-args (append gw-args login-args)))
7591
7592 ;; Check for port number. Until now, there's no need
7593 ;; for handling like method, user, host.
7594 (when (string-match tramp-host-with-port-regexp l-host)
7595 (setq l-port (match-string 2 l-host)
7596 l-host (match-string 1 l-host)))
7597
7598 ;; Set variables for computing the prompt for reading
7599 ;; password. They can also be derived from a gateway.
7600 (setq tramp-current-method (or g-method l-method)
7601 tramp-current-user (or g-user l-user)
7602 tramp-current-host (or g-host l-host))
7603
7604 ;; Replace login-args place holders.
7605 (setq
7606 l-host (or l-host "")
7607 l-user (or l-user "")
7608 l-port (or l-port "")
7609 spec (format-spec-make
7610 ?h l-host ?u l-user ?p l-port ?t tmpfile)
7611 command
7612 (concat
7613 ;; We do not want to see the trailing local prompt in
7614 ;; `start-file-process'.
7615 (unless (memq system-type '(windows-nt)) "exec ")
7616 command " "
7617 (mapconcat
7618 (lambda (x)
7619 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7620 (unless (member "" x) (mapconcat 'identity x " ")))
7621 login-args " ")
7622 ;; Local shell could be a Windows COMSPEC. It
7623 ;; doesn't know the ";" syntax, but we must exit
7624 ;; always for `start-file-process'. "exec" does not
7625 ;; work either.
7626 (if (memq system-type '(windows-nt)) " && exit || exit")))
7627
7628 ;; Send the command.
7629 (tramp-message vec 3 "Sending command `%s'" command)
7630 (tramp-send-command vec command t t)
7631 (tramp-process-actions p vec tramp-actions-before-shell 60)
7632 (tramp-message
7633 vec 3 "Found remote shell prompt on `%s'" l-host))
7634 ;; Next hop.
7635 (setq target-alist (cdr target-alist)))
7636
7637 ;; Make initial shell settings.
7638 (tramp-open-connection-setup-interactive-shell p vec)))))))
7639
7640 (defun tramp-send-command (vec command &optional neveropen nooutput)
7641 "Send the COMMAND to connection VEC.
7642 Erases temporary buffer before sending the command. If optional
7643 arg NEVEROPEN is non-nil, never try to open the connection. This
7644 is meant to be used from `tramp-maybe-open-connection' only. The
7645 function waits for output unless NOOUTPUT is set."
7646 (unless neveropen (tramp-maybe-open-connection vec))
7647 (let ((p (tramp-get-connection-process vec)))
7648 (when (tramp-get-connection-property p "remote-echo" nil)
7649 ;; We mark the command string that it can be erased in the output buffer.
7650 (tramp-set-connection-property p "check-remote-echo" t)
7651 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7652 (tramp-message vec 6 "%s" command)
7653 (tramp-send-string vec command)
7654 (unless nooutput (tramp-wait-for-output p))))
7655
7656 (defun tramp-wait-for-output (proc &optional timeout)
7657 "Wait for output from remote command."
7658 (unless (buffer-live-p (process-buffer proc))
7659 (delete-process proc)
7660 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7661 (with-current-buffer (process-buffer proc)
7662 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7663 ;; be leading escape sequences, which must be ignored.
7664 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7665 ;; Sometimes, the commands do not return a newline but a
7666 ;; null byte before the shell prompt, for example "git
7667 ;; ls-files -c -z ...".
7668 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7669 (found (tramp-wait-for-regexp proc timeout regexp1)))
7670 (if found
7671 (let (buffer-read-only)
7672 ;; A simple-minded busybox has sent " ^H" sequences.
7673 ;; Delete them.
7674 (goto-char (point-min))
7675 (when (re-search-forward
7676 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7677 (forward-line 1)
7678 (delete-region (point-min) (point)))
7679 ;; Delete the prompt.
7680 (goto-char (point-max))
7681 (re-search-backward regexp nil t)
7682 (delete-region (point) (point-max)))
7683 (if timeout
7684 (tramp-error
7685 proc 'file-error
7686 "[[Remote prompt `%s' not found in %d secs]]"
7687 tramp-end-of-output timeout)
7688 (tramp-error
7689 proc 'file-error
7690 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7691 ;; Return value is whether end-of-output sentinel was found.
7692 found)))
7693
7694 (defun tramp-send-command-and-check
7695 (vec command &optional subshell dont-suppress-err)
7696 "Run COMMAND and check its exit status.
7697 Sends `echo $?' along with the COMMAND for checking the exit status. If
7698 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7699
7700 If the optional argument SUBSHELL is non-nil, the command is
7701 executed in a subshell, ie surrounded by parentheses. If
7702 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7703 (tramp-send-command
7704 vec
7705 (concat (if subshell "( " "")
7706 command
7707 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7708 "echo tramp_exit_status $?"
7709 (if subshell " )" "")))
7710 (with-current-buffer (tramp-get-connection-buffer vec)
7711 (goto-char (point-max))
7712 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7713 (tramp-error
7714 vec 'file-error "Couldn't find exit status of `%s'" command))
7715 (skip-chars-forward "^ ")
7716 (prog1
7717 (read (current-buffer))
7718 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7719
7720 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7721 "Run COMMAND, check exit status, throw error if exit status not okay.
7722 Similar to `tramp-send-command-and-check' but accepts two more arguments
7723 FMT and ARGS which are passed to `error'."
7724 (unless (zerop (tramp-send-command-and-check vec command))
7725 (apply 'tramp-error vec 'file-error fmt args)))
7726
7727 (defun tramp-send-command-and-read (vec command)
7728 "Run COMMAND and return the output, which must be a Lisp expression.
7729 In case there is no valid Lisp expression, it raises an error"
7730 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7731 (with-current-buffer (tramp-get-connection-buffer vec)
7732 ;; Read the expression.
7733 (goto-char (point-min))
7734 (condition-case nil
7735 (prog1 (read (current-buffer))
7736 ;; Error handling.
7737 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7738 (error nil)))
7739 (error (tramp-error
7740 vec 'file-error
7741 "`%s' does not return a valid Lisp expression: `%s'"
7742 command (buffer-string))))))
7743
7744 ;; It seems that Tru64 Unix does not like it if long strings are sent
7745 ;; to it in one go. (This happens when sending the Perl
7746 ;; `file-attributes' implementation, for instance.) Therefore, we
7747 ;; have this function which sends the string in chunks.
7748 (defun tramp-send-string (vec string)
7749 "Send the STRING via connection VEC.
7750
7751 The STRING is expected to use Unix line-endings, but the lines sent to
7752 the remote host use line-endings as defined in the variable
7753 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7754 (let* ((p (tramp-get-connection-process vec))
7755 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7756 (unless p
7757 (tramp-error
7758 vec 'file-error "Can't send string to remote host -- not logged in"))
7759 (tramp-set-connection-property p "last-cmd-time" (current-time))
7760 (tramp-message vec 10 "%s" string)
7761 (with-current-buffer (tramp-get-connection-buffer vec)
7762 ;; Clean up the buffer. We cannot call `erase-buffer' because
7763 ;; narrowing might be in effect.
7764 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7765 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7766 (setq string
7767 (mapconcat 'identity
7768 (tramp-compat-split-string string "\n")
7769 tramp-rsh-end-of-line))
7770 (unless (or (string= string "")
7771 (string-equal (substring string -1) tramp-rsh-end-of-line))
7772 (setq string (concat string tramp-rsh-end-of-line)))
7773 ;; Send the string.
7774 (if (and chunksize (not (zerop chunksize)))
7775 (let ((pos 0)
7776 (end (length string)))
7777 (while (< pos end)
7778 (tramp-message
7779 vec 10 "Sending chunk from %s to %s"
7780 pos (min (+ pos chunksize) end))
7781 (process-send-string
7782 p (substring string pos (min (+ pos chunksize) end)))
7783 (setq pos (+ pos chunksize))))
7784 (process-send-string p string)))))
7785
7786 (defun tramp-mode-string-to-int (mode-string)
7787 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7788 (let* (case-fold-search
7789 (mode-chars (string-to-vector mode-string))
7790 (owner-read (aref mode-chars 1))
7791 (owner-write (aref mode-chars 2))
7792 (owner-execute-or-setid (aref mode-chars 3))
7793 (group-read (aref mode-chars 4))
7794 (group-write (aref mode-chars 5))
7795 (group-execute-or-setid (aref mode-chars 6))
7796 (other-read (aref mode-chars 7))
7797 (other-write (aref mode-chars 8))
7798 (other-execute-or-sticky (aref mode-chars 9)))
7799 (save-match-data
7800 (logior
7801 (cond
7802 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7803 ((char-equal owner-read ?-) 0)
7804 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7805 (cond
7806 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7807 ((char-equal owner-write ?-) 0)
7808 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7809 (cond
7810 ((char-equal owner-execute-or-setid ?x)
7811 (tramp-octal-to-decimal "00100"))
7812 ((char-equal owner-execute-or-setid ?S)
7813 (tramp-octal-to-decimal "04000"))
7814 ((char-equal owner-execute-or-setid ?s)
7815 (tramp-octal-to-decimal "04100"))
7816 ((char-equal owner-execute-or-setid ?-) 0)
7817 (t (error "Fourth char `%c' must be one of `xsS-'"
7818 owner-execute-or-setid)))
7819 (cond
7820 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7821 ((char-equal group-read ?-) 0)
7822 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7823 (cond
7824 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7825 ((char-equal group-write ?-) 0)
7826 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7827 (cond
7828 ((char-equal group-execute-or-setid ?x)
7829 (tramp-octal-to-decimal "00010"))
7830 ((char-equal group-execute-or-setid ?S)
7831 (tramp-octal-to-decimal "02000"))
7832 ((char-equal group-execute-or-setid ?s)
7833 (tramp-octal-to-decimal "02010"))
7834 ((char-equal group-execute-or-setid ?-) 0)
7835 (t (error "Seventh char `%c' must be one of `xsS-'"
7836 group-execute-or-setid)))
7837 (cond
7838 ((char-equal other-read ?r)
7839 (tramp-octal-to-decimal "00004"))
7840 ((char-equal other-read ?-) 0)
7841 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7842 (cond
7843 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7844 ((char-equal other-write ?-) 0)
7845 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7846 (cond
7847 ((char-equal other-execute-or-sticky ?x)
7848 (tramp-octal-to-decimal "00001"))
7849 ((char-equal other-execute-or-sticky ?T)
7850 (tramp-octal-to-decimal "01000"))
7851 ((char-equal other-execute-or-sticky ?t)
7852 (tramp-octal-to-decimal "01001"))
7853 ((char-equal other-execute-or-sticky ?-) 0)
7854 (t (error "Tenth char `%c' must be one of `xtT-'"
7855 other-execute-or-sticky)))))))
7856
7857 (defun tramp-convert-file-attributes (vec attr)
7858 "Convert file-attributes ATTR generated by perl script, stat or ls.
7859 Convert file mode bits to string and set virtual device number.
7860 Return ATTR."
7861 (when attr
7862 ;; Convert last access time.
7863 (unless (listp (nth 4 attr))
7864 (setcar (nthcdr 4 attr)
7865 (list (floor (nth 4 attr) 65536)
7866 (floor (mod (nth 4 attr) 65536)))))
7867 ;; Convert last modification time.
7868 (unless (listp (nth 5 attr))
7869 (setcar (nthcdr 5 attr)
7870 (list (floor (nth 5 attr) 65536)
7871 (floor (mod (nth 5 attr) 65536)))))
7872 ;; Convert last status change time.
7873 (unless (listp (nth 6 attr))
7874 (setcar (nthcdr 6 attr)
7875 (list (floor (nth 6 attr) 65536)
7876 (floor (mod (nth 6 attr) 65536)))))
7877 ;; Convert file size.
7878 (when (< (nth 7 attr) 0)
7879 (setcar (nthcdr 7 attr) -1))
7880 (when (and (floatp (nth 7 attr))
7881 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7882 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7883 ;; Convert file mode bits to string.
7884 (unless (stringp (nth 8 attr))
7885 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7886 (when (stringp (car attr))
7887 (aset (nth 8 attr) 0 ?l)))
7888 ;; Convert directory indication bit.
7889 (when (string-match "^d" (nth 8 attr))
7890 (setcar attr t))
7891 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7892 (when (consp (car attr))
7893 (if (and (stringp (caar attr))
7894 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7895 (setcar attr (match-string 1 (caar attr)))
7896 (setcar attr nil)))
7897 ;; Set file's gid change bit.
7898 (setcar (nthcdr 9 attr)
7899 (if (numberp (nth 3 attr))
7900 (not (= (nth 3 attr)
7901 (tramp-get-remote-gid vec 'integer)))
7902 (not (string-equal
7903 (nth 3 attr)
7904 (tramp-get-remote-gid vec 'string)))))
7905 ;; Convert inode.
7906 (unless (listp (nth 10 attr))
7907 (setcar (nthcdr 10 attr)
7908 (condition-case nil
7909 (cons (floor (nth 10 attr) 65536)
7910 (floor (mod (nth 10 attr) 65536)))
7911 ;; Inodes can be incredible huge. We must hide this.
7912 (error (tramp-get-inode vec)))))
7913 ;; Set virtual device number.
7914 (setcar (nthcdr 11 attr)
7915 (tramp-get-device vec))
7916 attr))
7917
7918 (defun tramp-check-cached-permissions (vec access)
7919 "Check `file-attributes' caches for VEC.
7920 Return t if according to the cache access type ACCESS is known to
7921 be granted."
7922 (let ((result nil)
7923 (offset (cond
7924 ((eq ?r access) 1)
7925 ((eq ?w access) 2)
7926 ((eq ?x access) 3))))
7927 (dolist (suffix '("string" "integer") result)
7928 (setq
7929 result
7930 (or
7931 result
7932 (let ((file-attr
7933 (tramp-get-file-property
7934 vec (tramp-file-name-localname vec)
7935 (concat "file-attributes-" suffix) nil))
7936 (remote-uid
7937 (tramp-get-connection-property
7938 vec (concat "uid-" suffix) nil))
7939 (remote-gid
7940 (tramp-get-connection-property
7941 vec (concat "gid-" suffix) nil)))
7942 (and
7943 file-attr
7944 (or
7945 ;; Not a symlink
7946 (eq t (car file-attr))
7947 (null (car file-attr)))
7948 (or
7949 ;; World accessible.
7950 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7951 ;; User accessible and owned by user.
7952 (and
7953 (eq access (aref (nth 8 file-attr) offset))
7954 (equal remote-uid (nth 2 file-attr)))
7955 ;; Group accessible and owned by user's
7956 ;; principal group.
7957 (and
7958 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7959 (equal remote-gid (nth 3 file-attr)))))))))))
7960
7961 (defun tramp-get-inode (vec)
7962 "Returns the virtual inode number.
7963 If it doesn't exist, generate a new one."
7964 (let ((string (tramp-make-tramp-file-name
7965 (tramp-file-name-method vec)
7966 (tramp-file-name-user vec)
7967 (tramp-file-name-host vec)
7968 "")))
7969 (unless (assoc string tramp-inodes)
7970 (add-to-list 'tramp-inodes
7971 (list string (length tramp-inodes))))
7972 (nth 1 (assoc string tramp-inodes))))
7973
7974 (defun tramp-get-device (vec)
7975 "Returns the virtual device number.
7976 If it doesn't exist, generate a new one."
7977 (let ((string (tramp-make-tramp-file-name
7978 (tramp-file-name-method vec)
7979 (tramp-file-name-user vec)
7980 (tramp-file-name-host vec)
7981 "")))
7982 (unless (assoc string tramp-devices)
7983 (add-to-list 'tramp-devices
7984 (list string (length tramp-devices))))
7985 (cons -1 (nth 1 (assoc string tramp-devices)))))
7986
7987 (defun tramp-file-mode-from-int (mode)
7988 "Turn an integer representing a file mode into an ls(1)-like string."
7989 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7990 (user (logand (lsh mode -6) 7))
7991 (group (logand (lsh mode -3) 7))
7992 (other (logand (lsh mode -0) 7))
7993 (suid (> (logand (lsh mode -9) 4) 0))
7994 (sgid (> (logand (lsh mode -9) 2) 0))
7995 (sticky (> (logand (lsh mode -9) 1) 0)))
7996 (setq user (tramp-file-mode-permissions user suid "s"))
7997 (setq group (tramp-file-mode-permissions group sgid "s"))
7998 (setq other (tramp-file-mode-permissions other sticky "t"))
7999 (concat type user group other)))
8000
8001 (defun tramp-file-mode-permissions (perm suid suid-text)
8002 "Convert a permission bitset into a string.
8003 This is used internally by `tramp-file-mode-from-int'."
8004 (let ((r (> (logand perm 4) 0))
8005 (w (> (logand perm 2) 0))
8006 (x (> (logand perm 1) 0)))
8007 (concat (or (and r "r") "-")
8008 (or (and w "w") "-")
8009 (or (and suid x suid-text) ; suid, execute
8010 (and suid (upcase suid-text)) ; suid, !execute
8011 (and x "x") "-")))) ; !suid
8012
8013 (defun tramp-decimal-to-octal (i)
8014 "Return a string consisting of the octal digits of I.
8015 Not actually used. Use `(format \"%o\" i)' instead?"
8016 (cond ((< i 0) (error "Cannot convert negative number to octal"))
8017 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
8018 ((zerop i) "0")
8019 (t (concat (tramp-decimal-to-octal (/ i 8))
8020 (number-to-string (% i 8))))))
8021
8022 ;; Kudos to Gerd Moellmann for this suggestion.
8023 (defun tramp-octal-to-decimal (ostr)
8024 "Given a string of octal digits, return a decimal number."
8025 (let ((x (or ostr "")))
8026 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
8027 (unless (string-match "\\`[0-7]*\\'" x)
8028 (error "Non-octal junk in string `%s'" x))
8029 (string-to-number ostr 8)))
8030
8031 (defun tramp-shell-case-fold (string)
8032 "Converts STRING to shell glob pattern which ignores case."
8033 (mapconcat
8034 (lambda (c)
8035 (if (equal (downcase c) (upcase c))
8036 (vector c)
8037 (format "[%c%c]" (downcase c) (upcase c))))
8038 string
8039 ""))
8040
8041
8042 ;; ------------------------------------------------------------
8043 ;; -- Tramp file names --
8044 ;; ------------------------------------------------------------
8045 ;; Conversion functions between external representation and
8046 ;; internal data structure. Convenience functions for internal
8047 ;; data structure.
8048
8049 (defun tramp-file-name-p (vec)
8050 "Check, whether VEC is a Tramp object."
8051 (and (vectorp vec) (= 4 (length vec))))
8052
8053 (defun tramp-file-name-method (vec)
8054 "Return method component of VEC."
8055 (and (tramp-file-name-p vec) (aref vec 0)))
8056
8057 (defun tramp-file-name-user (vec)
8058 "Return user component of VEC."
8059 (and (tramp-file-name-p vec) (aref vec 1)))
8060
8061 (defun tramp-file-name-host (vec)
8062 "Return host component of VEC."
8063 (and (tramp-file-name-p vec) (aref vec 2)))
8064
8065 (defun tramp-file-name-localname (vec)
8066 "Return localname component of VEC."
8067 (and (tramp-file-name-p vec) (aref vec 3)))
8068
8069 ;; The user part of a Tramp file name vector can be of kind
8070 ;; "user%domain". Sometimes, we must extract these parts.
8071 (defun tramp-file-name-real-user (vec)
8072 "Return the user name of VEC without domain."
8073 (save-match-data
8074 (let ((user (tramp-file-name-user vec)))
8075 (if (and (stringp user)
8076 (string-match tramp-user-with-domain-regexp user))
8077 (match-string 1 user)
8078 user))))
8079
8080 (defun tramp-file-name-domain (vec)
8081 "Return the domain name of VEC."
8082 (save-match-data
8083 (let ((user (tramp-file-name-user vec)))
8084 (and (stringp user)
8085 (string-match tramp-user-with-domain-regexp user)
8086 (match-string 2 user)))))
8087
8088 ;; The host part of a Tramp file name vector can be of kind
8089 ;; "host#port". Sometimes, we must extract these parts.
8090 (defun tramp-file-name-real-host (vec)
8091 "Return the host name of VEC without port."
8092 (save-match-data
8093 (let ((host (tramp-file-name-host vec)))
8094 (if (and (stringp host)
8095 (string-match tramp-host-with-port-regexp host))
8096 (match-string 1 host)
8097 host))))
8098
8099 (defun tramp-file-name-port (vec)
8100 "Return the port number of VEC."
8101 (save-match-data
8102 (let ((host (tramp-file-name-host vec)))
8103 (and (stringp host)
8104 (string-match tramp-host-with-port-regexp host)
8105 (string-to-number (match-string 2 host))))))
8106
8107 (defun tramp-tramp-file-p (name)
8108 "Return t if NAME is a string with Tramp file name syntax."
8109 (save-match-data
8110 (and (stringp name) (string-match tramp-file-name-regexp name))))
8111
8112 (defun tramp-find-method (method user host)
8113 "Return the right method string to use.
8114 This is METHOD, if non-nil. Otherwise, do a lookup in
8115 `tramp-default-method-alist'."
8116 (or method
8117 (let ((choices tramp-default-method-alist)
8118 lmethod item)
8119 (while choices
8120 (setq item (pop choices))
8121 (when (and (string-match (or (nth 0 item) "") (or host ""))
8122 (string-match (or (nth 1 item) "") (or user "")))
8123 (setq lmethod (nth 2 item))
8124 (setq choices nil)))
8125 lmethod)
8126 tramp-default-method))
8127
8128 (defun tramp-find-user (method user host)
8129 "Return the right user string to use.
8130 This is USER, if non-nil. Otherwise, do a lookup in
8131 `tramp-default-user-alist'."
8132 (or user
8133 (let ((choices tramp-default-user-alist)
8134 luser item)
8135 (while choices
8136 (setq item (pop choices))
8137 (when (and (string-match (or (nth 0 item) "") (or method ""))
8138 (string-match (or (nth 1 item) "") (or host "")))
8139 (setq luser (nth 2 item))
8140 (setq choices nil)))
8141 luser)
8142 tramp-default-user))
8143
8144 (defun tramp-find-host (method user host)
8145 "Return the right host string to use.
8146 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
8147 (or (and (> (length host) 0) host)
8148 tramp-default-host))
8149
8150 (defun tramp-dissect-file-name (name &optional nodefault)
8151 "Return a `tramp-file-name' structure.
8152 The structure consists of remote method, remote user, remote host
8153 and localname (file name on remote host). If NODEFAULT is
8154 non-nil, the file name parts are not expanded to their default
8155 values."
8156 (save-match-data
8157 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
8158 (unless match (error "Not a Tramp file name: %s" name))
8159 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
8160 (user (match-string (nth 2 tramp-file-name-structure) name))
8161 (host (match-string (nth 3 tramp-file-name-structure) name))
8162 (localname (match-string (nth 4 tramp-file-name-structure) name)))
8163 (when (member method '("multi" "multiu"))
8164 (error
8165 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
8166 method))
8167 (when host
8168 (when (string-match tramp-prefix-ipv6-regexp host)
8169 (setq host (replace-match "" nil t host)))
8170 (when (string-match tramp-postfix-ipv6-regexp host)
8171 (setq host (replace-match "" nil t host))))
8172 (if nodefault
8173 (vector method user host localname)
8174 (vector
8175 (tramp-find-method method user host)
8176 (tramp-find-user method user host)
8177 (tramp-find-host method user host)
8178 localname))))))
8179
8180 (defun tramp-equal-remote (file1 file2)
8181 "Check, whether the remote parts of FILE1 and FILE2 are identical.
8182 The check depends on method, user and host name of the files. If
8183 one of the components is missing, the default values are used.
8184 The local file name parts of FILE1 and FILE2 are not taken into
8185 account.
8186
8187 Example:
8188
8189 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
8190
8191 would yield `t'. On the other hand, the following check results in nil:
8192
8193 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
8194 (and (stringp (file-remote-p file1))
8195 (stringp (file-remote-p file2))
8196 (string-equal (file-remote-p file1) (file-remote-p file2))))
8197
8198 (defun tramp-make-tramp-file-name (method user host localname)
8199 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
8200 (concat tramp-prefix-format
8201 (when (not (zerop (length method)))
8202 (concat method tramp-postfix-method-format))
8203 (when (not (zerop (length user)))
8204 (concat user tramp-postfix-user-format))
8205 (when host
8206 (if (string-match tramp-ipv6-regexp host)
8207 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8208 host))
8209 tramp-postfix-host-format
8210 (when localname localname)))
8211
8212 (defun tramp-completion-make-tramp-file-name (method user host localname)
8213 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
8214 It must not be a complete Tramp file name, but as long as there are
8215 necessary only. This function will be used in file name completion."
8216 (concat tramp-prefix-format
8217 (when (not (zerop (length method)))
8218 (concat method tramp-postfix-method-format))
8219 (when (not (zerop (length user)))
8220 (concat user tramp-postfix-user-format))
8221 (when (not (zerop (length host)))
8222 (concat
8223 (if (string-match tramp-ipv6-regexp host)
8224 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8225 host)
8226 tramp-postfix-host-format))
8227 (when localname localname)))
8228
8229 (defun tramp-make-copy-program-file-name (vec)
8230 "Create a file name suitable to be passed to `rcp' and workalikes."
8231 (let ((user (tramp-file-name-user vec))
8232 (host (tramp-file-name-real-host vec))
8233 (localname (tramp-shell-quote-argument
8234 (tramp-file-name-localname vec))))
8235 (if (not (zerop (length user)))
8236 (format "%s@%s:%s" user host localname)
8237 (format "%s:%s" host localname))))
8238
8239 (defun tramp-method-out-of-band-p (vec size)
8240 "Return t if this is an out-of-band method, nil otherwise."
8241 (and
8242 ;; It shall be an out-of-band method.
8243 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
8244 ;; Either the file size is large enough, or (in rare cases) there
8245 ;; does not exist a remote encoding.
8246 (or (null tramp-copy-size-limit)
8247 (> size tramp-copy-size-limit)
8248 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
8249
8250 (defun tramp-local-host-p (vec)
8251 "Return t if this points to the local host, nil otherwise."
8252 ;; We cannot use `tramp-file-name-real-host'. A port is an
8253 ;; indication for an ssh tunnel or alike.
8254 (let ((host (tramp-file-name-host vec)))
8255 (and
8256 (stringp host)
8257 (string-match tramp-local-host-regexp host)
8258 ;; The method shall be applied to one of the shell file name
8259 ;; handler. `tramp-local-host-p' is also called for "smb" and
8260 ;; alike, where it must fail.
8261 (tramp-get-method-parameter
8262 (tramp-file-name-method vec) 'tramp-login-program)
8263 ;; The local temp directory must be writable for the other user.
8264 (file-writable-p
8265 (tramp-make-tramp-file-name
8266 (tramp-file-name-method vec)
8267 (tramp-file-name-user vec)
8268 host
8269 (tramp-compat-temporary-file-directory)))
8270 ;; On some systems, chown runs only for root.
8271 (or (zerop (user-uid))
8272 (zerop (tramp-get-remote-uid vec 'integer))))))
8273
8274 ;; Variables local to connection.
8275
8276 (defun tramp-get-remote-path (vec)
8277 (with-connection-property
8278 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8279 ;; cache the result for the session only. Otherwise, the result
8280 ;; is cached persistently.
8281 (if (memq 'tramp-own-remote-path tramp-remote-path)
8282 (tramp-get-connection-process vec)
8283 vec)
8284 "remote-path"
8285 (let* ((remote-path (copy-tree tramp-remote-path))
8286 (elt1 (memq 'tramp-default-remote-path remote-path))
8287 (elt2 (memq 'tramp-own-remote-path remote-path))
8288 (default-remote-path
8289 (when elt1
8290 (condition-case nil
8291 (tramp-send-command-and-read
8292 vec "echo \\\"`getconf PATH`\\\"")
8293 ;; Default if "getconf" is not available.
8294 (error
8295 (tramp-message
8296 vec 3
8297 "`getconf PATH' not successful, using default value \"%s\"."
8298 "/bin:/usr/bin")
8299 "/bin:/usr/bin"))))
8300 (own-remote-path
8301 (when elt2
8302 (condition-case nil
8303 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8304 ;; Default if "getconf" is not available.
8305 (error
8306 (tramp-message
8307 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8308 nil)))))
8309
8310 ;; Replace place holder `tramp-default-remote-path'.
8311 (when elt1
8312 (setcdr elt1
8313 (append
8314 (tramp-compat-split-string default-remote-path ":")
8315 (cdr elt1)))
8316 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8317
8318 ;; Replace place holder `tramp-own-remote-path'.
8319 (when elt2
8320 (setcdr elt2
8321 (append
8322 (tramp-compat-split-string own-remote-path ":")
8323 (cdr elt2)))
8324 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8325
8326 ;; Remove double entries.
8327 (setq elt1 remote-path)
8328 (while (consp elt1)
8329 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8330 (setcar elt2 nil))
8331 (setq elt1 (cdr elt1)))
8332
8333 ;; Remove non-existing directories.
8334 (delq
8335 nil
8336 (mapcar
8337 (lambda (x)
8338 (and
8339 (stringp x)
8340 (file-directory-p
8341 (tramp-make-tramp-file-name
8342 (tramp-file-name-method vec)
8343 (tramp-file-name-user vec)
8344 (tramp-file-name-host vec)
8345 x))
8346 x))
8347 remote-path)))))
8348
8349 (defun tramp-get-remote-tmpdir (vec)
8350 (with-connection-property vec "tmp-directory"
8351 (let ((dir (tramp-shell-quote-argument "/tmp")))
8352 (if (and (zerop
8353 (tramp-send-command-and-check
8354 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8355 (zerop
8356 (tramp-send-command-and-check
8357 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8358 dir
8359 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8360
8361 (defun tramp-get-ls-command (vec)
8362 (with-connection-property vec "ls"
8363 (tramp-message vec 5 "Finding a suitable `ls' command")
8364 (or
8365 (catch 'ls-found
8366 (dolist (cmd '("ls" "gnuls" "gls"))
8367 (let ((dl (tramp-get-remote-path vec))
8368 result)
8369 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8370 ;; Check parameters. On busybox, "ls" output coloring is
8371 ;; enabled by default sometimes. So we try to disable it
8372 ;; when possible. $LS_COLORING is not supported there.
8373 ;; Some "ls" versions are sensible wrt the order of
8374 ;; arguments, they fail when "-al" is after the
8375 ;; "--color=never" argument (for example on FreeBSD).
8376 (when (zerop (tramp-send-command-and-check
8377 vec (format "%s -lnd /" result)))
8378 (when (zerop (tramp-send-command-and-check
8379 vec (format
8380 "%s --color=never -al /dev/null" result)))
8381 (setq result (concat result " --color=never")))
8382 (throw 'ls-found result))
8383 (setq dl (cdr dl))))))
8384 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8385
8386 (defun tramp-get-ls-command-with-dired (vec)
8387 (save-match-data
8388 (with-connection-property vec "ls-dired"
8389 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8390 ;; Some "ls" versions are sensible wrt the order of arguments,
8391 ;; they fail when "-al" is after the "--dired" argument (for
8392 ;; example on FreeBSD).
8393 (zerop (tramp-send-command-and-check
8394 vec (format "%s --dired -al /dev/null"
8395 (tramp-get-ls-command vec)))))))
8396
8397 (defun tramp-get-test-command (vec)
8398 (with-connection-property vec "test"
8399 (tramp-message vec 5 "Finding a suitable `test' command")
8400 (if (zerop (tramp-send-command-and-check vec "test 0"))
8401 "test"
8402 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8403
8404 (defun tramp-get-test-nt-command (vec)
8405 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8406 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8407 ;; for otherwise the shell crashes.
8408 (with-connection-property vec "test-nt"
8409 (or
8410 (progn
8411 (tramp-send-command
8412 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8413 (with-current-buffer (tramp-get-buffer vec)
8414 (goto-char (point-min))
8415 (when (looking-at (regexp-quote tramp-end-of-output))
8416 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8417 (progn
8418 (tramp-send-command
8419 vec
8420 (format
8421 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8422 (tramp-get-test-command vec)))
8423 "tramp_test_nt %s %s"))))
8424
8425 (defun tramp-get-file-exists-command (vec)
8426 (with-connection-property vec "file-exists"
8427 (tramp-message vec 5 "Finding command to check if file exists")
8428 (tramp-find-file-exists-command vec)))
8429
8430 (defun tramp-get-remote-ln (vec)
8431 (with-connection-property vec "ln"
8432 (tramp-message vec 5 "Finding a suitable `ln' command")
8433 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8434
8435 (defun tramp-get-remote-perl (vec)
8436 (with-connection-property vec "perl"
8437 (tramp-message vec 5 "Finding a suitable `perl' command")
8438 (let ((result
8439 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8440 (tramp-find-executable
8441 vec "perl" (tramp-get-remote-path vec)))))
8442 ;; We must check also for some Perl modules.
8443 (when result
8444 (with-connection-property vec "perl-file-spec"
8445 (zerop
8446 (tramp-send-command-and-check
8447 vec (format "%s -e 'use File::Spec;'" result))))
8448 (with-connection-property vec "perl-cwd-realpath"
8449 (zerop
8450 (tramp-send-command-and-check
8451 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8452 result)))
8453
8454 (defun tramp-get-remote-stat (vec)
8455 (with-connection-property vec "stat"
8456 (tramp-message vec 5 "Finding a suitable `stat' command")
8457 (let ((result (tramp-find-executable
8458 vec "stat" (tramp-get-remote-path vec)))
8459 tmp)
8460 ;; Check whether stat(1) returns usable syntax. %s does not
8461 ;; work on older AIX systems.
8462 (when result
8463 (setq tmp
8464 ;; We don't want to display an error message.
8465 (with-temp-message (or (current-message) "")
8466 (condition-case nil
8467 (tramp-send-command-and-read
8468 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8469 (error nil))))
8470 (unless (and (listp tmp) (stringp (car tmp))
8471 (string-match "^./.$" (car tmp))
8472 (integerp (cadr tmp)))
8473 (setq result nil)))
8474 result)))
8475
8476 (defun tramp-get-remote-readlink (vec)
8477 (with-connection-property vec "readlink"
8478 (tramp-message vec 5 "Finding a suitable `readlink' command")
8479 (let ((result (tramp-find-executable
8480 vec "readlink" (tramp-get-remote-path vec))))
8481 (when (and result
8482 ;; We don't want to display an error message.
8483 (with-temp-message (or (current-message) "")
8484 (condition-case nil
8485 (zerop
8486 (tramp-send-command-and-check
8487 vec (format "%s --canonicalize-missing /" result)))
8488 (error nil))))
8489 result))))
8490
8491 (defun tramp-get-remote-trash (vec)
8492 (with-connection-property vec "trash"
8493 (tramp-message vec 5 "Finding a suitable `trash' command")
8494 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
8495
8496 (defun tramp-get-remote-id (vec)
8497 (with-connection-property vec "id"
8498 (tramp-message vec 5 "Finding POSIX `id' command")
8499 (or
8500 (catch 'id-found
8501 (let ((dl (tramp-get-remote-path vec))
8502 result)
8503 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8504 ;; Check POSIX parameter.
8505 (when (zerop (tramp-send-command-and-check
8506 vec (format "%s -u" result)))
8507 (throw 'id-found result))
8508 (setq dl (cdr dl)))))
8509 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8510
8511 (defun tramp-get-remote-uid (vec id-format)
8512 (with-connection-property vec (format "uid-%s" id-format)
8513 (let ((res (tramp-send-command-and-read
8514 vec
8515 (format "%s -u%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-remote-gid (vec id-format)
8524 (with-connection-property vec (format "gid-%s" id-format)
8525 (let ((res (tramp-send-command-and-read
8526 vec
8527 (format "%s -g%s %s"
8528 (tramp-get-remote-id vec)
8529 (if (equal id-format 'integer) "" "n")
8530 (if (equal id-format 'integer)
8531 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8532 ;; The command might not always return a number.
8533 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8534
8535 (defun tramp-get-local-uid (id-format)
8536 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8537
8538 (defun tramp-get-local-gid (id-format)
8539 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8540
8541 ;; Some predefined connection properties.
8542 (defun tramp-get-inline-compress (vec prop size)
8543 "Return the compress command related to PROP.
8544 PROP is either `inline-compress' or `inline-decompress'. SIZE is
8545 the length of the file to be compressed.
8546
8547 If no corresponding command is found, nil is returned."
8548 (when (and (integerp tramp-inline-compress-start-size)
8549 (> size tramp-inline-compress-start-size))
8550 (with-connection-property vec prop
8551 (tramp-find-inline-compress vec)
8552 (tramp-get-connection-property vec prop nil))))
8553
8554 (defun tramp-get-inline-coding (vec prop size)
8555 "Return the coding command related to PROP.
8556 PROP is either `remote-encoding', `remode-decoding',
8557 `local-encoding' or `local-decoding'.
8558
8559 SIZE is the length of the file to be coded. Depending on SIZE,
8560 compression might be applied.
8561
8562 If no corresponding command is found, nil is returned.
8563 Otherwise, either a string is returned which contains a `%s' mark
8564 to be used for the respective input or output file; or a Lisp
8565 function cell is returned to be applied on a buffer."
8566 (let ((coding
8567 (with-connection-property vec prop
8568 (tramp-find-inline-encoding vec)
8569 (tramp-get-connection-property vec prop nil)))
8570 (prop1 (if (string-match "encoding" prop)
8571 "inline-compress" "inline-decompress"))
8572 compress)
8573 ;; The connection property might have been cached. So we must send
8574 ;; the script to the remote side - maybe.
8575 (when (and coding (symbolp coding) (string-match "remote" prop))
8576 (let ((name (symbol-name coding)))
8577 (while (string-match (regexp-quote "-") name)
8578 (setq name (replace-match "_" nil t name)))
8579 (tramp-maybe-send-script vec (symbol-value coding) name)
8580 (setq coding name)))
8581 (when coding
8582 ;; Check for the `compress' command.
8583 (setq compress (tramp-get-inline-compress vec prop1 size))
8584 ;; Return the value.
8585 (cond
8586 ((and compress (symbolp coding))
8587 (if (string-match "decompress" prop1)
8588 `(lambda (beg end)
8589 (,coding beg end)
8590 (let ((coding-system-for-write 'binary)
8591 (coding-system-for-read 'binary))
8592 (apply
8593 'call-process-region (point-min) (point-max)
8594 (car (split-string ,compress)) t t nil
8595 (cdr (split-string ,compress)))))
8596 `(lambda (beg end)
8597 (let ((coding-system-for-write 'binary)
8598 (coding-system-for-read 'binary))
8599 (apply
8600 'call-process-region beg end
8601 (car (split-string ,compress)) t t nil
8602 (cdr (split-string ,compress))))
8603 (,coding (point-min) (point-max)))))
8604 ((symbolp coding)
8605 coding)
8606 ((and compress (string-match "decoding" prop))
8607 (format "(%s | %s >%%s)" coding compress))
8608 (compress
8609 (format "(%s <%%s | %s)" compress coding))
8610 ((string-match "decoding" prop)
8611 (format "%s >%%s" coding))
8612 (t
8613 (format "%s <%%s" coding))))))
8614
8615 (defun tramp-get-method-parameter (method param)
8616 "Return the method parameter PARAM.
8617 If the `tramp-methods' entry does not exist, return nil."
8618 (let ((entry (assoc param (assoc method tramp-methods))))
8619 (when entry (cadr entry))))
8620
8621 ;; Auto saving to a special directory.
8622
8623 (defun tramp-exists-file-name-handler (operation &rest args)
8624 "Check, whether OPERATION runs a file name handler."
8625 ;; The file name handler is determined on base of either an
8626 ;; argument, `buffer-file-name', or `default-directory'.
8627 (condition-case nil
8628 (let* ((buffer-file-name "/")
8629 (default-directory "/")
8630 (fnha file-name-handler-alist)
8631 (check-file-name-operation operation)
8632 (file-name-handler-alist
8633 (list
8634 (cons "/"
8635 (lambda (operation &rest args)
8636 "Returns OPERATION if it is the one to be checked."
8637 (if (equal check-file-name-operation operation)
8638 operation
8639 (let ((file-name-handler-alist fnha))
8640 (apply operation args))))))))
8641 (equal (apply operation args) operation))
8642 (error nil)))
8643
8644 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8645 (defadvice make-auto-save-file-name
8646 (around tramp-advice-make-auto-save-file-name () activate)
8647 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8648 (if (tramp-tramp-file-p (buffer-file-name))
8649 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8650 ;; directly, because this would bypass the locking mechanism.
8651 (setq ad-return-value
8652 (tramp-file-name-handler 'make-auto-save-file-name))
8653 ad-do-it))
8654 (add-hook
8655 'tramp-unload-hook
8656 (lambda ()
8657 (ad-remove-advice
8658 'make-auto-save-file-name
8659 'around 'tramp-advice-make-auto-save-file-name)
8660 (ad-activate 'make-auto-save-file-name))))
8661
8662 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8663 ;; umask. This is a security threat.
8664
8665 (defun tramp-set-auto-save-file-modes ()
8666 "Set permissions of autosaved remote files to the original permissions."
8667 (let ((bfn (buffer-file-name)))
8668 (when (and (tramp-tramp-file-p bfn)
8669 (buffer-modified-p)
8670 (stringp buffer-auto-save-file-name)
8671 (not (equal bfn buffer-auto-save-file-name)))
8672 (unless (file-exists-p buffer-auto-save-file-name)
8673 (write-region "" nil buffer-auto-save-file-name))
8674 ;; Permissions should be set always, because there might be an old
8675 ;; auto-saved file belonging to another original file. This could
8676 ;; be a security threat.
8677 (set-file-modes buffer-auto-save-file-name
8678 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8679
8680 (unless (and (featurep 'xemacs)
8681 (= emacs-major-version 21)
8682 (> emacs-minor-version 4))
8683 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8684 (add-hook 'tramp-unload-hook
8685 (lambda ()
8686 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8687
8688 (defun tramp-subst-strs-in-string (alist string)
8689 "Replace all occurrences of the string FROM with TO in STRING.
8690 ALIST is of the form ((FROM . TO) ...)."
8691 (save-match-data
8692 (while alist
8693 (let* ((pr (car alist))
8694 (from (car pr))
8695 (to (cdr pr)))
8696 (while (string-match (regexp-quote from) string)
8697 (setq string (replace-match to t t string)))
8698 (setq alist (cdr alist))))
8699 string))
8700
8701 ;; ------------------------------------------------------------
8702 ;; -- Compatibility functions section --
8703 ;; ------------------------------------------------------------
8704
8705 (defun tramp-read-passwd (proc &optional prompt)
8706 "Read a password from user (compat function).
8707 Consults the auth-source package.
8708 Invokes `password-read' if available, `read-passwd' else."
8709 (let* ((key (tramp-make-tramp-file-name
8710 tramp-current-method tramp-current-user
8711 tramp-current-host ""))
8712 (pw-prompt
8713 (or prompt
8714 (with-current-buffer (process-buffer proc)
8715 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8716 (format "%s for %s " (capitalize (match-string 1)) key)))))
8717 (with-parsed-tramp-file-name key nil
8718 (prog1
8719 (or
8720 ;; See if auth-sources contains something useful, if it's bound.
8721 (and (boundp 'auth-sources)
8722 (tramp-get-connection-property v "first-password-request" nil)
8723 ;; Try with Tramp's current method.
8724 (tramp-compat-funcall
8725 'auth-source-user-or-password
8726 "password" tramp-current-host tramp-current-method))
8727 ;; Try the password cache.
8728 (when (functionp 'password-read)
8729 (unless (tramp-get-connection-property
8730 v "first-password-request" nil)
8731 (tramp-compat-funcall 'password-cache-remove key))
8732 (let ((password
8733 (tramp-compat-funcall 'password-read pw-prompt key)))
8734 (tramp-compat-funcall 'password-cache-add key password)
8735 password))
8736 ;; Else, get the password interactively.
8737 (read-passwd pw-prompt))
8738 (tramp-set-connection-property v "first-password-request" nil)))))
8739
8740 (defun tramp-clear-passwd (vec)
8741 "Clear password cache for connection related to VEC."
8742 (tramp-compat-funcall
8743 'password-cache-remove
8744 (tramp-make-tramp-file-name
8745 (tramp-file-name-method vec)
8746 (tramp-file-name-user vec)
8747 (tramp-file-name-host vec)
8748 "")))
8749
8750 ;; Snarfed code from time-date.el and parse-time.el
8751
8752 (defconst tramp-half-a-year '(241 17024)
8753 "Evaluated by \"(days-to-time 183)\".")
8754
8755 (defconst tramp-parse-time-months
8756 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8757 ("apr" . 4) ("may" . 5) ("jun" . 6)
8758 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8759 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8760 "Alist mapping month names to integers.")
8761
8762 (defun tramp-time-less-p (t1 t2)
8763 "Say whether time value T1 is less than time value T2."
8764 (unless t1 (setq t1 '(0 0)))
8765 (unless t2 (setq t2 '(0 0)))
8766 (or (< (car t1) (car t2))
8767 (and (= (car t1) (car t2))
8768 (< (nth 1 t1) (nth 1 t2)))))
8769
8770 (defun tramp-time-subtract (t1 t2)
8771 "Subtract two time values.
8772 Return the difference in the format of a time value."
8773 (unless t1 (setq t1 '(0 0)))
8774 (unless t2 (setq t2 '(0 0)))
8775 (let ((borrow (< (cadr t1) (cadr t2))))
8776 (list (- (car t1) (car t2) (if borrow 1 0))
8777 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8778
8779 (defun tramp-time-diff (t1 t2)
8780 "Return the difference between the two times, in seconds.
8781 T1 and T2 are time values (as returned by `current-time' for example)."
8782 ;; Pacify byte-compiler with `symbol-function'.
8783 (cond ((and (fboundp 'subtract-time)
8784 (fboundp 'float-time))
8785 (tramp-compat-funcall
8786 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
8787 ((and (fboundp 'subtract-time)
8788 (fboundp 'time-to-seconds))
8789 (tramp-compat-funcall
8790 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
8791 ((fboundp 'itimer-time-difference)
8792 (tramp-compat-funcall
8793 'itimer-time-difference
8794 (if (< (length t1) 3) (append t1 '(0)) t1)
8795 (if (< (length t2) 3) (append t2 '(0)) t2)))
8796 (t
8797 (let ((time (tramp-time-subtract t1 t2)))
8798 (+ (* (car time) 65536.0)
8799 (cadr time)
8800 (/ (or (nth 2 time) 0) 1000000.0))))))
8801
8802 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8803 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8804 EOL-TYPE can be one of `dos', `unix', or `mac'."
8805 (cond ((fboundp 'coding-system-change-eol-conversion)
8806 (tramp-compat-funcall
8807 'coding-system-change-eol-conversion coding-system eol-type))
8808 ((fboundp 'subsidiary-coding-system)
8809 (tramp-compat-funcall
8810 'subsidiary-coding-system coding-system
8811 (cond ((eq eol-type 'dos) 'crlf)
8812 ((eq eol-type 'unix) 'lf)
8813 ((eq eol-type 'mac) 'cr)
8814 (t
8815 (error "Unknown EOL-TYPE `%s', must be %s"
8816 eol-type
8817 "`dos', `unix', or `mac'")))))
8818 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8819
8820 (defun tramp-set-process-query-on-exit-flag (process flag)
8821 "Specify if query is needed for process when Emacs is exited.
8822 If the second argument flag is non-nil, Emacs will query the user before
8823 exiting if process is running."
8824 (if (fboundp 'set-process-query-on-exit-flag)
8825 (tramp-compat-funcall 'set-process-query-on-exit-flag process flag)
8826 (tramp-compat-funcall 'process-kill-without-query process flag)))
8827
8828
8829 ;; ------------------------------------------------------------
8830 ;; -- Kludges section --
8831 ;; ------------------------------------------------------------
8832
8833 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8834 ;; does not deal well with newline characters. Newline is replaced by
8835 ;; backslash newline. But if, say, the string `a backslash newline b'
8836 ;; is passed to a shell, the shell will expand this into "ab",
8837 ;; completely omitting the newline. This is not what was intended.
8838 ;; It does not appear to be possible to make the function
8839 ;; `shell-quote-argument' work with newlines without making it
8840 ;; dependent on the shell used. But within this package, we know that
8841 ;; we will always use a Bourne-like shell, so we use an approach which
8842 ;; groks newlines.
8843 ;;
8844 ;; The approach is simple: we call `shell-quote-argument', then
8845 ;; massage the newline part of the result.
8846 ;;
8847 ;; This function should produce a string which is grokked by a Unix
8848 ;; shell, even if the Emacs is running on Windows. Since this is the
8849 ;; kludges section, we bind `system-type' in such a way that
8850 ;; `shell-quote-arguments' behaves as if on Unix.
8851 ;;
8852 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8853 ;; function to work with Bourne-like shells.
8854 ;;
8855 ;; CCC: This function should be rewritten so that
8856 ;; `shell-quote-argument' is not used. This way, we are safe from
8857 ;; changes in `shell-quote-argument'.
8858 (defun tramp-shell-quote-argument (s)
8859 "Similar to `shell-quote-argument', but groks newlines.
8860 Only works for Bourne-like shells."
8861 (let ((system-type 'not-windows))
8862 (save-match-data
8863 (let ((result (shell-quote-argument s))
8864 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8865 (when (and (>= (length result) 2)
8866 (string= (substring result 0 2) "\\~"))
8867 (setq result (substring result 1)))
8868 (while (string-match nl result)
8869 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8870 t t result)))
8871 result))))
8872
8873 ;; Checklist for `tramp-unload-hook'
8874 ;; - Unload all `tramp-*' packages
8875 ;; - Reset `file-name-handler-alist'
8876 ;; - Cleanup hooks where Tramp functions are in
8877 ;; - Cleanup advised functions
8878 ;; - Cleanup autoloads
8879 ;;;###autoload
8880 (defun tramp-unload-tramp ()
8881 "Discard Tramp from loading remote files."
8882 (interactive)
8883 ;; When Tramp is not loaded yet, its autoloads are still active.
8884 (tramp-unload-file-name-handlers)
8885 ;; ange-ftp settings must be enabled.
8886 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
8887 ;; Maybe its not loaded yet.
8888 (condition-case nil
8889 (unload-feature 'tramp 'force)
8890 (error nil)))
8891
8892 (when (and load-in-progress
8893 (string-match "Loading tramp..." (or (current-message) "")))
8894 (message "Loading tramp...done"))
8895
8896 (provide 'tramp)
8897
8898 ;;; TODO:
8899
8900 ;; * Handle nonlocal exits such as C-g.
8901 ;; * But it would probably be better to use with-local-quit at the
8902 ;; place where it's actually needed: around any potentially
8903 ;; indefinitely blocking piece of code. In this case it would be
8904 ;; within Tramp around one of its calls to accept-process-output (or
8905 ;; around one of the loops that calls accept-process-output)
8906 ;; (Stefan Monnier).
8907 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8908 ;; `shell-quote-argument'.
8909 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8910 ;; by the files in that directory. Add this here.
8911 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8912 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8913 ;; * Don't use globbing for directories with many files, as this is
8914 ;; likely to produce long command lines, and some shells choke on
8915 ;; long command lines.
8916 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8917 ;; * abbreviate-file-name
8918 ;; * Better error checking. At least whenever we see something
8919 ;; strange when doing zerop, we should kill the process and start
8920 ;; again. (Greg Stark)
8921 ;; * Remove unneeded parameters from methods.
8922 ;; * Make it work for different encodings, and for different file name
8923 ;; encodings, too. (Daniel Pittman)
8924 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8925 ;; then look if it's the right version (with `perl -v').
8926 ;; * When editing a remote CVS controlled file as a different user, VC
8927 ;; gets confused about the file locking status. Try to find out why
8928 ;; the workaround doesn't work.
8929 ;; * Username and hostname completion.
8930 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8931 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8932 ;; Code is nearly identical.
8933 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8934 ;; until the last but one hop via `start-file-process'. Apply it
8935 ;; also for ftp and smb.
8936 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8937 ;; some shell with root priviledges, it would be nice if I could
8938 ;; just call
8939 ;; trampclient filename.c
8940 ;; as an editor, and the _current_ shell would connect to an Emacs
8941 ;; server and would be used in an existing non-priviledged Emacs
8942 ;; session for doing the editing in question.
8943 ;; That way, I need not tell Emacs my password again and be afraid
8944 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8945 ;; once display a just typed password in the context of a keyboard
8946 ;; sequence prompt for a question immediately following in a shell
8947 ;; script run within Emacs -- nasty).
8948 ;; And if I have some ssh session running to a different computer,
8949 ;; having the possibility of passing a local file there to a local
8950 ;; Emacs session (in case I can arrange for a connection back) would
8951 ;; be nice.
8952 ;; Likely the corresponding Tramp server should not allow the
8953 ;; equivalent of the emacsclient -eval option in order to make this
8954 ;; reasonably unproblematic. And maybe trampclient should have some
8955 ;; way of passing credentials, like by using an SSL socket or
8956 ;; something. (David Kastrup)
8957 ;; * Reconnect directly to a compliant shell without first going
8958 ;; through the user's default shell. (Pete Forman)
8959 ;; * Make `tramp-default-user' obsolete.
8960 ;; * How can I interrupt the remote process with a signal
8961 ;; (interrupt-process seems not to work)? (Markus Triska)
8962 ;; * Avoid the local shell entirely for starting remote processes. If
8963 ;; so, I think even a signal, when delivered directly to the local
8964 ;; SSH instance, would correctly be propagated to the remote process
8965 ;; automatically; possibly SSH would have to be started with
8966 ;; "-t". (Markus Triska)
8967 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8968 ;; isn't on the remote host. (Mark A. Hershberger)
8969 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8970 ;; * Implement a general server-local-variable mechanism, as there are
8971 ;; probably other variables that need different values for different
8972 ;; servers too. The user could then configure a variable (such as
8973 ;; tramp-server-local-variable-alist) to define any such variables
8974 ;; that they need to, which would then be let bound as appropriate
8975 ;; in tramp functions. (Jason Rumney)
8976 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8977 ;; rsync).
8978 ;; * Keep a second connection open for out-of-band methods like scp or
8979 ;; rsync.
8980 ;; * IMHO, it's a drawback that currently Tramp doesn't support
8981 ;; Unicode in Dired file names by default. Is it possible to
8982 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8983 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
8984 ;; expects only English messages? (Juri Linkov)
8985 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8986 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
8987 ;; * Try telnet+curl as new method. It might be useful for busybox,
8988 ;; without built-in uuencode/uudecode.
8989 ;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
8990
8991 ;; Functions for file-name-handler-alist:
8992 ;; diff-latest-backup-file -- in diff.el
8993
8994 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8995 ;;; tramp.el ends here
8996
8997 ;; Local Variables:
8998 ;; mode: Emacs-Lisp
8999 ;; coding: utf-8
9000 ;; End: