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