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