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