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