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