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