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