Sync with Tramp 2.2.6-pre.
[bpt/emacs.git] / lisp / net / tramp.el
1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
2
3 ;; Copyright (C) 1998-2012 Free Software Foundation, Inc.
4
5 ;; Author: Kai Großjohann <kai.grossjohann@gmx.net>
6 ;; Michael Albinus <michael.albinus@gmx.de>
7 ;; Keywords: comm, processes
8 ;; Package: tramp
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This package provides remote file editing, similar to ange-ftp.
28 ;; The difference is that ange-ftp uses FTP to transfer files between
29 ;; the local and the remote host, whereas tramp.el uses a combination
30 ;; of rsh and rcp or other work-alike programs, such as ssh/scp.
31 ;;
32 ;; For more detailed instructions, please see the info file.
33 ;;
34 ;; Notes:
35 ;; -----
36 ;;
37 ;; This package only works for Emacs 22.1 and higher, and for XEmacs 21.4
38 ;; and higher. For XEmacs 21, you need the package `fsf-compat' for
39 ;; the `with-timeout' macro.
40 ;;
41 ;; Also see the todo list at the bottom of this file.
42 ;;
43 ;; The current version of Tramp can be retrieved from the following URL:
44 ;; http://ftp.gnu.org/gnu/tramp/
45 ;;
46 ;; There's a mailing list for this, as well. Its name is:
47 ;; tramp-devel@gnu.org
48 ;; You can use the Web to subscribe, under the following URL:
49 ;; http://lists.gnu.org/mailman/listinfo/tramp-devel
50 ;;
51 ;; For the adventurous, the current development sources are available
52 ;; via CVS. You can find instructions about this at the following URL:
53 ;; http://savannah.gnu.org/projects/tramp/
54 ;; Click on "CVS" in the navigation bar near the top.
55 ;;
56 ;; Don't forget to put on your asbestos longjohns, first!
57
58 ;;; Code:
59
60 (eval-when-compile (require 'cl)) ; ignore-errors
61 (require 'tramp-compat)
62
63 ;;; User Customizable Internal Variables:
64
65 (defgroup tramp nil
66 "Edit remote files with a combination of ssh, scp, etc."
67 :group 'files
68 :group 'comm
69 :version "22.1")
70
71 ;; Maybe we need once a real Tramp mode, with key bindings etc.
72 ;;;###autoload
73 (defcustom tramp-mode t
74 "Whether Tramp is enabled.
75 If it is set to nil, all remote file names are used literally."
76 :group 'tramp
77 :type 'boolean)
78
79 (defcustom tramp-verbose 3
80 "Verbosity level for Tramp messages.
81 Any level x includes messages for all levels 1 .. x-1. The levels are
82
83 0 silent (no tramp messages at all)
84 1 errors
85 2 warnings
86 3 connection to remote hosts (default level)
87 4 activities
88 5 internal
89 6 sent and received strings
90 7 file caching
91 8 connection properties
92 9 test commands
93 10 traces (huge)."
94 :group 'tramp
95 :type 'integer)
96
97 ;; Emacs case.
98 (eval-and-compile
99 (when (boundp 'backup-directory-alist)
100 (defcustom tramp-backup-directory-alist nil
101 "Alist of filename patterns and backup directory names.
102 Each element looks like (REGEXP . DIRECTORY), with the same meaning like
103 in `backup-directory-alist'. If a Tramp file is backed up, and DIRECTORY
104 is a local file name, the backup directory is prepended with Tramp file
105 name prefix \(method, user, host\) of file.
106
107 \(setq tramp-backup-directory-alist backup-directory-alist\)
108
109 gives the same backup policy for Tramp files on their hosts like the
110 policy for local files."
111 :group 'tramp
112 :type '(repeat (cons (regexp :tag "Regexp matching filename")
113 (directory :tag "Backup directory name"))))))
114
115 ;; XEmacs case. We cannot check for `bkup-backup-directory-info', because
116 ;; the package "backup-dir" might not be loaded yet.
117 (eval-and-compile
118 (when (featurep 'xemacs)
119 (defcustom tramp-bkup-backup-directory-info nil
120 "Alist of (FILE-REGEXP BACKUP-DIR OPTIONS ...))
121 It has the same meaning like `bkup-backup-directory-info' from package
122 `backup-dir'. If a Tramp file is backed up, and BACKUP-DIR is a local
123 file name, the backup directory is prepended with Tramp file name prefix
124 \(method, user, host\) of file.
125
126 \(setq tramp-bkup-backup-directory-info bkup-backup-directory-info\)
127
128 gives the same backup policy for Tramp files on their hosts like the
129 policy for local files."
130 :type '(repeat
131 (list (regexp :tag "File regexp")
132 (string :tag "Backup Dir")
133 (set :inline t
134 (const ok-create)
135 (const full-path)
136 (const prepend-name)
137 (const search-upward))))
138 :group 'tramp)))
139
140 (defcustom tramp-auto-save-directory nil
141 "Put auto-save files in this directory, if set.
142 The idea is to use a local directory so that auto-saving is faster."
143 :group 'tramp
144 :type '(choice (const nil) string))
145
146 (defcustom tramp-encoding-shell
147 (if (memq system-type '(windows-nt))
148 (getenv "COMSPEC")
149 "/bin/sh")
150 "Use this program for encoding and decoding commands on the local host.
151 This shell is used to execute the encoding and decoding command on the
152 local host, so if you want to use `~' in those commands, you should
153 choose a shell here which groks tilde expansion. `/bin/sh' normally
154 does not understand tilde expansion.
155
156 For encoding and decoding, commands like the following are executed:
157
158 /bin/sh -c COMMAND < INPUT > OUTPUT
159
160 This variable can be used to change the \"/bin/sh\" part. See the
161 variable `tramp-encoding-command-switch' for the \"-c\" part.
162
163 If the shell must be forced to be interactive, see
164 `tramp-encoding-command-interactive'.
165
166 Note that this variable is not used for remote commands. There are
167 mechanisms in tramp.el which automatically determine the right shell to
168 use for the remote host."
169 :group 'tramp
170 :type '(file :must-match t))
171
172 (defcustom tramp-encoding-command-switch
173 (if (string-match "cmd\\.exe" tramp-encoding-shell)
174 "/c"
175 "-c")
176 "Use this switch together with `tramp-encoding-shell' for local commands.
177 See the variable `tramp-encoding-shell' for more information."
178 :group 'tramp
179 :type 'string)
180
181 (defcustom tramp-encoding-command-interactive
182 (unless (string-match "cmd\\.exe" tramp-encoding-shell) "-i")
183 "Use this switch together with `tramp-encoding-shell' for interactive shells.
184 See the variable `tramp-encoding-shell' for more information."
185 :version "24.1"
186 :group 'tramp
187 :type '(choice (const nil) string))
188
189 ;;;###tramp-autoload
190 (defvar tramp-methods nil
191 "Alist of methods for remote files.
192 This is a list of entries of the form (NAME PARAM1 PARAM2 ...).
193 Each NAME stands for a remote access method. Each PARAM is a
194 pair of the form (KEY VALUE). The following KEYs are defined:
195 * `tramp-remote-shell'
196 This specifies the shell to use on the remote host. This
197 MUST be a Bourne-like shell. It is normally not necessary to
198 set this to any value other than \"/bin/sh\": Tramp wants to
199 use a shell which groks tilde expansion, but it can search
200 for it. Also note that \"/bin/sh\" exists on all Unixen,
201 this might not be true for the value that you decide to use.
202 You Have Been Warned.
203 * `tramp-remote-shell-args'
204 For implementation of `shell-command', this specifies the
205 arguments to let `tramp-remote-shell' run a single command.
206 * `tramp-login-program'
207 This specifies the name of the program to use for logging in to the
208 remote host. This may be the name of rsh or a workalike program,
209 or the name of telnet or a workalike, or the name of su or a workalike.
210 * `tramp-login-args'
211 This specifies the list of arguments to pass to the above
212 mentioned program. Please note that this is a list of list of arguments,
213 that is, normally you don't want to put \"-a -b\" or \"-f foo\"
214 here. Instead, you want a list (\"-a\" \"-b\"), or (\"-f\" \"foo\").
215 There are some patterns: \"%h\" in this list is replaced by the host
216 name, \"%u\" is replaced by the user name, \"%p\" is replaced by the
217 port number, and \"%%\" can be used to obtain a literal percent character.
218 If a list containing \"%h\", \"%u\" or \"%p\" is unchanged during
219 expansion (i.e. no host or no user specified), this list is not used as
220 argument. By this, arguments like (\"-l\" \"%u\") are optional.
221 \"%t\" is replaced by the temporary file name produced with
222 `tramp-make-tramp-temp-file'. \"%k\" indicates the keep-date
223 parameter of a program, if exists.
224 * `tramp-async-args'
225 When an asynchronous process is started, we know already that
226 the connection works. Therefore, we can pass additional
227 parameters to suppress diagnostic messages, in order not to
228 tamper the process output.
229 * `tramp-copy-program'
230 This specifies the name of the program to use for remotely copying
231 the file; this might be the absolute filename of rcp or the name of
232 a workalike program.
233 * `tramp-copy-args'
234 This specifies the list of parameters to pass to the above mentioned
235 program, the hints for `tramp-login-args' also apply here.
236 * `tramp-copy-keep-date'
237 This specifies whether the copying program when the preserves the
238 timestamp of the original file.
239 * `tramp-copy-keep-tmpfile'
240 This specifies whether a temporary local file shall be kept
241 for optimization reasons (useful for \"rsync\" methods).
242 * `tramp-copy-recursive'
243 Whether the operation copies directories recursively.
244 * `tramp-default-port'
245 The default port of a method is needed in case of gateway connections.
246 Additionally, it is used as indication which method is prepared for
247 passing gateways.
248 * `tramp-gw-args'
249 As the attribute name says, additional arguments are specified here
250 when a method is applied via a gateway.
251 * `tramp-tmpdir'
252 A directory on the remote host for temporary files. If not
253 specified, \"/tmp\" is taken as default.
254
255 What does all this mean? Well, you should specify `tramp-login-program'
256 for all methods; this program is used to log in to the remote site. Then,
257 there are two ways to actually transfer the files between the local and the
258 remote side. One way is using an additional rcp-like program. If you want
259 to do this, set `tramp-copy-program' in the method.
260
261 Another possibility for file transfer is inline transfer, i.e. the
262 file is passed through the same buffer used by `tramp-login-program'. In
263 this case, the file contents need to be protected since the
264 `tramp-login-program' might use escape codes or the connection might not
265 be eight-bit clean. Therefore, file contents are encoded for transit.
266 See the variables `tramp-local-coding-commands' and
267 `tramp-remote-coding-commands' for details.
268
269 So, to summarize: if the method is an out-of-band method, then you
270 must specify `tramp-copy-program' and `tramp-copy-args'. If it is an
271 inline method, then these two parameters should be nil. Methods which
272 are fit for gateways must have `tramp-default-port' at least.
273
274 Notes:
275
276 When using `su' or `sudo' the phrase `open connection to a remote
277 host' sounds strange, but it is used nevertheless, for consistency.
278 No connection is opened to a remote host, but `su' or `sudo' is
279 started on the local host. You should specify a remote host
280 `localhost' or the name of the local host. Another host name is
281 useful only in combination with `tramp-default-proxies-alist'.")
282
283 (defun tramp-detect-ssh-controlmaster ()
284 "Call ssh to detect whether it supports the ControlMaster argument.
285 This function may return nil when the argument is supported, but
286 shouldn't return t when it isn't."
287 (ignore-errors
288 (with-temp-buffer
289 (call-process "ssh" nil t nil "-o" "ControlMaster")
290 (goto-char (point-min))
291 (search-forward-regexp "Missing ControlMaster argument" nil t))))
292
293 (defcustom tramp-default-method
294 ;; An external copy method seems to be preferred, because it performs
295 ;; much better for large files, and it hasn't too serious delays
296 ;; for small files. But it must be ensured that there aren't
297 ;; permanent password queries. Either a password agent like
298 ;; "ssh-agent" or "Pageant" shall run, or the optional
299 ;; password-cache.el or auth-sources.el packages shall be active for
300 ;; password caching. "scpc" is chosen if we detect that the user is
301 ;; running OpenSSH 4.0 or newer.
302 (cond
303 ;; PuTTY is installed. We don't take it, if it is installed on a
304 ;; non-windows system, or pscp from the pssh (parallel ssh) package
305 ;; is found.
306 ((and (eq system-type 'windows-nt)
307 (executable-find "pscp"))
308 (if (or (fboundp 'password-read)
309 (fboundp 'auth-source-user-or-password)
310 (fboundp 'auth-source-search)
311 ;; Pageant is running.
312 (tramp-compat-process-running-p "Pageant"))
313 "pscp"
314 "plink"))
315 ;; There is an ssh installation.
316 ((executable-find "scp")
317 (cond
318 ((tramp-detect-ssh-controlmaster) "scpc")
319 ((or (fboundp 'password-read)
320 (fboundp 'auth-source-user-or-password)
321 (fboundp 'auth-source-search)
322 ;; ssh-agent is running.
323 (getenv "SSH_AUTH_SOCK")
324 (getenv "SSH_AGENT_PID"))
325 "scp")
326 (t "ssh")))
327 ;; Fallback.
328 (t "ftp"))
329 "Default method to use for transferring files.
330 See `tramp-methods' for possibilities.
331 Also see `tramp-default-method-alist'."
332 :group 'tramp
333 :type 'string)
334
335 ;;;###tramp-autoload
336 (defcustom tramp-default-method-alist nil
337 "Default method to use for specific host/user pairs.
338 This is an alist of items (HOST USER METHOD). The first matching item
339 specifies the method to use for a file name which does not specify a
340 method. HOST and USER are regular expressions or nil, which is
341 interpreted as a regular expression which always matches. If no entry
342 matches, the variable `tramp-default-method' takes effect.
343
344 If the file name does not specify the user, lookup is done using the
345 empty string for the user name.
346
347 See `tramp-methods' for a list of possibilities for METHOD."
348 :group 'tramp
349 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
350 (choice :tag "User regexp" regexp sexp)
351 (choice :tag "Method name" string (const nil)))))
352
353 (defcustom tramp-default-user nil
354 "Default user to use for transferring files.
355 It is nil by default; otherwise settings in configuration files like
356 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
357
358 This variable is regarded as obsolete, and will be removed soon."
359 :group 'tramp
360 :type '(choice (const nil) string))
361
362 ;;;###tramp-autoload
363 (defcustom tramp-default-user-alist nil
364 "Default user to use for specific method/host pairs.
365 This is an alist of items (METHOD HOST USER). The first matching item
366 specifies the user to use for a file name which does not specify a
367 user. METHOD and USER are regular expressions or nil, which is
368 interpreted as a regular expression which always matches. If no entry
369 matches, the variable `tramp-default-user' takes effect.
370
371 If the file name does not specify the method, lookup is done using the
372 empty string for the method name."
373 :group 'tramp
374 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
375 (choice :tag " Host regexp" regexp sexp)
376 (choice :tag " User name" string (const nil)))))
377
378 (defcustom tramp-default-host (system-name)
379 "Default host to use for transferring files.
380 Useful for su and sudo methods mostly."
381 :group 'tramp
382 :type 'string)
383
384 (defcustom tramp-default-proxies-alist nil
385 "Route to be followed for specific host/user pairs.
386 This is an alist of items (HOST USER PROXY). The first matching
387 item specifies the proxy to be passed for a file name located on
388 a remote target matching USER@HOST. HOST and USER are regular
389 expressions. PROXY must be a Tramp filename without a localname
390 part. Method and user name on PROXY are optional, which is
391 interpreted with the default values. PROXY can contain the
392 patterns %h and %u, which are replaced by the strings matching
393 HOST or USER, respectively.
394
395 HOST, USER or PROXY could also be Lisp forms, which will be
396 evaluated. The result must be a string or nil, which is
397 interpreted as a regular expression which always matches."
398 :group 'tramp
399 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
400 (choice :tag "User regexp" regexp sexp)
401 (choice :tag " Proxy name" string (const nil)))))
402
403 (defcustom tramp-save-ad-hoc-proxies nil
404 "Whether to save ad-hoc proxies persistently."
405 :group 'tramp
406 :type 'boolean)
407
408 ;;;###tramp-autoload
409 (defconst tramp-local-host-regexp
410 (concat
411 "\\`"
412 (regexp-opt
413 (list "localhost" "localhost6" (system-name) "127\.0\.0\.1" "::1") t)
414 "\\'")
415 "Host names which are regarded as local host.")
416
417 (defvar tramp-completion-function-alist nil
418 "Alist of methods for remote files.
419 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...\).
420 Each NAME stands for a remote access method. Each PAIR is of the form
421 \(FUNCTION FILE\). FUNCTION is responsible to extract user names and host
422 names from FILE for completion. The following predefined FUNCTIONs exists:
423
424 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
425 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
426 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
427 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
428 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
429 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
430 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
431 * `tramp-parse-netrc' for \"~/.netrc\" like files.
432 * `tramp-parse-putty' for PuTTY registered sessions.
433
434 FUNCTION can also be a customer defined function. For more details see
435 the info pages.")
436
437 (defconst tramp-echo-mark-marker "_echo"
438 "String marker to surround echoed commands.")
439
440 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
441 "String length of `tramp-echo-mark-marker'.")
442
443 (defconst tramp-echo-mark
444 (concat tramp-echo-mark-marker
445 (make-string tramp-echo-mark-marker-length ?\b))
446 "String mark to be transmitted around shell commands.
447 Used to separate their echo from the output they produce. This
448 will only be used if we cannot disable remote echo via stty.
449 This string must have no effect on the remote shell except for
450 producing some echo which can later be detected by
451 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
452 followed by an equal number of backspaces to erase them will
453 usually suffice.")
454
455 (defconst tramp-echoed-echo-mark-regexp
456 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
457 tramp-echo-mark-marker tramp-echo-mark-marker-length)
458 "Regexp which matches `tramp-echo-mark' as it gets echoed by
459 the remote shell.")
460
461 (defcustom tramp-local-end-of-line
462 (if (memq system-type '(windows-nt)) "\r\n" "\n")
463 "String used for end of line in local processes."
464 :version "24.1"
465 :group 'tramp
466 :type 'string)
467
468 (defcustom tramp-rsh-end-of-line "\n"
469 "String used for end of line in rsh connections.
470 I don't think this ever needs to be changed, so please tell me about it
471 if you need to change this."
472 :group 'tramp
473 :type 'string)
474
475 (defcustom tramp-login-prompt-regexp
476 ".*ogin\\( .*\\)?: *"
477 "Regexp matching login-like prompts.
478 The regexp should match at end of buffer.
479
480 Sometimes the prompt is reported to look like \"login as:\"."
481 :group 'tramp
482 :type 'regexp)
483
484 (defcustom tramp-shell-prompt-pattern
485 ;; Allow a prompt to start right after a ^M since it indeed would be
486 ;; displayed at the beginning of the line (and Zsh uses it). This
487 ;; regexp works only for GNU Emacs.
488 ;; Allow also [] style prompts. They can appear only during
489 ;; connection initialization; Tramp redefines the prompt afterwards.
490 (concat (if (featurep 'xemacs) "" "\\(?:^\\|\r\\)")
491 "[^]#$%>\n]*#?[]#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
492 "Regexp to match prompts from remote shell.
493 Normally, Tramp expects you to configure `shell-prompt-pattern'
494 correctly, but sometimes it happens that you are connecting to a
495 remote host which sends a different kind of shell prompt. Therefore,
496 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
497 and also things matched by this variable. The default value of this
498 variable is similar to the default value of `shell-prompt-pattern',
499 which should work well in many cases.
500
501 This regexp must match both `tramp-initial-end-of-output' and
502 `tramp-end-of-output'."
503 :group 'tramp
504 :type 'regexp)
505
506 (defcustom tramp-password-prompt-regexp
507 "^.*\\([pP]assword\\|[pP]assphrase\\).*:\^@? *"
508 "Regexp matching password-like prompts.
509 The regexp should match at end of buffer.
510
511 The `sudo' program appears to insert a `^@' character into the prompt."
512 :group 'tramp
513 :type 'regexp)
514
515 (defcustom tramp-wrong-passwd-regexp
516 (concat "^.*"
517 ;; These strings should be on the last line
518 (regexp-opt '("Permission denied"
519 "Login incorrect"
520 "Login Incorrect"
521 "Connection refused"
522 "Connection closed"
523 "Timeout, server not responding."
524 "Sorry, try again."
525 "Name or service not known"
526 "Host key verification failed."
527 "No supported authentication methods left to try!") t)
528 ".*"
529 "\\|"
530 "^.*\\("
531 ;; Here comes a list of regexes, separated by \\|
532 "Received signal [0-9]+"
533 "\\).*")
534 "Regexp matching a `login failed' message.
535 The regexp should match at end of buffer."
536 :group 'tramp
537 :type 'regexp)
538
539 (defcustom tramp-yesno-prompt-regexp
540 (concat
541 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
542 "\\s-*")
543 "Regular expression matching all yes/no queries which need to be confirmed.
544 The confirmation should be done with yes or no.
545 The regexp should match at end of buffer.
546 See also `tramp-yn-prompt-regexp'."
547 :group 'tramp
548 :type 'regexp)
549
550 (defcustom tramp-yn-prompt-regexp
551 (concat
552 (regexp-opt '("Store key in cache? (y/n)"
553 "Update cached key? (y/n, Return cancels connection)") t)
554 "\\s-*")
555 "Regular expression matching all y/n queries which need to be confirmed.
556 The confirmation should be done with y or n.
557 The regexp should match at end of buffer.
558 See also `tramp-yesno-prompt-regexp'."
559 :group 'tramp
560 :type 'regexp)
561
562 (defcustom tramp-terminal-prompt-regexp
563 (concat "\\("
564 "TERM = (.*)"
565 "\\|"
566 "Terminal type\\? \\[.*\\]"
567 "\\)\\s-*")
568 "Regular expression matching all terminal setting prompts.
569 The regexp should match at end of buffer.
570 The answer will be provided by `tramp-action-terminal', which see."
571 :group 'tramp
572 :type 'regexp)
573
574 (defcustom tramp-operation-not-permitted-regexp
575 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
576 (regexp-opt '("Operation not permitted") t))
577 "Regular expression matching keep-date problems in (s)cp operations.
578 Copying has been performed successfully already, so this message can
579 be ignored safely."
580 :group 'tramp
581 :type 'regexp)
582
583 (defcustom tramp-copy-failed-regexp
584 (concat "\\(.+: "
585 (regexp-opt '("Permission denied"
586 "not a regular file"
587 "is a directory"
588 "No such file or directory") t)
589 "\\)\\s-*")
590 "Regular expression matching copy problems in (s)cp operations."
591 :group 'tramp
592 :type 'regexp)
593
594 (defcustom tramp-process-alive-regexp
595 ""
596 "Regular expression indicating a process has finished.
597 In fact this expression is empty by intention, it will be used only to
598 check regularly the status of the associated process.
599 The answer will be provided by `tramp-action-process-alive',
600 `tramp-action-out-of-band', which see."
601 :group 'tramp
602 :type 'regexp)
603
604 (defconst tramp-temp-name-prefix "tramp."
605 "Prefix to use for temporary files.
606 If this is a relative file name (such as \"tramp.\"), it is considered
607 relative to the directory name returned by the function
608 `tramp-compat-temporary-file-directory' (which see). It may also be an
609 absolute file name; don't forget to include a prefix for the filename
610 part, though.")
611
612 (defconst tramp-temp-buffer-name " *tramp temp*"
613 "Buffer name for a temporary buffer.
614 It shall be used in combination with `generate-new-buffer-name'.")
615
616 (defvar tramp-temp-buffer-file-name nil
617 "File name of a persistent local temporary file.
618 Useful for \"rsync\" like methods.")
619 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
620 (put 'tramp-temp-buffer-file-name 'permanent-local t)
621
622 ;; XEmacs is distributed with few Lisp packages. Further packages are
623 ;; installed using EFS. If we use a unified filename format, then
624 ;; Tramp is required in addition to EFS. (But why can't Tramp just
625 ;; disable EFS when Tramp is loaded? Then XEmacs can ship with EFS
626 ;; just like before.) Another reason for using a separate filename
627 ;; syntax on XEmacs is that EFS hooks into XEmacs in many places, but
628 ;; Tramp only knows how to deal with `file-name-handler-alist', not
629 ;; the other places.
630
631 ;; Currently, we have the choice between 'ftp, 'sep, and 'url.
632 ;;;###autoload
633 (defcustom tramp-syntax
634 (if (featurep 'xemacs) 'sep 'ftp)
635 "Tramp filename syntax to be used.
636
637 It can have the following values:
638
639 'ftp -- Ange-FTP respective EFS like syntax (GNU Emacs default)
640 'sep -- Syntax as defined for XEmacs (not available yet for GNU Emacs)
641 'url -- URL-like syntax."
642 :group 'tramp
643 :type (if (featurep 'xemacs)
644 '(choice (const :tag "EFS" ftp)
645 (const :tag "XEmacs" sep)
646 (const :tag "URL" url))
647 '(choice (const :tag "Ange-FTP" ftp)
648 (const :tag "URL" url))))
649
650 (defconst tramp-prefix-format
651 (cond ((equal tramp-syntax 'ftp) "/")
652 ((equal tramp-syntax 'sep) "/[")
653 ((equal tramp-syntax 'url) "/")
654 (t (error "Wrong `tramp-syntax' defined")))
655 "String matching the very beginning of Tramp file names.
656 Used in `tramp-make-tramp-file-name'.")
657
658 (defconst tramp-prefix-regexp
659 (concat "^" (regexp-quote tramp-prefix-format))
660 "Regexp matching the very beginning of Tramp file names.
661 Should always start with \"^\". Derived from `tramp-prefix-format'.")
662
663 (defconst tramp-method-regexp
664 "[a-zA-Z_0-9-]+"
665 "Regexp matching methods identifiers.")
666
667 (defconst tramp-postfix-method-format
668 (cond ((equal tramp-syntax 'ftp) ":")
669 ((equal tramp-syntax 'sep) "/")
670 ((equal tramp-syntax 'url) "://")
671 (t (error "Wrong `tramp-syntax' defined")))
672 "String matching delimiter between method and user or host names.
673 Used in `tramp-make-tramp-file-name'.")
674
675 (defconst tramp-postfix-method-regexp
676 (regexp-quote tramp-postfix-method-format)
677 "Regexp matching delimiter between method and user or host names.
678 Derived from `tramp-postfix-method-format'.")
679
680 (defconst tramp-user-regexp "[^/|: \t]+"
681 "Regexp matching user names.")
682
683 ;;;###tramp-autoload
684 (defconst tramp-prefix-domain-format "%"
685 "String matching delimiter between user and domain names.")
686
687 ;;;###tramp-autoload
688 (defconst tramp-prefix-domain-regexp
689 (regexp-quote tramp-prefix-domain-format)
690 "Regexp matching delimiter between user and domain names.
691 Derived from `tramp-prefix-domain-format'.")
692
693 (defconst tramp-domain-regexp "[-a-zA-Z0-9_.]+"
694 "Regexp matching domain names.")
695
696 (defconst tramp-user-with-domain-regexp
697 (concat "\\(" tramp-user-regexp "\\)"
698 tramp-prefix-domain-regexp
699 "\\(" tramp-domain-regexp "\\)")
700 "Regexp matching user names with domain names.")
701
702 (defconst tramp-postfix-user-format "@"
703 "String matching delimiter between user and host names.
704 Used in `tramp-make-tramp-file-name'.")
705
706 (defconst tramp-postfix-user-regexp
707 (regexp-quote tramp-postfix-user-format)
708 "Regexp matching delimiter between user and host names.
709 Derived from `tramp-postfix-user-format'.")
710
711 (defconst tramp-host-regexp "[a-zA-Z0-9_.-]+"
712 "Regexp matching host names.")
713
714 (defconst tramp-prefix-ipv6-format
715 (cond ((equal tramp-syntax 'ftp) "[")
716 ((equal tramp-syntax 'sep) "")
717 ((equal tramp-syntax 'url) "[")
718 (t (error "Wrong `tramp-syntax' defined")))
719 "String matching left hand side of IPv6 addresses.
720 Used in `tramp-make-tramp-file-name'.")
721
722 (defconst tramp-prefix-ipv6-regexp
723 (regexp-quote tramp-prefix-ipv6-format)
724 "Regexp matching left hand side of IPv6 addresses.
725 Derived from `tramp-prefix-ipv6-format'.")
726
727 ;; The following regexp is a bit sloppy. But it shall serve our
728 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
729 ;; "::ffff:192.168.0.1".
730 (defconst tramp-ipv6-regexp
731 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
732 "Regexp matching IPv6 addresses.")
733
734 (defconst tramp-postfix-ipv6-format
735 (cond ((equal tramp-syntax 'ftp) "]")
736 ((equal tramp-syntax 'sep) "")
737 ((equal tramp-syntax 'url) "]")
738 (t (error "Wrong `tramp-syntax' defined")))
739 "String matching right hand side of IPv6 addresses.
740 Used in `tramp-make-tramp-file-name'.")
741
742 (defconst tramp-postfix-ipv6-regexp
743 (regexp-quote tramp-postfix-ipv6-format)
744 "Regexp matching right hand side of IPv6 addresses.
745 Derived from `tramp-postfix-ipv6-format'.")
746
747 (defconst tramp-prefix-port-format
748 (cond ((equal tramp-syntax 'ftp) "#")
749 ((equal tramp-syntax 'sep) "#")
750 ((equal tramp-syntax 'url) ":")
751 (t (error "Wrong `tramp-syntax' defined")))
752 "String matching delimiter between host names and port numbers.")
753
754 (defconst tramp-prefix-port-regexp
755 (regexp-quote tramp-prefix-port-format)
756 "Regexp matching delimiter between host names and port numbers.
757 Derived from `tramp-prefix-port-format'.")
758
759 (defconst tramp-port-regexp "[0-9]+"
760 "Regexp matching port numbers.")
761
762 (defconst tramp-host-with-port-regexp
763 (concat "\\(" tramp-host-regexp "\\)"
764 tramp-prefix-port-regexp
765 "\\(" tramp-port-regexp "\\)")
766 "Regexp matching host names with port numbers.")
767
768 (defconst tramp-postfix-hop-format "|"
769 "String matching delimiter after ad-hoc hop definitions.")
770
771 (defconst tramp-postfix-hop-regexp
772 (regexp-quote tramp-postfix-hop-format)
773 "Regexp matching delimiter after ad-hoc hop definitions.
774 Derived from `tramp-postfix-hop-format'.")
775
776 (defconst tramp-postfix-host-format
777 (cond ((equal tramp-syntax 'ftp) ":")
778 ((equal tramp-syntax 'sep) "]")
779 ((equal tramp-syntax 'url) "")
780 (t (error "Wrong `tramp-syntax' defined")))
781 "String matching delimiter between host names and localnames.
782 Used in `tramp-make-tramp-file-name'.")
783
784 (defconst tramp-postfix-host-regexp
785 (regexp-quote tramp-postfix-host-format)
786 "Regexp matching delimiter between host names and localnames.
787 Derived from `tramp-postfix-host-format'.")
788
789 (defconst tramp-localname-regexp ".*$"
790 "Regexp matching localnames.")
791
792 ;;; File name format:
793
794 (defconst tramp-remote-file-name-spec-regexp
795 (concat
796 "\\(?:" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
797 "\\(?:" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
798 "\\(" "\\(?:" tramp-host-regexp "\\|"
799 tramp-prefix-ipv6-regexp tramp-ipv6-regexp
800 tramp-postfix-ipv6-regexp "\\)"
801 "\\(?:" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?")
802 "Regular expression matching a Tramp file name between prefix and postfix.")
803
804 (defconst tramp-file-name-structure
805 (list
806 (concat
807 tramp-prefix-regexp
808 "\\(" "\\(?:" tramp-remote-file-name-spec-regexp
809 tramp-postfix-hop-regexp "\\)+" "\\)?"
810 tramp-remote-file-name-spec-regexp tramp-postfix-host-regexp
811 "\\(" tramp-localname-regexp "\\)")
812 5 6 7 8 1)
813 "List of six elements (REGEXP METHOD USER HOST FILE HOP), detailing \
814 the Tramp file name structure.
815
816 The first element REGEXP is a regular expression matching a Tramp file
817 name. The regex should contain parentheses around the method name,
818 the user name, the host name, and the file name parts.
819
820 The second element METHOD is a number, saying which pair of
821 parentheses matches the method name. The third element USER is
822 similar, but for the user name. The fourth element HOST is similar,
823 but for the host name. The fifth element FILE is for the file name.
824 The last element HOP is the ad-hoc hop definition, which could be a
825 cascade of several hops.
826
827 These numbers are passed directly to `match-string', which see. That
828 means the opening parentheses are counted to identify the pair.
829
830 See also `tramp-file-name-regexp'.")
831
832 ;;;###autoload
833 (defconst tramp-file-name-regexp-unified
834 (if (memq system-type '(cygwin windows-nt))
835 "\\`/\\([^[/|:]\\{2,\\}\\|[^/|]\\{2,\\}]\\):"
836 "\\`/\\([^[/|:]+\\|[^/|]+]\\):")
837 "Value for `tramp-file-name-regexp' for unified remoting.
838 Emacs (not XEmacs) uses a unified filename syntax for Ange-FTP and
839 Tramp. See `tramp-file-name-structure' for more explanations.
840
841 On W32 systems, the volume letter must be ignored.")
842
843 ;;;###autoload
844 (defconst tramp-file-name-regexp-separate "\\`/\\[.*\\]"
845 "Value for `tramp-file-name-regexp' for separate remoting.
846 XEmacs uses a separate filename syntax for Tramp and EFS.
847 See `tramp-file-name-structure' for more explanations.")
848
849 ;;;###autoload
850 (defconst tramp-file-name-regexp-url "\\`/[^/|:]+://"
851 "Value for `tramp-file-name-regexp' for URL-like remoting.
852 See `tramp-file-name-structure' for more explanations.")
853
854 ;;;###autoload
855 (defconst tramp-file-name-regexp
856 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
857 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
858 ((equal tramp-syntax 'url) tramp-file-name-regexp-url)
859 (t (error "Wrong `tramp-syntax' defined")))
860 "Regular expression matching file names handled by Tramp.
861 This regexp should match Tramp file names but no other file names.
862 When tramp.el is loaded, this regular expression is prepended to
863 `file-name-handler-alist', and that is searched sequentially. Thus,
864 if the Tramp entry appears rather early in the `file-name-handler-alist'
865 and is a bit too general, then some files might be considered Tramp
866 files which are not really Tramp files.
867
868 Please note that the entry in `file-name-handler-alist' is made when
869 this file \(tramp.el\) is loaded. This means that this variable must be set
870 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
871 updated after changing this variable.
872
873 Also see `tramp-file-name-structure'.")
874
875 ;;;###autoload
876 (defconst tramp-completion-file-name-regexp-unified
877 (if (memq system-type '(cygwin windows-nt))
878 "\\`/[^/]\\{2,\\}\\'" "\\`/[^/]*\\'")
879 "Value for `tramp-completion-file-name-regexp' for unified remoting.
880 GNU Emacs uses a unified filename syntax for Tramp and Ange-FTP.
881 See `tramp-file-name-structure' for more explanations.
882
883 On W32 systems, the volume letter must be ignored.")
884
885 ;;;###autoload
886 (defconst tramp-completion-file-name-regexp-separate
887 "\\`/\\([[][^]]*\\)?\\'"
888 "Value for `tramp-completion-file-name-regexp' for separate remoting.
889 XEmacs uses a separate filename syntax for Tramp and EFS.
890 See `tramp-file-name-structure' for more explanations.")
891
892 ;;;###autoload
893 (defconst tramp-completion-file-name-regexp-url
894 "\\`/[^/:]+\\(:\\(/\\(/[^/]*\\)?\\)?\\)?\\'"
895 "Value for `tramp-completion-file-name-regexp' for URL-like remoting.
896 See `tramp-file-name-structure' for more explanations.")
897
898 ;;;###autoload
899 (defconst tramp-completion-file-name-regexp
900 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
901 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
902 ((equal tramp-syntax 'url) tramp-completion-file-name-regexp-url)
903 (t (error "Wrong `tramp-syntax' defined")))
904 "Regular expression matching file names handled by Tramp completion.
905 This regexp should match partial Tramp file names only.
906
907 Please note that the entry in `file-name-handler-alist' is made when
908 this file (tramp.el) is loaded. This means that this variable must be set
909 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
910 updated after changing this variable.
911
912 Also see `tramp-file-name-structure'.")
913
914 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
915 ;; known to have a bug in `process-send-string'; some ssh connections appear
916 ;; to drop bytes when data is sent too quickly. There is also a connection
917 ;; buffer local variable, which is computed depending on remote host properties
918 ;; when `tramp-chunksize' is zero or nil.
919 (defcustom tramp-chunksize
920 (when (and (not (featurep 'xemacs))
921 (memq system-type '(hpux)))
922 500)
923 ;; Parentheses in docstring starting at beginning of line are escaped.
924 ;; Fontification is messed up when
925 ;; `open-paren-in-column-0-is-defun-start' set to t.
926 "If non-nil, chunksize for sending input to local process.
927 It is necessary only on systems which have a buggy `process-send-string'
928 implementation. The necessity, whether this variable must be set, can be
929 checked via the following code:
930
931 (with-temp-buffer
932 (let* ((user \"xxx\") (host \"yyy\")
933 (init 0) (step 50)
934 (sent init) (received init))
935 (while (= sent received)
936 (setq sent (+ sent step))
937 (erase-buffer)
938 (let ((proc (start-process (buffer-name) (current-buffer)
939 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
940 (when (memq (process-status proc) '(run open))
941 (process-send-string proc (make-string sent ?\\ ))
942 (process-send-eof proc)
943 (process-send-eof proc))
944 (while (not (progn (goto-char (point-min))
945 (re-search-forward \"\\\\w+\" (point-max) t)))
946 (accept-process-output proc 1))
947 (when (memq (process-status proc) '(run open))
948 (setq received (string-to-number (match-string 0)))
949 (delete-process proc)
950 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
951 (sit-for 0))))
952 (if (> sent (+ init step))
953 (message \"You should set `tramp-chunksize' to a maximum of %s\"
954 (- sent step))
955 (message \"Test does not work\")
956 (display-buffer (current-buffer))
957 (sit-for 30))))
958
959 In the Emacs normally running Tramp, evaluate the above code
960 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
961 respectively\). You can do this, for example, by pasting it into
962 the `*scratch*' buffer and then hitting C-j with the cursor after the
963 last closing parenthesis. Note that it works only if you have configured
964 \"ssh\" to run without password query, see ssh-agent\(1\).
965
966 You will see the number of bytes sent successfully to the remote host.
967 If that number exceeds 1000, you can stop the execution by hitting
968 C-g, because your Emacs is likely clean.
969
970 When it is necessary to set `tramp-chunksize', you might consider to
971 use an out-of-the-band method \(like \"scp\"\) instead of an internal one
972 \(like \"ssh\"\), because setting `tramp-chunksize' to non-nil decreases
973 performance.
974
975 If your Emacs is buggy, the code stops and gives you an indication
976 about the value `tramp-chunksize' should be set. Maybe you could just
977 experiment a bit, e.g. changing the values of `init' and `step'
978 in the third line of the code.
979
980 Please raise a bug report via \"M-x tramp-bug\" if your system needs
981 this variable to be set as well."
982 :group 'tramp
983 :type '(choice (const nil) integer))
984
985 ;; Logging in to a remote host normally requires obtaining a pty. But
986 ;; Emacs on MacOS X has process-connection-type set to nil by default,
987 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
988 ;; for an override of the system default.
989 (defcustom tramp-process-connection-type t
990 "Overrides `process-connection-type' for connections from Tramp.
991 Tramp binds process-connection-type to the value given here before
992 opening a connection to a remote host."
993 :group 'tramp
994 :type '(choice (const nil) (const t) (const pty)))
995
996 (defcustom tramp-completion-reread-directory-timeout 10
997 "Defines seconds since last remote command before rereading a directory.
998 A remote directory might have changed its contents. In order to
999 make it visible during file name completion in the minibuffer,
1000 Tramp flushes its cache and rereads the directory contents when
1001 more than `tramp-completion-reread-directory-timeout' seconds
1002 have been gone since last remote command execution. A value of `t'
1003 would require an immediate reread during filename completion, `nil'
1004 means to use always cached values for the directory contents."
1005 :group 'tramp
1006 :type '(choice (const nil) integer))
1007
1008 ;;; Internal Variables:
1009
1010 (defvar tramp-current-method nil
1011 "Connection method for this *tramp* buffer.")
1012
1013 (defvar tramp-current-user nil
1014 "Remote login name for this *tramp* buffer.")
1015
1016 (defvar tramp-current-host nil
1017 "Remote host for this *tramp* buffer.")
1018
1019 ;;;###autoload
1020 (defconst tramp-completion-file-name-handler-alist
1021 '((file-name-all-completions . tramp-completion-handle-file-name-all-completions)
1022 (file-name-completion . tramp-completion-handle-file-name-completion))
1023 "Alist of completion handler functions.
1024 Used for file names matching `tramp-file-name-regexp'. Operations
1025 not mentioned here will be handled by Tramp's file name handler
1026 functions, or the normal Emacs functions.")
1027
1028 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1029 ;;;###tramp-autoload
1030 (defvar tramp-foreign-file-name-handler-alist nil
1031 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1032 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1033 calling HANDLER.")
1034
1035 ;;; Internal functions which must come first:
1036
1037 ;; Conversion functions between external representation and
1038 ;; internal data structure. Convenience functions for internal
1039 ;; data structure.
1040
1041 (defun tramp-get-method-parameter (method param)
1042 "Return the method parameter PARAM.
1043 If the `tramp-methods' entry does not exist, return nil."
1044 (let ((entry (assoc param (assoc method tramp-methods))))
1045 (when entry (cadr entry))))
1046
1047 (defun tramp-file-name-p (vec)
1048 "Check, whether VEC is a Tramp object."
1049 (and (vectorp vec) (= 5 (length vec))))
1050
1051 (defun tramp-file-name-method (vec)
1052 "Return method component of VEC."
1053 (and (tramp-file-name-p vec) (aref vec 0)))
1054
1055 (defun tramp-file-name-user (vec)
1056 "Return user component of VEC."
1057 (and (tramp-file-name-p vec) (aref vec 1)))
1058
1059 (defun tramp-file-name-host (vec)
1060 "Return host component of VEC."
1061 (and (tramp-file-name-p vec) (aref vec 2)))
1062
1063 (defun tramp-file-name-localname (vec)
1064 "Return localname component of VEC."
1065 (and (tramp-file-name-p vec) (aref vec 3)))
1066
1067 (defun tramp-file-name-hop (vec)
1068 "Return hop component of VEC."
1069 (and (tramp-file-name-p vec) (aref vec 4)))
1070
1071 ;; The user part of a Tramp file name vector can be of kind
1072 ;; "user%domain". Sometimes, we must extract these parts.
1073 (defun tramp-file-name-real-user (vec)
1074 "Return the user name of VEC without domain."
1075 (save-match-data
1076 (let ((user (tramp-file-name-user vec)))
1077 (if (and (stringp user)
1078 (string-match tramp-user-with-domain-regexp user))
1079 (match-string 1 user)
1080 user))))
1081
1082 (defun tramp-file-name-domain (vec)
1083 "Return the domain name of VEC."
1084 (save-match-data
1085 (let ((user (tramp-file-name-user vec)))
1086 (and (stringp user)
1087 (string-match tramp-user-with-domain-regexp user)
1088 (match-string 2 user)))))
1089
1090 ;; The host part of a Tramp file name vector can be of kind
1091 ;; "host#port". Sometimes, we must extract these parts.
1092 (defun tramp-file-name-real-host (vec)
1093 "Return the host name of VEC without port."
1094 (save-match-data
1095 (let ((host (tramp-file-name-host vec)))
1096 (if (and (stringp host)
1097 (string-match tramp-host-with-port-regexp host))
1098 (match-string 1 host)
1099 host))))
1100
1101 (defun tramp-file-name-port (vec)
1102 "Return the port number of VEC."
1103 (save-match-data
1104 (let ((method (tramp-file-name-method vec))
1105 (host (tramp-file-name-host vec)))
1106 (or (and (stringp host)
1107 (string-match tramp-host-with-port-regexp host)
1108 (string-to-number (match-string 2 host)))
1109 (tramp-get-method-parameter method 'tramp-default-port)))))
1110
1111 ;;;###tramp-autoload
1112 (defun tramp-tramp-file-p (name)
1113 "Return t if NAME is a string with Tramp file name syntax."
1114 (save-match-data
1115 (and (stringp name) (string-match tramp-file-name-regexp name))))
1116
1117 (defun tramp-find-method (method user host)
1118 "Return the right method string to use.
1119 This is METHOD, if non-nil. Otherwise, do a lookup in
1120 `tramp-default-method-alist'."
1121 (or method
1122 (let ((choices tramp-default-method-alist)
1123 lmethod item)
1124 (while choices
1125 (setq item (pop choices))
1126 (when (and (string-match (or (nth 0 item) "") (or host ""))
1127 (string-match (or (nth 1 item) "") (or user "")))
1128 (setq lmethod (nth 2 item))
1129 (setq choices nil)))
1130 lmethod)
1131 tramp-default-method))
1132
1133 (defun tramp-find-user (method user host)
1134 "Return the right user string to use.
1135 This is USER, if non-nil. Otherwise, do a lookup in
1136 `tramp-default-user-alist'."
1137 (or user
1138 (let ((choices tramp-default-user-alist)
1139 luser item)
1140 (while choices
1141 (setq item (pop choices))
1142 (when (and (string-match (or (nth 0 item) "") (or method ""))
1143 (string-match (or (nth 1 item) "") (or host "")))
1144 (setq luser (nth 2 item))
1145 (setq choices nil)))
1146 luser)
1147 tramp-default-user))
1148
1149 (defun tramp-find-host (method user host)
1150 "Return the right host string to use.
1151 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
1152 (or (and (> (length host) 0) host)
1153 tramp-default-host))
1154
1155 (defun tramp-dissect-file-name (name &optional nodefault)
1156 "Return a `tramp-file-name' structure.
1157 The structure consists of remote method, remote user, remote host
1158 and localname (file name on remote host). If NODEFAULT is
1159 non-nil, the file name parts are not expanded to their default
1160 values."
1161 (save-match-data
1162 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
1163 (unless match (error "Not a Tramp file name: %s" name))
1164 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
1165 (user (match-string (nth 2 tramp-file-name-structure) name))
1166 (host (match-string (nth 3 tramp-file-name-structure) name))
1167 (localname (match-string (nth 4 tramp-file-name-structure) name))
1168 (hop (match-string (nth 5 tramp-file-name-structure) name)))
1169 (when host
1170 (when (string-match tramp-prefix-ipv6-regexp host)
1171 (setq host (replace-match "" nil t host)))
1172 (when (string-match tramp-postfix-ipv6-regexp host)
1173 (setq host (replace-match "" nil t host))))
1174 (if nodefault
1175 (vector method user host localname hop)
1176 (vector
1177 (tramp-find-method method user host)
1178 (tramp-find-user method user host)
1179 (tramp-find-host method user host)
1180 localname hop))))))
1181
1182 (defun tramp-buffer-name (vec)
1183 "A name for the connection buffer VEC."
1184 ;; We must use `tramp-file-name-real-host', because for gateway
1185 ;; methods the default port will be expanded later on, which would
1186 ;; tamper the name.
1187 (let ((method (tramp-file-name-method vec))
1188 (user (tramp-file-name-user vec))
1189 (host (tramp-file-name-real-host vec)))
1190 (if (not (zerop (length user)))
1191 (format "*tramp/%s %s@%s*" method user host)
1192 (format "*tramp/%s %s*" method host))))
1193
1194 (defun tramp-make-tramp-file-name (method user host localname &optional hop)
1195 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1196 When not nil, an optional HOP is prepended."
1197 (concat tramp-prefix-format hop
1198 (when (not (zerop (length method)))
1199 (concat method tramp-postfix-method-format))
1200 (when (not (zerop (length user)))
1201 (concat user tramp-postfix-user-format))
1202 (when host
1203 (if (string-match tramp-ipv6-regexp host)
1204 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1205 host))
1206 tramp-postfix-host-format
1207 (when localname localname)))
1208
1209 (defun tramp-completion-make-tramp-file-name (method user host localname)
1210 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1211 It must not be a complete Tramp file name, but as long as there are
1212 necessary only. This function will be used in file name completion."
1213 (concat tramp-prefix-format
1214 (when (not (zerop (length method)))
1215 (concat method tramp-postfix-method-format))
1216 (when (not (zerop (length user)))
1217 (concat user tramp-postfix-user-format))
1218 (when (not (zerop (length host)))
1219 (concat
1220 (if (string-match tramp-ipv6-regexp host)
1221 (concat
1222 tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1223 host)
1224 tramp-postfix-host-format))
1225 (when localname localname)))
1226
1227 (defun tramp-get-buffer (vec)
1228 "Get the connection buffer to be used for VEC."
1229 (or (get-buffer (tramp-buffer-name vec))
1230 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
1231 (setq buffer-undo-list t)
1232 (setq default-directory
1233 (tramp-make-tramp-file-name
1234 (tramp-file-name-method vec)
1235 (tramp-file-name-user vec)
1236 (tramp-file-name-host vec)
1237 "/"))
1238 (current-buffer))))
1239
1240 (defun tramp-get-connection-buffer (vec)
1241 "Get the connection buffer to be used for VEC.
1242 In case a second asynchronous communication has been started, it is different
1243 from `tramp-get-buffer'."
1244 (or (tramp-get-connection-property vec "process-buffer" nil)
1245 (tramp-get-buffer vec)))
1246
1247 (defun tramp-get-connection-name (vec)
1248 "Get the connection name to be used for VEC.
1249 In case a second asynchronous communication has been started, it is different
1250 from the default one."
1251 (or (tramp-get-connection-property vec "process-name" nil)
1252 (tramp-buffer-name vec)))
1253
1254 (defun tramp-get-connection-process (vec)
1255 "Get the connection process to be used for VEC.
1256 In case a second asynchronous communication has been started, it is different
1257 from the default one."
1258 (get-process (tramp-get-connection-name vec)))
1259
1260 (defun tramp-debug-buffer-name (vec)
1261 "A name for the debug buffer for VEC."
1262 ;; We must use `tramp-file-name-real-host', because for gateway
1263 ;; methods the default port will be expanded later on, which would
1264 ;; tamper the name.
1265 (let ((method (tramp-file-name-method vec))
1266 (user (tramp-file-name-user vec))
1267 (host (tramp-file-name-real-host vec)))
1268 (if (not (zerop (length user)))
1269 (format "*debug tramp/%s %s@%s*" method user host)
1270 (format "*debug tramp/%s %s*" method host))))
1271
1272 (defconst tramp-debug-outline-regexp
1273 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #"
1274 "Used for highlighting Tramp debug buffers in `outline-mode'.")
1275
1276 (defun tramp-debug-outline-level ()
1277 "Return the depth to which a statement is nested in the outline.
1278 Point must be at the beginning of a header line.
1279
1280 The outline level is equal to the verbosity of the Tramp message."
1281 (1+ (string-to-number (match-string 1))))
1282
1283 (defun tramp-get-debug-buffer (vec)
1284 "Get the debug buffer for VEC."
1285 (with-current-buffer
1286 (get-buffer-create (tramp-debug-buffer-name vec))
1287 (when (bobp)
1288 (setq buffer-undo-list t)
1289 ;; Activate `outline-mode'. This runs `text-mode-hook' and
1290 ;; `outline-mode-hook'. We must prevent that local processes
1291 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
1292 ;; Furthermore, `outline-regexp' must have the correct value
1293 ;; already, because it is used by `font-lock-compile-keywords'.
1294 (let ((default-directory (tramp-compat-temporary-file-directory))
1295 (outline-regexp tramp-debug-outline-regexp))
1296 (outline-mode))
1297 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
1298 (set (make-local-variable 'outline-level) 'tramp-debug-outline-level))
1299 (current-buffer)))
1300
1301 (defsubst tramp-debug-message (vec fmt-string &rest args)
1302 "Append message to debug buffer.
1303 Message is formatted with FMT-STRING as control string and the remaining
1304 ARGS to actually emit the message (if applicable)."
1305 (when (get-buffer (tramp-buffer-name vec))
1306 (with-current-buffer (tramp-get-debug-buffer vec)
1307 (goto-char (point-max))
1308 ;; Headline.
1309 (when (bobp)
1310 (insert
1311 (format
1312 ";; %sEmacs: %s Tramp: %s -*- mode: outline; -*-"
1313 (if (featurep 'sxemacs) "SX" (if (featurep 'xemacs) "X" "GNU "))
1314 emacs-version tramp-version)))
1315 (unless (bolp)
1316 (insert "\n"))
1317 ;; Timestamp.
1318 (let ((now (current-time)))
1319 (insert (format-time-string "%T." now))
1320 (insert (format "%06d " (nth 2 now))))
1321 ;; Calling Tramp function. We suppress compat and trace
1322 ;; functions from being displayed.
1323 (let ((btn 1) btf fn)
1324 (while (not fn)
1325 (setq btf (nth 1 (backtrace-frame btn)))
1326 (if (not btf)
1327 (setq fn "")
1328 (when (symbolp btf)
1329 (setq fn (symbol-name btf))
1330 (unless
1331 (and
1332 (string-match "^tramp" fn)
1333 (not
1334 (string-match
1335 (concat
1336 "^"
1337 (regexp-opt
1338 '("tramp-compat-funcall"
1339 "tramp-compat-with-temp-message"
1340 "tramp-debug-message"
1341 "tramp-error"
1342 "tramp-error-with-buffer"
1343 "tramp-message"
1344 "tramp-with-progress-reporter")
1345 t)
1346 "$")
1347 fn)))
1348 (setq fn nil)))
1349 (setq btn (1+ btn))))
1350 ;; The following code inserts filename and line number.
1351 ;; Should be inactive by default, because it is time
1352 ;; consuming.
1353 ; (let ((ffn (find-function-noselect (intern fn))))
1354 ; (insert
1355 ; (format
1356 ; "%s:%d: "
1357 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1358 ; (with-current-buffer (car ffn)
1359 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1360 (insert (format "%s " fn)))
1361 ;; The message.
1362 (insert (apply 'format fmt-string args)))))
1363
1364 (defvar tramp-message-show-message t
1365 "Show Tramp message in the minibuffer.
1366 This variable is used to disable messages from `tramp-error'.
1367 The messages are visible anyway, because an error is raised.")
1368
1369 (defvar tramp-message-show-progress-reporter-message t
1370 "Show Tramp progress reporter message in the minibuffer.
1371 This variable is used to disable recurive progress reporter messages.")
1372
1373 (defsubst tramp-message (vec-or-proc level fmt-string &rest args)
1374 "Emit a message depending on verbosity level.
1375 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1376 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1377 less than LEVEL. The message is emitted only if `tramp-verbose' is
1378 greater than or equal to LEVEL.
1379
1380 The message is also logged into the debug buffer when `tramp-verbose'
1381 is greater than or equal 4.
1382
1383 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1384 control string and the remaining ARGS to actually emit the message (if
1385 applicable)."
1386 (ignore-errors
1387 (when (<= level tramp-verbose)
1388 ;; Match data must be preserved!
1389 (save-match-data
1390 ;; Display only when there is a minimum level.
1391 (when (and tramp-message-show-message (<= level 3))
1392 (apply 'message
1393 (concat
1394 (cond
1395 ((= level 0) "")
1396 ((= level 1) "")
1397 ((= level 2) "Warning: ")
1398 (t "Tramp: "))
1399 fmt-string)
1400 args))
1401 ;; Log only when there is a minimum level.
1402 (when (>= tramp-verbose 4)
1403 (when (and vec-or-proc
1404 (processp vec-or-proc)
1405 (buffer-name (process-buffer vec-or-proc)))
1406 (with-current-buffer (process-buffer vec-or-proc)
1407 ;; Translate proc to vec.
1408 (setq vec-or-proc (tramp-dissect-file-name default-directory))))
1409 (when (and vec-or-proc (vectorp vec-or-proc))
1410 (apply 'tramp-debug-message
1411 vec-or-proc
1412 (concat (format "(%d) # " level) fmt-string)
1413 args)))))))
1414
1415 (defsubst tramp-error (vec-or-proc signal fmt-string &rest args)
1416 "Emit an error.
1417 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1418 signal identifier to be raised, remaining args passed to
1419 `tramp-message'. Finally, signal SIGNAL is raised."
1420 (let (tramp-message-show-message)
1421 (tramp-message
1422 vec-or-proc 1 "%s"
1423 (error-message-string
1424 (list signal
1425 (get signal 'error-message)
1426 (apply 'format fmt-string args))))
1427 (signal signal (list (apply 'format fmt-string args)))))
1428
1429 (defsubst tramp-error-with-buffer
1430 (buffer vec-or-proc signal fmt-string &rest args)
1431 "Emit an error, and show BUFFER.
1432 If BUFFER is nil, show the connection buffer. Wait for 30\", or until
1433 an input event arrives. The other arguments are passed to `tramp-error'."
1434 (save-window-excursion
1435 (unwind-protect
1436 (apply 'tramp-error vec-or-proc signal fmt-string args)
1437 (when (and vec-or-proc
1438 tramp-message-show-message
1439 (not (zerop tramp-verbose))
1440 (not (tramp-completion-mode-p)))
1441 (let ((enable-recursive-minibuffers t))
1442 (pop-to-buffer
1443 (or (and (bufferp buffer) buffer)
1444 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1445 (tramp-get-connection-buffer vec-or-proc)))
1446 (sit-for 30))))))
1447
1448 (defmacro with-parsed-tramp-file-name (filename var &rest body)
1449 "Parse a Tramp filename and make components available in the body.
1450
1451 First arg FILENAME is evaluated and dissected into its components.
1452 Second arg VAR is a symbol. It is used as a variable name to hold
1453 the filename structure. It is also used as a prefix for the variables
1454 holding the components. For example, if VAR is the symbol `foo', then
1455 `foo' will be bound to the whole structure, `foo-method' will be bound to
1456 the method component, and so on for `foo-user', `foo-host', `foo-localname',
1457 `foo-hop'.
1458
1459 Remaining args are Lisp expressions to be evaluated (inside an implicit
1460 `progn').
1461
1462 If VAR is nil, then we bind `v' to the structure and `method', `user',
1463 `host', `localname', `hop' to the components."
1464 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
1465 (,(if var (intern (concat (symbol-name var) "-method")) 'method)
1466 (tramp-file-name-method ,(or var 'v)))
1467 (,(if var (intern (concat (symbol-name var) "-user")) 'user)
1468 (tramp-file-name-user ,(or var 'v)))
1469 (,(if var (intern (concat (symbol-name var) "-host")) 'host)
1470 (tramp-file-name-host ,(or var 'v)))
1471 (,(if var (intern (concat (symbol-name var) "-localname")) 'localname)
1472 (tramp-file-name-localname ,(or var 'v)))
1473 (,(if var (intern (concat (symbol-name var) "-hop")) 'hop)
1474 (tramp-file-name-hop ,(or var 'v))))
1475 ,@body))
1476
1477 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
1478 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
1479 (tramp-compat-font-lock-add-keywords
1480 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
1481
1482 (defun tramp-progress-reporter-update (reporter &optional value)
1483 (let* ((parameters (cdr reporter))
1484 (message (aref parameters 3)))
1485 (when (string-match message (or (current-message) ""))
1486 (tramp-compat-funcall 'progress-reporter-update reporter value))))
1487
1488 (defmacro tramp-with-progress-reporter (vec level message &rest body)
1489 "Executes BODY, spinning a progress reporter with MESSAGE.
1490 If LEVEL does not fit for visible messages, or if this is a
1491 nested call of the macro, there are only traces without a visible
1492 progress reporter."
1493 (declare (indent 3) (debug t))
1494 `(let (pr tm)
1495 (tramp-message ,vec ,level "%s..." ,message)
1496 ;; We start a pulsing progress reporter after 3 seconds. Feature
1497 ;; introduced in Emacs 24.1.
1498 (when (and tramp-message-show-progress-reporter-message
1499 tramp-message-show-message
1500 ;; Display only when there is a minimum level.
1501 (<= ,level (min tramp-verbose 3)))
1502 (ignore-errors
1503 (setq pr (tramp-compat-funcall 'make-progress-reporter ,message)
1504 tm (when pr
1505 (run-at-time 3 0.1 'tramp-progress-reporter-update pr)))))
1506 (unwind-protect
1507 ;; Execute the body. Suppress concurrent progress reporter
1508 ;; messages.
1509 (let ((tramp-message-show-progress-reporter-message
1510 (and tramp-message-show-progress-reporter-message (not tm))))
1511 ,@body)
1512 ;; Stop progress reporter.
1513 (if tm (tramp-compat-funcall 'cancel-timer tm))
1514 (tramp-message ,vec ,level "%s...done" ,message))))
1515
1516 (tramp-compat-font-lock-add-keywords
1517 'emacs-lisp-mode '("\\<tramp-with-progress-reporter\\>"))
1518
1519 (defalias 'tramp-drop-volume-letter
1520 (if (memq system-type '(cygwin windows-nt))
1521 (lambda (name)
1522 "Cut off unnecessary drive letter from file NAME.
1523 The functions `tramp-*-handle-expand-file-name' call `expand-file-name'
1524 locally on a remote file name. When the local system is a W32 system
1525 but the remote system is Unix, this introduces a superfluous drive
1526 letter into the file name. This function removes it."
1527 (save-match-data
1528 (if (string-match "\\`[a-zA-Z]:/" name)
1529 (replace-match "/" nil t name)
1530 name)))
1531
1532 'identity))
1533
1534 (defun tramp-cleanup (vec)
1535 "Cleanup connection VEC, but keep the debug buffer."
1536 (with-current-buffer (tramp-get-debug-buffer vec)
1537 ;; Keep the debug buffer.
1538 (rename-buffer
1539 (generate-new-buffer-name tramp-temp-buffer-name) 'unique)
1540 (tramp-cleanup-connection vec)
1541 (if (= (point-min) (point-max))
1542 (kill-buffer nil)
1543 (rename-buffer (tramp-debug-buffer-name vec) 'unique))
1544 ;; We call `tramp-get-buffer' in order to keep the debug buffer.
1545 (tramp-get-buffer vec)))
1546
1547 ;;; Config Manipulation Functions:
1548
1549 ;;;###tramp-autoload
1550 (defun tramp-set-completion-function (method function-list)
1551 "Sets the list of completion functions for METHOD.
1552 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
1553 The FUNCTION is intended to parse FILE according its syntax.
1554 It might be a predefined FUNCTION, or a user defined FUNCTION.
1555 For the list of predefined FUNCTIONs see `tramp-completion-function-alist'.
1556
1557 Example:
1558
1559 (tramp-set-completion-function
1560 \"ssh\"
1561 '((tramp-parse-sconfig \"/etc/ssh_config\")
1562 (tramp-parse-sconfig \"~/.ssh/config\")))"
1563
1564 (let ((r function-list)
1565 (v function-list))
1566 (setq tramp-completion-function-alist
1567 (delete (assoc method tramp-completion-function-alist)
1568 tramp-completion-function-alist))
1569
1570 (while v
1571 ;; Remove double entries.
1572 (when (member (car v) (cdr v))
1573 (setcdr v (delete (car v) (cdr v))))
1574 ;; Check for function and file or registry key.
1575 (unless (and (functionp (nth 0 (car v)))
1576 (if (string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
1577 ;; Windows registry.
1578 (and (memq system-type '(cygwin windows-nt))
1579 (zerop
1580 (tramp-compat-call-process
1581 "reg" nil nil nil "query" (nth 1 (car v)))))
1582 ;; Configuration file.
1583 (file-exists-p (nth 1 (car v)))))
1584 (setq r (delete (car v) r)))
1585 (setq v (cdr v)))
1586
1587 (when r
1588 (add-to-list 'tramp-completion-function-alist
1589 (cons method r)))))
1590
1591 (defun tramp-get-completion-function (method)
1592 "Returns a list of completion functions for METHOD.
1593 For definition of that list see `tramp-set-completion-function'."
1594 (cons
1595 ;; Hosts visited once shall be remembered.
1596 `(tramp-parse-connection-properties ,method)
1597 ;; The method related defaults.
1598 (cdr (assoc method tramp-completion-function-alist))))
1599
1600
1601 ;;; Fontification of `read-file-name':
1602
1603 ;; rfn-eshadow.el is part of Emacs 22. It is autoloaded.
1604 (defvar tramp-rfn-eshadow-overlay)
1605 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
1606
1607 (defun tramp-rfn-eshadow-setup-minibuffer ()
1608 "Set up a minibuffer for `file-name-shadow-mode'.
1609 Adds another overlay hiding filename parts according to Tramp's
1610 special handling of `substitute-in-file-name'."
1611 (when (symbol-value 'minibuffer-completing-file-name)
1612 (setq tramp-rfn-eshadow-overlay
1613 (tramp-compat-funcall
1614 'make-overlay
1615 (tramp-compat-funcall 'minibuffer-prompt-end)
1616 (tramp-compat-funcall 'minibuffer-prompt-end)))
1617 ;; Copy rfn-eshadow-overlay properties.
1618 (let ((props (tramp-compat-funcall
1619 'overlay-properties (symbol-value 'rfn-eshadow-overlay))))
1620 (while props
1621 ;; The `field' property prevents correct minibuffer
1622 ;; completion; we exclude it.
1623 (if (not (eq (car props) 'field))
1624 (tramp-compat-funcall
1625 'overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))
1626 (pop props) (pop props))))))
1627
1628 (when (boundp 'rfn-eshadow-setup-minibuffer-hook)
1629 (add-hook 'rfn-eshadow-setup-minibuffer-hook
1630 'tramp-rfn-eshadow-setup-minibuffer)
1631 (add-hook 'tramp-unload-hook
1632 (lambda ()
1633 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
1634 'tramp-rfn-eshadow-setup-minibuffer))))
1635
1636 (defconst tramp-rfn-eshadow-update-overlay-regexp
1637 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
1638
1639 (defun tramp-rfn-eshadow-update-overlay ()
1640 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
1641 This is intended to be used as a minibuffer `post-command-hook' for
1642 `file-name-shadow-mode'; the minibuffer should have already
1643 been set up by `rfn-eshadow-setup-minibuffer'."
1644 ;; In remote files name, there is a shadowing just for the local part.
1645 (ignore-errors
1646 (let ((end (or (tramp-compat-funcall
1647 'overlay-end (symbol-value 'rfn-eshadow-overlay))
1648 (tramp-compat-funcall 'minibuffer-prompt-end)))
1649 ;; We do not want to send any remote command.
1650 (non-essential t))
1651 (when
1652 (file-remote-p
1653 (tramp-compat-funcall
1654 'buffer-substring-no-properties end (point-max)))
1655 (save-excursion
1656 (save-restriction
1657 (narrow-to-region
1658 (1+ (or (string-match
1659 tramp-rfn-eshadow-update-overlay-regexp
1660 (buffer-string) end)
1661 end))
1662 (point-max))
1663 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
1664 (rfn-eshadow-update-overlay-hook nil)
1665 file-name-handler-alist)
1666 (tramp-compat-funcall
1667 'move-overlay rfn-eshadow-overlay (point-max) (point-max))
1668 (tramp-compat-funcall 'rfn-eshadow-update-overlay))))))))
1669
1670 (when (boundp 'rfn-eshadow-update-overlay-hook)
1671 (add-hook 'rfn-eshadow-update-overlay-hook
1672 'tramp-rfn-eshadow-update-overlay)
1673 (add-hook 'tramp-unload-hook
1674 (lambda ()
1675 (remove-hook 'rfn-eshadow-update-overlay-hook
1676 'tramp-rfn-eshadow-update-overlay))))
1677
1678 ;; Inodes don't exist for some file systems. Therefore we must
1679 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
1680 ;; applied might be not so efficient (Ange-FTP uses hashes). But
1681 ;; performance isn't the major issue given that file transfer will
1682 ;; take time.
1683 (defvar tramp-inodes 0
1684 "Keeps virtual inodes numbers.")
1685
1686 ;; Devices must distinguish physical file systems. The device numbers
1687 ;; provided by "lstat" aren't unique, because we operate on different hosts.
1688 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
1689 ;; EFS use device number "-1". In order to be different, we use device number
1690 ;; (-1 . x), whereby "x" is unique for a given (method user host).
1691 (defvar tramp-devices 0
1692 "Keeps virtual device numbers.")
1693
1694 (defun tramp-default-file-modes (filename)
1695 "Return file modes of FILENAME as integer.
1696 If the file modes of FILENAME cannot be determined, return the
1697 value of `default-file-modes', without execute permissions."
1698 (or (file-modes filename)
1699 (logand (default-file-modes) (tramp-compat-octal-to-decimal "0666"))))
1700
1701 (defun tramp-replace-environment-variables (filename)
1702 "Replace environment variables in FILENAME.
1703 Return the string with the replaced variables."
1704 (save-match-data
1705 (let ((idx (string-match "$\\(\\w+\\)" filename)))
1706 ;; `$' is coded as `$$'.
1707 (when (and idx
1708 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
1709 (getenv (match-string 1 filename)))
1710 (setq filename
1711 (replace-match
1712 (substitute-in-file-name (match-string 0 filename))
1713 t nil filename)))
1714 filename)))
1715
1716 ;; In XEmacs, electricity is implemented via a key map for ?/ and ?~,
1717 ;; which calls corresponding functions (see minibuf.el).
1718 (when (fboundp 'minibuffer-electric-separator)
1719 (mapc
1720 (lambda (x)
1721 (eval
1722 `(defadvice ,x
1723 (around ,(intern (format "tramp-advice-%s" x)) activate)
1724 "Invoke `substitute-in-file-name' for Tramp files."
1725 (if (and (symbol-value 'minibuffer-electric-file-name-behavior)
1726 (tramp-tramp-file-p (buffer-substring)))
1727 ;; We don't need to handle `last-input-event', because
1728 ;; due to the key map we know it must be ?/ or ?~.
1729 (let ((s (concat (buffer-substring (point-min) (point))
1730 (string last-command-char))))
1731 (delete-region (point-min) (point))
1732 (insert (substitute-in-file-name s))
1733 (setq ad-return-value last-command-char))
1734 ad-do-it)))
1735 (eval
1736 `(add-hook
1737 'tramp-unload-hook
1738 (lambda ()
1739 (ad-remove-advice ',x 'around ',(intern (format "tramp-advice-%s" x)))
1740 (ad-activate ',x)))))
1741
1742 '(minibuffer-electric-separator
1743 minibuffer-electric-tilde)))
1744
1745 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
1746 "Like `find-operation-coding-system' for Tramp filenames.
1747 Tramp's `insert-file-contents' and `write-region' work over
1748 temporary file names. If `file-coding-system-alist' contains an
1749 expression, which matches more than the file name suffix, the
1750 coding system might not be determined. This function repairs it."
1751 (let (result)
1752 (dolist (elt file-coding-system-alist result)
1753 (when (and (consp elt) (string-match (car elt) filename))
1754 ;; We found a matching entry in `file-coding-system-alist'.
1755 ;; So we add a similar entry, but with the temporary file name
1756 ;; as regexp.
1757 (add-to-list
1758 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
1759
1760 ;;;###autoload
1761 (progn (defun tramp-run-real-handler (operation args)
1762 "Invoke normal file name handler for OPERATION.
1763 First arg specifies the OPERATION, second arg is a list of arguments to
1764 pass to the OPERATION."
1765 (let* ((inhibit-file-name-handlers
1766 `(tramp-file-name-handler
1767 tramp-vc-file-name-handler
1768 tramp-completion-file-name-handler
1769 cygwin-mount-name-hook-function
1770 cygwin-mount-map-drive-hook-function
1771 .
1772 ,(and (eq inhibit-file-name-operation operation)
1773 inhibit-file-name-handlers)))
1774 (inhibit-file-name-operation operation))
1775 (apply operation args))))
1776
1777 ;;;###autoload
1778 (progn (defun tramp-completion-run-real-handler (operation args)
1779 "Invoke `tramp-file-name-handler' for OPERATION.
1780 First arg specifies the OPERATION, second arg is a list of arguments to
1781 pass to the OPERATION."
1782 (let* ((inhibit-file-name-handlers
1783 `(tramp-completion-file-name-handler
1784 cygwin-mount-name-hook-function
1785 cygwin-mount-map-drive-hook-function
1786 .
1787 ,(and (eq inhibit-file-name-operation operation)
1788 inhibit-file-name-handlers)))
1789 (inhibit-file-name-operation operation))
1790 (apply operation args))))
1791
1792 ;; We handle here all file primitives. Most of them have the file
1793 ;; name as first parameter; nevertheless we check for them explicitly
1794 ;; in order to be signaled if a new primitive appears. This
1795 ;; scenario is needed because there isn't a way to decide by
1796 ;; syntactical means whether a foreign method must be called. It would
1797 ;; ease the life if `file-name-handler-alist' would support a decision
1798 ;; function as well but regexp only.
1799 (defun tramp-file-name-for-operation (operation &rest args)
1800 "Return file name related to OPERATION file primitive.
1801 ARGS are the arguments OPERATION has been called with."
1802 (cond
1803 ;; FILE resp DIRECTORY.
1804 ((member operation
1805 (list 'access-file 'byte-compiler-base-file-name 'delete-directory
1806 'delete-file 'diff-latest-backup-file 'directory-file-name
1807 'directory-files 'directory-files-and-attributes
1808 'dired-compress-file 'dired-uncache
1809 'file-accessible-directory-p 'file-attributes
1810 'file-directory-p 'file-executable-p 'file-exists-p
1811 'file-local-copy 'file-remote-p 'file-modes
1812 'file-name-as-directory 'file-name-directory
1813 'file-name-nondirectory 'file-name-sans-versions
1814 'file-ownership-preserved-p 'file-readable-p
1815 'file-regular-p 'file-symlink-p 'file-truename
1816 'file-writable-p 'find-backup-file-name 'find-file-noselect
1817 'get-file-buffer 'insert-directory 'insert-file-contents
1818 'load 'make-directory 'make-directory-internal
1819 'set-file-modes 'substitute-in-file-name
1820 'unhandled-file-name-directory 'vc-registered
1821 ;; Emacs 22+ only.
1822 'set-file-times
1823 ;; Emacs 24+ only.
1824 'file-selinux-context 'set-file-selinux-context
1825 ;; XEmacs only.
1826 'abbreviate-file-name 'create-file-buffer
1827 'dired-file-modtime 'dired-make-compressed-filename
1828 'dired-recursive-delete-directory 'dired-set-file-modtime
1829 'dired-shell-unhandle-file-name 'dired-uucode-file
1830 'insert-file-contents-literally 'make-temp-name 'recover-file
1831 'vm-imap-check-mail 'vm-pop-check-mail 'vm-spool-check-mail))
1832 (if (file-name-absolute-p (nth 0 args))
1833 (nth 0 args)
1834 (expand-file-name (nth 0 args))))
1835 ;; FILE DIRECTORY resp FILE1 FILE2.
1836 ((member operation
1837 (list 'add-name-to-file 'copy-file 'expand-file-name
1838 'file-name-all-completions 'file-name-completion
1839 'file-newer-than-file-p 'make-symbolic-link 'rename-file
1840 ;; Emacs 23+ only.
1841 'copy-directory
1842 ;; Emacs 24+ only.
1843 'file-in-directory-p 'file-equal-p
1844 ;; XEmacs only.
1845 'dired-make-relative-symlink
1846 'vm-imap-move-mail 'vm-pop-move-mail 'vm-spool-move-mail))
1847 (save-match-data
1848 (cond
1849 ((string-match tramp-file-name-regexp (nth 0 args)) (nth 0 args))
1850 ((string-match tramp-file-name-regexp (nth 1 args)) (nth 1 args))
1851 (t (buffer-file-name (current-buffer))))))
1852 ;; START END FILE.
1853 ((eq operation 'write-region)
1854 (nth 2 args))
1855 ;; BUFFER.
1856 ((member operation
1857 (list 'set-visited-file-modtime 'verify-visited-file-modtime
1858 ;; Emacs 22+ only.
1859 'make-auto-save-file-name
1860 ;; XEmacs only.
1861 'backup-buffer))
1862 (buffer-file-name
1863 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
1864 ;; COMMAND.
1865 ((member operation
1866 (list ;; not in Emacs 23+.
1867 'dired-call-process
1868 ;; Emacs only.
1869 'shell-command
1870 ;; Emacs 22+ only.
1871 'process-file
1872 ;; Emacs 23+ only.
1873 'start-file-process
1874 ;; XEmacs only.
1875 'dired-print-file 'dired-shell-call-process
1876 ;; nowhere yet.
1877 'executable-find 'start-process
1878 'call-process 'call-process-region))
1879 default-directory)
1880 ;; Unknown file primitive.
1881 (t (error "unknown file I/O primitive: %s" operation))))
1882
1883 (defun tramp-find-foreign-file-name-handler (filename)
1884 "Return foreign file name handler if exists."
1885 (when (tramp-tramp-file-p filename)
1886 (let ((v (tramp-dissect-file-name filename t))
1887 (handler tramp-foreign-file-name-handler-alist)
1888 elt res)
1889 ;; When we are not fully sure that filename completion is safe,
1890 ;; we should not return a handler.
1891 (when (or (tramp-file-name-method v) (tramp-file-name-user v)
1892 (and (tramp-file-name-host v)
1893 (not (member (tramp-file-name-host v)
1894 (mapcar 'car tramp-methods))))
1895 (not (tramp-completion-mode-p)))
1896 (while handler
1897 (setq elt (car handler)
1898 handler (cdr handler))
1899 (when (funcall (car elt) filename)
1900 (setq handler nil
1901 res (cdr elt))))
1902 res))))
1903
1904 ;; Main function.
1905 ;;;###autoload
1906 (defun tramp-file-name-handler (operation &rest args)
1907 "Invoke Tramp file name handler.
1908 Falls back to normal file name handler if no Tramp file name handler exists."
1909 (if tramp-mode
1910 (save-match-data
1911 (let* ((filename
1912 (tramp-replace-environment-variables
1913 (apply 'tramp-file-name-for-operation operation args)))
1914 (completion (tramp-completion-mode-p))
1915 (foreign (tramp-find-foreign-file-name-handler filename)))
1916 (with-parsed-tramp-file-name filename nil
1917 ;; Call the backend function.
1918 (if foreign
1919 (tramp-compat-condition-case-unless-debug err
1920 (let ((sf (symbol-function foreign))
1921 result)
1922 ;; Some packages set the default directory to a
1923 ;; remote path, before respective Tramp packages
1924 ;; are already loaded. This results in
1925 ;; recursive loading. Therefore, we load the
1926 ;; Tramp packages locally.
1927 (when (and (listp sf) (eq (car sf) 'autoload))
1928 (let ((default-directory
1929 (tramp-compat-temporary-file-directory)))
1930 (load (cadr sf) 'noerror 'nomessage)))
1931 ;; If Tramp detects that it shouldn't continue
1932 ;; to work, it throws the `suppress' event. We
1933 ;; try the default handler then.
1934 ;; This could happen for example, when Tramp
1935 ;; tries to open the same connection twice in a
1936 ;; short time frame.
1937 (setq result
1938 (catch 'suppress (apply foreign operation args)))
1939 (if (eq result 'suppress)
1940 (let (tramp-message-show-message)
1941 (tramp-message
1942 v 1 "Suppress received in operation %s"
1943 (append (list operation) args))
1944 (tramp-cleanup v)
1945 (tramp-run-real-handler operation args))
1946 result))
1947
1948 ;; Trace that somebody has interrupted the operation.
1949 ((debug quit)
1950 (let (tramp-message-show-message)
1951 (tramp-message
1952 v 1 "Interrupt received in operation %s"
1953 (append (list operation) args)))
1954 ;; Propagate the quit signal.
1955 (signal (car err) (cdr err)))
1956
1957 ;; When we are in completion mode, some failed
1958 ;; operations shall return at least a default value
1959 ;; in order to give the user a chance to correct the
1960 ;; file name in the minibuffer.
1961 ;; In order to get a full backtrace, one could apply
1962 ;; (setq debug-on-error t debug-on-signal t)
1963 (error
1964 (cond
1965 ((and completion (zerop (length localname))
1966 (memq operation '(file-exists-p file-directory-p)))
1967 t)
1968 ((and completion (zerop (length localname))
1969 (memq operation
1970 '(expand-file-name file-name-as-directory)))
1971 filename)
1972 ;; Propagate the error.
1973 (t (signal (car err) (cdr err))))))
1974
1975 ;; Nothing to do for us.
1976 (tramp-run-real-handler operation args)))))
1977
1978 ;; When `tramp-mode' is not enabled, we don't do anything.
1979 (tramp-run-real-handler operation args)))
1980
1981 ;; In Emacs, there is some concurrency due to timers. If a timer
1982 ;; interrupts Tramp and wishes to use the same connection buffer as
1983 ;; the "main" Emacs, then garbage might occur in the connection
1984 ;; buffer. Therefore, we need to make sure that a timer does not use
1985 ;; the same connection buffer as the "main" Emacs. We implement a
1986 ;; cheap global lock, instead of locking each connection buffer
1987 ;; separately. The global lock is based on two variables,
1988 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
1989 ;; (with setq) to indicate a lock. But Tramp also calls itself during
1990 ;; processing of a single file operation, so we need to allow
1991 ;; recursive calls. That's where the `tramp-locker' variable comes in
1992 ;; -- it is let-bound to t during the execution of the current
1993 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
1994 ;; then we should just proceed because we have been called
1995 ;; recursively. But if `tramp-locker' is nil, then we are a timer
1996 ;; interrupting the "main" Emacs, and then we signal an error.
1997
1998 (defvar tramp-locked nil
1999 "If non-nil, then Tramp is currently busy.
2000 Together with `tramp-locker', this implements a locking mechanism
2001 preventing reentrant calls of Tramp.")
2002
2003 (defvar tramp-locker nil
2004 "If non-nil, then a caller has locked Tramp.
2005 Together with `tramp-locked', this implements a locking mechanism
2006 preventing reentrant calls of Tramp.")
2007
2008 ;;;###autoload
2009 (progn (defun tramp-completion-file-name-handler (operation &rest args)
2010 "Invoke Tramp file name completion handler.
2011 Falls back to normal file name handler if no Tramp file name handler exists."
2012 ;; We bind `directory-sep-char' here for XEmacs on Windows, which
2013 ;; would otherwise use backslash.
2014 (let ((directory-sep-char ?/)
2015 (fn (assoc operation tramp-completion-file-name-handler-alist)))
2016 (if (and
2017 ;; When `tramp-mode' is not enabled, we don't do anything.
2018 fn tramp-mode
2019 ;; For other syntaxes than `sep', the regexp matches many common
2020 ;; situations where the user doesn't actually want to use Tramp.
2021 ;; So to avoid autoloading Tramp after typing just "/s", we
2022 ;; disable this part of the completion, unless the user implicitly
2023 ;; indicated his interest in using a fancier completion system.
2024 (or (eq tramp-syntax 'sep)
2025 (featurep 'tramp) ;; If it's loaded, we may as well use it.
2026 ;; `partial-completion-mode' does not exist in XEmacs.
2027 ;; It is obsoleted with Emacs 24.1.
2028 (and (boundp 'partial-completion-mode)
2029 (symbol-value 'partial-completion-mode))
2030 ;; FIXME: These may have been loaded even if the user never
2031 ;; intended to use them.
2032 (featurep 'ido)
2033 (featurep 'icicles)))
2034 (save-match-data (apply (cdr fn) args))
2035 (tramp-completion-run-real-handler operation args)))))
2036
2037 ;;;###autoload
2038 (progn (defun tramp-register-file-name-handlers ()
2039 "Add Tramp file name handlers to `file-name-handler-alist'."
2040 ;; Remove autoloaded handlers from file name handler alist. Useful,
2041 ;; if `tramp-syntax' has been changed.
2042 (let ((a1 (rassq 'tramp-file-name-handler file-name-handler-alist)))
2043 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
2044 (let ((a1 (rassq
2045 'tramp-completion-file-name-handler file-name-handler-alist)))
2046 (setq file-name-handler-alist (delq a1 file-name-handler-alist)))
2047 ;; Add the handlers.
2048 (add-to-list 'file-name-handler-alist
2049 (cons tramp-file-name-regexp 'tramp-file-name-handler))
2050 (put 'tramp-file-name-handler 'safe-magic t)
2051 (add-to-list 'file-name-handler-alist
2052 (cons tramp-completion-file-name-regexp
2053 'tramp-completion-file-name-handler))
2054 (put 'tramp-completion-file-name-handler 'safe-magic t)
2055 ;; If jka-compr or epa-file are already loaded, move them to the
2056 ;; front of `file-name-handler-alist'.
2057 (dolist (fnh '(epa-file-handler jka-compr-handler))
2058 (let ((entry (rassoc fnh file-name-handler-alist)))
2059 (when entry
2060 (setq file-name-handler-alist
2061 (cons entry (delete entry file-name-handler-alist))))))))
2062
2063 ;; `tramp-file-name-handler' must be registered before evaluation of
2064 ;; site-start and init files, because there might exist remote files
2065 ;; already, f.e. files kept via recentf-mode.
2066 ;;;###autoload
2067 (tramp-register-file-name-handlers)
2068
2069 (defun tramp-exists-file-name-handler (operation &rest args)
2070 "Check, whether OPERATION runs a file name handler."
2071 ;; The file name handler is determined on base of either an
2072 ;; argument, `buffer-file-name', or `default-directory'.
2073 (ignore-errors
2074 (let* ((buffer-file-name "/")
2075 (default-directory "/")
2076 (fnha file-name-handler-alist)
2077 (check-file-name-operation operation)
2078 (file-name-handler-alist
2079 (list
2080 (cons "/"
2081 (lambda (operation &rest args)
2082 "Returns OPERATION if it is the one to be checked."
2083 (if (equal check-file-name-operation operation)
2084 operation
2085 (let ((file-name-handler-alist fnha))
2086 (apply operation args))))))))
2087 (equal (apply operation args) operation))))
2088
2089 ;;;###autoload
2090 (defun tramp-unload-file-name-handlers ()
2091 (setq file-name-handler-alist
2092 (delete (rassoc 'tramp-file-name-handler
2093 file-name-handler-alist)
2094 (delete (rassoc 'tramp-completion-file-name-handler
2095 file-name-handler-alist)
2096 file-name-handler-alist))))
2097
2098 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
2099
2100 ;;; File name handler functions for completion mode:
2101
2102 (defvar tramp-completion-mode nil
2103 "If non-nil, external packages signal that they are in file name completion.
2104
2105 This is necessary, because Tramp uses a heuristic depending on last
2106 input event. This fails when external packages use other characters
2107 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
2108 should never be set globally, the intention is to let-bind it.")
2109
2110 ;; Necessary because `tramp-file-name-regexp-unified' and
2111 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
2112 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
2113 ;; to `tramp-file-name-handler'). Otherwise, it takes
2114 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
2115 ;; risky, because completing a file might require loading other files,
2116 ;; like "~/.netrc", and for them it shouldn't be decided based on that
2117 ;; variable. On the other hand, those files shouldn't have partial
2118 ;; Tramp file name syntax. Maybe another variable should be introduced
2119 ;; overwriting this check in such cases. Or we change Tramp file name
2120 ;; syntax in order to avoid ambiguities, like in XEmacs ...
2121 ;;;###tramp-autoload
2122 (defun tramp-completion-mode-p ()
2123 "Check, whether method / user name / host name completion is active."
2124 (or
2125 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
2126 (and (boundp 'non-essential) (symbol-value 'non-essential))
2127 tramp-completion-mode
2128 ;; Emacs.
2129 (equal last-input-event 'tab)
2130 (and (natnump last-input-event)
2131 (or
2132 ;; ?\t has event-modifier 'control.
2133 (equal last-input-event ?\t)
2134 (and (not (event-modifiers last-input-event))
2135 (or (equal last-input-event ?\?)
2136 (equal last-input-event ?\ )))))
2137 ;; XEmacs.
2138 (and (featurep 'xemacs)
2139 ;; `last-input-event' might be nil.
2140 (not (null last-input-event))
2141 ;; `last-input-event' may have no character approximation.
2142 (tramp-compat-funcall 'event-to-character last-input-event)
2143 (or
2144 ;; ?\t has event-modifier 'control.
2145 (equal
2146 (tramp-compat-funcall 'event-to-character last-input-event) ?\t)
2147 (and (not (event-modifiers last-input-event))
2148 (or (equal
2149 (tramp-compat-funcall 'event-to-character last-input-event)
2150 ?\?)
2151 (equal
2152 (tramp-compat-funcall 'event-to-character last-input-event)
2153 ?\ )))))))
2154
2155 (defun tramp-connectable-p (filename)
2156 "Check, whether it is possible to connect the remote host w/o side-effects.
2157 This is true, if either the remote host is already connected, or if we are
2158 not in completion mode."
2159 (and (tramp-tramp-file-p filename)
2160 (with-parsed-tramp-file-name filename nil
2161 (or (not (tramp-completion-mode-p))
2162 (let ((p (tramp-get-connection-process v)))
2163 (and p (processp p) (memq (process-status p) '(run open))))))))
2164
2165 ;; Method, host name and user name completion.
2166 ;; `tramp-completion-dissect-file-name' returns a list of
2167 ;; tramp-file-name structures. For all of them we return possible completions.
2168 ;;;###autoload
2169 (defun tramp-completion-handle-file-name-all-completions (filename directory)
2170 "Like `file-name-all-completions' for partial Tramp files."
2171
2172 (let ((fullname
2173 (tramp-drop-volume-letter (expand-file-name filename directory)))
2174 hop result result1)
2175
2176 ;; Suppress hop from completion.
2177 (when (string-match
2178 (concat
2179 tramp-prefix-regexp
2180 "\\(" "\\(" tramp-remote-file-name-spec-regexp
2181 tramp-postfix-hop-regexp
2182 "\\)+" "\\)")
2183 fullname)
2184 (setq hop (match-string 1 fullname)
2185 fullname (replace-match "" nil nil fullname 1)))
2186
2187 ;; Possible completion structures.
2188 (dolist (elt (tramp-completion-dissect-file-name fullname))
2189 (let* ((method (tramp-file-name-method elt))
2190 (user (tramp-file-name-user elt))
2191 (host (tramp-file-name-host elt))
2192 (localname (tramp-file-name-localname elt))
2193 (m (tramp-find-method method user host))
2194 (tramp-current-user user) ; see `tramp-parse-passwd'
2195 all-user-hosts)
2196
2197 (unless localname ;; Nothing to complete.
2198
2199 (if (or user host)
2200
2201 ;; Method dependent user / host combinations.
2202 (progn
2203 (mapc
2204 (lambda (x)
2205 (setq all-user-hosts
2206 (append all-user-hosts
2207 (funcall (nth 0 x) (nth 1 x)))))
2208 (tramp-get-completion-function m))
2209
2210 (setq result
2211 (append result
2212 (mapcar
2213 (lambda (x)
2214 (tramp-get-completion-user-host
2215 method user host (nth 0 x) (nth 1 x)))
2216 (delq nil all-user-hosts)))))
2217
2218 ;; Possible methods.
2219 (setq result
2220 (append result (tramp-get-completion-methods m)))))))
2221
2222 ;; Unify list, add hop, remove nil elements.
2223 (dolist (elt result)
2224 (when elt
2225 (string-match tramp-prefix-regexp elt)
2226 (setq elt (replace-match (concat tramp-prefix-format hop) nil nil elt))
2227 (add-to-list
2228 'result1
2229 (substring elt (length (tramp-drop-volume-letter directory))))))
2230
2231 ;; Complete local parts.
2232 (append
2233 result1
2234 (ignore-errors
2235 (apply (if (tramp-connectable-p fullname)
2236 'tramp-completion-run-real-handler
2237 'tramp-run-real-handler)
2238 'file-name-all-completions (list (list filename directory)))))))
2239
2240 ;; Method, host name and user name completion for a file.
2241 ;;;###autoload
2242 (defun tramp-completion-handle-file-name-completion
2243 (filename directory &optional predicate)
2244 "Like `file-name-completion' for Tramp files."
2245 (try-completion
2246 filename
2247 (mapcar 'list (file-name-all-completions filename directory))
2248 (when (and predicate
2249 (tramp-connectable-p (expand-file-name filename directory)))
2250 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2251
2252 ;; I misuse a little bit the tramp-file-name structure in order to handle
2253 ;; completion possibilities for partial methods / user names / host names.
2254 ;; Return value is a list of tramp-file-name structures according to possible
2255 ;; completions. If "localname" is non-nil it means there
2256 ;; shouldn't be a completion anymore.
2257
2258 ;; Expected results:
2259
2260 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
2261 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
2262 ;; [nil "x" nil nil]
2263 ;; ["x" nil nil nil]
2264
2265 ;; "/x:" "/x:y" "/x:y:"
2266 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
2267 ;; "/[x/" "/[x/y"
2268 ;; ["x" nil "" nil] ["x" nil "y" nil]
2269 ;; ["x" "" nil nil] ["x" "y" nil nil]
2270
2271 ;; "/x:y@" "/x:y@z" "/x:y@z:"
2272 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
2273 ;; "/[x/y@" "/[x/y@z"
2274 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
2275 (defun tramp-completion-dissect-file-name (name)
2276 "Returns a list of `tramp-file-name' structures.
2277 They are collected by `tramp-completion-dissect-file-name1'."
2278
2279 (let* ((result)
2280 (x-nil "\\|\\(\\)")
2281 (tramp-completion-ipv6-regexp
2282 (format
2283 "[^%s]*"
2284 (if (zerop (length tramp-postfix-ipv6-format))
2285 tramp-postfix-host-format
2286 tramp-postfix-ipv6-format)))
2287 ;; "/method" "/[method"
2288 (tramp-completion-file-name-structure1
2289 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
2290 1 nil nil nil))
2291 ;; "/user" "/[user"
2292 (tramp-completion-file-name-structure2
2293 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
2294 nil 1 nil nil))
2295 ;; "/host" "/[host"
2296 (tramp-completion-file-name-structure3
2297 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
2298 nil nil 1 nil))
2299 ;; "/[ipv6" "/[ipv6"
2300 (tramp-completion-file-name-structure4
2301 (list (concat tramp-prefix-regexp
2302 tramp-prefix-ipv6-regexp
2303 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2304 nil nil 1 nil))
2305 ;; "/user@host" "/[user@host"
2306 (tramp-completion-file-name-structure5
2307 (list (concat tramp-prefix-regexp
2308 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2309 "\\(" tramp-host-regexp x-nil "\\)$")
2310 nil 1 2 nil))
2311 ;; "/user@[ipv6" "/[user@ipv6"
2312 (tramp-completion-file-name-structure6
2313 (list (concat tramp-prefix-regexp
2314 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2315 tramp-prefix-ipv6-regexp
2316 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2317 nil 1 2 nil))
2318 ;; "/method:user" "/[method/user" "/method://user"
2319 (tramp-completion-file-name-structure7
2320 (list (concat tramp-prefix-regexp
2321 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2322 "\\(" tramp-user-regexp x-nil "\\)$")
2323 1 2 nil nil))
2324 ;; "/method:host" "/[method/host" "/method://host"
2325 (tramp-completion-file-name-structure8
2326 (list (concat tramp-prefix-regexp
2327 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2328 "\\(" tramp-host-regexp x-nil "\\)$")
2329 1 nil 2 nil))
2330 ;; "/method:[ipv6" "/[method/ipv6" "/method://[ipv6"
2331 (tramp-completion-file-name-structure9
2332 (list (concat tramp-prefix-regexp
2333 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2334 tramp-prefix-ipv6-regexp
2335 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2336 1 nil 2 nil))
2337 ;; "/method:user@host" "/[method/user@host" "/method://user@host"
2338 (tramp-completion-file-name-structure10
2339 (list (concat tramp-prefix-regexp
2340 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2341 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2342 "\\(" tramp-host-regexp x-nil "\\)$")
2343 1 2 3 nil))
2344 ;; "/method:user@[ipv6" "/[method/user@ipv6" "/method://user@[ipv6"
2345 (tramp-completion-file-name-structure11
2346 (list (concat tramp-prefix-regexp
2347 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2348 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2349 tramp-prefix-ipv6-regexp
2350 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2351 1 2 3 nil))
2352 ;; "/method: "/method:/"
2353 (tramp-completion-file-name-structure12
2354 (list
2355 (if (equal tramp-syntax 'url)
2356 (concat tramp-prefix-regexp
2357 "\\(" tramp-method-regexp "\\)"
2358 "\\(" (substring tramp-postfix-method-regexp 0 1)
2359 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2360 "\\(" "\\)$")
2361 ;; Should not match if not URL syntax.
2362 (concat tramp-prefix-regexp "/$"))
2363 1 3 nil nil))
2364 ;; "/method: "/method:/"
2365 (tramp-completion-file-name-structure13
2366 (list
2367 (if (equal tramp-syntax 'url)
2368 (concat tramp-prefix-regexp
2369 "\\(" tramp-method-regexp "\\)"
2370 "\\(" (substring tramp-postfix-method-regexp 0 1)
2371 "\\|" (substring tramp-postfix-method-regexp 1 2) "\\)"
2372 "\\(" "\\)$")
2373 ;; Should not match if not URL syntax.
2374 (concat tramp-prefix-regexp "/$"))
2375 1 nil 3 nil)))
2376
2377 (mapc (lambda (structure)
2378 (add-to-list 'result
2379 (tramp-completion-dissect-file-name1 structure name)))
2380 (list
2381 tramp-completion-file-name-structure1
2382 tramp-completion-file-name-structure2
2383 tramp-completion-file-name-structure3
2384 tramp-completion-file-name-structure4
2385 tramp-completion-file-name-structure5
2386 tramp-completion-file-name-structure6
2387 tramp-completion-file-name-structure7
2388 tramp-completion-file-name-structure8
2389 tramp-completion-file-name-structure9
2390 tramp-completion-file-name-structure10
2391 tramp-completion-file-name-structure11
2392 tramp-completion-file-name-structure12
2393 tramp-completion-file-name-structure13
2394 tramp-file-name-structure))
2395
2396 (delq nil result)))
2397
2398 (defun tramp-completion-dissect-file-name1 (structure name)
2399 "Returns a `tramp-file-name' structure matching STRUCTURE.
2400 The structure consists of remote method, remote user,
2401 remote host and localname (filename on remote host)."
2402
2403 (save-match-data
2404 (when (string-match (nth 0 structure) name)
2405 (let ((method (and (nth 1 structure)
2406 (match-string (nth 1 structure) name)))
2407 (user (and (nth 2 structure)
2408 (match-string (nth 2 structure) name)))
2409 (host (and (nth 3 structure)
2410 (match-string (nth 3 structure) name)))
2411 (localname (and (nth 4 structure)
2412 (match-string (nth 4 structure) name))))
2413 (vector method user host localname nil)))))
2414
2415 ;; This function returns all possible method completions, adding the
2416 ;; trailing method delimiter.
2417 (defun tramp-get-completion-methods (partial-method)
2418 "Returns all method completions for PARTIAL-METHOD."
2419 (mapcar
2420 (lambda (method)
2421 (and method
2422 (string-match (concat "^" (regexp-quote partial-method)) method)
2423 (tramp-completion-make-tramp-file-name method nil nil nil)))
2424 (mapcar 'car tramp-methods)))
2425
2426 ;; Compares partial user and host names with possible completions.
2427 (defun tramp-get-completion-user-host
2428 (method partial-user partial-host user host)
2429 "Returns the most expanded string for user and host name completion.
2430 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2431 (cond
2432
2433 ((and partial-user partial-host)
2434 (if (and host
2435 (string-match (concat "^" (regexp-quote partial-host)) host)
2436 (string-equal partial-user (or user partial-user)))
2437 (setq user partial-user)
2438 (setq user nil
2439 host nil)))
2440
2441 (partial-user
2442 (setq host nil)
2443 (unless
2444 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2445 (setq user nil)))
2446
2447 (partial-host
2448 (setq user nil)
2449 (unless
2450 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2451 (setq host nil)))
2452
2453 (t (setq user nil
2454 host nil)))
2455
2456 (unless (zerop (+ (length user) (length host)))
2457 (tramp-completion-make-tramp-file-name method user host nil)))
2458
2459 ;; Generic function.
2460 (defun tramp-parse-group (regexp match-level skip-regexp)
2461 "Return a (user host) tuple allowed to access.
2462 User is always nil."
2463 (let (result)
2464 (when (re-search-forward regexp (point-at-eol) t)
2465 (setq result (list nil (match-string match-level))))
2466 (or
2467 (> (skip-chars-forward skip-regexp) 0)
2468 (forward-line 1))
2469 result))
2470
2471 ;; Generic function.
2472 (defun tramp-parse-file (filename function)
2473 "Return a list of (user host) tuples allowed to access.
2474 User is always nil."
2475 ;; On Windows, there are problems in completion when
2476 ;; `default-directory' is remote.
2477 (let ((default-directory (tramp-compat-temporary-file-directory)))
2478 (when (file-readable-p filename)
2479 (with-temp-buffer
2480 (insert-file-contents filename)
2481 (goto-char (point-min))
2482 (loop while (not (eobp)) collect (funcall function))))))
2483
2484 ;;;###tramp-autoload
2485 (defun tramp-parse-rhosts (filename)
2486 "Return a list of (user host) tuples allowed to access.
2487 Either user or host may be nil."
2488 (tramp-parse-file filename 'tramp-parse-rhosts-group))
2489
2490 (defun tramp-parse-rhosts-group ()
2491 "Return a (user host) tuple allowed to access.
2492 Either user or host may be nil."
2493 (let ((result)
2494 (regexp
2495 (concat
2496 "^\\(" tramp-host-regexp "\\)"
2497 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2498 (when (re-search-forward regexp (point-at-eol) t)
2499 (setq result (append (list (match-string 3) (match-string 1)))))
2500 (forward-line 1)
2501 result))
2502
2503 ;;;###tramp-autoload
2504 (defun tramp-parse-shosts (filename)
2505 "Return a list of (user host) tuples allowed to access.
2506 User is always nil."
2507 (tramp-parse-file filename 'tramp-parse-shosts-group))
2508
2509 (defun tramp-parse-shosts-group ()
2510 "Return a (user host) tuple allowed to access.
2511 User is always nil."
2512 (tramp-parse-group (concat "^\\(" tramp-host-regexp "\\)") 1 ","))
2513
2514 ;;;###tramp-autoload
2515 (defun tramp-parse-sconfig (filename)
2516 "Return a list of (user host) tuples allowed to access.
2517 User is always nil."
2518 (tramp-parse-file filename 'tramp-parse-sconfig-group))
2519
2520 (defun tramp-parse-sconfig-group ()
2521 "Return a (user host) tuple allowed to access.
2522 User is always nil."
2523 (tramp-parse-group
2524 (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)") 1 ","))
2525
2526 ;; Generic function.
2527 (defun tramp-parse-shostkeys-sknownhosts (dirname regexp)
2528 "Return a list of (user host) tuples allowed to access.
2529 User is always nil."
2530 ;; On Windows, there are problems in completion when
2531 ;; `default-directory' is remote.
2532 (let* ((default-directory (tramp-compat-temporary-file-directory))
2533 (files (and (file-directory-p dirname) (directory-files dirname))))
2534 (loop for f in files
2535 when (and (not (string-match "^\\.\\.?$" f)) (string-match regexp f))
2536 collect (list nil (match-string 1 f)))))
2537
2538 ;;;###tramp-autoload
2539 (defun tramp-parse-shostkeys (dirname)
2540 "Return a list of (user host) tuples allowed to access.
2541 User is always nil."
2542 (tramp-parse-shostkeys-sknownhosts
2543 dirname (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$")))
2544
2545 ;;;###tramp-autoload
2546 (defun tramp-parse-sknownhosts (dirname)
2547 "Return a list of (user host) tuples allowed to access.
2548 User is always nil."
2549 (tramp-parse-shostkeys-sknownhosts
2550 dirname
2551 (concat "^\\(" tramp-host-regexp "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$")))
2552
2553 ;;;###tramp-autoload
2554 (defun tramp-parse-hosts (filename)
2555 "Return a list of (user host) tuples allowed to access.
2556 User is always nil."
2557 (tramp-parse-file filename 'tramp-parse-hosts-group))
2558
2559 (defun tramp-parse-hosts-group ()
2560 "Return a (user host) tuple allowed to access.
2561 User is always nil."
2562 (tramp-parse-group
2563 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)") 1 " \t"))
2564
2565 ;; For su-alike methods it would be desirable to return "root@localhost"
2566 ;; as default. Unfortunately, we have no information whether any user name
2567 ;; has been typed already. So we use `tramp-current-user' as indication,
2568 ;; assuming it is set in `tramp-completion-handle-file-name-all-completions'.
2569 ;;;###tramp-autoload
2570 (defun tramp-parse-passwd (filename)
2571 "Return a list of (user host) tuples allowed to access.
2572 Host is always \"localhost\"."
2573 (if (zerop (length tramp-current-user))
2574 '(("root" nil))
2575 (tramp-parse-file filename 'tramp-parse-passwd-group)))
2576
2577 (defun tramp-parse-passwd-group ()
2578 "Return a (user host) tuple allowed to access.
2579 Host is always \"localhost\"."
2580 (let ((result)
2581 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
2582 (when (re-search-forward regexp (point-at-eol) t)
2583 (setq result (list (match-string 1) "localhost")))
2584 (forward-line 1)
2585 result))
2586
2587 ;;;###tramp-autoload
2588 (defun tramp-parse-netrc (filename)
2589 "Return a list of (user host) tuples allowed to access.
2590 User may be nil."
2591 (tramp-parse-file filename 'tramp-parse-netrc-group))
2592
2593 (defun tramp-parse-netrc-group ()
2594 "Return a (user host) tuple allowed to access.
2595 User may be nil."
2596 (let ((result)
2597 (regexp
2598 (concat
2599 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2600 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2601 (when (re-search-forward regexp (point-at-eol) t)
2602 (setq result (list (match-string 3) (match-string 1))))
2603 (forward-line 1)
2604 result))
2605
2606 ;;;###tramp-autoload
2607 (defun tramp-parse-putty (registry-or-dirname)
2608 "Return a list of (user host) tuples allowed to access.
2609 User is always nil."
2610 (if (memq system-type '(windows-nt))
2611 (with-temp-buffer
2612 (when (zerop (tramp-compat-call-process
2613 "reg" nil t nil "query" registry-or-dirname))
2614 (goto-char (point-min))
2615 (loop while (not (eobp)) collect
2616 (tramp-parse-putty-group registry-or-dirname))))
2617 ;; UNIX case.
2618 (tramp-parse-shostkeys-sknownhosts
2619 registry-or-dirname (concat "^\\(" tramp-host-regexp "\\)$"))))
2620
2621 (defun tramp-parse-putty-group (registry)
2622 "Return a (user host) tuple allowed to access.
2623 User is always nil."
2624 (let ((result)
2625 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
2626 (when (re-search-forward regexp (point-at-eol) t)
2627 (setq result (list nil (match-string 1))))
2628 (forward-line 1)
2629 result))
2630
2631 ;;; Common file name handler functions for different backends:
2632
2633 (defvar tramp-handle-file-local-copy-hook nil
2634 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2635
2636 (defvar tramp-handle-write-region-hook nil
2637 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2638
2639 (defun tramp-handle-directory-file-name (directory)
2640 "Like `directory-file-name' for Tramp files."
2641 ;; If localname component of filename is "/", leave it unchanged.
2642 ;; Otherwise, remove any trailing slash from localname component.
2643 ;; Method, host, etc, are unchanged. Does it make sense to try
2644 ;; to avoid parsing the filename?
2645 (with-parsed-tramp-file-name directory nil
2646 (if (and (not (zerop (length localname)))
2647 (eq (aref localname (1- (length localname))) ?/)
2648 (not (string= localname "/")))
2649 (substring directory 0 -1)
2650 directory)))
2651
2652 (defun tramp-handle-directory-files
2653 (directory &optional full match nosort files-only)
2654 "Like `directory-files' for Tramp files."
2655 ;; FILES-ONLY is valid for XEmacs only.
2656 (when (file-directory-p directory)
2657 (setq directory (file-name-as-directory (expand-file-name directory)))
2658 (let ((temp (nreverse (file-name-all-completions "" directory)))
2659 result item)
2660
2661 (while temp
2662 (setq item (directory-file-name (pop temp)))
2663 (when (and (or (null match) (string-match match item))
2664 (or (null files-only)
2665 ;; Files only.
2666 (and (equal files-only t) (file-regular-p item))
2667 ;; Directories only.
2668 (file-directory-p item)))
2669 (push (if full (concat directory item) item)
2670 result)))
2671 (if nosort result (sort result 'string<)))))
2672
2673 (defun tramp-handle-directory-files-and-attributes
2674 (directory &optional full match nosort id-format)
2675 "Like `directory-files-and-attributes' for Tramp files."
2676 (mapcar
2677 (lambda (x)
2678 (cons x (tramp-compat-file-attributes
2679 (if full x (expand-file-name x directory)) id-format)))
2680 (directory-files directory full match nosort)))
2681
2682 (defun tramp-handle-dired-uncache (dir &optional dir-p)
2683 "Like `dired-uncache' for Tramp files."
2684 ;; DIR-P is valid for XEmacs only.
2685 (with-parsed-tramp-file-name
2686 (if (or dir-p (file-directory-p dir)) dir (file-name-directory dir)) nil
2687 (tramp-flush-directory-property v localname)))
2688
2689 (defun tramp-handle-file-exists-p (filename)
2690 "Like `file-exists-p' for Tramp files."
2691 (not (null (file-attributes filename))))
2692
2693 (defun tramp-handle-file-modes (filename)
2694 "Like `file-modes' for Tramp files."
2695 (let ((truename (or (file-truename filename) filename)))
2696 (when (file-exists-p truename)
2697 (tramp-mode-string-to-int (nth 8 (file-attributes truename))))))
2698
2699 ;; Localname manipulation functions that grok Tramp localnames...
2700 (defun tramp-handle-file-name-as-directory (file)
2701 "Like `file-name-as-directory' but aware of Tramp files."
2702 ;; `file-name-as-directory' would be sufficient except localname is
2703 ;; the empty string.
2704 (let ((v (tramp-dissect-file-name file t)))
2705 ;; Run the command on the localname portion only.
2706 (tramp-make-tramp-file-name
2707 (tramp-file-name-method v)
2708 (tramp-file-name-user v)
2709 (tramp-file-name-host v)
2710 (tramp-run-real-handler
2711 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))))
2712
2713 (defun tramp-handle-file-name-completion
2714 (filename directory &optional predicate)
2715 "Like `file-name-completion' for Tramp files."
2716 (unless (tramp-tramp-file-p directory)
2717 (error
2718 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2719 directory))
2720 (try-completion
2721 filename
2722 (mapcar 'list (file-name-all-completions filename directory))
2723 (when predicate
2724 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2725
2726 (defun tramp-handle-file-name-directory (file)
2727 "Like `file-name-directory' but aware of Tramp files."
2728 ;; Everything except the last filename thing is the directory. We
2729 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2730 ;; the remote file name parts. This is a problem when we are in
2731 ;; file name completion.
2732 (let ((v (tramp-dissect-file-name file t)))
2733 ;; Run the command on the localname portion only.
2734 (tramp-make-tramp-file-name
2735 (tramp-file-name-method v)
2736 (tramp-file-name-user v)
2737 (tramp-file-name-host v)
2738 (tramp-run-real-handler
2739 'file-name-directory (list (or (tramp-file-name-localname v) ""))))))
2740
2741 (defun tramp-handle-file-name-nondirectory (file)
2742 "Like `file-name-nondirectory' but aware of Tramp files."
2743 (with-parsed-tramp-file-name file nil
2744 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2745
2746 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2747 "Like `file-newer-than-file-p' for Tramp files."
2748 (cond
2749 ((not (file-exists-p file1)) nil)
2750 ((not (file-exists-p file2)) t)
2751 (t (tramp-time-less-p (nth 5 (file-attributes file2))
2752 (nth 5 (file-attributes file1))))))
2753
2754 (defun tramp-handle-file-regular-p (filename)
2755 "Like `file-regular-p' for Tramp files."
2756 (and (file-exists-p filename)
2757 (eq ?- (aref (nth 8 (file-attributes filename)) 0))))
2758
2759 (defun tramp-handle-file-remote-p (filename &optional identification connected)
2760 "Like `file-remote-p' for Tramp files."
2761 (let ((tramp-verbose 3))
2762 (when (tramp-tramp-file-p filename)
2763 (let* ((v (tramp-dissect-file-name filename))
2764 (p (tramp-get-connection-process v))
2765 (c (and p (processp p) (memq (process-status p) '(run open)))))
2766 ;; We expand the file name only, if there is already a connection.
2767 (with-parsed-tramp-file-name
2768 (if c (expand-file-name filename) filename) nil
2769 (and (or (not connected) c)
2770 (cond
2771 ((eq identification 'method) method)
2772 ((eq identification 'user) user)
2773 ((eq identification 'host) host)
2774 ((eq identification 'localname) localname)
2775 (t (tramp-make-tramp-file-name method user host "")))))))))
2776
2777 (defun tramp-handle-file-symlink-p (filename)
2778 "Like `file-symlink-p' for Tramp files."
2779 (with-parsed-tramp-file-name filename nil
2780 (let ((x (car (file-attributes filename))))
2781 (when (stringp x)
2782 ;; When Tramp is running on VMS, then `file-name-absolute-p'
2783 ;; might do weird things.
2784 (if (file-name-absolute-p x)
2785 (tramp-make-tramp-file-name method user host x)
2786 x)))))
2787
2788 (defun tramp-handle-find-backup-file-name (filename)
2789 "Like `find-backup-file-name' for Tramp files."
2790 (with-parsed-tramp-file-name filename nil
2791 ;; We set both variables. It doesn't matter whether it is
2792 ;; Emacs or XEmacs.
2793 (let ((backup-directory-alist
2794 ;; Emacs case.
2795 (when (boundp 'backup-directory-alist)
2796 (if (symbol-value 'tramp-backup-directory-alist)
2797 (mapcar
2798 (lambda (x)
2799 (cons
2800 (car x)
2801 (if (and (stringp (cdr x))
2802 (file-name-absolute-p (cdr x))
2803 (not (tramp-file-name-p (cdr x))))
2804 (tramp-make-tramp-file-name method user host (cdr x))
2805 (cdr x))))
2806 (symbol-value 'tramp-backup-directory-alist))
2807 (symbol-value 'backup-directory-alist))))
2808
2809 (bkup-backup-directory-info
2810 ;; XEmacs case.
2811 (when (boundp 'bkup-backup-directory-info)
2812 (if (symbol-value 'tramp-bkup-backup-directory-info)
2813 (mapcar
2814 (lambda (x)
2815 (nconc
2816 (list (car x))
2817 (list
2818 (if (and (stringp (car (cdr x)))
2819 (file-name-absolute-p (car (cdr x)))
2820 (not (tramp-file-name-p (car (cdr x)))))
2821 (tramp-make-tramp-file-name
2822 method user host (car (cdr x)))
2823 (car (cdr x))))
2824 (cdr (cdr x))))
2825 (symbol-value 'tramp-bkup-backup-directory-info))
2826 (symbol-value 'bkup-backup-directory-info)))))
2827
2828 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
2829
2830 (defun tramp-handle-insert-file-contents
2831 (filename &optional visit beg end replace)
2832 "Like `insert-file-contents' for Tramp files."
2833 (barf-if-buffer-read-only)
2834 (setq filename (expand-file-name filename))
2835 (let (result local-copy remote-copy)
2836 (with-parsed-tramp-file-name filename nil
2837 (tramp-with-progress-reporter
2838 v 3 (format "Inserting `%s'" filename)
2839 (unwind-protect
2840 (if (not (file-exists-p filename))
2841 ;; We don't raise a Tramp error, because it might be
2842 ;; suppressed, like in `find-file-noselect-1'.
2843 (signal 'file-error
2844 (list "File not found on remote host" filename))
2845
2846 (if (and (tramp-local-host-p v)
2847 (let (file-name-handler-alist)
2848 (file-readable-p localname)))
2849 ;; Short track: if we are on the local host, we can
2850 ;; run directly.
2851 (setq result
2852 (tramp-run-real-handler
2853 'insert-file-contents
2854 (list localname visit beg end replace)))
2855
2856 ;; When we shall insert only a part of the file, we
2857 ;; copy this part.
2858 (when (or beg end)
2859 (setq remote-copy (tramp-make-tramp-temp-file v))
2860 ;; This is defined in tramp-sh.el. Let's assume
2861 ;; this is loaded already.
2862 (tramp-compat-funcall
2863 'tramp-send-command
2864 v
2865 (cond
2866 ((and beg end)
2867 (format "dd bs=1 skip=%d if=%s count=%d of=%s"
2868 beg (tramp-shell-quote-argument localname)
2869 (- end beg) remote-copy))
2870 (beg
2871 (format "dd bs=1 skip=%d if=%s of=%s"
2872 beg (tramp-shell-quote-argument localname)
2873 remote-copy))
2874 (end
2875 (format "dd bs=1 count=%d if=%s of=%s"
2876 end (tramp-shell-quote-argument localname)
2877 remote-copy)))))
2878
2879 ;; `insert-file-contents-literally' takes care to
2880 ;; avoid calling jka-compr. By let-binding
2881 ;; `inhibit-file-name-operation', we propagate that
2882 ;; care to the `file-local-copy' operation.
2883 (setq local-copy
2884 (let ((inhibit-file-name-operation
2885 (when (eq inhibit-file-name-operation
2886 'insert-file-contents)
2887 'file-local-copy)))
2888 (cond
2889 ((stringp remote-copy)
2890 (file-local-copy
2891 (tramp-make-tramp-file-name
2892 method user host remote-copy)))
2893 ((stringp tramp-temp-buffer-file-name)
2894 (copy-file filename tramp-temp-buffer-file-name 'ok)
2895 tramp-temp-buffer-file-name)
2896 (t (file-local-copy filename)))))
2897
2898 ;; When the file is not readable for the owner, it
2899 ;; cannot be inserted, even if it is readable for the
2900 ;; group or for everybody.
2901 (set-file-modes
2902 local-copy (tramp-compat-octal-to-decimal "0600"))
2903
2904 (when (and (null remote-copy)
2905 (tramp-get-method-parameter
2906 method 'tramp-copy-keep-tmpfile))
2907 ;; We keep the local file for performance reasons,
2908 ;; useful for "rsync".
2909 (setq tramp-temp-buffer-file-name local-copy))
2910
2911 ;; We must ensure that `file-coding-system-alist'
2912 ;; matches `local-copy'.
2913 (let ((file-coding-system-alist
2914 (tramp-find-file-name-coding-system-alist
2915 filename local-copy)))
2916 (setq result
2917 (insert-file-contents
2918 local-copy nil nil nil replace)))))
2919
2920 ;; Save exit.
2921 (progn
2922 (when visit
2923 (setq buffer-file-name filename)
2924 (setq buffer-read-only (not (file-writable-p filename)))
2925 (set-visited-file-modtime)
2926 (set-buffer-modified-p nil))
2927 (when (and (stringp local-copy)
2928 (or remote-copy (null tramp-temp-buffer-file-name)))
2929 (delete-file local-copy))
2930 (when (stringp remote-copy)
2931 (delete-file
2932 (tramp-make-tramp-file-name method user host remote-copy)))))))
2933
2934 ;; Result.
2935 (list (expand-file-name filename)
2936 (cadr result))))
2937
2938 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
2939 "Like `load' for Tramp files."
2940 (with-parsed-tramp-file-name (expand-file-name file) nil
2941 (unless nosuffix
2942 (cond ((file-exists-p (concat file ".elc"))
2943 (setq file (concat file ".elc")))
2944 ((file-exists-p (concat file ".el"))
2945 (setq file (concat file ".el")))))
2946 (when must-suffix
2947 ;; The first condition is always true for absolute file names.
2948 ;; Included for safety's sake.
2949 (unless (or (file-name-directory file)
2950 (string-match "\\.elc?\\'" file))
2951 (tramp-error
2952 v 'file-error
2953 "File `%s' does not include a `.el' or `.elc' suffix" file)))
2954 (unless noerror
2955 (when (not (file-exists-p file))
2956 (tramp-error v 'file-error "Cannot load nonexistent file `%s'" file)))
2957 (if (not (file-exists-p file))
2958 nil
2959 (let ((tramp-message-show-message (not nomessage)))
2960 (tramp-with-progress-reporter v 0 (format "Loading %s" file)
2961 (let ((local-copy (file-local-copy file)))
2962 ;; MUST-SUFFIX doesn't exist on XEmacs, so let it default to nil.
2963 (unwind-protect
2964 (load local-copy noerror t t)
2965 (delete-file local-copy)))))
2966 t)))
2967
2968 (defun tramp-handle-shell-command
2969 (command &optional output-buffer error-buffer)
2970 "Like `shell-command' for Tramp files."
2971 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
2972 ;; We cannot use `shell-file-name' and `shell-command-switch',
2973 ;; they are variables of the local host.
2974 (args (append
2975 (cons
2976 (tramp-get-method-parameter
2977 (tramp-file-name-method
2978 (tramp-dissect-file-name default-directory))
2979 'tramp-remote-shell)
2980 (tramp-get-method-parameter
2981 (tramp-file-name-method
2982 (tramp-dissect-file-name default-directory))
2983 'tramp-remote-shell-args))
2984 (list (substring command 0 asynchronous))))
2985 current-buffer-p
2986 (output-buffer
2987 (cond
2988 ((bufferp output-buffer) output-buffer)
2989 ((stringp output-buffer) (get-buffer-create output-buffer))
2990 (output-buffer
2991 (setq current-buffer-p t)
2992 (current-buffer))
2993 (t (get-buffer-create
2994 (if asynchronous
2995 "*Async Shell Command*"
2996 "*Shell Command Output*")))))
2997 (error-buffer
2998 (cond
2999 ((bufferp error-buffer) error-buffer)
3000 ((stringp error-buffer) (get-buffer-create error-buffer))))
3001 (buffer
3002 (if (and (not asynchronous) error-buffer)
3003 (with-parsed-tramp-file-name default-directory nil
3004 (list output-buffer (tramp-make-tramp-temp-file v)))
3005 output-buffer))
3006 (p (get-buffer-process output-buffer)))
3007
3008 ;; Check whether there is another process running. Tramp does not
3009 ;; support 2 (asynchronous) processes in parallel.
3010 (when p
3011 (if (yes-or-no-p "A command is running. Kill it? ")
3012 (ignore-errors (kill-process p))
3013 (error "Shell command in progress")))
3014
3015 (if current-buffer-p
3016 (progn
3017 (barf-if-buffer-read-only)
3018 (push-mark nil t))
3019 (with-current-buffer output-buffer
3020 (setq buffer-read-only nil)
3021 (erase-buffer)))
3022
3023 (if (and (not current-buffer-p) (integerp asynchronous))
3024 (prog1
3025 ;; Run the process.
3026 (setq p (apply 'start-file-process "*Async Shell*" buffer args))
3027 ;; Display output.
3028 (pop-to-buffer output-buffer)
3029 (setq mode-line-process '(":%s"))
3030 (shell-mode)
3031 (set-process-sentinel p 'shell-command-sentinel)
3032 (set-process-filter p 'comint-output-filter))
3033
3034 (prog1
3035 ;; Run the process.
3036 (apply 'process-file (car args) nil buffer nil (cdr args))
3037 ;; Insert error messages if they were separated.
3038 (when (listp buffer)
3039 (with-current-buffer error-buffer
3040 (insert-file-contents (cadr buffer)))
3041 (delete-file (cadr buffer)))
3042 (if current-buffer-p
3043 ;; This is like exchange-point-and-mark, but doesn't
3044 ;; activate the mark. It is cleaner to avoid activation,
3045 ;; even though the command loop would deactivate the mark
3046 ;; because we inserted text.
3047 (goto-char (prog1 (mark t)
3048 (set-marker (mark-marker) (point)
3049 (current-buffer))))
3050 ;; There's some output, display it.
3051 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
3052 (if (functionp 'display-message-or-buffer)
3053 (tramp-compat-funcall 'display-message-or-buffer output-buffer)
3054 (pop-to-buffer output-buffer))))))))
3055
3056 (defun tramp-handle-substitute-in-file-name (filename)
3057 "Like `substitute-in-file-name' for Tramp files.
3058 \"//\" and \"/~\" substitute only in the local filename part.
3059 If the URL Tramp syntax is chosen, \"//\" as method delimiter and \"/~\" at
3060 beginning of local filename are not substituted."
3061 ;; First, we must replace environment variables.
3062 (setq filename (tramp-replace-environment-variables filename))
3063 (with-parsed-tramp-file-name filename nil
3064 (if (equal tramp-syntax 'url)
3065 ;; We need to check localname only. The other parts cannot contain
3066 ;; "//" or "/~".
3067 (if (and (> (length localname) 1)
3068 (or (string-match "//" localname)
3069 (string-match "/~" localname 1)))
3070 (tramp-run-real-handler 'substitute-in-file-name (list filename))
3071 (tramp-make-tramp-file-name
3072 (when method (substitute-in-file-name method))
3073 (when user (substitute-in-file-name user))
3074 (when host (substitute-in-file-name host))
3075 (when localname
3076 (tramp-run-real-handler
3077 'substitute-in-file-name (list localname)))))
3078 ;; Ignore in LOCALNAME everything before "//" or "/~".
3079 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3080 (setq filename
3081 (concat (file-remote-p filename)
3082 (replace-match "\\1" nil nil localname)))
3083 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3084 (when (string-match "~$" filename)
3085 (setq filename (concat filename "/"))))
3086 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
3087
3088 (defun tramp-handle-unhandled-file-name-directory (filename)
3089 "Like `unhandled-file-name-directory' for Tramp files."
3090 ;; With Emacs 23, we could simply return `nil'. But we must keep it
3091 ;; for backward compatibility.
3092 (expand-file-name "~/"))
3093
3094 ;;; Functions for establishing connection:
3095
3096 ;; The following functions are actions to be taken when seeing certain
3097 ;; prompts from the remote host. See the variable
3098 ;; `tramp-actions-before-shell' for usage of these functions.
3099
3100 (defun tramp-action-login (proc vec)
3101 "Send the login name."
3102 (when (not (stringp tramp-current-user))
3103 (setq tramp-current-user
3104 (with-connection-property vec "login-as"
3105 (save-window-excursion
3106 (let ((enable-recursive-minibuffers t))
3107 (pop-to-buffer (tramp-get-connection-buffer vec))
3108 (read-string (match-string 0)))))))
3109 (with-current-buffer (tramp-get-connection-buffer vec)
3110 (tramp-message vec 6 "\n%s" (buffer-string)))
3111 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
3112 (tramp-send-string vec (concat tramp-current-user tramp-local-end-of-line)))
3113
3114 (defun tramp-action-password (proc vec)
3115 "Query the user for a password."
3116 (with-current-buffer (process-buffer proc)
3117 (let ((enable-recursive-minibuffers t))
3118 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3119 (tramp-message vec 3 "Sending %s" (match-string 1))
3120 ;; We don't call `tramp-send-string' in order to hide the
3121 ;; password from the debug buffer.
3122 (process-send-string
3123 proc (concat (tramp-read-passwd proc) tramp-local-end-of-line))
3124 ;; Hide password prompt.
3125 (narrow-to-region (point-max) (point-max)))))
3126
3127 (defun tramp-action-succeed (proc vec)
3128 "Signal success in finding shell prompt."
3129 (throw 'tramp-action 'ok))
3130
3131 (defun tramp-action-permission-denied (proc vec)
3132 "Signal permission denied."
3133 (kill-process proc)
3134 (throw 'tramp-action 'permission-denied))
3135
3136 (defun tramp-action-yesno (proc vec)
3137 "Ask the user for confirmation using `yes-or-no-p'.
3138 Send \"yes\" to remote process on confirmation, abort otherwise.
3139 See also `tramp-action-yn'."
3140 (save-window-excursion
3141 (let ((enable-recursive-minibuffers t))
3142 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3143 (unless (yes-or-no-p (match-string 0))
3144 (kill-process proc)
3145 (throw 'tramp-action 'permission-denied))
3146 (with-current-buffer (tramp-get-connection-buffer vec)
3147 (tramp-message vec 6 "\n%s" (buffer-string)))
3148 (tramp-send-string vec (concat "yes" tramp-local-end-of-line)))))
3149
3150 (defun tramp-action-yn (proc vec)
3151 "Ask the user for confirmation using `y-or-n-p'.
3152 Send \"y\" to remote process on confirmation, abort otherwise.
3153 See also `tramp-action-yesno'."
3154 (save-window-excursion
3155 (let ((enable-recursive-minibuffers t))
3156 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3157 (unless (y-or-n-p (match-string 0))
3158 (kill-process proc)
3159 (throw 'tramp-action 'permission-denied))
3160 (with-current-buffer (tramp-get-connection-buffer vec)
3161 (tramp-message vec 6 "\n%s" (buffer-string)))
3162 (tramp-send-string vec (concat "y" tramp-local-end-of-line)))))
3163
3164 (defun tramp-action-terminal (proc vec)
3165 "Tell the remote host which terminal type to use.
3166 The terminal type can be configured with `tramp-terminal-type'."
3167 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
3168 (with-current-buffer (tramp-get-connection-buffer vec)
3169 (tramp-message vec 6 "\n%s" (buffer-string)))
3170 (tramp-send-string vec (concat tramp-terminal-type tramp-local-end-of-line)))
3171
3172 (defun tramp-action-process-alive (proc vec)
3173 "Check, whether a process has finished."
3174 (unless (memq (process-status proc) '(run open))
3175 (throw 'tramp-action 'process-died)))
3176
3177 (defun tramp-action-out-of-band (proc vec)
3178 "Check, whether an out-of-band copy has finished."
3179 (cond ((and (memq (process-status proc) '(stop exit))
3180 (zerop (process-exit-status proc)))
3181 (tramp-message vec 3 "Process has finished.")
3182 (throw 'tramp-action 'ok))
3183 ((or (and (memq (process-status proc) '(stop exit))
3184 (not (zerop (process-exit-status proc))))
3185 (memq (process-status proc) '(signal)))
3186 ;; `scp' could have copied correctly, but set modes could have failed.
3187 ;; This can be ignored.
3188 (with-current-buffer (process-buffer proc)
3189 (goto-char (point-min))
3190 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3191 (progn
3192 (tramp-message vec 5 "'set mode' error ignored.")
3193 (tramp-message vec 3 "Process has finished.")
3194 (throw 'tramp-action 'ok))
3195 (tramp-message vec 3 "Process has died.")
3196 (throw 'tramp-action 'process-died))))
3197 (t nil)))
3198
3199 ;;; Functions for processing the actions:
3200
3201 (defun tramp-process-one-action (proc vec actions)
3202 "Wait for output from the shell and perform one action."
3203 (let (found todo item pattern action)
3204 (while (not found)
3205 ;; Reread output once all actions have been performed.
3206 ;; Obviously, the output was not complete.
3207 (tramp-accept-process-output proc 1)
3208 (setq todo actions)
3209 (while todo
3210 (setq item (pop todo))
3211 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
3212 (setq action (nth 1 item))
3213 (tramp-message
3214 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3215 (when (tramp-check-for-regexp proc pattern)
3216 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3217 (setq found (funcall action proc vec)))))
3218 found))
3219
3220 (defun tramp-process-actions (proc vec pos actions &optional timeout)
3221 "Perform ACTIONS until success or TIMEOUT.
3222 PROC and VEC indicate the remote connection to be used. POS, if
3223 set, is the starting point of the region to be deleted in the
3224 connection buffer."
3225 ;; Preserve message for `progress-reporter'.
3226 (tramp-compat-with-temp-message ""
3227 ;; Enable `auth-source' and `password-cache'. We must use
3228 ;; tramp-current-* variables in case we have several hops.
3229 (tramp-set-connection-property
3230 (tramp-dissect-file-name
3231 (tramp-make-tramp-file-name
3232 tramp-current-method tramp-current-user tramp-current-host ""))
3233 "first-password-request" t)
3234 (save-restriction
3235 (let (exit)
3236 (while (not exit)
3237 (tramp-message proc 3 "Waiting for prompts from remote shell")
3238 (setq exit
3239 (catch 'tramp-action
3240 (if timeout
3241 (with-timeout (timeout)
3242 (tramp-process-one-action proc vec actions))
3243 (tramp-process-one-action proc vec actions)))))
3244 (with-current-buffer (tramp-get-connection-buffer vec)
3245 (widen)
3246 (tramp-message vec 6 "\n%s" (buffer-string)))
3247 (unless (eq exit 'ok)
3248 (tramp-clear-passwd vec)
3249 (tramp-error-with-buffer
3250 nil vec 'file-error
3251 (cond
3252 ((eq exit 'permission-denied) "Permission denied")
3253 ((eq exit 'process-died) "Process died")
3254 (t "Login failed"))))
3255 (when (numberp pos)
3256 (with-current-buffer (tramp-get-connection-buffer vec)
3257 (let (buffer-read-only) (delete-region pos (point)))))))))
3258
3259 :;; Utility functions:
3260
3261 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
3262 "Like `accept-process-output' for Tramp processes.
3263 This is needed in order to hide `last-coding-system-used', which is set
3264 for process communication also."
3265 (with-current-buffer (process-buffer proc)
3266 (tramp-message proc 10 "%s %s" proc (process-status proc))
3267 (let (buffer-read-only last-coding-system-used)
3268 ;; Under Windows XP, accept-process-output doesn't return
3269 ;; sometimes. So we add an additional timeout.
3270 (with-timeout ((or timeout 1))
3271 (accept-process-output proc timeout timeout-msecs)))
3272 (tramp-message proc 10 "\n%s" (buffer-string))))
3273
3274 (defun tramp-check-for-regexp (proc regexp)
3275 "Check, whether REGEXP is contained in process buffer of PROC.
3276 Erase echoed commands if exists."
3277 (with-current-buffer (process-buffer proc)
3278 (goto-char (point-min))
3279
3280 ;; Check whether we need to remove echo output.
3281 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3282 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3283 (let ((begin (match-beginning 0)))
3284 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3285 ;; Discard echo from remote output.
3286 (tramp-set-connection-property proc "check-remote-echo" nil)
3287 (tramp-message proc 5 "echo-mark found")
3288 (forward-line 1)
3289 (delete-region begin (point))
3290 (goto-char (point-min)))))
3291
3292 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3293 ;; Sometimes, the echo string is suppressed on the remote side.
3294 (not (string-equal
3295 (tramp-compat-funcall
3296 'substring-no-properties tramp-echo-mark-marker
3297 0 (min tramp-echo-mark-marker-length (1- (point-max))))
3298 (tramp-compat-funcall
3299 'buffer-substring-no-properties
3300 1 (min (1+ tramp-echo-mark-marker-length) (point-max))))))
3301 ;; No echo to be handled, now we can look for the regexp.
3302 ;; Sometimes, lines are much to long, and we run into a "Stack
3303 ;; overflow in regexp matcher". For example, //DIRED// lines of
3304 ;; directory listings with some thousand files. Therefore, we
3305 ;; look from the end.
3306 (goto-char (point-max))
3307 (ignore-errors (re-search-backward regexp nil t)))))
3308
3309 (defun tramp-wait-for-regexp (proc timeout regexp)
3310 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3311 Expects the output of PROC to be sent to the current buffer. Returns
3312 the string that matched, or nil. Waits indefinitely if TIMEOUT is
3313 nil."
3314 (with-current-buffer (process-buffer proc)
3315 (let ((found (tramp-check-for-regexp proc regexp))
3316 (start-time (current-time)))
3317 (cond (timeout
3318 ;; Work around a bug in XEmacs 21, where the timeout
3319 ;; expires faster than it should. This degenerates
3320 ;; to polling for buggy XEmacsen, but oh, well.
3321 (while (and (not found)
3322 (< (tramp-time-diff (current-time) start-time)
3323 timeout))
3324 (with-timeout (timeout)
3325 (while (not found)
3326 (tramp-accept-process-output proc 1)
3327 (unless (memq (process-status proc) '(run open))
3328 (tramp-error-with-buffer
3329 nil proc 'file-error "Process has died"))
3330 (setq found (tramp-check-for-regexp proc regexp))))))
3331 (t
3332 (while (not found)
3333 (tramp-accept-process-output proc 1)
3334 (unless (memq (process-status proc) '(run open))
3335 (tramp-error-with-buffer
3336 nil proc 'file-error "Process has died"))
3337 (setq found (tramp-check-for-regexp proc regexp)))))
3338 (tramp-message proc 6 "\n%s" (buffer-string))
3339 (when (not found)
3340 (if timeout
3341 (tramp-error
3342 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3343 regexp timeout)
3344 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3345 found)))
3346
3347 ;; It seems that Tru64 Unix does not like it if long strings are sent
3348 ;; to it in one go. (This happens when sending the Perl
3349 ;; `file-attributes' implementation, for instance.) Therefore, we
3350 ;; have this function which sends the string in chunks.
3351 (defun tramp-send-string (vec string)
3352 "Send the STRING via connection VEC.
3353
3354 The STRING is expected to use Unix line-endings, but the lines sent to
3355 the remote host use line-endings as defined in the variable
3356 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3357 (let* ((p (tramp-get-connection-process vec))
3358 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3359 (unless p
3360 (tramp-error
3361 vec 'file-error "Can't send string to remote host -- not logged in"))
3362 (tramp-set-connection-property p "last-cmd-time" (current-time))
3363 (tramp-message vec 10 "%s" string)
3364 (with-current-buffer (tramp-get-connection-buffer vec)
3365 ;; Clean up the buffer. We cannot call `erase-buffer' because
3366 ;; narrowing might be in effect.
3367 (let (buffer-read-only) (delete-region (point-min) (point-max)))
3368 ;; Replace "\n" by `tramp-rsh-end-of-line'.
3369 (setq string
3370 (mapconcat 'identity
3371 (tramp-compat-split-string string "\n")
3372 tramp-rsh-end-of-line))
3373 (unless (or (string= string "")
3374 (string-equal (substring string -1) tramp-rsh-end-of-line))
3375 (setq string (concat string tramp-rsh-end-of-line)))
3376 ;; Send the string.
3377 (if (and chunksize (not (zerop chunksize)))
3378 (let ((pos 0)
3379 (end (length string)))
3380 (while (< pos end)
3381 (tramp-message
3382 vec 10 "Sending chunk from %s to %s"
3383 pos (min (+ pos chunksize) end))
3384 (process-send-string
3385 p (substring string pos (min (+ pos chunksize) end)))
3386 (setq pos (+ pos chunksize))))
3387 (process-send-string p string)))))
3388
3389 (defun tramp-get-inode (vec)
3390 "Returns the virtual inode number.
3391 If it doesn't exist, generate a new one."
3392 (with-file-property vec (tramp-file-name-localname vec) "inode"
3393 (setq tramp-inodes (1+ tramp-inodes))))
3394
3395 (defun tramp-get-device (vec)
3396 "Returns the virtual device number.
3397 If it doesn't exist, generate a new one."
3398 (with-connection-property (tramp-get-connection-process vec) "device"
3399 (cons -1 (setq tramp-devices (1+ tramp-devices)))))
3400
3401 (defun tramp-equal-remote (file1 file2)
3402 "Check, whether the remote parts of FILE1 and FILE2 are identical.
3403 The check depends on method, user and host name of the files. If
3404 one of the components is missing, the default values are used.
3405 The local file name parts of FILE1 and FILE2 are not taken into
3406 account.
3407
3408 Example:
3409
3410 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3411
3412 would yield `t'. On the other hand, the following check results in nil:
3413
3414 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
3415 (and (stringp (file-remote-p file1))
3416 (stringp (file-remote-p file2))
3417 (string-equal (file-remote-p file1) (file-remote-p file2))))
3418
3419 ;;;###tramp-autoload
3420 (defun tramp-mode-string-to-int (mode-string)
3421 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3422 (let* (case-fold-search
3423 (mode-chars (string-to-vector mode-string))
3424 (owner-read (aref mode-chars 1))
3425 (owner-write (aref mode-chars 2))
3426 (owner-execute-or-setid (aref mode-chars 3))
3427 (group-read (aref mode-chars 4))
3428 (group-write (aref mode-chars 5))
3429 (group-execute-or-setid (aref mode-chars 6))
3430 (other-read (aref mode-chars 7))
3431 (other-write (aref mode-chars 8))
3432 (other-execute-or-sticky (aref mode-chars 9)))
3433 (save-match-data
3434 (logior
3435 (cond
3436 ((char-equal owner-read ?r) (tramp-compat-octal-to-decimal "00400"))
3437 ((char-equal owner-read ?-) 0)
3438 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3439 (cond
3440 ((char-equal owner-write ?w) (tramp-compat-octal-to-decimal "00200"))
3441 ((char-equal owner-write ?-) 0)
3442 (t (error "Third char `%c' must be one of `w-'" owner-write)))
3443 (cond
3444 ((char-equal owner-execute-or-setid ?x)
3445 (tramp-compat-octal-to-decimal "00100"))
3446 ((char-equal owner-execute-or-setid ?S)
3447 (tramp-compat-octal-to-decimal "04000"))
3448 ((char-equal owner-execute-or-setid ?s)
3449 (tramp-compat-octal-to-decimal "04100"))
3450 ((char-equal owner-execute-or-setid ?-) 0)
3451 (t (error "Fourth char `%c' must be one of `xsS-'"
3452 owner-execute-or-setid)))
3453 (cond
3454 ((char-equal group-read ?r) (tramp-compat-octal-to-decimal "00040"))
3455 ((char-equal group-read ?-) 0)
3456 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
3457 (cond
3458 ((char-equal group-write ?w) (tramp-compat-octal-to-decimal "00020"))
3459 ((char-equal group-write ?-) 0)
3460 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
3461 (cond
3462 ((char-equal group-execute-or-setid ?x)
3463 (tramp-compat-octal-to-decimal "00010"))
3464 ((char-equal group-execute-or-setid ?S)
3465 (tramp-compat-octal-to-decimal "02000"))
3466 ((char-equal group-execute-or-setid ?s)
3467 (tramp-compat-octal-to-decimal "02010"))
3468 ((char-equal group-execute-or-setid ?-) 0)
3469 (t (error "Seventh char `%c' must be one of `xsS-'"
3470 group-execute-or-setid)))
3471 (cond
3472 ((char-equal other-read ?r)
3473 (tramp-compat-octal-to-decimal "00004"))
3474 ((char-equal other-read ?-) 0)
3475 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
3476 (cond
3477 ((char-equal other-write ?w) (tramp-compat-octal-to-decimal "00002"))
3478 ((char-equal other-write ?-) 0)
3479 (t (error "Ninth char `%c' must be one of `w-'" other-write)))
3480 (cond
3481 ((char-equal other-execute-or-sticky ?x)
3482 (tramp-compat-octal-to-decimal "00001"))
3483 ((char-equal other-execute-or-sticky ?T)
3484 (tramp-compat-octal-to-decimal "01000"))
3485 ((char-equal other-execute-or-sticky ?t)
3486 (tramp-compat-octal-to-decimal "01001"))
3487 ((char-equal other-execute-or-sticky ?-) 0)
3488 (t (error "Tenth char `%c' must be one of `xtT-'"
3489 other-execute-or-sticky)))))))
3490
3491 ;;;###tramp-autoload
3492 (defun tramp-local-host-p (vec)
3493 "Return t if this points to the local host, nil otherwise."
3494 ;; We cannot use `tramp-file-name-real-host'. A port is an
3495 ;; indication for an ssh tunnel or alike.
3496 (let ((host (tramp-file-name-host vec)))
3497 (and
3498 (stringp host)
3499 (string-match tramp-local-host-regexp host)
3500 ;; The method shall be applied to one of the shell file name
3501 ;; handler. `tramp-local-host-p' is also called for "smb" and
3502 ;; alike, where it must fail.
3503 (tramp-get-method-parameter
3504 (tramp-file-name-method vec) 'tramp-login-program)
3505 ;; The local temp directory must be writable for the other user.
3506 (file-writable-p
3507 (tramp-make-tramp-file-name
3508 (tramp-file-name-method vec)
3509 (tramp-file-name-user vec)
3510 host
3511 (tramp-compat-temporary-file-directory)))
3512 ;; On some systems, chown runs only for root.
3513 (or (zerop (user-uid))
3514 ;; This is defined in tramp-sh.el. Let's assume this is
3515 ;; loaded already.
3516 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
3517
3518 (defun tramp-get-remote-tmpdir (vec)
3519 "Return directory for temporary files on the remote host identified by VEC."
3520 (with-connection-property vec "tmpdir"
3521 (let ((dir (tramp-make-tramp-file-name
3522 (tramp-file-name-method vec)
3523 (tramp-file-name-user vec)
3524 (tramp-file-name-host vec)
3525 (or
3526 (tramp-get-method-parameter
3527 (tramp-file-name-method vec) 'tramp-tmpdir)
3528 "/tmp"))))
3529 (if (and (file-directory-p dir) (file-writable-p dir))
3530 dir
3531 (tramp-error vec 'file-error "Directory %s not accessible" dir)))))
3532
3533 ;;;###tramp-autoload
3534 (defun tramp-make-tramp-temp-file (vec)
3535 "Create a temporary file on the remote host identified by VEC.
3536 Return the local name of the temporary file."
3537 (let ((prefix (expand-file-name
3538 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))
3539 result)
3540 (while (not result)
3541 ;; `make-temp-file' would be the natural choice for
3542 ;; implementation. But it calls `write-region' internally,
3543 ;; which also needs a temporary file - we would end in an
3544 ;; infinite loop.
3545 (setq result (make-temp-name prefix))
3546 (if (file-exists-p result)
3547 (setq result nil)
3548 ;; This creates the file by side effect.
3549 (set-file-times result)
3550 (set-file-modes result (tramp-compat-octal-to-decimal "0700"))))
3551
3552 ;; Return the local part.
3553 (with-parsed-tramp-file-name result nil localname)))
3554
3555 (defun tramp-delete-temp-file-function ()
3556 "Remove temporary files related to current buffer."
3557 (when (stringp tramp-temp-buffer-file-name)
3558 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
3559
3560 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
3561 (add-hook 'tramp-unload-hook
3562 (lambda ()
3563 (remove-hook 'kill-buffer-hook
3564 'tramp-delete-temp-file-function)))
3565
3566 ;;; Auto saving to a special directory:
3567
3568 (unless (tramp-exists-file-name-handler 'make-auto-save-file-name)
3569 (defadvice make-auto-save-file-name
3570 (around tramp-advice-make-auto-save-file-name () activate)
3571 "Invoke `tramp-*-handle-make-auto-save-file-name' for Tramp files."
3572 (if (tramp-tramp-file-p (buffer-file-name))
3573 ;; We cannot call `tramp-handle-make-auto-save-file-name'
3574 ;; directly, because this would bypass the locking mechanism.
3575 (setq ad-return-value
3576 (tramp-file-name-handler 'make-auto-save-file-name))
3577 ad-do-it))
3578 (add-hook
3579 'tramp-unload-hook
3580 (lambda ()
3581 (ad-remove-advice
3582 'make-auto-save-file-name
3583 'around 'tramp-advice-make-auto-save-file-name)
3584 (ad-activate 'make-auto-save-file-name))))
3585
3586 ;; In XEmacs < 21.5, autosaved remote files have permission 0666 minus
3587 ;; umask. This is a security threat.
3588
3589 (defun tramp-set-auto-save-file-modes ()
3590 "Set permissions of autosaved remote files to the original permissions."
3591 (let ((bfn (buffer-file-name)))
3592 (when (and (tramp-tramp-file-p bfn)
3593 (buffer-modified-p)
3594 (stringp buffer-auto-save-file-name)
3595 (not (equal bfn buffer-auto-save-file-name)))
3596 (unless (file-exists-p buffer-auto-save-file-name)
3597 (write-region "" nil buffer-auto-save-file-name))
3598 ;; Permissions should be set always, because there might be an old
3599 ;; auto-saved file belonging to another original file. This could
3600 ;; be a security threat.
3601 (set-file-modes
3602 buffer-auto-save-file-name
3603 (or (file-modes bfn) (tramp-compat-octal-to-decimal "0600"))))))
3604
3605 (unless (and (featurep 'xemacs)
3606 (= emacs-major-version 21)
3607 (> emacs-minor-version 4))
3608 (add-hook 'auto-save-hook 'tramp-set-auto-save-file-modes)
3609 (add-hook 'tramp-unload-hook
3610 (lambda ()
3611 (remove-hook 'auto-save-hook 'tramp-set-auto-save-file-modes))))
3612
3613 (defun tramp-subst-strs-in-string (alist string)
3614 "Replace all occurrences of the string FROM with TO in STRING.
3615 ALIST is of the form ((FROM . TO) ...)."
3616 (save-match-data
3617 (while alist
3618 (let* ((pr (car alist))
3619 (from (car pr))
3620 (to (cdr pr)))
3621 (while (string-match (regexp-quote from) string)
3622 (setq string (replace-match to t t string)))
3623 (setq alist (cdr alist))))
3624 string))
3625
3626 ;;; Compatibility functions section:
3627
3628 ;;;###tramp-autoload
3629 (defun tramp-read-passwd (proc &optional prompt)
3630 "Read a password from user (compat function).
3631 Consults the auth-source package.
3632 Invokes `password-read' if available, `read-passwd' else."
3633 (let* ((key (tramp-make-tramp-file-name
3634 tramp-current-method tramp-current-user
3635 tramp-current-host ""))
3636 (pw-prompt
3637 (or prompt
3638 (with-current-buffer (process-buffer proc)
3639 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3640 (format "%s for %s " (capitalize (match-string 1)) key))))
3641 auth-info auth-passwd)
3642 (with-parsed-tramp-file-name key nil
3643 (prog1
3644 (or
3645 ;; See if auth-sources contains something useful, if it's
3646 ;; bound. `auth-source-user-or-password' is an obsoleted
3647 ;; function, it has been replaced by `auth-source-search'.
3648 (and (boundp 'auth-sources)
3649 (tramp-get-connection-property v "first-password-request" nil)
3650 ;; Try with Tramp's current method.
3651 (if (fboundp 'auth-source-search)
3652 (setq auth-info
3653 (tramp-compat-funcall
3654 'auth-source-search
3655 :max 1
3656 :user (or tramp-current-user t)
3657 :host tramp-current-host
3658 :port tramp-current-method)
3659 auth-passwd (plist-get (nth 0 auth-info) :secret)
3660 auth-passwd (if (functionp auth-passwd)
3661 (funcall auth-passwd)
3662 auth-passwd))
3663 (tramp-compat-funcall
3664 'auth-source-user-or-password
3665 "password" tramp-current-host tramp-current-method)))
3666 ;; Try the password cache.
3667 (when (functionp 'password-read)
3668 (unless (tramp-get-connection-property
3669 v "first-password-request" nil)
3670 (tramp-compat-funcall 'password-cache-remove key))
3671 (let ((password
3672 (tramp-compat-funcall 'password-read pw-prompt key)))
3673 (tramp-compat-funcall 'password-cache-add key password)
3674 password))
3675 ;; Else, get the password interactively.
3676 (read-passwd pw-prompt))
3677 (tramp-set-connection-property v "first-password-request" nil)))))
3678
3679 ;;;###tramp-autoload
3680 (defun tramp-clear-passwd (vec)
3681 "Clear password cache for connection related to VEC."
3682 (tramp-compat-funcall
3683 'password-cache-remove
3684 (tramp-make-tramp-file-name
3685 (tramp-file-name-method vec)
3686 (tramp-file-name-user vec)
3687 (tramp-file-name-host vec)
3688 "")))
3689
3690 ;; Snarfed code from time-date.el and parse-time.el
3691
3692 (defconst tramp-half-a-year '(241 17024)
3693 "Evaluated by \"(days-to-time 183)\".")
3694
3695 (defconst tramp-parse-time-months
3696 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
3697 ("apr" . 4) ("may" . 5) ("jun" . 6)
3698 ("jul" . 7) ("aug" . 8) ("sep" . 9)
3699 ("oct" . 10) ("nov" . 11) ("dec" . 12))
3700 "Alist mapping month names to integers.")
3701
3702 ;;;###tramp-autoload
3703 (defun tramp-time-less-p (t1 t2)
3704 "Say whether time value T1 is less than time value T2."
3705 (unless t1 (setq t1 '(0 0)))
3706 (unless t2 (setq t2 '(0 0)))
3707 (or (< (car t1) (car t2))
3708 (and (= (car t1) (car t2))
3709 (< (nth 1 t1) (nth 1 t2)))))
3710
3711 (defun tramp-time-subtract (t1 t2)
3712 "Subtract two time values.
3713 Return the difference in the format of a time value."
3714 (unless t1 (setq t1 '(0 0)))
3715 (unless t2 (setq t2 '(0 0)))
3716 (let ((borrow (< (cadr t1) (cadr t2))))
3717 (list (- (car t1) (car t2) (if borrow 1 0))
3718 (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
3719
3720 ;;;###tramp-autoload
3721 (defun tramp-time-diff (t1 t2)
3722 "Return the difference between the two times, in seconds.
3723 T1 and T2 are time values (as returned by `current-time' for example)."
3724 (cond ((and (fboundp 'subtract-time)
3725 (fboundp 'float-time))
3726 (tramp-compat-funcall
3727 'float-time (tramp-compat-funcall 'subtract-time t1 t2)))
3728 ((and (fboundp 'subtract-time)
3729 (fboundp 'time-to-seconds))
3730 (tramp-compat-funcall
3731 'time-to-seconds (tramp-compat-funcall 'subtract-time t1 t2)))
3732 ((fboundp 'itimer-time-difference)
3733 (tramp-compat-funcall
3734 'itimer-time-difference
3735 (if (< (length t1) 3) (append t1 '(0)) t1)
3736 (if (< (length t2) 3) (append t2 '(0)) t2)))
3737 (t
3738 (let ((time (tramp-time-subtract t1 t2)))
3739 (+ (* (car time) 65536.0)
3740 (cadr time)
3741 (/ (or (nth 2 time) 0) 1000000.0))))))
3742
3743 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
3744 ;; does not deal well with newline characters. Newline is replaced by
3745 ;; backslash newline. But if, say, the string `a backslash newline b'
3746 ;; is passed to a shell, the shell will expand this into "ab",
3747 ;; completely omitting the newline. This is not what was intended.
3748 ;; It does not appear to be possible to make the function
3749 ;; `shell-quote-argument' work with newlines without making it
3750 ;; dependent on the shell used. But within this package, we know that
3751 ;; we will always use a Bourne-like shell, so we use an approach which
3752 ;; groks newlines.
3753 ;;
3754 ;; The approach is simple: we call `shell-quote-argument', then
3755 ;; massage the newline part of the result.
3756 ;;
3757 ;; This function should produce a string which is grokked by a Unix
3758 ;; shell, even if the Emacs is running on Windows. Since this is the
3759 ;; kludges section, we bind `system-type' in such a way that
3760 ;; `shell-quote-arguments' behaves as if on Unix.
3761 ;;
3762 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
3763 ;; function to work with Bourne-like shells.
3764 ;;
3765 ;; CCC: This function should be rewritten so that
3766 ;; `shell-quote-argument' is not used. This way, we are safe from
3767 ;; changes in `shell-quote-argument'.
3768 ;;;###tramp-autoload
3769 (defun tramp-shell-quote-argument (s)
3770 "Similar to `shell-quote-argument', but groks newlines.
3771 Only works for Bourne-like shells."
3772 (let ((system-type 'not-windows))
3773 (save-match-data
3774 (let ((result (shell-quote-argument s))
3775 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
3776 (when (and (>= (length result) 2)
3777 (string= (substring result 0 2) "\\~"))
3778 (setq result (substring result 1)))
3779 (while (string-match nl result)
3780 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
3781 t t result)))
3782 result))))
3783
3784 ;; Checklist for `tramp-unload-hook'
3785 ;; - Unload all `tramp-*' packages
3786 ;; - Reset `file-name-handler-alist'
3787 ;; - Cleanup hooks where Tramp functions are in
3788 ;; - Cleanup advised functions
3789 ;; - Cleanup autoloads
3790 ;;;###autoload
3791 (defun tramp-unload-tramp ()
3792 "Discard Tramp from loading remote files."
3793 (interactive)
3794 ;; ange-ftp settings must be enabled.
3795 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
3796 ;; Maybe it's not loaded yet.
3797 (ignore-errors (unload-feature 'tramp 'force)))
3798
3799 (provide 'tramp)
3800
3801 ;;; TODO:
3802
3803 ;; * Rewrite `tramp-shell-quote-argument' to abstain from using
3804 ;; `shell-quote-argument'.
3805 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
3806 ;; by the files in that directory. Add this here.
3807 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
3808 ;; * Make ffap.el grok Tramp filenames. (Eli Tziperman)
3809 ;; * abbreviate-file-name
3810 ;; * Better error checking. At least whenever we see something
3811 ;; strange when doing zerop, we should kill the process and start
3812 ;; again. (Greg Stark)
3813 ;; * Username and hostname completion.
3814 ;; ** Try to avoid usage of `last-input-event' in `tramp-completion-mode-p'.
3815 ;; * Make `tramp-default-user' obsolete.
3816 ;; * Implement a general server-local-variable mechanism, as there are
3817 ;; probably other variables that need different values for different
3818 ;; servers too. The user could then configure a variable (such as
3819 ;; tramp-server-local-variable-alist) to define any such variables
3820 ;; that they need to, which would then be let bound as appropriate
3821 ;; in tramp functions. (Jason Rumney)
3822 ;; * IMHO, it's a drawback that currently Tramp doesn't support
3823 ;; Unicode in Dired file names by default. Is it possible to
3824 ;; improve Tramp to set LC_ALL to "C" only for commands where Tramp
3825 ;; expects English? Or just to set LC_MESSAGES to "C" if Tramp
3826 ;; expects only English messages? (Juri Linkov)
3827 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
3828 ;; * I was wondering if it would be possible to use tramp even if I'm
3829 ;; actually using sshfs. But when I launch a command I would like
3830 ;; to get it executed on the remote machine where the files really
3831 ;; are. (Andrea Crotti)
3832 ;; * Run emerge on two remote files. Bug is described here:
3833 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
3834 ;; (Bug#6850)
3835
3836 ;;; tramp.el ends here
3837
3838 ;; Local Variables:
3839 ;; mode: Emacs-Lisp
3840 ;; coding: utf-8
3841 ;; End: