gdbusproxy.c 111 KB
Newer Older
1 2
/* GDBus - GLib D-Bus Library
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * 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
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

#include "config.h"

#include <stdlib.h>
David Zeuthen's avatar
David Zeuthen committed
26 27
#include <string.h>

28 29 30 31 32 33 34 35 36 37 38
#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"
#include "gasyncresult.h"
#include "gsimpleasyncresult.h"
39
#include "gcancellable.h"
40
#include "gdbusinterface.h"
41

42 43 44 45
#ifdef G_OS_UNIX
#include "gunixfdlist.h"
#endif

David Zeuthen's avatar
David Zeuthen committed
46 47
#include "glibintl.h"

48 49
/**
 * SECTION:gdbusproxy
50
 * @short_description: Client-side D-Bus interface proxy
David Zeuthen's avatar
David Zeuthen committed
51
 * @include: gio/gio.h
52 53
 *
 * #GDBusProxy is a base class used for proxies to access a D-Bus
54 55
 * interface on a remote object. A #GDBusProxy can be constructed for
 * both well-known and unique names.
56
 *
57 58
 * By default, #GDBusProxy will cache all properties (and listen to
 * changes) of the remote object, and proxy all signals that gets
59
 * emitted. This behaviour can be changed by passing suitable
60 61 62 63 64 65 66 67
 * #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.
 *
 * If a #GDBusProxy is used for a well-known name, the owner of the
 * name is tracked and can be read from
 * #GDBusProxy:g-name-owner. Connect to the #GObject::notify signal to
 * get notified of changes. Additionally, only signals and property
68 69 70 71 72 73 74
 * 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).
75
 *
76 77 78 79 80 81 82 83
 * The generic #GDBusProxy::g-properties-changed and
 * #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. See <xref linkend="gdbus-example-gdbus-codegen"/>
 * for how this can easily be done using the
 * <command><link linkend="gdbus-codegen">gdbus-codegen</link></command>
 * tool.
84
 *
85
 * A #GDBusProxy instance can be used from multiple threads but note
86
 * that all signals (e.g. #GDBusProxy::g-signal, #GDBusProxy::g-properties-changed
87 88 89 90
 * and #GObject::notify) are emitted in the
 * <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
 * of the thread where the instance was constructed.
 *
91
 * <example id="gdbus-wellknown-proxy"><title>GDBusProxy for a well-known-name</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-watch-proxy.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
92 93
 */

94 95 96
/* lock protecting the mutable properties: name_owner, timeout_msec,
 * expected_interface, and the properties hash table
 */
97 98
G_LOCK_DEFINE_STATIC (properties_lock);

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
/* ---------------------------------------------------------------------------------------------------- */

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);
    }
}

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

127 128
struct _GDBusProxyPrivate
{
129
  GBusType bus_type;
130
  GDBusProxyFlags flags;
131
  GDBusConnection *connection;
132 133

  gchar *name;
134
  /* mutable, protected by properties_lock */
135
  gchar *name_owner;
136 137
  gchar *object_path;
  gchar *interface_name;
138
  /* mutable, protected by properties_lock */
139 140
  gint timeout_msec;

141 142 143 144
  guint name_owner_changed_subscription_id;

  GCancellable *get_all_cancellable;

145
  /* gchar* -> GVariant*, protected by properties_lock */
146 147
  GHashTable *properties;

148
  /* mutable, protected by properties_lock */
149 150
  GDBusInterfaceInfo *expected_interface;

151 152
  guint properties_changed_subscription_id;
  guint signals_subscription_id;
153 154

  gboolean initialized;
155

156
  /* mutable, protected by properties_lock */
157
  GDBusObject *object;
158 159

  SignalSubscriptionData *signal_subscription_data;
160 161 162 163 164 165
};

enum
{
  PROP_0,
  PROP_G_CONNECTION,
166 167 168
  PROP_G_BUS_TYPE,
  PROP_G_NAME,
  PROP_G_NAME_OWNER,
169 170 171 172 173 174 175 176 177 178 179 180 181 182
  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,
};

183
static guint signals[LAST_SIGNAL] = {0};
184

185
static void dbus_interface_iface_init (GDBusInterfaceIface *dbus_interface_iface);
186 187 188 189
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,
190
                         G_IMPLEMENT_INTERFACE (G_TYPE_DBUS_INTERFACE, dbus_interface_iface_init)
191 192 193 194
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
                         G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
                         );

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
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);
}

211 212 213 214 215
static void
g_dbus_proxy_finalize (GObject *object)
{
  GDBusProxy *proxy = G_DBUS_PROXY (object);

216 217 218 219 220 221
  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);

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

226
  if (proxy->priv->signals_subscription_id > 0)
Matthias Clasen's avatar
Matthias Clasen committed
227
    g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
228
                                          proxy->priv->signals_subscription_id);
229

230 231
  if (proxy->priv->connection != NULL)
    g_object_unref (proxy->priv->connection);
232 233
  g_free (proxy->priv->name);
  g_free (proxy->priv->name_owner);
234 235 236 237 238 239
  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)
240 241 242 243
    {
      g_dbus_interface_info_cache_release (proxy->priv->expected_interface);
      g_dbus_interface_info_unref (proxy->priv->expected_interface);
    }
244

245 246 247
  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
248
  G_OBJECT_CLASS (g_dbus_proxy_parent_class)->finalize (object);
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
}

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;

269 270 271 272 273
    case PROP_G_NAME:
      g_value_set_string (value, proxy->priv->name);
      break;

    case PROP_G_NAME_OWNER:
274
      g_value_take_string (value, g_dbus_proxy_get_name_owner (proxy));
275 276 277 278 279 280 281 282 283 284 285
      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:
286
      g_value_set_int (value, g_dbus_proxy_get_default_timeout (proxy));
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
      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;

317 318
    case PROP_G_NAME:
      proxy->priv->name = g_value_dup_string (value);
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
      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;

337 338 339 340
    case PROP_G_BUS_TYPE:
      proxy->priv->bus_type = g_value_get_enum (value);
      break;

341 342 343 344 345 346 347 348 349 350 351
    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);

352
  gobject_class->dispose      = g_dbus_proxy_dispose;
353 354 355 356 357 358 359 360 361 362 363
  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
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
   * interface. This is mainly to ensure that malformed data received
   * from the other peer is ignored. The given #GDBusInterfaceInfo is
   * said to be the <emphasis>expected interface</emphasis>.
   *
   * The checks performed are:
   * <itemizedlist>
   *   <listitem><para>
   *     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.
   *   </para></listitem>
   *   <listitem><para>
   *     Received signals that have a type signature mismatch are dropped and
   *     a warning is logged via g_warning().
   *   </para></listitem>
   *   <listitem><para>
   *     Properties received via the initial <literal>GetAll()</literal> call
   *     or via the <literal>::PropertiesChanged</literal> signal (on the
   *     <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties">org.freedesktop.DBus.Properties</ulink> 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().
   *   </para></listitem>
   * </itemizedlist>
   * 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.
391 392
   *
   * Since: 2.26
393 394 395 396
   */
  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
397 398
                                                       P_("Interface Information"),
                                                       P_("Interface Information"),
399 400 401 402 403 404 405 406 407 408 409
                                                       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.
410 411
   *
   * Since: 2.26
412 413 414 415
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_CONNECTION,
                                   g_param_spec_object ("g-connection",
Matthias Clasen's avatar
Matthias Clasen committed
416 417
                                                        P_("g-connection"),
                                                        P_("The connection the proxy is for"),
418 419 420 421 422 423 424 425
                                                        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));

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
  /**
   * 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));

449 450 451 452
  /**
   * GDBusProxy:g-flags:
   *
   * Flags from the #GDBusProxyFlags enumeration.
453 454
   *
   * Since: 2.26
455 456 457 458
   */
  g_object_class_install_property (gobject_class,
                                   PROP_G_FLAGS,
                                   g_param_spec_flags ("g-flags",
Matthias Clasen's avatar
Matthias Clasen committed
459 460
                                                       P_("g-flags"),
                                                       P_("Flags for the proxy"),
461 462 463 464 465 466 467 468 469 470
                                                       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));

  /**
471
   * GDBusProxy:g-name:
472
   *
473
   * The well-known or unique name that the proxy is for.
474 475
   *
   * Since: 2.26
476 477
   */
  g_object_class_install_property (gobject_class,
478 479 480 481
                                   PROP_G_NAME,
                                   g_param_spec_string ("g-name",
                                                        P_("g-name"),
                                                        P_("The well-known or unique name that the proxy is for"),
482 483 484 485 486 487 488 489
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

490 491 492
  /**
   * GDBusProxy:g-name-owner:
   *
493
   * The unique name that owns #GDBusProxy:g-name or %NULL if no-one
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
   * 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));

510 511 512 513
  /**
   * GDBusProxy:g-object-path:
   *
   * The object path the proxy is for.
514 515
   *
   * Since: 2.26
516 517 518 519
   */
  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
520 521
                                                        P_("g-object-path"),
                                                        P_("The object path the proxy is for"),
522 523 524 525 526 527 528 529 530 531 532 533
                                                        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.
534 535
   *
   * Since: 2.26
536 537 538 539
   */
  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
540 541
                                                        P_("g-interface-name"),
                                                        P_("The D-Bus interface name the proxy is for"),
542 543 544 545 546 547 548 549 550 551 552 553
                                                        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
554 555
   * as @timeout_msec in the g_dbus_proxy_call() and
   * g_dbus_proxy_call_sync() functions.
556 557 558 559 560
   *
   * 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.
561 562
   *
   * Since: 2.26
563 564 565 566
   */
  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
567 568
                                                     P_("Default Timeout"),
                                                     P_("Timeout for remote method invocation"),
569 570 571 572 573 574 575 576 577 578 579 580 581
                                                     -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.
582 583
   * @changed_properties: A #GVariant containing the properties that changed
   * @invalidated_properties: A %NULL terminated array of properties that was invalidated
584
   *
585
   * Emitted when one or more D-Bus properties on @proxy changes. The
586 587 588
   * 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).
589
   *
590 591 592 593
   * If the proxy has the flag
   * %G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES set, then
   * @invalidated_properties will always be empty.
   *
594 595 596
   * This signal corresponds to the
   * <literal>PropertiesChanged</literal> D-Bus signal on the
   * <literal>org.freedesktop.DBus.Properties</literal> interface.
597 598
   *
   * Since: 2.26
599 600 601
   */
  signals[PROPERTIES_CHANGED_SIGNAL] = g_signal_new ("g-properties-changed",
                                                     G_TYPE_DBUS_PROXY,
602
                                                     G_SIGNAL_RUN_LAST | G_SIGNAL_MUST_COLLECT,
603 604 605
                                                     G_STRUCT_OFFSET (GDBusProxyClass, g_properties_changed),
                                                     NULL,
                                                     NULL,
606
                                                     NULL,
607
                                                     G_TYPE_NONE,
608 609
                                                     2,
                                                     G_TYPE_VARIANT,
610
                                                     G_TYPE_STRV | G_SIGNAL_TYPE_STATIC_SCOPE);
611 612 613 614

  /**
   * GDBusProxy::g-signal:
   * @proxy: The #GDBusProxy emitting the signal.
615
   * @sender_name: (allow-none): The sender of the signal or %NULL if the connection is not a bus connection.
616 617 618 619
   * @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.
620 621 622
   *
   * Since: 2.26
   */
623 624
  signals[SIGNAL_SIGNAL] = g_signal_new ("g-signal",
                                         G_TYPE_DBUS_PROXY,
625
                                         G_SIGNAL_RUN_LAST | G_SIGNAL_MUST_COLLECT,
626 627 628
                                         G_STRUCT_OFFSET (GDBusProxyClass, g_signal),
                                         NULL,
                                         NULL,
629
                                         NULL,
630 631 632 633 634 635 636 637 638 639 640 641 642 643
                                         G_TYPE_NONE,
                                         3,
                                         G_TYPE_STRING,
                                         G_TYPE_STRING,
                                         G_TYPE_VARIANT);


  g_type_class_add_private (klass, sizeof (GDBusProxyPrivate));
}

static void
g_dbus_proxy_init (GDBusProxy *proxy)
{
  proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, G_TYPE_DBUS_PROXY, GDBusProxyPrivate);
644 645 646
  proxy->priv->signal_subscription_data = g_slice_new0 (SignalSubscriptionData);
  proxy->priv->signal_subscription_data->ref_count = 1;
  proxy->priv->signal_subscription_data->proxy = proxy;
647 648 649 650
  proxy->priv->properties = g_hash_table_new_full (g_str_hash,
                                                   g_str_equal,
                                                   g_free,
                                                   (GDestroyNotify) g_variant_unref);
651 652 653 654
}

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

655 656 657 658 659 660 661
static gint
property_name_sort_func (const gchar **a,
                         const gchar **b)
{
  return g_strcmp0 (*a, *b);
}

662 663 664 665 666 667
/**
 * g_dbus_proxy_get_cached_property_names:
 * @proxy: A #GDBusProxy.
 *
 * Gets the names of all cached properties on @proxy.
 *
668 669 670
 * Returns: (transfer full): A %NULL-terminated array of strings or %NULL if
 *          @proxy has no cached properties. Free the returned array with
 *          g_strfreev().
671 672
 *
 * Since: 2.26
673 674
 */
gchar **
675
g_dbus_proxy_get_cached_property_names (GDBusProxy  *proxy)
676 677 678 679 680 681 682 683
{
  gchar **names;
  GPtrArray *p;
  GHashTableIter iter;
  const gchar *key;

  g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);

684 685
  G_LOCK (properties_lock);

686
  names = NULL;
687 688
  if (g_hash_table_size (proxy->priv->properties) == 0)
    goto out;
689 690 691 692 693

  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
694
    g_ptr_array_add (p, g_strdup (key));
695
  g_ptr_array_sort (p, (GCompareFunc) property_name_sort_func);
696 697 698 699 700
  g_ptr_array_add (p, NULL);

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

 out:
701
  G_UNLOCK (properties_lock);
702 703 704
  return names;
}

705 706 707
/* properties_lock must be held for as long as you will keep the
 * returned value
 */
708
static const GDBusPropertyInfo *
709 710
lookup_property_info (GDBusProxy  *proxy,
                      const gchar *property_name)
711
{
712
  const GDBusPropertyInfo *info = NULL;
713 714

  if (proxy->priv->expected_interface == NULL)
715
    goto out;
716 717 718

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

719
 out:
720 721 722
  return info;
}

723 724 725 726 727
/**
 * g_dbus_proxy_get_cached_property:
 * @proxy: A #GDBusProxy.
 * @property_name: Property name.
 *
728 729
 * Looks up the value for a property from the cache. This call does no
 * blocking IO.
730
 *
731
 * If @proxy has an expected interface (see
732 733
 * #GDBusProxy:g-interface-info) and @property_name is referenced by
 * it, then @value is checked against the type of the property.
734
 *
735 736 737
 * Returns: 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().
738 739
 *
 * Since: 2.26
740 741
 */
GVariant *
Matthias Clasen's avatar
Matthias Clasen committed
742
g_dbus_proxy_get_cached_property (GDBusProxy   *proxy,
743
                                  const gchar  *property_name)
744
{
745
  const GDBusPropertyInfo *info;
746 747 748 749 750
  GVariant *value;

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

751 752
  G_LOCK (properties_lock);

753 754
  value = g_hash_table_lookup (proxy->priv->properties, property_name);
  if (value == NULL)
755 756 757 758
    goto out;

  info = lookup_property_info (proxy, property_name);
  if (info != NULL)
759
    {
760 761 762 763 764 765 766 767 768 769 770
      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;
        }
771 772 773 774 775
    }

  g_variant_ref (value);

 out:
776
  G_UNLOCK (properties_lock);
777 778 779
  return value;
}

780 781 782 783
/**
 * g_dbus_proxy_set_cached_property:
 * @proxy: A #GDBusProxy
 * @property_name: Property name.
784
 * @value: (allow-none): Value for the property or %NULL to remove it from the cache.
785 786 787 788 789 790 791 792
 *
 * 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
793 794
 * #GDBusProxy:g-interface-info) and @property_name is referenced by
 * it, then @value is checked against the type of the property.
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
 *
 * If the @value #GVariant is floating, it is consumed. This allows
 * convenient 'inline' use of g_variant_new(), e.g.
 * |[
 *  g_dbus_proxy_set_cached_property (proxy,
 *                                    "SomeProperty",
 *                                    g_variant_new ("(si)",
 *                                                  "A String",
 *                                                  42));
 * ]|
 *
 * Normally you will not need to use this method since @proxy is
 * tracking changes using the
 * <literal>org.freedesktop.DBus.Properties.PropertiesChanged</literal>
 * 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.
 *
 * As a concrete example, consider an object with a property
 * <literal>ChatroomParticipants</literal> 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 <literal>ChatroomParticipantJoined(String
 * name)</literal> and <literal>ChatroomParticipantParted(String
 * name)</literal>.
 *
 * 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);

833 834
  G_LOCK (properties_lock);

835 836
  if (value != NULL)
    {
837
      info = lookup_property_info (proxy, property_name);
838 839 840 841
      if (info != NULL)
        {
          if (g_strcmp0 (info->signature, g_variant_get_type_string (value)) != 0)
            {
842 843
              g_warning ("Trying to set property %s of type %s but according to the expected "
			 "interface the type is %s",
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
                         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:
860
  G_UNLOCK (properties_lock);
861 862
}

863 864 865
/* ---------------------------------------------------------------------------------------------------- */

static void
Matthias Clasen's avatar
Matthias Clasen committed
866 867 868 869 870 871 872
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)
873
{
874 875 876 877 878 879
  SignalSubscriptionData *data = user_data;
  GDBusProxy *proxy;

  G_LOCK (signal_subscription_lock);
  proxy = data->proxy;
  if (proxy == NULL)
880 881
    {
      G_UNLOCK (signal_subscription_lock);
882
      return;
883 884 885 886 887 888
    }
  else
    {
      g_object_ref (proxy);
      G_UNLOCK (signal_subscription_lock);
    }
889

890 891 892
  if (!proxy->priv->initialized)
    goto out;

893 894
  G_LOCK (properties_lock);

895
  if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
896 897 898 899
    {
      G_UNLOCK (properties_lock);
      goto out;
    }
900

901 902 903 904
  if (proxy->priv->expected_interface != NULL)
    {
      const GDBusSignalInfo *info;
      info = g_dbus_interface_info_lookup_signal (proxy->priv->expected_interface, signal_name);
905
      if (info != NULL)
906
        {
907 908 909 910 911 912 913 914 915 916 917 918 919 920
          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;
            }
921 922
          g_variant_type_free (expected_type);
        }
923 924
    }

925 926
  G_UNLOCK (properties_lock);

927 928 929 930 931 932
  g_signal_emit (proxy,
                 signals[SIGNAL_SIGNAL],
                 0,
                 sender_name,
                 signal_name,
                 parameters);
933

934
 out:
935 936
  if (proxy != NULL)
    g_object_unref (proxy);
937 938 939 940
}

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

941
/* must hold properties_lock */
942 943 944 945 946 947 948 949 950
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);
951 952 953 954 955 956 957 958 959 960 961 962 963 964
      /* 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;
            }
        }
965 966 967 968 969 970 971 972 973 974 975 976 977
    }

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

  return;

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

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 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 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
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)")))
    {
      g_warning ("Expected type `(v)' for Get() reply, got `%s'", g_variant_get_type_string (value));
      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);
}

1035
static void
Matthias Clasen's avatar
Matthias Clasen committed
1036 1037 1038 1039 1040 1041 1042
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)
1043
{
1044
  SignalSubscriptionData *data = user_data;
1045
  gboolean emit_g_signal = FALSE;
1046
  GDBusProxy *proxy;
1047
  const gchar *interface_name_for_signal;
1048
  GVariant *changed_properties;
1049
  gchar **invalidated_properties;
1050 1051 1052
  GVariantIter iter;
  gchar *key;
  GVariant *value;
1053
  guint n;
1054

1055 1056 1057
  changed_properties = NULL;
  invalidated_properties = NULL;

1058 1059 1060
  G_LOCK (signal_subscription_lock);
  proxy = data->proxy;
  if (proxy == NULL)
1061 1062 1063 1064 1065 1066 1067 1068 1069
    {
      G_UNLOCK (signal_subscription_lock);
      goto out;
    }
  else
    {
      g_object_ref (proxy);
      G_UNLOCK (signal_subscription_lock);
    }
1070

1071 1072
  if (!proxy->priv->initialized)
    goto out;
1073

1074 1075
  G_LOCK (properties_lock);

1076
  if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
1077 1078 1079 1080
    {
      G_UNLOCK (properties_lock);
      goto out;
    }
1081

1082
  if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(sa{sv}as)")))
1083
    {
1084
      g_warning ("Value for PropertiesChanged signal with type `%s' does not match `(sa{sv}as)'",
1085
                 g_variant_get_type_string (parameters));
1086
      G_UNLOCK (properties_lock);
1087
      goto out;
1088 1089 1090
    }

  g_variant_get (parameters,
1091
                 "(&s@a{sv}^a&s)",
1092
                 &interface_name_for_signal,
1093 1094
                 &changed_properties,
                 &invalidated_properties);
1095 1096

  if (g_strcmp0 (interface_name_for_signal, proxy->priv->interface_name) != 0)
1097 1098 1099 1100
    {
      G_UNLOCK (properties_lock);
      goto out;
    }
1101

1102 1103
  g_variant_iter_init (&iter, changed_properties);
  while (g_variant_iter_next (&iter, "{sv}", &key, &value))
1104
    {
1105 1106 1107
      insert_property_checked (proxy,
			       key, /* adopts string */
			       value); /* adopts value */
1108
      emit_g_signal = TRUE;
1109 1110
    }

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  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
1137
    {
1138 1139 1140 1141 1142
      emit_g_signal = TRUE;
      for (n = 0; invalidated_properties[n] != NULL; n++)
        {
          g_hash_table_remove (proxy->priv->properties, invalidated_properties[n]);
        }
1143 1144
    }

1145 1146
  G_UNLOCK (properties_lock);

1147 1148 1149 1150 1151 1152 1153
  if (emit_g_signal)
    {
      g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
                     0,
                     changed_properties,
                     invalidated_properties);
    }
1154 1155

 out:
1156 1157
  if (changed_properties != NULL)
    g_variant_unref (changed_properties);
1158
  g_free (invalidated_properties);
1159 1160
  if (proxy != NULL)
    g_object_unref (proxy);
1161 1162 1163 1164 1165 1166 1167 1168
}

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

static void
process_get_all_reply (GDBusProxy *proxy,
                       GVariant   *result)
{
Christian Persch's avatar
Christian Persch committed
1169 1170 1171
  GVariantIter *iter;
  gchar *key;
  GVariant *value;
1172
  guint num_properties;
1173

1174
  if (!g_variant_is_of_type (result, G_VARIANT_TYPE ("(a{sv})")))
1175 1176 1177 1178 1179 1180
    {
      g_warning ("Value for GetAll reply with type `%s' does not match `(a{sv})'",
                 g_variant_get_type_string (result));
      goto out;
    }

1181 1182
  G_LOCK (properties_lock);

Christian Persch's avatar
Christian Persch committed
1183 1184
  g_variant_get (result, "(a{sv})", &iter);
  while (g_variant_iter_next (iter, "{sv}", &key, &value))
1185
    {
1186 1187 1188
      insert_property_checked (proxy,
			       key, /* adopts string */
			       value); /* adopts value */
1189
    }
Christian Persch's avatar
Christian Persch committed
1190 1191
  g_variant_iter_free (iter);

1192 1193 1194
  num_properties = g_hash_table_size (proxy->priv->properties);
  G_UNLOCK (properties_lock);

1195
  /* Synthesize ::g-properties-changed changed */
1196
  if (num_properties > 0)
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
    {
      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);
    }

1211 1212 1213 1214
 out:
  ;
}

1215
typedef struct
1216
{
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
  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;
1228
  GVariant *result;
1229 1230
  GError *error;
  gboolean cancelled;
1231

1232
  cancelled = FALSE;
1233

1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
  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().
       *
       * TODO: handle G_DBUS_DEBUG flag 'proxy' and, if enabled, log the
       * fact that GetAll() failed
       */
      //g_debug ("error: %d %d %s", error->domain, error->code, error->message);
      g_error_free (error);
    }
1255

1256 1257
  /* and finally we can notify */
  if (!cancelled)
1258
    {
1259
      G_LOCK (properties_lock);
1260 1261 1262 1263
      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);
1264
      G_UNLOCK (properties_lock);
1265
      if (result != NULL)
1266
        {
1267 1268
          process_get_all_reply (data->proxy, result);
          g_variant_unref (result);
1269
        }
1270

1271
      g_object_notify (G_OBJECT (data->proxy), "g-name-owner");
1272 1273
    }

1274 1275
  if (data->cancellable == data->proxy->priv->get_all_cancellable)
    data->proxy->priv->get_all_cancellable = NULL;
1276

1277 1278 1279 1280
  g_object_unref (data->proxy);
  g_object_unref (data->cancellable);
  g_free (data->name_owner);
  g_free (data);
1281 1282 1283
}

static void
1284 1285 1286 1287 1288 1289 1290
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)
1291
{
1292 1293
  SignalSubscriptionData *data = user_data;
  GDBusProxy *proxy;
1294 1295 1296
  const gchar *old_owner;
  const gchar *new_owner;

1297 1298 1299
  G_LOCK (signal_subscription_lock);
  proxy = data->proxy;
  if (proxy == NULL)
1300 1301 1302 1303 1304 1305 1306 1307 1308
    {
      G_UNLOCK (signal_subscription_lock);
      goto out;
    }
  else
    {
      g_object_ref (proxy);
      G_UNLOCK (signal_subscription_lock);
    }
1309

1310 1311 1312 1313 1314 1315 1316 1317 1318
  /* 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)",
1319
                 NULL,
1320 1321 1322 1323 1324
                 &old_owner,
                 &new_owner);

  if (strlen (new_owner) == 0)
    {
1325
      G_LOCK (properties_lock);
1326 1327
      g_free (proxy->priv->name_owner);
      proxy->priv->name_owner = NULL;
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

      /* 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}"));
1340

1341 1342 1343 1344 1345 1346 1347 1348 1349
          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);

1350 1351
          G_UNLOCK (properties_lock);

1352 1353 1354
          /* ... and finally emit the ::g-properties-changed signal */
          g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
                         0,
1355
                         g_variant_builder_end (&builder) /* consumed */,
1356 1357 1358
                         (const gchar* const *) invalidated_properties->pdata);
          g_ptr_array_unref (invalidated_properties);
        }
1359 1360 1361 1362
      else
        {
          G_UNLOCK (properties_lock);
        }
1363 1364 1365 1366
      g_object_notify (G_OBJECT (proxy), "g-name-owner");
    }
  else
    {
1367 1368
      G_LOCK (properties_lock);

1369 1370
      /* ignore duplicates - this can happen when activating the service */
      if (g_strcmp0 (new_owner, proxy->priv->name_owner) == 0)
1371 1372 1373 1374
        {
          G_UNLOCK (properties_lock);
          goto out;
        }
1375 1376 1377 1378 1379

      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);
1380

1381
          g_hash_table_remove_all (proxy->priv->properties);
1382
          G_UNLOCK (properties_lock);
1383 1384 1385 1386 1387 1388
          g_object_notify (G_OBJECT (proxy), "g-name-owner");
        }
      else
        {
          LoadPropertiesOnNameOwnerChangedData *data;

1389 1390
          G_UNLOCK (properties_lock);

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
          /* 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:
1418 1419
  if (proxy != NULL)
    g_object_unref (proxy);
1420 1421 1422 1423
}

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

1424 1425 1426 1427 1428 1429 1430
typedef struct
{
  GDBusProxy *proxy;
  GCancellable *cancellable;
  GSimpleAsyncResult *simple;
} AsyncInitData;

1431
static void
1432
async_init_data_free (AsyncInitData *data)
1433
{
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
  g_object_unref (data->proxy);
  if (data->cancellable != NULL)
    g_object_unref (data->cancellable);
  g_object_unref (data->simple);
  g_free (data);
}

static void
async_init_get_all_cb (GDBusConnection *connection,
                       GAsyncResult    *res,
                       gpointer         user_data)
{
  AsyncInitData *data = user_data;
1447 1448 1449 1450
  GVariant *result;
  GError *error;

  error = NULL;
1451 1452 1453
  result = g_dbus_connection_call_finish (connection,
                                          res,
                                          &error);
1454 1455
  if (result == NULL)
    {
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
      /* 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().
       *
       * TODO: handle G_DBUS_DEBUG flag 'proxy' and, if enabled, log the
       * fact that GetAll() failed
       */
      //g_debug ("error: %d %d %s", error->domain, error->code, error->message);
1467 1468 1469 1470
      g_error_free (error);
    }
  else
    {
1471
      g_simple_async_result_set_op_res_gpointer (data->simple,
1472 1473 1474 1475
                                                 result,
                                                 (GDestroyNotify) g_variant_unref);
    }

1476 1477
  g_simple_async_result_complete_in_idle (data->simple);
  async_init_data_free (data);
1478 1479 1480
}

static void
1481 1482
async_init_data_set_name_owner (AsyncInitData *data,
                                const gchar   *name_owner)
1483
{
1484
  gboolean get_all;
1485

1486

1487
  if (name_owner != NULL)
1488
    {
1489
      /* it starts as NULL anyway */
1490
      G_LOCK (properties_lock);
1491
      data->proxy->priv->name_owner = g_strdup (name_owner);
1492
      G_UNLOCK (properties_lock);
1493
    }
1494

1495 1496 1497 1498 1499 1500 1501
  get_all = TRUE;

  if (data->proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES)
    {
      /* Don't load properties if the API user doesn't want them */
      get_all = FALSE;
    }
1502
  else if (name_owner == NULL && data->proxy->priv->name != NULL)
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
    {
      /* 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)
1513 1514
    {
      /* load all properties asynchronously */
1515
      g_dbus_connection_call (data->proxy->priv->connection,
1516
                              name_owner,
1517
                              data->proxy->priv->object_path,
1518 1519
                              "org.freedesktop.DBus.Properties",
                              "GetAll",
1520
                              g_variant_new ("(s)", data->proxy->priv->interface_name),
1521
                              G_VARIANT_TYPE ("(a{sv})"),
1522 1523
                              G_DBUS_CALL_FLAGS_NONE,
                              -1,           /* timeout */
1524 1525 1526
                              data->cancellable,
                              (GAsyncReadyCallback) async_init_get_all_cb,
                              data);
1527 1528 1529
    }
  else
    {
1530 1531 1532
      g_simple_async_result_complete_in_idle (data->simple);
      async_init_data_free (data);
    }
1533
}
1534

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
static void
async_init_get_name_owner_cb (GDBusConnection *connection,
                              GAsyncResult    *res,
                              gpointer         user_data)
{
  AsyncInitData *data = user_data;
  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);
          async_init_data_set_name_owner (data, NULL);
        }
      else
        {
          g_simple_async_result_take_error (data->simple, error);
          g_simple_async_result_complete_in_idle (data->simple);
          async_init_data_free (data);
        }
    }
  else
    {
      /* borrowed from result to avoid an extra copy */
      const gchar *name_owner;

      g_variant_get (result, "(&s)", &name_owner);
      async_init_data_set_name_owner (data, name_owner);
      g_variant_unref (result);
    }
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
}

static void
async_init_call_get_name_owner (AsyncInitData *data)
{
  g_dbus_connection_call (data->proxy->priv->connection,
                          "org.freedesktop.DBus",  /* name */
                          "/org/freedesktop/DBus", /* object path */
                          "org.freedesktop.DBus",  /* interface */
                          "GetNameOwner",
                          g_variant_new ("(s)",
                                         data->proxy->priv->name),
                          G_VARIANT_TYPE ("(s)"),
                          G_DBUS_CALL_FLAGS_NONE,
                          -1,           /* timeout */
                          data->cancellable,
                          (GAsyncReadyCallback) async_init_get_name_owner_cb,
                          data);
}

static void
async_init_start_service_by_name_cb (GDBusConnection *connection,
                                     GAsyncResult    *res,
                                     gpointer         user_data)
{
  AsyncInitData *data = user_data;
  GError *error;
  GVariant *result;

  error = NULL;
  result = g_dbus_connection_call_finish (connection,
                                          res,
                                          &error);
  if (result == NULL)
    {
      /* Errors are not unexpected; the bus will reply e.g.
       *
       *   org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Epiphany2
       *   was not provided by any .service files
       *
       * This doesn't mean that the name doesn't have an owner, just
       * that it's not provided by a .service file. So just proceed to
       * invoke GetNameOwner() if dealing with that error.
       */
      if (error->domain == G_DBUS_ERROR &&
          error->code == G_DBUS_ERROR_SERVICE_UNKNOWN)
        {
          g_error_free (error);
        }
      else
        {
          g_prefix_error (&error,
                          _("Error calling StartServiceByName for %s: "),
                          data->proxy->priv->name);
          goto failed;
        }
    }
  else
    {
      guint32 start_service_result;
      g_variant_get (result,
                     "(u)",
                     &start_service_result);
      g_variant_unref (result);
      if (start_service_result == 1 ||  /* DBUS_START_REPLY_SUCCESS */
          start_service_result == 2)    /* DBUS_START_REPLY_ALREADY_RUNNING */
        {
          /* continue to invoke GetNameOwner() */
        }
      else
        {
          error = g_error_new (G_IO_ERROR,
                               G_IO_ERROR_FAILED,
                               _("Unexpected reply %d from StartServiceByName(\"%s\") method"),
                               start_service_result,
                               data->proxy->priv->name);
          goto failed;
        }
    }

  async_init_call_get_name_owner (data);
  return;

 failed:
  g_warn_if_fail (error != NULL);
1657
  g_simple_async_result_take_error (data->simple, error);
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
  g_simple_async_result_complete_in_idle (data->simple);
  async_init_data_free (data);
}

static void
async_init_call_start_service_by_name (AsyncInitData *data)
{
  g_dbus_connection_call (data->proxy->priv->connection,
                          "org.freedesktop.DBus",  /* name */
                          "/org/freedesktop/DBus", /* object path */
                          "org.freedesktop.DBus",  /* interface */
                          "StartServiceByName",
                          g_variant_new ("(su)",
                                         data->proxy->priv->name,
                                         0),
                          G_VARIANT_TYPE ("(u)"),
                          G_DBUS_CALL_FLAGS_NONE,
                          -1,           /* timeout */
                          data->cancellable,
                          (GAsyncReadyCallback) async_init_start_service_by_name_cb,
                          data);
}

static void
async_initable_init_second_async (GAsyncInitable      *initable,
                                  gint                 io_priority,
                                  GCancellable        *cancellable,
                                  GAsyncReadyCallback  callback,
                                  gpointer             user_data)
{
  GDBusProxy *proxy = G_DBUS_PROXY (initable);
  AsyncInitData *data;

  data = g_new0 (AsyncInitData, 1);
  data->proxy = g_object_ref (proxy);
  data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
  data->simple = g_simple_async_result_new (G_OBJECT (proxy),
                                            callback,
                                            user_data,
                                            NULL);
1698
  g_simple_async_result_set_check_cancellable (data->simple, cancellable);
1699 1700 1701 1702 1703

  /* Check name ownership asynchronously - possibly also start the service */
  if (proxy->priv->name == NULL)
    {
      /* Do nothing */
1704
      async_init_data_set_name_owner (data, NULL);
1705 1706 1707
    }
  else if (g_dbus_is_unique_name (proxy->priv->name))
    {
1708
      async_init_data_set_name_owner (data, proxy->priv->name);
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    }
  else
    {
      if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START)
        {
          async_init_call_get_name_owner (data);
        }
      else
        {
          async_init_call_start_service_by_name (data);
        }
1720 1721 1722 1723
    }
}

static gboolean
1724 1725 1726
async_initable_init_second_finish (GAsyncInitable  *initable,
                                   GAsyncResult    *res,
                                   GError         **error)
1727 1728 1729 1730 1731 1732 1733 1734
{
  GDBusProxy *proxy = G_DBUS_PROXY (initable);
  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
  GVariant *result;
  gboolean ret;

  ret = FALSE;

1735 1736 1737
  if (g_simple_async_result_propagate_error (simple, error))
    goto out;

1738
  result = g_simple_async_result_get_op_res_gpointer (simple);