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