]> code.delx.au - gnu-emacs/blob - lisp/net/tramp.el
Don't use png_jmpbuf, it doesn't work with dynamic loading.
[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, 2011 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") ("-r")
557 ("-o" "ControlPath=%t.%%r@%%h:%%p")
558 ("-o" "ControlMaster=auto")))
559 (tramp-copy-keep-date t)
560 (tramp-copy-recursive t)
561 (tramp-password-end-of-line nil)
562 (tramp-gw-args (("-o"
563 "GlobalKnownHostsFile=/dev/null")
564 ("-o" "UserKnownHostsFile=/dev/null")
565 ("-o" "StrictHostKeyChecking=no")))
566 (tramp-default-port 22))
567 ("scpx" (tramp-login-program "ssh")
568 (tramp-login-args (("-l" "%u") ("-p" "%p")
569 ("-e" "none") ("-t" "-t")
570 ("%h") ("/bin/sh")))
571 (tramp-async-args (("-q")))
572 (tramp-remote-sh "/bin/sh")
573 (tramp-copy-program "scp")
574 (tramp-copy-args (("-P" "%p") ("-p" "%k")
575 ("-q") ("-r")))
576 (tramp-copy-keep-date t)
577 (tramp-copy-recursive t)
578 (tramp-password-end-of-line nil)
579 (tramp-gw-args (("-o"
580 "GlobalKnownHostsFile=/dev/null")
581 ("-o" "UserKnownHostsFile=/dev/null")
582 ("-o" "StrictHostKeyChecking=no")))
583 (tramp-default-port 22))
584 ("sshx" (tramp-login-program "ssh")
585 (tramp-login-args (("-l" "%u") ("-p" "%p")
586 ("-e" "none") ("-t" "-t")
587 ("%h") ("/bin/sh")))
588 (tramp-async-args (("-q")))
589 (tramp-remote-sh "/bin/sh")
590 (tramp-copy-program nil)
591 (tramp-copy-args nil)
592 (tramp-copy-keep-date nil)
593 (tramp-password-end-of-line nil)
594 (tramp-gw-args (("-o"
595 "GlobalKnownHostsFile=/dev/null")
596 ("-o" "UserKnownHostsFile=/dev/null")
597 ("-o" "StrictHostKeyChecking=no")))
598 (tramp-default-port 22))
599 ("krlogin"
600 (tramp-login-program "krlogin")
601 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
602 (tramp-remote-sh "/bin/sh")
603 (tramp-copy-program nil)
604 (tramp-copy-args nil)
605 (tramp-copy-keep-date nil)
606 (tramp-password-end-of-line nil))
607 ("plink" (tramp-login-program "plink")
608 (tramp-login-args (("-l" "%u") ("-P" "%p")
609 ("-ssh") ("%h")))
610 (tramp-remote-sh "/bin/sh")
611 (tramp-copy-program nil)
612 (tramp-copy-args nil)
613 (tramp-copy-keep-date nil)
614 (tramp-password-end-of-line "xy") ;see docstring for "xy"
615 (tramp-default-port 22))
616 ("plink1"
617 (tramp-login-program "plink")
618 (tramp-login-args (("-l" "%u") ("-P" "%p")
619 ("-1" "-ssh") ("%h")))
620 (tramp-remote-sh "/bin/sh")
621 (tramp-copy-program nil)
622 (tramp-copy-args nil)
623 (tramp-copy-keep-date nil)
624 (tramp-password-end-of-line "xy") ;see docstring for "xy"
625 (tramp-default-port 22))
626 ("plinkx"
627 (tramp-login-program "plink")
628 ;; ("%h") must be a single element, see
629 ;; `tramp-compute-multi-hops'.
630 (tramp-login-args (("-load") ("%h") ("-t")
631 (,(format
632 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
633 tramp-terminal-type
634 tramp-initial-end-of-output))
635 ("/bin/sh")))
636 (tramp-remote-sh "/bin/sh")
637 (tramp-copy-program nil)
638 (tramp-copy-args nil)
639 (tramp-copy-keep-date nil)
640 (tramp-password-end-of-line nil))
641 ("pscp" (tramp-login-program "plink")
642 (tramp-login-args (("-l" "%u") ("-P" "%p")
643 ("-ssh") ("%h")))
644 (tramp-remote-sh "/bin/sh")
645 (tramp-copy-program "pscp")
646 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")
647 ("-r")))
648 (tramp-copy-keep-date t)
649 (tramp-copy-recursive t)
650 (tramp-password-end-of-line "xy") ;see docstring for "xy"
651 (tramp-default-port 22))
652 ("psftp" (tramp-login-program "plink")
653 (tramp-login-args (("-l" "%u") ("-P" "%p")
654 ("-ssh") ("%h")))
655 (tramp-remote-sh "/bin/sh")
656 (tramp-copy-program "pscp")
657 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")
658 ("-r")))
659 (tramp-copy-keep-date t)
660 (tramp-copy-recursive t)
661 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
662 ("fcp" (tramp-login-program "fsh")
663 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
664 (tramp-remote-sh "/bin/sh -i")
665 (tramp-copy-program "fcp")
666 (tramp-copy-args (("-p" "%k")))
667 (tramp-copy-keep-date t)
668 (tramp-password-end-of-line nil)))
669 "*Alist of methods for remote files.
670 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
671 Each NAME stands for a remote access method. Each PARAM is a
672 pair of the form (KEY VALUE). The following KEYs are defined:
673 * `tramp-remote-sh'
674 This specifies the Bourne shell to use on the remote host. This
675 MUST be a Bourne-like shell. It is normally not necessary to set
676 this to any value other than \"/bin/sh\": Tramp wants to use a shell
677 which groks tilde expansion, but it can search for it. Also note
678 that \"/bin/sh\" exists on all Unixen, this might not be true for
679 the value that you decide to use. You Have Been Warned.
680 * `tramp-login-program'
681 This specifies the name of the program to use for logging in to the
682 remote host. This may be the name of rsh or a workalike program,
683 or the name of telnet or a workalike, or the name of su or a workalike.
684 * `tramp-login-args'
685 This specifies the list of arguments to pass to the above
686 mentioned program. Please note that this is a list of list of arguments,
687 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
688 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
689 There are some patterns: \"%h\" in this list is replaced by the host
690 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
691 port number, and \"%%\" can be used to obtain a literal percent character.
692 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
693 expansion (i.e. no host or no user specified), this list is not used as
694 argument. By this, arguments like (\"-l\" \"%u\") are optional.
695 \"%t\" is replaced by the temporary file name produced with
696 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
697 parameter of a program, if exists.
698 * `tramp-async-args'
699 When an asynchronous process is started, we know already that
700 the connection works. Therefore, we can pass additional
701 parameters to suppress diagnostic messages, in order not to
702 tamper the process output.
703 * `tramp-copy-program'
704 This specifies the name of the program to use for remotely copying
705 the file; this might be the absolute filename of rcp or the name of
706 a workalike program.
707 * `tramp-copy-args'
708 This specifies the list of parameters to pass to the above mentioned
709 program, the hints for `tramp-login-args' also apply here.
710 * `tramp-copy-keep-date'
711 This specifies whether the copying program when the preserves the
712 timestamp of the original file.
713 * `tramp-copy-keep-tmpfile'
714 This specifies whether a temporary local file shall be kept
715 for optimization reasons (useful for \"rsync\" methods).
716 * `tramp-copy-recursive'
717 Whether the operation copies directories recursively.
718 * `tramp-default-port'
719 The default port of a method is needed in case of gateway connections.
720 Additionally, it is used as indication which method is prepared for
721 passing gateways.
722 * `tramp-gw-args'
723 As the attribute name says, additional arguments are specified here
724 when a method is applied via a gateway.
725 * `tramp-password-end-of-line'
726 This specifies the string to use for terminating the line after
727 submitting the password. If this method parameter is nil, then the
728 value of the normal variable `tramp-default-password-end-of-line'
729 is used. This parameter is necessary because the \"plink\" program
730 requires any two characters after sending the password. These do
731 not have to be newline or carriage return characters. Other login
732 programs are happy with just one character, the newline character.
733 We use \"xy\" as the value for methods using \"plink\".
734
735 What does all this mean? Well, you should specify `tramp-login-program'
736 for all methods; this program is used to log in to the remote site. Then,
737 there are two ways to actually transfer the files between the local and the
738 remote side. One way is using an additional rcp-like program. If you want
739 to do this, set `tramp-copy-program' in the method.
740
741 Another possibility for file transfer is inline transfer, i.e. the
742 file is passed through the same buffer used by `tramp-login-program'. In
743 this case, the file contents need to be protected since the
744 `tramp-login-program' might use escape codes or the connection might not
745 be eight-bit clean. Therefore, file contents are encoded for transit.
746 See the variables `tramp-local-coding-commands' and
747 `tramp-remote-coding-commands' for details.
748
749 So, to summarize: if the method is an out-of-band method, then you
750 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
751 inline method, then these two parameters should be nil. Methods which
752 are fit for gateways must have `tramp-default-port' at least.
753
754 Notes:
755
756 When using `su' or `sudo' the phrase `open connection to a remote
757 host' sounds strange, but it is used nevertheless, for consistency.
758 No connection is opened to a remote host, but `su' or `sudo' is
759 started on the local host. You should specify a remote host
760 `localhost' or the name of the local host. Another host name is
761 useful only in combination with `tramp-default-proxies-alist'.")
762
763 (defun tramp-detect-ssh-controlmaster ()
764 "Call ssh to detect whether it supports the ControlMaster argument.
765 This function may return nil when the argument is supported, but
766 shouldn't return t when it isn't."
767 (ignore-errors
768 (with-temp-buffer
769 (call-process "ssh" nil t nil "-o" "ControlMaster")
770 (goto-char (point-min))
771 (search-forward-regexp "Missing ControlMaster argument" nil t))))
772
773 (defcustom tramp-default-method
774 ;; An external copy method seems to be preferred, because it is much
775 ;; more performant for large files, and it hasn't too serious delays
776 ;; for small files. But it must be ensured that there aren't
777 ;; permanent password queries. Either a password agent like
778 ;; "ssh-agent" or "Pageant" shall run, or the optional
779 ;; password-cache.el or auth-sources.el packages shall be active for
780 ;; password caching. "scpc" is chosen if we detect that the user is
781 ;; running OpenSSH 4.0 or newer.
782 (cond
783 ;; PuTTY is installed.
784 ((executable-find "pscp")
785 (if (or (fboundp 'password-read)
786 (fboundp 'auth-source-user-or-password)
787 ;; Pageant is running.
788 (tramp-compat-process-running-p "Pageant"))
789 "pscp"
790 "plink"))
791 ;; There is an ssh installation.
792 ((executable-find "scp")
793 (cond
794 ((tramp-detect-ssh-controlmaster) "scpc")
795 ((or (fboundp 'password-read)
796 (fboundp 'auth-source-user-or-password)
797 ;; ssh-agent is running.
798 (getenv "SSH_AUTH_SOCK")
799 (getenv "SSH_AGENT_PID"))
800 "scp")
801 (t "ssh")))
802 ;; Fallback.
803 (t "ftp"))
804 "*Default method to use for transferring files.
805 See `tramp-methods' for possibilities.
806 Also see `tramp-default-method-alist'."
807 :group 'tramp
808 :type 'string)
809
810 (defcustom tramp-default-method-alist
811 '(("\\`localhost\\'" "\\`root\\'" "su"))
812 "*Default method to use for specific host/user pairs.
813 This is an alist of items (HOST USER METHOD). The first matching item
814 specifies the method to use for a file name which does not specify a
815 method. HOST and USER are regular expressions or nil, which is
816 interpreted as a regular expression which always matches. If no entry
817 matches, the variable `tramp-default-method' takes effect.
818
819 If the file name does not specify the user, lookup is done using the
820 empty string for the user name.
821
822 See `tramp-methods' for a list of possibilities for METHOD."
823 :group 'tramp
824 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
825 (choice :tag "User regexp" regexp sexp)
826 (choice :tag "Method name" string (const nil)))))
827
828 (defcustom tramp-default-user
829 nil
830 "*Default user to use for transferring files.
831 It is nil by default; otherwise settings in configuration files like
832 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
833
834 This variable is regarded as obsolete, and will be removed soon."
835 :group 'tramp
836 :type '(choice (const nil) string))
837
838 (defcustom tramp-default-user-alist
839 `(("\\`su\\(do\\)?\\'" nil "root")
840 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
841 nil ,(user-login-name)))
842 "*Default user to use for specific method/host pairs.
843 This is an alist of items (METHOD HOST USER). The first matching item
844 specifies the user to use for a file name which does not specify a
845 user. METHOD and USER are regular expressions or nil, which is
846 interpreted as a regular expression which always matches. If no entry
847 matches, the variable `tramp-default-user' takes effect.
848
849 If the file name does not specify the method, lookup is done using the
850 empty string for the method name."
851 :group 'tramp
852 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
853 (choice :tag " Host regexp" regexp sexp)
854 (choice :tag " User name" string (const nil)))))
855
856 (defcustom tramp-default-host
857 (system-name)
858 "*Default host to use for transferring files.
859 Useful for su and sudo methods mostly."
860 :group 'tramp
861 :type 'string)
862
863 (defcustom tramp-default-proxies-alist nil
864 "*Route to be followed for specific host/user pairs.
865 This is an alist of items (HOST USER PROXY). The first matching
866 item specifies the proxy to be passed for a file name located on
867 a remote target matching USER@HOST. HOST and USER are regular
868 expressions. PROXY must be a Tramp filename without a localname
869 part. Method and user name on PROXY are optional, which is
870 interpreted with the default values. PROXY can contain the
871 patterns %h and %u, which are replaced by the strings matching
872 HOST or USER, respectively.
873
874 HOST, USER or PROXY could also be Lisp forms, which will be
875 evaluated. The result must be a string or nil, which is
876 interpreted as a regular expression which always matches."
877 :group 'tramp
878 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
879 (choice :tag "User regexp" regexp sexp)
880 (choice :tag " Proxy name" string (const nil)))))
881
882 (defconst tramp-local-host-regexp
883 (concat
884 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
885 "*Host names which are regarded as local host.")
886
887 (defconst tramp-completion-function-alist-rsh
888 '((tramp-parse-rhosts "/etc/hosts.equiv")
889 (tramp-parse-rhosts "~/.rhosts"))
890 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
891
892 (defconst tramp-completion-function-alist-ssh
893 '((tramp-parse-rhosts "/etc/hosts.equiv")
894 (tramp-parse-rhosts "/etc/shosts.equiv")
895 (tramp-parse-shosts "/etc/ssh_known_hosts")
896 (tramp-parse-sconfig "/etc/ssh_config")
897 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
898 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
899 (tramp-parse-rhosts "~/.rhosts")
900 (tramp-parse-rhosts "~/.shosts")
901 (tramp-parse-shosts "~/.ssh/known_hosts")
902 (tramp-parse-sconfig "~/.ssh/config")
903 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
904 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
905 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
906
907 (defconst tramp-completion-function-alist-telnet
908 '((tramp-parse-hosts "/etc/hosts"))
909 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
910
911 (defconst tramp-completion-function-alist-su
912 '((tramp-parse-passwd "/etc/passwd"))
913 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
914
915 (defconst tramp-completion-function-alist-putty
916 '((tramp-parse-putty
917 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
918 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
919
920 (defvar tramp-completion-function-alist nil
921 "*Alist of methods for remote files.
922 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
923 Each NAME stands for a remote access method. Each PAIR is of the form
924 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
925 names from FILE for completion. The following predefined FUNCTIONs exists:
926
927 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
928 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
929 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
930 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
931 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
932 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
933 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
934 * `tramp-parse-netrc' for \"~/.netrc\" like files.
935 * `tramp-parse-putty' for PuTTY registry keys.
936
937 FUNCTION can also be a customer defined function. For more details see
938 the info pages.")
939
940 (eval-after-load "tramp"
941 '(progn
942 (tramp-set-completion-function
943 "rcp" tramp-completion-function-alist-rsh)
944 (tramp-set-completion-function
945 "scp" tramp-completion-function-alist-ssh)
946 (tramp-set-completion-function
947 "scp1" tramp-completion-function-alist-ssh)
948 (tramp-set-completion-function
949 "scp2" tramp-completion-function-alist-ssh)
950 (tramp-set-completion-function
951 "scp1_old" tramp-completion-function-alist-ssh)
952 (tramp-set-completion-function
953 "scp2_old" tramp-completion-function-alist-ssh)
954 (tramp-set-completion-function
955 "rsync" tramp-completion-function-alist-ssh)
956 (tramp-set-completion-function
957 "rsyncc" tramp-completion-function-alist-ssh)
958 (tramp-set-completion-function
959 "remcp" tramp-completion-function-alist-rsh)
960 (tramp-set-completion-function
961 "rsh" tramp-completion-function-alist-rsh)
962 (tramp-set-completion-function
963 "ssh" tramp-completion-function-alist-ssh)
964 (tramp-set-completion-function
965 "ssh1" tramp-completion-function-alist-ssh)
966 (tramp-set-completion-function
967 "ssh2" tramp-completion-function-alist-ssh)
968 (tramp-set-completion-function
969 "ssh1_old" tramp-completion-function-alist-ssh)
970 (tramp-set-completion-function
971 "ssh2_old" tramp-completion-function-alist-ssh)
972 (tramp-set-completion-function
973 "remsh" tramp-completion-function-alist-rsh)
974 (tramp-set-completion-function
975 "telnet" tramp-completion-function-alist-telnet)
976 (tramp-set-completion-function
977 "su" tramp-completion-function-alist-su)
978 (tramp-set-completion-function
979 "sudo" tramp-completion-function-alist-su)
980 (tramp-set-completion-function
981 "scpx" tramp-completion-function-alist-ssh)
982 (tramp-set-completion-function
983 "sshx" tramp-completion-function-alist-ssh)
984 (tramp-set-completion-function
985 "krlogin" tramp-completion-function-alist-rsh)
986 (tramp-set-completion-function
987 "plink" tramp-completion-function-alist-ssh)
988 (tramp-set-completion-function
989 "plink1" tramp-completion-function-alist-ssh)
990 (tramp-set-completion-function
991 "plinkx" tramp-completion-function-alist-putty)
992 (tramp-set-completion-function
993 "pscp" tramp-completion-function-alist-ssh)
994 (tramp-set-completion-function
995 "fcp" tramp-completion-function-alist-ssh)))
996
997 (defconst tramp-echo-mark-marker "_echo"
998 "String marker to surround echoed commands.")
999
1000 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
1001 "String length of `tramp-echo-mark-marker'.")
1002
1003 (defconst tramp-echo-mark
1004 (concat tramp-echo-mark-marker
1005 (make-string tramp-echo-mark-marker-length ?\b))
1006 "String mark to be transmitted around shell commands.
1007 Used to separate their echo from the output they produce. This
1008 will only be used if we cannot disable remote echo via stty.
1009 This string must have no effect on the remote shell except for
1010 producing some echo which can later be detected by
1011 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
1012 followed by an equal number of backspaces to erase them will
1013 usually suffice.")
1014
1015 (defconst tramp-echoed-echo-mark-regexp
1016 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
1017 tramp-echo-mark-marker tramp-echo-mark-marker-length)
1018 "Regexp which matches `tramp-echo-mark' as it gets echoed by
1019 the remote shell.")
1020
1021 (defcustom tramp-rsh-end-of-line "\n"
1022 "*String used for end of line in rsh connections.
1023 I don't think this ever needs to be changed, so please tell me about it
1024 if you need to change this.
1025 Also see the method parameter `tramp-password-end-of-line' and the normal
1026 variable `tramp-default-password-end-of-line'."
1027 :group 'tramp
1028 :type 'string)
1029
1030 (defcustom tramp-default-password-end-of-line
1031 tramp-rsh-end-of-line
1032 "*String used for end of line after sending a password.
1033 This variable provides the default value for the method parameter
1034 `tramp-password-end-of-line', see `tramp-methods' for more details.
1035
1036 It seems that people using plink under Windows need to send
1037 \"\\r\\n\" (carriage-return, then newline) after a password, but just
1038 \"\\n\" after all other lines. This variable can be used for the
1039 password, see `tramp-rsh-end-of-line' for the other cases.
1040
1041 The default value is to use the same value as `tramp-rsh-end-of-line'."
1042 :group 'tramp
1043 :type 'string)
1044
1045 ;; "getconf PATH" yields:
1046 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
1047 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
1048 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1049 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1050 ;; IRIX64: /usr/bin
1051 (defcustom tramp-remote-path
1052 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1053 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1054 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1055 "*List of directories to search for executables on remote host.
1056 For every remote host, this variable will be set buffer local,
1057 keeping the list of existing directories on that host.
1058
1059 You can use `~' in this list, but when searching for a shell which groks
1060 tilde expansion, all directory names starting with `~' will be ignored.
1061
1062 `Default Directories' represent the list of directories given by
1063 the command \"getconf PATH\". It is recommended to use this
1064 entry on top of this list, because these are the default
1065 directories for POSIX compatible commands.
1066
1067 `Private Directories' are the settings of the $PATH environment,
1068 as given in your `~/.profile'."
1069 :group 'tramp
1070 :type '(repeat (choice
1071 (const :tag "Default Directories" tramp-default-remote-path)
1072 (const :tag "Private Directories" tramp-own-remote-path)
1073 (string :tag "Directory"))))
1074
1075 (defcustom tramp-remote-process-environment
1076 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1077 ,(format "TERM=%s" tramp-terminal-type)
1078 "EMACS=t" ;; Deprecated.
1079 ,(format "INSIDE_EMACS='%s,tramp:%s'" emacs-version tramp-version)
1080 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1081 "autocorrect=" "correct=")
1082
1083 "*List of environment variables to be set on the remote host.
1084
1085 Each element should be a string of the form ENVVARNAME=VALUE. An
1086 entry ENVVARNAME= diables the corresponding environment variable,
1087 which might have been set in the init files like ~/.profile.
1088
1089 Special handling is applied to the PATH environment, which should
1090 not be set here. Instead of, it should be set via `tramp-remote-path'."
1091 :group 'tramp
1092 :type '(repeat string))
1093
1094 (defcustom tramp-login-prompt-regexp
1095 ".*ogin\\( .*\\)?: *"
1096 "*Regexp matching login-like prompts.
1097 The regexp should match at end of buffer.
1098
1099 Sometimes the prompt is reported to look like \"login as:\"."
1100 :group 'tramp
1101 :type 'regexp)
1102
1103 (defcustom tramp-shell-prompt-pattern
1104 ;; Allow a prompt to start right after a ^M since it indeed would be
1105 ;; displayed at the beginning of the line (and Zsh uses it). This
1106 ;; regexp works only for GNU Emacs.
1107 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
1108 "[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
1109 "Regexp to match prompts from remote shell.
1110 Normally, Tramp expects you to configure `shell-prompt-pattern'
1111 correctly, but sometimes it happens that you are connecting to a
1112 remote host which sends a different kind of shell prompt. Therefore,
1113 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1114 and also things matched by this variable. The default value of this
1115 variable is similar to the default value of `shell-prompt-pattern',
1116 which should work well in many cases.
1117
1118 This regexp must match both `tramp-initial-end-of-output' and
1119 `tramp-end-of-output'."
1120 :group 'tramp
1121 :type 'regexp)
1122
1123 (defcustom tramp-password-prompt-regexp
1124 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1125 "*Regexp matching password-like prompts.
1126 The regexp should match at end of buffer.
1127
1128 The `sudo' program appears to insert a `^@' character into the prompt."
1129 :group 'tramp
1130 :type 'regexp)
1131
1132 (defcustom tramp-wrong-passwd-regexp
1133 (concat "^.*"
1134 ;; These strings should be on the last line
1135 (regexp-opt '("Permission denied"
1136 "Login incorrect"
1137 "Login Incorrect"
1138 "Connection refused"
1139 "Connection closed"
1140 "Timeout, server not responding."
1141 "Sorry, try again."
1142 "Name or service not known"
1143 "Host key verification failed."
1144 "No supported authentication methods left to try!") t)
1145 ".*"
1146 "\\|"
1147 "^.*\\("
1148 ;; Here comes a list of regexes, separated by \\|
1149 "Received signal [0-9]+"
1150 "\\).*")
1151 "*Regexp matching a `login failed' message.
1152 The regexp should match at end of buffer."
1153 :group 'tramp
1154 :type 'regexp)
1155
1156 (defcustom tramp-yesno-prompt-regexp
1157 (concat
1158 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1159 "\\s-*")
1160 "Regular expression matching all yes/no queries which need to be confirmed.
1161 The confirmation should be done with yes or no.
1162 The regexp should match at end of buffer.
1163 See also `tramp-yn-prompt-regexp'."
1164 :group 'tramp
1165 :type 'regexp)
1166
1167 (defcustom tramp-yn-prompt-regexp
1168 (concat
1169 (regexp-opt '("Store key in cache? (y/n)"
1170 "Update cached key? (y/n, Return cancels connection)") t)
1171 "\\s-*")
1172 "Regular expression matching all y/n queries which need to be confirmed.
1173 The confirmation should be done with y or n.
1174 The regexp should match at end of buffer.
1175 See also `tramp-yesno-prompt-regexp'."
1176 :group 'tramp
1177 :type 'regexp)
1178
1179 (defcustom tramp-terminal-prompt-regexp
1180 (concat "\\("
1181 "TERM = (.*)"
1182 "\\|"
1183 "Terminal type\\? \\[.*\\]"
1184 "\\)\\s-*")
1185 "Regular expression matching all terminal setting prompts.
1186 The regexp should match at end of buffer.
1187 The answer will be provided by `tramp-action-terminal', which see."
1188 :group 'tramp
1189 :type 'regexp)
1190
1191 (defcustom tramp-operation-not-permitted-regexp
1192 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1193 (regexp-opt '("Operation not permitted") t))
1194 "Regular expression matching keep-date problems in (s)cp operations.
1195 Copying has been performed successfully already, so this message can
1196 be ignored safely."
1197 :group 'tramp
1198 :type 'regexp)
1199
1200 (defcustom tramp-copy-failed-regexp
1201 (concat "\\(.+: "
1202 (regexp-opt '("Permission denied"
1203 "not a regular file"
1204 "is a directory"
1205 "No such file or directory") t)
1206 "\\)\\s-*")
1207 "Regular expression matching copy problems in (s)cp operations."
1208 :group 'tramp
1209 :type 'regexp)
1210
1211 (defcustom tramp-process-alive-regexp
1212 ""
1213 "Regular expression indicating a process has finished.
1214 In fact this expression is empty by intention, it will be used only to
1215 check regularly the status of the associated process.
1216 The answer will be provided by `tramp-action-process-alive',
1217 `tramp-action-out-of-band', which see."
1218 :group 'tramp
1219 :type 'regexp)
1220
1221 (defcustom tramp-temp-name-prefix "tramp."
1222 "*Prefix to use for temporary files.
1223 If this is a relative file name (such as \"tramp.\"), it is considered
1224 relative to the directory name returned by the function
1225 `tramp-compat-temporary-file-directory' (which see). It may also be an
1226 absolute file name; don't forget to include a prefix for the filename
1227 part, though."
1228 :group 'tramp
1229 :type 'string)
1230
1231 (defconst tramp-temp-buffer-name " *tramp temp*"
1232 "Buffer name for a temporary buffer.
1233 It shall be used in combination with `generate-new-buffer-name'.")
1234
1235 (defvar tramp-temp-buffer-file-name nil
1236 "File name of a persistent local temporary file.
1237 Useful for \"rsync\" like methods.")
1238 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1239
1240 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1241 "*Alist specifying extra arguments to pass to the remote shell.
1242 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1243 matching the shell file name and ARGS is a string specifying the
1244 arguments.
1245
1246 This variable is only used when Tramp needs to start up another shell
1247 for tilde expansion. The extra arguments should typically prevent the
1248 shell from reading its init file."
1249 :group 'tramp
1250 ;; This might be the wrong way to test whether the widget type
1251 ;; `alist' is available. Who knows the right way to test it?
1252 :type (if (get 'alist 'widget-type)
1253 '(alist :key-type string :value-type string)
1254 '(repeat (cons string string))))
1255
1256 ;; XEmacs is distributed with few Lisp packages. Further packages are
1257 ;; installed using EFS. If we use a unified filename format, then
1258 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1259 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1260 ;; just like before.) Another reason for using a separate filename
1261 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1262 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1263 ;; the other places.
1264
1265 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1266 ;;;###autoload
1267 (defcustom tramp-syntax
1268 (if (featurep 'xemacs) 'sep 'ftp)
1269 "Tramp filename syntax to be used.
1270
1271 It can have the following values:
1272
1273 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1274 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1275 'url -- URL-like syntax."
1276 :group 'tramp
1277 :type (if (featurep 'xemacs)
1278 '(choice (const :tag "EFS" ftp)
1279 (const :tag "XEmacs" sep)
1280 (const :tag "URL" url))
1281 '(choice (const :tag "Ange-FTP" ftp)
1282 (const :tag "URL" url))))
1283
1284 (defconst tramp-prefix-format
1285 (cond ((equal tramp-syntax 'ftp) "/")
1286 ((equal tramp-syntax 'sep) "/[")
1287 ((equal tramp-syntax 'url) "/")
1288 (t (error "Wrong `tramp-syntax' defined")))
1289 "*String matching the very beginning of Tramp file names.
1290 Used in `tramp-make-tramp-file-name'.")
1291
1292 (defconst tramp-prefix-regexp
1293 (concat "^" (regexp-quote tramp-prefix-format))
1294 "*Regexp matching the very beginning of Tramp file names.
1295 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1296
1297 (defconst tramp-method-regexp
1298 "[a-zA-Z_0-9-]+"
1299 "*Regexp matching methods identifiers.")
1300
1301 (defconst tramp-postfix-method-format
1302 (cond ((equal tramp-syntax 'ftp) ":")
1303 ((equal tramp-syntax 'sep) "/")
1304 ((equal tramp-syntax 'url) "://")
1305 (t (error "Wrong `tramp-syntax' defined")))
1306 "*String matching delimeter between method and user or host names.
1307 Used in `tramp-make-tramp-file-name'.")
1308
1309 (defconst tramp-postfix-method-regexp
1310 (regexp-quote tramp-postfix-method-format)
1311 "*Regexp matching delimeter between method and user or host names.
1312 Derived from `tramp-postfix-method-format'.")
1313
1314 (defconst tramp-user-regexp
1315 "[^:/ \t]+"
1316 "*Regexp matching user names.")
1317
1318 (defconst tramp-prefix-domain-format "%"
1319 "*String matching delimeter between user and domain names.")
1320
1321 (defconst tramp-prefix-domain-regexp
1322 (regexp-quote tramp-prefix-domain-format)
1323 "*Regexp matching delimeter between user and domain names.
1324 Derived from `tramp-prefix-domain-format'.")
1325
1326 (defconst tramp-domain-regexp
1327 "[-a-zA-Z0-9_.]+"
1328 "*Regexp matching domain names.")
1329
1330 (defconst tramp-user-with-domain-regexp
1331 (concat "\\(" tramp-user-regexp "\\)"
1332 tramp-prefix-domain-regexp
1333 "\\(" tramp-domain-regexp "\\)")
1334 "*Regexp matching user names with domain names.")
1335
1336 (defconst tramp-postfix-user-format
1337 "@"
1338 "*String matching delimeter between user and host names.
1339 Used in `tramp-make-tramp-file-name'.")
1340
1341 (defconst tramp-postfix-user-regexp
1342 (regexp-quote tramp-postfix-user-format)
1343 "*Regexp matching delimeter between user and host names.
1344 Derived from `tramp-postfix-user-format'.")
1345
1346 (defconst tramp-host-regexp
1347 "[a-zA-Z0-9_.-]+"
1348 "*Regexp matching host names.")
1349
1350 (defconst tramp-prefix-ipv6-format
1351 (cond ((equal tramp-syntax 'ftp) "[")
1352 ((equal tramp-syntax 'sep) "")
1353 ((equal tramp-syntax 'url) "[")
1354 (t (error "Wrong `tramp-syntax' defined")))
1355 "*String matching left hand side of IPv6 addresses.
1356 Used in `tramp-make-tramp-file-name'.")
1357
1358 (defconst tramp-prefix-ipv6-regexp
1359 (regexp-quote tramp-prefix-ipv6-format)
1360 "*Regexp matching left hand side of IPv6 addresses.
1361 Derived from `tramp-prefix-ipv6-format'.")
1362
1363 ;; The following regexp is a bit sloppy. But it shall serve our
1364 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1365 ;; "::ffff:192.168.0.1".
1366 (defconst tramp-ipv6-regexp
1367 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1368 "*Regexp matching IPv6 addresses.")
1369
1370 (defconst tramp-postfix-ipv6-format
1371 (cond ((equal tramp-syntax 'ftp) "]")
1372 ((equal tramp-syntax 'sep) "")
1373 ((equal tramp-syntax 'url) "]")
1374 (t (error "Wrong `tramp-syntax' defined")))
1375 "*String matching right hand side of IPv6 addresses.
1376 Used in `tramp-make-tramp-file-name'.")
1377
1378 (defconst tramp-postfix-ipv6-regexp
1379 (regexp-quote tramp-postfix-ipv6-format)
1380 "*Regexp matching right hand side of IPv6 addresses.
1381 Derived from `tramp-postfix-ipv6-format'.")
1382
1383 (defconst tramp-prefix-port-format
1384 (cond ((equal tramp-syntax 'ftp) "#")
1385 ((equal tramp-syntax 'sep) "#")
1386 ((equal tramp-syntax 'url) ":")
1387 (t (error "Wrong `tramp-syntax' defined")))
1388 "*String matching delimeter between host names and port numbers.")
1389
1390 (defconst tramp-prefix-port-regexp
1391 (regexp-quote tramp-prefix-port-format)
1392 "*Regexp matching delimeter between host names and port numbers.
1393 Derived from `tramp-prefix-port-format'.")
1394
1395 (defconst tramp-port-regexp
1396 "[0-9]+"
1397 "*Regexp matching port numbers.")
1398
1399 (defconst tramp-host-with-port-regexp
1400 (concat "\\(" tramp-host-regexp "\\)"
1401 tramp-prefix-port-regexp
1402 "\\(" tramp-port-regexp "\\)")
1403 "*Regexp matching host names with port numbers.")
1404
1405 (defconst tramp-postfix-host-format
1406 (cond ((equal tramp-syntax 'ftp) ":")
1407 ((equal tramp-syntax 'sep) "]")
1408 ((equal tramp-syntax 'url) "")
1409 (t (error "Wrong `tramp-syntax' defined")))
1410 "*String matching delimeter between host names and localnames.
1411 Used in `tramp-make-tramp-file-name'.")
1412
1413 (defconst tramp-postfix-host-regexp
1414 (regexp-quote tramp-postfix-host-format)
1415 "*Regexp matching delimeter between host names and localnames.
1416 Derived from `tramp-postfix-host-format'.")
1417
1418 (defconst tramp-localname-regexp
1419 ".*$"
1420 "*Regexp matching localnames.")
1421
1422 ;; File name format.
1423
1424 (defconst tramp-file-name-structure
1425 (list
1426 (concat
1427 tramp-prefix-regexp
1428 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1429 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1430 "\\(" "\\(" tramp-host-regexp
1431 "\\|"
1432 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1433 tramp-postfix-ipv6-regexp "\\)"
1434 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1435 tramp-postfix-host-regexp
1436 "\\(" tramp-localname-regexp "\\)")
1437 2 4 5 8)
1438
1439 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1440 the Tramp file name structure.
1441
1442 The first element REGEXP is a regular expression matching a Tramp file
1443 name. The regex should contain parentheses around the method name,
1444 the user name, the host name, and the file name parts.
1445
1446 The second element METHOD is a number, saying which pair of
1447 parentheses matches the method name. The third element USER is
1448 similar, but for the user name. The fourth element HOST is similar,
1449 but for the host name. The fifth element FILE is for the file name.
1450 These numbers are passed directly to `match-string', which see. That
1451 means the opening parentheses are counted to identify the pair.
1452
1453 See also `tramp-file-name-regexp'.")
1454
1455 ;;;###autoload
1456 (defconst tramp-file-name-regexp-unified
1457 (if (memq system-type '(cygwin windows-nt))
1458 "\\`/\\([^[/:]\\{2,\\}\\|[^/]\\{2,\\}]\\):"
1459 "\\`/\\([^[/:]+\\|[^/]+]\\):")
1460 "Value for `tramp-file-name-regexp' for unified remoting.
1461 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1462 Tramp. See `tramp-file-name-structure' for more explanations.
1463
1464 On W32 systems, the volume letter must be ignored.")
1465
1466 ;;;###autoload
1467 (defconst tramp-file-name-regexp-separate
1468 "\\`/\\[.*\\]"
1469 "Value for `tramp-file-name-regexp' for separate remoting.
1470 XEmacs uses a separate filename syntax for Tramp and EFS.
1471 See `tramp-file-name-structure' for more explanations.")
1472
1473 ;;;###autoload
1474 (defconst tramp-file-name-regexp-url
1475 "\\`/[^/:]+://"
1476 "Value for `tramp-file-name-regexp' for URL-like remoting.
1477 See `tramp-file-name-structure' for more explanations.")
1478
1479 ;;;###autoload
1480 (defconst tramp-file-name-regexp
1481 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1482 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1483 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1484 (t (error "Wrong `tramp-syntax' defined")))
1485 "*Regular expression matching file names handled by Tramp.
1486 This regexp should match Tramp file names but no other file names.
1487 When tramp.el is loaded, this regular expression is prepended to
1488 `file-name-handler-alist', and that is searched sequentially. Thus,
1489 if the Tramp entry appears rather early in the `file-name-handler-alist'
1490 and is a bit too general, then some files might be considered Tramp
1491 files which are not really Tramp files.
1492
1493 Please note that the entry in `file-name-handler-alist' is made when
1494 this file \(tramp.el\) is loaded. This means that this variable must be set
1495 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1496 updated after changing this variable.
1497
1498 Also see `tramp-file-name-structure'.")
1499
1500 ;;;###autoload
1501 (defconst tramp-root-regexp
1502 (if (memq system-type '(cygwin windows-nt))
1503 "\\`\\([a-zA-Z]:\\)?/"
1504 "\\`/")
1505 "Beginning of an incomplete Tramp file name.
1506 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1507 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1508
1509 ;;;###autoload
1510 (defconst tramp-completion-file-name-regexp-unified
1511 (if (memq system-type '(cygwin windows-nt))
1512 (concat tramp-root-regexp "[^/]\\{2,\\}\\'")
1513 (concat tramp-root-regexp "[^/]*\\'"))
1514 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1515 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1516 See `tramp-file-name-structure' for more explanations.
1517
1518 On W32 systems, the volume letter must be ignored.")
1519
1520 ;;;###autoload
1521 (defconst tramp-completion-file-name-regexp-separate
1522 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1523 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1524 XEmacs uses a separate filename syntax for Tramp and EFS.
1525 See `tramp-file-name-structure' for more explanations.")
1526
1527 ;;;###autoload
1528 (defconst tramp-completion-file-name-regexp-url
1529 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1530 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1531 See `tramp-file-name-structure' for more explanations.")
1532
1533 ;;;###autoload
1534 (defconst tramp-completion-file-name-regexp
1535 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1536 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1537 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1538 (t (error "Wrong `tramp-syntax' defined")))
1539 "*Regular expression matching file names handled by Tramp completion.
1540 This regexp should match partial Tramp file names only.
1541
1542 Please note that the entry in `file-name-handler-alist' is made when
1543 this file (tramp.el) is loaded. This means that this variable must be set
1544 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1545 updated after changing this variable.
1546
1547 Also see `tramp-file-name-structure'.")
1548
1549 (defconst tramp-actions-before-shell
1550 '((tramp-login-prompt-regexp tramp-action-login)
1551 (tramp-password-prompt-regexp tramp-action-password)
1552 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1553 (shell-prompt-pattern tramp-action-succeed)
1554 (tramp-shell-prompt-pattern tramp-action-succeed)
1555 (tramp-yesno-prompt-regexp tramp-action-yesno)
1556 (tramp-yn-prompt-regexp tramp-action-yn)
1557 (tramp-terminal-prompt-regexp tramp-action-terminal)
1558 (tramp-process-alive-regexp tramp-action-process-alive))
1559 "List of pattern/action pairs.
1560 Whenever a pattern matches, the corresponding action is performed.
1561 Each item looks like (PATTERN ACTION).
1562
1563 The PATTERN should be a symbol, a variable. The value of this
1564 variable gives the regular expression to search for. Note that the
1565 regexp must match at the end of the buffer, \"\\'\" is implicitly
1566 appended to it.
1567
1568 The ACTION should also be a symbol, but a function. When the
1569 corresponding PATTERN matches, the ACTION function is called.")
1570
1571 (defconst tramp-actions-copy-out-of-band
1572 '((tramp-password-prompt-regexp tramp-action-password)
1573 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1574 (tramp-copy-failed-regexp tramp-action-permission-denied)
1575 (tramp-process-alive-regexp tramp-action-out-of-band))
1576 "List of pattern/action pairs.
1577 This list is used for copying/renaming with out-of-band methods.
1578
1579 See `tramp-actions-before-shell' for more info.")
1580
1581 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1582 ;; known to have a bug in `process-send-string'; some ssh connections appear
1583 ;; to drop bytes when data is sent too quickly. There is also a connection
1584 ;; buffer local variable, which is computed depending on remote host properties
1585 ;; when `tramp-chunksize' is zero or nil.
1586 (defcustom tramp-chunksize
1587 (when (and (not (featurep 'xemacs))
1588 (memq system-type '(hpux)))
1589 500)
1590 ;; Parentheses in docstring starting at beginning of line are escaped.
1591 ;; Fontification is messed up when
1592 ;; `open-paren-in-column-0-is-defun-start' set to t.
1593 "*If non-nil, chunksize for sending input to local process.
1594 It is necessary only on systems which have a buggy `process-send-string'
1595 implementation. The necessity, whether this variable must be set, can be
1596 checked via the following code:
1597
1598 (with-temp-buffer
1599 (let* ((user \"xxx\") (host \"yyy\")
1600 (init 0) (step 50)
1601 (sent init) (received init))
1602 (while (= sent received)
1603 (setq sent (+ sent step))
1604 (erase-buffer)
1605 (let ((proc (start-process (buffer-name) (current-buffer)
1606 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1607 (when (memq (process-status proc) '(run open))
1608 (process-send-string proc (make-string sent ?\\ ))
1609 (process-send-eof proc)
1610 (process-send-eof proc))
1611 (while (not (progn (goto-char (point-min))
1612 (re-search-forward \"\\\\w+\" (point-max) t)))
1613 (accept-process-output proc 1))
1614 (when (memq (process-status proc) '(run open))
1615 (setq received (string-to-number (match-string 0)))
1616 (delete-process proc)
1617 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1618 (sit-for 0))))
1619 (if (> sent (+ init step))
1620 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1621 (- sent step))
1622 (message \"Test does not work\")
1623 (display-buffer (current-buffer))
1624 (sit-for 30))))
1625
1626 In the Emacs normally running Tramp, evaluate the above code
1627 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1628 respectively\). You can do this, for example, by pasting it into
1629 the `*scratch*' buffer and then hitting C-j with the cursor after the
1630 last closing parenthesis. Note that it works only if you have configured
1631 \"ssh\" to run without password query, see ssh-agent\(1\).
1632
1633 You will see the number of bytes sent successfully to the remote host.
1634 If that number exceeds 1000, you can stop the execution by hitting
1635 C-g, because your Emacs is likely clean.
1636
1637 When it is necessary to set `tramp-chunksize', you might consider to
1638 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
1639 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
1640 performance.
1641
1642 If your Emacs is buggy, the code stops and gives you an indication
1643 about the value `tramp-chunksize' should be set. Maybe you could just
1644 experiment a bit, e.g. changing the values of `init' and `step'
1645 in the third line of the code.
1646
1647 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1648 this variable to be set as well."
1649 :group 'tramp
1650 :type '(choice (const nil) integer))
1651
1652 ;; Logging in to a remote host normally requires obtaining a pty. But
1653 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1654 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1655 ;; for an override of the system default.
1656 (defcustom tramp-process-connection-type t
1657 "Overrides `process-connection-type' for connections from Tramp.
1658 Tramp binds process-connection-type to the value given here before
1659 opening a connection to a remote host."
1660 :group 'tramp
1661 :type '(choice (const nil) (const t) (const pty)))
1662
1663 (defcustom tramp-completion-reread-directory-timeout 10
1664 "Defines seconds since last remote command before rereading a directory.
1665 A remote directory might have changed its contents. In order to
1666 make it visible during file name completion in the minibuffer,
1667 Tramp flushes its cache and rereads the directory contents when
1668 more than `tramp-completion-reread-directory-timeout' seconds
1669 have been gone since last remote command execution. A value of 0
1670 would require an immediate reread during filename completion, nil
1671 means to use always cached values for the directory contents."
1672 :group 'tramp
1673 :type '(choice (const nil) integer))
1674
1675 ;;; Internal Variables:
1676
1677 (defvar tramp-current-method nil
1678 "Connection method for this *tramp* buffer.")
1679
1680 (defvar tramp-current-user nil
1681 "Remote login name for this *tramp* buffer.")
1682
1683 (defvar tramp-current-host nil
1684 "Remote host for this *tramp* buffer.")
1685
1686 (defconst tramp-uudecode
1687 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1688 cat /tmp/tramp.$$
1689 rm -f /tmp/tramp.$$"
1690 "Shell function to implement `uudecode' to standard output.
1691 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1692 for this or `uudecode -p', but some systems don't, and for them
1693 we have this shell function.")
1694
1695 (defconst tramp-perl-file-truename
1696 "%s -e '
1697 use File::Spec;
1698 use Cwd \"realpath\";
1699
1700 sub recursive {
1701 my ($volume, @dirs) = @_;
1702 my $real = realpath(File::Spec->catpath(
1703 $volume, File::Spec->catdir(@dirs), \"\"));
1704 if ($real) {
1705 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1706 return ($vol, File::Spec->splitdir($dir));
1707 }
1708 else {
1709 my $last = pop(@dirs);
1710 ($volume, @dirs) = recursive($volume, @dirs);
1711 push(@dirs, $last);
1712 return ($volume, @dirs);
1713 }
1714 }
1715
1716 $result = realpath($ARGV[0]);
1717 if (!$result) {
1718 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1719 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1720
1721 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1722 }
1723
1724 if ($ARGV[0] =~ /\\/$/) {
1725 $result = $result . \"/\";
1726 }
1727
1728 print \"\\\"$result\\\"\\n\";
1729 ' \"$1\" 2>/dev/null"
1730 "Perl script to produce output suitable for use with `file-truename'
1731 on the remote file system.
1732 Escape sequence %s is replaced with name of Perl binary.
1733 This string is passed to `format', so percent characters need to be doubled.")
1734
1735 (defconst tramp-perl-file-name-all-completions
1736 "%s -e 'sub case {
1737 my $str = shift;
1738 if ($ARGV[2]) {
1739 return lc($str);
1740 }
1741 else {
1742 return $str;
1743 }
1744 }
1745 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1746 @files = readdir(d); closedir(d);
1747 foreach $f (@files) {
1748 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1749 if (-d \"$ARGV[0]/$f\") {
1750 print \"$f/\\n\";
1751 }
1752 else {
1753 print \"$f\\n\";
1754 }
1755 }
1756 }
1757 print \"ok\\n\"
1758 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1759 "Perl script to produce output suitable for use with
1760 `file-name-all-completions' on the remote file system. Escape
1761 sequence %s is replaced with name of Perl binary. This string is
1762 passed to `format', so percent characters need to be doubled.")
1763
1764 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1765 ;; output. If you are hacking on this, note that you get *no* output
1766 ;; unless this spits out a complete line, including the '\n' at the
1767 ;; end.
1768 ;; The device number is returned as "-1", because there will be a virtual
1769 ;; device number set in `tramp-handle-file-attributes'.
1770 (defconst tramp-perl-file-attributes
1771 "%s -e '
1772 @stat = lstat($ARGV[0]);
1773 if (!@stat) {
1774 print \"nil\\n\";
1775 exit 0;
1776 }
1777 if (($stat[2] & 0170000) == 0120000)
1778 {
1779 $type = readlink($ARGV[0]);
1780 $type = \"\\\"$type\\\"\";
1781 }
1782 elsif (($stat[2] & 0170000) == 040000)
1783 {
1784 $type = \"t\";
1785 }
1786 else
1787 {
1788 $type = \"nil\"
1789 };
1790 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1791 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1792 printf(
1793 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1794 $type,
1795 $stat[3],
1796 $uid,
1797 $gid,
1798 $stat[8] >> 16 & 0xffff,
1799 $stat[8] & 0xffff,
1800 $stat[9] >> 16 & 0xffff,
1801 $stat[9] & 0xffff,
1802 $stat[10] >> 16 & 0xffff,
1803 $stat[10] & 0xffff,
1804 $stat[7],
1805 $stat[2],
1806 $stat[1] >> 16 & 0xffff,
1807 $stat[1] & 0xffff
1808 );' \"$1\" \"$2\" 2>/dev/null"
1809 "Perl script to produce output suitable for use with `file-attributes'
1810 on the remote file system.
1811 Escape sequence %s is replaced with name of Perl binary.
1812 This string is passed to `format', so percent characters need to be doubled.")
1813
1814 (defconst tramp-perl-directory-files-and-attributes
1815 "%s -e '
1816 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1817 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1818 @list = readdir(DIR);
1819 closedir(DIR);
1820 $n = scalar(@list);
1821 printf(\"(\\n\");
1822 for($i = 0; $i < $n; $i++)
1823 {
1824 $filename = $list[$i];
1825 @stat = lstat($filename);
1826 if (($stat[2] & 0170000) == 0120000)
1827 {
1828 $type = readlink($filename);
1829 $type = \"\\\"$type\\\"\";
1830 }
1831 elsif (($stat[2] & 0170000) == 040000)
1832 {
1833 $type = \"t\";
1834 }
1835 else
1836 {
1837 $type = \"nil\"
1838 };
1839 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1840 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1841 printf(
1842 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1843 $filename,
1844 $type,
1845 $stat[3],
1846 $uid,
1847 $gid,
1848 $stat[8] >> 16 & 0xffff,
1849 $stat[8] & 0xffff,
1850 $stat[9] >> 16 & 0xffff,
1851 $stat[9] & 0xffff,
1852 $stat[10] >> 16 & 0xffff,
1853 $stat[10] & 0xffff,
1854 $stat[7],
1855 $stat[2],
1856 $stat[1] >> 16 & 0xffff,
1857 $stat[1] & 0xffff,
1858 $stat[0] >> 16 & 0xffff,
1859 $stat[0] & 0xffff);
1860 }
1861 printf(\")\\n\");' \"$1\" \"$2\" 2>/dev/null"
1862 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1863 output.
1864 Escape sequence %s is replaced with name of Perl binary.
1865 This string is passed to `format', so percent characters need to be doubled.")
1866
1867 ;; ;; These two use uu encoding.
1868 ;; (defvar tramp-perl-encode "%s -e'\
1869 ;; print qq(begin 644 xxx\n);
1870 ;; my $s = q();
1871 ;; my $res = q();
1872 ;; while (read(STDIN, $s, 45)) {
1873 ;; print pack(q(u), $s);
1874 ;; }
1875 ;; print qq(`\n);
1876 ;; print qq(end\n);
1877 ;; '"
1878 ;; "Perl program to use for encoding a file.
1879 ;; Escape sequence %s is replaced with name of Perl binary.")
1880
1881 ;; (defvar tramp-perl-decode "%s -ne '
1882 ;; print unpack q(u), $_;
1883 ;; '"
1884 ;; "Perl program to use for decoding a file.
1885 ;; Escape sequence %s is replaced with name of Perl binary.")
1886
1887 ;; These two use base64 encoding.
1888 (defconst tramp-perl-encode-with-module
1889 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1890 "Perl program to use for encoding a file.
1891 Escape sequence %s is replaced with name of Perl binary.
1892 This string is passed to `format', so percent characters need to be doubled.
1893 This implementation requires the MIME::Base64 Perl module to be installed
1894 on the remote host.")
1895
1896 (defconst tramp-perl-decode-with-module
1897 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1898 "Perl program to use for decoding a file.
1899 Escape sequence %s is replaced with name of Perl binary.
1900 This string is passed to `format', so percent characters need to be doubled.
1901 This implementation requires the MIME::Base64 Perl module to be installed
1902 on the remote host.")
1903
1904 (defconst tramp-perl-encode
1905 "%s -e '
1906 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1907 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
1908 # Free Software Foundation, Inc.
1909 use strict;
1910
1911 my %%trans = do {
1912 my $i = 0;
1913 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1914 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1915 };
1916
1917 binmode(\\*STDIN);
1918
1919 # We read in chunks of 54 bytes, to generate output lines
1920 # of 72 chars (plus end of line)
1921 $/ = \\54;
1922
1923 while (my $data = <STDIN>) {
1924 my $pad = q();
1925
1926 # Only for the last chunk, and only if did not fill the last three-byte packet
1927 if (eof) {
1928 my $mod = length($data) %% 3;
1929 $pad = q(=) x (3 - $mod) if $mod;
1930 }
1931
1932 # Not the fastest method, but it is simple: unpack to binary string, split
1933 # by groups of 6 bits and convert back from binary to byte; then map into
1934 # the translation table
1935 print
1936 join q(),
1937 map($trans{$_},
1938 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1939 $pad,
1940 qq(\\n);
1941 }' 2>/dev/null"
1942 "Perl program to use for encoding a file.
1943 Escape sequence %s is replaced with name of Perl binary.
1944 This string is passed to `format', so percent characters need to be doubled.")
1945
1946 (defconst tramp-perl-decode
1947 "%s -e '
1948 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1949 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
1950 # Free Software Foundation, Inc.
1951 use strict;
1952
1953 my %%trans = do {
1954 my $i = 0;
1955 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1956 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1957 };
1958
1959 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1960
1961 binmode(\\*STDOUT);
1962
1963 # We are going to accumulate into $pending to accept any line length
1964 # (we do not check they are <= 76 chars as the RFC says)
1965 my $pending = q();
1966
1967 while (my $data = <STDIN>) {
1968 chomp $data;
1969
1970 # If we find one or two =, we have reached the end and
1971 # any following data is to be discarded
1972 my $finished = $data =~ s/(==?).*/$1/;
1973 $pending .= $data;
1974
1975 my $len = length($pending);
1976 my $chunk = substr($pending, 0, $len & ~3);
1977 $pending = substr($pending, $len & ~3 + 1);
1978
1979 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1980 # split in 8-bit chunks and convert back to char.
1981 print join q(),
1982 map $bytes{$_},
1983 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1984
1985 last if $finished;
1986 }' 2>/dev/null"
1987 "Perl program to use for decoding a file.
1988 Escape sequence %s is replaced with name of Perl binary.
1989 This string is passed to `format', so percent characters need to be doubled.")
1990
1991 (defconst tramp-vc-registered-read-file-names
1992 "echo \"(\"
1993 while read file; do
1994 if %s \"$file\"; then
1995 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1996 else
1997 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1998 fi
1999 if %s \"$file\"; then
2000 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
2001 else
2002 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
2003 fi
2004 done
2005 echo \")\""
2006 "Script to check existence of VC related files.
2007 It must be send formatted with two strings; the tests for file
2008 existence, and file readability. Input shall be read via
2009 here-document, otherwise the command could exceed maximum length
2010 of command line.")
2011
2012 (defconst tramp-file-mode-type-map
2013 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
2014 (1 . "p") ; fifo
2015 (2 . "c") ; character device
2016 (3 . "m") ; multiplexed character device (v7)
2017 (4 . "d") ; directory
2018 (5 . "?") ; Named special file (XENIX)
2019 (6 . "b") ; block device
2020 (7 . "?") ; multiplexed block device (v7)
2021 (8 . "-") ; regular file
2022 (9 . "n") ; network special file (HP-UX)
2023 (10 . "l") ; symlink
2024 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
2025 (12 . "s") ; socket
2026 (13 . "D") ; door special (Solaris)
2027 (14 . "w")) ; whiteout (BSD)
2028 "A list of file types returned from the `stat' system call.
2029 This is used to map a mode number to a permission string.")
2030
2031 ;; New handlers should be added here. The following operations can be
2032 ;; handled using the normal primitives: file-name-sans-versions,
2033 ;; get-file-buffer.
2034 (defconst tramp-file-name-handler-alist
2035 '((load . tramp-handle-load)
2036 (make-symbolic-link . tramp-handle-make-symbolic-link)
2037 (file-name-as-directory . tramp-handle-file-name-as-directory)
2038 (file-name-directory . tramp-handle-file-name-directory)
2039 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
2040 (file-truename . tramp-handle-file-truename)
2041 (file-exists-p . tramp-handle-file-exists-p)
2042 (file-directory-p . tramp-handle-file-directory-p)
2043 (file-executable-p . tramp-handle-file-executable-p)
2044 (file-readable-p . tramp-handle-file-readable-p)
2045 (file-regular-p . tramp-handle-file-regular-p)
2046 (file-symlink-p . tramp-handle-file-symlink-p)
2047 (file-writable-p . tramp-handle-file-writable-p)
2048 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
2049 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
2050 (file-attributes . tramp-handle-file-attributes)
2051 (file-modes . tramp-handle-file-modes)
2052 (directory-files . tramp-handle-directory-files)
2053 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
2054 (file-name-all-completions . tramp-handle-file-name-all-completions)
2055 (file-name-completion . tramp-handle-file-name-completion)
2056 (add-name-to-file . tramp-handle-add-name-to-file)
2057 (copy-file . tramp-handle-copy-file)
2058 (copy-directory . tramp-handle-copy-directory)
2059 (rename-file . tramp-handle-rename-file)
2060 (set-file-modes . tramp-handle-set-file-modes)
2061 (set-file-times . tramp-handle-set-file-times)
2062 (make-directory . tramp-handle-make-directory)
2063 (delete-directory . tramp-handle-delete-directory)
2064 (delete-file . tramp-handle-delete-file)
2065 (directory-file-name . tramp-handle-directory-file-name)
2066 ;; `executable-find' is not official yet.
2067 (executable-find . tramp-handle-executable-find)
2068 (start-file-process . tramp-handle-start-file-process)
2069 (process-file . tramp-handle-process-file)
2070 (shell-command . tramp-handle-shell-command)
2071 (insert-directory . tramp-handle-insert-directory)
2072 (expand-file-name . tramp-handle-expand-file-name)
2073 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2074 (file-local-copy . tramp-handle-file-local-copy)
2075 (file-remote-p . tramp-handle-file-remote-p)
2076 (insert-file-contents . tramp-handle-insert-file-contents)
2077 (insert-file-contents-literally
2078 . tramp-handle-insert-file-contents-literally)
2079 (write-region . tramp-handle-write-region)
2080 (find-backup-file-name . tramp-handle-find-backup-file-name)
2081 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2082 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2083 (dired-compress-file . tramp-handle-dired-compress-file)
2084 (dired-recursive-delete-directory
2085 . tramp-handle-dired-recursive-delete-directory)
2086 (dired-uncache . tramp-handle-dired-uncache)
2087 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2088 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2089 (file-selinux-context . tramp-handle-file-selinux-context)
2090 (set-file-selinux-context . tramp-handle-set-file-selinux-context)
2091 (vc-registered . tramp-handle-vc-registered))
2092 "Alist of handler functions.
2093 Operations not mentioned here will be handled by the normal Emacs functions.")
2094
2095 ;; Handlers for partial Tramp file names. For Emacs just
2096 ;; `file-name-all-completions' is needed.
2097 ;;;###autoload
2098 (defconst tramp-completion-file-name-handler-alist
2099 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2100 (file-name-completion . tramp-completion-handle-file-name-completion))
2101 "Alist of completion handler functions.
2102 Used for file names matching `tramp-file-name-regexp'. Operations not
2103 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2104 normal Emacs functions.")
2105
2106 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2107 (defvar tramp-foreign-file-name-handler-alist
2108 ;; (identity . tramp-sh-file-name-handler) should always be the last
2109 ;; entry, because `identity' always matches.
2110 '((identity . tramp-sh-file-name-handler))
2111 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2112 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2113 calling HANDLER.")
2114
2115 ;;; Internal functions which must come first:
2116
2117 (defsubst tramp-debug-message (vec fmt-string &rest args)
2118 "Append message to debug buffer.
2119 Message is formatted with FMT-STRING as control string and the remaining
2120 ARGS to actually emit the message (if applicable)."
2121 (when (get-buffer (tramp-buffer-name vec))
2122 (with-current-buffer (tramp-get-debug-buffer vec)
2123 (goto-char (point-max))
2124 ;; Headline.
2125 (when (bobp)
2126 (insert
2127 (format
2128 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2129 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2130 emacs-version tramp-version)))
2131 (unless (bolp)
2132 (insert "\n"))
2133 ;; Timestamp.
2134 (let ((now (current-time)))
2135 (insert (format-time-string "%T." now))
2136 (insert (format "%06d " (nth 2 now))))
2137 ;; Calling function.
2138 (let ((btn 1) btf fn)
2139 (while (not fn)
2140 (setq btf (nth 1 (backtrace-frame btn)))
2141 (if (not btf)
2142 (setq fn "")
2143 (when (symbolp btf)
2144 (setq fn (symbol-name btf))
2145 (unless (and (string-match "^tramp" fn)
2146 (not (string-match
2147 "^tramp\\(-debug\\)?\\(-message\\|-error\\|-compat-funcall\\)$"
2148 fn)))
2149 (setq fn nil)))
2150 (setq btn (1+ btn))))
2151 ;; The following code inserts filename and line number.
2152 ;; Should be deactivated by default, because it is time
2153 ;; consuming.
2154 ; (let ((ffn (find-function-noselect (intern fn))))
2155 ; (insert
2156 ; (format
2157 ; "%s:%d: "
2158 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2159 ; (with-current-buffer (car ffn)
2160 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2161 (insert (format "%s " fn)))
2162 ;; The message.
2163 (insert (apply 'format fmt-string args)))))
2164
2165 (defvar tramp-message-show-message t
2166 "Show Tramp message in the minibuffer.
2167 This variable is used to disable messages from `tramp-error'.
2168 The messages are visible anyway, because an error is raised.")
2169
2170 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2171 "Emit a message depending on verbosity level.
2172 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2173 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2174 less than LEVEL. The message is emitted only if `tramp-verbose' is
2175 greater than or equal to LEVEL.
2176
2177 The message is also logged into the debug buffer when `tramp-verbose'
2178 is greater than or equal 4.
2179
2180 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2181 control string and the remaining ARGS to actually emit the message (if
2182 applicable)."
2183 (condition-case nil
2184 (when (<= level tramp-verbose)
2185 ;; Match data must be preserved!
2186 (save-match-data
2187 ;; Display only when there is a minimum level.
2188 (when (and tramp-message-show-message (<= level 3))
2189 (apply 'message
2190 (concat
2191 (cond
2192 ((= level 0) "")
2193 ((= level 1) "")
2194 ((= level 2) "Warning: ")
2195 (t "Tramp: "))
2196 fmt-string)
2197 args))
2198 ;; Log only when there is a minimum level.
2199 (when (>= tramp-verbose 4)
2200 (when (and vec-or-proc
2201 (processp vec-or-proc)
2202 (buffer-name (process-buffer vec-or-proc)))
2203 (with-current-buffer (process-buffer vec-or-proc)
2204 ;; Translate proc to vec.
2205 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2206 (when (and vec-or-proc (vectorp vec-or-proc))
2207 (apply 'tramp-debug-message
2208 vec-or-proc
2209 (concat (format "(%d) # " level) fmt-string)
2210 args)))))
2211 ;; Suppress all errors.
2212 (error nil)))
2213
2214 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2215 "Emit an error.
2216 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2217 signal identifier to be raised, remaining args passed to
2218 `tramp-message'. Finally, signal SIGNAL is raised."
2219 (let (tramp-message-show-message)
2220 (tramp-message
2221 vec-or-proc 1 "%s"
2222 (error-message-string
2223 (list signal
2224 (get signal 'error-message)
2225 (apply 'format fmt-string args))))
2226 (signal signal (list (apply 'format fmt-string args)))))
2227
2228 (defsubst tramp-error-with-buffer
2229 (buffer vec-or-proc signal fmt-string &rest args)
2230 "Emit an error, and show BUFFER.
2231 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2232 an input event arrives. The other arguments are passed to `tramp-error'."
2233 (save-window-excursion
2234 (unwind-protect
2235 (apply 'tramp-error vec-or-proc signal fmt-string args)
2236 (when (and vec-or-proc
2237 (not (zerop tramp-verbose))
2238 (not (tramp-completion-mode-p)))
2239 (let ((enable-recursive-minibuffers t))
2240 (pop-to-buffer
2241 (or (and (bufferp buffer) buffer)
2242 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2243 (tramp-get-buffer vec-or-proc)))
2244 (sit-for 30))))))
2245
2246 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2247 "Parse a Tramp filename and make components available in the body.
2248
2249 First arg FILENAME is evaluated and dissected into its components.
2250 Second arg VAR is a symbol. It is used as a variable name to hold
2251 the filename structure. It is also used as a prefix for the variables
2252 holding the components. For example, if VAR is the symbol `foo', then
2253 `foo' will be bound to the whole structure, `foo-method' will be bound to
2254 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2255
2256 Remaining args are Lisp expressions to be evaluated (inside an implicit
2257 `progn').
2258
2259 If VAR is nil, then we bind `v' to the structure and `method', `user',
2260 `host', `localname' to the components."
2261 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2262 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2263 (tramp-file-name-method ,(or var 'v)))
2264 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2265 (tramp-file-name-user ,(or var 'v)))
2266 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2267 (tramp-file-name-host ,(or var 'v)))
2268 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2269 (tramp-file-name-localname ,(or var 'v))))
2270 ,@body))
2271
2272 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2273 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2274 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2275
2276 (defmacro with-file-property (vec file property &rest body)
2277 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2278 FILE must be a local file name on a connection identified via VEC."
2279 `(if (file-name-absolute-p ,file)
2280 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2281 (when (eq value 'undef)
2282 ;; We cannot pass @body as parameter to
2283 ;; `tramp-set-file-property' because it mangles our
2284 ;; debug messages.
2285 (setq value (progn ,@body))
2286 (tramp-set-file-property ,vec ,file ,property value))
2287 value)
2288 ,@body))
2289
2290 (put 'with-file-property 'lisp-indent-function 3)
2291 (put 'with-file-property 'edebug-form-spec t)
2292 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2293
2294 (defmacro with-connection-property (key property &rest body)
2295 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
2296 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2297 (when (eq value 'undef)
2298 ;; We cannot pass ,@body as parameter to
2299 ;; `tramp-set-connection-property' because it mangles our debug
2300 ;; messages.
2301 (setq value (progn ,@body))
2302 (tramp-set-connection-property ,key ,property value))
2303 value))
2304
2305 (put 'with-connection-property 'lisp-indent-function 2)
2306 (put 'with-connection-property 'edebug-form-spec t)
2307 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2308
2309 (defun tramp-progress-reporter-update (reporter &optional value)
2310 (let* ((parameters (cdr reporter))
2311 (message (aref parameters 3)))
2312 (when (string-match message (or (current-message) ""))
2313 (funcall 'progress-reporter-update reporter value))))
2314
2315 (defmacro with-progress-reporter (vec level message &rest body)
2316 "Executes BODY, spinning a progress reporter with MESSAGE.
2317 If LEVEL does not fit for visible messages, or if this is a
2318 nested call of the macro, there are only traces without a visible
2319 progress reporter."
2320 `(let (pr tm)
2321 (tramp-message ,vec ,level "%s..." ,message)
2322 ;; We start a pulsing progress reporter after 3 seconds. Feature
2323 ;; introduced in Emacs 24.1.
2324 (when (and tramp-message-show-message
2325 ;; Display only when there is a minimum level.
2326 (<= ,level (min tramp-verbose 3)))
2327 (condition-case nil
2328 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
2329 tm (when pr
2330 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))
2331 (error nil)))
2332 (unwind-protect
2333 ;; Execute the body. Unset `tramp-message-show-message' when
2334 ;; the timer object is created, in order to suppress
2335 ;; concurrent timers.
2336 (let ((tramp-message-show-message
2337 (and tramp-message-show-message (not tm))))
2338 ,@body)
2339 ;; Stop progress reporter.
2340 (if tm (tramp-compat-funcall 'cancel-timer tm))
2341 (tramp-message ,vec ,level "%s...done" ,message))))
2342
2343 (put 'with-progress-reporter 'lisp-indent-function 3)
2344 (put 'with-progress-reporter 'edebug-form-spec t)
2345 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-progress-reporter\\>"))
2346
2347 (eval-and-compile ;; Silence compiler.
2348 (if (memq system-type '(cygwin windows-nt))
2349 (defun tramp-drop-volume-letter (name)
2350 "Cut off unnecessary drive letter from file NAME.
2351 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2352 locally on a remote file name. When the local system is a W32 system
2353 but the remote system is Unix, this introduces a superfluous drive
2354 letter into the file name. This function removes it."
2355 (save-match-data
2356 (if (string-match tramp-root-regexp name)
2357 (replace-match "/" nil t name)
2358 name)))
2359
2360 (defalias 'tramp-drop-volume-letter 'identity)))
2361
2362 (defsubst tramp-make-tramp-temp-file (vec)
2363 "Create a temporary file on the remote host identified by VEC.
2364 Return the local name of the temporary file."
2365 (let ((prefix
2366 (tramp-make-tramp-file-name
2367 (tramp-file-name-method vec)
2368 (tramp-file-name-user vec)
2369 (tramp-file-name-host vec)
2370 (tramp-drop-volume-letter
2371 (expand-file-name
2372 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2373 result)
2374 (while (not result)
2375 ;; `make-temp-file' would be the natural choice for
2376 ;; implementation. But it calls `write-region' internally,
2377 ;; which also needs a temporary file - we would end in an
2378 ;; infinite loop.
2379 (setq result (make-temp-name prefix))
2380 (if (file-exists-p result)
2381 (setq result nil)
2382 ;; This creates the file by side effect.
2383 (set-file-times result)
2384 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2385
2386 ;; Return the local part.
2387 (with-parsed-tramp-file-name result nil localname)))
2388
2389
2390 ;;; Config Manipulation Functions:
2391
2392 (defun tramp-set-completion-function (method function-list)
2393 "Sets the list of completion functions for METHOD.
2394 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2395 The FUNCTION is intended to parse FILE according its syntax.
2396 It might be a predefined FUNCTION, or a user defined FUNCTION.
2397 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2398 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2399 and `tramp-parse-netrc'.
2400
2401 Example:
2402
2403 (tramp-set-completion-function
2404 \"ssh\"
2405 '((tramp-parse-sconfig \"/etc/ssh_config\")
2406 (tramp-parse-sconfig \"~/.ssh/config\")))"
2407
2408 (let ((r function-list)
2409 (v function-list))
2410 (setq tramp-completion-function-alist
2411 (delete (assoc method tramp-completion-function-alist)
2412 tramp-completion-function-alist))
2413
2414 (while v
2415 ;; Remove double entries.
2416 (when (member (car v) (cdr v))
2417 (setcdr v (delete (car v) (cdr v))))
2418 ;; Check for function and file or registry key.
2419 (unless (and (functionp (nth 0 (car v)))
2420 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2421 ;; Windows registry.
2422 (and (memq system-type '(cygwin windows-nt))
2423 (zerop
2424 (tramp-local-call-process
2425 "reg" nil nil nil "query" (nth 1 (car v)))))
2426 ;; Configuration file.
2427 (file-exists-p (nth 1 (car v)))))
2428 (setq r (delete (car v) r)))
2429 (setq v (cdr v)))
2430
2431 (when r
2432 (add-to-list 'tramp-completion-function-alist
2433 (cons method r)))))
2434
2435 (defun tramp-get-completion-function (method)
2436 "Returns a list of completion functions for METHOD.
2437 For definition of that list see `tramp-set-completion-function'."
2438 (cons
2439 ;; Hosts visited once shall be remembered.
2440 `(tramp-parse-connection-properties ,method)
2441 ;; The method related defaults.
2442 (cdr (assoc method tramp-completion-function-alist))))
2443
2444
2445 ;;; Fontification of `read-file-name':
2446
2447 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2448 (defvar tramp-rfn-eshadow-overlay)
2449 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2450
2451 (defun tramp-rfn-eshadow-setup-minibuffer ()
2452 "Set up a minibuffer for `file-name-shadow-mode'.
2453 Adds another overlay hiding filename parts according to Tramp's
2454 special handling of `substitute-in-file-name'."
2455 (when (symbol-value 'minibuffer-completing-file-name)
2456 (setq tramp-rfn-eshadow-overlay
2457 (tramp-compat-funcall
2458 'make-overlay
2459 (tramp-compat-funcall 'minibuffer-prompt-end)
2460 (tramp-compat-funcall 'minibuffer-prompt-end)))
2461 ;; Copy rfn-eshadow-overlay properties.
2462 (let ((props (tramp-compat-funcall
2463 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
2464 (while props
2465 (tramp-compat-funcall
2466 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2467
2468 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2469 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2470 'tramp-rfn-eshadow-setup-minibuffer)
2471 (add-hook 'tramp-unload-hook
2472 (lambda ()
2473 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2474 'tramp-rfn-eshadow-setup-minibuffer))))
2475
2476 (defconst tramp-rfn-eshadow-update-overlay-regexp
2477 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2478
2479 (defun tramp-rfn-eshadow-update-overlay ()
2480 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2481 This is intended to be used as a minibuffer `post-command-hook' for
2482 `file-name-shadow-mode'; the minibuffer should have already
2483 been set up by `rfn-eshadow-setup-minibuffer'."
2484 ;; In remote files name, there is a shadowing just for the local part.
2485 (let ((end (or (tramp-compat-funcall
2486 'overlay-end (symbol-value 'rfn-eshadow-overlay))
2487 (tramp-compat-funcall 'minibuffer-prompt-end))))
2488 (when
2489 (file-remote-p
2490 (tramp-compat-funcall 'buffer-substring-no-properties end (point-max)))
2491 (save-excursion
2492 (save-restriction
2493 (narrow-to-region
2494 (1+ (or (string-match
2495 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2496 end))
2497 (point-max))
2498 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2499 (rfn-eshadow-update-overlay-hook nil))
2500 (tramp-compat-funcall
2501 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
2502 (tramp-compat-funcall 'rfn-eshadow-update-overlay)))))))
2503
2504 (when (boundp 'rfn-eshadow-update-overlay-hook)
2505 (add-hook 'rfn-eshadow-update-overlay-hook
2506 'tramp-rfn-eshadow-update-overlay)
2507 (add-hook 'tramp-unload-hook
2508 (lambda ()
2509 (remove-hook 'rfn-eshadow-update-overlay-hook
2510 'tramp-rfn-eshadow-update-overlay))))
2511
2512
2513 ;;; Integration of eshell.el:
2514
2515 (eval-when-compile
2516 (defvar eshell-path-env))
2517
2518 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2519 ;; when `default-directory' points to another host.
2520 (defun tramp-eshell-directory-change ()
2521 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2522 (setq eshell-path-env
2523 (if (file-remote-p default-directory)
2524 (with-parsed-tramp-file-name default-directory nil
2525 (mapconcat
2526 'identity
2527 (tramp-get-remote-path v)
2528 ":"))
2529 (getenv "PATH"))))
2530
2531 (eval-after-load "esh-util"
2532 '(progn
2533 (tramp-eshell-directory-change)
2534 (add-hook 'eshell-directory-change-hook
2535 'tramp-eshell-directory-change)
2536 (add-hook 'tramp-unload-hook
2537 (lambda ()
2538 (remove-hook 'eshell-directory-change-hook
2539 'tramp-eshell-directory-change)))))
2540
2541
2542 ;;; File Name Handler Functions:
2543
2544 (defun tramp-handle-make-symbolic-link
2545 (filename linkname &optional ok-if-already-exists)
2546 "Like `make-symbolic-link' for Tramp files.
2547 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2548 the symlink. If LINKNAME is a Tramp file, only the localname component is
2549 used as the target of the symlink.
2550
2551 If LINKNAME is a Tramp file and the localname component is relative, then
2552 it is expanded first, before the localname component is taken. Note that
2553 this can give surprising results if the user/host for the source and
2554 target of the symlink differ."
2555 (with-parsed-tramp-file-name linkname l
2556 (let ((ln (tramp-get-remote-ln l))
2557 (cwd (tramp-run-real-handler
2558 'file-name-directory (list l-localname))))
2559 (unless ln
2560 (tramp-error
2561 l 'file-error
2562 "Making a symbolic link. ln(1) does not exist on the remote host."))
2563
2564 ;; Do the 'confirm if exists' thing.
2565 (when (file-exists-p linkname)
2566 ;; What to do?
2567 (if (or (null ok-if-already-exists) ; not allowed to exist
2568 (and (numberp ok-if-already-exists)
2569 (not (yes-or-no-p
2570 (format
2571 "File %s already exists; make it a link anyway? "
2572 l-localname)))))
2573 (tramp-error
2574 l 'file-already-exists "File %s already exists" l-localname)
2575 (delete-file linkname)))
2576
2577 ;; If FILENAME is a Tramp name, use just the localname component.
2578 (when (tramp-tramp-file-p filename)
2579 (setq filename
2580 (tramp-file-name-localname
2581 (tramp-dissect-file-name (expand-file-name filename)))))
2582
2583 (tramp-flush-file-property l (file-name-directory l-localname))
2584 (tramp-flush-file-property l l-localname)
2585
2586 ;; Right, they are on the same host, regardless of user, method, etc.
2587 ;; We now make the link on the remote machine. This will occur as the user
2588 ;; that FILENAME belongs to.
2589 (zerop
2590 (tramp-send-command-and-check
2591 l
2592 (format
2593 "cd %s && %s -sf %s %s"
2594 (tramp-shell-quote-argument cwd)
2595 ln
2596 (tramp-shell-quote-argument filename)
2597 (tramp-shell-quote-argument l-localname))
2598 t)))))
2599
2600 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2601 "Like `load' for Tramp files."
2602 (with-parsed-tramp-file-name (expand-file-name file) nil
2603 (unless nosuffix
2604 (cond ((file-exists-p (concat file ".elc"))
2605 (setq file (concat file ".elc")))
2606 ((file-exists-p (concat file ".el"))
2607 (setq file (concat file ".el")))))
2608 (when must-suffix
2609 ;; The first condition is always true for absolute file names.
2610 ;; Included for safety's sake.
2611 (unless (or (file-name-directory file)
2612 (string-match "\\.elc?\\'" file))
2613 (tramp-error
2614 v 'file-error
2615 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2616 (unless noerror
2617 (when (not (file-exists-p file))
2618 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2619 (if (not (file-exists-p file))
2620 nil
2621 (let ((tramp-message-show-message (not nomessage)))
2622 (with-progress-reporter v 0 (format "Loading %s" file)
2623 (let ((local-copy (file-local-copy file)))
2624 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2625 (unwind-protect
2626 (load local-copy noerror t t)
2627 (delete-file local-copy)))))
2628 t)))
2629
2630 ;; Localname manipulation functions that grok Tramp localnames...
2631 (defun tramp-handle-file-name-as-directory (file)
2632 "Like `file-name-as-directory' but aware of Tramp files."
2633 ;; `file-name-as-directory' would be sufficient except localname is
2634 ;; the empty string.
2635 (let ((v (tramp-dissect-file-name file t)))
2636 ;; Run the command on the localname portion only.
2637 (tramp-make-tramp-file-name
2638 (tramp-file-name-method v)
2639 (tramp-file-name-user v)
2640 (tramp-file-name-host v)
2641 (tramp-run-real-handler
2642 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2643
2644 (defun tramp-handle-file-name-directory (file)
2645 "Like `file-name-directory' but aware of Tramp files."
2646 ;; Everything except the last filename thing is the directory. We
2647 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2648 ;; the remote file name parts. This is a problem when we are in
2649 ;; file name completion.
2650 (let ((v (tramp-dissect-file-name file t)))
2651 ;; Run the command on the localname portion only.
2652 (tramp-make-tramp-file-name
2653 (tramp-file-name-method v)
2654 (tramp-file-name-user v)
2655 (tramp-file-name-host v)
2656 (tramp-run-real-handler
2657 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2658
2659 (defun tramp-handle-file-name-nondirectory (file)
2660 "Like `file-name-nondirectory' but aware of Tramp files."
2661 (with-parsed-tramp-file-name file nil
2662 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2663
2664 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2665 "Like `file-truename' for Tramp files."
2666 (with-parsed-tramp-file-name (expand-file-name filename) nil
2667 (with-file-property v localname "file-truename"
2668 (let ((result nil)) ; result steps in reverse order
2669 (tramp-message v 4 "Finding true name for `%s'" filename)
2670 (cond
2671 ;; Use GNU readlink --canonicalize-missing where available.
2672 ((tramp-get-remote-readlink v)
2673 (setq result
2674 (tramp-send-command-and-read
2675 v
2676 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2677 (tramp-get-remote-readlink v)
2678 (tramp-shell-quote-argument localname)))))
2679
2680 ;; Use Perl implementation.
2681 ((and (tramp-get-remote-perl v)
2682 (tramp-get-connection-property v "perl-file-spec" nil)
2683 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2684 (tramp-maybe-send-script
2685 v tramp-perl-file-truename "tramp_perl_file_truename")
2686 (setq result
2687 (tramp-send-command-and-read
2688 v
2689 (format "tramp_perl_file_truename %s"
2690 (tramp-shell-quote-argument localname)))))
2691
2692 ;; Do it yourself. We bind `directory-sep-char' here for
2693 ;; XEmacs on Windows, which would otherwise use backslash.
2694 (t (let* ((directory-sep-char ?/)
2695 (steps (tramp-compat-split-string localname "/"))
2696 (localnamedir (tramp-run-real-handler
2697 'file-name-as-directory (list localname)))
2698 (is-dir (string= localname localnamedir))
2699 (thisstep nil)
2700 (numchase 0)
2701 ;; Don't make the following value larger than
2702 ;; necessary. People expect an error message in a
2703 ;; timely fashion when something is wrong;
2704 ;; otherwise they might think that Emacs is hung.
2705 ;; Of course, correctness has to come first.
2706 (numchase-limit 20)
2707 symlink-target)
2708 (while (and steps (< numchase numchase-limit))
2709 (setq thisstep (pop steps))
2710 (tramp-message
2711 v 5 "Check %s"
2712 (mapconcat 'identity
2713 (append '("") (reverse result) (list thisstep))
2714 "/"))
2715 (setq symlink-target
2716 (nth 0 (file-attributes
2717 (tramp-make-tramp-file-name
2718 method user host
2719 (mapconcat 'identity
2720 (append '("")
2721 (reverse result)
2722 (list thisstep))
2723 "/")))))
2724 (cond ((string= "." thisstep)
2725 (tramp-message v 5 "Ignoring step `.'"))
2726 ((string= ".." thisstep)
2727 (tramp-message v 5 "Processing step `..'")
2728 (pop result))
2729 ((stringp symlink-target)
2730 ;; It's a symlink, follow it.
2731 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2732 (setq numchase (1+ numchase))
2733 (when (file-name-absolute-p symlink-target)
2734 (setq result nil))
2735 ;; If the symlink was absolute, we'll get a string like
2736 ;; "/user@host:/some/target"; extract the
2737 ;; "/some/target" part from it.
2738 (when (tramp-tramp-file-p symlink-target)
2739 (unless (tramp-equal-remote filename symlink-target)
2740 (tramp-error
2741 v 'file-error
2742 "Symlink target `%s' on wrong host" symlink-target))
2743 (setq symlink-target localname))
2744 (setq steps
2745 (append (tramp-compat-split-string
2746 symlink-target "/")
2747 steps)))
2748 (t
2749 ;; It's a file.
2750 (setq result (cons thisstep result)))))
2751 (when (>= numchase numchase-limit)
2752 (tramp-error
2753 v 'file-error
2754 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2755 (setq result (reverse result))
2756 ;; Combine list to form string.
2757 (setq result
2758 (if result
2759 (mapconcat 'identity (cons "" result) "/")
2760 "/"))
2761 (when (and is-dir (or (string= "" result)
2762 (not (string= (substring result -1) "/"))))
2763 (setq result (concat result "/"))))))
2764
2765 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2766 (tramp-make-tramp-file-name method user host result)))))
2767
2768 ;; Basic functions.
2769
2770 (defun tramp-handle-file-exists-p (filename)
2771 "Like `file-exists-p' for Tramp files."
2772 (with-parsed-tramp-file-name filename nil
2773 (with-file-property v localname "file-exists-p"
2774 (or (not (null (tramp-get-file-property
2775 v localname "file-attributes-integer" nil)))
2776 (not (null (tramp-get-file-property
2777 v localname "file-attributes-string" nil)))
2778 (zerop (tramp-send-command-and-check
2779 v
2780 (format
2781 "%s %s"
2782 (tramp-get-file-exists-command v)
2783 (tramp-shell-quote-argument localname))))))))
2784
2785 ;; Inodes don't exist for some file systems. Therefore we must
2786 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2787 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2788 ;; performance isn't the major issue given that file transfer will
2789 ;; take time.
2790 (defvar tramp-inodes nil
2791 "Keeps virtual inodes numbers.")
2792
2793 ;; Devices must distinguish physical file systems. The device numbers
2794 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2795 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2796 ;; EFS use device number "-1". In order to be different, we use device number
2797 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2798 (defvar tramp-devices nil
2799 "Keeps virtual device numbers.")
2800
2801 ;; CCC: This should check for an error condition and signal failure
2802 ;; when something goes wrong.
2803 ;; Daniel Pittman <daniel@danann.net>
2804 (defun tramp-handle-file-attributes (filename &optional id-format)
2805 "Like `file-attributes' for Tramp files."
2806 (unless id-format (setq id-format 'integer))
2807 ;; Don't modify `last-coding-system-used' by accident.
2808 (let ((last-coding-system-used last-coding-system-used))
2809 (with-parsed-tramp-file-name (expand-file-name filename) nil
2810 (with-file-property v localname (format "file-attributes-%s" id-format)
2811 (save-excursion
2812 (tramp-convert-file-attributes
2813 v
2814 (cond
2815 ((tramp-get-remote-stat v)
2816 (tramp-do-file-attributes-with-stat v localname id-format))
2817 ((tramp-get-remote-perl v)
2818 (tramp-do-file-attributes-with-perl v localname id-format))
2819 (t
2820 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2821
2822 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2823 "Implement `file-attributes' for Tramp files using the ls(1) command."
2824 (let (symlinkp dirp
2825 res-inode res-filemodes res-numlinks
2826 res-uid res-gid res-size res-symlink-target)
2827 (tramp-message vec 5 "file attributes with ls: %s" localname)
2828 (tramp-send-command
2829 vec
2830 (format "(%s %s || %s -h %s) && %s %s %s"
2831 (tramp-get-file-exists-command vec)
2832 (tramp-shell-quote-argument localname)
2833 (tramp-get-test-command vec)
2834 (tramp-shell-quote-argument localname)
2835 (tramp-get-ls-command vec)
2836 (if (eq id-format 'integer) "-ildn" "-ild")
2837 (tramp-shell-quote-argument localname)))
2838 ;; parse `ls -l' output ...
2839 (with-current-buffer (tramp-get-buffer vec)
2840 (when (> (buffer-size) 0)
2841 (goto-char (point-min))
2842 ;; ... inode
2843 (setq res-inode
2844 (condition-case err
2845 (read (current-buffer))
2846 (invalid-read-syntax
2847 (when (and (equal (cadr err)
2848 "Integer constant overflow in reader")
2849 (string-match
2850 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2851 (car (cddr err))))
2852 (let* ((big (read (substring (car (cddr err)) 0
2853 (match-beginning 1))))
2854 (small (read (match-string 1 (car (cddr err)))))
2855 (twiddle (/ small 65536)))
2856 (cons (+ big twiddle)
2857 (- small (* twiddle 65536))))))))
2858 ;; ... file mode flags
2859 (setq res-filemodes (symbol-name (read (current-buffer))))
2860 ;; ... number links
2861 (setq res-numlinks (read (current-buffer)))
2862 ;; ... uid and gid
2863 (setq res-uid (read (current-buffer)))
2864 (setq res-gid (read (current-buffer)))
2865 (if (eq id-format 'integer)
2866 (progn
2867 (unless (numberp res-uid) (setq res-uid -1))
2868 (unless (numberp res-gid) (setq res-gid -1)))
2869 (progn
2870 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2871 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2872 ;; ... size
2873 (setq res-size (read (current-buffer)))
2874 ;; From the file modes, figure out other stuff.
2875 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2876 (setq dirp (eq ?d (aref res-filemodes 0)))
2877 ;; if symlink, find out file name pointed to
2878 (when symlinkp
2879 (search-forward "-> ")
2880 (setq res-symlink-target
2881 (buffer-substring (point) (tramp-compat-line-end-position))))
2882 ;; return data gathered
2883 (list
2884 ;; 0. t for directory, string (name linked to) for symbolic
2885 ;; link, or nil.
2886 (or dirp res-symlink-target)
2887 ;; 1. Number of links to file.
2888 res-numlinks
2889 ;; 2. File uid.
2890 res-uid
2891 ;; 3. File gid.
2892 res-gid
2893 ;; 4. Last access time, as a list of two integers. First
2894 ;; integer has high-order 16 bits of time, second has low 16
2895 ;; bits.
2896 ;; 5. Last modification time, likewise.
2897 ;; 6. Last status change time, likewise.
2898 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2899 ;; 7. Size in bytes (-1, if number is out of range).
2900 res-size
2901 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2902 res-filemodes
2903 ;; 9. t if file's gid would change if file were deleted and
2904 ;; recreated. Will be set in `tramp-convert-file-attributes'
2905 t
2906 ;; 10. inode number.
2907 res-inode
2908 ;; 11. Device number. Will be replaced by a virtual device number.
2909 -1
2910 )))))
2911
2912 (defun tramp-do-file-attributes-with-perl
2913 (vec localname &optional id-format)
2914 "Implement `file-attributes' for Tramp files using a Perl script."
2915 (tramp-message vec 5 "file attributes with perl: %s" localname)
2916 (tramp-maybe-send-script
2917 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2918 (tramp-send-command-and-read
2919 vec
2920 (format "tramp_perl_file_attributes %s %s"
2921 (tramp-shell-quote-argument localname) id-format)))
2922
2923 (defun tramp-do-file-attributes-with-stat
2924 (vec localname &optional id-format)
2925 "Implement `file-attributes' for Tramp files using stat(1) command."
2926 (tramp-message vec 5 "file attributes with stat: %s" localname)
2927 (tramp-send-command-and-read
2928 vec
2929 (format
2930 ;; On Opsware, pdksh (which is the true name of ksh there) doesn't
2931 ;; parse correctly the sequence "((". Therefore, we add a space.
2932 "( (%s %s || %s -h %s) && %s -c '( (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)' %s || echo nil)"
2933 (tramp-get-file-exists-command vec)
2934 (tramp-shell-quote-argument localname)
2935 (tramp-get-test-command vec)
2936 (tramp-shell-quote-argument localname)
2937 (tramp-get-remote-stat vec)
2938 (if (eq id-format 'integer) "%u" "\"%U\"")
2939 (if (eq id-format 'integer) "%g" "\"%G\"")
2940 (tramp-shell-quote-argument localname))))
2941
2942 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2943 "Like `set-visited-file-modtime' for Tramp files."
2944 (unless (buffer-file-name)
2945 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2946 (buffer-name)))
2947 (if time-list
2948 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2949 (let ((f (buffer-file-name))
2950 coding-system-used)
2951 (with-parsed-tramp-file-name f nil
2952 (let* ((attr (file-attributes f))
2953 ;; '(-1 65535) means file doesn't exists yet.
2954 (modtime (or (nth 5 attr) '(-1 65535))))
2955 (when (boundp 'last-coding-system-used)
2956 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2957 ;; We use '(0 0) as a don't-know value. See also
2958 ;; `tramp-do-file-attributes-with-ls'.
2959 (if (not (equal modtime '(0 0)))
2960 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2961 (progn
2962 (tramp-send-command
2963 v
2964 (format "%s -ild %s"
2965 (tramp-get-ls-command v)
2966 (tramp-shell-quote-argument localname)))
2967 (setq attr (buffer-substring (point)
2968 (progn (end-of-line) (point)))))
2969 (tramp-set-file-property
2970 v localname "visited-file-modtime-ild" attr))
2971 (when (boundp 'last-coding-system-used)
2972 (set 'last-coding-system-used coding-system-used))
2973 nil)))))
2974
2975 ;; This function makes the same assumption as
2976 ;; `tramp-handle-set-visited-file-modtime'.
2977 (defun tramp-handle-verify-visited-file-modtime (buf)
2978 "Like `verify-visited-file-modtime' for Tramp files.
2979 At the time `verify-visited-file-modtime' calls this function, we
2980 already know that the buffer is visiting a file and that
2981 `visited-file-modtime' does not return 0. Do not call this
2982 function directly, unless those two cases are already taken care
2983 of."
2984 (with-current-buffer buf
2985 (let ((f (buffer-file-name)))
2986 ;; There is no file visiting the buffer, or the buffer has no
2987 ;; recorded last modification time, or there is no established
2988 ;; connection.
2989 (if (or (not f)
2990 (eq (visited-file-modtime) 0)
2991 (not (tramp-file-name-handler 'file-remote-p f nil 'connected)))
2992 t
2993 (with-parsed-tramp-file-name f nil
2994 (tramp-flush-file-property v localname)
2995 (let* ((attr (file-attributes f))
2996 (modtime (nth 5 attr))
2997 (mt (visited-file-modtime)))
2998
2999 (cond
3000 ;; File exists, and has a known modtime.
3001 ((and attr (not (equal modtime '(0 0))))
3002 (< (abs (tramp-time-diff
3003 modtime
3004 ;; For compatibility, deal with both the old
3005 ;; (HIGH . LOW) and the new (HIGH LOW) return
3006 ;; values of `visited-file-modtime'.
3007 (if (atom (cdr mt))
3008 (list (car mt) (cdr mt))
3009 mt)))
3010 2))
3011 ;; Modtime has the don't know value.
3012 (attr
3013 (tramp-send-command
3014 v
3015 (format "%s -ild %s"
3016 (tramp-get-ls-command v)
3017 (tramp-shell-quote-argument localname)))
3018 (with-current-buffer (tramp-get-buffer v)
3019 (setq attr (buffer-substring
3020 (point) (progn (end-of-line) (point)))))
3021 (equal
3022 attr
3023 (tramp-get-file-property
3024 v localname "visited-file-modtime-ild" "")))
3025 ;; If file does not exist, say it is not modified if and
3026 ;; only if that agrees with the buffer's record.
3027 (t (equal mt '(-1 65535))))))))))
3028
3029 (defun tramp-handle-set-file-modes (filename mode)
3030 "Like `set-file-modes' for Tramp files."
3031 (with-parsed-tramp-file-name filename nil
3032 (tramp-flush-file-property v localname)
3033 (unless (zerop (tramp-send-command-and-check
3034 v
3035 (format "chmod %s %s"
3036 (tramp-decimal-to-octal mode)
3037 (tramp-shell-quote-argument localname))))
3038 ;; FIXME: extract the proper text from chmod's stderr.
3039 (tramp-error
3040 v 'file-error "Error while changing file's mode %s" filename))))
3041
3042 (defun tramp-handle-set-file-times (filename &optional time)
3043 "Like `set-file-times' for Tramp files."
3044 (zerop
3045 (if (file-remote-p filename)
3046 (with-parsed-tramp-file-name filename nil
3047 (tramp-flush-file-property v localname)
3048 (let ((time (if (or (null time) (equal time '(0 0)))
3049 (current-time)
3050 time))
3051 ;; With GNU Emacs, `format-time-string' has an optional
3052 ;; parameter UNIVERSAL. This is preferred, because we
3053 ;; could handle the case when the remote host is
3054 ;; located in a different time zone as the local host.
3055 (utc (not (featurep 'xemacs))))
3056 (tramp-send-command-and-check
3057 v (format "%s touch -t %s %s"
3058 (if utc "TZ=UTC; export TZ;" "")
3059 (if utc
3060 (format-time-string "%Y%m%d%H%M.%S" time t)
3061 (format-time-string "%Y%m%d%H%M.%S" time))
3062 (tramp-shell-quote-argument localname)))))
3063
3064 ;; We handle also the local part, because in older Emacsen,
3065 ;; without `set-file-times', this function is an alias for this.
3066 ;; We are local, so we don't need the UTC settings.
3067 (tramp-local-call-process
3068 "touch" nil nil nil "-t"
3069 (format-time-string "%Y%m%d%H%M.%S" time)
3070 (tramp-shell-quote-argument filename)))))
3071
3072 (defun tramp-set-file-uid-gid (filename &optional uid gid)
3073 "Set the ownership for FILENAME.
3074 If UID and GID are provided, these values are used; otherwise uid
3075 and gid of the corresponding user is taken. Both parameters must be integers."
3076 ;; Modern Unices allow chown only for root. So we might need
3077 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
3078 ;; working with su(do)? when it is needed, so it shall succeed in
3079 ;; the majority of cases.
3080 ;; Don't modify `last-coding-system-used' by accident.
3081 (let ((last-coding-system-used last-coding-system-used))
3082 (if (file-remote-p filename)
3083 (with-parsed-tramp-file-name filename nil
3084 (if (and (zerop (user-uid)) (tramp-local-host-p v))
3085 ;; If we are root on the local host, we can do it directly.
3086 (tramp-set-file-uid-gid localname uid gid)
3087 (let ((uid (or (and (integerp uid) uid)
3088 (tramp-get-remote-uid v 'integer)))
3089 (gid (or (and (integerp gid) gid)
3090 (tramp-get-remote-gid v 'integer))))
3091 (tramp-send-command
3092 v (format
3093 "chown %d:%d %s" uid gid
3094 (tramp-shell-quote-argument localname))))))
3095
3096 ;; We handle also the local part, because there doesn't exist
3097 ;; `set-file-uid-gid'. On W32 "chown" might not work.
3098 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
3099 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
3100 (tramp-local-call-process
3101 "chown" nil nil nil
3102 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
3103
3104 (defun tramp-remote-selinux-p (vec)
3105 "Check, whether SELINUX is enabled on the remote host."
3106 (with-connection-property (tramp-get-connection-process vec) "selinux-p"
3107 (let ((result (tramp-find-executable
3108 vec "getenforce" (tramp-get-remote-path vec) t t)))
3109 (and result
3110 (string-equal
3111 (tramp-send-command-and-read
3112 vec (format "echo \\\"`%S`\\\"" result))
3113 "Enforcing")))))
3114
3115 (defun tramp-handle-file-selinux-context (filename)
3116 "Like `file-selinux-context' for Tramp files."
3117 (with-parsed-tramp-file-name filename nil
3118 (with-file-property v localname "file-selinux-context"
3119 (let ((context '(nil nil nil nil))
3120 (regexp (concat "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\):"
3121 "\\([a-z0-9_]+\\):" "\\([a-z0-9_]+\\)")))
3122 (when (and (tramp-remote-selinux-p v)
3123 (zerop (tramp-send-command-and-check
3124 v (format
3125 "%s -d -Z %s"
3126 (tramp-get-ls-command v)
3127 (tramp-shell-quote-argument localname)))))
3128 (with-current-buffer (tramp-get-connection-buffer v)
3129 (goto-char (point-min))
3130 (when (re-search-forward regexp (tramp-compat-line-end-position) t)
3131 (setq context (list (match-string 1) (match-string 2)
3132 (match-string 3) (match-string 4))))))
3133 ;; Return the context.
3134 context))))
3135
3136 (defun tramp-handle-set-file-selinux-context (filename context)
3137 "Like `set-file-selinux-context' for Tramp files."
3138 (with-parsed-tramp-file-name filename nil
3139 (if (and (consp context)
3140 (tramp-remote-selinux-p v)
3141 (zerop (tramp-send-command-and-check
3142 v (format "chcon %s %s %s %s %s"
3143 (if (stringp (nth 0 context))
3144 (format "--user=%s" (nth 0 context)) "")
3145 (if (stringp (nth 1 context))
3146 (format "--role=%s" (nth 1 context)) "")
3147 (if (stringp (nth 2 context))
3148 (format "--type=%s" (nth 2 context)) "")
3149 (if (stringp (nth 3 context))
3150 (format "--range=%s" (nth 3 context)) "")
3151 (tramp-shell-quote-argument localname)))))
3152 (tramp-set-file-property v localname "file-selinux-context" context)
3153 (tramp-set-file-property v localname "file-selinux-context" 'undef)))
3154 ;; We always return nil.
3155 nil)
3156
3157 ;; Simple functions using the `test' command.
3158
3159 (defun tramp-handle-file-executable-p (filename)
3160 "Like `file-executable-p' for Tramp files."
3161 (with-parsed-tramp-file-name filename nil
3162 (with-file-property v localname "file-executable-p"
3163 ;; Examine `file-attributes' cache to see if request can be
3164 ;; satisfied without remote operation.
3165 (or (tramp-check-cached-permissions v ?x)
3166 (zerop (tramp-run-test "-x" filename))))))
3167
3168 (defun tramp-handle-file-readable-p (filename)
3169 "Like `file-readable-p' for Tramp files."
3170 (with-parsed-tramp-file-name filename nil
3171 (with-file-property v localname "file-readable-p"
3172 ;; Examine `file-attributes' cache to see if request can be
3173 ;; satisfied without remote operation.
3174 (or (tramp-check-cached-permissions v ?r)
3175 (zerop (tramp-run-test "-r" filename))))))
3176
3177 ;; When the remote shell is started, it looks for a shell which groks
3178 ;; tilde expansion. Here, we assume that all shells which grok tilde
3179 ;; expansion will also provide a `test' command which groks `-nt' (for
3180 ;; newer than). If this breaks, tell me about it and I'll try to do
3181 ;; something smarter about it.
3182 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3183 "Like `file-newer-than-file-p' for Tramp files."
3184 (cond ((not (file-exists-p file1))
3185 nil)
3186 ((not (file-exists-p file2))
3187 t)
3188 ;; We are sure both files exist at this point.
3189 (t
3190 (save-excursion
3191 ;; We try to get the mtime of both files. If they are not
3192 ;; equal to the "dont-know" value, then we subtract the times
3193 ;; and obtain the result.
3194 (let ((fa1 (file-attributes file1))
3195 (fa2 (file-attributes file2)))
3196 (if (and (not (equal (nth 5 fa1) '(0 0)))
3197 (not (equal (nth 5 fa2) '(0 0))))
3198 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3199 ;; If one of them is the dont-know value, then we can
3200 ;; still try to run a shell command on the remote host.
3201 ;; However, this only works if both files are Tramp
3202 ;; files and both have the same method, same user, same
3203 ;; host.
3204 (unless (tramp-equal-remote file1 file2)
3205 (with-parsed-tramp-file-name
3206 (if (tramp-tramp-file-p file1) file1 file2) nil
3207 (tramp-error
3208 v 'file-error
3209 "Files %s and %s must have same method, user, host"
3210 file1 file2)))
3211 (with-parsed-tramp-file-name file1 nil
3212 (zerop (tramp-run-test2
3213 (tramp-get-test-nt-command v) file1 file2)))))))))
3214
3215 ;; Functions implemented using the basic functions above.
3216
3217 (defun tramp-handle-file-modes (filename)
3218 "Like `file-modes' for Tramp files."
3219 (let ((truename (or (file-truename filename) filename)))
3220 (when (file-exists-p truename)
3221 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3222
3223 (defun tramp-default-file-modes (filename)
3224 "Return file modes of FILENAME as integer.
3225 If the file modes of FILENAME cannot be determined, return the
3226 value of `default-file-modes', without execute permissions."
3227 (or (file-modes filename)
3228 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3229
3230 (defun tramp-handle-file-directory-p (filename)
3231 "Like `file-directory-p' for Tramp files."
3232 ;; Care must be taken that this function returns `t' for symlinks
3233 ;; pointing to directories. Surely the most obvious implementation
3234 ;; would be `test -d', but that returns false for such symlinks.
3235 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3236 ;; I now think he's right. So we could be using `test -d', couldn't
3237 ;; we?
3238 ;;
3239 ;; Alternatives: `cd %s', `test -d %s'
3240 (with-parsed-tramp-file-name filename nil
3241 (with-file-property v localname "file-directory-p"
3242 (zerop (tramp-run-test "-d" filename)))))
3243
3244 (defun tramp-handle-file-regular-p (filename)
3245 "Like `file-regular-p' for Tramp files."
3246 (and (file-exists-p filename)
3247 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3248
3249 (defun tramp-handle-file-symlink-p (filename)
3250 "Like `file-symlink-p' for Tramp files."
3251 (with-parsed-tramp-file-name filename nil
3252 (let ((x (car (file-attributes filename))))
3253 (when (stringp x)
3254 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3255 ;; might do weird things.
3256 (if (file-name-absolute-p x)
3257 (tramp-make-tramp-file-name method user host x)
3258 x)))))
3259
3260 (defun tramp-handle-file-writable-p (filename)
3261 "Like `file-writable-p' for Tramp files."
3262 (with-parsed-tramp-file-name filename nil
3263 (with-file-property v localname "file-writable-p"
3264 (if (file-exists-p filename)
3265 ;; Examine `file-attributes' cache to see if request can be
3266 ;; satisfied without remote operation.
3267 (or (tramp-check-cached-permissions v ?w)
3268 (zerop (tramp-run-test "-w" filename)))
3269 ;; If file doesn't exist, check if directory is writable.
3270 (and (zerop (tramp-run-test
3271 "-d" (file-name-directory filename)))
3272 (zerop (tramp-run-test
3273 "-w" (file-name-directory filename))))))))
3274
3275 (defun tramp-handle-file-ownership-preserved-p (filename)
3276 "Like `file-ownership-preserved-p' for Tramp files."
3277 (with-parsed-tramp-file-name filename nil
3278 (with-file-property v localname "file-ownership-preserved-p"
3279 (let ((attributes (file-attributes filename)))
3280 ;; Return t if the file doesn't exist, since it's true that no
3281 ;; information would be lost by an (attempted) delete and create.
3282 (or (null attributes)
3283 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3284
3285 ;; Other file name ops.
3286
3287 (defun tramp-handle-directory-file-name (directory)
3288 "Like `directory-file-name' for Tramp files."
3289 ;; If localname component of filename is "/", leave it unchanged.
3290 ;; Otherwise, remove any trailing slash from localname component.
3291 ;; Method, host, etc, are unchanged. Does it make sense to try
3292 ;; to avoid parsing the filename?
3293 (with-parsed-tramp-file-name directory nil
3294 (if (and (not (zerop (length localname)))
3295 (eq (aref localname (1- (length localname))) ?/)
3296 (not (string= localname "/")))
3297 (substring directory 0 -1)
3298 directory)))
3299
3300 ;; Directory listings.
3301
3302 (defun tramp-handle-directory-files
3303 (directory &optional full match nosort files-only)
3304 "Like `directory-files' for Tramp files."
3305 ;; FILES-ONLY is valid for XEmacs only.
3306 (when (file-directory-p directory)
3307 (setq directory (file-name-as-directory (expand-file-name directory)))
3308 (let ((temp (nreverse (file-name-all-completions "" directory)))
3309 result item)
3310
3311 (while temp
3312 (setq item (directory-file-name (pop temp)))
3313 (when (and (or (null match) (string-match match item))
3314 (or (null files-only)
3315 ;; Files only.
3316 (and (equal files-only t) (file-regular-p item))
3317 ;; Directories only.
3318 (file-directory-p item)))
3319 (push (if full (concat directory item) item)
3320 result)))
3321 (if nosort result (sort result 'string<)))))
3322
3323 (defun tramp-handle-directory-files-and-attributes
3324 (directory &optional full match nosort id-format)
3325 "Like `directory-files-and-attributes' for Tramp files."
3326 (unless id-format (setq id-format 'integer))
3327 (when (file-directory-p directory)
3328 (setq directory (expand-file-name directory))
3329 (let* ((temp
3330 (copy-tree
3331 (with-parsed-tramp-file-name directory nil
3332 (with-file-property
3333 v localname
3334 (format "directory-files-and-attributes-%s" id-format)
3335 (save-excursion
3336 (mapcar
3337 (lambda (x)
3338 (cons (car x)
3339 (tramp-convert-file-attributes v (cdr x))))
3340 (cond
3341 ((tramp-get-remote-stat v)
3342 (tramp-do-directory-files-and-attributes-with-stat
3343 v localname id-format))
3344 ((tramp-get-remote-perl v)
3345 (tramp-do-directory-files-and-attributes-with-perl
3346 v localname id-format)))))))))
3347 result item)
3348
3349 (while temp
3350 (setq item (pop temp))
3351 (when (or (null match) (string-match match (car item)))
3352 (when full
3353 (setcar item (expand-file-name (car item) directory)))
3354 (push item result)))
3355
3356 (if nosort
3357 result
3358 (sort result (lambda (x y) (string< (car x) (car y))))))))
3359
3360 (defun tramp-do-directory-files-and-attributes-with-perl
3361 (vec localname &optional id-format)
3362 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3363 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3364 (tramp-maybe-send-script
3365 vec tramp-perl-directory-files-and-attributes
3366 "tramp_perl_directory_files_and_attributes")
3367 (let ((object
3368 (tramp-send-command-and-read
3369 vec
3370 (format "tramp_perl_directory_files_and_attributes %s %s"
3371 (tramp-shell-quote-argument localname) id-format))))
3372 (when (stringp object) (tramp-error vec 'file-error object))
3373 object))
3374
3375 (defun tramp-do-directory-files-and-attributes-with-stat
3376 (vec localname &optional id-format)
3377 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3378 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3379 (tramp-send-command-and-read
3380 vec
3381 (format
3382 (concat
3383 ;; We must care about filenames with spaces, or starting with
3384 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3385 ;; but it does not work on all remote systems. Therefore, we
3386 ;; quote the filenames via sed.
3387 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3388 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%Xe0 %%Ye0 %%Ze0 %%se0 \"%%A\" t %%ie0 -1)'); "
3389 "echo \")\"")
3390 (tramp-shell-quote-argument localname)
3391 (tramp-get-ls-command vec)
3392 (tramp-get-remote-stat vec)
3393 (if (eq id-format 'integer) "%u" "\"%U\"")
3394 (if (eq id-format 'integer) "%g" "\"%G\""))))
3395
3396 ;; This function should return "foo/" for directories and "bar" for
3397 ;; files.
3398 (defun tramp-handle-file-name-all-completions (filename directory)
3399 "Like `file-name-all-completions' for Tramp files."
3400 (unless (save-match-data (string-match "/" filename))
3401 (with-parsed-tramp-file-name (expand-file-name directory) nil
3402
3403 (all-completions
3404 filename
3405 (mapcar
3406 'list
3407 (or
3408 ;; Try cache first
3409 (and
3410 ;; Ignore if expired
3411 (or (not (integerp tramp-completion-reread-directory-timeout))
3412 (<= (tramp-time-diff
3413 (current-time)
3414 (tramp-get-file-property
3415 v localname "last-completion" '(0 0 0)))
3416 tramp-completion-reread-directory-timeout))
3417
3418 ;; Try cache entries for filename, filename with last
3419 ;; character removed, filename with last two characters
3420 ;; removed, ..., and finally the empty string - all
3421 ;; concatenated to the local directory name
3422
3423 ;; This is inefficient for very long filenames, pity
3424 ;; `reduce' is not available...
3425 (car
3426 (apply
3427 'append
3428 (mapcar
3429 (lambda (x)
3430 (let ((cache-hit
3431 (tramp-get-file-property
3432 v
3433 (concat localname (substring filename 0 x))
3434 "file-name-all-completions"
3435 nil)))
3436 (when cache-hit (list cache-hit))))
3437 (tramp-compat-number-sequence (length filename) 0 -1)))))
3438
3439 ;; Cache expired or no matching cache entry found so we need
3440 ;; to perform a remote operation
3441 (let (result)
3442 ;; Get a list of directories and files, including reliably
3443 ;; tagging the directories with a trailing '/'. Because I
3444 ;; rock. --daniel@danann.net
3445
3446 ;; Changed to perform `cd' in the same remote op and only
3447 ;; get entries starting with `filename'. Capture any `cd'
3448 ;; error messages. Ensure any `cd' and `echo' aliases are
3449 ;; ignored.
3450 (tramp-send-command
3451 v
3452 (if (tramp-get-remote-perl v)
3453 (progn
3454 (tramp-maybe-send-script
3455 v tramp-perl-file-name-all-completions
3456 "tramp_perl_file_name_all_completions")
3457 (format "tramp_perl_file_name_all_completions %s %s %d"
3458 (tramp-shell-quote-argument localname)
3459 (tramp-shell-quote-argument filename)
3460 (if (symbol-value
3461 ;; `read-file-name-completion-ignore-case'
3462 ;; is introduced with Emacs 22.1.
3463 (if (boundp
3464 'read-file-name-completion-ignore-case)
3465 'read-file-name-completion-ignore-case
3466 'completion-ignore-case))
3467 1 0)))
3468
3469 (format (concat
3470 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3471 ;; `ls' with wildcard might fail with `Argument
3472 ;; list too long' error in some corner cases; if
3473 ;; `ls' fails after `cd' succeeded, chances are
3474 ;; that's the case, so let's retry without
3475 ;; wildcard. This will return "too many" entries
3476 ;; but that isn't harmful.
3477 " || %s -a 2>/dev/null)"
3478 " | while read f; do"
3479 " if %s -d \"$f\" 2>/dev/null;"
3480 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3481 " && \\echo ok) || \\echo fail")
3482 (tramp-shell-quote-argument localname)
3483 (tramp-get-ls-command v)
3484 ;; When `filename' is empty, just `ls' without
3485 ;; filename argument is more efficient than `ls *'
3486 ;; for very large directories and might avoid the
3487 ;; `Argument list too long' error.
3488 ;;
3489 ;; With and only with wildcard, we need to add
3490 ;; `-d' to prevent `ls' from descending into
3491 ;; sub-directories.
3492 (if (zerop (length filename))
3493 "."
3494 (concat (tramp-shell-quote-argument filename) "* -d"))
3495 (tramp-get-ls-command v)
3496 (tramp-get-test-command v))))
3497
3498 ;; Now grab the output.
3499 (with-current-buffer (tramp-get-buffer v)
3500 (goto-char (point-max))
3501
3502 ;; Check result code, found in last line of output
3503 (forward-line -1)
3504 (if (looking-at "^fail$")
3505 (progn
3506 ;; Grab error message from line before last line
3507 ;; (it was put there by `cd 2>&1')
3508 (forward-line -1)
3509 (tramp-error
3510 v 'file-error
3511 "tramp-handle-file-name-all-completions: %s"
3512 (buffer-substring
3513 (point) (tramp-compat-line-end-position))))
3514 ;; For peace of mind, if buffer doesn't end in `fail'
3515 ;; then it should end in `ok'. If neither are in the
3516 ;; buffer something went seriously wrong on the remote
3517 ;; side.
3518 (unless (looking-at "^ok$")
3519 (tramp-error
3520 v 'file-error
3521 "\
3522 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3523 (tramp-shell-quote-argument localname) (buffer-string))))
3524
3525 (while (zerop (forward-line -1))
3526 (push (buffer-substring
3527 (point) (tramp-compat-line-end-position))
3528 result)))
3529
3530 ;; Because the remote op went through OK we know the
3531 ;; directory we `cd'-ed to exists
3532 (tramp-set-file-property
3533 v localname "file-exists-p" t)
3534
3535 ;; Because the remote op went through OK we know every
3536 ;; file listed by `ls' exists.
3537 (mapc (lambda (entry)
3538 (tramp-set-file-property
3539 v (concat localname entry) "file-exists-p" t))
3540 result)
3541
3542 (tramp-set-file-property
3543 v localname "last-completion" (current-time))
3544
3545 ;; Store result in the cache
3546 (tramp-set-file-property
3547 v (concat localname filename)
3548 "file-name-all-completions"
3549 result))))))))
3550
3551 (defun tramp-handle-file-name-completion
3552 (filename directory &optional predicate)
3553 "Like `file-name-completion' for Tramp files."
3554 (unless (tramp-tramp-file-p directory)
3555 (error
3556 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3557 directory))
3558 (try-completion
3559 filename
3560 (mapcar 'list (file-name-all-completions filename directory))
3561 (when predicate
3562 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3563
3564 ;; cp, mv and ln
3565
3566 (defun tramp-handle-add-name-to-file
3567 (filename newname &optional ok-if-already-exists)
3568 "Like `add-name-to-file' for Tramp files."
3569 (unless (tramp-equal-remote filename newname)
3570 (with-parsed-tramp-file-name
3571 (if (tramp-tramp-file-p filename) filename newname) nil
3572 (tramp-error
3573 v 'file-error
3574 "add-name-to-file: %s"
3575 "only implemented for same method, same user, same host")))
3576 (with-parsed-tramp-file-name filename v1
3577 (with-parsed-tramp-file-name newname v2
3578 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3579 (when (and (not ok-if-already-exists)
3580 (file-exists-p newname)
3581 (not (numberp ok-if-already-exists))
3582 (y-or-n-p
3583 (format
3584 "File %s already exists; make it a new name anyway? "
3585 newname)))
3586 (tramp-error
3587 v2 'file-error
3588 "add-name-to-file: file %s already exists" newname))
3589 (tramp-flush-file-property v2 (file-name-directory v2-localname))
3590 (tramp-flush-file-property v2 v2-localname)
3591 (tramp-barf-unless-okay
3592 v1
3593 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3594 (tramp-shell-quote-argument v2-localname))
3595 "error with add-name-to-file, see buffer `%s' for details"
3596 (buffer-name))))))
3597
3598 (defun tramp-handle-copy-file
3599 (filename newname &optional ok-if-already-exists keep-date
3600 preserve-uid-gid preserve-selinux-context)
3601 "Like `copy-file' for Tramp files."
3602 (setq filename (expand-file-name filename))
3603 (setq newname (expand-file-name newname))
3604 (cond
3605 ;; At least one file a Tramp file?
3606 ((or (tramp-tramp-file-p filename)
3607 (tramp-tramp-file-p newname))
3608 (tramp-do-copy-or-rename-file
3609 'copy filename newname ok-if-already-exists keep-date
3610 preserve-uid-gid preserve-selinux-context))
3611 ;; Compat section.
3612 (preserve-selinux-context
3613 (tramp-run-real-handler
3614 'copy-file
3615 (list filename newname ok-if-already-exists keep-date
3616 preserve-uid-gid preserve-selinux-context)))
3617 (preserve-uid-gid
3618 (tramp-run-real-handler
3619 'copy-file
3620 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3621 (t
3622 (tramp-run-real-handler
3623 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3624
3625 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3626 "Like `copy-directory' for Tramp files."
3627 (let ((t1 (tramp-tramp-file-p dirname))
3628 (t2 (tramp-tramp-file-p newname)))
3629 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3630 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3631 ;; When DIRNAME and NEWNAME are remote, they must have
3632 ;; the same method.
3633 (or (null t1) (null t2)
3634 (string-equal
3635 (tramp-file-name-method (tramp-dissect-file-name dirname))
3636 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3637 ;; scp or rsync DTRT.
3638 (progn
3639 (setq dirname (directory-file-name (expand-file-name dirname))
3640 newname (directory-file-name (expand-file-name newname)))
3641 (if (and (file-directory-p newname)
3642 (not (string-equal (file-name-nondirectory dirname)
3643 (file-name-nondirectory newname))))
3644 (setq newname
3645 (expand-file-name
3646 (file-name-nondirectory dirname) newname)))
3647 (if (not (file-directory-p (file-name-directory newname)))
3648 (make-directory (file-name-directory newname) parents))
3649 (tramp-do-copy-or-rename-file-out-of-band
3650 'copy dirname newname keep-date))
3651 ;; We must do it file-wise.
3652 (tramp-run-real-handler
3653 'copy-directory (list dirname newname keep-date parents)))
3654
3655 ;; When newname did exist, we have wrong cached values.
3656 (when t2
3657 (with-parsed-tramp-file-name newname nil
3658 (tramp-flush-file-property v (file-name-directory localname))
3659 (tramp-flush-file-property v localname))))))
3660
3661 (defun tramp-handle-rename-file
3662 (filename newname &optional ok-if-already-exists)
3663 "Like `rename-file' for Tramp files."
3664 ;; Check if both files are local -- invoke normal rename-file.
3665 ;; Otherwise, use Tramp from local system.
3666 (setq filename (expand-file-name filename))
3667 (setq newname (expand-file-name newname))
3668 ;; At least one file a Tramp file?
3669 (if (or (tramp-tramp-file-p filename)
3670 (tramp-tramp-file-p newname))
3671 (tramp-do-copy-or-rename-file
3672 'rename filename newname ok-if-already-exists t t)
3673 (tramp-run-real-handler
3674 'rename-file (list filename newname ok-if-already-exists))))
3675
3676 (defun tramp-do-copy-or-rename-file
3677 (op filename newname &optional ok-if-already-exists keep-date
3678 preserve-uid-gid preserve-selinux-context)
3679 "Copy or rename a remote file.
3680 OP must be `copy' or `rename' and indicates the operation to perform.
3681 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3682 the new file (for copy) or the new name of the file (for rename).
3683 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3684 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3685 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3686 the uid and gid if both files are on the same host.
3687 PRESERVE-SELINUX-CONTEXT activates selinux commands.
3688
3689 This function is invoked by `tramp-handle-copy-file' and
3690 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3691 and `rename'. FILENAME and NEWNAME must be absolute file names."
3692 (unless (memq op '(copy rename))
3693 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3694 (let ((t1 (tramp-tramp-file-p filename))
3695 (t2 (tramp-tramp-file-p newname))
3696 (context (and preserve-selinux-context
3697 (apply 'file-selinux-context (list filename))))
3698 pr tm)
3699
3700 (with-parsed-tramp-file-name (if t1 filename newname) nil
3701 (when (and (not ok-if-already-exists) (file-exists-p newname))
3702 (tramp-error
3703 v 'file-already-exists "File %s already exists" newname))
3704
3705 (with-progress-reporter
3706 v 0 (format "%s %s to %s"
3707 (if (eq op 'copy) "Copying" "Renaming")
3708 filename newname)
3709
3710 (cond
3711 ;; Both are Tramp files.
3712 ((and t1 t2)
3713 (with-parsed-tramp-file-name filename v1
3714 (with-parsed-tramp-file-name newname v2
3715 (cond
3716 ;; Shortcut: if method, host, user are the same for
3717 ;; both files, we invoke `cp' or `mv' on the remote
3718 ;; host directly.
3719 ((tramp-equal-remote filename newname)
3720 (tramp-do-copy-or-rename-file-directly
3721 op filename newname
3722 ok-if-already-exists keep-date preserve-uid-gid))
3723
3724 ;; Try out-of-band operation.
3725 ((tramp-method-out-of-band-p
3726 v1 (nth 7 (file-attributes filename)))
3727 (tramp-do-copy-or-rename-file-out-of-band
3728 op filename newname keep-date))
3729
3730 ;; No shortcut was possible. So we copy the file
3731 ;; first. If the operation was `rename', we go back
3732 ;; and delete the original file (if the copy was
3733 ;; successful). The approach is simple-minded: we
3734 ;; create a new buffer, insert the contents of the
3735 ;; source file into it, then write out the buffer to
3736 ;; the target file. The advantage is that it doesn't
3737 ;; matter which filename handlers are used for the
3738 ;; source and target file.
3739 (t
3740 (tramp-do-copy-or-rename-file-via-buffer
3741 op filename newname keep-date))))))
3742
3743 ;; One file is a Tramp file, the other one is local.
3744 ((or t1 t2)
3745 (cond
3746 ;; Fast track on local machine.
3747 ((tramp-local-host-p v)
3748 (tramp-do-copy-or-rename-file-directly
3749 op filename newname
3750 ok-if-already-exists keep-date preserve-uid-gid))
3751
3752 ;; If the Tramp file has an out-of-band method, the
3753 ;; corresponding copy-program can be invoked.
3754 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3755 (tramp-do-copy-or-rename-file-out-of-band
3756 op filename newname keep-date))
3757
3758 ;; Use the inline method via a Tramp buffer.
3759 (t (tramp-do-copy-or-rename-file-via-buffer
3760 op filename newname keep-date))))
3761
3762 (t
3763 ;; One of them must be a Tramp file.
3764 (error "Tramp implementation says this cannot happen")))
3765
3766 ;; Handle `preserve-selinux-context'.
3767 (when context (apply 'set-file-selinux-context (list newname context)))
3768
3769 ;; In case of `rename', we must flush the cache of the source file.
3770 (when (and t1 (eq op 'rename))
3771 (with-parsed-tramp-file-name filename v1
3772 (tramp-flush-file-property v1 (file-name-directory localname))
3773 (tramp-flush-file-property v1 localname)))
3774
3775 ;; When newname did exist, we have wrong cached values.
3776 (when t2
3777 (with-parsed-tramp-file-name newname v2
3778 (tramp-flush-file-property v2 (file-name-directory localname))
3779 (tramp-flush-file-property v2 localname)))))))
3780
3781 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3782 "Use an Emacs buffer to copy or rename a file.
3783 First arg OP is either `copy' or `rename' and indicates the operation.
3784 FILENAME is the source file, NEWNAME the target file.
3785 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3786 (with-temp-buffer
3787 ;; We must disable multibyte, because binary data shall not be
3788 ;; converted.
3789 (set-buffer-multibyte nil)
3790 (let ((coding-system-for-read 'binary)
3791 (jka-compr-inhibit t))
3792 (insert-file-contents-literally filename))
3793 ;; We don't want the target file to be compressed, so we let-bind
3794 ;; `jka-compr-inhibit' to t.
3795 (let ((coding-system-for-write 'binary)
3796 (jka-compr-inhibit t))
3797 (write-region (point-min) (point-max) newname)))
3798 ;; KEEP-DATE handling.
3799 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3800 ;; Set the mode.
3801 (set-file-modes newname (tramp-default-file-modes filename))
3802 ;; If the operation was `rename', delete the original file.
3803 (unless (eq op 'copy) (delete-file filename)))
3804
3805 (defun tramp-do-copy-or-rename-file-directly
3806 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3807 "Invokes `cp' or `mv' on the remote system.
3808 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3809 respectively. FILENAME specifies the file to copy or rename,
3810 NEWNAME is the name of the new file (for copy) or the new name of
3811 the file (for rename). Both files must reside on the same host.
3812 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3813 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3814 the uid and gid from FILENAME."
3815 (let ((t1 (tramp-tramp-file-p filename))
3816 (t2 (tramp-tramp-file-p newname))
3817 (file-times (nth 5 (file-attributes filename)))
3818 (file-modes (tramp-default-file-modes filename)))
3819 (with-parsed-tramp-file-name (if t1 filename newname) nil
3820 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3821 ((eq op 'copy) "cp -f")
3822 ((eq op 'rename) "mv -f")
3823 (t (tramp-error
3824 v 'file-error
3825 "Unknown operation `%s', must be `copy' or `rename'"
3826 op))))
3827 (localname1
3828 (if t1
3829 (tramp-file-name-handler 'file-remote-p filename 'localname)
3830 filename))
3831 (localname2
3832 (if t2
3833 (tramp-file-name-handler 'file-remote-p newname 'localname)
3834 newname))
3835 (prefix (file-remote-p (if t1 filename newname)))
3836 cmd-result)
3837
3838 (cond
3839 ;; Both files are on a remote host, with same user.
3840 ((and t1 t2)
3841 (setq cmd-result
3842 (tramp-send-command-and-check
3843 v
3844 (format "%s %s %s" cmd
3845 (tramp-shell-quote-argument localname1)
3846 (tramp-shell-quote-argument localname2))))
3847 (with-current-buffer (tramp-get-buffer v)
3848 (goto-char (point-min))
3849 (unless
3850 (or
3851 (and keep-date
3852 ;; Mask cp -f error.
3853 (re-search-forward
3854 tramp-operation-not-permitted-regexp nil t))
3855 (zerop cmd-result))
3856 (tramp-error-with-buffer
3857 nil v 'file-error
3858 "Copying directly failed, see buffer `%s' for details."
3859 (buffer-name)))))
3860
3861 ;; We are on the local host.
3862 ((or t1 t2)
3863 (cond
3864 ;; We can do it directly.
3865 ((let (file-name-handler-alist)
3866 (and (file-readable-p localname1)
3867 (file-writable-p (file-name-directory localname2))
3868 (or (file-directory-p localname2)
3869 (file-writable-p localname2))))
3870 (if (eq op 'copy)
3871 (tramp-compat-copy-file
3872 localname1 localname2 ok-if-already-exists
3873 keep-date preserve-uid-gid)
3874 (tramp-run-real-handler
3875 'rename-file (list localname1 localname2 ok-if-already-exists))))
3876
3877 ;; We can do it directly with `tramp-send-command'
3878 ((and (file-readable-p (concat prefix localname1))
3879 (file-writable-p
3880 (file-name-directory (concat prefix localname2)))
3881 (or (file-directory-p (concat prefix localname2))
3882 (file-writable-p (concat prefix localname2))))
3883 (tramp-do-copy-or-rename-file-directly
3884 op (concat prefix localname1) (concat prefix localname2)
3885 ok-if-already-exists keep-date t)
3886 ;; We must change the ownership to the local user.
3887 (tramp-set-file-uid-gid
3888 (concat prefix localname2)
3889 (tramp-get-local-uid 'integer)
3890 (tramp-get-local-gid 'integer)))
3891
3892 ;; We need a temporary file in between.
3893 (t
3894 ;; Create the temporary file.
3895 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3896 (unwind-protect
3897 (progn
3898 (cond
3899 (t1
3900 (or
3901 (zerop
3902 (tramp-send-command-and-check
3903 v (format
3904 "%s %s %s" cmd
3905 (tramp-shell-quote-argument localname1)
3906 (tramp-shell-quote-argument tmpfile))))
3907 (tramp-error-with-buffer
3908 nil v 'file-error
3909 "Copying directly failed, see buffer `%s' for details."
3910 (tramp-get-buffer v)))
3911 ;; We must change the ownership as remote user.
3912 ;; Since this does not work reliable, we also
3913 ;; give read permissions.
3914 (set-file-modes
3915 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3916 (tramp-set-file-uid-gid
3917 (concat prefix tmpfile)
3918 (tramp-get-local-uid 'integer)
3919 (tramp-get-local-gid 'integer)))
3920 (t2
3921 (if (eq op 'copy)
3922 (tramp-compat-copy-file
3923 localname1 tmpfile t
3924 keep-date preserve-uid-gid)
3925 (tramp-run-real-handler
3926 'rename-file
3927 (list localname1 tmpfile t)))
3928 ;; We must change the ownership as local user.
3929 ;; Since this does not work reliable, we also
3930 ;; give read permissions.
3931 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3932 (tramp-set-file-uid-gid
3933 tmpfile
3934 (tramp-get-remote-uid v 'integer)
3935 (tramp-get-remote-gid v 'integer))))
3936
3937 ;; Move the temporary file to its destination.
3938 (cond
3939 (t2
3940 (or
3941 (zerop
3942 (tramp-send-command-and-check
3943 v (format
3944 "cp -f -p %s %s"
3945 (tramp-shell-quote-argument tmpfile)
3946 (tramp-shell-quote-argument localname2))))
3947 (tramp-error-with-buffer
3948 nil v 'file-error
3949 "Copying directly failed, see buffer `%s' for details."
3950 (tramp-get-buffer v))))
3951 (t1
3952 (tramp-run-real-handler
3953 'rename-file
3954 (list tmpfile localname2 ok-if-already-exists)))))
3955
3956 ;; Save exit.
3957 (condition-case nil
3958 (delete-file tmpfile)
3959 (error)))))))))
3960
3961 ;; Set the time and mode. Mask possible errors.
3962 (condition-case nil
3963 (when keep-date
3964 (set-file-times newname file-times)
3965 (set-file-modes newname file-modes))
3966 (error)))))
3967
3968 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3969 "Invoke rcp program to copy.
3970 The method used must be an out-of-band method."
3971 (let ((t1 (tramp-tramp-file-p filename))
3972 (t2 (tramp-tramp-file-p newname))
3973 copy-program copy-args copy-env copy-keep-date port spec
3974 source target)
3975
3976 (with-parsed-tramp-file-name (if t1 filename newname) nil
3977 (if (and t1 t2)
3978
3979 ;; Both are Tramp files. We shall optimize it, when the
3980 ;; methods for filename and newname are the same.
3981 (let* ((dir-flag (file-directory-p filename))
3982 (tmpfile (tramp-compat-make-temp-file localname dir-flag)))
3983 (if dir-flag
3984 (setq tmpfile
3985 (expand-file-name
3986 (file-name-nondirectory newname) tmpfile)))
3987 (unwind-protect
3988 (progn
3989 (tramp-do-copy-or-rename-file-out-of-band
3990 op filename tmpfile keep-date)
3991 (tramp-do-copy-or-rename-file-out-of-band
3992 'rename tmpfile newname keep-date))
3993 ;; Save exit.
3994 (condition-case nil
3995 (if dir-flag
3996 (tramp-compat-delete-directory
3997 (expand-file-name ".." tmpfile) 'recursive)
3998 (delete-file tmpfile))
3999 (error))))
4000
4001 ;; Expand hops. Might be necessary for gateway methods.
4002 (setq v (car (tramp-compute-multi-hops v)))
4003 (aset v 3 localname)
4004
4005 ;; Check which ones of source and target are Tramp files.
4006 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
4007 target (funcall
4008 (if (and (file-directory-p filename)
4009 (string-equal
4010 (file-name-nondirectory filename)
4011 (file-name-nondirectory newname)))
4012 'file-name-directory
4013 'identity)
4014 (if t2 (tramp-make-copy-program-file-name v) newname)))
4015
4016 ;; Check for port number. Until now, there's no need for handling
4017 ;; like method, user, host.
4018 (setq host (tramp-file-name-real-host v)
4019 port (tramp-file-name-port v)
4020 port (or (and port (number-to-string port)) ""))
4021
4022 ;; Compose copy command.
4023 (setq spec (format-spec-make
4024 ?h host ?u user ?p port
4025 ?t (tramp-get-connection-property
4026 (tramp-get-connection-process v) "temp-file" "")
4027 ?k (if keep-date " " ""))
4028 copy-program (tramp-get-method-parameter
4029 method 'tramp-copy-program)
4030 copy-keep-date (tramp-get-method-parameter
4031 method 'tramp-copy-keep-date)
4032 copy-args
4033 (delq
4034 nil
4035 (mapcar
4036 (lambda (x)
4037 (setq
4038 x
4039 ;; " " is indication for keep-date argument.
4040 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
4041 (unless (member "" x) (mapconcat 'identity x " ")))
4042 (tramp-get-method-parameter method 'tramp-copy-args)))
4043 copy-env
4044 (delq
4045 nil
4046 (mapcar
4047 (lambda (x)
4048 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
4049 (unless (member "" x) (mapconcat 'identity x " ")))
4050 (tramp-get-method-parameter method 'tramp-copy-env))))
4051
4052 ;; Check for program.
4053 (when (and (fboundp 'executable-find)
4054 (not (let ((default-directory
4055 (tramp-compat-temporary-file-directory)))
4056 (executable-find copy-program))))
4057 (tramp-error
4058 v 'file-error "Cannot find copy program: %s" copy-program))
4059
4060 ;; Set variables for computing the prompt for reading
4061 ;; password.
4062 (setq tramp-current-method (tramp-file-name-method v)
4063 tramp-current-user (tramp-file-name-user v)
4064 tramp-current-host (tramp-file-name-host v))
4065
4066 (unwind-protect
4067 (with-temp-buffer
4068 ;; The default directory must be remote.
4069 (let ((default-directory
4070 (file-name-directory (if t1 filename newname)))
4071 (process-environment (copy-sequence process-environment)))
4072 ;; Set the transfer process properties.
4073 (tramp-set-connection-property
4074 v "process-name" (buffer-name (current-buffer)))
4075 (tramp-set-connection-property
4076 v "process-buffer" (current-buffer))
4077 (while copy-env
4078 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
4079 (setenv (pop copy-env) (pop copy-env)))
4080
4081 ;; Use an asynchronous process. By this, password can
4082 ;; be handled. The default directory must be local, in
4083 ;; order to apply the correct `copy-program'. We don't
4084 ;; set a timeout, because the copying of large files can
4085 ;; last longer than 60 secs.
4086 (let ((p (let ((default-directory
4087 (tramp-compat-temporary-file-directory)))
4088 (apply 'start-process
4089 (tramp-get-connection-property
4090 v "process-name" nil)
4091 (tramp-get-connection-property
4092 v "process-buffer" nil)
4093 copy-program
4094 (append copy-args (list source target))))))
4095 (tramp-message
4096 v 6 "%s" (mapconcat 'identity (process-command p) " "))
4097 (tramp-set-process-query-on-exit-flag p nil)
4098 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
4099
4100 ;; Reset the transfer process properties.
4101 (tramp-set-connection-property v "process-name" nil)
4102 (tramp-set-connection-property v "process-buffer" nil))
4103
4104 ;; Handle KEEP-DATE argument.
4105 (when (and keep-date (not copy-keep-date))
4106 (set-file-times newname (nth 5 (file-attributes filename))))
4107
4108 ;; Set the mode.
4109 (unless (and keep-date copy-keep-date)
4110 (ignore-errors
4111 (set-file-modes newname (tramp-default-file-modes filename)))))
4112
4113 ;; If the operation was `rename', delete the original file.
4114 (unless (eq op 'copy)
4115 (if (file-regular-p filename)
4116 (delete-file filename)
4117 (tramp-compat-delete-directory filename 'recursive))))))
4118
4119 (defun tramp-handle-make-directory (dir &optional parents)
4120 "Like `make-directory' for Tramp files."
4121 (setq dir (expand-file-name dir))
4122 (with-parsed-tramp-file-name dir nil
4123 (tramp-flush-directory-property v (file-name-directory localname))
4124 (save-excursion
4125 (tramp-barf-unless-okay
4126 v
4127 (format "%s %s"
4128 (if parents "mkdir -p" "mkdir")
4129 (tramp-shell-quote-argument localname))
4130 "Couldn't make directory %s" dir))))
4131
4132 (defun tramp-handle-delete-directory (directory &optional recursive)
4133 "Like `delete-directory' for Tramp files."
4134 (setq directory (expand-file-name directory))
4135 (with-parsed-tramp-file-name directory nil
4136 (tramp-flush-file-property v (file-name-directory localname))
4137 (tramp-flush-directory-property v localname)
4138 (unless (zerop (tramp-send-command-and-check
4139 v
4140 (format
4141 "%s %s"
4142 (if recursive "rm -rf" "rmdir")
4143 (tramp-shell-quote-argument localname))))
4144 (tramp-error v 'file-error "Couldn't delete %s" directory))))
4145
4146 (defun tramp-handle-delete-file (filename &optional trash)
4147 "Like `delete-file' for Tramp files."
4148 (setq filename (expand-file-name filename))
4149 (with-parsed-tramp-file-name filename nil
4150 (tramp-flush-file-property v (file-name-directory localname))
4151 (tramp-flush-file-property v localname)
4152 (unless
4153 (zerop
4154 (tramp-send-command-and-check
4155 v (format "%s %s"
4156 (or (and trash (tramp-get-remote-trash v)) "rm -f")
4157 (tramp-shell-quote-argument localname))))
4158 (tramp-error v 'file-error "Couldn't delete %s" filename))))
4159
4160 ;; Dired.
4161
4162 ;; CCC: This does not seem to be enough. Something dies when
4163 ;; we try and delete two directories under Tramp :/
4164 (defun tramp-handle-dired-recursive-delete-directory (filename)
4165 "Recursively delete the directory given.
4166 This is like `dired-recursive-delete-directory' for Tramp files."
4167 (with-parsed-tramp-file-name filename nil
4168 ;; Run a shell command 'rm -r <localname>'
4169 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
4170 (unless (file-exists-p filename)
4171 (tramp-error v 'file-error "No such directory: %s" filename))
4172 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
4173 (tramp-send-command
4174 v
4175 (format "rm -rf %s" (tramp-shell-quote-argument localname))
4176 ;; Don't read the output, do it explicitely.
4177 nil t)
4178 ;; Wait for the remote system to return to us...
4179 ;; This might take a while, allow it plenty of time.
4180 (tramp-wait-for-output (tramp-get-connection-process v) 120)
4181 ;; Make sure that it worked...
4182 (tramp-flush-file-property v (file-name-directory localname))
4183 (tramp-flush-directory-property v localname)
4184 (and (file-exists-p filename)
4185 (tramp-error
4186 v 'file-error "Failed to recursively delete %s" filename))))
4187
4188 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
4189 "Like `dired-compress-file' for Tramp files."
4190 ;; OK-FLAG is valid for XEmacs only, but not implemented.
4191 ;; Code stolen mainly from dired-aux.el.
4192 (with-parsed-tramp-file-name file nil
4193 (tramp-flush-file-property v localname)
4194 (save-excursion
4195 (let ((suffixes
4196 (if (not (featurep 'xemacs))
4197 ;; Emacs case
4198 (symbol-value 'dired-compress-file-suffixes)
4199 ;; XEmacs has `dired-compression-method-alist', which is
4200 ;; transformed into `dired-compress-file-suffixes' structure.
4201 (mapcar
4202 (lambda (x)
4203 (list (concat (regexp-quote (nth 1 x)) "\\'")
4204 nil
4205 (mapconcat 'identity (nth 3 x) " ")))
4206 (symbol-value 'dired-compression-method-alist))))
4207 suffix)
4208 ;; See if any suffix rule matches this file name.
4209 (while suffixes
4210 (let (case-fold-search)
4211 (if (string-match (car (car suffixes)) localname)
4212 (setq suffix (car suffixes) suffixes nil))
4213 (setq suffixes (cdr suffixes))))
4214
4215 (cond ((file-symlink-p file)
4216 nil)
4217 ((and suffix (nth 2 suffix))
4218 ;; We found an uncompression rule.
4219 (with-progress-reporter v 0 (format "Uncompressing %s" file)
4220 (when (zerop
4221 (tramp-send-command-and-check
4222 v (concat (nth 2 suffix) " "
4223 (tramp-shell-quote-argument localname))))
4224 ;; `dired-remove-file' is not defined in XEmacs.
4225 (tramp-compat-funcall 'dired-remove-file file)
4226 (string-match (car suffix) file)
4227 (concat (substring file 0 (match-beginning 0))))))
4228 (t
4229 ;; We don't recognize the file as compressed, so compress it.
4230 ;; Try gzip.
4231 (with-progress-reporter v 0 (format "Compressing %s" file)
4232 (when (zerop
4233 (tramp-send-command-and-check
4234 v (concat "gzip -f "
4235 (tramp-shell-quote-argument localname))))
4236 ;; `dired-remove-file' is not defined in XEmacs.
4237 (tramp-compat-funcall 'dired-remove-file file)
4238 (cond ((file-exists-p (concat file ".gz"))
4239 (concat file ".gz"))
4240 ((file-exists-p (concat file ".z"))
4241 (concat file ".z"))
4242 (t nil))))))))))
4243
4244 (defun tramp-handle-dired-uncache (dir &optional dir-p)
4245 "Like `dired-uncache' for Tramp files."
4246 ;; DIR-P is valid for XEmacs only.
4247 (with-parsed-tramp-file-name
4248 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
4249 (tramp-flush-directory-property v localname)))
4250
4251 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4252 ;; not sure at all that this is the right way to do it, but let's hope
4253 ;; it works for now, and wait for a guru to point out the Right Way to
4254 ;; achieve this.
4255 ;;(eval-when-compile
4256 ;; (unless (fboundp 'dired-insert-set-properties)
4257 ;; (fset 'dired-insert-set-properties 'ignore)))
4258 ;; Gerd suggests this:
4259 (eval-when-compile (require 'dired))
4260 ;; Note that dired is required at run-time, too, when it is needed.
4261 ;; It is only needed on XEmacs for the function
4262 ;; `dired-insert-set-properties'.
4263
4264 (defun tramp-handle-insert-directory
4265 (filename switches &optional wildcard full-directory-p)
4266 "Like `insert-directory' for Tramp files."
4267 (setq filename (expand-file-name filename))
4268 (with-parsed-tramp-file-name filename nil
4269 (if (and (featurep 'ls-lisp)
4270 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4271 (tramp-run-real-handler
4272 'insert-directory (list filename switches wildcard full-directory-p))
4273 (when (stringp switches)
4274 (setq switches (split-string switches)))
4275 (when (and (member "--dired" switches)
4276 (not (tramp-get-ls-command-with-dired v)))
4277 (setq switches (delete "--dired" switches)))
4278 (when wildcard
4279 (setq wildcard (tramp-run-real-handler
4280 'file-name-nondirectory (list localname)))
4281 (setq localname (tramp-run-real-handler
4282 'file-name-directory (list localname))))
4283 (unless full-directory-p
4284 (setq switches (add-to-list 'switches "-d" 'append)))
4285 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4286 (when wildcard
4287 (setq switches (concat switches " " wildcard)))
4288 (tramp-message
4289 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4290 switches filename (if wildcard "yes" "no")
4291 (if full-directory-p "yes" "no"))
4292 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4293 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4294 (if full-directory-p
4295 (tramp-send-command
4296 v
4297 (format "%s %s %s 2>/dev/null"
4298 (tramp-get-ls-command v)
4299 switches
4300 (if wildcard
4301 localname
4302 (tramp-shell-quote-argument (concat localname ".")))))
4303 (tramp-barf-unless-okay
4304 v
4305 (format "cd %s" (tramp-shell-quote-argument
4306 (tramp-run-real-handler
4307 'file-name-directory (list localname))))
4308 "Couldn't `cd %s'"
4309 (tramp-shell-quote-argument
4310 (tramp-run-real-handler 'file-name-directory (list localname))))
4311 (tramp-send-command
4312 v
4313 (format "%s %s %s"
4314 (tramp-get-ls-command v)
4315 switches
4316 (if (or wildcard
4317 (zerop (length
4318 (tramp-run-real-handler
4319 'file-name-nondirectory (list localname)))))
4320 ""
4321 (tramp-shell-quote-argument
4322 (tramp-run-real-handler
4323 'file-name-nondirectory (list localname)))))))
4324 (let ((beg (point)))
4325 ;; We cannot use `insert-buffer-substring' because the Tramp
4326 ;; buffer changes its contents before insertion due to calling
4327 ;; `expand-file' and alike.
4328 (insert
4329 (with-current-buffer (tramp-get-buffer v)
4330 (buffer-string)))
4331
4332 ;; Check for "--dired" output.
4333 (forward-line -2)
4334 (when (looking-at "//SUBDIRED//")
4335 (forward-line -1))
4336 (when (looking-at "//DIRED//\\s-+")
4337 (let ((databeg (match-end 0))
4338 (end (tramp-compat-line-end-position)))
4339 ;; Now read the numeric positions of file names.
4340 (goto-char databeg)
4341 (while (< (point) end)
4342 (let ((start (+ beg (read (current-buffer))))
4343 (end (+ beg (read (current-buffer)))))
4344 (if (memq (char-after end) '(?\n ?\ ))
4345 ;; End is followed by \n or by " -> ".
4346 (put-text-property start end 'dired-filename t))))))
4347 ;; Remove trailing lines.
4348 (goto-char (tramp-compat-line-beginning-position))
4349 (while (looking-at "//")
4350 (forward-line 1)
4351 (delete-region (match-beginning 0) (point)))
4352
4353 ;; The inserted file could be from somewhere else.
4354 (when (and (not wildcard) (not full-directory-p))
4355 (goto-char (point-max))
4356 (when (file-symlink-p filename)
4357 (goto-char (search-backward "->" beg 'noerror)))
4358 (search-backward
4359 (if (zerop (length (file-name-nondirectory filename)))
4360 "."
4361 (file-name-nondirectory filename))
4362 beg 'noerror)
4363 (replace-match (file-relative-name filename) t))
4364
4365 (goto-char (point-max))))))
4366
4367 (defun tramp-handle-unhandled-file-name-directory (filename)
4368 "Like `unhandled-file-name-directory' for Tramp files."
4369 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4370 ;; for backward compatibility.
4371 (expand-file-name "~/"))
4372
4373 ;; Canonicalization of file names.
4374
4375 (defun tramp-handle-expand-file-name (name &optional dir)
4376 "Like `expand-file-name' for Tramp files.
4377 If the localname part of the given filename starts with \"/../\" then
4378 the result will be a local, non-Tramp, filename."
4379 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4380 (setq dir (or dir default-directory "/"))
4381 ;; Unless NAME is absolute, concat DIR and NAME.
4382 (unless (file-name-absolute-p name)
4383 (setq name (concat (file-name-as-directory dir) name)))
4384 ;; If NAME is not a Tramp file, run the real handler.
4385 (if (not (tramp-connectable-p name))
4386 (tramp-run-real-handler 'expand-file-name (list name nil))
4387 ;; Dissect NAME.
4388 (with-parsed-tramp-file-name name nil
4389 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4390 (setq localname (concat "~/" localname)))
4391 ;; Tilde expansion if necessary. This needs a shell which
4392 ;; groks tilde expansion! The function `tramp-find-shell' is
4393 ;; supposed to find such a shell on the remote host. Please
4394 ;; tell me about it when this doesn't work on your system.
4395 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4396 (let ((uname (match-string 1 localname))
4397 (fname (match-string 2 localname)))
4398 ;; We cannot simply apply "~/", because under sudo "~/" is
4399 ;; expanded to the local user home directory but to the
4400 ;; root home directory. On the other hand, using always
4401 ;; the default user name for tilde expansion is not
4402 ;; appropriate either, because ssh and companions might
4403 ;; use a user name from the config file.
4404 (when (and (string-equal uname "~")
4405 (string-match "\\`su\\(do\\)?\\'" method))
4406 (setq uname (concat uname user)))
4407 (setq uname
4408 (with-connection-property v uname
4409 (tramp-send-command
4410 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4411 (with-current-buffer (tramp-get-buffer v)
4412 (goto-char (point-min))
4413 (buffer-substring
4414 (point) (tramp-compat-line-end-position)))))
4415 (setq localname (concat uname fname))))
4416 ;; There might be a double slash, for example when "~/"
4417 ;; expands to "/". Remove this.
4418 (while (string-match "//" localname)
4419 (setq localname (replace-match "/" t t localname)))
4420 ;; No tilde characters in file name, do normal
4421 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4422 ;; `directory-sep-char' here for XEmacs on Windows, which would
4423 ;; otherwise use backslash. `default-directory' is bound,
4424 ;; because on Windows there would be problems with UNC shares or
4425 ;; Cygwin mounts.
4426 (let ((directory-sep-char ?/)
4427 (default-directory (tramp-compat-temporary-file-directory)))
4428 (tramp-make-tramp-file-name
4429 method user host
4430 (tramp-drop-volume-letter
4431 (tramp-run-real-handler
4432 'expand-file-name (list localname))))))))
4433
4434 (defun tramp-replace-environment-variables (filename)
4435 "Replace environment variables in FILENAME.
4436 Return the string with the replaced variables."
4437 (save-match-data
4438 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4439 ;; `$' is coded as `$$'.
4440 (when (and idx
4441 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4442 (getenv (match-string 1 filename)))
4443 (setq filename
4444 (replace-match
4445 (substitute-in-file-name (match-string 0 filename))
4446 t nil filename)))
4447 filename)))
4448
4449 (defun tramp-handle-substitute-in-file-name (filename)
4450 "Like `substitute-in-file-name' for Tramp files.
4451 \"//\" and \"/~\" substitute only in the local filename part.
4452 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4453 beginning of local filename are not substituted."
4454 ;; First, we must replace environment variables.
4455 (setq filename (tramp-replace-environment-variables filename))
4456 (with-parsed-tramp-file-name filename nil
4457 (if (equal tramp-syntax 'url)
4458 ;; We need to check localname only. The other parts cannot contain
4459 ;; "//" or "/~".
4460 (if (and (> (length localname) 1)
4461 (or (string-match "//" localname)
4462 (string-match "/~" localname 1)))
4463 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4464 (tramp-make-tramp-file-name
4465 (when method (substitute-in-file-name method))
4466 (when user (substitute-in-file-name user))
4467 (when host (substitute-in-file-name host))
4468 (when localname
4469 (tramp-run-real-handler
4470 'substitute-in-file-name (list localname)))))
4471 ;; Ignore in LOCALNAME everything before "//" or "/~".
4472 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4473 (setq filename
4474 (concat (file-remote-p filename)
4475 (replace-match "\\1" nil nil localname)))
4476 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4477 (when (string-match "~$" filename)
4478 (setq filename (concat filename "/"))))
4479 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4480
4481 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4482 ;; which calls corresponding functions (see minibuf.el).
4483 (when (fboundp 'minibuffer-electric-separator)
4484 (mapc
4485 (lambda (x)
4486 (eval
4487 `(defadvice ,x
4488 (around ,(intern (format "tramp-advice-%s" x)) activate)
4489 "Invoke `substitute-in-file-name' for Tramp files."
4490 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4491 (tramp-tramp-file-p (buffer-substring)))
4492 ;; We don't need to handle `last-input-event', because
4493 ;; due to the key map we know it must be ?/ or ?~.
4494 (let ((s (concat (buffer-substring (point-min) (point))
4495 (string last-command-char))))
4496 (delete-region (point-min) (point))
4497 (insert (substitute-in-file-name s))
4498 (setq ad-return-value last-command-char))
4499 ad-do-it)))
4500 (eval
4501 `(add-hook
4502 'tramp-unload-hook
4503 (lambda ()
4504 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4505 (ad-activate ',x)))))
4506
4507 '(minibuffer-electric-separator
4508 minibuffer-electric-tilde)))
4509
4510
4511 ;;; Remote commands:
4512
4513 (defun tramp-handle-executable-find (command)
4514 "Like `executable-find' for Tramp files."
4515 (with-parsed-tramp-file-name default-directory nil
4516 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4517
4518 (defun tramp-process-sentinel (proc event)
4519 "Flush file caches."
4520 (unless (memq (process-status proc) '(run open))
4521 (let ((vec (tramp-get-connection-property proc "vector" nil)))
4522 (when vec
4523 (tramp-message vec 5 "Sentinel called: `%s' `%s'" proc event)
4524 (tramp-flush-directory-property vec "")))))
4525
4526 ;; We use BUFFER also as connection buffer during setup. Because of
4527 ;; this, its original contents must be saved, and restored once
4528 ;; connection has been setup.
4529 (defun tramp-handle-start-file-process (name buffer program &rest args)
4530 "Like `start-file-process' for Tramp files."
4531 (with-parsed-tramp-file-name default-directory nil
4532 ;; When PROGRAM is nil, we just provide a tty.
4533 (let ((command
4534 (when (stringp program)
4535 (format "cd %s; exec %s"
4536 (tramp-shell-quote-argument localname)
4537 (mapconcat 'tramp-shell-quote-argument
4538 (cons program args) " "))))
4539 (tramp-process-connection-type
4540 (or (null program) tramp-process-connection-type))
4541 (bmp (and (buffer-live-p buffer) (buffer-modified-p buffer)))
4542 (name1 name)
4543 (i 0))
4544 (unwind-protect
4545 (save-excursion
4546 (save-restriction
4547 (unless buffer
4548 ;; BUFFER can be nil. We use a temporary buffer.
4549 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4550 (while (get-process name1)
4551 ;; NAME must be unique as process name.
4552 (setq i (1+ i)
4553 name1 (format "%s<%d>" name i)))
4554 (setq name name1)
4555 ;; Set the new process properties.
4556 (tramp-set-connection-property v "process-name" name)
4557 (tramp-set-connection-property v "process-buffer" buffer)
4558 ;; Activate narrowing in order to save BUFFER contents.
4559 ;; Clear also the modification time; otherwise we might
4560 ;; be interrupted by `verify-visited-file-modtime'.
4561 (with-current-buffer (tramp-get-connection-buffer v)
4562 (let ((buffer-undo-list t))
4563 (clear-visited-file-modtime)
4564 (narrow-to-region (point-max) (point-max))
4565 (if command
4566 ;; Send the command.
4567 (tramp-send-command v command nil t) ; nooutput
4568 ;; Check, whether a pty is associated.
4569 (tramp-maybe-open-connection v)
4570 (unless (process-get
4571 (tramp-get-connection-process v) 'remote-tty)
4572 (tramp-error
4573 v 'file-error
4574 "pty association is not supported for `%s'" name)))))
4575 (let ((p (tramp-get-connection-process v)))
4576 ;; Set sentinel and query flag for this process.
4577 (tramp-set-connection-property p "vector" v)
4578 (set-process-sentinel p 'tramp-process-sentinel)
4579 (tramp-set-process-query-on-exit-flag p t)
4580 ;; Return process.
4581 p)))
4582 ;; Save exit.
4583 (with-current-buffer (tramp-get-connection-buffer v)
4584 (if (string-match tramp-temp-buffer-name (buffer-name))
4585 (progn
4586 (set-process-buffer (tramp-get-connection-process v) nil)
4587 (kill-buffer (current-buffer)))
4588 (set-buffer-modified-p bmp)))
4589 (tramp-set-connection-property v "process-name" nil)
4590 (tramp-set-connection-property v "process-buffer" nil)))))
4591
4592 (defun tramp-handle-process-file
4593 (program &optional infile destination display &rest args)
4594 "Like `process-file' for Tramp files."
4595 ;; The implementation is not complete yet.
4596 (when (and (numberp destination) (zerop destination))
4597 (error "Implementation does not handle immediate return"))
4598
4599 (with-parsed-tramp-file-name default-directory nil
4600 (let (command input tmpinput stderr tmpstderr outbuf ret)
4601 ;; Compute command.
4602 (setq command (mapconcat 'tramp-shell-quote-argument
4603 (cons program args) " "))
4604 ;; Determine input.
4605 (if (null infile)
4606 (setq input "/dev/null")
4607 (setq infile (expand-file-name infile))
4608 (if (tramp-equal-remote default-directory infile)
4609 ;; INFILE is on the same remote host.
4610 (setq input (with-parsed-tramp-file-name infile nil localname))
4611 ;; INFILE must be copied to remote host.
4612 (setq input (tramp-make-tramp-temp-file v)
4613 tmpinput (tramp-make-tramp-file-name method user host input))
4614 (copy-file infile tmpinput t)))
4615 (when input (setq command (format "%s <%s" command input)))
4616
4617 ;; Determine output.
4618 (cond
4619 ;; Just a buffer.
4620 ((bufferp destination)
4621 (setq outbuf destination))
4622 ;; A buffer name.
4623 ((stringp destination)
4624 (setq outbuf (get-buffer-create destination)))
4625 ;; (REAL-DESTINATION ERROR-DESTINATION)
4626 ((consp destination)
4627 ;; output.
4628 (cond
4629 ((bufferp (car destination))
4630 (setq outbuf (car destination)))
4631 ((stringp (car destination))
4632 (setq outbuf (get-buffer-create (car destination))))
4633 ((car destination)
4634 (setq outbuf (current-buffer))))
4635 ;; stderr.
4636 (cond
4637 ((stringp (cadr destination))
4638 (setcar (cdr destination) (expand-file-name (cadr destination)))
4639 (if (tramp-equal-remote default-directory (cadr destination))
4640 ;; stderr is on the same remote host.
4641 (setq stderr (with-parsed-tramp-file-name
4642 (cadr destination) nil localname))
4643 ;; stderr must be copied to remote host. The temporary
4644 ;; file must be deleted after execution.
4645 (setq stderr (tramp-make-tramp-temp-file v)
4646 tmpstderr (tramp-make-tramp-file-name
4647 method user host stderr))))
4648 ;; stderr to be discarded.
4649 ((null (cadr destination))
4650 (setq stderr "/dev/null"))))
4651 ;; 't
4652 (destination
4653 (setq outbuf (current-buffer))))
4654 (when stderr (setq command (format "%s 2>%s" command stderr)))
4655
4656 ;; Send the command. It might not return in time, so we protect
4657 ;; it. Call it in a subshell, in order to preserve working
4658 ;; directory.
4659 (condition-case nil
4660 (unwind-protect
4661 (setq ret
4662 (tramp-send-command-and-check
4663 v (format "\\cd %s; %s"
4664 (tramp-shell-quote-argument localname)
4665 command)
4666 t t))
4667 ;; We should show the output anyway.
4668 (when outbuf
4669 (with-current-buffer outbuf
4670 (insert
4671 (with-current-buffer (tramp-get-connection-buffer v)
4672 (buffer-string))))
4673 (when display (display-buffer outbuf))))
4674 ;; When the user did interrupt, we should do it also. We use
4675 ;; return code -1 as marker.
4676 (quit
4677 (kill-buffer (tramp-get-connection-buffer v))
4678 (setq ret -1))
4679 ;; Handle errors.
4680 (error
4681 (kill-buffer (tramp-get-connection-buffer v))
4682 (setq ret 1)))
4683
4684 ;; Provide error file.
4685 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4686
4687 ;; Cleanup. We remove all file cache values for the connection,
4688 ;; because the remote process could have changed them.
4689 (when tmpinput (delete-file tmpinput))
4690
4691 ;; `process-file-side-effects' has been introduced with GNU
4692 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4693 ;; by `program'. If it doesn't exist, we assume its default
4694 ;; value 't'.
4695 (unless (and (boundp 'process-file-side-effects)
4696 (not (symbol-value 'process-file-side-effects)))
4697 (tramp-flush-directory-property v ""))
4698
4699 ;; Return exit status.
4700 (if (equal ret -1)
4701 (keyboard-quit)
4702 ret))))
4703
4704 (defun tramp-local-call-process
4705 (program &optional infile destination display &rest args)
4706 "Calls `call-process' on the local host.
4707 This is needed because for some Emacs flavors Tramp has
4708 defadviced `call-process' to behave like `process-file'. The
4709 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4710 (let ((default-directory
4711 (if (file-remote-p default-directory)
4712 (tramp-compat-temporary-file-directory)
4713 default-directory)))
4714 (if (executable-find program)
4715 (apply 'call-process program infile destination display args)
4716 1)))
4717
4718 (defun tramp-handle-call-process-region
4719 (start end program &optional delete buffer display &rest args)
4720 "Like `call-process-region' for Tramp files."
4721 (let ((tmpfile (tramp-compat-make-temp-file "")))
4722 (write-region start end tmpfile)
4723 (when delete (delete-region start end))
4724 (unwind-protect
4725 (apply 'call-process program tmpfile buffer display args)
4726 (delete-file tmpfile))))
4727
4728 (defun tramp-handle-shell-command
4729 (command &optional output-buffer error-buffer)
4730 "Like `shell-command' for Tramp files."
4731 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4732 ;; We cannot use `shell-file-name' and `shell-command-switch',
4733 ;; they are variables of the local host.
4734 (args (list
4735 (tramp-get-method-parameter
4736 (tramp-file-name-method
4737 (tramp-dissect-file-name default-directory))
4738 'tramp-remote-sh)
4739 "-c" (substring command 0 asynchronous)))
4740 current-buffer-p
4741 (output-buffer
4742 (cond
4743 ((bufferp output-buffer) output-buffer)
4744 ((stringp output-buffer) (get-buffer-create output-buffer))
4745 (output-buffer
4746 (setq current-buffer-p t)
4747 (current-buffer))
4748 (t (get-buffer-create
4749 (if asynchronous
4750 "*Async Shell Command*"
4751 "*Shell Command Output*")))))
4752 (error-buffer
4753 (cond
4754 ((bufferp error-buffer) error-buffer)
4755 ((stringp error-buffer) (get-buffer-create error-buffer))))
4756 (buffer
4757 (if (and (not asynchronous) error-buffer)
4758 (with-parsed-tramp-file-name default-directory nil
4759 (list output-buffer (tramp-make-tramp-temp-file v)))
4760 output-buffer))
4761 (p (get-buffer-process output-buffer)))
4762
4763 ;; Check whether there is another process running. Tramp does not
4764 ;; support 2 (asynchronous) processes in parallel.
4765 (when p
4766 (if (yes-or-no-p "A command is running. Kill it? ")
4767 (condition-case nil
4768 (kill-process p)
4769 (error nil))
4770 (error "Shell command in progress")))
4771
4772 (if current-buffer-p
4773 (progn
4774 (barf-if-buffer-read-only)
4775 (push-mark nil t))
4776 (with-current-buffer output-buffer
4777 (setq buffer-read-only nil)
4778 (erase-buffer)))
4779
4780 (if (and (not current-buffer-p) (integerp asynchronous))
4781 (prog1
4782 ;; Run the process.
4783 (apply 'start-file-process "*Async Shell*" buffer args)
4784 ;; Display output.
4785 (pop-to-buffer output-buffer)
4786 (setq mode-line-process '(":%s"))
4787 (require 'shell) (shell-mode))
4788
4789 (prog1
4790 ;; Run the process.
4791 (apply 'process-file (car args) nil buffer nil (cdr args))
4792 ;; Insert error messages if they were separated.
4793 (when (listp buffer)
4794 (with-current-buffer error-buffer
4795 (insert-file-contents (cadr buffer)))
4796 (delete-file (cadr buffer)))
4797 (if current-buffer-p
4798 ;; This is like exchange-point-and-mark, but doesn't
4799 ;; activate the mark. It is cleaner to avoid activation,
4800 ;; even though the command loop would deactivate the mark
4801 ;; because we inserted text.
4802 (goto-char (prog1 (mark t)
4803 (set-marker (mark-marker) (point)
4804 (current-buffer))))
4805 ;; There's some output, display it.
4806 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4807 (if (functionp 'display-message-or-buffer)
4808 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
4809 (pop-to-buffer output-buffer))))))))
4810
4811 ;; File Editing.
4812
4813 (defvar tramp-handle-file-local-copy-hook nil
4814 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4815
4816 (defun tramp-handle-file-local-copy (filename)
4817 "Like `file-local-copy' for Tramp files."
4818
4819 (with-parsed-tramp-file-name filename nil
4820 (unless (file-exists-p filename)
4821 (tramp-error
4822 v 'file-error
4823 "Cannot make local copy of non-existing file `%s'" filename))
4824
4825 (let* ((size (nth 7 (file-attributes filename)))
4826 (rem-enc (tramp-get-inline-coding v "remote-encoding" size))
4827 (loc-dec (tramp-get-inline-coding v "local-decoding" size))
4828 (tmpfile (tramp-compat-make-temp-file filename)))
4829
4830 (condition-case err
4831 (cond
4832 ;; `copy-file' handles direct copy and out-of-band methods.
4833 ((or (tramp-local-host-p v)
4834 (tramp-method-out-of-band-p v size))
4835 (copy-file filename tmpfile t t))
4836
4837 ;; Use inline encoding for file transfer.
4838 (rem-enc
4839 (save-excursion
4840 (with-progress-reporter
4841 v 3 (format "Encoding remote file %s" filename)
4842 (tramp-barf-unless-okay
4843 v (format rem-enc (tramp-shell-quote-argument localname))
4844 "Encoding remote file failed"))
4845
4846 (if (functionp loc-dec)
4847 ;; If local decoding is a function, we call it. We
4848 ;; must disable multibyte, because
4849 ;; `uudecode-decode-region' doesn't handle it
4850 ;; correctly.
4851 (with-temp-buffer
4852 (set-buffer-multibyte nil)
4853 (insert-buffer-substring (tramp-get-buffer v))
4854 (with-progress-reporter
4855 v 3 (format "Decoding remote file %s with function %s"
4856 filename loc-dec)
4857 (funcall loc-dec (point-min) (point-max))
4858 ;; Unset `file-name-handler-alist'. Otherwise,
4859 ;; epa-file gets confused.
4860 (let (file-name-handler-alist
4861 (coding-system-for-write 'binary))
4862 (write-region (point-min) (point-max) tmpfile))))
4863
4864 ;; If tramp-decoding-function is not defined for this
4865 ;; method, we invoke tramp-decoding-command instead.
4866 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4867 ;; Unset `file-name-handler-alist'. Otherwise,
4868 ;; epa-file gets confused.
4869 (let (file-name-handler-alist
4870 (coding-system-for-write 'binary))
4871 (write-region (point-min) (point-max) tmpfile2))
4872 (with-progress-reporter
4873 v 3 (format "Decoding remote file %s with command %s"
4874 filename loc-dec)
4875 (unwind-protect
4876 (tramp-call-local-coding-command
4877 loc-dec tmpfile2 tmpfile)
4878 (delete-file tmpfile2)))))
4879
4880 ;; Set proper permissions.
4881 (set-file-modes tmpfile (tramp-default-file-modes filename))
4882 ;; Set local user ownership.
4883 (tramp-set-file-uid-gid tmpfile)))
4884
4885 ;; Oops, I don't know what to do.
4886 (t (tramp-error
4887 v 'file-error "Wrong method specification for `%s'" method)))
4888
4889 ;; Error handling.
4890 ((error quit)
4891 (delete-file tmpfile)
4892 (signal (car err) (cdr err))))
4893
4894 (run-hooks 'tramp-handle-file-local-copy-hook)
4895 tmpfile)))
4896
4897 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4898 "Like `file-remote-p' for Tramp files."
4899 (let ((tramp-verbose 3))
4900 (when (tramp-tramp-file-p filename)
4901 (let* ((v (tramp-dissect-file-name filename))
4902 (p (tramp-get-connection-process v))
4903 (c (and p (processp p) (memq (process-status p) '(run open)))))
4904 ;; We expand the file name only, if there is already a connection.
4905 (with-parsed-tramp-file-name
4906 (if c (expand-file-name filename) filename) nil
4907 (and (or (not connected) c)
4908 (cond
4909 ((eq identification 'method) method)
4910 ((eq identification 'user) user)
4911 ((eq identification 'host) host)
4912 ((eq identification 'localname) localname)
4913 (t (tramp-make-tramp-file-name method user host "")))))))))
4914
4915 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4916 "Like `find-operation-coding-system' for Tramp filenames.
4917 Tramp's `insert-file-contents' and `write-region' work over
4918 temporary file names. If `file-coding-system-alist' contains an
4919 expression, which matches more than the file name suffix, the
4920 coding system might not be determined. This function repairs it."
4921 (let (result)
4922 (dolist (elt file-coding-system-alist result)
4923 (when (and (consp elt) (string-match (car elt) filename))
4924 ;; We found a matching entry in `file-coding-system-alist'.
4925 ;; So we add a similar entry, but with the temporary file name
4926 ;; as regexp.
4927 (add-to-list
4928 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4929
4930 (defun tramp-handle-insert-file-contents
4931 (filename &optional visit beg end replace)
4932 "Like `insert-file-contents' for Tramp files."
4933 (barf-if-buffer-read-only)
4934 (setq filename (expand-file-name filename))
4935 (let (result local-copy remote-copy)
4936 (with-parsed-tramp-file-name filename nil
4937 (unwind-protect
4938 (if (not (file-exists-p filename))
4939 ;; We don't raise a Tramp error, because it might be
4940 ;; suppressed, like in `find-file-noselect-1'.
4941 (signal 'file-error
4942 (list "File not found on remote host" filename))
4943
4944 (if (and (tramp-local-host-p v)
4945 (let (file-name-handler-alist)
4946 (file-readable-p localname)))
4947 ;; Short track: if we are on the local host, we can
4948 ;; run directly.
4949 (setq result
4950 (tramp-run-real-handler
4951 'insert-file-contents
4952 (list localname visit beg end replace)))
4953
4954 ;; When we shall insert only a part of the file, we copy
4955 ;; this part.
4956 (when (or beg end)
4957 (setq remote-copy (tramp-make-tramp-temp-file v))
4958 (tramp-send-command
4959 v
4960 (cond
4961 ((and beg end)
4962 (format "tail -c +%d %s | head -c +%d >%s"
4963 (1+ beg) (tramp-shell-quote-argument localname)
4964 (- end beg) remote-copy))
4965 (beg
4966 (format "tail -c +%d %s >%s"
4967 (1+ beg) (tramp-shell-quote-argument localname)
4968 remote-copy))
4969 (end
4970 (format "head -c +%d %s >%s"
4971 (1+ end) (tramp-shell-quote-argument localname)
4972 remote-copy)))))
4973
4974 ;; `insert-file-contents-literally' takes care to avoid
4975 ;; calling jka-compr. By let-binding
4976 ;; `inhibit-file-name-operation', we propagate that care
4977 ;; to the `file-local-copy' operation.
4978 (setq local-copy
4979 (let ((inhibit-file-name-operation
4980 (when (eq inhibit-file-name-operation
4981 'insert-file-contents)
4982 'file-local-copy)))
4983 (cond
4984 ((stringp remote-copy)
4985 (file-local-copy
4986 (tramp-make-tramp-file-name
4987 method user host remote-copy)))
4988 ((stringp tramp-temp-buffer-file-name)
4989 (copy-file filename tramp-temp-buffer-file-name 'ok)
4990 tramp-temp-buffer-file-name)
4991 (t (file-local-copy filename)))))
4992
4993 ;; When the file is not readable for the owner, it
4994 ;; cannot be inserted, even it is redable for the group
4995 ;; or for everybody.
4996 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4997
4998 (when (and (null remote-copy)
4999 (tramp-get-method-parameter
5000 method 'tramp-copy-keep-tmpfile))
5001 ;; We keep the local file for performance reasons,
5002 ;; useful for "rsync".
5003 (setq tramp-temp-buffer-file-name local-copy)
5004 (put 'tramp-temp-buffer-file-name 'permanent-local t))
5005
5006 (with-progress-reporter
5007 v 3 (format "Inserting local temp file `%s'" local-copy)
5008 ;; We must ensure that `file-coding-system-alist'
5009 ;; matches `local-copy'.
5010 (let ((file-coding-system-alist
5011 (tramp-find-file-name-coding-system-alist
5012 filename local-copy)))
5013 (setq result
5014 (insert-file-contents
5015 local-copy nil nil nil replace))))))
5016
5017 ;; Save exit.
5018 (progn
5019 (when visit
5020 (setq buffer-file-name filename)
5021 (setq buffer-read-only (not (file-writable-p filename)))
5022 (set-visited-file-modtime)
5023 (set-buffer-modified-p nil)
5024 ;; For root, preserve owner and group when editing files.
5025 (when (string-equal (file-remote-p filename 'user) "root")
5026 (set (make-local-variable 'backup-by-copying-when-mismatch) t)))
5027 (when (and (stringp local-copy)
5028 (or remote-copy (null tramp-temp-buffer-file-name)))
5029 (delete-file local-copy))
5030 (when (stringp remote-copy)
5031 (delete-file
5032 (tramp-make-tramp-file-name method user host remote-copy))))))
5033
5034 ;; Result.
5035 (list (expand-file-name filename)
5036 (cadr result))))
5037
5038 ;; This is needed for XEmacs only. Code stolen from files.el.
5039 (defun tramp-handle-insert-file-contents-literally
5040 (filename &optional visit beg end replace)
5041 "Like `insert-file-contents-literally' for Tramp files."
5042 (let ((format-alist nil)
5043 (after-insert-file-functions nil)
5044 (coding-system-for-read 'no-conversion)
5045 (coding-system-for-write 'no-conversion)
5046 (find-buffer-file-type-function
5047 (if (fboundp 'find-buffer-file-type)
5048 (symbol-function 'find-buffer-file-type)
5049 nil))
5050 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
5051 (inhibit-file-name-operation 'insert-file-contents))
5052 (unwind-protect
5053 (progn
5054 (fset 'find-buffer-file-type (lambda (filename) t))
5055 (insert-file-contents filename visit beg end replace))
5056 ;; Save exit.
5057 (if find-buffer-file-type-function
5058 (fset 'find-buffer-file-type find-buffer-file-type-function)
5059 (fmakunbound 'find-buffer-file-type)))))
5060
5061 (defun tramp-handle-find-backup-file-name (filename)
5062 "Like `find-backup-file-name' for Tramp files."
5063 (with-parsed-tramp-file-name filename nil
5064 ;; We set both variables. It doesn't matter whether it is
5065 ;; Emacs or XEmacs.
5066 (let ((backup-directory-alist
5067 ;; Emacs case.
5068 (when (boundp 'backup-directory-alist)
5069 (if (symbol-value 'tramp-backup-directory-alist)
5070 (mapcar
5071 (lambda (x)
5072 (cons
5073 (car x)
5074 (if (and (stringp (cdr x))
5075 (file-name-absolute-p (cdr x))
5076 (not (tramp-file-name-p (cdr x))))
5077 (tramp-make-tramp-file-name method user host (cdr x))
5078 (cdr x))))
5079 (symbol-value 'tramp-backup-directory-alist))
5080 (symbol-value 'backup-directory-alist))))
5081
5082 (bkup-backup-directory-info
5083 ;; XEmacs case.
5084 (when (boundp 'bkup-backup-directory-info)
5085 (if (symbol-value 'tramp-bkup-backup-directory-info)
5086 (mapcar
5087 (lambda (x)
5088 (nconc
5089 (list (car x))
5090 (list
5091 (if (and (stringp (car (cdr x)))
5092 (file-name-absolute-p (car (cdr x)))
5093 (not (tramp-file-name-p (car (cdr x)))))
5094 (tramp-make-tramp-file-name
5095 method user host (car (cdr x)))
5096 (car (cdr x))))
5097 (cdr (cdr x))))
5098 (symbol-value 'tramp-bkup-backup-directory-info))
5099 (symbol-value 'bkup-backup-directory-info)))))
5100
5101 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
5102
5103 (defun tramp-handle-make-auto-save-file-name ()
5104 "Like `make-auto-save-file-name' for Tramp files.
5105 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
5106 (let ((tramp-auto-save-directory tramp-auto-save-directory)
5107 (buffer-file-name
5108 (tramp-subst-strs-in-string
5109 '(("_" . "|")
5110 ("/" . "_a")
5111 (":" . "_b")
5112 ("|" . "__")
5113 ("[" . "_l")
5114 ("]" . "_r"))
5115 (buffer-file-name))))
5116 ;; File name must be unique. This is ensured with Emacs 22 (see
5117 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
5118 ;; all other cases we must do it ourselves.
5119 (when (boundp 'auto-save-file-name-transforms)
5120 (mapc
5121 (lambda (x)
5122 (when (and (string-match (car x) buffer-file-name)
5123 (not (car (cddr x))))
5124 (setq tramp-auto-save-directory
5125 (or tramp-auto-save-directory
5126 (tramp-compat-temporary-file-directory)))))
5127 (symbol-value 'auto-save-file-name-transforms)))
5128 ;; Create directory.
5129 (when tramp-auto-save-directory
5130 (setq buffer-file-name
5131 (expand-file-name buffer-file-name tramp-auto-save-directory))
5132 (unless (file-exists-p tramp-auto-save-directory)
5133 (make-directory tramp-auto-save-directory t)))
5134 ;; Run plain `make-auto-save-file-name'. There might be an advice when
5135 ;; it is not a magic file name operation (since Emacs 22).
5136 ;; We must deactivate it temporarily.
5137 (if (not (ad-is-active 'make-auto-save-file-name))
5138 (tramp-run-real-handler 'make-auto-save-file-name nil)
5139 ;; else
5140 (ad-deactivate 'make-auto-save-file-name)
5141 (prog1
5142 (tramp-run-real-handler 'make-auto-save-file-name nil)
5143 (ad-activate 'make-auto-save-file-name)))))
5144
5145 (defvar tramp-handle-write-region-hook nil
5146 "Normal hook to be run at the end of `tramp-handle-write-region'.")
5147
5148 ;; CCC grok LOCKNAME
5149 (defun tramp-handle-write-region
5150 (start end filename &optional append visit lockname confirm)
5151 "Like `write-region' for Tramp files."
5152 (setq filename (expand-file-name filename))
5153 (with-parsed-tramp-file-name filename nil
5154 ;; Following part commented out because we don't know what to do about
5155 ;; file locking, and it does not appear to be a problem to ignore it.
5156 ;; Ange-ftp ignores it, too.
5157 ;; (when (and lockname (stringp lockname))
5158 ;; (setq lockname (expand-file-name lockname)))
5159 ;; (unless (or (eq lockname nil)
5160 ;; (string= lockname filename))
5161 ;; (error
5162 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
5163
5164 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
5165 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
5166 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
5167 (tramp-error v 'file-error "File not overwritten")))
5168
5169 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
5170 (tramp-get-remote-uid v 'integer)))
5171 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
5172 (tramp-get-remote-gid v 'integer))))
5173
5174 (if (and (tramp-local-host-p v)
5175 ;; `file-writable-p' calls `file-expand-file-name'. We
5176 ;; cannot use `tramp-run-real-handler' therefore.
5177 (let (file-name-handler-alist)
5178 (and
5179 (file-writable-p (file-name-directory localname))
5180 (or (file-directory-p localname)
5181 (file-writable-p localname)))))
5182 ;; Short track: if we are on the local host, we can run directly.
5183 (tramp-run-real-handler
5184 'write-region
5185 (list start end localname append 'no-message lockname confirm))
5186
5187 (let ((modes (save-excursion (tramp-default-file-modes filename)))
5188 ;; We use this to save the value of
5189 ;; `last-coding-system-used' after writing the tmp
5190 ;; file. At the end of the function, we set
5191 ;; `last-coding-system-used' to this saved value. This
5192 ;; way, any intermediary coding systems used while
5193 ;; talking to the remote shell or suchlike won't hose
5194 ;; this variable. This approach was snarfed from
5195 ;; ange-ftp.el.
5196 coding-system-used
5197 ;; Write region into a tmp file. This isn't really
5198 ;; needed if we use an encoding function, but currently
5199 ;; we use it always because this makes the logic
5200 ;; simpler.
5201 (tmpfile (or tramp-temp-buffer-file-name
5202 (tramp-compat-make-temp-file filename))))
5203
5204 ;; If `append' is non-nil, we copy the file locally, and let
5205 ;; the native `write-region' implementation do the job.
5206 (when append (copy-file filename tmpfile 'ok))
5207
5208 ;; We say `no-message' here because we don't want the
5209 ;; visited file modtime data to be clobbered from the temp
5210 ;; file. We call `set-visited-file-modtime' ourselves later
5211 ;; on. We must ensure that `file-coding-system-alist'
5212 ;; matches `tmpfile'.
5213 (let (file-name-handler-alist
5214 (file-coding-system-alist
5215 (tramp-find-file-name-coding-system-alist filename tmpfile)))
5216 (condition-case err
5217 (tramp-run-real-handler
5218 'write-region
5219 (list start end tmpfile append 'no-message lockname confirm))
5220 ((error quit)
5221 (setq tramp-temp-buffer-file-name nil)
5222 (delete-file tmpfile)
5223 (signal (car err) (cdr err))))
5224
5225 ;; Now, `last-coding-system-used' has the right value. Remember it.
5226 (when (boundp 'last-coding-system-used)
5227 (setq coding-system-used
5228 (symbol-value 'last-coding-system-used))))
5229
5230 ;; The permissions of the temporary file should be set. If
5231 ;; filename does not exist (eq modes nil) it has been
5232 ;; renamed to the backup file. This case `save-buffer'
5233 ;; handles permissions.
5234 ;; Ensure, that it is still readable.
5235 (when modes
5236 (set-file-modes
5237 tmpfile (logior (or modes 0) (tramp-octal-to-decimal "0400"))))
5238
5239 ;; This is a bit lengthy due to the different methods
5240 ;; possible for file transfer. First, we check whether the
5241 ;; method uses an rcp program. If so, we call it.
5242 ;; Otherwise, both encoding and decoding command must be
5243 ;; specified. However, if the method _also_ specifies an
5244 ;; encoding function, then that is used for encoding the
5245 ;; contents of the tmp file.
5246 (let* ((size (nth 7 (file-attributes tmpfile)))
5247 (rem-dec (tramp-get-inline-coding v "remote-decoding" size))
5248 (loc-enc (tramp-get-inline-coding v "local-encoding" size)))
5249 (cond
5250 ;; `copy-file' handles direct copy and out-of-band methods.
5251 ((or (tramp-local-host-p v)
5252 (tramp-method-out-of-band-p v size))
5253 (if (and (not (stringp start))
5254 (= (or end (point-max)) (point-max))
5255 (= (or start (point-min)) (point-min))
5256 (tramp-get-method-parameter
5257 method 'tramp-copy-keep-tmpfile))
5258 (progn
5259 (setq tramp-temp-buffer-file-name tmpfile)
5260 (condition-case err
5261 ;; We keep the local file for performance
5262 ;; reasons, useful for "rsync".
5263 (copy-file tmpfile filename t)
5264 ((error quit)
5265 (setq tramp-temp-buffer-file-name nil)
5266 (delete-file tmpfile)
5267 (signal (car err) (cdr err)))))
5268 (setq tramp-temp-buffer-file-name nil)
5269 ;; Don't rename, in order to keep context in SELinux.
5270 (unwind-protect
5271 (copy-file tmpfile filename t)
5272 (delete-file tmpfile))))
5273
5274 ;; Use inline file transfer.
5275 (rem-dec
5276 ;; Encode tmpfile.
5277 (unwind-protect
5278 (with-temp-buffer
5279 (set-buffer-multibyte nil)
5280 ;; Use encoding function or command.
5281 (if (functionp loc-enc)
5282 (with-progress-reporter
5283 v 3 (format "Encoding region using function `%s'"
5284 loc-enc)
5285 (let ((coding-system-for-read 'binary))
5286 (insert-file-contents-literally tmpfile))
5287 ;; The following `let' is a workaround for the
5288 ;; base64.el that comes with pgnus-0.84. If
5289 ;; both of the following conditions are
5290 ;; satisfied, it tries to write to a local
5291 ;; file in default-directory, but at this
5292 ;; point, default-directory is remote.
5293 ;; (`call-process-region' can't write to
5294 ;; remote files, it seems.) The file in
5295 ;; question is a tmp file anyway.
5296 (let ((default-directory
5297 (tramp-compat-temporary-file-directory)))
5298 (funcall loc-enc (point-min) (point-max))))
5299
5300 (with-progress-reporter
5301 v 3 (format "Encoding region using command `%s'"
5302 loc-enc)
5303 (unless (zerop (tramp-call-local-coding-command
5304 loc-enc tmpfile t))
5305 (tramp-error
5306 v 'file-error
5307 (concat "Cannot write to `%s', "
5308 "local encoding command `%s' failed")
5309 filename loc-enc))))
5310
5311 ;; Send buffer into remote decoding command which
5312 ;; writes to remote file. Because this happens on
5313 ;; the remote host, we cannot use the function.
5314 (with-progress-reporter
5315 v 3
5316 (format "Decoding region into remote file %s" filename)
5317 (goto-char (point-max))
5318 (unless (bolp) (newline))
5319 (tramp-send-command
5320 v
5321 (format
5322 (concat rem-dec " <<'EOF'\n%sEOF")
5323 (tramp-shell-quote-argument localname)
5324 (buffer-string)))
5325 (tramp-barf-unless-okay
5326 v nil
5327 "Couldn't write region to `%s', decode using `%s' failed"
5328 filename rem-dec)
5329 ;; When `file-precious-flag' is set, the region is
5330 ;; written to a temporary file. Check that the
5331 ;; checksum is equal to that from the local tmpfile.
5332 (when file-precious-flag
5333 (erase-buffer)
5334 (and
5335 ;; cksum runs locally, if possible.
5336 (zerop (tramp-local-call-process "cksum" tmpfile t))
5337 ;; cksum runs remotely.
5338 (zerop
5339 (tramp-send-command-and-check
5340 v
5341 (format
5342 "cksum <%s"
5343 (tramp-shell-quote-argument localname))))
5344 ;; ... they are different.
5345 (not
5346 (string-equal
5347 (buffer-string)
5348 (with-current-buffer (tramp-get-buffer v)
5349 (buffer-string))))
5350 (tramp-error
5351 v 'file-error
5352 (concat "Couldn't write region to `%s',"
5353 " decode using `%s' failed")
5354 filename rem-dec)))))
5355
5356 ;; Save exit.
5357 (delete-file tmpfile)))
5358
5359 ;; That's not expected.
5360 (t
5361 (tramp-error
5362 v 'file-error
5363 (concat "Method `%s' should specify both encoding and "
5364 "decoding command or an rcp program")
5365 method))))
5366
5367 ;; Make `last-coding-system-used' have the right value.
5368 (when coding-system-used
5369 (set 'last-coding-system-used coding-system-used))))
5370
5371 (tramp-flush-file-property v (file-name-directory localname))
5372 (tramp-flush-file-property v localname)
5373
5374 ;; We must protect `last-coding-system-used', now we have set it
5375 ;; to its correct value.
5376 (let (last-coding-system-used (need-chown t))
5377 ;; Set file modification time.
5378 (when (or (eq visit t) (stringp visit))
5379 (let ((file-attr (file-attributes filename)))
5380 (set-visited-file-modtime
5381 ;; We must pass modtime explicitely, because filename can
5382 ;; be different from (buffer-file-name), f.e. if
5383 ;; `file-precious-flag' is set.
5384 (nth 5 file-attr))
5385 (when (and (eq (nth 2 file-attr) uid)
5386 (eq (nth 3 file-attr) gid))
5387 (setq need-chown nil))))
5388
5389 ;; Set the ownership.
5390 (when need-chown
5391 (tramp-set-file-uid-gid filename uid gid))
5392 (when (or (eq visit t) (null visit) (stringp visit))
5393 (tramp-message v 0 "Wrote %s" filename))
5394 (run-hooks 'tramp-handle-write-region-hook)))))
5395
5396 (defvar tramp-vc-registered-file-names nil
5397 "List used to collect file names, which are checked during `vc-registered'.")
5398
5399 ;; VC backends check for the existence of various different special
5400 ;; files. This is very time consuming, because every single check
5401 ;; requires a remote command (the file cache must be invalidated).
5402 ;; Therefore, we apply a kind of optimization. We install the file
5403 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5404 ;; remembers all file names for which `file-exists-p' or
5405 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5406 ;; is performed. Afterwards, a script is applied for all collected
5407 ;; file names, using just one remote command. The result of this
5408 ;; script is used to fill the file cache with actual values. Now we
5409 ;; can reset the file name handlers, and we make a second run of
5410 ;; `vc-registered', which returns the expected result without sending
5411 ;; any other remote command.
5412 (defun tramp-handle-vc-registered (file)
5413 "Like `vc-registered' for Tramp files."
5414 (with-temp-message ""
5415 (with-parsed-tramp-file-name file nil
5416 (with-progress-reporter
5417 v 3 (format "Checking `vc-registered' for %s" file)
5418
5419 ;; There could be new files, created by the vc backend. We
5420 ;; cannot reuse the old cache entries, therefore.
5421 (let (tramp-vc-registered-file-names
5422 (tramp-cache-inhibit-cache (current-time))
5423 (file-name-handler-alist
5424 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5425
5426 ;; Here we collect only file names, which need an operation.
5427 (tramp-run-real-handler 'vc-registered (list file))
5428 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5429
5430 ;; Send just one command, in order to fill the cache.
5431 (when tramp-vc-registered-file-names
5432 (tramp-maybe-send-script
5433 v
5434 (format tramp-vc-registered-read-file-names
5435 (tramp-get-file-exists-command v)
5436 (format "%s -r" (tramp-get-test-command v)))
5437 "tramp_vc_registered_read_file_names")
5438
5439 (dolist
5440 (elt
5441 (tramp-send-command-and-read
5442 v
5443 (format
5444 "tramp_vc_registered_read_file_names <<'EOF'\n%s\nEOF\n"
5445 (mapconcat 'tramp-shell-quote-argument
5446 tramp-vc-registered-file-names
5447 "\n"))))
5448
5449 (tramp-set-file-property
5450 v (car elt) (cadr elt) (cadr (cdr elt))))))
5451
5452 ;; Second run. Now all `file-exists-p' or `file-readable-p'
5453 ;; calls shall be answered from the file cache. We unset
5454 ;; `process-file-side-effects' in order to keep the cache when
5455 ;; `process-file' calls appear.
5456 (let (process-file-side-effects)
5457 (tramp-run-real-handler 'vc-registered (list file)))))))
5458
5459 ;;;###autoload
5460 (progn (defun tramp-run-real-handler (operation args)
5461 "Invoke normal file name handler for OPERATION.
5462 First arg specifies the OPERATION, second arg is a list of arguments to
5463 pass to the OPERATION."
5464 (let* ((inhibit-file-name-handlers
5465 `(tramp-file-name-handler
5466 tramp-vc-file-name-handler
5467 tramp-completion-file-name-handler
5468 cygwin-mount-name-hook-function
5469 cygwin-mount-map-drive-hook-function
5470 .
5471 ,(and (eq inhibit-file-name-operation operation)
5472 inhibit-file-name-handlers)))
5473 (inhibit-file-name-operation operation))
5474 (apply operation args))))
5475
5476 ;;;###autoload
5477 (progn (defun tramp-completion-run-real-handler (operation args)
5478 "Invoke `tramp-file-name-handler' for OPERATION.
5479 First arg specifies the OPERATION, second arg is a list of arguments to
5480 pass to the OPERATION."
5481 (let* ((inhibit-file-name-handlers
5482 `(tramp-completion-file-name-handler
5483 cygwin-mount-name-hook-function
5484 cygwin-mount-map-drive-hook-function
5485 .
5486 ,(and (eq inhibit-file-name-operation operation)
5487 inhibit-file-name-handlers)))
5488 (inhibit-file-name-operation operation))
5489 (apply operation args))))
5490
5491 ;; We handle here all file primitives. Most of them have the file
5492 ;; name as first parameter; nevertheless we check for them explicitly
5493 ;; in order to be signaled if a new primitive appears. This
5494 ;; scenario is needed because there isn't a way to decide by
5495 ;; syntactical means whether a foreign method must be called. It would
5496 ;; ease the life if `file-name-handler-alist' would support a decision
5497 ;; function as well but regexp only.
5498 (defun tramp-file-name-for-operation (operation &rest args)
5499 "Return file name related to OPERATION file primitive.
5500 ARGS are the arguments OPERATION has been called with."
5501 (cond
5502 ;; FILE resp DIRECTORY.
5503 ((member operation
5504 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5505 'delete-file 'diff-latest-backup-file 'directory-file-name
5506 'directory-files 'directory-files-and-attributes
5507 'dired-compress-file 'dired-uncache
5508 'file-accessible-directory-p 'file-attributes
5509 'file-directory-p 'file-executable-p 'file-exists-p
5510 'file-local-copy 'file-remote-p 'file-modes
5511 'file-name-as-directory 'file-name-directory
5512 'file-name-nondirectory 'file-name-sans-versions
5513 'file-ownership-preserved-p 'file-readable-p
5514 'file-regular-p 'file-symlink-p 'file-truename
5515 'file-writable-p 'find-backup-file-name 'find-file-noselect
5516 'get-file-buffer 'insert-directory 'insert-file-contents
5517 'load 'make-directory 'make-directory-internal
5518 'set-file-modes 'substitute-in-file-name
5519 'unhandled-file-name-directory 'vc-registered
5520 ;; Emacs 22+ only.
5521 'set-file-times
5522 ;; Emacs 24+ only.
5523 'file-selinux-context 'set-file-selinux-context
5524 ;; XEmacs only.
5525 'abbreviate-file-name 'create-file-buffer
5526 'dired-file-modtime 'dired-make-compressed-filename
5527 'dired-recursive-delete-directory 'dired-set-file-modtime
5528 'dired-shell-unhandle-file-name 'dired-uucode-file
5529 'insert-file-contents-literally 'make-temp-name 'recover-file
5530 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5531 (if (file-name-absolute-p (nth 0 args))
5532 (nth 0 args)
5533 (expand-file-name (nth 0 args))))
5534 ;; FILE DIRECTORY resp FILE1 FILE2.
5535 ((member operation
5536 (list 'add-name-to-file 'copy-file 'expand-file-name
5537 'file-name-all-completions 'file-name-completion
5538 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5539 ;; Emacs 23+ only.
5540 'copy-directory
5541 ;; XEmacs only.
5542 'dired-make-relative-symlink
5543 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5544 (save-match-data
5545 (cond
5546 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5547 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5548 (t (buffer-file-name (current-buffer))))))
5549 ;; START END FILE.
5550 ((eq operation 'write-region)
5551 (nth 2 args))
5552 ;; BUFFER.
5553 ((member operation
5554 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5555 ;; Emacs 22+ only.
5556 'make-auto-save-file-name
5557 ;; XEmacs only.
5558 'backup-buffer))
5559 (buffer-file-name
5560 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5561 ;; COMMAND.
5562 ((member operation
5563 (list ;; not in Emacs 23+.
5564 'dired-call-process
5565 ;; Emacs only.
5566 'shell-command
5567 ;; Emacs 22+ only.
5568 'process-file
5569 ;; Emacs 23+ only.
5570 'start-file-process
5571 ;; XEmacs only.
5572 'dired-print-file 'dired-shell-call-process
5573 ;; nowhere yet.
5574 'executable-find 'start-process
5575 'call-process 'call-process-region))
5576 default-directory)
5577 ;; Unknown file primitive.
5578 (t (error "unknown file I/O primitive: %s" operation))))
5579
5580 (defun tramp-find-foreign-file-name-handler (filename)
5581 "Return foreign file name handler if exists."
5582 (when (tramp-tramp-file-p filename)
5583 (let ((v (tramp-dissect-file-name filename t))
5584 (handler tramp-foreign-file-name-handler-alist)
5585 elt res)
5586 ;; When we are not fully sure that filename completion is safe,
5587 ;; we should not return a handler.
5588 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5589 (and (tramp-file-name-host v)
5590 (not (member (tramp-file-name-host v)
5591 (mapcar 'car tramp-methods))))
5592 (not (tramp-completion-mode-p)))
5593 (while handler
5594 (setq elt (car handler)
5595 handler (cdr handler))
5596 (when (funcall (car elt) filename)
5597 (setq handler nil
5598 res (cdr elt))))
5599 res))))
5600
5601 ;; Main function.
5602 ;;;###autoload
5603 (defun tramp-file-name-handler (operation &rest args)
5604 "Invoke Tramp file name handler.
5605 Falls back to normal file name handler if no Tramp file name handler exists."
5606 (if tramp-mode
5607 (save-match-data
5608 (let* ((filename
5609 (tramp-replace-environment-variables
5610 (apply 'tramp-file-name-for-operation operation args)))
5611 (completion (tramp-completion-mode-p))
5612 (foreign (tramp-find-foreign-file-name-handler filename)))
5613 (with-parsed-tramp-file-name filename nil
5614 ;; Call the backend function.
5615 (if foreign
5616 (condition-case err
5617 (apply foreign operation args)
5618
5619 ;; Trace that somebody has interrupted the
5620 ;; operation.
5621 (quit
5622 (let (tramp-message-show-message)
5623 (tramp-message
5624 v 1 "Interrupt received in operation %s"
5625 (append (list operation) args)))
5626 ;; Propagate the quit signal.
5627 (signal (car err) (cdr err)))
5628
5629 ;; When we are in completion mode, some failed
5630 ;; operations shall return at least a default value
5631 ;; in order to give the user a chance to correct the
5632 ;; file name in the minibuffer.
5633 (error
5634 (cond
5635 ((and completion (zerop (length localname))
5636 (memq operation '(file-exists-p file-directory-p)))
5637 t)
5638 ((and completion (zerop (length localname))
5639 (memq operation
5640 '(expand-file-name file-name-as-directory)))
5641 filename)
5642 ;; Propagate the error.
5643 (t (signal (car err) (cdr err))))))
5644
5645 ;; Nothing to do for us.
5646 (tramp-run-real-handler operation args)))))
5647
5648 ;; When `tramp-mode' is not enabled, we don't do anything.
5649 (tramp-run-real-handler operation args)))
5650
5651 ;; In Emacs, there is some concurrency due to timers. If a timer
5652 ;; interrupts Tramp and wishes to use the same connection buffer as
5653 ;; the "main" Emacs, then garbage might occur in the connection
5654 ;; buffer. Therefore, we need to make sure that a timer does not use
5655 ;; the same connection buffer as the "main" Emacs. We implement a
5656 ;; cheap global lock, instead of locking each connection buffer
5657 ;; separately. The global lock is based on two variables,
5658 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5659 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5660 ;; processing of a single file operation, so we need to allow
5661 ;; recursive calls. That's where the `tramp-locker' variable comes in
5662 ;; -- it is let-bound to t during the execution of the current
5663 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5664 ;; then we should just proceed because we have been called
5665 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5666 ;; interrupting the "main" Emacs, and then we signal an error.
5667
5668 (defvar tramp-locked nil
5669 "If non-nil, then Tramp is currently busy.
5670 Together with `tramp-locker', this implements a locking mechanism
5671 preventing reentrant calls of Tramp.")
5672
5673 (defvar tramp-locker nil
5674 "If non-nil, then a caller has locked Tramp.
5675 Together with `tramp-locked', this implements a locking mechanism
5676 preventing reentrant calls of Tramp.")
5677
5678 (defun tramp-sh-file-name-handler (operation &rest args)
5679 "Invoke remote-shell Tramp file name handler.
5680 Fall back to normal file name handler if no Tramp handler exists."
5681 (when (and tramp-locked (not tramp-locker))
5682 (setq tramp-locked nil)
5683 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5684 (let ((tl tramp-locked))
5685 (unwind-protect
5686 (progn
5687 (setq tramp-locked t)
5688 (let ((tramp-locker t))
5689 (save-match-data
5690 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5691 (if fn
5692 (apply (cdr fn) args)
5693 (tramp-run-real-handler operation args))))))
5694 (setq tramp-locked tl))))
5695
5696 (defun tramp-vc-file-name-handler (operation &rest args)
5697 "Invoke special file name handler, which collects files to be handled."
5698 (save-match-data
5699 (let ((filename
5700 (tramp-replace-environment-variables
5701 (apply 'tramp-file-name-for-operation operation args)))
5702 (fn (assoc operation tramp-file-name-handler-alist)))
5703 (with-parsed-tramp-file-name filename nil
5704 (cond
5705 ;; That's what we want: file names, for which checks are
5706 ;; applied. We assume, that VC uses only `file-exists-p' and
5707 ;; `file-readable-p' checks; otherwise we must extend the
5708 ;; list. We do not perform any action, but return nil, in
5709 ;; order to keep `vc-registered' running.
5710 ((and fn (memq operation '(file-exists-p file-readable-p)))
5711 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5712 nil)
5713 ;; Tramp file name handlers like `expand-file-name'. They
5714 ;; must still work.
5715 (fn
5716 (save-match-data (apply (cdr fn) args)))
5717 ;; Default file name handlers, we don't care.
5718 (t (tramp-run-real-handler operation args)))))))
5719
5720 ;;;###autoload
5721 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5722 "Invoke Tramp file name completion handler.
5723 Falls back to normal file name handler if no Tramp file name handler exists."
5724 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5725 ;; would otherwise use backslash.
5726 (let ((directory-sep-char ?/)
5727 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5728 (if (and
5729 ;; When `tramp-mode' is not enabled, we don't do anything.
5730 fn tramp-mode
5731 ;; For other syntaxes than `sep', the regexp matches many common
5732 ;; situations where the user doesn't actually want to use Tramp.
5733 ;; So to avoid autoloading Tramp after typing just "/s", we
5734 ;; disable this part of the completion, unless the user implicitly
5735 ;; indicated his interest in using a fancier completion system.
5736 (or (eq tramp-syntax 'sep)
5737 (featurep 'tramp) ;; If it's loaded, we may as well use it.
5738 ;; `partial-completion-mode' does not exist in XEmacs.
5739 ;; It is obsoleted with Emacs 24.1.
5740 (and (boundp 'partial-completion-mode)
5741 (symbol-value 'partial-completion-mode))
5742 ;; FIXME: These may have been loaded even if the user never
5743 ;; intended to use them.
5744 (featurep 'ido)
5745 (featurep 'icicles)))
5746 (save-match-data (apply (cdr fn) args))
5747 (tramp-completion-run-real-handler operation args)))))
5748
5749 ;;;###autoload
5750 (progn (defun tramp-register-file-name-handlers ()
5751 "Add Tramp file name handlers to `file-name-handler-alist'."
5752 ;; Remove autoloaded handlers from file name handler alist. Useful,
5753 ;; if `tramp-syntax' has been changed.
5754 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5755 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5756 (let ((a1 (rassq
5757 'tramp-completion-file-name-handler file-name-handler-alist)))
5758 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5759 ;; Add the handlers.
5760 (add-to-list 'file-name-handler-alist
5761 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5762 (put 'tramp-file-name-handler 'safe-magic t)
5763 (add-to-list 'file-name-handler-alist
5764 (cons tramp-completion-file-name-regexp
5765 'tramp-completion-file-name-handler))
5766 (put 'tramp-completion-file-name-handler 'safe-magic t)
5767 ;; If jka-compr or epa-file are already loaded, move them to the
5768 ;; front of `file-name-handler-alist'.
5769 (dolist (fnh '(epa-file-handler jka-compr-handler))
5770 (let ((entry (rassoc fnh file-name-handler-alist)))
5771 (when entry
5772 (setq file-name-handler-alist
5773 (cons entry (delete entry file-name-handler-alist))))))))
5774
5775 ;; `tramp-file-name-handler' must be registered before evaluation of
5776 ;; site-start and init files, because there might exist remote files
5777 ;; already, f.e. files kept via recentf-mode.
5778 ;;;###autoload(tramp-register-file-name-handlers)
5779 (tramp-register-file-name-handlers)
5780
5781 ;;;###autoload
5782 (defun tramp-unload-file-name-handlers ()
5783 (setq file-name-handler-alist
5784 (delete (rassoc 'tramp-file-name-handler
5785 file-name-handler-alist)
5786 (delete (rassoc 'tramp-completion-file-name-handler
5787 file-name-handler-alist)
5788 file-name-handler-alist))))
5789
5790 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5791
5792 ;;; File name handler functions for completion mode:
5793
5794 (defvar tramp-completion-mode nil
5795 "If non-nil, external packages signal that they are in file name completion.
5796
5797 This is necessary, because Tramp uses a heuristic depending on last
5798 input event. This fails when external packages use other characters
5799 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5800 should never be set globally, the intention is to let-bind it.")
5801
5802 ;; Necessary because `tramp-file-name-regexp-unified' and
5803 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5804 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5805 ;; to `tramp-file-name-handler'). Otherwise, it takes
5806 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5807 ;; risky, because completing a file might require loading other files,
5808 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5809 ;; variable. On the other hand, those files shouldn't have partial
5810 ;; Tramp file name syntax. Maybe another variable should be introduced
5811 ;; overwriting this check in such cases. Or we change Tramp file name
5812 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5813 (defun tramp-completion-mode-p ()
5814 "Check, whether method / user name / host name completion is active."
5815 (or
5816 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
5817 (and (boundp 'non-essential) (symbol-value 'non-essential))
5818 tramp-completion-mode
5819 ;; Emacs.
5820 (equal last-input-event 'tab)
5821 (and (natnump last-input-event)
5822 (or
5823 ;; ?\t has event-modifier 'control.
5824 (equal last-input-event ?\t)
5825 (and (not (event-modifiers last-input-event))
5826 (or (equal last-input-event ?\?)
5827 (equal last-input-event ?\ )))))
5828 ;; XEmacs.
5829 (and (featurep 'xemacs)
5830 ;; `last-input-event' might be nil.
5831 (not (null last-input-event))
5832 ;; `last-input-event' may have no character approximation.
5833 (tramp-compat-funcall 'event-to-character last-input-event)
5834 (or
5835 ;; ?\t has event-modifier 'control.
5836 (equal
5837 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
5838 (and (not (event-modifiers last-input-event))
5839 (or (equal
5840 (tramp-compat-funcall 'event-to-character last-input-event)
5841 ?\?)
5842 (equal
5843 (tramp-compat-funcall 'event-to-character last-input-event)
5844 ?\ )))))))
5845
5846 (defun tramp-connectable-p (filename)
5847 "Check, whether it is possible to connect the remote host w/o side-effects.
5848 This is true, if either the remote host is already connected, or if we are
5849 not in completion mode."
5850 (and (tramp-tramp-file-p filename)
5851 (with-parsed-tramp-file-name filename nil
5852 (or (get-buffer (tramp-buffer-name v))
5853 (not (tramp-completion-mode-p))))))
5854
5855 ;; Method, host name and user name completion.
5856 ;; `tramp-completion-dissect-file-name' returns a list of
5857 ;; tramp-file-name structures. For all of them we return possible completions.
5858 ;;;###autoload
5859 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5860 "Like `file-name-all-completions' for partial Tramp files."
5861
5862 (let* ((fullname (tramp-drop-volume-letter
5863 (expand-file-name filename directory)))
5864 ;; Possible completion structures.
5865 (v (tramp-completion-dissect-file-name fullname))
5866 result result1)
5867
5868 (while v
5869 (let* ((car (car v))
5870 (method (tramp-file-name-method car))
5871 (user (tramp-file-name-user car))
5872 (host (tramp-file-name-host car))
5873 (localname (tramp-file-name-localname car))
5874 (m (tramp-find-method method user host))
5875 (tramp-current-user user) ; see `tramp-parse-passwd'
5876 all-user-hosts)
5877
5878 (unless localname ;; Nothing to complete.
5879
5880 (if (or user host)
5881
5882 ;; Method dependent user / host combinations.
5883 (progn
5884 (mapc
5885 (lambda (x)
5886 (setq all-user-hosts
5887 (append all-user-hosts
5888 (funcall (nth 0 x) (nth 1 x)))))
5889 (tramp-get-completion-function m))
5890
5891 (setq result
5892 (append result
5893 (mapcar
5894 (lambda (x)
5895 (tramp-get-completion-user-host
5896 method user host (nth 0 x) (nth 1 x)))
5897 (delq nil all-user-hosts)))))
5898
5899 ;; Possible methods.
5900 (setq result
5901 (append result (tramp-get-completion-methods m)))))
5902
5903 (setq v (cdr v))))
5904
5905 ;; Unify list, remove nil elements.
5906 (while result
5907 (let ((car (car result)))
5908 (when car
5909 (add-to-list
5910 'result1
5911 (substring car (length (tramp-drop-volume-letter directory)))))
5912 (setq result (cdr result))))
5913
5914 ;; Complete local parts.
5915 (append
5916 result1
5917 (condition-case nil
5918 (apply (if (tramp-connectable-p fullname)
5919 'tramp-completion-run-real-handler
5920 'tramp-run-real-handler)
5921 'file-name-all-completions (list (list filename directory)))
5922 (error nil)))))
5923
5924 ;; Method, host name and user name completion for a file.
5925 ;;;###autoload
5926 (defun tramp-completion-handle-file-name-completion
5927 (filename directory &optional predicate)
5928 "Like `file-name-completion' for Tramp files."
5929 (try-completion
5930 filename
5931 (mapcar 'list (file-name-all-completions filename directory))
5932 (when (and predicate
5933 (tramp-connectable-p (expand-file-name filename directory)))
5934 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5935
5936 ;; I misuse a little bit the tramp-file-name structure in order to handle
5937 ;; completion possibilities for partial methods / user names / host names.
5938 ;; Return value is a list of tramp-file-name structures according to possible
5939 ;; completions. If "localname" is non-nil it means there
5940 ;; shouldn't be a completion anymore.
5941
5942 ;; Expected results:
5943
5944 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5945 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5946 ;; [nil "x" nil nil]
5947 ;; ["x" nil nil nil]
5948
5949 ;; "/x:" "/x:y" "/x:y:"
5950 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5951 ;; "/[x/" "/[x/y"
5952 ;; ["x" nil "" nil] ["x" nil "y" nil]
5953 ;; ["x" "" nil nil] ["x" "y" nil nil]
5954
5955 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5956 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5957 ;; "/[x/y@" "/[x/y@z"
5958 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5959 (defun tramp-completion-dissect-file-name (name)
5960 "Returns a list of `tramp-file-name' structures.
5961 They are collected by `tramp-completion-dissect-file-name1'."
5962
5963 (let* ((result)
5964 (x-nil "\\|\\(\\)")
5965 (tramp-completion-ipv6-regexp
5966 (format
5967 "[^%s]*"
5968 (if (zerop (length tramp-postfix-ipv6-format))
5969 tramp-postfix-host-format
5970 tramp-postfix-ipv6-format)))
5971 ;; "/method" "/[method"
5972 (tramp-completion-file-name-structure1
5973 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5974 1 nil nil nil))
5975 ;; "/user" "/[user"
5976 (tramp-completion-file-name-structure2
5977 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5978 nil 1 nil nil))
5979 ;; "/host" "/[host"
5980 (tramp-completion-file-name-structure3
5981 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5982 nil nil 1 nil))
5983 ;; "/[ipv6" "/[ipv6"
5984 (tramp-completion-file-name-structure4
5985 (list (concat tramp-prefix-regexp
5986 tramp-prefix-ipv6-regexp
5987 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5988 nil nil 1 nil))
5989 ;; "/user@host" "/[user@host"
5990 (tramp-completion-file-name-structure5
5991 (list (concat tramp-prefix-regexp
5992 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5993 "\\(" tramp-host-regexp x-nil "\\)$")
5994 nil 1 2 nil))
5995 ;; "/user@[ipv6" "/[user@ipv6"
5996 (tramp-completion-file-name-structure6
5997 (list (concat tramp-prefix-regexp
5998 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5999 tramp-prefix-ipv6-regexp
6000 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6001 nil 1 2 nil))
6002 ;; "/method:user" "/[method/user" "/method://user"
6003 (tramp-completion-file-name-structure7
6004 (list (concat tramp-prefix-regexp
6005 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6006 "\\(" tramp-user-regexp x-nil "\\)$")
6007 1 2 nil nil))
6008 ;; "/method:host" "/[method/host" "/method://host"
6009 (tramp-completion-file-name-structure8
6010 (list (concat tramp-prefix-regexp
6011 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6012 "\\(" tramp-host-regexp x-nil "\\)$")
6013 1 nil 2 nil))
6014 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
6015 (tramp-completion-file-name-structure9
6016 (list (concat tramp-prefix-regexp
6017 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6018 tramp-prefix-ipv6-regexp
6019 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6020 1 nil 2 nil))
6021 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
6022 (tramp-completion-file-name-structure10
6023 (list (concat tramp-prefix-regexp
6024 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6025 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6026 "\\(" tramp-host-regexp x-nil "\\)$")
6027 1 2 3 nil))
6028 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
6029 (tramp-completion-file-name-structure11
6030 (list (concat tramp-prefix-regexp
6031 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
6032 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
6033 tramp-prefix-ipv6-regexp
6034 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
6035 1 2 3 nil))
6036 ;; "/method: "/method:/"
6037 (tramp-completion-file-name-structure12
6038 (list
6039 (if (equal tramp-syntax 'url)
6040 (concat tramp-prefix-regexp
6041 "\\(" tramp-method-regexp "\\)"
6042 "\\(" (substring tramp-postfix-method-regexp 0 1)
6043 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6044 "\\(" "\\)$")
6045 ;; Should not match if not URL syntax.
6046 (concat tramp-prefix-regexp "/$"))
6047 1 3 nil nil))
6048 ;; "/method: "/method:/"
6049 (tramp-completion-file-name-structure13
6050 (list
6051 (if (equal tramp-syntax 'url)
6052 (concat tramp-prefix-regexp
6053 "\\(" tramp-method-regexp "\\)"
6054 "\\(" (substring tramp-postfix-method-regexp 0 1)
6055 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
6056 "\\(" "\\)$")
6057 ;; Should not match if not URL syntax.
6058 (concat tramp-prefix-regexp "/$"))
6059 1 nil 3 nil)))
6060
6061 (mapc (lambda (regexp)
6062 (add-to-list 'result
6063 (tramp-completion-dissect-file-name1 regexp name)))
6064 (list
6065 tramp-completion-file-name-structure1
6066 tramp-completion-file-name-structure2
6067 tramp-completion-file-name-structure3
6068 tramp-completion-file-name-structure4
6069 tramp-completion-file-name-structure5
6070 tramp-completion-file-name-structure6
6071 tramp-completion-file-name-structure7
6072 tramp-completion-file-name-structure8
6073 tramp-completion-file-name-structure9
6074 tramp-completion-file-name-structure10
6075 tramp-completion-file-name-structure11
6076 tramp-completion-file-name-structure12
6077 tramp-completion-file-name-structure13
6078 tramp-file-name-structure))
6079
6080 (delq nil result)))
6081
6082 (defun tramp-completion-dissect-file-name1 (structure name)
6083 "Returns a `tramp-file-name' structure matching STRUCTURE.
6084 The structure consists of remote method, remote user,
6085 remote host and localname (filename on remote host)."
6086
6087 (save-match-data
6088 (when (string-match (nth 0 structure) name)
6089 (let ((method (and (nth 1 structure)
6090 (match-string (nth 1 structure) name)))
6091 (user (and (nth 2 structure)
6092 (match-string (nth 2 structure) name)))
6093 (host (and (nth 3 structure)
6094 (match-string (nth 3 structure) name)))
6095 (localname (and (nth 4 structure)
6096 (match-string (nth 4 structure) name))))
6097 (vector method user host localname)))))
6098
6099 ;; This function returns all possible method completions, adding the
6100 ;; trailing method delimeter.
6101 (defun tramp-get-completion-methods (partial-method)
6102 "Returns all method completions for PARTIAL-METHOD."
6103 (mapcar
6104 (lambda (method)
6105 (and method
6106 (string-match (concat "^" (regexp-quote partial-method)) method)
6107 (tramp-completion-make-tramp-file-name method nil nil nil)))
6108 (mapcar 'car tramp-methods)))
6109
6110 ;; Compares partial user and host names with possible completions.
6111 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
6112 "Returns the most expanded string for user and host name completion.
6113 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
6114 (cond
6115
6116 ((and partial-user partial-host)
6117 (if (and host
6118 (string-match (concat "^" (regexp-quote partial-host)) host)
6119 (string-equal partial-user (or user partial-user)))
6120 (setq user partial-user)
6121 (setq user nil
6122 host nil)))
6123
6124 (partial-user
6125 (setq host nil)
6126 (unless
6127 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
6128 (setq user nil)))
6129
6130 (partial-host
6131 (setq user nil)
6132 (unless
6133 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
6134 (setq host nil)))
6135
6136 (t (setq user nil
6137 host nil)))
6138
6139 (unless (zerop (+ (length user) (length host)))
6140 (tramp-completion-make-tramp-file-name method user host nil)))
6141
6142 (defun tramp-parse-rhosts (filename)
6143 "Return a list of (user host) tuples allowed to access.
6144 Either user or host may be nil."
6145 ;; On Windows, there are problems in completion when
6146 ;; `default-directory' is remote.
6147 (let ((default-directory (tramp-compat-temporary-file-directory))
6148 res)
6149 (when (file-readable-p filename)
6150 (with-temp-buffer
6151 (insert-file-contents filename)
6152 (goto-char (point-min))
6153 (while (not (eobp))
6154 (push (tramp-parse-rhosts-group) res))))
6155 res))
6156
6157 (defun tramp-parse-rhosts-group ()
6158 "Return a (user host) tuple allowed to access.
6159 Either user or host may be nil."
6160 (let ((result)
6161 (regexp
6162 (concat
6163 "^\\(" tramp-host-regexp "\\)"
6164 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6165 (narrow-to-region (point) (tramp-compat-line-end-position))
6166 (when (re-search-forward regexp nil t)
6167 (setq result (append (list (match-string 3) (match-string 1)))))
6168 (widen)
6169 (forward-line 1)
6170 result))
6171
6172 (defun tramp-parse-shosts (filename)
6173 "Return a list of (user host) tuples allowed to access.
6174 User is always nil."
6175 ;; On Windows, there are problems in completion when
6176 ;; `default-directory' is remote.
6177 (let ((default-directory (tramp-compat-temporary-file-directory))
6178 res)
6179 (when (file-readable-p filename)
6180 (with-temp-buffer
6181 (insert-file-contents filename)
6182 (goto-char (point-min))
6183 (while (not (eobp))
6184 (push (tramp-parse-shosts-group) res))))
6185 res))
6186
6187 (defun tramp-parse-shosts-group ()
6188 "Return a (user host) tuple allowed to access.
6189 User is always nil."
6190 (let ((result)
6191 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
6192 (narrow-to-region (point) (tramp-compat-line-end-position))
6193 (when (re-search-forward regexp nil t)
6194 (setq result (list nil (match-string 1))))
6195 (widen)
6196 (or
6197 (> (skip-chars-forward ",") 0)
6198 (forward-line 1))
6199 result))
6200
6201 (defun tramp-parse-sconfig (filename)
6202 "Return a list of (user host) tuples allowed to access.
6203 User is always nil."
6204 ;; On Windows, there are problems in completion when
6205 ;; `default-directory' is remote.
6206 (let ((default-directory (tramp-compat-temporary-file-directory))
6207 res)
6208 (when (file-readable-p filename)
6209 (with-temp-buffer
6210 (insert-file-contents filename)
6211 (goto-char (point-min))
6212 (while (not (eobp))
6213 (push (tramp-parse-sconfig-group) res))))
6214 res))
6215
6216 (defun tramp-parse-sconfig-group ()
6217 "Return a (user host) tuple allowed to access.
6218 User is always nil."
6219 (let ((result)
6220 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
6221 (narrow-to-region (point) (tramp-compat-line-end-position))
6222 (when (re-search-forward regexp nil t)
6223 (setq result (list nil (match-string 1))))
6224 (widen)
6225 (or
6226 (> (skip-chars-forward ",") 0)
6227 (forward-line 1))
6228 result))
6229
6230 (defun tramp-parse-shostkeys (dirname)
6231 "Return a list of (user host) tuples allowed to access.
6232 User is always nil."
6233 ;; On Windows, there are problems in completion when
6234 ;; `default-directory' is remote.
6235 (let* ((default-directory (tramp-compat-temporary-file-directory))
6236 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
6237 (files (when (file-directory-p dirname) (directory-files dirname)))
6238 result)
6239 (while files
6240 (when (string-match regexp (car files))
6241 (push (list nil (match-string 1 (car files))) result))
6242 (setq files (cdr files)))
6243 result))
6244
6245 (defun tramp-parse-sknownhosts (dirname)
6246 "Return a list of (user host) tuples allowed to access.
6247 User is always nil."
6248 ;; On Windows, there are problems in completion when
6249 ;; `default-directory' is remote.
6250 (let* ((default-directory (tramp-compat-temporary-file-directory))
6251 (regexp (concat "^\\(" tramp-host-regexp
6252 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
6253 (files (when (file-directory-p dirname) (directory-files dirname)))
6254 result)
6255 (while files
6256 (when (string-match regexp (car files))
6257 (push (list nil (match-string 1 (car files))) result))
6258 (setq files (cdr files)))
6259 result))
6260
6261 (defun tramp-parse-hosts (filename)
6262 "Return a list of (user host) tuples allowed to access.
6263 User is always nil."
6264 ;; On Windows, there are problems in completion when
6265 ;; `default-directory' is remote.
6266 (let ((default-directory (tramp-compat-temporary-file-directory))
6267 res)
6268 (when (file-readable-p filename)
6269 (with-temp-buffer
6270 (insert-file-contents filename)
6271 (goto-char (point-min))
6272 (while (not (eobp))
6273 (push (tramp-parse-hosts-group) res))))
6274 res))
6275
6276 (defun tramp-parse-hosts-group ()
6277 "Return a (user host) tuple allowed to access.
6278 User is always nil."
6279 (let ((result)
6280 (regexp
6281 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6282 (narrow-to-region (point) (tramp-compat-line-end-position))
6283 (when (re-search-forward regexp nil t)
6284 (setq result (list nil (match-string 1))))
6285 (widen)
6286 (or
6287 (> (skip-chars-forward " \t") 0)
6288 (forward-line 1))
6289 result))
6290
6291 ;; For su-alike methods it would be desirable to return "root@localhost"
6292 ;; as default. Unfortunately, we have no information whether any user name
6293 ;; has been typed already. So we use `tramp-current-user' as indication,
6294 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6295 (defun tramp-parse-passwd (filename)
6296 "Return a list of (user host) tuples allowed to access.
6297 Host is always \"localhost\"."
6298 ;; On Windows, there are problems in completion when
6299 ;; `default-directory' is remote.
6300 (let ((default-directory (tramp-compat-temporary-file-directory))
6301 res)
6302 (if (zerop (length tramp-current-user))
6303 '(("root" nil))
6304 (when (file-readable-p filename)
6305 (with-temp-buffer
6306 (insert-file-contents filename)
6307 (goto-char (point-min))
6308 (while (not (eobp))
6309 (push (tramp-parse-passwd-group) res))))
6310 res)))
6311
6312 (defun tramp-parse-passwd-group ()
6313 "Return a (user host) tuple allowed to access.
6314 Host is always \"localhost\"."
6315 (let ((result)
6316 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6317 (narrow-to-region (point) (tramp-compat-line-end-position))
6318 (when (re-search-forward regexp nil t)
6319 (setq result (list (match-string 1) "localhost")))
6320 (widen)
6321 (forward-line 1)
6322 result))
6323
6324 (defun tramp-parse-netrc (filename)
6325 "Return a list of (user host) tuples allowed to access.
6326 User may be nil."
6327 ;; On Windows, there are problems in completion when
6328 ;; `default-directory' is remote.
6329 (let ((default-directory (tramp-compat-temporary-file-directory))
6330 res)
6331 (when (file-readable-p filename)
6332 (with-temp-buffer
6333 (insert-file-contents filename)
6334 (goto-char (point-min))
6335 (while (not (eobp))
6336 (push (tramp-parse-netrc-group) res))))
6337 res))
6338
6339 (defun tramp-parse-netrc-group ()
6340 "Return a (user host) tuple allowed to access.
6341 User may be nil."
6342 (let ((result)
6343 (regexp
6344 (concat
6345 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6346 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6347 (narrow-to-region (point) (tramp-compat-line-end-position))
6348 (when (re-search-forward regexp nil t)
6349 (setq result (list (match-string 3) (match-string 1))))
6350 (widen)
6351 (forward-line 1)
6352 result))
6353
6354 (defun tramp-parse-putty (registry)
6355 "Return a list of (user host) tuples allowed to access.
6356 User is always nil."
6357 ;; On Windows, there are problems in completion when
6358 ;; `default-directory' is remote.
6359 (let ((default-directory (tramp-compat-temporary-file-directory))
6360 res)
6361 (with-temp-buffer
6362 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6363 (goto-char (point-min))
6364 (while (not (eobp))
6365 (push (tramp-parse-putty-group registry) res))))
6366 res))
6367
6368 (defun tramp-parse-putty-group (registry)
6369 "Return a (user host) tuple allowed to access.
6370 User is always nil."
6371 (let ((result)
6372 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6373 (narrow-to-region (point) (tramp-compat-line-end-position))
6374 (when (re-search-forward regexp nil t)
6375 (setq result (list nil (match-string 1))))
6376 (widen)
6377 (forward-line 1)
6378 result))
6379
6380 ;;; Internal Functions:
6381
6382 (defun tramp-maybe-send-script (vec script name)
6383 "Define in remote shell function NAME implemented as SCRIPT.
6384 Only send the definition if it has not already been done."
6385 (let* ((p (tramp-get-connection-process vec))
6386 (scripts (tramp-get-connection-property p "scripts" nil)))
6387 (unless (member name scripts)
6388 (with-progress-reporter vec 5 (format "Sending script `%s'" name)
6389 ;; The script could contain a call of Perl. This is masked with `%s'.
6390 (tramp-send-command-and-check
6391 vec
6392 (format "%s () {\n%s\n}" name
6393 (format script (tramp-get-remote-perl vec))))
6394 (tramp-set-connection-property p "scripts" (cons name scripts))))))
6395
6396 (defun tramp-set-auto-save ()
6397 (when (and ;; ange-ftp has its own auto-save mechanism
6398 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6399 'tramp-sh-file-name-handler)
6400 auto-save-default)
6401 (auto-save-mode 1)))
6402 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6403 (add-hook 'tramp-unload-hook
6404 (lambda ()
6405 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6406
6407 (defun tramp-run-test (switch filename)
6408 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6409 Returns the exit code of the `test' program."
6410 (with-parsed-tramp-file-name filename nil
6411 (tramp-send-command-and-check
6412 v
6413 (format
6414 "%s %s %s"
6415 (tramp-get-test-command v)
6416 switch
6417 (tramp-shell-quote-argument localname)))))
6418
6419 (defun tramp-run-test2 (format-string file1 file2)
6420 "Run `test'-like program on the remote system, given FILE1, FILE2.
6421 FORMAT-STRING contains the program name, switches, and place holders.
6422 Returns the exit code of the `test' program. Barfs if the methods,
6423 hosts, or files, disagree."
6424 (unless (tramp-equal-remote file1 file2)
6425 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6426 (tramp-error
6427 v 'file-error
6428 "tramp-run-test2 only implemented for same method, user, host")))
6429 (with-parsed-tramp-file-name file1 v1
6430 (with-parsed-tramp-file-name file1 v2
6431 (tramp-send-command-and-check
6432 v1
6433 (format format-string
6434 (tramp-shell-quote-argument v1-localname)
6435 (tramp-shell-quote-argument v2-localname))))))
6436
6437 (defun tramp-buffer-name (vec)
6438 "A name for the connection buffer VEC."
6439 ;; We must use `tramp-file-name-real-host', because for gateway
6440 ;; methods the default port will be expanded later on, which would
6441 ;; tamper the name.
6442 (let ((method (tramp-file-name-method vec))
6443 (user (tramp-file-name-user vec))
6444 (host (tramp-file-name-real-host vec)))
6445 (if (not (zerop (length user)))
6446 (format "*tramp/%s %s@%s*" method user host)
6447 (format "*tramp/%s %s*" method host))))
6448
6449 (defun tramp-delete-temp-file-function ()
6450 "Remove temporary files related to current buffer."
6451 (when (stringp tramp-temp-buffer-file-name)
6452 (condition-case nil
6453 (delete-file tramp-temp-buffer-file-name)
6454 (error nil))))
6455
6456 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6457 (add-hook 'tramp-cache-unload-hook
6458 (lambda ()
6459 (remove-hook 'kill-buffer-hook
6460 'tramp-delete-temp-file-function)))
6461
6462 (defun tramp-get-buffer (vec)
6463 "Get the connection buffer to be used for VEC."
6464 (or (get-buffer (tramp-buffer-name vec))
6465 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6466 (setq buffer-undo-list t)
6467 (setq default-directory
6468 (tramp-make-tramp-file-name
6469 (tramp-file-name-method vec)
6470 (tramp-file-name-user vec)
6471 (tramp-file-name-host vec)
6472 "/"))
6473 (current-buffer))))
6474
6475 (defun tramp-get-connection-buffer (vec)
6476 "Get the connection buffer to be used for VEC.
6477 In case a second asynchronous communication has been started, it is different
6478 from `tramp-get-buffer'."
6479 (or (tramp-get-connection-property vec "process-buffer" nil)
6480 (tramp-get-buffer vec)))
6481
6482 (defun tramp-get-connection-process (vec)
6483 "Get the connection process to be used for VEC.
6484 In case a second asynchronous communication has been started, it is different
6485 from the default one."
6486 (get-process
6487 (or (tramp-get-connection-property vec "process-name" nil)
6488 (tramp-buffer-name vec))))
6489
6490 (defun tramp-debug-buffer-name (vec)
6491 "A name for the debug buffer for VEC."
6492 ;; We must use `tramp-file-name-real-host', because for gateway
6493 ;; methods the default port will be expanded later on, which would
6494 ;; tamper the name.
6495 (let ((method (tramp-file-name-method vec))
6496 (user (tramp-file-name-user vec))
6497 (host (tramp-file-name-real-host vec)))
6498 (if (not (zerop (length user)))
6499 (format "*debug tramp/%s %s@%s*" method user host)
6500 (format "*debug tramp/%s %s*" method host))))
6501
6502 (defconst tramp-debug-outline-regexp
6503 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6504
6505 (defun tramp-get-debug-buffer (vec)
6506 "Get the debug buffer for VEC."
6507 (with-current-buffer
6508 (get-buffer-create (tramp-debug-buffer-name vec))
6509 (when (bobp)
6510 (setq buffer-undo-list t)
6511 ;; Activate `outline-mode'. This runs `text-mode-hook' and
6512 ;; `outline-mode-hook'. We must prevent that local processes
6513 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
6514 ;; Furthermore, `outline-regexp' must have the correct value
6515 ;; already, because it is used by `font-lock-compile-keywords'.
6516 (let ((default-directory (tramp-compat-temporary-file-directory))
6517 (outline-regexp tramp-debug-outline-regexp))
6518 (outline-mode))
6519 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
6520 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6521 (current-buffer)))
6522
6523 (defun tramp-outline-level ()
6524 "Return the depth to which a statement is nested in the outline.
6525 Point must be at the beginning of a header line.
6526
6527 The outline level is equal to the verbosity of the Tramp message."
6528 (1+ (string-to-number (match-string 1))))
6529
6530 (defun tramp-find-executable
6531 (vec progname dirlist &optional ignore-tilde ignore-path)
6532 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6533 First arg VEC specifies the connection, PROGNAME is the program
6534 to search for, and DIRLIST gives the list of directories to
6535 search. If IGNORE-TILDE is non-nil, directory names starting
6536 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6537 only in DIRLIST.
6538
6539 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6540
6541 This function expects to be in the right *tramp* buffer."
6542 (with-current-buffer (tramp-get-connection-buffer vec)
6543 (let (result)
6544 ;; Check whether the executable is in $PATH. "which(1)" does not
6545 ;; report always a correct error code; therefore we check the
6546 ;; number of words it returns.
6547 (unless ignore-path
6548 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6549 (goto-char (point-min))
6550 (if (looking-at "^\\s-*1$")
6551 (setq result (concat "\\" progname))))
6552 (unless result
6553 (when ignore-tilde
6554 ;; Remove all ~/foo directories from dirlist. In XEmacs,
6555 ;; `remove' is in CL, and we want to avoid CL dependencies.
6556 (let (newdl d)
6557 (while dirlist
6558 (setq d (car dirlist))
6559 (setq dirlist (cdr dirlist))
6560 (unless (char-equal ?~ (aref d 0))
6561 (setq newdl (cons d newdl))))
6562 (setq dirlist (nreverse newdl))))
6563 (tramp-send-command
6564 vec
6565 (format (concat "while read d; "
6566 "do if test -x $d/%s -a -f $d/%s; "
6567 "then echo tramp_executable $d/%s; "
6568 "break; fi; done <<'EOF'\n"
6569 "%s\nEOF")
6570 progname progname progname (mapconcat 'identity dirlist "\n")))
6571 (goto-char (point-max))
6572 (when (search-backward "tramp_executable " nil t)
6573 (skip-chars-forward "^ ")
6574 (skip-chars-forward " ")
6575 (setq result (buffer-substring
6576 (point) (tramp-compat-line-end-position)))))
6577 result)))
6578
6579 (defun tramp-set-remote-path (vec)
6580 "Sets the remote environment PATH to existing directories.
6581 I.e., for each directory in `tramp-remote-path', it is tested
6582 whether it exists and if so, it is added to the environment
6583 variable PATH."
6584 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6585 (tramp-send-command
6586 vec (format "PATH=%s; export PATH"
6587 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6588
6589 ;; ------------------------------------------------------------
6590 ;; -- Communication with external shell --
6591 ;; ------------------------------------------------------------
6592
6593 (defun tramp-find-file-exists-command (vec)
6594 "Find a command on the remote host for checking if a file exists.
6595 Here, we are looking for a command which has zero exit status if the
6596 file exists and nonzero exit status otherwise."
6597 (let ((existing "/")
6598 (nonexisting
6599 (tramp-shell-quote-argument "/ this file does not exist "))
6600 result)
6601 ;; The algorithm is as follows: we try a list of several commands.
6602 ;; For each command, we first run `$cmd /' -- this should return
6603 ;; true, as the root directory always exists. And then we run
6604 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6605 ;; does not exist. This should return false. We use the first
6606 ;; command we find that seems to work.
6607 ;; The list of commands to try is as follows:
6608 ;; `ls -d' This works on most systems, but NetBSD 1.4
6609 ;; has a bug: `ls' always returns zero exit
6610 ;; status, even for files which don't exist.
6611 ;; `test -e' Some Bourne shells have a `test' builtin
6612 ;; which does not know the `-e' option.
6613 ;; `/bin/test -e' For those, the `test' binary on disk normally
6614 ;; provides the option. Alas, the binary
6615 ;; is sometimes `/bin/test' and sometimes it's
6616 ;; `/usr/bin/test'.
6617 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6618 (unless (or
6619 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6620 (zerop (tramp-send-command-and-check
6621 vec (format "%s %s" result existing)))
6622 (not (zerop (tramp-send-command-and-check
6623 vec (format "%s %s" result nonexisting)))))
6624 (and (setq result "/bin/test -e")
6625 (zerop (tramp-send-command-and-check
6626 vec (format "%s %s" result existing)))
6627 (not (zerop (tramp-send-command-and-check
6628 vec (format "%s %s" result nonexisting)))))
6629 (and (setq result "/usr/bin/test -e")
6630 (zerop (tramp-send-command-and-check
6631 vec (format "%s %s" result existing)))
6632 (not (zerop (tramp-send-command-and-check
6633 vec (format "%s %s" result nonexisting)))))
6634 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6635 (zerop (tramp-send-command-and-check
6636 vec (format "%s %s" result existing)))
6637 (not (zerop (tramp-send-command-and-check
6638 vec (format "%s %s" result nonexisting))))))
6639 (tramp-error
6640 vec 'file-error "Couldn't find command to check if file exists"))
6641 result))
6642
6643 (defun tramp-open-shell (vec shell)
6644 "Opens shell SHELL."
6645 (with-progress-reporter vec 5 (format "Opening remote shell `%s'" shell)
6646 ;; Find arguments for this shell.
6647 (let ((tramp-end-of-output tramp-initial-end-of-output)
6648 (alist tramp-sh-extra-args)
6649 item extra-args)
6650 (while (and alist (null extra-args))
6651 (setq item (pop alist))
6652 (when (string-match (car item) shell)
6653 (setq extra-args (cdr item))))
6654 (when extra-args (setq shell (concat shell " " extra-args)))
6655 (tramp-send-command
6656 vec (format "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6657 (shell-quote-argument tramp-end-of-output) shell)
6658 t))
6659 ;; Setting prompts.
6660 (tramp-send-command
6661 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6662 (tramp-send-command vec "PS2=''" t)
6663 (tramp-send-command vec "PS3=''" t)
6664 (tramp-send-command vec "PROMPT_COMMAND=''" t)))
6665
6666 (defun tramp-find-shell (vec)
6667 "Opens a shell on the remote host which groks tilde expansion."
6668 (unless (tramp-get-connection-property vec "remote-shell" nil)
6669 (let (shell)
6670 (with-current-buffer (tramp-get-buffer vec)
6671 (tramp-send-command vec "echo ~root" t)
6672 (cond
6673 ((or (string-match "^~root$" (buffer-string))
6674 ;; The default shell (ksh93) of OpenSolaris is buggy.
6675 (string-equal (tramp-get-connection-property vec "uname" "")
6676 "SunOS 5.11"))
6677 (setq shell
6678 (or (tramp-find-executable
6679 vec "bash" (tramp-get-remote-path vec) t t)
6680 (tramp-find-executable
6681 vec "ksh" (tramp-get-remote-path vec) t t)))
6682 (unless shell
6683 (tramp-error
6684 vec 'file-error
6685 "Couldn't find a shell which groks tilde expansion"))
6686 (tramp-message
6687 vec 5 "Starting remote shell `%s' for tilde expansion" shell)
6688 (tramp-open-shell vec shell))
6689
6690 (t (tramp-message
6691 vec 5 "Remote `%s' groks tilde expansion, good"
6692 (tramp-set-connection-property
6693 vec "remote-shell"
6694 (tramp-get-method-parameter
6695 (tramp-file-name-method vec) 'tramp-remote-sh)))))))))
6696
6697 ;; ------------------------------------------------------------
6698 ;; -- Functions for establishing connection --
6699 ;; ------------------------------------------------------------
6700
6701 ;; The following functions are actions to be taken when seeing certain
6702 ;; prompts from the remote host. See the variable
6703 ;; `tramp-actions-before-shell' for usage of these functions.
6704
6705 (defun tramp-action-login (proc vec)
6706 "Send the login name."
6707 (when (not (stringp tramp-current-user))
6708 (save-window-excursion
6709 (let ((enable-recursive-minibuffers t))
6710 (pop-to-buffer (tramp-get-connection-buffer vec))
6711 (setq tramp-current-user (read-string (match-string 0))))))
6712 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6713 (with-current-buffer (tramp-get-connection-buffer vec)
6714 (tramp-message vec 6 "\n%s" (buffer-string)))
6715 (tramp-send-string vec tramp-current-user))
6716
6717 (defun tramp-action-password (proc vec)
6718 "Query the user for a password."
6719 (with-current-buffer (process-buffer proc)
6720 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6721 (tramp-message vec 3 "Sending %s" (match-string 1))
6722 (tramp-enter-password proc)
6723 ;; Hide password prompt.
6724 (narrow-to-region (point-max) (point-max))))
6725
6726 (defun tramp-action-succeed (proc vec)
6727 "Signal success in finding shell prompt."
6728 (throw 'tramp-action 'ok))
6729
6730 (defun tramp-action-permission-denied (proc vec)
6731 "Signal permission denied."
6732 (kill-process proc)
6733 (throw 'tramp-action 'permission-denied))
6734
6735 (defun tramp-action-yesno (proc vec)
6736 "Ask the user for confirmation using `yes-or-no-p'.
6737 Send \"yes\" to remote process on confirmation, abort otherwise.
6738 See also `tramp-action-yn'."
6739 (save-window-excursion
6740 (let ((enable-recursive-minibuffers t))
6741 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6742 (unless (yes-or-no-p (match-string 0))
6743 (kill-process proc)
6744 (throw 'tramp-action 'permission-denied))
6745 (with-current-buffer (tramp-get-connection-buffer vec)
6746 (tramp-message vec 6 "\n%s" (buffer-string)))
6747 (tramp-send-string vec "yes"))))
6748
6749 (defun tramp-action-yn (proc vec)
6750 "Ask the user for confirmation using `y-or-n-p'.
6751 Send \"y\" to remote process on confirmation, abort otherwise.
6752 See also `tramp-action-yesno'."
6753 (save-window-excursion
6754 (let ((enable-recursive-minibuffers t))
6755 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6756 (unless (y-or-n-p (match-string 0))
6757 (kill-process proc)
6758 (throw 'tramp-action 'permission-denied))
6759 (with-current-buffer (tramp-get-connection-buffer vec)
6760 (tramp-message vec 6 "\n%s" (buffer-string)))
6761 (tramp-send-string vec "y"))))
6762
6763 (defun tramp-action-terminal (proc vec)
6764 "Tell the remote host which terminal type to use.
6765 The terminal type can be configured with `tramp-terminal-type'."
6766 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6767 (with-current-buffer (tramp-get-connection-buffer vec)
6768 (tramp-message vec 6 "\n%s" (buffer-string)))
6769 (tramp-send-string vec tramp-terminal-type))
6770
6771 (defun tramp-action-process-alive (proc vec)
6772 "Check, whether a process has finished."
6773 (unless (memq (process-status proc) '(run open))
6774 (throw 'tramp-action 'process-died)))
6775
6776 (defun tramp-action-out-of-band (proc vec)
6777 "Check, whether an out-of-band copy has finished."
6778 (cond ((and (memq (process-status proc) '(stop exit))
6779 (zerop (process-exit-status proc)))
6780 (tramp-message vec 3 "Process has finished.")
6781 (throw 'tramp-action 'ok))
6782 ((or (and (memq (process-status proc) '(stop exit))
6783 (not (zerop (process-exit-status proc))))
6784 (memq (process-status proc) '(signal)))
6785 ;; `scp' could have copied correctly, but set modes could have failed.
6786 ;; This can be ignored.
6787 (with-current-buffer (process-buffer proc)
6788 (goto-char (point-min))
6789 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6790 (progn
6791 (tramp-message vec 5 "'set mode' error ignored.")
6792 (tramp-message vec 3 "Process has finished.")
6793 (throw 'tramp-action 'ok))
6794 (tramp-message vec 3 "Process has died.")
6795 (throw 'tramp-action 'process-died))))
6796 (t nil)))
6797
6798 ;; Functions for processing the actions.
6799
6800 (defun tramp-process-one-action (proc vec actions)
6801 "Wait for output from the shell and perform one action."
6802 (let (found todo item pattern action)
6803 (while (not found)
6804 ;; Reread output once all actions have been performed.
6805 ;; Obviously, the output was not complete.
6806 (tramp-accept-process-output proc 1)
6807 (setq todo actions)
6808 (while todo
6809 (setq item (pop todo))
6810 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6811 (setq action (nth 1 item))
6812 (tramp-message
6813 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6814 (when (tramp-check-for-regexp proc pattern)
6815 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6816 (setq found (funcall action proc vec)))))
6817 found))
6818
6819 (defun tramp-process-actions (proc vec actions &optional timeout)
6820 "Perform actions until success or TIMEOUT."
6821 ;; Preserve message for `progress-reporter'.
6822 (with-temp-message ""
6823 ;; Enable auth-source and password-cache.
6824 (tramp-set-connection-property vec "first-password-request" t)
6825 (save-restriction
6826 (let (exit)
6827 (while (not exit)
6828 (tramp-message proc 3 "Waiting for prompts from remote shell")
6829 (setq exit
6830 (catch 'tramp-action
6831 (if timeout
6832 (with-timeout (timeout)
6833 (tramp-process-one-action proc vec actions))
6834 (tramp-process-one-action proc vec actions)))))
6835 (with-current-buffer (tramp-get-connection-buffer vec)
6836 (widen)
6837 (tramp-message vec 6 "\n%s" (buffer-string)))
6838 (unless (eq exit 'ok)
6839 (tramp-clear-passwd vec)
6840 (tramp-error-with-buffer
6841 nil vec 'file-error
6842 (cond
6843 ((eq exit 'permission-denied) "Permission denied")
6844 ((eq exit 'process-died) "Process died")
6845 (t "Login failed"))))))))
6846
6847 ;; Utility functions.
6848
6849 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6850 "Like `accept-process-output' for Tramp processes.
6851 This is needed in order to hide `last-coding-system-used', which is set
6852 for process communication also."
6853 (with-current-buffer (process-buffer proc)
6854 (tramp-message proc 10 "%s %s" proc (process-status proc))
6855 (let (buffer-read-only last-coding-system-used)
6856 ;; Under Windows XP, accept-process-output doesn't return
6857 ;; sometimes. So we add an additional timeout.
6858 (with-timeout ((or timeout 1))
6859 (accept-process-output proc timeout timeout-msecs)))
6860 (tramp-message proc 10 "\n%s" (buffer-string))))
6861
6862 (defun tramp-check-for-regexp (proc regexp)
6863 "Check, whether REGEXP is contained in process buffer of PROC.
6864 Erase echoed commands if exists."
6865 (with-current-buffer (process-buffer proc)
6866 (goto-char (point-min))
6867
6868 ;; Check whether we need to remove echo output.
6869 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6870 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6871 (let ((begin (match-beginning 0)))
6872 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6873 ;; Discard echo from remote output.
6874 (tramp-set-connection-property proc "check-remote-echo" nil)
6875 (tramp-message proc 5 "echo-mark found")
6876 (forward-line 1)
6877 (delete-region begin (point))
6878 (goto-char (point-min)))))
6879
6880 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6881 ;; Sometimes, the echo string is suppressed on the remote side.
6882 (not (string-equal
6883 (tramp-compat-funcall
6884 'substring-no-properties tramp-echo-mark-marker
6885 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6886 (tramp-compat-funcall
6887 'buffer-substring-no-properties
6888 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6889 ;; No echo to be handled, now we can look for the regexp.
6890 (goto-char (point-min))
6891 (re-search-forward regexp nil t))))
6892
6893 (defun tramp-wait-for-regexp (proc timeout regexp)
6894 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6895 Expects the output of PROC to be sent to the current buffer. Returns
6896 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6897 nil."
6898 (with-current-buffer (process-buffer proc)
6899 (let ((found (tramp-check-for-regexp proc regexp))
6900 (start-time (current-time)))
6901 (cond (timeout
6902 ;; Work around a bug in XEmacs 21, where the timeout
6903 ;; expires faster than it should. This degenerates
6904 ;; to polling for buggy XEmacsen, but oh, well.
6905 (while (and (not found)
6906 (< (tramp-time-diff (current-time) start-time)
6907 timeout))
6908 (with-timeout (timeout)
6909 (while (not found)
6910 (tramp-accept-process-output proc 1)
6911 (unless (memq (process-status proc) '(run open))
6912 (tramp-error-with-buffer
6913 nil proc 'file-error "Process has died"))
6914 (setq found (tramp-check-for-regexp proc regexp))))))
6915 (t
6916 (while (not found)
6917 (tramp-accept-process-output proc 1)
6918 (unless (memq (process-status proc) '(run open))
6919 (tramp-error-with-buffer
6920 nil proc 'file-error "Process has died"))
6921 (setq found (tramp-check-for-regexp proc regexp)))))
6922 (tramp-message proc 6 "\n%s" (buffer-string))
6923 (when (not found)
6924 (if timeout
6925 (tramp-error
6926 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6927 regexp timeout)
6928 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6929 found)))
6930
6931 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6932 "Wait for shell prompt and barf if none appears.
6933 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6934 seconds. If not, it produces an error message with the given ERROR-ARGS."
6935 (unless
6936 (tramp-wait-for-regexp
6937 proc timeout
6938 (format
6939 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6940 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6941
6942 ;; We don't call `tramp-send-string' in order to hide the password
6943 ;; from the debug buffer, and because end-of-line handling of the
6944 ;; string.
6945 (defun tramp-enter-password (proc)
6946 "Prompt for a password and send it to the remote end."
6947 (process-send-string
6948 proc (concat (tramp-read-passwd proc)
6949 (or (tramp-get-method-parameter
6950 tramp-current-method
6951 'tramp-password-end-of-line)
6952 tramp-default-password-end-of-line))))
6953
6954 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6955 "Set up an interactive shell.
6956 Mainly sets the prompt and the echo correctly. PROC is the shell
6957 process to set up. VEC specifies the connection."
6958 (let ((tramp-end-of-output tramp-initial-end-of-output))
6959 ;; It is useful to set the prompt in the following command because
6960 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6961 ;; about and thus /bin/sh will display a strange prompt. For
6962 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6963 ;; display the current working directory but /bin/sh will display
6964 ;; a dollar sign. The following command line sets $PS1 to a sane
6965 ;; value, and works under Bourne-ish shells as well as csh-like
6966 ;; shells. Daniel Pittman reports that the unusual positioning of
6967 ;; the single quotes makes it work under `rc', too. We also unset
6968 ;; the variable $ENV because that is read by some sh
6969 ;; implementations (eg, bash when called as sh) on startup; this
6970 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6971 ;; is another way to set the prompt in /bin/bash, it must be
6972 ;; discarded as well.
6973 (tramp-open-shell
6974 vec
6975 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-remote-sh))
6976
6977 ;; Disable echo.
6978 (tramp-message vec 5 "Setting up remote shell environment")
6979 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6980 ;; Check whether the echo has really been disabled. Some
6981 ;; implementations, like busybox of embedded GNU/Linux, don't
6982 ;; support disabling.
6983 (tramp-send-command vec "echo foo" t)
6984 (with-current-buffer (process-buffer proc)
6985 (goto-char (point-min))
6986 (when (looking-at "echo foo")
6987 (tramp-set-connection-property proc "remote-echo" t)
6988 (tramp-message vec 5 "Remote echo still on. Ok.")
6989 ;; Make sure backspaces and their echo are enabled and no line
6990 ;; width magic interferes with them.
6991 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6992
6993 (tramp-message vec 5 "Setting shell prompt")
6994 (tramp-send-command
6995 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6996 (tramp-send-command vec "PS2=''" t)
6997 (tramp-send-command vec "PS3=''" t)
6998 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6999
7000 ;; Try to set up the coding system correctly.
7001 ;; CCC this can't be the right way to do it. Hm.
7002 (tramp-message vec 5 "Determining coding system")
7003 (tramp-send-command vec "echo foo ; echo bar" t)
7004 (with-current-buffer (process-buffer proc)
7005 (goto-char (point-min))
7006 (if (featurep 'mule)
7007 ;; Use MULE to select the right EOL convention for communicating
7008 ;; with the process.
7009 (let* ((cs (or (tramp-compat-funcall 'process-coding-system proc)
7010 (cons 'undecided 'undecided)))
7011 cs-decode cs-encode)
7012 (when (symbolp cs) (setq cs (cons cs cs)))
7013 (setq cs-decode (car cs))
7014 (setq cs-encode (cdr cs))
7015 (unless cs-decode (setq cs-decode 'undecided))
7016 (unless cs-encode (setq cs-encode 'undecided))
7017 (setq cs-encode (tramp-coding-system-change-eol-conversion
7018 cs-encode 'unix))
7019 (when (search-forward "\r" nil t)
7020 (setq cs-decode (tramp-coding-system-change-eol-conversion
7021 cs-decode 'dos)))
7022 (tramp-compat-funcall
7023 'set-buffer-process-coding-system cs-decode cs-encode)
7024 (tramp-message
7025 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
7026 ;; Look for ^M and do something useful if found.
7027 (when (search-forward "\r" nil t)
7028 ;; We have found a ^M but cannot frob the process coding system
7029 ;; because we're running on a non-MULE Emacs. Let's try
7030 ;; stty, instead.
7031 (tramp-send-command vec "stty -onlcr" t))))
7032
7033 (tramp-send-command vec "set +o vi +o emacs" t)
7034
7035 ;; Check whether the output of "uname -sr" has been changed. If
7036 ;; yes, this is a strong indication that we must expire all
7037 ;; connection properties. We start again with
7038 ;; `tramp-maybe-open-connection', it will be catched there.
7039 (tramp-message vec 5 "Checking system information")
7040 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
7041 (new-uname
7042 (tramp-set-connection-property
7043 vec "uname"
7044 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
7045 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
7046 (with-current-buffer (tramp-get-debug-buffer vec)
7047 ;; Keep the debug buffer.
7048 (rename-buffer
7049 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
7050 (tramp-compat-funcall 'tramp-cleanup-connection vec)
7051 (if (= (point-min) (point-max))
7052 (kill-buffer nil)
7053 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
7054 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
7055 (tramp-get-buffer vec)
7056 (tramp-message
7057 vec 3
7058 "Connection reset, because remote host changed from `%s' to `%s'"
7059 old-uname new-uname)
7060 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
7061
7062 ;; Check whether the remote host suffers from buggy
7063 ;; `send-process-string'. This is known for FreeBSD (see comment in
7064 ;; `send_process', file process.c). I've tested sending 624 bytes
7065 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
7066 ;; this host type is detected locally. It cannot handle remote
7067 ;; hosts, though.
7068 (with-connection-property proc "chunksize"
7069 (cond
7070 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
7071 tramp-chunksize)
7072 (t
7073 (tramp-message
7074 vec 5 "Checking remote host type for `send-process-string' bug")
7075 (if (string-match
7076 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
7077 500 0))))
7078
7079 ;; Set remote PATH variable.
7080 (tramp-set-remote-path vec)
7081
7082 ;; Search for a good shell before searching for a command which
7083 ;; checks if a file exists. This is done because Tramp wants to use
7084 ;; "test foo; echo $?" to check if various conditions hold, and
7085 ;; there are buggy /bin/sh implementations which don't execute the
7086 ;; "echo $?" part if the "test" part has an error. In particular,
7087 ;; the OpenSolaris /bin/sh is a problem. There are also other
7088 ;; problems with /bin/sh of OpenSolaris, like redirection of stderr
7089 ;; in function declarations, or changing HISTFILE in place.
7090 ;; Therefore, OpenSolaris' /bin/sh is replaced by bash, when
7091 ;; detected.
7092 (tramp-find-shell vec)
7093
7094 ;; Disable unexpected output.
7095 (tramp-send-command vec "mesg n; biff n" t)
7096
7097 ;; IRIX64 bash expands "!" even when in single quotes. This
7098 ;; destroys our shell functions, we must disable it. See
7099 ;; <http://stackoverflow.com/questions/3291692/irix-bash-shell-expands-expression-in-single-quotes-yet-shouldnt>.
7100 (when (string-match "^IRIX64" (tramp-get-connection-property vec "uname" ""))
7101 (tramp-send-command vec "set +H" t))
7102
7103 ;; On BSD-like systems, ?\t is expanded to spaces. Suppress this.
7104 (when (string-match "BSD\\|Darwin"
7105 (tramp-get-connection-property vec "uname" ""))
7106 (tramp-send-command vec "stty -oxtabs" t))
7107
7108 ;; Set `remote-tty' process property.
7109 (ignore-errors
7110 (let ((tty (tramp-send-command-and-read vec "echo \\\"`tty`\\\"")))
7111 (unless (zerop (length tty)) (process-put proc 'remote-tty tty))))
7112
7113 ;; Dump stty settings in the traces.
7114 (when (>= tramp-verbose 9)
7115 (tramp-send-command vec "stty -a" t))
7116
7117 ;; Set the environment.
7118 (tramp-message vec 5 "Setting default environment")
7119
7120 (let ((env (copy-sequence tramp-remote-process-environment))
7121 unset item)
7122 (while env
7123 (setq item (tramp-compat-split-string (car env) "="))
7124 (setcdr item (mapconcat 'identity (cdr item) "="))
7125 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
7126 (tramp-send-command
7127 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
7128 (push (car item) unset))
7129 (setq env (cdr env)))
7130 (when unset
7131 (tramp-send-command
7132 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
7133
7134 ;; CCC: We should either implement a Perl version of base64 encoding
7135 ;; and decoding. Then we just use that in the last item. The other
7136 ;; alternative is to use the Perl version of UU encoding. But then
7137 ;; we need a Lisp version of uuencode.
7138 ;;
7139 ;; Old text from documentation of tramp-methods:
7140 ;; Using a uuencode/uudecode inline method is discouraged, please use one
7141 ;; of the base64 methods instead since base64 encoding is much more
7142 ;; reliable and the commands are more standardized between the different
7143 ;; Unix versions. But if you can't use base64 for some reason, please
7144 ;; note that the default uudecode command does not work well for some
7145 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
7146 ;; the following command for uudecode:
7147 ;;
7148 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
7149 ;;
7150 ;; For Irix, no solution is known yet.
7151
7152 (defconst tramp-local-coding-commands
7153 '((b64 base64-encode-region base64-decode-region)
7154 (uu tramp-uuencode-region uudecode-decode-region)
7155 (pack
7156 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7157 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7158 "List of local coding commands for inline transfer.
7159 Each item is a list that looks like this:
7160
7161 \(FORMAT ENCODING DECODING\)
7162
7163 FORMAT is symbol describing the encoding/decoding format. It can be
7164 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7165
7166 ENCODING and DECODING can be strings, giving commands, or symbols,
7167 giving functions. If they are strings, then they can contain
7168 the \"%s\" format specifier. If that specifier is present, the input
7169 filename will be put into the command line at that spot. If the
7170 specifier is not present, the input should be read from standard
7171 input.
7172
7173 If they are functions, they will be called with two arguments, start
7174 and end of region, and are expected to replace the region contents
7175 with the encoded or decoded results, respectively.")
7176
7177 (defconst tramp-remote-coding-commands
7178 '((b64 "base64" "base64 -d -i")
7179 ;; "-i" is more robust with older base64 from GNU coreutils.
7180 ;; However, I don't know whether all base64 versions do supports
7181 ;; this option.
7182 (b64 "base64" "base64 -d")
7183 (b64 "mimencode -b" "mimencode -u -b")
7184 (b64 "mmencode -b" "mmencode -u -b")
7185 (b64 "recode data..base64" "recode base64..data")
7186 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
7187 (b64 tramp-perl-encode tramp-perl-decode)
7188 (uu "uuencode xxx" "uudecode -o /dev/stdout")
7189 (uu "uuencode xxx" "uudecode -o -")
7190 (uu "uuencode xxx" "uudecode -p")
7191 (uu "uuencode xxx" tramp-uudecode)
7192 (pack
7193 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
7194 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
7195 "List of remote coding commands for inline transfer.
7196 Each item is a list that looks like this:
7197
7198 \(FORMAT ENCODING DECODING\)
7199
7200 FORMAT is symbol describing the encoding/decoding format. It can be
7201 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
7202
7203 ENCODING and DECODING can be strings, giving commands, or symbols,
7204 giving variables. If they are strings, then they can contain
7205 the \"%s\" format specifier. If that specifier is present, the input
7206 filename will be put into the command line at that spot. If the
7207 specifier is not present, the input should be read from standard
7208 input.
7209
7210 If they are variables, this variable is a string containing a Perl
7211 implementation for this functionality. This Perl program will be transferred
7212 to the remote host, and it is available as shell function with the same name.")
7213
7214 (defun tramp-find-inline-encoding (vec)
7215 "Find an inline transfer encoding that works.
7216 Goes through the list `tramp-local-coding-commands' and
7217 `tramp-remote-coding-commands'."
7218 (save-excursion
7219 (let ((local-commands tramp-local-coding-commands)
7220 (magic "xyzzy")
7221 loc-enc loc-dec rem-enc rem-dec litem ritem found)
7222 (while (and local-commands (not found))
7223 (setq litem (pop local-commands))
7224 (catch 'wont-work-local
7225 (let ((format (nth 0 litem))
7226 (remote-commands tramp-remote-coding-commands))
7227 (setq loc-enc (nth 1 litem))
7228 (setq loc-dec (nth 2 litem))
7229 ;; If the local encoder or decoder is a string, the
7230 ;; corresponding command has to work locally.
7231 (if (not (stringp loc-enc))
7232 (tramp-message
7233 vec 5 "Checking local encoding function `%s'" loc-enc)
7234 (tramp-message
7235 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
7236 (unless (zerop (tramp-call-local-coding-command
7237 loc-enc nil nil))
7238 (throw 'wont-work-local nil)))
7239 (if (not (stringp loc-dec))
7240 (tramp-message
7241 vec 5 "Checking local decoding function `%s'" loc-dec)
7242 (tramp-message
7243 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
7244 (unless (zerop (tramp-call-local-coding-command
7245 loc-dec nil nil))
7246 (throw 'wont-work-local nil)))
7247 ;; Search for remote coding commands with the same format
7248 (while (and remote-commands (not found))
7249 (setq ritem (pop remote-commands))
7250 (catch 'wont-work-remote
7251 (when (equal format (nth 0 ritem))
7252 (setq rem-enc (nth 1 ritem))
7253 (setq rem-dec (nth 2 ritem))
7254 ;; Check if remote encoding and decoding commands can be
7255 ;; called remotely with null input and output. This makes
7256 ;; sure there are no syntax errors and the command is really
7257 ;; found. Note that we do not redirect stdout to /dev/null,
7258 ;; for two reasons: when checking the decoding command, we
7259 ;; actually check the output it gives. And also, when
7260 ;; redirecting "mimencode" output to /dev/null, then as root
7261 ;; it might change the permissions of /dev/null!
7262 (when (not (stringp rem-enc))
7263 (let ((name (symbol-name rem-enc)))
7264 (while (string-match (regexp-quote "-") name)
7265 (setq name (replace-match "_" nil t name)))
7266 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
7267 (setq rem-enc name)))
7268 (tramp-message
7269 vec 5
7270 "Checking remote encoding command `%s' for sanity" rem-enc)
7271 (unless (zerop (tramp-send-command-and-check
7272 vec (format "%s </dev/null" rem-enc) t))
7273 (throw 'wont-work-remote nil))
7274
7275 (when (not (stringp rem-dec))
7276 (let ((name (symbol-name rem-dec)))
7277 (while (string-match (regexp-quote "-") name)
7278 (setq name (replace-match "_" nil t name)))
7279 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
7280 (setq rem-dec name)))
7281 (tramp-message
7282 vec 5
7283 "Checking remote decoding command `%s' for sanity" rem-dec)
7284 (unless (zerop (tramp-send-command-and-check
7285 vec
7286 (format "echo %s | %s | %s"
7287 magic rem-enc rem-dec)
7288 t))
7289 (throw 'wont-work-remote nil))
7290
7291 (with-current-buffer (tramp-get-buffer vec)
7292 (goto-char (point-min))
7293 (unless (looking-at (regexp-quote magic))
7294 (throw 'wont-work-remote nil)))
7295
7296 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
7297 (setq rem-enc (nth 1 ritem))
7298 (setq rem-dec (nth 2 ritem))
7299 (setq found t)))))))
7300
7301 ;; Did we find something?
7302 (unless found
7303 (tramp-error
7304 vec 'file-error "Couldn't find an inline transfer encoding"))
7305
7306 ;; Set connection properties.
7307 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7308 (tramp-set-connection-property vec "local-encoding" loc-enc)
7309 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7310 (tramp-set-connection-property vec "local-decoding" loc-dec)
7311 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7312 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7313 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7314 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7315
7316 (defun tramp-call-local-coding-command (cmd input output)
7317 "Call the local encoding or decoding command.
7318 If CMD contains \"%s\", provide input file INPUT there in command.
7319 Otherwise, INPUT is passed via standard input.
7320 INPUT can also be nil which means `/dev/null'.
7321 OUTPUT can be a string (which specifies a filename), or t (which
7322 means standard output and thus the current buffer), or nil (which
7323 means discard it)."
7324 (tramp-local-call-process
7325 tramp-encoding-shell
7326 (when (and input (not (string-match "%s" cmd))) input)
7327 (if (eq output t) t nil)
7328 nil
7329 tramp-encoding-command-switch
7330 (concat
7331 (if (string-match "%s" cmd) (format cmd input) cmd)
7332 (if (stringp output) (concat "> " output) ""))))
7333
7334 (defconst tramp-inline-compress-commands
7335 '(("gzip" "gzip -d")
7336 ("bzip2" "bzip2 -d")
7337 ("compress" "compress -d"))
7338 "List of compress and decompress commands for inline transfer.
7339 Each item is a list that looks like this:
7340
7341 \(COMPRESS DECOMPRESS\)
7342
7343 COMPRESS or DECOMPRESS are strings with the respective commands.")
7344
7345 (defun tramp-find-inline-compress (vec)
7346 "Find an inline transfer compress command that works.
7347 Goes through the list `tramp-inline-compress-commands'."
7348 (save-excursion
7349 (let ((commands tramp-inline-compress-commands)
7350 (magic "xyzzy")
7351 item compress decompress
7352 found)
7353 (while (and commands (not found))
7354 (catch 'next
7355 (setq item (pop commands)
7356 compress (nth 0 item)
7357 decompress (nth 1 item))
7358 (tramp-message
7359 vec 5
7360 "Checking local compress command `%s', `%s' for sanity"
7361 compress decompress)
7362 (unless (zerop (tramp-call-local-coding-command
7363 (format "echo %s | %s | %s"
7364 magic compress decompress) nil nil))
7365 (throw 'next nil))
7366 (tramp-message
7367 vec 5
7368 "Checking remote compress command `%s', `%s' for sanity"
7369 compress decompress)
7370 (unless (zerop (tramp-send-command-and-check
7371 vec (format "echo %s | %s | %s"
7372 magic compress decompress) t))
7373 (throw 'next nil))
7374 (setq found t)))
7375
7376 ;; Did we find something?
7377 (if found
7378 (progn
7379 ;; Set connection properties.
7380 (tramp-message
7381 vec 5 "Using inline transfer compress command `%s'" compress)
7382 (tramp-set-connection-property vec "inline-compress" compress)
7383 (tramp-message
7384 vec 5 "Using inline transfer decompress command `%s'" decompress)
7385 (tramp-set-connection-property vec "inline-decompress" decompress))
7386
7387 (tramp-set-connection-property vec "inline-compress" nil)
7388 (tramp-set-connection-property vec "inline-decompress" nil)
7389 (tramp-message
7390 vec 2 "Couldn't find an inline transfer compress command")))))
7391
7392 (defun tramp-compute-multi-hops (vec)
7393 "Expands VEC according to `tramp-default-proxies-alist'.
7394 Gateway hops are already opened."
7395 (let ((target-alist `(,vec))
7396 (choices tramp-default-proxies-alist)
7397 item proxy)
7398
7399 ;; Look for proxy hosts to be passed.
7400 (while choices
7401 (setq item (pop choices)
7402 proxy (eval (nth 2 item)))
7403 (when (and
7404 ;; host
7405 (string-match (or (eval (nth 0 item)) "")
7406 (or (tramp-file-name-host (car target-alist)) ""))
7407 ;; user
7408 (string-match (or (eval (nth 1 item)) "")
7409 (or (tramp-file-name-user (car target-alist)) "")))
7410 (if (null proxy)
7411 ;; No more hops needed.
7412 (setq choices nil)
7413 ;; Replace placeholders.
7414 (setq proxy
7415 (format-spec
7416 proxy
7417 (format-spec-make
7418 ?u (or (tramp-file-name-user (car target-alist)) "")
7419 ?h (or (tramp-file-name-host (car target-alist)) ""))))
7420 (with-parsed-tramp-file-name proxy l
7421 ;; Add the hop.
7422 (add-to-list 'target-alist l)
7423 ;; Start next search.
7424 (setq choices tramp-default-proxies-alist)))))
7425
7426 ;; Handle gateways.
7427 (when (and (boundp 'tramp-gw-tunnel-method)
7428 (string-match (format
7429 "^\\(%s\\|%s\\)$"
7430 (symbol-value 'tramp-gw-tunnel-method)
7431 (symbol-value 'tramp-gw-socks-method))
7432 (tramp-file-name-method (car target-alist))))
7433 (let ((gw (pop target-alist))
7434 (hop (pop target-alist)))
7435 ;; Is the method prepared for gateways?
7436 (unless (tramp-get-method-parameter
7437 (tramp-file-name-method hop) 'tramp-default-port)
7438 (tramp-error
7439 vec 'file-error
7440 "Method `%s' is not supported for gateway access."
7441 (tramp-file-name-method hop)))
7442 ;; Add default port if needed.
7443 (unless
7444 (string-match
7445 tramp-host-with-port-regexp (tramp-file-name-host hop))
7446 (aset hop 2
7447 (concat
7448 (tramp-file-name-host hop) tramp-prefix-port-format
7449 (number-to-string
7450 (tramp-get-method-parameter
7451 (tramp-file-name-method hop) 'tramp-default-port)))))
7452 ;; Open the gateway connection.
7453 (add-to-list
7454 'target-alist
7455 (vector
7456 (tramp-file-name-method hop) (tramp-file-name-user hop)
7457 (tramp-compat-funcall 'tramp-gw-open-connection vec gw hop) nil))
7458 ;; For the password prompt, we need the correct values.
7459 ;; Therefore, we must remember the gateway vector. But we
7460 ;; cannot do it as connection property, because it shouldn't
7461 ;; be persistent. And we have no started process yet either.
7462 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7463
7464 ;; Foreign and out-of-band methods are not supported for multi-hops.
7465 (when (cdr target-alist)
7466 (setq choices target-alist)
7467 (while choices
7468 (setq item (pop choices))
7469 (when
7470 (or
7471 (not
7472 (tramp-get-method-parameter
7473 (tramp-file-name-method item) 'tramp-login-program))
7474 (tramp-get-method-parameter
7475 (tramp-file-name-method item) 'tramp-copy-program))
7476 (tramp-error
7477 vec 'file-error
7478 "Method `%s' is not supported for multi-hops."
7479 (tramp-file-name-method item)))))
7480
7481 ;; In case the host name is not used for the remote shell
7482 ;; command, the user could be misguided by applying a random
7483 ;; hostname.
7484 (let* ((v (car target-alist))
7485 (method (tramp-file-name-method v))
7486 (host (tramp-file-name-host v)))
7487 (unless
7488 (or
7489 ;; There are multi-hops.
7490 (cdr target-alist)
7491 ;; The host name is used for the remote shell command.
7492 (member
7493 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7494 ;; The host is local. We cannot use `tramp-local-host-p'
7495 ;; here, because it opens a connection as well.
7496 (string-match tramp-local-host-regexp host))
7497 (tramp-error
7498 v 'file-error
7499 "Host `%s' looks like a remote host, `%s' can only use the local host"
7500 host method)))
7501
7502 ;; Result.
7503 target-alist))
7504
7505 (defun tramp-maybe-open-connection (vec)
7506 "Maybe open a connection VEC.
7507 Does not do anything if a connection is already open, but re-opens the
7508 connection if a previous connection has died for some reason."
7509 (catch 'uname-changed
7510 (let ((p (tramp-get-connection-process vec))
7511 (process-name (tramp-get-connection-property vec "process-name" nil))
7512 (process-environment (copy-sequence process-environment)))
7513
7514 ;; If too much time has passed since last command was sent, look
7515 ;; whether process is still alive. If it isn't, kill it. When
7516 ;; using ssh, it can sometimes happen that the remote end has
7517 ;; hung up but the local ssh client doesn't recognize this until
7518 ;; it tries to send some data to the remote end. So that's why
7519 ;; we try to send a command from time to time, then look again
7520 ;; whether the process is really alive.
7521 (condition-case nil
7522 (when (and (> (tramp-time-diff
7523 (current-time)
7524 (tramp-get-connection-property
7525 p "last-cmd-time" '(0 0 0)))
7526 60)
7527 p (processp p) (memq (process-status p) '(run open)))
7528 (tramp-send-command vec "echo are you awake" t t)
7529 (unless (and (memq (process-status p) '(run open))
7530 (tramp-wait-for-output p 10))
7531 ;; The error will be catched locally.
7532 (tramp-error vec 'file-error "Awake did fail")))
7533 (file-error
7534 (tramp-flush-connection-property vec)
7535 (tramp-flush-connection-property p)
7536 (delete-process p)
7537 (setq p nil)))
7538
7539 ;; New connection must be opened.
7540 (unless (and p (processp p) (memq (process-status p) '(run open)))
7541
7542 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7543 ;; messages from the beginning.
7544 (tramp-get-buffer vec)
7545 (with-progress-reporter
7546 vec 3
7547 (if (zerop (length (tramp-file-name-user vec)))
7548 (format "Opening connection for %s using %s"
7549 (tramp-file-name-host vec)
7550 (tramp-file-name-method vec))
7551 (format "Opening connection for %s@%s using %s"
7552 (tramp-file-name-user vec)
7553 (tramp-file-name-host vec)
7554 (tramp-file-name-method vec)))
7555
7556 ;; Start new process.
7557 (when (and p (processp p))
7558 (delete-process p))
7559 (setenv "TERM" tramp-terminal-type)
7560 (setenv "LC_ALL" "C")
7561 (setenv "PROMPT_COMMAND")
7562 (setenv "PS1" tramp-initial-end-of-output)
7563 (let* ((target-alist (tramp-compute-multi-hops vec))
7564 (process-connection-type tramp-process-connection-type)
7565 (process-adaptive-read-buffering nil)
7566 (coding-system-for-read nil)
7567 ;; This must be done in order to avoid our file name handler.
7568 (p (let ((default-directory
7569 (tramp-compat-temporary-file-directory)))
7570 (start-process
7571 (or process-name (tramp-buffer-name vec))
7572 (tramp-get-connection-buffer vec)
7573 tramp-encoding-shell))))
7574
7575 (tramp-message
7576 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7577
7578 ;; Check whether process is alive.
7579 (tramp-set-process-query-on-exit-flag p nil)
7580 (tramp-barf-if-no-shell-prompt
7581 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7582
7583 ;; Now do all the connections as specified.
7584 (while target-alist
7585 (let* ((hop (car target-alist))
7586 (l-method (tramp-file-name-method hop))
7587 (l-user (tramp-file-name-user hop))
7588 (l-host (tramp-file-name-host hop))
7589 (l-port nil)
7590 (login-program
7591 (tramp-get-method-parameter
7592 l-method 'tramp-login-program))
7593 (login-args
7594 (tramp-get-method-parameter l-method 'tramp-login-args))
7595 (async-args
7596 (tramp-get-method-parameter l-method 'tramp-async-args))
7597 (gw-args
7598 (tramp-get-method-parameter l-method 'tramp-gw-args))
7599 (gw (tramp-get-file-property hop "" "gateway" nil))
7600 (g-method (and gw (tramp-file-name-method gw)))
7601 (g-user (and gw (tramp-file-name-user gw)))
7602 (g-host (and gw (tramp-file-name-host gw)))
7603 (command login-program)
7604 ;; We don't create the temporary file. In fact,
7605 ;; it is just a prefix for the ControlPath option
7606 ;; of ssh; the real temporary file has another
7607 ;; name, and it is created and protected by ssh.
7608 ;; It is also removed by ssh, when the connection
7609 ;; is closed.
7610 (tmpfile
7611 (tramp-set-connection-property
7612 p "temp-file"
7613 (make-temp-name
7614 (expand-file-name
7615 tramp-temp-name-prefix
7616 (tramp-compat-temporary-file-directory)))))
7617 spec)
7618
7619 ;; Add arguments for asynchrononous processes.
7620 (when (and process-name async-args)
7621 (setq login-args (append async-args login-args)))
7622
7623 ;; Add gateway arguments if necessary.
7624 (when (and gw gw-args)
7625 (setq login-args (append gw-args login-args)))
7626
7627 ;; Check for port number. Until now, there's no need
7628 ;; for handling like method, user, host.
7629 (when (string-match tramp-host-with-port-regexp l-host)
7630 (setq l-port (match-string 2 l-host)
7631 l-host (match-string 1 l-host)))
7632
7633 ;; Set variables for computing the prompt for reading
7634 ;; password. They can also be derived from a gateway.
7635 (setq tramp-current-method (or g-method l-method)
7636 tramp-current-user (or g-user l-user)
7637 tramp-current-host (or g-host l-host))
7638
7639 ;; Replace login-args place holders.
7640 (setq
7641 l-host (or l-host "")
7642 l-user (or l-user "")
7643 l-port (or l-port "")
7644 spec (format-spec-make
7645 ?h l-host ?u l-user ?p l-port ?t tmpfile)
7646 command
7647 (concat
7648 ;; We do not want to see the trailing local prompt in
7649 ;; `start-file-process'.
7650 (unless (memq system-type '(windows-nt)) "exec ")
7651 command " "
7652 (mapconcat
7653 (lambda (x)
7654 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7655 (unless (member "" x) (mapconcat 'identity x " ")))
7656 login-args " ")
7657 ;; Local shell could be a Windows COMSPEC. It
7658 ;; doesn't know the ";" syntax, but we must exit
7659 ;; always for `start-file-process'. "exec" does not
7660 ;; work either.
7661 (if (memq system-type '(windows-nt)) " && exit || exit")))
7662
7663 ;; Send the command.
7664 (tramp-message vec 3 "Sending command `%s'" command)
7665 (tramp-send-command vec command t t)
7666 (tramp-process-actions p vec tramp-actions-before-shell 60)
7667 (tramp-message
7668 vec 3 "Found remote shell prompt on `%s'" l-host))
7669 ;; Next hop.
7670 (setq target-alist (cdr target-alist)))
7671
7672 ;; Make initial shell settings.
7673 (tramp-open-connection-setup-interactive-shell p vec)))))))
7674
7675 (defun tramp-send-command (vec command &optional neveropen nooutput)
7676 "Send the COMMAND to connection VEC.
7677 Erases temporary buffer before sending the command. If optional
7678 arg NEVEROPEN is non-nil, never try to open the connection. This
7679 is meant to be used from `tramp-maybe-open-connection' only. The
7680 function waits for output unless NOOUTPUT is set."
7681 (unless neveropen (tramp-maybe-open-connection vec))
7682 (let ((p (tramp-get-connection-process vec)))
7683 (when (tramp-get-connection-property p "remote-echo" nil)
7684 ;; We mark the command string that it can be erased in the output buffer.
7685 (tramp-set-connection-property p "check-remote-echo" t)
7686 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7687 (tramp-message vec 6 "%s" command)
7688 (tramp-send-string vec command)
7689 (unless nooutput (tramp-wait-for-output p))))
7690
7691 (defun tramp-wait-for-output (proc &optional timeout)
7692 "Wait for output from remote command."
7693 (unless (buffer-live-p (process-buffer proc))
7694 (delete-process proc)
7695 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7696 (with-current-buffer (process-buffer proc)
7697 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7698 ;; be leading escape sequences, which must be ignored.
7699 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7700 ;; Sometimes, the commands do not return a newline but a
7701 ;; null byte before the shell prompt, for example "git
7702 ;; ls-files -c -z ...".
7703 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7704 (found (tramp-wait-for-regexp proc timeout regexp1)))
7705 (if found
7706 (let (buffer-read-only)
7707 ;; A simple-minded busybox has sent " ^H" sequences.
7708 ;; Delete them.
7709 (goto-char (point-min))
7710 (when (re-search-forward
7711 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7712 (forward-line 1)
7713 (delete-region (point-min) (point)))
7714 ;; Delete the prompt.
7715 (goto-char (point-max))
7716 (re-search-backward regexp nil t)
7717 (delete-region (point) (point-max)))
7718 (if timeout
7719 (tramp-error
7720 proc 'file-error
7721 "[[Remote prompt `%s' not found in %d secs]]"
7722 tramp-end-of-output timeout)
7723 (tramp-error
7724 proc 'file-error
7725 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7726 ;; Return value is whether end-of-output sentinel was found.
7727 found)))
7728
7729 (defun tramp-send-command-and-check
7730 (vec command &optional subshell dont-suppress-err)
7731 "Run COMMAND and check its exit status.
7732 Sends `echo $?' along with the COMMAND for checking the exit status. If
7733 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7734
7735 If the optional argument SUBSHELL is non-nil, the command is
7736 executed in a subshell, ie surrounded by parentheses. If
7737 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7738 (tramp-send-command
7739 vec
7740 (concat (if subshell "( " "")
7741 command
7742 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7743 "echo tramp_exit_status $?"
7744 (if subshell " )" "")))
7745 (with-current-buffer (tramp-get-connection-buffer vec)
7746 (goto-char (point-max))
7747 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7748 (tramp-error
7749 vec 'file-error "Couldn't find exit status of `%s'" command))
7750 (skip-chars-forward "^ ")
7751 (prog1
7752 (read (current-buffer))
7753 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7754
7755 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7756 "Run COMMAND, check exit status, throw error if exit status not okay.
7757 Similar to `tramp-send-command-and-check' but accepts two more arguments
7758 FMT and ARGS which are passed to `error'."
7759 (unless (zerop (tramp-send-command-and-check vec command))
7760 (apply 'tramp-error vec 'file-error fmt args)))
7761
7762 (defun tramp-send-command-and-read (vec command)
7763 "Run COMMAND and return the output, which must be a Lisp expression.
7764 In case there is no valid Lisp expression, it raises an error"
7765 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7766 (with-current-buffer (tramp-get-connection-buffer vec)
7767 ;; Read the expression.
7768 (goto-char (point-min))
7769 (condition-case nil
7770 (prog1 (read (current-buffer))
7771 ;; Error handling.
7772 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7773 (error nil)))
7774 (error (tramp-error
7775 vec 'file-error
7776 "`%s' does not return a valid Lisp expression: `%s'"
7777 command (buffer-string))))))
7778
7779 ;; It seems that Tru64 Unix does not like it if long strings are sent
7780 ;; to it in one go. (This happens when sending the Perl
7781 ;; `file-attributes' implementation, for instance.) Therefore, we
7782 ;; have this function which sends the string in chunks.
7783 (defun tramp-send-string (vec string)
7784 "Send the STRING via connection VEC.
7785
7786 The STRING is expected to use Unix line-endings, but the lines sent to
7787 the remote host use line-endings as defined in the variable
7788 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7789 (let* ((p (tramp-get-connection-process vec))
7790 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7791 (unless p
7792 (tramp-error
7793 vec 'file-error "Can't send string to remote host -- not logged in"))
7794 (tramp-set-connection-property p "last-cmd-time" (current-time))
7795 (tramp-message vec 10 "%s" string)
7796 (with-current-buffer (tramp-get-connection-buffer vec)
7797 ;; Clean up the buffer. We cannot call `erase-buffer' because
7798 ;; narrowing might be in effect.
7799 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7800 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7801 (setq string
7802 (mapconcat 'identity
7803 (tramp-compat-split-string string "\n")
7804 tramp-rsh-end-of-line))
7805 (unless (or (string= string "")
7806 (string-equal (substring string -1) tramp-rsh-end-of-line))
7807 (setq string (concat string tramp-rsh-end-of-line)))
7808 ;; Send the string.
7809 (if (and chunksize (not (zerop chunksize)))
7810 (let ((pos 0)
7811 (end (length string)))
7812 (while (< pos end)
7813 (tramp-message
7814 vec 10 "Sending chunk from %s to %s"
7815 pos (min (+ pos chunksize) end))
7816 (process-send-string
7817 p (substring string pos (min (+ pos chunksize) end)))
7818 (setq pos (+ pos chunksize))))
7819 (process-send-string p string)))))
7820
7821 (defun tramp-mode-string-to-int (mode-string)
7822 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7823 (let* (case-fold-search
7824 (mode-chars (string-to-vector mode-string))
7825 (owner-read (aref mode-chars 1))
7826 (owner-write (aref mode-chars 2))
7827 (owner-execute-or-setid (aref mode-chars 3))
7828 (group-read (aref mode-chars 4))
7829 (group-write (aref mode-chars 5))
7830 (group-execute-or-setid (aref mode-chars 6))
7831 (other-read (aref mode-chars 7))
7832 (other-write (aref mode-chars 8))
7833 (other-execute-or-sticky (aref mode-chars 9)))
7834 (save-match-data
7835 (logior
7836 (cond
7837 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7838 ((char-equal owner-read ?-) 0)
7839 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7840 (cond
7841 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7842 ((char-equal owner-write ?-) 0)
7843 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7844 (cond
7845 ((char-equal owner-execute-or-setid ?x)
7846 (tramp-octal-to-decimal "00100"))
7847 ((char-equal owner-execute-or-setid ?S)
7848 (tramp-octal-to-decimal "04000"))
7849 ((char-equal owner-execute-or-setid ?s)
7850 (tramp-octal-to-decimal "04100"))
7851 ((char-equal owner-execute-or-setid ?-) 0)
7852 (t (error "Fourth char `%c' must be one of `xsS-'"
7853 owner-execute-or-setid)))
7854 (cond
7855 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7856 ((char-equal group-read ?-) 0)
7857 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7858 (cond
7859 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7860 ((char-equal group-write ?-) 0)
7861 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7862 (cond
7863 ((char-equal group-execute-or-setid ?x)
7864 (tramp-octal-to-decimal "00010"))
7865 ((char-equal group-execute-or-setid ?S)
7866 (tramp-octal-to-decimal "02000"))
7867 ((char-equal group-execute-or-setid ?s)
7868 (tramp-octal-to-decimal "02010"))
7869 ((char-equal group-execute-or-setid ?-) 0)
7870 (t (error "Seventh char `%c' must be one of `xsS-'"
7871 group-execute-or-setid)))
7872 (cond
7873 ((char-equal other-read ?r)
7874 (tramp-octal-to-decimal "00004"))
7875 ((char-equal other-read ?-) 0)
7876 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7877 (cond
7878 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7879 ((char-equal other-write ?-) 0)
7880 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7881 (cond
7882 ((char-equal other-execute-or-sticky ?x)
7883 (tramp-octal-to-decimal "00001"))
7884 ((char-equal other-execute-or-sticky ?T)
7885 (tramp-octal-to-decimal "01000"))
7886 ((char-equal other-execute-or-sticky ?t)
7887 (tramp-octal-to-decimal "01001"))
7888 ((char-equal other-execute-or-sticky ?-) 0)
7889 (t (error "Tenth char `%c' must be one of `xtT-'"
7890 other-execute-or-sticky)))))))
7891
7892 (defun tramp-convert-file-attributes (vec attr)
7893 "Convert file-attributes ATTR generated by perl script, stat or ls.
7894 Convert file mode bits to string and set virtual device number.
7895 Return ATTR."
7896 (when attr
7897 ;; Convert last access time.
7898 (unless (listp (nth 4 attr))
7899 (setcar (nthcdr 4 attr)
7900 (list (floor (nth 4 attr) 65536)
7901 (floor (mod (nth 4 attr) 65536)))))
7902 ;; Convert last modification time.
7903 (unless (listp (nth 5 attr))
7904 (setcar (nthcdr 5 attr)
7905 (list (floor (nth 5 attr) 65536)
7906 (floor (mod (nth 5 attr) 65536)))))
7907 ;; Convert last status change time.
7908 (unless (listp (nth 6 attr))
7909 (setcar (nthcdr 6 attr)
7910 (list (floor (nth 6 attr) 65536)
7911 (floor (mod (nth 6 attr) 65536)))))
7912 ;; Convert file size.
7913 (when (< (nth 7 attr) 0)
7914 (setcar (nthcdr 7 attr) -1))
7915 (when (and (floatp (nth 7 attr))
7916 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7917 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7918 ;; Convert file mode bits to string.
7919 (unless (stringp (nth 8 attr))
7920 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7921 (when (stringp (car attr))
7922 (aset (nth 8 attr) 0 ?l)))
7923 ;; Convert directory indication bit.
7924 (when (string-match "^d" (nth 8 attr))
7925 (setcar attr t))
7926 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7927 (when (consp (car attr))
7928 (if (and (stringp (caar attr))
7929 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7930 (setcar attr (match-string 1 (caar attr)))
7931 (setcar attr nil)))
7932 ;; Set file's gid change bit.
7933 (setcar (nthcdr 9 attr)
7934 (if (numberp (nth 3 attr))
7935 (not (= (nth 3 attr)
7936 (tramp-get-remote-gid vec 'integer)))
7937 (not (string-equal
7938 (nth 3 attr)
7939 (tramp-get-remote-gid vec 'string)))))
7940 ;; Convert inode.
7941 (unless (listp (nth 10 attr))
7942 (setcar (nthcdr 10 attr)
7943 (condition-case nil
7944 (cons (floor (nth 10 attr) 65536)
7945 (floor (mod (nth 10 attr) 65536)))
7946 ;; Inodes can be incredible huge. We must hide this.
7947 (error (tramp-get-inode vec)))))
7948 ;; Set virtual device number.
7949 (setcar (nthcdr 11 attr)
7950 (tramp-get-device vec))
7951 attr))
7952
7953 (defun tramp-check-cached-permissions (vec access)
7954 "Check `file-attributes' caches for VEC.
7955 Return t if according to the cache access type ACCESS is known to
7956 be granted."
7957 (let ((result nil)
7958 (offset (cond
7959 ((eq ?r access) 1)
7960 ((eq ?w access) 2)
7961 ((eq ?x access) 3))))
7962 (dolist (suffix '("string" "integer") result)
7963 (setq
7964 result
7965 (or
7966 result
7967 (let ((file-attr
7968 (tramp-get-file-property
7969 vec (tramp-file-name-localname vec)
7970 (concat "file-attributes-" suffix) nil))
7971 (remote-uid
7972 (tramp-get-connection-property
7973 vec (concat "uid-" suffix) nil))
7974 (remote-gid
7975 (tramp-get-connection-property
7976 vec (concat "gid-" suffix) nil)))
7977 (and
7978 file-attr
7979 (or
7980 ;; Not a symlink
7981 (eq t (car file-attr))
7982 (null (car file-attr)))
7983 (or
7984 ;; World accessible.
7985 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7986 ;; User accessible and owned by user.
7987 (and
7988 (eq access (aref (nth 8 file-attr) offset))
7989 (equal remote-uid (nth 2 file-attr)))
7990 ;; Group accessible and owned by user's
7991 ;; principal group.
7992 (and
7993 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7994 (equal remote-gid (nth 3 file-attr)))))))))))
7995
7996 (defun tramp-get-inode (vec)
7997 "Returns the virtual inode number.
7998 If it doesn't exist, generate a new one."
7999 (let ((string (tramp-make-tramp-file-name
8000 (tramp-file-name-method vec)
8001 (tramp-file-name-user vec)
8002 (tramp-file-name-host vec)
8003 "")))
8004 (unless (assoc string tramp-inodes)
8005 (add-to-list 'tramp-inodes
8006 (list string (length tramp-inodes))))
8007 (nth 1 (assoc string tramp-inodes))))
8008
8009 (defun tramp-get-device (vec)
8010 "Returns the virtual device number.
8011 If it doesn't exist, generate a new one."
8012 (let ((string (tramp-make-tramp-file-name
8013 (tramp-file-name-method vec)
8014 (tramp-file-name-user vec)
8015 (tramp-file-name-host vec)
8016 "")))
8017 (unless (assoc string tramp-devices)
8018 (add-to-list 'tramp-devices
8019 (list string (length tramp-devices))))
8020 (cons -1 (nth 1 (assoc string tramp-devices)))))
8021
8022 (defun tramp-file-mode-from-int (mode)
8023 "Turn an integer representing a file mode into an ls(1)-like string."
8024 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
8025 (user (logand (lsh mode -6) 7))
8026 (group (logand (lsh mode -3) 7))
8027 (other (logand (lsh mode -0) 7))
8028 (suid (> (logand (lsh mode -9) 4) 0))
8029 (sgid (> (logand (lsh mode -9) 2) 0))
8030 (sticky (> (logand (lsh mode -9) 1) 0)))
8031 (setq user (tramp-file-mode-permissions user suid "s"))
8032 (setq group (tramp-file-mode-permissions group sgid "s"))
8033 (setq other (tramp-file-mode-permissions other sticky "t"))
8034 (concat type user group other)))
8035
8036 (defun tramp-file-mode-permissions (perm suid suid-text)
8037 "Convert a permission bitset into a string.
8038 This is used internally by `tramp-file-mode-from-int'."
8039 (let ((r (> (logand perm 4) 0))
8040 (w (> (logand perm 2) 0))
8041 (x (> (logand perm 1) 0)))
8042 (concat (or (and r "r") "-")
8043 (or (and w "w") "-")
8044 (or (and suid x suid-text) ; suid, execute
8045 (and suid (upcase suid-text)) ; suid, !execute
8046 (and x "x") "-")))) ; !suid
8047
8048 (defun tramp-decimal-to-octal (i)
8049 "Return a string consisting of the octal digits of I.
8050 Not actually used. Use `(format \"%o\" i)' instead?"
8051 (cond ((< i 0) (error "Cannot convert negative number to octal"))
8052 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
8053 ((zerop i) "0")
8054 (t (concat (tramp-decimal-to-octal (/ i 8))
8055 (number-to-string (% i 8))))))
8056
8057 ;; Kudos to Gerd Moellmann for this suggestion.
8058 (defun tramp-octal-to-decimal (ostr)
8059 "Given a string of octal digits, return a decimal number."
8060 (let ((x (or ostr "")))
8061 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
8062 (unless (string-match "\\`[0-7]*\\'" x)
8063 (error "Non-octal junk in string `%s'" x))
8064 (string-to-number ostr 8)))
8065
8066 (defun tramp-shell-case-fold (string)
8067 "Converts STRING to shell glob pattern which ignores case."
8068 (mapconcat
8069 (lambda (c)
8070 (if (equal (downcase c) (upcase c))
8071 (vector c)
8072 (format "[%c%c]" (downcase c) (upcase c))))
8073 string
8074 ""))
8075
8076
8077 ;; ------------------------------------------------------------
8078 ;; -- Tramp file names --
8079 ;; ------------------------------------------------------------
8080 ;; Conversion functions between external representation and
8081 ;; internal data structure. Convenience functions for internal
8082 ;; data structure.
8083
8084 (defun tramp-file-name-p (vec)
8085 "Check, whether VEC is a Tramp object."
8086 (and (vectorp vec) (= 4 (length vec))))
8087
8088 (defun tramp-file-name-method (vec)
8089 "Return method component of VEC."
8090 (and (tramp-file-name-p vec) (aref vec 0)))
8091
8092 (defun tramp-file-name-user (vec)
8093 "Return user component of VEC."
8094 (and (tramp-file-name-p vec) (aref vec 1)))
8095
8096 (defun tramp-file-name-host (vec)
8097 "Return host component of VEC."
8098 (and (tramp-file-name-p vec) (aref vec 2)))
8099
8100 (defun tramp-file-name-localname (vec)
8101 "Return localname component of VEC."
8102 (and (tramp-file-name-p vec) (aref vec 3)))
8103
8104 ;; The user part of a Tramp file name vector can be of kind
8105 ;; "user%domain". Sometimes, we must extract these parts.
8106 (defun tramp-file-name-real-user (vec)
8107 "Return the user name of VEC without domain."
8108 (save-match-data
8109 (let ((user (tramp-file-name-user vec)))
8110 (if (and (stringp user)
8111 (string-match tramp-user-with-domain-regexp user))
8112 (match-string 1 user)
8113 user))))
8114
8115 (defun tramp-file-name-domain (vec)
8116 "Return the domain name of VEC."
8117 (save-match-data
8118 (let ((user (tramp-file-name-user vec)))
8119 (and (stringp user)
8120 (string-match tramp-user-with-domain-regexp user)
8121 (match-string 2 user)))))
8122
8123 ;; The host part of a Tramp file name vector can be of kind
8124 ;; "host#port". Sometimes, we must extract these parts.
8125 (defun tramp-file-name-real-host (vec)
8126 "Return the host name of VEC without port."
8127 (save-match-data
8128 (let ((host (tramp-file-name-host vec)))
8129 (if (and (stringp host)
8130 (string-match tramp-host-with-port-regexp host))
8131 (match-string 1 host)
8132 host))))
8133
8134 (defun tramp-file-name-port (vec)
8135 "Return the port number of VEC."
8136 (save-match-data
8137 (let ((host (tramp-file-name-host vec)))
8138 (and (stringp host)
8139 (string-match tramp-host-with-port-regexp host)
8140 (string-to-number (match-string 2 host))))))
8141
8142 (defun tramp-tramp-file-p (name)
8143 "Return t if NAME is a string with Tramp file name syntax."
8144 (save-match-data
8145 (and (stringp name) (string-match tramp-file-name-regexp name))))
8146
8147 (defun tramp-find-method (method user host)
8148 "Return the right method string to use.
8149 This is METHOD, if non-nil. Otherwise, do a lookup in
8150 `tramp-default-method-alist'."
8151 (or method
8152 (let ((choices tramp-default-method-alist)
8153 lmethod item)
8154 (while choices
8155 (setq item (pop choices))
8156 (when (and (string-match (or (nth 0 item) "") (or host ""))
8157 (string-match (or (nth 1 item) "") (or user "")))
8158 (setq lmethod (nth 2 item))
8159 (setq choices nil)))
8160 lmethod)
8161 tramp-default-method))
8162
8163 (defun tramp-find-user (method user host)
8164 "Return the right user string to use.
8165 This is USER, if non-nil. Otherwise, do a lookup in
8166 `tramp-default-user-alist'."
8167 (or user
8168 (let ((choices tramp-default-user-alist)
8169 luser item)
8170 (while choices
8171 (setq item (pop choices))
8172 (when (and (string-match (or (nth 0 item) "") (or method ""))
8173 (string-match (or (nth 1 item) "") (or host "")))
8174 (setq luser (nth 2 item))
8175 (setq choices nil)))
8176 luser)
8177 tramp-default-user))
8178
8179 (defun tramp-find-host (method user host)
8180 "Return the right host string to use.
8181 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
8182 (or (and (> (length host) 0) host)
8183 tramp-default-host))
8184
8185 (defun tramp-dissect-file-name (name &optional nodefault)
8186 "Return a `tramp-file-name' structure.
8187 The structure consists of remote method, remote user, remote host
8188 and localname (file name on remote host). If NODEFAULT is
8189 non-nil, the file name parts are not expanded to their default
8190 values."
8191 (save-match-data
8192 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
8193 (unless match (error "Not a Tramp file name: %s" name))
8194 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
8195 (user (match-string (nth 2 tramp-file-name-structure) name))
8196 (host (match-string (nth 3 tramp-file-name-structure) name))
8197 (localname (match-string (nth 4 tramp-file-name-structure) name)))
8198 (when (member method '("multi" "multiu"))
8199 (error
8200 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
8201 method))
8202 (when host
8203 (when (string-match tramp-prefix-ipv6-regexp host)
8204 (setq host (replace-match "" nil t host)))
8205 (when (string-match tramp-postfix-ipv6-regexp host)
8206 (setq host (replace-match "" nil t host))))
8207 (if nodefault
8208 (vector method user host localname)
8209 (vector
8210 (tramp-find-method method user host)
8211 (tramp-find-user method user host)
8212 (tramp-find-host method user host)
8213 localname))))))
8214
8215 (defun tramp-equal-remote (file1 file2)
8216 "Check, whether the remote parts of FILE1 and FILE2 are identical.
8217 The check depends on method, user and host name of the files. If
8218 one of the components is missing, the default values are used.
8219 The local file name parts of FILE1 and FILE2 are not taken into
8220 account.
8221
8222 Example:
8223
8224 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
8225
8226 would yield `t'. On the other hand, the following check results in nil:
8227
8228 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
8229 (and (stringp (file-remote-p file1))
8230 (stringp (file-remote-p file2))
8231 (string-equal (file-remote-p file1) (file-remote-p file2))))
8232
8233 (defun tramp-make-tramp-file-name (method user host localname)
8234 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
8235 (concat tramp-prefix-format
8236 (when (not (zerop (length method)))
8237 (concat method tramp-postfix-method-format))
8238 (when (not (zerop (length user)))
8239 (concat user tramp-postfix-user-format))
8240 (when host
8241 (if (string-match tramp-ipv6-regexp host)
8242 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8243 host))
8244 tramp-postfix-host-format
8245 (when localname localname)))
8246
8247 (defun tramp-completion-make-tramp-file-name (method user host localname)
8248 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
8249 It must not be a complete Tramp file name, but as long as there are
8250 necessary only. This function will be used in file name completion."
8251 (concat tramp-prefix-format
8252 (when (not (zerop (length method)))
8253 (concat method tramp-postfix-method-format))
8254 (when (not (zerop (length user)))
8255 (concat user tramp-postfix-user-format))
8256 (when (not (zerop (length host)))
8257 (concat
8258 (if (string-match tramp-ipv6-regexp host)
8259 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
8260 host)
8261 tramp-postfix-host-format))
8262 (when localname localname)))
8263
8264 (defun tramp-make-copy-program-file-name (vec)
8265 "Create a file name suitable to be passed to `rcp' and workalikes."
8266 (let ((user (tramp-file-name-user vec))
8267 (host (tramp-file-name-real-host vec))
8268 (localname (tramp-shell-quote-argument
8269 (tramp-file-name-localname vec))))
8270 (if (not (zerop (length user)))
8271 (format "%s@%s:%s" user host localname)
8272 (format "%s:%s" host localname))))
8273
8274 (defun tramp-method-out-of-band-p (vec size)
8275 "Return t if this is an out-of-band method, nil otherwise."
8276 (and
8277 ;; It shall be an out-of-band method.
8278 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
8279 ;; Either the file size is large enough, or (in rare cases) there
8280 ;; does not exist a remote encoding.
8281 (or (null tramp-copy-size-limit)
8282 (> size tramp-copy-size-limit)
8283 (null (tramp-get-inline-coding vec "remote-encoding" size)))))
8284
8285 (defun tramp-local-host-p (vec)
8286 "Return t if this points to the local host, nil otherwise."
8287 ;; We cannot use `tramp-file-name-real-host'. A port is an
8288 ;; indication for an ssh tunnel or alike.
8289 (let ((host (tramp-file-name-host vec)))
8290 (and
8291 (stringp host)
8292 (string-match tramp-local-host-regexp host)
8293 ;; The method shall be applied to one of the shell file name
8294 ;; handler. `tramp-local-host-p' is also called for "smb" and
8295 ;; alike, where it must fail.
8296 (tramp-get-method-parameter
8297 (tramp-file-name-method vec) 'tramp-login-program)
8298 ;; The local temp directory must be writable for the other user.
8299 (file-writable-p
8300 (tramp-make-tramp-file-name
8301 (tramp-file-name-method vec)
8302 (tramp-file-name-user vec)
8303 host
8304 (tramp-compat-temporary-file-directory)))
8305 ;; On some systems, chown runs only for root.
8306 (or (zerop (user-uid))
8307 (zerop (tramp-get-remote-uid vec 'integer))))))
8308
8309 ;; Variables local to connection.
8310
8311 (defun tramp-get-remote-path (vec)
8312 (with-connection-property
8313 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
8314 ;; cache the result for the session only. Otherwise, the result
8315 ;; is cached persistently.
8316 (if (memq 'tramp-own-remote-path tramp-remote-path)
8317 (tramp-get-connection-process vec)
8318 vec)
8319 "remote-path"
8320 (let* ((remote-path (copy-tree tramp-remote-path))
8321 (elt1 (memq 'tramp-default-remote-path remote-path))
8322 (elt2 (memq 'tramp-own-remote-path remote-path))
8323 (default-remote-path
8324 (when elt1
8325 (condition-case nil
8326 (tramp-send-command-and-read
8327 vec "echo \\\"`getconf PATH`\\\"")
8328 ;; Default if "getconf" is not available.
8329 (error
8330 (tramp-message
8331 vec 3
8332 "`getconf PATH' not successful, using default value \"%s\"."
8333 "/bin:/usr/bin")
8334 "/bin:/usr/bin"))))
8335 (own-remote-path
8336 (when elt2
8337 (condition-case nil
8338 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
8339 ;; Default if "getconf" is not available.
8340 (error
8341 (tramp-message
8342 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
8343 nil)))))
8344
8345 ;; Replace place holder `tramp-default-remote-path'.
8346 (when elt1
8347 (setcdr elt1
8348 (append
8349 (tramp-compat-split-string default-remote-path ":")
8350 (cdr elt1)))
8351 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
8352
8353 ;; Replace place holder `tramp-own-remote-path'.
8354 (when elt2
8355 (setcdr elt2
8356 (append
8357 (tramp-compat-split-string own-remote-path ":")
8358 (cdr elt2)))
8359 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
8360
8361 ;; Remove double entries.
8362 (setq elt1 remote-path)
8363 (while (consp elt1)
8364 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
8365 (setcar elt2 nil))
8366 (setq elt1 (cdr elt1)))
8367
8368 ;; Remove non-existing directories.
8369 (delq
8370 nil
8371 (mapcar
8372 (lambda (x)
8373 (and
8374 (stringp x)
8375 (file-directory-p
8376 (tramp-make-tramp-file-name
8377 (tramp-file-name-method vec)
8378 (tramp-file-name-user vec)
8379 (tramp-file-name-host vec)
8380 x))
8381 x))
8382 remote-path)))))
8383
8384 (defun tramp-get-remote-tmpdir (vec)
8385 (with-connection-property vec "tmp-directory"
8386 (let ((dir (tramp-shell-quote-argument "/tmp")))
8387 (if (and (zerop
8388 (tramp-send-command-and-check
8389 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8390 (zerop
8391 (tramp-send-command-and-check
8392 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8393 dir
8394 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8395
8396 (defun tramp-get-ls-command (vec)
8397 (with-connection-property vec "ls"
8398 (tramp-message vec 5 "Finding a suitable `ls' command")
8399 (or
8400 (catch 'ls-found
8401 (dolist (cmd '("ls" "gnuls" "gls"))
8402 (let ((dl (tramp-get-remote-path vec))
8403 result)
8404 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8405 ;; Check parameters. On busybox, "ls" output coloring is
8406 ;; enabled by default sometimes. So we try to disable it
8407 ;; when possible. $LS_COLORING is not supported there.
8408 ;; Some "ls" versions are sensible wrt the order of
8409 ;; arguments, they fail when "-al" is after the
8410 ;; "--color=never" argument (for example on FreeBSD).
8411 (when (zerop (tramp-send-command-and-check
8412 vec (format "%s -lnd /" result)))
8413 (when (zerop (tramp-send-command-and-check
8414 vec (format
8415 "%s --color=never -al /dev/null" result)))
8416 (setq result (concat result " --color=never")))
8417 (throw 'ls-found result))
8418 (setq dl (cdr dl))))))
8419 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8420
8421 (defun tramp-get-ls-command-with-dired (vec)
8422 (save-match-data
8423 (with-connection-property vec "ls-dired"
8424 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8425 ;; Some "ls" versions are sensible wrt the order of arguments,
8426 ;; they fail when "-al" is after the "--dired" argument (for
8427 ;; example on FreeBSD).
8428 (zerop (tramp-send-command-and-check
8429 vec (format "%s --dired -al /dev/null"
8430 (tramp-get-ls-command vec)))))))
8431
8432 (defun tramp-get-test-command (vec)
8433 (with-connection-property vec "test"
8434 (tramp-message vec 5 "Finding a suitable `test' command")
8435 (if (zerop (tramp-send-command-and-check vec "test 0"))
8436 "test"
8437 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8438
8439 (defun tramp-get-test-nt-command (vec)
8440 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8441 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8442 ;; for otherwise the shell crashes.
8443 (with-connection-property vec "test-nt"
8444 (or
8445 (progn
8446 (tramp-send-command
8447 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8448 (with-current-buffer (tramp-get-buffer vec)
8449 (goto-char (point-min))
8450 (when (looking-at (regexp-quote tramp-end-of-output))
8451 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8452 (progn
8453 (tramp-send-command
8454 vec
8455 (format
8456 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8457 (tramp-get-test-command vec)))
8458 "tramp_test_nt %s %s"))))
8459
8460 (defun tramp-get-file-exists-command (vec)
8461 (with-connection-property vec "file-exists"
8462 (tramp-message vec 5 "Finding command to check if file exists")
8463 (tramp-find-file-exists-command vec)))
8464
8465 (defun tramp-get-remote-ln (vec)
8466 (with-connection-property vec "ln"
8467 (tramp-message vec 5 "Finding a suitable `ln' command")
8468 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8469
8470 (defun tramp-get-remote-perl (vec)
8471 (with-connection-property vec "perl"
8472 (tramp-message vec 5 "Finding a suitable `perl' command")
8473 (let ((result
8474 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8475 (tramp-find-executable
8476 vec "perl" (tramp-get-remote-path vec)))))
8477 ;; We must check also for some Perl modules.
8478 (when result
8479 (with-connection-property vec "perl-file-spec"
8480 (zerop
8481 (tramp-send-command-and-check
8482 vec (format "%s -e 'use File::Spec;'" result))))
8483 (with-connection-property vec "perl-cwd-realpath"
8484 (zerop
8485 (tramp-send-command-and-check
8486 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8487 result)))
8488
8489 (defun tramp-get-remote-stat (vec)
8490 (with-connection-property vec "stat"
8491 (tramp-message vec 5 "Finding a suitable `stat' command")
8492 (let ((result (tramp-find-executable
8493 vec "stat" (tramp-get-remote-path vec)))
8494 tmp)
8495 ;; Check whether stat(1) returns usable syntax. %s does not
8496 ;; work on older AIX systems.
8497 (when result
8498 (setq tmp
8499 ;; We don't want to display an error message.
8500 (with-temp-message (or (current-message) "")
8501 (condition-case nil
8502 (tramp-send-command-and-read
8503 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8504 (error nil))))
8505 (unless (and (listp tmp) (stringp (car tmp))
8506 (string-match "^./.$" (car tmp))
8507 (integerp (cadr tmp)))
8508 (setq result nil)))
8509 result)))
8510
8511 (defun tramp-get-remote-readlink (vec)
8512 (with-connection-property vec "readlink"
8513 (tramp-message vec 5 "Finding a suitable `readlink' command")
8514 (let ((result (tramp-find-executable
8515 vec "readlink" (tramp-get-remote-path vec))))
8516 (when (and result
8517 ;; We don't want to display an error message.
8518 (with-temp-message (or (current-message) "")
8519 (condition-case nil
8520 (zerop
8521 (tramp-send-command-and-check
8522 vec (format "%s --canonicalize-missing /" result)))
8523 (error nil))))
8524 result))))
8525
8526 (defun tramp-get-remote-trash (vec)
8527 (with-connection-property vec "trash"
8528 (tramp-message vec 5 "Finding a suitable `trash' command")
8529 (tramp-find-executable vec "trash" (tramp-get-remote-path vec))))
8530
8531 (defun tramp-get-remote-id (vec)
8532 (with-connection-property vec "id"
8533 (tramp-message vec 5 "Finding POSIX `id' command")
8534 (or
8535 (catch 'id-found
8536 (let ((dl (tramp-get-remote-path vec))
8537 result)
8538 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8539 ;; Check POSIX parameter.
8540 (when (zerop (tramp-send-command-and-check
8541 vec (format "%s -u" result)))
8542 (throw 'id-found result))
8543 (setq dl (cdr dl)))))
8544 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8545
8546 (defun tramp-get-remote-uid (vec id-format)
8547 (with-connection-property vec (format "uid-%s" id-format)
8548 (let ((res (tramp-send-command-and-read
8549 vec
8550 (format "%s -u%s %s"
8551 (tramp-get-remote-id vec)
8552 (if (equal id-format 'integer) "" "n")
8553 (if (equal id-format 'integer)
8554 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8555 ;; The command might not always return a number.
8556 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8557
8558 (defun tramp-get-remote-gid (vec id-format)
8559 (with-connection-property vec (format "gid-%s" id-format)
8560 (let ((res (tramp-send-command-and-read
8561 vec
8562 (format "%s -g%s %s"
8563 (tramp-get-remote-id vec)
8564 (if (equal id-format 'integer) "" "n")
8565 (if (equal id-format 'integer)
8566 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8567 ;; The command might not always return a number.
8568 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8569
8570 (defun tramp-get-local-uid (id-format)
8571 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8572
8573 (defun tramp-get-local-gid (id-format)
8574 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8575
8576 ;; Some predefined connection properties.
8577 (defun tramp-get-inline-compress (vec prop size)
8578 "Return the compress command related to PROP.
8579 PROP is either `inline-compress' or `inline-decompress'. SIZE is
8580 the length of the file to be compressed.
8581
8582 If no corresponding command is found, nil is returned."
8583 (when (and (integerp tramp-inline-compress-start-size)
8584 (> size tramp-inline-compress-start-size))
8585 (with-connection-property vec prop
8586 (tramp-find-inline-compress vec)
8587 (tramp-get-connection-property vec prop nil))))
8588
8589 (defun tramp-get-inline-coding (vec prop size)
8590 "Return the coding command related to PROP.
8591 PROP is either `remote-encoding', `remode-decoding',
8592 `local-encoding' or `local-decoding'.
8593
8594 SIZE is the length of the file to be coded. Depending on SIZE,
8595 compression might be applied.
8596
8597 If no corresponding command is found, nil is returned.
8598 Otherwise, either a string is returned which contains a `%s' mark
8599 to be used for the respective input or output file; or a Lisp
8600 function cell is returned to be applied on a buffer."
8601 ;; We must catch the errors, because we want to return `nil', when
8602 ;; no inline coding is found.
8603 (ignore-errors
8604 (let ((coding
8605 (with-connection-property vec prop
8606 (tramp-find-inline-encoding vec)
8607 (tramp-get-connection-property vec prop nil)))
8608 (prop1 (if (string-match "encoding" prop)
8609 "inline-compress" "inline-decompress"))
8610 compress)
8611 ;; The connection property might have been cached. So we must
8612 ;; send the script to the remote side - maybe.
8613 (when (and coding (symbolp coding) (string-match "remote" prop))
8614 (let ((name (symbol-name coding)))
8615 (while (string-match (regexp-quote "-") name)
8616 (setq name (replace-match "_" nil t name)))
8617 (tramp-maybe-send-script vec (symbol-value coding) name)
8618 (setq coding name)))
8619 (when coding
8620 ;; Check for the `compress' command.
8621 (setq compress (tramp-get-inline-compress vec prop1 size))
8622 ;; Return the value.
8623 (cond
8624 ((and compress (symbolp coding))
8625 (if (string-match "decompress" prop1)
8626 `(lambda (beg end)
8627 (,coding beg end)
8628 (let ((coding-system-for-write 'binary)
8629 (coding-system-for-read 'binary))
8630 (apply
8631 'call-process-region (point-min) (point-max)
8632 (car (split-string ,compress)) t t nil
8633 (cdr (split-string ,compress)))))
8634 `(lambda (beg end)
8635 (let ((coding-system-for-write 'binary)
8636 (coding-system-for-read 'binary))
8637 (apply
8638 'call-process-region beg end
8639 (car (split-string ,compress)) t t nil
8640 (cdr (split-string ,compress))))
8641 (,coding (point-min) (point-max)))))
8642 ((symbolp coding)
8643 coding)
8644 ((and compress (string-match "decoding" prop))
8645 (format "(%s | %s >%%s)" coding compress))
8646 (compress
8647 (format "(%s <%%s | %s)" compress coding))
8648 ((string-match "decoding" prop)
8649 (format "%s >%%s" coding))
8650 (t
8651 (format "%s <%%s" coding)))))))
8652
8653 (defun tramp-get-method-parameter (method param)
8654 "Return the method parameter PARAM.
8655 If the `tramp-methods' entry does not exist, return nil."
8656 (let ((entry (assoc param (assoc method tramp-methods))))
8657 (when entry (cadr entry))))
8658
8659 ;; Auto saving to a special directory.
8660
8661 (defun tramp-exists-file-name-handler (operation &rest args)
8662 "Check, whether OPERATION runs a file name handler."
8663 ;; The file name handler is determined on base of either an
8664 ;; argument, `buffer-file-name', or `default-directory'.
8665 (condition-case nil
8666 (let* ((buffer-file-name "/")
8667 (default-directory "/")
8668 (fnha file-name-handler-alist)
8669 (check-file-name-operation operation)
8670 (file-name-handler-alist
8671 (list
8672 (cons "/"
8673 (lambda (operation &rest args)
8674 "Returns OPERATION if it is the one to be checked."
8675 (if (equal check-file-name-operation operation)
8676 operation
8677 (let ((file-name-handler-alist fnha))
8678 (apply operation args))))))))
8679 (equal (apply operation args) operation))
8680 (error nil)))
8681
8682 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8683 (defadvice make-auto-save-file-name
8684 (around tramp-advice-make-auto-save-file-name () activate)
8685 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8686 (if (tramp-tramp-file-p (buffer-file-name))
8687 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8688 ;; directly, because this would bypass the locking mechanism.
8689 (setq ad-return-value
8690 (tramp-file-name-handler 'make-auto-save-file-name))
8691 ad-do-it))
8692 (add-hook
8693 'tramp-unload-hook
8694 (lambda ()
8695 (ad-remove-advice
8696 'make-auto-save-file-name
8697 'around 'tramp-advice-make-auto-save-file-name)
8698 (ad-activate 'make-auto-save-file-name))))
8699
8700 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
8701 ;; umask. This is a security threat.
8702
8703 (defun tramp-set-auto-save-file-modes ()
8704 "Set permissions of autosaved remote files to the original permissions."
8705 (let ((bfn (buffer-file-name)))
8706 (when (and (tramp-tramp-file-p bfn)
8707 (buffer-modified-p)
8708 (stringp buffer-auto-save-file-name)
8709 (not (equal bfn buffer-auto-save-file-name)))
8710 (unless (file-exists-p buffer-auto-save-file-name)
8711 (write-region "" nil buffer-auto-save-file-name))
8712 ;; Permissions should be set always, because there might be an old
8713 ;; auto-saved file belonging to another original file. This could
8714 ;; be a security threat.
8715 (set-file-modes buffer-auto-save-file-name
8716 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8717
8718 (unless (and (featurep 'xemacs)
8719 (= emacs-major-version 21)
8720 (> emacs-minor-version 4))
8721 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8722 (add-hook 'tramp-unload-hook
8723 (lambda ()
8724 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8725
8726 (defun tramp-subst-strs-in-string (alist string)
8727 "Replace all occurrences of the string FROM with TO in STRING.
8728 ALIST is of the form ((FROM . TO) ...)."
8729 (save-match-data
8730 (while alist
8731 (let* ((pr (car alist))
8732 (from (car pr))
8733 (to (cdr pr)))
8734 (while (string-match (regexp-quote from) string)
8735 (setq string (replace-match to t t string)))
8736 (setq alist (cdr alist))))
8737 string))
8738
8739 ;; ------------------------------------------------------------
8740 ;; -- Compatibility functions section --
8741 ;; ------------------------------------------------------------
8742
8743 (defun tramp-read-passwd (proc &optional prompt)
8744 "Read a password from user (compat function).
8745 Consults the auth-source package.
8746 Invokes `password-read' if available, `read-passwd' else."
8747 (let* ((key (tramp-make-tramp-file-name
8748 tramp-current-method tramp-current-user
8749 tramp-current-host ""))
8750 (pw-prompt
8751 (or prompt
8752 (with-current-buffer (process-buffer proc)
8753 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8754 (format "%s for %s " (capitalize (match-string 1)) key)))))
8755 (with-parsed-tramp-file-name key nil
8756 (prog1
8757 (or
8758 ;; See if auth-sources contains something useful, if it's bound.
8759 (and (boundp 'auth-sources)
8760 (tramp-get-connection-property v "first-password-request" nil)
8761 ;; Try with Tramp's current method.
8762 (tramp-compat-funcall
8763 'auth-source-user-or-password
8764 "password" tramp-current-host tramp-current-method))
8765 ;; Try the password cache.
8766 (when (functionp 'password-read)
8767 (unless (tramp-get-connection-property
8768 v "first-password-request" nil)
8769 (tramp-compat-funcall 'password-cache-remove key))
8770 (let ((password
8771 (tramp-compat-funcall 'password-read pw-prompt key)))
8772 (tramp-compat-funcall 'password-cache-add key password)
8773 password))
8774 ;; Else, get the password interactively.
8775 (read-passwd pw-prompt))
8776 (tramp-set-connection-property v "first-password-request" nil)))))
8777
8778 (defun tramp-clear-passwd (vec)
8779 "Clear password cache for connection related to VEC."
8780 (tramp-compat-funcall
8781 'password-cache-remove
8782 (tramp-make-tramp-file-name
8783 (tramp-file-name-method vec)
8784 (tramp-file-name-user vec)
8785 (tramp-file-name-host vec)
8786 "")))
8787
8788 ;; Snarfed code from time-date.el and parse-time.el
8789
8790 (defconst tramp-half-a-year '(241 17024)
8791 "Evaluated by \"(days-to-time 183)\".")
8792
8793 (defconst tramp-parse-time-months
8794 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8795 ("apr" . 4) ("may" . 5) ("jun" . 6)
8796 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8797 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8798 "Alist mapping month names to integers.")
8799
8800 (defun tramp-time-less-p (t1 t2)
8801 "Say whether time value T1 is less than time value T2."
8802 (unless t1 (setq t1 '(0 0)))
8803 (unless t2 (setq t2 '(0 0)))
8804 (or (< (car t1) (car t2))
8805 (and (= (car t1) (car t2))
8806 (< (nth 1 t1) (nth 1 t2)))))
8807
8808 (defun tramp-time-subtract (t1 t2)
8809 "Subtract two time values.
8810 Return the difference in the format of a time value."
8811 (unless t1 (setq t1 '(0 0)))
8812 (unless t2 (setq t2 '(0 0)))
8813 (let ((borrow (< (cadr t1) (cadr t2))))
8814 (list (- (car t1) (car t2) (if borrow 1 0))
8815 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8816
8817 (defun tramp-time-diff (t1 t2)
8818 "Return the difference between the two times, in seconds.
8819 T1 and T2 are time values (as returned by `current-time' for example)."
8820 ;; Pacify byte-compiler with `symbol-function'.
8821 (cond ((and (fboundp 'subtract-time)
8822 (fboundp 'float-time))
8823 (tramp-compat-funcall
8824 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
8825 ((and (fboundp 'subtract-time)
8826 (fboundp 'time-to-seconds))
8827 (tramp-compat-funcall
8828 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
8829 ((fboundp 'itimer-time-difference)
8830 (tramp-compat-funcall
8831 'itimer-time-difference
8832 (if (< (length t1) 3) (append t1 '(0)) t1)
8833 (if (< (length t2) 3) (append t2 '(0)) t2)))
8834 (t
8835 (let ((time (tramp-time-subtract t1 t2)))
8836 (+ (* (car time) 65536.0)
8837 (cadr time)
8838 (/ (or (nth 2 time) 0) 1000000.0))))))
8839
8840 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8841 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8842 EOL-TYPE can be one of `dos', `unix', or `mac'."
8843 (cond ((fboundp 'coding-system-change-eol-conversion)
8844 (tramp-compat-funcall
8845 'coding-system-change-eol-conversion coding-system eol-type))
8846 ((fboundp 'subsidiary-coding-system)
8847 (tramp-compat-funcall
8848 'subsidiary-coding-system coding-system
8849 (cond ((eq eol-type 'dos) 'crlf)
8850 ((eq eol-type 'unix) 'lf)
8851 ((eq eol-type 'mac) 'cr)
8852 (t
8853 (error "Unknown EOL-TYPE `%s', must be %s"
8854 eol-type
8855 "`dos', `unix', or `mac'")))))
8856 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8857
8858 (defun tramp-set-process-query-on-exit-flag (process flag)
8859 "Specify if query is needed for process when Emacs is exited.
8860 If the second argument flag is non-nil, Emacs will query the user before
8861 exiting if process is running."
8862 (if (fboundp 'set-process-query-on-exit-flag)
8863 (tramp-compat-funcall 'set-process-query-on-exit-flag process flag)
8864 (tramp-compat-funcall 'process-kill-without-query process flag)))
8865
8866
8867 ;; ------------------------------------------------------------
8868 ;; -- Kludges section --
8869 ;; ------------------------------------------------------------
8870
8871 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8872 ;; does not deal well with newline characters. Newline is replaced by
8873 ;; backslash newline. But if, say, the string `a backslash newline b'
8874 ;; is passed to a shell, the shell will expand this into "ab",
8875 ;; completely omitting the newline. This is not what was intended.
8876 ;; It does not appear to be possible to make the function
8877 ;; `shell-quote-argument' work with newlines without making it
8878 ;; dependent on the shell used. But within this package, we know that
8879 ;; we will always use a Bourne-like shell, so we use an approach which
8880 ;; groks newlines.
8881 ;;
8882 ;; The approach is simple: we call `shell-quote-argument', then
8883 ;; massage the newline part of the result.
8884 ;;
8885 ;; This function should produce a string which is grokked by a Unix
8886 ;; shell, even if the Emacs is running on Windows. Since this is the
8887 ;; kludges section, we bind `system-type' in such a way that
8888 ;; `shell-quote-arguments' behaves as if on Unix.
8889 ;;
8890 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8891 ;; function to work with Bourne-like shells.
8892 ;;
8893 ;; CCC: This function should be rewritten so that
8894 ;; `shell-quote-argument' is not used. This way, we are safe from
8895 ;; changes in `shell-quote-argument'.
8896 (defun tramp-shell-quote-argument (s)
8897 "Similar to `shell-quote-argument', but groks newlines.
8898 Only works for Bourne-like shells."
8899 (let ((system-type 'not-windows))
8900 (save-match-data
8901 (let ((result (shell-quote-argument s))
8902 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8903 (when (and (>= (length result) 2)
8904 (string= (substring result 0 2) "\\~"))
8905 (setq result (substring result 1)))
8906 (while (string-match nl result)
8907 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8908 t t result)))
8909 result))))
8910
8911 ;; Checklist for `tramp-unload-hook'
8912 ;; - Unload all `tramp-*' packages
8913 ;; - Reset `file-name-handler-alist'
8914 ;; - Cleanup hooks where Tramp functions are in
8915 ;; - Cleanup advised functions
8916 ;; - Cleanup autoloads
8917 ;;;###autoload
8918 (defun tramp-unload-tramp ()
8919 "Discard Tramp from loading remote files."
8920 (interactive)
8921 ;; When Tramp is not loaded yet, its autoloads are still active.
8922 (tramp-unload-file-name-handlers)
8923 ;; ange-ftp settings must be enabled.
8924 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
8925 ;; Maybe its not loaded yet.
8926 (condition-case nil
8927 (unload-feature 'tramp 'force)
8928 (error nil)))
8929
8930 (when (and load-in-progress
8931 (string-match "Loading tramp..." (or (current-message) "")))
8932 (message "Loading tramp...done"))
8933
8934 (provide 'tramp)
8935
8936 ;;; TODO:
8937
8938 ;; * Handle nonlocal exits such as C-g.
8939 ;; * But it would probably be better to use with-local-quit at the
8940 ;; place where it's actually needed: around any potentially
8941 ;; indefinitely blocking piece of code. In this case it would be
8942 ;; within Tramp around one of its calls to accept-process-output (or
8943 ;; around one of the loops that calls accept-process-output)
8944 ;; (Stefan Monnier).
8945 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8946 ;; `shell-quote-argument'.
8947 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8948 ;; by the files in that directory. Add this here.
8949 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8950 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8951 ;; * Don't use globbing for directories with many files, as this is
8952 ;; likely to produce long command lines, and some shells choke on
8953 ;; long command lines.
8954 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8955 ;; * abbreviate-file-name
8956 ;; * Better error checking. At least whenever we see something
8957 ;; strange when doing zerop, we should kill the process and start
8958 ;; again. (Greg Stark)
8959 ;; * Remove unneeded parameters from methods.
8960 ;; * Make it work for different encodings, and for different file name
8961 ;; encodings, too. (Daniel Pittman)
8962 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8963 ;; then look if it's the right version (with `perl -v').
8964 ;; * When editing a remote CVS controlled file as a different user, VC
8965 ;; gets confused about the file locking status. Try to find out why
8966 ;; the workaround doesn't work.
8967 ;; * Username and hostname completion.
8968 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8969 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8970 ;; Code is nearly identical.
8971 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8972 ;; until the last but one hop via `start-file-process'. Apply it
8973 ;; also for ftp and smb.
8974 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8975 ;; some shell with root priviledges, it would be nice if I could
8976 ;; just call
8977 ;; trampclient filename.c
8978 ;; as an editor, and the _current_ shell would connect to an Emacs
8979 ;; server and would be used in an existing non-priviledged Emacs
8980 ;; session for doing the editing in question.
8981 ;; That way, I need not tell Emacs my password again and be afraid
8982 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8983 ;; once display a just typed password in the context of a keyboard
8984 ;; sequence prompt for a question immediately following in a shell
8985 ;; script run within Emacs -- nasty).
8986 ;; And if I have some ssh session running to a different computer,
8987 ;; having the possibility of passing a local file there to a local
8988 ;; Emacs session (in case I can arrange for a connection back) would
8989 ;; be nice.
8990 ;; Likely the corresponding Tramp server should not allow the
8991 ;; equivalent of the emacsclient -eval option in order to make this
8992 ;; reasonably unproblematic. And maybe trampclient should have some
8993 ;; way of passing credentials, like by using an SSL socket or
8994 ;; something. (David Kastrup)
8995 ;; * Reconnect directly to a compliant shell without first going
8996 ;; through the user's default shell. (Pete Forman)
8997 ;; * Make `tramp-default-user' obsolete.
8998 ;; * How can I interrupt the remote process with a signal
8999 ;; (interrupt-process seems not to work)? (Markus Triska)
9000 ;; * Avoid the local shell entirely for starting remote processes. If
9001 ;; so, I think even a signal, when delivered directly to the local
9002 ;; SSH instance, would correctly be propagated to the remote process
9003 ;; automatically; possibly SSH would have to be started with
9004 ;; "-t". (Markus Triska)
9005 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
9006 ;; isn't on the remote host. (Mark A. Hershberger)
9007 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
9008 ;; * Implement a general server-local-variable mechanism, as there are
9009 ;; probably other variables that need different values for different
9010 ;; servers too. The user could then configure a variable (such as
9011 ;; tramp-server-local-variable-alist) to define any such variables
9012 ;; that they need to, which would then be let bound as appropriate
9013 ;; in tramp functions. (Jason Rumney)
9014 ;; * Optimize out-of-band copying, when both methods are scp-like (not
9015 ;; rsync).
9016 ;; * Keep a second connection open for out-of-band methods like scp or
9017 ;; rsync.
9018 ;; * IMHO, it's a drawback that currently Tramp doesn't support
9019 ;; Unicode in Dired file names by default. Is it possible to
9020 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
9021 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
9022 ;; expects only English messages? (Juri Linkov)
9023 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
9024 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448, Bug#5705)
9025 ;; * Try telnet+curl as new method. It might be useful for busybox,
9026 ;; without built-in uuencode/uudecode.
9027 ;; * Load ~/.emacs_SHELLNAME on the remote host for `shell'.
9028 ;; * I was wondering it it would be possible to use tramp even if I'm
9029 ;; actually using sshfs. But when I launch a command I would like
9030 ;; to get it executed on the remote machine where the files really
9031 ;; are. (Andrea Crotti)
9032 ;; * Run emerge on two remote files. Bug is described here:
9033 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
9034 ;; (Bug#6850)
9035
9036 ;; Functions for file-name-handler-alist:
9037 ;; diff-latest-backup-file -- in diff.el
9038
9039 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
9040 ;;; tramp.el ends here
9041
9042 ;; Local Variables:
9043 ;; mode: Emacs-Lisp
9044 ;; coding: utf-8
9045 ;; End: