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