]> code.delx.au - gnu-emacs/blob - lisp/net/tramp.el
* net/tramp.el (tramp-handle-insert-directory): Handle also
[gnu-emacs] / lisp / net / tramp.el
1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; (copyright statements below in code to be updated with the above notice)
7
8 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
9 ;; Michael Albinus <michael.albinus@gmx.de>
10 ;; Keywords: comm, processes
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; This package provides remote file editing, similar to ange-ftp.
30 ;; The difference is that ange-ftp uses FTP to transfer files between
31 ;; the local and the remote host, whereas tramp.el uses a combination
32 ;; of rsh and rcp or other work-alike programs, such as ssh/scp.
33 ;;
34 ;; For more detailed instructions, please see the info file.
35 ;;
36 ;; Notes:
37 ;; -----
38 ;;
39 ;; This package only works for Emacs 21.1 and higher, and for XEmacs 21.4
40 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
41 ;; the `with-timeout' macro.
42 ;;
43 ;; Also see the todo list at the bottom of this file.
44 ;;
45 ;; The current version of Tramp can be retrieved from the following URL:
46 ;; http://ftp.gnu.org/gnu/tramp/
47 ;;
48 ;; There's a mailing list for this, as well. Its name is:
49 ;; tramp-devel@gnu.org
50 ;; You can use the Web to subscribe, under the following URL:
51 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
52 ;;
53 ;; For the adventurous, the current development sources are available
54 ;; via CVS. You can find instructions about this at the following URL:
55 ;; http://savannah.gnu.org/projects/tramp/
56 ;; Click on "CVS" in the navigation bar near the top.
57 ;;
58 ;; Don't forget to put on your asbestos longjohns, first!
59
60 ;;; Code:
61
62 ;; Since Emacs 23.1, loading messages have been disabled during
63 ;; autoload. However, loading Tramp takes a while, and it could
64 ;; happen while typing a filename in the minibuffer. Therefore, Tramp
65 ;; shall inform about.
66 (when (and load-in-progress (null (current-message)))
67 (message "Loading tramp..."))
68
69 ;; The Tramp version number and bug report address, as prepared by configure.
70 (require 'trampver)
71 (add-hook 'tramp-unload-hook
72 (lambda ()
73 (when (featurep 'trampver)
74 (unload-feature 'trampver 'force))))
75
76 (require 'tramp-compat)
77 (add-hook 'tramp-unload-hook
78 (lambda ()
79 (when (featurep 'tramp-compat)
80 (unload-feature 'tramp-compat 'force))))
81
82 (require 'format-spec) ; from Gnus 5.8, also in tar ball
83 ;; As long as password.el is not part of (X)Emacs, it shouldn't
84 ;; be mandatory
85 (if (featurep 'xemacs)
86 (load "password" 'noerror)
87 (or (require 'password-cache nil 'noerror)
88 (require 'password nil 'noerror))) ; from No Gnus, also in tar ball
89
90 (require 'shell)
91 (require 'advice)
92
93 (eval-and-compile
94 (if (featurep 'xemacs)
95 (load "auth-source" 'noerror)
96 (require 'auth-source nil 'noerror)))
97
98 ;; Requiring 'tramp-cache results in an endless loop.
99 (autoload 'tramp-get-file-property "tramp-cache")
100 (autoload 'tramp-set-file-property "tramp-cache")
101 (autoload 'tramp-flush-file-property "tramp-cache")
102 (autoload 'tramp-flush-directory-property "tramp-cache")
103 (autoload 'tramp-get-connection-property "tramp-cache")
104 (autoload 'tramp-set-connection-property "tramp-cache")
105 (autoload 'tramp-flush-connection-property "tramp-cache")
106 (autoload 'tramp-parse-connection-properties "tramp-cache")
107 (add-hook 'tramp-unload-hook
108 (lambda ()
109 (when (featurep 'tramp-cache)
110 (unload-feature 'tramp-cache 'force))))
111
112 (autoload 'tramp-uuencode-region "tramp-uu"
113 "Implementation of `uuencode' in Lisp.")
114 (add-hook 'tramp-unload-hook
115 (lambda ()
116 (when (featurep 'tramp-uu)
117 (unload-feature 'tramp-uu 'force))))
118
119 (autoload 'uudecode-decode-region "uudecode")
120
121 ;; The following Tramp packages must be loaded after tramp.el, because
122 ;; they require it as well.
123 (eval-after-load "tramp"
124 '(dolist
125 (feature
126 (list
127
128 ;; Tramp interactive commands.
129 'tramp-cmds
130
131 ;; Load foreign FTP method.
132 (if (featurep 'xemacs) 'tramp-efs 'tramp-ftp)
133
134 ;; tramp-smb uses "smbclient" from Samba. Not available
135 ;; under Cygwin and Windows, because they don't offer
136 ;; "smbclient". And even not necessary there, because Emacs
137 ;; supports UNC file names like "//host/share/localname".
138 (unless (memq system-type '(cygwin windows-nt)) 'tramp-smb)
139
140 ;; Load foreign FISH method.
141 'tramp-fish
142
143 ;; tramp-gvfs needs D-Bus messages. Available since Emacs 23
144 ;; on some system types. We don't call `dbus-ping', because
145 ;; this would load dbus.el.
146 (when (and (featurep 'dbusbind)
147 (condition-case nil
148 (funcall 'dbus-get-unique-name :session)
149 (error nil))
150 (tramp-compat-process-running-p "gvfs-fuse-daemon"))
151 'tramp-gvfs)
152
153 ;; Load gateways. It needs `make-network-process' from Emacs 22.
154 (when (functionp 'make-network-process) 'tramp-gw)
155
156 ;; tramp-imap needs both epa (from Emacs 23.1) and imap-hash
157 ;; (from Emacs 23.2).
158 (when (and (locate-library "epa") (locate-library "imap-hash"))
159 'tramp-imap)))
160
161 (when feature
162 ;; We have used just some basic tests, whether a package shall
163 ;; be added. There might still be other errors during loading,
164 ;; which we will catch here.
165 (catch 'tramp-loading
166 (require feature)
167 (add-hook 'tramp-unload-hook
168 `(lambda ()
169 (when (featurep (quote ,feature))
170 (unload-feature (quote ,feature) 'force)))))
171 (unless (featurep feature)
172 (message "Loading %s failed, ignoring this package" feature)))))
173
174 ;;; User Customizable Internal Variables:
175
176 (defgroup tramp nil
177 "Edit remote files with a combination of rsh and rcp or similar programs."
178 :group 'files
179 :version "22.1")
180
181 ;; Maybe we need once a real Tramp mode, with key bindings etc.
182 ;;;###autoload
183 (defcustom tramp-mode t
184 "*Whether Tramp is enabled.
185 If it is set to nil, all remote file names are used literally."
186 :group 'tramp
187 :type 'boolean)
188
189 (defcustom tramp-verbose 3
190 "*Verbosity level for Tramp messages.
191 Any level x includes messages for all levels 1 .. x-1. The levels are
192
193 0 silent (no tramp messages at all)
194 1 errors
195 2 warnings
196 3 connection to remote hosts (default level)
197 4 activities
198 5 internal
199 6 sent and received strings
200 7 file caching
201 8 connection properties
202 10 traces (huge)."
203 :group 'tramp
204 :type 'integer)
205
206 ;; Emacs case.
207 (eval-and-compile
208 (when (boundp 'backup-directory-alist)
209 (defcustom tramp-backup-directory-alist nil
210 "Alist of filename patterns and backup directory names.
211 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
212 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
213 is a local file name, the backup directory is prepended with Tramp file
214 name prefix \(method, user, host\) of file.
215
216 \(setq tramp-backup-directory-alist backup-directory-alist\)
217
218 gives the same backup policy for Tramp files on their hosts like the
219 policy for local files."
220 :group 'tramp
221 :type '(repeat (cons (regexp :tag "Regexp matching filename")
222 (directory :tag "Backup directory name"))))))
223
224 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
225 ;; the package "backup-dir" might not be loaded yet.
226 (eval-and-compile
227 (when (featurep 'xemacs)
228 (defcustom tramp-bkup-backup-directory-info nil
229 "*Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
230 It has the same meaning like `bkup-backup-directory-info' from package
231 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
232 file name, the backup directory is prepended with Tramp file name prefix
233 \(method, user, host\) of file.
234
235 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
236
237 gives the same backup policy for Tramp files on their hosts like the
238 policy for local files."
239 :type '(repeat
240 (list (regexp :tag "File regexp")
241 (string :tag "Backup Dir")
242 (set :inline t
243 (const ok-create)
244 (const full-path)
245 (const prepend-name)
246 (const search-upward))))
247 :group 'tramp)))
248
249 (defcustom tramp-auto-save-directory nil
250 "*Put auto-save files in this directory, if set.
251 The idea is to use a local directory so that auto-saving is faster."
252 :group 'tramp
253 :type '(choice (const nil) string))
254
255 (defcustom tramp-encoding-shell
256 (if (memq system-type '(windows-nt))
257 (getenv "COMSPEC")
258 "/bin/sh")
259 "*Use this program for encoding and decoding commands on the local host.
260 This shell is used to execute the encoding and decoding command on the
261 local host, so if you want to use `~' in those commands, you should
262 choose a shell here which groks tilde expansion. `/bin/sh' normally
263 does not understand tilde expansion.
264
265 For encoding and deocding, commands like the following are executed:
266
267 /bin/sh -c COMMAND < INPUT > OUTPUT
268
269 This variable can be used to change the \"/bin/sh\" part. See the
270 variable `tramp-encoding-command-switch' for the \"-c\" part.
271
272 Note that this variable is not used for remote commands. There are
273 mechanisms in tramp.el which automatically determine the right shell to
274 use for the remote host."
275 :group 'tramp
276 :type '(file :must-match t))
277
278 (defcustom tramp-encoding-command-switch
279 (if (string-match "cmd\\.exe" tramp-encoding-shell)
280 "/c"
281 "-c")
282 "*Use this switch together with `tramp-encoding-shell' for local commands.
283 See the variable `tramp-encoding-shell' for more information."
284 :group 'tramp
285 :type 'string)
286
287 (defcustom tramp-copy-size-limit 10240
288 "*The maximum file size where inline copying is preferred over an out-of-the-band copy."
289 :group 'tramp
290 :type 'integer)
291
292 (defcustom tramp-terminal-type "dumb"
293 "*Value of TERM environment variable for logging in to remote host.
294 Because Tramp wants to parse the output of the remote shell, it is easily
295 confused by ANSI color escape sequences and suchlike. Often, shell init
296 files conditionalize this setup based on the TERM environment variable."
297 :group 'tramp
298 :type 'string)
299
300 ;; ksh on OpenBSD 4.5 requires, that PS1 contains a `#' character for
301 ;; root users. It uses the `$' character for other users. In order
302 ;; to guarantee a proper prompt, we use "#$" for the prompt.
303
304 (defvar tramp-end-of-output
305 (format
306 "///%s#$"
307 (md5 (concat (prin1-to-string process-environment) (current-time-string))))
308 "String used to recognize end of output.
309 The '$' character at the end is quoted; the string cannot be
310 detected as prompt when being sent on echoing hosts, therefore.")
311
312 (defconst tramp-initial-end-of-output "#$ "
313 "Prompt when establishing a connection.")
314
315 (defvar tramp-methods
316 `(("rcp" (tramp-login-program "rsh")
317 (tramp-login-args (("%h") ("-l" "%u")))
318 (tramp-remote-sh "/bin/sh")
319 (tramp-copy-program "rcp")
320 (tramp-copy-args (("-p" "%k") ("-r")))
321 (tramp-copy-keep-date t)
322 (tramp-copy-recursive t)
323 (tramp-password-end-of-line nil))
324 ("scp" (tramp-login-program "ssh")
325 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
326 ("-e" "none")))
327 (tramp-remote-sh "/bin/sh")
328 (tramp-copy-program "scp")
329 (tramp-copy-args (("-P" "%p") ("-p" "%k")
330 ("-q") ("-r")))
331 (tramp-copy-keep-date t)
332 (tramp-copy-recursive t)
333 (tramp-password-end-of-line nil)
334 (tramp-gw-args (("-o"
335 "GlobalKnownHostsFile=/dev/null")
336 ("-o" "UserKnownHostsFile=/dev/null")
337 ("-o" "StrictHostKeyChecking=no")))
338 (tramp-default-port 22))
339 ("scp1" (tramp-login-program "ssh")
340 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
341 ("-1" "-e" "none")))
342 (tramp-remote-sh "/bin/sh")
343 (tramp-copy-program "scp")
344 (tramp-copy-args (("-1") ("-P" "%p") ("-p" "%k")
345 ("-q") ("-r")))
346 (tramp-copy-keep-date t)
347 (tramp-copy-recursive t)
348 (tramp-password-end-of-line nil)
349 (tramp-gw-args (("-o"
350 "GlobalKnownHostsFile=/dev/null")
351 ("-o" "UserKnownHostsFile=/dev/null")
352 ("-o" "StrictHostKeyChecking=no")))
353 (tramp-default-port 22))
354 ("scp2" (tramp-login-program "ssh")
355 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
356 ("-2" "-e" "none")))
357 (tramp-remote-sh "/bin/sh")
358 (tramp-copy-program "scp")
359 (tramp-copy-args (("-2") ("-P" "%p") ("-p" "%k")
360 ("-q") ("-r")))
361 (tramp-copy-keep-date t)
362 (tramp-copy-recursive t)
363 (tramp-password-end-of-line nil)
364 (tramp-gw-args (("-o"
365 "GlobalKnownHostsFile=/dev/null")
366 ("-o" "UserKnownHostsFile=/dev/null")
367 ("-o" "StrictHostKeyChecking=no")))
368 (tramp-default-port 22))
369 ("scp1_old"
370 (tramp-login-program "ssh1")
371 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
372 ("-e" "none")))
373 (tramp-remote-sh "/bin/sh")
374 (tramp-copy-program "scp1")
375 (tramp-copy-args (("-p" "%k") ("-r")))
376 (tramp-copy-keep-date t)
377 (tramp-copy-recursive t)
378 (tramp-password-end-of-line nil))
379 ("scp2_old"
380 (tramp-login-program "ssh2")
381 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
382 ("-e" "none")))
383 (tramp-remote-sh "/bin/sh")
384 (tramp-copy-program "scp2")
385 (tramp-copy-args (("-p" "%k") ("-r")))
386 (tramp-copy-keep-date t)
387 (tramp-copy-recursive t)
388 (tramp-password-end-of-line nil))
389 ("sftp" (tramp-login-program "ssh")
390 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
391 ("-e" "none")))
392 (tramp-remote-sh "/bin/sh")
393 (tramp-copy-program "sftp")
394 (tramp-copy-args nil)
395 (tramp-copy-keep-date nil)
396 (tramp-password-end-of-line nil))
397 ("rsync" (tramp-login-program "ssh")
398 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
399 ("-e" "none")))
400 (tramp-remote-sh "/bin/sh")
401 (tramp-copy-program "rsync")
402 (tramp-copy-args (("-e" "ssh") ("-t" "%k") ("-r")))
403 (tramp-copy-keep-date t)
404 (tramp-copy-keep-tmpfile t)
405 (tramp-copy-recursive t)
406 (tramp-password-end-of-line nil))
407 ("rsyncc"
408 (tramp-login-program "ssh")
409 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
410 ("-o" "ControlPath=%t.%%r@%%h:%%p")
411 ("-o" "ControlMaster=yes")
412 ("-e" "none")))
413 (tramp-remote-sh "/bin/sh")
414 (tramp-copy-program "rsync")
415 (tramp-copy-args (("-t" "%k") ("-r")))
416 (tramp-copy-env (("RSYNC_RSH")
417 (,(concat
418 "ssh"
419 " -o ControlPath=%t.%%r@%%h:%%p"
420 " -o ControlMaster=auto"))))
421 (tramp-copy-keep-date t)
422 (tramp-copy-keep-tmpfile t)
423 (tramp-copy-recursive t)
424 (tramp-password-end-of-line nil))
425 ("remcp" (tramp-login-program "remsh")
426 (tramp-login-args (("%h") ("-l" "%u")))
427 (tramp-remote-sh "/bin/sh")
428 (tramp-copy-program "rcp")
429 (tramp-copy-args (("-p" "%k")))
430 (tramp-copy-keep-date t)
431 (tramp-password-end-of-line nil))
432 ("rsh" (tramp-login-program "rsh")
433 (tramp-login-args (("%h") ("-l" "%u")))
434 (tramp-remote-sh "/bin/sh")
435 (tramp-copy-program nil)
436 (tramp-copy-args nil)
437 (tramp-copy-keep-date nil)
438 (tramp-password-end-of-line nil))
439 ("ssh" (tramp-login-program "ssh")
440 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
441 ("-e" "none")))
442 (tramp-remote-sh "/bin/sh")
443 (tramp-copy-program nil)
444 (tramp-copy-args nil)
445 (tramp-copy-keep-date nil)
446 (tramp-password-end-of-line nil)
447 (tramp-gw-args (("-o"
448 "GlobalKnownHostsFile=/dev/null")
449 ("-o" "UserKnownHostsFile=/dev/null")
450 ("-o" "StrictHostKeyChecking=no")))
451 (tramp-default-port 22))
452 ("ssh1" (tramp-login-program "ssh")
453 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
454 ("-1" "-e" "none")))
455 (tramp-remote-sh "/bin/sh")
456 (tramp-copy-program nil)
457 (tramp-copy-args nil)
458 (tramp-copy-keep-date nil)
459 (tramp-password-end-of-line nil)
460 (tramp-gw-args (("-o"
461 "GlobalKnownHostsFile=/dev/null")
462 ("-o" "UserKnownHostsFile=/dev/null")
463 ("-o" "StrictHostKeyChecking=no")))
464 (tramp-default-port 22))
465 ("ssh2" (tramp-login-program "ssh")
466 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
467 ("-2" "-e" "none")))
468 (tramp-remote-sh "/bin/sh")
469 (tramp-copy-program nil)
470 (tramp-copy-args nil)
471 (tramp-copy-keep-date nil)
472 (tramp-password-end-of-line nil)
473 (tramp-gw-args (("-o"
474 "GlobalKnownHostsFile=/dev/null")
475 ("-o" "UserKnownHostsFile=/dev/null")
476 ("-o" "StrictHostKeyChecking=no")))
477 (tramp-default-port 22))
478 ("ssh1_old"
479 (tramp-login-program "ssh1")
480 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
481 ("-e" "none")))
482 (tramp-remote-sh "/bin/sh")
483 (tramp-copy-program nil)
484 (tramp-copy-args nil)
485 (tramp-copy-keep-date nil)
486 (tramp-password-end-of-line nil))
487 ("ssh2_old"
488 (tramp-login-program "ssh2")
489 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p")
490 ("-e" "none")))
491 (tramp-remote-sh "/bin/sh")
492 (tramp-copy-program nil)
493 (tramp-copy-args nil)
494 (tramp-copy-keep-date nil)
495 (tramp-password-end-of-line nil))
496 ("remsh" (tramp-login-program "remsh")
497 (tramp-login-args (("%h") ("-l" "%u")))
498 (tramp-remote-sh "/bin/sh")
499 (tramp-copy-program nil)
500 (tramp-copy-args nil)
501 (tramp-copy-keep-date nil)
502 (tramp-password-end-of-line nil))
503 ("telnet"
504 (tramp-login-program "telnet")
505 (tramp-login-args (("%h") ("%p")))
506 (tramp-remote-sh "/bin/sh")
507 (tramp-copy-program nil)
508 (tramp-copy-args nil)
509 (tramp-copy-keep-date nil)
510 (tramp-password-end-of-line nil)
511 (tramp-default-port 23))
512 ("su" (tramp-login-program "su")
513 (tramp-login-args (("-") ("%u")))
514 (tramp-remote-sh "/bin/sh")
515 (tramp-copy-program nil)
516 (tramp-copy-args nil)
517 (tramp-copy-keep-date nil)
518 (tramp-password-end-of-line nil))
519 ("sudo" (tramp-login-program "sudo")
520 (tramp-login-args (("-u" "%u")
521 ("-s") ("-H") ("-p" "Password:")))
522 (tramp-remote-sh "/bin/sh")
523 (tramp-copy-program nil)
524 (tramp-copy-args nil)
525 (tramp-copy-keep-date nil)
526 (tramp-password-end-of-line nil))
527 ("scpc" (tramp-login-program "ssh")
528 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
529 ("-o" "ControlPath=%t.%%r@%%h:%%p")
530 ("-o" "ControlMaster=yes")
531 ("-e" "none")))
532 (tramp-remote-sh "/bin/sh")
533 (tramp-copy-program "scp")
534 (tramp-copy-args (("-P" "%p") ("-p" "%k") ("-q")
535 ("-o" "ControlPath=%t.%%r@%%h:%%p")
536 ("-o" "ControlMaster=auto")))
537 (tramp-copy-keep-date t)
538 (tramp-password-end-of-line nil)
539 (tramp-gw-args (("-o"
540 "GlobalKnownHostsFile=/dev/null")
541 ("-o" "UserKnownHostsFile=/dev/null")
542 ("-o" "StrictHostKeyChecking=no")))
543 (tramp-default-port 22))
544 ("scpx" (tramp-login-program "ssh")
545 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
546 ("-e" "none" "-t" "-t" "/bin/sh")))
547 (tramp-remote-sh "/bin/sh")
548 (tramp-copy-program "scp")
549 (tramp-copy-args (("-p" "%k")))
550 (tramp-copy-keep-date t)
551 (tramp-password-end-of-line nil)
552 (tramp-gw-args (("-o"
553 "GlobalKnownHostsFile=/dev/null")
554 ("-o" "UserKnownHostsFile=/dev/null")
555 ("-o" "StrictHostKeyChecking=no")))
556 (tramp-default-port 22))
557 ("sshx" (tramp-login-program "ssh")
558 (tramp-login-args (("%h") ("-l" "%u") ("-p" "%p") ("-q")
559 ("-e" "none" "-t" "-t" "/bin/sh")))
560 (tramp-remote-sh "/bin/sh")
561 (tramp-copy-program nil)
562 (tramp-copy-args nil)
563 (tramp-copy-keep-date nil)
564 (tramp-password-end-of-line nil)
565 (tramp-gw-args (("-o"
566 "GlobalKnownHostsFile=/dev/null")
567 ("-o" "UserKnownHostsFile=/dev/null")
568 ("-o" "StrictHostKeyChecking=no")))
569 (tramp-default-port 22))
570 ("krlogin"
571 (tramp-login-program "krlogin")
572 (tramp-login-args (("%h") ("-l" "%u") ("-x")))
573 (tramp-remote-sh "/bin/sh")
574 (tramp-copy-program nil)
575 (tramp-copy-args nil)
576 (tramp-copy-keep-date nil)
577 (tramp-password-end-of-line nil))
578 ("plink" (tramp-login-program "plink")
579 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
580 ("-ssh")))
581 (tramp-remote-sh "/bin/sh")
582 (tramp-copy-program nil)
583 (tramp-copy-args nil)
584 (tramp-copy-keep-date nil)
585 (tramp-password-end-of-line "xy") ;see docstring for "xy"
586 (tramp-default-port 22))
587 ("plink1"
588 (tramp-login-program "plink")
589 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
590 ("-1" "-ssh")))
591 (tramp-remote-sh "/bin/sh")
592 (tramp-copy-program nil)
593 (tramp-copy-args nil)
594 (tramp-copy-keep-date nil)
595 (tramp-password-end-of-line "xy") ;see docstring for "xy"
596 (tramp-default-port 22))
597 ("plinkx"
598 (tramp-login-program "plink")
599 ;; ("%h") must be a single element, see
600 ;; `tramp-compute-multi-hops'.
601 (tramp-login-args (("-load") ("%h") ("-t")
602 (,(format
603 "env 'TERM=%s' 'PROMPT_COMMAND=' 'PS1=%s'"
604 tramp-terminal-type
605 tramp-initial-end-of-output))
606 ("/bin/sh")))
607 (tramp-remote-sh "/bin/sh")
608 (tramp-copy-program nil)
609 (tramp-copy-args nil)
610 (tramp-copy-keep-date nil)
611 (tramp-password-end-of-line nil))
612 ("pscp" (tramp-login-program "plink")
613 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
614 ("-ssh")))
615 (tramp-remote-sh "/bin/sh")
616 (tramp-copy-program "pscp")
617 (tramp-copy-args (("-P" "%p") ("-scp") ("-p" "%k")))
618 (tramp-copy-keep-date t)
619 (tramp-password-end-of-line "xy") ;see docstring for "xy"
620 (tramp-default-port 22))
621 ("psftp" (tramp-login-program "plink")
622 (tramp-login-args (("%h") ("-l" "%u") ("-P" "%p")
623 ("-ssh")))
624 (tramp-remote-sh "/bin/sh")
625 (tramp-copy-program "pscp")
626 (tramp-copy-args (("-P" "%p") ("-sftp") ("-p" "%k")))
627 (tramp-copy-keep-date t)
628 (tramp-password-end-of-line "xy")) ;see docstring for "xy"
629 ("fcp" (tramp-login-program "fsh")
630 (tramp-login-args (("%h") ("-l" "%u") ("sh" "-i")))
631 (tramp-remote-sh "/bin/sh -i")
632 (tramp-copy-program "fcp")
633 (tramp-copy-args (("-p" "%k")))
634 (tramp-copy-keep-date t)
635 (tramp-password-end-of-line nil)))
636 "*Alist of methods for remote files.
637 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
638 Each NAME stands for a remote access method. Each PARAM is a
639 pair of the form (KEY VALUE). The following KEYs are defined:
640 * `tramp-remote-sh'
641 This specifies the Bourne shell to use on the remote host. This
642 MUST be a Bourne-like shell. It is normally not necessary to set
643 this to any value other than \"/bin/sh\": Tramp wants to use a shell
644 which groks tilde expansion, but it can search for it. Also note
645 that \"/bin/sh\" exists on all Unixen, this might not be true for
646 the value that you decide to use. You Have Been Warned.
647 * `tramp-login-program'
648 This specifies the name of the program to use for logging in to the
649 remote host. This may be the name of rsh or a workalike program,
650 or the name of telnet or a workalike, or the name of su or a workalike.
651 * `tramp-login-args'
652 This specifies the list of arguments to pass to the above
653 mentioned program. Please note that this is a list of list of arguments,
654 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
655 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
656 There are some patterns: \"%h\" in this list is replaced by the host
657 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
658 port number, and \"%%\" can be used to obtain a literal percent character.
659 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
660 expansion (i.e. no host or no user specified), this list is not used as
661 argument. By this, arguments like (\"-l\" \"%u\") are optional.
662 \"%t\" is replaced by the temporary file name produced with
663 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
664 parameter of a program, if exists.
665 * `tramp-copy-program'
666 This specifies the name of the program to use for remotely copying
667 the file; this might be the absolute filename of rcp or the name of
668 a workalike program.
669 * `tramp-copy-args'
670 This specifies the list of parameters to pass to the above mentioned
671 program, the hints for `tramp-login-args' also apply here.
672 * `tramp-copy-keep-date'
673 This specifies whether the copying program when the preserves the
674 timestamp of the original file.
675 * `tramp-copy-keep-tmpfile'
676 This specifies whether a temporary local file shall be kept
677 for optimization reasons (useful for \"rsync\" methods).
678 * `tramp-copy-recursive'
679 Whether the operation copies directories recursively.
680 * `tramp-default-port'
681 The default port of a method is needed in case of gateway connections.
682 Additionally, it is used as indication which method is prepared for
683 passing gateways.
684 * `tramp-gw-args'
685 As the attribute name says, additional arguments are specified here
686 when a method is applied via a gateway.
687 * `tramp-password-end-of-line'
688 This specifies the string to use for terminating the line after
689 submitting the password. If this method parameter is nil, then the
690 value of the normal variable `tramp-default-password-end-of-line'
691 is used. This parameter is necessary because the \"plink\" program
692 requires any two characters after sending the password. These do
693 not have to be newline or carriage return characters. Other login
694 programs are happy with just one character, the newline character.
695 We use \"xy\" as the value for methods using \"plink\".
696
697 What does all this mean? Well, you should specify `tramp-login-program'
698 for all methods; this program is used to log in to the remote site. Then,
699 there are two ways to actually transfer the files between the local and the
700 remote side. One way is using an additional rcp-like program. If you want
701 to do this, set `tramp-copy-program' in the method.
702
703 Another possibility for file transfer is inline transfer, i.e. the
704 file is passed through the same buffer used by `tramp-login-program'. In
705 this case, the file contents need to be protected since the
706 `tramp-login-program' might use escape codes or the connection might not
707 be eight-bit clean. Therefore, file contents are encoded for transit.
708 See the variables `tramp-local-coding-commands' and
709 `tramp-remote-coding-commands' for details.
710
711 So, to summarize: if the method is an out-of-band method, then you
712 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
713 inline method, then these two parameters should be nil. Methods which
714 are fit for gateways must have `tramp-default-port' at least.
715
716 Notes:
717
718 When using `su' or `sudo' the phrase `open connection to a remote
719 host' sounds strange, but it is used nevertheless, for consistency.
720 No connection is opened to a remote host, but `su' or `sudo' is
721 started on the local host. You should specify a remote host
722 `localhost' or the name of the local host. Another host name is
723 useful only in combination with `tramp-default-proxies-alist'.")
724
725 (defcustom tramp-default-method
726 ;; An external copy method seems to be preferred, because it is much
727 ;; more performant for large files, and it hasn't too serious delays
728 ;; for small files. But it must be ensured that there aren't
729 ;; permanent password queries. Either a password agent like
730 ;; "ssh-agent" or "Pageant" shall run, or the optional
731 ;; password-cache.el or auth-sources.el packages shall be active for
732 ;; password caching. "scpc" would be another good choice because of
733 ;; the "ControlMaster" option, but this is a more modern alternative
734 ;; in OpenSSH 4, which cannot be taken as default.
735 (cond
736 ;; PuTTY is installed.
737 ((executable-find "pscp")
738 (if (or (fboundp 'password-read)
739 (fboundp 'auth-source-user-or-password)
740 ;; Pageant is running.
741 (tramp-compat-process-running-p "Pageant"))
742 "pscp"
743 "plink"))
744 ;; There is an ssh installation.
745 ((executable-find "scp")
746 (if (or (fboundp 'password-read)
747 (fboundp 'auth-source-user-or-password)
748 ;; ssh-agent is running.
749 (getenv "SSH_AUTH_SOCK")
750 (getenv "SSH_AGENT_PID"))
751 "scp"
752 "ssh"))
753 ;; Fallback.
754 (t "ftp"))
755 "*Default method to use for transferring files.
756 See `tramp-methods' for possibilities.
757 Also see `tramp-default-method-alist'."
758 :group 'tramp
759 :type 'string)
760
761 (defcustom tramp-default-method-alist
762 '(("\\`localhost\\'" "\\`root\\'" "su"))
763 "*Default method to use for specific host/user pairs.
764 This is an alist of items (HOST USER METHOD). The first matching item
765 specifies the method to use for a file name which does not specify a
766 method. HOST and USER are regular expressions or nil, which is
767 interpreted as a regular expression which always matches. If no entry
768 matches, the variable `tramp-default-method' takes effect.
769
770 If the file name does not specify the user, lookup is done using the
771 empty string for the user name.
772
773 See `tramp-methods' for a list of possibilities for METHOD."
774 :group 'tramp
775 :type '(repeat (list (regexp :tag "Host regexp")
776 (regexp :tag "User regexp")
777 (string :tag "Method"))))
778
779 (defcustom tramp-default-user
780 nil
781 "*Default user to use for transferring files.
782 It is nil by default; otherwise settings in configuration files like
783 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
784
785 This variable is regarded as obsolete, and will be removed soon."
786 :group 'tramp
787 :type '(choice (const nil) string))
788
789 (defcustom tramp-default-user-alist
790 `(("\\`su\\(do\\)?\\'" nil "root")
791 ("\\`r\\(em\\)?\\(cp\\|sh\\)\\|telnet\\|plink1?\\'"
792 nil ,(user-login-name)))
793 "*Default user to use for specific method/host pairs.
794 This is an alist of items (METHOD HOST USER). The first matching item
795 specifies the user to use for a file name which does not specify a
796 user. METHOD and USER are regular expressions or nil, which is
797 interpreted as a regular expression which always matches. If no entry
798 matches, the variable `tramp-default-user' takes effect.
799
800 If the file name does not specify the method, lookup is done using the
801 empty string for the method name."
802 :group 'tramp
803 :type '(repeat (list (regexp :tag "Method regexp")
804 (regexp :tag "Host regexp")
805 (string :tag "User"))))
806
807 (defcustom tramp-default-host
808 (system-name)
809 "*Default host to use for transferring files.
810 Useful for su and sudo methods mostly."
811 :group 'tramp
812 :type 'string)
813
814 (defcustom tramp-default-proxies-alist nil
815 "*Route to be followed for specific host/user pairs.
816 This is an alist of items (HOST USER PROXY). The first matching
817 item specifies the proxy to be passed for a file name located on
818 a remote target matching USER@HOST. HOST and USER are regular
819 expressions. PROXY must be a Tramp filename without a localname
820 part. Method and user name on PROXY are optional, which is
821 interpreted with the default values. PROXY can contain the
822 patterns %h and %u, which are replaced by the strings matching
823 HOST or USER, respectively.
824
825 HOST, USER or PROXY could also be Lisp forms, which will be
826 evaluated. The result must be a string or nil, which is
827 interpreted as a regular expression which always matches."
828 :group 'tramp
829 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
830 (choice :tag "User regexp" regexp sexp)
831 (choice :tag "Proxy remote name" string (const nil)))))
832
833 (defconst tramp-local-host-regexp
834 (concat
835 "^" (regexp-opt (list "localhost" (system-name) "127\.0\.0\.1" "::1") t) "$")
836 "*Host names which are regarded as local host.")
837
838 (defconst tramp-completion-function-alist-rsh
839 '((tramp-parse-rhosts "/etc/hosts.equiv")
840 (tramp-parse-rhosts "~/.rhosts"))
841 "Default list of (FUNCTION FILE) pairs to be examined for rsh methods.")
842
843 (defconst tramp-completion-function-alist-ssh
844 '((tramp-parse-rhosts "/etc/hosts.equiv")
845 (tramp-parse-rhosts "/etc/shosts.equiv")
846 (tramp-parse-shosts "/etc/ssh_known_hosts")
847 (tramp-parse-sconfig "/etc/ssh_config")
848 (tramp-parse-shostkeys "/etc/ssh2/hostkeys")
849 (tramp-parse-sknownhosts "/etc/ssh2/knownhosts")
850 (tramp-parse-rhosts "~/.rhosts")
851 (tramp-parse-rhosts "~/.shosts")
852 (tramp-parse-shosts "~/.ssh/known_hosts")
853 (tramp-parse-sconfig "~/.ssh/config")
854 (tramp-parse-shostkeys "~/.ssh2/hostkeys")
855 (tramp-parse-sknownhosts "~/.ssh2/knownhosts"))
856 "Default list of (FUNCTION FILE) pairs to be examined for ssh methods.")
857
858 (defconst tramp-completion-function-alist-telnet
859 '((tramp-parse-hosts "/etc/hosts"))
860 "Default list of (FUNCTION FILE) pairs to be examined for telnet methods.")
861
862 (defconst tramp-completion-function-alist-su
863 '((tramp-parse-passwd "/etc/passwd"))
864 "Default list of (FUNCTION FILE) pairs to be examined for su methods.")
865
866 (defconst tramp-completion-function-alist-putty
867 '((tramp-parse-putty
868 "HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions"))
869 "Default list of (FUNCTION REGISTRY) pairs to be examined for putty methods.")
870
871 (defvar tramp-completion-function-alist nil
872 "*Alist of methods for remote files.
873 This is a list of entries of the form (NAME PAIR1 PAIR2 ...).
874 Each NAME stands for a remote access method. Each PAIR is of the form
875 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
876 names from FILE for completion. The following predefined FUNCTIONs exists:
877
878 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
879 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
880 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
881 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
882 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
883 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
884 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
885 * `tramp-parse-netrc' for \"~/.netrc\" like files.
886 * `tramp-parse-putty' for PuTTY registry keys.
887
888 FUNCTION can also be a customer defined function. For more details see
889 the info pages.")
890
891 (eval-after-load "tramp"
892 '(progn
893 (tramp-set-completion-function
894 "rcp" tramp-completion-function-alist-rsh)
895 (tramp-set-completion-function
896 "scp" tramp-completion-function-alist-ssh)
897 (tramp-set-completion-function
898 "scp1" tramp-completion-function-alist-ssh)
899 (tramp-set-completion-function
900 "scp2" tramp-completion-function-alist-ssh)
901 (tramp-set-completion-function
902 "scp1_old" tramp-completion-function-alist-ssh)
903 (tramp-set-completion-function
904 "scp2_old" tramp-completion-function-alist-ssh)
905 (tramp-set-completion-function
906 "rsync" tramp-completion-function-alist-ssh)
907 (tramp-set-completion-function
908 "rsyncc" tramp-completion-function-alist-ssh)
909 (tramp-set-completion-function
910 "remcp" tramp-completion-function-alist-rsh)
911 (tramp-set-completion-function
912 "rsh" tramp-completion-function-alist-rsh)
913 (tramp-set-completion-function
914 "ssh" tramp-completion-function-alist-ssh)
915 (tramp-set-completion-function
916 "ssh1" tramp-completion-function-alist-ssh)
917 (tramp-set-completion-function
918 "ssh2" tramp-completion-function-alist-ssh)
919 (tramp-set-completion-function
920 "ssh1_old" tramp-completion-function-alist-ssh)
921 (tramp-set-completion-function
922 "ssh2_old" tramp-completion-function-alist-ssh)
923 (tramp-set-completion-function
924 "remsh" tramp-completion-function-alist-rsh)
925 (tramp-set-completion-function
926 "telnet" tramp-completion-function-alist-telnet)
927 (tramp-set-completion-function
928 "su" tramp-completion-function-alist-su)
929 (tramp-set-completion-function
930 "sudo" tramp-completion-function-alist-su)
931 (tramp-set-completion-function
932 "scpx" tramp-completion-function-alist-ssh)
933 (tramp-set-completion-function
934 "sshx" tramp-completion-function-alist-ssh)
935 (tramp-set-completion-function
936 "krlogin" tramp-completion-function-alist-rsh)
937 (tramp-set-completion-function
938 "plink" tramp-completion-function-alist-ssh)
939 (tramp-set-completion-function
940 "plink1" tramp-completion-function-alist-ssh)
941 (tramp-set-completion-function
942 "plinkx" tramp-completion-function-alist-putty)
943 (tramp-set-completion-function
944 "pscp" tramp-completion-function-alist-ssh)
945 (tramp-set-completion-function
946 "fcp" tramp-completion-function-alist-ssh)))
947
948 (defconst tramp-echo-mark-marker "_echo"
949 "String marker to surround echoed commands.")
950
951 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
952 "String length of `tramp-echo-mark-marker'.")
953
954 (defconst tramp-echo-mark
955 (concat tramp-echo-mark-marker
956 (make-string tramp-echo-mark-marker-length ?\b))
957 "String mark to be transmitted around shell commands.
958 Used to separate their echo from the output they produce. This
959 will only be used if we cannot disable remote echo via stty.
960 This string must have no effect on the remote shell except for
961 producing some echo which can later be detected by
962 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
963 followed by an equal number of backspaces to erase them will
964 usually suffice.")
965
966 (defconst tramp-echoed-echo-mark-regexp
967 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
968 tramp-echo-mark-marker tramp-echo-mark-marker-length)
969 "Regexp which matches `tramp-echo-mark' as it gets echoed by
970 the remote shell.")
971
972 (defcustom tramp-rsh-end-of-line "\n"
973 "*String used for end of line in rsh connections.
974 I don't think this ever needs to be changed, so please tell me about it
975 if you need to change this.
976 Also see the method parameter `tramp-password-end-of-line' and the normal
977 variable `tramp-default-password-end-of-line'."
978 :group 'tramp
979 :type 'string)
980
981 (defcustom tramp-default-password-end-of-line
982 tramp-rsh-end-of-line
983 "*String used for end of line after sending a password.
984 This variable provides the default value for the method parameter
985 `tramp-password-end-of-line', see `tramp-methods' for more details.
986
987 It seems that people using plink under Windows need to send
988 \"\\r\\n\" (carriage-return, then newline) after a password, but just
989 \"\\n\" after all other lines. This variable can be used for the
990 password, see `tramp-rsh-end-of-line' for the other cases.
991
992 The default value is to use the same value as `tramp-rsh-end-of-line'."
993 :group 'tramp
994 :type 'string)
995
996 ;; "getconf PATH" yields:
997 ;; HP-UX: /usr/bin:/usr/ccs/bin:/opt/ansic/bin:/opt/langtools/bin:/opt/fortran/bin
998 ;; Solaris: /usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin
999 ;; GNU/Linux (Debian, Suse): /bin:/usr/bin
1000 ;; FreeBSD: /usr/bin:/bin:/usr/sbin:/sbin: - beware trailing ":"!
1001 (defcustom tramp-remote-path
1002 '(tramp-default-remote-path "/usr/sbin" "/usr/local/bin"
1003 "/local/bin" "/local/freeware/bin" "/local/gnu/bin"
1004 "/usr/freeware/bin" "/usr/pkg/bin" "/usr/contrib/bin")
1005 "*List of directories to search for executables on remote host.
1006 For every remote host, this variable will be set buffer local,
1007 keeping the list of existing directories on that host.
1008
1009 You can use `~' in this list, but when searching for a shell which groks
1010 tilde expansion, all directory names starting with `~' will be ignored.
1011
1012 `Default Directories' represent the list of directories given by
1013 the command \"getconf PATH\". It is recommended to use this
1014 entry on top of this list, because these are the default
1015 directories for POSIX compatible commands.
1016
1017 `Private Directories' are the settings of the $PATH environment,
1018 as given in your `~/.profile'."
1019 :group 'tramp
1020 :type '(repeat (choice
1021 (const :tag "Default Directories" tramp-default-remote-path)
1022 (const :tag "Private Directories" tramp-own-remote-path)
1023 (string :tag "Directory"))))
1024
1025 (defcustom tramp-remote-process-environment
1026 `("HISTFILE=$HOME/.tramp_history" "HISTSIZE=1" "LC_ALL=C"
1027 ,(concat "TERM=" tramp-terminal-type)
1028 "EMACS=t" ;; Deprecated.
1029 ,(format "INSIDE_EMACS=%s,tramp:%s" emacs-version tramp-version)
1030 "CDPATH=" "HISTORY=" "MAIL=" "MAILCHECK=" "MAILPATH="
1031 "autocorrect=" "correct=")
1032
1033 "*List of environment variables to be set on the remote host.
1034
1035 Each element should be a string of the form ENVVARNAME=VALUE. An
1036 entry ENVVARNAME= diables the corresponding environment variable,
1037 which might have been set in the init files like ~/.profile.
1038
1039 Special handling is applied to the PATH environment, which should
1040 not be set here. Instead of, it should be set via `tramp-remote-path'."
1041 :group 'tramp
1042 :type '(repeat string))
1043
1044 (defcustom tramp-login-prompt-regexp
1045 ".*ogin\\( .*\\)?: *"
1046 "*Regexp matching login-like prompts.
1047 The regexp should match at end of buffer.
1048
1049 Sometimes the prompt is reported to look like \"login as:\"."
1050 :group 'tramp
1051 :type 'regexp)
1052
1053 (defcustom tramp-shell-prompt-pattern
1054 ;; Allow a prompt to start right after a ^M since it indeed would be
1055 ;; displayed at the beginning of the line (and Zsh uses it).
1056 "\\(?:^\\|\r\\)[^#$%>\n]*#?[#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*"
1057 "Regexp to match prompts from remote shell.
1058 Normally, Tramp expects you to configure `shell-prompt-pattern'
1059 correctly, but sometimes it happens that you are connecting to a
1060 remote host which sends a different kind of shell prompt. Therefore,
1061 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
1062 and also things matched by this variable. The default value of this
1063 variable is similar to the default value of `shell-prompt-pattern',
1064 which should work well in many cases.
1065
1066 This regexp must match both `tramp-initial-end-of-output' and
1067 `tramp-end-of-output'."
1068 :group 'tramp
1069 :type 'regexp)
1070
1071 (defcustom tramp-password-prompt-regexp
1072 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
1073 "*Regexp matching password-like prompts.
1074 The regexp should match at end of buffer.
1075
1076 The `sudo' program appears to insert a `^@' character into the prompt."
1077 :group 'tramp
1078 :type 'regexp)
1079
1080 (defcustom tramp-wrong-passwd-regexp
1081 (concat "^.*"
1082 ;; These strings should be on the last line
1083 (regexp-opt '("Permission denied"
1084 "Login incorrect"
1085 "Login Incorrect"
1086 "Connection refused"
1087 "Connection closed"
1088 "Timeout, server not responding."
1089 "Sorry, try again."
1090 "Name or service not known"
1091 "Host key verification failed."
1092 "No supported authentication methods left to try!") t)
1093 ".*"
1094 "\\|"
1095 "^.*\\("
1096 ;; Here comes a list of regexes, separated by \\|
1097 "Received signal [0-9]+"
1098 "\\).*")
1099 "*Regexp matching a `login failed' message.
1100 The regexp should match at end of buffer."
1101 :group 'tramp
1102 :type 'regexp)
1103
1104 (defcustom tramp-yesno-prompt-regexp
1105 (concat
1106 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
1107 "\\s-*")
1108 "Regular expression matching all yes/no queries which need to be confirmed.
1109 The confirmation should be done with yes or no.
1110 The regexp should match at end of buffer.
1111 See also `tramp-yn-prompt-regexp'."
1112 :group 'tramp
1113 :type 'regexp)
1114
1115 (defcustom tramp-yn-prompt-regexp
1116 (concat
1117 (regexp-opt '("Store key in cache? (y/n)"
1118 "Update cached key? (y/n, Return cancels connection)") t)
1119 "\\s-*")
1120 "Regular expression matching all y/n queries which need to be confirmed.
1121 The confirmation should be done with y or n.
1122 The regexp should match at end of buffer.
1123 See also `tramp-yesno-prompt-regexp'."
1124 :group 'tramp
1125 :type 'regexp)
1126
1127 (defcustom tramp-terminal-prompt-regexp
1128 (concat "\\("
1129 "TERM = (.*)"
1130 "\\|"
1131 "Terminal type\\? \\[.*\\]"
1132 "\\)\\s-*")
1133 "Regular expression matching all terminal setting prompts.
1134 The regexp should match at end of buffer.
1135 The answer will be provided by `tramp-action-terminal', which see."
1136 :group 'tramp
1137 :type 'regexp)
1138
1139 (defcustom tramp-operation-not-permitted-regexp
1140 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
1141 (regexp-opt '("Operation not permitted") t))
1142 "Regular expression matching keep-date problems in (s)cp operations.
1143 Copying has been performed successfully already, so this message can
1144 be ignored safely."
1145 :group 'tramp
1146 :type 'regexp)
1147
1148 (defcustom tramp-copy-failed-regexp
1149 (concat "\\(.+: "
1150 (regexp-opt '("Permission denied"
1151 "not a regular file"
1152 "is a directory"
1153 "No such file or directory") t)
1154 "\\)\\s-*")
1155 "Regular expression matching copy problems in (s)cp operations."
1156 :group 'tramp
1157 :type 'regexp)
1158
1159 (defcustom tramp-process-alive-regexp
1160 ""
1161 "Regular expression indicating a process has finished.
1162 In fact this expression is empty by intention, it will be used only to
1163 check regularly the status of the associated process.
1164 The answer will be provided by `tramp-action-process-alive',
1165 `tramp-action-out-of-band', which see."
1166 :group 'tramp
1167 :type 'regexp)
1168
1169 (defcustom tramp-temp-name-prefix "tramp."
1170 "*Prefix to use for temporary files.
1171 If this is a relative file name (such as \"tramp.\"), it is considered
1172 relative to the directory name returned by the function
1173 `tramp-compat-temporary-file-directory' (which see). It may also be an
1174 absolute file name; don't forget to include a prefix for the filename
1175 part, though."
1176 :group 'tramp
1177 :type 'string)
1178
1179 (defconst tramp-temp-buffer-name " *tramp temp*"
1180 "Buffer name for a temporary buffer.
1181 It shall be used in combination with `generate-new-buffer-name'.")
1182
1183 (defvar tramp-temp-buffer-file-name nil
1184 "File name of a persistent local temporary file.
1185 Useful for \"rsync\" like methods.")
1186 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
1187
1188 (defcustom tramp-sh-extra-args '(("/bash\\'" . "-norc -noprofile"))
1189 "*Alist specifying extra arguments to pass to the remote shell.
1190 Entries are (REGEXP . ARGS) where REGEXP is a regular expression
1191 matching the shell file name and ARGS is a string specifying the
1192 arguments.
1193
1194 This variable is only used when Tramp needs to start up another shell
1195 for tilde expansion. The extra arguments should typically prevent the
1196 shell from reading its init file."
1197 :group 'tramp
1198 ;; This might be the wrong way to test whether the widget type
1199 ;; `alist' is available. Who knows the right way to test it?
1200 :type (if (get 'alist 'widget-type)
1201 '(alist :key-type string :value-type string)
1202 '(repeat (cons string string))))
1203
1204 ;; XEmacs is distributed with few Lisp packages. Further packages are
1205 ;; installed using EFS. If we use a unified filename format, then
1206 ;; Tramp is required in addition to EFS. (But why can't Tramp just
1207 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
1208 ;; just like before.) Another reason for using a separate filename
1209 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
1210 ;; Tramp only knows how to deal with `file-name-handler-alist', not
1211 ;; the other places.
1212
1213 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
1214 ;;;###autoload
1215 (defcustom tramp-syntax
1216 (if (featurep 'xemacs) 'sep 'ftp)
1217 "Tramp filename syntax to be used.
1218
1219 It can have the following values:
1220
1221 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
1222 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
1223 'url -- URL-like syntax."
1224 :group 'tramp
1225 :type (if (featurep 'xemacs)
1226 '(choice (const :tag "EFS" ftp)
1227 (const :tag "XEmacs" sep)
1228 (const :tag "URL" url))
1229 '(choice (const :tag "Ange-FTP" ftp)
1230 (const :tag "URL" url))))
1231
1232 (defconst tramp-prefix-format
1233 (cond ((equal tramp-syntax 'ftp) "/")
1234 ((equal tramp-syntax 'sep) "/[")
1235 ((equal tramp-syntax 'url) "/")
1236 (t (error "Wrong `tramp-syntax' defined")))
1237 "*String matching the very beginning of Tramp file names.
1238 Used in `tramp-make-tramp-file-name'.")
1239
1240 (defconst tramp-prefix-regexp
1241 (concat "^" (regexp-quote tramp-prefix-format))
1242 "*Regexp matching the very beginning of Tramp file names.
1243 Should always start with \"^\". Derived from `tramp-prefix-format'.")
1244
1245 (defconst tramp-method-regexp
1246 "[a-zA-Z_0-9-]+"
1247 "*Regexp matching methods identifiers.")
1248
1249 (defconst tramp-postfix-method-format
1250 (cond ((equal tramp-syntax 'ftp) ":")
1251 ((equal tramp-syntax 'sep) "/")
1252 ((equal tramp-syntax 'url) "://")
1253 (t (error "Wrong `tramp-syntax' defined")))
1254 "*String matching delimeter between method and user or host names.
1255 Used in `tramp-make-tramp-file-name'.")
1256
1257 (defconst tramp-postfix-method-regexp
1258 (regexp-quote tramp-postfix-method-format)
1259 "*Regexp matching delimeter between method and user or host names.
1260 Derived from `tramp-postfix-method-format'.")
1261
1262 (defconst tramp-user-regexp
1263 "[^:/ \t]+"
1264 "*Regexp matching user names.")
1265
1266 (defconst tramp-prefix-domain-format "%"
1267 "*String matching delimeter between user and domain names.")
1268
1269 (defconst tramp-prefix-domain-regexp
1270 (regexp-quote tramp-prefix-domain-format)
1271 "*Regexp matching delimeter between user and domain names.
1272 Derived from `tramp-prefix-domain-format'.")
1273
1274 (defconst tramp-domain-regexp
1275 "[-a-zA-Z0-9_.]+"
1276 "*Regexp matching domain names.")
1277
1278 (defconst tramp-user-with-domain-regexp
1279 (concat "\\(" tramp-user-regexp "\\)"
1280 tramp-prefix-domain-regexp
1281 "\\(" tramp-domain-regexp "\\)")
1282 "*Regexp matching user names with domain names.")
1283
1284 (defconst tramp-postfix-user-format
1285 "@"
1286 "*String matching delimeter between user and host names.
1287 Used in `tramp-make-tramp-file-name'.")
1288
1289 (defconst tramp-postfix-user-regexp
1290 (regexp-quote tramp-postfix-user-format)
1291 "*Regexp matching delimeter between user and host names.
1292 Derived from `tramp-postfix-user-format'.")
1293
1294 (defconst tramp-host-regexp
1295 "[a-zA-Z0-9_.-]+"
1296 "*Regexp matching host names.")
1297
1298 (defconst tramp-prefix-ipv6-format
1299 (cond ((equal tramp-syntax 'ftp) "[")
1300 ((equal tramp-syntax 'sep) "")
1301 ((equal tramp-syntax 'url) "[")
1302 (t (error "Wrong `tramp-syntax' defined")))
1303 "*String matching left hand side of IPv6 addresses.
1304 Used in `tramp-make-tramp-file-name'.")
1305
1306 (defconst tramp-prefix-ipv6-regexp
1307 (regexp-quote tramp-prefix-ipv6-format)
1308 "*Regexp matching left hand side of IPv6 addresses.
1309 Derived from `tramp-prefix-ipv6-format'.")
1310
1311 ;; The following regexp is a bit sloppy. But it shall serve our
1312 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
1313 ;; "::ffff:192.168.0.1".
1314 (defconst tramp-ipv6-regexp
1315 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
1316 "*Regexp matching IPv6 addresses.")
1317
1318 (defconst tramp-postfix-ipv6-format
1319 (cond ((equal tramp-syntax 'ftp) "]")
1320 ((equal tramp-syntax 'sep) "")
1321 ((equal tramp-syntax 'url) "]")
1322 (t (error "Wrong `tramp-syntax' defined")))
1323 "*String matching right hand side of IPv6 addresses.
1324 Used in `tramp-make-tramp-file-name'.")
1325
1326 (defconst tramp-postfix-ipv6-regexp
1327 (regexp-quote tramp-postfix-ipv6-format)
1328 "*Regexp matching right hand side of IPv6 addresses.
1329 Derived from `tramp-postfix-ipv6-format'.")
1330
1331 (defconst tramp-prefix-port-format
1332 (cond ((equal tramp-syntax 'ftp) "#")
1333 ((equal tramp-syntax 'sep) "#")
1334 ((equal tramp-syntax 'url) ":")
1335 (t (error "Wrong `tramp-syntax' defined")))
1336 "*String matching delimeter between host names and port numbers.")
1337
1338 (defconst tramp-prefix-port-regexp
1339 (regexp-quote tramp-prefix-port-format)
1340 "*Regexp matching delimeter between host names and port numbers.
1341 Derived from `tramp-prefix-port-format'.")
1342
1343 (defconst tramp-port-regexp
1344 "[0-9]+"
1345 "*Regexp matching port numbers.")
1346
1347 (defconst tramp-host-with-port-regexp
1348 (concat "\\(" tramp-host-regexp "\\)"
1349 tramp-prefix-port-regexp
1350 "\\(" tramp-port-regexp "\\)")
1351 "*Regexp matching host names with port numbers.")
1352
1353 (defconst tramp-postfix-host-format
1354 (cond ((equal tramp-syntax 'ftp) ":")
1355 ((equal tramp-syntax 'sep) "]")
1356 ((equal tramp-syntax 'url) "")
1357 (t (error "Wrong `tramp-syntax' defined")))
1358 "*String matching delimeter between host names and localnames.
1359 Used in `tramp-make-tramp-file-name'.")
1360
1361 (defconst tramp-postfix-host-regexp
1362 (regexp-quote tramp-postfix-host-format)
1363 "*Regexp matching delimeter between host names and localnames.
1364 Derived from `tramp-postfix-host-format'.")
1365
1366 (defconst tramp-localname-regexp
1367 ".*$"
1368 "*Regexp matching localnames.")
1369
1370 ;; File name format.
1371
1372 (defconst tramp-file-name-structure
1373 (list
1374 (concat
1375 tramp-prefix-regexp
1376 "\\(" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
1377 "\\(" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
1378 "\\(" "\\(" tramp-host-regexp
1379 "\\|"
1380 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
1381 tramp-postfix-ipv6-regexp "\\)"
1382 "\\(" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?"
1383 tramp-postfix-host-regexp
1384 "\\(" tramp-localname-regexp "\\)")
1385 2 4 5 8)
1386
1387 "*List of five elements (REGEXP METHOD USER HOST FILE), detailing \
1388 the Tramp file name structure.
1389
1390 The first element REGEXP is a regular expression matching a Tramp file
1391 name. The regex should contain parentheses around the method name,
1392 the user name, the host name, and the file name parts.
1393
1394 The second element METHOD is a number, saying which pair of
1395 parentheses matches the method name. The third element USER is
1396 similar, but for the user name. The fourth element HOST is similar,
1397 but for the host name. The fifth element FILE is for the file name.
1398 These numbers are passed directly to `match-string', which see. That
1399 means the opening parentheses are counted to identify the pair.
1400
1401 See also `tramp-file-name-regexp'.")
1402
1403 ;;;###autoload
1404 (defconst tramp-file-name-regexp-unified
1405 "\\`/\\([^[/:]+\\|[^/]+]\\):"
1406 "Value for `tramp-file-name-regexp' for unified remoting.
1407 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
1408 Tramp. See `tramp-file-name-structure' for more explanations.")
1409
1410 ;;;###autoload
1411 (defconst tramp-file-name-regexp-separate
1412 "\\`/\\[.*\\]"
1413 "Value for `tramp-file-name-regexp' for separate remoting.
1414 XEmacs uses a separate filename syntax for Tramp and EFS.
1415 See `tramp-file-name-structure' for more explanations.")
1416
1417 ;;;###autoload
1418 (defconst tramp-file-name-regexp-url
1419 "\\`/[^/:]+://"
1420 "Value for `tramp-file-name-regexp' for URL-like remoting.
1421 See `tramp-file-name-structure' for more explanations.")
1422
1423 ;;;###autoload
1424 (defconst tramp-file-name-regexp
1425 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
1426 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
1427 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
1428 (t (error "Wrong `tramp-syntax' defined")))
1429 "*Regular expression matching file names handled by Tramp.
1430 This regexp should match Tramp file names but no other file names.
1431 \(When tramp.el is loaded, this regular expression is prepended to
1432 `file-name-handler-alist', and that is searched sequentially. Thus,
1433 if the Tramp entry appears rather early in the `file-name-handler-alist'
1434 and is a bit too general, then some files might be considered Tramp
1435 files which are not really Tramp files.
1436
1437 Please note that the entry in `file-name-handler-alist' is made when
1438 this file (tramp.el) is loaded. This means that this variable must be set
1439 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1440 updated after changing this variable.
1441
1442 Also see `tramp-file-name-structure'.")
1443
1444 ;;;###autoload
1445 (defconst tramp-root-regexp
1446 (if (memq system-type '(cygwin windows-nt))
1447 "\\`\\([a-zA-Z]:\\)?/"
1448 "\\`/")
1449 "Beginning of an incomplete Tramp file name.
1450 Usually, it is just \"\\\\`/\". On W32 systems, there might be a
1451 volume letter, which will be removed by `tramp-drop-volume-letter'.")
1452
1453 ;;;###autoload
1454 (defconst tramp-completion-file-name-regexp-unified
1455 (concat tramp-root-regexp "[^/]*\\'")
1456 "Value for `tramp-completion-file-name-regexp' for unified remoting.
1457 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
1458 See `tramp-file-name-structure' for more explanations.")
1459
1460 ;;;###autoload
1461 (defconst tramp-completion-file-name-regexp-separate
1462 (concat tramp-root-regexp "\\([[][^]]*\\)?\\'")
1463 "Value for `tramp-completion-file-name-regexp' for separate remoting.
1464 XEmacs uses a separate filename syntax for Tramp and EFS.
1465 See `tramp-file-name-structure' for more explanations.")
1466
1467 ;;;###autoload
1468 (defconst tramp-completion-file-name-regexp-url
1469 (concat tramp-root-regexp "[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'")
1470 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
1471 See `tramp-file-name-structure' for more explanations.")
1472
1473 ;;;###autoload
1474 (defconst tramp-completion-file-name-regexp
1475 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
1476 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
1477 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
1478 (t (error "Wrong `tramp-syntax' defined")))
1479 "*Regular expression matching file names handled by Tramp completion.
1480 This regexp should match partial Tramp file names only.
1481
1482 Please note that the entry in `file-name-handler-alist' is made when
1483 this file (tramp.el) is loaded. This means that this variable must be set
1484 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
1485 updated after changing this variable.
1486
1487 Also see `tramp-file-name-structure'.")
1488
1489 (defconst tramp-actions-before-shell
1490 '((tramp-login-prompt-regexp tramp-action-login)
1491 (tramp-password-prompt-regexp tramp-action-password)
1492 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1493 (shell-prompt-pattern tramp-action-succeed)
1494 (tramp-shell-prompt-pattern tramp-action-succeed)
1495 (tramp-yesno-prompt-regexp tramp-action-yesno)
1496 (tramp-yn-prompt-regexp tramp-action-yn)
1497 (tramp-terminal-prompt-regexp tramp-action-terminal)
1498 (tramp-process-alive-regexp tramp-action-process-alive))
1499 "List of pattern/action pairs.
1500 Whenever a pattern matches, the corresponding action is performed.
1501 Each item looks like (PATTERN ACTION).
1502
1503 The PATTERN should be a symbol, a variable. The value of this
1504 variable gives the regular expression to search for. Note that the
1505 regexp must match at the end of the buffer, \"\\'\" is implicitly
1506 appended to it.
1507
1508 The ACTION should also be a symbol, but a function. When the
1509 corresponding PATTERN matches, the ACTION function is called.")
1510
1511 (defconst tramp-actions-copy-out-of-band
1512 '((tramp-password-prompt-regexp tramp-action-password)
1513 (tramp-wrong-passwd-regexp tramp-action-permission-denied)
1514 (tramp-copy-failed-regexp tramp-action-permission-denied)
1515 (tramp-process-alive-regexp tramp-action-out-of-band))
1516 "List of pattern/action pairs.
1517 This list is used for copying/renaming with out-of-band methods.
1518
1519 See `tramp-actions-before-shell' for more info.")
1520
1521 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
1522 ;; known to have a bug in `process-send-string'; some ssh connections appear
1523 ;; to drop bytes when data is sent too quickly. There is also a connection
1524 ;; buffer local variable, which is computed depending on remote host properties
1525 ;; when `tramp-chunksize' is zero or nil.
1526 (defcustom tramp-chunksize
1527 (when (and (not (featurep 'xemacs))
1528 (memq system-type '(hpux)))
1529 500)
1530 ;; Parentheses in docstring starting at beginning of line are escaped.
1531 ;; Fontification is messed up when
1532 ;; `open-paren-in-column-0-is-defun-start' set to t.
1533 "*If non-nil, chunksize for sending input to local process.
1534 It is necessary only on systems which have a buggy `process-send-string'
1535 implementation. The necessity, whether this variable must be set, can be
1536 checked via the following code:
1537
1538 (with-temp-buffer
1539 (let* ((user \"xxx\") (host \"yyy\")
1540 (init 0) (step 50)
1541 (sent init) (received init))
1542 (while (= sent received)
1543 (setq sent (+ sent step))
1544 (erase-buffer)
1545 (let ((proc (start-process (buffer-name) (current-buffer)
1546 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
1547 (when (memq (process-status proc) '(run open))
1548 (process-send-string proc (make-string sent ?\\ ))
1549 (process-send-eof proc)
1550 (process-send-eof proc))
1551 (while (not (progn (goto-char (point-min))
1552 (re-search-forward \"\\\\w+\" (point-max) t)))
1553 (accept-process-output proc 1))
1554 (when (memq (process-status proc) '(run open))
1555 (setq received (string-to-number (match-string 0)))
1556 (delete-process proc)
1557 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
1558 (sit-for 0))))
1559 (if (> sent (+ init step))
1560 (message \"You should set `tramp-chunksize' to a maximum of %s\"
1561 (- sent step))
1562 (message \"Test does not work\")
1563 (display-buffer (current-buffer))
1564 (sit-for 30))))
1565
1566 In the Emacs normally running Tramp, evaluate the above code
1567 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
1568 respectively). You can do this, for example, by pasting it into
1569 the `*scratch*' buffer and then hitting C-j with the cursor after the
1570 last closing parenthesis. Note that it works only if you have configured
1571 \"ssh\" to run without password query, see ssh-agent(1).
1572
1573 You will see the number of bytes sent successfully to the remote host.
1574 If that number exceeds 1000, you can stop the execution by hitting
1575 C-g, because your Emacs is likely clean.
1576
1577 When it is necessary to set `tramp-chunksize', you might consider to
1578 use an out-of-the-band method (like \"scp\") instead of an internal one
1579 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
1580 performance.
1581
1582 If your Emacs is buggy, the code stops and gives you an indication
1583 about the value `tramp-chunksize' should be set. Maybe you could just
1584 experiment a bit, e.g. changing the values of `init' and `step'
1585 in the third line of the code.
1586
1587 Please raise a bug report via \"M-x tramp-bug\" if your system needs
1588 this variable to be set as well."
1589 :group 'tramp
1590 :type '(choice (const nil) integer))
1591
1592 ;; Logging in to a remote host normally requires obtaining a pty. But
1593 ;; Emacs on MacOS X has process-connection-type set to nil by default,
1594 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
1595 ;; for an override of the system default.
1596 (defcustom tramp-process-connection-type t
1597 "Overrides `process-connection-type' for connections from Tramp.
1598 Tramp binds process-connection-type to the value given here before
1599 opening a connection to a remote host."
1600 :group 'tramp
1601 :type '(choice (const nil) (const t) (const pty)))
1602
1603 (defcustom tramp-completion-reread-directory-timeout 10
1604 "Defines seconds since last remote command before rereading a directory.
1605 A remote directory might have changed its contents. In order to
1606 make it visible during file name completion in the minibuffer,
1607 Tramp flushes its cache and rereads the directory contents when
1608 more than `tramp-completion-reread-directory-timeout' seconds
1609 have been gone since last remote command execution. A value of 0
1610 would require an immediate reread during filename completion, nil
1611 means to use always cached values for the directory contents."
1612 :group 'tramp
1613 :type '(choice (const nil) integer))
1614
1615 ;;; Internal Variables:
1616
1617 (defvar tramp-current-method nil
1618 "Connection method for this *tramp* buffer.")
1619
1620 (defvar tramp-current-user nil
1621 "Remote login name for this *tramp* buffer.")
1622
1623 (defvar tramp-current-host nil
1624 "Remote host for this *tramp* buffer.")
1625
1626 (defconst tramp-uudecode
1627 "(echo begin 600 /tmp/tramp.$$; tail +2) | uudecode
1628 cat /tmp/tramp.$$
1629 rm -f /tmp/tramp.$$"
1630 "Shell function to implement `uudecode' to standard output.
1631 Many systems support `uudecode -o /dev/stdout' or `uudecode -o -'
1632 for this or `uudecode -p', but some systems don't, and for them
1633 we have this shell function.")
1634
1635 (defconst tramp-perl-file-truename
1636 "%s -e '
1637 use File::Spec;
1638 use Cwd \"realpath\";
1639
1640 sub recursive {
1641 my ($volume, @dirs) = @_;
1642 my $real = realpath(File::Spec->catpath(
1643 $volume, File::Spec->catdir(@dirs), \"\"));
1644 if ($real) {
1645 my ($vol, $dir) = File::Spec->splitpath($real, 1);
1646 return ($vol, File::Spec->splitdir($dir));
1647 }
1648 else {
1649 my $last = pop(@dirs);
1650 ($volume, @dirs) = recursive($volume, @dirs);
1651 push(@dirs, $last);
1652 return ($volume, @dirs);
1653 }
1654 }
1655
1656 $result = realpath($ARGV[0]);
1657 if (!$result) {
1658 my ($vol, $dir) = File::Spec->splitpath($ARGV[0], 1);
1659 ($vol, @dirs) = recursive($vol, File::Spec->splitdir($dir));
1660
1661 $result = File::Spec->catpath($vol, File::Spec->catdir(@dirs), \"\");
1662 }
1663
1664 if ($ARGV[0] =~ /\\/$/) {
1665 $result = $result . \"/\";
1666 }
1667
1668 print \"\\\"$result\\\"\\n\";
1669 ' \"$1\" 2>/dev/null"
1670 "Perl script to produce output suitable for use with `file-truename'
1671 on the remote file system.
1672 Escape sequence %s is replaced with name of Perl binary.
1673 This string is passed to `format', so percent characters need to be doubled.")
1674
1675 (defconst tramp-perl-file-name-all-completions
1676 "%s -e 'sub case {
1677 my $str = shift;
1678 if ($ARGV[2]) {
1679 return lc($str);
1680 }
1681 else {
1682 return $str;
1683 }
1684 }
1685 opendir(d, $ARGV[0]) || die(\"$ARGV[0]: $!\\nfail\\n\");
1686 @files = readdir(d); closedir(d);
1687 foreach $f (@files) {
1688 if (case(substr($f, 0, length($ARGV[1]))) eq case($ARGV[1])) {
1689 if (-d \"$ARGV[0]/$f\") {
1690 print \"$f/\\n\";
1691 }
1692 else {
1693 print \"$f\\n\";
1694 }
1695 }
1696 }
1697 print \"ok\\n\"
1698 ' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1699 "Perl script to produce output suitable for use with
1700 `file-name-all-completions' on the remote file system. Escape
1701 sequence %s is replaced with name of Perl binary. This string is
1702 passed to `format', so percent characters need to be doubled.")
1703
1704 ;; Perl script to implement `file-attributes' in a Lisp `read'able
1705 ;; output. If you are hacking on this, note that you get *no* output
1706 ;; unless this spits out a complete line, including the '\n' at the
1707 ;; end.
1708 ;; The device number is returned as "-1", because there will be a virtual
1709 ;; device number set in `tramp-handle-file-attributes'.
1710 (defconst tramp-perl-file-attributes
1711 "%s -e '
1712 @stat = lstat($ARGV[0]);
1713 if (!@stat) {
1714 print \"nil\\n\";
1715 exit 0;
1716 }
1717 if (($stat[2] & 0170000) == 0120000)
1718 {
1719 $type = readlink($ARGV[0]);
1720 $type = \"\\\"$type\\\"\";
1721 }
1722 elsif (($stat[2] & 0170000) == 040000)
1723 {
1724 $type = \"t\";
1725 }
1726 else
1727 {
1728 $type = \"nil\"
1729 };
1730 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1731 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1732 printf(
1733 \"(%%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) -1)\\n\",
1734 $type,
1735 $stat[3],
1736 $uid,
1737 $gid,
1738 $stat[8] >> 16 & 0xffff,
1739 $stat[8] & 0xffff,
1740 $stat[9] >> 16 & 0xffff,
1741 $stat[9] & 0xffff,
1742 $stat[10] >> 16 & 0xffff,
1743 $stat[10] & 0xffff,
1744 $stat[7],
1745 $stat[2],
1746 $stat[1] >> 16 & 0xffff,
1747 $stat[1] & 0xffff
1748 );' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1749 "Perl script to produce output suitable for use with `file-attributes'
1750 on the remote file system.
1751 Escape sequence %s is replaced with name of Perl binary.
1752 This string is passed to `format', so percent characters need to be doubled.")
1753
1754 (defconst tramp-perl-directory-files-and-attributes
1755 "%s -e '
1756 chdir($ARGV[0]) or printf(\"\\\"Cannot change to $ARGV[0]: $''!''\\\"\\n\"), exit();
1757 opendir(DIR,\".\") or printf(\"\\\"Cannot open directory $ARGV[0]: $''!''\\\"\\n\"), exit();
1758 @list = readdir(DIR);
1759 closedir(DIR);
1760 $n = scalar(@list);
1761 printf(\"(\\n\");
1762 for($i = 0; $i < $n; $i++)
1763 {
1764 $filename = $list[$i];
1765 @stat = lstat($filename);
1766 if (($stat[2] & 0170000) == 0120000)
1767 {
1768 $type = readlink($filename);
1769 $type = \"\\\"$type\\\"\";
1770 }
1771 elsif (($stat[2] & 0170000) == 040000)
1772 {
1773 $type = \"t\";
1774 }
1775 else
1776 {
1777 $type = \"nil\"
1778 };
1779 $uid = ($ARGV[1] eq \"integer\") ? $stat[4] : \"\\\"\" . getpwuid($stat[4]) . \"\\\"\";
1780 $gid = ($ARGV[1] eq \"integer\") ? $stat[5] : \"\\\"\" . getgrgid($stat[5]) . \"\\\"\";
1781 printf(
1782 \"(\\\"%%s\\\" %%s %%u %%s %%s (%%u %%u) (%%u %%u) (%%u %%u) %%u.0 %%u t (%%u . %%u) (%%u . %%u))\\n\",
1783 $filename,
1784 $type,
1785 $stat[3],
1786 $uid,
1787 $gid,
1788 $stat[8] >> 16 & 0xffff,
1789 $stat[8] & 0xffff,
1790 $stat[9] >> 16 & 0xffff,
1791 $stat[9] & 0xffff,
1792 $stat[10] >> 16 & 0xffff,
1793 $stat[10] & 0xffff,
1794 $stat[7],
1795 $stat[2],
1796 $stat[1] >> 16 & 0xffff,
1797 $stat[1] & 0xffff,
1798 $stat[0] >> 16 & 0xffff,
1799 $stat[0] & 0xffff);
1800 }
1801 printf(\")\\n\");' \"$1\" \"$2\" \"$3\" 2>/dev/null"
1802 "Perl script implementing `directory-files-attributes' as Lisp `read'able
1803 output.
1804 Escape sequence %s is replaced with name of Perl binary.
1805 This string is passed to `format', so percent characters need to be doubled.")
1806
1807 ;; ;; These two use uu encoding.
1808 ;; (defvar tramp-perl-encode "%s -e'\
1809 ;; print qq(begin 644 xxx\n);
1810 ;; my $s = q();
1811 ;; my $res = q();
1812 ;; while (read(STDIN, $s, 45)) {
1813 ;; print pack(q(u), $s);
1814 ;; }
1815 ;; print qq(`\n);
1816 ;; print qq(end\n);
1817 ;; '"
1818 ;; "Perl program to use for encoding a file.
1819 ;; Escape sequence %s is replaced with name of Perl binary.")
1820
1821 ;; (defvar tramp-perl-decode "%s -ne '
1822 ;; print unpack q(u), $_;
1823 ;; '"
1824 ;; "Perl program to use for decoding a file.
1825 ;; Escape sequence %s is replaced with name of Perl binary.")
1826
1827 ;; These two use base64 encoding.
1828 (defconst tramp-perl-encode-with-module
1829 "%s -MMIME::Base64 -0777 -ne 'print encode_base64($_)' 2>/dev/null"
1830 "Perl program to use for encoding a file.
1831 Escape sequence %s is replaced with name of Perl binary.
1832 This string is passed to `format', so percent characters need to be doubled.
1833 This implementation requires the MIME::Base64 Perl module to be installed
1834 on the remote host.")
1835
1836 (defconst tramp-perl-decode-with-module
1837 "%s -MMIME::Base64 -0777 -ne 'print decode_base64($_)' 2>/dev/null"
1838 "Perl program to use for decoding a file.
1839 Escape sequence %s is replaced with name of Perl binary.
1840 This string is passed to `format', so percent characters need to be doubled.
1841 This implementation requires the MIME::Base64 Perl module to be installed
1842 on the remote host.")
1843
1844 (defconst tramp-perl-encode
1845 "%s -e '
1846 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1847 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1848 # Free Software Foundation, Inc.
1849 use strict;
1850
1851 my %%trans = do {
1852 my $i = 0;
1853 map {(substr(unpack(q(B8), chr $i++), 2, 6), $_)}
1854 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/);
1855 };
1856
1857 binmode(\\*STDIN);
1858
1859 # We read in chunks of 54 bytes, to generate output lines
1860 # of 72 chars (plus end of line)
1861 $/ = \\54;
1862
1863 while (my $data = <STDIN>) {
1864 my $pad = q();
1865
1866 # Only for the last chunk, and only if did not fill the last three-byte packet
1867 if (eof) {
1868 my $mod = length($data) %% 3;
1869 $pad = q(=) x (3 - $mod) if $mod;
1870 }
1871
1872 # Not the fastest method, but it is simple: unpack to binary string, split
1873 # by groups of 6 bits and convert back from binary to byte; then map into
1874 # the translation table
1875 print
1876 join q(),
1877 map($trans{$_},
1878 (substr(unpack(q(B*), $data) . q(00000), 0, 432) =~ /....../g)),
1879 $pad,
1880 qq(\\n);
1881 }' 2>/dev/null"
1882 "Perl program to use for encoding a file.
1883 Escape sequence %s is replaced with name of Perl binary.
1884 This string is passed to `format', so percent characters need to be doubled.")
1885
1886 (defconst tramp-perl-decode
1887 "%s -e '
1888 # This script contributed by Juanma Barranquero <lektu@terra.es>.
1889 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
1890 # Free Software Foundation, Inc.
1891 use strict;
1892
1893 my %%trans = do {
1894 my $i = 0;
1895 map {($_, substr(unpack(q(B8), chr $i++), 2, 6))}
1896 split //, q(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)
1897 };
1898
1899 my %%bytes = map {(unpack(q(B8), chr $_), chr $_)} 0 .. 255;
1900
1901 binmode(\\*STDOUT);
1902
1903 # We are going to accumulate into $pending to accept any line length
1904 # (we do not check they are <= 76 chars as the RFC says)
1905 my $pending = q();
1906
1907 while (my $data = <STDIN>) {
1908 chomp $data;
1909
1910 # If we find one or two =, we have reached the end and
1911 # any following data is to be discarded
1912 my $finished = $data =~ s/(==?).*/$1/;
1913 $pending .= $data;
1914
1915 my $len = length($pending);
1916 my $chunk = substr($pending, 0, $len & ~3);
1917 $pending = substr($pending, $len & ~3 + 1);
1918
1919 # Easy method: translate from chars to (pregenerated) six-bit packets, join,
1920 # split in 8-bit chunks and convert back to char.
1921 print join q(),
1922 map $bytes{$_},
1923 ((join q(), map {$trans{$_} || q()} split //, $chunk) =~ /......../g);
1924
1925 last if $finished;
1926 }' 2>/dev/null"
1927 "Perl program to use for decoding a file.
1928 Escape sequence %s is replaced with name of Perl binary.
1929 This string is passed to `format', so percent characters need to be doubled.")
1930
1931 (defconst tramp-vc-registered-read-file-names
1932 "echo \"(\"
1933 for file in \"$@\"; do
1934 if %s $file; then
1935 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" t)\"
1936 else
1937 echo \"(\\\"$file\\\" \\\"file-exists-p\\\" nil)\"
1938 fi
1939 if %s $file; then
1940 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" t)\"
1941 else
1942 echo \"(\\\"$file\\\" \\\"file-readable-p\\\" nil)\"
1943 fi
1944 done
1945 echo \")\""
1946 "Script to check existence of VC related files.
1947 It must be send formatted with two strings; the tests for file
1948 existence, and file readability.")
1949
1950 (defconst tramp-file-mode-type-map
1951 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
1952 (1 . "p") ; fifo
1953 (2 . "c") ; character device
1954 (3 . "m") ; multiplexed character device (v7)
1955 (4 . "d") ; directory
1956 (5 . "?") ; Named special file (XENIX)
1957 (6 . "b") ; block device
1958 (7 . "?") ; multiplexed block device (v7)
1959 (8 . "-") ; regular file
1960 (9 . "n") ; network special file (HP-UX)
1961 (10 . "l") ; symlink
1962 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
1963 (12 . "s") ; socket
1964 (13 . "D") ; door special (Solaris)
1965 (14 . "w")) ; whiteout (BSD)
1966 "A list of file types returned from the `stat' system call.
1967 This is used to map a mode number to a permission string.")
1968
1969 ;; New handlers should be added here. The following operations can be
1970 ;; handled using the normal primitives: file-name-sans-versions,
1971 ;; get-file-buffer.
1972 (defconst tramp-file-name-handler-alist
1973 '((load . tramp-handle-load)
1974 (make-symbolic-link . tramp-handle-make-symbolic-link)
1975 (file-name-as-directory . tramp-handle-file-name-as-directory)
1976 (file-name-directory . tramp-handle-file-name-directory)
1977 (file-name-nondirectory . tramp-handle-file-name-nondirectory)
1978 (file-truename . tramp-handle-file-truename)
1979 (file-exists-p . tramp-handle-file-exists-p)
1980 (file-directory-p . tramp-handle-file-directory-p)
1981 (file-executable-p . tramp-handle-file-executable-p)
1982 (file-readable-p . tramp-handle-file-readable-p)
1983 (file-regular-p . tramp-handle-file-regular-p)
1984 (file-symlink-p . tramp-handle-file-symlink-p)
1985 (file-writable-p . tramp-handle-file-writable-p)
1986 (file-ownership-preserved-p . tramp-handle-file-ownership-preserved-p)
1987 (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
1988 (file-attributes . tramp-handle-file-attributes)
1989 (file-modes . tramp-handle-file-modes)
1990 (directory-files . tramp-handle-directory-files)
1991 (directory-files-and-attributes . tramp-handle-directory-files-and-attributes)
1992 (file-name-all-completions . tramp-handle-file-name-all-completions)
1993 (file-name-completion . tramp-handle-file-name-completion)
1994 (add-name-to-file . tramp-handle-add-name-to-file)
1995 (copy-file . tramp-handle-copy-file)
1996 (copy-directory . tramp-handle-copy-directory)
1997 (rename-file . tramp-handle-rename-file)
1998 (set-file-modes . tramp-handle-set-file-modes)
1999 (set-file-times . tramp-handle-set-file-times)
2000 (make-directory . tramp-handle-make-directory)
2001 (delete-directory . tramp-handle-delete-directory)
2002 (delete-file . tramp-handle-delete-file)
2003 (directory-file-name . tramp-handle-directory-file-name)
2004 ;; `executable-find' is not official yet.
2005 (executable-find . tramp-handle-executable-find)
2006 (start-file-process . tramp-handle-start-file-process)
2007 (process-file . tramp-handle-process-file)
2008 (shell-command . tramp-handle-shell-command)
2009 (insert-directory . tramp-handle-insert-directory)
2010 (expand-file-name . tramp-handle-expand-file-name)
2011 (substitute-in-file-name . tramp-handle-substitute-in-file-name)
2012 (file-local-copy . tramp-handle-file-local-copy)
2013 (file-remote-p . tramp-handle-file-remote-p)
2014 (insert-file-contents . tramp-handle-insert-file-contents)
2015 (insert-file-contents-literally
2016 . tramp-handle-insert-file-contents-literally)
2017 (write-region . tramp-handle-write-region)
2018 (find-backup-file-name . tramp-handle-find-backup-file-name)
2019 (make-auto-save-file-name . tramp-handle-make-auto-save-file-name)
2020 (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
2021 (dired-compress-file . tramp-handle-dired-compress-file)
2022 (dired-recursive-delete-directory
2023 . tramp-handle-dired-recursive-delete-directory)
2024 (dired-uncache . tramp-handle-dired-uncache)
2025 (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
2026 (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
2027 (vc-registered . tramp-handle-vc-registered))
2028 "Alist of handler functions.
2029 Operations not mentioned here will be handled by the normal Emacs functions.")
2030
2031 ;; Handlers for partial Tramp file names. For Emacs just
2032 ;; `file-name-all-completions' is needed.
2033 ;;;###autoload
2034 (defconst tramp-completion-file-name-handler-alist
2035 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
2036 (file-name-completion . tramp-completion-handle-file-name-completion))
2037 "Alist of completion handler functions.
2038 Used for file names matching `tramp-file-name-regexp'. Operations not
2039 mentioned here will be handled by `tramp-file-name-handler-alist' or the
2040 normal Emacs functions.")
2041
2042 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
2043 (defvar tramp-foreign-file-name-handler-alist
2044 ;; (identity . tramp-sh-file-name-handler) should always be the last
2045 ;; entry, because `identity' always matches.
2046 '((identity . tramp-sh-file-name-handler))
2047 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
2048 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
2049 calling HANDLER.")
2050
2051 ;;; Internal functions which must come first:
2052
2053 (defsubst tramp-debug-message (vec fmt-string &rest args)
2054 "Append message to debug buffer.
2055 Message is formatted with FMT-STRING as control string and the remaining
2056 ARGS to actually emit the message (if applicable)."
2057 (when (get-buffer (tramp-buffer-name vec))
2058 (with-current-buffer (tramp-get-debug-buffer vec)
2059 (goto-char (point-max))
2060 ;; Headline.
2061 (when (bobp)
2062 (insert
2063 (format
2064 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
2065 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
2066 emacs-version tramp-version)))
2067 (unless (bolp)
2068 (insert "\n"))
2069 ;; Timestamp.
2070 (let ((now (current-time)))
2071 (insert (format-time-string "%T." now))
2072 (insert (format "%06d " (nth 2 now))))
2073 ;; Calling function.
2074 (let ((btn 1) btf fn)
2075 (while (not fn)
2076 (setq btf (nth 1 (backtrace-frame btn)))
2077 (if (not btf)
2078 (setq fn "")
2079 (when (symbolp btf)
2080 (setq fn (symbol-name btf))
2081 (unless (and (string-match "^tramp" fn)
2082 (not (string-match
2083 "^tramp\\(-debug\\)?\\(-message\\|-error\\)$"
2084 fn)))
2085 (setq fn nil)))
2086 (setq btn (1+ btn))))
2087 ;; The following code inserts filename and line number.
2088 ;; Should be deactivated by default, because it is time
2089 ;; consuming.
2090 ; (let ((ffn (find-function-noselect (intern fn))))
2091 ; (insert
2092 ; (format
2093 ; "%s:%d: "
2094 ; (file-name-nondirectory (buffer-file-name (car ffn)))
2095 ; (with-current-buffer (car ffn)
2096 ; (1+ (count-lines (point-min) (cdr ffn)))))))
2097 (insert (format "%s " fn)))
2098 ;; The message.
2099 (insert (apply 'format fmt-string args)))))
2100
2101 (defvar tramp-message-show-message t
2102 "Show Tramp message in the minibuffer.
2103 This variable is used to disable messages from `tramp-error'.
2104 The messages are visible anyway, because an error is raised.")
2105
2106 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
2107 "Emit a message depending on verbosity level.
2108 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
2109 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
2110 less than LEVEL. The message is emitted only if `tramp-verbose' is
2111 greater than or equal to LEVEL.
2112
2113 The message is also logged into the debug buffer when `tramp-verbose'
2114 is greater than or equal 4.
2115
2116 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
2117 control string and the remaining ARGS to actually emit the message (if
2118 applicable)."
2119 (condition-case nil
2120 (when (<= level tramp-verbose)
2121 ;; Match data must be preserved!
2122 (save-match-data
2123 ;; Display only when there is a minimum level.
2124 (when (and tramp-message-show-message (<= level 3))
2125 (apply 'message
2126 (concat
2127 (cond
2128 ((= level 0) "")
2129 ((= level 1) "")
2130 ((= level 2) "Warning: ")
2131 (t "Tramp: "))
2132 fmt-string)
2133 args))
2134 ;; Log only when there is a minimum level.
2135 (when (>= tramp-verbose 4)
2136 (when (and vec-or-proc
2137 (processp vec-or-proc)
2138 (buffer-name (process-buffer vec-or-proc)))
2139 (with-current-buffer (process-buffer vec-or-proc)
2140 ;; Translate proc to vec.
2141 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
2142 (when (and vec-or-proc (vectorp vec-or-proc))
2143 (apply 'tramp-debug-message
2144 vec-or-proc
2145 (concat (format "(%d) # " level) fmt-string)
2146 args)))))
2147 ;; Suppress all errors.
2148 (error nil)))
2149
2150 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
2151 "Emit an error.
2152 VEC-OR-PROC identifies the connection to use, SIGNAL is the
2153 signal identifier to be raised, remaining args passed to
2154 `tramp-message'. Finally, signal SIGNAL is raised."
2155 (let (tramp-message-show-message)
2156 (tramp-message
2157 vec-or-proc 1 "%s"
2158 (error-message-string
2159 (list signal
2160 (get signal 'error-message)
2161 (apply 'format fmt-string args))))
2162 (signal signal (list (apply 'format fmt-string args)))))
2163
2164 (defsubst tramp-error-with-buffer
2165 (buffer vec-or-proc signal fmt-string &rest args)
2166 "Emit an error, and show BUFFER.
2167 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
2168 an input event arrives. The other arguments are passed to `tramp-error'."
2169 (save-window-excursion
2170 (unwind-protect
2171 (apply 'tramp-error vec-or-proc signal fmt-string args)
2172 (when (and vec-or-proc (not (zerop tramp-verbose)))
2173 (let ((enable-recursive-minibuffers t))
2174 (pop-to-buffer
2175 (or (and (bufferp buffer) buffer)
2176 (and (processp vec-or-proc) (process-buffer vec-or-proc))
2177 (tramp-get-buffer vec-or-proc)))
2178 (sit-for 30))))))
2179
2180 (defmacro with-parsed-tramp-file-name (filename var &rest body)
2181 "Parse a Tramp filename and make components available in the body.
2182
2183 First arg FILENAME is evaluated and dissected into its components.
2184 Second arg VAR is a symbol. It is used as a variable name to hold
2185 the filename structure. It is also used as a prefix for the variables
2186 holding the components. For example, if VAR is the symbol `foo', then
2187 `foo' will be bound to the whole structure, `foo-method' will be bound to
2188 the method component, and so on for `foo-user', `foo-host', `foo-localname'.
2189
2190 Remaining args are Lisp expressions to be evaluated (inside an implicit
2191 `progn').
2192
2193 If VAR is nil, then we bind `v' to the structure and `method', `user',
2194 `host', `localname' to the components."
2195 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
2196 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
2197 (tramp-file-name-method ,(or var 'v)))
2198 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
2199 (tramp-file-name-user ,(or var 'v)))
2200 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
2201 (tramp-file-name-host ,(or var 'v)))
2202 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
2203 (tramp-file-name-localname ,(or var 'v))))
2204 ,@body))
2205
2206 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
2207 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
2208 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
2209
2210 (defmacro with-file-property (vec file property &rest body)
2211 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
2212 FILE must be a local file name on a connection identified via VEC."
2213 `(if (file-name-absolute-p ,file)
2214 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
2215 (when (eq value 'undef)
2216 ;; We cannot pass @body as parameter to
2217 ;; `tramp-set-file-property' because it mangles our
2218 ;; debug messages.
2219 (setq value (progn ,@body))
2220 (tramp-set-file-property ,vec ,file ,property value))
2221 value)
2222 ,@body))
2223
2224 (put 'with-file-property 'lisp-indent-function 3)
2225 (put 'with-file-property 'edebug-form-spec t)
2226 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-file-property\\>"))
2227
2228 (defmacro with-connection-property (key property &rest body)
2229 "Checks in Tramp for property PROPERTY, otherwise executes BODY and set."
2230 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
2231 (when (eq value 'undef)
2232 ;; We cannot pass ,@body as parameter to
2233 ;; `tramp-set-connection-property' because it mangles our debug
2234 ;; messages.
2235 (setq value (progn ,@body))
2236 (tramp-set-connection-property ,key ,property value))
2237 value))
2238
2239 (put 'with-connection-property 'lisp-indent-function 2)
2240 (put 'with-connection-property 'edebug-form-spec t)
2241 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-connection-property\\>"))
2242
2243 (eval-and-compile ; silence compiler
2244 (if (memq system-type '(cygwin windows-nt))
2245 (defun tramp-drop-volume-letter (name)
2246 "Cut off unnecessary drive letter from file NAME.
2247 The function `tramp-handle-expand-file-name' calls `expand-file-name'
2248 locally on a remote file name. When the local system is a W32 system
2249 but the remote system is Unix, this introduces a superfluous drive
2250 letter into the file name. This function removes it."
2251 (save-match-data
2252 (if (string-match tramp-root-regexp name)
2253 (replace-match "/" nil t name)
2254 name)))
2255
2256 (defalias 'tramp-drop-volume-letter 'identity)))
2257
2258 (defsubst tramp-make-tramp-temp-file (vec)
2259 "Create a temporary file on the remote host identified by VEC.
2260 Return the local name of the temporary file."
2261 (let ((prefix
2262 (tramp-make-tramp-file-name
2263 (tramp-file-name-method vec)
2264 (tramp-file-name-user vec)
2265 (tramp-file-name-host vec)
2266 (tramp-drop-volume-letter
2267 (expand-file-name
2268 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))))
2269 result)
2270 (while (not result)
2271 ;; `make-temp-file' would be the natural choice for
2272 ;; implementation. But it calls `write-region' internally,
2273 ;; which also needs a temporary file - we would end in an
2274 ;; infinite loop.
2275 (setq result (make-temp-name prefix))
2276 (if (file-exists-p result)
2277 (setq result nil)
2278 ;; This creates the file by side effect.
2279 (set-file-times result)
2280 (set-file-modes result (tramp-octal-to-decimal "0700"))))
2281
2282 ;; Return the local part.
2283 (with-parsed-tramp-file-name result nil localname)))
2284
2285
2286 ;;; Config Manipulation Functions:
2287
2288 (defun tramp-set-completion-function (method function-list)
2289 "Sets the list of completion functions for METHOD.
2290 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
2291 The FUNCTION is intended to parse FILE according its syntax.
2292 It might be a predefined FUNCTION, or a user defined FUNCTION.
2293 Predefined FUNCTIONs are `tramp-parse-rhosts', `tramp-parse-shosts',
2294 `tramp-parse-sconfig', `tramp-parse-hosts', `tramp-parse-passwd',
2295 and `tramp-parse-netrc'.
2296
2297 Example:
2298
2299 (tramp-set-completion-function
2300 \"ssh\"
2301 '((tramp-parse-sconfig \"/etc/ssh_config\")
2302 (tramp-parse-sconfig \"~/.ssh/config\")))"
2303
2304 (let ((r function-list)
2305 (v function-list))
2306 (setq tramp-completion-function-alist
2307 (delete (assoc method tramp-completion-function-alist)
2308 tramp-completion-function-alist))
2309
2310 (while v
2311 ;; Remove double entries.
2312 (when (member (car v) (cdr v))
2313 (setcdr v (delete (car v) (cdr v))))
2314 ;; Check for function and file or registry key.
2315 (unless (and (functionp (nth 0 (car v)))
2316 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
2317 ;; Windows registry.
2318 (and (memq system-type '(cygwin windows-nt))
2319 (zerop
2320 (tramp-local-call-process
2321 "reg" nil nil nil "query" (nth 1 (car v)))))
2322 ;; Configuration file.
2323 (file-exists-p (nth 1 (car v)))))
2324 (setq r (delete (car v) r)))
2325 (setq v (cdr v)))
2326
2327 (when r
2328 (add-to-list 'tramp-completion-function-alist
2329 (cons method r)))))
2330
2331 (defun tramp-get-completion-function (method)
2332 "Returns a list of completion functions for METHOD.
2333 For definition of that list see `tramp-set-completion-function'."
2334 (cons
2335 ;; Hosts visited once shall be remembered.
2336 `(tramp-parse-connection-properties ,method)
2337 ;; The method related defaults.
2338 (cdr (assoc method tramp-completion-function-alist))))
2339
2340
2341 ;;; Fontification of `read-file-name':
2342
2343 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
2344 (defvar tramp-rfn-eshadow-overlay)
2345 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
2346
2347 (defun tramp-rfn-eshadow-setup-minibuffer ()
2348 "Set up a minibuffer for `file-name-shadow-mode'.
2349 Adds another overlay hiding filename parts according to Tramp's
2350 special handling of `substitute-in-file-name'."
2351 (when (symbol-value 'minibuffer-completing-file-name)
2352 (setq tramp-rfn-eshadow-overlay
2353 (funcall (symbol-function 'make-overlay)
2354 (funcall (symbol-function 'minibuffer-prompt-end))
2355 (funcall (symbol-function 'minibuffer-prompt-end))))
2356 ;; Copy rfn-eshadow-overlay properties.
2357 (let ((props (funcall (symbol-function 'overlay-properties)
2358 (symbol-value 'rfn-eshadow-overlay))))
2359 (while props
2360 (funcall (symbol-function 'overlay-put)
2361 tramp-rfn-eshadow-overlay (pop props) (pop props))))))
2362
2363 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
2364 (add-hook 'rfn-eshadow-setup-minibuffer-hook
2365 'tramp-rfn-eshadow-setup-minibuffer)
2366 (add-hook 'tramp-unload-hook
2367 (lambda ()
2368 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
2369 'tramp-rfn-eshadow-setup-minibuffer))))
2370
2371 (defconst tramp-rfn-eshadow-update-overlay-regexp
2372 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
2373
2374 (defun tramp-rfn-eshadow-update-overlay ()
2375 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
2376 This is intended to be used as a minibuffer `post-command-hook' for
2377 `file-name-shadow-mode'; the minibuffer should have already
2378 been set up by `rfn-eshadow-setup-minibuffer'."
2379 ;; In remote files name, there is a shadowing just for the local part.
2380 (let ((end (or (funcall (symbol-function 'overlay-end)
2381 (symbol-value 'rfn-eshadow-overlay))
2382 (funcall (symbol-function 'minibuffer-prompt-end)))))
2383 (when (file-remote-p (buffer-substring-no-properties end (point-max)))
2384 (save-excursion
2385 (save-restriction
2386 (narrow-to-region
2387 (1+ (or (string-match
2388 tramp-rfn-eshadow-update-overlay-regexp (buffer-string) end)
2389 end))
2390 (point-max))
2391 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
2392 (rfn-eshadow-update-overlay-hook nil))
2393 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
2394 (funcall (symbol-function 'rfn-eshadow-update-overlay))))))))
2395
2396 (when (boundp 'rfn-eshadow-update-overlay-hook)
2397 (add-hook 'rfn-eshadow-update-overlay-hook
2398 'tramp-rfn-eshadow-update-overlay)
2399 (add-hook 'tramp-unload-hook
2400 (lambda ()
2401 (remove-hook 'rfn-eshadow-update-overlay-hook
2402 'tramp-rfn-eshadow-update-overlay))))
2403
2404
2405 ;;; Integration of eshell.el:
2406
2407 (eval-when-compile
2408 (defvar eshell-path-env))
2409
2410 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
2411 ;; when `default-directory' points to another host.
2412 (defun tramp-eshell-directory-change ()
2413 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
2414 (setq eshell-path-env
2415 (if (file-remote-p default-directory)
2416 (with-parsed-tramp-file-name default-directory nil
2417 (mapconcat
2418 'identity
2419 (tramp-get-remote-path v)
2420 ":"))
2421 (getenv "PATH"))))
2422
2423 (eval-after-load "esh-util"
2424 '(progn
2425 (tramp-eshell-directory-change)
2426 (add-hook 'eshell-directory-change-hook
2427 'tramp-eshell-directory-change)
2428 (add-hook 'tramp-unload-hook
2429 (lambda ()
2430 (remove-hook 'eshell-directory-change-hook
2431 'tramp-eshell-directory-change)))))
2432
2433
2434 ;;; File Name Handler Functions:
2435
2436 (defun tramp-handle-make-symbolic-link
2437 (filename linkname &optional ok-if-already-exists)
2438 "Like `make-symbolic-link' for Tramp files.
2439 If LINKNAME is a non-Tramp file, it is used verbatim as the target of
2440 the symlink. If LINKNAME is a Tramp file, only the localname component is
2441 used as the target of the symlink.
2442
2443 If LINKNAME is a Tramp file and the localname component is relative, then
2444 it is expanded first, before the localname component is taken. Note that
2445 this can give surprising results if the user/host for the source and
2446 target of the symlink differ."
2447 (with-parsed-tramp-file-name linkname l
2448 (let ((ln (tramp-get-remote-ln l))
2449 (cwd (tramp-run-real-handler
2450 'file-name-directory (list l-localname))))
2451 (unless ln
2452 (tramp-error
2453 l 'file-error
2454 "Making a symbolic link. ln(1) does not exist on the remote host."))
2455
2456 ;; Do the 'confirm if exists' thing.
2457 (when (file-exists-p linkname)
2458 ;; What to do?
2459 (if (or (null ok-if-already-exists) ; not allowed to exist
2460 (and (numberp ok-if-already-exists)
2461 (not (yes-or-no-p
2462 (format
2463 "File %s already exists; make it a link anyway? "
2464 l-localname)))))
2465 (tramp-error
2466 l 'file-already-exists "File %s already exists" l-localname)
2467 (delete-file linkname)))
2468
2469 ;; If FILENAME is a Tramp name, use just the localname component.
2470 (when (tramp-tramp-file-p filename)
2471 (setq filename
2472 (tramp-file-name-localname
2473 (tramp-dissect-file-name (expand-file-name filename)))))
2474
2475 ;; Right, they are on the same host, regardless of user, method, etc.
2476 ;; We now make the link on the remote machine. This will occur as the user
2477 ;; that FILENAME belongs to.
2478 (zerop
2479 (tramp-send-command-and-check
2480 l
2481 (format
2482 "cd %s && %s -sf %s %s"
2483 (tramp-shell-quote-argument cwd)
2484 ln
2485 (tramp-shell-quote-argument filename)
2486 (tramp-shell-quote-argument l-localname))
2487 t)))))
2488
2489 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2490 "Like `load' for Tramp files."
2491 (with-parsed-tramp-file-name (expand-file-name file) nil
2492 (unless nosuffix
2493 (cond ((file-exists-p (concat file ".elc"))
2494 (setq file (concat file ".elc")))
2495 ((file-exists-p (concat file ".el"))
2496 (setq file (concat file ".el")))))
2497 (when must-suffix
2498 ;; The first condition is always true for absolute file names.
2499 ;; Included for safety's sake.
2500 (unless (or (file-name-directory file)
2501 (string-match "\\.elc?\\'" file))
2502 (tramp-error
2503 v 'file-error
2504 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2505 (unless noerror
2506 (when (not (file-exists-p file))
2507 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2508 (if (not (file-exists-p file))
2509 nil
2510 (unless nomessage (tramp-message v 0 "Loading %s..." file))
2511 (let ((local-copy (file-local-copy file)))
2512 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2513 (unwind-protect
2514 (load local-copy noerror t t)
2515 (delete-file local-copy)))
2516 (unless nomessage (tramp-message v 0 "Loading %s...done" file))
2517 t)))
2518
2519 ;; Localname manipulation functions that grok Tramp localnames...
2520 (defun tramp-handle-file-name-as-directory (file)
2521 "Like `file-name-as-directory' but aware of Tramp files."
2522 ;; `file-name-as-directory' would be sufficient except localname is
2523 ;; the empty string.
2524 (let ((v (tramp-dissect-file-name file t)))
2525 ;; Run the command on the localname portion only.
2526 (tramp-make-tramp-file-name
2527 (tramp-file-name-method v)
2528 (tramp-file-name-user v)
2529 (tramp-file-name-host v)
2530 (tramp-run-real-handler
2531 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2532
2533 (defun tramp-handle-file-name-directory (file)
2534 "Like `file-name-directory' but aware of Tramp files."
2535 ;; Everything except the last filename thing is the directory. We
2536 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2537 ;; the remote file name parts. This is a problem when we are in
2538 ;; file name completion.
2539 (let ((v (tramp-dissect-file-name file t)))
2540 ;; Run the command on the localname portion only.
2541 (tramp-make-tramp-file-name
2542 (tramp-file-name-method v)
2543 (tramp-file-name-user v)
2544 (tramp-file-name-host v)
2545 (tramp-run-real-handler
2546 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2547
2548 (defun tramp-handle-file-name-nondirectory (file)
2549 "Like `file-name-nondirectory' but aware of Tramp files."
2550 (with-parsed-tramp-file-name file nil
2551 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2552
2553 (defun tramp-handle-file-truename (filename &optional counter prev-dirs)
2554 "Like `file-truename' for Tramp files."
2555 (with-parsed-tramp-file-name (expand-file-name filename) nil
2556 (with-file-property v localname "file-truename"
2557 (let ((result nil)) ; result steps in reverse order
2558 (tramp-message v 4 "Finding true name for `%s'" filename)
2559 (cond
2560 ;; Use GNU readlink --canonicalize-missing where available.
2561 ((tramp-get-remote-readlink v)
2562 (setq result
2563 (tramp-send-command-and-read
2564 v
2565 (format "echo \"\\\"`%s --canonicalize-missing %s`\\\"\""
2566 (tramp-get-remote-readlink v)
2567 (tramp-shell-quote-argument localname)))))
2568
2569 ;; Use Perl implementation.
2570 ((and (tramp-get-remote-perl v)
2571 (tramp-get-connection-property v "perl-file-spec" nil)
2572 (tramp-get-connection-property v "perl-cwd-realpath" nil))
2573 (tramp-maybe-send-script
2574 v tramp-perl-file-truename "tramp_perl_file_truename")
2575 (setq result
2576 (tramp-send-command-and-read
2577 v
2578 (format "tramp_perl_file_truename %s"
2579 (tramp-shell-quote-argument localname)))))
2580
2581 ;; Do it yourself. We bind `directory-sep-char' here for
2582 ;; XEmacs on Windows, which would otherwise use backslash.
2583 (t (let* ((directory-sep-char ?/)
2584 (steps (tramp-compat-split-string localname "/"))
2585 (localnamedir (tramp-run-real-handler
2586 'file-name-as-directory (list localname)))
2587 (is-dir (string= localname localnamedir))
2588 (thisstep nil)
2589 (numchase 0)
2590 ;; Don't make the following value larger than
2591 ;; necessary. People expect an error message in a
2592 ;; timely fashion when something is wrong;
2593 ;; otherwise they might think that Emacs is hung.
2594 ;; Of course, correctness has to come first.
2595 (numchase-limit 20)
2596 symlink-target)
2597 (while (and steps (< numchase numchase-limit))
2598 (setq thisstep (pop steps))
2599 (tramp-message
2600 v 5 "Check %s"
2601 (mapconcat 'identity
2602 (append '("") (reverse result) (list thisstep))
2603 "/"))
2604 (setq symlink-target
2605 (nth 0 (file-attributes
2606 (tramp-make-tramp-file-name
2607 method user host
2608 (mapconcat 'identity
2609 (append '("")
2610 (reverse result)
2611 (list thisstep))
2612 "/")))))
2613 (cond ((string= "." thisstep)
2614 (tramp-message v 5 "Ignoring step `.'"))
2615 ((string= ".." thisstep)
2616 (tramp-message v 5 "Processing step `..'")
2617 (pop result))
2618 ((stringp symlink-target)
2619 ;; It's a symlink, follow it.
2620 (tramp-message v 5 "Follow symlink to %s" symlink-target)
2621 (setq numchase (1+ numchase))
2622 (when (file-name-absolute-p symlink-target)
2623 (setq result nil))
2624 ;; If the symlink was absolute, we'll get a string like
2625 ;; "/user@host:/some/target"; extract the
2626 ;; "/some/target" part from it.
2627 (when (tramp-tramp-file-p symlink-target)
2628 (unless (tramp-equal-remote filename symlink-target)
2629 (tramp-error
2630 v 'file-error
2631 "Symlink target `%s' on wrong host" symlink-target))
2632 (setq symlink-target localname))
2633 (setq steps
2634 (append (tramp-compat-split-string
2635 symlink-target "/")
2636 steps)))
2637 (t
2638 ;; It's a file.
2639 (setq result (cons thisstep result)))))
2640 (when (>= numchase numchase-limit)
2641 (tramp-error
2642 v 'file-error
2643 "Maximum number (%d) of symlinks exceeded" numchase-limit))
2644 (setq result (reverse result))
2645 ;; Combine list to form string.
2646 (setq result
2647 (if result
2648 (mapconcat 'identity (cons "" result) "/")
2649 "/"))
2650 (when (and is-dir (or (string= "" result)
2651 (not (string= (substring result -1) "/"))))
2652 (setq result (concat result "/"))))))
2653
2654 (tramp-message v 4 "True name of `%s' is `%s'" filename result)
2655 (tramp-make-tramp-file-name method user host result)))))
2656
2657 ;; Basic functions.
2658
2659 (defun tramp-handle-file-exists-p (filename)
2660 "Like `file-exists-p' for Tramp files."
2661 (with-parsed-tramp-file-name filename nil
2662 (with-file-property v localname "file-exists-p"
2663 (or (not (null (tramp-get-file-property
2664 v localname "file-attributes-integer" nil)))
2665 (not (null (tramp-get-file-property
2666 v localname "file-attributes-string" nil)))
2667 (zerop (tramp-send-command-and-check
2668 v
2669 (format
2670 "%s %s"
2671 (tramp-get-file-exists-command v)
2672 (tramp-shell-quote-argument localname))))))))
2673
2674 ;; Inodes don't exist for some file systems. Therefore we must
2675 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
2676 ;; applied might be not so efficient (Ange-FTP uses hashes). But
2677 ;; performance isn't the major issue given that file transfer will
2678 ;; take time.
2679 (defvar tramp-inodes nil
2680 "Keeps virtual inodes numbers.")
2681
2682 ;; Devices must distinguish physical file systems. The device numbers
2683 ;; provided by "lstat" aren't unique, because we operate on different hosts.
2684 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
2685 ;; EFS use device number "-1". In order to be different, we use device number
2686 ;; (-1 . x), whereby "x" is unique for a given (method user host).
2687 (defvar tramp-devices nil
2688 "Keeps virtual device numbers.")
2689
2690 ;; CCC: This should check for an error condition and signal failure
2691 ;; when something goes wrong.
2692 ;; Daniel Pittman <daniel@danann.net>
2693 (defun tramp-handle-file-attributes (filename &optional id-format)
2694 "Like `file-attributes' for Tramp files."
2695 (unless id-format (setq id-format 'integer))
2696 ;; Don't modify `last-coding-system-used' by accident.
2697 (let ((last-coding-system-used last-coding-system-used))
2698 (with-parsed-tramp-file-name (expand-file-name filename) nil
2699 (with-file-property v localname (format "file-attributes-%s" id-format)
2700 (save-excursion
2701 (tramp-convert-file-attributes
2702 v
2703 (cond
2704 ((tramp-get-remote-stat v)
2705 (tramp-do-file-attributes-with-stat v localname id-format))
2706 ((tramp-get-remote-perl v)
2707 (tramp-do-file-attributes-with-perl v localname id-format))
2708 (t
2709 (tramp-do-file-attributes-with-ls v localname id-format)))))))))
2710
2711 (defun tramp-do-file-attributes-with-ls (vec localname &optional id-format)
2712 "Implement `file-attributes' for Tramp files using the ls(1) command."
2713 (let (symlinkp dirp
2714 res-inode res-filemodes res-numlinks
2715 res-uid res-gid res-size res-symlink-target)
2716 (tramp-message vec 5 "file attributes with ls: %s" localname)
2717 (tramp-send-command
2718 vec
2719 (format "(%s %s || %s -h %s) && %s %s %s"
2720 (tramp-get-file-exists-command vec)
2721 (tramp-shell-quote-argument localname)
2722 (tramp-get-test-command vec)
2723 (tramp-shell-quote-argument localname)
2724 (tramp-get-ls-command vec)
2725 (if (eq id-format 'integer) "-ildn" "-ild")
2726 (tramp-shell-quote-argument localname)))
2727 ;; parse `ls -l' output ...
2728 (with-current-buffer (tramp-get-buffer vec)
2729 (when (> (buffer-size) 0)
2730 (goto-char (point-min))
2731 ;; ... inode
2732 (setq res-inode
2733 (condition-case err
2734 (read (current-buffer))
2735 (invalid-read-syntax
2736 (when (and (equal (cadr err)
2737 "Integer constant overflow in reader")
2738 (string-match
2739 "^[0-9]+\\([0-9][0-9][0-9][0-9][0-9]\\)\\'"
2740 (car (cddr err))))
2741 (let* ((big (read (substring (car (cddr err)) 0
2742 (match-beginning 1))))
2743 (small (read (match-string 1 (car (cddr err)))))
2744 (twiddle (/ small 65536)))
2745 (cons (+ big twiddle)
2746 (- small (* twiddle 65536))))))))
2747 ;; ... file mode flags
2748 (setq res-filemodes (symbol-name (read (current-buffer))))
2749 ;; ... number links
2750 (setq res-numlinks (read (current-buffer)))
2751 ;; ... uid and gid
2752 (setq res-uid (read (current-buffer)))
2753 (setq res-gid (read (current-buffer)))
2754 (if (eq id-format 'integer)
2755 (progn
2756 (unless (numberp res-uid) (setq res-uid -1))
2757 (unless (numberp res-gid) (setq res-gid -1)))
2758 (progn
2759 (unless (stringp res-uid) (setq res-uid (symbol-name res-uid)))
2760 (unless (stringp res-gid) (setq res-gid (symbol-name res-gid)))))
2761 ;; ... size
2762 (setq res-size (read (current-buffer)))
2763 ;; From the file modes, figure out other stuff.
2764 (setq symlinkp (eq ?l (aref res-filemodes 0)))
2765 (setq dirp (eq ?d (aref res-filemodes 0)))
2766 ;; if symlink, find out file name pointed to
2767 (when symlinkp
2768 (search-forward "-> ")
2769 (setq res-symlink-target
2770 (buffer-substring (point) (tramp-compat-line-end-position))))
2771 ;; return data gathered
2772 (list
2773 ;; 0. t for directory, string (name linked to) for symbolic
2774 ;; link, or nil.
2775 (or dirp res-symlink-target)
2776 ;; 1. Number of links to file.
2777 res-numlinks
2778 ;; 2. File uid.
2779 res-uid
2780 ;; 3. File gid.
2781 res-gid
2782 ;; 4. Last access time, as a list of two integers. First
2783 ;; integer has high-order 16 bits of time, second has low 16
2784 ;; bits.
2785 ;; 5. Last modification time, likewise.
2786 ;; 6. Last status change time, likewise.
2787 '(0 0) '(0 0) '(0 0) ;CCC how to find out?
2788 ;; 7. Size in bytes (-1, if number is out of range).
2789 res-size
2790 ;; 8. File modes, as a string of ten letters or dashes as in ls -l.
2791 res-filemodes
2792 ;; 9. t if file's gid would change if file were deleted and
2793 ;; recreated. Will be set in `tramp-convert-file-attributes'
2794 t
2795 ;; 10. inode number.
2796 res-inode
2797 ;; 11. Device number. Will be replaced by a virtual device number.
2798 -1
2799 )))))
2800
2801 (defun tramp-do-file-attributes-with-perl
2802 (vec localname &optional id-format)
2803 "Implement `file-attributes' for Tramp files using a Perl script."
2804 (tramp-message vec 5 "file attributes with perl: %s" localname)
2805 (tramp-maybe-send-script
2806 vec tramp-perl-file-attributes "tramp_perl_file_attributes")
2807 (tramp-send-command-and-read
2808 vec
2809 (format "tramp_perl_file_attributes %s %s"
2810 (tramp-shell-quote-argument localname) id-format)))
2811
2812 (defun tramp-do-file-attributes-with-stat
2813 (vec localname &optional id-format)
2814 "Implement `file-attributes' for Tramp files using stat(1) command."
2815 (tramp-message vec 5 "file attributes with stat: %s" localname)
2816 (tramp-send-command-and-read
2817 vec
2818 (format
2819 "((%s %s || %s -h %s) && %s -c '((\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)' %s || echo nil)"
2820 (tramp-get-file-exists-command vec)
2821 (tramp-shell-quote-argument localname)
2822 (tramp-get-test-command vec)
2823 (tramp-shell-quote-argument localname)
2824 (tramp-get-remote-stat vec)
2825 (if (eq id-format 'integer) "%u" "\"%U\"")
2826 (if (eq id-format 'integer) "%g" "\"%G\"")
2827 (tramp-shell-quote-argument localname))))
2828
2829 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
2830 "Like `set-visited-file-modtime' for Tramp files."
2831 (unless (buffer-file-name)
2832 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
2833 (buffer-name)))
2834 (if time-list
2835 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))
2836 (let ((f (buffer-file-name))
2837 coding-system-used)
2838 (with-parsed-tramp-file-name f nil
2839 (let* ((attr (file-attributes f))
2840 ;; '(-1 65535) means file doesn't exists yet.
2841 (modtime (or (nth 5 attr) '(-1 65535))))
2842 (when (boundp 'last-coding-system-used)
2843 (setq coding-system-used (symbol-value 'last-coding-system-used)))
2844 ;; We use '(0 0) as a don't-know value. See also
2845 ;; `tramp-do-file-attributes-with-ls'.
2846 (if (not (equal modtime '(0 0)))
2847 (tramp-run-real-handler 'set-visited-file-modtime (list modtime))
2848 (progn
2849 (tramp-send-command
2850 v
2851 (format "%s -ild %s"
2852 (tramp-get-ls-command v)
2853 (tramp-shell-quote-argument localname)))
2854 (setq attr (buffer-substring (point)
2855 (progn (end-of-line) (point)))))
2856 (tramp-set-file-property
2857 v localname "visited-file-modtime-ild" attr))
2858 (when (boundp 'last-coding-system-used)
2859 (set 'last-coding-system-used coding-system-used))
2860 nil)))))
2861
2862 ;; This function makes the same assumption as
2863 ;; `tramp-handle-set-visited-file-modtime'.
2864 (defun tramp-handle-verify-visited-file-modtime (buf)
2865 "Like `verify-visited-file-modtime' for Tramp files.
2866 At the time `verify-visited-file-modtime' calls this function, we
2867 already know that the buffer is visiting a file and that
2868 `visited-file-modtime' does not return 0. Do not call this
2869 function directly, unless those two cases are already taken care
2870 of."
2871 (with-current-buffer buf
2872 ;; There is no file visiting the buffer, or the buffer has no
2873 ;; recorded last modification time.
2874 (if (or (not (buffer-file-name))
2875 (eq (visited-file-modtime) 0))
2876 t
2877 (let ((f (buffer-file-name)))
2878 (with-parsed-tramp-file-name f nil
2879 (tramp-flush-file-property v localname)
2880 (let* ((attr (file-attributes f))
2881 (modtime (nth 5 attr))
2882 (mt (visited-file-modtime)))
2883
2884 (cond
2885 ;; File exists, and has a known modtime.
2886 ((and attr (not (equal modtime '(0 0))))
2887 (< (abs (tramp-time-diff
2888 modtime
2889 ;; For compatibility, deal with both the old
2890 ;; (HIGH . LOW) and the new (HIGH LOW) return
2891 ;; values of `visited-file-modtime'.
2892 (if (atom (cdr mt))
2893 (list (car mt) (cdr mt))
2894 mt)))
2895 2))
2896 ;; Modtime has the don't know value.
2897 (attr
2898 (tramp-send-command
2899 v
2900 (format "%s -ild %s"
2901 (tramp-get-ls-command v)
2902 (tramp-shell-quote-argument localname)))
2903 (with-current-buffer (tramp-get-buffer v)
2904 (setq attr (buffer-substring
2905 (point) (progn (end-of-line) (point)))))
2906 (equal
2907 attr
2908 (tramp-get-file-property
2909 v localname "visited-file-modtime-ild" "")))
2910 ;; If file does not exist, say it is not modified if and
2911 ;; only if that agrees with the buffer's record.
2912 (t (equal mt '(-1 65535))))))))))
2913
2914 (defun tramp-handle-set-file-modes (filename mode)
2915 "Like `set-file-modes' for Tramp files."
2916 (with-parsed-tramp-file-name filename nil
2917 (tramp-flush-file-property v localname)
2918 (unless (zerop (tramp-send-command-and-check
2919 v
2920 (format "chmod %s %s"
2921 (tramp-decimal-to-octal mode)
2922 (tramp-shell-quote-argument localname))))
2923 ;; FIXME: extract the proper text from chmod's stderr.
2924 (tramp-error
2925 v 'file-error "Error while changing file's mode %s" filename))))
2926
2927 (defun tramp-handle-set-file-times (filename &optional time)
2928 "Like `set-file-times' for Tramp files."
2929 (zerop
2930 (if (file-remote-p filename)
2931 (with-parsed-tramp-file-name filename nil
2932 (tramp-flush-file-property v localname)
2933 (let ((time (if (or (null time) (equal time '(0 0)))
2934 (current-time)
2935 time))
2936 (utc
2937 ;; With GNU Emacs, `format-time-string' has an
2938 ;; optional parameter UNIVERSAL. This is preferred,
2939 ;; because we could handle the case when the remote
2940 ;; host is located in a different time zone as the
2941 ;; local host.
2942 (and (functionp 'subr-arity)
2943 (subrp (symbol-function 'format-time-string))
2944 (= 3 (cdr (funcall (symbol-function 'subr-arity)
2945 (symbol-function
2946 'format-time-string)))))))
2947 (tramp-send-command-and-check
2948 v (format "%s touch -t %s %s"
2949 (if utc "TZ=UTC; export TZ;" "")
2950 (if utc
2951 (format-time-string "%Y%m%d%H%M.%S" time t)
2952 (format-time-string "%Y%m%d%H%M.%S" time))
2953 (tramp-shell-quote-argument localname)))))
2954
2955 ;; We handle also the local part, because in older Emacsen,
2956 ;; without `set-file-times', this function is an alias for this.
2957 ;; We are local, so we don't need the UTC settings.
2958 (tramp-local-call-process
2959 "touch" nil nil nil "-t"
2960 (format-time-string "%Y%m%d%H%M.%S" time)
2961 (tramp-shell-quote-argument filename)))))
2962
2963 (defun tramp-set-file-uid-gid (filename &optional uid gid)
2964 "Set the ownership for FILENAME.
2965 If UID and GID are provided, these values are used; otherwise uid
2966 and gid of the corresponding user is taken. Both parameters must be integers."
2967 ;; Modern Unices allow chown only for root. So we might need
2968 ;; another implementation, see `dired-do-chown'. OTOH, it is mostly
2969 ;; working with su(do)? when it is needed, so it shall succeed in
2970 ;; the majority of cases.
2971 ;; Don't modify `last-coding-system-used' by accident.
2972 (let ((last-coding-system-used last-coding-system-used))
2973 (if (file-remote-p filename)
2974 (with-parsed-tramp-file-name filename nil
2975 (if (and (zerop (user-uid)) (tramp-local-host-p v))
2976 ;; If we are root on the local host, we can do it directly.
2977 (tramp-set-file-uid-gid localname uid gid)
2978 (let ((uid (or (and (integerp uid) uid)
2979 (tramp-get-remote-uid v 'integer)))
2980 (gid (or (and (integerp gid) gid)
2981 (tramp-get-remote-gid v 'integer))))
2982 (tramp-send-command
2983 v (format
2984 "chown %d:%d %s" uid gid
2985 (tramp-shell-quote-argument localname))))))
2986
2987 ;; We handle also the local part, because there doesn't exist
2988 ;; `set-file-uid-gid'. On W32 "chown" might not work.
2989 (let ((uid (or (and (integerp uid) uid) (tramp-get-local-uid 'integer)))
2990 (gid (or (and (integerp gid) gid) (tramp-get-local-gid 'integer))))
2991 (tramp-local-call-process
2992 "chown" nil nil nil
2993 (format "%d:%d" uid gid) (tramp-shell-quote-argument filename))))))
2994
2995 ;; Simple functions using the `test' command.
2996
2997 (defun tramp-handle-file-executable-p (filename)
2998 "Like `file-executable-p' for Tramp files."
2999 (with-parsed-tramp-file-name filename nil
3000 (with-file-property v localname "file-executable-p"
3001 ;; Examine `file-attributes' cache to see if request can be
3002 ;; satisfied without remote operation.
3003 (or (tramp-check-cached-permissions v ?x)
3004 (zerop (tramp-run-test "-x" filename))))))
3005
3006 (defun tramp-handle-file-readable-p (filename)
3007 "Like `file-readable-p' for Tramp files."
3008 (with-parsed-tramp-file-name filename nil
3009 (with-file-property v localname "file-readable-p"
3010 ;; Examine `file-attributes' cache to see if request can be
3011 ;; satisfied without remote operation.
3012 (or (tramp-check-cached-permissions v ?r)
3013 (zerop (tramp-run-test "-r" filename))))))
3014
3015 ;; When the remote shell is started, it looks for a shell which groks
3016 ;; tilde expansion. Here, we assume that all shells which grok tilde
3017 ;; expansion will also provide a `test' command which groks `-nt' (for
3018 ;; newer than). If this breaks, tell me about it and I'll try to do
3019 ;; something smarter about it.
3020 (defun tramp-handle-file-newer-than-file-p (file1 file2)
3021 "Like `file-newer-than-file-p' for Tramp files."
3022 (cond ((not (file-exists-p file1))
3023 nil)
3024 ((not (file-exists-p file2))
3025 t)
3026 ;; We are sure both files exist at this point.
3027 (t
3028 (save-excursion
3029 ;; We try to get the mtime of both files. If they are not
3030 ;; equal to the "dont-know" value, then we subtract the times
3031 ;; and obtain the result.
3032 (let ((fa1 (file-attributes file1))
3033 (fa2 (file-attributes file2)))
3034 (if (and (not (equal (nth 5 fa1) '(0 0)))
3035 (not (equal (nth 5 fa2) '(0 0))))
3036 (> 0 (tramp-time-diff (nth 5 fa2) (nth 5 fa1)))
3037 ;; If one of them is the dont-know value, then we can
3038 ;; still try to run a shell command on the remote host.
3039 ;; However, this only works if both files are Tramp
3040 ;; files and both have the same method, same user, same
3041 ;; host.
3042 (unless (tramp-equal-remote file1 file2)
3043 (with-parsed-tramp-file-name
3044 (if (tramp-tramp-file-p file1) file1 file2) nil
3045 (tramp-error
3046 v 'file-error
3047 "Files %s and %s must have same method, user, host"
3048 file1 file2)))
3049 (with-parsed-tramp-file-name file1 nil
3050 (zerop (tramp-run-test2
3051 (tramp-get-test-nt-command v) file1 file2)))))))))
3052
3053 ;; Functions implemented using the basic functions above.
3054
3055 (defun tramp-handle-file-modes (filename)
3056 "Like `file-modes' for Tramp files."
3057 (let ((truename (or (file-truename filename) filename)))
3058 (when (file-exists-p truename)
3059 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
3060
3061 (defun tramp-default-file-modes (filename)
3062 "Return file modes of FILENAME as integer.
3063 If the file modes of FILENAME cannot be determined, return the
3064 value of `default-file-modes', without execute permissions."
3065 (or (file-modes filename)
3066 (logand (default-file-modes) (tramp-octal-to-decimal "0666"))))
3067
3068 (defun tramp-handle-file-directory-p (filename)
3069 "Like `file-directory-p' for Tramp files."
3070 ;; Care must be taken that this function returns `t' for symlinks
3071 ;; pointing to directories. Surely the most obvious implementation
3072 ;; would be `test -d', but that returns false for such symlinks.
3073 ;; CCC: Stefan Monnier says that `test -d' follows symlinks. And
3074 ;; I now think he's right. So we could be using `test -d', couldn't
3075 ;; we?
3076 ;;
3077 ;; Alternatives: `cd %s', `test -d %s'
3078 (with-parsed-tramp-file-name filename nil
3079 (with-file-property v localname "file-directory-p"
3080 (zerop (tramp-run-test "-d" filename)))))
3081
3082 (defun tramp-handle-file-regular-p (filename)
3083 "Like `file-regular-p' for Tramp files."
3084 (and (file-exists-p filename)
3085 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
3086
3087 (defun tramp-handle-file-symlink-p (filename)
3088 "Like `file-symlink-p' for Tramp files."
3089 (with-parsed-tramp-file-name filename nil
3090 (let ((x (car (file-attributes filename))))
3091 (when (stringp x)
3092 ;; When Tramp is running on VMS, then `file-name-absolute-p'
3093 ;; might do weird things.
3094 (if (file-name-absolute-p x)
3095 (tramp-make-tramp-file-name method user host x)
3096 x)))))
3097
3098 (defun tramp-handle-file-writable-p (filename)
3099 "Like `file-writable-p' for Tramp files."
3100 (with-parsed-tramp-file-name filename nil
3101 (with-file-property v localname "file-writable-p"
3102 (if (file-exists-p filename)
3103 ;; Examine `file-attributes' cache to see if request can be
3104 ;; satisfied without remote operation.
3105 (or (tramp-check-cached-permissions v ?w)
3106 (zerop (tramp-run-test "-w" filename)))
3107 ;; If file doesn't exist, check if directory is writable.
3108 (and (zerop (tramp-run-test
3109 "-d" (file-name-directory filename)))
3110 (zerop (tramp-run-test
3111 "-w" (file-name-directory filename))))))))
3112
3113 (defun tramp-handle-file-ownership-preserved-p (filename)
3114 "Like `file-ownership-preserved-p' for Tramp files."
3115 (with-parsed-tramp-file-name filename nil
3116 (with-file-property v localname "file-ownership-preserved-p"
3117 (let ((attributes (file-attributes filename)))
3118 ;; Return t if the file doesn't exist, since it's true that no
3119 ;; information would be lost by an (attempted) delete and create.
3120 (or (null attributes)
3121 (= (nth 2 attributes) (tramp-get-remote-uid v 'integer)))))))
3122
3123 ;; Other file name ops.
3124
3125 (defun tramp-handle-directory-file-name (directory)
3126 "Like `directory-file-name' for Tramp files."
3127 ;; If localname component of filename is "/", leave it unchanged.
3128 ;; Otherwise, remove any trailing slash from localname component.
3129 ;; Method, host, etc, are unchanged. Does it make sense to try
3130 ;; to avoid parsing the filename?
3131 (with-parsed-tramp-file-name directory nil
3132 (if (and (not (zerop (length localname)))
3133 (eq (aref localname (1- (length localname))) ?/)
3134 (not (string= localname "/")))
3135 (substring directory 0 -1)
3136 directory)))
3137
3138 ;; Directory listings.
3139
3140 (defun tramp-handle-directory-files
3141 (directory &optional full match nosort files-only)
3142 "Like `directory-files' for Tramp files."
3143 ;; FILES-ONLY is valid for XEmacs only.
3144 (when (file-directory-p directory)
3145 (setq directory (expand-file-name directory))
3146 (let ((temp (nreverse (file-name-all-completions "" directory)))
3147 result item)
3148
3149 (while temp
3150 (setq item (directory-file-name (pop temp)))
3151 (when (and (or (null match) (string-match match item))
3152 (or (null files-only)
3153 ;; files only
3154 (and (equal files-only t) (file-regular-p item))
3155 ;; directories only
3156 (file-directory-p item)))
3157 (push (if full (expand-file-name item directory) item)
3158 result)))
3159 result)))
3160
3161 (defun tramp-handle-directory-files-and-attributes
3162 (directory &optional full match nosort id-format)
3163 "Like `directory-files-and-attributes' for Tramp files."
3164 (unless id-format (setq id-format 'integer))
3165 (when (file-directory-p directory)
3166 (setq directory (expand-file-name directory))
3167 (let* ((temp
3168 (tramp-compat-copy-tree
3169 (with-parsed-tramp-file-name directory nil
3170 (with-file-property
3171 v localname
3172 (format "directory-files-and-attributes-%s" id-format)
3173 (save-excursion
3174 (mapcar
3175 (lambda (x)
3176 (cons (car x)
3177 (tramp-convert-file-attributes v (cdr x))))
3178 (cond
3179 ((tramp-get-remote-stat v)
3180 (tramp-do-directory-files-and-attributes-with-stat
3181 v localname id-format))
3182 ((tramp-get-remote-perl v)
3183 (tramp-do-directory-files-and-attributes-with-perl
3184 v localname id-format)))))))))
3185 result item)
3186
3187 (while temp
3188 (setq item (pop temp))
3189 (when (or (null match) (string-match match (car item)))
3190 (when full
3191 (setcar item (expand-file-name (car item) directory)))
3192 (push item result)))
3193
3194 (if nosort
3195 result
3196 (sort result (lambda (x y) (string< (car x) (car y))))))))
3197
3198 (defun tramp-do-directory-files-and-attributes-with-perl
3199 (vec localname &optional id-format)
3200 "Implement `directory-files-and-attributes' for Tramp files using a Perl script."
3201 (tramp-message vec 5 "directory-files-and-attributes with perl: %s" localname)
3202 (tramp-maybe-send-script
3203 vec tramp-perl-directory-files-and-attributes
3204 "tramp_perl_directory_files_and_attributes")
3205 (let ((object
3206 (tramp-send-command-and-read
3207 vec
3208 (format "tramp_perl_directory_files_and_attributes %s %s"
3209 (tramp-shell-quote-argument localname) id-format))))
3210 (when (stringp object) (tramp-error vec 'file-error object))
3211 object))
3212
3213 (defun tramp-do-directory-files-and-attributes-with-stat
3214 (vec localname &optional id-format)
3215 "Implement `directory-files-and-attributes' for Tramp files using stat(1) command."
3216 (tramp-message vec 5 "directory-files-and-attributes with stat: %s" localname)
3217 (tramp-send-command-and-read
3218 vec
3219 (format
3220 (concat
3221 ;; We must care about filenames with spaces, or starting with
3222 ;; "-"; this would confuse xargs. "ls -aQ" might be a solution,
3223 ;; but it does not work on all remote systems. Therefore, we
3224 ;; quote the filenames via sed.
3225 "cd %s; echo \"(\"; (%s -a | sed -e s/\\$/\\\"/g -e s/^/\\\"/g | xargs "
3226 "%s -c '(\"%%n\" (\"%%N\") %%h %s %s %%X.0 %%Y.0 %%Z.0 %%s.0 \"%%A\" t %%i.0 -1)'); "
3227 "echo \")\"")
3228 (tramp-shell-quote-argument localname)
3229 (tramp-get-ls-command vec)
3230 (tramp-get-remote-stat vec)
3231 (if (eq id-format 'integer) "%u" "\"%U\"")
3232 (if (eq id-format 'integer) "%g" "\"%G\""))))
3233
3234 ;; This function should return "foo/" for directories and "bar" for
3235 ;; files.
3236 (defun tramp-handle-file-name-all-completions (filename directory)
3237 "Like `file-name-all-completions' for Tramp files."
3238 (unless (save-match-data (string-match "/" filename))
3239 (with-parsed-tramp-file-name (expand-file-name directory) nil
3240
3241 (all-completions
3242 filename
3243 (mapcar
3244 'list
3245 (or
3246 ;; Try cache first
3247 (and
3248 ;; Ignore if expired
3249 (or (not (integerp tramp-completion-reread-directory-timeout))
3250 (<= (tramp-time-diff
3251 (current-time)
3252 (tramp-get-file-property
3253 v localname "last-completion" '(0 0 0)))
3254 tramp-completion-reread-directory-timeout))
3255
3256 ;; Try cache entries for filename, filename with last
3257 ;; character removed, filename with last two characters
3258 ;; removed, ..., and finally the empty string - all
3259 ;; concatenated to the local directory name
3260
3261 ;; This is inefficient for very long filenames, pity
3262 ;; `reduce' is not available...
3263 (car
3264 (apply
3265 'append
3266 (mapcar
3267 (lambda (x)
3268 (let ((cache-hit
3269 (tramp-get-file-property
3270 v
3271 (concat localname (substring filename 0 x))
3272 "file-name-all-completions"
3273 nil)))
3274 (when cache-hit (list cache-hit))))
3275 (tramp-compat-number-sequence (length filename) 0 -1)))))
3276
3277 ;; Cache expired or no matching cache entry found so we need
3278 ;; to perform a remote operation
3279 (let (result)
3280 ;; Get a list of directories and files, including reliably
3281 ;; tagging the directories with a trailing '/'. Because I
3282 ;; rock. --daniel@danann.net
3283
3284 ;; Changed to perform `cd' in the same remote op and only
3285 ;; get entries starting with `filename'. Capture any `cd'
3286 ;; error messages. Ensure any `cd' and `echo' aliases are
3287 ;; ignored.
3288 (tramp-send-command
3289 v
3290 (if (tramp-get-remote-perl v)
3291 (progn
3292 (tramp-maybe-send-script
3293 v tramp-perl-file-name-all-completions
3294 "tramp_perl_file_name_all_completions")
3295 (format "tramp_perl_file_name_all_completions %s %s %d"
3296 (tramp-shell-quote-argument localname)
3297 (tramp-shell-quote-argument filename)
3298 (if (symbol-value
3299 'read-file-name-completion-ignore-case)
3300 1 0)))
3301
3302 (format (concat
3303 "(\\cd %s 2>&1 && (%s %s -a 2>/dev/null"
3304 ;; `ls' with wildcard might fail with `Argument
3305 ;; list too long' error in some corner cases; if
3306 ;; `ls' fails after `cd' succeeded, chances are
3307 ;; that's the case, so let's retry without
3308 ;; wildcard. This will return "too many" entries
3309 ;; but that isn't harmful.
3310 " || %s -a 2>/dev/null)"
3311 " | while read f; do"
3312 " if %s -d \"$f\" 2>/dev/null;"
3313 " then \\echo \"$f/\"; else \\echo \"$f\"; fi; done"
3314 " && \\echo ok) || \\echo fail")
3315 (tramp-shell-quote-argument localname)
3316 (tramp-get-ls-command v)
3317 ;; When `filename' is empty, just `ls' without
3318 ;; filename argument is more efficient than `ls *'
3319 ;; for very large directories and might avoid the
3320 ;; `Argument list too long' error.
3321 ;;
3322 ;; With and only with wildcard, we need to add
3323 ;; `-d' to prevent `ls' from descending into
3324 ;; sub-directories.
3325 (if (zerop (length filename))
3326 "."
3327 (concat (tramp-shell-quote-argument filename) "* -d"))
3328 (tramp-get-ls-command v)
3329 (tramp-get-test-command v))))
3330
3331 ;; Now grab the output.
3332 (with-current-buffer (tramp-get-buffer v)
3333 (goto-char (point-max))
3334
3335 ;; Check result code, found in last line of output
3336 (forward-line -1)
3337 (if (looking-at "^fail$")
3338 (progn
3339 ;; Grab error message from line before last line
3340 ;; (it was put there by `cd 2>&1')
3341 (forward-line -1)
3342 (tramp-error
3343 v 'file-error
3344 "tramp-handle-file-name-all-completions: %s"
3345 (buffer-substring
3346 (point) (tramp-compat-line-end-position))))
3347 ;; For peace of mind, if buffer doesn't end in `fail'
3348 ;; then it should end in `ok'. If neither are in the
3349 ;; buffer something went seriously wrong on the remote
3350 ;; side.
3351 (unless (looking-at "^ok$")
3352 (tramp-error
3353 v 'file-error
3354 "\
3355 tramp-handle-file-name-all-completions: internal error accessing `%s': `%s'"
3356 (tramp-shell-quote-argument localname) (buffer-string))))
3357
3358 (while (zerop (forward-line -1))
3359 (push (buffer-substring
3360 (point) (tramp-compat-line-end-position))
3361 result)))
3362
3363 ;; Because the remote op went through OK we know the
3364 ;; directory we `cd'-ed to exists
3365 (tramp-set-file-property
3366 v localname "file-exists-p" t)
3367
3368 ;; Because the remote op went through OK we know every
3369 ;; file listed by `ls' exists.
3370 (mapc (lambda (entry)
3371 (tramp-set-file-property
3372 v (concat localname entry) "file-exists-p" t))
3373 result)
3374
3375 (tramp-set-file-property
3376 v localname "last-completion" (current-time))
3377
3378 ;; Store result in the cache
3379 (tramp-set-file-property
3380 v (concat localname filename)
3381 "file-name-all-completions"
3382 result))))))))
3383
3384 ;; The following isn't needed for Emacs 20 but for 19.34?
3385 (defun tramp-handle-file-name-completion
3386 (filename directory &optional predicate)
3387 "Like `file-name-completion' for Tramp files."
3388 (unless (tramp-tramp-file-p directory)
3389 (error
3390 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
3391 directory))
3392 (try-completion
3393 filename
3394 (mapcar 'list (file-name-all-completions filename directory))
3395 (when predicate
3396 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
3397
3398 ;; cp, mv and ln
3399
3400 (defun tramp-handle-add-name-to-file
3401 (filename newname &optional ok-if-already-exists)
3402 "Like `add-name-to-file' for Tramp files."
3403 (unless (tramp-equal-remote filename newname)
3404 (with-parsed-tramp-file-name
3405 (if (tramp-tramp-file-p filename) filename newname) nil
3406 (tramp-error
3407 v 'file-error
3408 "add-name-to-file: %s"
3409 "only implemented for same method, same user, same host")))
3410 (with-parsed-tramp-file-name filename v1
3411 (with-parsed-tramp-file-name newname v2
3412 (let ((ln (when v1 (tramp-get-remote-ln v1))))
3413 (when (and (not ok-if-already-exists)
3414 (file-exists-p newname)
3415 (not (numberp ok-if-already-exists))
3416 (y-or-n-p
3417 (format
3418 "File %s already exists; make it a new name anyway? "
3419 newname)))
3420 (tramp-error
3421 v2 'file-error
3422 "add-name-to-file: file %s already exists" newname))
3423 (tramp-flush-file-property v2 v2-localname)
3424 (tramp-barf-unless-okay
3425 v1
3426 (format "%s %s %s" ln (tramp-shell-quote-argument v1-localname)
3427 (tramp-shell-quote-argument v2-localname))
3428 "error with add-name-to-file, see buffer `%s' for details"
3429 (buffer-name))))))
3430
3431 (defun tramp-handle-copy-file
3432 (filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3433 "Like `copy-file' for Tramp files."
3434 ;; Check if both files are local -- invoke normal copy-file.
3435 ;; Otherwise, use Tramp from local system.
3436 (setq filename (expand-file-name filename))
3437 (setq newname (expand-file-name newname))
3438 (cond
3439 ;; At least one file a Tramp file?
3440 ((or (tramp-tramp-file-p filename)
3441 (tramp-tramp-file-p newname))
3442 (tramp-do-copy-or-rename-file
3443 'copy filename newname ok-if-already-exists keep-date preserve-uid-gid))
3444 ;; Compat section.
3445 (preserve-uid-gid
3446 (tramp-run-real-handler
3447 'copy-file
3448 (list filename newname ok-if-already-exists keep-date preserve-uid-gid)))
3449 (t
3450 (tramp-run-real-handler
3451 'copy-file (list filename newname ok-if-already-exists keep-date)))))
3452
3453 (defun tramp-handle-copy-directory (dirname newname &optional keep-date parents)
3454 "Like `copy-directory' for Tramp files."
3455 (let ((t1 (tramp-tramp-file-p dirname))
3456 (t2 (tramp-tramp-file-p newname)))
3457 (with-parsed-tramp-file-name (if t1 dirname newname) nil
3458 (if (and (tramp-get-method-parameter method 'tramp-copy-recursive)
3459 ;; When DIRNAME and NEWNAME are remote, they must have
3460 ;; the same method.
3461 (or (null t1) (null t2)
3462 (string-equal
3463 (tramp-file-name-method (tramp-dissect-file-name dirname))
3464 (tramp-file-name-method (tramp-dissect-file-name newname)))))
3465 ;; scp or rsync DTRT.
3466 (progn
3467 (setq dirname (directory-file-name (expand-file-name dirname))
3468 newname (directory-file-name (expand-file-name newname)))
3469 (if (and (file-directory-p newname)
3470 (not (string-equal (file-name-nondirectory dirname)
3471 (file-name-nondirectory newname))))
3472 (setq newname
3473 (expand-file-name
3474 (file-name-nondirectory dirname) newname)))
3475 (if (not (file-directory-p (file-name-directory newname)))
3476 (make-directory (file-name-directory newname) parents))
3477 (tramp-do-copy-or-rename-file-out-of-band
3478 'copy dirname newname keep-date))
3479 ;; We must do it file-wise.
3480 (tramp-run-real-handler
3481 'copy-directory (list dirname newname keep-date parents))))))
3482
3483 (defun tramp-handle-rename-file
3484 (filename newname &optional ok-if-already-exists)
3485 "Like `rename-file' for Tramp files."
3486 ;; Check if both files are local -- invoke normal rename-file.
3487 ;; Otherwise, use Tramp from local system.
3488 (setq filename (expand-file-name filename))
3489 (setq newname (expand-file-name newname))
3490 ;; At least one file a Tramp file?
3491 (if (or (tramp-tramp-file-p filename)
3492 (tramp-tramp-file-p newname))
3493 (tramp-do-copy-or-rename-file
3494 'rename filename newname ok-if-already-exists t t)
3495 (tramp-run-real-handler
3496 'rename-file (list filename newname ok-if-already-exists))))
3497
3498 (defun tramp-do-copy-or-rename-file
3499 (op filename newname &optional ok-if-already-exists keep-date preserve-uid-gid)
3500 "Copy or rename a remote file.
3501 OP must be `copy' or `rename' and indicates the operation to perform.
3502 FILENAME specifies the file to copy or rename, NEWNAME is the name of
3503 the new file (for copy) or the new name of the file (for rename).
3504 OK-IF-ALREADY-EXISTS means don't barf if NEWNAME exists already.
3505 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3506 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3507 the uid and gid if both files are on the same host.
3508
3509 This function is invoked by `tramp-handle-copy-file' and
3510 `tramp-handle-rename-file'. It is an error if OP is neither of `copy'
3511 and `rename'. FILENAME and NEWNAME must be absolute file names."
3512 (unless (memq op '(copy rename))
3513 (error "Unknown operation `%s', must be `copy' or `rename'" op))
3514 (let ((t1 (tramp-tramp-file-p filename))
3515 (t2 (tramp-tramp-file-p newname)))
3516
3517 (when (and (not ok-if-already-exists) (file-exists-p newname))
3518 (with-parsed-tramp-file-name (if t1 filename newname) nil
3519 (tramp-error
3520 v 'file-already-exists "File %s already exists" newname)))
3521
3522 (with-parsed-tramp-file-name (if t1 filename newname) nil
3523 (tramp-message v 0 "Transferring %s to %s..." filename newname))
3524
3525 (prog1
3526 (cond
3527 ;; Both are Tramp files.
3528 ((and t1 t2)
3529 (with-parsed-tramp-file-name filename v1
3530 (with-parsed-tramp-file-name newname v2
3531 (cond
3532 ;; Shortcut: if method, host, user are the same for both
3533 ;; files, we invoke `cp' or `mv' on the remote host
3534 ;; directly.
3535 ((tramp-equal-remote filename newname)
3536 (tramp-do-copy-or-rename-file-directly
3537 op filename newname
3538 ok-if-already-exists keep-date preserve-uid-gid))
3539
3540 ;; Try out-of-band operation.
3541 ((tramp-method-out-of-band-p
3542 v1 (nth 7 (file-attributes filename)))
3543 (tramp-do-copy-or-rename-file-out-of-band
3544 op filename newname keep-date))
3545
3546 ;; No shortcut was possible. So we copy the
3547 ;; file first. If the operation was `rename', we go
3548 ;; back and delete the original file (if the copy was
3549 ;; successful). The approach is simple-minded: we
3550 ;; create a new buffer, insert the contents of the
3551 ;; source file into it, then write out the buffer to
3552 ;; the target file. The advantage is that it doesn't
3553 ;; matter which filename handlers are used for the
3554 ;; source and target file.
3555 (t
3556 (tramp-do-copy-or-rename-file-via-buffer
3557 op filename newname keep-date))))))
3558
3559 ;; One file is a Tramp file, the other one is local.
3560 ((or t1 t2)
3561 (with-parsed-tramp-file-name (if t1 filename newname) nil
3562 (cond
3563 ;; Fast track on local machine.
3564 ((tramp-local-host-p v)
3565 (tramp-do-copy-or-rename-file-directly
3566 op filename newname
3567 ok-if-already-exists keep-date preserve-uid-gid))
3568
3569 ;; If the Tramp file has an out-of-band method, the corresponding
3570 ;; copy-program can be invoked.
3571 ((tramp-method-out-of-band-p v (nth 7 (file-attributes filename)))
3572 (tramp-do-copy-or-rename-file-out-of-band
3573 op filename newname keep-date))
3574
3575 ;; Use the inline method via a Tramp buffer.
3576 (t (tramp-do-copy-or-rename-file-via-buffer
3577 op filename newname keep-date)))))
3578
3579 (t
3580 ;; One of them must be a Tramp file.
3581 (error "Tramp implementation says this cannot happen")))
3582
3583 ;; In case of `rename', we must flush the cache of the source file.
3584 (when (and t1 (eq op 'rename))
3585 (with-parsed-tramp-file-name filename nil
3586 (tramp-flush-file-property v localname)))
3587
3588 ;; When newname did exist, we have wrong cached values.
3589 (when t2
3590 (with-parsed-tramp-file-name newname nil
3591 (tramp-flush-file-property v localname)))
3592
3593 (with-parsed-tramp-file-name (if t1 filename newname) nil
3594 (tramp-message v 0 "Transferring %s to %s...done" filename newname)))))
3595
3596 (defun tramp-do-copy-or-rename-file-via-buffer (op filename newname keep-date)
3597 "Use an Emacs buffer to copy or rename a file.
3598 First arg OP is either `copy' or `rename' and indicates the operation.
3599 FILENAME is the source file, NEWNAME the target file.
3600 KEEP-DATE is non-nil if NEWNAME should have the same timestamp as FILENAME."
3601 (with-temp-buffer
3602 ;; We must disable multibyte, because binary data shall not be
3603 ;; converted.
3604 (set-buffer-multibyte nil)
3605 (let ((coding-system-for-read 'binary)
3606 (jka-compr-inhibit t))
3607 (insert-file-contents-literally filename))
3608 ;; We don't want the target file to be compressed, so we let-bind
3609 ;; `jka-compr-inhibit' to t.
3610 (let ((coding-system-for-write 'binary)
3611 (jka-compr-inhibit t))
3612 (write-region (point-min) (point-max) newname)))
3613 ;; KEEP-DATE handling.
3614 (when keep-date (set-file-times newname (nth 5 (file-attributes filename))))
3615 ;; Set the mode.
3616 (set-file-modes newname (tramp-default-file-modes filename))
3617 ;; If the operation was `rename', delete the original file.
3618 (unless (eq op 'copy) (delete-file filename)))
3619
3620 (defun tramp-do-copy-or-rename-file-directly
3621 (op filename newname ok-if-already-exists keep-date preserve-uid-gid)
3622 "Invokes `cp' or `mv' on the remote system.
3623 OP must be one of `copy' or `rename', indicating `cp' or `mv',
3624 respectively. FILENAME specifies the file to copy or rename,
3625 NEWNAME is the name of the new file (for copy) or the new name of
3626 the file (for rename). Both files must reside on the same host.
3627 KEEP-DATE means to make sure that NEWNAME has the same timestamp
3628 as FILENAME. PRESERVE-UID-GID, when non-nil, instructs to keep
3629 the uid and gid from FILENAME."
3630 (let ((t1 (tramp-tramp-file-p filename))
3631 (t2 (tramp-tramp-file-p newname))
3632 (file-times (nth 5 (file-attributes filename)))
3633 (file-modes (tramp-default-file-modes filename)))
3634 (with-parsed-tramp-file-name (if t1 filename newname) nil
3635 (let* ((cmd (cond ((and (eq op 'copy) preserve-uid-gid) "cp -f -p")
3636 ((eq op 'copy) "cp -f")
3637 ((eq op 'rename) "mv -f")
3638 (t (tramp-error
3639 v 'file-error
3640 "Unknown operation `%s', must be `copy' or `rename'"
3641 op))))
3642 (localname1
3643 (if t1 (tramp-handle-file-remote-p filename 'localname) filename))
3644 (localname2
3645 (if t2 (tramp-handle-file-remote-p newname 'localname) newname))
3646 (prefix (file-remote-p (if t1 filename newname)))
3647 cmd-result)
3648
3649 (cond
3650 ;; Both files are on a remote host, with same user.
3651 ((and t1 t2)
3652 (setq cmd-result
3653 (tramp-send-command-and-check
3654 v
3655 (format "%s %s %s" cmd
3656 (tramp-shell-quote-argument localname1)
3657 (tramp-shell-quote-argument localname2))))
3658 (with-current-buffer (tramp-get-buffer v)
3659 (goto-char (point-min))
3660 (unless
3661 (or
3662 (and keep-date
3663 ;; Mask cp -f error.
3664 (re-search-forward
3665 tramp-operation-not-permitted-regexp nil t))
3666 (zerop cmd-result))
3667 (tramp-error-with-buffer
3668 nil v 'file-error
3669 "Copying directly failed, see buffer `%s' for details."
3670 (buffer-name)))))
3671
3672 ;; We are on the local host.
3673 ((or t1 t2)
3674 (cond
3675 ;; We can do it directly.
3676 ((let (file-name-handler-alist)
3677 (and (file-readable-p localname1)
3678 (file-writable-p (file-name-directory localname2))
3679 (or (file-directory-p localname2)
3680 (file-writable-p localname2))))
3681 (if (eq op 'copy)
3682 (tramp-compat-copy-file
3683 localname1 localname2 ok-if-already-exists
3684 keep-date preserve-uid-gid)
3685 (tramp-run-real-handler
3686 'rename-file (list localname1 localname2 ok-if-already-exists))))
3687
3688 ;; We can do it directly with `tramp-send-command'
3689 ((and (file-readable-p (concat prefix localname1))
3690 (file-writable-p
3691 (file-name-directory (concat prefix localname2)))
3692 (or (file-directory-p (concat prefix localname2))
3693 (file-writable-p (concat prefix localname2))))
3694 (tramp-do-copy-or-rename-file-directly
3695 op (concat prefix localname1) (concat prefix localname2)
3696 ok-if-already-exists keep-date t)
3697 ;; We must change the ownership to the local user.
3698 (tramp-set-file-uid-gid
3699 (concat prefix localname2)
3700 (tramp-get-local-uid 'integer)
3701 (tramp-get-local-gid 'integer)))
3702
3703 ;; We need a temporary file in between.
3704 (t
3705 ;; Create the temporary file.
3706 (let ((tmpfile (tramp-compat-make-temp-file localname1)))
3707 (unwind-protect
3708 (progn
3709 (cond
3710 (t1
3711 (or
3712 (zerop
3713 (tramp-send-command-and-check
3714 v (format
3715 "%s %s %s" cmd
3716 (tramp-shell-quote-argument localname1)
3717 (tramp-shell-quote-argument tmpfile))))
3718 (tramp-error-with-buffer
3719 nil v 'file-error
3720 "Copying directly failed, see buffer `%s' for details."
3721 (tramp-get-buffer v)))
3722 ;; We must change the ownership as remote user.
3723 ;; Since this does not work reliable, we also
3724 ;; give read permissions.
3725 (set-file-modes
3726 (concat prefix tmpfile) (tramp-octal-to-decimal "0777"))
3727 (tramp-set-file-uid-gid
3728 (concat prefix tmpfile)
3729 (tramp-get-local-uid 'integer)
3730 (tramp-get-local-gid 'integer)))
3731 (t2
3732 (if (eq op 'copy)
3733 (tramp-compat-copy-file
3734 localname1 tmpfile t
3735 keep-date preserve-uid-gid)
3736 (tramp-run-real-handler
3737 'rename-file
3738 (list localname1 tmpfile t)))
3739 ;; We must change the ownership as local user.
3740 ;; Since this does not work reliable, we also
3741 ;; give read permissions.
3742 (set-file-modes tmpfile (tramp-octal-to-decimal "0777"))
3743 (tramp-set-file-uid-gid
3744 tmpfile
3745 (tramp-get-remote-uid v 'integer)
3746 (tramp-get-remote-gid v 'integer))))
3747
3748 ;; Move the temporary file to its destination.
3749 (cond
3750 (t2
3751 (or
3752 (zerop
3753 (tramp-send-command-and-check
3754 v (format
3755 "cp -f -p %s %s"
3756 (tramp-shell-quote-argument tmpfile)
3757 (tramp-shell-quote-argument localname2))))
3758 (tramp-error-with-buffer
3759 nil v 'file-error
3760 "Copying directly failed, see buffer `%s' for details."
3761 (tramp-get-buffer v))))
3762 (t1
3763 (tramp-run-real-handler
3764 'rename-file
3765 (list tmpfile localname2 ok-if-already-exists)))))
3766
3767 ;; Save exit.
3768 (condition-case nil
3769 (delete-file tmpfile)
3770 (error)))))))))
3771
3772 ;; Set the time and mode. Mask possible errors.
3773 (condition-case nil
3774 (when keep-date
3775 (set-file-times newname file-times)
3776 (set-file-modes newname file-modes))
3777 (error)))))
3778
3779 (defun tramp-do-copy-or-rename-file-out-of-band (op filename newname keep-date)
3780 "Invoke rcp program to copy.
3781 The method used must be an out-of-band method."
3782 (let ((t1 (tramp-tramp-file-p filename))
3783 (t2 (tramp-tramp-file-p newname))
3784 copy-program copy-args copy-env copy-keep-date port spec
3785 source target)
3786
3787 (with-parsed-tramp-file-name (if t1 filename newname) nil
3788 (if (and t1 t2)
3789
3790 ;; Both are Tramp files. We shall optimize it, when the
3791 ;; methods for filename and newname are the same.
3792 (let ((tmpfile (tramp-compat-make-temp-file localname)))
3793 (unwind-protect
3794 (progn
3795 (tramp-do-copy-or-rename-file-out-of-band
3796 op filename tmpfile keep-date)
3797 (tramp-do-copy-or-rename-file-out-of-band
3798 'rename tmpfile newname keep-date))
3799 ;; Save exit.
3800 (condition-case nil
3801 (delete-file tmpfile)
3802 (error))))
3803
3804 ;; Expand hops. Might be necessary for gateway methods.
3805 (setq v (car (tramp-compute-multi-hops v)))
3806 (aset v 3 localname)
3807
3808 ;; Check which ones of source and target are Tramp files.
3809 (setq source (if t1 (tramp-make-copy-program-file-name v) filename)
3810 target (funcall
3811 (if (and (file-directory-p filename)
3812 (string-equal
3813 (file-name-nondirectory filename)
3814 (file-name-nondirectory newname)))
3815 'file-name-directory
3816 'identity)
3817 (if t2 (tramp-make-copy-program-file-name v) newname)))
3818
3819 ;; Check for port number. Until now, there's no need for handling
3820 ;; like method, user, host.
3821 (setq host (tramp-file-name-real-host v)
3822 port (tramp-file-name-port v)
3823 port (or (and port (number-to-string port)) ""))
3824
3825 ;; Compose copy command.
3826 (setq spec `((?h . ,host) (?u . ,user) (?p . ,port)
3827 (?t . ,(tramp-get-connection-property
3828 (tramp-get-connection-process v) "temp-file" ""))
3829 (?k . ,(if keep-date " " "")))
3830 copy-program (tramp-get-method-parameter
3831 method 'tramp-copy-program)
3832 copy-keep-date (tramp-get-method-parameter
3833 method 'tramp-copy-keep-date)
3834 copy-args
3835 (delq
3836 nil
3837 (mapcar
3838 (lambda (x)
3839 (setq
3840 x
3841 ;; " " is indication for keep-date argument.
3842 (delete " " (mapcar (lambda (y) (format-spec y spec)) x)))
3843 (unless (member "" x) (mapconcat 'identity x " ")))
3844 (tramp-get-method-parameter method 'tramp-copy-args)))
3845 copy-env
3846 (delq
3847 nil
3848 (mapcar
3849 (lambda (x)
3850 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
3851 (unless (member "" x) (mapconcat 'identity x " ")))
3852 (tramp-get-method-parameter method 'tramp-copy-env))))
3853
3854 ;; Check for program.
3855 (when (and (fboundp 'executable-find)
3856 (not (let ((default-directory
3857 (tramp-compat-temporary-file-directory)))
3858 (executable-find copy-program))))
3859 (tramp-error
3860 v 'file-error "Cannot find copy program: %s" copy-program))
3861
3862 ;; Set variables for computing the prompt for reading
3863 ;; password.
3864 (setq tramp-current-method (tramp-file-name-method v)
3865 tramp-current-user (tramp-file-name-user v)
3866 tramp-current-host (tramp-file-name-host v))
3867
3868 (unwind-protect
3869 (with-temp-buffer
3870 ;; The default directory must be remote.
3871 (let ((default-directory
3872 (file-name-directory (if t1 filename newname)))
3873 (process-environment (copy-sequence process-environment)))
3874 ;; Set the transfer process properties.
3875 (tramp-set-connection-property
3876 v "process-name" (buffer-name (current-buffer)))
3877 (tramp-set-connection-property
3878 v "process-buffer" (current-buffer))
3879 (while copy-env
3880 (tramp-message v 5 "%s=\"%s\"" (car copy-env) (cadr copy-env))
3881 (setenv (pop copy-env) (pop copy-env)))
3882
3883 ;; Use an asynchronous process. By this, password can
3884 ;; be handled. The default directory must be local, in
3885 ;; order to apply the correct `copy-program'. We don't
3886 ;; set a timeout, because the copying of large files can
3887 ;; last longer than 60 secs.
3888 (let ((p (let ((default-directory
3889 (tramp-compat-temporary-file-directory)))
3890 (apply 'start-process
3891 (tramp-get-connection-property
3892 v "process-name" nil)
3893 (tramp-get-connection-property
3894 v "process-buffer" nil)
3895 copy-program
3896 (append copy-args (list source target))))))
3897 (tramp-message
3898 v 6 "%s" (mapconcat 'identity (process-command p) " "))
3899 (tramp-set-process-query-on-exit-flag p nil)
3900 (tramp-process-actions p v tramp-actions-copy-out-of-band))))
3901
3902 ;; Reset the transfer process properties.
3903 (tramp-set-connection-property v "process-name" nil)
3904 (tramp-set-connection-property v "process-buffer" nil))
3905
3906 ;; Handle KEEP-DATE argument.
3907 (when (and keep-date (not copy-keep-date))
3908 (set-file-times newname (nth 5 (file-attributes filename))))
3909
3910 ;; Set the mode.
3911 (unless (and keep-date copy-keep-date)
3912 (set-file-modes newname (tramp-default-file-modes filename))))
3913
3914 ;; If the operation was `rename', delete the original file.
3915 (unless (eq op 'copy)
3916 (delete-file filename)))))
3917
3918 (defun tramp-handle-make-directory (dir &optional parents)
3919 "Like `make-directory' for Tramp files."
3920 (setq dir (expand-file-name dir))
3921 (with-parsed-tramp-file-name dir nil
3922 (tramp-flush-directory-property v (file-name-directory localname))
3923 (save-excursion
3924 (tramp-barf-unless-okay
3925 v
3926 (format "%s %s"
3927 (if parents "mkdir -p" "mkdir")
3928 (tramp-shell-quote-argument localname))
3929 "Couldn't make directory %s" dir))))
3930
3931 (defun tramp-handle-delete-directory (directory &optional recursive)
3932 "Like `delete-directory' for Tramp files."
3933 (setq directory (expand-file-name directory))
3934 (with-parsed-tramp-file-name directory nil
3935 (tramp-flush-directory-property v localname)
3936 (unless (zerop (tramp-send-command-and-check
3937 v
3938 (format
3939 "%s %s"
3940 (if recursive "rm -rf" "rmdir")
3941 (tramp-shell-quote-argument localname))))
3942 (tramp-error v 'file-error "Couldn't delete %s" directory))))
3943
3944 (defun tramp-handle-delete-file (filename)
3945 "Like `delete-file' for Tramp files."
3946 (setq filename (expand-file-name filename))
3947 (with-parsed-tramp-file-name filename nil
3948 (tramp-flush-file-property v localname)
3949 (unless (zerop (tramp-send-command-and-check
3950 v
3951 (format "rm -f %s"
3952 (tramp-shell-quote-argument localname))))
3953 (tramp-error v 'file-error "Couldn't delete %s" filename))))
3954
3955 ;; Dired.
3956
3957 ;; CCC: This does not seem to be enough. Something dies when
3958 ;; we try and delete two directories under Tramp :/
3959 (defun tramp-handle-dired-recursive-delete-directory (filename)
3960 "Recursively delete the directory given.
3961 This is like `dired-recursive-delete-directory' for Tramp files."
3962 (with-parsed-tramp-file-name filename nil
3963 ;; Run a shell command 'rm -r <localname>'
3964 ;; Code shamelessly stolen from the dired implementation and, um, hacked :)
3965 (unless (file-exists-p filename)
3966 (tramp-error v 'file-error "No such directory: %s" filename))
3967 ;; Which is better, -r or -R? (-r works for me <daniel@danann.net>)
3968 (tramp-send-command
3969 v
3970 (format "rm -rf %s" (tramp-shell-quote-argument localname))
3971 ;; Don't read the output, do it explicitely.
3972 nil t)
3973 ;; Wait for the remote system to return to us...
3974 ;; This might take a while, allow it plenty of time.
3975 (tramp-wait-for-output (tramp-get-connection-process v) 120)
3976 ;; Make sure that it worked...
3977 (tramp-flush-directory-property v localname)
3978 (and (file-exists-p filename)
3979 (tramp-error
3980 v 'file-error "Failed to recursively delete %s" filename))))
3981
3982 (defun tramp-handle-dired-compress-file (file &rest ok-flag)
3983 "Like `dired-compress-file' for Tramp files."
3984 ;; OK-FLAG is valid for XEmacs only, but not implemented.
3985 ;; Code stolen mainly from dired-aux.el.
3986 (with-parsed-tramp-file-name file nil
3987 (tramp-flush-file-property v localname)
3988 (save-excursion
3989 (let ((suffixes
3990 (if (not (featurep 'xemacs))
3991 ;; Emacs case
3992 (symbol-value 'dired-compress-file-suffixes)
3993 ;; XEmacs has `dired-compression-method-alist', which is
3994 ;; transformed into `dired-compress-file-suffixes' structure.
3995 (mapcar
3996 (lambda (x)
3997 (list (concat (regexp-quote (nth 1 x)) "\\'")
3998 nil
3999 (mapconcat 'identity (nth 3 x) " ")))
4000 (symbol-value 'dired-compression-method-alist))))
4001 suffix)
4002 ;; See if any suffix rule matches this file name.
4003 (while suffixes
4004 (let (case-fold-search)
4005 (if (string-match (car (car suffixes)) localname)
4006 (setq suffix (car suffixes) suffixes nil))
4007 (setq suffixes (cdr suffixes))))
4008
4009 (cond ((file-symlink-p file)
4010 nil)
4011 ((and suffix (nth 2 suffix))
4012 ;; We found an uncompression rule.
4013 (tramp-message v 0 "Uncompressing %s..." file)
4014 (when (zerop (tramp-send-command-and-check
4015 v (concat (nth 2 suffix) " "
4016 (tramp-shell-quote-argument localname))))
4017 (tramp-message v 0 "Uncompressing %s...done" file)
4018 ;; `dired-remove-file' is not defined in XEmacs
4019 (funcall (symbol-function 'dired-remove-file) file)
4020 (string-match (car suffix) file)
4021 (concat (substring file 0 (match-beginning 0)))))
4022 (t
4023 ;; We don't recognize the file as compressed, so compress it.
4024 ;; Try gzip.
4025 (tramp-message v 0 "Compressing %s..." file)
4026 (when (zerop (tramp-send-command-and-check
4027 v (concat "gzip -f "
4028 (tramp-shell-quote-argument localname))))
4029 (tramp-message v 0 "Compressing %s...done" file)
4030 ;; `dired-remove-file' is not defined in XEmacs
4031 (funcall (symbol-function 'dired-remove-file) file)
4032 (cond ((file-exists-p (concat file ".gz"))
4033 (concat file ".gz"))
4034 ((file-exists-p (concat file ".z"))
4035 (concat file ".z"))
4036 (t nil)))))))))
4037
4038 (defun tramp-handle-dired-uncache (dir)
4039 "Like `dired-uncache' for Tramp files."
4040 (with-parsed-tramp-file-name dir nil
4041 (tramp-flush-file-property v localname)))
4042
4043 ;; Pacify byte-compiler. The function is needed on XEmacs only. I'm
4044 ;; not sure at all that this is the right way to do it, but let's hope
4045 ;; it works for now, and wait for a guru to point out the Right Way to
4046 ;; achieve this.
4047 ;;(eval-when-compile
4048 ;; (unless (fboundp 'dired-insert-set-properties)
4049 ;; (fset 'dired-insert-set-properties 'ignore)))
4050 ;; Gerd suggests this:
4051 (eval-when-compile (require 'dired))
4052 ;; Note that dired is required at run-time, too, when it is needed.
4053 ;; It is only needed on XEmacs for the function
4054 ;; `dired-insert-set-properties'.
4055
4056 (defun tramp-handle-insert-directory
4057 (filename switches &optional wildcard full-directory-p)
4058 "Like `insert-directory' for Tramp files."
4059 (setq filename (expand-file-name filename))
4060 (with-parsed-tramp-file-name filename nil
4061 (if (and (featurep 'ls-lisp)
4062 (not (symbol-value 'ls-lisp-use-insert-directory-program)))
4063 (tramp-run-real-handler
4064 'insert-directory (list filename switches wildcard full-directory-p))
4065 (when (stringp switches)
4066 (setq switches (split-string switches)))
4067 (when (and (member "--dired" switches)
4068 (not (tramp-get-ls-command-with-dired v)))
4069 (setq switches (delete "--dired" switches)))
4070 (when wildcard
4071 (setq wildcard (tramp-run-real-handler
4072 'file-name-nondirectory (list localname)))
4073 (setq localname (tramp-run-real-handler
4074 'file-name-directory (list localname))))
4075 (unless full-directory-p
4076 (setq switches (add-to-list 'switches "-d" 'append)))
4077 (setq switches (mapconcat 'tramp-shell-quote-argument switches " "))
4078 (when wildcard
4079 (setq switches (concat switches " " wildcard)))
4080 (tramp-message
4081 v 4 "Inserting directory `ls %s %s', wildcard %s, fulldir %s"
4082 switches filename (if wildcard "yes" "no")
4083 (if full-directory-p "yes" "no"))
4084 ;; If `full-directory-p', we just say `ls -l FILENAME'.
4085 ;; Else we chdir to the parent directory, then say `ls -ld BASENAME'.
4086 (if full-directory-p
4087 (tramp-send-command
4088 v
4089 (format "%s %s %s 2>/dev/null"
4090 (tramp-get-ls-command v)
4091 switches
4092 (if wildcard
4093 localname
4094 (tramp-shell-quote-argument (concat localname ".")))))
4095 (tramp-barf-unless-okay
4096 v
4097 (format "cd %s" (tramp-shell-quote-argument
4098 (tramp-run-real-handler
4099 'file-name-directory (list localname))))
4100 "Couldn't `cd %s'"
4101 (tramp-shell-quote-argument
4102 (tramp-run-real-handler 'file-name-directory (list localname))))
4103 (tramp-send-command
4104 v
4105 (format "%s %s %s"
4106 (tramp-get-ls-command v)
4107 switches
4108 (if (or wildcard
4109 (zerop (length
4110 (tramp-run-real-handler
4111 'file-name-nondirectory (list localname)))))
4112 ""
4113 (tramp-shell-quote-argument
4114 (tramp-run-real-handler
4115 'file-name-nondirectory (list localname)))))))
4116 (let ((beg (point)))
4117 ;; We cannot use `insert-buffer-substring' because the Tramp
4118 ;; buffer changes its contents before insertion due to calling
4119 ;; `expand-file' and alike.
4120 (insert
4121 (with-current-buffer (tramp-get-buffer v)
4122 (buffer-string)))
4123
4124 ;; Check for "--dired" output.
4125 (forward-line -2)
4126 (when (looking-at "//SUBDIRED//")
4127 (forward-line -1))
4128 (when (looking-at "//DIRED//")
4129 (let ((end (tramp-compat-line-end-position))
4130 (linebeg (point)))
4131 ;; Now read the numeric positions of file names.
4132 (goto-char linebeg)
4133 (forward-word 1)
4134 (forward-char 3)
4135 (while (< (point) end)
4136 (let ((start (+ beg (read (current-buffer))))
4137 (end (+ beg (read (current-buffer)))))
4138 (if (memq (char-after end) '(?\n ?\ ))
4139 ;; End is followed by \n or by " -> ".
4140 (put-text-property start end 'dired-filename t))))))
4141 ;; Remove trailing lines.
4142 (goto-char (tramp-compat-line-beginning-position))
4143 (while (looking-at "//")
4144 (forward-line 1)
4145 (delete-region (match-beginning 0) (point)))
4146
4147 ;; The inserted file could be from somewhere else.
4148 (when (and (not wildcard) (not full-directory-p))
4149 (goto-char (point-max))
4150 (when (file-symlink-p filename)
4151 (goto-char (search-backward "->" beg 'noerror)))
4152 (search-backward
4153 (if (zerop (length (file-name-nondirectory filename)))
4154 "."
4155 (file-name-nondirectory filename))
4156 beg 'noerror)
4157 (replace-match (file-relative-name filename) t))
4158
4159 (goto-char (point-max))))))
4160
4161 (defun tramp-handle-unhandled-file-name-directory (filename)
4162 "Like `unhandled-file-name-directory' for Tramp files."
4163 ;; With Emacs 23, we could simply return `nil'. But we must keep it
4164 ;; for backward compatibility.
4165 (expand-file-name "~/"))
4166
4167 ;; Canonicalization of file names.
4168
4169 (defun tramp-handle-expand-file-name (name &optional dir)
4170 "Like `expand-file-name' for Tramp files.
4171 If the localname part of the given filename starts with \"/../\" then
4172 the result will be a local, non-Tramp, filename."
4173 ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
4174 (setq dir (or dir default-directory "/"))
4175 ;; Unless NAME is absolute, concat DIR and NAME.
4176 (unless (file-name-absolute-p name)
4177 (setq name (concat (file-name-as-directory dir) name)))
4178 ;; If NAME is not a Tramp file, run the real handler.
4179 (if (not (tramp-tramp-file-p name))
4180 (tramp-run-real-handler 'expand-file-name (list name nil))
4181 ;; Dissect NAME.
4182 (with-parsed-tramp-file-name name nil
4183 (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
4184 (setq localname (concat "~/" localname)))
4185 ;; Tilde expansion if necessary. This needs a shell which
4186 ;; groks tilde expansion! The function `tramp-find-shell' is
4187 ;; supposed to find such a shell on the remote host. Please
4188 ;; tell me about it when this doesn't work on your system.
4189 (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
4190 (let ((uname (match-string 1 localname))
4191 (fname (match-string 2 localname)))
4192 ;; We cannot simply apply "~/", because under sudo "~/" is
4193 ;; expanded to the local user home directory but to the
4194 ;; root home directory. On the other hand, using always
4195 ;; the default user name for tilde expansion is not
4196 ;; appropriate either, because ssh and companions might
4197 ;; use a user name from the config file.
4198 (when (and (string-equal uname "~")
4199 (string-match "\\`su\\(do\\)?\\'" method))
4200 (setq uname (concat uname user)))
4201 (setq uname
4202 (with-connection-property v uname
4203 (tramp-send-command
4204 v (format "cd %s; pwd" (tramp-shell-quote-argument uname)))
4205 (with-current-buffer (tramp-get-buffer v)
4206 (goto-char (point-min))
4207 (buffer-substring
4208 (point) (tramp-compat-line-end-position)))))
4209 (setq localname (concat uname fname))))
4210 ;; There might be a double slash, for example when "~/"
4211 ;; expands to "/". Remove this.
4212 (while (string-match "//" localname)
4213 (setq localname (replace-match "/" t t localname)))
4214 ;; No tilde characters in file name, do normal
4215 ;; `expand-file-name' (this does "/./" and "/../"). We bind
4216 ;; `directory-sep-char' here for XEmacs on Windows, which would
4217 ;; otherwise use backslash. `default-directory' is bound,
4218 ;; because on Windows there would be problems with UNC shares or
4219 ;; Cygwin mounts.
4220 (let ((directory-sep-char ?/)
4221 (default-directory (tramp-compat-temporary-file-directory)))
4222 (tramp-make-tramp-file-name
4223 method user host
4224 (tramp-drop-volume-letter
4225 (tramp-run-real-handler
4226 'expand-file-name (list localname))))))))
4227
4228 (defun tramp-replace-environment-variables (filename)
4229 "Replace environment variables in FILENAME.
4230 Return the string with the replaced variables."
4231 (save-match-data
4232 (let ((idx (string-match "$\\(\\w+\\)" filename)))
4233 ;; `$' is coded as `$$'.
4234 (when (and idx
4235 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
4236 (getenv (match-string 1 filename)))
4237 (setq filename
4238 (replace-match
4239 (substitute-in-file-name (match-string 0 filename))
4240 t nil filename)))
4241 filename)))
4242
4243 (defun tramp-handle-substitute-in-file-name (filename)
4244 "Like `substitute-in-file-name' for Tramp files.
4245 \"//\" and \"/~\" substitute only in the local filename part.
4246 If the URL Tramp syntax is chosen, \"//\" as method delimeter and \"/~\" at
4247 beginning of local filename are not substituted."
4248 ;; First, we must replace environment variables.
4249 (setq filename (tramp-replace-environment-variables filename))
4250 (with-parsed-tramp-file-name filename nil
4251 (if (equal tramp-syntax 'url)
4252 ;; We need to check localname only. The other parts cannot contain
4253 ;; "//" or "/~".
4254 (if (and (> (length localname) 1)
4255 (or (string-match "//" localname)
4256 (string-match "/~" localname 1)))
4257 (tramp-run-real-handler 'substitute-in-file-name (list filename))
4258 (tramp-make-tramp-file-name
4259 (when method (substitute-in-file-name method))
4260 (when user (substitute-in-file-name user))
4261 (when host (substitute-in-file-name host))
4262 (when localname
4263 (tramp-run-real-handler
4264 'substitute-in-file-name (list localname)))))
4265 ;; Ignore in LOCALNAME everything before "//" or "/~".
4266 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
4267 (setq filename
4268 (concat (file-remote-p filename)
4269 (replace-match "\\1" nil nil localname)))
4270 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
4271 (when (string-match "~$" filename)
4272 (setq filename (concat filename "/"))))
4273 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
4274
4275 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
4276 ;; which calls corresponding functions (see minibuf.el).
4277 (when (fboundp 'minibuffer-electric-separator)
4278 (mapc
4279 (lambda (x)
4280 (eval
4281 `(defadvice ,x
4282 (around ,(intern (format "tramp-advice-%s" x)) activate)
4283 "Invoke `substitute-in-file-name' for Tramp files."
4284 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
4285 (tramp-tramp-file-p (buffer-substring)))
4286 ;; We don't need to handle `last-input-event', because
4287 ;; due to the key map we know it must be ?/ or ?~.
4288 (let ((s (concat (buffer-substring (point-min) (point))
4289 (string last-command-char))))
4290 (delete-region (point-min) (point))
4291 (insert (substitute-in-file-name s))
4292 (setq ad-return-value last-command-char))
4293 ad-do-it)))
4294 (eval
4295 `(add-hook
4296 'tramp-unload-hook
4297 (lambda ()
4298 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
4299 (ad-activate ',x)))))
4300
4301 '(minibuffer-electric-separator
4302 minibuffer-electric-tilde)))
4303
4304
4305 ;;; Remote commands:
4306
4307 (defun tramp-handle-executable-find (command)
4308 "Like `executable-find' for Tramp files."
4309 (with-parsed-tramp-file-name default-directory nil
4310 (tramp-find-executable v command (tramp-get-remote-path v) t)))
4311
4312 ;; We use BUFFER also as connection buffer during setup. Because of
4313 ;; this, its original contents must be saved, and restored once
4314 ;; connection has been setup.
4315 (defun tramp-handle-start-file-process (name buffer program &rest args)
4316 "Like `start-file-process' for Tramp files."
4317 (with-parsed-tramp-file-name default-directory nil
4318 (unless (stringp program)
4319 (tramp-error
4320 v 'file-error "pty association is not supported for `%s'" name))
4321 (unwind-protect
4322 (let ((command (format "cd %s; exec %s"
4323 (tramp-shell-quote-argument localname)
4324 (mapconcat 'tramp-shell-quote-argument
4325 (cons program args) " ")))
4326 (name1 name)
4327 (i 0))
4328 (unless buffer
4329 ;; BUFFER can be nil. We use a temporary buffer.
4330 (setq buffer (generate-new-buffer tramp-temp-buffer-name)))
4331 (while (get-process name1)
4332 ;; NAME must be unique as process name.
4333 (setq i (1+ i)
4334 name1 (format "%s<%d>" name i)))
4335 (setq name name1)
4336 ;; Set the new process properties.
4337 (tramp-set-connection-property v "process-name" name)
4338 (tramp-set-connection-property v "process-buffer" buffer)
4339 ;; Activate narrowing in order to save BUFFER contents.
4340 ;; Clear also the modification time; otherwise we might be
4341 ;; interrupted by `verify-visited-file-modtime'.
4342 (with-current-buffer (tramp-get-connection-buffer v)
4343 (clear-visited-file-modtime)
4344 (narrow-to-region (point-max) (point-max)))
4345 ;; Send the command. `tramp-send-command' opens a new
4346 ;; connection.
4347 (tramp-send-command v command nil t) ; nooutput
4348 ;; Set query flag for this process.
4349 (tramp-set-process-query-on-exit-flag
4350 (tramp-get-connection-process v) t)
4351 ;; Return process.
4352 (tramp-get-connection-process v))
4353 ;; Save exit.
4354 (with-current-buffer (tramp-get-connection-buffer v)
4355 (if (string-match tramp-temp-buffer-name (buffer-name))
4356 (progn
4357 (set-process-buffer (tramp-get-connection-process v) nil)
4358 (kill-buffer (current-buffer)))
4359 (widen)
4360 (goto-char (point-max))))
4361 (tramp-set-connection-property v "process-name" nil)
4362 (tramp-set-connection-property v "process-buffer" nil))))
4363
4364 (defun tramp-handle-process-file
4365 (program &optional infile destination display &rest args)
4366 "Like `process-file' for Tramp files."
4367 ;; The implementation is not complete yet.
4368 (when (and (numberp destination) (zerop destination))
4369 (error "Implementation does not handle immediate return"))
4370
4371 (with-parsed-tramp-file-name default-directory nil
4372 (let (command input tmpinput stderr tmpstderr outbuf ret)
4373 ;; Compute command.
4374 (setq command (mapconcat 'tramp-shell-quote-argument
4375 (cons program args) " "))
4376 ;; Determine input.
4377 (if (null infile)
4378 (setq input "/dev/null")
4379 (setq infile (expand-file-name infile))
4380 (if (tramp-equal-remote default-directory infile)
4381 ;; INFILE is on the same remote host.
4382 (setq input (with-parsed-tramp-file-name infile nil localname))
4383 ;; INFILE must be copied to remote host.
4384 (setq input (tramp-make-tramp-temp-file v)
4385 tmpinput (tramp-make-tramp-file-name method user host input))
4386 (copy-file infile tmpinput t)))
4387 (when input (setq command (format "%s <%s" command input)))
4388
4389 ;; Determine output.
4390 (cond
4391 ;; Just a buffer.
4392 ((bufferp destination)
4393 (setq outbuf destination))
4394 ;; A buffer name.
4395 ((stringp destination)
4396 (setq outbuf (get-buffer-create destination)))
4397 ;; (REAL-DESTINATION ERROR-DESTINATION)
4398 ((consp destination)
4399 ;; output.
4400 (cond
4401 ((bufferp (car destination))
4402 (setq outbuf (car destination)))
4403 ((stringp (car destination))
4404 (setq outbuf (get-buffer-create (car destination))))
4405 ((car destination)
4406 (setq outbuf (current-buffer))))
4407 ;; stderr.
4408 (cond
4409 ((stringp (cadr destination))
4410 (setcar (cdr destination) (expand-file-name (cadr destination)))
4411 (if (tramp-equal-remote default-directory (cadr destination))
4412 ;; stderr is on the same remote host.
4413 (setq stderr (with-parsed-tramp-file-name
4414 (cadr destination) nil localname))
4415 ;; stderr must be copied to remote host. The temporary
4416 ;; file must be deleted after execution.
4417 (setq stderr (tramp-make-tramp-temp-file v)
4418 tmpstderr (tramp-make-tramp-file-name
4419 method user host stderr))))
4420 ;; stderr to be discarded.
4421 ((null (cadr destination))
4422 (setq stderr "/dev/null"))))
4423 ;; 't
4424 (destination
4425 (setq outbuf (current-buffer))))
4426 (when stderr (setq command (format "%s 2>%s" command stderr)))
4427
4428 ;; Send the command. It might not return in time, so we protect it.
4429 (condition-case nil
4430 (unwind-protect
4431 (setq ret
4432 (tramp-send-command-and-check
4433 v (format "\\cd %s; %s"
4434 (tramp-shell-quote-argument localname)
4435 command)
4436 nil t))
4437 ;; We should show the output anyway.
4438 (when outbuf
4439 (with-current-buffer outbuf
4440 (insert
4441 (with-current-buffer (tramp-get-connection-buffer v)
4442 (buffer-string))))
4443 (when display (display-buffer outbuf))))
4444 ;; When the user did interrupt, we should do it also. We use
4445 ;; return code -1 as marker.
4446 (quit
4447 (kill-buffer (tramp-get-connection-buffer v))
4448 (setq ret -1))
4449 ;; Handle errors.
4450 (error
4451 (kill-buffer (tramp-get-connection-buffer v))
4452 (setq ret 1)))
4453
4454 ;; Provide error file.
4455 (when tmpstderr (rename-file tmpstderr (cadr destination) t))
4456
4457 ;; Cleanup. We remove all file cache values for the connection,
4458 ;; because the remote process could have changed them.
4459 (when tmpinput (delete-file tmpinput))
4460
4461 ;; `process-file-side-effects' has been introduced with GNU
4462 ;; Emacs 23.2. If set to `nil', no remote file will be changed
4463 ;; by `program'. If it doesn't exist, we assume its default
4464 ;; value 't'.
4465 (unless (and (boundp 'process-file-side-effects)
4466 (not (symbol-value 'process-file-side-effects)))
4467 (tramp-flush-directory-property v ""))
4468
4469 ;; Return exit status.
4470 (if (equal ret -1)
4471 (keyboard-quit)
4472 ret))))
4473
4474 (defun tramp-local-call-process
4475 (program &optional infile destination display &rest args)
4476 "Calls `call-process' on the local host.
4477 This is needed because for some Emacs flavors Tramp has
4478 defadviced `call-process' to behave like `process-file'. The
4479 Lisp error raised when PROGRAM is nil is trapped also, returning 1."
4480 (let ((default-directory
4481 (if (file-remote-p default-directory)
4482 (tramp-compat-temporary-file-directory)
4483 default-directory)))
4484 (if (executable-find program)
4485 (apply 'call-process program infile destination display args)
4486 1)))
4487
4488 (defun tramp-handle-call-process-region
4489 (start end program &optional delete buffer display &rest args)
4490 "Like `call-process-region' for Tramp files."
4491 (let ((tmpfile (tramp-compat-make-temp-file "")))
4492 (write-region start end tmpfile)
4493 (when delete (delete-region start end))
4494 (unwind-protect
4495 (apply 'call-process program tmpfile buffer display args)
4496 (delete-file tmpfile))))
4497
4498 (defun tramp-handle-shell-command
4499 (command &optional output-buffer error-buffer)
4500 "Like `shell-command' for Tramp files."
4501 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
4502 ;; We cannot use `shell-file-name' and `shell-command-switch',
4503 ;; they are variables of the local host.
4504 (args (list "/bin/sh" "-c" (substring command 0 asynchronous)))
4505 current-buffer-p
4506 (output-buffer
4507 (cond
4508 ((bufferp output-buffer) output-buffer)
4509 ((stringp output-buffer) (get-buffer-create output-buffer))
4510 (output-buffer
4511 (setq current-buffer-p t)
4512 (current-buffer))
4513 (t (get-buffer-create
4514 (if asynchronous
4515 "*Async Shell Command*"
4516 "*Shell Command Output*")))))
4517 (error-buffer
4518 (cond
4519 ((bufferp error-buffer) error-buffer)
4520 ((stringp error-buffer) (get-buffer-create error-buffer))))
4521 (buffer
4522 (if (and (not asynchronous) error-buffer)
4523 (with-parsed-tramp-file-name default-directory nil
4524 (list output-buffer (tramp-make-tramp-temp-file v)))
4525 output-buffer))
4526 (p (get-buffer-process output-buffer)))
4527
4528 ;; Check whether there is another process running. Tramp does not
4529 ;; support 2 (asynchronous) processes in parallel.
4530 (when p
4531 (if (yes-or-no-p "A command is running. Kill it? ")
4532 (condition-case nil
4533 (kill-process p)
4534 (error nil))
4535 (error "Shell command in progress")))
4536
4537 (if current-buffer-p
4538 (progn
4539 (barf-if-buffer-read-only)
4540 (push-mark nil t))
4541 (with-current-buffer output-buffer
4542 (setq buffer-read-only nil)
4543 (erase-buffer)))
4544
4545 (if (and (not current-buffer-p) (integerp asynchronous))
4546 (prog1
4547 ;; Run the process.
4548 (apply 'start-file-process "*Async Shell*" buffer args)
4549 ;; Display output.
4550 (pop-to-buffer output-buffer)
4551 (setq mode-line-process '(":%s"))
4552 (require 'shell) (shell-mode))
4553
4554 (prog1
4555 ;; Run the process.
4556 (apply 'process-file (car args) nil buffer nil (cdr args))
4557 ;; Insert error messages if they were separated.
4558 (when (listp buffer)
4559 (with-current-buffer error-buffer
4560 (insert-file-contents (cadr buffer)))
4561 (delete-file (cadr buffer)))
4562 (if current-buffer-p
4563 ;; This is like exchange-point-and-mark, but doesn't
4564 ;; activate the mark. It is cleaner to avoid activation,
4565 ;; even though the command loop would deactivate the mark
4566 ;; because we inserted text.
4567 (goto-char (prog1 (mark t)
4568 (set-marker (mark-marker) (point)
4569 (current-buffer))))
4570 ;; There's some output, display it.
4571 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
4572 (if (functionp 'display-message-or-buffer)
4573 (funcall (symbol-function 'display-message-or-buffer)
4574 output-buffer)
4575 (pop-to-buffer output-buffer))))))))
4576
4577 ;; File Editing.
4578
4579 (defvar tramp-handle-file-local-copy-hook nil
4580 "Normal hook to be run at the end of `tramp-handle-file-local-copy'.")
4581
4582 (defun tramp-handle-file-local-copy (filename)
4583 "Like `file-local-copy' for Tramp files."
4584
4585 (with-parsed-tramp-file-name filename nil
4586 (unless (file-exists-p filename)
4587 (tramp-error
4588 v 'file-error
4589 "Cannot make local copy of non-existing file `%s'" filename))
4590
4591 (let ((rem-enc (tramp-get-remote-coding v "remote-encoding"))
4592 (loc-dec (tramp-get-local-coding v "local-decoding"))
4593 (tmpfile (tramp-compat-make-temp-file filename)))
4594
4595 (condition-case err
4596 (cond
4597 ;; `copy-file' handles direct copy and out-of-band methods.
4598 ((or (tramp-local-host-p v)
4599 (tramp-method-out-of-band-p
4600 v (nth 7 (file-attributes filename))))
4601 (copy-file filename tmpfile t t))
4602
4603 ;; Use inline encoding for file transfer.
4604 (rem-enc
4605 (save-excursion
4606 (tramp-message v 5 "Encoding remote file %s..." filename)
4607 (tramp-barf-unless-okay
4608 v
4609 (format "%s < %s" rem-enc (tramp-shell-quote-argument localname))
4610 "Encoding remote file failed")
4611 (tramp-message v 5 "Encoding remote file %s...done" filename)
4612
4613 (if (and (symbolp loc-dec) (fboundp loc-dec))
4614 ;; If local decoding is a function, we call it. We
4615 ;; must disable multibyte, because
4616 ;; `uudecode-decode-region' doesn't handle it
4617 ;; correctly.
4618 (with-temp-buffer
4619 (set-buffer-multibyte nil)
4620 (insert-buffer-substring (tramp-get-buffer v))
4621 (tramp-message
4622 v 5 "Decoding remote file %s with function %s..."
4623 filename loc-dec)
4624 (funcall loc-dec (point-min) (point-max))
4625 ;; Unset `file-name-handler-alist'. Otherwise,
4626 ;; epa-file gets confused.
4627 (let (file-name-handler-alist
4628 (coding-system-for-write 'binary))
4629 (write-region (point-min) (point-max) tmpfile)))
4630
4631 ;; If tramp-decoding-function is not defined for this
4632 ;; method, we invoke tramp-decoding-command instead.
4633 (let ((tmpfile2 (tramp-compat-make-temp-file filename)))
4634 ;; Unset `file-name-handler-alist'. Otherwise,
4635 ;; epa-file gets confused.
4636 (let (file-name-handler-alist
4637 (coding-system-for-write 'binary))
4638 (write-region (point-min) (point-max) tmpfile2))
4639 (tramp-message
4640 v 5 "Decoding remote file %s with command %s..."
4641 filename loc-dec)
4642 (unwind-protect
4643 (tramp-call-local-coding-command loc-dec tmpfile2 tmpfile)
4644 (delete-file tmpfile2))))
4645
4646 (tramp-message v 5 "Decoding remote file %s...done" filename)
4647 ;; Set proper permissions.
4648 (set-file-modes tmpfile (tramp-default-file-modes filename))
4649 ;; Set local user ownership.
4650 (tramp-set-file-uid-gid tmpfile)))
4651
4652 ;; Oops, I don't know what to do.
4653 (t (tramp-error
4654 v 'file-error "Wrong method specification for `%s'" method)))
4655
4656 ;; Error handling.
4657 ((error quit)
4658 (delete-file tmpfile)
4659 (signal (car err) (cdr err))))
4660
4661 (run-hooks 'tramp-handle-file-local-copy-hook)
4662 tmpfile)))
4663
4664 (defun tramp-handle-file-remote-p (filename &optional identification connected)
4665 "Like `file-remote-p' for Tramp files."
4666 (when (tramp-tramp-file-p filename)
4667 (let* ((v (tramp-dissect-file-name filename))
4668 (p (tramp-get-connection-process v))
4669 (c (and p (processp p) (memq (process-status p) '(run open)))))
4670 ;; We expand the file name only, if there is already a connection.
4671 (with-parsed-tramp-file-name
4672 (if c (expand-file-name filename) filename) nil
4673 (and (or (not connected) c)
4674 (cond
4675 ((eq identification 'method) method)
4676 ((eq identification 'user) user)
4677 ((eq identification 'host) host)
4678 ((eq identification 'localname) localname)
4679 (t (tramp-make-tramp-file-name method user host ""))))))))
4680
4681 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
4682 "Like `find-operation-coding-system' for Tramp filenames.
4683 Tramp's `insert-file-contents' and `write-region' work over
4684 temporary file names. If `file-coding-system-alist' contains an
4685 expression, which matches more than the file name suffix, the
4686 coding system might not be determined. This function repairs it."
4687 (let (result)
4688 (dolist (elt file-coding-system-alist result)
4689 (when (and (consp elt) (string-match (car elt) filename))
4690 ;; We found a matching entry in `file-coding-system-alist'.
4691 ;; So we add a similar entry, but with the temporary file name
4692 ;; as regexp.
4693 (add-to-list
4694 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
4695
4696 (defun tramp-handle-insert-file-contents
4697 (filename &optional visit beg end replace)
4698 "Like `insert-file-contents' for Tramp files."
4699 (barf-if-buffer-read-only)
4700 (setq filename (expand-file-name filename))
4701 (let (coding-system-used result local-copy remote-copy)
4702 (with-parsed-tramp-file-name filename nil
4703 (unwind-protect
4704 (if (not (file-exists-p filename))
4705 ;; We don't raise a Tramp error, because it might be
4706 ;; suppressed, like in `find-file-noselect-1'.
4707 (signal 'file-error
4708 (list "File not found on remote host" filename))
4709
4710 (if (and (tramp-local-host-p v)
4711 (let (file-name-handler-alist)
4712 (file-readable-p localname)))
4713 ;; Short track: if we are on the local host, we can
4714 ;; run directly.
4715 (setq result
4716 (tramp-run-real-handler
4717 'insert-file-contents
4718 (list localname visit beg end replace)))
4719
4720 ;; When we shall insert only a part of the file, we copy
4721 ;; this part.
4722 (when (or beg end)
4723 (setq remote-copy (tramp-make-tramp-temp-file v))
4724 (tramp-send-command
4725 v
4726 (cond
4727 ((and beg end)
4728 (format "tail -c +%d %s | head -c +%d >%s"
4729 (1+ beg) (tramp-shell-quote-argument localname)
4730 (- end beg) remote-copy))
4731 (beg
4732 (format "tail -c +%d %s >%s"
4733 (1+ beg) (tramp-shell-quote-argument localname)
4734 remote-copy))
4735 (end
4736 (format "head -c +%d %s >%s"
4737 (1+ end) (tramp-shell-quote-argument localname)
4738 remote-copy)))))
4739
4740 ;; `insert-file-contents-literally' takes care to avoid
4741 ;; calling jka-compr. By let-binding
4742 ;; `inhibit-file-name-operation', we propagate that care
4743 ;; to the `file-local-copy' operation.
4744 (setq local-copy
4745 (let ((inhibit-file-name-operation
4746 (when (eq inhibit-file-name-operation
4747 'insert-file-contents)
4748 'file-local-copy)))
4749 (cond
4750 ((stringp remote-copy)
4751 (file-local-copy
4752 (tramp-make-tramp-file-name
4753 method user host remote-copy)))
4754 ((stringp tramp-temp-buffer-file-name)
4755 (copy-file filename tramp-temp-buffer-file-name 'ok)
4756 tramp-temp-buffer-file-name)
4757 (t (file-local-copy filename)))))
4758
4759 (when (and (null remote-copy)
4760 (tramp-get-method-parameter
4761 method 'tramp-copy-keep-tmpfile))
4762 ;; We keep the local file for performance reasons,
4763 ;; useful for "rsync".
4764 (set-file-modes local-copy (tramp-octal-to-decimal "0600"))
4765 (setq tramp-temp-buffer-file-name local-copy)
4766 (put 'tramp-temp-buffer-file-name 'permanent-local t))
4767
4768 (tramp-message
4769 v 4 "Inserting local temp file `%s'..." local-copy)
4770
4771 ;; We must ensure that `file-coding-system-alist'
4772 ;; matches `local-copy'.
4773 (let ((file-coding-system-alist
4774 (tramp-find-file-name-coding-system-alist
4775 filename local-copy)))
4776 (setq result
4777 (insert-file-contents
4778 local-copy nil nil nil replace))
4779 ;; Now `last-coding-system-used' has right value.
4780 ;; Remember it.
4781 (when (boundp 'last-coding-system-used)
4782 (setq coding-system-used
4783 (symbol-value 'last-coding-system-used))))
4784
4785 (tramp-message
4786 v 4 "Inserting local temp file `%s'...done" local-copy)
4787 (when (boundp 'last-coding-system-used)
4788 (set 'last-coding-system-used coding-system-used))))
4789
4790 ;; Save exit.
4791 (progn
4792 (when visit
4793 (setq buffer-file-name filename)
4794 (setq buffer-read-only (not (file-writable-p filename)))
4795 (set-visited-file-modtime)
4796 (set-buffer-modified-p nil))
4797 (when (and (stringp local-copy)
4798 (or remote-copy (null tramp-temp-buffer-file-name)))
4799 (delete-file local-copy))
4800 (when (stringp remote-copy)
4801 (delete-file
4802 (tramp-make-tramp-file-name method user host remote-copy))))))
4803
4804 ;; Result.
4805 (list (expand-file-name filename)
4806 (cadr result))))
4807
4808 ;; This is needed for XEmacs only. Code stolen from files.el.
4809 (defun tramp-handle-insert-file-contents-literally
4810 (filename &optional visit beg end replace)
4811 "Like `insert-file-contents-literally' for Tramp files."
4812 (let ((format-alist nil)
4813 (after-insert-file-functions nil)
4814 (coding-system-for-read 'no-conversion)
4815 (coding-system-for-write 'no-conversion)
4816 (find-buffer-file-type-function
4817 (if (fboundp 'find-buffer-file-type)
4818 (symbol-function 'find-buffer-file-type)
4819 nil))
4820 (inhibit-file-name-handlers '(jka-compr-handler image-file-handler))
4821 (inhibit-file-name-operation 'insert-file-contents))
4822 (unwind-protect
4823 (progn
4824 (fset 'find-buffer-file-type (lambda (filename) t))
4825 (insert-file-contents filename visit beg end replace))
4826 ;; Save exit.
4827 (if find-buffer-file-type-function
4828 (fset 'find-buffer-file-type find-buffer-file-type-function)
4829 (fmakunbound 'find-buffer-file-type)))))
4830
4831 (defun tramp-handle-find-backup-file-name (filename)
4832 "Like `find-backup-file-name' for Tramp files."
4833 (with-parsed-tramp-file-name filename nil
4834 ;; We set both variables. It doesn't matter whether it is
4835 ;; Emacs or XEmacs
4836 (let ((backup-directory-alist
4837 ;; Emacs case
4838 (when (boundp 'backup-directory-alist)
4839 (if (symbol-value 'tramp-backup-directory-alist)
4840 (mapcar
4841 (lambda (x)
4842 (cons
4843 (car x)
4844 (if (and (stringp (cdr x))
4845 (file-name-absolute-p (cdr x))
4846 (not (tramp-file-name-p (cdr x))))
4847 (tramp-make-tramp-file-name method user host (cdr x))
4848 (cdr x))))
4849 (symbol-value 'tramp-backup-directory-alist))
4850 (symbol-value 'backup-directory-alist))))
4851
4852 (bkup-backup-directory-info
4853 ;; XEmacs case
4854 (when (boundp 'bkup-backup-directory-info)
4855 (if (symbol-value 'tramp-bkup-backup-directory-info)
4856 (mapcar
4857 (lambda (x)
4858 (nconc
4859 (list (car x))
4860 (list
4861 (if (and (stringp (car (cdr x)))
4862 (file-name-absolute-p (car (cdr x)))
4863 (not (tramp-file-name-p (car (cdr x)))))
4864 (tramp-make-tramp-file-name
4865 method user host (car (cdr x)))
4866 (car (cdr x))))
4867 (cdr (cdr x))))
4868 (symbol-value 'tramp-bkup-backup-directory-info))
4869 (symbol-value 'bkup-backup-directory-info)))))
4870
4871 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
4872
4873 (defun tramp-handle-make-auto-save-file-name ()
4874 "Like `make-auto-save-file-name' for Tramp files.
4875 Returns a file name in `tramp-auto-save-directory' for autosaving this file."
4876 (let ((tramp-auto-save-directory tramp-auto-save-directory)
4877 (buffer-file-name
4878 (tramp-subst-strs-in-string
4879 '(("_" . "|")
4880 ("/" . "_a")
4881 (":" . "_b")
4882 ("|" . "__")
4883 ("[" . "_l")
4884 ("]" . "_r"))
4885 (buffer-file-name))))
4886 ;; File name must be unique. This is ensured with Emacs 22 (see
4887 ;; UNIQUIFY element of `auto-save-file-name-transforms'); but for
4888 ;; all other cases we must do it ourselves.
4889 (when (boundp 'auto-save-file-name-transforms)
4890 (mapc
4891 (lambda (x)
4892 (when (and (string-match (car x) buffer-file-name)
4893 (not (car (cddr x))))
4894 (setq tramp-auto-save-directory
4895 (or tramp-auto-save-directory
4896 (tramp-compat-temporary-file-directory)))))
4897 (symbol-value 'auto-save-file-name-transforms)))
4898 ;; Create directory.
4899 (when tramp-auto-save-directory
4900 (setq buffer-file-name
4901 (expand-file-name buffer-file-name tramp-auto-save-directory))
4902 (unless (file-exists-p tramp-auto-save-directory)
4903 (make-directory tramp-auto-save-directory t)))
4904 ;; Run plain `make-auto-save-file-name'. There might be an advice when
4905 ;; it is not a magic file name operation (since Emacs 22).
4906 ;; We must deactivate it temporarily.
4907 (if (not (ad-is-active 'make-auto-save-file-name))
4908 (tramp-run-real-handler 'make-auto-save-file-name nil)
4909 ;; else
4910 (ad-deactivate 'make-auto-save-file-name)
4911 (prog1
4912 (tramp-run-real-handler 'make-auto-save-file-name nil)
4913 (ad-activate 'make-auto-save-file-name)))))
4914
4915 (defvar tramp-handle-write-region-hook nil
4916 "Normal hook to be run at the end of `tramp-handle-write-region'.")
4917
4918 ;; CCC grok LOCKNAME
4919 (defun tramp-handle-write-region
4920 (start end filename &optional append visit lockname confirm)
4921 "Like `write-region' for Tramp files."
4922 (setq filename (expand-file-name filename))
4923 (with-parsed-tramp-file-name filename nil
4924 ;; Following part commented out because we don't know what to do about
4925 ;; file locking, and it does not appear to be a problem to ignore it.
4926 ;; Ange-ftp ignores it, too.
4927 ;; (when (and lockname (stringp lockname))
4928 ;; (setq lockname (expand-file-name lockname)))
4929 ;; (unless (or (eq lockname nil)
4930 ;; (string= lockname filename))
4931 ;; (error
4932 ;; "tramp-handle-write-region: LOCKNAME must be nil or equal FILENAME"))
4933
4934 ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
4935 (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
4936 (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
4937 (tramp-error v 'file-error "File not overwritten")))
4938
4939 (let ((uid (or (nth 2 (tramp-compat-file-attributes filename 'integer))
4940 (tramp-get-remote-uid v 'integer)))
4941 (gid (or (nth 3 (tramp-compat-file-attributes filename 'integer))
4942 (tramp-get-remote-gid v 'integer))))
4943
4944 (if (and (tramp-local-host-p v)
4945 ;; `file-writable-p' calls `file-expand-file-name'. We
4946 ;; cannot use `tramp-run-real-handler' therefore.
4947 (let (file-name-handler-alist)
4948 (and
4949 (file-writable-p (file-name-directory localname))
4950 (or (file-directory-p localname)
4951 (file-writable-p localname)))))
4952 ;; Short track: if we are on the local host, we can run directly.
4953 (progn
4954 (tramp-run-real-handler
4955 'write-region
4956 (list start end localname append 'no-message lockname confirm))
4957 (tramp-flush-file-property v localname))
4958
4959 (let ((rem-dec (tramp-get-remote-coding v "remote-decoding"))
4960 (loc-enc (tramp-get-local-coding v "local-encoding"))
4961 (modes (save-excursion (tramp-default-file-modes filename)))
4962 ;; We use this to save the value of
4963 ;; `last-coding-system-used' after writing the tmp file.
4964 ;; At the end of the function, we set
4965 ;; `last-coding-system-used' to this saved value. This
4966 ;; way, any intermediary coding systems used while
4967 ;; talking to the remote shell or suchlike won't hose
4968 ;; this variable. This approach was snarfed from
4969 ;; ange-ftp.el.
4970 coding-system-used
4971 ;; Write region into a tmp file. This isn't really
4972 ;; needed if we use an encoding function, but currently
4973 ;; we use it always because this makes the logic
4974 ;; simpler.
4975 (tmpfile (or tramp-temp-buffer-file-name
4976 (tramp-compat-make-temp-file filename))))
4977
4978 ;; If `append' is non-nil, we copy the file locally, and let
4979 ;; the native `write-region' implementation do the job.
4980 (when append (copy-file filename tmpfile 'ok))
4981
4982 ;; We say `no-message' here because we don't want the
4983 ;; visited file modtime data to be clobbered from the temp
4984 ;; file. We call `set-visited-file-modtime' ourselves later
4985 ;; on. We must ensure that `file-coding-system-alist'
4986 ;; matches `tmpfile'.
4987 (let ((file-coding-system-alist
4988 (tramp-find-file-name-coding-system-alist filename tmpfile)))
4989 (condition-case err
4990 (tramp-run-real-handler
4991 'write-region
4992 (list start end tmpfile append 'no-message lockname confirm))
4993 ((error quit)
4994 (setq tramp-temp-buffer-file-name nil)
4995 (delete-file tmpfile)
4996 (signal (car err) (cdr err))))
4997
4998 ;; Now, `last-coding-system-used' has the right value. Remember it.
4999 (when (boundp 'last-coding-system-used)
5000 (setq coding-system-used
5001 (symbol-value 'last-coding-system-used))))
5002
5003 ;; The permissions of the temporary file should be set. If
5004 ;; filename does not exist (eq modes nil) it has been
5005 ;; renamed to the backup file. This case `save-buffer'
5006 ;; handles permissions.
5007 (when modes (set-file-modes tmpfile modes))
5008
5009 ;; This is a bit lengthy due to the different methods
5010 ;; possible for file transfer. First, we check whether the
5011 ;; method uses an rcp program. If so, we call it.
5012 ;; Otherwise, both encoding and decoding command must be
5013 ;; specified. However, if the method _also_ specifies an
5014 ;; encoding function, then that is used for encoding the
5015 ;; contents of the tmp file.
5016 (cond
5017 ;; `rename-file' handles direct copy and out-of-band methods.
5018 ((or (tramp-local-host-p v)
5019 (tramp-method-out-of-band-p
5020 v (- (or end (point-max)) (or start (point-min)))))
5021 (if (and (= (or end (point-max)) (point-max))
5022 (= (or start (point-min)) (point-min))
5023 (tramp-get-method-parameter
5024 method 'tramp-copy-keep-tmpfile))
5025 (progn
5026 (setq tramp-temp-buffer-file-name tmpfile)
5027 (condition-case err
5028 ;; We keep the local file for performance
5029 ;; reasons, useful for "rsync".
5030 (copy-file tmpfile filename t)
5031 ((error quit)
5032 (setq tramp-temp-buffer-file-name nil)
5033 (delete-file tmpfile)
5034 (signal (car err) (cdr err)))))
5035 (setq tramp-temp-buffer-file-name nil)
5036 ;; Don't rename, in order to keep context in SELinux.
5037 (unwind-protect
5038 (copy-file tmpfile filename t)
5039 (delete-file tmpfile))))
5040
5041 ;; Use inline file transfer.
5042 (rem-dec
5043 ;; Encode tmpfile.
5044 (tramp-message v 5 "Encoding region...")
5045 (unwind-protect
5046 (with-temp-buffer
5047 ;; Use encoding function or command.
5048 (if (and (symbolp loc-enc) (fboundp loc-enc))
5049 (progn
5050 (tramp-message
5051 v 5 "Encoding region using function `%s'..."
5052 (symbol-name loc-enc))
5053 (let ((coding-system-for-read 'binary))
5054 (insert-file-contents-literally tmpfile))
5055 ;; The following `let' is a workaround for the
5056 ;; base64.el that comes with pgnus-0.84. If
5057 ;; both of the following conditions are
5058 ;; satisfied, it tries to write to a local
5059 ;; file in default-directory, but at this
5060 ;; point, default-directory is remote.
5061 ;; (`call-process-region' can't write to
5062 ;; remote files, it seems.) The file in
5063 ;; question is a tmp file anyway.
5064 (let ((default-directory
5065 (tramp-compat-temporary-file-directory)))
5066 (funcall loc-enc (point-min) (point-max))))
5067
5068 (tramp-message
5069 v 5 "Encoding region using command `%s'..." loc-enc)
5070 (unless (equal 0 (tramp-call-local-coding-command
5071 loc-enc tmpfile t))
5072 (tramp-error
5073 v 'file-error
5074 "Cannot write to `%s', local encoding command `%s' failed"
5075 filename loc-enc)))
5076
5077 ;; Send buffer into remote decoding command which
5078 ;; writes to remote file. Because this happens on
5079 ;; the remote host, we cannot use the function.
5080 (goto-char (point-max))
5081 (unless (bolp) (newline))
5082 (tramp-message
5083 v 5 "Decoding region into remote file %s..." filename)
5084 (tramp-send-command
5085 v
5086 (format
5087 "%s >%s <<'EOF'\n%sEOF"
5088 rem-dec
5089 (tramp-shell-quote-argument localname)
5090 (buffer-string)))
5091 (tramp-barf-unless-okay
5092 v nil
5093 "Couldn't write region to `%s', decode using `%s' failed"
5094 filename rem-dec)
5095 ;; When `file-precious-flag' is set, the region is
5096 ;; written to a temporary file. Check that the
5097 ;; checksum is equal to that from the local tmpfile.
5098 (when file-precious-flag
5099 (erase-buffer)
5100 (and
5101 ;; cksum runs locally, if possible.
5102 (zerop (tramp-local-call-process "cksum" tmpfile t))
5103 ;; cksum runs remotely.
5104 (zerop
5105 (tramp-send-command-and-check
5106 v
5107 (format
5108 "cksum <%s" (tramp-shell-quote-argument localname))))
5109 ;; ... they are different.
5110 (not
5111 (string-equal
5112 (buffer-string)
5113 (with-current-buffer (tramp-get-buffer v)
5114 (buffer-string))))
5115 (tramp-error
5116 v 'file-error
5117 (concat "Couldn't write region to `%s',"
5118 " decode using `%s' failed")
5119 filename rem-dec)))
5120 (tramp-message
5121 v 5 "Decoding region into remote file %s...done" filename)
5122 (tramp-flush-file-property v localname))
5123
5124 ;; Save exit.
5125 (delete-file tmpfile)))
5126
5127 ;; That's not expected.
5128 (t
5129 (tramp-error
5130 v 'file-error
5131 (concat "Method `%s' should specify both encoding and "
5132 "decoding command or an rcp program")
5133 method)))
5134
5135 ;; Make `last-coding-system-used' have the right value.
5136 (when coding-system-used
5137 (set 'last-coding-system-used coding-system-used))))
5138
5139 ;; We must protect `last-coding-system-used', now we have set it
5140 ;; to its correct value.
5141 (let (last-coding-system-used (need-chown t))
5142 ;; Set file modification time.
5143 (when (or (eq visit t) (stringp visit))
5144 (let ((file-attr (file-attributes filename)))
5145 (set-visited-file-modtime
5146 ;; We must pass modtime explicitely, because filename can
5147 ;; be different from (buffer-file-name), f.e. if
5148 ;; `file-precious-flag' is set.
5149 (nth 5 file-attr))
5150 (when (and (eq (nth 2 file-attr) uid)
5151 (eq (nth 3 file-attr) gid))
5152 (setq need-chown nil))))
5153
5154 ;; Set the ownership.
5155 (when need-chown
5156 (tramp-set-file-uid-gid filename uid gid))
5157 (when (or (eq visit t) (null visit) (stringp visit))
5158 (tramp-message v 0 "Wrote %s" filename))
5159 (run-hooks 'tramp-handle-write-region-hook)))))
5160
5161 (defvar tramp-vc-registered-file-names nil
5162 "List used to collect file names, which are checked during `vc-registered'.")
5163
5164 ;; VC backends check for the existence of various different special
5165 ;; files. This is very time consuming, because every single check
5166 ;; requires a remote command (the file cache must be invalidated).
5167 ;; Therefore, we apply a kind of optimization. We install the file
5168 ;; name handler `tramp-vc-file-name-handler', which does nothing but
5169 ;; remembers all file names for which `file-exists-p' or
5170 ;; `file-readable-p' has been applied. A first run of `vc-registered'
5171 ;; is performed. Afterwards, a script is applied for all collected
5172 ;; file names, using just one remote command. The result of this
5173 ;; script is used to fill the file cache with actual values. Now we
5174 ;; can reset the file name handlers, and we make a second run of
5175 ;; `vc-registered', which returns the expected result without sending
5176 ;; any other remote command.
5177 (defun tramp-handle-vc-registered (file)
5178 "Like `vc-registered' for Tramp files."
5179 (with-parsed-tramp-file-name file nil
5180
5181 ;; There could be new files, created by the vc backend. We cannot
5182 ;; reuse the old cache entries, therefore.
5183 (let (tramp-vc-registered-file-names
5184 (tramp-cache-inhibit-cache (current-time))
5185 (file-name-handler-alist
5186 `((,tramp-file-name-regexp . tramp-vc-file-name-handler))))
5187
5188 ;; Here we collect only file names, which need an operation.
5189 (tramp-run-real-handler 'vc-registered (list file))
5190 (tramp-message v 10 "\n%s" tramp-vc-registered-file-names)
5191
5192 ;; Send just one command, in order to fill the cache.
5193 (when tramp-vc-registered-file-names
5194 (tramp-maybe-send-script
5195 v
5196 (format tramp-vc-registered-read-file-names
5197 (tramp-get-file-exists-command v)
5198 (format "%s -r" (tramp-get-test-command v)))
5199 "tramp_vc_registered_read_file_names")
5200
5201 (dolist
5202 (elt
5203 (tramp-send-command-and-read
5204 v
5205 (format
5206 "tramp_vc_registered_read_file_names %s"
5207 (mapconcat 'tramp-shell-quote-argument
5208 tramp-vc-registered-file-names
5209 " "))))
5210
5211 (tramp-set-file-property v (car elt) (cadr elt) (cadr (cdr elt))))))
5212
5213 ;; Second run. Now all `file-exists-p' or `file-readable-p' calls
5214 ;; shall be answered from the file cache.
5215 ;; We unset `process-file-side-effects' in order to keep the cache
5216 ;; when `process-file' calls appear.
5217 (let (process-file-side-effects)
5218 (tramp-run-real-handler 'vc-registered (list file)))))
5219
5220 ;;;###autoload
5221 (progn (defun tramp-run-real-handler (operation args)
5222 "Invoke normal file name handler for OPERATION.
5223 First arg specifies the OPERATION, second arg is a list of arguments to
5224 pass to the OPERATION."
5225 (let* ((inhibit-file-name-handlers
5226 `(tramp-file-name-handler
5227 tramp-vc-file-name-handler
5228 tramp-completion-file-name-handler
5229 cygwin-mount-name-hook-function
5230 cygwin-mount-map-drive-hook-function
5231 .
5232 ,(and (eq inhibit-file-name-operation operation)
5233 inhibit-file-name-handlers)))
5234 (inhibit-file-name-operation operation))
5235 (apply operation args))))
5236
5237 ;;;###autoload
5238 (progn (defun tramp-completion-run-real-handler (operation args)
5239 "Invoke `tramp-file-name-handler' for OPERATION.
5240 First arg specifies the OPERATION, second arg is a list of arguments to
5241 pass to the OPERATION."
5242 (let* ((inhibit-file-name-handlers
5243 `(tramp-completion-file-name-handler
5244 cygwin-mount-name-hook-function
5245 cygwin-mount-map-drive-hook-function
5246 .
5247 ,(and (eq inhibit-file-name-operation operation)
5248 inhibit-file-name-handlers)))
5249 (inhibit-file-name-operation operation))
5250 (apply operation args))))
5251
5252 ;; We handle here all file primitives. Most of them have the file
5253 ;; name as first parameter; nevertheless we check for them explicitly
5254 ;; in order to be signaled if a new primitive appears. This
5255 ;; scenario is needed because there isn't a way to decide by
5256 ;; syntactical means whether a foreign method must be called. It would
5257 ;; ease the life if `file-name-handler-alist' would support a decision
5258 ;; function as well but regexp only.
5259 (defun tramp-file-name-for-operation (operation &rest args)
5260 "Return file name related to OPERATION file primitive.
5261 ARGS are the arguments OPERATION has been called with."
5262 (cond
5263 ; FILE resp DIRECTORY
5264 ((member operation
5265 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
5266 'delete-file 'diff-latest-backup-file 'directory-file-name
5267 'directory-files 'directory-files-and-attributes
5268 'dired-compress-file 'dired-uncache
5269 'file-accessible-directory-p 'file-attributes
5270 'file-directory-p 'file-executable-p 'file-exists-p
5271 'file-local-copy 'file-remote-p 'file-modes
5272 'file-name-as-directory 'file-name-directory
5273 'file-name-nondirectory 'file-name-sans-versions
5274 'file-ownership-preserved-p 'file-readable-p
5275 'file-regular-p 'file-symlink-p 'file-truename
5276 'file-writable-p 'find-backup-file-name 'find-file-noselect
5277 'get-file-buffer 'insert-directory 'insert-file-contents
5278 'load 'make-directory 'make-directory-internal
5279 'set-file-modes 'substitute-in-file-name
5280 'unhandled-file-name-directory 'vc-registered
5281 ; Emacs 22 only
5282 'set-file-times
5283 ; XEmacs only
5284 'abbreviate-file-name 'create-file-buffer
5285 'dired-file-modtime 'dired-make-compressed-filename
5286 'dired-recursive-delete-directory 'dired-set-file-modtime
5287 'dired-shell-unhandle-file-name 'dired-uucode-file
5288 'insert-file-contents-literally 'make-temp-name 'recover-file
5289 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
5290 (if (file-name-absolute-p (nth 0 args))
5291 (nth 0 args)
5292 (expand-file-name (nth 0 args))))
5293 ; FILE DIRECTORY resp FILE1 FILE2
5294 ((member operation
5295 (list 'add-name-to-file 'copy-file 'expand-file-name
5296 'file-name-all-completions 'file-name-completion
5297 'file-newer-than-file-p 'make-symbolic-link 'rename-file
5298 ; Emacs 23 only
5299 'copy-directory
5300 ; XEmacs only
5301 'dired-make-relative-symlink
5302 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
5303 (save-match-data
5304 (cond
5305 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
5306 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
5307 (t (buffer-file-name (current-buffer))))))
5308 ; START END FILE
5309 ((eq operation 'write-region)
5310 (nth 2 args))
5311 ; BUF
5312 ((member operation
5313 (list 'set-visited-file-modtime 'verify-visited-file-modtime
5314 ; since Emacs 22 only
5315 'make-auto-save-file-name
5316 ; XEmacs only
5317 'backup-buffer))
5318 (buffer-file-name
5319 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
5320 ; COMMAND
5321 ((member operation
5322 (list ; not in Emacs 23
5323 'dired-call-process
5324 ; Emacs only
5325 'shell-command
5326 ; since Emacs 22 only
5327 'process-file
5328 ; since Emacs 23 only
5329 'start-file-process
5330 ; XEmacs only
5331 'dired-print-file 'dired-shell-call-process
5332 ; nowhere yet
5333 'executable-find 'start-process 'call-process))
5334 default-directory)
5335 ; unknown file primitive
5336 (t (error "unknown file I/O primitive: %s" operation))))
5337
5338 (defun tramp-find-foreign-file-name-handler (filename)
5339 "Return foreign file name handler if exists."
5340 (when (and (stringp filename) (tramp-tramp-file-p filename))
5341 (let ((v (tramp-dissect-file-name filename t))
5342 (handler tramp-foreign-file-name-handler-alist)
5343 elt res)
5344 ;; When we are not fully sure that filename completion is safe,
5345 ;; we should not return a handler.
5346 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
5347 (and (tramp-file-name-host v)
5348 (not (member (tramp-file-name-host v)
5349 (mapcar 'car tramp-methods))))
5350 (not (tramp-completion-mode-p)))
5351 (while handler
5352 (setq elt (car handler)
5353 handler (cdr handler))
5354 (when (funcall (car elt) filename)
5355 (setq handler nil
5356 res (cdr elt))))
5357 res))))
5358
5359 ;; Main function.
5360 ;;;###autoload
5361 (defun tramp-file-name-handler (operation &rest args)
5362 "Invoke Tramp file name handler.
5363 Falls back to normal file name handler if no Tramp file name handler exists."
5364 (if tramp-mode
5365 (save-match-data
5366 (let* ((filename
5367 (tramp-replace-environment-variables
5368 (apply 'tramp-file-name-for-operation operation args)))
5369 (completion (tramp-completion-mode-p))
5370 (foreign (tramp-find-foreign-file-name-handler filename)))
5371 (with-parsed-tramp-file-name filename nil
5372 (cond
5373 ;; When we are in completion mode, some operations
5374 ;; shouldn't be handled by backend.
5375 ((and completion (zerop (length localname))
5376 (memq operation '(file-exists-p file-directory-p)))
5377 t)
5378 ((and completion (zerop (length localname))
5379 (memq operation '(file-name-as-directory)))
5380 filename)
5381 ;; Call the backend function.
5382 (foreign (apply foreign operation args))
5383 ;; Nothing to do for us.
5384 (t (tramp-run-real-handler operation args))))))
5385 ;; When `tramp-mode' is not enabled, we don't do anything.
5386 (tramp-run-real-handler operation args)))
5387
5388 ;; In Emacs, there is some concurrency due to timers. If a timer
5389 ;; interrupts Tramp and wishes to use the same connection buffer as
5390 ;; the "main" Emacs, then garbage might occur in the connection
5391 ;; buffer. Therefore, we need to make sure that a timer does not use
5392 ;; the same connection buffer as the "main" Emacs. We implement a
5393 ;; cheap global lock, instead of locking each connection buffer
5394 ;; separately. The global lock is based on two variables,
5395 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
5396 ;; (with setq) to indicate a lock. But Tramp also calls itself during
5397 ;; processing of a single file operation, so we need to allow
5398 ;; recursive calls. That's where the `tramp-locker' variable comes in
5399 ;; -- it is let-bound to t during the execution of the current
5400 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
5401 ;; then we should just proceed because we have been called
5402 ;; recursively. But if `tramp-locker' is nil, then we are a timer
5403 ;; interrupting the "main" Emacs, and then we signal an error.
5404
5405 (defvar tramp-locked nil
5406 "If non-nil, then Tramp is currently busy.
5407 Together with `tramp-locker', this implements a locking mechanism
5408 preventing reentrant calls of Tramp.")
5409
5410 (defvar tramp-locker nil
5411 "If non-nil, then a caller has locked Tramp.
5412 Together with `tramp-locked', this implements a locking mechanism
5413 preventing reentrant calls of Tramp.")
5414
5415 (defun tramp-sh-file-name-handler (operation &rest args)
5416 "Invoke remote-shell Tramp file name handler.
5417 Fall back to normal file name handler if no Tramp handler exists."
5418 (when (and tramp-locked (not tramp-locker))
5419 (setq tramp-locked nil)
5420 (signal 'file-error (list "Forbidden reentrant call of Tramp")))
5421 (let ((tl tramp-locked))
5422 (unwind-protect
5423 (progn
5424 (setq tramp-locked t)
5425 (let ((tramp-locker t))
5426 (save-match-data
5427 (let ((fn (assoc operation tramp-file-name-handler-alist)))
5428 (if fn
5429 (apply (cdr fn) args)
5430 (tramp-run-real-handler operation args))))))
5431 (setq tramp-locked tl))))
5432
5433 (defun tramp-vc-file-name-handler (operation &rest args)
5434 "Invoke special file name handler, which collects files to be handled."
5435 (save-match-data
5436 (let ((filename
5437 (tramp-replace-environment-variables
5438 (apply 'tramp-file-name-for-operation operation args)))
5439 (fn (assoc operation tramp-file-name-handler-alist)))
5440 (with-parsed-tramp-file-name filename nil
5441 (cond
5442 ;; That's what we want: file names, for which checks are
5443 ;; applied. We assume, that VC uses only `file-exists-p' and
5444 ;; `file-readable-p' checks; otherwise we must extend the
5445 ;; list. We do not perform any action, but return nil, in
5446 ;; order to keep `vc-registered' running.
5447 ((and fn (memq operation '(file-exists-p file-readable-p)))
5448 (add-to-list 'tramp-vc-registered-file-names localname 'append)
5449 nil)
5450 ;; Tramp file name handlers like `expand-file-name'. They
5451 ;; must still work.
5452 (fn
5453 (save-match-data (apply (cdr fn) args)))
5454 ;; Default file name handlers, we don't care.
5455 (t (tramp-run-real-handler operation args)))))))
5456
5457 ;;;###autoload
5458 (progn (defun tramp-completion-file-name-handler (operation &rest args)
5459 "Invoke Tramp file name completion handler.
5460 Falls back to normal file name handler if no Tramp file name handler exists."
5461 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
5462 ;; would otherwise use backslash.
5463 (let ((directory-sep-char ?/)
5464 (fn (assoc operation tramp-completion-file-name-handler-alist)))
5465 (if (and
5466 ;; When `tramp-mode' is not enabled, we don't do anything.
5467 fn tramp-mode
5468 ;; For other syntaxes than `sep', the regexp matches many common
5469 ;; situations where the user doesn't actually want to use Tramp.
5470 ;; So to avoid autoloading Tramp after typing just "/s", we
5471 ;; disable this part of the completion, unless the user implicitly
5472 ;; indicated his interest in using a fancier completion system.
5473 (or (eq tramp-syntax 'sep)
5474 (featurep 'tramp) ; If it's loaded, we may as well use it.
5475 (and (boundp 'partial-completion-mode) partial-completion-mode)
5476 ;; FIXME: These may have been loaded even if the user never
5477 ;; intended to use them.
5478 (featurep 'ido)
5479 (featurep 'icicles)))
5480 (save-match-data (apply (cdr fn) args))
5481 (tramp-completion-run-real-handler operation args)))))
5482
5483 ;;;###autoload
5484 (progn (defun tramp-register-file-name-handlers ()
5485 "Add Tramp file name handlers to `file-name-handler-alist'."
5486 ;; Remove autoloaded handlers from file name handler alist. Useful,
5487 ;; if `tramp-syntax' has been changed.
5488 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
5489 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5490 (let ((a1 (rassq
5491 'tramp-completion-file-name-handler file-name-handler-alist)))
5492 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
5493 ;; Add the handlers.
5494 (add-to-list 'file-name-handler-alist
5495 (cons tramp-file-name-regexp 'tramp-file-name-handler))
5496 (put 'tramp-file-name-handler 'safe-magic t)
5497 (add-to-list 'file-name-handler-alist
5498 (cons tramp-completion-file-name-regexp
5499 'tramp-completion-file-name-handler))
5500 (put 'tramp-completion-file-name-handler 'safe-magic t)
5501 ;; If jka-compr or epa-file are already loaded, move them to the
5502 ;; front of `file-name-handler-alist'.
5503 (dolist (fnh '(epa-file-handler jka-compr-handler))
5504 (let ((entry (rassoc fnh file-name-handler-alist)))
5505 (when entry
5506 (setq file-name-handler-alist
5507 (cons entry (delete entry file-name-handler-alist))))))))
5508
5509 ;; `tramp-file-name-handler' must be registered before evaluation of
5510 ;; site-start and init files, because there might exist remote files
5511 ;; already, f.e. files kept via recentf-mode.
5512 ;;;###autoload(tramp-register-file-name-handlers)
5513 (tramp-register-file-name-handlers)
5514
5515 ;;;###autoload
5516 (defun tramp-unload-file-name-handlers ()
5517 (setq file-name-handler-alist
5518 (delete (rassoc 'tramp-file-name-handler
5519 file-name-handler-alist)
5520 (delete (rassoc 'tramp-completion-file-name-handler
5521 file-name-handler-alist)
5522 file-name-handler-alist))))
5523
5524 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
5525
5526 ;;; File name handler functions for completion mode:
5527
5528 (defvar tramp-completion-mode nil
5529 "If non-nil, external packages signal that they are in file name completion.
5530
5531 This is necessary, because Tramp uses a heuristic depending on last
5532 input event. This fails when external packages use other characters
5533 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
5534 should never be set globally, the intention is to let-bind it.")
5535
5536 ;; Necessary because `tramp-file-name-regexp-unified' and
5537 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
5538 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
5539 ;; to `tramp-file-name-handler'). Otherwise, it takes
5540 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
5541 ;; risky, because completing a file might require loading other files,
5542 ;; like "~/.netrc", and for them it shouldn't be decided based on that
5543 ;; variable. On the other hand, those files shouldn't have partial
5544 ;; Tramp file name syntax. Maybe another variable should be introduced
5545 ;; overwriting this check in such cases. Or we change Tramp file name
5546 ;; syntax in order to avoid ambiguities, like in XEmacs ...
5547 (defun tramp-completion-mode-p ()
5548 "Checks whether method / user name / host name completion is active."
5549 (or
5550 ;; Signal from outside.
5551 tramp-completion-mode
5552 ;; Emacs.
5553 (equal last-input-event 'tab)
5554 (and (natnump last-input-event)
5555 (or
5556 ;; ?\t has event-modifier 'control.
5557 (equal last-input-event ?\t)
5558 (and (not (event-modifiers last-input-event))
5559 (or (equal last-input-event ?\?)
5560 (equal last-input-event ?\ )))))
5561 ;; XEmacs.
5562 (and (featurep 'xemacs)
5563 ;; `last-input-event' might be nil.
5564 (not (null last-input-event))
5565 ;; `last-input-event' may have no character approximation.
5566 (funcall (symbol-function 'event-to-character) last-input-event)
5567 (or
5568 ;; ?\t has event-modifier 'control.
5569 (equal
5570 (funcall (symbol-function 'event-to-character)
5571 last-input-event) ?\t)
5572 (and (not (event-modifiers last-input-event))
5573 (or (equal
5574 (funcall (symbol-function 'event-to-character)
5575 last-input-event) ?\?)
5576 (equal
5577 (funcall (symbol-function 'event-to-character)
5578 last-input-event) ?\ )))))))
5579
5580 ;; Method, host name and user name completion.
5581 ;; `tramp-completion-dissect-file-name' returns a list of
5582 ;; tramp-file-name structures. For all of them we return possible completions.
5583 ;;;###autoload
5584 (defun tramp-completion-handle-file-name-all-completions (filename directory)
5585 "Like `file-name-all-completions' for partial Tramp files."
5586
5587 (let* ((fullname (tramp-drop-volume-letter
5588 (expand-file-name filename directory)))
5589 ;; Possible completion structures.
5590 (v (tramp-completion-dissect-file-name fullname))
5591 result result1)
5592
5593 (while v
5594 (let* ((car (car v))
5595 (method (tramp-file-name-method car))
5596 (user (tramp-file-name-user car))
5597 (host (tramp-file-name-host car))
5598 (localname (tramp-file-name-localname car))
5599 (m (tramp-find-method method user host))
5600 (tramp-current-user user) ; see `tramp-parse-passwd'
5601 all-user-hosts)
5602
5603 (unless localname ;; Nothing to complete.
5604
5605 (if (or user host)
5606
5607 ;; Method dependent user / host combinations.
5608 (progn
5609 (mapc
5610 (lambda (x)
5611 (setq all-user-hosts
5612 (append all-user-hosts
5613 (funcall (nth 0 x) (nth 1 x)))))
5614 (tramp-get-completion-function m))
5615
5616 (setq result
5617 (append result
5618 (mapcar
5619 (lambda (x)
5620 (tramp-get-completion-user-host
5621 method user host (nth 0 x) (nth 1 x)))
5622 (delq nil all-user-hosts)))))
5623
5624 ;; Possible methods.
5625 (setq result
5626 (append result (tramp-get-completion-methods m)))))
5627
5628 (setq v (cdr v))))
5629
5630 ;; Unify list, remove nil elements.
5631 (while result
5632 (let ((car (car result)))
5633 (when car
5634 (add-to-list
5635 'result1
5636 (substring car (length (tramp-drop-volume-letter directory)))))
5637 (setq result (cdr result))))
5638
5639 ;; Complete local parts.
5640 (append
5641 result1
5642 (condition-case nil
5643 (tramp-completion-run-real-handler
5644 'file-name-all-completions (list filename directory))
5645 (error nil)))))
5646
5647 ;; Method, host name and user name completion for a file.
5648 ;;;###autoload
5649 (defun tramp-completion-handle-file-name-completion
5650 (filename directory &optional predicate)
5651 "Like `file-name-completion' for Tramp files."
5652 (try-completion
5653 filename
5654 (mapcar 'list (file-name-all-completions filename directory))
5655 (when predicate
5656 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
5657
5658 ;; I misuse a little bit the tramp-file-name structure in order to handle
5659 ;; completion possibilities for partial methods / user names / host names.
5660 ;; Return value is a list of tramp-file-name structures according to possible
5661 ;; completions. If "localname" is non-nil it means there
5662 ;; shouldn't be a completion anymore.
5663
5664 ;; Expected results:
5665
5666 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
5667 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
5668 ;; [nil "x" nil nil]
5669 ;; ["x" nil nil nil]
5670
5671 ;; "/x:" "/x:y" "/x:y:"
5672 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
5673 ;; "/[x/" "/[x/y"
5674 ;; ["x" nil "" nil] ["x" nil "y" nil]
5675 ;; ["x" "" nil nil] ["x" "y" nil nil]
5676
5677 ;; "/x:y@" "/x:y@z" "/x:y@z:"
5678 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
5679 ;; "/[x/y@" "/[x/y@z"
5680 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
5681 (defun tramp-completion-dissect-file-name (name)
5682 "Returns a list of `tramp-file-name' structures.
5683 They are collected by `tramp-completion-dissect-file-name1'."
5684
5685 (let* ((result)
5686 (x-nil "\\|\\(\\)")
5687 (tramp-completion-ipv6-regexp
5688 (format
5689 "[^%s]*"
5690 (if (zerop (length tramp-postfix-ipv6-format))
5691 tramp-postfix-host-format
5692 tramp-postfix-ipv6-format)))
5693 ;; "/method" "/[method"
5694 (tramp-completion-file-name-structure1
5695 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
5696 1 nil nil nil))
5697 ;; "/user" "/[user"
5698 (tramp-completion-file-name-structure2
5699 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
5700 nil 1 nil nil))
5701 ;; "/host" "/[host"
5702 (tramp-completion-file-name-structure3
5703 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
5704 nil nil 1 nil))
5705 ;; "/[ipv6" "/[ipv6"
5706 (tramp-completion-file-name-structure4
5707 (list (concat tramp-prefix-regexp
5708 tramp-prefix-ipv6-regexp
5709 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5710 nil nil 1 nil))
5711 ;; "/user@host" "/[user@host"
5712 (tramp-completion-file-name-structure5
5713 (list (concat tramp-prefix-regexp
5714 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5715 "\\(" tramp-host-regexp x-nil "\\)$")
5716 nil 1 2 nil))
5717 ;; "/user@[ipv6" "/[user@ipv6"
5718 (tramp-completion-file-name-structure6
5719 (list (concat tramp-prefix-regexp
5720 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5721 tramp-prefix-ipv6-regexp
5722 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5723 nil 1 2 nil))
5724 ;; "/method:user" "/[method/user" "/method://user"
5725 (tramp-completion-file-name-structure7
5726 (list (concat tramp-prefix-regexp
5727 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5728 "\\(" tramp-user-regexp x-nil "\\)$")
5729 1 2 nil nil))
5730 ;; "/method:host" "/[method/host" "/method://host"
5731 (tramp-completion-file-name-structure8
5732 (list (concat tramp-prefix-regexp
5733 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5734 "\\(" tramp-host-regexp x-nil "\\)$")
5735 1 nil 2 nil))
5736 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
5737 (tramp-completion-file-name-structure9
5738 (list (concat tramp-prefix-regexp
5739 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5740 tramp-prefix-ipv6-regexp
5741 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5742 1 nil 2 nil))
5743 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
5744 (tramp-completion-file-name-structure10
5745 (list (concat tramp-prefix-regexp
5746 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5747 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5748 "\\(" tramp-host-regexp x-nil "\\)$")
5749 1 2 3 nil))
5750 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
5751 (tramp-completion-file-name-structure11
5752 (list (concat tramp-prefix-regexp
5753 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
5754 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
5755 tramp-prefix-ipv6-regexp
5756 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
5757 1 2 3 nil))
5758 ;; "/method: "/method:/"
5759 (tramp-completion-file-name-structure12
5760 (list
5761 (if (equal tramp-syntax 'url)
5762 (concat tramp-prefix-regexp
5763 "\\(" tramp-method-regexp "\\)"
5764 "\\(" (substring tramp-postfix-method-regexp 0 1)
5765 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5766 "\\(" "\\)$")
5767 ;; Should not match if not URL syntax.
5768 (concat tramp-prefix-regexp "/$"))
5769 1 3 nil nil))
5770 ;; "/method: "/method:/"
5771 (tramp-completion-file-name-structure13
5772 (list
5773 (if (equal tramp-syntax 'url)
5774 (concat tramp-prefix-regexp
5775 "\\(" tramp-method-regexp "\\)"
5776 "\\(" (substring tramp-postfix-method-regexp 0 1)
5777 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
5778 "\\(" "\\)$")
5779 ;; Should not match if not URL syntax.
5780 (concat tramp-prefix-regexp "/$"))
5781 1 nil 3 nil)))
5782
5783 (mapc (lambda (regexp)
5784 (add-to-list 'result
5785 (tramp-completion-dissect-file-name1 regexp name)))
5786 (list
5787 tramp-completion-file-name-structure1
5788 tramp-completion-file-name-structure2
5789 tramp-completion-file-name-structure3
5790 tramp-completion-file-name-structure4
5791 tramp-completion-file-name-structure5
5792 tramp-completion-file-name-structure6
5793 tramp-completion-file-name-structure7
5794 tramp-completion-file-name-structure8
5795 tramp-completion-file-name-structure9
5796 tramp-completion-file-name-structure10
5797 tramp-completion-file-name-structure11
5798 tramp-completion-file-name-structure12
5799 tramp-completion-file-name-structure13
5800 tramp-file-name-structure))
5801
5802 (delq nil result)))
5803
5804 (defun tramp-completion-dissect-file-name1 (structure name)
5805 "Returns a `tramp-file-name' structure matching STRUCTURE.
5806 The structure consists of remote method, remote user,
5807 remote host and localname (filename on remote host)."
5808
5809 (save-match-data
5810 (when (string-match (nth 0 structure) name)
5811 (let ((method (and (nth 1 structure)
5812 (match-string (nth 1 structure) name)))
5813 (user (and (nth 2 structure)
5814 (match-string (nth 2 structure) name)))
5815 (host (and (nth 3 structure)
5816 (match-string (nth 3 structure) name)))
5817 (localname (and (nth 4 structure)
5818 (match-string (nth 4 structure) name))))
5819 (vector method user host localname)))))
5820
5821 ;; This function returns all possible method completions, adding the
5822 ;; trailing method delimeter.
5823 (defun tramp-get-completion-methods (partial-method)
5824 "Returns all method completions for PARTIAL-METHOD."
5825 (mapcar
5826 (lambda (method)
5827 (and method
5828 (string-match (concat "^" (regexp-quote partial-method)) method)
5829 (tramp-completion-make-tramp-file-name method nil nil nil)))
5830 (mapcar 'car tramp-methods)))
5831
5832 ;; Compares partial user and host names with possible completions.
5833 (defun tramp-get-completion-user-host (method partial-user partial-host user host)
5834 "Returns the most expanded string for user and host name completion.
5835 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
5836 (cond
5837
5838 ((and partial-user partial-host)
5839 (if (and host
5840 (string-match (concat "^" (regexp-quote partial-host)) host)
5841 (string-equal partial-user (or user partial-user)))
5842 (setq user partial-user)
5843 (setq user nil
5844 host nil)))
5845
5846 (partial-user
5847 (setq host nil)
5848 (unless
5849 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
5850 (setq user nil)))
5851
5852 (partial-host
5853 (setq user nil)
5854 (unless
5855 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
5856 (setq host nil)))
5857
5858 (t (setq user nil
5859 host nil)))
5860
5861 (unless (zerop (+ (length user) (length host)))
5862 (tramp-completion-make-tramp-file-name method user host nil)))
5863
5864 (defun tramp-parse-rhosts (filename)
5865 "Return a list of (user host) tuples allowed to access.
5866 Either user or host may be nil."
5867 ;; On Windows, there are problems in completion when
5868 ;; `default-directory' is remote.
5869 (let ((default-directory (tramp-compat-temporary-file-directory))
5870 res)
5871 (when (file-readable-p filename)
5872 (with-temp-buffer
5873 (insert-file-contents filename)
5874 (goto-char (point-min))
5875 (while (not (eobp))
5876 (push (tramp-parse-rhosts-group) res))))
5877 res))
5878
5879 (defun tramp-parse-rhosts-group ()
5880 "Return a (user host) tuple allowed to access.
5881 Either user or host may be nil."
5882 (let ((result)
5883 (regexp
5884 (concat
5885 "^\\(" tramp-host-regexp "\\)"
5886 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
5887 (narrow-to-region (point) (tramp-compat-line-end-position))
5888 (when (re-search-forward regexp nil t)
5889 (setq result (append (list (match-string 3) (match-string 1)))))
5890 (widen)
5891 (forward-line 1)
5892 result))
5893
5894 (defun tramp-parse-shosts (filename)
5895 "Return a list of (user host) tuples allowed to access.
5896 User is always nil."
5897 ;; On Windows, there are problems in completion when
5898 ;; `default-directory' is remote.
5899 (let ((default-directory (tramp-compat-temporary-file-directory))
5900 res)
5901 (when (file-readable-p filename)
5902 (with-temp-buffer
5903 (insert-file-contents filename)
5904 (goto-char (point-min))
5905 (while (not (eobp))
5906 (push (tramp-parse-shosts-group) res))))
5907 res))
5908
5909 (defun tramp-parse-shosts-group ()
5910 "Return a (user host) tuple allowed to access.
5911 User is always nil."
5912 (let ((result)
5913 (regexp (concat "^\\(" tramp-host-regexp "\\)")))
5914 (narrow-to-region (point) (tramp-compat-line-end-position))
5915 (when (re-search-forward regexp nil t)
5916 (setq result (list nil (match-string 1))))
5917 (widen)
5918 (or
5919 (> (skip-chars-forward ",") 0)
5920 (forward-line 1))
5921 result))
5922
5923 (defun tramp-parse-sconfig (filename)
5924 "Return a list of (user host) tuples allowed to access.
5925 User is always nil."
5926 ;; On Windows, there are problems in completion when
5927 ;; `default-directory' is remote.
5928 (let ((default-directory (tramp-compat-temporary-file-directory))
5929 res)
5930 (when (file-readable-p filename)
5931 (with-temp-buffer
5932 (insert-file-contents filename)
5933 (goto-char (point-min))
5934 (while (not (eobp))
5935 (push (tramp-parse-sconfig-group) res))))
5936 res))
5937
5938 (defun tramp-parse-sconfig-group ()
5939 "Return a (user host) tuple allowed to access.
5940 User is always nil."
5941 (let ((result)
5942 (regexp (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)")))
5943 (narrow-to-region (point) (tramp-compat-line-end-position))
5944 (when (re-search-forward regexp nil t)
5945 (setq result (list nil (match-string 1))))
5946 (widen)
5947 (or
5948 (> (skip-chars-forward ",") 0)
5949 (forward-line 1))
5950 result))
5951
5952 (defun tramp-parse-shostkeys (dirname)
5953 "Return a list of (user host) tuples allowed to access.
5954 User is always nil."
5955 ;; On Windows, there are problems in completion when
5956 ;; `default-directory' is remote.
5957 (let* ((default-directory (tramp-compat-temporary-file-directory))
5958 (regexp (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$"))
5959 (files (when (file-directory-p dirname) (directory-files dirname)))
5960 result)
5961 (while files
5962 (when (string-match regexp (car files))
5963 (push (list nil (match-string 1 (car files))) result))
5964 (setq files (cdr files)))
5965 result))
5966
5967 (defun tramp-parse-sknownhosts (dirname)
5968 "Return a list of (user host) tuples allowed to access.
5969 User is always nil."
5970 ;; On Windows, there are problems in completion when
5971 ;; `default-directory' is remote.
5972 (let* ((default-directory (tramp-compat-temporary-file-directory))
5973 (regexp (concat "^\\(" tramp-host-regexp
5974 "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$"))
5975 (files (when (file-directory-p dirname) (directory-files dirname)))
5976 result)
5977 (while files
5978 (when (string-match regexp (car files))
5979 (push (list nil (match-string 1 (car files))) result))
5980 (setq files (cdr files)))
5981 result))
5982
5983 (defun tramp-parse-hosts (filename)
5984 "Return a list of (user host) tuples allowed to access.
5985 User is always nil."
5986 ;; On Windows, there are problems in completion when
5987 ;; `default-directory' is remote.
5988 (let ((default-directory (tramp-compat-temporary-file-directory))
5989 res)
5990 (when (file-readable-p filename)
5991 (with-temp-buffer
5992 (insert-file-contents filename)
5993 (goto-char (point-min))
5994 (while (not (eobp))
5995 (push (tramp-parse-hosts-group) res))))
5996 res))
5997
5998 (defun tramp-parse-hosts-group ()
5999 "Return a (user host) tuple allowed to access.
6000 User is always nil."
6001 (let ((result)
6002 (regexp
6003 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)")))
6004 (narrow-to-region (point) (tramp-compat-line-end-position))
6005 (when (re-search-forward regexp nil t)
6006 (setq result (list nil (match-string 1))))
6007 (widen)
6008 (or
6009 (> (skip-chars-forward " \t") 0)
6010 (forward-line 1))
6011 result))
6012
6013 ;; For su-alike methods it would be desirable to return "root@localhost"
6014 ;; as default. Unfortunately, we have no information whether any user name
6015 ;; has been typed already. So we use `tramp-current-user' as indication,
6016 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
6017 (defun tramp-parse-passwd (filename)
6018 "Return a list of (user host) tuples allowed to access.
6019 Host is always \"localhost\"."
6020 ;; On Windows, there are problems in completion when
6021 ;; `default-directory' is remote.
6022 (let ((default-directory (tramp-compat-temporary-file-directory))
6023 res)
6024 (if (zerop (length tramp-current-user))
6025 '(("root" nil))
6026 (when (file-readable-p filename)
6027 (with-temp-buffer
6028 (insert-file-contents filename)
6029 (goto-char (point-min))
6030 (while (not (eobp))
6031 (push (tramp-parse-passwd-group) res))))
6032 res)))
6033
6034 (defun tramp-parse-passwd-group ()
6035 "Return a (user host) tuple allowed to access.
6036 Host is always \"localhost\"."
6037 (let ((result)
6038 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
6039 (narrow-to-region (point) (tramp-compat-line-end-position))
6040 (when (re-search-forward regexp nil t)
6041 (setq result (list (match-string 1) "localhost")))
6042 (widen)
6043 (forward-line 1)
6044 result))
6045
6046 (defun tramp-parse-netrc (filename)
6047 "Return a list of (user host) tuples allowed to access.
6048 User may be nil."
6049 ;; On Windows, there are problems in completion when
6050 ;; `default-directory' is remote.
6051 (let ((default-directory (tramp-compat-temporary-file-directory))
6052 res)
6053 (when (file-readable-p filename)
6054 (with-temp-buffer
6055 (insert-file-contents filename)
6056 (goto-char (point-min))
6057 (while (not (eobp))
6058 (push (tramp-parse-netrc-group) res))))
6059 res))
6060
6061 (defun tramp-parse-netrc-group ()
6062 "Return a (user host) tuple allowed to access.
6063 User may be nil."
6064 (let ((result)
6065 (regexp
6066 (concat
6067 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
6068 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
6069 (narrow-to-region (point) (tramp-compat-line-end-position))
6070 (when (re-search-forward regexp nil t)
6071 (setq result (list (match-string 3) (match-string 1))))
6072 (widen)
6073 (forward-line 1)
6074 result))
6075
6076 (defun tramp-parse-putty (registry)
6077 "Return a list of (user host) tuples allowed to access.
6078 User is always nil."
6079 ;; On Windows, there are problems in completion when
6080 ;; `default-directory' is remote.
6081 (let ((default-directory (tramp-compat-temporary-file-directory))
6082 res)
6083 (with-temp-buffer
6084 (when (zerop (tramp-local-call-process "reg" nil t nil "query" registry))
6085 (goto-char (point-min))
6086 (while (not (eobp))
6087 (push (tramp-parse-putty-group registry) res))))
6088 res))
6089
6090 (defun tramp-parse-putty-group (registry)
6091 "Return a (user host) tuple allowed to access.
6092 User is always nil."
6093 (let ((result)
6094 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
6095 (narrow-to-region (point) (tramp-compat-line-end-position))
6096 (when (re-search-forward regexp nil t)
6097 (setq result (list nil (match-string 1))))
6098 (widen)
6099 (forward-line 1)
6100 result))
6101
6102 ;;; Internal Functions:
6103
6104 (defun tramp-maybe-send-script (vec script name)
6105 "Define in remote shell function NAME implemented as SCRIPT.
6106 Only send the definition if it has not already been done."
6107 (let* ((p (tramp-get-connection-process vec))
6108 (scripts (tramp-get-connection-property p "scripts" nil)))
6109 (unless (member name scripts)
6110 (tramp-message vec 5 "Sending script `%s'..." name)
6111 ;; The script could contain a call of Perl. This is masked with `%s'.
6112 (tramp-send-command-and-check
6113 vec
6114 (format "%s () {\n%s\n}" name
6115 (format script (tramp-get-remote-perl vec))))
6116 (tramp-set-connection-property p "scripts" (cons name scripts))
6117 (tramp-message vec 5 "Sending script `%s'...done." name))))
6118
6119 (defun tramp-set-auto-save ()
6120 (when (and ;; ange-ftp has its own auto-save mechanism
6121 (eq (tramp-find-foreign-file-name-handler (buffer-file-name))
6122 'tramp-sh-file-name-handler)
6123 auto-save-default)
6124 (auto-save-mode 1)))
6125 (add-hook 'find-file-hooks 'tramp-set-auto-save t)
6126 (add-hook 'tramp-unload-hook
6127 (lambda ()
6128 (remove-hook 'find-file-hooks 'tramp-set-auto-save)))
6129
6130 (defun tramp-run-test (switch filename)
6131 "Run `test' on the remote system, given a SWITCH and a FILENAME.
6132 Returns the exit code of the `test' program."
6133 (with-parsed-tramp-file-name filename nil
6134 (tramp-send-command-and-check
6135 v
6136 (format
6137 "%s %s %s"
6138 (tramp-get-test-command v)
6139 switch
6140 (tramp-shell-quote-argument localname)))))
6141
6142 (defun tramp-run-test2 (format-string file1 file2)
6143 "Run `test'-like program on the remote system, given FILE1, FILE2.
6144 FORMAT-STRING contains the program name, switches, and place holders.
6145 Returns the exit code of the `test' program. Barfs if the methods,
6146 hosts, or files, disagree."
6147 (unless (tramp-equal-remote file1 file2)
6148 (with-parsed-tramp-file-name (if (tramp-tramp-file-p file1) file1 file2) nil
6149 (tramp-error
6150 v 'file-error
6151 "tramp-run-test2 only implemented for same method, user, host")))
6152 (with-parsed-tramp-file-name file1 v1
6153 (with-parsed-tramp-file-name file1 v2
6154 (tramp-send-command-and-check
6155 v1
6156 (format format-string
6157 (tramp-shell-quote-argument v1-localname)
6158 (tramp-shell-quote-argument v2-localname))))))
6159
6160 (defun tramp-buffer-name (vec)
6161 "A name for the connection buffer VEC."
6162 ;; We must use `tramp-file-name-real-host', because for gateway
6163 ;; methods the default port will be expanded later on, which would
6164 ;; tamper the name.
6165 (let ((method (tramp-file-name-method vec))
6166 (user (tramp-file-name-user vec))
6167 (host (tramp-file-name-real-host vec)))
6168 (if (not (zerop (length user)))
6169 (format "*tramp/%s %s@%s*" method user host)
6170 (format "*tramp/%s %s*" method host))))
6171
6172 (defun tramp-delete-temp-file-function ()
6173 "Remove temporary files related to current buffer."
6174 (when (stringp tramp-temp-buffer-file-name)
6175 (condition-case nil
6176 (delete-file tramp-temp-buffer-file-name)
6177 (error nil))))
6178
6179 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
6180 (add-hook 'tramp-cache-unload-hook
6181 (lambda ()
6182 (remove-hook 'kill-buffer-hook
6183 'tramp-delete-temp-file-function)))
6184
6185 (defun tramp-get-buffer (vec)
6186 "Get the connection buffer to be used for VEC."
6187 (or (get-buffer (tramp-buffer-name vec))
6188 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
6189 (setq buffer-undo-list t)
6190 (setq default-directory
6191 (tramp-make-tramp-file-name
6192 (tramp-file-name-method vec)
6193 (tramp-file-name-user vec)
6194 (tramp-file-name-host vec)
6195 "/"))
6196 (current-buffer))))
6197
6198 (defun tramp-get-connection-buffer (vec)
6199 "Get the connection buffer to be used for VEC.
6200 In case a second asynchronous communication has been started, it is different
6201 from `tramp-get-buffer'."
6202 (or (tramp-get-connection-property vec "process-buffer" nil)
6203 (tramp-get-buffer vec)))
6204
6205 (defun tramp-get-connection-process (vec)
6206 "Get the connection process to be used for VEC.
6207 In case a second asynchronous communication has been started, it is different
6208 from the default one."
6209 (get-process
6210 (or (tramp-get-connection-property vec "process-name" nil)
6211 (tramp-buffer-name vec))))
6212
6213 (defun tramp-debug-buffer-name (vec)
6214 "A name for the debug buffer for VEC."
6215 ;; We must use `tramp-file-name-real-host', because for gateway
6216 ;; methods the default port will be expanded later on, which would
6217 ;; tamper the name.
6218 (let ((method (tramp-file-name-method vec))
6219 (user (tramp-file-name-user vec))
6220 (host (tramp-file-name-real-host vec)))
6221 (if (not (zerop (length user)))
6222 (format "*debug tramp/%s %s@%s*" method user host)
6223 (format "*debug tramp/%s %s*" method host))))
6224
6225 (defun tramp-get-debug-buffer (vec)
6226 "Get the debug buffer for VEC."
6227 (with-current-buffer
6228 (get-buffer-create (tramp-debug-buffer-name vec))
6229 (when (bobp)
6230 (setq buffer-undo-list t)
6231 ;; Activate outline-mode. This runs `text-mode-hook' and
6232 ;; `outline-mode-hook'. We must prevent that local processes
6233 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell"
6234 ;; ...
6235 (let ((default-directory (tramp-compat-temporary-file-directory)))
6236 (outline-mode))
6237 (set (make-local-variable 'outline-regexp)
6238 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #")
6239 ; (set (make-local-variable 'outline-regexp)
6240 ; "[a-z.-]+:[0-9]+: [a-z0-9-]+ (\\([0-9]+\\)) #")
6241 (set (make-local-variable 'outline-level) 'tramp-outline-level))
6242 (current-buffer)))
6243
6244 (defun tramp-outline-level ()
6245 "Return the depth to which a statement is nested in the outline.
6246 Point must be at the beginning of a header line.
6247
6248 The outline level is equal to the verbosity of the Tramp message."
6249 (1+ (string-to-number (match-string 1))))
6250
6251 (defun tramp-find-executable
6252 (vec progname dirlist &optional ignore-tilde ignore-path)
6253 "Searches for PROGNAME in $PATH and all directories mentioned in DIRLIST.
6254 First arg VEC specifies the connection, PROGNAME is the program
6255 to search for, and DIRLIST gives the list of directories to
6256 search. If IGNORE-TILDE is non-nil, directory names starting
6257 with `~' will be ignored. If IGNORE-PATH is non-nil, searches
6258 only in DIRLIST.
6259
6260 Returns the absolute file name of PROGNAME, if found, and nil otherwise.
6261
6262 This function expects to be in the right *tramp* buffer."
6263 (with-current-buffer (tramp-get-buffer vec)
6264 (let (result)
6265 ;; Check whether the executable is in $PATH. "which(1)" does not
6266 ;; report always a correct error code; therefore we check the
6267 ;; number of words it returns.
6268 (unless ignore-path
6269 (tramp-send-command vec (format "which \\%s | wc -w" progname))
6270 (goto-char (point-min))
6271 (if (looking-at "^1$")
6272 (setq result (concat "\\" progname))))
6273 (unless result
6274 (when ignore-tilde
6275 ;; Remove all ~/foo directories from dirlist. In Emacs 20,
6276 ;; `remove' is in CL, and we want to avoid CL dependencies.
6277 (let (newdl d)
6278 (while dirlist
6279 (setq d (car dirlist))
6280 (setq dirlist (cdr dirlist))
6281 (unless (char-equal ?~ (aref d 0))
6282 (setq newdl (cons d newdl))))
6283 (setq dirlist (nreverse newdl))))
6284 (tramp-send-command
6285 vec
6286 (format (concat "while read d; "
6287 "do if test -x $d/%s -a -f $d/%s; "
6288 "then echo tramp_executable $d/%s; "
6289 "break; fi; done <<'EOF'\n"
6290 "%s\nEOF")
6291 progname progname progname (mapconcat 'identity dirlist "\n")))
6292 (goto-char (point-max))
6293 (when (search-backward "tramp_executable " nil t)
6294 (skip-chars-forward "^ ")
6295 (skip-chars-forward " ")
6296 (setq result (buffer-substring
6297 (point) (tramp-compat-line-end-position)))))
6298 result)))
6299
6300 (defun tramp-set-remote-path (vec)
6301 "Sets the remote environment PATH to existing directories.
6302 I.e., for each directory in `tramp-remote-path', it is tested
6303 whether it exists and if so, it is added to the environment
6304 variable PATH."
6305 (tramp-message vec 5 (format "Setting $PATH environment variable"))
6306 (tramp-send-command
6307 vec (format "PATH=%s; export PATH"
6308 (mapconcat 'identity (tramp-get-remote-path vec) ":"))))
6309
6310 ;; ------------------------------------------------------------
6311 ;; -- Communication with external shell --
6312 ;; ------------------------------------------------------------
6313
6314 (defun tramp-find-file-exists-command (vec)
6315 "Find a command on the remote host for checking if a file exists.
6316 Here, we are looking for a command which has zero exit status if the
6317 file exists and nonzero exit status otherwise."
6318 (let ((existing "/")
6319 (nonexisting
6320 (tramp-shell-quote-argument "/ this file does not exist "))
6321 result)
6322 ;; The algorithm is as follows: we try a list of several commands.
6323 ;; For each command, we first run `$cmd /' -- this should return
6324 ;; true, as the root directory always exists. And then we run
6325 ;; `$cmd /this\ file\ does\ not\ exist ', hoping that the file indeed
6326 ;; does not exist. This should return false. We use the first
6327 ;; command we find that seems to work.
6328 ;; The list of commands to try is as follows:
6329 ;; `ls -d' This works on most systems, but NetBSD 1.4
6330 ;; has a bug: `ls' always returns zero exit
6331 ;; status, even for files which don't exist.
6332 ;; `test -e' Some Bourne shells have a `test' builtin
6333 ;; which does not know the `-e' option.
6334 ;; `/bin/test -e' For those, the `test' binary on disk normally
6335 ;; provides the option. Alas, the binary
6336 ;; is sometimes `/bin/test' and sometimes it's
6337 ;; `/usr/bin/test'.
6338 ;; `/usr/bin/test -e' In case `/bin/test' does not exist.
6339 (unless (or
6340 (and (setq result (format "%s -e" (tramp-get-test-command vec)))
6341 (zerop (tramp-send-command-and-check
6342 vec (format "%s %s" result existing)))
6343 (not (zerop (tramp-send-command-and-check
6344 vec (format "%s %s" result nonexisting)))))
6345 (and (setq result "/bin/test -e")
6346 (zerop (tramp-send-command-and-check
6347 vec (format "%s %s" result existing)))
6348 (not (zerop (tramp-send-command-and-check
6349 vec (format "%s %s" result nonexisting)))))
6350 (and (setq result "/usr/bin/test -e")
6351 (zerop (tramp-send-command-and-check
6352 vec (format "%s %s" result existing)))
6353 (not (zerop (tramp-send-command-and-check
6354 vec (format "%s %s" result nonexisting)))))
6355 (and (setq result (format "%s -d" (tramp-get-ls-command vec)))
6356 (zerop (tramp-send-command-and-check
6357 vec (format "%s %s" result existing)))
6358 (not (zerop (tramp-send-command-and-check
6359 vec (format "%s %s" result nonexisting))))))
6360 (tramp-error
6361 vec 'file-error "Couldn't find command to check if file exists"))
6362 result))
6363
6364 ;; CCC test ksh or bash found for tilde expansion?
6365 (defun tramp-find-shell (vec)
6366 "Opens a shell on the remote host which groks tilde expansion."
6367 (unless (tramp-get-connection-property vec "remote-shell" nil)
6368 (let (shell)
6369 (with-current-buffer (tramp-get-buffer vec)
6370 (tramp-send-command vec "echo ~root" t)
6371 (cond
6372 ((string-match "^~root$" (buffer-string))
6373 (setq shell
6374 (or (tramp-find-executable
6375 vec "bash" (tramp-get-remote-path vec) t)
6376 (tramp-find-executable
6377 vec "ksh" (tramp-get-remote-path vec) t)))
6378 (unless shell
6379 (tramp-error
6380 vec 'file-error
6381 "Couldn't find a shell which groks tilde expansion"))
6382 ;; Find arguments for this shell.
6383 (let ((alist tramp-sh-extra-args)
6384 item extra-args)
6385 (while (and alist (null extra-args))
6386 (setq item (pop alist))
6387 (when (string-match (car item) shell)
6388 (setq extra-args (cdr item))))
6389 (when extra-args (setq shell (concat shell " " extra-args))))
6390 (tramp-message
6391 vec 5 "Starting remote shell `%s' for tilde expansion..." shell)
6392 (let ((tramp-end-of-output tramp-initial-end-of-output))
6393 (tramp-send-command
6394 vec
6395 (format "PROMPT_COMMAND='' PS1=%s PS2='' PS3='' exec %s"
6396 (shell-quote-argument tramp-end-of-output) shell)
6397 t))
6398 ;; Setting prompts.
6399 (tramp-message vec 5 "Setting remote shell prompt...")
6400 (tramp-send-command
6401 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6402 (tramp-send-command vec "PS2=''" t)
6403 (tramp-send-command vec "PS3=''" t)
6404 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6405 (tramp-message vec 5 "Setting remote shell prompt...done"))
6406
6407 (t (tramp-message
6408 vec 5 "Remote `%s' groks tilde expansion, good"
6409 (tramp-get-method-parameter
6410 (tramp-file-name-method vec) 'tramp-remote-sh))
6411 (tramp-set-connection-property
6412 vec "remote-shell"
6413 (tramp-get-method-parameter
6414 (tramp-file-name-method vec) 'tramp-remote-sh))))))))
6415
6416 ;; ------------------------------------------------------------
6417 ;; -- Functions for establishing connection --
6418 ;; ------------------------------------------------------------
6419
6420 ;; The following functions are actions to be taken when seeing certain
6421 ;; prompts from the remote host. See the variable
6422 ;; `tramp-actions-before-shell' for usage of these functions.
6423
6424 (defun tramp-action-login (proc vec)
6425 "Send the login name."
6426 (when (not (stringp tramp-current-user))
6427 (save-window-excursion
6428 (let ((enable-recursive-minibuffers t))
6429 (pop-to-buffer (tramp-get-connection-buffer vec))
6430 (setq tramp-current-user (read-string (match-string 0))))))
6431 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
6432 (with-current-buffer (tramp-get-connection-buffer vec)
6433 (tramp-message vec 6 "\n%s" (buffer-string)))
6434 (tramp-send-string vec tramp-current-user))
6435
6436 (defun tramp-action-password (proc vec)
6437 "Query the user for a password."
6438 (with-current-buffer (process-buffer proc)
6439 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
6440 (tramp-message vec 3 "Sending %s" (match-string 1)))
6441 (tramp-enter-password proc))
6442
6443 (defun tramp-action-succeed (proc vec)
6444 "Signal success in finding shell prompt."
6445 (throw 'tramp-action 'ok))
6446
6447 (defun tramp-action-permission-denied (proc vec)
6448 "Signal permission denied."
6449 (kill-process proc)
6450 (throw 'tramp-action 'permission-denied))
6451
6452 (defun tramp-action-yesno (proc vec)
6453 "Ask the user for confirmation using `yes-or-no-p'.
6454 Send \"yes\" to remote process on confirmation, abort otherwise.
6455 See also `tramp-action-yn'."
6456 (save-window-excursion
6457 (let ((enable-recursive-minibuffers t))
6458 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6459 (unless (yes-or-no-p (match-string 0))
6460 (kill-process proc)
6461 (throw 'tramp-action 'permission-denied))
6462 (with-current-buffer (tramp-get-connection-buffer vec)
6463 (tramp-message vec 6 "\n%s" (buffer-string)))
6464 (tramp-send-string vec "yes"))))
6465
6466 (defun tramp-action-yn (proc vec)
6467 "Ask the user for confirmation using `y-or-n-p'.
6468 Send \"y\" to remote process on confirmation, abort otherwise.
6469 See also `tramp-action-yesno'."
6470 (save-window-excursion
6471 (let ((enable-recursive-minibuffers t))
6472 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
6473 (unless (y-or-n-p (match-string 0))
6474 (kill-process proc)
6475 (throw 'tramp-action 'permission-denied))
6476 (with-current-buffer (tramp-get-connection-buffer vec)
6477 (tramp-message vec 6 "\n%s" (buffer-string)))
6478 (tramp-send-string vec "y"))))
6479
6480 (defun tramp-action-terminal (proc vec)
6481 "Tell the remote host which terminal type to use.
6482 The terminal type can be configured with `tramp-terminal-type'."
6483 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
6484 (with-current-buffer (tramp-get-connection-buffer vec)
6485 (tramp-message vec 6 "\n%s" (buffer-string)))
6486 (tramp-send-string vec tramp-terminal-type))
6487
6488 (defun tramp-action-process-alive (proc vec)
6489 "Check whether a process has finished."
6490 (unless (memq (process-status proc) '(run open))
6491 (throw 'tramp-action 'process-died)))
6492
6493 (defun tramp-action-out-of-band (proc vec)
6494 "Check whether an out-of-band copy has finished."
6495 (cond ((and (memq (process-status proc) '(stop exit))
6496 (zerop (process-exit-status proc)))
6497 (tramp-message vec 3 "Process has finished.")
6498 (throw 'tramp-action 'ok))
6499 ((or (and (memq (process-status proc) '(stop exit))
6500 (not (zerop (process-exit-status proc))))
6501 (memq (process-status proc) '(signal)))
6502 ;; `scp' could have copied correctly, but set modes could have failed.
6503 ;; This can be ignored.
6504 (with-current-buffer (process-buffer proc)
6505 (goto-char (point-min))
6506 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
6507 (progn
6508 (tramp-message vec 5 "'set mode' error ignored.")
6509 (tramp-message vec 3 "Process has finished.")
6510 (throw 'tramp-action 'ok))
6511 (tramp-message vec 3 "Process has died.")
6512 (throw 'tramp-action 'process-died))))
6513 (t nil)))
6514
6515 ;; Functions for processing the actions.
6516
6517 (defun tramp-process-one-action (proc vec actions)
6518 "Wait for output from the shell and perform one action."
6519 (let (found todo item pattern action)
6520 (while (not found)
6521 ;; Reread output once all actions have been performed.
6522 ;; Obviously, the output was not complete.
6523 (tramp-accept-process-output proc 1)
6524 (setq todo actions)
6525 (while todo
6526 (setq item (pop todo))
6527 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
6528 (setq action (nth 1 item))
6529 (tramp-message
6530 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
6531 (when (tramp-check-for-regexp proc pattern)
6532 (tramp-message vec 5 "Call `%s'" (symbol-name action))
6533 (setq found (funcall action proc vec)))))
6534 found))
6535
6536 (defun tramp-process-actions (proc vec actions &optional timeout)
6537 "Perform actions until success or TIMEOUT."
6538 ;; Enable auth-source and password-cache.
6539 (tramp-set-connection-property proc "first-password-request" t)
6540 (let (exit)
6541 (while (not exit)
6542 (tramp-message proc 3 "Waiting for prompts from remote shell")
6543 (setq exit
6544 (catch 'tramp-action
6545 (if timeout
6546 (with-timeout (timeout)
6547 (tramp-process-one-action proc vec actions))
6548 (tramp-process-one-action proc vec actions)))))
6549 (with-current-buffer (tramp-get-connection-buffer vec)
6550 (tramp-message vec 6 "\n%s" (buffer-string)))
6551 (unless (eq exit 'ok)
6552 (tramp-clear-passwd vec)
6553 (tramp-error-with-buffer
6554 nil vec 'file-error
6555 (cond
6556 ((eq exit 'permission-denied) "Permission denied")
6557 ((eq exit 'process-died) "Process died")
6558 (t "Login failed"))))))
6559
6560 ;; Utility functions.
6561
6562 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
6563 "Like `accept-process-output' for Tramp processes.
6564 This is needed in order to hide `last-coding-system-used', which is set
6565 for process communication also."
6566 (with-current-buffer (process-buffer proc)
6567 (tramp-message proc 10 "%s %s" proc (process-status proc))
6568 (let (buffer-read-only last-coding-system-used)
6569 ;; Under Windows XP, accept-process-output doesn't return
6570 ;; sometimes. So we add an additional timeout.
6571 (with-timeout ((or timeout 1))
6572 (accept-process-output proc timeout timeout-msecs)))
6573 (tramp-message proc 10 "\n%s" (buffer-string))))
6574
6575 (defun tramp-check-for-regexp (proc regexp)
6576 "Check whether REGEXP is contained in process buffer of PROC.
6577 Erase echoed commands if exists."
6578 (with-current-buffer (process-buffer proc)
6579 (goto-char (point-min))
6580
6581 ;; Check whether we need to remove echo output.
6582 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
6583 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
6584 (let ((begin (match-beginning 0)))
6585 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
6586 ;; Discard echo from remote output.
6587 (tramp-set-connection-property proc "check-remote-echo" nil)
6588 (tramp-message proc 5 "echo-mark found")
6589 (forward-line)
6590 (delete-region begin (point))
6591 (goto-char (point-min)))))
6592
6593 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
6594 ;; Sometimes, the echo string is suppressed on the remote side.
6595 (not (string-equal
6596 (substring-no-properties
6597 tramp-echo-mark-marker
6598 0 (min tramp-echo-mark-marker-length (1- (point-max))))
6599 (buffer-substring-no-properties
6600 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
6601 ;; No echo to be handled, now we can look for the regexp.
6602 (goto-char (point-min))
6603 (re-search-forward regexp nil t))))
6604
6605 (defun tramp-wait-for-regexp (proc timeout regexp)
6606 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
6607 Expects the output of PROC to be sent to the current buffer. Returns
6608 the string that matched, or nil. Waits indefinitely if TIMEOUT is
6609 nil."
6610 (with-current-buffer (process-buffer proc)
6611 (let ((found (tramp-check-for-regexp proc regexp))
6612 (start-time (current-time)))
6613 (cond (timeout
6614 ;; Work around a bug in XEmacs 21, where the timeout
6615 ;; expires faster than it should. This degenerates
6616 ;; to polling for buggy XEmacsen, but oh, well.
6617 (while (and (not found)
6618 (< (tramp-time-diff (current-time) start-time)
6619 timeout))
6620 (with-timeout (timeout)
6621 (while (not found)
6622 (tramp-accept-process-output proc 1)
6623 (unless (memq (process-status proc) '(run open))
6624 (tramp-error-with-buffer
6625 nil proc 'file-error "Process has died"))
6626 (setq found (tramp-check-for-regexp proc regexp))))))
6627 (t
6628 (while (not found)
6629 (tramp-accept-process-output proc 1)
6630 (unless (memq (process-status proc) '(run open))
6631 (tramp-error-with-buffer
6632 nil proc 'file-error "Process has died"))
6633 (setq found (tramp-check-for-regexp proc regexp)))))
6634 (tramp-message proc 6 "\n%s" (buffer-string))
6635 (when (not found)
6636 (if timeout
6637 (tramp-error
6638 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
6639 regexp timeout)
6640 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
6641 found)))
6642
6643 (defun tramp-barf-if-no-shell-prompt (proc timeout &rest error-args)
6644 "Wait for shell prompt and barf if none appears.
6645 Looks at process PROC to see if a shell prompt appears in TIMEOUT
6646 seconds. If not, it produces an error message with the given ERROR-ARGS."
6647 (unless
6648 (tramp-wait-for-regexp
6649 proc timeout
6650 (format
6651 "\\(%s\\|%s\\)\\'" shell-prompt-pattern tramp-shell-prompt-pattern))
6652 (apply 'tramp-error-with-buffer nil proc 'file-error error-args)))
6653
6654 ;; We don't call `tramp-send-string' in order to hide the password
6655 ;; from the debug buffer, and because end-of-line handling of the
6656 ;; string.
6657 (defun tramp-enter-password (proc)
6658 "Prompt for a password and send it to the remote end."
6659 (process-send-string
6660 proc (concat (tramp-read-passwd proc)
6661 (or (tramp-get-method-parameter
6662 tramp-current-method
6663 'tramp-password-end-of-line)
6664 tramp-default-password-end-of-line))))
6665
6666 (defun tramp-open-connection-setup-interactive-shell (proc vec)
6667 "Set up an interactive shell.
6668 Mainly sets the prompt and the echo correctly. PROC is the shell
6669 process to set up. VEC specifies the connection."
6670 (let ((tramp-end-of-output tramp-initial-end-of-output))
6671 ;; It is useful to set the prompt in the following command because
6672 ;; some people have a setting for $PS1 which /bin/sh doesn't know
6673 ;; about and thus /bin/sh will display a strange prompt. For
6674 ;; example, if $PS1 has "${CWD}" in the value, then ksh will
6675 ;; display the current working directory but /bin/sh will display
6676 ;; a dollar sign. The following command line sets $PS1 to a sane
6677 ;; value, and works under Bourne-ish shells as well as csh-like
6678 ;; shells. Daniel Pittman reports that the unusual positioning of
6679 ;; the single quotes makes it work under `rc', too. We also unset
6680 ;; the variable $ENV because that is read by some sh
6681 ;; implementations (eg, bash when called as sh) on startup; this
6682 ;; way, we avoid the startup file clobbering $PS1. $PROMP_COMMAND
6683 ;; is another way to set the prompt in /bin/bash, it must be
6684 ;; discarded as well.
6685 (tramp-send-command
6686 vec
6687 (format
6688 "exec env ENV='' PROMPT_COMMAND='' PS1=%s PS2='' PS3='' %s"
6689 (shell-quote-argument tramp-end-of-output)
6690 (tramp-get-method-parameter
6691 (tramp-file-name-method vec) 'tramp-remote-sh))
6692 t)
6693
6694 ;; Disable echo.
6695 (tramp-message vec 5 "Setting up remote shell environment")
6696 (tramp-send-command vec "stty -inlcr -echo kill '^U' erase '^H'" t)
6697 ;; Check whether the echo has really been disabled. Some
6698 ;; implementations, like busybox of embedded GNU/Linux, don't
6699 ;; support disabling.
6700 (tramp-send-command vec "echo foo" t)
6701 (with-current-buffer (process-buffer proc)
6702 (goto-char (point-min))
6703 (when (looking-at "echo foo")
6704 (tramp-set-connection-property proc "remote-echo" t)
6705 (tramp-message vec 5 "Remote echo still on. Ok.")
6706 ;; Make sure backspaces and their echo are enabled and no line
6707 ;; width magic interferes with them.
6708 (tramp-send-command vec "stty icanon erase ^H cols 32767" t))))
6709
6710 (tramp-message vec 5 "Setting shell prompt")
6711 (tramp-send-command
6712 vec (format "PS1=%s" (shell-quote-argument tramp-end-of-output)) t)
6713 (tramp-send-command vec "PS2=''" t)
6714 (tramp-send-command vec "PS3=''" t)
6715 (tramp-send-command vec "PROMPT_COMMAND=''" t)
6716
6717 ;; Try to set up the coding system correctly.
6718 ;; CCC this can't be the right way to do it. Hm.
6719 (tramp-message vec 5 "Determining coding system")
6720 (tramp-send-command vec "echo foo ; echo bar" t)
6721 (with-current-buffer (process-buffer proc)
6722 (goto-char (point-min))
6723 (if (featurep 'mule)
6724 ;; Use MULE to select the right EOL convention for communicating
6725 ;; with the process.
6726 (let* ((cs (or (funcall (symbol-function 'process-coding-system) proc)
6727 (cons 'undecided 'undecided)))
6728 cs-decode cs-encode)
6729 (when (symbolp cs) (setq cs (cons cs cs)))
6730 (setq cs-decode (car cs))
6731 (setq cs-encode (cdr cs))
6732 (unless cs-decode (setq cs-decode 'undecided))
6733 (unless cs-encode (setq cs-encode 'undecided))
6734 (setq cs-encode (tramp-coding-system-change-eol-conversion
6735 cs-encode 'unix))
6736 (when (search-forward "\r" nil t)
6737 (setq cs-decode (tramp-coding-system-change-eol-conversion
6738 cs-decode 'dos)))
6739 (funcall (symbol-function 'set-buffer-process-coding-system)
6740 cs-decode cs-encode)
6741 (tramp-message
6742 vec 5 "Setting coding system to `%s' and `%s'" cs-decode cs-encode))
6743 ;; Look for ^M and do something useful if found.
6744 (when (search-forward "\r" nil t)
6745 ;; We have found a ^M but cannot frob the process coding system
6746 ;; because we're running on a non-MULE Emacs. Let's try
6747 ;; stty, instead.
6748 (tramp-send-command vec "stty -onlcr" t))))
6749 ;; Dump stty settings in the traces.
6750 (when (>= tramp-verbose 10)
6751 (tramp-send-command vec "stty -a" t))
6752 (tramp-send-command vec "set +o vi +o emacs" t)
6753
6754 ;; Check whether the output of "uname -sr" has been changed. If
6755 ;; yes, this is a strong indication that we must expire all
6756 ;; connection properties. We start again with
6757 ;; `tramp-maybe-open-connection', it will be catched there.
6758 (tramp-message vec 5 "Checking system information")
6759 (let ((old-uname (tramp-get-connection-property vec "uname" nil))
6760 (new-uname
6761 (tramp-set-connection-property
6762 vec "uname"
6763 (tramp-send-command-and-read vec "echo \\\"`uname -sr`\\\""))))
6764 (when (and (stringp old-uname) (not (string-equal old-uname new-uname)))
6765 (with-current-buffer (tramp-get-debug-buffer vec)
6766 ;; Keep the debug buffer
6767 (rename-buffer
6768 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
6769 (funcall (symbol-function 'tramp-cleanup-connection) vec)
6770 (if (= (point-min) (point-max))
6771 (kill-buffer nil)
6772 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
6773 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
6774 (tramp-get-buffer vec)
6775 (tramp-message
6776 vec 3
6777 "Connection reset, because remote host changed from `%s' to `%s'"
6778 old-uname new-uname)
6779 (throw 'uname-changed (tramp-maybe-open-connection vec)))))
6780
6781 ;; Check whether the remote host suffers from buggy
6782 ;; `send-process-string'. This is known for FreeBSD (see comment in
6783 ;; `send_process', file process.c). I've tested sending 624 bytes
6784 ;; successfully, sending 625 bytes failed. Emacs makes a hack when
6785 ;; this host type is detected locally. It cannot handle remote
6786 ;; hosts, though.
6787 (with-connection-property proc "chunksize"
6788 (cond
6789 ((and (integerp tramp-chunksize) (> tramp-chunksize 0))
6790 tramp-chunksize)
6791 (t
6792 (tramp-message
6793 vec 5 "Checking remote host type for `send-process-string' bug")
6794 (if (string-match
6795 "^FreeBSD" (tramp-get-connection-property vec "uname" ""))
6796 500 0))))
6797
6798 ;; Set remote PATH variable.
6799 (tramp-set-remote-path vec)
6800
6801 ;; Search for a good shell before searching for a command which
6802 ;; checks if a file exists. This is done because Tramp wants to use
6803 ;; "test foo; echo $?" to check if various conditions hold, and
6804 ;; there are buggy /bin/sh implementations which don't execute the
6805 ;; "echo $?" part if the "test" part has an error. In particular,
6806 ;; the Solaris /bin/sh is a problem. I'm betting that all systems
6807 ;; with buggy /bin/sh implementations will have a working bash or
6808 ;; ksh. Whee...
6809 (tramp-find-shell vec)
6810
6811 ;; Disable unexpected output.
6812 (tramp-send-command vec "mesg n; biff n" t)
6813
6814 ;; Set the environment.
6815 (tramp-message vec 5 "Setting default environment")
6816
6817 ;; On OpenSolaris, there is a bug when HISTFILE is changed in place
6818 ;; <http://bugs.opensolaris.org/view_bug.do?bug_id=6834184>. We
6819 ;; apply the workaround.
6820 (if (string-equal (tramp-get-connection-property vec "uname" "") "SunOS 5.11")
6821 (tramp-send-command vec "unset HISTFILE" t))
6822
6823 (let ((env (copy-sequence tramp-remote-process-environment))
6824 unset item)
6825 (while env
6826 (setq item (tramp-compat-split-string (car env) "="))
6827 (setcdr item (mapconcat 'identity (cdr item) "="))
6828 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
6829 (tramp-send-command
6830 vec (format "%s=%s; export %s" (car item) (cdr item) (car item)) t)
6831 (push (car item) unset))
6832 (setq env (cdr env)))
6833 (when unset
6834 (tramp-send-command
6835 vec (format "unset %s" (mapconcat 'identity unset " "))))) t)
6836
6837 ;; CCC: We should either implement a Perl version of base64 encoding
6838 ;; and decoding. Then we just use that in the last item. The other
6839 ;; alternative is to use the Perl version of UU encoding. But then
6840 ;; we need a Lisp version of uuencode.
6841 ;;
6842 ;; Old text from documentation of tramp-methods:
6843 ;; Using a uuencode/uudecode inline method is discouraged, please use one
6844 ;; of the base64 methods instead since base64 encoding is much more
6845 ;; reliable and the commands are more standardized between the different
6846 ;; Unix versions. But if you can't use base64 for some reason, please
6847 ;; note that the default uudecode command does not work well for some
6848 ;; Unices, in particular AIX and Irix. For AIX, you might want to use
6849 ;; the following command for uudecode:
6850 ;;
6851 ;; sed '/^begin/d;/^[` ]$/d;/^end/d' | iconv -f uucode -t ISO8859-1
6852 ;;
6853 ;; For Irix, no solution is known yet.
6854
6855 (defconst tramp-local-coding-commands
6856 '((b64 base64-encode-region base64-decode-region)
6857 (uu tramp-uuencode-region uudecode-decode-region)
6858 (pack
6859 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6860 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6861 "List of local coding commands for inline transfer.
6862 Each item is a list that looks like this:
6863
6864 \(FORMAT ENCODING DECODING)
6865
6866 FORMAT is symbol describing the encoding/decoding format. It can be
6867 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6868
6869 ENCODING and DECODING can be strings, giving commands, or symbols,
6870 giving functions. If they are strings, then they can contain
6871 the \"%s\" format specifier. If that specifier is present, the input
6872 filename will be put into the command line at that spot. If the
6873 specifier is not present, the input should be read from standard
6874 input.
6875
6876 If they are functions, they will be called with two arguments, start
6877 and end of region, and are expected to replace the region contents
6878 with the encoded or decoded results, respectively.")
6879
6880 (defconst tramp-remote-coding-commands
6881 '((b64 "base64" "base64 -d")
6882 (b64 "mimencode -b" "mimencode -u -b")
6883 (b64 "mmencode -b" "mmencode -u -b")
6884 (b64 "recode data..base64" "recode base64..data")
6885 (b64 tramp-perl-encode-with-module tramp-perl-decode-with-module)
6886 (b64 tramp-perl-encode tramp-perl-decode)
6887 (uu "uuencode xxx" "uudecode -o /dev/stdout")
6888 (uu "uuencode xxx" "uudecode -o -")
6889 (uu "uuencode xxx" "uudecode -p")
6890 (uu "uuencode xxx" tramp-uudecode)
6891 (pack
6892 "perl -e 'binmode STDIN; binmode STDOUT; print pack(q{u*}, join q{}, <>)'"
6893 "perl -e 'binmode STDIN; binmode STDOUT; print unpack(q{u*}, join q{}, <>)'"))
6894 "List of remote coding commands for inline transfer.
6895 Each item is a list that looks like this:
6896
6897 \(FORMAT ENCODING DECODING)
6898
6899 FORMAT is symbol describing the encoding/decoding format. It can be
6900 `b64' for base64 encoding, `uu' for uu encoding, or `pack' for simple packing.
6901
6902 ENCODING and DECODING can be strings, giving commands, or symbols,
6903 giving variables. If they are strings, then they can contain
6904 the \"%s\" format specifier. If that specifier is present, the input
6905 filename will be put into the command line at that spot. If the
6906 specifier is not present, the input should be read from standard
6907 input.
6908
6909 If they are variables, this variable is a string containing a Perl
6910 implementation for this functionality. This Perl program will be transferred
6911 to the remote host, and it is available as shell function with the same name.")
6912
6913 (defun tramp-find-inline-encoding (vec)
6914 "Find an inline transfer encoding that works.
6915 Goes through the list `tramp-local-coding-commands' and
6916 `tramp-remote-coding-commands'."
6917 (save-excursion
6918 (let ((local-commands tramp-local-coding-commands)
6919 (magic "xyzzy")
6920 loc-enc loc-dec rem-enc rem-dec litem ritem found)
6921 (while (and local-commands (not found))
6922 (setq litem (pop local-commands))
6923 (catch 'wont-work-local
6924 (let ((format (nth 0 litem))
6925 (remote-commands tramp-remote-coding-commands))
6926 (setq loc-enc (nth 1 litem))
6927 (setq loc-dec (nth 2 litem))
6928 ;; If the local encoder or decoder is a string, the
6929 ;; corresponding command has to work locally.
6930 (if (not (stringp loc-enc))
6931 (tramp-message
6932 vec 5 "Checking local encoding function `%s'" loc-enc)
6933 (tramp-message
6934 vec 5 "Checking local encoding command `%s' for sanity" loc-enc)
6935 (unless (zerop (tramp-call-local-coding-command
6936 loc-enc nil nil))
6937 (throw 'wont-work-local nil)))
6938 (if (not (stringp loc-dec))
6939 (tramp-message
6940 vec 5 "Checking local decoding function `%s'" loc-dec)
6941 (tramp-message
6942 vec 5 "Checking local decoding command `%s' for sanity" loc-dec)
6943 (unless (zerop (tramp-call-local-coding-command
6944 loc-dec nil nil))
6945 (throw 'wont-work-local nil)))
6946 ;; Search for remote coding commands with the same format
6947 (while (and remote-commands (not found))
6948 (setq ritem (pop remote-commands))
6949 (catch 'wont-work-remote
6950 (when (equal format (nth 0 ritem))
6951 (setq rem-enc (nth 1 ritem))
6952 (setq rem-dec (nth 2 ritem))
6953 ;; Check if remote encoding and decoding commands can be
6954 ;; called remotely with null input and output. This makes
6955 ;; sure there are no syntax errors and the command is really
6956 ;; found. Note that we do not redirect stdout to /dev/null,
6957 ;; for two reasons: when checking the decoding command, we
6958 ;; actually check the output it gives. And also, when
6959 ;; redirecting "mimencode" output to /dev/null, then as root
6960 ;; it might change the permissions of /dev/null!
6961 (when (not (stringp rem-enc))
6962 (let ((name (symbol-name rem-enc)))
6963 (while (string-match (regexp-quote "-") name)
6964 (setq name (replace-match "_" nil t name)))
6965 (tramp-maybe-send-script vec (symbol-value rem-enc) name)
6966 (setq rem-enc name)))
6967 (tramp-message
6968 vec 5
6969 "Checking remote encoding command `%s' for sanity" rem-enc)
6970 (unless (zerop (tramp-send-command-and-check
6971 vec (format "%s </dev/null" rem-enc) t))
6972 (throw 'wont-work-remote nil))
6973
6974 (when (not (stringp rem-dec))
6975 (let ((name (symbol-name rem-dec)))
6976 (while (string-match (regexp-quote "-") name)
6977 (setq name (replace-match "_" nil t name)))
6978 (tramp-maybe-send-script vec (symbol-value rem-dec) name)
6979 (setq rem-dec name)))
6980 (tramp-message
6981 vec 5
6982 "Checking remote decoding command `%s' for sanity" rem-dec)
6983 (unless (zerop (tramp-send-command-and-check
6984 vec
6985 (format "echo %s | %s | %s"
6986 magic rem-enc rem-dec)
6987 t))
6988 (throw 'wont-work-remote nil))
6989
6990 (with-current-buffer (tramp-get-buffer vec)
6991 (goto-char (point-min))
6992 (unless (looking-at (regexp-quote magic))
6993 (throw 'wont-work-remote nil)))
6994
6995 ;; `rem-enc' and `rem-dec' could be a string meanwhile.
6996 (setq rem-enc (nth 1 ritem))
6997 (setq rem-dec (nth 2 ritem))
6998 (setq found t)))))))
6999
7000 ;; Did we find something?
7001 (unless found
7002 (tramp-error
7003 vec 'file-error "Couldn't find an inline transfer encoding"))
7004
7005 ;; Set connection properties.
7006 (tramp-message vec 5 "Using local encoding `%s'" loc-enc)
7007 (tramp-set-connection-property vec "local-encoding" loc-enc)
7008 (tramp-message vec 5 "Using local decoding `%s'" loc-dec)
7009 (tramp-set-connection-property vec "local-decoding" loc-dec)
7010 (tramp-message vec 5 "Using remote encoding `%s'" rem-enc)
7011 (tramp-set-connection-property vec "remote-encoding" rem-enc)
7012 (tramp-message vec 5 "Using remote decoding `%s'" rem-dec)
7013 (tramp-set-connection-property vec "remote-decoding" rem-dec))))
7014
7015 (defun tramp-call-local-coding-command (cmd input output)
7016 "Call the local encoding or decoding command.
7017 If CMD contains \"%s\", provide input file INPUT there in command.
7018 Otherwise, INPUT is passed via standard input.
7019 INPUT can also be nil which means `/dev/null'.
7020 OUTPUT can be a string (which specifies a filename), or t (which
7021 means standard output and thus the current buffer), or nil (which
7022 means discard it)."
7023 (tramp-local-call-process
7024 tramp-encoding-shell
7025 (when (and input (not (string-match "%s" cmd))) input)
7026 (if (eq output t) t nil)
7027 nil
7028 tramp-encoding-command-switch
7029 (concat
7030 (if (string-match "%s" cmd) (format cmd input) cmd)
7031 (if (stringp output) (concat "> " output) ""))))
7032
7033 (defun tramp-compute-multi-hops (vec)
7034 "Expands VEC according to `tramp-default-proxies-alist'.
7035 Gateway hops are already opened."
7036 (let ((target-alist `(,vec))
7037 (choices tramp-default-proxies-alist)
7038 item proxy)
7039
7040 ;; Look for proxy hosts to be passed.
7041 (while choices
7042 (setq item (pop choices)
7043 proxy (eval (nth 2 item)))
7044 (when (and
7045 ;; host
7046 (string-match (or (eval (nth 0 item)) "")
7047 (or (tramp-file-name-host (car target-alist)) ""))
7048 ;; user
7049 (string-match (or (eval (nth 1 item)) "")
7050 (or (tramp-file-name-user (car target-alist)) "")))
7051 (if (null proxy)
7052 ;; No more hops needed.
7053 (setq choices nil)
7054 ;; Replace placeholders.
7055 (setq proxy
7056 (format-spec
7057 proxy
7058 `((?u . ,(or (tramp-file-name-user (car target-alist)) ""))
7059 (?h . ,(or (tramp-file-name-host (car target-alist)) "")))))
7060 (with-parsed-tramp-file-name proxy l
7061 ;; Add the hop.
7062 (add-to-list 'target-alist l)
7063 ;; Start next search.
7064 (setq choices tramp-default-proxies-alist)))))
7065
7066 ;; Handle gateways.
7067 (when (and (boundp 'tramp-gw-tunnel-method)
7068 (string-match (format
7069 "^\\(%s\\|%s\\)$"
7070 (symbol-value 'tramp-gw-tunnel-method)
7071 (symbol-value 'tramp-gw-socks-method))
7072 (tramp-file-name-method (car target-alist))))
7073 (let ((gw (pop target-alist))
7074 (hop (pop target-alist)))
7075 ;; Is the method prepared for gateways?
7076 (unless (tramp-get-method-parameter
7077 (tramp-file-name-method hop) 'tramp-default-port)
7078 (tramp-error
7079 vec 'file-error
7080 "Method `%s' is not supported for gateway access."
7081 (tramp-file-name-method hop)))
7082 ;; Add default port if needed.
7083 (unless
7084 (string-match
7085 tramp-host-with-port-regexp (tramp-file-name-host hop))
7086 (aset hop 2
7087 (concat
7088 (tramp-file-name-host hop) tramp-prefix-port-format
7089 (number-to-string
7090 (tramp-get-method-parameter
7091 (tramp-file-name-method hop) 'tramp-default-port)))))
7092 ;; Open the gateway connection.
7093 (add-to-list
7094 'target-alist
7095 (vector
7096 (tramp-file-name-method hop) (tramp-file-name-user hop)
7097 (funcall (symbol-function 'tramp-gw-open-connection) vec gw hop) nil))
7098 ;; For the password prompt, we need the correct values.
7099 ;; Therefore, we must remember the gateway vector. But we
7100 ;; cannot do it as connection property, because it shouldn't
7101 ;; be persistent. And we have no started process yet either.
7102 (tramp-set-file-property (car target-alist) "" "gateway" hop)))
7103
7104 ;; Foreign and out-of-band methods are not supported for multi-hops.
7105 (when (cdr target-alist)
7106 (setq choices target-alist)
7107 (while choices
7108 (setq item (pop choices))
7109 (when
7110 (or
7111 (not
7112 (tramp-get-method-parameter
7113 (tramp-file-name-method item) 'tramp-login-program))
7114 (tramp-get-method-parameter
7115 (tramp-file-name-method item) 'tramp-copy-program))
7116 (tramp-error
7117 vec 'file-error
7118 "Method `%s' is not supported for multi-hops."
7119 (tramp-file-name-method item)))))
7120
7121 ;; In case the host name is not used for the remote shell
7122 ;; command, the user could be misguided by applying a random
7123 ;; hostname.
7124 (let* ((v (car target-alist))
7125 (method (tramp-file-name-method v))
7126 (host (tramp-file-name-host v)))
7127 (unless
7128 (or
7129 ;; There are multi-hops.
7130 (cdr target-alist)
7131 ;; The host name is used for the remote shell command.
7132 (member
7133 '("%h") (tramp-get-method-parameter method 'tramp-login-args))
7134 ;; The host is local. We cannot use `tramp-local-host-p'
7135 ;; here, because it opens a connection as well.
7136 (string-match tramp-local-host-regexp host))
7137 (tramp-error
7138 v 'file-error
7139 "Host `%s' looks like a remote host, `%s' can only use the local host"
7140 host method)))
7141
7142 ;; Result.
7143 target-alist))
7144
7145 (defun tramp-maybe-open-connection (vec)
7146 "Maybe open a connection VEC.
7147 Does not do anything if a connection is already open, but re-opens the
7148 connection if a previous connection has died for some reason."
7149 (catch 'uname-changed
7150 (let ((p (tramp-get-connection-process vec))
7151 (process-environment (copy-sequence process-environment)))
7152
7153 ;; If too much time has passed since last command was sent, look
7154 ;; whether process is still alive. If it isn't, kill it. When
7155 ;; using ssh, it can sometimes happen that the remote end has
7156 ;; hung up but the local ssh client doesn't recognize this until
7157 ;; it tries to send some data to the remote end. So that's why
7158 ;; we try to send a command from time to time, then look again
7159 ;; whether the process is really alive.
7160 (condition-case nil
7161 (when (and (> (tramp-time-diff
7162 (current-time)
7163 (tramp-get-connection-property
7164 p "last-cmd-time" '(0 0 0)))
7165 60)
7166 p (processp p) (memq (process-status p) '(run open)))
7167 (tramp-send-command vec "echo are you awake" t t)
7168 (unless (and (memq (process-status p) '(run open))
7169 (tramp-wait-for-output p 10))
7170 ;; The error will be catched locally.
7171 (tramp-error vec 'file-error "Awake did fail")))
7172 (file-error
7173 (tramp-flush-connection-property vec)
7174 (tramp-flush-connection-property p)
7175 (delete-process p)
7176 (setq p nil)))
7177
7178 ;; New connection must be opened.
7179 (unless (and p (processp p) (memq (process-status p) '(run open)))
7180
7181 ;; We call `tramp-get-buffer' in order to get a debug buffer for
7182 ;; messages from the beginning.
7183 (tramp-get-buffer vec)
7184 (if (zerop (length (tramp-file-name-user vec)))
7185 (tramp-message
7186 vec 3 "Opening connection for %s using %s..."
7187 (tramp-file-name-host vec)
7188 (tramp-file-name-method vec))
7189 (tramp-message
7190 vec 3 "Opening connection for %s@%s using %s..."
7191 (tramp-file-name-user vec)
7192 (tramp-file-name-host vec)
7193 (tramp-file-name-method vec)))
7194
7195 ;; Start new process.
7196 (when (and p (processp p))
7197 (delete-process p))
7198 (setenv "TERM" tramp-terminal-type)
7199 (setenv "LC_ALL" "C")
7200 (setenv "PROMPT_COMMAND")
7201 (setenv "PS1" tramp-initial-end-of-output)
7202 (let* ((target-alist (tramp-compute-multi-hops vec))
7203 (process-connection-type tramp-process-connection-type)
7204 (process-adaptive-read-buffering nil)
7205 (coding-system-for-read nil)
7206 ;; This must be done in order to avoid our file name handler.
7207 (p (let ((default-directory
7208 (tramp-compat-temporary-file-directory)))
7209 (start-process
7210 (or (tramp-get-connection-property vec "process-name" nil)
7211 (tramp-buffer-name vec))
7212 (tramp-get-connection-buffer vec)
7213 tramp-encoding-shell))))
7214
7215 (tramp-message
7216 vec 6 "%s" (mapconcat 'identity (process-command p) " "))
7217
7218 ;; Check whether process is alive.
7219 (tramp-set-process-query-on-exit-flag p nil)
7220 (tramp-message vec 3 "Waiting 60s for local shell to come up...")
7221 (tramp-barf-if-no-shell-prompt
7222 p 60 "Couldn't find local shell prompt %s" tramp-encoding-shell)
7223
7224 ;; Now do all the connections as specified.
7225 (while target-alist
7226 (let* ((hop (car target-alist))
7227 (l-method (tramp-file-name-method hop))
7228 (l-user (tramp-file-name-user hop))
7229 (l-host (tramp-file-name-host hop))
7230 (l-port nil)
7231 (login-program
7232 (tramp-get-method-parameter l-method 'tramp-login-program))
7233 (login-args
7234 (tramp-get-method-parameter l-method 'tramp-login-args))
7235 (gw-args
7236 (tramp-get-method-parameter l-method 'tramp-gw-args))
7237 (gw (tramp-get-file-property hop "" "gateway" nil))
7238 (g-method (and gw (tramp-file-name-method gw)))
7239 (g-user (and gw (tramp-file-name-user gw)))
7240 (g-host (and gw (tramp-file-name-host gw)))
7241 (command login-program)
7242 ;; We don't create the temporary file. In fact, it
7243 ;; is just a prefix for the ControlPath option of
7244 ;; ssh; the real temporary file has another name, and
7245 ;; it is created and protected by ssh. It is also
7246 ;; removed by ssh, when the connection is closed.
7247 (tmpfile
7248 (tramp-set-connection-property
7249 p "temp-file"
7250 (make-temp-name
7251 (expand-file-name
7252 tramp-temp-name-prefix
7253 (tramp-compat-temporary-file-directory)))))
7254 spec)
7255
7256 ;; Add gateway arguments if necessary.
7257 (when (and gw gw-args)
7258 (setq login-args (append login-args gw-args)))
7259
7260 ;; Check for port number. Until now, there's no need
7261 ;; for handling like method, user, host.
7262 (when (string-match tramp-host-with-port-regexp l-host)
7263 (setq l-port (match-string 2 l-host)
7264 l-host (match-string 1 l-host)))
7265
7266 ;; Set variables for computing the prompt for reading
7267 ;; password. They can also be derived from a gateway.
7268 (setq tramp-current-method (or g-method l-method)
7269 tramp-current-user (or g-user l-user)
7270 tramp-current-host (or g-host l-host))
7271
7272 ;; Replace login-args place holders.
7273 (setq
7274 l-host (or l-host "")
7275 l-user (or l-user "")
7276 l-port (or l-port "")
7277 spec `((?h . ,l-host) (?u . ,l-user) (?p . ,l-port)
7278 (?t . ,tmpfile))
7279 command
7280 (concat
7281 ;; We do not want to see the trailing local prompt in
7282 ;; `start-file-process'.
7283 (unless (memq system-type '(windows-nt)) "exec ")
7284 command " "
7285 (mapconcat
7286 (lambda (x)
7287 (setq x (mapcar (lambda (y) (format-spec y spec)) x))
7288 (unless (member "" x) (mapconcat 'identity x " ")))
7289 login-args " ")
7290 ;; Local shell could be a Windows COMSPEC. It doesn't
7291 ;; know the ";" syntax, but we must exit always for
7292 ;; `start-file-process'. "exec" does not work either.
7293 (if (memq system-type '(windows-nt)) " && exit || exit")))
7294
7295 ;; Send the command.
7296 (tramp-message vec 3 "Sending command `%s'" command)
7297 (tramp-send-command vec command t t)
7298 (tramp-process-actions p vec tramp-actions-before-shell 60)
7299 (tramp-message vec 3 "Found remote shell prompt on `%s'" l-host))
7300 ;; Next hop.
7301 (setq target-alist (cdr target-alist)))
7302
7303 ;; Make initial shell settings.
7304 (tramp-open-connection-setup-interactive-shell p vec))))))
7305
7306 (defun tramp-send-command (vec command &optional neveropen nooutput)
7307 "Send the COMMAND to connection VEC.
7308 Erases temporary buffer before sending the command. If optional
7309 arg NEVEROPEN is non-nil, never try to open the connection. This
7310 is meant to be used from `tramp-maybe-open-connection' only. The
7311 function waits for output unless NOOUTPUT is set."
7312 (unless neveropen (tramp-maybe-open-connection vec))
7313 (let ((p (tramp-get-connection-process vec)))
7314 (when (tramp-get-connection-property p "remote-echo" nil)
7315 ;; We mark the command string that it can be erased in the output buffer.
7316 (tramp-set-connection-property p "check-remote-echo" t)
7317 (setq command (format "%s%s%s" tramp-echo-mark command tramp-echo-mark)))
7318 (tramp-message vec 6 "%s" command)
7319 (tramp-send-string vec command)
7320 (unless nooutput (tramp-wait-for-output p))))
7321
7322 (defun tramp-wait-for-output (proc &optional timeout)
7323 "Wait for output from remote command."
7324 (unless (buffer-live-p (process-buffer proc))
7325 (delete-process proc)
7326 (tramp-error proc 'file-error "Process `%s' not available, try again" proc))
7327 (with-current-buffer (process-buffer proc)
7328 (let* (;; Initially, `tramp-end-of-output' is "#$ ". There might
7329 ;; be leading escape sequences, which must be ignored.
7330 (regexp (format "[^#$\n]*%s\r?$" (regexp-quote tramp-end-of-output)))
7331 ;; Sometimes, the commands do not return a newline but a
7332 ;; null byte before the shell prompt, for example "git
7333 ;; ls-files -c -z ...".
7334 (regexp1 (format "\\(^\\|\000\\)%s" regexp))
7335 (found (tramp-wait-for-regexp proc timeout regexp1)))
7336 (if found
7337 (let (buffer-read-only)
7338 ;; A simple-minded busybox has sent " ^H" sequences.
7339 ;; Delete them.
7340 (goto-char (point-min))
7341 (when (re-search-forward
7342 "^\\(.\b\\)+$" (tramp-compat-line-end-position) t)
7343 (forward-line 1)
7344 (delete-region (point-min) (point)))
7345 ;; Delete the prompt.
7346 (goto-char (point-max))
7347 (re-search-backward regexp nil t)
7348 (delete-region (point) (point-max)))
7349 (if timeout
7350 (tramp-error
7351 proc 'file-error
7352 "[[Remote prompt `%s' not found in %d secs]]"
7353 tramp-end-of-output timeout)
7354 (tramp-error
7355 proc 'file-error
7356 "[[Remote prompt `%s' not found]]" tramp-end-of-output)))
7357 ;; Return value is whether end-of-output sentinel was found.
7358 found)))
7359
7360 (defun tramp-send-command-and-check
7361 (vec command &optional subshell dont-suppress-err)
7362 "Run COMMAND and check its exit status.
7363 Sends `echo $?' along with the COMMAND for checking the exit status. If
7364 COMMAND is nil, just sends `echo $?'. Returns the exit status found.
7365
7366 If the optional argument SUBSHELL is non-nil, the command is
7367 executed in a subshell, ie surrounded by parentheses. If
7368 DONT-SUPPRESS-ERR is non-nil, stderr won't be sent to /dev/null."
7369 (tramp-send-command
7370 vec
7371 (concat (if subshell "( " "")
7372 command
7373 (if command (if dont-suppress-err "; " " 2>/dev/null; ") "")
7374 "echo tramp_exit_status $?"
7375 (if subshell " )" "")))
7376 (with-current-buffer (tramp-get-connection-buffer vec)
7377 (goto-char (point-max))
7378 (unless (re-search-backward "tramp_exit_status [0-9]+" nil t)
7379 (tramp-error
7380 vec 'file-error "Couldn't find exit status of `%s'" command))
7381 (skip-chars-forward "^ ")
7382 (prog1
7383 (read (current-buffer))
7384 (let (buffer-read-only) (delete-region (match-beginning 0) (point-max))))))
7385
7386 (defun tramp-barf-unless-okay (vec command fmt &rest args)
7387 "Run COMMAND, check exit status, throw error if exit status not okay.
7388 Similar to `tramp-send-command-and-check' but accepts two more arguments
7389 FMT and ARGS which are passed to `error'."
7390 (unless (zerop (tramp-send-command-and-check vec command))
7391 (apply 'tramp-error vec 'file-error fmt args)))
7392
7393 (defun tramp-send-command-and-read (vec command)
7394 "Run COMMAND and return the output, which must be a Lisp expression.
7395 In case there is no valid Lisp expression, it raises an error"
7396 (tramp-barf-unless-okay vec command "`%s' returns with error" command)
7397 (with-current-buffer (tramp-get-connection-buffer vec)
7398 ;; Read the expression.
7399 (goto-char (point-min))
7400 (condition-case nil
7401 (prog1 (read (current-buffer))
7402 ;; Error handling.
7403 (when (re-search-forward "\\S-" (tramp-compat-line-end-position) t)
7404 (error nil)))
7405 (error (tramp-error
7406 vec 'file-error
7407 "`%s' does not return a valid Lisp expression: `%s'"
7408 command (buffer-string))))))
7409
7410 ;; It seems that Tru64 Unix does not like it if long strings are sent
7411 ;; to it in one go. (This happens when sending the Perl
7412 ;; `file-attributes' implementation, for instance.) Therefore, we
7413 ;; have this function which sends the string in chunks.
7414 (defun tramp-send-string (vec string)
7415 "Send the STRING via connection VEC.
7416
7417 The STRING is expected to use Unix line-endings, but the lines sent to
7418 the remote host use line-endings as defined in the variable
7419 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
7420 (let* ((p (tramp-get-connection-process vec))
7421 (chunksize (tramp-get-connection-property p "chunksize" nil)))
7422 (unless p
7423 (tramp-error
7424 vec 'file-error "Can't send string to remote host -- not logged in"))
7425 (tramp-set-connection-property p "last-cmd-time" (current-time))
7426 (tramp-message vec 10 "%s" string)
7427 (with-current-buffer (tramp-get-connection-buffer vec)
7428 ;; Clean up the buffer. We cannot call `erase-buffer' because
7429 ;; narrowing might be in effect.
7430 (let (buffer-read-only) (delete-region (point-min) (point-max)))
7431 ;; Replace "\n" by `tramp-rsh-end-of-line'.
7432 (setq string
7433 (mapconcat 'identity
7434 (tramp-compat-split-string string "\n")
7435 tramp-rsh-end-of-line))
7436 (unless (or (string= string "")
7437 (string-equal (substring string -1) tramp-rsh-end-of-line))
7438 (setq string (concat string tramp-rsh-end-of-line)))
7439 ;; Send the string.
7440 (if (and chunksize (not (zerop chunksize)))
7441 (let ((pos 0)
7442 (end (length string)))
7443 (while (< pos end)
7444 (tramp-message
7445 vec 10 "Sending chunk from %s to %s"
7446 pos (min (+ pos chunksize) end))
7447 (process-send-string
7448 p (substring string pos (min (+ pos chunksize) end)))
7449 (setq pos (+ pos chunksize))))
7450 (process-send-string p string)))))
7451
7452 (defun tramp-mode-string-to-int (mode-string)
7453 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
7454 (let* (case-fold-search
7455 (mode-chars (string-to-vector mode-string))
7456 (owner-read (aref mode-chars 1))
7457 (owner-write (aref mode-chars 2))
7458 (owner-execute-or-setid (aref mode-chars 3))
7459 (group-read (aref mode-chars 4))
7460 (group-write (aref mode-chars 5))
7461 (group-execute-or-setid (aref mode-chars 6))
7462 (other-read (aref mode-chars 7))
7463 (other-write (aref mode-chars 8))
7464 (other-execute-or-sticky (aref mode-chars 9)))
7465 (save-match-data
7466 (logior
7467 (cond
7468 ((char-equal owner-read ?r) (tramp-octal-to-decimal "00400"))
7469 ((char-equal owner-read ?-) 0)
7470 (t (error "Second char `%c' must be one of `r-'" owner-read)))
7471 (cond
7472 ((char-equal owner-write ?w) (tramp-octal-to-decimal "00200"))
7473 ((char-equal owner-write ?-) 0)
7474 (t (error "Third char `%c' must be one of `w-'" owner-write)))
7475 (cond
7476 ((char-equal owner-execute-or-setid ?x)
7477 (tramp-octal-to-decimal "00100"))
7478 ((char-equal owner-execute-or-setid ?S)
7479 (tramp-octal-to-decimal "04000"))
7480 ((char-equal owner-execute-or-setid ?s)
7481 (tramp-octal-to-decimal "04100"))
7482 ((char-equal owner-execute-or-setid ?-) 0)
7483 (t (error "Fourth char `%c' must be one of `xsS-'"
7484 owner-execute-or-setid)))
7485 (cond
7486 ((char-equal group-read ?r) (tramp-octal-to-decimal "00040"))
7487 ((char-equal group-read ?-) 0)
7488 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
7489 (cond
7490 ((char-equal group-write ?w) (tramp-octal-to-decimal "00020"))
7491 ((char-equal group-write ?-) 0)
7492 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
7493 (cond
7494 ((char-equal group-execute-or-setid ?x)
7495 (tramp-octal-to-decimal "00010"))
7496 ((char-equal group-execute-or-setid ?S)
7497 (tramp-octal-to-decimal "02000"))
7498 ((char-equal group-execute-or-setid ?s)
7499 (tramp-octal-to-decimal "02010"))
7500 ((char-equal group-execute-or-setid ?-) 0)
7501 (t (error "Seventh char `%c' must be one of `xsS-'"
7502 group-execute-or-setid)))
7503 (cond
7504 ((char-equal other-read ?r)
7505 (tramp-octal-to-decimal "00004"))
7506 ((char-equal other-read ?-) 0)
7507 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
7508 (cond
7509 ((char-equal other-write ?w) (tramp-octal-to-decimal "00002"))
7510 ((char-equal other-write ?-) 0)
7511 (t (error "Nineth char `%c' must be one of `w-'" other-write)))
7512 (cond
7513 ((char-equal other-execute-or-sticky ?x)
7514 (tramp-octal-to-decimal "00001"))
7515 ((char-equal other-execute-or-sticky ?T)
7516 (tramp-octal-to-decimal "01000"))
7517 ((char-equal other-execute-or-sticky ?t)
7518 (tramp-octal-to-decimal "01001"))
7519 ((char-equal other-execute-or-sticky ?-) 0)
7520 (t (error "Tenth char `%c' must be one of `xtT-'"
7521 other-execute-or-sticky)))))))
7522
7523 (defun tramp-convert-file-attributes (vec attr)
7524 "Convert file-attributes ATTR generated by perl script, stat or ls.
7525 Convert file mode bits to string and set virtual device number.
7526 Return ATTR."
7527 (when attr
7528 ;; Convert last access time.
7529 (unless (listp (nth 4 attr))
7530 (setcar (nthcdr 4 attr)
7531 (list (floor (nth 4 attr) 65536)
7532 (floor (mod (nth 4 attr) 65536)))))
7533 ;; Convert last modification time.
7534 (unless (listp (nth 5 attr))
7535 (setcar (nthcdr 5 attr)
7536 (list (floor (nth 5 attr) 65536)
7537 (floor (mod (nth 5 attr) 65536)))))
7538 ;; Convert last status change time.
7539 (unless (listp (nth 6 attr))
7540 (setcar (nthcdr 6 attr)
7541 (list (floor (nth 6 attr) 65536)
7542 (floor (mod (nth 6 attr) 65536)))))
7543 ;; Convert file size.
7544 (when (< (nth 7 attr) 0)
7545 (setcar (nthcdr 7 attr) -1))
7546 (when (and (floatp (nth 7 attr))
7547 (<= (nth 7 attr) (tramp-compat-most-positive-fixnum)))
7548 (setcar (nthcdr 7 attr) (round (nth 7 attr))))
7549 ;; Convert file mode bits to string.
7550 (unless (stringp (nth 8 attr))
7551 (setcar (nthcdr 8 attr) (tramp-file-mode-from-int (nth 8 attr)))
7552 (when (stringp (car attr))
7553 (aset (nth 8 attr) 0 ?l)))
7554 ;; Convert directory indication bit.
7555 (when (string-match "^d" (nth 8 attr))
7556 (setcar attr t))
7557 ;; Convert symlink from `tramp-do-file-attributes-with-stat'.
7558 (when (consp (car attr))
7559 (if (and (stringp (caar attr))
7560 (string-match ".+ -> .\\(.+\\)." (caar attr)))
7561 (setcar attr (match-string 1 (caar attr)))
7562 (setcar attr nil)))
7563 ;; Set file's gid change bit.
7564 (setcar (nthcdr 9 attr)
7565 (if (numberp (nth 3 attr))
7566 (not (= (nth 3 attr)
7567 (tramp-get-remote-gid vec 'integer)))
7568 (not (string-equal
7569 (nth 3 attr)
7570 (tramp-get-remote-gid vec 'string)))))
7571 ;; Convert inode.
7572 (unless (listp (nth 10 attr))
7573 (setcar (nthcdr 10 attr)
7574 (condition-case nil
7575 (cons (floor (nth 10 attr) 65536)
7576 (floor (mod (nth 10 attr) 65536)))
7577 ;; Inodes can be incredible huge. We must hide this.
7578 (error (tramp-get-inode vec)))))
7579 ;; Set virtual device number.
7580 (setcar (nthcdr 11 attr)
7581 (tramp-get-device vec))
7582 attr))
7583
7584 (defun tramp-check-cached-permissions (vec access)
7585 "Check `file-attributes' caches for VEC.
7586 Return t if according to the cache access type ACCESS is known to
7587 be granted."
7588 (let ((result nil)
7589 (offset (cond
7590 ((eq ?r access) 1)
7591 ((eq ?w access) 2)
7592 ((eq ?x access) 3))))
7593 (dolist (suffix '("string" "integer") result)
7594 (setq
7595 result
7596 (or
7597 result
7598 (let ((file-attr
7599 (tramp-get-file-property
7600 vec (tramp-file-name-localname vec)
7601 (concat "file-attributes-" suffix) nil))
7602 (remote-uid
7603 (tramp-get-connection-property
7604 vec (concat "uid-" suffix) nil))
7605 (remote-gid
7606 (tramp-get-connection-property
7607 vec (concat "gid-" suffix) nil)))
7608 (and
7609 file-attr
7610 (or
7611 ;; Not a symlink
7612 (eq t (car file-attr))
7613 (null (car file-attr)))
7614 (or
7615 ;; World accessible.
7616 (eq access (aref (nth 8 file-attr) (+ offset 6)))
7617 ;; User accessible and owned by user.
7618 (and
7619 (eq access (aref (nth 8 file-attr) offset))
7620 (equal remote-uid (nth 2 file-attr)))
7621 ;; Group accessible and owned by user's
7622 ;; principal group.
7623 (and
7624 (eq access (aref (nth 8 file-attr) (+ offset 3)))
7625 (equal remote-gid (nth 3 file-attr)))))))))))
7626
7627 (defun tramp-get-inode (vec)
7628 "Returns the virtual inode number.
7629 If it doesn't exist, generate a new one."
7630 (let ((string (tramp-make-tramp-file-name
7631 (tramp-file-name-method vec)
7632 (tramp-file-name-user vec)
7633 (tramp-file-name-host vec)
7634 "")))
7635 (unless (assoc string tramp-inodes)
7636 (add-to-list 'tramp-inodes
7637 (list string (length tramp-inodes))))
7638 (nth 1 (assoc string tramp-inodes))))
7639
7640 (defun tramp-get-device (vec)
7641 "Returns the virtual device number.
7642 If it doesn't exist, generate a new one."
7643 (let ((string (tramp-make-tramp-file-name
7644 (tramp-file-name-method vec)
7645 (tramp-file-name-user vec)
7646 (tramp-file-name-host vec)
7647 "")))
7648 (unless (assoc string tramp-devices)
7649 (add-to-list 'tramp-devices
7650 (list string (length tramp-devices))))
7651 (cons -1 (nth 1 (assoc string tramp-devices)))))
7652
7653 (defun tramp-file-mode-from-int (mode)
7654 "Turn an integer representing a file mode into an ls(1)-like string."
7655 (let ((type (cdr (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
7656 (user (logand (lsh mode -6) 7))
7657 (group (logand (lsh mode -3) 7))
7658 (other (logand (lsh mode -0) 7))
7659 (suid (> (logand (lsh mode -9) 4) 0))
7660 (sgid (> (logand (lsh mode -9) 2) 0))
7661 (sticky (> (logand (lsh mode -9) 1) 0)))
7662 (setq user (tramp-file-mode-permissions user suid "s"))
7663 (setq group (tramp-file-mode-permissions group sgid "s"))
7664 (setq other (tramp-file-mode-permissions other sticky "t"))
7665 (concat type user group other)))
7666
7667 (defun tramp-file-mode-permissions (perm suid suid-text)
7668 "Convert a permission bitset into a string.
7669 This is used internally by `tramp-file-mode-from-int'."
7670 (let ((r (> (logand perm 4) 0))
7671 (w (> (logand perm 2) 0))
7672 (x (> (logand perm 1) 0)))
7673 (concat (or (and r "r") "-")
7674 (or (and w "w") "-")
7675 (or (and suid x suid-text) ; suid, execute
7676 (and suid (upcase suid-text)) ; suid, !execute
7677 (and x "x") "-")))) ; !suid
7678
7679 (defun tramp-decimal-to-octal (i)
7680 "Return a string consisting of the octal digits of I.
7681 Not actually used. Use `(format \"%o\" i)' instead?"
7682 (cond ((< i 0) (error "Cannot convert negative number to octal"))
7683 ((not (integerp i)) (error "Cannot convert non-integer to octal"))
7684 ((zerop i) "0")
7685 (t (concat (tramp-decimal-to-octal (/ i 8))
7686 (number-to-string (% i 8))))))
7687
7688 ;; Kudos to Gerd Moellmann for this suggestion.
7689 (defun tramp-octal-to-decimal (ostr)
7690 "Given a string of octal digits, return a decimal number."
7691 (let ((x (or ostr "")))
7692 ;; `save-match' is in `tramp-mode-string-to-int' which calls this.
7693 (unless (string-match "\\`[0-7]*\\'" x)
7694 (error "Non-octal junk in string `%s'" x))
7695 (string-to-number ostr 8)))
7696
7697 (defun tramp-shell-case-fold (string)
7698 "Converts STRING to shell glob pattern which ignores case."
7699 (mapconcat
7700 (lambda (c)
7701 (if (equal (downcase c) (upcase c))
7702 (vector c)
7703 (format "[%c%c]" (downcase c) (upcase c))))
7704 string
7705 ""))
7706
7707
7708 ;; ------------------------------------------------------------
7709 ;; -- Tramp file names --
7710 ;; ------------------------------------------------------------
7711 ;; Conversion functions between external representation and
7712 ;; internal data structure. Convenience functions for internal
7713 ;; data structure.
7714
7715 (defun tramp-file-name-p (vec)
7716 "Check whether VEC is a Tramp object."
7717 (and (vectorp vec) (= 4 (length vec))))
7718
7719 (defun tramp-file-name-method (vec)
7720 "Return method component of VEC."
7721 (and (tramp-file-name-p vec) (aref vec 0)))
7722
7723 (defun tramp-file-name-user (vec)
7724 "Return user component of VEC."
7725 (and (tramp-file-name-p vec) (aref vec 1)))
7726
7727 (defun tramp-file-name-host (vec)
7728 "Return host component of VEC."
7729 (and (tramp-file-name-p vec) (aref vec 2)))
7730
7731 (defun tramp-file-name-localname (vec)
7732 "Return localname component of VEC."
7733 (and (tramp-file-name-p vec) (aref vec 3)))
7734
7735 ;; The user part of a Tramp file name vector can be of kind
7736 ;; "user%domain". Sometimes, we must extract these parts.
7737 (defun tramp-file-name-real-user (vec)
7738 "Return the user name of VEC without domain."
7739 (save-match-data
7740 (let ((user (tramp-file-name-user vec)))
7741 (if (and (stringp user)
7742 (string-match tramp-user-with-domain-regexp user))
7743 (match-string 1 user)
7744 user))))
7745
7746 (defun tramp-file-name-domain (vec)
7747 "Return the domain name of VEC."
7748 (save-match-data
7749 (let ((user (tramp-file-name-user vec)))
7750 (and (stringp user)
7751 (string-match tramp-user-with-domain-regexp user)
7752 (match-string 2 user)))))
7753
7754 ;; The host part of a Tramp file name vector can be of kind
7755 ;; "host#port". Sometimes, we must extract these parts.
7756 (defun tramp-file-name-real-host (vec)
7757 "Return the host name of VEC without port."
7758 (save-match-data
7759 (let ((host (tramp-file-name-host vec)))
7760 (if (and (stringp host)
7761 (string-match tramp-host-with-port-regexp host))
7762 (match-string 1 host)
7763 host))))
7764
7765 (defun tramp-file-name-port (vec)
7766 "Return the port number of VEC."
7767 (save-match-data
7768 (let ((host (tramp-file-name-host vec)))
7769 (and (stringp host)
7770 (string-match tramp-host-with-port-regexp host)
7771 (string-to-number (match-string 2 host))))))
7772
7773 (defun tramp-tramp-file-p (name)
7774 "Return t if NAME is a string with Tramp file name syntax."
7775 (save-match-data
7776 (and (stringp name) (string-match tramp-file-name-regexp name))))
7777
7778 (defun tramp-find-method (method user host)
7779 "Return the right method string to use.
7780 This is METHOD, if non-nil. Otherwise, do a lookup in
7781 `tramp-default-method-alist'."
7782 (or method
7783 (let ((choices tramp-default-method-alist)
7784 lmethod item)
7785 (while choices
7786 (setq item (pop choices))
7787 (when (and (string-match (or (nth 0 item) "") (or host ""))
7788 (string-match (or (nth 1 item) "") (or user "")))
7789 (setq lmethod (nth 2 item))
7790 (setq choices nil)))
7791 lmethod)
7792 tramp-default-method))
7793
7794 (defun tramp-find-user (method user host)
7795 "Return the right user string to use.
7796 This is USER, if non-nil. Otherwise, do a lookup in
7797 `tramp-default-user-alist'."
7798 (or user
7799 (let ((choices tramp-default-user-alist)
7800 luser item)
7801 (while choices
7802 (setq item (pop choices))
7803 (when (and (string-match (or (nth 0 item) "") (or method ""))
7804 (string-match (or (nth 1 item) "") (or host "")))
7805 (setq luser (nth 2 item))
7806 (setq choices nil)))
7807 luser)
7808 tramp-default-user))
7809
7810 (defun tramp-find-host (method user host)
7811 "Return the right host string to use.
7812 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
7813 (or (and (> (length host) 0) host)
7814 tramp-default-host))
7815
7816 (defun tramp-dissect-file-name (name &optional nodefault)
7817 "Return a `tramp-file-name' structure.
7818 The structure consists of remote method, remote user, remote host
7819 and localname (file name on remote host). If NODEFAULT is
7820 non-nil, the file name parts are not expanded to their default
7821 values."
7822 (save-match-data
7823 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
7824 (unless match (error "Not a Tramp file name: %s" name))
7825 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
7826 (user (match-string (nth 2 tramp-file-name-structure) name))
7827 (host (match-string (nth 3 tramp-file-name-structure) name))
7828 (localname (match-string (nth 4 tramp-file-name-structure) name)))
7829 (when (member method '("multi" "multiu"))
7830 (error
7831 "`%s' method is no longer supported, see (info \"(tramp)Multi-hops\")"
7832 method))
7833 (when host
7834 (when (string-match tramp-prefix-ipv6-regexp host)
7835 (setq host (replace-match "" nil t host)))
7836 (when (string-match tramp-postfix-ipv6-regexp host)
7837 (setq host (replace-match "" nil t host))))
7838 (if nodefault
7839 (vector method user host localname)
7840 (vector
7841 (tramp-find-method method user host)
7842 (tramp-find-user method user host)
7843 (tramp-find-host method user host)
7844 localname))))))
7845
7846 (defun tramp-equal-remote (file1 file2)
7847 "Checks, whether the remote parts of FILE1 and FILE2 are identical.
7848 The check depends on method, user and host name of the files. If
7849 one of the components is missing, the default values are used.
7850 The local file name parts of FILE1 and FILE2 are not taken into
7851 account.
7852
7853 Example:
7854
7855 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
7856
7857 would yield `t'. On the other hand, the following check results in nil:
7858
7859 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
7860 (and (stringp (file-remote-p file1))
7861 (stringp (file-remote-p file2))
7862 (string-equal (file-remote-p file1) (file-remote-p file2))))
7863
7864 (defun tramp-make-tramp-file-name (method user host localname)
7865 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME."
7866 (concat tramp-prefix-format
7867 (when (not (zerop (length method)))
7868 (concat method tramp-postfix-method-format))
7869 (when (not (zerop (length user)))
7870 (concat user tramp-postfix-user-format))
7871 (when host
7872 (if (string-match tramp-ipv6-regexp host)
7873 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7874 host))
7875 tramp-postfix-host-format
7876 (when localname localname)))
7877
7878 (defun tramp-completion-make-tramp-file-name (method user host localname)
7879 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
7880 It must not be a complete Tramp file name, but as long as there are
7881 necessary only. This function will be used in file name completion."
7882 (concat tramp-prefix-format
7883 (when (not (zerop (length method)))
7884 (concat method tramp-postfix-method-format))
7885 (when (not (zerop (length user)))
7886 (concat user tramp-postfix-user-format))
7887 (when (not (zerop (length host)))
7888 (concat
7889 (if (string-match tramp-ipv6-regexp host)
7890 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
7891 host)
7892 tramp-postfix-host-format))
7893 (when localname localname)))
7894
7895 (defun tramp-make-copy-program-file-name (vec)
7896 "Create a file name suitable to be passed to `rcp' and workalikes."
7897 (let ((user (tramp-file-name-user vec))
7898 (host (tramp-file-name-real-host vec))
7899 (localname (tramp-shell-quote-argument
7900 (tramp-file-name-localname vec))))
7901 (if (not (zerop (length user)))
7902 (format "%s@%s:%s" user host localname)
7903 (format "%s:%s" host localname))))
7904
7905 (defun tramp-method-out-of-band-p (vec size)
7906 "Return t if this is an out-of-band method, nil otherwise."
7907 (and
7908 ;; It shall be an out-of-band method.
7909 (tramp-get-method-parameter (tramp-file-name-method vec) 'tramp-copy-program)
7910 ;; Either the file size is large enough, or (in rare cases) there
7911 ;; does not exist a remote encoding.
7912 (or (> size tramp-copy-size-limit)
7913 (null (tramp-get-remote-coding vec "remote-encoding")))))
7914
7915 (defun tramp-local-host-p (vec)
7916 "Return t if this points to the local host, nil otherwise."
7917 ;; We cannot use `tramp-file-name-real-host'. A port is an
7918 ;; indication for an ssh tunnel or alike.
7919 (let ((host (tramp-file-name-host vec)))
7920 (and
7921 (stringp host)
7922 (string-match tramp-local-host-regexp host)
7923 ;; The method shall be applied to one of the shell file name
7924 ;; handler. `tramp-local-host-p' is also called for "smb" and
7925 ;; alike, where it must fail.
7926 (tramp-get-method-parameter
7927 (tramp-file-name-method vec) 'tramp-login-program)
7928 ;; The local temp directory must be writable for the other user.
7929 (file-writable-p
7930 (tramp-make-tramp-file-name
7931 (tramp-file-name-method vec)
7932 (tramp-file-name-user vec)
7933 host
7934 (tramp-compat-temporary-file-directory)))
7935 ;; On some systems, chown runs only for root.
7936 (or (zerop (user-uid))
7937 (zerop (tramp-get-remote-uid vec 'integer))))))
7938
7939 ;; Variables local to connection.
7940
7941 (defun tramp-get-remote-path (vec)
7942 (with-connection-property
7943 ;; When `tramp-own-remote-path' is in `tramp-remote-path', we
7944 ;; cache the result for the session only. Otherwise, the result
7945 ;; is cached persistently.
7946 (if (memq 'tramp-own-remote-path tramp-remote-path)
7947 (tramp-get-connection-process vec)
7948 vec)
7949 "remote-path"
7950 (let* ((remote-path (tramp-compat-copy-tree tramp-remote-path))
7951 (elt1 (memq 'tramp-default-remote-path remote-path))
7952 (elt2 (memq 'tramp-own-remote-path remote-path))
7953 (default-remote-path
7954 (when elt1
7955 (condition-case nil
7956 (tramp-send-command-and-read
7957 vec "echo \\\"`getconf PATH`\\\"")
7958 ;; Default if "getconf" is not available.
7959 (error
7960 (tramp-message
7961 vec 3
7962 "`getconf PATH' not successful, using default value \"%s\"."
7963 "/bin:/usr/bin")
7964 "/bin:/usr/bin"))))
7965 (own-remote-path
7966 (when elt2
7967 (condition-case nil
7968 (tramp-send-command-and-read vec "echo \\\"$PATH\\\"")
7969 ;; Default if "getconf" is not available.
7970 (error
7971 (tramp-message
7972 vec 3 "$PATH not set, ignoring `tramp-own-remote-path'.")
7973 nil)))))
7974
7975 ;; Replace place holder `tramp-default-remote-path'.
7976 (when elt1
7977 (setcdr elt1
7978 (append
7979 (tramp-compat-split-string default-remote-path ":")
7980 (cdr elt1)))
7981 (setq remote-path (delq 'tramp-default-remote-path remote-path)))
7982
7983 ;; Replace place holder `tramp-own-remote-path'.
7984 (when elt2
7985 (setcdr elt2
7986 (append
7987 (tramp-compat-split-string own-remote-path ":")
7988 (cdr elt2)))
7989 (setq remote-path (delq 'tramp-own-remote-path remote-path)))
7990
7991 ;; Remove double entries.
7992 (setq elt1 remote-path)
7993 (while (consp elt1)
7994 (while (and (car elt1) (setq elt2 (member (car elt1) (cdr elt1))))
7995 (setcar elt2 nil))
7996 (setq elt1 (cdr elt1)))
7997
7998 ;; Remove non-existing directories.
7999 (delq
8000 nil
8001 (mapcar
8002 (lambda (x)
8003 (and
8004 (stringp x)
8005 (file-directory-p
8006 (tramp-make-tramp-file-name
8007 (tramp-file-name-method vec)
8008 (tramp-file-name-user vec)
8009 (tramp-file-name-host vec)
8010 x))
8011 x))
8012 remote-path)))))
8013
8014 (defun tramp-get-remote-tmpdir (vec)
8015 (with-connection-property vec "tmp-directory"
8016 (let ((dir (tramp-shell-quote-argument "/tmp")))
8017 (if (and (zerop
8018 (tramp-send-command-and-check
8019 vec (format "%s -d %s" (tramp-get-test-command vec) dir)))
8020 (zerop
8021 (tramp-send-command-and-check
8022 vec (format "%s -w %s" (tramp-get-test-command vec) dir))))
8023 dir
8024 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
8025
8026 (defun tramp-get-ls-command (vec)
8027 (with-connection-property vec "ls"
8028 (tramp-message vec 5 "Finding a suitable `ls' command")
8029 (or
8030 (catch 'ls-found
8031 (dolist (cmd '("ls" "gnuls" "gls"))
8032 (let ((dl (tramp-get-remote-path vec))
8033 result)
8034 (while (and dl (setq result (tramp-find-executable vec cmd dl t t)))
8035 ;; Check parameters. On busybox, "ls" output coloring is
8036 ;; enabled by default sometimes. So we try to disable it
8037 ;; when possible. $LS_COLORING is not supported there.
8038 (when (zerop (tramp-send-command-and-check
8039 vec (format "%s -lnd /" result)))
8040 (when (zerop (tramp-send-command-and-check
8041 vec (format "%s --color=never /" result)))
8042 (setq result (concat result " --color=never")))
8043 (throw 'ls-found result))
8044 (setq dl (cdr dl))))))
8045 (tramp-error vec 'file-error "Couldn't find a proper `ls' command"))))
8046
8047 (defun tramp-get-ls-command-with-dired (vec)
8048 (save-match-data
8049 (with-connection-property vec "ls-dired"
8050 (tramp-message vec 5 "Checking, whether `ls --dired' works")
8051 (zerop (tramp-send-command-and-check
8052 vec (format "%s --dired /" (tramp-get-ls-command vec)))))))
8053
8054 (defun tramp-get-test-command (vec)
8055 (with-connection-property vec "test"
8056 (tramp-message vec 5 "Finding a suitable `test' command")
8057 (if (zerop (tramp-send-command-and-check vec "test 0"))
8058 "test"
8059 (tramp-find-executable vec "test" (tramp-get-remote-path vec)))))
8060
8061 (defun tramp-get-test-nt-command (vec)
8062 ;; Does `test A -nt B' work? Use abominable `find' construct if it
8063 ;; doesn't. BSD/OS 4.0 wants the parentheses around the command,
8064 ;; for otherwise the shell crashes.
8065 (with-connection-property vec "test-nt"
8066 (or
8067 (progn
8068 (tramp-send-command
8069 vec (format "( %s / -nt / )" (tramp-get-test-command vec)))
8070 (with-current-buffer (tramp-get-buffer vec)
8071 (goto-char (point-min))
8072 (when (looking-at (regexp-quote tramp-end-of-output))
8073 (format "%s %%s -nt %%s" (tramp-get-test-command vec)))))
8074 (progn
8075 (tramp-send-command
8076 vec
8077 (format
8078 "tramp_test_nt () {\n%s -n \"`find $1 -prune -newer $2 -print`\"\n}"
8079 (tramp-get-test-command vec)))
8080 "tramp_test_nt %s %s"))))
8081
8082 (defun tramp-get-file-exists-command (vec)
8083 (with-connection-property vec "file-exists"
8084 (tramp-message vec 5 "Finding command to check if file exists")
8085 (tramp-find-file-exists-command vec)))
8086
8087 (defun tramp-get-remote-ln (vec)
8088 (with-connection-property vec "ln"
8089 (tramp-message vec 5 "Finding a suitable `ln' command")
8090 (tramp-find-executable vec "ln" (tramp-get-remote-path vec))))
8091
8092 (defun tramp-get-remote-perl (vec)
8093 (with-connection-property vec "perl"
8094 (tramp-message vec 5 "Finding a suitable `perl' command")
8095 (let ((result
8096 (or (tramp-find-executable vec "perl5" (tramp-get-remote-path vec))
8097 (tramp-find-executable
8098 vec "perl" (tramp-get-remote-path vec)))))
8099 ;; We must check also for some Perl modules.
8100 (when result
8101 (with-connection-property vec "perl-file-spec"
8102 (zerop
8103 (tramp-send-command-and-check
8104 vec (format "%s -e 'use File::Spec;'" result))))
8105 (with-connection-property vec "perl-cwd-realpath"
8106 (zerop
8107 (tramp-send-command-and-check
8108 vec (format "%s -e 'use Cwd \"realpath\";'" result)))))
8109 result)))
8110
8111 (defun tramp-get-remote-stat (vec)
8112 (with-connection-property vec "stat"
8113 (tramp-message vec 5 "Finding a suitable `stat' command")
8114 (let ((result (tramp-find-executable
8115 vec "stat" (tramp-get-remote-path vec)))
8116 tmp)
8117 ;; Check whether stat(1) returns usable syntax. %s does not
8118 ;; work on older AIX systems.
8119 (when result
8120 (setq tmp
8121 ;; We don't want to display an error message.
8122 (with-temp-message (or (current-message) "")
8123 (condition-case nil
8124 (tramp-send-command-and-read
8125 vec (format "%s -c '(\"%%N\" %%s)' /" result))
8126 (error nil))))
8127 (unless (and (listp tmp) (stringp (car tmp))
8128 (string-match "^./.$" (car tmp))
8129 (integerp (cadr tmp)))
8130 (setq result nil)))
8131 result)))
8132
8133 (defun tramp-get-remote-readlink (vec)
8134 (with-connection-property vec "readlink"
8135 (tramp-message vec 5 "Finding a suitable `readlink' command")
8136 (let ((result (tramp-find-executable
8137 vec "readlink" (tramp-get-remote-path vec))))
8138 (when (and result
8139 ;; We don't want to display an error message.
8140 (with-temp-message (or (current-message) "")
8141 (condition-case nil
8142 (zerop
8143 (tramp-send-command-and-check
8144 vec (format "%s --canonicalize-missing /" result)))
8145 (error nil))))
8146 result))))
8147
8148 (defun tramp-get-remote-id (vec)
8149 (with-connection-property vec "id"
8150 (tramp-message vec 5 "Finding POSIX `id' command")
8151 (or
8152 (catch 'id-found
8153 (let ((dl (tramp-get-remote-path vec))
8154 result)
8155 (while (and dl (setq result (tramp-find-executable vec "id" dl t t)))
8156 ;; Check POSIX parameter.
8157 (when (zerop (tramp-send-command-and-check
8158 vec (format "%s -u" result)))
8159 (throw 'id-found result))
8160 (setq dl (cdr dl)))))
8161 (tramp-error vec 'file-error "Couldn't find a POSIX `id' command"))))
8162
8163 (defun tramp-get-remote-uid (vec id-format)
8164 (with-connection-property vec (format "uid-%s" id-format)
8165 (let ((res (tramp-send-command-and-read
8166 vec
8167 (format "%s -u%s %s"
8168 (tramp-get-remote-id vec)
8169 (if (equal id-format 'integer) "" "n")
8170 (if (equal id-format 'integer)
8171 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8172 ;; The command might not always return a number.
8173 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8174
8175 (defun tramp-get-remote-gid (vec id-format)
8176 (with-connection-property vec (format "gid-%s" id-format)
8177 (let ((res (tramp-send-command-and-read
8178 vec
8179 (format "%s -g%s %s"
8180 (tramp-get-remote-id vec)
8181 (if (equal id-format 'integer) "" "n")
8182 (if (equal id-format 'integer)
8183 "" "| sed -e s/^/\\\"/ -e s/\$/\\\"/")))))
8184 ;; The command might not always return a number.
8185 (if (and (equal id-format 'integer) (not (integerp res))) -1 res))))
8186
8187 (defun tramp-get-local-uid (id-format)
8188 (if (equal id-format 'integer) (user-uid) (user-login-name)))
8189
8190 (defun tramp-get-local-gid (id-format)
8191 (nth 3 (tramp-compat-file-attributes "~/" id-format)))
8192
8193 ;; Some predefined connection properties.
8194 (defun tramp-get-remote-coding (vec prop)
8195 ;; Local coding handles properties like remote coding. So we could
8196 ;; call it without pain.
8197 (let ((ret (tramp-get-local-coding vec prop)))
8198 ;; The connection property might have been cached. So we must send
8199 ;; the script - maybe.
8200 (when (and ret (symbolp ret))
8201 (let ((name (symbol-name ret)))
8202 (while (string-match (regexp-quote "-") name)
8203 (setq name (replace-match "_" nil t name)))
8204 (tramp-maybe-send-script vec (symbol-value ret) name)
8205 (setq ret name)))
8206 ;; Return the value.
8207 ret))
8208
8209 (defun tramp-get-local-coding (vec prop)
8210 (or
8211 (tramp-get-connection-property vec prop nil)
8212 (progn
8213 (tramp-find-inline-encoding vec)
8214 (tramp-get-connection-property vec prop nil))))
8215
8216 (defun tramp-get-method-parameter (method param)
8217 "Return the method parameter PARAM.
8218 If the `tramp-methods' entry does not exist, return NIL."
8219 (let ((entry (assoc param (assoc method tramp-methods))))
8220 (when entry (cadr entry))))
8221
8222 ;; Auto saving to a special directory.
8223
8224 (defun tramp-exists-file-name-handler (operation &rest args)
8225 "Checks whether OPERATION runs a file name handler."
8226 ;; The file name handler is determined on base of either an
8227 ;; argument, `buffer-file-name', or `default-directory'.
8228 (condition-case nil
8229 (let* ((buffer-file-name "/")
8230 (default-directory "/")
8231 (fnha file-name-handler-alist)
8232 (check-file-name-operation operation)
8233 (file-name-handler-alist
8234 (list
8235 (cons "/"
8236 (lambda (operation &rest args)
8237 "Returns OPERATION if it is the one to be checked."
8238 (if (equal check-file-name-operation operation)
8239 operation
8240 (let ((file-name-handler-alist fnha))
8241 (apply operation args))))))))
8242 (equal (apply operation args) operation))
8243 (error nil)))
8244
8245 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
8246 (defadvice make-auto-save-file-name
8247 (around tramp-advice-make-auto-save-file-name () activate)
8248 "Invoke `tramp-handle-make-auto-save-file-name' for Tramp files."
8249 (if (and (buffer-file-name) (tramp-tramp-file-p (buffer-file-name)))
8250 ;; We cannot call `tramp-handle-make-auto-save-file-name'
8251 ;; directly, because this would bypass the locking mechanism.
8252 (setq ad-return-value
8253 (tramp-file-name-handler 'make-auto-save-file-name))
8254 ad-do-it))
8255 (add-hook
8256 'tramp-unload-hook
8257 (lambda ()
8258 (ad-remove-advice
8259 'make-auto-save-file-name
8260 'around 'tramp-advice-make-auto-save-file-name)
8261 (ad-activate 'make-auto-save-file-name))))
8262
8263 ;; In Emacs < 22 and XEmacs < 21.5 autosaved remote files have
8264 ;; permission 0666 minus umask. This is a security threat.
8265
8266 (defun tramp-set-auto-save-file-modes ()
8267 "Set permissions of autosaved remote files to the original permissions."
8268 (let ((bfn (buffer-file-name)))
8269 (when (and (stringp bfn)
8270 (tramp-tramp-file-p bfn)
8271 (buffer-modified-p)
8272 (stringp buffer-auto-save-file-name)
8273 (not (equal bfn buffer-auto-save-file-name)))
8274 (unless (file-exists-p buffer-auto-save-file-name)
8275 (write-region "" nil buffer-auto-save-file-name))
8276 ;; Permissions should be set always, because there might be an old
8277 ;; auto-saved file belonging to another original file. This could
8278 ;; be a security threat.
8279 (set-file-modes buffer-auto-save-file-name
8280 (or (file-modes bfn) (tramp-octal-to-decimal "0600"))))))
8281
8282 (unless (or (> emacs-major-version 21)
8283 (and (featurep 'xemacs)
8284 (= emacs-major-version 21)
8285 (> emacs-minor-version 4)))
8286 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
8287 (add-hook 'tramp-unload-hook
8288 (lambda ()
8289 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
8290
8291 (defun tramp-subst-strs-in-string (alist string)
8292 "Replace all occurrences of the string FROM with TO in STRING.
8293 ALIST is of the form ((FROM . TO) ...)."
8294 (save-match-data
8295 (while alist
8296 (let* ((pr (car alist))
8297 (from (car pr))
8298 (to (cdr pr)))
8299 (while (string-match (regexp-quote from) string)
8300 (setq string (replace-match to t t string)))
8301 (setq alist (cdr alist))))
8302 string))
8303
8304 ;; ------------------------------------------------------------
8305 ;; -- Compatibility functions section --
8306 ;; ------------------------------------------------------------
8307
8308 (defun tramp-read-passwd (proc &optional prompt)
8309 "Read a password from user (compat function).
8310 Consults the auth-source package.
8311 Invokes `password-read' if available, `read-passwd' else."
8312 (let* ((key (tramp-make-tramp-file-name
8313 tramp-current-method tramp-current-user
8314 tramp-current-host ""))
8315 (pw-prompt
8316 (or prompt
8317 (with-current-buffer (process-buffer proc)
8318 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
8319 (format "%s for %s " (capitalize (match-string 1)) key)))))
8320 (prog1
8321 (or
8322 ;; See if auth-sources contains something useful, if it's bound.
8323 (and (boundp 'auth-sources)
8324 (tramp-get-connection-property proc "first-password-request" nil)
8325 ;; Try with Tramp's current method.
8326 (funcall (symbol-function 'auth-source-user-or-password)
8327 "password" tramp-current-host tramp-current-method))
8328 ;; Try the password cache.
8329 (when (functionp 'password-read)
8330 (unless (tramp-get-connection-property
8331 proc "first-password-request" nil)
8332 (funcall (symbol-function 'password-cache-remove) key))
8333 (let ((password
8334 (funcall (symbol-function 'password-read) pw-prompt key)))
8335 (funcall (symbol-function 'password-cache-add) key password)
8336 password))
8337 ;; Else, get the password interactively.
8338 (read-passwd pw-prompt))
8339 (tramp-set-connection-property proc "first-password-request" nil))))
8340
8341 (defun tramp-clear-passwd (vec)
8342 "Clear password cache for connection related to VEC."
8343 (when (functionp 'password-cache-remove)
8344 (funcall
8345 (symbol-function 'password-cache-remove)
8346 (tramp-make-tramp-file-name
8347 (tramp-file-name-method vec)
8348 (tramp-file-name-user vec)
8349 (tramp-file-name-host vec)
8350 ""))))
8351
8352 ;; Snarfed code from time-date.el and parse-time.el
8353
8354 (defconst tramp-half-a-year '(241 17024)
8355 "Evaluated by \"(days-to-time 183)\".")
8356
8357 (defconst tramp-parse-time-months
8358 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
8359 ("apr" . 4) ("may" . 5) ("jun" . 6)
8360 ("jul" . 7) ("aug" . 8) ("sep" . 9)
8361 ("oct" . 10) ("nov" . 11) ("dec" . 12))
8362 "Alist mapping month names to integers.")
8363
8364 (defun tramp-time-less-p (t1 t2)
8365 "Say whether time value T1 is less than time value T2."
8366 (unless t1 (setq t1 '(0 0)))
8367 (unless t2 (setq t2 '(0 0)))
8368 (or (< (car t1) (car t2))
8369 (and (= (car t1) (car t2))
8370 (< (nth 1 t1) (nth 1 t2)))))
8371
8372 (defun tramp-time-subtract (t1 t2)
8373 "Subtract two time values.
8374 Return the difference in the format of a time value."
8375 (unless t1 (setq t1 '(0 0)))
8376 (unless t2 (setq t2 '(0 0)))
8377 (let ((borrow (< (cadr t1) (cadr t2))))
8378 (list (- (car t1) (car t2) (if borrow 1 0))
8379 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
8380
8381 (defun tramp-time-diff (t1 t2)
8382 "Return the difference between the two times, in seconds.
8383 T1 and T2 are time values (as returned by `current-time' for example)."
8384 ;; Pacify byte-compiler with `symbol-function'.
8385 (cond ((and (fboundp 'subtract-time)
8386 (fboundp 'float-time))
8387 (funcall (symbol-function 'float-time)
8388 (funcall (symbol-function 'subtract-time) t1 t2)))
8389 ((and (fboundp 'subtract-time)
8390 (fboundp 'time-to-seconds))
8391 (funcall (symbol-function 'time-to-seconds)
8392 (funcall (symbol-function 'subtract-time) t1 t2)))
8393 ((fboundp 'itimer-time-difference)
8394 (funcall (symbol-function 'itimer-time-difference)
8395 (if (< (length t1) 3) (append t1 '(0)) t1)
8396 (if (< (length t2) 3) (append t2 '(0)) t2)))
8397 (t
8398 (let ((time (tramp-time-subtract t1 t2)))
8399 (+ (* (car time) 65536.0)
8400 (cadr time)
8401 (/ (or (nth 2 time) 0) 1000000.0))))))
8402
8403 (defun tramp-coding-system-change-eol-conversion (coding-system eol-type)
8404 "Return a coding system like CODING-SYSTEM but with given EOL-TYPE.
8405 EOL-TYPE can be one of `dos', `unix', or `mac'."
8406 (cond ((fboundp 'coding-system-change-eol-conversion)
8407 (funcall (symbol-function 'coding-system-change-eol-conversion)
8408 coding-system eol-type))
8409 ((fboundp 'subsidiary-coding-system)
8410 (funcall (symbol-function 'subsidiary-coding-system)
8411 coding-system
8412 (cond ((eq eol-type 'dos) 'crlf)
8413 ((eq eol-type 'unix) 'lf)
8414 ((eq eol-type 'mac) 'cr)
8415 (t
8416 (error "Unknown EOL-TYPE `%s', must be %s"
8417 eol-type
8418 "`dos', `unix', or `mac'")))))
8419 (t (error "Can't change EOL conversion -- is MULE missing?"))))
8420
8421 (defun tramp-set-process-query-on-exit-flag (process flag)
8422 "Specify if query is needed for process when Emacs is exited.
8423 If the second argument flag is non-nil, Emacs will query the user before
8424 exiting if process is running."
8425 (if (fboundp 'set-process-query-on-exit-flag)
8426 (funcall (symbol-function 'set-process-query-on-exit-flag) process flag)
8427 (funcall (symbol-function 'process-kill-without-query) process flag)))
8428
8429
8430 ;; ------------------------------------------------------------
8431 ;; -- Kludges section --
8432 ;; ------------------------------------------------------------
8433
8434 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
8435 ;; does not deal well with newline characters. Newline is replaced by
8436 ;; backslash newline. But if, say, the string `a backslash newline b'
8437 ;; is passed to a shell, the shell will expand this into "ab",
8438 ;; completely omitting the newline. This is not what was intended.
8439 ;; It does not appear to be possible to make the function
8440 ;; `shell-quote-argument' work with newlines without making it
8441 ;; dependent on the shell used. But within this package, we know that
8442 ;; we will always use a Bourne-like shell, so we use an approach which
8443 ;; groks newlines.
8444 ;;
8445 ;; The approach is simple: we call `shell-quote-argument', then
8446 ;; massage the newline part of the result.
8447 ;;
8448 ;; This function should produce a string which is grokked by a Unix
8449 ;; shell, even if the Emacs is running on Windows. Since this is the
8450 ;; kludges section, we bind `system-type' in such a way that
8451 ;; `shell-quote-arguments' behaves as if on Unix.
8452 ;;
8453 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
8454 ;; function to work with Bourne-like shells.
8455 ;;
8456 ;; CCC: This function should be rewritten so that
8457 ;; `shell-quote-argument' is not used. This way, we are safe from
8458 ;; changes in `shell-quote-argument'.
8459 (defun tramp-shell-quote-argument (s)
8460 "Similar to `shell-quote-argument', but groks newlines.
8461 Only works for Bourne-like shells."
8462 (let ((system-type 'not-windows))
8463 (save-match-data
8464 (let ((result (shell-quote-argument s))
8465 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
8466 (when (and (>= (length result) 2)
8467 (string= (substring result 0 2) "\\~"))
8468 (setq result (substring result 1)))
8469 (while (string-match nl result)
8470 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
8471 t t result)))
8472 result))))
8473
8474 ;; Checklist for `tramp-unload-hook'
8475 ;; - Unload all `tramp-*' packages
8476 ;; - Reset `file-name-handler-alist'
8477 ;; - Cleanup hooks where Tramp functions are in
8478 ;; - Cleanup advised functions
8479 ;; - Cleanup autoloads
8480 ;;;###autoload
8481 (defun tramp-unload-tramp ()
8482 "Discard Tramp from loading remote files."
8483 (interactive)
8484 ;; When Tramp is not loaded yet, its autoloads are still active.
8485 (tramp-unload-file-name-handlers)
8486 ;; ange-ftp settings must be enabled.
8487 (when (functionp 'tramp-ftp-enable-ange-ftp)
8488 (funcall (symbol-function 'tramp-ftp-enable-ange-ftp)))
8489 ;; Maybe its not loaded yet.
8490 (condition-case nil
8491 (unload-feature 'tramp 'force)
8492 (error nil)))
8493
8494 (when (and load-in-progress
8495 (string-match "Loading tramp..." (or (current-message) "")))
8496 (message "Loading tramp...done"))
8497
8498 (provide 'tramp)
8499
8500 ;;; TODO:
8501
8502 ;; * Handle nonlocal exits such as C-g.
8503 ;; * But it would probably be better to use with-local-quit at the
8504 ;; place where it's actually needed: around any potentially
8505 ;; indefinitely blocking piece of code. In this case it would be
8506 ;; within Tramp around one of its calls to accept-process-output (or
8507 ;; around one of the loops that calls accept-process-output)
8508 ;; (Stefan Monnier).
8509 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
8510 ;; `shell-quote-argument'.
8511 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
8512 ;; by the files in that directory. Add this here.
8513 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
8514 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
8515 ;; * Case-insensitive filename completion. (Norbert Goevert.)
8516 ;; * Don't use globbing for directories with many files, as this is
8517 ;; likely to produce long command lines, and some shells choke on
8518 ;; long command lines.
8519 ;; * How to deal with MULE in `insert-file-contents' and `write-region'?
8520 ;; * Test remote ksh or bash for tilde expansion in `tramp-find-shell'?
8521 ;; * abbreviate-file-name
8522 ;; * Better error checking. At least whenever we see something
8523 ;; strange when doing zerop, we should kill the process and start
8524 ;; again. (Greg Stark)
8525 ;; * Remove unneeded parameters from methods.
8526 ;; * Make it work for different encodings, and for different file name
8527 ;; encodings, too. (Daniel Pittman)
8528 ;; * Progress reports while copying files. (Michael Kifer)
8529 ;; * Don't search for perl5 and perl. Instead, only search for perl and
8530 ;; then look if it's the right version (with `perl -v').
8531 ;; * When editing a remote CVS controlled file as a different user, VC
8532 ;; gets confused about the file locking status. Try to find out why
8533 ;; the workaround doesn't work.
8534 ;; * Username and hostname completion.
8535 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
8536 ;; ** Unify `tramp-parse-{rhosts,shosts,sconfig,hosts,passwd,netrc}'.
8537 ;; Code is nearly identical.
8538 ;; * Allow out-of-band methods as _last_ multi-hop. Open a connection
8539 ;; until the last but one hop via `start-file-process'. Apply it
8540 ;; also for ftp and smb.
8541 ;; * WIBNI if we had a command "trampclient"? If I was editing in
8542 ;; some shell with root priviledges, it would be nice if I could
8543 ;; just call
8544 ;; trampclient filename.c
8545 ;; as an editor, and the _current_ shell would connect to an Emacs
8546 ;; server and would be used in an existing non-priviledged Emacs
8547 ;; session for doing the editing in question.
8548 ;; That way, I need not tell Emacs my password again and be afraid
8549 ;; that it makes it into core dumps or other ugly stuff (I had Emacs
8550 ;; once display a just typed password in the context of a keyboard
8551 ;; sequence prompt for a question immediately following in a shell
8552 ;; script run within Emacs -- nasty).
8553 ;; And if I have some ssh session running to a different computer,
8554 ;; having the possibility of passing a local file there to a local
8555 ;; Emacs session (in case I can arrange for a connection back) would
8556 ;; be nice.
8557 ;; Likely the corresponding Tramp server should not allow the
8558 ;; equivalent of the emacsclient -eval option in order to make this
8559 ;; reasonably unproblematic. And maybe trampclient should have some
8560 ;; way of passing credentials, like by using an SSL socket or
8561 ;; something. (David Kastrup)
8562 ;; * Reconnect directly to a compliant shell without first going
8563 ;; through the user's default shell. (Pete Forman)
8564 ;; * Make `tramp-default-user' obsolete.
8565 ;; * How can I interrupt the remote process with a signal
8566 ;; (interrupt-process seems not to work)? (Markus Triska)
8567 ;; * Avoid the local shell entirely for starting remote processes. If
8568 ;; so, I think even a signal, when delivered directly to the local
8569 ;; SSH instance, would correctly be propagated to the remote process
8570 ;; automatically; possibly SSH would have to be started with
8571 ;; "-t". (Markus Triska)
8572 ;; * It makes me wonder if tramp couldn't fall back to ssh when scp
8573 ;; isn't on the remote host. (Mark A. Hershberger)
8574 ;; * Use lsh instead of ssh. (Alfred M. Szmidt)
8575 ;; * Implement a general server-local-variable mechanism, as there are
8576 ;; probably other variables that need different values for different
8577 ;; servers too. The user could then configure a variable (such as
8578 ;; tramp-server-local-variable-alist) to define any such variables
8579 ;; that they need to, which would then be let bound as appropriate
8580 ;; in tramp functions. (Jason Rumney)
8581 ;; * Optimize out-of-band copying, when both methods are scp-like (not
8582 ;; rsync).
8583 ;; * Keep a second connection open for out-of-band methods like scp or
8584 ;; rsync.
8585 ;; * Support ptys in `tramp-handle-start-file-process'.
8586 ;; * IMHO, it's a drawback that currently Tramp doesn't support
8587 ;; Unicode in Dired file names by default. Is it possible to
8588 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
8589 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
8590 ;; expects only English messages? (Juri Linkov)
8591 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
8592 ;; * Do not handle files with drive letter as remote. (Bug#5447)
8593 ;; * Load Tramp subpackages only when needed. (Bug#1529, Bug#5448)
8594 ;; * Try telnet+curl as new method. It might be useful for busybox,
8595 ;; without built-in uuencode/uudecode.
8596
8597 ;; Functions for file-name-handler-alist:
8598 ;; diff-latest-backup-file -- in diff.el
8599
8600 ;; arch-tag: 3a21a994-182b-48fa-b0cd-c1d9fede424a
8601 ;;; tramp.el ends here
8602
8603 ;; Local Variables:
8604 ;; mode: Emacs-Lisp
8605 ;; coding: utf-8
8606 ;; End: