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