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