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