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