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