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