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