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