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