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