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