Implement file name handler for `file-name-case-insensitive-p'
[emacs.git] / lisp / net / tramp.el
blobb0391ec77145073a112ba7ed7acfc0e8bb4e69f4
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 X 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 (let ((match (string-match (nth 0 tramp-file-name-structure) name)))
1243 (unless match
1244 (tramp-compat-user-error nil "Not a Tramp file name: \"%s\"" 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 (defun tramp-drop-volume-letter (name)
1683 "Cut off unnecessary drive letter from file NAME.
1684 The functions `tramp-*-handle-expand-file-name' call `expand-file-name'
1685 locally on a remote file name. When the local system is a W32 system
1686 but the remote system is Unix, this introduces a superfluous drive
1687 letter into the file name. This function removes it."
1688 (save-match-data
1689 (if (string-match "\\`[a-zA-Z]:/" name)
1690 (replace-match "/" nil t name)
1691 name)))
1693 ;;; Config Manipulation Functions:
1695 ;;;###tramp-autoload
1696 (defun tramp-set-completion-function (method function-list)
1697 "Sets the list of completion functions for METHOD.
1698 FUNCTION-LIST is a list of entries of the form (FUNCTION FILE).
1699 The FUNCTION is intended to parse FILE according its syntax.
1700 It might be a predefined FUNCTION, or a user defined FUNCTION.
1701 For the list of predefined FUNCTIONs see `tramp-completion-function-alist'.
1703 Example:
1705 (tramp-set-completion-function
1706 \"ssh\"
1707 \\='((tramp-parse-sconfig \"/etc/ssh_config\")
1708 (tramp-parse-sconfig \"~/.ssh/config\")))"
1710 (let ((r function-list)
1711 (v function-list))
1712 (setq tramp-completion-function-alist
1713 (delete (assoc method tramp-completion-function-alist)
1714 tramp-completion-function-alist))
1716 (while v
1717 ;; Remove double entries.
1718 (when (member (car v) (cdr v))
1719 (setcdr v (delete (car v) (cdr v))))
1720 ;; Check for function and file or registry key.
1721 (unless (and (functionp (nth 0 (car v)))
1722 (cond
1723 ;; Windows registry.
1724 ((string-match "^HKEY_CURRENT_USER" (nth 1 (car v)))
1725 (and (memq system-type '(cygwin windows-nt))
1726 (zerop
1727 (tramp-call-process
1728 v "reg" nil nil nil "query" (nth 1 (car v))))))
1729 ;; Zeroconf service type.
1730 ((string-match
1731 "^_[[:alpha:]]+\\._[[:alpha:]]+$" (nth 1 (car v))))
1732 ;; Configuration file.
1733 (t (file-exists-p (nth 1 (car v))))))
1734 (setq r (delete (car v) r)))
1735 (setq v (cdr v)))
1737 (when r
1738 (add-to-list 'tramp-completion-function-alist
1739 (cons method r)))))
1741 (defun tramp-get-completion-function (method)
1742 "Returns a list of completion functions for METHOD.
1743 For definition of that list see `tramp-set-completion-function'."
1744 (append
1745 `(;; Default settings are taken into account.
1746 (tramp-parse-default-user-host ,method)
1747 ;; Hosts visited once shall be remembered.
1748 (tramp-parse-connection-properties ,method))
1749 ;; The method related defaults.
1750 (cdr (assoc method tramp-completion-function-alist))))
1753 ;;; Fontification of `read-file-name':
1755 (defvar tramp-rfn-eshadow-overlay)
1756 (make-variable-buffer-local 'tramp-rfn-eshadow-overlay)
1758 (defun tramp-rfn-eshadow-setup-minibuffer ()
1759 "Set up a minibuffer for `file-name-shadow-mode'.
1760 Adds another overlay hiding filename parts according to Tramp's
1761 special handling of `substitute-in-file-name'."
1762 (when (symbol-value 'minibuffer-completing-file-name)
1763 (setq tramp-rfn-eshadow-overlay
1764 (make-overlay (minibuffer-prompt-end) (minibuffer-prompt-end)))
1765 ;; Copy rfn-eshadow-overlay properties.
1766 (let ((props (overlay-properties (symbol-value 'rfn-eshadow-overlay))))
1767 (while props
1768 ;; The `field' property prevents correct minibuffer
1769 ;; completion; we exclude it.
1770 (if (not (eq (car props) 'field))
1771 (overlay-put tramp-rfn-eshadow-overlay (pop props) (pop props))
1772 (pop props) (pop props))))))
1774 (add-hook 'rfn-eshadow-setup-minibuffer-hook
1775 'tramp-rfn-eshadow-setup-minibuffer)
1776 (add-hook 'tramp-unload-hook
1777 (lambda ()
1778 (remove-hook 'rfn-eshadow-setup-minibuffer-hook
1779 'tramp-rfn-eshadow-setup-minibuffer)))
1781 (defconst tramp-rfn-eshadow-update-overlay-regexp
1782 (format "[^%s/~]*\\(/\\|~\\)" tramp-postfix-host-format))
1784 (defun tramp-rfn-eshadow-update-overlay ()
1785 "Update `rfn-eshadow-overlay' to cover shadowed part of minibuffer input.
1786 This is intended to be used as a minibuffer `post-command-hook' for
1787 `file-name-shadow-mode'; the minibuffer should have already
1788 been set up by `rfn-eshadow-setup-minibuffer'."
1789 ;; In remote files name, there is a shadowing just for the local part.
1790 (ignore-errors
1791 (let ((end (or (overlay-end (symbol-value 'rfn-eshadow-overlay))
1792 (minibuffer-prompt-end)))
1793 ;; We do not want to send any remote command.
1794 (non-essential t))
1795 (when
1796 (tramp-tramp-file-p
1797 (buffer-substring-no-properties end (point-max)))
1798 (save-excursion
1799 (save-restriction
1800 (narrow-to-region
1801 (1+ (or (string-match
1802 tramp-rfn-eshadow-update-overlay-regexp
1803 (buffer-string) end)
1804 end))
1805 (point-max))
1806 (let ((rfn-eshadow-overlay tramp-rfn-eshadow-overlay)
1807 (rfn-eshadow-update-overlay-hook nil)
1808 file-name-handler-alist)
1809 (move-overlay rfn-eshadow-overlay (point-max) (point-max))
1810 (rfn-eshadow-update-overlay))))))))
1812 (add-hook 'rfn-eshadow-update-overlay-hook
1813 'tramp-rfn-eshadow-update-overlay)
1814 (add-hook 'tramp-unload-hook
1815 (lambda ()
1816 (remove-hook 'rfn-eshadow-update-overlay-hook
1817 'tramp-rfn-eshadow-update-overlay)))
1819 ;; Inodes don't exist for some file systems. Therefore we must
1820 ;; generate virtual ones. Used in `find-buffer-visiting'. The method
1821 ;; applied might be not so efficient (Ange-FTP uses hashes). But
1822 ;; performance isn't the major issue given that file transfer will
1823 ;; take time.
1824 (defvar tramp-inodes 0
1825 "Keeps virtual inodes numbers.")
1827 ;; Devices must distinguish physical file systems. The device numbers
1828 ;; provided by "lstat" aren't unique, because we operate on different hosts.
1829 ;; So we use virtual device numbers, generated by Tramp. Both Ange-FTP and
1830 ;; EFS use device number "-1". In order to be different, we use device number
1831 ;; (-1 . x), whereby "x" is unique for a given (method user host).
1832 (defvar tramp-devices 0
1833 "Keeps virtual device numbers.")
1835 (defun tramp-default-file-modes (filename)
1836 "Return file modes of FILENAME as integer.
1837 If the file modes of FILENAME cannot be determined, return the
1838 value of `default-file-modes', without execute permissions."
1839 (or (file-modes filename)
1840 (logand (default-file-modes) (string-to-number "0666" 8))))
1842 (defun tramp-replace-environment-variables (filename)
1843 "Replace environment variables in FILENAME.
1844 Return the string with the replaced variables."
1845 (or (ignore-errors
1846 ;; Optional arg has been introduced with Emacs 24 (?).
1847 (tramp-compat-funcall 'substitute-env-vars filename 'only-defined))
1848 ;; We need an own implementation.
1849 (save-match-data
1850 (let ((idx (string-match "$\\(\\w+\\)" filename)))
1851 ;; `$' is coded as `$$'.
1852 (when (and idx
1853 (or (zerop idx) (not (eq ?$ (aref filename (1- idx)))))
1854 (getenv (match-string 1 filename)))
1855 (setq filename
1856 (replace-match
1857 (substitute-in-file-name (match-string 0 filename))
1858 t nil filename)))
1859 filename))))
1861 (defun tramp-find-file-name-coding-system-alist (filename tmpname)
1862 "Like `find-operation-coding-system' for Tramp filenames.
1863 Tramp's `insert-file-contents' and `write-region' work over
1864 temporary file names. If `file-coding-system-alist' contains an
1865 expression, which matches more than the file name suffix, the
1866 coding system might not be determined. This function repairs it."
1867 (let (result)
1868 (dolist (elt file-coding-system-alist result)
1869 (when (and (consp elt) (string-match (car elt) filename))
1870 ;; We found a matching entry in `file-coding-system-alist'.
1871 ;; So we add a similar entry, but with the temporary file name
1872 ;; as regexp.
1873 (add-to-list
1874 'result (cons (regexp-quote tmpname) (cdr elt)) 'append)))))
1876 (defun tramp-run-real-handler (operation args)
1877 "Invoke normal file name handler for OPERATION.
1878 First arg specifies the OPERATION, second arg is a list of arguments to
1879 pass to the OPERATION."
1880 (let* ((inhibit-file-name-handlers
1881 `(tramp-file-name-handler
1882 tramp-vc-file-name-handler
1883 tramp-completion-file-name-handler
1884 cygwin-mount-name-hook-function
1885 cygwin-mount-map-drive-hook-function
1887 ,(and (eq inhibit-file-name-operation operation)
1888 inhibit-file-name-handlers)))
1889 (inhibit-file-name-operation operation))
1890 (apply operation args)))
1892 ;;;###autoload
1893 (progn (defun tramp-completion-run-real-handler (operation args)
1894 "Invoke `tramp-file-name-handler' for OPERATION.
1895 First arg specifies the OPERATION, second arg is a list of arguments to
1896 pass to the OPERATION."
1897 (let* ((inhibit-file-name-handlers
1898 `(tramp-completion-file-name-handler
1899 cygwin-mount-name-hook-function
1900 cygwin-mount-map-drive-hook-function
1902 ,(and (eq inhibit-file-name-operation operation)
1903 inhibit-file-name-handlers)))
1904 (inhibit-file-name-operation operation))
1905 (apply operation args))))
1907 ;; We handle here all file primitives. Most of them have the file
1908 ;; name as first parameter; nevertheless we check for them explicitly
1909 ;; in order to be signaled if a new primitive appears. This
1910 ;; scenario is needed because there isn't a way to decide by
1911 ;; syntactical means whether a foreign method must be called. It would
1912 ;; ease the life if `file-name-handler-alist' would support a decision
1913 ;; function as well but regexp only.
1914 (defun tramp-file-name-for-operation (operation &rest args)
1915 "Return file name related to OPERATION file primitive.
1916 ARGS are the arguments OPERATION has been called with."
1917 (cond
1918 ;; FILE resp DIRECTORY.
1919 ((member operation
1920 '(access-file byte-compiler-base-file-name delete-directory
1921 delete-file diff-latest-backup-file directory-file-name
1922 directory-files directory-files-and-attributes
1923 dired-compress-file dired-uncache
1924 file-accessible-directory-p file-attributes
1925 file-directory-p file-executable-p file-exists-p
1926 file-local-copy file-modes
1927 file-name-as-directory file-name-directory
1928 file-name-nondirectory file-name-sans-versions
1929 file-ownership-preserved-p file-readable-p
1930 file-regular-p file-remote-p file-symlink-p file-truename
1931 file-writable-p find-backup-file-name find-file-noselect
1932 get-file-buffer insert-directory insert-file-contents
1933 load make-directory make-directory-internal
1934 set-file-modes set-file-times substitute-in-file-name
1935 unhandled-file-name-directory vc-registered
1936 ;; Emacs 24+ only.
1937 file-acl file-notify-add-watch file-selinux-context
1938 set-file-acl set-file-selinux-context
1939 ;; Emacs 26+ only.
1940 file-name-case-insensitive-p))
1941 (if (file-name-absolute-p (nth 0 args))
1942 (nth 0 args)
1943 (expand-file-name (nth 0 args))))
1944 ;; FILE DIRECTORY resp FILE1 FILE2.
1945 ((member operation
1946 '(add-name-to-file copy-directory copy-file expand-file-name
1947 file-name-all-completions file-name-completion
1948 file-newer-than-file-p make-symbolic-link rename-file
1949 ;; Emacs 24+ only.
1950 file-equal-p file-in-directory-p))
1951 (save-match-data
1952 (cond
1953 ((tramp-tramp-file-p (nth 0 args)) (nth 0 args))
1954 ((tramp-tramp-file-p (nth 1 args)) (nth 1 args))
1955 (t (buffer-file-name (current-buffer))))))
1956 ;; START END FILE.
1957 ((eq operation 'write-region)
1958 (nth 2 args))
1959 ;; BUFFER.
1960 ((member operation
1961 '(make-auto-save-file-name
1962 set-visited-file-modtime verify-visited-file-modtime))
1963 (buffer-file-name
1964 (if (bufferp (nth 0 args)) (nth 0 args) (current-buffer))))
1965 ;; COMMAND.
1966 ((member operation
1967 '(process-file shell-command start-file-process
1968 ;; Emacs 26+ only.
1969 make-nearby-temp-file temporary-file-directory))
1970 default-directory)
1971 ;; PROC.
1972 ((member operation
1973 '(;; Emacs 24+ only.
1974 file-notify-rm-watch
1975 ;; Emacs 25+ only.
1976 file-notify-valid-p))
1977 (when (processp (nth 0 args))
1978 (with-current-buffer (process-buffer (nth 0 args))
1979 default-directory)))
1980 ;; Unknown file primitive.
1981 (t (error "unknown file I/O primitive: %s" operation))))
1983 (defun tramp-find-foreign-file-name-handler
1984 (filename &optional operation completion)
1985 "Return foreign file name handler if exists."
1986 (when (tramp-tramp-file-p filename)
1987 (let ((v (tramp-dissect-file-name filename t))
1988 (handler tramp-foreign-file-name-handler-alist)
1989 elt res)
1990 ;; When we are not fully sure that filename completion is safe,
1991 ;; we should not return a handler.
1992 (when (or (not completion)
1993 (tramp-file-name-method v) (tramp-file-name-user v)
1994 (and (tramp-file-name-host v)
1995 (not (member (tramp-file-name-host v)
1996 (mapcar 'car tramp-methods))))
1997 ;; Some operations are safe by default.
1998 (member
1999 operation
2000 '(file-name-as-directory
2001 file-name-directory
2002 file-name-nondirectory)))
2003 (while handler
2004 (setq elt (car handler)
2005 handler (cdr handler))
2006 (when (funcall (car elt) filename)
2007 (setq handler nil
2008 res (cdr elt))))
2009 res))))
2011 (defvar tramp-debug-on-error nil
2012 "Like `debug-on-error' but used Tramp internal.")
2014 (defmacro tramp-condition-case-unless-debug
2015 (var bodyform &rest handlers)
2016 "Like `condition-case-unless-debug' but `tramp-debug-on-error'."
2017 `(let ((debug-on-error tramp-debug-on-error))
2018 (tramp-compat-condition-case-unless-debug ,var ,bodyform ,@handlers)))
2020 ;; Main function.
2021 (defun tramp-file-name-handler (operation &rest args)
2022 "Invoke Tramp file name handler.
2023 Falls back to normal file name handler if no Tramp file name handler exists."
2024 (if tramp-mode
2025 (save-match-data
2026 (let* ((filename
2027 (tramp-replace-environment-variables
2028 (apply 'tramp-file-name-for-operation operation args)))
2029 (completion (tramp-completion-mode-p))
2030 (foreign
2031 (tramp-find-foreign-file-name-handler
2032 filename operation completion))
2033 result)
2034 (with-parsed-tramp-file-name filename nil
2035 ;; Call the backend function.
2036 (if foreign
2037 (tramp-condition-case-unless-debug err
2038 (let ((sf (symbol-function foreign)))
2039 ;; Some packages set the default directory to a
2040 ;; remote path, before respective Tramp packages
2041 ;; are already loaded. This results in
2042 ;; recursive loading. Therefore, we load the
2043 ;; Tramp packages locally.
2044 (when (and (listp sf) (eq (car sf) 'autoload))
2045 (let ((default-directory
2046 (tramp-compat-temporary-file-directory)))
2047 (load (cadr sf) 'noerror 'nomessage)))
2048 ;; If `non-essential' is non-nil, Tramp shall
2049 ;; not open a new connection.
2050 ;; If Tramp detects that it shouldn't continue
2051 ;; to work, it throws the `suppress' event.
2052 ;; This could happen for example, when Tramp
2053 ;; tries to open the same connection twice in a
2054 ;; short time frame.
2055 ;; In both cases, we try the default handler then.
2056 (setq result
2057 (catch 'non-essential
2058 (catch 'suppress
2059 (apply foreign operation args))))
2060 (cond
2061 ((eq result 'non-essential)
2062 (tramp-message
2063 v 5 "Non-essential received in operation %s"
2064 (cons operation args))
2065 (tramp-run-real-handler operation args))
2066 ((eq result 'suppress)
2067 (let (tramp-message-show-message)
2068 (tramp-message
2069 v 1 "Suppress received in operation %s"
2070 (cons operation args))
2071 (tramp-cleanup-connection v t)
2072 (tramp-run-real-handler operation args)))
2073 (t result)))
2075 ;; Trace that somebody has interrupted the operation.
2076 ((debug quit)
2077 (let (tramp-message-show-message)
2078 (tramp-message
2079 v 1 "Interrupt received in operation %s"
2080 (cons operation args)))
2081 ;; Propagate the quit signal.
2082 (signal (car err) (cdr err)))
2084 ;; When we are in completion mode, some failed
2085 ;; operations shall return at least a default value
2086 ;; in order to give the user a chance to correct the
2087 ;; file name in the minibuffer.
2088 ;; In order to get a full backtrace, one could apply
2089 ;; (setq tramp-debug-on-error t)
2090 (error
2091 (cond
2092 ((and completion (zerop (length localname))
2093 (memq operation '(file-exists-p file-directory-p)))
2095 ((and completion (zerop (length localname))
2096 (memq operation
2097 '(expand-file-name file-name-as-directory)))
2098 filename)
2099 ;; Propagate the error.
2100 (t (signal (car err) (cdr err))))))
2102 ;; Nothing to do for us. However, since we are in
2103 ;; `tramp-mode', we must suppress the volume letter on
2104 ;; MS Windows.
2105 (setq result (tramp-run-real-handler operation args))
2106 (if (stringp result)
2107 (tramp-drop-volume-letter result)
2108 result)))))
2110 ;; When `tramp-mode' is not enabled, we don't do anything.
2111 (tramp-run-real-handler operation args)))
2113 ;; In Emacs, there is some concurrency due to timers. If a timer
2114 ;; interrupts Tramp and wishes to use the same connection buffer as
2115 ;; the "main" Emacs, then garbage might occur in the connection
2116 ;; buffer. Therefore, we need to make sure that a timer does not use
2117 ;; the same connection buffer as the "main" Emacs. We implement a
2118 ;; cheap global lock, instead of locking each connection buffer
2119 ;; separately. The global lock is based on two variables,
2120 ;; `tramp-locked' and `tramp-locker'. `tramp-locked' is set to true
2121 ;; (with setq) to indicate a lock. But Tramp also calls itself during
2122 ;; processing of a single file operation, so we need to allow
2123 ;; recursive calls. That's where the `tramp-locker' variable comes in
2124 ;; -- it is let-bound to t during the execution of the current
2125 ;; handler. So if `tramp-locked' is t and `tramp-locker' is also t,
2126 ;; then we should just proceed because we have been called
2127 ;; recursively. But if `tramp-locker' is nil, then we are a timer
2128 ;; interrupting the "main" Emacs, and then we signal an error.
2130 (defvar tramp-locked nil
2131 "If non-nil, then Tramp is currently busy.
2132 Together with `tramp-locker', this implements a locking mechanism
2133 preventing reentrant calls of Tramp.")
2135 (defvar tramp-locker nil
2136 "If non-nil, then a caller has locked Tramp.
2137 Together with `tramp-locked', this implements a locking mechanism
2138 preventing reentrant calls of Tramp.")
2140 ;; Avoid recursive loading of tramp.el.
2141 ;;;###autoload(defun tramp-completion-file-name-handler (operation &rest args)
2142 ;;;###autoload (tramp-completion-run-real-handler operation args))
2144 (defun tramp-completion-file-name-handler (operation &rest args)
2145 "Invoke Tramp file name completion handler.
2146 Falls back to normal file name handler if no Tramp file name handler exists."
2147 (let ((fn (assoc operation tramp-completion-file-name-handler-alist)))
2148 (if (and
2149 ;; When `tramp-mode' is not enabled, we don't do anything.
2150 fn tramp-mode (tramp-completion-mode-p)
2151 ;; For other syntaxes than `sep', the regexp matches many common
2152 ;; situations where the user doesn't actually want to use Tramp.
2153 ;; So to avoid autoloading Tramp after typing just "/s", we
2154 ;; disable this part of the completion, unless the user implicitly
2155 ;; indicated his interest in using a fancier completion system.
2156 (or (eq tramp-syntax 'sep)
2157 (featurep 'tramp) ;; If it's loaded, we may as well use it.
2158 ;; `partial-completion-mode' is obsoleted with Emacs 24.1.
2159 (and (boundp 'partial-completion-mode)
2160 (symbol-value 'partial-completion-mode))
2161 ;; FIXME: These may have been loaded even if the user never
2162 ;; intended to use them.
2163 (featurep 'ido)
2164 (featurep 'icicles)))
2165 (save-match-data (apply (cdr fn) args))
2166 (tramp-completion-run-real-handler operation args))))
2168 ;;;###autoload
2169 (progn (defun tramp-autoload-file-name-handler (operation &rest args)
2170 "Load Tramp file name handler, and perform OPERATION."
2171 ;; Avoid recursive loading of tramp.el.
2172 (let ((default-directory temporary-file-directory))
2173 (load "tramp" nil t))
2174 (apply operation args)))
2176 ;; `tramp-autoload-file-name-handler' must be registered before
2177 ;; evaluation of site-start and init files, because there might exist
2178 ;; remote files already, f.e. files kept via recentf-mode. We cannot
2179 ;; autoload `tramp-file-name-handler', because it would result in
2180 ;; recursive loading of tramp.el when `default-directory' is set to
2181 ;; remote.
2182 ;;;###autoload
2183 (progn (defun tramp-register-autoload-file-name-handlers ()
2184 "Add Tramp file name handlers to `file-name-handler-alist' during autoload."
2185 (add-to-list 'file-name-handler-alist
2186 (cons tramp-file-name-regexp
2187 'tramp-autoload-file-name-handler))
2188 (put 'tramp-autoload-file-name-handler 'safe-magic t)
2189 (add-to-list 'file-name-handler-alist
2190 (cons tramp-completion-file-name-regexp
2191 'tramp-completion-file-name-handler))
2192 (put 'tramp-completion-file-name-handler 'safe-magic t)))
2194 ;;;###autoload
2195 (tramp-register-autoload-file-name-handlers)
2197 (defun tramp-register-file-name-handlers ()
2198 "Add Tramp file name handlers to `file-name-handler-alist'."
2199 ;; Remove autoloaded handlers from file name handler alist. Useful,
2200 ;; if `tramp-syntax' has been changed.
2201 (dolist (fnh '(tramp-file-name-handler
2202 tramp-completion-file-name-handler
2203 tramp-autoload-file-name-handler))
2204 (let ((a1 (rassq fnh file-name-handler-alist)))
2205 (setq file-name-handler-alist (delq a1 file-name-handler-alist))))
2206 ;; The initial value of `tramp-file-name-regexp' is too simple
2207 ;; minded, but we cannot give it the real value in the autoload
2208 ;; pattern. See Bug#24889.
2209 (setq tramp-file-name-regexp (car tramp-file-name-structure))
2210 ;; Add the handlers.
2211 (add-to-list 'file-name-handler-alist
2212 (cons tramp-file-name-regexp 'tramp-file-name-handler))
2213 (put 'tramp-file-name-handler 'safe-magic t)
2214 (add-to-list 'file-name-handler-alist
2215 (cons tramp-completion-file-name-regexp
2216 'tramp-completion-file-name-handler))
2217 (put 'tramp-completion-file-name-handler 'safe-magic t)
2218 ;; If jka-compr or epa-file are already loaded, move them to the
2219 ;; front of `file-name-handler-alist'.
2220 (dolist (fnh '(epa-file-handler jka-compr-handler))
2221 (let ((entry (rassoc fnh file-name-handler-alist)))
2222 (when entry
2223 (setq file-name-handler-alist
2224 (cons entry (delete entry file-name-handler-alist)))))))
2226 (eval-after-load 'tramp (tramp-register-file-name-handlers))
2228 (defun tramp-exists-file-name-handler (operation &rest args)
2229 "Check, whether OPERATION runs a file name handler."
2230 ;; The file name handler is determined on base of either an
2231 ;; argument, `buffer-file-name', or `default-directory'.
2232 (ignore-errors
2233 (let* ((buffer-file-name "/")
2234 (default-directory "/")
2235 (fnha file-name-handler-alist)
2236 (check-file-name-operation operation)
2237 (file-name-handler-alist
2238 (list
2239 (cons "/"
2240 (lambda (operation &rest args)
2241 "Returns OPERATION if it is the one to be checked."
2242 (if (equal check-file-name-operation operation)
2243 operation
2244 (let ((file-name-handler-alist fnha))
2245 (apply operation args))))))))
2246 (equal (apply operation args) operation))))
2248 ;;;###autoload
2249 (defun tramp-unload-file-name-handlers ()
2250 "Unload Tramp file name handlers from `file-name-handler-alist'."
2251 (setq file-name-handler-alist
2252 (delete (rassoc 'tramp-file-name-handler
2253 file-name-handler-alist)
2254 (delete (rassoc 'tramp-completion-file-name-handler
2255 file-name-handler-alist)
2256 file-name-handler-alist))))
2258 (add-hook 'tramp-unload-hook 'tramp-unload-file-name-handlers)
2260 ;;; File name handler functions for completion mode:
2262 ;;;###autoload
2263 (defvar tramp-completion-mode nil
2264 "If non-nil, external packages signal that they are in file name completion.
2266 This is necessary, because Tramp uses a heuristic depending on last
2267 input event. This fails when external packages use other characters
2268 but <TAB>, <SPACE> or ?\\? for file name completion. This variable
2269 should never be set globally, the intention is to let-bind it.")
2271 ;; Necessary because `tramp-file-name-regexp-unified' and
2272 ;; `tramp-completion-file-name-regexp-unified' aren't different. If
2273 ;; nil, `tramp-completion-run-real-handler' is called (i.e. forwarding
2274 ;; to `tramp-file-name-handler'). Otherwise, it takes
2275 ;; `tramp-run-real-handler'. Using `last-input-event' is a little bit
2276 ;; risky, because completing a file might require loading other files,
2277 ;; like "~/.netrc", and for them it shouldn't be decided based on that
2278 ;; variable. On the other hand, those files shouldn't have partial
2279 ;; Tramp file name syntax. Maybe another variable should be introduced
2280 ;; overwriting this check in such cases. Or we change Tramp file name
2281 ;; syntax in order to avoid ambiguities.
2282 (defun tramp-completion-mode-p ()
2283 "Check, whether method / user name / host name completion is active."
2285 ;; Signal from outside. `non-essential' has been introduced in Emacs 24.
2286 (and (boundp 'non-essential) (symbol-value 'non-essential))
2287 tramp-completion-mode
2288 (equal last-input-event 'tab)
2289 (and (natnump last-input-event)
2291 ;; ?\t has event-modifier 'control.
2292 (equal last-input-event ?\t)
2293 (and (not (event-modifiers last-input-event))
2294 (or (equal last-input-event ?\?)
2295 (equal last-input-event ?\ )))))))
2297 (defun tramp-connectable-p (filename)
2298 "Check, whether it is possible to connect the remote host w/o side-effects.
2299 This is true, if either the remote host is already connected, or if we are
2300 not in completion mode."
2301 (let (tramp-verbose)
2302 (and (tramp-tramp-file-p filename)
2303 (or (not (tramp-completion-mode-p))
2304 (tramp-compat-process-live-p
2305 (tramp-get-connection-process
2306 (tramp-dissect-file-name filename)))))))
2308 (defun tramp-completion-handle-expand-file-name (name &optional dir)
2309 "Like `expand-file-name' for Tramp files."
2310 (if (tramp-completion-mode-p)
2311 (progn
2312 ;; If DIR is not given, use `default-directory' or "/".
2313 (setq dir (or dir default-directory "/"))
2314 ;; Unless NAME is absolute, concat DIR and NAME.
2315 (unless (file-name-absolute-p name)
2316 (setq name (concat (file-name-as-directory dir) name)))
2317 ;; Return NAME.
2318 name)
2320 (tramp-completion-run-real-handler
2321 'expand-file-name (list name dir))))
2323 ;; Method, host name and user name completion.
2324 ;; `tramp-completion-dissect-file-name' returns a list of
2325 ;; tramp-file-name structures. For all of them we return possible completions.
2326 (defun tramp-completion-handle-file-name-all-completions (filename directory)
2327 "Like `file-name-all-completions' for partial Tramp files."
2329 (let ((fullname
2330 (tramp-drop-volume-letter (expand-file-name filename directory)))
2331 hop result result1)
2333 ;; Suppress hop from completion.
2334 (when (string-match
2335 (concat
2336 tramp-prefix-regexp
2337 "\\(" "\\(" tramp-remote-file-name-spec-regexp
2338 tramp-postfix-hop-regexp
2339 "\\)+" "\\)")
2340 fullname)
2341 (setq hop (match-string 1 fullname)
2342 fullname (replace-match "" nil nil fullname 1)))
2344 ;; Possible completion structures.
2345 (dolist (elt (tramp-completion-dissect-file-name fullname))
2346 (let* ((method (tramp-file-name-method elt))
2347 (user (tramp-file-name-user elt))
2348 (host (tramp-file-name-host elt))
2349 (localname (tramp-file-name-localname elt))
2350 (m (tramp-find-method method user host))
2351 (tramp-current-user user) ; see `tramp-parse-passwd'
2352 all-user-hosts)
2354 (unless localname ;; Nothing to complete.
2356 (if (or user host)
2358 ;; Method dependent user / host combinations.
2359 (progn
2360 (mapc
2361 (lambda (x)
2362 (setq all-user-hosts
2363 (append all-user-hosts
2364 (funcall (nth 0 x) (nth 1 x)))))
2365 (tramp-get-completion-function m))
2367 (setq result
2368 (append result
2369 (mapcar
2370 (lambda (x)
2371 (tramp-get-completion-user-host
2372 method user host (nth 0 x) (nth 1 x)))
2373 (delq nil all-user-hosts)))))
2375 ;; Possible methods.
2376 (setq result
2377 (append result (tramp-get-completion-methods m)))))))
2379 ;; Unify list, add hop, remove nil elements.
2380 (dolist (elt result)
2381 (when elt
2382 (string-match tramp-prefix-regexp elt)
2383 (setq elt (replace-match (concat tramp-prefix-format hop) nil nil elt))
2384 (add-to-list
2385 'result1
2386 (substring elt (length (tramp-drop-volume-letter directory))))))
2388 ;; Complete local parts.
2389 (append
2390 result1
2391 (ignore-errors
2392 (apply (if (tramp-connectable-p fullname)
2393 'tramp-completion-run-real-handler
2394 'tramp-run-real-handler)
2395 'file-name-all-completions (list (list filename directory)))))))
2397 ;; Method, host name and user name completion for a file.
2398 (defun tramp-completion-handle-file-name-completion
2399 (filename directory &optional predicate)
2400 "Like `file-name-completion' for Tramp files."
2401 (try-completion
2402 filename
2403 (mapcar 'list (file-name-all-completions filename directory))
2404 (when (and predicate
2405 (tramp-connectable-p (expand-file-name filename directory)))
2406 (lambda (x) (funcall predicate (expand-file-name (car x) directory))))))
2408 ;; I misuse a little bit the tramp-file-name structure in order to handle
2409 ;; completion possibilities for partial methods / user names / host names.
2410 ;; Return value is a list of tramp-file-name structures according to possible
2411 ;; completions. If "localname" is non-nil it means there
2412 ;; shouldn't be a completion anymore.
2414 ;; Expected results:
2416 ;; "/x" "/[x" "/x@" "/[x@" "/x@y" "/[x@y"
2417 ;; [nil nil "x" nil] [nil "x" nil nil] [nil "x" "y" nil]
2418 ;; [nil "x" nil nil]
2419 ;; ["x" nil nil nil]
2421 ;; "/x:" "/x:y" "/x:y:"
2422 ;; [nil nil "x" ""] [nil nil "x" "y"] ["x" nil "y" ""]
2423 ;; "/[x/" "/[x/y"
2424 ;; ["x" nil "" nil] ["x" nil "y" nil]
2425 ;; ["x" "" nil nil] ["x" "y" nil nil]
2427 ;; "/x:y@" "/x:y@z" "/x:y@z:"
2428 ;; [nil nil "x" "y@"] [nil nil "x" "y@z"] ["x" "y" "z" ""]
2429 ;; "/[x/y@" "/[x/y@z"
2430 ;; ["x" nil "y" nil] ["x" "y" "z" nil]
2431 (defun tramp-completion-dissect-file-name (name)
2432 "Returns a list of `tramp-file-name' structures.
2433 They are collected by `tramp-completion-dissect-file-name1'."
2435 (let* ((result)
2436 (x-nil "\\|\\(\\)")
2437 (tramp-completion-ipv6-regexp
2438 (format
2439 "[^%s]*"
2440 (if (zerop (length tramp-postfix-ipv6-format))
2441 tramp-postfix-host-format
2442 tramp-postfix-ipv6-format)))
2443 ;; "/method" "/[method"
2444 (tramp-completion-file-name-structure1
2445 (list (concat tramp-prefix-regexp "\\(" tramp-method-regexp x-nil "\\)$")
2446 1 nil nil nil))
2447 ;; "/user" "/[user"
2448 (tramp-completion-file-name-structure2
2449 (list (concat tramp-prefix-regexp "\\(" tramp-user-regexp x-nil "\\)$")
2450 nil 1 nil nil))
2451 ;; "/host" "/[host"
2452 (tramp-completion-file-name-structure3
2453 (list (concat tramp-prefix-regexp "\\(" tramp-host-regexp x-nil "\\)$")
2454 nil nil 1 nil))
2455 ;; "/[ipv6" "/[ipv6"
2456 (tramp-completion-file-name-structure4
2457 (list (concat tramp-prefix-regexp
2458 tramp-prefix-ipv6-regexp
2459 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2460 nil nil 1 nil))
2461 ;; "/user@host" "/[user@host"
2462 (tramp-completion-file-name-structure5
2463 (list (concat tramp-prefix-regexp
2464 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2465 "\\(" tramp-host-regexp x-nil "\\)$")
2466 nil 1 2 nil))
2467 ;; "/user@[ipv6" "/[user@ipv6"
2468 (tramp-completion-file-name-structure6
2469 (list (concat tramp-prefix-regexp
2470 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2471 tramp-prefix-ipv6-regexp
2472 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2473 nil 1 2 nil))
2474 ;; "/method:user" "/[method/user"
2475 (tramp-completion-file-name-structure7
2476 (list (concat tramp-prefix-regexp
2477 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2478 "\\(" tramp-user-regexp x-nil "\\)$")
2479 1 2 nil nil))
2480 ;; "/method:host" "/[method/host"
2481 (tramp-completion-file-name-structure8
2482 (list (concat tramp-prefix-regexp
2483 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2484 "\\(" tramp-host-regexp x-nil "\\)$")
2485 1 nil 2 nil))
2486 ;; "/method:[ipv6" "/[method/ipv6"
2487 (tramp-completion-file-name-structure9
2488 (list (concat tramp-prefix-regexp
2489 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2490 tramp-prefix-ipv6-regexp
2491 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2492 1 nil 2 nil))
2493 ;; "/method:user@host" "/[method/user@host"
2494 (tramp-completion-file-name-structure10
2495 (list (concat tramp-prefix-regexp
2496 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2497 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2498 "\\(" tramp-host-regexp x-nil "\\)$")
2499 1 2 3 nil))
2500 ;; "/method:user@[ipv6" "/[method/user@ipv6"
2501 (tramp-completion-file-name-structure11
2502 (list (concat tramp-prefix-regexp
2503 "\\(" tramp-method-regexp "\\)" tramp-postfix-method-regexp
2504 "\\(" tramp-user-regexp "\\)" tramp-postfix-user-regexp
2505 tramp-prefix-ipv6-regexp
2506 "\\(" tramp-completion-ipv6-regexp x-nil "\\)$")
2507 1 2 3 nil)))
2509 (mapc (lambda (structure)
2510 (add-to-list 'result
2511 (tramp-completion-dissect-file-name1 structure name)))
2512 (list
2513 tramp-completion-file-name-structure1
2514 tramp-completion-file-name-structure2
2515 tramp-completion-file-name-structure3
2516 tramp-completion-file-name-structure4
2517 tramp-completion-file-name-structure5
2518 tramp-completion-file-name-structure6
2519 tramp-completion-file-name-structure7
2520 tramp-completion-file-name-structure8
2521 tramp-completion-file-name-structure9
2522 tramp-completion-file-name-structure10
2523 tramp-completion-file-name-structure11
2524 tramp-file-name-structure))
2526 (delq nil result)))
2528 (defun tramp-completion-dissect-file-name1 (structure name)
2529 "Returns a `tramp-file-name' structure matching STRUCTURE.
2530 The structure consists of remote method, remote user,
2531 remote host and localname (filename on remote host)."
2533 (save-match-data
2534 (when (string-match (nth 0 structure) name)
2535 (let ((method (and (nth 1 structure)
2536 (match-string (nth 1 structure) name)))
2537 (user (and (nth 2 structure)
2538 (match-string (nth 2 structure) name)))
2539 (host (and (nth 3 structure)
2540 (match-string (nth 3 structure) name)))
2541 (localname (and (nth 4 structure)
2542 (match-string (nth 4 structure) name))))
2543 (vector method user host localname nil)))))
2545 ;; This function returns all possible method completions, adding the
2546 ;; trailing method delimiter.
2547 (defun tramp-get-completion-methods (partial-method)
2548 "Returns all method completions for PARTIAL-METHOD."
2549 (mapcar
2550 (lambda (method)
2551 (and method
2552 (string-match (concat "^" (regexp-quote partial-method)) method)
2553 (tramp-completion-make-tramp-file-name method nil nil nil)))
2554 (mapcar 'car tramp-methods)))
2556 ;; Compares partial user and host names with possible completions.
2557 (defun tramp-get-completion-user-host
2558 (method partial-user partial-host user host)
2559 "Returns the most expanded string for user and host name completion.
2560 PARTIAL-USER must match USER, PARTIAL-HOST must match HOST."
2561 (cond
2563 ((and partial-user partial-host)
2564 (if (and host
2565 (string-match (concat "^" (regexp-quote partial-host)) host)
2566 (string-equal partial-user (or user partial-user)))
2567 (setq user partial-user)
2568 (setq user nil
2569 host nil)))
2571 (partial-user
2572 (setq host nil)
2573 (unless
2574 (and user (string-match (concat "^" (regexp-quote partial-user)) user))
2575 (setq user nil)))
2577 (partial-host
2578 (setq user nil)
2579 (unless
2580 (and host (string-match (concat "^" (regexp-quote partial-host)) host))
2581 (setq host nil)))
2583 (t (setq user nil
2584 host nil)))
2586 (unless (zerop (+ (length user) (length host)))
2587 (tramp-completion-make-tramp-file-name method user host nil)))
2589 (defun tramp-parse-default-user-host (method)
2590 "Return a list of (user host) tuples allowed to access for METHOD.
2591 This function is added always in `tramp-get-completion-function'
2592 for all methods. Resulting data are derived from default settings."
2593 `((,(tramp-find-user method nil nil) ,(tramp-find-host method nil nil))))
2595 ;; Generic function.
2596 (defun tramp-parse-group (regexp match-level skip-regexp)
2597 "Return a (user host) tuple allowed to access.
2598 User is always nil."
2599 (let (result)
2600 (when (re-search-forward regexp (point-at-eol) t)
2601 (setq result (list nil (match-string match-level))))
2603 (> (skip-chars-forward skip-regexp) 0)
2604 (forward-line 1))
2605 result))
2607 ;; Generic function.
2608 (defun tramp-parse-file (filename function)
2609 "Return a list of (user host) tuples allowed to access.
2610 User is always nil."
2611 ;; On Windows, there are problems in completion when
2612 ;; `default-directory' is remote.
2613 (let ((default-directory (tramp-compat-temporary-file-directory)))
2614 (when (file-readable-p filename)
2615 (with-temp-buffer
2616 (insert-file-contents filename)
2617 (goto-char (point-min))
2618 (loop while (not (eobp)) collect (funcall function))))))
2620 ;;;###tramp-autoload
2621 (defun tramp-parse-rhosts (filename)
2622 "Return a list of (user host) tuples allowed to access.
2623 Either user or host may be nil."
2624 (tramp-parse-file filename 'tramp-parse-rhosts-group))
2626 (defun tramp-parse-rhosts-group ()
2627 "Return a (user host) tuple allowed to access.
2628 Either user or host may be nil."
2629 (let ((result)
2630 (regexp
2631 (concat
2632 "^\\(" tramp-host-regexp "\\)"
2633 "\\([ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2634 (when (re-search-forward regexp (point-at-eol) t)
2635 (setq result (append (list (match-string 3) (match-string 1)))))
2636 (forward-line 1)
2637 result))
2639 ;;;###tramp-autoload
2640 (defun tramp-parse-shosts (filename)
2641 "Return a list of (user host) tuples allowed to access.
2642 User is always nil."
2643 (tramp-parse-file filename 'tramp-parse-shosts-group))
2645 (defun tramp-parse-shosts-group ()
2646 "Return a (user host) tuple allowed to access.
2647 User is always nil."
2648 (tramp-parse-group (concat "^\\(" tramp-host-regexp "\\)") 1 ","))
2650 ;;;###tramp-autoload
2651 (defun tramp-parse-sconfig (filename)
2652 "Return a list of (user host) tuples allowed to access.
2653 User is always nil."
2654 (tramp-parse-file filename 'tramp-parse-sconfig-group))
2656 (defun tramp-parse-sconfig-group ()
2657 "Return a (user host) tuple allowed to access.
2658 User is always nil."
2659 (tramp-parse-group
2660 (concat "^[ \t]*Host[ \t]+" "\\(" tramp-host-regexp "\\)") 1 ","))
2662 ;; Generic function.
2663 (defun tramp-parse-shostkeys-sknownhosts (dirname regexp)
2664 "Return a list of (user host) tuples allowed to access.
2665 User is always nil."
2666 ;; On Windows, there are problems in completion when
2667 ;; `default-directory' is remote.
2668 (let* ((default-directory (tramp-compat-temporary-file-directory))
2669 (files (and (file-directory-p dirname) (directory-files dirname))))
2670 (loop for f in files
2671 when (and (not (string-match "^\\.\\.?$" f)) (string-match regexp f))
2672 collect (list nil (match-string 1 f)))))
2674 ;;;###tramp-autoload
2675 (defun tramp-parse-shostkeys (dirname)
2676 "Return a list of (user host) tuples allowed to access.
2677 User is always nil."
2678 (tramp-parse-shostkeys-sknownhosts
2679 dirname (concat "^key_[0-9]+_\\(" tramp-host-regexp "\\)\\.pub$")))
2681 ;;;###tramp-autoload
2682 (defun tramp-parse-sknownhosts (dirname)
2683 "Return a list of (user host) tuples allowed to access.
2684 User is always nil."
2685 (tramp-parse-shostkeys-sknownhosts
2686 dirname
2687 (concat "^\\(" tramp-host-regexp "\\)\\.ssh-\\(dss\\|rsa\\)\\.pub$")))
2689 ;;;###tramp-autoload
2690 (defun tramp-parse-hosts (filename)
2691 "Return a list of (user host) tuples allowed to access.
2692 User is always nil."
2693 (tramp-parse-file filename 'tramp-parse-hosts-group))
2695 (defun tramp-parse-hosts-group ()
2696 "Return a (user host) tuple allowed to access.
2697 User is always nil."
2698 (tramp-parse-group
2699 (concat "^\\(" tramp-ipv6-regexp "\\|" tramp-host-regexp "\\)") 1 " \t"))
2701 ;;;###tramp-autoload
2702 (defun tramp-parse-passwd (filename)
2703 "Return a list of (user host) tuples allowed to access.
2704 Host is always \"localhost\"."
2705 (with-tramp-connection-property nil "parse-passwd"
2706 (if (executable-find "getent")
2707 (with-temp-buffer
2708 (when (zerop (tramp-call-process nil "getent" nil t nil "passwd"))
2709 (goto-char (point-min))
2710 (loop while (not (eobp)) collect
2711 (tramp-parse-etc-group-group))))
2712 (tramp-parse-file filename 'tramp-parse-passwd-group))))
2714 (defun tramp-parse-passwd-group ()
2715 "Return a (user host) tuple allowed to access.
2716 Host is always \"localhost\"."
2717 (let ((result)
2718 (regexp (concat "^\\(" tramp-user-regexp "\\):")))
2719 (when (re-search-forward regexp (point-at-eol) t)
2720 (setq result (list (match-string 1) "localhost")))
2721 (forward-line 1)
2722 result))
2724 ;;;###tramp-autoload
2725 (defun tramp-parse-etc-group (filename)
2726 "Return a list of (group host) tuples allowed to access.
2727 Host is always \"localhost\"."
2728 (with-tramp-connection-property nil "parse-group"
2729 (if (executable-find "getent")
2730 (with-temp-buffer
2731 (when (zerop (tramp-call-process nil "getent" nil t nil "group"))
2732 (goto-char (point-min))
2733 (loop while (not (eobp)) collect
2734 (tramp-parse-etc-group-group))))
2735 (tramp-parse-file filename 'tramp-parse-etc-group-group))))
2737 (defun tramp-parse-etc-group-group ()
2738 "Return a (group host) tuple allowed to access.
2739 Host is always \"localhost\"."
2740 (let ((result)
2741 (split (split-string (buffer-substring (point) (point-at-eol)) ":")))
2742 (when (member (user-login-name) (split-string (nth 3 split) "," 'omit))
2743 (setq result (list (nth 0 split) "localhost")))
2744 (forward-line 1)
2745 result))
2747 ;;;###tramp-autoload
2748 (defun tramp-parse-netrc (filename)
2749 "Return a list of (user host) tuples allowed to access.
2750 User may be nil."
2751 (tramp-parse-file filename 'tramp-parse-netrc-group))
2753 (defun tramp-parse-netrc-group ()
2754 "Return a (user host) tuple allowed to access.
2755 User may be nil."
2756 (let ((result)
2757 (regexp
2758 (concat
2759 "^[ \t]*machine[ \t]+" "\\(" tramp-host-regexp "\\)"
2760 "\\([ \t]+login[ \t]+" "\\(" tramp-user-regexp "\\)" "\\)?")))
2761 (when (re-search-forward regexp (point-at-eol) t)
2762 (setq result (list (match-string 3) (match-string 1))))
2763 (forward-line 1)
2764 result))
2766 ;;;###tramp-autoload
2767 (defun tramp-parse-putty (registry-or-dirname)
2768 "Return a list of (user host) tuples allowed to access.
2769 User is always nil."
2770 (if (memq system-type '(windows-nt))
2771 (with-tramp-connection-property nil "parse-putty"
2772 (with-temp-buffer
2773 (when (zerop (tramp-call-process
2774 nil "reg" nil t nil "query" registry-or-dirname))
2775 (goto-char (point-min))
2776 (loop while (not (eobp)) collect
2777 (tramp-parse-putty-group registry-or-dirname)))))
2778 ;; UNIX case.
2779 (tramp-parse-shostkeys-sknownhosts
2780 registry-or-dirname (concat "^\\(" tramp-host-regexp "\\)$"))))
2782 (defun tramp-parse-putty-group (registry)
2783 "Return a (user host) tuple allowed to access.
2784 User is always nil."
2785 (let ((result)
2786 (regexp (concat (regexp-quote registry) "\\\\\\(.+\\)")))
2787 (when (re-search-forward regexp (point-at-eol) t)
2788 (setq result (list nil (match-string 1))))
2789 (forward-line 1)
2790 result))
2792 ;;; Common file name handler functions for different backends:
2794 (defvar tramp-handle-file-local-copy-hook nil
2795 "Normal hook to be run at the end of `tramp-*-handle-file-local-copy'.")
2797 (defvar tramp-handle-write-region-hook nil
2798 "Normal hook to be run at the end of `tramp-*-handle-write-region'.")
2800 (defun tramp-handle-directory-file-name (directory)
2801 "Like `directory-file-name' for Tramp files."
2802 ;; If localname component of filename is "/", leave it unchanged.
2803 ;; Otherwise, remove any trailing slash from localname component.
2804 ;; Method, host, etc, are unchanged. Does it make sense to try
2805 ;; to avoid parsing the filename?
2806 (with-parsed-tramp-file-name directory nil
2807 (if (and (not (zerop (length localname)))
2808 (eq (aref localname (1- (length localname))) ?/)
2809 (not (string= localname "/")))
2810 (substring directory 0 -1)
2811 directory)))
2813 (defun tramp-handle-directory-files (directory &optional full match nosort)
2814 "Like `directory-files' for Tramp files."
2815 (when (file-directory-p directory)
2816 (setq directory (file-name-as-directory (expand-file-name directory)))
2817 (let ((temp (nreverse (file-name-all-completions "" directory)))
2818 result item)
2820 (while temp
2821 (setq item (directory-file-name (pop temp)))
2822 (when (or (null match) (string-match match item))
2823 (push (if full (concat directory item) item)
2824 result)))
2825 (if nosort result (sort result 'string<)))))
2827 (defun tramp-handle-directory-files-and-attributes
2828 (directory &optional full match nosort id-format)
2829 "Like `directory-files-and-attributes' for Tramp files."
2830 (mapcar
2831 (lambda (x)
2832 (cons x (file-attributes
2833 (if full x (expand-file-name x directory)) id-format)))
2834 (directory-files directory full match nosort)))
2836 (defun tramp-handle-dired-uncache (dir)
2837 "Like `dired-uncache' for Tramp files."
2838 (with-parsed-tramp-file-name
2839 (if (file-directory-p dir) dir (file-name-directory dir)) nil
2840 (tramp-flush-directory-property v localname)))
2842 (defun tramp-handle-file-accessible-directory-p (filename)
2843 "Like `file-accessible-directory-p' for Tramp files."
2844 (and (file-directory-p filename)
2845 (file-readable-p filename)))
2847 (defun tramp-handle-file-equal-p (filename1 filename2)
2848 "Like `file-equalp-p' for Tramp files."
2849 ;; Native `file-equalp-p' calls `file-truename', which requires a
2850 ;; remote connection. This can be avoided, if FILENAME1 and
2851 ;; FILENAME2 are not located on the same remote host.
2852 (when (string-equal
2853 (file-remote-p (expand-file-name filename1))
2854 (file-remote-p (expand-file-name filename2)))
2855 (tramp-run-real-handler 'file-equal-p (list filename1 filename2))))
2857 (defun tramp-handle-file-exists-p (filename)
2858 "Like `file-exists-p' for Tramp files."
2859 (not (null (file-attributes filename))))
2861 (defun tramp-handle-file-in-directory-p (filename directory)
2862 "Like `file-in-directory-p' for Tramp files."
2863 ;; Native `file-in-directory-p' calls `file-truename', which
2864 ;; requires a remote connection. This can be avoided, if FILENAME
2865 ;; and DIRECTORY are not located on the same remote host.
2866 (when (string-equal
2867 (file-remote-p (expand-file-name filename))
2868 (file-remote-p (expand-file-name directory)))
2869 (tramp-run-real-handler 'file-in-directory-p (list filename directory))))
2871 (defun tramp-handle-file-modes (filename)
2872 "Like `file-modes' for Tramp files."
2873 (let ((truename (or (file-truename filename) filename)))
2874 (when (file-exists-p truename)
2875 (tramp-mode-string-to-int
2876 (tramp-compat-file-attribute-modes (file-attributes truename))))))
2878 ;; Localname manipulation functions that grok Tramp localnames...
2879 (defun tramp-handle-file-name-as-directory (file)
2880 "Like `file-name-as-directory' but aware of Tramp files."
2881 ;; `file-name-as-directory' would be sufficient except localname is
2882 ;; the empty string.
2883 (let ((v (tramp-dissect-file-name file t)))
2884 ;; Run the command on the localname portion only unless we are in
2885 ;; completion mode.
2886 (tramp-make-tramp-file-name
2887 (tramp-file-name-method v)
2888 (tramp-file-name-user v)
2889 (tramp-file-name-host v)
2890 (if (and (tramp-completion-mode-p)
2891 (zerop (length (tramp-file-name-localname v))))
2893 (tramp-run-real-handler
2894 'file-name-as-directory (list (or (tramp-file-name-localname v) ""))))
2895 (tramp-file-name-hop v))))
2897 (defun tramp-handle-file-name-case-insensitive-p (filename)
2898 "Like `file-name-case-insensitive-p' for Tramp files."
2899 ;; We make it a connection property, assuming that all file systems
2900 ;; on the remote host behave similar. This might be wrong for
2901 ;; mounted NFS directories or SMB/AFP shares; such more granular
2902 ;; tests will be added in case they are needed.
2903 (setq filename (expand-file-name filename))
2904 (with-parsed-tramp-file-name filename nil
2905 (or ;; Maybe there is a default value.
2906 (tramp-get-method-parameter v 'tramp-case-insensitive)
2908 ;; There isn't. So we must check.
2909 (with-tramp-connection-property v "case-insensitive"
2910 ;; The idea is to compare a file with lower case letters with
2911 ;; the same file with upper case letters.
2912 (let ((candidate (directory-file-name filename))
2913 tmpfile)
2914 ;; Check, whether we find an existing file with lower case
2915 ;; letters. This avoids us to create a temporary file.
2916 (while (and (string-match "[a-z]" (file-remote-p candidate 'localname))
2917 (not (file-exists-p candidate)))
2918 (setq candidate
2919 (directory-file-name (file-name-directory candidate))))
2920 ;; Nothing found, so we must use a temporary file for
2921 ;; comparision. `make-nearby-temp-file' is added to Emacs
2922 ;; 26+ like `file-name-case-insensitive-p', so there is no
2923 ;; compatibility problem calling it.
2924 (unless (string-match "[a-z]" (file-remote-p candidate 'localname))
2925 (setq tmpfile
2926 (let ((default-directory (file-name-directory filename)))
2927 (tramp-compat-funcall 'make-nearby-temp-file "tramp."))
2928 candidate tmpfile))
2929 ;; Check for the existence of the same file with upper case letters.
2930 (unwind-protect
2931 (file-exists-p
2932 (concat
2933 (file-remote-p candidate)
2934 (upcase (file-remote-p candidate 'localname))))
2935 ;; Cleanup.
2936 (when tmpfile (delete-file tmpfile))))))))
2938 (defun tramp-handle-file-name-completion
2939 (filename directory &optional predicate)
2940 "Like `file-name-completion' for Tramp files."
2941 (unless (tramp-tramp-file-p directory)
2942 (error
2943 "tramp-handle-file-name-completion invoked on non-tramp directory `%s'"
2944 directory))
2945 (let (hits-ignored-extensions)
2947 (try-completion
2948 filename (file-name-all-completions filename directory)
2949 (lambda (x)
2950 (when (funcall (or predicate 'identity) (expand-file-name x directory))
2951 (not
2952 (and
2953 completion-ignored-extensions
2954 (string-match
2955 (concat (regexp-opt completion-ignored-extensions 'paren) "$") x)
2956 ;; We remember the hit.
2957 (push x hits-ignored-extensions))))))
2958 ;; No match. So we try again for ignored files.
2959 (try-completion filename hits-ignored-extensions))))
2961 (defun tramp-handle-file-name-directory (file)
2962 "Like `file-name-directory' but aware of Tramp files."
2963 ;; Everything except the last filename thing is the directory. We
2964 ;; cannot apply `with-parsed-tramp-file-name', because this expands
2965 ;; the remote file name parts. This is a problem when we are in
2966 ;; file name completion.
2967 (let ((v (tramp-dissect-file-name file t)))
2968 ;; Run the command on the localname portion only.
2969 (tramp-make-tramp-file-name
2970 (tramp-file-name-method v)
2971 (tramp-file-name-user v)
2972 (tramp-file-name-host v)
2973 (tramp-run-real-handler
2974 'file-name-directory (list (or (tramp-file-name-localname v) "")))
2975 (tramp-file-name-hop v))))
2977 (defun tramp-handle-file-name-nondirectory (file)
2978 "Like `file-name-nondirectory' but aware of Tramp files."
2979 (with-parsed-tramp-file-name file nil
2980 (tramp-run-real-handler 'file-name-nondirectory (list localname))))
2982 (defun tramp-handle-file-newer-than-file-p (file1 file2)
2983 "Like `file-newer-than-file-p' for Tramp files."
2984 (cond
2985 ((not (file-exists-p file1)) nil)
2986 ((not (file-exists-p file2)) t)
2987 (t (time-less-p (tramp-compat-file-attribute-modification-time
2988 (file-attributes file2))
2989 (tramp-compat-file-attribute-modification-time
2990 (file-attributes file1))))))
2992 (defun tramp-handle-file-regular-p (filename)
2993 "Like `file-regular-p' for Tramp files."
2994 (and (file-exists-p filename)
2995 (eq ?-
2996 (aref (tramp-compat-file-attribute-modes (file-attributes filename))
2997 0))))
2999 (defun tramp-handle-file-remote-p (filename &optional identification connected)
3000 "Like `file-remote-p' for Tramp files."
3001 ;; We do not want traces in the debug buffer.
3002 (let ((tramp-verbose (min tramp-verbose 3)))
3003 (when (tramp-tramp-file-p filename)
3004 (let* ((v (tramp-dissect-file-name filename))
3005 (p (tramp-get-connection-process v))
3006 (c (and (tramp-compat-process-live-p p)
3007 (tramp-get-connection-property p "connected" nil))))
3008 ;; We expand the file name only, if there is already a connection.
3009 (with-parsed-tramp-file-name
3010 (if c (expand-file-name filename) filename) nil
3011 (and (or (not connected) c)
3012 (cond
3013 ((eq identification 'method) method)
3014 ((eq identification 'user) user)
3015 ((eq identification 'host) host)
3016 ((eq identification 'localname) localname)
3017 ((eq identification 'hop) hop)
3018 (t (tramp-make-tramp-file-name method user host "" hop)))))))))
3020 (defun tramp-handle-file-symlink-p (filename)
3021 "Like `file-symlink-p' for Tramp files."
3022 (with-parsed-tramp-file-name filename nil
3023 (let ((x (tramp-compat-file-attribute-type (file-attributes filename))))
3024 (when (stringp x)
3025 (if (file-name-absolute-p x)
3026 (tramp-make-tramp-file-name method user host x)
3027 x)))))
3029 (defun tramp-handle-find-backup-file-name (filename)
3030 "Like `find-backup-file-name' for Tramp files."
3031 (with-parsed-tramp-file-name filename nil
3032 (let ((backup-directory-alist
3033 (if tramp-backup-directory-alist
3034 (mapcar
3035 (lambda (x)
3036 (cons
3037 (car x)
3038 (if (and (stringp (cdr x))
3039 (file-name-absolute-p (cdr x))
3040 (not (tramp-file-name-p (cdr x))))
3041 (tramp-make-tramp-file-name method user host (cdr x))
3042 (cdr x))))
3043 tramp-backup-directory-alist)
3044 backup-directory-alist)))
3045 (tramp-run-real-handler 'find-backup-file-name (list filename)))))
3047 (defun tramp-handle-insert-directory
3048 (filename switches &optional wildcard full-directory-p)
3049 "Like `insert-directory' for Tramp files."
3050 (unless switches (setq switches ""))
3051 ;; Mark trailing "/".
3052 (when (and (zerop (length (file-name-nondirectory filename)))
3053 (not full-directory-p))
3054 (setq switches (concat switches "F")))
3055 (with-parsed-tramp-file-name (expand-file-name filename) nil
3056 (with-tramp-progress-reporter v 0 (format "Opening directory %s" filename)
3057 (require 'ls-lisp)
3058 (let (ls-lisp-use-insert-directory-program start)
3059 (tramp-run-real-handler
3060 'insert-directory
3061 (list filename switches wildcard full-directory-p))
3062 ;; `ls-lisp' always returns full listings. We must remove
3063 ;; superfluous parts.
3064 (unless (string-match "l" switches)
3065 (save-excursion
3066 (goto-char (point-min))
3067 (while (setq start
3068 (text-property-not-all
3069 (point) (point-at-eol) 'dired-filename t))
3070 (delete-region
3071 start
3072 (or (text-property-any start (point-at-eol) 'dired-filename t)
3073 (point-at-eol)))
3074 (if (= (point-at-bol) (point-at-eol))
3075 ;; Empty line.
3076 (delete-region (point) (progn (forward-line) (point)))
3077 (forward-line)))))))))
3079 (defun tramp-handle-insert-file-contents
3080 (filename &optional visit beg end replace)
3081 "Like `insert-file-contents' for Tramp files."
3082 (barf-if-buffer-read-only)
3083 (setq filename (expand-file-name filename))
3084 (let (result local-copy remote-copy)
3085 (with-parsed-tramp-file-name filename nil
3086 (unwind-protect
3087 (if (not (file-exists-p filename))
3088 (tramp-error
3089 v tramp-file-missing
3090 "File `%s' not found on remote host" filename)
3092 (with-tramp-progress-reporter
3093 v 3 (format-message "Inserting `%s'" filename)
3094 (condition-case err
3095 (if (and (tramp-local-host-p v)
3096 (let (file-name-handler-alist)
3097 (file-readable-p localname)))
3098 ;; Short track: if we are on the local host, we can
3099 ;; run directly.
3100 (setq result
3101 (tramp-run-real-handler
3102 'insert-file-contents
3103 (list localname visit beg end replace)))
3105 ;; When we shall insert only a part of the file, we
3106 ;; copy this part. This works only for the shell file
3107 ;; name handlers.
3108 (when (and (or beg end)
3109 (tramp-get-method-parameter
3110 v 'tramp-login-program))
3111 (setq remote-copy (tramp-make-tramp-temp-file v))
3112 ;; This is defined in tramp-sh.el. Let's assume
3113 ;; this is loaded already.
3114 (tramp-compat-funcall
3115 'tramp-send-command
3117 (cond
3118 ((and beg end)
3119 (format "dd bs=1 skip=%d if=%s count=%d of=%s"
3120 beg (tramp-shell-quote-argument localname)
3121 (- end beg) remote-copy))
3122 (beg
3123 (format "dd bs=1 skip=%d if=%s of=%s"
3124 beg (tramp-shell-quote-argument localname)
3125 remote-copy))
3126 (end
3127 (format "dd bs=1 count=%d if=%s of=%s"
3128 end (tramp-shell-quote-argument localname)
3129 remote-copy))))
3130 (setq tramp-temp-buffer-file-name nil beg nil end nil))
3132 ;; `insert-file-contents-literally' takes care to
3133 ;; avoid calling jka-compr.el and epa.el. By
3134 ;; let-binding `inhibit-file-name-operation', we
3135 ;; propagate that care to the `file-local-copy'
3136 ;; operation.
3137 (setq local-copy
3138 (let ((inhibit-file-name-operation
3139 (when (eq inhibit-file-name-operation
3140 'insert-file-contents)
3141 'file-local-copy)))
3142 (cond
3143 ((stringp remote-copy)
3144 (file-local-copy
3145 (tramp-make-tramp-file-name
3146 method user host remote-copy)))
3147 ((stringp tramp-temp-buffer-file-name)
3148 (copy-file
3149 filename tramp-temp-buffer-file-name 'ok)
3150 tramp-temp-buffer-file-name)
3151 (t (file-local-copy filename)))))
3153 ;; When the file is not readable for the owner, it
3154 ;; cannot be inserted, even if it is readable for the
3155 ;; group or for everybody.
3156 (set-file-modes local-copy (string-to-number "0600" 8))
3158 (when (and (null remote-copy)
3159 (tramp-get-method-parameter
3160 v 'tramp-copy-keep-tmpfile))
3161 ;; We keep the local file for performance reasons,
3162 ;; useful for "rsync".
3163 (setq tramp-temp-buffer-file-name local-copy))
3165 ;; We must ensure that `file-coding-system-alist'
3166 ;; matches `local-copy'.
3167 (let ((file-coding-system-alist
3168 (tramp-find-file-name-coding-system-alist
3169 filename local-copy)))
3170 (setq result
3171 (insert-file-contents
3172 local-copy visit beg end replace))))
3173 (error
3174 (add-hook 'find-file-not-found-functions
3175 `(lambda () (signal ',(car err) ',(cdr err)))
3176 nil t)
3177 (signal (car err) (cdr err))))))
3179 ;; Save exit.
3180 (progn
3181 (when visit
3182 (setq buffer-file-name filename)
3183 (setq buffer-read-only (not (file-writable-p filename)))
3184 (set-visited-file-modtime)
3185 (set-buffer-modified-p nil))
3186 (when (and (stringp local-copy)
3187 (or remote-copy (null tramp-temp-buffer-file-name)))
3188 (delete-file local-copy))
3189 (when (stringp remote-copy)
3190 (delete-file
3191 (tramp-make-tramp-file-name method user host remote-copy)))))
3193 ;; Result.
3194 (list (expand-file-name filename)
3195 (cadr result)))))
3197 (defun tramp-handle-load (file &optional noerror nomessage nosuffix must-suffix)
3198 "Like `load' for Tramp files."
3199 (with-parsed-tramp-file-name (expand-file-name file) nil
3200 (unless nosuffix
3201 (cond ((file-exists-p (concat file ".elc"))
3202 (setq file (concat file ".elc")))
3203 ((file-exists-p (concat file ".el"))
3204 (setq file (concat file ".el")))))
3205 (when must-suffix
3206 ;; The first condition is always true for absolute file names.
3207 ;; Included for safety's sake.
3208 (unless (or (file-name-directory file)
3209 (string-match "\\.elc?\\'" file))
3210 (tramp-error
3211 v 'file-error
3212 "File `%s' does not include a `.el' or `.elc' suffix" file)))
3213 (unless noerror
3214 (when (not (file-exists-p file))
3215 (tramp-error
3216 v tramp-file-missing "Cannot load nonexistent file `%s'" file)))
3217 (if (not (file-exists-p file))
3219 (let ((tramp-message-show-message (not nomessage)))
3220 (with-tramp-progress-reporter v 0 (format "Loading %s" file)
3221 (let ((local-copy (file-local-copy file)))
3222 (unwind-protect
3223 (load local-copy noerror t nosuffix must-suffix)
3224 (delete-file local-copy)))))
3225 t)))
3227 (defun tramp-handle-make-symbolic-link
3228 (filename linkname &optional _ok-if-already-exists)
3229 "Like `make-symbolic-link' for Tramp files."
3230 (with-parsed-tramp-file-name
3231 (if (tramp-tramp-file-p filename) filename linkname) nil
3232 (tramp-error v 'file-error "make-symbolic-link not supported")))
3234 (defun tramp-handle-shell-command
3235 (command &optional output-buffer error-buffer)
3236 "Like `shell-command' for Tramp files."
3237 (let* ((asynchronous (string-match "[ \t]*&[ \t]*\\'" command))
3238 ;; We cannot use `shell-file-name' and `shell-command-switch',
3239 ;; they are variables of the local host.
3240 (args (append
3241 (cons
3242 (tramp-get-method-parameter
3243 (tramp-dissect-file-name default-directory)
3244 'tramp-remote-shell)
3245 (tramp-get-method-parameter
3246 (tramp-dissect-file-name default-directory)
3247 'tramp-remote-shell-args))
3248 (list (substring command 0 asynchronous))))
3249 current-buffer-p
3250 (output-buffer
3251 (cond
3252 ((bufferp output-buffer) output-buffer)
3253 ((stringp output-buffer) (get-buffer-create output-buffer))
3254 (output-buffer
3255 (setq current-buffer-p t)
3256 (current-buffer))
3257 (t (get-buffer-create
3258 (if asynchronous
3259 "*Async Shell Command*"
3260 "*Shell Command Output*")))))
3261 (error-buffer
3262 (cond
3263 ((bufferp error-buffer) error-buffer)
3264 ((stringp error-buffer) (get-buffer-create error-buffer))))
3265 (buffer
3266 (if (and (not asynchronous) error-buffer)
3267 (with-parsed-tramp-file-name default-directory nil
3268 (list output-buffer (tramp-make-tramp-temp-file v)))
3269 output-buffer))
3270 (p (get-buffer-process output-buffer)))
3272 ;; Check whether there is another process running. Tramp does not
3273 ;; support 2 (asynchronous) processes in parallel.
3274 (when p
3275 (if (yes-or-no-p "A command is running. Kill it? ")
3276 (ignore-errors (kill-process p))
3277 (tramp-compat-user-error p "Shell command in progress")))
3279 (if current-buffer-p
3280 (progn
3281 (barf-if-buffer-read-only)
3282 (push-mark nil t))
3283 (with-current-buffer output-buffer
3284 (setq buffer-read-only nil)
3285 (erase-buffer)))
3287 (if (and (not current-buffer-p) (integerp asynchronous))
3288 (prog1
3289 ;; Run the process.
3290 (setq p (apply 'start-file-process "*Async Shell*" buffer args))
3291 ;; Display output.
3292 (with-current-buffer output-buffer
3293 (display-buffer output-buffer '(nil (allow-no-window . t)))
3294 (setq mode-line-process '(":%s"))
3295 (shell-mode)
3296 (set-process-sentinel p 'shell-command-sentinel)
3297 (set-process-filter p 'comint-output-filter)))
3299 (prog1
3300 ;; Run the process.
3301 (apply 'process-file (car args) nil buffer nil (cdr args))
3302 ;; Insert error messages if they were separated.
3303 (when (listp buffer)
3304 (with-current-buffer error-buffer
3305 (insert-file-contents (cadr buffer)))
3306 (delete-file (cadr buffer)))
3307 (if current-buffer-p
3308 ;; This is like exchange-point-and-mark, but doesn't
3309 ;; activate the mark. It is cleaner to avoid activation,
3310 ;; even though the command loop would deactivate the mark
3311 ;; because we inserted text.
3312 (goto-char (prog1 (mark t)
3313 (set-marker (mark-marker) (point)
3314 (current-buffer))))
3315 ;; There's some output, display it.
3316 (when (with-current-buffer output-buffer (> (point-max) (point-min)))
3317 (display-message-or-buffer output-buffer)))))))
3319 (defun tramp-handle-substitute-in-file-name (filename)
3320 "Like `substitute-in-file-name' for Tramp files.
3321 \"//\" and \"/~\" substitute only in the local filename part."
3322 ;; First, we must replace environment variables.
3323 (setq filename (tramp-replace-environment-variables filename))
3324 (with-parsed-tramp-file-name filename nil
3325 ;; Ignore in LOCALNAME everything before "//" or "/~".
3326 (when (and (stringp localname) (string-match ".+?/\\(/\\|~\\)" localname))
3327 (setq filename
3328 (concat (file-remote-p filename)
3329 (replace-match "\\1" nil nil localname)))
3330 ;; "/m:h:~" does not work for completion. We use "/m:h:~/".
3331 (when (string-match "~$" filename)
3332 (setq filename (concat filename "/"))))
3333 ;; We do not want to replace environment variables, again.
3334 (let (process-environment)
3335 (tramp-run-real-handler 'substitute-in-file-name (list filename)))))
3337 (defun tramp-handle-set-visited-file-modtime (&optional time-list)
3338 "Like `set-visited-file-modtime' for Tramp files."
3339 (unless (buffer-file-name)
3340 (error "Can't set-visited-file-modtime: buffer `%s' not visiting a file"
3341 (buffer-name)))
3342 (unless time-list
3343 (let ((remote-file-name-inhibit-cache t))
3344 ;; '(-1 65535) means file doesn't exists yet.
3345 (setq time-list
3346 (or (tramp-compat-file-attribute-modification-time
3347 (file-attributes (buffer-file-name)))
3348 '(-1 65535)))))
3349 ;; We use '(0 0) as a don't-know value.
3350 (unless (equal time-list '(0 0))
3351 (tramp-run-real-handler 'set-visited-file-modtime (list time-list))))
3353 (defun tramp-handle-verify-visited-file-modtime (&optional buf)
3354 "Like `verify-visited-file-modtime' for Tramp files.
3355 At the time `verify-visited-file-modtime' calls this function, we
3356 already know that the buffer is visiting a file and that
3357 `visited-file-modtime' does not return 0. Do not call this
3358 function directly, unless those two cases are already taken care
3359 of."
3360 (with-current-buffer (or buf (current-buffer))
3361 (let ((f (buffer-file-name)))
3362 ;; There is no file visiting the buffer, or the buffer has no
3363 ;; recorded last modification time, or there is no established
3364 ;; connection.
3365 (if (or (not f)
3366 (eq (visited-file-modtime) 0)
3367 (not (file-remote-p f nil 'connected)))
3369 (with-parsed-tramp-file-name f nil
3370 (let* ((remote-file-name-inhibit-cache t)
3371 (attr (file-attributes f))
3372 (modtime (tramp-compat-file-attribute-modification-time attr))
3373 (mt (visited-file-modtime)))
3375 (cond
3376 ;; File exists, and has a known modtime.
3377 ((and attr (not (equal modtime '(0 0))))
3378 (< (abs (tramp-time-diff
3379 modtime
3380 ;; For compatibility, deal with both the old
3381 ;; (HIGH . LOW) and the new (HIGH LOW) return
3382 ;; values of `visited-file-modtime'.
3383 (if (atom (cdr mt))
3384 (list (car mt) (cdr mt))
3385 mt)))
3387 ;; Modtime has the don't know value.
3388 (attr t)
3389 ;; If file does not exist, say it is not modified if and
3390 ;; only if that agrees with the buffer's record.
3391 (t (equal mt '(-1 65535))))))))))
3393 (defun tramp-handle-file-notify-add-watch (filename _flags _callback)
3394 "Like `file-notify-add-watch' for Tramp files."
3395 ;; This is the default handler. tramp-gvfs.el and tramp-sh.el have
3396 ;; their own one.
3397 (setq filename (expand-file-name filename))
3398 (with-parsed-tramp-file-name filename nil
3399 (tramp-error
3400 v 'file-notify-error "File notification not supported for `%s'" filename)))
3402 (defun tramp-handle-file-notify-rm-watch (proc)
3403 "Like `file-notify-rm-watch' for Tramp files."
3404 ;; The descriptor must be a process object.
3405 (unless (processp proc)
3406 (tramp-error proc 'file-notify-error "Not a valid descriptor %S" proc))
3407 (tramp-message proc 6 "Kill %S" proc)
3408 (delete-process proc))
3410 (defun tramp-handle-file-notify-valid-p (proc)
3411 "Like `file-notify-valid-p' for Tramp files."
3412 (and (tramp-compat-process-live-p proc)
3413 ;; Sometimes, the process is still in status `run' when the
3414 ;; file or directory to be watched is deleted already.
3415 (with-current-buffer (process-buffer proc)
3416 (file-exists-p
3417 (concat (file-remote-p default-directory)
3418 (process-get proc 'watch-name))))))
3420 ;;; Functions for establishing connection:
3422 ;; The following functions are actions to be taken when seeing certain
3423 ;; prompts from the remote host. See the variable
3424 ;; `tramp-actions-before-shell' for usage of these functions.
3426 (defun tramp-action-login (_proc vec)
3427 "Send the login name."
3428 (when (not (stringp tramp-current-user))
3429 (setq tramp-current-user
3430 (with-tramp-connection-property vec "login-as"
3431 (save-window-excursion
3432 (let ((enable-recursive-minibuffers t))
3433 (pop-to-buffer (tramp-get-connection-buffer vec))
3434 (read-string (match-string 0)))))))
3435 (with-current-buffer (tramp-get-connection-buffer vec)
3436 (tramp-message vec 6 "\n%s" (buffer-string)))
3437 (tramp-message vec 3 "Sending login name `%s'" tramp-current-user)
3438 (tramp-send-string vec (concat tramp-current-user tramp-local-end-of-line)))
3440 (defun tramp-action-password (proc vec)
3441 "Query the user for a password."
3442 (with-current-buffer (process-buffer proc)
3443 (let ((enable-recursive-minibuffers t)
3444 (case-fold-search t))
3445 ;; Let's check whether a wrong password has been sent already.
3446 ;; Sometimes, the process returns a new password request
3447 ;; immediately after rejecting the previous (wrong) one.
3448 (unless (tramp-get-connection-property vec "first-password-request" nil)
3449 (tramp-clear-passwd vec))
3450 (goto-char (point-min))
3451 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
3452 (tramp-message vec 3 "Sending %s" (match-string 1))
3453 ;; We don't call `tramp-send-string' in order to hide the
3454 ;; password from the debug buffer.
3455 (process-send-string
3456 proc (concat (tramp-read-passwd proc) tramp-local-end-of-line))
3457 ;; Hide password prompt.
3458 (narrow-to-region (point-max) (point-max)))))
3460 (defun tramp-action-succeed (_proc _vec)
3461 "Signal success in finding shell prompt."
3462 (throw 'tramp-action 'ok))
3464 (defun tramp-action-permission-denied (proc _vec)
3465 "Signal permission denied."
3466 (kill-process proc)
3467 (throw 'tramp-action 'permission-denied))
3469 (defun tramp-action-yesno (proc vec)
3470 "Ask the user for confirmation using `yes-or-no-p'.
3471 Send \"yes\" to remote process on confirmation, abort otherwise.
3472 See also `tramp-action-yn'."
3473 (save-window-excursion
3474 (let ((enable-recursive-minibuffers t))
3475 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3476 (unless (yes-or-no-p (match-string 0))
3477 (kill-process proc)
3478 (throw 'tramp-action 'permission-denied))
3479 (with-current-buffer (tramp-get-connection-buffer vec)
3480 (tramp-message vec 6 "\n%s" (buffer-string)))
3481 (tramp-send-string vec (concat "yes" tramp-local-end-of-line)))))
3483 (defun tramp-action-yn (proc vec)
3484 "Ask the user for confirmation using `y-or-n-p'.
3485 Send \"y\" to remote process on confirmation, abort otherwise.
3486 See also `tramp-action-yesno'."
3487 (save-window-excursion
3488 (let ((enable-recursive-minibuffers t))
3489 (save-match-data (pop-to-buffer (tramp-get-connection-buffer vec)))
3490 (unless (y-or-n-p (match-string 0))
3491 (kill-process proc)
3492 (throw 'tramp-action 'permission-denied))
3493 (with-current-buffer (tramp-get-connection-buffer vec)
3494 (tramp-message vec 6 "\n%s" (buffer-string)))
3495 (tramp-send-string vec (concat "y" tramp-local-end-of-line)))))
3497 (defun tramp-action-terminal (_proc vec)
3498 "Tell the remote host which terminal type to use.
3499 The terminal type can be configured with `tramp-terminal-type'."
3500 (tramp-message vec 5 "Setting `%s' as terminal type." tramp-terminal-type)
3501 (with-current-buffer (tramp-get-connection-buffer vec)
3502 (tramp-message vec 6 "\n%s" (buffer-string)))
3503 (tramp-send-string vec (concat tramp-terminal-type tramp-local-end-of-line)))
3505 (defun tramp-action-process-alive (proc _vec)
3506 "Check, whether a process has finished."
3507 (unless (tramp-compat-process-live-p proc)
3508 (throw 'tramp-action 'process-died)))
3510 (defun tramp-action-out-of-band (proc vec)
3511 "Check, whether an out-of-band copy has finished."
3512 ;; There might be pending output for the exit status.
3513 (tramp-accept-process-output proc 0.1)
3514 (cond ((and (not (tramp-compat-process-live-p proc))
3515 (zerop (process-exit-status proc)))
3516 (tramp-message vec 3 "Process has finished.")
3517 (throw 'tramp-action 'ok))
3518 ((or (and (memq (process-status proc) '(stop exit))
3519 (not (zerop (process-exit-status proc))))
3520 (memq (process-status proc) '(signal)))
3521 ;; `scp' could have copied correctly, but set modes could have failed.
3522 ;; This can be ignored.
3523 (with-current-buffer (process-buffer proc)
3524 (goto-char (point-min))
3525 (if (re-search-forward tramp-operation-not-permitted-regexp nil t)
3526 (progn
3527 (tramp-message vec 5 "'set mode' error ignored.")
3528 (tramp-message vec 3 "Process has finished.")
3529 (throw 'tramp-action 'ok))
3530 (tramp-message vec 3 "Process has died.")
3531 (throw 'tramp-action 'out-of-band-failed))))
3532 (t nil)))
3534 ;;; Functions for processing the actions:
3536 (defun tramp-process-one-action (proc vec actions)
3537 "Wait for output from the shell and perform one action."
3538 (let ((case-fold-search t)
3539 found todo item pattern action)
3540 (while (not found)
3541 ;; Reread output once all actions have been performed.
3542 ;; Obviously, the output was not complete.
3543 (tramp-accept-process-output proc 1)
3544 (setq todo actions)
3545 (while todo
3546 (setq item (pop todo))
3547 (setq pattern (format "\\(%s\\)\\'" (symbol-value (nth 0 item))))
3548 (setq action (nth 1 item))
3549 (tramp-message
3550 vec 5 "Looking for regexp \"%s\" from remote shell" pattern)
3551 (when (tramp-check-for-regexp proc pattern)
3552 (tramp-message vec 5 "Call `%s'" (symbol-name action))
3553 (setq found (funcall action proc vec)))))
3554 found))
3556 (defun tramp-process-actions (proc vec pos actions &optional timeout)
3557 "Perform ACTIONS until success or TIMEOUT.
3558 PROC and VEC indicate the remote connection to be used. POS, if
3559 set, is the starting point of the region to be deleted in the
3560 connection buffer."
3561 ;; Enable `auth-source'. We must use tramp-current-* variables in
3562 ;; case we have several hops.
3563 (tramp-set-connection-property
3564 (tramp-dissect-file-name
3565 (tramp-make-tramp-file-name
3566 tramp-current-method tramp-current-user tramp-current-host ""))
3567 "first-password-request" t)
3568 (save-restriction
3569 (with-tramp-progress-reporter
3570 proc 3 "Waiting for prompts from remote shell"
3571 (let (exit)
3572 (if timeout
3573 (with-timeout (timeout (setq exit 'timeout))
3574 (while (not exit)
3575 (setq exit
3576 (catch 'tramp-action
3577 (tramp-process-one-action proc vec actions)))))
3578 (while (not exit)
3579 (setq exit
3580 (catch 'tramp-action
3581 (tramp-process-one-action proc vec actions)))))
3582 (with-current-buffer (tramp-get-connection-buffer vec)
3583 (widen)
3584 (tramp-message vec 6 "\n%s" (buffer-string)))
3585 (unless (eq exit 'ok)
3586 (tramp-clear-passwd vec)
3587 (delete-process proc)
3588 (tramp-error-with-buffer
3589 (tramp-get-connection-buffer vec) vec 'file-error
3590 (cond
3591 ((eq exit 'permission-denied) "Permission denied")
3592 ((eq exit 'out-of-band-failed)
3593 (format-message
3594 "Copy failed, see buffer `%s' for details"
3595 (tramp-get-connection-buffer vec)))
3596 ((eq exit 'process-died)
3597 (substitute-command-keys
3598 (concat
3599 "Tramp failed to connect. If this happens repeatedly, try\n"
3600 " `\\[tramp-cleanup-this-connection]'")))
3601 ((eq exit 'timeout)
3602 (format-message
3603 "Timeout reached, see buffer `%s' for details"
3604 (tramp-get-connection-buffer vec)))
3605 (t "Login failed")))))
3606 (when (numberp pos)
3607 (with-current-buffer (tramp-get-connection-buffer vec)
3608 (let (buffer-read-only) (delete-region pos (point))))))))
3610 ;;; Utility functions:
3612 (defun tramp-accept-process-output (&optional proc timeout timeout-msecs)
3613 "Like `accept-process-output' for Tramp processes.
3614 This is needed in order to hide `last-coding-system-used', which is set
3615 for process communication also."
3616 (with-current-buffer (process-buffer proc)
3617 ;; FIXME: If there is a gateway process, we need communication
3618 ;; between several processes. Too complicate to implement, so we
3619 ;; read output from all processes.
3620 (let ((p (if (tramp-get-connection-property proc "gateway" nil) nil proc))
3621 buffer-read-only last-coding-system-used)
3622 ;; Under Windows XP, accept-process-output doesn't return
3623 ;; sometimes. So we add an additional timeout.
3624 (with-timeout ((or timeout 1))
3625 (accept-process-output p timeout timeout-msecs (and proc t)))
3626 (tramp-message proc 10 "%s %s %s\n%s"
3627 proc (process-status proc) p (buffer-string)))))
3629 (defun tramp-check-for-regexp (proc regexp)
3630 "Check, whether REGEXP is contained in process buffer of PROC.
3631 Erase echoed commands if exists."
3632 (with-current-buffer (process-buffer proc)
3633 (goto-char (point-min))
3635 ;; Check whether we need to remove echo output.
3636 (when (and (tramp-get-connection-property proc "check-remote-echo" nil)
3637 (re-search-forward tramp-echoed-echo-mark-regexp nil t))
3638 (let ((begin (match-beginning 0)))
3639 (when (re-search-forward tramp-echoed-echo-mark-regexp nil t)
3640 ;; Discard echo from remote output.
3641 (tramp-set-connection-property proc "check-remote-echo" nil)
3642 (tramp-message proc 5 "echo-mark found")
3643 (forward-line 1)
3644 (delete-region begin (point))
3645 (goto-char (point-min)))))
3647 (when (or (not (tramp-get-connection-property proc "check-remote-echo" nil))
3648 ;; Sometimes, the echo string is suppressed on the remote side.
3649 (not (string-equal
3650 (substring-no-properties
3651 tramp-echo-mark-marker
3652 0 (min tramp-echo-mark-marker-length (1- (point-max))))
3653 (buffer-substring-no-properties
3654 (point-min)
3655 (min (+ (point-min) tramp-echo-mark-marker-length)
3656 (point-max))))))
3657 ;; No echo to be handled, now we can look for the regexp.
3658 ;; Sometimes, lines are much to long, and we run into a "Stack
3659 ;; overflow in regexp matcher". For example, //DIRED// lines of
3660 ;; directory listings with some thousand files. Therefore, we
3661 ;; look from the end.
3662 (goto-char (point-max))
3663 (ignore-errors (re-search-backward regexp nil t)))))
3665 (defun tramp-wait-for-regexp (proc timeout regexp)
3666 "Wait for a REGEXP to appear from process PROC within TIMEOUT seconds.
3667 Expects the output of PROC to be sent to the current buffer. Returns
3668 the string that matched, or nil. Waits indefinitely if TIMEOUT is
3669 nil."
3670 (with-current-buffer (process-buffer proc)
3671 (let ((found (tramp-check-for-regexp proc regexp)))
3672 (cond (timeout
3673 (with-timeout (timeout)
3674 (while (not found)
3675 (tramp-accept-process-output proc 1)
3676 (unless (tramp-compat-process-live-p proc)
3677 (tramp-error-with-buffer
3678 nil proc 'file-error "Process has died"))
3679 (setq found (tramp-check-for-regexp proc regexp)))))
3681 (while (not found)
3682 (tramp-accept-process-output proc 1)
3683 (unless (tramp-compat-process-live-p proc)
3684 (tramp-error-with-buffer
3685 nil proc 'file-error "Process has died"))
3686 (setq found (tramp-check-for-regexp proc regexp)))))
3687 (tramp-message proc 6 "\n%s" (buffer-string))
3688 (when (not found)
3689 (if timeout
3690 (tramp-error
3691 proc 'file-error "[[Regexp `%s' not found in %d secs]]"
3692 regexp timeout)
3693 (tramp-error proc 'file-error "[[Regexp `%s' not found]]" regexp)))
3694 found)))
3696 ;; It seems that Tru64 Unix does not like it if long strings are sent
3697 ;; to it in one go. (This happens when sending the Perl
3698 ;; `file-attributes' implementation, for instance.) Therefore, we
3699 ;; have this function which sends the string in chunks.
3700 (defun tramp-send-string (vec string)
3701 "Send the STRING via connection VEC.
3703 The STRING is expected to use Unix line-endings, but the lines sent to
3704 the remote host use line-endings as defined in the variable
3705 `tramp-rsh-end-of-line'. The communication buffer is erased before sending."
3706 (let* ((p (tramp-get-connection-process vec))
3707 (chunksize (tramp-get-connection-property p "chunksize" nil)))
3708 (unless p
3709 (tramp-error
3710 vec 'file-error "Can't send string to remote host -- not logged in"))
3711 (tramp-set-connection-property p "last-cmd-time" (current-time))
3712 (tramp-message vec 10 "%s" string)
3713 (with-current-buffer (tramp-get-connection-buffer vec)
3714 ;; Clean up the buffer. We cannot call `erase-buffer' because
3715 ;; narrowing might be in effect.
3716 (let (buffer-read-only) (delete-region (point-min) (point-max)))
3717 ;; Replace "\n" by `tramp-rsh-end-of-line'.
3718 (setq string
3719 (mapconcat
3720 'identity (split-string string "\n") tramp-rsh-end-of-line))
3721 (unless (or (string= string "")
3722 (string-equal (substring string -1) tramp-rsh-end-of-line))
3723 (setq string (concat string tramp-rsh-end-of-line)))
3724 ;; Send the string.
3725 (if (and chunksize (not (zerop chunksize)))
3726 (let ((pos 0)
3727 (end (length string)))
3728 (while (< pos end)
3729 (tramp-message
3730 vec 10 "Sending chunk from %s to %s"
3731 pos (min (+ pos chunksize) end))
3732 (process-send-string
3733 p (substring string pos (min (+ pos chunksize) end)))
3734 (setq pos (+ pos chunksize))))
3735 (process-send-string p string)))))
3737 (defun tramp-get-inode (vec)
3738 "Returns the virtual inode number.
3739 If it doesn't exist, generate a new one."
3740 (with-tramp-file-property vec (tramp-file-name-localname vec) "inode"
3741 (setq tramp-inodes (1+ tramp-inodes))))
3743 (defun tramp-get-device (vec)
3744 "Returns the virtual device number.
3745 If it doesn't exist, generate a new one."
3746 (with-tramp-connection-property (tramp-get-connection-process vec) "device"
3747 (cons -1 (setq tramp-devices (1+ tramp-devices)))))
3749 (defun tramp-equal-remote (file1 file2)
3750 "Check, whether the remote parts of FILE1 and FILE2 are identical.
3751 The check depends on method, user and host name of the files. If
3752 one of the components is missing, the default values are used.
3753 The local file name parts of FILE1 and FILE2 are not taken into
3754 account.
3756 Example:
3758 (tramp-equal-remote \"/ssh::/etc\" \"/<your host name>:/home\")
3760 would yield t. On the other hand, the following check results in nil:
3762 (tramp-equal-remote \"/sudo::/etc\" \"/su::/etc\")"
3763 (and (tramp-tramp-file-p file1)
3764 (tramp-tramp-file-p file2)
3765 (string-equal (file-remote-p file1) (file-remote-p file2))))
3767 ;;;###tramp-autoload
3768 (defun tramp-mode-string-to-int (mode-string)
3769 "Converts a ten-letter `drwxrwxrwx'-style mode string into mode bits."
3770 (let* (case-fold-search
3771 (mode-chars (string-to-vector mode-string))
3772 (owner-read (aref mode-chars 1))
3773 (owner-write (aref mode-chars 2))
3774 (owner-execute-or-setid (aref mode-chars 3))
3775 (group-read (aref mode-chars 4))
3776 (group-write (aref mode-chars 5))
3777 (group-execute-or-setid (aref mode-chars 6))
3778 (other-read (aref mode-chars 7))
3779 (other-write (aref mode-chars 8))
3780 (other-execute-or-sticky (aref mode-chars 9)))
3781 (save-match-data
3782 (logior
3783 (cond
3784 ((char-equal owner-read ?r) (string-to-number "00400" 8))
3785 ((char-equal owner-read ?-) 0)
3786 (t (error "Second char `%c' must be one of `r-'" owner-read)))
3787 (cond
3788 ((char-equal owner-write ?w) (string-to-number "00200" 8))
3789 ((char-equal owner-write ?-) 0)
3790 (t (error "Third char `%c' must be one of `w-'" owner-write)))
3791 (cond
3792 ((char-equal owner-execute-or-setid ?x) (string-to-number "00100" 8))
3793 ((char-equal owner-execute-or-setid ?S) (string-to-number "04000" 8))
3794 ((char-equal owner-execute-or-setid ?s) (string-to-number "04100" 8))
3795 ((char-equal owner-execute-or-setid ?-) 0)
3796 (t (error "Fourth char `%c' must be one of `xsS-'"
3797 owner-execute-or-setid)))
3798 (cond
3799 ((char-equal group-read ?r) (string-to-number "00040" 8))
3800 ((char-equal group-read ?-) 0)
3801 (t (error "Fifth char `%c' must be one of `r-'" group-read)))
3802 (cond
3803 ((char-equal group-write ?w) (string-to-number "00020" 8))
3804 ((char-equal group-write ?-) 0)
3805 (t (error "Sixth char `%c' must be one of `w-'" group-write)))
3806 (cond
3807 ((char-equal group-execute-or-setid ?x) (string-to-number "00010" 8))
3808 ((char-equal group-execute-or-setid ?S) (string-to-number "02000" 8))
3809 ((char-equal group-execute-or-setid ?s) (string-to-number "02010" 8))
3810 ((char-equal group-execute-or-setid ?-) 0)
3811 (t (error "Seventh char `%c' must be one of `xsS-'"
3812 group-execute-or-setid)))
3813 (cond
3814 ((char-equal other-read ?r) (string-to-number "00004" 8))
3815 ((char-equal other-read ?-) 0)
3816 (t (error "Eighth char `%c' must be one of `r-'" other-read)))
3817 (cond
3818 ((char-equal other-write ?w) (string-to-number "00002" 8))
3819 ((char-equal other-write ?-) 0)
3820 (t (error "Ninth char `%c' must be one of `w-'" other-write)))
3821 (cond
3822 ((char-equal other-execute-or-sticky ?x) (string-to-number "00001" 8))
3823 ((char-equal other-execute-or-sticky ?T) (string-to-number "01000" 8))
3824 ((char-equal other-execute-or-sticky ?t) (string-to-number "01001" 8))
3825 ((char-equal other-execute-or-sticky ?-) 0)
3826 (t (error "Tenth char `%c' must be one of `xtT-'"
3827 other-execute-or-sticky)))))))
3829 (defconst tramp-file-mode-type-map
3830 '((0 . "-") ; Normal file (SVID-v2 and XPG2)
3831 (1 . "p") ; fifo
3832 (2 . "c") ; character device
3833 (3 . "m") ; multiplexed character device (v7)
3834 (4 . "d") ; directory
3835 (5 . "?") ; Named special file (XENIX)
3836 (6 . "b") ; block device
3837 (7 . "?") ; multiplexed block device (v7)
3838 (8 . "-") ; regular file
3839 (9 . "n") ; network special file (HP-UX)
3840 (10 . "l") ; symlink
3841 (11 . "?") ; ACL shadow inode (Solaris, not userspace)
3842 (12 . "s") ; socket
3843 (13 . "D") ; door special (Solaris)
3844 (14 . "w")) ; whiteout (BSD)
3845 "A list of file types returned from the `stat' system call.
3846 This is used to map a mode number to a permission string.")
3848 ;;;###tramp-autoload
3849 (defun tramp-file-mode-from-int (mode)
3850 "Turn an integer representing a file mode into an ls(1)-like string."
3851 (let ((type (cdr
3852 (assoc (logand (lsh mode -12) 15) tramp-file-mode-type-map)))
3853 (user (logand (lsh mode -6) 7))
3854 (group (logand (lsh mode -3) 7))
3855 (other (logand (lsh mode -0) 7))
3856 (suid (> (logand (lsh mode -9) 4) 0))
3857 (sgid (> (logand (lsh mode -9) 2) 0))
3858 (sticky (> (logand (lsh mode -9) 1) 0)))
3859 (setq user (tramp-file-mode-permissions user suid "s"))
3860 (setq group (tramp-file-mode-permissions group sgid "s"))
3861 (setq other (tramp-file-mode-permissions other sticky "t"))
3862 (concat type user group other)))
3864 (defun tramp-file-mode-permissions (perm suid suid-text)
3865 "Convert a permission bitset into a string.
3866 This is used internally by `tramp-file-mode-from-int'."
3867 (let ((r (> (logand perm 4) 0))
3868 (w (> (logand perm 2) 0))
3869 (x (> (logand perm 1) 0)))
3870 (concat (or (and r "r") "-")
3871 (or (and w "w") "-")
3872 (or (and suid x suid-text) ; suid, execute
3873 (and suid (upcase suid-text)) ; suid, !execute
3874 (and x "x") "-")))) ; !suid
3876 ;;;###tramp-autoload
3877 (defun tramp-get-local-uid (id-format)
3878 "The uid of the local user, in ID-FORMAT.
3879 ID-FORMAT valid values are `string' and `integer'."
3880 (if (equal id-format 'integer) (user-uid) (user-login-name)))
3882 ;;;###tramp-autoload
3883 (defun tramp-get-local-gid (id-format)
3884 "The gid of the local user, in ID-FORMAT.
3885 ID-FORMAT valid values are `string' and `integer'."
3886 ;; `group-gid' has been introduced with Emacs 24.4.
3887 (if (and (fboundp 'group-gid) (equal id-format 'integer))
3888 (tramp-compat-funcall 'group-gid)
3889 (tramp-compat-file-attribute-group-id (file-attributes "~/" id-format))))
3891 (defun tramp-get-local-locale (&optional vec)
3892 "Determine locale, supporting UTF8 if possible.
3893 VEC is used for tracing."
3894 ;; We use key nil for local connection properties.
3895 (with-tramp-connection-property nil "locale"
3896 (let ((candidates '("en_US.utf8" "C.utf8" "en_US.UTF-8"))
3897 locale)
3898 (with-temp-buffer
3899 (unless (or (memq system-type '(windows-nt))
3900 (not (zerop (tramp-call-process
3901 nil "locale" nil t nil "-a"))))
3902 (while candidates
3903 (goto-char (point-min))
3904 (if (string-match (format "^%s\r?$" (regexp-quote (car candidates)))
3905 (buffer-string))
3906 (setq locale (car candidates)
3907 candidates nil)
3908 (setq candidates (cdr candidates))))))
3909 ;; Return value.
3910 (when vec (tramp-message vec 7 "locale %s" (or locale "C")))
3911 (or locale "C"))))
3913 ;;;###tramp-autoload
3914 (defun tramp-check-cached-permissions (vec access)
3915 "Check `file-attributes' caches for VEC.
3916 Return t if according to the cache access type ACCESS is known to
3917 be granted."
3918 (let ((result nil)
3919 (offset (cond
3920 ((eq ?r access) 1)
3921 ((eq ?w access) 2)
3922 ((eq ?x access) 3))))
3923 (dolist (suffix '("string" "integer") result)
3924 (setq
3925 result
3927 result
3928 (let ((file-attr
3930 (tramp-get-file-property
3931 vec (tramp-file-name-localname vec)
3932 (concat "file-attributes-" suffix) nil)
3933 (file-attributes
3934 (tramp-make-tramp-file-name
3935 (tramp-file-name-method vec)
3936 (tramp-file-name-user vec)
3937 (tramp-file-name-host vec)
3938 (tramp-file-name-localname vec)
3939 (tramp-file-name-hop vec))
3940 (intern suffix))))
3941 (remote-uid
3942 (tramp-get-connection-property
3943 vec (concat "uid-" suffix) nil))
3944 (remote-gid
3945 (tramp-get-connection-property
3946 vec (concat "gid-" suffix) nil))
3947 (unknown-id
3948 (if (string-equal suffix "string")
3949 tramp-unknown-id-string tramp-unknown-id-integer)))
3950 (and
3951 file-attr
3953 ;; Not a symlink.
3954 (eq t (tramp-compat-file-attribute-type file-attr))
3955 (null (tramp-compat-file-attribute-type file-attr)))
3957 ;; World accessible.
3958 (eq access
3959 (aref (tramp-compat-file-attribute-modes file-attr)
3960 (+ offset 6)))
3961 ;; User accessible and owned by user.
3962 (and
3963 (eq access
3964 (aref (tramp-compat-file-attribute-modes file-attr) offset))
3965 (or (equal remote-uid
3966 (tramp-compat-file-attribute-user-id file-attr))
3967 (equal unknown-id
3968 (tramp-compat-file-attribute-user-id file-attr))))
3969 ;; Group accessible and owned by user's principal group.
3970 (and
3971 (eq access
3972 (aref (tramp-compat-file-attribute-modes file-attr)
3973 (+ offset 3)))
3974 (or (equal remote-gid
3975 (tramp-compat-file-attribute-group-id file-attr))
3976 (equal unknown-id
3977 (tramp-compat-file-attribute-group-id
3978 file-attr))))))))))))
3980 ;;;###tramp-autoload
3981 (defun tramp-local-host-p (vec)
3982 "Return t if this points to the local host, nil otherwise."
3983 ;; We cannot use `tramp-file-name-real-host'. A port is an
3984 ;; indication for an ssh tunnel or alike.
3985 (let ((host (tramp-file-name-host vec)))
3986 (and
3987 (stringp host)
3988 (string-match tramp-local-host-regexp host)
3989 ;; The method shall be applied to one of the shell file name
3990 ;; handlers. `tramp-local-host-p' is also called for "smb" and
3991 ;; alike, where it must fail.
3992 (tramp-get-method-parameter vec 'tramp-login-program)
3993 ;; The local temp directory must be writable for the other user.
3994 (file-writable-p
3995 (tramp-make-tramp-file-name
3996 (tramp-file-name-method vec)
3997 (tramp-file-name-user vec)
3998 host
3999 (tramp-compat-temporary-file-directory)))
4000 ;; On some systems, chown runs only for root.
4001 (or (zerop (user-uid))
4002 ;; This is defined in tramp-sh.el. Let's assume this is
4003 ;; loaded already.
4004 (zerop (tramp-compat-funcall 'tramp-get-remote-uid vec 'integer))))))
4006 (defun tramp-get-remote-tmpdir (vec)
4007 "Return directory for temporary files on the remote host identified by VEC."
4008 (let ((dir (tramp-make-tramp-file-name
4009 (tramp-file-name-method vec)
4010 (tramp-file-name-user vec)
4011 (tramp-file-name-host vec)
4012 (or (tramp-get-method-parameter vec 'tramp-tmpdir) "/tmp"))))
4013 (with-tramp-connection-property vec "tmpdir"
4014 (or (and (file-directory-p dir) (file-writable-p dir)
4015 (file-remote-p dir 'localname))
4016 (tramp-error vec 'file-error "Directory %s not accessible" dir)))
4017 dir))
4019 ;;;###tramp-autoload
4020 (defun tramp-make-tramp-temp-file (vec)
4021 "Create a temporary file on the remote host identified by VEC.
4022 Return the local name of the temporary file."
4023 (let ((prefix (expand-file-name
4024 tramp-temp-name-prefix (tramp-get-remote-tmpdir vec)))
4025 result)
4026 (while (not result)
4027 ;; `make-temp-file' would be the natural choice for
4028 ;; implementation. But it calls `write-region' internally,
4029 ;; which also needs a temporary file - we would end in an
4030 ;; infinite loop.
4031 (setq result (make-temp-name prefix))
4032 (if (file-exists-p result)
4033 (setq result nil)
4034 ;; This creates the file by side effect.
4035 (set-file-times result)
4036 (set-file-modes result (string-to-number "0700" 8))))
4038 ;; Return the local part.
4039 (with-parsed-tramp-file-name result nil localname)))
4041 (defun tramp-delete-temp-file-function ()
4042 "Remove temporary files related to current buffer."
4043 (when (stringp tramp-temp-buffer-file-name)
4044 (ignore-errors (delete-file tramp-temp-buffer-file-name))))
4046 (add-hook 'kill-buffer-hook 'tramp-delete-temp-file-function)
4047 (add-hook 'tramp-unload-hook
4048 (lambda ()
4049 (remove-hook 'kill-buffer-hook
4050 'tramp-delete-temp-file-function)))
4052 (defun tramp-handle-make-auto-save-file-name ()
4053 "Like `make-auto-save-file-name' for Tramp files.
4054 Returns a file name in `tramp-auto-save-directory' for autosaving
4055 this file, if that variable is non-nil."
4056 (when (stringp tramp-auto-save-directory)
4057 (setq tramp-auto-save-directory
4058 (expand-file-name tramp-auto-save-directory)))
4059 ;; Create directory.
4060 (unless (or (null tramp-auto-save-directory)
4061 (file-exists-p tramp-auto-save-directory))
4062 (make-directory tramp-auto-save-directory t))
4064 (let ((system-type 'not-windows)
4065 (auto-save-file-name-transforms
4066 (if (null tramp-auto-save-directory)
4067 auto-save-file-name-transforms))
4068 (buffer-file-name
4069 (if (null tramp-auto-save-directory)
4070 buffer-file-name
4071 (expand-file-name
4072 (tramp-subst-strs-in-string
4073 '(("_" . "|")
4074 ("/" . "_a")
4075 (":" . "_b")
4076 ("|" . "__")
4077 ("[" . "_l")
4078 ("]" . "_r"))
4079 (buffer-file-name))
4080 tramp-auto-save-directory))))
4081 ;; Run plain `make-auto-save-file-name'.
4082 (tramp-run-real-handler 'make-auto-save-file-name nil)))
4084 (defun tramp-subst-strs-in-string (alist string)
4085 "Replace all occurrences of the string FROM with TO in STRING.
4086 ALIST is of the form ((FROM . TO) ...)."
4087 (save-match-data
4088 (while alist
4089 (let* ((pr (car alist))
4090 (from (car pr))
4091 (to (cdr pr)))
4092 (while (string-match (regexp-quote from) string)
4093 (setq string (replace-match to t t string)))
4094 (setq alist (cdr alist))))
4095 string))
4097 (defun tramp-handle-temporary-file-directory ()
4098 "Like `temporary-file-directory' for Tramp files."
4099 (catch 'result
4100 (dolist (dir `(,(ignore-errors
4101 (tramp-get-remote-tmpdir
4102 (tramp-dissect-file-name default-directory)))
4103 ,default-directory))
4104 (when (and (stringp dir) (file-directory-p dir) (file-writable-p dir))
4105 (throw 'result (expand-file-name dir))))))
4107 (defun tramp-handle-make-nearby-temp-file (prefix &optional dir-flag suffix)
4108 "Like `make-nearby-temp-file' for Tramp files."
4109 (let ((temporary-file-directory
4110 (tramp-compat-temporary-file-directory-function)))
4111 (make-temp-file prefix dir-flag suffix)))
4113 ;;; Compatibility functions section:
4115 (defun tramp-call-process
4116 (vec program &optional infile destination display &rest args)
4117 "Calls `call-process' on the local host.
4118 It always returns a return code. The Lisp error raised when
4119 PROGRAM is nil is trapped also, returning 1. Furthermore, traces
4120 are written with verbosity of 6."
4121 (let ((default-directory (tramp-compat-temporary-file-directory))
4122 (v (or vec
4123 (vector tramp-current-method tramp-current-user
4124 tramp-current-host nil nil)))
4125 (destination (if (eq destination t) (current-buffer) destination))
4126 output error result)
4127 (tramp-message
4128 v 6 "`%s %s' %s %s"
4129 program (mapconcat 'identity args " ") infile destination)
4130 (condition-case err
4131 (with-temp-buffer
4132 (setq result
4133 (apply
4134 'call-process program infile (or destination t) display args))
4135 ;; `result' could also be an error string.
4136 (when (stringp result)
4137 (setq error result
4138 result 1))
4139 (with-current-buffer
4140 (if (bufferp destination) destination (current-buffer))
4141 (setq output (buffer-string))))
4142 (error
4143 (setq error (error-message-string err)
4144 result 1)))
4145 (if (zerop (length error))
4146 (tramp-message v 6 "%d\n%s" result output)
4147 (tramp-message v 6 "%d\n%s\n%s" result output error))
4148 result))
4150 (defun tramp-call-process-region
4151 (vec start end program &optional delete buffer display &rest args)
4152 "Calls `call-process-region' on the local host.
4153 It always returns a return code. The Lisp error raised when
4154 PROGRAM is nil is trapped also, returning 1. Furthermore, traces
4155 are written with verbosity of 6."
4156 (let ((default-directory (tramp-compat-temporary-file-directory))
4157 (v (or vec
4158 (vector tramp-current-method tramp-current-user
4159 tramp-current-host nil nil)))
4160 (buffer (if (eq buffer t) (current-buffer) buffer))
4161 result)
4162 (tramp-message
4163 v 6 "`%s %s' %s %s %s %s"
4164 program (mapconcat 'identity args " ") start end delete buffer)
4165 (condition-case err
4166 (progn
4167 (setq result
4168 (apply
4169 'call-process-region
4170 start end program delete buffer display args))
4171 ;; `result' could also be an error string.
4172 (when (stringp result)
4173 (signal 'file-error (list result)))
4174 (with-current-buffer (if (bufferp buffer) buffer (current-buffer))
4175 (if (zerop result)
4176 (tramp-message v 6 "%d" result)
4177 (tramp-message v 6 "%d\n%s" result (buffer-string)))))
4178 (error
4179 (setq result 1)
4180 (tramp-message v 6 "%d\n%s" result (error-message-string err))))
4181 result))
4183 ;;;###tramp-autoload
4184 (defun tramp-read-passwd (proc &optional prompt)
4185 "Read a password from user (compat function).
4186 Consults the auth-source package.
4187 Invokes `password-read' if available, `read-passwd' else."
4188 (let* ((case-fold-search t)
4189 (key (tramp-make-tramp-file-name
4190 tramp-current-method tramp-current-user
4191 tramp-current-host ""))
4192 (pw-prompt
4193 (or prompt
4194 (with-current-buffer (process-buffer proc)
4195 (tramp-check-for-regexp proc tramp-password-prompt-regexp)
4196 (format "%s for %s " (capitalize (match-string 1)) key))))
4197 ;; We suspend the timers while reading the password.
4198 (stimers (with-timeout-suspend))
4199 auth-info auth-passwd)
4201 (unwind-protect
4202 (with-parsed-tramp-file-name key nil
4203 (prog1
4205 ;; See if auth-sources contains something useful.
4206 ;; `auth-source-user-or-password' is an obsoleted
4207 ;; function since Emacs 24.1, it has been replaced by
4208 ;; `auth-source-search'.
4209 (ignore-errors
4210 (and (tramp-get-connection-property
4211 v "first-password-request" nil)
4212 ;; Try with Tramp's current method.
4213 (if (fboundp 'auth-source-search)
4214 (setq auth-info
4215 (auth-source-search
4216 :max 1
4217 :user (or tramp-current-user t)
4218 :host tramp-current-host
4219 :port tramp-current-method
4220 :require
4221 (cons
4222 :secret (and tramp-current-user '(:user))))
4223 auth-passwd (plist-get
4224 (nth 0 auth-info) :secret)
4225 auth-passwd (if (functionp auth-passwd)
4226 (funcall auth-passwd)
4227 auth-passwd))
4228 (tramp-compat-funcall
4229 'auth-source-user-or-password
4230 "password" tramp-current-host tramp-current-method))))
4231 ;; Try the password cache.
4232 (let ((password (password-read pw-prompt key)))
4233 (password-cache-add key password)
4234 password)
4235 ;; Else, get the password interactively.
4236 (read-passwd pw-prompt))
4237 (tramp-set-connection-property v "first-password-request" nil)))
4238 ;; Reenable the timers.
4239 (with-timeout-unsuspend stimers))))
4241 ;;;###tramp-autoload
4242 (defun tramp-clear-passwd (vec)
4243 "Clear password cache for connection related to VEC."
4244 (let ((method (tramp-file-name-method vec))
4245 (user (tramp-file-name-user vec))
4246 (host (tramp-file-name-host vec))
4247 (hop (tramp-file-name-hop vec)))
4248 (when hop
4249 ;; Clear also the passwords of the hops.
4250 (tramp-clear-passwd
4251 (tramp-dissect-file-name
4252 (concat
4253 tramp-prefix-format
4254 (replace-regexp-in-string
4255 (concat tramp-postfix-hop-regexp "$")
4256 tramp-postfix-host-format hop)))))
4257 ;; `auth-source-forget-user-or-password' is an obsoleted function
4258 ;; since Emacs 24.1, it has been replaced by `auth-source-forget'.
4259 (if (fboundp 'auth-source-forget)
4260 (auth-source-forget
4261 `(:max 1 :user ,(or user t) :host ,host :port ,method))
4262 (tramp-compat-funcall
4263 'auth-source-forget-user-or-password "password" host method))
4264 (password-cache-remove (tramp-make-tramp-file-name method user host ""))))
4266 ;; Snarfed code from time-date.el and parse-time.el
4268 (defconst tramp-half-a-year '(241 17024)
4269 "Evaluated by \"(days-to-time 183)\".")
4271 (defconst tramp-parse-time-months
4272 '(("jan" . 1) ("feb" . 2) ("mar" . 3)
4273 ("apr" . 4) ("may" . 5) ("jun" . 6)
4274 ("jul" . 7) ("aug" . 8) ("sep" . 9)
4275 ("oct" . 10) ("nov" . 11) ("dec" . 12))
4276 "Alist mapping month names to integers.")
4278 ;;;###tramp-autoload
4279 (defun tramp-time-diff (t1 t2)
4280 "Return the difference between the two times, in seconds.
4281 T1 and T2 are time values (as returned by `current-time' for example)."
4282 ;; Starting with Emacs 25.1, we could change this to use `time-subtract'.
4283 (float-time (tramp-compat-funcall 'subtract-time t1 t2)))
4285 ;; Currently (as of Emacs 20.5), the function `shell-quote-argument'
4286 ;; does not deal well with newline characters. Newline is replaced by
4287 ;; backslash newline. But if, say, the string `a backslash newline b'
4288 ;; is passed to a shell, the shell will expand this into "ab",
4289 ;; completely omitting the newline. This is not what was intended.
4290 ;; It does not appear to be possible to make the function
4291 ;; `shell-quote-argument' work with newlines without making it
4292 ;; dependent on the shell used. But within this package, we know that
4293 ;; we will always use a Bourne-like shell, so we use an approach which
4294 ;; groks newlines.
4296 ;; The approach is simple: we call `shell-quote-argument', then
4297 ;; massage the newline part of the result.
4299 ;; This function should produce a string which is grokked by a Unix
4300 ;; shell, even if the Emacs is running on Windows. Since this is the
4301 ;; kludges section, we bind `system-type' in such a way that
4302 ;; `shell-quote-argument' behaves as if on Unix.
4304 ;; Thanks to Mario DeWeerd for the hint that it is sufficient for this
4305 ;; function to work with Bourne-like shells.
4307 ;; CCC: This function should be rewritten so that
4308 ;; `shell-quote-argument' is not used. This way, we are safe from
4309 ;; changes in `shell-quote-argument'.
4310 ;;;###tramp-autoload
4311 (defun tramp-shell-quote-argument (s)
4312 "Similar to `shell-quote-argument', but groks newlines.
4313 Only works for Bourne-like shells."
4314 (let ((system-type 'not-windows))
4315 (save-match-data
4316 (let ((result (shell-quote-argument s))
4317 (nl (regexp-quote (format "\\%s" tramp-rsh-end-of-line))))
4318 (when (and (>= (length result) 2)
4319 (string= (substring result 0 2) "\\~"))
4320 (setq result (substring result 1)))
4321 (while (string-match nl result)
4322 (setq result (replace-match (format "'%s'" tramp-rsh-end-of-line)
4323 t t result)))
4324 result))))
4326 ;;; Integration of eshell.el:
4328 ;; eshell.el keeps the path in `eshell-path-env'. We must change it
4329 ;; when `default-directory' points to another host.
4330 (defun tramp-eshell-directory-change ()
4331 "Set `eshell-path-env' to $PATH of the host related to `default-directory'."
4332 (setq eshell-path-env
4333 (if (tramp-tramp-file-p default-directory)
4334 (with-parsed-tramp-file-name default-directory nil
4335 (mapconcat
4336 'identity
4338 ;; When `tramp-own-remote-path' is in `tramp-remote-path',
4339 ;; the remote path is only set in the session cache.
4340 (tramp-get-connection-property
4341 (tramp-get-connection-process v) "remote-path" nil)
4342 (tramp-get-connection-property v "remote-path" nil))
4343 ":"))
4344 (getenv "PATH"))))
4346 (eval-after-load "esh-util"
4347 '(progn
4348 (tramp-eshell-directory-change)
4349 (add-hook 'eshell-directory-change-hook
4350 'tramp-eshell-directory-change)
4351 (add-hook 'tramp-unload-hook
4352 (lambda ()
4353 (remove-hook 'eshell-directory-change-hook
4354 'tramp-eshell-directory-change)))))
4356 ;; Checklist for `tramp-unload-hook'
4357 ;; - Unload all `tramp-*' packages
4358 ;; - Reset `file-name-handler-alist'
4359 ;; - Cleanup hooks where Tramp functions are in
4360 ;; - Cleanup advised functions
4361 ;; - Cleanup autoloads
4362 ;;;###autoload
4363 (defun tramp-unload-tramp ()
4364 "Discard Tramp from loading remote files."
4365 (interactive)
4366 ;; ange-ftp settings must be enabled.
4367 (tramp-compat-funcall 'tramp-ftp-enable-ange-ftp)
4368 ;; Maybe it's not loaded yet.
4369 (ignore-errors (unload-feature 'tramp 'force)))
4371 (provide 'tramp)
4373 ;;; TODO:
4375 ;; * In Emacs 21, `insert-directory' shows total number of bytes used
4376 ;; by the files in that directory. Add this here.
4378 ;; * Avoid screen blanking when hitting `g' in dired. (Eli Tziperman)
4380 ;; * Better error checking. At least whenever we see something
4381 ;; strange when doing zerop, we should kill the process and start
4382 ;; again. (Greg Stark)
4384 ;; * Make shadowfile.el grok Tramp filenames. (Bug#4526, Bug#4846)
4386 ;; * I was wondering if it would be possible to use tramp even if I'm
4387 ;; actually using sshfs. But when I launch a command I would like
4388 ;; to get it executed on the remote machine where the files really
4389 ;; are. (Andrea Crotti)
4391 ;; * Run emerge on two remote files. Bug is described here:
4392 ;; <http://www.mail-archive.com/tramp-devel@nongnu.org/msg01041.html>.
4393 ;; (Bug#6850)
4395 ;; * Use also port to distinguish connections. This is needed for
4396 ;; different hosts sitting behind a single router (distinguished by
4397 ;; different port numbers). (Tzvi Edelman)
4399 ;; * Refactor code from different handlers. Start with
4400 ;; *-process-file. One idea is to generalize `tramp-send-command'
4401 ;; and friends, for most of the handlers this is the major
4402 ;; difference between the different backends. Other handlers but
4403 ;; *-process-file would profit from this as well.
4405 ;;; tramp.el ends here
4407 ;; Local Variables:
4408 ;; mode: Emacs-Lisp
4409 ;; coding: utf-8
4410 ;; End: