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