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