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