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