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