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