Merge branch 'master' into comment-cache
[emacs.git] / lisp / net / tramp.el
blob48dcd5edd11d474c6545e8125f9eb68846eca8ae
1 ;;; tramp.el --- Transparent Remote Access, Multiple Protocol
3 ;; Copyright (C) 1998-2017 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.
245 * `tramp-tmpdir'
246 A directory on the remote host for temporary files. If not
247 specified, \"/tmp\" is taken as default.
248 * `tramp-connection-timeout'
249 This is the maximum time to be spent for establishing a connection.
250 In general, the global default value shall be used, but for
251 some methods, like \"su\" or \"sudo\", a shorter timeout
252 might be desirable.
253 * `tramp-case-insensitive'
254 Whether the remote file system handles file names case insensitive.
255 Only a non-nil value counts, the default value nil means to
256 perform further checks on the remote host. See
257 `tramp-connection-properties' for a way to overwrite this.
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.
277 Notes:
279 When using `su' or `sudo' the phrase \"open connection to a remote
280 host\" sounds strange, but it is used nevertheless, for consistency.
281 No connection is opened to a remote host, but `su' or `sudo' is
282 started on the local host. You should specify a remote host
283 `localhost' or the name of the local host. Another host name is
284 useful only in combination with `tramp-default-proxies-alist'.")
286 (defcustom tramp-default-method
287 ;; An external copy method seems to be preferred, because it performs
288 ;; much better for large files, and it hasn't too serious delays
289 ;; for small files. But it must be ensured that there aren't
290 ;; permanent password queries. Either a password agent like
291 ;; "ssh-agent" or "Pageant" shall run, or the optional
292 ;; password-cache.el or auth-sources.el packages shall be active for
293 ;; password caching. If we detect that the user is running OpenSSH
294 ;; 4.0 or newer, we could reuse the connection, which calls also for
295 ;; an external method.
296 (cond
297 ;; PuTTY is installed. We don't take it, if it is installed on a
298 ;; non-windows system, or pscp from the pssh (parallel ssh) package
299 ;; is found.
300 ((and (eq system-type 'windows-nt) (executable-find "pscp")) "pscp")
301 ;; There is an ssh installation.
302 ((executable-find "scp") "scp")
303 ;; Fallback.
304 (t "ftp"))
305 "Default method to use for transferring files.
306 See `tramp-methods' for possibilities.
307 Also see `tramp-default-method-alist'."
308 :group 'tramp
309 :type 'string
310 :require 'tramp)
312 ;;;###tramp-autoload
313 (defcustom tramp-default-method-alist nil
314 "Default method to use for specific host/user pairs.
315 This is an alist of items (HOST USER METHOD). The first matching item
316 specifies the method to use for a file name which does not specify a
317 method. HOST and USER are regular expressions or nil, which is
318 interpreted as a regular expression which always matches. If no entry
319 matches, the variable `tramp-default-method' takes effect.
321 If the file name does not specify the user, lookup is done using the
322 empty string for the user name.
324 See `tramp-methods' for a list of possibilities for METHOD."
325 :group 'tramp
326 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
327 (choice :tag "User regexp" regexp sexp)
328 (choice :tag "Method name" string (const nil))))
329 :require 'tramp)
331 (defcustom tramp-default-user nil
332 "Default user to use for transferring files.
333 It is nil by default; otherwise settings in configuration files like
334 \"~/.ssh/config\" would be overwritten. Also see `tramp-default-user-alist'.
336 This variable is regarded as obsolete, and will be removed soon."
337 :group 'tramp
338 :type '(choice (const nil) string)
339 :require 'tramp)
341 ;;;###tramp-autoload
342 (defcustom tramp-default-user-alist nil
343 "Default user to use for specific method/host pairs.
344 This is an alist of items (METHOD HOST USER). The first matching item
345 specifies the user to use for a file name which does not specify a
346 user. METHOD and USER are regular expressions or nil, which is
347 interpreted as a regular expression which always matches. If no entry
348 matches, the variable `tramp-default-user' takes effect.
350 If the file name does not specify the method, lookup is done using the
351 empty string for the method name."
352 :group 'tramp
353 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
354 (choice :tag " Host regexp" regexp sexp)
355 (choice :tag " User name" string (const nil))))
356 :require 'tramp)
358 (defcustom tramp-default-host (system-name)
359 "Default host to use for transferring files.
360 Useful for su and sudo methods mostly."
361 :group 'tramp
362 :type 'string
363 :require 'tramp)
365 ;;;###tramp-autoload
366 (defcustom tramp-default-host-alist nil
367 "Default host to use for specific method/user pairs.
368 This is an alist of items (METHOD USER HOST). The first matching item
369 specifies the host to use for a file name which does not specify a
370 host. METHOD and HOST are regular expressions or nil, which is
371 interpreted as a regular expression which always matches. If no entry
372 matches, the variable `tramp-default-host' takes effect.
374 If the file name does not specify the method, lookup is done using the
375 empty string for the method name."
376 :group 'tramp
377 :version "24.4"
378 :type '(repeat (list (choice :tag "Method regexp" regexp sexp)
379 (choice :tag " User regexp" regexp sexp)
380 (choice :tag " Host name" string (const nil))))
381 :require 'tramp)
383 (defcustom tramp-default-proxies-alist nil
384 "Route to be followed for specific host/user pairs.
385 This is an alist of items (HOST USER PROXY). The first matching
386 item specifies the proxy to be passed for a file name located on
387 a remote target matching USER@HOST. HOST and USER are regular
388 expressions. PROXY must be a Tramp filename without a localname
389 part. Method and user name on PROXY are optional, which is
390 interpreted with the default values. PROXY can contain the
391 patterns %h and %u, which are replaced by the strings matching
392 HOST or USER, respectively.
394 HOST, USER or PROXY could also be Lisp forms, which will be
395 evaluated. The result must be a string or nil, which is
396 interpreted as a regular expression which always matches."
397 :group 'tramp
398 :type '(repeat (list (choice :tag "Host regexp" regexp sexp)
399 (choice :tag "User regexp" regexp sexp)
400 (choice :tag " Proxy name" string (const nil))))
401 :require 'tramp)
403 (defcustom tramp-save-ad-hoc-proxies nil
404 "Whether to save ad-hoc proxies persistently."
405 :group 'tramp
406 :version "24.3"
407 :type 'boolean
408 :require 'tramp)
410 (defcustom tramp-restricted-shell-hosts-alist
411 (when (memq system-type '(windows-nt))
412 (list (concat "\\`" (regexp-quote (system-name)) "\\'")))
413 "List of hosts, which run a restricted shell.
414 This is a list of regular expressions, which denote hosts running
415 a registered shell like \"rbash\". Those hosts can be used as
416 proxies only, see `tramp-default-proxies-alist'. If the local
417 host runs a registered shell, it shall be added to this list, too."
418 :version "24.3"
419 :group 'tramp
420 :type '(repeat (regexp :tag "Host regexp"))
421 :require 'tramp)
423 ;;;###tramp-autoload
424 (defconst tramp-local-host-regexp
425 (concat
426 "\\`"
427 (regexp-opt
428 (list "localhost" "localhost6" (system-name) "127.0.0.1" "::1") t)
429 "\\'")
430 "Host names which are regarded as local host.")
432 (defvar tramp-completion-function-alist nil
433 "Alist of methods for remote files.
434 This is a list of entries of the form \(NAME PAIR1 PAIR2 ...).
435 Each NAME stands for a remote access method. Each PAIR is of the form
436 \(FUNCTION FILE). FUNCTION is responsible to extract user names and host
437 names from FILE for completion. The following predefined FUNCTIONs exists:
439 * `tramp-parse-rhosts' for \"~/.rhosts\" like files,
440 * `tramp-parse-shosts' for \"~/.ssh/known_hosts\" like files,
441 * `tramp-parse-sconfig' for \"~/.ssh/config\" like files,
442 * `tramp-parse-shostkeys' for \"~/.ssh2/hostkeys/*\" like files,
443 * `tramp-parse-sknownhosts' for \"~/.ssh2/knownhosts/*\" like files,
444 * `tramp-parse-hosts' for \"/etc/hosts\" like files,
445 * `tramp-parse-passwd' for \"/etc/passwd\" like files.
446 * `tramp-parse-etc-group' for \"/etc/group\" like files.
447 * `tramp-parse-netrc' for \"~/.netrc\" like files.
448 * `tramp-parse-putty' for PuTTY registered sessions.
450 FUNCTION can also be a user defined function. For more details see
451 the info pages.")
453 (defconst tramp-echo-mark-marker "_echo"
454 "String marker to surround echoed commands.")
456 (defconst tramp-echo-mark-marker-length (length tramp-echo-mark-marker)
457 "String length of `tramp-echo-mark-marker'.")
459 (defconst tramp-echo-mark
460 (concat tramp-echo-mark-marker
461 (make-string tramp-echo-mark-marker-length ?\b))
462 "String mark to be transmitted around shell commands.
463 Used to separate their echo from the output they produce. This
464 will only be used if we cannot disable remote echo via stty.
465 This string must have no effect on the remote shell except for
466 producing some echo which can later be detected by
467 `tramp-echoed-echo-mark-regexp'. Using `tramp-echo-mark-marker',
468 followed by an equal number of backspaces to erase them will
469 usually suffice.")
471 (defconst tramp-echoed-echo-mark-regexp
472 (format "%s\\(\b\\( \b\\)?\\)\\{%d\\}"
473 tramp-echo-mark-marker tramp-echo-mark-marker-length)
474 "Regexp which matches `tramp-echo-mark' as it gets echoed by
475 the remote shell.")
477 (defcustom tramp-local-end-of-line
478 (if (memq system-type '(windows-nt)) "\r\n" "\n")
479 "String used for end of line in local processes."
480 :version "24.1"
481 :group 'tramp
482 :type 'string
483 :require 'tramp)
485 (defcustom tramp-rsh-end-of-line "\n"
486 "String used for end of line in rsh connections.
487 I don't think this ever needs to be changed, so please tell me about it
488 if you need to change this."
489 :group 'tramp
490 :type 'string
491 :require 'tramp)
493 (defcustom tramp-login-prompt-regexp
494 ".*\\(user\\|login\\)\\( .*\\)?: *"
495 "Regexp matching login-like prompts.
496 The regexp should match at end of buffer.
498 Sometimes the prompt is reported to look like \"login as:\"."
499 :group 'tramp
500 :type 'regexp
501 :require 'tramp)
503 (defcustom tramp-shell-prompt-pattern
504 ;; Allow a prompt to start right after a ^M since it indeed would be
505 ;; displayed at the beginning of the line (and Zsh uses it). This
506 ;; regexp works only for GNU Emacs.
507 ;; Allow also [] style prompts. They can appear only during
508 ;; connection initialization; Tramp redefines the prompt afterwards.
509 (concat "\\(?:^\\|\r\\)"
510 "[^]#$%>\n]*#?[]#$%>] *\\(\e\\[[0-9;]*[a-zA-Z] *\\)*")
511 "Regexp to match prompts from remote shell.
512 Normally, Tramp expects you to configure `shell-prompt-pattern'
513 correctly, but sometimes it happens that you are connecting to a
514 remote host which sends a different kind of shell prompt. Therefore,
515 Tramp recognizes things matched by `shell-prompt-pattern' as prompt,
516 and also things matched by this variable. The default value of this
517 variable is similar to the default value of `shell-prompt-pattern',
518 which should work well in many cases.
520 This regexp must match both `tramp-initial-end-of-output' and
521 `tramp-end-of-output'."
522 :group 'tramp
523 :type 'regexp
524 :require 'tramp)
526 (defcustom tramp-password-prompt-regexp
527 (format "^.*\\(%s\\).*:\^@? *"
528 ;; `password-word-equivalents' has been introduced with Emacs 24.4.
529 (if (boundp 'password-word-equivalents)
530 (regexp-opt (symbol-value 'password-word-equivalents))
531 "password\\|passphrase"))
532 "Regexp matching password-like prompts.
533 The regexp should match at end of buffer.
535 The `sudo' program appears to insert a `^@' character into the prompt."
536 :version "24.4"
537 :group 'tramp
538 :type 'regexp
539 :require 'tramp)
541 (defcustom tramp-wrong-passwd-regexp
542 (concat "^.*"
543 ;; These strings should be on the last line
544 (regexp-opt '("Permission denied"
545 "Login incorrect"
546 "Login Incorrect"
547 "Connection refused"
548 "Connection closed"
549 "Timeout, server not responding."
550 "Sorry, try again."
551 "Name or service not known"
552 "Host key verification failed."
553 "No supported authentication methods left to try!") t)
554 ".*"
555 "\\|"
556 "^.*\\("
557 ;; Here comes a list of regexes, separated by \\|
558 "Received signal [0-9]+"
559 "\\).*")
560 "Regexp matching a `login failed' message.
561 The regexp should match at end of buffer."
562 :group 'tramp
563 :type 'regexp
564 :require 'tramp)
566 (defcustom tramp-yesno-prompt-regexp
567 (concat
568 (regexp-opt '("Are you sure you want to continue connecting (yes/no)?") t)
569 "\\s-*")
570 "Regular expression matching all yes/no queries which need to be confirmed.
571 The confirmation should be done with yes or no.
572 The regexp should match at end of buffer.
573 See also `tramp-yn-prompt-regexp'."
574 :group 'tramp
575 :type 'regexp
576 :require 'tramp)
578 (defcustom tramp-yn-prompt-regexp
579 (concat
580 (regexp-opt '("Store key in cache? (y/n)"
581 "Update cached key? (y/n, Return cancels connection)")
583 "\\s-*")
584 "Regular expression matching all y/n queries which need to be confirmed.
585 The confirmation should be done with y or n.
586 The regexp should match at end of buffer.
587 See also `tramp-yesno-prompt-regexp'."
588 :group 'tramp
589 :type 'regexp
590 :require 'tramp)
592 (defcustom tramp-terminal-prompt-regexp
593 (concat "\\("
594 "TERM = (.*)"
595 "\\|"
596 "Terminal type\\? \\[.*\\]"
597 "\\)\\s-*")
598 "Regular expression matching all terminal setting prompts.
599 The regexp should match at end of buffer.
600 The answer will be provided by `tramp-action-terminal', which see."
601 :group 'tramp
602 :type 'regexp
603 :require 'tramp)
605 (defcustom tramp-operation-not-permitted-regexp
606 (concat "\\(" "preserving times.*" "\\|" "set mode" "\\)" ":\\s-*"
607 (regexp-opt '("Operation not permitted") t))
608 "Regular expression matching keep-date problems in (s)cp operations.
609 Copying has been performed successfully already, so this message can
610 be ignored safely."
611 :group 'tramp
612 :type 'regexp
613 :require 'tramp)
615 (defcustom tramp-copy-failed-regexp
616 (concat "\\(.+: "
617 (regexp-opt '("Permission denied"
618 "not a regular file"
619 "is a directory"
620 "No such file or directory")
622 "\\)\\s-*")
623 "Regular expression matching copy problems in (s)cp operations."
624 :group 'tramp
625 :type 'regexp
626 :require 'tramp)
628 (defcustom tramp-process-alive-regexp
630 "Regular expression indicating a process has finished.
631 In fact this expression is empty by intention, it will be used only to
632 check regularly the status of the associated process.
633 The answer will be provided by `tramp-action-process-alive',
634 `tramp-action-out-of-band', which see."
635 :group 'tramp
636 :type 'regexp
637 :require 'tramp)
639 (defconst tramp-temp-name-prefix "tramp."
640 "Prefix to use for temporary files.
641 If this is a relative file name (such as \"tramp.\"), it is considered
642 relative to the directory name returned by the function
643 `tramp-compat-temporary-file-directory' (which see). It may also be an
644 absolute file name; don't forget to include a prefix for the filename
645 part, though.")
647 (defconst tramp-temp-buffer-name " *tramp temp*"
648 "Buffer name for a temporary buffer.
649 It shall be used in combination with `generate-new-buffer-name'.")
651 (defvar tramp-temp-buffer-file-name nil
652 "File name of a persistent local temporary file.
653 Useful for \"rsync\" like methods.")
654 (make-variable-buffer-local 'tramp-temp-buffer-file-name)
655 (put 'tramp-temp-buffer-file-name 'permanent-local t)
657 ;;;###autoload
658 (defcustom tramp-syntax 'ftp
659 "Tramp filename syntax to be used.
661 It can have the following values:
663 `ftp' -- Ange-FTP like syntax
664 `sep' -- Syntax as defined for XEmacs originally."
665 :group 'tramp
666 :version "24.4"
667 :type '(choice (const :tag "Ange-FTP" ftp)
668 (const :tag "XEmacs" sep))
669 :require 'tramp)
671 (defconst tramp-prefix-format
672 (cond ((equal tramp-syntax 'ftp) "/")
673 ((equal tramp-syntax 'sep) "/[")
674 (t (error "Wrong `tramp-syntax' defined")))
675 "String matching the very beginning of Tramp file names.
676 Used in `tramp-make-tramp-file-name'.")
678 (defconst tramp-prefix-regexp
679 (concat "^" (regexp-quote tramp-prefix-format))
680 "Regexp matching the very beginning of Tramp file names.
681 Should always start with \"^\". Derived from `tramp-prefix-format'.")
683 (defconst tramp-method-regexp
684 "[a-zA-Z_0-9-]+"
685 "Regexp matching methods identifiers.")
687 (defconst tramp-postfix-method-format
688 (cond ((equal tramp-syntax 'ftp) ":")
689 ((equal tramp-syntax 'sep) "/")
690 (t (error "Wrong `tramp-syntax' defined")))
691 "String matching delimiter between method and user or host names.
692 Used in `tramp-make-tramp-file-name'.")
694 (defconst tramp-postfix-method-regexp
695 (regexp-quote tramp-postfix-method-format)
696 "Regexp matching delimiter between method and user or host names.
697 Derived from `tramp-postfix-method-format'.")
699 (defconst tramp-user-regexp "[^/|: \t]+"
700 "Regexp matching user names.")
702 ;;;###tramp-autoload
703 (defconst tramp-prefix-domain-format "%"
704 "String matching delimiter between user and domain names.")
706 ;;;###tramp-autoload
707 (defconst tramp-prefix-domain-regexp
708 (regexp-quote tramp-prefix-domain-format)
709 "Regexp matching delimiter between user and domain names.
710 Derived from `tramp-prefix-domain-format'.")
712 (defconst tramp-domain-regexp "[-a-zA-Z0-9_.]+"
713 "Regexp matching domain names.")
715 (defconst tramp-user-with-domain-regexp
716 (concat "\\(" tramp-user-regexp "\\)"
717 tramp-prefix-domain-regexp
718 "\\(" tramp-domain-regexp "\\)")
719 "Regexp matching user names with domain names.")
721 (defconst tramp-postfix-user-format "@"
722 "String matching delimiter between user and host names.
723 Used in `tramp-make-tramp-file-name'.")
725 (defconst tramp-postfix-user-regexp
726 (regexp-quote tramp-postfix-user-format)
727 "Regexp matching delimiter between user and host names.
728 Derived from `tramp-postfix-user-format'.")
730 (defconst tramp-host-regexp "[a-zA-Z0-9_.-]+"
731 "Regexp matching host names.")
733 (defconst tramp-prefix-ipv6-format
734 (cond ((equal tramp-syntax 'ftp) "[")
735 ((equal tramp-syntax 'sep) "")
736 (t (error "Wrong `tramp-syntax' defined")))
737 "String matching left hand side of IPv6 addresses.
738 Used in `tramp-make-tramp-file-name'.")
740 (defconst tramp-prefix-ipv6-regexp
741 (regexp-quote tramp-prefix-ipv6-format)
742 "Regexp matching left hand side of IPv6 addresses.
743 Derived from `tramp-prefix-ipv6-format'.")
745 ;; The following regexp is a bit sloppy. But it shall serve our
746 ;; purposes. It covers also IPv4 mapped IPv6 addresses, like in
747 ;; "::ffff:192.168.0.1".
748 (defconst tramp-ipv6-regexp
749 "\\(?:\\(?:[a-zA-Z0-9]+\\)?:\\)+[a-zA-Z0-9.]+"
750 "Regexp matching IPv6 addresses.")
752 (defconst tramp-postfix-ipv6-format
753 (cond ((equal tramp-syntax 'ftp) "]")
754 ((equal tramp-syntax 'sep) "")
755 (t (error "Wrong `tramp-syntax' defined")))
756 "String matching right hand side of IPv6 addresses.
757 Used in `tramp-make-tramp-file-name'.")
759 (defconst tramp-postfix-ipv6-regexp
760 (regexp-quote tramp-postfix-ipv6-format)
761 "Regexp matching right hand side of IPv6 addresses.
762 Derived from `tramp-postfix-ipv6-format'.")
764 (defconst tramp-prefix-port-format
765 (cond ((equal tramp-syntax 'ftp) "#")
766 ((equal tramp-syntax 'sep) "#")
767 (t (error "Wrong `tramp-syntax' defined")))
768 "String matching delimiter between host names and port numbers.")
770 (defconst tramp-prefix-port-regexp
771 (regexp-quote tramp-prefix-port-format)
772 "Regexp matching delimiter between host names and port numbers.
773 Derived from `tramp-prefix-port-format'.")
775 (defconst tramp-port-regexp "[0-9]+"
776 "Regexp matching port numbers.")
778 (defconst tramp-host-with-port-regexp
779 (concat "\\(" tramp-host-regexp "\\)"
780 tramp-prefix-port-regexp
781 "\\(" tramp-port-regexp "\\)")
782 "Regexp matching host names with port numbers.")
784 (defconst tramp-postfix-hop-format "|"
785 "String matching delimiter after ad-hoc hop definitions.")
787 (defconst tramp-postfix-hop-regexp
788 (regexp-quote tramp-postfix-hop-format)
789 "Regexp matching delimiter after ad-hoc hop definitions.
790 Derived from `tramp-postfix-hop-format'.")
792 (defconst tramp-postfix-host-format
793 (cond ((equal tramp-syntax 'ftp) ":")
794 ((equal tramp-syntax 'sep) "]")
795 (t (error "Wrong `tramp-syntax' defined")))
796 "String matching delimiter between host names and localnames.
797 Used in `tramp-make-tramp-file-name'.")
799 (defconst tramp-postfix-host-regexp
800 (regexp-quote tramp-postfix-host-format)
801 "Regexp matching delimiter between host names and localnames.
802 Derived from `tramp-postfix-host-format'.")
804 (defconst tramp-localname-regexp ".*$"
805 "Regexp matching localnames.")
807 (defconst tramp-unknown-id-string "UNKNOWN"
808 "String used to denote an unknown user or group")
810 (defconst tramp-unknown-id-integer -1
811 "Integer used to denote an unknown user or group")
813 ;;; File name format:
815 (defconst tramp-remote-file-name-spec-regexp
816 (concat
817 "\\(?:" "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp "\\)?"
818 "\\(?:" "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp "\\)?"
819 "\\(" "\\(?:" tramp-host-regexp "\\|"
820 tramp-prefix-ipv6-regexp "\\(?:" tramp-ipv6-regexp "\\)?"
821 tramp-postfix-ipv6-regexp "\\)"
822 "\\(?:" tramp-prefix-port-regexp tramp-port-regexp "\\)?" "\\)?")
823 "Regular expression matching a Tramp file name between prefix and postfix.")
825 (defconst tramp-file-name-structure
826 (list
827 (concat
828 tramp-prefix-regexp
829 "\\(" "\\(?:" tramp-remote-file-name-spec-regexp
830 tramp-postfix-hop-regexp "\\)+" "\\)?"
831 tramp-remote-file-name-spec-regexp tramp-postfix-host-regexp
832 "\\(" tramp-localname-regexp "\\)")
833 5 6 7 8 1)
834 "List of six elements (REGEXP METHOD USER HOST FILE HOP), detailing \
835 the Tramp file name structure.
837 The first element REGEXP is a regular expression matching a Tramp file
838 name. The regex should contain parentheses around the method name,
839 the user name, the host name, and the file name parts.
841 The second element METHOD is a number, saying which pair of
842 parentheses matches the method name. The third element USER is
843 similar, but for the user name. The fourth element HOST is similar,
844 but for the host name. The fifth element FILE is for the file name.
845 The last element HOP is the ad-hoc hop definition, which could be a
846 cascade of several hops.
848 These numbers are passed directly to `match-string', which see. That
849 means the opening parentheses are counted to identify the pair.
851 See also `tramp-file-name-regexp'.")
853 ;;;###autoload
854 (defconst tramp-file-name-regexp-unified
855 (if (memq system-type '(cygwin windows-nt))
856 "\\`/\\(\\[.*\\]\\|[^/|:]\\{2,\\}[^/|]*\\):"
857 "\\`/[^/|:][^/|]*:")
858 "Value for `tramp-file-name-regexp' for unified remoting.
859 See `tramp-file-name-structure' for more explanations.
861 On W32 systems, the volume letter must be ignored.")
863 ;;;###autoload
864 (defconst tramp-file-name-regexp-separate "\\`/\\[.*\\]"
865 "Value for `tramp-file-name-regexp' for separate remoting.
866 See `tramp-file-name-structure' for more explanations.")
868 ;;;###autoload
869 (defvar tramp-file-name-regexp
870 (cond ((equal tramp-syntax 'ftp) tramp-file-name-regexp-unified)
871 ((equal tramp-syntax 'sep) tramp-file-name-regexp-separate)
872 (t (error "Wrong `tramp-syntax' defined")))
873 "Regular expression matching file names handled by Tramp.
874 This regexp should match Tramp file names but no other file
875 names. When calling `tramp-register-file-name-handlers', the
876 initial value is overwritten by the car of `tramp-file-name-structure'.")
878 ;;;###autoload
879 (defconst tramp-completion-file-name-regexp-unified
880 (if (memq system-type '(cygwin windows-nt))
881 "\\`/[^/]\\{2,\\}\\'" "\\`/[^/]*\\'")
882 "Value for `tramp-completion-file-name-regexp' for unified remoting.
883 See `tramp-file-name-structure' for more explanations.
885 On W32 systems, the volume letter must be ignored.")
887 ;;;###autoload
888 (defconst tramp-completion-file-name-regexp-separate
889 "\\`/\\([[][^]]*\\)?\\'"
890 "Value for `tramp-completion-file-name-regexp' for separate remoting.
891 See `tramp-file-name-structure' for more explanations.")
893 ;;;###autoload
894 (defconst tramp-completion-file-name-regexp
895 (cond ((equal tramp-syntax 'ftp) tramp-completion-file-name-regexp-unified)
896 ((equal tramp-syntax 'sep) tramp-completion-file-name-regexp-separate)
897 (t (error "Wrong `tramp-syntax' defined")))
898 "Regular expression matching file names handled by Tramp completion.
899 This regexp should match partial Tramp file names only.
901 Please note that the entry in `file-name-handler-alist' is made when
902 this file \(tramp.el) is loaded. This means that this variable must be set
903 before loading tramp.el. Alternatively, `file-name-handler-alist' can be
904 updated after changing this variable.
906 Also see `tramp-file-name-structure'.")
908 ;; Chunked sending kludge. We set this to 500 for black-listed constellations
909 ;; known to have a bug in `process-send-string'; some ssh connections appear
910 ;; to drop bytes when data is sent too quickly. There is also a connection
911 ;; buffer local variable, which is computed depending on remote host properties
912 ;; when `tramp-chunksize' is zero or nil.
913 (defcustom tramp-chunksize (when (memq system-type '(hpux)) 500)
914 ;; Parentheses in docstring starting at beginning of line are escaped.
915 ;; Fontification is messed up when
916 ;; `open-paren-in-column-0-is-defun-start' set to t.
917 "If non-nil, chunksize for sending input to local process.
918 It is necessary only on systems which have a buggy `process-send-string'
919 implementation. The necessity, whether this variable must be set, can be
920 checked via the following code:
922 (with-temp-buffer
923 (let* ((user \"xxx\") (host \"yyy\")
924 (init 0) (step 50)
925 (sent init) (received init))
926 (while (= sent received)
927 (setq sent (+ sent step))
928 (erase-buffer)
929 (let ((proc (start-process (buffer-name) (current-buffer)
930 \"ssh\" \"-l\" user host \"wc\" \"-c\")))
931 (when (process-live-p proc)
932 (process-send-string proc (make-string sent ?\\ ))
933 (process-send-eof proc)
934 (process-send-eof proc))
935 (while (not (progn (goto-char (point-min))
936 (re-search-forward \"\\\\w+\" (point-max) t)))
937 (accept-process-output proc 1))
938 (when (process-live-p proc)
939 (setq received (string-to-number (match-string 0)))
940 (delete-process proc)
941 (message \"Bytes sent: %s\\tBytes received: %s\" sent received)
942 (sit-for 0))))
943 (if (> sent (+ init step))
944 (message \"You should set `tramp-chunksize' to a maximum of %s\"
945 (- sent step))
946 (message \"Test does not work\")
947 (display-buffer (current-buffer))
948 (sit-for 30))))
950 In the Emacs normally running Tramp, evaluate the above code
951 \(replace \"xxx\" and \"yyy\" by the remote user and host name,
952 respectively). You can do this, for example, by pasting it into
953 the `*scratch*' buffer and then hitting C-j with the cursor after the
954 last closing parenthesis. Note that it works only if you have configured
955 \"ssh\" to run without password query, see ssh-agent(1).
957 You will see the number of bytes sent successfully to the remote host.
958 If that number exceeds 1000, you can stop the execution by hitting
959 C-g, because your Emacs is likely clean.
961 When it is necessary to set `tramp-chunksize', you might consider to
962 use an out-of-the-band method \(like \"scp\") instead of an internal one
963 \(like \"ssh\"), because setting `tramp-chunksize' to non-nil decreases
964 performance.
966 If your Emacs is buggy, the code stops and gives you an indication
967 about the value `tramp-chunksize' should be set. Maybe you could just
968 experiment a bit, e.g. changing the values of `init' and `step'
969 in the third line of the code.
971 Please raise a bug report via \"M-x tramp-bug\" if your system needs
972 this variable to be set as well."
973 :group 'tramp
974 :type '(choice (const nil) integer)
975 :require 'tramp)
977 ;; Logging in to a remote host normally requires obtaining a pty. But
978 ;; Emacs on macOS has process-connection-type set to nil by default,
979 ;; so on those systems Tramp doesn't obtain a pty. Here, we allow
980 ;; for an override of the system default.
981 (defcustom tramp-process-connection-type t
982 "Overrides `process-connection-type' for connections from Tramp.
983 Tramp binds `process-connection-type' to the value given here before
984 opening a connection to a remote host."
985 :group 'tramp
986 :type '(choice (const nil) (const t) (const pty))
987 :require 'tramp)
989 (defcustom tramp-connection-timeout 60
990 "Defines the max time to wait for establishing a connection (in seconds).
991 This can be overwritten for different connection types in `tramp-methods'.
993 The timeout does not include the time reading a password."
994 :group 'tramp
995 :version "24.4"
996 :type 'integer
997 :require 'tramp)
999 (defcustom tramp-connection-min-time-diff 5
1000 "Defines seconds between two consecutive connection attempts.
1001 This is necessary as self defense mechanism, in order to avoid
1002 yo-yo connection attempts when the remote host is unavailable.
1004 A value of 0 or nil suppresses this check. This might be
1005 necessary, when several out-of-order copy operations are
1006 performed, or when several asynchronous processes will be started
1007 in a short time frame. In those cases it is recommended to
1008 let-bind this variable."
1009 :group 'tramp
1010 :version "24.4"
1011 :type '(choice (const nil) integer)
1012 :require 'tramp)
1014 (defcustom tramp-completion-reread-directory-timeout 10
1015 "Defines seconds since last remote command before rereading a directory.
1016 A remote directory might have changed its contents. In order to
1017 make it visible during file name completion in the minibuffer,
1018 Tramp flushes its cache and rereads the directory contents when
1019 more than `tramp-completion-reread-directory-timeout' seconds
1020 have been gone since last remote command execution. A value of t
1021 would require an immediate reread during filename completion, nil
1022 means to use always cached values for the directory contents."
1023 :group 'tramp
1024 :type '(choice (const nil) (const t) integer)
1025 :require 'tramp)
1027 ;;; Internal Variables:
1029 (defvar tramp-current-method nil
1030 "Connection method for this *tramp* buffer.")
1032 (defvar tramp-current-user nil
1033 "Remote login name for this *tramp* buffer.")
1035 (defvar tramp-current-host nil
1036 "Remote host for this *tramp* buffer.")
1038 (defvar tramp-current-connection nil
1039 "Last connection timestamp.")
1041 (defconst tramp-completion-file-name-handler-alist
1042 '((expand-file-name . tramp-completion-handle-expand-file-name)
1043 (file-name-all-completions
1044 . tramp-completion-handle-file-name-all-completions)
1045 (file-name-completion . tramp-completion-handle-file-name-completion))
1046 "Alist of completion handler functions.
1047 Used for file names matching `tramp-completion-file-name-regexp'.
1048 Operations not mentioned here will be handled by Tramp's file
1049 name handler functions, or the normal Emacs functions.")
1051 ;; Handlers for foreign methods, like FTP or SMB, shall be plugged here.
1052 ;;;###tramp-autoload
1053 (defvar tramp-foreign-file-name-handler-alist nil
1054 "Alist of elements (FUNCTION . HANDLER) for foreign methods handled specially.
1055 If (FUNCTION FILENAME) returns non-nil, then all I/O on that file is done by
1056 calling HANDLER.")
1058 ;;; Internal functions which must come first:
1060 ;; Conversion functions between external representation and
1061 ;; internal data structure. Convenience functions for internal
1062 ;; data structure.
1064 (defun tramp-get-method-parameter (vec param)
1065 "Return the method parameter PARAM.
1066 If VEC is a vector, check first in connection properties.
1067 Afterwards, check in `tramp-methods'. If the `tramp-methods'
1068 entry does not exist, return nil."
1069 (let ((hash-entry
1070 (replace-regexp-in-string "^tramp-" "" (symbol-name param))))
1071 (if (tramp-connection-property-p vec hash-entry)
1072 ;; We use the cached property.
1073 (tramp-get-connection-property vec hash-entry nil)
1074 ;; Use the static value from `tramp-methods'.
1075 (let ((methods-entry
1076 (assoc param (assoc (tramp-file-name-method vec) tramp-methods))))
1077 (when methods-entry (cadr methods-entry))))))
1079 (defun tramp-file-name-p (vec)
1080 "Check, whether VEC is a Tramp object."
1081 (and (vectorp vec) (= 5 (length vec))))
1083 (defun tramp-file-name-method (vec)
1084 "Return method component of VEC."
1085 (and (tramp-file-name-p vec) (aref vec 0)))
1087 (defun tramp-file-name-user (vec)
1088 "Return user component of VEC."
1089 (and (tramp-file-name-p vec) (aref vec 1)))
1091 (defun tramp-file-name-host (vec)
1092 "Return host component of VEC."
1093 (and (tramp-file-name-p vec) (aref vec 2)))
1095 (defun tramp-file-name-localname (vec)
1096 "Return localname component of VEC."
1097 (and (tramp-file-name-p vec) (aref vec 3)))
1099 (defun tramp-file-name-hop (vec)
1100 "Return hop component of VEC."
1101 (and (tramp-file-name-p vec) (aref vec 4)))
1103 ;; The user part of a Tramp file name vector can be of kind
1104 ;; "user%domain". Sometimes, we must extract these parts.
1105 (defun tramp-file-name-real-user (vec)
1106 "Return the user name of VEC without domain."
1107 (save-match-data
1108 (let ((user (tramp-file-name-user vec)))
1109 (if (and (stringp user)
1110 (string-match tramp-user-with-domain-regexp user))
1111 (match-string 1 user)
1112 user))))
1114 (defun tramp-file-name-domain (vec)
1115 "Return the domain name of VEC."
1116 (save-match-data
1117 (let ((user (tramp-file-name-user vec)))
1118 (and (stringp user)
1119 (string-match tramp-user-with-domain-regexp user)
1120 (match-string 2 user)))))
1122 ;; The host part of a Tramp file name vector can be of kind
1123 ;; "host#port". Sometimes, we must extract these parts.
1124 (defun tramp-file-name-real-host (vec)
1125 "Return the host name of VEC without port."
1126 (save-match-data
1127 (let ((host (tramp-file-name-host vec)))
1128 (if (and (stringp host)
1129 (string-match tramp-host-with-port-regexp host))
1130 (match-string 1 host)
1131 host))))
1133 (defun tramp-file-name-port (vec)
1134 "Return the port number of VEC."
1135 (save-match-data
1136 (let ((host (tramp-file-name-host vec)))
1137 (or (and (stringp host)
1138 (string-match tramp-host-with-port-regexp host)
1139 (string-to-number (match-string 2 host)))
1140 (tramp-get-method-parameter vec 'tramp-default-port)))))
1142 ;; The localname can be quoted with "/:". Extract this.
1143 (defun tramp-file-name-unquote-localname (vec)
1144 "Return unquoted localname component of VEC."
1145 (tramp-compat-file-name-unquote (tramp-file-name-localname vec)))
1147 ;;;###tramp-autoload
1148 (defun tramp-tramp-file-p (name)
1149 "Return t if NAME is a string with Tramp file name syntax."
1150 (save-match-data
1151 (and (stringp name)
1152 ;; No "/:" and "/c:". This is not covered by `tramp-file-name-regexp'.
1153 (not (string-match
1154 (if (memq system-type '(cygwin windows-nt))
1155 "^/[[:alpha:]]?:" "^/:")
1156 name))
1157 (string-match tramp-file-name-regexp name))))
1159 (defun tramp-find-method (method user host)
1160 "Return the right method string to use.
1161 This is METHOD, if non-nil. Otherwise, do a lookup in
1162 `tramp-default-method-alist'."
1163 (let ((result
1164 (or method
1165 (let ((choices tramp-default-method-alist)
1166 lmethod item)
1167 (while choices
1168 (setq item (pop choices))
1169 (when (and (string-match (or (nth 0 item) "") (or host ""))
1170 (string-match (or (nth 1 item) "") (or user "")))
1171 (setq lmethod (nth 2 item))
1172 (setq choices nil)))
1173 lmethod)
1174 tramp-default-method)))
1175 ;; We must mark, whether a default value has been used.
1176 (if (or method (null result))
1177 result
1178 (propertize result 'tramp-default t))))
1180 (defun tramp-find-user (method user host)
1181 "Return the right user string to use.
1182 This is USER, if non-nil. Otherwise, do a lookup in
1183 `tramp-default-user-alist'."
1184 (let ((result
1185 (or user
1186 (let ((choices tramp-default-user-alist)
1187 luser item)
1188 (while choices
1189 (setq item (pop choices))
1190 (when (and (string-match (or (nth 0 item) "") (or method ""))
1191 (string-match (or (nth 1 item) "") (or host "")))
1192 (setq luser (nth 2 item))
1193 (setq choices nil)))
1194 luser)
1195 tramp-default-user)))
1196 ;; We must mark, whether a default value has been used.
1197 (if (or user (null result))
1198 result
1199 (propertize result 'tramp-default t))))
1201 (defun tramp-find-host (method user host)
1202 "Return the right host string to use.
1203 This is HOST, if non-nil. Otherwise, it is `tramp-default-host'."
1204 (or (and (> (length host) 0) host)
1205 (let ((choices tramp-default-host-alist)
1206 lhost item)
1207 (while choices
1208 (setq item (pop choices))
1209 (when (and (string-match (or (nth 0 item) "") (or method ""))
1210 (string-match (or (nth 1 item) "") (or user "")))
1211 (setq lhost (nth 2 item))
1212 (setq choices nil)))
1213 lhost)
1214 tramp-default-host))
1216 (defun tramp-check-proper-method-and-host (vec)
1217 "Check method and host name of VEC."
1218 (let ((method (tramp-file-name-method vec))
1219 (user (tramp-file-name-user vec))
1220 (host (tramp-file-name-host vec))
1221 (methods (mapcar 'car tramp-methods)))
1222 (when (and method (not (member method methods)))
1223 (tramp-cleanup-connection vec)
1224 (tramp-compat-user-error vec "Unknown method \"%s\"" method))
1225 (when (and (equal tramp-syntax 'ftp) host
1226 (or (null method) (get-text-property 0 'tramp-default method))
1227 (or (null user) (get-text-property 0 'tramp-default user))
1228 (member host methods))
1229 (tramp-cleanup-connection vec)
1230 (tramp-compat-user-error
1231 vec "Host name must not match method \"%s\"" host))))
1233 (defun tramp-dissect-file-name (name &optional nodefault)
1234 "Return a `tramp-file-name' structure.
1235 The structure consists of remote method, remote user, remote host,
1236 localname (file name on remote host) and hop. If NODEFAULT is
1237 non-nil, the file name parts are not expanded to their default
1238 values."
1239 (save-match-data
1240 (unless (tramp-tramp-file-p name)
1241 (tramp-compat-user-error nil "Not a Tramp file name: \"%s\"" name))
1242 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
1243 (let ((method (match-string (nth 1 tramp-file-name-structure) name))
1244 (user (match-string (nth 2 tramp-file-name-structure) name))
1245 (host (match-string (nth 3 tramp-file-name-structure) name))
1246 (localname (match-string (nth 4 tramp-file-name-structure) name))
1247 (hop (match-string (nth 5 tramp-file-name-structure) name)))
1248 (when host
1249 (when (string-match tramp-prefix-ipv6-regexp host)
1250 (setq host (replace-match "" nil t host)))
1251 (when (string-match tramp-postfix-ipv6-regexp host)
1252 (setq host (replace-match "" nil t host))))
1253 (if nodefault
1254 (vector method user host localname hop)
1255 (vector
1256 (tramp-find-method method user host)
1257 (tramp-find-user method user host)
1258 (tramp-find-host method user host)
1259 localname hop))))))
1261 (defun tramp-buffer-name (vec)
1262 "A name for the connection buffer VEC."
1263 (let ((method (tramp-file-name-method vec))
1264 (user (tramp-file-name-user vec))
1265 (host (tramp-file-name-real-host vec)))
1266 (if (not (zerop (length user)))
1267 (format "*tramp/%s %s@%s*" method user host)
1268 (format "*tramp/%s %s*" method host))))
1270 (defun tramp-make-tramp-file-name (method user host localname &optional hop)
1271 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1272 When not nil, an optional HOP is prepended."
1273 (concat tramp-prefix-format hop
1274 (when (not (zerop (length method)))
1275 (concat method tramp-postfix-method-format))
1276 (when (not (zerop (length user)))
1277 (concat user tramp-postfix-user-format))
1278 (when host
1279 (if (string-match tramp-ipv6-regexp host)
1280 (concat tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1281 host))
1282 tramp-postfix-host-format
1283 (when localname localname)))
1285 (defun tramp-completion-make-tramp-file-name (method user host localname)
1286 "Constructs a Tramp file name from METHOD, USER, HOST and LOCALNAME.
1287 It must not be a complete Tramp file name, but as long as there are
1288 necessary only. This function will be used in file name completion."
1289 (concat tramp-prefix-format
1290 (when (not (zerop (length method)))
1291 (concat method tramp-postfix-method-format))
1292 (when (not (zerop (length user)))
1293 (concat user tramp-postfix-user-format))
1294 (when (not (zerop (length host)))
1295 (concat
1296 (if (string-match tramp-ipv6-regexp host)
1297 (concat
1298 tramp-prefix-ipv6-format host tramp-postfix-ipv6-format)
1299 host)
1300 tramp-postfix-host-format))
1301 (when localname localname)))
1303 (defun tramp-get-buffer (vec)
1304 "Get the connection buffer to be used for VEC."
1305 (or (get-buffer (tramp-buffer-name vec))
1306 (with-current-buffer (get-buffer-create (tramp-buffer-name vec))
1307 ;; We use the existence of connection property "process-buffer"
1308 ;; as indication, whether a connection is active.
1309 (tramp-set-connection-property
1310 vec "process-buffer"
1311 (tramp-get-connection-property vec "process-buffer" nil))
1312 (setq buffer-undo-list t)
1313 (setq default-directory
1314 (tramp-make-tramp-file-name
1315 (tramp-file-name-method vec)
1316 (tramp-file-name-user vec)
1317 (tramp-file-name-host vec)
1318 "/"))
1319 (current-buffer))))
1321 (defun tramp-get-connection-buffer (vec)
1322 "Get the connection buffer to be used for VEC.
1323 In case a second asynchronous communication has been started, it is different
1324 from `tramp-get-buffer'."
1325 (or (tramp-get-connection-property vec "process-buffer" nil)
1326 (tramp-get-buffer vec)))
1328 (defun tramp-get-connection-name (vec)
1329 "Get the connection name to be used for VEC.
1330 In case a second asynchronous communication has been started, it is different
1331 from the default one."
1332 (or (tramp-get-connection-property vec "process-name" nil)
1333 (tramp-buffer-name vec)))
1335 (defun tramp-get-connection-process (vec)
1336 "Get the connection process to be used for VEC.
1337 In case a second asynchronous communication has been started, it is different
1338 from the default one."
1339 (get-process (tramp-get-connection-name vec)))
1341 (defun tramp-set-connection-local-variables (vec)
1342 "Set connection-local variables in the connection buffer used for VEC.
1343 If connection-local variables are not supported by this Emacs
1344 version, the function does nothing."
1345 ;; `tramp-get-connection-buffer' sets proper `default-directory'."
1346 (with-current-buffer (tramp-get-connection-buffer vec)
1347 ;; `hack-connection-local-variables-apply' exists since Emacs 26.1.
1348 (tramp-compat-funcall 'hack-connection-local-variables-apply)))
1350 (defun tramp-debug-buffer-name (vec)
1351 "A name for the debug buffer for VEC."
1352 (let ((method (tramp-file-name-method vec))
1353 (user (tramp-file-name-user vec))
1354 (host (tramp-file-name-real-host vec)))
1355 (if (not (zerop (length user)))
1356 (format "*debug tramp/%s %s@%s*" method user host)
1357 (format "*debug tramp/%s %s*" method host))))
1359 (defconst tramp-debug-outline-regexp
1360 "[0-9]+:[0-9]+:[0-9]+\\.[0-9]+ [a-z0-9-]+ (\\([0-9]+\\)) #"
1361 "Used for highlighting Tramp debug buffers in `outline-mode'.")
1363 (defun tramp-debug-outline-level ()
1364 "Return the depth to which a statement is nested in the outline.
1365 Point must be at the beginning of a header line.
1367 The outline level is equal to the verbosity of the Tramp message."
1368 (1+ (string-to-number (match-string 1))))
1370 (defun tramp-get-debug-buffer (vec)
1371 "Get the debug buffer for VEC."
1372 (with-current-buffer
1373 (get-buffer-create (tramp-debug-buffer-name vec))
1374 (when (bobp)
1375 (setq buffer-undo-list t)
1376 ;; So it does not get loaded while `outline-regexp' is let-bound.
1377 (require 'outline)
1378 ;; Activate `outline-mode'. This runs `text-mode-hook' and
1379 ;; `outline-mode-hook'. We must prevent that local processes
1380 ;; die. Yes: I've seen `flyspell-mode', which starts "ispell".
1381 ;; Furthermore, `outline-regexp' must have the correct value
1382 ;; already, because it is used by `font-lock-compile-keywords'.
1383 (let ((default-directory (tramp-compat-temporary-file-directory))
1384 (outline-regexp tramp-debug-outline-regexp))
1385 (outline-mode))
1386 (set (make-local-variable 'outline-regexp) tramp-debug-outline-regexp)
1387 (set (make-local-variable 'outline-level) 'tramp-debug-outline-level))
1388 (current-buffer)))
1390 (defsubst tramp-debug-message (vec fmt-string &rest arguments)
1391 "Append message to debug buffer.
1392 Message is formatted with FMT-STRING as control string and the remaining
1393 ARGUMENTS to actually emit the message (if applicable)."
1394 (with-current-buffer (tramp-get-debug-buffer vec)
1395 (goto-char (point-max))
1396 ;; Headline.
1397 (when (bobp)
1398 (insert
1399 (format
1400 ";; Emacs: %s Tramp: %s -*- mode: outline; -*-"
1401 emacs-version tramp-version))
1402 (when (>= tramp-verbose 10)
1403 (insert
1404 (format
1405 "\n;; Location: %s Git: %s"
1406 (locate-library "tramp") (tramp-repository-get-version)))))
1407 (unless (bolp)
1408 (insert "\n"))
1409 ;; Timestamp.
1410 (let ((now (current-time)))
1411 (insert (format-time-string "%T." now))
1412 (insert (format "%06d " (nth 2 now))))
1413 ;; Calling Tramp function. We suppress compat and trace functions
1414 ;; from being displayed.
1415 (let ((btn 1) btf fn)
1416 (while (not fn)
1417 (setq btf (nth 1 (backtrace-frame btn)))
1418 (if (not btf)
1419 (setq fn "")
1420 (when (symbolp btf)
1421 (setq fn (symbol-name btf))
1422 (unless
1423 (and
1424 (string-match "^tramp" fn)
1425 (not
1426 (string-match
1427 (concat
1429 (regexp-opt
1430 '("tramp-backtrace"
1431 "tramp-compat-condition-case-unless-debug"
1432 "tramp-compat-funcall"
1433 "tramp-compat-user-error"
1434 "tramp-condition-case-unless-debug"
1435 "tramp-debug-message"
1436 "tramp-error"
1437 "tramp-error-with-buffer"
1438 "tramp-message")
1440 "$")
1441 fn)))
1442 (setq fn nil)))
1443 (setq btn (1+ btn))))
1444 ;; The following code inserts filename and line number. Should
1445 ;; be inactive by default, because it is time consuming.
1446 ; (let ((ffn (find-function-noselect (intern fn))))
1447 ; (insert
1448 ; (format
1449 ; "%s:%d: "
1450 ; (file-name-nondirectory (buffer-file-name (car ffn)))
1451 ; (with-current-buffer (car ffn)
1452 ; (1+ (count-lines (point-min) (cdr ffn)))))))
1453 (insert (format "%s " fn)))
1454 ;; The message.
1455 (insert (apply #'format-message fmt-string arguments))))
1457 (defvar tramp-message-show-message t
1458 "Show Tramp message in the minibuffer.
1459 This variable is used to disable messages from `tramp-error'.
1460 The messages are visible anyway, because an error is raised.")
1462 (defsubst tramp-message (vec-or-proc level fmt-string &rest arguments)
1463 "Emit a message depending on verbosity level.
1464 VEC-OR-PROC identifies the Tramp buffer to use. It can be either a
1465 vector or a process. LEVEL says to be quiet if `tramp-verbose' is
1466 less than LEVEL. The message is emitted only if `tramp-verbose' is
1467 greater than or equal to LEVEL.
1469 The message is also logged into the debug buffer when `tramp-verbose'
1470 is greater than or equal 4.
1472 Calls functions `message' and `tramp-debug-message' with FMT-STRING as
1473 control string and the remaining ARGUMENTS to actually emit the message (if
1474 applicable)."
1475 (ignore-errors
1476 (when (<= level tramp-verbose)
1477 ;; Match data must be preserved!
1478 (save-match-data
1479 ;; Display only when there is a minimum level.
1480 (when (and tramp-message-show-message (<= level 3))
1481 (apply 'message
1482 (concat
1483 (cond
1484 ((= level 0) "")
1485 ((= level 1) "")
1486 ((= level 2) "Warning: ")
1487 (t "Tramp: "))
1488 fmt-string)
1489 arguments))
1490 ;; Log only when there is a minimum level.
1491 (when (>= tramp-verbose 4)
1492 ;; Translate proc to vec.
1493 (when (processp vec-or-proc)
1494 (let ((tramp-verbose 0))
1495 (setq vec-or-proc
1496 (tramp-get-connection-property vec-or-proc "vector" nil))))
1497 ;; Append connection buffer for error messages.
1498 (when (= level 1)
1499 (let ((tramp-verbose 0))
1500 (with-current-buffer (tramp-get-connection-buffer vec-or-proc)
1501 (setq fmt-string (concat fmt-string "\n%s")
1502 arguments (append arguments (list (buffer-string)))))))
1503 ;; Do it.
1504 (when (vectorp vec-or-proc)
1505 (apply 'tramp-debug-message
1506 vec-or-proc
1507 (concat (format "(%d) # " level) fmt-string)
1508 arguments)))))))
1510 (defsubst tramp-backtrace (&optional vec-or-proc)
1511 "Dump a backtrace into the debug buffer.
1512 If VEC-OR-PROC is nil, the buffer *debug tramp* is used. This
1513 function is meant for debugging purposes."
1514 (if vec-or-proc
1515 (tramp-message vec-or-proc 10 "\n%s" (with-output-to-string (backtrace)))
1516 (if (>= tramp-verbose 10)
1517 (with-output-to-temp-buffer "*debug tramp*" (backtrace)))))
1519 (defsubst tramp-error (vec-or-proc signal fmt-string &rest arguments)
1520 "Emit an error.
1521 VEC-OR-PROC identifies the connection to use, SIGNAL is the
1522 signal identifier to be raised, remaining arguments passed to
1523 `tramp-message'. Finally, signal SIGNAL is raised."
1524 (let (tramp-message-show-message)
1525 (tramp-backtrace vec-or-proc)
1526 (when vec-or-proc
1527 (tramp-message
1528 vec-or-proc 1 "%s"
1529 (error-message-string
1530 (list signal
1531 (get signal 'error-message)
1532 (apply #'format-message fmt-string arguments)))))
1533 (signal signal (list (apply #'format-message fmt-string arguments)))))
1535 (defsubst tramp-error-with-buffer
1536 (buf vec-or-proc signal fmt-string &rest arguments)
1537 "Emit an error, and show BUF.
1538 If BUF is nil, show the connection buf. Wait for 30\", or until
1539 an input event arrives. The other arguments are passed to `tramp-error'."
1540 (save-window-excursion
1541 (let* ((buf (or (and (bufferp buf) buf)
1542 (and (processp vec-or-proc) (process-buffer vec-or-proc))
1543 (and (vectorp vec-or-proc)
1544 (tramp-get-connection-buffer vec-or-proc))))
1545 (vec (or (and (vectorp vec-or-proc) vec-or-proc)
1546 (and buf (with-current-buffer buf
1547 (tramp-dissect-file-name default-directory))))))
1548 (unwind-protect
1549 (apply 'tramp-error vec-or-proc signal fmt-string arguments)
1550 ;; Save exit.
1551 (when (and buf
1552 tramp-message-show-message
1553 (not (zerop tramp-verbose))
1554 (not (tramp-completion-mode-p))
1555 ;; Show only when Emacs has started already.
1556 (current-message))
1557 (let ((enable-recursive-minibuffers t))
1558 ;; `tramp-error' does not show messages. So we must do it
1559 ;; ourselves.
1560 (apply 'message fmt-string arguments)
1561 ;; Show buffer.
1562 (pop-to-buffer buf)
1563 (discard-input)
1564 (sit-for 30)))
1565 ;; Reset timestamp. It would be wrong after waiting for a while.
1566 (when (equal (butlast (append vec nil) 2)
1567 (car tramp-current-connection))
1568 (setcdr tramp-current-connection (current-time)))))))
1570 (defmacro with-parsed-tramp-file-name (filename var &rest body)
1571 "Parse a Tramp filename and make components available in the body.
1573 First arg FILENAME is evaluated and dissected into its components.
1574 Second arg VAR is a symbol. It is used as a variable name to hold
1575 the filename structure. It is also used as a prefix for the variables
1576 holding the components. For example, if VAR is the symbol `foo', then
1577 `foo' will be bound to the whole structure, `foo-method' will be bound to
1578 the method component, and so on for `foo-user', `foo-host', `foo-localname',
1579 `foo-hop'.
1581 Remaining args are Lisp expressions to be evaluated (inside an implicit
1582 `progn').
1584 If VAR is nil, then we bind `v' to the structure and `method', `user',
1585 `host', `localname', `hop' to the components."
1586 (let ((bindings
1587 (mapcar (lambda (elem)
1588 `(,(if var (intern (format "%s-%s" var elem)) elem)
1589 (,(intern (format "tramp-file-name-%s" elem))
1590 ,(or var 'v))))
1591 '(method user host localname hop))))
1592 `(let* ((,(or var 'v) (tramp-dissect-file-name ,filename))
1593 ,@bindings)
1594 ;; We don't know which of those vars will be used, so we bind them all,
1595 ;; and then add here a dummy use of all those variables, so we don't get
1596 ;; flooded by warnings about those vars `body' didn't use.
1597 (ignore ,@(mapcar #'car bindings))
1598 ,@body)))
1600 (put 'with-parsed-tramp-file-name 'lisp-indent-function 2)
1601 (put 'with-parsed-tramp-file-name 'edebug-form-spec '(form symbolp body))
1602 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-parsed-tramp-file-name\\>"))
1604 (defun tramp-progress-reporter-update (reporter &optional value)
1605 "Report progress of an operation for Tramp."
1606 (let* ((parameters (cdr reporter))
1607 (message (aref parameters 3)))
1608 (when (string-match message (or (current-message) ""))
1609 (progress-reporter-update reporter value))))
1611 (defmacro with-tramp-progress-reporter (vec level message &rest body)
1612 "Executes BODY, spinning a progress reporter with MESSAGE.
1613 If LEVEL does not fit for visible messages, there are only traces
1614 without a visible progress reporter."
1615 (declare (indent 3) (debug t))
1616 `(progn
1617 (tramp-message ,vec ,level "%s..." ,message)
1618 (let ((cookie "failed")
1620 ;; We start a pulsing progress reporter after 3 seconds. Feature
1621 ;; introduced in Emacs 24.1.
1622 (when (and tramp-message-show-message
1623 ;; Display only when there is a minimum level.
1624 (<= ,level (min tramp-verbose 3)))
1625 (ignore-errors
1626 (let ((pr (make-progress-reporter ,message nil nil)))
1627 (when pr
1628 (run-at-time
1629 3 0.1 #'tramp-progress-reporter-update pr)))))))
1630 (unwind-protect
1631 ;; Execute the body.
1632 (prog1 (progn ,@body) (setq cookie "done"))
1633 ;; Stop progress reporter.
1634 (if tm (cancel-timer tm))
1635 (tramp-message ,vec ,level "%s...%s" ,message cookie)))))
1637 (font-lock-add-keywords
1638 'emacs-lisp-mode '("\\<with-tramp-progress-reporter\\>"))
1640 (defmacro with-tramp-file-property (vec file property &rest body)
1641 "Check in Tramp cache for PROPERTY, otherwise execute BODY and set cache.
1642 FILE must be a local file name on a connection identified via VEC."
1643 `(if (file-name-absolute-p ,file)
1644 (let ((value (tramp-get-file-property ,vec ,file ,property 'undef)))
1645 (when (eq value 'undef)
1646 ;; We cannot pass @body as parameter to
1647 ;; `tramp-set-file-property' because it mangles our
1648 ;; debug messages.
1649 (setq value (progn ,@body))
1650 (tramp-set-file-property ,vec ,file ,property value))
1651 value)
1652 ,@body))
1654 (put 'with-tramp-file-property 'lisp-indent-function 3)
1655 (put 'with-tramp-file-property 'edebug-form-spec t)
1656 (font-lock-add-keywords 'emacs-lisp-mode '("\\<with-tramp-file-property\\>"))
1658 (defmacro with-tramp-connection-property (key property &rest body)
1659 "Check in Tramp for property PROPERTY, otherwise executes BODY and set."
1660 `(let ((value (tramp-get-connection-property ,key ,property 'undef)))
1661 (when (eq value 'undef)
1662 ;; We cannot pass ,@body as parameter to
1663 ;; `tramp-set-connection-property' because it mangles our debug
1664 ;; messages.
1665 (setq value (progn ,@body))
1666 (tramp-set-connection-property ,key ,property value))
1667 value))
1669 (put 'with-tramp-connection-property 'lisp-indent-function 2)
1670 (put 'with-tramp-connection-property 'edebug-form-spec t)
1671 (font-lock-add-keywords
1672 'emacs-lisp-mode '("\\<with-tramp-connection-property\\>"))
1674 (defun tramp-drop-volume-letter (name)
1675 "Cut off unnecessary drive letter from file NAME.
1676 The functions `tramp-*-handle-expand-file-name' call `expand-file-name'
1677 locally on a remote file name. When the local system is a W32 system
1678 but the remote system is Unix, this introduces a superfluous drive
1679 letter into the file name. This function removes it."
1680 (save-match-data
1681 (funcall
1682 (if (tramp-compat-file-name-quoted-p name)
1683 'tramp-compat-file-name-quote 'identity)
1684 (let ((name (tramp-compat-file-name-unquote name)))
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 ;; Emacs 26+ only.
1936 file-name-case-insensitive-p))
1937 (if (file-name-absolute-p (nth 0 args))
1938 (nth 0 args)
1939 (expand-file-name (nth 0 args))))
1940 ;; FILE DIRECTORY resp FILE1 FILE2.
1941 ((member operation
1942 '(add-name-to-file copy-directory copy-file expand-file-name
1943 file-name-all-completions file-name-completion
1944 file-newer-than-file-p make-symbolic-link rename-file
1945 ;; Emacs 24+ only.
1946 file-equal-p file-in-directory-p))
1947 (save-match-data
1948 (cond
1949 ((tramp-tramp-file-p (nth 0 args)) (nth 0 args))
1950 ((tramp-tramp-file-p (nth 1 args)) (nth 1 args))
1951 (t (buffer-file-name (current-buffer))))))
1952 ;; START END FILE.
1953 ((eq operation 'write-region)
1954 (nth 2 args))
1955 ;; BUFFER.
1956 ((member operation
1957 '(make-auto-save-file-name
1958 set-visited-file-modtime verify-visited-file-modtime))
1959 (buffer-file-name
1960 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
1961 ;; COMMAND.
1962 ((member operation
1963 '(process-file shell-command start-file-process
1964 ;; Emacs 26+ only.
1965 make-nearby-temp-file temporary-file-directory))
1966 default-directory)
1967 ;; PROC.
1968 ((member operation
1969 '(;; Emacs 24+ only.
1970 file-notify-rm-watch
1971 ;; Emacs 25+ only.
1972 file-notify-valid-p))
1973 (when (processp (nth 0 args))
1974 (with-current-buffer (process-buffer (nth 0 args))
1975 default-directory)))
1976 ;; Unknown file primitive.
1977 (t (error "unknown file I/O primitive: %s" operation))))
1979 (defun tramp-find-foreign-file-name-handler
1980 (filename &optional operation completion)
1981 "Return foreign file name handler if exists."
1982 (when (tramp-tramp-file-p filename)
1983 (let ((v (tramp-dissect-file-name filename t))
1984 (handler tramp-foreign-file-name-handler-alist)
1985 elt res)
1986 ;; When we are not fully sure that filename completion is safe,
1987 ;; we should not return a handler.
1988 (when (or (not completion)
1989 (tramp-file-name-method v) (tramp-file-name-user v)
1990 (and (tramp-file-name-host v)
1991 (not (member (tramp-file-name-host v)
1992 (mapcar 'car tramp-methods))))
1993 ;; Some operations are safe by default.
1994 (member
1995 operation
1996 '(file-name-as-directory
1997 file-name-directory
1998 file-name-nondirectory)))
1999 (while handler
2000 (setq elt (car handler)
2001 handler (cdr handler))
2002 (when (funcall (car elt) filename)
2003 (setq handler nil
2004 res (cdr elt))))
2005 res))))
2007 (defvar tramp-debug-on-error nil
2008 "Like `debug-on-error' but used Tramp internal.")
2010 (defmacro tramp-condition-case-unless-debug
2011 (var bodyform &rest handlers)
2012 "Like `condition-case-unless-debug' but `tramp-debug-on-error'."
2013 `(let ((debug-on-error tramp-debug-on-error))
2014 (tramp-compat-condition-case-unless-debug ,var ,bodyform ,@handlers)))
2016 ;; Main function.
2017 (defun tramp-file-name-handler (operation &rest args)
2018 "Invoke Tramp file name handler.
2019 Falls back to normal file name handler if no Tramp file name handler exists."
2020 (let ((filename (apply 'tramp-file-name-for-operation operation args)))
2021 (if (and tramp-mode (tramp-tramp-file-p filename))
2022 (save-match-data
2023 (let* ((filename (tramp-replace-environment-variables filename))
2024 (completion (tramp-completion-mode-p))
2025 (foreign
2026 (tramp-find-foreign-file-name-handler
2027 filename operation completion))
2028 result)
2029 (with-parsed-tramp-file-name filename nil
2030 ;; Call the backend function.
2031 (if foreign
2032 (tramp-condition-case-unless-debug err
2033 (let ((sf (symbol-function foreign)))
2034 ;; Some packages set the default directory to a
2035 ;; remote path, before respective Tramp packages
2036 ;; are already loaded. This results in
2037 ;; recursive loading. Therefore, we load the
2038 ;; Tramp packages locally.
2039 (when (and (listp sf) (eq (car sf) 'autoload))
2040 (let ((default-directory
2041 (tramp-compat-temporary-file-directory)))
2042 (load (cadr sf) 'noerror 'nomessage)))
2043 ;; If `non-essential' is non-nil, Tramp shall
2044 ;; not open a new connection.
2045 ;; If Tramp detects that it shouldn't continue
2046 ;; to work, it throws the `suppress' event.
2047 ;; This could happen for example, when Tramp
2048 ;; tries to open the same connection twice in a
2049 ;; short time frame.
2050 ;; In both cases, we try the default handler then.
2051 (setq result
2052 (catch 'non-essential
2053 (catch 'suppress
2054 (apply foreign operation args))))
2055 (cond
2056 ((eq result 'non-essential)
2057 (tramp-message
2058 v 5 "Non-essential received in operation %s"
2059 (cons operation args))
2060 (tramp-run-real-handler operation args))
2061 ((eq result 'suppress)
2062 (let (tramp-message-show-message)
2063 (tramp-message
2064 v 1 "Suppress received in operation %s"
2065 (cons operation args))
2066 (tramp-cleanup-connection v t)
2067 (tramp-run-real-handler operation args)))
2068 (t result)))
2070 ;; Trace that somebody has interrupted the operation.
2071 ((debug quit)
2072 (let (tramp-message-show-message)
2073 (tramp-message
2074 v 1 "Interrupt received in operation %s"
2075 (cons operation args)))
2076 ;; Propagate the quit signal.
2077 (signal (car err) (cdr err)))
2079 ;; When we are in completion mode, some failed
2080 ;; operations shall return at least a default
2081 ;; value in order to give the user a chance to
2082 ;; correct the file name in the minibuffer.
2083 ;; In order to get a full backtrace, one could apply
2084 ;; (setq tramp-debug-on-error t)
2085 (error
2086 (cond
2087 ((and completion (zerop (length localname))
2088 (memq operation '(file-exists-p file-directory-p)))
2090 ((and completion (zerop (length localname))
2091 (memq operation
2092 '(expand-file-name file-name-as-directory)))
2093 filename)
2094 ;; Propagate the error.
2095 (t (signal (car err) (cdr err))))))
2097 ;; Nothing to do for us. However, since we are in
2098 ;; `tramp-mode', we must suppress the volume letter on
2099 ;; MS Windows.
2100 (setq result (tramp-run-real-handler operation args))
2101 (if (stringp result)
2102 (tramp-drop-volume-letter result)
2103 result)))))
2105 ;; When `tramp-mode' is not enabled, or the file name is quoted,
2106 ;; we don't do anything.
2107 (tramp-run-real-handler operation args))))
2109 ;; In Emacs, there is some concurrency due to timers. If a timer
2110 ;; interrupts Tramp and wishes to use the same connection buffer as
2111 ;; the "main" Emacs, then garbage might occur in the connection
2112 ;; buffer. Therefore, we need to make sure that a timer does not use
2113 ;; the same connection buffer as the "main" Emacs. We implement a
2114 ;; cheap global lock, instead of locking each connection buffer
2115 ;; separately. The global lock is based on two variables,
2116 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
2117 ;; (with setq) to indicate a lock. But Tramp also calls itself during
2118 ;; processing of a single file operation, so we need to allow
2119 ;; recursive calls. That's where the `tramp-locker' variable comes in
2120 ;; -- it is let-bound to t during the execution of the current
2121 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
2122 ;; then we should just proceed because we have been called
2123 ;; recursively. But if `tramp-locker' is nil, then we are a timer
2124 ;; interrupting the "main" Emacs, and then we signal an error.
2126 (defvar tramp-locked nil
2127 "If non-nil, then Tramp is currently busy.
2128 Together with `tramp-locker', this implements a locking mechanism
2129 preventing reentrant calls of Tramp.")
2131 (defvar tramp-locker nil
2132 "If non-nil, then a caller has locked Tramp.
2133 Together with `tramp-locked', this implements a locking mechanism
2134 preventing reentrant calls of Tramp.")
2136 ;; Avoid recursive loading of tramp.el.
2137 ;;;###autoload(defun tramp-completion-file-name-handler (operation &rest args)
2138 ;;;###autoload (tramp-completion-run-real-handler operation args))
2140 (defun tramp-completion-file-name-handler (operation &rest args)
2141 "Invoke Tramp file name completion handler.
2142 Falls back to normal file name handler if no Tramp file name handler exists."
2143 (let ((fn (assoc operation tramp-completion-file-name-handler-alist)))
2144 (if (and
2145 ;; When `tramp-mode' is not enabled, we don't do anything.
2146 fn tramp-mode (tramp-completion-mode-p)
2147 ;; For other syntaxes than `sep', the regexp matches many common
2148 ;; situations where the user doesn't actually want to use Tramp.
2149 ;; So to avoid autoloading Tramp after typing just "/s", we
2150 ;; disable this part of the completion, unless the user implicitly
2151 ;; indicated his interest in using a fancier completion system.
2152 (or (eq tramp-syntax 'sep)
2153 (featurep 'tramp) ;; If it's loaded, we may as well use it.
2154 ;; `partial-completion-mode' is obsoleted with Emacs 24.1.
2155 (and (boundp 'partial-completion-mode)
2156 (symbol-value 'partial-completion-mode))
2157 ;; FIXME: These may have been loaded even if the user never
2158 ;; intended to use them.
2159 (featurep 'ido)
2160 (featurep 'icicles)))
2161 (save-match-data (apply (cdr fn) args))
2162 (tramp-completion-run-real-handler operation args))))
2164 ;;;###autoload
2165 (progn (defun tramp-autoload-file-name-handler (operation &rest args)
2166 "Load Tramp file name handler, and perform OPERATION."
2167 ;; Avoid recursive loading of tramp.el.
2168 (let ((default-directory temporary-file-directory))
2169 (load "tramp" nil t))
2170 (apply operation args)))
2172 ;; `tramp-autoload-file-name-handler' must be registered before
2173 ;; evaluation of site-start and init files, because there might exist
2174 ;; remote files already, f.e. files kept via recentf-mode. We cannot
2175 ;; autoload `tramp-file-name-handler', because it would result in
2176 ;; recursive loading of tramp.el when `default-directory' is set to
2177 ;; remote.
2178 ;;;###autoload
2179 (progn (defun tramp-register-autoload-file-name-handlers ()
2180 "Add Tramp file name handlers to `file-name-handler-alist' during autoload."
2181 (add-to-list 'file-name-handler-alist
2182 (cons tramp-file-name-regexp
2183 'tramp-autoload-file-name-handler))
2184 (put 'tramp-autoload-file-name-handler 'safe-magic t)
2185 (add-to-list 'file-name-handler-alist
2186 (cons tramp-completion-file-name-regexp
2187 'tramp-completion-file-name-handler))
2188 (put 'tramp-completion-file-name-handler 'safe-magic t)))
2190 ;;;###autoload
2191 (tramp-register-autoload-file-name-handlers)
2193 (defun tramp-register-file-name-handlers ()
2194 "Add Tramp file name handlers to `file-name-handler-alist'."
2195 ;; Remove autoloaded handlers from file name handler alist. Useful,
2196 ;; if `tramp-syntax' has been changed.
2197 (dolist (fnh '(tramp-file-name-handler
2198 tramp-completion-file-name-handler
2199 tramp-autoload-file-name-handler))
2200 (let ((a1 (rassq fnh file-name-handler-alist)))
2201 (setq file-name-handler-alist (delq a1 file-name-handler-alist))))
2202 ;; The initial value of `tramp-file-name-regexp' is too simple
2203 ;; minded, but we cannot give it the real value in the autoload
2204 ;; pattern. See Bug#24889.
2205 (setq tramp-file-name-regexp (car tramp-file-name-structure))
2206 ;; Add the handlers.
2207 (add-to-list 'file-name-handler-alist
2208 (cons tramp-file-name-regexp 'tramp-file-name-handler))
2209 (put 'tramp-file-name-handler 'safe-magic t)
2210 (add-to-list 'file-name-handler-alist
2211 (cons tramp-completion-file-name-regexp
2212 'tramp-completion-file-name-handler))
2213 (put 'tramp-completion-file-name-handler 'safe-magic t)
2214 ;; If jka-compr or epa-file are already loaded, move them to the
2215 ;; front of `file-name-handler-alist'.
2216 (dolist (fnh '(epa-file-handler jka-compr-handler))
2217 (let ((entry (rassoc fnh file-name-handler-alist)))
2218 (when entry
2219 (setq file-name-handler-alist
2220 (cons entry (delete entry file-name-handler-alist)))))))
2222 (eval-after-load 'tramp (tramp-register-file-name-handlers))
2224 (defun tramp-exists-file-name-handler (operation &rest args)
2225 "Check, whether OPERATION runs a file name handler."
2226 ;; The file name handler is determined on base of either an
2227 ;; argument, `buffer-file-name', or `default-directory'.
2228 (ignore-errors
2229 (let* ((buffer-file-name "/")
2230 (default-directory "/")
2231 (fnha file-name-handler-alist)
2232 (check-file-name-operation operation)
2233 (file-name-handler-alist
2234 (list
2235 (cons "/"
2236 (lambda (operation &rest args)
2237 "Returns OPERATION if it is the one to be checked."
2238 (if (equal check-file-name-operation operation)
2239 operation
2240 (let ((file-name-handler-alist fnha))
2241 (apply operation args))))))))
2242 (equal (apply operation args) operation))))
2244 ;;;###autoload
2245 (defun tramp-unload-file-name-handlers ()
2246 "Unload Tramp file name handlers from `file-name-handler-alist'."
2247 (setq file-name-handler-alist
2248 (delete (rassoc 'tramp-file-name-handler
2249 file-name-handler-alist)
2250 (delete (rassoc 'tramp-completion-file-name-handler
2251 file-name-handler-alist)
2252 file-name-handler-alist))))
2254 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
2256 ;;; File name handler functions for completion mode:
2258 ;;;###autoload
2259 (defvar tramp-completion-mode nil
2260 "If non-nil, external packages signal that they are in file name completion.
2262 This is necessary, because Tramp uses a heuristic depending on last
2263 input event. This fails when external packages use other characters
2264 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
2265 should never be set globally, the intention is to let-bind it.")
2267 ;; Necessary because `tramp-file-name-regexp-unified' and
2268 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
2269 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
2270 ;; to `tramp-file-name-handler'). Otherwise, it takes
2271 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
2272 ;; risky, because completing a file might require loading other files,
2273 ;; like "~/.netrc", and for them it shouldn't be decided based on that
2274 ;; variable. On the other hand, those files shouldn't have partial
2275 ;; Tramp file name syntax. Maybe another variable should be introduced
2276 ;; overwriting this check in such cases. Or we change Tramp file name
2277 ;; syntax in order to avoid ambiguities.
2278 (defun tramp-completion-mode-p ()
2279 "Check, whether method / user name / host name completion is active."
2281 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
2282 (and (boundp 'non-essential) (symbol-value 'non-essential))
2283 tramp-completion-mode
2284 (equal last-input-event 'tab)
2285 (and (natnump last-input-event)
2287 ;; ?\t has event-modifier 'control.
2288 (equal last-input-event ?\t)
2289 (and (not (event-modifiers last-input-event))
2290 (or (equal last-input-event ?\?)
2291 (equal last-input-event ?\ )))))))
2293 (defun tramp-connectable-p (filename)
2294 "Check, whether it is possible to connect the remote host w/o side-effects.
2295 This is true, if either the remote host is already connected, or if we are
2296 not in completion mode."
2297 (let (tramp-verbose)
2298 (and (tramp-tramp-file-p filename)
2299 (or (not (tramp-completion-mode-p))
2300 (tramp-compat-process-live-p
2301 (tramp-get-connection-process
2302 (tramp-dissect-file-name filename)))))))
2304 (defun tramp-completion-handle-expand-file-name (name &optional dir)
2305 "Like `expand-file-name' for Tramp files."
2306 (if (tramp-completion-mode-p)
2307 (progn
2308 ;; If DIR is not given, use `default-directory' or "/".
2309 (setq dir (or dir default-directory "/"))
2310 ;; Unless NAME is absolute, concat DIR and NAME.
2311 (unless (file-name-absolute-p name)
2312 (setq name (concat (file-name-as-directory dir) name)))
2313 ;; Return NAME.
2314 name)
2316 (tramp-completion-run-real-handler
2317 'expand-file-name (list name dir))))
2319 ;; Method, host name and user name completion.
2320 ;; `tramp-completion-dissect-file-name' returns a list of
2321 ;; tramp-file-name structures. For all of them we return possible completions.
2322 (defun tramp-completion-handle-file-name-all-completions (filename directory)
2323 "Like `file-name-all-completions' for partial Tramp files."
2325 (let ((fullname
2326 (tramp-drop-volume-letter (expand-file-name filename directory)))
2327 hop result result1)
2329 ;; Suppress hop from completion.
2330 (when (string-match
2331 (concat
2332 tramp-prefix-regexp
2333 "\\(" "\\(" tramp-remote-file-name-spec-regexp
2334 tramp-postfix-hop-regexp
2335 "\\)+" "\\)")
2336 fullname)
2337 (setq hop (match-string 1 fullname)
2338 fullname (replace-match "" nil nil fullname 1)))
2340 ;; Possible completion structures.
2341 (dolist (elt (tramp-completion-dissect-file-name fullname))
2342 (let* ((method (tramp-file-name-method elt))
2343 (user (tramp-file-name-user elt))
2344 (host (tramp-file-name-host elt))
2345 (localname (tramp-file-name-localname elt))
2346 (m (tramp-find-method method user host))
2347 (tramp-current-user user) ; see `tramp-parse-passwd'
2348 all-user-hosts)
2350 (unless localname ;; Nothing to complete.
2352 (if (or user host)
2354 ;; Method dependent user / host combinations.
2355 (progn
2356 (mapc
2357 (lambda (x)
2358 (setq all-user-hosts
2359 (append all-user-hosts
2360 (funcall (nth 0 x) (nth 1 x)))))
2361 (tramp-get-completion-function m))
2363 (setq result
2364 (append result
2365 (mapcar
2366 (lambda (x)
2367 (tramp-get-completion-user-host
2368 method user host (nth 0 x) (nth 1 x)))
2369 (delq nil all-user-hosts)))))
2371 ;; Possible methods.
2372 (setq result
2373 (append result (tramp-get-completion-methods m)))))))
2375 ;; Unify list, add hop, remove nil elements.
2376 (dolist (elt result)
2377 (when elt
2378 (string-match tramp-prefix-regexp elt)
2379 (setq elt (replace-match (concat tramp-prefix-format hop) nil nil elt))
2380 (add-to-list
2381 'result1
2382 (substring elt (length (tramp-drop-volume-letter directory))))))
2384 ;; Complete local parts.
2385 (append
2386 result1
2387 (ignore-errors
2388 (apply (if (tramp-connectable-p fullname)
2389 'tramp-completion-run-real-handler
2390 'tramp-run-real-handler)
2391 'file-name-all-completions (list (list filename directory)))))))
2393 ;; Method, host name and user name completion for a file.
2394 (defun tramp-completion-handle-file-name-completion
2395 (filename directory &optional predicate)
2396 "Like `file-name-completion' for Tramp files."
2397 (try-completion
2398 filename
2399 (mapcar 'list (file-name-all-completions filename directory))
2400 (when (and predicate
2401 (tramp-connectable-p (expand-file-name filename directory)))
2402 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2404 ;; I misuse a little bit the tramp-file-name structure in order to handle
2405 ;; completion possibilities for partial methods / user names / host names.
2406 ;; Return value is a list of tramp-file-name structures according to possible
2407 ;; completions. If "localname" is non-nil it means there
2408 ;; shouldn't be a completion anymore.
2410 ;; Expected results:
2412 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
2413 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
2414 ;; [nil "x" nil nil]
2415 ;; ["x" nil nil nil]
2417 ;; "/x:" "/x:y" "/x:y:"
2418 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
2419 ;; "/[x/" "/[x/y"
2420 ;; ["x" nil "" nil] ["x" nil "y" nil]
2421 ;; ["x" "" nil nil] ["x" "y" nil nil]
2423 ;; "/x:y@" "/x:y@z" "/x:y@z:"
2424 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
2425 ;; "/[x/y@" "/[x/y@z"
2426 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
2427 (defun tramp-completion-dissect-file-name (name)
2428 "Returns a list of `tramp-file-name' structures.
2429 They are collected by `tramp-completion-dissect-file-name1'."
2431 (let* ((result)
2432 (x-nil "\\|\\(\\)")
2433 (tramp-completion-ipv6-regexp
2434 (format
2435 "[^%s]*"
2436 (if (zerop (length tramp-postfix-ipv6-format))
2437 tramp-postfix-host-format
2438 tramp-postfix-ipv6-format)))
2439 ;; "/method" "/[method"
2440 (tramp-completion-file-name-structure1
2441 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
2442 1 nil nil nil))
2443 ;; "/user" "/[user"
2444 (tramp-completion-file-name-structure2
2445 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
2446 nil 1 nil nil))
2447 ;; "/host" "/[host"
2448 (tramp-completion-file-name-structure3
2449 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
2450 nil nil 1 nil))
2451 ;; "/[ipv6" "/[ipv6"
2452 (tramp-completion-file-name-structure4
2453 (list (concat tramp-prefix-regexp
2454 tramp-prefix-ipv6-regexp
2455 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2456 nil nil 1 nil))
2457 ;; "/user@host" "/[user@host"
2458 (tramp-completion-file-name-structure5
2459 (list (concat tramp-prefix-regexp
2460 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2461 "\\(" tramp-host-regexp x-nil "\\)$")
2462 nil 1 2 nil))
2463 ;; "/user@[ipv6" "/[user@ipv6"
2464 (tramp-completion-file-name-structure6
2465 (list (concat tramp-prefix-regexp
2466 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2467 tramp-prefix-ipv6-regexp
2468 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2469 nil 1 2 nil))
2470 ;; "/method:user" "/[method/user"
2471 (tramp-completion-file-name-structure7
2472 (list (concat tramp-prefix-regexp
2473 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2474 "\\(" tramp-user-regexp x-nil "\\)$")
2475 1 2 nil nil))
2476 ;; "/method:host" "/[method/host"
2477 (tramp-completion-file-name-structure8
2478 (list (concat tramp-prefix-regexp
2479 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2480 "\\(" tramp-host-regexp x-nil "\\)$")
2481 1 nil 2 nil))
2482 ;; "/method:[ipv6" "/[method/ipv6"
2483 (tramp-completion-file-name-structure9
2484 (list (concat tramp-prefix-regexp
2485 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2486 tramp-prefix-ipv6-regexp
2487 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2488 1 nil 2 nil))
2489 ;; "/method:user@host" "/[method/user@host"
2490 (tramp-completion-file-name-structure10
2491 (list (concat tramp-prefix-regexp
2492 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2493 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2494 "\\(" tramp-host-regexp x-nil "\\)$")
2495 1 2 3 nil))
2496 ;; "/method:user@[ipv6" "/[method/user@ipv6"
2497 (tramp-completion-file-name-structure11
2498 (list (concat tramp-prefix-regexp
2499 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2500 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2501 tramp-prefix-ipv6-regexp
2502 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2503 1 2 3 nil)))
2505 (mapc (lambda (structure)
2506 (add-to-list 'result
2507 (tramp-completion-dissect-file-name1 structure name)))
2508 (list
2509 tramp-completion-file-name-structure1
2510 tramp-completion-file-name-structure2
2511 tramp-completion-file-name-structure3
2512 tramp-completion-file-name-structure4
2513 tramp-completion-file-name-structure5
2514 tramp-completion-file-name-structure6
2515 tramp-completion-file-name-structure7
2516 tramp-completion-file-name-structure8
2517 tramp-completion-file-name-structure9
2518 tramp-completion-file-name-structure10
2519 tramp-completion-file-name-structure11
2520 tramp-file-name-structure))
2522 (delq nil result)))
2524 (defun tramp-completion-dissect-file-name1 (structure name)
2525 "Returns a `tramp-file-name' structure matching STRUCTURE.
2526 The structure consists of remote method, remote user,
2527 remote host and localname (filename on remote host)."
2529 (save-match-data
2530 (when (string-match (nth 0 structure) name)
2531 (let ((method (and (nth 1 structure)
2532 (match-string (nth 1 structure) name)))
2533 (user (and (nth 2 structure)
2534 (match-string (nth 2 structure) name)))
2535 (host (and (nth 3 structure)
2536 (match-string (nth 3 structure) name)))
2537 (localname (and (nth 4 structure)
2538 (match-string (nth 4 structure) name))))
2539 (vector method user host localname nil)))))
2541 ;; This function returns all possible method completions, adding the
2542 ;; trailing method delimiter.
2543 (defun tramp-get-completion-methods (partial-method)
2544 "Returns all method completions for PARTIAL-METHOD."
2545 (mapcar
2546 (lambda (method)
2547 (and method
2548 (string-match (concat "^" (regexp-quote partial-method)) method)
2549 (tramp-completion-make-tramp-file-name method nil nil nil)))
2550 (mapcar 'car tramp-methods)))
2552 ;; Compares partial user and host names with possible completions.
2553 (defun tramp-get-completion-user-host
2554 (method partial-user partial-host user host)
2555 "Returns the most expanded string for user and host name completion.
2556 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2557 (cond
2559 ((and partial-user partial-host)
2560 (if (and host
2561 (string-match (concat "^" (regexp-quote partial-host)) host)
2562 (string-equal partial-user (or user partial-user)))
2563 (setq user partial-user)
2564 (setq user nil
2565 host nil)))
2567 (partial-user
2568 (setq host nil)
2569 (unless
2570 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2571 (setq user nil)))
2573 (partial-host
2574 (setq user nil)
2575 (unless
2576 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2577 (setq host nil)))
2579 (t (setq user nil
2580 host nil)))
2582 (unless (zerop (+ (length user) (length host)))
2583 (tramp-completion-make-tramp-file-name method user host nil)))
2585 (defun tramp-parse-default-user-host (method)
2586 "Return a list of (user host) tuples allowed to access for METHOD.
2587 This function is added always in `tramp-get-completion-function'
2588 for all methods. Resulting data are derived from default settings."
2589 `((,(tramp-find-user method nil nil) ,(tramp-find-host method nil nil))))
2591 ;; Generic function.
2592 (defun tramp-parse-group (regexp match-level skip-regexp)
2593 "Return a (user host) tuple allowed to access.
2594 User is always nil."
2595 (let (result)
2596 (when (re-search-forward regexp (point-at-eol) t)
2597 (setq result (list nil (match-string match-level))))
2599 (> (skip-chars-forward skip-regexp) 0)
2600 (forward-line 1))
2601 result))
2603 ;; Generic function.
2604 (defun tramp-parse-file (filename function)
2605 "Return a list of (user host) tuples allowed to access.
2606 User is always nil."
2607 ;; On Windows, there are problems in completion when
2608 ;; `default-directory' is remote.
2609 (let ((default-directory (tramp-compat-temporary-file-directory)))
2610 (when (file-readable-p filename)
2611 (with-temp-buffer
2612 (insert-file-contents filename)
2613 (goto-char (point-min))
2614 (loop while (not (eobp)) collect (funcall function))))))
2616 ;;;###tramp-autoload
2617 (defun tramp-parse-rhosts (filename)
2618 "Return a list of (user host) tuples allowed to access.
2619 Either user or host may be nil."
2620 (tramp-parse-file filename 'tramp-parse-rhosts-group))
2622 (defun tramp-parse-rhosts-group ()
2623 "Return a (user host) tuple allowed to access.
2624 Either user or host may be nil."
2625 (let ((result)
2626 (regexp
2627 (concat
2628 "^\\(" tramp-host-regexp "\\)"
2629 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2630 (when (re-search-forward regexp (point-at-eol) t)
2631 (setq result (append (list (match-string 3) (match-string 1)))))
2632 (forward-line 1)
2633 result))
2635 ;;;###tramp-autoload
2636 (defun tramp-parse-shosts (filename)
2637 "Return a list of (user host) tuples allowed to access.
2638 User is always nil."
2639 (tramp-parse-file filename 'tramp-parse-shosts-group))
2641 (defun tramp-parse-shosts-group ()
2642 "Return a (user host) tuple allowed to access.
2643 User is always nil."
2644 (tramp-parse-group (concat "^\\(" tramp-host-regexp "\\)") 1 ","))
2646 ;;;###tramp-autoload
2647 (defun tramp-parse-sconfig (filename)
2648 "Return a list of (user host) tuples allowed to access.
2649 User is always nil."
2650 (tramp-parse-file filename 'tramp-parse-sconfig-group))
2652 (defun tramp-parse-sconfig-group ()
2653 "Return a (user host) tuple allowed to access.
2654 User is always nil."
2655 (tramp-parse-group
2656 (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)") 1 ","))
2658 ;; Generic function.
2659 (defun tramp-parse-shostkeys-sknownhosts (dirname regexp)
2660 "Return a list of (user host) tuples allowed to access.
2661 User is always nil."
2662 ;; On Windows, there are problems in completion when
2663 ;; `default-directory' is remote.
2664 (let* ((default-directory (tramp-compat-temporary-file-directory))
2665 (files (and (file-directory-p dirname) (directory-files dirname))))
2666 (loop for f in files
2667 when (and (not (string-match "^\\.\\.?$" f)) (string-match regexp f))
2668 collect (list nil (match-string 1 f)))))
2670 ;;;###tramp-autoload
2671 (defun tramp-parse-shostkeys (dirname)
2672 "Return a list of (user host) tuples allowed to access.
2673 User is always nil."
2674 (tramp-parse-shostkeys-sknownhosts
2675 dirname (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$")))
2677 ;;;###tramp-autoload
2678 (defun tramp-parse-sknownhosts (dirname)
2679 "Return a list of (user host) tuples allowed to access.
2680 User is always nil."
2681 (tramp-parse-shostkeys-sknownhosts
2682 dirname
2683 (concat "^\\(" tramp-host-regexp "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$")))
2685 ;;;###tramp-autoload
2686 (defun tramp-parse-hosts (filename)
2687 "Return a list of (user host) tuples allowed to access.
2688 User is always nil."
2689 (tramp-parse-file filename 'tramp-parse-hosts-group))
2691 (defun tramp-parse-hosts-group ()
2692 "Return a (user host) tuple allowed to access.
2693 User is always nil."
2694 (tramp-parse-group
2695 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)") 1 " \t"))
2697 ;;;###tramp-autoload
2698 (defun tramp-parse-passwd (filename)
2699 "Return a list of (user host) tuples allowed to access.
2700 Host is always \"localhost\"."
2701 (with-tramp-connection-property nil "parse-passwd"
2702 (if (executable-find "getent")
2703 (with-temp-buffer
2704 (when (zerop (tramp-call-process nil "getent" nil t nil "passwd"))
2705 (goto-char (point-min))
2706 (loop while (not (eobp)) collect
2707 (tramp-parse-etc-group-group))))
2708 (tramp-parse-file filename 'tramp-parse-passwd-group))))
2710 (defun tramp-parse-passwd-group ()
2711 "Return a (user host) tuple allowed to access.
2712 Host is always \"localhost\"."
2713 (let ((result)
2714 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
2715 (when (re-search-forward regexp (point-at-eol) t)
2716 (setq result (list (match-string 1) "localhost")))
2717 (forward-line 1)
2718 result))
2720 ;;;###tramp-autoload
2721 (defun tramp-parse-etc-group (filename)
2722 "Return a list of (group host) tuples allowed to access.
2723 Host is always \"localhost\"."
2724 (with-tramp-connection-property nil "parse-group"
2725 (if (executable-find "getent")
2726 (with-temp-buffer
2727 (when (zerop (tramp-call-process nil "getent" nil t nil "group"))
2728 (goto-char (point-min))
2729 (loop while (not (eobp)) collect
2730 (tramp-parse-etc-group-group))))
2731 (tramp-parse-file filename 'tramp-parse-etc-group-group))))
2733 (defun tramp-parse-etc-group-group ()
2734 "Return a (group host) tuple allowed to access.
2735 Host is always \"localhost\"."
2736 (let ((result)
2737 (split (split-string (buffer-substring (point) (point-at-eol)) ":")))
2738 (when (member (user-login-name) (split-string (nth 3 split) "," 'omit))
2739 (setq result (list (nth 0 split) "localhost")))
2740 (forward-line 1)
2741 result))
2743 ;;;###tramp-autoload
2744 (defun tramp-parse-netrc (filename)
2745 "Return a list of (user host) tuples allowed to access.
2746 User may be nil."
2747 (tramp-parse-file filename 'tramp-parse-netrc-group))
2749 (defun tramp-parse-netrc-group ()
2750 "Return a (user host) tuple allowed to access.
2751 User may be nil."
2752 (let ((result)
2753 (regexp
2754 (concat
2755 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2756 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2757 (when (re-search-forward regexp (point-at-eol) t)
2758 (setq result (list (match-string 3) (match-string 1))))
2759 (forward-line 1)
2760 result))
2762 ;;;###tramp-autoload
2763 (defun tramp-parse-putty (registry-or-dirname)
2764 "Return a list of (user host) tuples allowed to access.
2765 User is always nil."
2766 (if (memq system-type '(windows-nt))
2767 (with-tramp-connection-property nil "parse-putty"
2768 (with-temp-buffer
2769 (when (zerop (tramp-call-process
2770 nil "reg" nil t nil "query" registry-or-dirname))
2771 (goto-char (point-min))
2772 (loop while (not (eobp)) collect
2773 (tramp-parse-putty-group registry-or-dirname)))))
2774 ;; UNIX case.
2775 (tramp-parse-shostkeys-sknownhosts
2776 registry-or-dirname (concat "^\\(" tramp-host-regexp "\\)$"))))
2778 (defun tramp-parse-putty-group (registry)
2779 "Return a (user host) tuple allowed to access.
2780 User is always nil."
2781 (let ((result)
2782 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
2783 (when (re-search-forward regexp (point-at-eol) t)
2784 (setq result (list nil (match-string 1))))
2785 (forward-line 1)
2786 result))
2788 ;;; Common file name handler functions for different backends:
2790 (defvar tramp-handle-file-local-copy-hook nil
2791 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2793 (defvar tramp-handle-write-region-hook nil
2794 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2796 (defun tramp-handle-directory-file-name (directory)
2797 "Like `directory-file-name' for Tramp files."
2798 ;; If localname component of filename is "/", leave it unchanged.
2799 ;; Otherwise, remove any trailing slash from localname component.
2800 ;; Method, host, etc, are unchanged. Does it make sense to try
2801 ;; to avoid parsing the filename?
2802 (with-parsed-tramp-file-name directory nil
2803 (if (and (not (zerop (length localname)))
2804 (eq (aref localname (1- (length localname))) ?/)
2805 (not (string= localname "/")))
2806 (substring directory 0 -1)
2807 directory)))
2809 (defun tramp-handle-directory-files (directory &optional full match nosort)
2810 "Like `directory-files' for Tramp files."
2811 (when (file-directory-p directory)
2812 (setq directory (file-name-as-directory (expand-file-name directory)))
2813 (let ((temp (nreverse (file-name-all-completions "" directory)))
2814 result item)
2816 (while temp
2817 (setq item (directory-file-name (pop temp)))
2818 (when (or (null match) (string-match match item))
2819 (push (if full (concat directory item) item)
2820 result)))
2821 (if nosort result (sort result 'string<)))))
2823 (defun tramp-handle-directory-files-and-attributes
2824 (directory &optional full match nosort id-format)
2825 "Like `directory-files-and-attributes' for Tramp files."
2826 (mapcar
2827 (lambda (x)
2828 (cons x (file-attributes
2829 (if full x (expand-file-name x directory)) id-format)))
2830 (directory-files directory full match nosort)))
2832 (defun tramp-handle-dired-uncache (dir)
2833 "Like `dired-uncache' for Tramp files."
2834 (with-parsed-tramp-file-name
2835 (if (file-directory-p dir) dir (file-name-directory dir)) nil
2836 (tramp-flush-directory-property v localname)))
2838 (defun tramp-handle-file-accessible-directory-p (filename)
2839 "Like `file-accessible-directory-p' for Tramp files."
2840 (and (file-directory-p filename)
2841 (file-readable-p filename)))
2843 (defun tramp-handle-file-equal-p (filename1 filename2)
2844 "Like `file-equalp-p' for Tramp files."
2845 ;; Native `file-equalp-p' calls `file-truename', which requires a
2846 ;; remote connection. This can be avoided, if FILENAME1 and
2847 ;; FILENAME2 are not located on the same remote host.
2848 (when (string-equal
2849 (file-remote-p (expand-file-name filename1))
2850 (file-remote-p (expand-file-name filename2)))
2851 (tramp-run-real-handler 'file-equal-p (list filename1 filename2))))
2853 (defun tramp-handle-file-exists-p (filename)
2854 "Like `file-exists-p' for Tramp files."
2855 (not (null (file-attributes filename))))
2857 (defun tramp-handle-file-in-directory-p (filename directory)
2858 "Like `file-in-directory-p' for Tramp files."
2859 ;; Native `file-in-directory-p' calls `file-truename', which
2860 ;; requires a remote connection. This can be avoided, if FILENAME
2861 ;; and DIRECTORY are not located on the same remote host.
2862 (when (string-equal
2863 (file-remote-p (expand-file-name filename))
2864 (file-remote-p (expand-file-name directory)))
2865 (tramp-run-real-handler 'file-in-directory-p (list filename directory))))
2867 (defun tramp-handle-file-modes (filename)
2868 "Like `file-modes' for Tramp files."
2869 (let ((truename (or (file-truename filename) filename)))
2870 (when (file-exists-p truename)
2871 (tramp-mode-string-to-int
2872 (tramp-compat-file-attribute-modes (file-attributes truename))))))
2874 ;; Localname manipulation functions that grok Tramp localnames...
2875 (defun tramp-handle-file-name-as-directory (file)
2876 "Like `file-name-as-directory' but aware of Tramp files."
2877 ;; `file-name-as-directory' would be sufficient except localname is
2878 ;; the empty string.
2879 (let ((v (tramp-dissect-file-name file t)))
2880 ;; Run the command on the localname portion only unless we are in
2881 ;; completion mode.
2882 (tramp-make-tramp-file-name
2883 (tramp-file-name-method v)
2884 (tramp-file-name-user v)
2885 (tramp-file-name-host v)
2886 (if (and (tramp-completion-mode-p)
2887 (zerop (length (tramp-file-name-localname v))))
2889 (tramp-run-real-handler
2890 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))
2891 (tramp-file-name-hop v))))
2893 (defun tramp-handle-file-name-case-insensitive-p (filename)
2894 "Like `file-name-case-insensitive-p' for Tramp files."
2895 ;; We make it a connection property, assuming that all file systems
2896 ;; on the remote host behave similar. This might be wrong for
2897 ;; mounted NFS directories or SMB/AFP shares; such more granular
2898 ;; tests will be added in case they are needed.
2899 (setq filename (expand-file-name filename))
2900 (with-parsed-tramp-file-name filename nil
2901 (or ;; Maybe there is a default value.
2902 (tramp-get-method-parameter v 'tramp-case-insensitive)
2904 ;; There isn't. So we must check, in case there's a connection already.
2905 (and (tramp-connectable-p filename)
2906 (with-tramp-connection-property v "case-insensitive"
2907 ;; The idea is to compare a file with lower case letters
2908 ;; with the same file with upper case letters.
2909 (let ((candidate
2910 (tramp-compat-file-name-unquote
2911 (directory-file-name filename)))
2912 tmpfile)
2913 ;; Check, whether we find an existing file with lower case
2914 ;; letters. This avoids us to create a temporary file.
2915 (while (and (string-match
2916 "[a-z]" (file-remote-p candidate 'localname))
2917 (not (file-exists-p candidate)))
2918 (setq candidate
2919 (directory-file-name (file-name-directory candidate))))
2920 ;; Nothing found, so we must use a temporary file for
2921 ;; comparison. `make-nearby-temp-file' is added to
2922 ;; Emacs 26+ like `file-name-case-insensitive-p', so
2923 ;; there is no compatibility problem calling it.
2924 (unless
2925 (string-match "[a-z]" (file-remote-p candidate 'localname))
2926 (setq tmpfile
2927 (let ((default-directory (file-name-directory filename)))
2928 (tramp-compat-funcall 'make-nearby-temp-file "tramp."))
2929 candidate tmpfile))
2930 ;; Check for the existence of the same file with upper
2931 ;; case letters.
2932 (unwind-protect
2933 (file-exists-p
2934 (concat
2935 (file-remote-p candidate)
2936 (upcase (file-remote-p candidate 'localname))))
2937 ;; Cleanup.
2938 (when tmpfile (delete-file tmpfile)))))))))
2940 (defun tramp-handle-file-name-completion
2941 (filename directory &optional predicate)
2942 "Like `file-name-completion' for Tramp files."
2943 (unless (tramp-tramp-file-p directory)
2944 (error
2945 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2946 directory))
2947 (let (hits-ignored-extensions)
2949 (try-completion
2950 filename (file-name-all-completions filename directory)
2951 (lambda (x)
2952 (when (funcall (or predicate 'identity) (expand-file-name x directory))
2953 (not
2954 (and
2955 completion-ignored-extensions
2956 (string-match
2957 (concat (regexp-opt completion-ignored-extensions 'paren) "$") x)
2958 ;; We remember the hit.
2959 (push x hits-ignored-extensions))))))
2960 ;; No match. So we try again for ignored files.
2961 (try-completion filename hits-ignored-extensions))))
2963 (defun tramp-handle-file-name-directory (file)
2964 "Like `file-name-directory' but aware of Tramp files."
2965 ;; Everything except the last filename thing is the directory. We
2966 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2967 ;; the remote file name parts. This is a problem when we are in
2968 ;; file name completion.
2969 (let ((v (tramp-dissect-file-name file t)))
2970 ;; Run the command on the localname portion only.
2971 (tramp-make-tramp-file-name
2972 (tramp-file-name-method v)
2973 (tramp-file-name-user v)
2974 (tramp-file-name-host v)
2975 (tramp-run-real-handler
2976 'file-name-directory (list (or (tramp-file-name-localname v) "")))
2977 (tramp-file-name-hop v))))
2979 (defun tramp-handle-file-name-nondirectory (file)
2980 "Like `file-name-nondirectory' but aware of Tramp files."
2981 (with-parsed-tramp-file-name file nil
2982 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2984 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2985 "Like `file-newer-than-file-p' for Tramp files."
2986 (cond
2987 ((not (file-exists-p file1)) nil)
2988 ((not (file-exists-p file2)) t)
2989 (t (time-less-p (tramp-compat-file-attribute-modification-time
2990 (file-attributes file2))
2991 (tramp-compat-file-attribute-modification-time
2992 (file-attributes file1))))))
2994 (defun tramp-handle-file-regular-p (filename)
2995 "Like `file-regular-p' for Tramp files."
2996 (and (file-exists-p filename)
2997 (eq ?-
2998 (aref (tramp-compat-file-attribute-modes (file-attributes filename))
2999 0))))
3001 (defun tramp-handle-file-remote-p (filename &optional identification connected)
3002 "Like `file-remote-p' for Tramp files."
3003 ;; We do not want traces in the debug buffer.
3004 (let ((tramp-verbose (min tramp-verbose 3)))
3005 (when (tramp-tramp-file-p filename)
3006 (let* ((v (tramp-dissect-file-name filename))
3007 (p (tramp-get-connection-process v))
3008 (c (and (tramp-compat-process-live-p p)
3009 (tramp-get-connection-property p "connected" nil))))
3010 ;; We expand the file name only, if there is already a connection.
3011 (with-parsed-tramp-file-name
3012 (if c (expand-file-name filename) filename) nil
3013 (and (or (not connected) c)
3014 (cond
3015 ((eq identification 'method) method)
3016 ((eq identification 'user) user)
3017 ((eq identification 'host) host)
3018 ((eq identification 'localname) localname)
3019 ((eq identification 'hop) hop)
3020 (t (tramp-make-tramp-file-name method user host "" hop)))))))))
3022 (defun tramp-handle-file-symlink-p (filename)
3023 "Like `file-symlink-p' for Tramp files."
3024 (with-parsed-tramp-file-name filename nil
3025 (let ((x (tramp-compat-file-attribute-type (file-attributes filename))))
3026 (when (stringp x)
3027 (if (file-name-absolute-p x)
3028 (tramp-make-tramp-file-name method user host x)
3029 x)))))
3031 (defun tramp-handle-find-backup-file-name (filename)
3032 "Like `find-backup-file-name' for Tramp files."
3033 (with-parsed-tramp-file-name filename nil
3034 (let ((backup-directory-alist
3035 (if tramp-backup-directory-alist
3036 (mapcar
3037 (lambda (x)
3038 (cons
3039 (car x)
3040 (if (and (stringp (cdr x))
3041 (file-name-absolute-p (cdr x))
3042 (not (tramp-file-name-p (cdr x))))
3043 (tramp-make-tramp-file-name method user host (cdr x))
3044 (cdr x))))
3045 tramp-backup-directory-alist)
3046 backup-directory-alist)))
3047 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
3049 (defun tramp-handle-insert-directory
3050 (filename switches &optional wildcard full-directory-p)
3051 "Like `insert-directory' for Tramp files."
3052 (unless switches (setq switches ""))
3053 ;; Mark trailing "/".
3054 (when (and (zerop (length (file-name-nondirectory filename)))
3055 (not full-directory-p))
3056 (setq switches (concat switches "F")))
3057 (with-parsed-tramp-file-name (expand-file-name filename) nil
3058 (with-tramp-progress-reporter v 0 (format "Opening directory %s" filename)
3059 (require 'ls-lisp)
3060 (let (ls-lisp-use-insert-directory-program start)
3061 (tramp-run-real-handler
3062 'insert-directory
3063 (list filename switches wildcard full-directory-p))
3064 ;; `ls-lisp' always returns full listings. We must remove
3065 ;; superfluous parts.
3066 (unless (string-match "l" switches)
3067 (save-excursion
3068 (goto-char (point-min))
3069 (while (setq start
3070 (text-property-not-all
3071 (point) (point-at-eol) 'dired-filename t))
3072 (delete-region
3073 start
3074 (or (text-property-any start (point-at-eol) 'dired-filename t)
3075 (point-at-eol)))
3076 (if (= (point-at-bol) (point-at-eol))
3077 ;; Empty line.
3078 (delete-region (point) (progn (forward-line) (point)))
3079 (forward-line)))))))))
3081 (defun tramp-handle-insert-file-contents
3082 (filename &optional visit beg end replace)
3083 "Like `insert-file-contents' for Tramp files."
3084 (barf-if-buffer-read-only)
3085 (setq filename (expand-file-name filename))
3086 (let (result local-copy remote-copy)
3087 (with-parsed-tramp-file-name filename nil
3088 (unwind-protect
3089 (if (not (file-exists-p filename))
3090 (tramp-error
3091 v tramp-file-missing
3092 "File `%s' not found on remote host" filename)
3094 (with-tramp-progress-reporter
3095 v 3 (format-message "Inserting `%s'" filename)
3096 (condition-case err
3097 (if (and (tramp-local-host-p v)
3098 (let (file-name-handler-alist)
3099 (file-readable-p localname)))
3100 ;; Short track: if we are on the local host, we can
3101 ;; run directly.
3102 (setq result
3103 (tramp-run-real-handler
3104 'insert-file-contents
3105 (list localname visit beg end replace)))
3107 ;; When we shall insert only a part of the file, we
3108 ;; copy this part. This works only for the shell file
3109 ;; name handlers.
3110 (when (and (or beg end)
3111 (tramp-get-method-parameter
3112 v 'tramp-login-program))
3113 (setq remote-copy (tramp-make-tramp-temp-file v))
3114 ;; This is defined in tramp-sh.el. Let's assume
3115 ;; this is loaded already.
3116 (tramp-compat-funcall
3117 'tramp-send-command
3119 (cond
3120 ((and beg end)
3121 (format "dd bs=1 skip=%d if=%s count=%d of=%s"
3122 beg (tramp-shell-quote-argument localname)
3123 (- end beg) remote-copy))
3124 (beg
3125 (format "dd bs=1 skip=%d if=%s of=%s"
3126 beg (tramp-shell-quote-argument localname)
3127 remote-copy))
3128 (end
3129 (format "dd bs=1 count=%d if=%s of=%s"
3130 end (tramp-shell-quote-argument localname)
3131 remote-copy))))
3132 (setq tramp-temp-buffer-file-name nil beg nil end nil))
3134 ;; `insert-file-contents-literally' takes care to
3135 ;; avoid calling jka-compr.el and epa.el. By
3136 ;; let-binding `inhibit-file-name-operation', we
3137 ;; propagate that care to the `file-local-copy'
3138 ;; operation.
3139 (setq local-copy
3140 (let ((inhibit-file-name-operation
3141 (when (eq inhibit-file-name-operation
3142 'insert-file-contents)
3143 'file-local-copy)))
3144 (cond
3145 ((stringp remote-copy)
3146 (file-local-copy
3147 (tramp-make-tramp-file-name
3148 method user host remote-copy)))
3149 ((stringp tramp-temp-buffer-file-name)
3150 (copy-file
3151 filename tramp-temp-buffer-file-name 'ok)
3152 tramp-temp-buffer-file-name)
3153 (t (file-local-copy filename)))))
3155 ;; When the file is not readable for the owner, it
3156 ;; cannot be inserted, even if it is readable for the
3157 ;; group or for everybody.
3158 (set-file-modes local-copy (string-to-number "0600" 8))
3160 (when (and (null remote-copy)
3161 (tramp-get-method-parameter
3162 v 'tramp-copy-keep-tmpfile))
3163 ;; We keep the local file for performance reasons,
3164 ;; useful for "rsync".
3165 (setq tramp-temp-buffer-file-name local-copy))
3167 ;; We must ensure that `file-coding-system-alist'
3168 ;; matches `local-copy'.
3169 (let ((file-coding-system-alist
3170 (tramp-find-file-name-coding-system-alist
3171 filename local-copy)))
3172 (setq result
3173 (insert-file-contents
3174 local-copy visit beg end replace))))
3175 (error
3176 (add-hook 'find-file-not-found-functions
3177 `(lambda () (signal ',(car err) ',(cdr err)))
3178 nil t)
3179 (signal (car err) (cdr err))))))
3181 ;; Save exit.
3182 (progn
3183 (when visit
3184 (setq buffer-file-name filename)
3185 (setq buffer-read-only (not (file-writable-p filename)))
3186 (set-visited-file-modtime)
3187 (set-buffer-modified-p nil))
3188 (when (and (stringp local-copy)
3189 (or remote-copy (null tramp-temp-buffer-file-name)))
3190 (delete-file local-copy))
3191 (when (stringp remote-copy)
3192 (delete-file
3193 (tramp-make-tramp-file-name method user host remote-copy)))))
3195 ;; Result.
3196 (list (expand-file-name filename)
3197 (cadr result)))))
3199 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
3200 "Like `load' for Tramp files."
3201 (with-parsed-tramp-file-name (expand-file-name file) nil
3202 (unless nosuffix
3203 (cond ((file-exists-p (concat file ".elc"))
3204 (setq file (concat file ".elc")))
3205 ((file-exists-p (concat file ".el"))
3206 (setq file (concat file ".el")))))
3207 (when must-suffix
3208 ;; The first condition is always true for absolute file names.
3209 ;; Included for safety's sake.
3210 (unless (or (file-name-directory file)
3211 (string-match "\\.elc?\\'" file))
3212 (tramp-error
3213 v 'file-error
3214 "File `%s' does not include a `.el' or `.elc' suffix" file)))
3215 (unless noerror
3216 (when (not (file-exists-p file))
3217 (tramp-error
3218 v tramp-file-missing "Cannot load nonexistent file `%s'" file)))
3219 (if (not (file-exists-p file))
3221 (let ((tramp-message-show-message (not nomessage)))
3222 (with-tramp-progress-reporter v 0 (format "Loading %s" file)
3223 (let ((local-copy (file-local-copy file)))
3224 (unwind-protect
3225 (load local-copy noerror t nosuffix must-suffix)
3226 (delete-file local-copy)))))
3227 t)))
3229 (defun tramp-handle-make-symbolic-link
3230 (filename linkname &optional _ok-if-already-exists)
3231 "Like `make-symbolic-link' for Tramp files."
3232 (with-parsed-tramp-file-name
3233 (if (tramp-tramp-file-p filename) filename linkname) nil
3234 (tramp-error v 'file-error "make-symbolic-link not supported")))
3236 (defun tramp-handle-shell-command
3237 (command &optional output-buffer error-buffer)
3238 "Like `shell-command' for Tramp files."
3239 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
3240 ;; We cannot use `shell-file-name' and `shell-command-switch',
3241 ;; they are variables of the local host.
3242 (args (append
3243 (cons
3244 (tramp-get-method-parameter
3245 (tramp-dissect-file-name default-directory)
3246 'tramp-remote-shell)
3247 (tramp-get-method-parameter
3248 (tramp-dissect-file-name default-directory)
3249 'tramp-remote-shell-args))
3250 (list (substring command 0 asynchronous))))
3251 current-buffer-p
3252 (output-buffer
3253 (cond
3254 ((bufferp output-buffer) output-buffer)
3255 ((stringp output-buffer) (get-buffer-create output-buffer))
3256 (output-buffer
3257 (setq current-buffer-p t)
3258 (current-buffer))
3259 (t (get-buffer-create
3260 (if asynchronous
3261 "*Async Shell Command*"
3262 "*Shell Command Output*")))))
3263 (error-buffer
3264 (cond
3265 ((bufferp error-buffer) error-buffer)
3266 ((stringp error-buffer) (get-buffer-create error-buffer))))
3267 (buffer
3268 (if (and (not asynchronous) error-buffer)
3269 (with-parsed-tramp-file-name default-directory nil
3270 (list output-buffer (tramp-make-tramp-temp-file v)))
3271 output-buffer))
3272 (p (get-buffer-process output-buffer)))
3274 ;; Check whether there is another process running. Tramp does not
3275 ;; support 2 (asynchronous) processes in parallel.
3276 (when p
3277 (if (yes-or-no-p "A command is running. Kill it? ")
3278 (ignore-errors (kill-process p))
3279 (tramp-compat-user-error p "Shell command in progress")))
3281 (if current-buffer-p
3282 (progn
3283 (barf-if-buffer-read-only)
3284 (push-mark nil t))
3285 (with-current-buffer output-buffer
3286 (setq buffer-read-only nil)
3287 (erase-buffer)))
3289 (if (and (not current-buffer-p) (integerp asynchronous))
3290 (prog1
3291 ;; Run the process.
3292 (setq p (apply 'start-file-process "*Async Shell*" buffer args))
3293 ;; Display output.
3294 (with-current-buffer output-buffer
3295 (display-buffer output-buffer '(nil (allow-no-window . t)))
3296 (setq mode-line-process '(":%s"))
3297 (shell-mode)
3298 (set-process-sentinel p 'shell-command-sentinel)
3299 (set-process-filter p 'comint-output-filter)))
3301 (prog1
3302 ;; Run the process.
3303 (apply 'process-file (car args) nil buffer nil (cdr args))
3304 ;; Insert error messages if they were separated.
3305 (when (listp buffer)
3306 (with-current-buffer error-buffer
3307 (insert-file-contents (cadr buffer)))
3308 (delete-file (cadr buffer)))
3309 (if current-buffer-p
3310 ;; This is like exchange-point-and-mark, but doesn't
3311 ;; activate the mark. It is cleaner to avoid activation,
3312 ;; even though the command loop would deactivate the mark
3313 ;; because we inserted text.
3314 (goto-char (prog1 (mark t)
3315 (set-marker (mark-marker) (point)
3316 (current-buffer))))
3317 ;; There's some output, display it.
3318 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
3319 (display-message-or-buffer output-buffer)))))))
3321 (defun tramp-handle-substitute-in-file-name (filename)
3322 "Like `substitute-in-file-name' for Tramp files.
3323 \"//\" and \"/~\" substitute only in the local filename part."
3324 ;; Check, whether the local part is a quoted file name.
3325 (if (tramp-compat-file-name-quoted-p filename)
3326 filename
3327 ;; First, we must replace environment variables.
3328 (setq filename (tramp-replace-environment-variables filename))
3329 (with-parsed-tramp-file-name filename nil
3330 ;; Ignore in LOCALNAME everything before "//" or "/~".
3331 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3332 (setq filename
3333 (concat (file-remote-p filename)
3334 (replace-match "\\1" nil nil localname)))
3335 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3336 (when (string-match "~$" filename)
3337 (setq filename (concat filename "/"))))
3338 ;; We do not want to replace environment variables, again.
3339 (let (process-environment)
3340 (tramp-run-real-handler 'substitute-in-file-name (list filename))))))
3342 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
3343 "Like `set-visited-file-modtime' for Tramp files."
3344 (unless (buffer-file-name)
3345 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
3346 (buffer-name)))
3347 (unless time-list
3348 (let ((remote-file-name-inhibit-cache t))
3349 ;; '(-1 65535) means file doesn't exists yet.
3350 (setq time-list
3351 (or (tramp-compat-file-attribute-modification-time
3352 (file-attributes (buffer-file-name)))
3353 '(-1 65535)))))
3354 ;; We use '(0 0) as a don't-know value.
3355 (unless (equal time-list '(0 0))
3356 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))))
3358 (defun tramp-handle-verify-visited-file-modtime (&optional buf)
3359 "Like `verify-visited-file-modtime' for Tramp files.
3360 At the time `verify-visited-file-modtime' calls this function, we
3361 already know that the buffer is visiting a file and that
3362 `visited-file-modtime' does not return 0. Do not call this
3363 function directly, unless those two cases are already taken care
3364 of."
3365 (with-current-buffer (or buf (current-buffer))
3366 (let ((f (buffer-file-name)))
3367 ;; There is no file visiting the buffer, or the buffer has no
3368 ;; recorded last modification time, or there is no established
3369 ;; connection.
3370 (if (or (not f)
3371 (eq (visited-file-modtime) 0)
3372 (not (file-remote-p f nil 'connected)))
3374 (with-parsed-tramp-file-name f nil
3375 (let* ((remote-file-name-inhibit-cache t)
3376 (attr (file-attributes f))
3377 (modtime (tramp-compat-file-attribute-modification-time attr))
3378 (mt (visited-file-modtime)))
3380 (cond
3381 ;; File exists, and has a known modtime.
3382 ((and attr (not (equal modtime '(0 0))))
3383 (< (abs (tramp-time-diff
3384 modtime
3385 ;; For compatibility, deal with both the old
3386 ;; (HIGH . LOW) and the new (HIGH LOW) return
3387 ;; values of `visited-file-modtime'.
3388 (if (atom (cdr mt))
3389 (list (car mt) (cdr mt))
3390 mt)))
3392 ;; Modtime has the don't know value.
3393 (attr t)
3394 ;; If file does not exist, say it is not modified if and
3395 ;; only if that agrees with the buffer's record.
3396 (t (equal mt '(-1 65535))))))))))
3398 (defun tramp-handle-file-notify-add-watch (filename _flags _callback)
3399 "Like `file-notify-add-watch' for Tramp files."
3400 ;; This is the default handler. tramp-gvfs.el and tramp-sh.el have
3401 ;; their own one.
3402 (setq filename (expand-file-name filename))
3403 (with-parsed-tramp-file-name filename nil
3404 (tramp-error
3405 v 'file-notify-error "File notification not supported for `%s'" filename)))
3407 (defun tramp-handle-file-notify-rm-watch (proc)
3408 "Like `file-notify-rm-watch' for Tramp files."
3409 ;; The descriptor must be a process object.
3410 (unless (processp proc)
3411 (tramp-error proc 'file-notify-error "Not a valid descriptor %S" proc))
3412 (tramp-message proc 6 "Kill %S" proc)
3413 (delete-process proc))
3415 (defun tramp-handle-file-notify-valid-p (proc)
3416 "Like `file-notify-valid-p' for Tramp files."
3417 (and (tramp-compat-process-live-p proc)
3418 ;; Sometimes, the process is still in status `run' when the
3419 ;; file or directory to be watched is deleted already.
3420 (with-current-buffer (process-buffer proc)
3421 (file-exists-p
3422 (concat (file-remote-p default-directory)
3423 (process-get proc 'watch-name))))))
3425 ;;; Functions for establishing connection:
3427 ;; The following functions are actions to be taken when seeing certain
3428 ;; prompts from the remote host. See the variable
3429 ;; `tramp-actions-before-shell' for usage of these functions.
3431 (defun tramp-action-login (_proc vec)
3432 "Send the login name."
3433 (when (not (stringp tramp-current-user))
3434 (setq tramp-current-user
3435 (with-tramp-connection-property vec "login-as"
3436 (save-window-excursion
3437 (let ((enable-recursive-minibuffers t))
3438 (pop-to-buffer (tramp-get-connection-buffer vec))
3439 (read-string (match-string 0)))))))
3440 (with-current-buffer (tramp-get-connection-buffer vec)
3441 (tramp-message vec 6 "\n%s" (buffer-string)))
3442 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
3443 (tramp-send-string vec (concat tramp-current-user tramp-local-end-of-line)))
3445 (defun tramp-action-password (proc vec)
3446 "Query the user for a password."
3447 (with-current-buffer (process-buffer proc)
3448 (let ((enable-recursive-minibuffers t)
3449 (case-fold-search t))
3450 ;; Let's check whether a wrong password has been sent already.
3451 ;; Sometimes, the process returns a new password request
3452 ;; immediately after rejecting the previous (wrong) one.
3453 (unless (tramp-get-connection-property vec "first-password-request" nil)
3454 (tramp-clear-passwd vec))
3455 (goto-char (point-min))
3456 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3457 (tramp-message vec 3 "Sending %s" (match-string 1))
3458 ;; We don't call `tramp-send-string' in order to hide the
3459 ;; password from the debug buffer.
3460 (process-send-string
3461 proc (concat (tramp-read-passwd proc) tramp-local-end-of-line))
3462 ;; Hide password prompt.
3463 (narrow-to-region (point-max) (point-max)))))
3465 (defun tramp-action-succeed (_proc _vec)
3466 "Signal success in finding shell prompt."
3467 (throw 'tramp-action 'ok))
3469 (defun tramp-action-permission-denied (proc _vec)
3470 "Signal permission denied."
3471 (kill-process proc)
3472 (throw 'tramp-action 'permission-denied))
3474 (defun tramp-action-yesno (proc vec)
3475 "Ask the user for confirmation using `yes-or-no-p'.
3476 Send \"yes\" to remote process on confirmation, abort otherwise.
3477 See also `tramp-action-yn'."
3478 (save-window-excursion
3479 (let ((enable-recursive-minibuffers t))
3480 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3481 (unless (yes-or-no-p (match-string 0))
3482 (kill-process proc)
3483 (throw 'tramp-action 'permission-denied))
3484 (with-current-buffer (tramp-get-connection-buffer vec)
3485 (tramp-message vec 6 "\n%s" (buffer-string)))
3486 (tramp-send-string vec (concat "yes" tramp-local-end-of-line)))))
3488 (defun tramp-action-yn (proc vec)
3489 "Ask the user for confirmation using `y-or-n-p'.
3490 Send \"y\" to remote process on confirmation, abort otherwise.
3491 See also `tramp-action-yesno'."
3492 (save-window-excursion
3493 (let ((enable-recursive-minibuffers t))
3494 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3495 (unless (y-or-n-p (match-string 0))
3496 (kill-process proc)
3497 (throw 'tramp-action 'permission-denied))
3498 (with-current-buffer (tramp-get-connection-buffer vec)
3499 (tramp-message vec 6 "\n%s" (buffer-string)))
3500 (tramp-send-string vec (concat "y" tramp-local-end-of-line)))))
3502 (defun tramp-action-terminal (_proc vec)
3503 "Tell the remote host which terminal type to use.
3504 The terminal type can be configured with `tramp-terminal-type'."
3505 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
3506 (with-current-buffer (tramp-get-connection-buffer vec)
3507 (tramp-message vec 6 "\n%s" (buffer-string)))
3508 (tramp-send-string vec (concat tramp-terminal-type tramp-local-end-of-line)))
3510 (defun tramp-action-process-alive (proc _vec)
3511 "Check, whether a process has finished."
3512 (unless (tramp-compat-process-live-p proc)
3513 (throw 'tramp-action 'process-died)))
3515 (defun tramp-action-out-of-band (proc vec)
3516 "Check, whether an out-of-band copy has finished."
3517 ;; There might be pending output for the exit status.
3518 (tramp-accept-process-output proc 0.1)
3519 (cond ((and (not (tramp-compat-process-live-p proc))
3520 (zerop (process-exit-status proc)))
3521 (tramp-message vec 3 "Process has finished.")
3522 (throw 'tramp-action 'ok))
3523 ((or (and (memq (process-status proc) '(stop exit))
3524 (not (zerop (process-exit-status proc))))
3525 (memq (process-status proc) '(signal)))
3526 ;; `scp' could have copied correctly, but set modes could have failed.
3527 ;; This can be ignored.
3528 (with-current-buffer (process-buffer proc)
3529 (goto-char (point-min))
3530 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3531 (progn
3532 (tramp-message vec 5 "'set mode' error ignored.")
3533 (tramp-message vec 3 "Process has finished.")
3534 (throw 'tramp-action 'ok))
3535 (tramp-message vec 3 "Process has died.")
3536 (throw 'tramp-action 'out-of-band-failed))))
3537 (t nil)))
3539 ;;; Functions for processing the actions:
3541 (defun tramp-process-one-action (proc vec actions)
3542 "Wait for output from the shell and perform one action."
3543 (let ((case-fold-search t)
3544 found todo item pattern action)
3545 (while (not found)
3546 ;; Reread output once all actions have been performed.
3547 ;; Obviously, the output was not complete.
3548 (tramp-accept-process-output proc 1)
3549 (setq todo actions)
3550 (while todo
3551 (setq item (pop todo))
3552 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
3553 (setq action (nth 1 item))
3554 (tramp-message
3555 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3556 (when (tramp-check-for-regexp proc pattern)
3557 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3558 (setq found (funcall action proc vec)))))
3559 found))
3561 (defun tramp-process-actions (proc vec pos actions &optional timeout)
3562 "Perform ACTIONS until success or TIMEOUT.
3563 PROC and VEC indicate the remote connection to be used. POS, if
3564 set, is the starting point of the region to be deleted in the
3565 connection buffer."
3566 ;; Enable `auth-source'. We must use tramp-current-* variables in
3567 ;; case we have several hops.
3568 (tramp-set-connection-property
3569 (tramp-dissect-file-name
3570 (tramp-make-tramp-file-name
3571 tramp-current-method tramp-current-user tramp-current-host ""))
3572 "first-password-request" t)
3573 (save-restriction
3574 (with-tramp-progress-reporter
3575 proc 3 "Waiting for prompts from remote shell"
3576 (let (exit)
3577 (if timeout
3578 (with-timeout (timeout (setq exit 'timeout))
3579 (while (not exit)
3580 (setq exit
3581 (catch 'tramp-action
3582 (tramp-process-one-action proc vec actions)))))
3583 (while (not exit)
3584 (setq exit
3585 (catch 'tramp-action
3586 (tramp-process-one-action proc vec actions)))))
3587 (with-current-buffer (tramp-get-connection-buffer vec)
3588 (widen)
3589 (tramp-message vec 6 "\n%s" (buffer-string)))
3590 (unless (eq exit 'ok)
3591 (tramp-clear-passwd vec)
3592 (delete-process proc)
3593 (tramp-error-with-buffer
3594 (tramp-get-connection-buffer vec) vec 'file-error
3595 (cond
3596 ((eq exit 'permission-denied) "Permission denied")
3597 ((eq exit 'out-of-band-failed)
3598 (format-message
3599 "Copy failed, see buffer `%s' for details"
3600 (tramp-get-connection-buffer vec)))
3601 ((eq exit 'process-died)
3602 (substitute-command-keys
3603 (concat
3604 "Tramp failed to connect. If this happens repeatedly, try\n"
3605 " `\\[tramp-cleanup-this-connection]'")))
3606 ((eq exit 'timeout)
3607 (format-message
3608 "Timeout reached, see buffer `%s' for details"
3609 (tramp-get-connection-buffer vec)))
3610 (t "Login failed")))))
3611 (when (numberp pos)
3612 (with-current-buffer (tramp-get-connection-buffer vec)
3613 (let (buffer-read-only) (delete-region pos (point))))))))
3615 ;;; Utility functions:
3617 (defun tramp-accept-process-output (proc timeout)
3618 "Like `accept-process-output' for Tramp processes.
3619 This is needed in order to hide `last-coding-system-used', which is set
3620 for process communication also."
3621 ;; FIXME: There are problems, when an asynchronous process runs in
3622 ;; parallel, and also timers are active. See
3623 ;; <http://lists.gnu.org/archive/html/tramp-devel/2017-01/msg00010.html>.
3624 (when (and timer-event-last
3625 (string-prefix-p "*tramp/" (process-name proc))
3626 (let (result)
3627 (maphash
3628 (lambda (key _value)
3629 (and (processp key)
3630 (not (string-prefix-p "*tramp/" (process-name key)))
3631 (tramp-compat-process-live-p key)
3632 (setq result t)))
3633 tramp-cache-data)
3634 result))
3635 (sit-for 0.01 'nodisp))
3636 (with-current-buffer (process-buffer proc)
3637 (let (buffer-read-only last-coding-system-used)
3638 ;; Under Windows XP, accept-process-output doesn't return
3639 ;; sometimes. So we add an additional timeout. JUST-THIS-ONE
3640 ;; is set due to Bug#12145.
3641 (tramp-message
3642 proc 10 "%s %s %s\n%s"
3643 proc (process-status proc)
3644 (with-timeout (timeout)
3645 (accept-process-output proc timeout nil t))
3646 (buffer-string)))))
3648 (defun tramp-check-for-regexp (proc regexp)
3649 "Check, whether REGEXP is contained in process buffer of PROC.
3650 Erase echoed commands if exists."
3651 (with-current-buffer (process-buffer proc)
3652 (goto-char (point-min))
3654 ;; Check whether we need to remove echo output.
3655 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3656 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3657 (let ((begin (match-beginning 0)))
3658 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3659 ;; Discard echo from remote output.
3660 (tramp-set-connection-property proc "check-remote-echo" nil)
3661 (tramp-message proc 5 "echo-mark found")
3662 (forward-line 1)
3663 (delete-region begin (point))
3664 (goto-char (point-min)))))
3666 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3667 ;; Sometimes, the echo string is suppressed on the remote side.
3668 (not (string-equal
3669 (substring-no-properties
3670 tramp-echo-mark-marker
3671 0 (min tramp-echo-mark-marker-length (1- (point-max))))
3672 (buffer-substring-no-properties
3673 (point-min)
3674 (min (+ (point-min) tramp-echo-mark-marker-length)
3675 (point-max))))))
3676 ;; No echo to be handled, now we can look for the regexp.
3677 ;; Sometimes, lines are much to long, and we run into a "Stack
3678 ;; overflow in regexp matcher". For example, //DIRED// lines of
3679 ;; directory listings with some thousand files. Therefore, we
3680 ;; look from the end.
3681 (goto-char (point-max))
3682 (ignore-errors (re-search-backward regexp nil t)))))
3684 (defun tramp-wait-for-regexp (proc timeout regexp)
3685 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3686 Expects the output of PROC to be sent to the current buffer. Returns
3687 the string that matched, or nil. Waits indefinitely if TIMEOUT is
3688 nil."
3689 (with-current-buffer (process-buffer proc)
3690 (let ((found (tramp-check-for-regexp proc regexp)))
3691 (cond (timeout
3692 (with-timeout (timeout)
3693 (while (not found)
3694 (tramp-accept-process-output proc 1)
3695 (unless (tramp-compat-process-live-p proc)
3696 (tramp-error-with-buffer
3697 nil proc 'file-error "Process has died"))
3698 (setq found (tramp-check-for-regexp proc regexp)))))
3700 (while (not found)
3701 (tramp-accept-process-output proc 1)
3702 (unless (tramp-compat-process-live-p proc)
3703 (tramp-error-with-buffer
3704 nil proc 'file-error "Process has died"))
3705 (setq found (tramp-check-for-regexp proc regexp)))))
3706 (tramp-message proc 6 "\n%s" (buffer-string))
3707 (when (not found)
3708 (if timeout
3709 (tramp-error
3710 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3711 regexp timeout)
3712 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3713 found)))
3715 ;; It seems that Tru64 Unix does not like it if long strings are sent
3716 ;; to it in one go. (This happens when sending the Perl
3717 ;; `file-attributes' implementation, for instance.) Therefore, we
3718 ;; have this function which sends the string in chunks.
3719 (defun tramp-send-string (vec string)
3720 "Send the STRING via connection VEC.
3722 The STRING is expected to use Unix line-endings, but the lines sent to
3723 the remote host use line-endings as defined in the variable
3724 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3725 (let* ((p (tramp-get-connection-process vec))
3726 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3727 (unless p
3728 (tramp-error
3729 vec 'file-error "Can't send string to remote host -- not logged in"))
3730 (tramp-set-connection-property p "last-cmd-time" (current-time))
3731 (tramp-message vec 10 "%s" string)
3732 (with-current-buffer (tramp-get-connection-buffer vec)
3733 ;; Clean up the buffer. We cannot call `erase-buffer' because
3734 ;; narrowing might be in effect.
3735 (let (buffer-read-only) (delete-region (point-min) (point-max)))
3736 ;; Replace "\n" by `tramp-rsh-end-of-line'.
3737 (setq string
3738 (mapconcat
3739 'identity (split-string string "\n") tramp-rsh-end-of-line))
3740 (unless (or (string= string "")
3741 (string-equal (substring string -1) tramp-rsh-end-of-line))
3742 (setq string (concat string tramp-rsh-end-of-line)))
3743 ;; Send the string.
3744 (if (and chunksize (not (zerop chunksize)))
3745 (let ((pos 0)
3746 (end (length string)))
3747 (while (< pos end)
3748 (tramp-message
3749 vec 10 "Sending chunk from %s to %s"
3750 pos (min (+ pos chunksize) end))
3751 (process-send-string
3752 p (substring string pos (min (+ pos chunksize) end)))
3753 (setq pos (+ pos chunksize))))
3754 (process-send-string p string)))))
3756 (defun tramp-get-inode (vec)
3757 "Returns the virtual inode number.
3758 If it doesn't exist, generate a new one."
3759 (with-tramp-file-property vec (tramp-file-name-localname vec) "inode"
3760 (setq tramp-inodes (1+ tramp-inodes))))
3762 (defun tramp-get-device (vec)
3763 "Returns the virtual device number.
3764 If it doesn't exist, generate a new one."
3765 (with-tramp-connection-property (tramp-get-connection-process vec) "device"
3766 (cons -1 (setq tramp-devices (1+ tramp-devices)))))
3768 (defun tramp-equal-remote (file1 file2)
3769 "Check, whether the remote parts of FILE1 and FILE2 are identical.
3770 The check depends on method, user and host name of the files. If
3771 one of the components is missing, the default values are used.
3772 The local file name parts of FILE1 and FILE2 are not taken into
3773 account.
3775 Example:
3777 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3779 would yield t. On the other hand, the following check results in nil:
3781 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
3782 (and (tramp-tramp-file-p file1)
3783 (tramp-tramp-file-p file2)
3784 (string-equal (file-remote-p file1) (file-remote-p file2))))
3786 ;;;###tramp-autoload
3787 (defun tramp-mode-string-to-int (mode-string)
3788 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3789 (let* (case-fold-search
3790 (mode-chars (string-to-vector mode-string))
3791 (owner-read (aref mode-chars 1))
3792 (owner-write (aref mode-chars 2))
3793 (owner-execute-or-setid (aref mode-chars 3))
3794 (group-read (aref mode-chars 4))
3795 (group-write (aref mode-chars 5))
3796 (group-execute-or-setid (aref mode-chars 6))
3797 (other-read (aref mode-chars 7))
3798 (other-write (aref mode-chars 8))
3799 (other-execute-or-sticky (aref mode-chars 9)))
3800 (save-match-data
3801 (logior
3802 (cond
3803 ((char-equal owner-read ?r) (string-to-number "00400" 8))
3804 ((char-equal owner-read ?-) 0)
3805 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3806 (cond
3807 ((char-equal owner-write ?w) (string-to-number "00200" 8))
3808 ((char-equal owner-write ?-) 0)
3809 (t (error "Third char `%c' must be one of `w-'" owner-write)))
3810 (cond
3811 ((char-equal owner-execute-or-setid ?x) (string-to-number "00100" 8))
3812 ((char-equal owner-execute-or-setid ?S) (string-to-number "04000" 8))
3813 ((char-equal owner-execute-or-setid ?s) (string-to-number "04100" 8))
3814 ((char-equal owner-execute-or-setid ?-) 0)
3815 (t (error "Fourth char `%c' must be one of `xsS-'"
3816 owner-execute-or-setid)))
3817 (cond
3818 ((char-equal group-read ?r) (string-to-number "00040" 8))
3819 ((char-equal group-read ?-) 0)
3820 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
3821 (cond
3822 ((char-equal group-write ?w) (string-to-number "00020" 8))
3823 ((char-equal group-write ?-) 0)
3824 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
3825 (cond
3826 ((char-equal group-execute-or-setid ?x) (string-to-number "00010" 8))
3827 ((char-equal group-execute-or-setid ?S) (string-to-number "02000" 8))
3828 ((char-equal group-execute-or-setid ?s) (string-to-number "02010" 8))
3829 ((char-equal group-execute-or-setid ?-) 0)
3830 (t (error "Seventh char `%c' must be one of `xsS-'"
3831 group-execute-or-setid)))
3832 (cond
3833 ((char-equal other-read ?r) (string-to-number "00004" 8))
3834 ((char-equal other-read ?-) 0)
3835 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
3836 (cond
3837 ((char-equal other-write ?w) (string-to-number "00002" 8))
3838 ((char-equal other-write ?-) 0)
3839 (t (error "Ninth char `%c' must be one of `w-'" other-write)))
3840 (cond
3841 ((char-equal other-execute-or-sticky ?x) (string-to-number "00001" 8))
3842 ((char-equal other-execute-or-sticky ?T) (string-to-number "01000" 8))
3843 ((char-equal other-execute-or-sticky ?t) (string-to-number "01001" 8))
3844 ((char-equal other-execute-or-sticky ?-) 0)
3845 (t (error "Tenth char `%c' must be one of `xtT-'"
3846 other-execute-or-sticky)))))))
3848 (defconst tramp-file-mode-type-map
3849 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
3850 (1 . "p") ; fifo
3851 (2 . "c") ; character device
3852 (3 . "m") ; multiplexed character device (v7)
3853 (4 . "d") ; directory
3854 (5 . "?") ; Named special file (XENIX)
3855 (6 . "b") ; block device
3856 (7 . "?") ; multiplexed block device (v7)
3857 (8 . "-") ; regular file
3858 (9 . "n") ; network special file (HP-UX)
3859 (10 . "l") ; symlink
3860 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
3861 (12 . "s") ; socket
3862 (13 . "D") ; door special (Solaris)
3863 (14 . "w")) ; whiteout (BSD)
3864 "A list of file types returned from the `stat' system call.
3865 This is used to map a mode number to a permission string.")
3867 ;;;###tramp-autoload
3868 (defun tramp-file-mode-from-int (mode)
3869 "Turn an integer representing a file mode into an ls(1)-like string."
3870 (let ((type (cdr
3871 (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
3872 (user (logand (lsh mode -6) 7))
3873 (group (logand (lsh mode -3) 7))
3874 (other (logand (lsh mode -0) 7))
3875 (suid (> (logand (lsh mode -9) 4) 0))
3876 (sgid (> (logand (lsh mode -9) 2) 0))
3877 (sticky (> (logand (lsh mode -9) 1) 0)))
3878 (setq user (tramp-file-mode-permissions user suid "s"))
3879 (setq group (tramp-file-mode-permissions group sgid "s"))
3880 (setq other (tramp-file-mode-permissions other sticky "t"))
3881 (concat type user group other)))
3883 (defun tramp-file-mode-permissions (perm suid suid-text)
3884 "Convert a permission bitset into a string.
3885 This is used internally by `tramp-file-mode-from-int'."
3886 (let ((r (> (logand perm 4) 0))
3887 (w (> (logand perm 2) 0))
3888 (x (> (logand perm 1) 0)))
3889 (concat (or (and r "r") "-")
3890 (or (and w "w") "-")
3891 (or (and suid x suid-text) ; suid, execute
3892 (and suid (upcase suid-text)) ; suid, !execute
3893 (and x "x") "-")))) ; !suid
3895 ;;;###tramp-autoload
3896 (defun tramp-get-local-uid (id-format)
3897 "The uid of the local user, in ID-FORMAT.
3898 ID-FORMAT valid values are `string' and `integer'."
3899 (if (equal id-format 'integer) (user-uid) (user-login-name)))
3901 ;;;###tramp-autoload
3902 (defun tramp-get-local-gid (id-format)
3903 "The gid of the local user, in ID-FORMAT.
3904 ID-FORMAT valid values are `string' and `integer'."
3905 ;; `group-gid' has been introduced with Emacs 24.4.
3906 (if (and (fboundp 'group-gid) (equal id-format 'integer))
3907 (tramp-compat-funcall 'group-gid)
3908 (tramp-compat-file-attribute-group-id (file-attributes "~/" id-format))))
3910 (defun tramp-get-local-locale (&optional vec)
3911 "Determine locale, supporting UTF8 if possible.
3912 VEC is used for tracing."
3913 ;; We use key nil for local connection properties.
3914 (with-tramp-connection-property nil "locale"
3915 (let ((candidates '("en_US.utf8" "C.utf8" "en_US.UTF-8"))
3916 locale)
3917 (with-temp-buffer
3918 (unless (or (memq system-type '(windows-nt))
3919 (not (zerop (tramp-call-process
3920 nil "locale" nil t nil "-a"))))
3921 (while candidates
3922 (goto-char (point-min))
3923 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
3924 (buffer-string))
3925 (setq locale (car candidates)
3926 candidates nil)
3927 (setq candidates (cdr candidates))))))
3928 ;; Return value.
3929 (when vec (tramp-message vec 7 "locale %s" (or locale "C")))
3930 (or locale "C"))))
3932 ;;;###tramp-autoload
3933 (defun tramp-check-cached-permissions (vec access)
3934 "Check `file-attributes' caches for VEC.
3935 Return t if according to the cache access type ACCESS is known to
3936 be granted."
3937 (let ((result nil)
3938 (offset (cond
3939 ((eq ?r access) 1)
3940 ((eq ?w access) 2)
3941 ((eq ?x access) 3))))
3942 (dolist (suffix '("string" "integer") result)
3943 (setq
3944 result
3946 result
3947 (let ((file-attr
3949 (tramp-get-file-property
3950 vec (tramp-file-name-localname vec)
3951 (concat "file-attributes-" suffix) nil)
3952 (file-attributes
3953 (tramp-make-tramp-file-name
3954 (tramp-file-name-method vec)
3955 (tramp-file-name-user vec)
3956 (tramp-file-name-host vec)
3957 (tramp-file-name-localname vec)
3958 (tramp-file-name-hop vec))
3959 (intern suffix))))
3960 (remote-uid
3961 (tramp-get-connection-property
3962 vec (concat "uid-" suffix) nil))
3963 (remote-gid
3964 (tramp-get-connection-property
3965 vec (concat "gid-" suffix) nil))
3966 (unknown-id
3967 (if (string-equal suffix "string")
3968 tramp-unknown-id-string tramp-unknown-id-integer)))
3969 (and
3970 file-attr
3972 ;; Not a symlink.
3973 (eq t (tramp-compat-file-attribute-type file-attr))
3974 (null (tramp-compat-file-attribute-type file-attr)))
3976 ;; World accessible.
3977 (eq access
3978 (aref (tramp-compat-file-attribute-modes file-attr)
3979 (+ offset 6)))
3980 ;; User accessible and owned by user.
3981 (and
3982 (eq access
3983 (aref (tramp-compat-file-attribute-modes file-attr) offset))
3984 (or (equal remote-uid
3985 (tramp-compat-file-attribute-user-id file-attr))
3986 (equal unknown-id
3987 (tramp-compat-file-attribute-user-id file-attr))))
3988 ;; Group accessible and owned by user's principal group.
3989 (and
3990 (eq access
3991 (aref (tramp-compat-file-attribute-modes file-attr)
3992 (+ offset 3)))
3993 (or (equal remote-gid
3994 (tramp-compat-file-attribute-group-id file-attr))
3995 (equal unknown-id
3996 (tramp-compat-file-attribute-group-id
3997 file-attr))))))))))))
3999 ;;;###tramp-autoload
4000 (defun tramp-local-host-p (vec)
4001 "Return t if this points to the local host, nil otherwise."
4002 ;; We cannot use `tramp-file-name-real-host'. A port is an
4003 ;; indication for an ssh tunnel or alike.
4004 (let ((host (tramp-file-name-host vec)))
4005 (and
4006 (stringp host)
4007 (string-match tramp-local-host-regexp host)
4008 ;; The method shall be applied to one of the shell file name
4009 ;; handlers. `tramp-local-host-p' is also called for "smb" and
4010 ;; alike, where it must fail.
4011 (tramp-get-method-parameter vec 'tramp-login-program)
4012 ;; The local temp directory must be writable for the other user.
4013 (file-writable-p
4014 (tramp-make-tramp-file-name
4015 (tramp-file-name-method vec)
4016 (tramp-file-name-user vec)
4017 host
4018 (tramp-compat-temporary-file-directory)))
4019 ;; On some systems, chown runs only for root.
4020 (or (zerop (user-uid))
4021 ;; This is defined in tramp-sh.el. Let's assume this is
4022 ;; loaded already.
4023 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
4025 (defun tramp-get-remote-tmpdir (vec)
4026 "Return directory for temporary files on the remote host identified by VEC."
4027 (with-tramp-connection-property vec "tmpdir"
4028 (let ((dir (tramp-make-tramp-file-name
4029 (tramp-file-name-method vec)
4030 (tramp-file-name-user vec)
4031 (tramp-file-name-host vec)
4032 (or (tramp-get-method-parameter vec 'tramp-tmpdir) "/tmp")
4033 (tramp-file-name-hop vec))))
4034 (or (and (file-directory-p dir) (file-writable-p dir)
4035 (file-remote-p dir 'localname))
4036 (tramp-error vec 'file-error "Directory %s not accessible" dir))
4037 dir)))
4039 ;;;###tramp-autoload
4040 (defun tramp-make-tramp-temp-file (vec)
4041 "Create a temporary file on the remote host identified by VEC.
4042 Return the local name of the temporary file."
4043 (let ((prefix (expand-file-name
4044 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))
4045 result)
4046 (while (not result)
4047 ;; `make-temp-file' would be the natural choice for
4048 ;; implementation. But it calls `write-region' internally,
4049 ;; which also needs a temporary file - we would end in an
4050 ;; infinite loop.
4051 (setq result (make-temp-name prefix))
4052 (if (file-exists-p result)
4053 (setq result nil)
4054 ;; This creates the file by side effect.
4055 (set-file-times result)
4056 (set-file-modes result (string-to-number "0700" 8))))
4058 ;; Return the local part.
4059 (with-parsed-tramp-file-name result nil localname)))
4061 (defun tramp-delete-temp-file-function ()
4062 "Remove temporary files related to current buffer."
4063 (when (stringp tramp-temp-buffer-file-name)
4064 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
4066 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
4067 (add-hook 'tramp-unload-hook
4068 (lambda ()
4069 (remove-hook 'kill-buffer-hook
4070 'tramp-delete-temp-file-function)))
4072 (defun tramp-handle-make-auto-save-file-name ()
4073 "Like `make-auto-save-file-name' for Tramp files.
4074 Returns a file name in `tramp-auto-save-directory' for autosaving
4075 this file, if that variable is non-nil."
4076 (when (stringp tramp-auto-save-directory)
4077 (setq tramp-auto-save-directory
4078 (expand-file-name tramp-auto-save-directory)))
4079 ;; Create directory.
4080 (unless (or (null tramp-auto-save-directory)
4081 (file-exists-p tramp-auto-save-directory))
4082 (make-directory tramp-auto-save-directory t))
4084 (let ((system-type
4085 (if (and (stringp tramp-auto-save-directory)
4086 (file-remote-p tramp-auto-save-directory))
4087 'not-windows
4088 system-type))
4089 (auto-save-file-name-transforms
4090 (if (null tramp-auto-save-directory)
4091 auto-save-file-name-transforms))
4092 (buffer-file-name
4093 (if (null tramp-auto-save-directory)
4094 buffer-file-name
4095 (expand-file-name
4096 (tramp-subst-strs-in-string
4097 '(("_" . "|")
4098 ("/" . "_a")
4099 (":" . "_b")
4100 ("|" . "__")
4101 ("[" . "_l")
4102 ("]" . "_r"))
4103 (tramp-compat-file-name-unquote (buffer-file-name)))
4104 tramp-auto-save-directory))))
4105 ;; Run plain `make-auto-save-file-name'.
4106 (tramp-run-real-handler 'make-auto-save-file-name nil)))
4108 (defun tramp-subst-strs-in-string (alist string)
4109 "Replace all occurrences of the string FROM with TO in STRING.
4110 ALIST is of the form ((FROM . TO) ...)."
4111 (save-match-data
4112 (while alist
4113 (let* ((pr (car alist))
4114 (from (car pr))
4115 (to (cdr pr)))
4116 (while (string-match (regexp-quote from) string)
4117 (setq string (replace-match to t t string)))
4118 (setq alist (cdr alist))))
4119 string))
4121 (defun tramp-handle-temporary-file-directory ()
4122 "Like `temporary-file-directory' for Tramp files."
4123 (catch 'result
4124 (dolist (dir `(,(ignore-errors
4125 (tramp-get-remote-tmpdir
4126 (tramp-dissect-file-name default-directory)))
4127 ,default-directory))
4128 (when (and (stringp dir) (file-directory-p dir) (file-writable-p dir))
4129 (throw 'result (expand-file-name dir))))))
4131 (defun tramp-handle-make-nearby-temp-file (prefix &optional dir-flag suffix)
4132 "Like `make-nearby-temp-file' for Tramp files."
4133 (let ((temporary-file-directory
4134 (tramp-compat-temporary-file-directory-function)))
4135 (make-temp-file prefix dir-flag suffix)))
4137 ;;; Compatibility functions section:
4139 (defun tramp-call-process
4140 (vec program &optional infile destination display &rest args)
4141 "Calls `call-process' on the local host.
4142 It always returns a return code. The Lisp error raised when
4143 PROGRAM is nil is trapped also, returning 1. Furthermore, traces
4144 are written with verbosity of 6."
4145 (let ((default-directory (tramp-compat-temporary-file-directory))
4146 (v (or vec
4147 (vector tramp-current-method tramp-current-user
4148 tramp-current-host nil nil)))
4149 (destination (if (eq destination t) (current-buffer) destination))
4150 output error result)
4151 (tramp-message
4152 v 6 "`%s %s' %s %s"
4153 program (mapconcat 'identity args " ") infile destination)
4154 (condition-case err
4155 (with-temp-buffer
4156 (setq result
4157 (apply
4158 'call-process program infile (or destination t) display args))
4159 ;; `result' could also be an error string.
4160 (when (stringp result)
4161 (setq error result
4162 result 1))
4163 (with-current-buffer
4164 (if (bufferp destination) destination (current-buffer))
4165 (setq output (buffer-string))))
4166 (error
4167 (setq error (error-message-string err)
4168 result 1)))
4169 (if (zerop (length error))
4170 (tramp-message v 6 "%d\n%s" result output)
4171 (tramp-message v 6 "%d\n%s\n%s" result output error))
4172 result))
4174 (defun tramp-call-process-region
4175 (vec start end program &optional delete buffer display &rest args)
4176 "Calls `call-process-region' on the local host.
4177 It always returns a return code. The Lisp error raised when
4178 PROGRAM is nil is trapped also, returning 1. Furthermore, traces
4179 are written with verbosity of 6."
4180 (let ((default-directory (tramp-compat-temporary-file-directory))
4181 (v (or vec
4182 (vector tramp-current-method tramp-current-user
4183 tramp-current-host nil nil)))
4184 (buffer (if (eq buffer t) (current-buffer) buffer))
4185 result)
4186 (tramp-message
4187 v 6 "`%s %s' %s %s %s %s"
4188 program (mapconcat 'identity args " ") start end delete buffer)
4189 (condition-case err
4190 (progn
4191 (setq result
4192 (apply
4193 'call-process-region
4194 start end program delete buffer display args))
4195 ;; `result' could also be an error string.
4196 (when (stringp result)
4197 (signal 'file-error (list result)))
4198 (with-current-buffer (if (bufferp buffer) buffer (current-buffer))
4199 (if (zerop result)
4200 (tramp-message v 6 "%d" result)
4201 (tramp-message v 6 "%d\n%s" result (buffer-string)))))
4202 (error
4203 (setq result 1)
4204 (tramp-message v 6 "%d\n%s" result (error-message-string err))))
4205 result))
4207 ;;;###tramp-autoload
4208 (defun tramp-read-passwd (proc &optional prompt)
4209 "Read a password from user (compat function).
4210 Consults the auth-source package.
4211 Invokes `password-read' if available, `read-passwd' else."
4212 (let* ((case-fold-search t)
4213 (key (tramp-make-tramp-file-name
4214 tramp-current-method tramp-current-user
4215 tramp-current-host ""))
4216 (pw-prompt
4217 (or prompt
4218 (with-current-buffer (process-buffer proc)
4219 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
4220 (format "%s for %s " (capitalize (match-string 1)) key))))
4221 ;; We suspend the timers while reading the password.
4222 (stimers (with-timeout-suspend))
4223 auth-info auth-passwd)
4225 (unwind-protect
4226 (with-parsed-tramp-file-name key nil
4227 (prog1
4229 ;; See if auth-sources contains something useful.
4230 ;; `auth-source-user-or-password' is an obsoleted
4231 ;; function since Emacs 24.1, it has been replaced by
4232 ;; `auth-source-search'.
4233 (ignore-errors
4234 (and (tramp-get-connection-property
4235 v "first-password-request" nil)
4236 ;; Try with Tramp's current method.
4237 (if (fboundp 'auth-source-search)
4238 (setq auth-info
4239 (auth-source-search
4240 :max 1
4241 (and tramp-current-user :user)
4242 tramp-current-user
4243 :host tramp-current-host
4244 :port tramp-current-method
4245 :require
4246 (cons
4247 :secret (and tramp-current-user '(:user))))
4248 auth-passwd (plist-get
4249 (nth 0 auth-info) :secret)
4250 auth-passwd (if (functionp auth-passwd)
4251 (funcall auth-passwd)
4252 auth-passwd))
4253 (tramp-compat-funcall
4254 'auth-source-user-or-password
4255 "password" tramp-current-host tramp-current-method))))
4256 ;; Try the password cache.
4257 (let ((password (password-read pw-prompt key)))
4258 (password-cache-add key password)
4259 password)
4260 ;; Else, get the password interactively.
4261 (read-passwd pw-prompt))
4262 (tramp-set-connection-property v "first-password-request" nil)))
4263 ;; Reenable the timers.
4264 (with-timeout-unsuspend stimers))))
4266 ;;;###tramp-autoload
4267 (defun tramp-clear-passwd (vec)
4268 "Clear password cache for connection related to VEC."
4269 (let ((method (tramp-file-name-method vec))
4270 (user (tramp-file-name-user vec))
4271 (host (tramp-file-name-host vec))
4272 (hop (tramp-file-name-hop vec)))
4273 (when hop
4274 ;; Clear also the passwords of the hops.
4275 (tramp-clear-passwd
4276 (tramp-dissect-file-name
4277 (concat
4278 tramp-prefix-format
4279 (replace-regexp-in-string
4280 (concat tramp-postfix-hop-regexp "$")
4281 tramp-postfix-host-format hop)))))
4282 ;; `auth-source-forget-user-or-password' is an obsoleted function
4283 ;; since Emacs 24.1, it has been replaced by `auth-source-forget'.
4284 (if (fboundp 'auth-source-forget)
4285 (auth-source-forget
4286 `(:max 1 ,(and user :user) ,user :host ,host :port ,method))
4287 (tramp-compat-funcall
4288 'auth-source-forget-user-or-password "password" host method))
4289 (password-cache-remove (tramp-make-tramp-file-name method user host ""))))
4291 ;; Snarfed code from time-date.el.
4293 (defconst tramp-half-a-year '(241 17024)
4294 "Evaluated by \"(days-to-time 183)\".")
4296 ;;;###tramp-autoload
4297 (defun tramp-time-diff (t1 t2)
4298 "Return the difference between the two times, in seconds.
4299 T1 and T2 are time values (as returned by `current-time' for example)."
4300 ;; Starting with Emacs 25.1, we could change this to use `time-subtract'.
4301 (float-time (tramp-compat-funcall 'subtract-time t1 t2)))
4303 (defun tramp-unquote-shell-quote-argument (s)
4304 "Remove quotation prefix \"/:\" from string S, and quote it then for shell."
4305 (shell-quote-argument (tramp-compat-file-name-unquote s)))
4307 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
4308 ;; does not deal well with newline characters. Newline is replaced by
4309 ;; backslash newline. But if, say, the string `a backslash newline b'
4310 ;; is passed to a shell, the shell will expand this into "ab",
4311 ;; completely omitting the newline. This is not what was intended.
4312 ;; It does not appear to be possible to make the function
4313 ;; `shell-quote-argument' work with newlines without making it
4314 ;; dependent on the shell used. But within this package, we know that
4315 ;; we will always use a Bourne-like shell, so we use an approach which
4316 ;; groks newlines.
4318 ;; The approach is simple: we call `shell-quote-argument', then
4319 ;; massage the newline part of the result.
4321 ;; This function should produce a string which is grokked by a Unix
4322 ;; shell, even if the Emacs is running on Windows. Since this is the
4323 ;; kludges section, we bind `system-type' in such a way that
4324 ;; `shell-quote-argument' behaves as if on Unix.
4326 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
4327 ;; function to work with Bourne-like shells.
4329 ;; CCC: This function should be rewritten so that
4330 ;; `shell-quote-argument' is not used. This way, we are safe from
4331 ;; changes in `shell-quote-argument'.
4332 ;;;###tramp-autoload
4333 (defun tramp-shell-quote-argument (s)
4334 "Similar to `shell-quote-argument', but groks newlines.
4335 Only works for Bourne-like shells."
4336 (let ((system-type 'not-windows))
4337 (save-match-data
4338 (let ((result (tramp-unquote-shell-quote-argument s))
4339 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
4340 (when (and (>= (length result) 2)
4341 (string= (substring result 0 2) "\\~"))
4342 (setq result (substring result 1)))
4343 (while (string-match nl result)
4344 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
4345 t t result)))
4346 result))))
4348 ;;; Integration of eshell.el:
4350 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
4351 ;; when `default-directory' points to another host.
4352 (defun tramp-eshell-directory-change ()
4353 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
4354 (setq eshell-path-env
4355 (if (tramp-tramp-file-p default-directory)
4356 (with-parsed-tramp-file-name default-directory nil
4357 (mapconcat
4358 'identity
4360 ;; When `tramp-own-remote-path' is in `tramp-remote-path',
4361 ;; the remote path is only set in the session cache.
4362 (tramp-get-connection-property
4363 (tramp-get-connection-process v) "remote-path" nil)
4364 (tramp-get-connection-property v "remote-path" nil))
4365 ":"))
4366 (getenv "PATH"))))
4368 (eval-after-load "esh-util"
4369 '(progn
4370 (add-hook 'eshell-mode-hook
4371 'tramp-eshell-directory-change)
4372 (add-hook 'eshell-directory-change-hook
4373 'tramp-eshell-directory-change)
4374 (add-hook 'tramp-unload-hook
4375 (lambda ()
4376 (remove-hook 'eshell-mode-hook
4377 'tramp-eshell-directory-change)
4378 (remove-hook 'eshell-directory-change-hook
4379 'tramp-eshell-directory-change)))))
4381 ;; Checklist for `tramp-unload-hook'
4382 ;; - Unload all `tramp-*' packages
4383 ;; - Reset `file-name-handler-alist'
4384 ;; - Cleanup hooks where Tramp functions are in
4385 ;; - Cleanup advised functions
4386 ;; - Cleanup autoloads
4387 ;;;###autoload
4388 (defun tramp-unload-tramp ()
4389 "Discard Tramp from loading remote files."
4390 (interactive)
4391 ;; ange-ftp settings must be enabled.
4392 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
4393 ;; Maybe it's not loaded yet.
4394 (ignore-errors (unload-feature 'tramp 'force)))
4396 (provide 'tramp)
4398 ;;; TODO:
4400 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
4401 ;; by the files in that directory. Add this here.
4403 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
4405 ;; * Better error checking. At least whenever we see something
4406 ;; strange when doing zerop, we should kill the process and start
4407 ;; again. (Greg Stark)
4409 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
4411 ;; * I was wondering if it would be possible to use tramp even if I'm
4412 ;; actually using sshfs. But when I launch a command I would like
4413 ;; to get it executed on the remote machine where the files really
4414 ;; are. (Andrea Crotti)
4416 ;; * Run emerge on two remote files. Bug is described here:
4417 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
4418 ;; (Bug#6850)
4420 ;; * Use also port to distinguish connections. This is needed for
4421 ;; different hosts sitting behind a single router (distinguished by
4422 ;; different port numbers). (Tzvi Edelman)
4424 ;; * Refactor code from different handlers. Start with
4425 ;; *-process-file. One idea is to generalize `tramp-send-command'
4426 ;; and friends, for most of the handlers this is the major
4427 ;; difference between the different backends. Other handlers but
4428 ;; *-process-file would profit from this as well.
4430 ;;; tramp.el ends here
4432 ;; Local Variables:
4433 ;; mode: Emacs-Lisp
4434 ;; coding: utf-8
4435 ;; End: