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