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