tramp-gvfs.el 65.4 KB
Newer Older
1 2
;;; tramp-gvfs.el --- Tramp access functions for GVFS daemon

3
;; Copyright (C) 2009-2013 Free Software Foundation, Inc.
4 5 6

;; Author: Michael Albinus <michael.albinus@gmx.de>
;; Keywords: comm, processes
7
;; Package: tramp
8

Glenn Morris's avatar
Glenn Morris committed
9 10 11
;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
12 13 14 15
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

Glenn Morris's avatar
Glenn Morris committed
16 17 18 19
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
20 21 22 23 24 25 26

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; Access functions for the GVFS daemon from Tramp.  Tested with GVFS
27
;; 1.0 (Ubuntu 8.10, Gnome 2.24).  It has been reported also to run
28 29 30
;; with GVFS 0.2.5 (Ubuntu 8.04, Gnome 2.22), but there is an
;; incompatibility with the mount_info structure, which has been
;; worked around.
31

32
;; It has also been tested with GVFS 1.6 (Ubuntu 10.04, Gnome 2.30),
33 34 35
;; where the default_location has been added to mount_info (see
;; <https://bugzilla.gnome.org/show_bug.cgi?id=561998>.

36 37 38
;; With GVFS 1.14 (Ubuntu 12.10, Gnome 3.6) the interfaces have been
;; changed, again.  So we must introspect the D-Bus interfaces.

39 40 41
;; All actions to mount a remote location, and to retrieve mount
;; information, are performed by D-Bus messages.  File operations
;; themselves are performed via the mounted filesystem in ~/.gvfs.
42
;; Consequently, GNU Emacs 23.1 with enabled D-Bus bindings is a
43 44
;; precondition.

45 46 47 48
;; The GVFS D-Bus interface is said to be unstable.  There were even
;; no introspection data before GVFS 1.14.  The interface, as
;; discovered during development time, is given in respective
;; comments.
49 50

;; The customer option `tramp-gvfs-methods' contains the list of
51 52 53 54 55
;; supported connection methods.  Per default, these are "dav",
;; "davs", "obex" and "synce".  Note that with "obex" it might be
;; necessary to pair with the other bluetooth device, if it hasn't
;; been done already.  There might be also some few seconds delay in
;; discovering available bluetooth devices.
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

;; Other possible connection methods are "ftp", "sftp" and "smb".
;; When one of these methods is added to the list, the remote access
;; for that method is performed via GVFS instead of the native Tramp
;; implementation.

;; GVFS offers even more connection methods.  The complete list of
;; connection methods of the actual GVFS implementation can be
;; retrieved by:
;;
;; (message
;;  "%s"
;;  (mapcar
;;   'car
;;   (dbus-call-method
;;    :session tramp-gvfs-service-daemon tramp-gvfs-path-mounttracker
;;    tramp-gvfs-interface-mounttracker "listMountableInfo")))

;; Note that all other connection methods are not tested, beside the
;; ones offered for customization in `tramp-gvfs-methods'.  If you
;; request an additional connection method to be supported, please
;; drop me a note.

;; For hostname completion, information is retrieved either from the
80 81 82 83 84 85
;; bluez daemon (for the "obex" method), the hal daemon (for the
;; "synce" method), or from the zeroconf daemon (for the "dav",
;; "davs", and "sftp" methods).  The zeroconf daemon is pre-configured
;; to discover services in the "local" domain.  If another domain
;; shall be used for discovering services, the customer option
;; `tramp-gvfs-zeroconf-domain' can be set accordingly.
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

;; Restrictions:

;; * The current GVFS implementation does not allow to write on the
;;   remote bluetooth device via OBEX.
;;
;; * Two shares of the same SMB server cannot be mounted in parallel.

;;; Code:

;; D-Bus support in the Emacs core can be disabled with configuration
;; option "--without-dbus".  Declare used subroutines and variables.
(declare-function dbus-get-unique-name "dbusbind.c")

;; Pacify byte-compiler
(eval-when-compile
  (require 'cl)
  (require 'custom))

(require 'tramp)
106

107 108
(require 'dbus)
(require 'url-parse)
109
(require 'url-util)
110 111
(require 'zeroconf)

112
;;;###tramp-autoload
113
(defcustom tramp-gvfs-methods '("dav" "davs" "obex" "synce")
114
  "List of methods for remote files, accessed with GVFS."
115
  :group 'tramp
116
  :version "23.2"
117 118 119 120 121
  :type '(repeat (choice (const "dav")
			 (const "davs")
			 (const "ftp")
			 (const "obex")
			 (const "sftp")
122 123
			 (const "smb")
			 (const "synce"))))
124

125 126
;; Add a default for `tramp-default-user-alist'.  Rule: For the SYNCE
;; method, no user is chosen.
127
;;;###tramp-autoload
128
(add-to-list 'tramp-default-user-alist '("\\`synce\\'" nil nil))
129

130
(defcustom tramp-gvfs-zeroconf-domain "local"
131
  "Zeroconf domain to be used for discovering services, like host names."
132
  :group 'tramp
133
  :version "23.2"
134 135 136 137
  :type 'string)

;; Add the methods to `tramp-methods', in order to allow minibuffer
;; completion.
138 139 140 141 142
;;;###tramp-autoload
(when (featurep 'dbusbind)
  (dolist (elt tramp-gvfs-methods)
    (unless (assoc elt tramp-methods)
      (add-to-list 'tramp-methods (cons elt nil)))))
143 144

(defconst tramp-gvfs-path-tramp (concat dbus-path-emacs "/Tramp")
Glenn Morris's avatar
Glenn Morris committed
145
  "The preceding object path for own objects.")
146 147 148 149

(defconst tramp-gvfs-service-daemon "org.gtk.vfs.Daemon"
  "The well known name of the GVFS daemon.")

150 151 152 153 154 155 156 157 158
;; D-Bus integration is available since Emacs 23 on some system types.
;; We don't call `dbus-ping', because this would load dbus.el.
(defconst tramp-gvfs-enabled
  (ignore-errors
    (and (featurep 'dbusbind)
	 (tramp-compat-funcall 'dbus-get-unique-name :session)
	 (or (tramp-compat-process-running-p "gvfs-fuse-daemon")
	     (tramp-compat-process-running-p "gvfsd-fuse"))))
  "Non-nil when GVFS is available.")
159 160 161 162 163 164 165

(defconst tramp-gvfs-path-mounttracker "/org/gtk/vfs/mounttracker"
  "The object path of the GVFS daemon.")

(defconst tramp-gvfs-interface-mounttracker "org.gtk.vfs.MountTracker"
  "The mount tracking interface in the GVFS daemon.")

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
;; Introspection data exist since GVFS 1.14.  If there are no such
;; data, we expect an earlier interface.
(defconst tramp-gvfs-methods-mounttracker
  (dbus-introspect-get-method-names
   :session tramp-gvfs-service-daemon tramp-gvfs-path-mounttracker
   tramp-gvfs-interface-mounttracker)
  "The list of supported methods of the mount tracking interface.")

(defconst tramp-gvfs-listmounts
  (if (member "ListMounts" tramp-gvfs-methods-mounttracker)
      "ListMounts"
    "listMounts")
  "The name of the \"listMounts\" method.
It has been changed in GVFS 1.14.")

(defconst tramp-gvfs-mountlocation
  (if (member "MountLocation" tramp-gvfs-methods-mounttracker)
      "MountLocation"
    "mountLocation")
  "The name of the \"mountLocation\" method.
It has been changed in GVFS 1.14.")

(defconst tramp-gvfs-mountlocation-signature
  (dbus-introspect-get-signature
   :session tramp-gvfs-service-daemon tramp-gvfs-path-mounttracker
   tramp-gvfs-interface-mounttracker tramp-gvfs-mountlocation)
  "The D-Bus signature of the \"mountLocation\" method.
It has been changed in GVFS 1.14.")

195 196 197
;; <interface name='org.gtk.vfs.MountTracker'>
;;   <method name='listMounts'>
;;     <arg name='mount_info_list'
198
;;          type='a{sosssssbay{aya{say}}ay}'
199 200 201 202 203 204 205 206 207
;;          direction='out'/>
;;   </method>
;;   <method name='mountLocation'>
;;     <arg name='mount_spec'  type='{aya{say}}' direction='in'/>
;;     <arg name='dbus_id'     type='s'          direction='in'/>
;;     <arg name='object_path' type='o'          direction='in'/>
;;   </method>
;;   <signal name='mounted'>
;;     <arg name='mount_info'
208
;;          type='{sosssssbay{aya{say}}ay}'/>
209 210 211
;;   </signal>
;;   <signal name='unmounted'>
;;     <arg name='mount_info'
212
;;          type='{sosssssbay{aya{say}}ay}'/>
213 214 215 216 217 218 219 220
;;   </signal>
;; </interface>
;;
;; STRUCT		mount_info
;;   STRING		  dbus_id
;;   OBJECT_PATH	  object_path
;;   STRING		  display_name
;;   STRING		  stable_name
221
;;   STRING		  x_content_types	Since GVFS 1.0 only !!!
222
;;   STRING		  icon
Paul Eggert's avatar
Paul Eggert committed
223
;;   STRING		  preferred_filename_encoding
224 225 226 227 228 229 230 231
;;   BOOLEAN		  user_visible
;;   ARRAY BYTE		  fuse_mountpoint
;;   STRUCT		  mount_spec
;;     ARRAY BYTE	    mount_prefix
;;     ARRAY
;;       STRUCT		    mount_spec_item
;;         STRING	      key (server, share, type, user, host, port)
;;         ARRAY BYTE	      value
232
;;   ARRAY BYTE           default_location	Since GVFS 1.5 only !!!
233 234 235 236 237 238

(defconst tramp-gvfs-interface-mountoperation "org.gtk.vfs.MountOperation"
  "Used by the dbus-proxying implementation of GMountOperation.")

;; <interface name='org.gtk.vfs.MountOperation'>
;;   <method name='askPassword'>
239
;;     <arg name='message'        type='s' direction='in'/>
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
;;     <arg name='default_user'   type='s' direction='in'/>
;;     <arg name='default_domain' type='s' direction='in'/>
;;     <arg name='flags'          type='u' direction='in'/>
;;     <arg name='handled'        type='b' direction='out'/>
;;     <arg name='aborted'        type='b' direction='out'/>
;;     <arg name='password'       type='s' direction='out'/>
;;     <arg name='username'       type='s' direction='out'/>
;;     <arg name='domain'         type='s' direction='out'/>
;;     <arg name='anonymous'      type='b' direction='out'/>
;;     <arg name='password_save'  type='u' direction='out'/>
;;   </method>
;;   <method name='askQuestion'>
;;     <arg name='message' type='s'  direction='in'/>
;;     <arg name='choices' type='as' direction='in'/>
;;     <arg name='handled' type='b'  direction='out'/>
;;     <arg name='aborted' type='b'  direction='out'/>
;;     <arg name='choice'  type='u'  direction='out'/>
;;   </method>
;; </interface>

;; The following flags are used in "askPassword".  They are defined in
;; /usr/include/glib-2.0/gio/gioenums.h.

(defconst tramp-gvfs-password-need-password 1
  "Operation requires a password.")

(defconst tramp-gvfs-password-need-username 2
  "Operation requires a username.")

(defconst tramp-gvfs-password-need-domain 4
  "Operation requires a domain.")

(defconst tramp-gvfs-password-saving-supported 8
  "Operation supports saving settings.")

(defconst tramp-gvfs-password-anonymous-supported 16
  "Operation supports anonymous users.")

(defconst tramp-bluez-service "org.bluez"
  "The well known name of the BLUEZ service.")

(defconst tramp-bluez-interface-manager "org.bluez.Manager"
  "The manager interface of the BLUEZ daemon.")

;; <interface name='org.bluez.Manager'>
;;   <method name='DefaultAdapter'>
;;     <arg type='o' direction='out'/>
;;   </method>
;;   <method name='FindAdapter'>
;;     <arg type='s' direction='in'/>
;;     <arg type='o' direction='out'/>
;;   </method>
;;   <method name='ListAdapters'>
;;     <arg type='ao' direction='out'/>
;;   </method>
;;   <signal name='AdapterAdded'>
;;     <arg type='o'/>
;;   </signal>
;;   <signal name='AdapterRemoved'>
;;     <arg type='o'/>
;;   </signal>
;;   <signal name='DefaultAdapterChanged'>
;;     <arg type='o'/>
;;   </signal>
;; </interface>

(defconst tramp-bluez-interface-adapter "org.bluez.Adapter"
  "The adapter interface of the BLUEZ daemon.")

;; <interface name='org.bluez.Adapter'>
;;   <method name='GetProperties'>
;;     <arg type='a{sv}' direction='out'/>
;;   </method>
;;   <method name='SetProperty'>
;;     <arg type='s' direction='in'/>
;;     <arg type='v' direction='in'/>
;;   </method>
;;   <method name='RequestMode'>
;;     <arg type='s' direction='in'/>
;;   </method>
;;   <method name='ReleaseMode'/>
;;   <method name='RequestSession'/>
;;   <method name='ReleaseSession'/>
;;   <method name='StartDiscovery'/>
;;   <method name='StopDiscovery'/>
;;   <method name='ListDevices'>
;;     <arg type='ao' direction='out'/>
;;   </method>
;;   <method name='CreateDevice'>
;;     <arg type='s' direction='in'/>
;;     <arg type='o' direction='out'/>
;;   </method>
;;   <method name='CreatePairedDevice'>
;;     <arg type='s' direction='in'/>
;;     <arg type='o' direction='in'/>
;;     <arg type='s' direction='in'/>
;;     <arg type='o' direction='out'/>
;;   </method>
;;   <method name='CancelDeviceCreation'>
;;     <arg type='s' direction='in'/>
;;   </method>
;;   <method name='RemoveDevice'>
;;     <arg type='o' direction='in'/>
;;   </method>
;;   <method name='FindDevice'>
;;     <arg type='s' direction='in'/>
;;     <arg type='o' direction='out'/>
;;   </method>
;;   <method name='RegisterAgent'>
;;     <arg type='o' direction='in'/>
;;     <arg type='s' direction='in'/>
;;   </method>
;;   <method name='UnregisterAgent'>
;;     <arg type='o' direction='in'/>
;;   </method>
;;   <signal name='DeviceCreated'>
;;     <arg type='o'/>
;;   </signal>
;;   <signal name='DeviceRemoved'>
;;     <arg type='o'/>
;;   </signal>
;;   <signal name='DeviceFound'>
;;     <arg type='s'/>
;;     <arg type='a{sv}'/>
;;   </signal>
;;   <signal name='PropertyChanged'>
;;     <arg type='s'/>
;;     <arg type='v'/>
;;   </signal>
;;   <signal name='DeviceDisappeared'>
;;     <arg type='s'/>
;;   </signal>
;; </interface>

(defcustom tramp-bluez-discover-devices-timeout 60
  "Defines seconds since last bluetooth device discovery before rescanning.
A value of 0 would require an immediate discovery during hostname
completion, nil means to use always cached values for discovered
devices."
  :group 'tramp
380
  :version "23.2"
381 382 383 384 385 386 387 388 389 390
  :type '(choice (const nil) integer))

(defvar tramp-bluez-discovery nil
  "Indicator for a running bluetooth device discovery.
It keeps the timestamp of last discovery.")

(defvar tramp-bluez-devices nil
  "Alist of detected bluetooth devices.
Every entry is a list (NAME ADDRESS).")

391 392 393 394 395 396 397 398 399 400 401 402 403
(defconst tramp-hal-service "org.freedesktop.Hal"
  "The well known name of the HAL service.")

(defconst tramp-hal-path-manager "/org/freedesktop/Hal/Manager"
  "The object path of the HAL daemon manager.")

(defconst tramp-hal-interface-manager "org.freedesktop.Hal.Manager"
  "The manager interface of the HAL daemon.")

(defconst tramp-hal-interface-device "org.freedesktop.Hal.Device"
  "The device interface of the HAL daemon.")


404 405
;; New handlers should be added here.
(defconst tramp-gvfs-file-name-handler-alist
Michael Albinus's avatar
Michael Albinus committed
406
  '((access-file . ignore)
407
    (add-name-to-file . tramp-gvfs-handle-copy-file)
408
    ;; `byte-compiler-base-file-name' performed by default handler.
Michael Albinus's avatar
Michael Albinus committed
409
    ;; `copy-directory' performed by default handler.
410 411 412
    (copy-file . tramp-gvfs-handle-copy-file)
    (delete-directory . tramp-gvfs-handle-delete-directory)
    (delete-file . tramp-gvfs-handle-delete-file)
413
    ;; `diff-latest-backup-file' performed by default handler.
414
    (directory-file-name . tramp-handle-directory-file-name)
415
    (directory-files . tramp-handle-directory-files)
416
    (directory-files-and-attributes
417
     . tramp-handle-directory-files-and-attributes)
418 419 420 421
    (dired-call-process . ignore)
    (dired-compress-file . ignore)
    (dired-uncache . tramp-handle-dired-uncache)
    (expand-file-name . tramp-gvfs-handle-expand-file-name)
422
    (file-accessible-directory-p . tramp-handle-file-accessible-directory-p)
423
    (file-acl . ignore)
424
    (file-attributes . tramp-gvfs-handle-file-attributes)
425
    (file-directory-p . tramp-gvfs-handle-file-directory-p)
Michael Albinus's avatar
Michael Albinus committed
426
    ;; `file-equal-p' performed by default handler.
427
    (file-executable-p . tramp-gvfs-handle-file-executable-p)
428
    (file-exists-p . tramp-handle-file-exists-p)
Michael Albinus's avatar
Michael Albinus committed
429
    ;; `file-in-directory-p' performed by default handler.
430
    (file-local-copy . tramp-gvfs-handle-file-local-copy)
431
    (file-modes . tramp-handle-file-modes)
432 433 434 435 436
    (file-name-all-completions . tramp-gvfs-handle-file-name-all-completions)
    (file-name-as-directory . tramp-handle-file-name-as-directory)
    (file-name-completion . tramp-handle-file-name-completion)
    (file-name-directory . tramp-handle-file-name-directory)
    (file-name-nondirectory . tramp-handle-file-name-nondirectory)
437
    ;; `file-name-sans-versions' performed by default handler.
438
    (file-newer-than-file-p . tramp-handle-file-newer-than-file-p)
Michael Albinus's avatar
Michael Albinus committed
439 440
    (file-notify-add-watch . tramp-gvfs-handle-file-notify-add-watch)
    (file-notify-rm-watch . tramp-handle-file-notify-rm-watch)
441 442 443
    (file-ownership-preserved-p . ignore)
    (file-readable-p . tramp-gvfs-handle-file-readable-p)
    (file-regular-p . tramp-handle-file-regular-p)
Michael Albinus's avatar
Michael Albinus committed
444
    (file-remote-p . tramp-handle-file-remote-p)
445
    (file-selinux-context . ignore)
446
    (file-symlink-p . tramp-handle-file-symlink-p)
447
    ;; `file-truename' performed by default handler.
448 449
    (file-writable-p . tramp-gvfs-handle-file-writable-p)
    (find-backup-file-name . tramp-handle-find-backup-file-name)
450 451
    ;; `find-file-noselect' performed by default handler.
    ;; `get-file-buffer' performed by default handler.
452 453 454
    (insert-directory . tramp-gvfs-handle-insert-directory)
    (insert-file-contents . tramp-gvfs-handle-insert-file-contents)
    (load . tramp-handle-load)
Michael Albinus's avatar
Michael Albinus committed
455
    ;; `make-auto-save-file-name' performed by default handler.
456 457 458
    (make-directory . tramp-gvfs-handle-make-directory)
    (make-directory-internal . ignore)
    (make-symbolic-link . ignore)
459
    (process-file . ignore)
460
    (rename-file . tramp-gvfs-handle-rename-file)
461 462 463
    (set-file-acl . ignore)
    (set-file-modes . ignore)
    (set-file-selinux-context . ignore)
Michael Albinus's avatar
Michael Albinus committed
464 465
    (set-file-times . ignore)
    (set-visited-file-modtime . tramp-handle-set-visited-file-modtime)
466 467
    (shell-command . ignore)
    (start-file-process . ignore)
468 469 470
    (substitute-in-file-name . tramp-handle-substitute-in-file-name)
    (unhandled-file-name-directory . tramp-handle-unhandled-file-name-directory)
    (vc-registered . ignore)
Michael Albinus's avatar
Michael Albinus committed
471 472
    (verify-visited-file-modtime . tramp-handle-verify-visited-file-modtime)
    (write-region . tramp-gvfs-handle-write-region))
473 474 475
  "Alist of handler functions for Tramp GVFS method.
Operations not mentioned here will be handled by the default Emacs primitives.")

476 477
;; It must be a `defsubst' in order to push the whole code into
;; tramp-loaddefs.el.  Otherwise, there would be recursive autoloading.
478 479
;;;###tramp-autoload
(defsubst tramp-gvfs-file-name-p (filename)
480 481 482 483 484 485
  "Check if it's a filename handled by the GVFS daemon."
  (and (tramp-tramp-file-p filename)
       (let ((method
	      (tramp-file-name-method (tramp-dissect-file-name filename))))
	 (and (stringp method) (member method tramp-gvfs-methods)))))

486
;;;###tramp-autoload
487 488 489 490
(defun tramp-gvfs-file-name-handler (operation &rest args)
  "Invoke the GVFS related OPERATION.
First arg specifies the OPERATION, second arg is a list of arguments to
pass to the OPERATION."
491 492
  (unless tramp-gvfs-enabled
    (tramp-compat-user-error "Package `tramp-gvfs' not supported"))
493 494 495 496 497 498 499
  (let ((fn (assoc operation tramp-gvfs-file-name-handler-alist)))
    (if fn
	(save-match-data (apply (cdr fn) args))
      (tramp-run-real-handler operation args))))

;; This might be moved to tramp.el.  It shall be the first file name
;; handler.
500 501 502 503
;;;###tramp-autoload
(when (featurep 'dbusbind)
  (add-to-list 'tramp-foreign-file-name-handler-alist
	       (cons 'tramp-gvfs-file-name-p 'tramp-gvfs-file-name-handler)))
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

;; D-Bus helper function.

(defun tramp-gvfs-dbus-string-to-byte-array (string)
  "Like `dbus-string-to-byte-array' but add trailing \\0 if needed."
  (dbus-string-to-byte-array
   (if (string-match "^(aya{sv})" tramp-gvfs-mountlocation-signature)
       (concat string (string 0)) string)))

(defun tramp-gvfs-dbus-byte-array-to-string (byte-array)
  "Like `dbus-byte-array-to-string' but remove trailing \\0 if exists."
  ;; The byte array could be a variant.  Take care.
  (let ((byte-array
	 (if (and (consp byte-array) (atom (car byte-array)))
	     byte-array (car byte-array))))
    (dbus-byte-array-to-string
     (if (and (consp byte-array) (zerop (car (last byte-array))))
	 (butlast byte-array) byte-array))))

524 525 526 527
(defun tramp-gvfs-stringify-dbus-message (message)
  "Convert a D-Bus message into readable UTF8 strings, used for traces."
  (cond
   ((and (consp message) (characterp (car message)))
528
    (format "%S" (tramp-gvfs-dbus-byte-array-to-string message)))
529 530 531 532 533 534
   ((consp message)
    (mapcar 'tramp-gvfs-stringify-dbus-message message))
   ((stringp message)
    (format "%S" message))
   (t message)))

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
(defmacro with-tramp-dbus-call-method
  (vec synchronous bus service path interface method &rest args)
  "Apply a D-Bus call on bus BUS.

If SYNCHRONOUS is non-nil, the call is synchronously.  Otherwise,
it is an asynchronous call, with `ignore' as callback function.

The other arguments have the same meaning as with `dbus-call-method'
or `dbus-call-method-asynchronously'.  Additionally, the call
will be traced by Tramp with trace level 6."
  `(let ((func (if ,synchronous
		   'dbus-call-method 'dbus-call-method-asynchronously))
	 (args (append (list ,bus ,service ,path ,interface ,method)
		       (if ,synchronous (list ,@args) (list 'ignore ,@args))))
	 result)
     (tramp-message ,vec 6 "%s %s" func args)
     (setq result (apply func args))
552
     (tramp-message ,vec 6 "%s" (tramp-gvfs-stringify-dbus-message result))
553 554 555 556
     result))

(put 'with-tramp-dbus-call-method 'lisp-indent-function 2)
(put 'with-tramp-dbus-call-method 'edebug-form-spec '(form symbolp body))
557 558
(tramp-compat-font-lock-add-keywords
 'emacs-lisp-mode '("\\<with-tramp-dbus-call-method\\>"))
559 560 561 562 563 564 565

(defvar tramp-gvfs-dbus-event-vector nil
  "Current Tramp file name to be used, as vector.
It is needed when D-Bus signals or errors arrive, because there
is no information where to trace the message.")

(defun tramp-gvfs-dbus-event-error (event err)
566
  "Called when a D-Bus error message arrives, see `dbus-event-error-functions'."
567 568 569
  (when tramp-gvfs-dbus-event-vector
    (tramp-message tramp-gvfs-dbus-event-vector 10 "%S" event)
    (tramp-error tramp-gvfs-dbus-event-vector 'file-error "%s" (cadr err))))
570

571 572 573 574 575
;; `dbus-event-error-hooks' has been renamed to `dbus-event-error-functions'.
(add-hook
 (if (boundp 'dbus-event-error-functions)
     'dbus-event-error-functions 'dbus-event-error-hooks)
 'tramp-gvfs-dbus-event-error)
576 577 578 579 580


;; File name primitives.

(defun tramp-gvfs-handle-copy-file
Michael Albinus's avatar
Michael Albinus committed
581
  (filename newname &optional ok-if-already-exists keep-date
582
	    preserve-uid-gid preserve-extended-attributes)
583
  "Like `copy-file' for Tramp files."
584 585
  (with-parsed-tramp-file-name
      (if (tramp-tramp-file-p filename) filename newname) nil
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633

    (when (and (not ok-if-already-exists) (file-exists-p newname))
      (tramp-error
       v 'file-already-exists "File %s already exists" newname))

    (if (or (and (tramp-tramp-file-p filename)
		 (not (tramp-gvfs-file-name-p filename)))
	    (and (tramp-tramp-file-p newname)
		 (not (tramp-gvfs-file-name-p newname))))

	;; We cannot copy directly.
	(let ((tmpfile (tramp-compat-make-temp-file filename)))
	  (cond
	   (preserve-extended-attributes
	    (copy-file
	     filename tmpfile t keep-date preserve-uid-gid
	     preserve-extended-attributes))
	   (preserve-uid-gid
	    (copy-file filename tmpfile t keep-date preserve-uid-gid))
	   (t
	    (copy-file filename tmpfile t keep-date)))
	  (rename-file tmpfile newname ok-if-already-exists))

      ;; Direct copy.
      (with-tramp-progress-reporter
	  v 0 (format "Copying %s to %s" filename newname)
	(unless
	    (let ((args
		   (append (if (or keep-date preserve-uid-gid)
			       (list "--preserve")
			     nil)
			   (list
			    (tramp-gvfs-url-file-name filename)
			    (tramp-gvfs-url-file-name newname)))))
	      (apply 'tramp-gvfs-send-command v "gvfs-copy" args))
	  ;; Propagate the error.
	  (with-current-buffer (tramp-get-connection-buffer v)
	    (goto-char (point-min))
	    (tramp-error-with-buffer
	     nil v 'file-error
	     "Copying failed, see buffer `%s' for details." (buffer-name)))))

      (when (file-remote-p newname)
	(with-parsed-tramp-file-name newname nil
	  (tramp-flush-file-property v (file-name-directory localname))
	  (tramp-flush-file-property v localname))))))

(defun tramp-gvfs-handle-delete-directory (directory &optional recursive trash)
634
  "Like `delete-directory' for Tramp files."
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
  (when (and recursive (not (file-symlink-p directory)))
    (mapc (lambda (file)
	    (if (eq t (car (file-attributes file)))
		(tramp-compat-delete-directory file recursive trash)
	      (tramp-compat-delete-file file trash)))
	  (directory-files
	   directory 'full "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*")))
  (with-parsed-tramp-file-name directory nil
    (tramp-flush-file-property v (file-name-directory localname))
    (tramp-flush-directory-property v localname)
    (unless
	(tramp-gvfs-send-command
	 v (if (and trash delete-by-moving-to-trash) "gvfs-trash" "gvfs-rm")
	 (tramp-gvfs-url-file-name directory))
      ;; Propagate the error.
      (with-current-buffer (tramp-get-connection-buffer v)
	(goto-char (point-min))
	(tramp-error-with-buffer
	 nil v 'file-error "Couldn't delete %s" directory)))))
654

655
(defun tramp-gvfs-handle-delete-file (filename &optional trash)
656
  "Like `delete-file' for Tramp files."
657 658 659 660 661 662 663 664 665 666 667 668
  (with-parsed-tramp-file-name filename nil
    (tramp-flush-file-property v (file-name-directory localname))
    (tramp-flush-directory-property v localname)
    (unless
	(tramp-gvfs-send-command
	 v (if (and trash delete-by-moving-to-trash) "gvfs-trash" "gvfs-rm")
	 (tramp-gvfs-url-file-name filename))
      ;; Propagate the error.
      (with-current-buffer (tramp-get-connection-buffer v)
	(goto-char (point-min))
	(tramp-error-with-buffer
	 nil v 'file-error "Couldn't delete %s" filename)))))
669 670 671 672 673 674 675 676 677 678 679 680 681

(defun tramp-gvfs-handle-expand-file-name (name &optional dir)
  "Like `expand-file-name' for Tramp files."
  ;; If DIR is not given, use DEFAULT-DIRECTORY or "/".
  (setq dir (or dir default-directory "/"))
  ;; Unless NAME is absolute, concat DIR and NAME.
  (unless (file-name-absolute-p name)
    (setq name (concat (file-name-as-directory dir) name)))
  ;; If NAME is not a Tramp file, run the real handler.
  (if (not (tramp-tramp-file-p name))
      (tramp-run-real-handler 'expand-file-name (list name nil))
    ;; Dissect NAME.
    (with-parsed-tramp-file-name name nil
682 683 684
      ;; If there is a default location, expand tilde.
      (when (string-match "\\`\\(~\\)\\(/\\|\\'\\)" localname)
	(save-match-data
Michael Albinus's avatar
Michael Albinus committed
685
	  (tramp-gvfs-maybe-open-connection (vector method user host "/" hop)))
686 687 688 689
	(setq localname
	      (replace-match
	       (tramp-get-file-property  v "/" "default-location" "~")
	       nil t localname 1)))
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
      ;; Tilde expansion is not possible.
      (when (string-match "\\`\\(~[^/]*\\)\\(.*\\)\\'" localname)
	(tramp-error
	 v 'file-error
	 "Cannot expand tilde in file `%s'" name))
      (unless (tramp-run-real-handler 'file-name-absolute-p (list localname))
	(setq localname (concat "/" localname)))
      ;; We do not pass "/..".
      (if (string-equal "smb" method)
	  (when (string-match "^/[^/]+\\(/\\.\\./?\\)" localname)
	    (setq localname (replace-match "/" t t localname 1)))
	(when (string-match "^/\\.\\./?" localname)
	  (setq localname (replace-match "/" t t localname))))
      ;; There might be a double slash.  Remove this.
      (while (string-match "//" localname)
	(setq localname (replace-match "/" t t localname)))
      ;; No tilde characters in file name, do normal
      ;; `expand-file-name' (this does "/./" and "/../").
      (tramp-make-tramp-file-name
       method user host
       (tramp-run-real-handler
	'expand-file-name (list localname))))))

(defun tramp-gvfs-handle-file-attributes (filename &optional id-format)
  "Like `file-attributes' for Tramp files."
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
  (unless id-format (setq id-format 'integer))
  ;; Don't modify `last-coding-system-used' by accident.
  (let ((last-coding-system-used last-coding-system-used)
	dirp res-symlink-target res-numlinks res-uid res-gid res-access
	res-mod res-change res-size res-filemodes res-inode res-device)
    (with-parsed-tramp-file-name filename nil
      (with-tramp-file-property
	  v localname (format "file-attributes-%s" id-format)
	(tramp-message v 5 "file attributes: %s" localname)
	(tramp-gvfs-send-command
	 v "gvfs-info" (tramp-gvfs-url-file-name filename))
	;; Parse output ...
	(with-current-buffer (tramp-get-connection-buffer v)
	  (goto-char (point-min))
	  (when (re-search-forward "attributes:" nil t)
	    ;; ... directory or symlink
	    (goto-char (point-min))
	    (setq dirp (if (re-search-forward "type:\\s-+directory" nil t) t))
	    (goto-char (point-min))
	    (setq res-symlink-target
		  (if (re-search-forward
		       "standard::symlink-target:\\s-+\\(\\S-+\\)" nil t)
		      (match-string 1)))
	    ;; ... number links
	    (goto-char (point-min))
	    (setq res-numlinks
		  (if (re-search-forward "unix::nlink:\\s-+\\([0-9]+\\)" nil t)
		      (string-to-number (match-string 1)) 0))
	    ;; ... uid and gid
	    (goto-char (point-min))
	    (setq res-uid
		  (or (if (eq id-format 'integer)
			  (if (re-search-forward
			       "unix::uid:\\s-+\\([0-9]+\\)" nil t)
			      (string-to-number (match-string 1)))
			(if (re-search-forward
			     "owner::user:\\s-+\\(\\S-+\\)" nil t)
			    (match-string 1)))
		      (tramp-get-local-uid id-format)))
	    (setq res-gid
		  (or (if (eq id-format 'integer)
			  (if (re-search-forward
			       "unix::gid:\\s-+\\([0-9]+\\)" nil t)
			      (string-to-number (match-string 1)))
			(if (re-search-forward
			     "owner::group:\\s-+\\(\\S-+\\)" nil t)
			    (match-string 1)))
		      (tramp-get-local-gid id-format)))
	    ;; ... last access, modification and change time
	    (goto-char (point-min))
	    (setq res-access
		  (if (re-search-forward
		       "time::access:\\s-+\\([0-9]+\\)" nil t)
		      (seconds-to-time (string-to-number (match-string 1)))
		    '(0 0)))
	    (goto-char (point-min))
	    (setq res-mod
		  (if (re-search-forward
		       "time::modified:\\s-+\\([0-9]+\\)" nil t)
		      (seconds-to-time (string-to-number (match-string 1)))
		    '(0 0)))
	    (goto-char (point-min))
	    (setq res-change
		  (if (re-search-forward
		       "time::changed:\\s-+\\([0-9]+\\)" nil t)
		      (seconds-to-time (string-to-number (match-string 1)))
		    '(0 0)))
	    ;; ... size
	    (goto-char (point-min))
	    (setq res-size
		  (if (re-search-forward
		       "standard::size:\\s-+\\([0-9]+\\)" nil t)
		      (string-to-number (match-string 1)) 0))
	    ;; ... file mode flags
	    (goto-char (point-min))
	    (setq res-filemodes
		  (if (re-search-forward "unix::mode:\\s-+\\([0-9]+\\)" nil t)
		      (tramp-file-mode-from-int (match-string 1))
		    (if dirp "drwx------" "-rwx------")))
	    ;; ... inode and device
	    (goto-char (point-min))
	    (setq res-inode
		  (if (re-search-forward "unix::inode:\\s-+\\([0-9]+\\)" nil t)
		      (string-to-number (match-string 1))
		    (tramp-get-inode v)))
	    (goto-char (point-min))
	    (setq res-device
		  (if (re-search-forward "unix::device:\\s-+\\([0-9]+\\)" nil t)
		      (string-to-number (match-string 1))
		    (tramp-get-device v)))

	    ;; Return data gathered.
	    (list
	     ;; 0. t for directory, string (name linked to) for
	     ;; symbolic link, or nil.
	     (or dirp res-symlink-target)
	     ;; 1. Number of links to file.
	     res-numlinks
	     ;; 2. File uid.
	     res-uid
	     ;; 3. File gid.
	     res-gid
	     ;; 4. Last access time, as a list of integers.
	     ;; 5. Last modification time, likewise.
	     ;; 6. Last status change time, likewise.
	     res-access res-mod res-change
	     ;; 7. Size in bytes (-1, if number is out of range).
	     res-size
	     ;; 8. File modes.
	     res-filemodes
	     ;; 9. t if file's gid would change if file were deleted
	     ;; and recreated.
	     nil
	     ;; 10. Inode number.
	     res-inode
	     ;; 11. Device number.
	     res-device
	     )))))))
833

834 835
(defun tramp-gvfs-handle-file-directory-p (filename)
  "Like `file-directory-p' for Tramp files."
836
  (eq t (car (file-attributes filename))))
837

838 839
(defun tramp-gvfs-handle-file-executable-p (filename)
  "Like `file-executable-p' for Tramp files."
840 841 842
  (with-parsed-tramp-file-name filename nil
    (with-tramp-file-property v localname "file-executable-p"
      (tramp-check-cached-permissions v ?x))))
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857

(defun tramp-gvfs-handle-file-local-copy (filename)
  "Like `file-local-copy' for Tramp files."
  (with-parsed-tramp-file-name filename nil
    (let ((tmpfile (tramp-compat-make-temp-file filename)))
      (unless (file-exists-p filename)
	(tramp-error
	 v 'file-error
	 "Cannot make local copy of non-existing file `%s'" filename))
      (copy-file filename tmpfile t t)
      tmpfile)))

(defun tramp-gvfs-handle-file-name-all-completions (filename directory)
  "Like `file-name-all-completions' for Tramp files."
  (unless (save-match-data (string-match "/" filename))
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    (with-parsed-tramp-file-name (expand-file-name directory) nil

      (all-completions
       filename
       (mapcar
	'list
        (or
	 ;; Try cache entries for filename, filename with last
	 ;; character removed, filename with last two characters
	 ;; removed, ..., and finally the empty string - all
	 ;; concatenated to the local directory name.
         (let ((remote-file-name-inhibit-cache
		(or remote-file-name-inhibit-cache
		    tramp-completion-reread-directory-timeout)))

	   ;; This is inefficient for very long filenames, pity
	   ;; `reduce' is not available...
	   (car
	    (apply
	     'append
	     (mapcar
	      (lambda (x)
		(let ((cache-hit
		       (tramp-get-file-property
			v
			(concat localname (substring filename 0 x))
			"file-name-all-completions"
			nil)))
		  (when cache-hit (list cache-hit))))
	      ;; We cannot use a length of 0, because file properties
	      ;; for "foo" and "foo/" are identical.
	      (tramp-compat-number-sequence (length filename) 1 -1)))))

         ;; Cache expired or no matching cache entry found so we need
         ;; to perform a remote operation.
         (let ((result '("." ".."))
	       entry)
           ;; Get a list of directories and files.
	   (tramp-gvfs-send-command
	    v "gvfs-ls" (tramp-gvfs-url-file-name directory))

	   ;; Now grab the output.
           (with-temp-buffer
	     (insert-buffer-substring (tramp-get-connection-buffer v))
             (goto-char (point-max))
             (while (zerop (forward-line -1))
	       (setq entry (buffer-substring (point) (point-at-eol)))
	       (when (string-match filename entry)
		 (if (file-directory-p (expand-file-name entry directory))
		     (push (concat entry "/") result)
		   (push entry result)))))

           ;; Because the remote op went through OK we know the
           ;; directory we `cd'-ed to exists.
           (tramp-set-file-property v localname "file-exists-p" t)

           ;; Because the remote op went through OK we know every
           ;; file listed by `ls' exists.
           (mapc (lambda (entry)
		   (tramp-set-file-property
		    v (concat localname entry) "file-exists-p" t))
		 result)

           ;; Store result in the cache.
           (tramp-set-file-property
            v (concat localname filename)
	    "file-name-all-completions" result))))))))
925

926
(defun tramp-gvfs-handle-file-notify-add-watch (file-name _flags _callback)
Michael Albinus's avatar
Michael Albinus committed
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
  "Like `file-notify-add-watch' for Tramp files."
  (setq file-name (expand-file-name file-name))
  (with-parsed-tramp-file-name file-name nil
    (let ((p (start-process
	      "gvfs-monitor-file" (generate-new-buffer " *gvfs-monitor-file*")
	      "gvfs-monitor-file" (tramp-gvfs-url-file-name file-name))))
      (if (not (processp p))
	  (tramp-error
	   v 'file-notify-error "gvfs-monitor-file failed to start")
	(tramp-compat-set-process-query-on-exit-flag p nil)
	(set-process-filter p 'tramp-gvfs-file-gvfs-monitor-file-process-filter)
	(with-current-buffer (process-buffer p)
	  (setq default-directory (file-name-directory file-name)))
	p))))

(defun tramp-gvfs-file-gvfs-monitor-file-process-filter (proc string)
  "Read output from \"gvfs-monitor-file\" and add corresponding file-notify events."
  (let* ((rest-string (tramp-compat-process-get proc 'rest-string))
	 (dd (with-current-buffer (process-buffer proc) default-directory))
	 (ddu (regexp-quote (tramp-gvfs-url-file-name dd))))
    (when rest-string
      (tramp-message proc 10 "Previous string:\n%s" rest-string))
    (tramp-message proc 6 "%S\n%s" proc string)
    (setq string (concat rest-string string)
	  ;; Attribute change is returned in unused wording.
	  string (replace-regexp-in-string
		  "ATTRIB CHANGED" "ATTRIBUTE_CHANGED" string))

    (while (string-match
	    (concat "^[\n\r]*"
		    "File Monitor Event:[\n\r]+"
		    "File = \\([^\n\r]+\\)[\n\r]+"
		    "Event = \\([^[:blank:]]+\\)[\n\r]+")
	    string)
      (let ((action (intern-soft
		     (replace-regexp-in-string
		      "_" "-" (downcase (match-string 2 string)))))
	    (file (match-string 1 string)))
	(setq string (replace-match "" nil nil string))
	;; File names are returned as URL paths.  We must convert them.
	(when (string-match ddu file)
	  (setq file (replace-match dd nil nil file)))
	(while (string-match "%\\([0-9A-F]\\{2\\}\\)" file)
	  (setq file
		(replace-match
		 (char-to-string (string-to-number (match-string 1 file) 16))
		 nil nil file)))
	;; Usually, we would add an Emacs event now.  Unfortunately,
	;; `unread-command-events' does not accept several events at
	;; once.  Therefore, we apply the callback directly.
	(tramp-compat-funcall 'file-notify-callback (list proc action file))))

    ;; Save rest of the string.
    (when (zerop (length string)) (setq string nil))
    (when string (tramp-message proc 10 "Rest string:\n%s" string))
    (tramp-compat-process-put proc 'rest-string string)))

984 985
(defun tramp-gvfs-handle-file-readable-p (filename)
  "Like `file-readable-p' for Tramp files."
986 987 988
  (with-parsed-tramp-file-name filename nil
    (with-tramp-file-property v localname "file-executable-p"
      (tramp-check-cached-permissions v ?r))))
Michael Albinus's avatar
Michael Albinus committed
989

990 991
(defun tramp-gvfs-handle-file-writable-p (filename)
  "Like `file-writable-p' for Tramp files."
992 993 994 995 996 997 998
  (with-parsed-tramp-file-name filename nil
    (with-tramp-file-property v localname "file-writable-p"
      (if (file-exists-p filename)
	  (tramp-check-cached-permissions v ?w)
	;; If file doesn't exist, check if directory is writable.
	(and (file-directory-p (file-name-directory filename))
	     (file-writable-p (file-name-directory filename)))))))
999 1000 1001 1002

(defun tramp-gvfs-handle-insert-directory
  (filename switches &optional wildcard full-directory-p)
  "Like `insert-directory' for Tramp files."
1003 1004 1005 1006 1007 1008 1009 1010
  ;; gvfs-* output is hard to parse.  So we let `ls-lisp' do the job.
  (with-parsed-tramp-file-name (expand-file-name filename) nil
    (with-tramp-progress-reporter v 0 (format "Opening directory %s" filename)
      (require 'ls-lisp)
      (let (ls-lisp-use-insert-directory-program)
	(tramp-run-real-handler
	 'insert-directory
	 (list filename switches wildcard full-directory-p))))))
1011 1012 1013 1014

(defun tramp-gvfs-handle-insert-file-contents
  (filename &optional visit beg end replace)
  "Like `insert-file-contents' for Tramp files."
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  (barf-if-buffer-read-only)
  (setq filename (expand-file-name filename))
  (let (tmpfile result)
    (unwind-protect
	(if (not (file-exists-p filename))
	    ;; We don't raise a Tramp error, because it might be
	    ;; suppressed, like in `find-file-noselect-1'.
	    (signal 'file-error (list "File not found on remote host" filename))

	  (setq tmpfile (file-local-copy filename)
		result (insert-file-contents tmpfile visit beg end replace)))
      ;; Save exit.
      (when visit
	(setq buffer-file-name filename)
	(setq buffer-read-only (not (file-writable-p filename)))
	(set-visited-file-modtime)
	(set-buffer-modified-p nil))
      (when (stringp tmpfile)
	(delete-file tmpfile)))

    ;; Result.
    (list filename (cadr result))))
1037 1038 1039

(defun tramp-gvfs-handle-make-directory (dir &optional parents)
  "Like `make-directory' for Tramp files."
1040
  (with-parsed-tramp-file-name dir nil
1041 1042 1043 1044 1045 1046 1047 1048
    (unless
	(apply
	 'tramp-gvfs-send-command v "gvfs-mkdir"
	 (if parents
	     (list "-p" (tramp-gvfs-url-file-name dir))
	   (list (tramp-gvfs-url-file-name dir))))
      ;; Propagate the error.
      (tramp-error v 'file-error "Couldn't make directory %s" dir))))
1049

1050 1051 1052
(defun tramp-gvfs-handle-rename-file
  (filename newname &optional ok-if-already-exists)
  "Like `rename-file' for Tramp files."
1053 1054 1055
  (with-parsed-tramp-file-name
      (if (tramp-tramp-file-p filename) filename newname) nil

1056 1057 1058
    (when (and (not ok-if-already-exists) (file-exists-p newname))
      (tramp-error
       v 'file-already-exists "File %s already exists" newname))
1059

1060 1061 1062 1063
    (if (or (and (tramp-tramp-file-p filename)
		 (not (tramp-gvfs-file-name-p filename)))
	    (and (tramp-tramp-file-p newname)
		 (not (tramp-gvfs-file-name-p newname))))
1064

1065 1066 1067 1068
	;; We cannot move directly.
	(let ((tmpfile (tramp-compat-make-temp-file filename)))
	  (rename-file filename tmpfile t)
	  (rename-file tmpfile newname ok-if-already-exists))
1069

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
      ;; Direct move.
      (with-tramp-progress-reporter
	  v 0 (format "Renaming %s to %s" filename newname)
	(unless
	    (tramp-gvfs-send-command
	     v "gvfs-move"
	     (tramp-gvfs-url-file-name filename)
	     (tramp-gvfs-url-file-name newname))
	  ;; Propagate the error.
	  (with-current-buffer (tramp-get-buffer v)
	    (goto-char (point-min))
	    (tramp-error-with-buffer
	     nil v 'file-error
	     "Renaming failed, see buffer `%s' for details." (buffer-name)))))

      (when (file-remote-p filename)
	(with-parsed-tramp-file-name filename nil
	  (tramp-flush-file-property v (file-name-directory localname))
	  (tramp-flush-file-property v localname)))

      (when (file-remote-p newname)
	(with-parsed-tramp-file-name newname nil
	  (tramp-flush-file-property v (file-name-directory localname))
	  (tramp-flush-file-property v localname))))))
Michael Albinus's avatar
Michael Albinus committed
1094

1095
(defun tramp-gvfs-handle-write-region
1096
  (start end filename &optional _append visit _lockname confirm)
1097 1098
  "Like `write-region' for Tramp files."
  (with-parsed-tramp-file-name filename nil
1099 1100 1101 1102 1103 1104 1105 1106
    ;; XEmacs takes a coding system as the seventh argument, not `confirm'.
    (when (and (not (featurep 'xemacs)) confirm (file-exists-p filename))
      (unless (y-or-n-p (format "File %s exists; overwrite anyway? " filename))
	(tramp-error v 'file-error "File not overwritten")))

    (let ((tmpfile (tramp-compat-make-temp-file filename)))
      (write-region start end tmpfile)
      (condition-case nil
Michael Albinus's avatar
Michael Albinus committed
1107
	  (rename-file tmpfile filename 'ok-if-already-exists)
1108 1109 1110 1111 1112 1113 1114
	(error
	 (delete-file tmpfile)
	 (tramp-error
	  v 'file-error "Couldn't write region to `%s'" filename))))

    (tramp-flush-file-property v (file-name-directory localname))
    (tramp-flush-file-property v localname)
1115

1116 1117 1118 1119
    ;; Set file modification time.
    (when (or (eq visit t) (stringp visit))
      (set-visited-file-modtime (nth 5 (file-attributes filename))))

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    ;; The end.
    (when (or (eq visit t) (null visit) (stringp visit))
      (tramp-message v 0 "Wrote %s" filename))
    (run-hooks 'tramp-handle-write-region-hook)))


;; File name conversions.

(defun tramp-gvfs-url-file-name (filename)
  "Return FILENAME in URL syntax."
1130
  ;; "/" must NOT be hexlified.
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
  (let ((url-unreserved-chars (append '(?/) url-unreserved-chars))
	result)
    (setq
     result
     (url-recreate-url
      (if (tramp-tramp-file-p filename)
	  (with-parsed-tramp-file-name filename nil
	    (when (and user (string-match tramp-user-with-domain-regexp user))
	      (setq user
		    (concat (match-string 2 user) ";" (match-string 1 user))))
	    (url-parse-make-urlobj
	     method (url-hexify-string user) nil
	     (tramp-file-name-real-host v) (tramp-file-name-port v)
	     (url-hexify-string localname) nil nil t))
	(url-parse-make-urlobj
	 "file" nil nil nil nil
	 (url-hexify-string (file-truename filename)) nil nil t))))
    (when (tramp-tramp-file-p filename)
      (with-parsed-tramp-file-name filename nil
	(tramp-message v 10 "remote file `%s' is URL `%s'" filename result)))
    result))
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

(defun tramp-gvfs-object-path (filename)
  "Create a D-Bus object path from FILENAME."
  (expand-file-name (dbus-escape-as-identifier filename) tramp-gvfs-path-tramp))

(defun tramp-gvfs-file-name (object-path)
  "Retrieve file name from D-Bus OBJECT-PATH."
  (dbus-unescape-from-identifier
   (replace-regexp-in-string "^.*/\\([^/]+\\)$" "\\1" object-path)))

(defun tramp-bluez-address (device)
  "Return bluetooth device address from a given bluetooth DEVICE name."
  (when (stringp device)
    (if (string-match tramp-ipv6-regexp device)
	(match-string 0 device)
      (cadr (assoc device (tramp-bluez-list-devices))))))

(defun tramp-bluez-device (address)
  "Return bluetooth device name from a given bluetooth device ADDRESS.
ADDRESS can have the form \"xx:xx:xx:xx:xx:xx\" or \"[xx:xx:xx:xx:xx:xx]\"."
  (when (stringp address)
    (while (string-match "[][]" address)
      (setq address (replace-match "" t t address)))
    (let (result)
      (dolist (item (tramp-bluez-list-devices) result)
	(when (string-match address (cadr item))
	  (setq result (car item)))))))


;; D-Bus GVFS functions.

(defun tramp-gvfs-handler-askpassword (message user domain flags)
  "Implementation for the \"org.gtk.vfs.MountOperation.askPassword\" method."
  (let* ((filename
	  (tramp-gvfs-file-name (dbus-event-path-name last-input-event)))
	 (pw-prompt
	  (format
	   "%s for %s "
	   (if (string-match "\\([pP]assword\\|[pP]assphrase\\)" message)
	       (capitalize (match-string 1 message))
	     "Password")
	   filename))
	 password)

    (condition-case nil
	(with-parsed-tramp-file-name filename l
	  (when (and (zerop (length user))
		     (not
		      (zerop (logand flags tramp-gvfs-password-need-username))))
	    (setq user (read-string "User name: ")))
	  (when (and (zerop (length domain))
		     (not (zerop (logand flags tramp-gvfs-password-need-domain))))
	    (setq domain (read-string "Domain name: ")))

	  (tramp-message l 6 "%S %S %S %d" message user domain flags)
	  (setq tramp-current-method l-method
		tramp-current-user user
		tramp-current-host l-host
		password (tramp-read-passwd
			  (tramp-get-connection-process l) pw-prompt))

	  ;; Return result.
	  (if (stringp password)
	      (list
	       t ;; password handled.
	       nil ;; no abort of D-Bus.
	       password
	       (tramp-file-name-real-user l)
	       domain
	       nil ;; not anonymous.
	       0) ;; no password save.
	    ;; No password provided.
	    (list nil t "" (tramp-file-name-real-user l) domain nil 0)))

      ;; When QUIT is raised, we shall return this information to D-Bus.
      (quit (list nil t "" "" "" nil 0)))))

(defun tramp-gvfs-handler-askquestion (message choices)
  "Implementation for the \"org.gtk.vfs.MountOperation.askQuestion\" method."
  (save-window-excursion
    (let ((enable-recursive-minibuffers t)
	  choice)

      (condition-case nil
	  (with-parsed-tramp-file-name
	      (tramp-gvfs-file-name (dbus-event-path-name last-input-event)) nil
	    (tramp-message v 6 "%S %S" message choices)

	    ;; In theory, there can be several choices.  Until now,
	    ;; there is only the question whether to accept an unknown
	    ;; host signature.
	    (with-temp-buffer
1244
	      ;; Preserve message for `progress-reporter'.
1245
	      (tramp-compat-with-temp-message ""
1246 1247 1248 1249
		(insert message)
		(pop-to-buffer (current-buffer))
		(setq choice (if (yes-or-no-p (concat (car choices) " ")) 0 1))
		(tramp-message v 6 "%d" choice)))
1250

1251 1252
	    ;; When the choice is "no", we set a dummy fuse-mountpoint
	    ;; in order to leave the timeout.
1253
	    (unless (zerop choice)
1254
	      (tramp-set-file-property v "/" "fuse-mountpoint" "/"))
1255 1256 1257 1258 1259 1260

	    (list
	     t ;; handled.
	     nil ;; no abort of D-Bus.
	     choice))

1261 1262
	;; When QUIT is raised, we shall return this information to D-Bus.
	(quit (list nil t 0))))))
1263 1264 1265 1266 1267

(defun tramp-gvfs-handler-mounted-unmounted (mount-info)
  "Signal handler for the \"org.gtk.vfs.MountTracker.mounted\" and
\"org.gtk.vfs.MountTracker.unmounted\" signals."
  (ignore-errors
1268 1269 1270
    (let ((signal-name (dbus-event-member-name last-input-event))
	  (elt mount-info))
      ;; Jump over the first elements of the mount info. Since there
Paul Eggert's avatar
Paul Eggert committed
1271
      ;; were changes in the entries, we cannot access dedicated
1272 1273
      ;; elements.
      (while (stringp (car elt)) (setq elt (cdr elt)))
1274
      (let* ((fuse-mountpoint (tramp-gvfs-dbus-byte-array-to-string (cadr elt)))
1275
	     (mount-spec (caddr elt))
1276 1277 1278
	     (default-location (tramp-gvfs-dbus-byte-array-to-string
				(cadddr elt)))
	     (method (tramp-gvfs-dbus-byte-array-to-string
1279
		      (cadr (assoc "type" (cadr mount-spec)))))
1280
	     (user (tramp-gvfs-dbus-byte-array-to-string
1281
		    (cadr (assoc "user" (cadr mount-spec)))))
1282
	     (domain (tramp-gvfs-dbus-byte-array-to-string
1283
		      (cadr (assoc "domain" (cadr mount-spec)))))
1284
	     (host (tramp-gvfs-dbus-byte-array-to-string
1285 1286
		    (cadr (or (assoc "host" (cadr mount-spec))
			      (assoc "server" (cadr mount-spec))))))
1287
	     (port (tramp-gvfs-dbus-byte-array-to-string
1288
		    (cadr (assoc "port" (cadr mount-spec)))))
1289
	     (ssl (tramp-gvfs-dbus-byte-array-to-string
1290
		   (cadr (assoc "ssl" (cadr mount-spec)))))
1291 1292 1293
	     (prefix (concat (tramp-gvfs-dbus-byte-array-to-string
			      (car mount-spec))
			     (tramp-gvfs-dbus-byte-array-to-string
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
			      (cadr (assoc "share" (cadr mount-spec)))))))
	(when (string-match "^smb" method)
	  (setq method "smb"))
	(when (string-equal "obex" method)
	  (setq host (tramp-bluez-device host)))
	(when (and (string-equal "dav" method) (string-equal "true" ssl))
	  (setq method "davs"))
	(unless (zerop (length domain))
	  (setq user (concat user tramp-prefix-domain-format domain)))
	(unless (zerop (length port))
	  (setq host (concat host tramp-prefix-port-format port)))
	(with-parsed-tramp-file-name
	    (tramp-make-tramp-file-name method user host "") nil
	  (tramp-message
	   v 6 "%s %s"
	   signal-name (tramp-gvfs-stringify-dbus-message mount-info))
	  (tramp-set-file-property v "/" "list-mounts" 'undef)
1311
	  (if (string-equal (downcase signal-name) "unmounted")
1312 1313 1314 1315 1316 1317 1318
	      (tramp-set-file-property v "/" "fuse-mountpoint" nil)
	    ;; Set prefix, mountpoint and location.
	    (unless (string-equal prefix "/")
	      (tramp-set-file-property v "/" "prefix" prefix))
	    (tramp-set-file-property v "/" "fuse-mountpoint" fuse-mountpoint)
	    (tramp-set-file-property
	     v "/" "default-location" default-location)))))))
1319

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
(when tramp-gvfs-enabled
  (dbus-register-signal
   :session nil tramp-gvfs-path-mounttracker
   tramp-gvfs-interface-mounttracker "mounted"
   'tramp-gvfs-handler-mounted-unmounted)
  (dbus-register-signal
   :session nil tramp-gvfs-path-mounttracker
   tramp-gvfs-interface-mounttracker "Mounted"
   'tramp-gvfs-handler-mounted-unmounted)

  (dbus-register-signal
   :session nil tramp-gvfs-path-mounttracker
   tramp-gvfs-interface-mounttracker "unmounted"
   'tramp-gvfs-handler-mounted-unmounted)
  (dbus-register-signal
   :session nil tramp-gvfs-path-mounttracker
   tramp-gvfs-interface-mounttracker "Unmounted"
   'tramp-gvfs-handler-mounted-unmounted))
1338 1339 1340

(defun tramp-gvfs-connection-mounted-p (vec)
  "Check, whether the location is already mounted."
1341 1342 1343 1344 1345
  (or
   (tramp-get-file-property vec "/" "fuse-mountpoint" nil)
   (catch 'mounted
     (dolist
	 (elt
1346
	  (with-tramp-file-property vec "/" "list-mounts"
1347 1348
	    (with-tramp-dbus-call-method vec t
	      :session tramp-gvfs-service-daemon tramp-gvfs-path-mounttracker
1349
	      tramp-gvfs-interface-mounttracker tramp-gvfs-listmounts))
1350
	  nil)
1351
       ;; Jump over the first elements of the mount info. Since there
Paul Eggert's avatar
Paul Eggert committed
1352
       ;; were changes in the entries, we cannot access dedicated
1353 1354
       ;; elements.
       (while (stringp (car elt)) (setq elt (cdr elt)))
Michael Albinus's avatar