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