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