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