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