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