gdbusproxy.c 112 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_ADD_PRIVATE (GDBusProxy)
191
                         G_IMPLEMENT_INTERFACE (G_TYPE_DBUS_INTERFACE, dbus_interface_iface_init)
192
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
193
                         G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init))
194

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
                                         G_TYPE_NONE,
                                         3,
                                         G_TYPE_STRING,
                                         G_TYPE_STRING,
                                         G_TYPE_VARIANT);

}

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

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

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

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

  g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);

682 683
  G_LOCK (properties_lock);

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

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

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

 out:
699
  G_UNLOCK (properties_lock);
700 701 702
  return names;
}

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

  if (proxy->priv->expected_interface == NULL)
713
    goto out;
714 715 716

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

717
 out:
718 719 720
  return info;
}

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

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

749 750
  G_LOCK (properties_lock);

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

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

  g_variant_ref (value);

 out:
774
  G_UNLOCK (properties_lock);
775 776 777
  return value;
}

778 779 780 781
/**
 * g_dbus_proxy_set_cached_property:
 * @proxy: A #GDBusProxy
 * @property_name: Property name.
782
 * @value: (allow-none): Value for the property or %NULL to remove it from the cache.
783 784 785 786 787 788 789 790
 *
 * 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
791 792
 * #GDBusProxy:g-interface-info) and @property_name is referenced by
 * it, then @value is checked against the type of the property.
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
 *
 * 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);

831 832
  G_LOCK (properties_lock);

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

861 862 863
/* ---------------------------------------------------------------------------------------------------- */

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

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

888 889 890
  if (!proxy->priv->initialized)
    goto out;

891 892
  G_LOCK (properties_lock);

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

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

923 924
  G_UNLOCK (properties_lock);

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

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

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

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

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

  return;

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

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
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)")))
    {
1002
      g_warning ("Expected type '(v)' for Get() reply, got '%s'", g_variant_get_type_string (value));
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
      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);
}

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

1053 1054 1055
  changed_properties = NULL;
  invalidated_properties = NULL;

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

1069 1070
  if (!proxy->priv->initialized)
    goto out;
1071

1072 1073
  G_LOCK (properties_lock);

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

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

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

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

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

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
  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
1135
    {
1136 1137 1138 1139 1140
      emit_g_signal = TRUE;
      for (n = 0; invalidated_properties[n] != NULL; n++)
        {
          g_hash_table_remove (proxy->priv->properties, invalidated_properties[n]);
        }
1141 1142
    }

1143 1144
  G_UNLOCK (properties_lock);

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

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

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

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

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

1179 1180
  G_LOCK (properties_lock);

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

1190 1191 1192
  num_properties = g_hash_table_size (proxy->priv->properties);
  G_UNLOCK (properties_lock);

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

1209 1210 1211 1212
 out:
  ;
}

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

1230
  cancelled = FALSE;
1231

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
  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);
    }
1253

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

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

1272 1273
  if (data->cancellable == data->proxy->priv->get_all_cancellable)
    data->proxy->priv->get_all_cancellable = NULL;
1274

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

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

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

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

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

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

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

1348 1349
          G_UNLOCK (properties_lock);

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

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

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

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

1387 1388
          G_UNLOCK (properties_lock);

1389 1390 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
          /* 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:
1416 1417
  if (proxy != NULL)
    g_object_unref (proxy);
1418 1419 1420 1421
}

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

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

1429
static void
1430
async_init_data_free (AsyncInitData *data)
1431
{
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
  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;
1445 1446 1447 1448
  GVariant *result;
  GError *error;

  error = NULL;
1449 1450 1451
  result = g_dbus_connection_call_finish (connection,
                                          res,
                                          &error);
1452 1453
  if (result == NULL)
    {
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
      /* 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);
1465 1466 1467 1468
      g_error_free (error);
    }
  else
    {
1469
      g_simple_async_result_set_op_res_gpointer (data->simple,
1470 1471 1472 1473
                                                 result,
                                                 (GDestroyNotify) g_variant_unref);
    }

1474 1475
  g_simple_async_result_complete_in_idle (data->simple);
  async_init_data_free (data);
1476 1477 1478
}

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

1484

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

1493 1494 1495 1496 1497 1498 1499
  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;
    }
1500
  else if (name_owner == NULL && data->proxy->priv->name != NULL)
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
    {
      /* 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)
1511 1512
    {
      /* load all properties asynchronously */
1513
      g_dbus_connection_call (data->proxy->priv->connection,
1514
                              name_owner,
1515
                              data->proxy->priv->object_path,
1516 1517
                              "org.freedesktop.DBus.Properties",
                              "GetAll",
1518
                              g_variant_new ("(s)", data->proxy->priv->interface_name),
1519
                              G_VARIANT_TYPE ("(a{sv})"),
1520 1521
                              G_DBUS_CALL_FLAGS_NONE,
                              -1,           /* timeout */
1522 1523 1524
                              data->cancellable,
                              (GAsyncReadyCallback) async_init_get_all_cb,
                              data);
1525 1526 1527
    }
  else
    {
1528 1529 1530
      g_simple_async_result_complete_in_idle (data->simple);
      async_init_data_free (data);
    }
1531
}
1532

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

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
       *
1610 1611 1612 1613
       * or (see #677718)
       *
       *   org.freedesktop.systemd1.Masked: Unit polkit.service is masked.
       *
1614
       * This doesn't mean that the name doesn't have an owner, just
1615 1616 1617 1618 1619 1620 1621
       * that it's not provided by a .service file or can't currently
       * be started.
       *
       * In particular, in both cases, it could be that a service
       * owner will actually appear later. So instead of erroring out,
       * we just proceed to invoke GetNameOwner() if dealing with the
       * kind of errors above.
1622
       */
1623
      if (error->domain == G_DBUS_ERROR && error->code == G_DBUS_ERROR_SERVICE_UNKNOWN)
1624 1625 1626 1627 1628
        {
          g_error_free (error);
        }
      else
        {
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
          gchar *remote_error = g_dbus_error_get_remote_error (error);
          if (g_strcmp0 (remote_error, "org.freedesktop.systemd1.Masked") == 0)
            {
              g_error_free (error);
              g_free (remote_error);
            }
          else
            {
              g_prefix_error (&error,
                              _("Error calling StartServiceByName for %s: "),
                              data->proxy->priv->name);
              g_free (remote_error);
              goto failed;
            }
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
        }
    }
  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);
1673
  g_simple_async_result_take_error (data->simple, error);
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
  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);
1714
  g_simple_async_result_set_check_cancellable (data->simple, cancellable);