gdbusproxy.c 110 KB
Newer Older
1 2
/* GDBus - GLib D-Bus Library
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4 5 6 7
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9 10 11 12 13 14 15
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
16
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 18 19 20 21 22 23
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

#include "config.h"

#include <stdlib.h>
David Zeuthen's avatar
David Zeuthen committed
24 25
#include <string.h>

26 27 28 29 30 31 32 33 34
#include "gdbusutils.h"
#include "gdbusproxy.h"
#include "gioenumtypes.h"
#include "gdbusconnection.h"
#include "gdbuserror.h"
#include "gdbusprivate.h"
#include "ginitable.h"
#include "gasyncinitable.h"
#include "gioerror.h"
35
#include "gtask.h"
36
#include "gcancellable.h"
37
#include "gdbusinterface.h"
38
#include "gasyncresult.h"
39

40 41 42 43
#ifdef G_OS_UNIX
#include "gunixfdlist.h"
#endif

David Zeuthen's avatar
David Zeuthen committed
44 45
#include "glibintl.h"

46 47
/**
 * SECTION:gdbusproxy
48
 * @short_description: Client-side D-Bus interface proxy
David Zeuthen's avatar
David Zeuthen committed
49
 * @include: gio/gio.h
50 51
 *
 * #GDBusProxy is a base class used for proxies to access a D-Bus
52 53
 * interface on a remote object. A #GDBusProxy can be constructed for
 * both well-known and unique names.
54
 *
55
 * By default, #GDBusProxy will cache all properties (and listen to
56
 * changes) of the remote object, and proxy all signals that get
57
 * emitted. This behaviour can be changed by passing suitable
58 59 60 61
 * #GDBusProxyFlags when the proxy is created. If the proxy is for a
 * well-known name, the property cache is flushed when the name owner
 * vanishes and reloaded when a name owner appears.
 *
62
 * The unique name owner of the proxy's name is tracked and can be read from
63 64
 * #GDBusProxy:g-name-owner. Connect to the #GObject::notify signal to
 * get notified of changes. Additionally, only signals and property
65 66 67 68 69 70 71
 * changes emitted from the current name owner are considered and
 * calls are always sent to the current name owner. This avoids a
 * number of race conditions when the name is lost by one owner and
 * claimed by another. However, if no name owner currently exists,
 * then calls will be sent to the well-known name which may result in
 * the message bus launching an owner (unless
 * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START is set).
72
 *
73
 * The generic #GDBusProxy::g-properties-changed and
74 75 76 77 78
 * #GDBusProxy::g-signal signals are not very convenient to work with.
 * Therefore, the recommended way of working with proxies is to subclass
 * #GDBusProxy, and have more natural properties and signals in your derived
 * class. This [example][gdbus-example-gdbus-codegen] shows how this can
 * easily be done using the [gdbus-codegen][gdbus-codegen] tool.
79
 *
80
 * A #GDBusProxy instance can be used from multiple threads but note
81
 * that all signals (e.g. #GDBusProxy::g-signal, #GDBusProxy::g-properties-changed
82
 * and #GObject::notify) are emitted in the
83
 * [thread-default main context][g-main-context-push-thread-default]
84 85
 * of the thread where the instance was constructed.
 *
86 87
 * An example using a proxy for a well-known name can be found in
 * [gdbus-example-watch-proxy.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-watch-proxy.c)
88 89
 */

90 91 92
/* lock protecting the mutable properties: name_owner, timeout_msec,
 * expected_interface, and the properties hash table
 */
93 94
G_LOCK_DEFINE_STATIC (properties_lock);

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
/* ---------------------------------------------------------------------------------------------------- */

G_LOCK_DEFINE_STATIC (signal_subscription_lock);

typedef struct
{
  volatile gint ref_count;
  GDBusProxy *proxy;
} SignalSubscriptionData;

static SignalSubscriptionData *
signal_subscription_ref (SignalSubscriptionData *data)
{
  g_atomic_int_inc (&data->ref_count);
  return data;
}

static void
signal_subscription_unref (SignalSubscriptionData *data)
{
  if (g_atomic_int_dec_and_test (&data->ref_count))
    {
      g_slice_free (SignalSubscriptionData, data);
    }
}

/* ---------------------------------------------------------------------------------------------------- */

123 124
struct _GDBusProxyPrivate
{
125
  GBusType bus_type;
126
  GDBusProxyFlags flags;
127
  GDBusConnection *connection;
128 129

  gchar *name;
130
  /* mutable, protected by properties_lock */
131
  gchar *name_owner;
132 133
  gchar *object_path;
  gchar *interface_name;
134
  /* mutable, protected by properties_lock */
135 136
  gint timeout_msec;

137 138 139 140
  guint name_owner_changed_subscription_id;

  GCancellable *get_all_cancellable;

141
  /* gchar* -> GVariant*, protected by properties_lock */
142 143
  GHashTable *properties;

144
  /* mutable, protected by properties_lock */
145 146
  GDBusInterfaceInfo *expected_interface;

147 148
  guint properties_changed_subscription_id;
  guint signals_subscription_id;
149 150

  gboolean initialized;
151

152
  /* mutable, protected by properties_lock */
153
  GDBusObject *object;
154 155

  SignalSubscriptionData *signal_subscription_data;
156 157 158 159 160 161
};

enum
{
  PROP_0,
  PROP_G_CONNECTION,
162 163 164
  PROP_G_BUS_TYPE,
  PROP_G_NAME,
  PROP_G_NAME_OWNER,
165 166 167 168 169 170 171 172 173 174 175 176 177 178
  PROP_G_FLAGS,
  PROP_G_OBJECT_PATH,
  PROP_G_INTERFACE_NAME,
  PROP_G_DEFAULT_TIMEOUT,
  PROP_G_INTERFACE_INFO
};

enum
{
  PROPERTIES_CHANGED_SIGNAL,
  SIGNAL_SIGNAL,
  LAST_SIGNAL,
};

179
static guint signals[LAST_SIGNAL] = {0};
180

181
static void dbus_interface_iface_init (GDBusInterfaceIface *dbus_interface_iface);
182 183 184 185
static void initable_iface_init       (GInitableIface *initable_iface);
static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);

G_DEFINE_TYPE_WITH_CODE (GDBusProxy, g_dbus_proxy, G_TYPE_OBJECT,
186
                         G_ADD_PRIVATE (GDBusProxy)
187
                         G_IMPLEMENT_INTERFACE (G_TYPE_DBUS_INTERFACE, dbus_interface_iface_init)
188
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
189
                         G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init))
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
static void
g_dbus_proxy_dispose (GObject *object)
{
  GDBusProxy *proxy = G_DBUS_PROXY (object);
  G_LOCK (signal_subscription_lock);
  if (proxy->priv->signal_subscription_data != NULL)
    {
      proxy->priv->signal_subscription_data->proxy = NULL;
      signal_subscription_unref (proxy->priv->signal_subscription_data);
      proxy->priv->signal_subscription_data = NULL;
    }
  G_UNLOCK (signal_subscription_lock);

  G_OBJECT_CLASS (g_dbus_proxy_parent_class)->dispose (object);
}

207 208 209 210 211
static void
g_dbus_proxy_finalize (GObject *object)
{
  GDBusProxy *proxy = G_DBUS_PROXY (object);

212 213 214 215 216 217
  g_warn_if_fail (proxy->priv->get_all_cancellable == NULL);

  if (proxy->priv->name_owner_changed_subscription_id > 0)
    g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
                                          proxy->priv->name_owner_changed_subscription_id);

218
  if (proxy->priv->properties_changed_subscription_id > 0)
Matthias Clasen's avatar
Matthias Clasen committed
219
    g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
220
                                          proxy->priv->properties_changed_subscription_id);
221

222
  if (proxy->priv->signals_subscription_id > 0)
Matthias Clasen's avatar
Matthias Clasen committed
223
    g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
224
                                          proxy->priv->signals_subscription_id);
225

226 227
  if (proxy->priv->connection != NULL)
    g_object_unref (proxy->priv->connection);
228 229
  g_free (proxy->priv->name);
  g_free (proxy->priv->name_owner);
230 231 232 233 234 235
  g_free (proxy->priv->object_path);
  g_free (proxy->priv->interface_name);
  if (proxy->priv->properties != NULL)
    g_hash_table_unref (proxy->priv->properties);

  if (proxy->priv->expected_interface != NULL)
236 237 238 239
    {
      g_dbus_interface_info_cache_release (proxy->priv->expected_interface);
      g_dbus_interface_info_unref (proxy->priv->expected_interface);
    }
240

241 242 243
  if (proxy->priv->object != NULL)
    g_object_remove_weak_pointer (G_OBJECT (proxy->priv->object), (gpointer *) &proxy->priv->object);

Matthias Clasen's avatar
Matthias Clasen committed
244
  G_OBJECT_CLASS (g_dbus_proxy_parent_class)->finalize (object);
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
}

static void
g_dbus_proxy_get_property (GObject    *object,
                           guint       prop_id,
                           GValue     *value,
                           GParamSpec *pspec)
{
  GDBusProxy *proxy = G_DBUS_PROXY (object);

  switch (prop_id)
    {
    case PROP_G_CONNECTION:
      g_value_set_object (value, proxy->priv->connection);
      break;

    case PROP_G_FLAGS:
      g_value_set_flags (value, proxy->priv->flags);
      break;

265 266 267 268 269
    case PROP_G_NAME:
      g_value_set_string (value, proxy->priv->name);
      break;

    case PROP_G_NAME_OWNER:
270
      g_value_take_string (value, g_dbus_proxy_get_name_owner (proxy));
271 272 273 274 275 276 277 278 279 280 281
      break;

    case PROP_G_OBJECT_PATH:
      g_value_set_string (value, proxy->priv->object_path);
      break;

    case PROP_G_INTERFACE_NAME:
      g_value_set_string (value, proxy->priv->interface_name);
      break;

    case PROP_G_DEFAULT_TIMEOUT:
282
      g_value_set_int (value, g_dbus_proxy_get_default_timeout (proxy));
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
      break;

    case PROP_G_INTERFACE_INFO:
      g_value_set_boxed (value, g_dbus_proxy_get_interface_info (proxy));
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
g_dbus_proxy_set_property (GObject      *object,
                           guint         prop_id,
                           const GValue *value,
                           GParamSpec   *pspec)
{
  GDBusProxy *proxy = G_DBUS_PROXY (object);

  switch (prop_id)
    {
    case PROP_G_CONNECTION:
      proxy->priv->connection = g_value_dup_object (value);
      break;

    case PROP_G_FLAGS:
      proxy->priv->flags = g_value_get_flags (value);
      break;

313 314
    case PROP_G_NAME:
      proxy->priv->name = g_value_dup_string (value);
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
      break;

    case PROP_G_OBJECT_PATH:
      proxy->priv->object_path = g_value_dup_string (value);
      break;

    case PROP_G_INTERFACE_NAME:
      proxy->priv->interface_name = g_value_dup_string (value);
      break;

    case PROP_G_DEFAULT_TIMEOUT:
      g_dbus_proxy_set_default_timeout (proxy, g_value_get_int (value));
      break;

    case PROP_G_INTERFACE_INFO:
      g_dbus_proxy_set_interface_info (proxy, g_value_get_boxed (value));
      break;

333 334 335 336
    case PROP_G_BUS_TYPE:
      proxy->priv->bus_type = g_value_get_enum (value);
      break;

337 338 339 340 341 342 343 344 345 346 347
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
g_dbus_proxy_class_init (GDBusProxyClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

348
  gobject_class->dispose      = g_dbus_proxy_dispose;
349 350 351 352 353 354 355 356 357 358 359
  gobject_class->finalize     = g_dbus_proxy_finalize;
  gobject_class->set_property = g_dbus_proxy_set_property;
  gobject_class->get_property = g_dbus_proxy_get_property;

  /* Note that all property names are prefixed to avoid collisions with D-Bus property names
   * in derived classes */

  /**
   * GDBusProxy:g-interface-info:
   *
   * Ensure that interactions with this proxy conform to the given
360 361
   * interface. This is mainly to ensure that malformed data received
   * from the other peer is ignored. The given #GDBusInterfaceInfo is
362
   * said to be the "expected interface".
363 364
   *
   * The checks performed are:
365 366 367 368 369 370 371
   * - When completing a method call, if the type signature of
   *   the reply message isn't what's expected, the reply is
   *   discarded and the #GError is set to %G_IO_ERROR_INVALID_ARGUMENT.
   *
   * - Received signals that have a type signature mismatch are dropped and
   *   a warning is logged via g_warning().
   *
372 373
   * - Properties received via the initial `GetAll()` call or via the 
   *   `::PropertiesChanged` signal (on the
374 375 376 377
   *   [org.freedesktop.DBus.Properties](http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties)
   *   interface) or set using g_dbus_proxy_set_cached_property()
   *   with a type signature mismatch are ignored and a warning is
   *   logged via g_warning().
378
   *
379 380 381 382
   * Note that these checks are never done on methods, signals and
   * properties that are not referenced in the given
   * #GDBusInterfaceInfo, since extending a D-Bus interface on the
   * service-side is not considered an ABI break.
383 384
   *
   * Since: 2.26
385 386 387 388
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_INTERFACE_INFO,
                                   g_param_spec_boxed ("g-interface-info",
Matthias Clasen's avatar
Matthias Clasen committed
389 390
                                                       P_("Interface Information"),
                                                       P_("Interface Information"),
391 392 393 394 395 396 397 398 399 400 401
                                                       G_TYPE_DBUS_INTERFACE_INFO,
                                                       G_PARAM_READABLE |
                                                       G_PARAM_WRITABLE |
                                                       G_PARAM_STATIC_NAME |
                                                       G_PARAM_STATIC_BLURB |
                                                       G_PARAM_STATIC_NICK));

  /**
   * GDBusProxy:g-connection:
   *
   * The #GDBusConnection the proxy is for.
402 403
   *
   * Since: 2.26
404 405 406 407
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_CONNECTION,
                                   g_param_spec_object ("g-connection",
Matthias Clasen's avatar
Matthias Clasen committed
408 409
                                                        P_("g-connection"),
                                                        P_("The connection the proxy is for"),
410 411 412 413 414 415 416 417
                                                        G_TYPE_DBUS_CONNECTION,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  /**
   * GDBusProxy:g-bus-type:
   *
   * If this property is not %G_BUS_TYPE_NONE, then
   * #GDBusProxy:g-connection must be %NULL and will be set to the
   * #GDBusConnection obtained by calling g_bus_get() with the value
   * of this property.
   *
   * Since: 2.26
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_BUS_TYPE,
                                   g_param_spec_enum ("g-bus-type",
                                                      P_("Bus Type"),
                                                      P_("The bus to connect to, if any"),
                                                      G_TYPE_BUS_TYPE,
                                                      G_BUS_TYPE_NONE,
                                                      G_PARAM_WRITABLE |
                                                      G_PARAM_CONSTRUCT_ONLY |
                                                      G_PARAM_STATIC_NAME |
                                                      G_PARAM_STATIC_BLURB |
                                                      G_PARAM_STATIC_NICK));

441 442 443 444
  /**
   * GDBusProxy:g-flags:
   *
   * Flags from the #GDBusProxyFlags enumeration.
445 446
   *
   * Since: 2.26
447 448 449 450
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_FLAGS,
                                   g_param_spec_flags ("g-flags",
Matthias Clasen's avatar
Matthias Clasen committed
451 452
                                                       P_("g-flags"),
                                                       P_("Flags for the proxy"),
453 454 455 456 457 458 459 460 461 462
                                                       G_TYPE_DBUS_PROXY_FLAGS,
                                                       G_DBUS_PROXY_FLAGS_NONE,
                                                       G_PARAM_READABLE |
                                                       G_PARAM_WRITABLE |
                                                       G_PARAM_CONSTRUCT_ONLY |
                                                       G_PARAM_STATIC_NAME |
                                                       G_PARAM_STATIC_BLURB |
                                                       G_PARAM_STATIC_NICK));

  /**
463
   * GDBusProxy:g-name:
464
   *
465
   * The well-known or unique name that the proxy is for.
466 467
   *
   * Since: 2.26
468 469
   */
  g_object_class_install_property (gobject_class,
470 471 472 473
                                   PROP_G_NAME,
                                   g_param_spec_string ("g-name",
                                                        P_("g-name"),
                                                        P_("The well-known or unique name that the proxy is for"),
474 475 476 477 478 479 480 481
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

482 483 484
  /**
   * GDBusProxy:g-name-owner:
   *
485
   * The unique name that owns #GDBusProxy:g-name or %NULL if no-one
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
   * currently owns that name. You may connect to #GObject::notify signal to
   * track changes to this property.
   *
   * Since: 2.26
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_NAME_OWNER,
                                   g_param_spec_string ("g-name-owner",
                                                        P_("g-name-owner"),
                                                        P_("The unique name for the owner"),
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

502 503 504 505
  /**
   * GDBusProxy:g-object-path:
   *
   * The object path the proxy is for.
506 507
   *
   * Since: 2.26
508 509 510 511
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_OBJECT_PATH,
                                   g_param_spec_string ("g-object-path",
Matthias Clasen's avatar
Matthias Clasen committed
512 513
                                                        P_("g-object-path"),
                                                        P_("The object path the proxy is for"),
514 515 516 517 518 519 520 521 522 523 524 525
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusProxy:g-interface-name:
   *
   * The D-Bus interface name the proxy is for.
526 527
   *
   * Since: 2.26
528 529 530 531
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_INTERFACE_NAME,
                                   g_param_spec_string ("g-interface-name",
Matthias Clasen's avatar
Matthias Clasen committed
532 533
                                                        P_("g-interface-name"),
                                                        P_("The D-Bus interface name the proxy is for"),
534 535 536 537 538 539 540 541 542 543 544 545
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusProxy:g-default-timeout:
   *
   * The timeout to use if -1 (specifying default timeout) is passed
546 547
   * as @timeout_msec in the g_dbus_proxy_call() and
   * g_dbus_proxy_call_sync() functions.
548 549 550 551 552
   *
   * This allows applications to set a proxy-wide timeout for all
   * remote method invocations on the proxy. If this property is -1,
   * the default timeout (typically 25 seconds) is used. If set to
   * %G_MAXINT, then no timeout is used.
553 554
   *
   * Since: 2.26
555 556 557 558
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_DEFAULT_TIMEOUT,
                                   g_param_spec_int ("g-default-timeout",
Matthias Clasen's avatar
Matthias Clasen committed
559 560
                                                     P_("Default Timeout"),
                                                     P_("Timeout for remote method invocation"),
561 562 563 564 565 566 567 568 569 570 571 572 573
                                                     -1,
                                                     G_MAXINT,
                                                     -1,
                                                     G_PARAM_READABLE |
                                                     G_PARAM_WRITABLE |
                                                     G_PARAM_CONSTRUCT |
                                                     G_PARAM_STATIC_NAME |
                                                     G_PARAM_STATIC_BLURB |
                                                     G_PARAM_STATIC_NICK));

  /**
   * GDBusProxy::g-properties-changed:
   * @proxy: The #GDBusProxy emitting the signal.
574
   * @changed_properties: A #GVariant containing the properties that changed (type: `a{sv}`)
575
   * @invalidated_properties: A %NULL terminated array of properties that was invalidated
576
   *
577
   * Emitted when one or more D-Bus properties on @proxy changes. The
578 579 580
   * local cache has already been updated when this signal fires. Note
   * that both @changed_properties and @invalidated_properties are
   * guaranteed to never be %NULL (either may be empty though).
581
   *
582 583 584 585
   * If the proxy has the flag
   * %G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES set, then
   * @invalidated_properties will always be empty.
   *
586
   * This signal corresponds to the
587 588
   * `PropertiesChanged` D-Bus signal on the
   * `org.freedesktop.DBus.Properties` interface.
589 590
   *
   * Since: 2.26
591
   */
592
  signals[PROPERTIES_CHANGED_SIGNAL] = g_signal_new (I_("g-properties-changed"),
593
                                                     G_TYPE_DBUS_PROXY,
594
                                                     G_SIGNAL_RUN_LAST | G_SIGNAL_MUST_COLLECT,
595 596 597
                                                     G_STRUCT_OFFSET (GDBusProxyClass, g_properties_changed),
                                                     NULL,
                                                     NULL,
598
                                                     NULL,
599
                                                     G_TYPE_NONE,
600 601
                                                     2,
                                                     G_TYPE_VARIANT,
602
                                                     G_TYPE_STRV | G_SIGNAL_TYPE_STATIC_SCOPE);
603 604 605 606

  /**
   * GDBusProxy::g-signal:
   * @proxy: The #GDBusProxy emitting the signal.
607
   * @sender_name: (nullable): The sender of the signal or %NULL if the connection is not a bus connection.
608 609 610 611
   * @signal_name: The name of the signal.
   * @parameters: A #GVariant tuple with parameters for the signal.
   *
   * Emitted when a signal from the remote object and interface that @proxy is for, has been received.
612 613 614
   *
   * Since: 2.26
   */
615
  signals[SIGNAL_SIGNAL] = g_signal_new (I_("g-signal"),
616
                                         G_TYPE_DBUS_PROXY,
617
                                         G_SIGNAL_RUN_LAST | G_SIGNAL_MUST_COLLECT,
618 619 620
                                         G_STRUCT_OFFSET (GDBusProxyClass, g_signal),
                                         NULL,
                                         NULL,
621
                                         NULL,
622 623 624 625 626 627 628 629 630 631 632
                                         G_TYPE_NONE,
                                         3,
                                         G_TYPE_STRING,
                                         G_TYPE_STRING,
                                         G_TYPE_VARIANT);

}

static void
g_dbus_proxy_init (GDBusProxy *proxy)
{
633
  proxy->priv = g_dbus_proxy_get_instance_private (proxy);
634 635 636
  proxy->priv->signal_subscription_data = g_slice_new0 (SignalSubscriptionData);
  proxy->priv->signal_subscription_data->ref_count = 1;
  proxy->priv->signal_subscription_data->proxy = proxy;
637 638 639 640
  proxy->priv->properties = g_hash_table_new_full (g_str_hash,
                                                   g_str_equal,
                                                   g_free,
                                                   (GDestroyNotify) g_variant_unref);
641 642 643 644
}

/* ---------------------------------------------------------------------------------------------------- */

645 646 647 648 649 650 651
static gint
property_name_sort_func (const gchar **a,
                         const gchar **b)
{
  return g_strcmp0 (*a, *b);
}

652 653 654 655 656 657
/**
 * g_dbus_proxy_get_cached_property_names:
 * @proxy: A #GDBusProxy.
 *
 * Gets the names of all cached properties on @proxy.
 *
658 659
 * Returns: (transfer full) (nullable) (array zero-terminated=1): A
 *          %NULL-terminated array of strings or %NULL if
660 661
 *          @proxy has no cached properties. Free the returned array with
 *          g_strfreev().
662 663
 *
 * Since: 2.26
664 665
 */
gchar **
666
g_dbus_proxy_get_cached_property_names (GDBusProxy  *proxy)
667 668 669 670 671 672 673 674
{
  gchar **names;
  GPtrArray *p;
  GHashTableIter iter;
  const gchar *key;

  g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);

675 676
  G_LOCK (properties_lock);

677
  names = NULL;
678 679
  if (g_hash_table_size (proxy->priv->properties) == 0)
    goto out;
680 681 682 683 684

  p = g_ptr_array_new ();

  g_hash_table_iter_init (&iter, proxy->priv->properties);
  while (g_hash_table_iter_next (&iter, (gpointer) &key, NULL))
Matthias Clasen's avatar
Matthias Clasen committed
685
    g_ptr_array_add (p, g_strdup (key));
686
  g_ptr_array_sort (p, (GCompareFunc) property_name_sort_func);
687 688 689 690 691
  g_ptr_array_add (p, NULL);

  names = (gchar **) g_ptr_array_free (p, FALSE);

 out:
692
  G_UNLOCK (properties_lock);
693 694 695
  return names;
}

696 697 698
/* properties_lock must be held for as long as you will keep the
 * returned value
 */
699
static const GDBusPropertyInfo *
700 701
lookup_property_info (GDBusProxy  *proxy,
                      const gchar *property_name)
702
{
703
  const GDBusPropertyInfo *info = NULL;
704 705

  if (proxy->priv->expected_interface == NULL)
706
    goto out;
707 708 709

  info = g_dbus_interface_info_lookup_property (proxy->priv->expected_interface, property_name);

710
 out:
711 712 713
  return info;
}

714 715 716 717 718
/**
 * g_dbus_proxy_get_cached_property:
 * @proxy: A #GDBusProxy.
 * @property_name: Property name.
 *
719 720
 * Looks up the value for a property from the cache. This call does no
 * blocking IO.
721
 *
722
 * If @proxy has an expected interface (see
723 724
 * #GDBusProxy:g-interface-info) and @property_name is referenced by
 * it, then @value is checked against the type of the property.
725
 *
726 727 728
 * Returns: (transfer full) (nullable): A reference to the #GVariant instance
 *    that holds the value for @property_name or %NULL if the value is not in
 *    the cache. The returned reference must be freed with g_variant_unref().
729 730
 *
 * Since: 2.26
731 732
 */
GVariant *
Matthias Clasen's avatar
Matthias Clasen committed
733
g_dbus_proxy_get_cached_property (GDBusProxy   *proxy,
734
                                  const gchar  *property_name)
735
{
736
  const GDBusPropertyInfo *info;
737 738 739 740 741
  GVariant *value;

  g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
  g_return_val_if_fail (property_name != NULL, NULL);

742 743
  G_LOCK (properties_lock);

744 745
  value = g_hash_table_lookup (proxy->priv->properties, property_name);
  if (value == NULL)
746 747 748 749
    goto out;

  info = lookup_property_info (proxy, property_name);
  if (info != NULL)
750
    {
751 752 753 754 755 756 757 758 759 760 761
      const gchar *type_string = g_variant_get_type_string (value);
      if (g_strcmp0 (type_string, info->signature) != 0)
        {
          g_warning ("Trying to get property %s with type %s but according to the expected "
                     "interface the type is %s",
                     property_name,
                     type_string,
                     info->signature);
          value = NULL;
          goto out;
        }
762 763 764 765 766
    }

  g_variant_ref (value);

 out:
767
  G_UNLOCK (properties_lock);
768 769 770
  return value;
}

771 772 773 774
/**
 * g_dbus_proxy_set_cached_property:
 * @proxy: A #GDBusProxy
 * @property_name: Property name.
775
 * @value: (nullable): Value for the property or %NULL to remove it from the cache.
776 777 778 779 780 781 782 783
 *
 * If @value is not %NULL, sets the cached value for the property with
 * name @property_name to the value in @value.
 *
 * If @value is %NULL, then the cached value is removed from the
 * property cache.
 *
 * If @proxy has an expected interface (see
784 785
 * #GDBusProxy:g-interface-info) and @property_name is referenced by
 * it, then @value is checked against the type of the property.
786 787 788
 *
 * If the @value #GVariant is floating, it is consumed. This allows
 * convenient 'inline' use of g_variant_new(), e.g.
789
 * |[<!-- language="C" -->
790 791 792 793 794 795 796
 *  g_dbus_proxy_set_cached_property (proxy,
 *                                    "SomeProperty",
 *                                    g_variant_new ("(si)",
 *                                                  "A String",
 *                                                  42));
 * ]|
 *
797 798 799 800 801 802
 * Normally you will not need to use this method since @proxy
 * is tracking changes using the
 * `org.freedesktop.DBus.Properties.PropertiesChanged`
 * D-Bus signal. However, for performance reasons an object may
 * decide to not use this signal for some properties and instead
 * use a proprietary out-of-band mechanism to transmit changes.
803 804
 *
 * As a concrete example, consider an object with a property
805 806 807 808 809
 * `ChatroomParticipants` which is an array of strings. Instead of
 * transmitting the same (long) array every time the property changes,
 * it is more efficient to only transmit the delta using e.g. signals
 * `ChatroomParticipantJoined(String name)` and
 * `ChatroomParticipantParted(String name)`.
810 811 812 813 814 815 816 817 818 819 820 821 822
 *
 * Since: 2.26
 */
void
g_dbus_proxy_set_cached_property (GDBusProxy   *proxy,
                                  const gchar  *property_name,
                                  GVariant     *value)
{
  const GDBusPropertyInfo *info;

  g_return_if_fail (G_IS_DBUS_PROXY (proxy));
  g_return_if_fail (property_name != NULL);

823 824
  G_LOCK (properties_lock);

825 826
  if (value != NULL)
    {
827
      info = lookup_property_info (proxy, property_name);
828 829 830 831
      if (info != NULL)
        {
          if (g_strcmp0 (info->signature, g_variant_get_type_string (value)) != 0)
            {
832 833
              g_warning ("Trying to set property %s of type %s but according to the expected "
			 "interface the type is %s",
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
                         property_name,
                         g_variant_get_type_string (value),
                         info->signature);
              goto out;
            }
        }
      g_hash_table_insert (proxy->priv->properties,
                           g_strdup (property_name),
                           g_variant_ref_sink (value));
    }
  else
    {
      g_hash_table_remove (proxy->priv->properties, property_name);
    }

 out:
850
  G_UNLOCK (properties_lock);
851 852
}

853 854 855
/* ---------------------------------------------------------------------------------------------------- */

static void
Matthias Clasen's avatar
Matthias Clasen committed
856 857 858 859 860 861 862
on_signal_received (GDBusConnection *connection,
                    const gchar     *sender_name,
                    const gchar     *object_path,
                    const gchar     *interface_name,
                    const gchar     *signal_name,
                    GVariant        *parameters,
                    gpointer         user_data)
863
{
864 865 866 867 868 869
  SignalSubscriptionData *data = user_data;
  GDBusProxy *proxy;

  G_LOCK (signal_subscription_lock);
  proxy = data->proxy;
  if (proxy == NULL)
870 871
    {
      G_UNLOCK (signal_subscription_lock);
872
      return;
873 874 875 876 877 878
    }
  else
    {
      g_object_ref (proxy);
      G_UNLOCK (signal_subscription_lock);
    }
879

880 881 882
  if (!proxy->priv->initialized)
    goto out;

883 884
  G_LOCK (properties_lock);

885
  if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
886 887 888 889
    {
      G_UNLOCK (properties_lock);
      goto out;
    }
890

891 892 893 894
  if (proxy->priv->expected_interface != NULL)
    {
      const GDBusSignalInfo *info;
      info = g_dbus_interface_info_lookup_signal (proxy->priv->expected_interface, signal_name);
895
      if (info != NULL)
896
        {
897 898 899 900 901 902 903 904 905 906 907 908 909 910
          GVariantType *expected_type;
          expected_type = _g_dbus_compute_complete_signature (info->args);
          if (!g_variant_type_equal (expected_type, g_variant_get_type (parameters)))
            {
              gchar *expected_type_string = g_variant_type_dup_string (expected_type);
              g_warning ("Dropping signal %s of type %s since the type from the expected interface is %s",
                         info->name,
                         g_variant_get_type_string (parameters),
                         expected_type_string);
              g_free (expected_type_string);
              g_variant_type_free (expected_type);
              G_UNLOCK (properties_lock);
              goto out;
            }
911 912
          g_variant_type_free (expected_type);
        }
913 914
    }

915 916
  G_UNLOCK (properties_lock);

917 918 919 920 921 922
  g_signal_emit (proxy,
                 signals[SIGNAL_SIGNAL],
                 0,
                 sender_name,
                 signal_name,
                 parameters);
923

924
 out:
925 926
  if (proxy != NULL)
    g_object_unref (proxy);
927 928 929 930
}

/* ---------------------------------------------------------------------------------------------------- */

931
/* must hold properties_lock */
932 933 934 935 936 937 938 939 940
static void
insert_property_checked (GDBusProxy  *proxy,
			 gchar *property_name,
			 GVariant *value)
{
  if (proxy->priv->expected_interface != NULL)
    {
      const GDBusPropertyInfo *info;
      info = g_dbus_interface_info_lookup_property (proxy->priv->expected_interface, property_name);
941 942 943 944 945 946 947 948 949 950 951 952 953 954
      /* Only check known properties */
      if (info != NULL)
        {
          /* Warn about properties with the wrong type */
          if (g_strcmp0 (info->signature, g_variant_get_type_string (value)) != 0)
            {
              g_warning ("Received property %s with type %s does not match expected type "
                         "%s in the expected interface",
                         property_name,
                         g_variant_get_type_string (value),
                         info->signature);
              goto invalid;
            }
        }
955 956 957 958 959 960 961 962 963 964 965 966 967
    }

  g_hash_table_insert (proxy->priv->properties,
		       property_name, /* adopts string */
		       value); /* adopts value */

  return;

 invalid:
  g_variant_unref (value);
  g_free (property_name);
}

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
typedef struct
{
  GDBusProxy *proxy;
  gchar *prop_name;
} InvalidatedPropGetData;

static void
invalidated_property_get_cb (GDBusConnection *connection,
                             GAsyncResult    *res,
                             gpointer         user_data)
{
  InvalidatedPropGetData *data = user_data;
  const gchar *invalidated_properties[] = {NULL};
  GVariantBuilder builder;
  GVariant *value = NULL;
  GVariant *unpacked_value = NULL;

  /* errors are fine, the other end could have disconnected */
  value = g_dbus_connection_call_finish (connection, res, NULL);
  if (value == NULL)
    {
      goto out;
    }

  if (!g_variant_is_of_type (value, G_VARIANT_TYPE ("(v)")))
    {
994
      g_warning ("Expected type '(v)' for Get() reply, got '%s'", g_variant_get_type_string (value));
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
      goto out;
    }

  g_variant_get (value, "(v)", &unpacked_value);

  /* synthesize the a{sv} in the PropertiesChanged signal */
  g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
  g_variant_builder_add (&builder, "{sv}", data->prop_name, unpacked_value);

  G_LOCK (properties_lock);
  insert_property_checked (data->proxy,
                           data->prop_name,  /* adopts string */
                           unpacked_value);  /* adopts value */
  data->prop_name = NULL;
  G_UNLOCK (properties_lock);

  g_signal_emit (data->proxy,
                 signals[PROPERTIES_CHANGED_SIGNAL], 0,
                 g_variant_builder_end (&builder), /* consumed */
                 invalidated_properties);


 out:
  if (value != NULL)
    g_variant_unref (value);
  g_object_unref (data->proxy);
  g_free (data->prop_name);
  g_slice_free (InvalidatedPropGetData, data);
}

1025
static void
Matthias Clasen's avatar
Matthias Clasen committed
1026 1027 1028 1029 1030 1031 1032
on_properties_changed (GDBusConnection *connection,
                       const gchar     *sender_name,
                       const gchar     *object_path,
                       const gchar     *interface_name,
                       const gchar     *signal_name,
                       GVariant        *parameters,
                       gpointer         user_data)
1033
{
1034
  SignalSubscriptionData *data = user_data;
1035
  gboolean emit_g_signal = FALSE;
1036
  GDBusProxy *proxy;
1037
  const gchar *interface_name_for_signal;
1038
  GVariant *changed_properties;
1039
  gchar **invalidated_properties;
1040 1041 1042
  GVariantIter iter;
  gchar *key;
  GVariant *value;
1043
  guint n;
1044

1045 1046 1047
  changed_properties = NULL;
  invalidated_properties = NULL;

1048 1049 1050
  G_LOCK (signal_subscription_lock);
  proxy = data->proxy;
  if (proxy == NULL)
1051 1052 1053 1054 1055 1056 1057 1058 1059
    {
      G_UNLOCK (signal_subscription_lock);
      goto out;
    }
  else
    {
      g_object_ref (proxy);
      G_UNLOCK (signal_subscription_lock);
    }
1060

1061 1062
  if (!proxy->priv->initialized)
    goto out;
1063

1064 1065
  G_LOCK (properties_lock);

1066
  if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
1067 1068 1069 1070
    {
      G_UNLOCK (properties_lock);
      goto out;
    }
1071

1072
  if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(sa{sv}as)")))
1073
    {
1074
      g_warning ("Value for PropertiesChanged signal with type '%s' does not match '(sa{sv}as)'",
1075
                 g_variant_get_type_string (parameters));
1076
      G_UNLOCK (properties_lock);
1077
      goto out;
1078 1079 1080
    }

  g_variant_get (parameters,
1081
                 "(&s@a{sv}^a&s)",
1082
                 &interface_name_for_signal,
1083 1084
                 &changed_properties,
                 &invalidated_properties);
1085 1086

  if (g_strcmp0 (interface_name_for_signal, proxy->priv->interface_name) != 0)
1087 1088 1089 1090
    {
      G_UNLOCK (properties_lock);
      goto out;
    }
1091

1092 1093
  g_variant_iter_init (&iter, changed_properties);
  while (g_variant_iter_next (&iter, "{sv}", &key, &value))
1094
    {
1095 1096 1097
      insert_property_checked (proxy,
			       key, /* adopts string */
			       value); /* adopts value */
1098
      emit_g_signal = TRUE;
1099 1100
    }

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
  if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES)
    {
      if (proxy->priv->name_owner != NULL)
        {
          for (n = 0; invalidated_properties[n] != NULL; n++)
            {
              InvalidatedPropGetData *data;
              data = g_slice_new0 (InvalidatedPropGetData);
              data->proxy = g_object_ref (proxy);
              data->prop_name = g_strdup (invalidated_properties[n]);
              g_dbus_connection_call (proxy->priv->connection,
                                      proxy->priv->name_owner,
                                      proxy->priv->object_path,
                                      "org.freedesktop.DBus.Properties",
                                      "Get",
                                      g_variant_new ("(ss)", proxy->priv->interface_name, data->prop_name),
                                      G_VARIANT_TYPE ("(v)"),
                                      G_DBUS_CALL_FLAGS_NONE,
                                      -1,           /* timeout */
                                      NULL,         /* GCancellable */
                                      (GAsyncReadyCallback) invalidated_property_get_cb,
                                      data);
            }
        }
    }
  else
1127
    {
1128 1129 1130 1131 1132
      emit_g_signal = TRUE;
      for (n = 0; invalidated_properties[n] != NULL; n++)
        {
          g_hash_table_remove (proxy->priv->properties, invalidated_properties[n]);
        }
1133 1134
    }

1135 1136
  G_UNLOCK (properties_lock);

1137 1138 1139 1140 1141 1142 1143
  if (emit_g_signal)
    {
      g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
                     0,
                     changed_properties,
                     invalidated_properties);
    }
1144 1145

 out:
1146 1147
  if (changed_properties != NULL)
    g_variant_unref (changed_properties);
1148
  g_free (invalidated_properties);
1149 1150
  if (proxy != NULL)
    g_object_unref (proxy);
1151 1152 1153 1154 1155 1156 1157 1158
}

/* ---------------------------------------------------------------------------------------------------- */

static void
process_get_all_reply (GDBusProxy *proxy,
                       GVariant   *result)
{
Christian Persch's avatar
Christian Persch committed
1159 1160 1161
  GVariantIter *iter;
  gchar *key;
  GVariant *value;
1162
  guint num_properties;
1163

1164
  if (!g_variant_is_of_type (result, G_VARIANT_TYPE ("(a{sv})")))
1165
    {
1166
      g_warning ("Value for GetAll reply with type '%s' does not match '(a{sv})'",
1167 1168 1169 1170
                 g_variant_get_type_string (result));
      goto out;
    }

1171 1172
  G_LOCK (properties_lock);

Christian Persch's avatar
Christian Persch committed
1173 1174
  g_variant_get (result, "(a{sv})", &iter);
  while (g_variant_iter_next (iter, "{sv}", &key, &value))
1175
    {
1176 1177 1178
      insert_property_checked (proxy,
			       key, /* adopts string */
			       value); /* adopts value */
1179
    }
Christian Persch's avatar
Christian Persch committed
1180 1181
  g_variant_iter_free (iter);

1182 1183 1184
  num_properties = g_hash_table_size (proxy->priv->properties);
  G_UNLOCK (properties_lock);

1185
  /* Synthesize ::g-properties-changed changed */
1186
  if (num_properties > 0)
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    {
      GVariant *changed_properties;
      const gchar *invalidated_properties[1] = {NULL};

      g_variant_get (result,
                     "(@a{sv})",
                     &changed_properties);
      g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
                     0,
                     changed_properties,
                     invalidated_properties);
      g_variant_unref (changed_properties);
    }

1201 1202 1203 1204
 out:
  ;
}

1205
typedef struct
1206
{
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  GDBusProxy *proxy;
  GCancellable *cancellable;
  gchar *name_owner;
} LoadPropertiesOnNameOwnerChangedData;

static void
on_name_owner_changed_get_all_cb (GDBusConnection *connection,
                                  GAsyncResult    *res,
                                  gpointer         user_data)
{
  LoadPropertiesOnNameOwnerChangedData *data = user_data;
1218
  GVariant *result;
1219 1220
  GError *error;
  gboolean cancelled;
1221

1222
  cancelled = FALSE;
1223

1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
  error = NULL;
  result = g_dbus_connection_call_finish (connection,
                                          res,
                                          &error);
  if (result == NULL)
    {
      if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_CANCELLED)
        cancelled = TRUE;
      /* We just ignore if GetAll() is failing. Because this might happen
       * if the object has no properties at all. Or if the caller is
       * not authorized to see the properties.
       *
       * Either way, apps can know about this by using
       * get_cached_property_names() or get_cached_property().
       */
1239 1240 1241 1242 1243 1244 1245
      if (G_UNLIKELY (_g_dbus_debug_proxy ()))
        {
          g_debug ("error: %d %d %s",
                   error->domain,
                   error->code,
                   error->message);
        }
1246 1247
      g_error_free (error);
    }
1248

1249 1250
  /* and finally we can notify */
  if (!cancelled)
1251
    {
1252
      G_LOCK (properties_lock);
1253 1254 1255 1256
      g_free (data->proxy->priv->name_owner);
      data->proxy->priv->name_owner = data->name_owner;
      data->name_owner = NULL; /* to avoid an extra copy, we steal the string */
      g_hash_table_remove_all (data->proxy->priv->properties);
1257
      G_UNLOCK (properties_lock);
1258
      if (result != NULL)
1259
        {
1260 1261
          process_get_all_reply (data->proxy, result);
          g_variant_unref (result);
1262
        }
1263

1264
      g_object_notify (G_OBJECT (data->proxy), "g-name-owner");
1265 1266
    }

1267 1268
  if (data->cancellable == data->proxy->priv->get_all_cancellable)
    data->proxy->priv->get_all_cancellable = NULL;
1269

1270 1271 1272 1273
  g_object_unref (data->proxy);
  g_object_unref (data->cancellable);
  g_free (data->name_owner);
  g_free (data);
1274 1275 1276
}

static void
1277 1278 1279 1280 1281 1282 1283
on_name_owner_changed (GDBusConnection *connection,
                       const gchar      *sender_name,
                       const gchar      *object_path,
                       const gchar      *interface_name,
                       const gchar      *signal_name,
                       GVariant         *parameters,
                       gpointer          user_data)
1284
{
1285 1286
  SignalSubscriptionData *data = user_data;
  GDBusProxy *proxy;
1287 1288 1289
  const gchar *old_owner;
  const gchar *new_owner;

1290 1291 1292
  G_LOCK (signal_subscription_lock);
  proxy = data->proxy;
  if (proxy == NULL)
1293 1294 1295 1296 1297 1298 1299 1300 1301
    {
      G_UNLOCK (signal_subscription_lock);
      goto out;
    }
  else
    {
      g_object_ref (proxy);
      G_UNLOCK (signal_subscription_lock);
    }
1302

1303 1304 1305 1306 1307 1308 1309 1310 1311
  /* if we are already trying to load properties, cancel that */
  if (proxy->priv->get_all_cancellable != NULL)
    {
      g_cancellable_cancel (proxy->priv->get_all_cancellable);
      proxy->priv->get_all_cancellable = NULL;
    }

  g_variant_get (parameters,
                 "(&s&s&s)",
1312
                 NULL,
1313 1314 1315 1316 1317
                 &old_owner,
                 &new_owner);

  if (strlen (new_owner) == 0)
    {
1318
      G_LOCK (properties_lock);
1319 1320
      g_free (proxy->priv->name_owner);
      proxy->priv->name_owner = NULL;
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332

      /* Synthesize ::g-properties-changed changed */
      if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES) &&
          g_hash_table_size (proxy->priv->properties) > 0)
        {
          GVariantBuilder builder;
          GPtrArray *invalidated_properties;
          GHashTableIter iter;
          const gchar *key;

          /* Build changed_properties (always empty) and invalidated_properties ... */
          g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
1333

1334 1335 1336 1337 1338 1339 1340 1341 1342
          invalidated_properties = g_ptr_array_new_with_free_func (g_free);
          g_hash_table_iter_init (&iter, proxy->priv->properties);
          while (g_hash_table_iter_next (&iter, (gpointer) &key, NULL))
            g_ptr_array_add (invalidated_properties, g_strdup (key));
          g_ptr_array_add (invalidated_properties, NULL);

          /* ... throw out the properties ... */
          g_hash_table_remove_all (proxy->priv->properties);

1343 1344
          G_UNLOCK (properties_lock);

1345 1346 1347
          /* ... and finally emit the ::g-properties-changed signal */
          g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
                         0,
1348
                         g_variant_builder_end (&builder) /* consumed */,
1349 1350 1351
                         (const gchar* const *) invalidated_properties->pdata);
          g_ptr_array_unref (invalidated_properties);
        }
1352 1353 1354 1355
      else
        {
          G_UNLOCK (properties_lock);
        }
1356 1357 1358 1359
      g_object_notify (G_OBJECT (proxy), "g-name-owner");
    }
  else
    {
1360 1361
      G_LOCK (properties_lock);

1362 1363
      /* ignore duplicates - this can happen when activating the service */
      if (g_strcmp0 (new_owner, proxy->priv->name_owner) == 0)
1364 1365 1366 1367
        {
          G_UNLOCK (properties_lock);
          goto out;
        }
1368 1369 1370 1371 1372

      if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES)
        {
          g_free (proxy->priv->name_owner);
          proxy->priv->name_owner = g_strdup (new_owner);
1373

1374
          g_hash_table_remove_all (proxy->priv->properties);
1375
          G_UNLOCK (properties_lock);
1376 1377 1378 1379 1380 1381
          g_object_notify (G_OBJECT (proxy), "g-name-owner");
        }
      else
        {
          LoadPropertiesOnNameOwnerChangedData *data;

1382 1383
          G_UNLOCK (properties_lock);

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
          /* start loading properties.. only then emit notify::g-name-owner .. we
           * need to be able to cancel this in the event another NameOwnerChanged
           * signal suddenly happens
           */

          g_assert (proxy->priv->get_all_cancellable == NULL);
          proxy->priv->get_all_cancellable = g_cancellable_new ();
          data = g_new0 (LoadPropertiesOnNameOwnerChangedData, 1);
          data->proxy = g_object_ref (proxy);
          data->cancellable = proxy->priv->get_all_cancellable;
          data->name_owner = g_strdup (new_owner);
          g_dbus_connection_call (proxy->priv->connection,
                                  data->name_owner,
                                  proxy->priv->object_path,
                                  "org.freedesktop.DBus.Properties",
                                  "GetAll",
                                  g_variant_new ("(s)", proxy->priv->interface_name),
                                  G_VARIANT_TYPE ("(a{sv})"),
                                  G_DBUS_CALL_FLAGS_NONE,
                                  -1,           /* timeout */
                                  proxy->priv->get_all_cancellable,
                                  (GAsyncReadyCallback) on_name_owner_changed_get_all_cb,
                                  data);
        }
    }

 out:
1411 1412
  if (proxy != NULL)
    g_object_unref (proxy);
1413 1414 1415 1416
}

/* ---------------------------------------------------------------------------------------------------- */

1417 1418 1419 1420 1421
static void
async_init_get_all_cb (GDBusConnection *connection,
                       GAsyncResult    *res,
                       gpointer         user_data)
{
1422
  GTask *task = user_data;
1423 1424 1425 1426
  GVariant *result;
  GError *error;

  error = NULL;
1427 1428 1429
  result = g_dbus_connection_call_finish (connection,
                                          res,
                                          &error);
1430 1431
  if (result == NULL)
    {
1432 1433 1434 1435 1436 1437 1438
      /* We just ignore if GetAll() is failing. Because this might happen
       * if the object has no properties at all. Or if the caller is
       * not authorized to see the properties.
       *
       * Either way, apps can know about this by using
       * get_cached_property_names() or get_cached_property().
       */
1439 1440 1441 1442 1443 1444 1445
      if (G_UNLIKELY (_g_dbus_debug_proxy ()))
        {
          g_debug ("error: %d %d %s",
                   error->domain,
                   error->code,
                   error->message);
        }
1446 1447 1448
      g_error_free (error);
    }

1449 1450 1451
  g_task_return_pointer (task, result,
                         (GDestroyNotify) g_variant_unref);
  g_object_unref (task);
1452 1453 1454
}

static void
1455 1456
async_init_data_set_name_owner (GTask       *task,
                                const gchar *name_owner)
1457
{
1458
  GDBusProxy *proxy = g_task_get_source_object (task);
1459
  gboolean get_all;
1460

1461
  if (name_owner != NULL)
1462
    {
1463
      G_LOCK (properties_lock);
1464 1465
      /* Must free first, since on_name_owner_changed() could run before us */
      g_free (proxy->priv->name_owner);
1466
      proxy->priv->name_owner = g_strdup (name_owner);
1467
      G_UNLOCK (properties_lock);
1468
    }
1469

1470 1471
  get_all = TRUE;

1472
  if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES)
1473 1474 1475 1476
    {
      /* Don't load properties if the API user doesn't want them */
      get_all = FALSE;
    }
1477
  else if (name_owner == NULL && proxy->priv->name != NULL)
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
    {
      /* Don't attempt to load properties if the name_owner is NULL (which
       * usually means the name isn't owned), unless name is also NULL (which
       * means we actually wanted to talk to the directly-connected process -
       * either dbus-daemon or a peer - instead of going via dbus-daemon)
       */
        get_all = FALSE;
    }

  if (get_all)
1488 1489
    {
      /* load all properties asynchronously */
1490
      g_dbus_connection_call (proxy->priv->connection,
1491
                              name_owner,
1492
                              proxy->priv->object_path,
1493 1494
                              "org.freedesktop.DBus.Properties",
                              "GetAll",
1495
                              g_variant_new ("(s)", proxy->priv->interface_name),
1496
                              G_VARIANT_TYPE ("(a{sv})"),
1497 1498
                              G_DBUS_CALL_FLAGS_NONE,
                              -1,           /* timeout */
1499
                              g_task_get_cancellable (task),
1500
                              (GAsyncReadyCallback) async_init_get_all_cb,
1501
                              task);
1502 1503 1504
    }
  else
    {
1505 1506
      g_task_return_pointer (task, NULL, NULL);
      g_object_unref (task);
1507
    }
1508
}
1509

1510 1511 1512 1513 1514
static void
async_init_get_name_owner_cb (GDBusConnection *connection,
                              GAsyncResult    *res,
                              gpointer         user_data)
{
1515
  GTask *task = user_data;
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
  GError *error;
  GVariant *result;

  error = NULL;
  result = g_dbus_connection_call_finish (connection,
                                          res,
                                          &error);
  if (result == NULL)
    {
      if (error->domain == G_DBUS_ERROR &&
          error->code == G_DBUS_ERROR_NAME_HAS_NO_OWNER)
        {
          g_error_free (error);
1529
          async_init_data_set_name_owner (task, NULL);
1530 1531 1532
        }
      else
        {
1533 1534
          g_task_return_error (task, error);
          g_object_unref (task);
1535 1536 1537 1538 1539 1540 1541 1542
        }
    }
  else
    {
      /* borrowed from result to avoid an extra copy */
      const gchar *name_owner;

      g_variant_get (result, "(&s)", &name_owner);
1543
      async_init_data_set_name_owner (task, name_owner);
1544 1545
      g_variant_unref (result);
    }
1546 1547 1548
}

static void
1549
async_init_call_get_name_owner (GTask *task)
1550
{
1551 1552 1553
  GDBusProxy *proxy = g_task_get_source_object (task);

  g_dbus_connection_call (proxy->priv->connection,
1554 1555 1556 1557 1558
                          "org.freedesktop.DBus",  /* name */
                          "/org/freedesktop/DBus", /* object path */
                          "org.freedesktop.DBus",  /* interface */
                          "GetNameOwner",
                          g_variant_new ("(s)",
1559
                                         proxy->priv->name),
1560 1561 1562
                          G_VARIANT_TYPE ("(s)"),
                          G_DBUS_CALL_FLAGS_NONE,
                          -1,           /* timeout */
1563
                          g_task_get_cancellable (task),
1564
                          (GAsyncReadyCallback) async_init_get_name_owner_cb,
1565
                          task);
1566 1567 1568