Updated FSF's address
[platform/upstream/glib.git] / gio / gdbusproxy.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: David Zeuthen <davidz@redhat.com>
19  */
20
21 #include "config.h"
22
23 #include <stdlib.h>
24 #include <string.h>
25
26 #include "gdbusutils.h"
27 #include "gdbusproxy.h"
28 #include "gioenumtypes.h"
29 #include "gdbusconnection.h"
30 #include "gdbuserror.h"
31 #include "gdbusprivate.h"
32 #include "ginitable.h"
33 #include "gasyncinitable.h"
34 #include "gioerror.h"
35 #include "gasyncresult.h"
36 #include "gsimpleasyncresult.h"
37 #include "gcancellable.h"
38 #include "gdbusinterface.h"
39
40 #ifdef G_OS_UNIX
41 #include "gunixfdlist.h"
42 #endif
43
44 #include "glibintl.h"
45
46 /**
47  * SECTION:gdbusproxy
48  * @short_description: Client-side D-Bus interface proxy
49  * @include: gio/gio.h
50  *
51  * #GDBusProxy is a base class used for proxies to access a D-Bus
52  * interface on a remote object. A #GDBusProxy can be constructed for
53  * both well-known and unique names.
54  *
55  * By default, #GDBusProxy will cache all properties (and listen to
56  * changes) of the remote object, and proxy all signals that gets
57  * emitted. This behaviour can be changed by passing suitable
58  * #GDBusProxyFlags when the proxy is created. If the proxy is for a
59  * well-known name, the property cache is flushed when the name owner
60  * vanishes and reloaded when a name owner appears.
61  *
62  * If a #GDBusProxy is used for a well-known name, the owner of the
63  * name is tracked and can be read from
64  * #GDBusProxy:g-name-owner. Connect to the #GObject::notify signal to
65  * get notified of changes. Additionally, only signals and property
66  * changes emitted from the current name owner are considered and
67  * calls are always sent to the current name owner. This avoids a
68  * number of race conditions when the name is lost by one owner and
69  * claimed by another. However, if no name owner currently exists,
70  * then calls will be sent to the well-known name which may result in
71  * the message bus launching an owner (unless
72  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START is set).
73  *
74  * The generic #GDBusProxy::g-properties-changed and
75  * #GDBusProxy::g-signal signals are not very convenient to work
76  * with. Therefore, the recommended way of working with proxies is to
77  * subclass #GDBusProxy, and have more natural properties and signals
78  * in your derived class. See <xref linkend="gdbus-example-gdbus-codegen"/>
79  * for how this can easily be done using the
80  * <command><link linkend="gdbus-codegen">gdbus-codegen</link></command>
81  * tool.
82  *
83  * A #GDBusProxy instance can be used from multiple threads but note
84  * that all signals (e.g. #GDBusProxy::g-signal, #GDBusProxy::g-properties-changed
85  * and #GObject::notify) are emitted in the
86  * <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
87  * of the thread where the instance was constructed.
88  *
89  * <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>
90  */
91
92 /* lock protecting the mutable properties: name_owner, timeout_msec,
93  * expected_interface, and the properties hash table
94  */
95 G_LOCK_DEFINE_STATIC (properties_lock);
96
97 /* ---------------------------------------------------------------------------------------------------- */
98
99 G_LOCK_DEFINE_STATIC (signal_subscription_lock);
100
101 typedef struct
102 {
103   volatile gint ref_count;
104   GDBusProxy *proxy;
105 } SignalSubscriptionData;
106
107 static SignalSubscriptionData *
108 signal_subscription_ref (SignalSubscriptionData *data)
109 {
110   g_atomic_int_inc (&data->ref_count);
111   return data;
112 }
113
114 static void
115 signal_subscription_unref (SignalSubscriptionData *data)
116 {
117   if (g_atomic_int_dec_and_test (&data->ref_count))
118     {
119       g_slice_free (SignalSubscriptionData, data);
120     }
121 }
122
123 /* ---------------------------------------------------------------------------------------------------- */
124
125 struct _GDBusProxyPrivate
126 {
127   GBusType bus_type;
128   GDBusProxyFlags flags;
129   GDBusConnection *connection;
130
131   gchar *name;
132   /* mutable, protected by properties_lock */
133   gchar *name_owner;
134   gchar *object_path;
135   gchar *interface_name;
136   /* mutable, protected by properties_lock */
137   gint timeout_msec;
138
139   guint name_owner_changed_subscription_id;
140
141   GCancellable *get_all_cancellable;
142
143   /* gchar* -> GVariant*, protected by properties_lock */
144   GHashTable *properties;
145
146   /* mutable, protected by properties_lock */
147   GDBusInterfaceInfo *expected_interface;
148
149   guint properties_changed_subscription_id;
150   guint signals_subscription_id;
151
152   gboolean initialized;
153
154   /* mutable, protected by properties_lock */
155   GDBusObject *object;
156
157   SignalSubscriptionData *signal_subscription_data;
158 };
159
160 enum
161 {
162   PROP_0,
163   PROP_G_CONNECTION,
164   PROP_G_BUS_TYPE,
165   PROP_G_NAME,
166   PROP_G_NAME_OWNER,
167   PROP_G_FLAGS,
168   PROP_G_OBJECT_PATH,
169   PROP_G_INTERFACE_NAME,
170   PROP_G_DEFAULT_TIMEOUT,
171   PROP_G_INTERFACE_INFO
172 };
173
174 enum
175 {
176   PROPERTIES_CHANGED_SIGNAL,
177   SIGNAL_SIGNAL,
178   LAST_SIGNAL,
179 };
180
181 static guint signals[LAST_SIGNAL] = {0};
182
183 static void dbus_interface_iface_init (GDBusInterfaceIface *dbus_interface_iface);
184 static void initable_iface_init       (GInitableIface *initable_iface);
185 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
186
187 G_DEFINE_TYPE_WITH_CODE (GDBusProxy, g_dbus_proxy, G_TYPE_OBJECT,
188                          G_ADD_PRIVATE (GDBusProxy)
189                          G_IMPLEMENT_INTERFACE (G_TYPE_DBUS_INTERFACE, dbus_interface_iface_init)
190                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
191                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init))
192
193 static void
194 g_dbus_proxy_dispose (GObject *object)
195 {
196   GDBusProxy *proxy = G_DBUS_PROXY (object);
197   G_LOCK (signal_subscription_lock);
198   if (proxy->priv->signal_subscription_data != NULL)
199     {
200       proxy->priv->signal_subscription_data->proxy = NULL;
201       signal_subscription_unref (proxy->priv->signal_subscription_data);
202       proxy->priv->signal_subscription_data = NULL;
203     }
204   G_UNLOCK (signal_subscription_lock);
205
206   G_OBJECT_CLASS (g_dbus_proxy_parent_class)->dispose (object);
207 }
208
209 static void
210 g_dbus_proxy_finalize (GObject *object)
211 {
212   GDBusProxy *proxy = G_DBUS_PROXY (object);
213
214   g_warn_if_fail (proxy->priv->get_all_cancellable == NULL);
215
216   if (proxy->priv->name_owner_changed_subscription_id > 0)
217     g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
218                                           proxy->priv->name_owner_changed_subscription_id);
219
220   if (proxy->priv->properties_changed_subscription_id > 0)
221     g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
222                                           proxy->priv->properties_changed_subscription_id);
223
224   if (proxy->priv->signals_subscription_id > 0)
225     g_dbus_connection_signal_unsubscribe (proxy->priv->connection,
226                                           proxy->priv->signals_subscription_id);
227
228   if (proxy->priv->connection != NULL)
229     g_object_unref (proxy->priv->connection);
230   g_free (proxy->priv->name);
231   g_free (proxy->priv->name_owner);
232   g_free (proxy->priv->object_path);
233   g_free (proxy->priv->interface_name);
234   if (proxy->priv->properties != NULL)
235     g_hash_table_unref (proxy->priv->properties);
236
237   if (proxy->priv->expected_interface != NULL)
238     {
239       g_dbus_interface_info_cache_release (proxy->priv->expected_interface);
240       g_dbus_interface_info_unref (proxy->priv->expected_interface);
241     }
242
243   if (proxy->priv->object != NULL)
244     g_object_remove_weak_pointer (G_OBJECT (proxy->priv->object), (gpointer *) &proxy->priv->object);
245
246   G_OBJECT_CLASS (g_dbus_proxy_parent_class)->finalize (object);
247 }
248
249 static void
250 g_dbus_proxy_get_property (GObject    *object,
251                            guint       prop_id,
252                            GValue     *value,
253                            GParamSpec *pspec)
254 {
255   GDBusProxy *proxy = G_DBUS_PROXY (object);
256
257   switch (prop_id)
258     {
259     case PROP_G_CONNECTION:
260       g_value_set_object (value, proxy->priv->connection);
261       break;
262
263     case PROP_G_FLAGS:
264       g_value_set_flags (value, proxy->priv->flags);
265       break;
266
267     case PROP_G_NAME:
268       g_value_set_string (value, proxy->priv->name);
269       break;
270
271     case PROP_G_NAME_OWNER:
272       g_value_take_string (value, g_dbus_proxy_get_name_owner (proxy));
273       break;
274
275     case PROP_G_OBJECT_PATH:
276       g_value_set_string (value, proxy->priv->object_path);
277       break;
278
279     case PROP_G_INTERFACE_NAME:
280       g_value_set_string (value, proxy->priv->interface_name);
281       break;
282
283     case PROP_G_DEFAULT_TIMEOUT:
284       g_value_set_int (value, g_dbus_proxy_get_default_timeout (proxy));
285       break;
286
287     case PROP_G_INTERFACE_INFO:
288       g_value_set_boxed (value, g_dbus_proxy_get_interface_info (proxy));
289       break;
290
291     default:
292       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
293       break;
294     }
295 }
296
297 static void
298 g_dbus_proxy_set_property (GObject      *object,
299                            guint         prop_id,
300                            const GValue *value,
301                            GParamSpec   *pspec)
302 {
303   GDBusProxy *proxy = G_DBUS_PROXY (object);
304
305   switch (prop_id)
306     {
307     case PROP_G_CONNECTION:
308       proxy->priv->connection = g_value_dup_object (value);
309       break;
310
311     case PROP_G_FLAGS:
312       proxy->priv->flags = g_value_get_flags (value);
313       break;
314
315     case PROP_G_NAME:
316       proxy->priv->name = g_value_dup_string (value);
317       break;
318
319     case PROP_G_OBJECT_PATH:
320       proxy->priv->object_path = g_value_dup_string (value);
321       break;
322
323     case PROP_G_INTERFACE_NAME:
324       proxy->priv->interface_name = g_value_dup_string (value);
325       break;
326
327     case PROP_G_DEFAULT_TIMEOUT:
328       g_dbus_proxy_set_default_timeout (proxy, g_value_get_int (value));
329       break;
330
331     case PROP_G_INTERFACE_INFO:
332       g_dbus_proxy_set_interface_info (proxy, g_value_get_boxed (value));
333       break;
334
335     case PROP_G_BUS_TYPE:
336       proxy->priv->bus_type = g_value_get_enum (value);
337       break;
338
339     default:
340       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
341       break;
342     }
343 }
344
345 static void
346 g_dbus_proxy_class_init (GDBusProxyClass *klass)
347 {
348   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
349
350   gobject_class->dispose      = g_dbus_proxy_dispose;
351   gobject_class->finalize     = g_dbus_proxy_finalize;
352   gobject_class->set_property = g_dbus_proxy_set_property;
353   gobject_class->get_property = g_dbus_proxy_get_property;
354
355   /* Note that all property names are prefixed to avoid collisions with D-Bus property names
356    * in derived classes */
357
358   /**
359    * GDBusProxy:g-interface-info:
360    *
361    * Ensure that interactions with this proxy conform to the given
362    * interface. This is mainly to ensure that malformed data received
363    * from the other peer is ignored. The given #GDBusInterfaceInfo is
364    * said to be the <emphasis>expected interface</emphasis>.
365    *
366    * The checks performed are:
367    * <itemizedlist>
368    *   <listitem><para>
369    *     When completing a method call, if the type signature of
370    *     the reply message isn't what's expected, the reply is
371    *     discarded and the #GError is set to %G_IO_ERROR_INVALID_ARGUMENT.
372    *   </para></listitem>
373    *   <listitem><para>
374    *     Received signals that have a type signature mismatch are dropped and
375    *     a warning is logged via g_warning().
376    *   </para></listitem>
377    *   <listitem><para>
378    *     Properties received via the initial <literal>GetAll()</literal> call
379    *     or via the <literal>::PropertiesChanged</literal> signal (on the
380    *     <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties">org.freedesktop.DBus.Properties</ulink> interface) or
381    *     set using g_dbus_proxy_set_cached_property() with a type signature
382    *     mismatch are ignored and a warning is logged via g_warning().
383    *   </para></listitem>
384    * </itemizedlist>
385    * Note that these checks are never done on methods, signals and
386    * properties that are not referenced in the given
387    * #GDBusInterfaceInfo, since extending a D-Bus interface on the
388    * service-side is not considered an ABI break.
389    *
390    * Since: 2.26
391    */
392   g_object_class_install_property (gobject_class,
393                                    PROP_G_INTERFACE_INFO,
394                                    g_param_spec_boxed ("g-interface-info",
395                                                        P_("Interface Information"),
396                                                        P_("Interface Information"),
397                                                        G_TYPE_DBUS_INTERFACE_INFO,
398                                                        G_PARAM_READABLE |
399                                                        G_PARAM_WRITABLE |
400                                                        G_PARAM_STATIC_NAME |
401                                                        G_PARAM_STATIC_BLURB |
402                                                        G_PARAM_STATIC_NICK));
403
404   /**
405    * GDBusProxy:g-connection:
406    *
407    * The #GDBusConnection the proxy is for.
408    *
409    * Since: 2.26
410    */
411   g_object_class_install_property (gobject_class,
412                                    PROP_G_CONNECTION,
413                                    g_param_spec_object ("g-connection",
414                                                         P_("g-connection"),
415                                                         P_("The connection the proxy is for"),
416                                                         G_TYPE_DBUS_CONNECTION,
417                                                         G_PARAM_READABLE |
418                                                         G_PARAM_WRITABLE |
419                                                         G_PARAM_CONSTRUCT_ONLY |
420                                                         G_PARAM_STATIC_NAME |
421                                                         G_PARAM_STATIC_BLURB |
422                                                         G_PARAM_STATIC_NICK));
423
424   /**
425    * GDBusProxy:g-bus-type:
426    *
427    * If this property is not %G_BUS_TYPE_NONE, then
428    * #GDBusProxy:g-connection must be %NULL and will be set to the
429    * #GDBusConnection obtained by calling g_bus_get() with the value
430    * of this property.
431    *
432    * Since: 2.26
433    */
434   g_object_class_install_property (gobject_class,
435                                    PROP_G_BUS_TYPE,
436                                    g_param_spec_enum ("g-bus-type",
437                                                       P_("Bus Type"),
438                                                       P_("The bus to connect to, if any"),
439                                                       G_TYPE_BUS_TYPE,
440                                                       G_BUS_TYPE_NONE,
441                                                       G_PARAM_WRITABLE |
442                                                       G_PARAM_CONSTRUCT_ONLY |
443                                                       G_PARAM_STATIC_NAME |
444                                                       G_PARAM_STATIC_BLURB |
445                                                       G_PARAM_STATIC_NICK));
446
447   /**
448    * GDBusProxy:g-flags:
449    *
450    * Flags from the #GDBusProxyFlags enumeration.
451    *
452    * Since: 2.26
453    */
454   g_object_class_install_property (gobject_class,
455                                    PROP_G_FLAGS,
456                                    g_param_spec_flags ("g-flags",
457                                                        P_("g-flags"),
458                                                        P_("Flags for the proxy"),
459                                                        G_TYPE_DBUS_PROXY_FLAGS,
460                                                        G_DBUS_PROXY_FLAGS_NONE,
461                                                        G_PARAM_READABLE |
462                                                        G_PARAM_WRITABLE |
463                                                        G_PARAM_CONSTRUCT_ONLY |
464                                                        G_PARAM_STATIC_NAME |
465                                                        G_PARAM_STATIC_BLURB |
466                                                        G_PARAM_STATIC_NICK));
467
468   /**
469    * GDBusProxy:g-name:
470    *
471    * The well-known or unique name that the proxy is for.
472    *
473    * Since: 2.26
474    */
475   g_object_class_install_property (gobject_class,
476                                    PROP_G_NAME,
477                                    g_param_spec_string ("g-name",
478                                                         P_("g-name"),
479                                                         P_("The well-known or unique name that the proxy is for"),
480                                                         NULL,
481                                                         G_PARAM_READABLE |
482                                                         G_PARAM_WRITABLE |
483                                                         G_PARAM_CONSTRUCT_ONLY |
484                                                         G_PARAM_STATIC_NAME |
485                                                         G_PARAM_STATIC_BLURB |
486                                                         G_PARAM_STATIC_NICK));
487
488   /**
489    * GDBusProxy:g-name-owner:
490    *
491    * The unique name that owns #GDBusProxy:g-name or %NULL if no-one
492    * currently owns that name. You may connect to #GObject::notify signal to
493    * track changes to this property.
494    *
495    * Since: 2.26
496    */
497   g_object_class_install_property (gobject_class,
498                                    PROP_G_NAME_OWNER,
499                                    g_param_spec_string ("g-name-owner",
500                                                         P_("g-name-owner"),
501                                                         P_("The unique name for the owner"),
502                                                         NULL,
503                                                         G_PARAM_READABLE |
504                                                         G_PARAM_STATIC_NAME |
505                                                         G_PARAM_STATIC_BLURB |
506                                                         G_PARAM_STATIC_NICK));
507
508   /**
509    * GDBusProxy:g-object-path:
510    *
511    * The object path the proxy is for.
512    *
513    * Since: 2.26
514    */
515   g_object_class_install_property (gobject_class,
516                                    PROP_G_OBJECT_PATH,
517                                    g_param_spec_string ("g-object-path",
518                                                         P_("g-object-path"),
519                                                         P_("The object path the proxy is for"),
520                                                         NULL,
521                                                         G_PARAM_READABLE |
522                                                         G_PARAM_WRITABLE |
523                                                         G_PARAM_CONSTRUCT_ONLY |
524                                                         G_PARAM_STATIC_NAME |
525                                                         G_PARAM_STATIC_BLURB |
526                                                         G_PARAM_STATIC_NICK));
527
528   /**
529    * GDBusProxy:g-interface-name:
530    *
531    * The D-Bus interface name the proxy is for.
532    *
533    * Since: 2.26
534    */
535   g_object_class_install_property (gobject_class,
536                                    PROP_G_INTERFACE_NAME,
537                                    g_param_spec_string ("g-interface-name",
538                                                         P_("g-interface-name"),
539                                                         P_("The D-Bus interface name the proxy is for"),
540                                                         NULL,
541                                                         G_PARAM_READABLE |
542                                                         G_PARAM_WRITABLE |
543                                                         G_PARAM_CONSTRUCT_ONLY |
544                                                         G_PARAM_STATIC_NAME |
545                                                         G_PARAM_STATIC_BLURB |
546                                                         G_PARAM_STATIC_NICK));
547
548   /**
549    * GDBusProxy:g-default-timeout:
550    *
551    * The timeout to use if -1 (specifying default timeout) is passed
552    * as @timeout_msec in the g_dbus_proxy_call() and
553    * g_dbus_proxy_call_sync() functions.
554    *
555    * This allows applications to set a proxy-wide timeout for all
556    * remote method invocations on the proxy. If this property is -1,
557    * the default timeout (typically 25 seconds) is used. If set to
558    * %G_MAXINT, then no timeout is used.
559    *
560    * Since: 2.26
561    */
562   g_object_class_install_property (gobject_class,
563                                    PROP_G_DEFAULT_TIMEOUT,
564                                    g_param_spec_int ("g-default-timeout",
565                                                      P_("Default Timeout"),
566                                                      P_("Timeout for remote method invocation"),
567                                                      -1,
568                                                      G_MAXINT,
569                                                      -1,
570                                                      G_PARAM_READABLE |
571                                                      G_PARAM_WRITABLE |
572                                                      G_PARAM_CONSTRUCT |
573                                                      G_PARAM_STATIC_NAME |
574                                                      G_PARAM_STATIC_BLURB |
575                                                      G_PARAM_STATIC_NICK));
576
577   /**
578    * GDBusProxy::g-properties-changed:
579    * @proxy: The #GDBusProxy emitting the signal.
580    * @changed_properties: A #GVariant containing the properties that changed
581    * @invalidated_properties: A %NULL terminated array of properties that was invalidated
582    *
583    * Emitted when one or more D-Bus properties on @proxy changes. The
584    * local cache has already been updated when this signal fires. Note
585    * that both @changed_properties and @invalidated_properties are
586    * guaranteed to never be %NULL (either may be empty though).
587    *
588    * If the proxy has the flag
589    * %G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES set, then
590    * @invalidated_properties will always be empty.
591    *
592    * This signal corresponds to the
593    * <literal>PropertiesChanged</literal> D-Bus signal on the
594    * <literal>org.freedesktop.DBus.Properties</literal> interface.
595    *
596    * Since: 2.26
597    */
598   signals[PROPERTIES_CHANGED_SIGNAL] = g_signal_new ("g-properties-changed",
599                                                      G_TYPE_DBUS_PROXY,
600                                                      G_SIGNAL_RUN_LAST | G_SIGNAL_MUST_COLLECT,
601                                                      G_STRUCT_OFFSET (GDBusProxyClass, g_properties_changed),
602                                                      NULL,
603                                                      NULL,
604                                                      NULL,
605                                                      G_TYPE_NONE,
606                                                      2,
607                                                      G_TYPE_VARIANT,
608                                                      G_TYPE_STRV | G_SIGNAL_TYPE_STATIC_SCOPE);
609
610   /**
611    * GDBusProxy::g-signal:
612    * @proxy: The #GDBusProxy emitting the signal.
613    * @sender_name: (allow-none): The sender of the signal or %NULL if the connection is not a bus connection.
614    * @signal_name: The name of the signal.
615    * @parameters: A #GVariant tuple with parameters for the signal.
616    *
617    * Emitted when a signal from the remote object and interface that @proxy is for, has been received.
618    *
619    * Since: 2.26
620    */
621   signals[SIGNAL_SIGNAL] = g_signal_new ("g-signal",
622                                          G_TYPE_DBUS_PROXY,
623                                          G_SIGNAL_RUN_LAST | G_SIGNAL_MUST_COLLECT,
624                                          G_STRUCT_OFFSET (GDBusProxyClass, g_signal),
625                                          NULL,
626                                          NULL,
627                                          NULL,
628                                          G_TYPE_NONE,
629                                          3,
630                                          G_TYPE_STRING,
631                                          G_TYPE_STRING,
632                                          G_TYPE_VARIANT);
633
634 }
635
636 static void
637 g_dbus_proxy_init (GDBusProxy *proxy)
638 {
639   proxy->priv = g_dbus_proxy_get_instance_private (proxy);
640   proxy->priv->signal_subscription_data = g_slice_new0 (SignalSubscriptionData);
641   proxy->priv->signal_subscription_data->ref_count = 1;
642   proxy->priv->signal_subscription_data->proxy = proxy;
643   proxy->priv->properties = g_hash_table_new_full (g_str_hash,
644                                                    g_str_equal,
645                                                    g_free,
646                                                    (GDestroyNotify) g_variant_unref);
647 }
648
649 /* ---------------------------------------------------------------------------------------------------- */
650
651 static gint
652 property_name_sort_func (const gchar **a,
653                          const gchar **b)
654 {
655   return g_strcmp0 (*a, *b);
656 }
657
658 /**
659  * g_dbus_proxy_get_cached_property_names:
660  * @proxy: A #GDBusProxy.
661  *
662  * Gets the names of all cached properties on @proxy.
663  *
664  * Returns: (transfer full): A %NULL-terminated array of strings or %NULL if
665  *          @proxy has no cached properties. Free the returned array with
666  *          g_strfreev().
667  *
668  * Since: 2.26
669  */
670 gchar **
671 g_dbus_proxy_get_cached_property_names (GDBusProxy  *proxy)
672 {
673   gchar **names;
674   GPtrArray *p;
675   GHashTableIter iter;
676   const gchar *key;
677
678   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
679
680   G_LOCK (properties_lock);
681
682   names = NULL;
683   if (g_hash_table_size (proxy->priv->properties) == 0)
684     goto out;
685
686   p = g_ptr_array_new ();
687
688   g_hash_table_iter_init (&iter, proxy->priv->properties);
689   while (g_hash_table_iter_next (&iter, (gpointer) &key, NULL))
690     g_ptr_array_add (p, g_strdup (key));
691   g_ptr_array_sort (p, (GCompareFunc) property_name_sort_func);
692   g_ptr_array_add (p, NULL);
693
694   names = (gchar **) g_ptr_array_free (p, FALSE);
695
696  out:
697   G_UNLOCK (properties_lock);
698   return names;
699 }
700
701 /* properties_lock must be held for as long as you will keep the
702  * returned value
703  */
704 static const GDBusPropertyInfo *
705 lookup_property_info (GDBusProxy  *proxy,
706                       const gchar *property_name)
707 {
708   const GDBusPropertyInfo *info = NULL;
709
710   if (proxy->priv->expected_interface == NULL)
711     goto out;
712
713   info = g_dbus_interface_info_lookup_property (proxy->priv->expected_interface, property_name);
714
715  out:
716   return info;
717 }
718
719 /**
720  * g_dbus_proxy_get_cached_property:
721  * @proxy: A #GDBusProxy.
722  * @property_name: Property name.
723  *
724  * Looks up the value for a property from the cache. This call does no
725  * blocking IO.
726  *
727  * If @proxy has an expected interface (see
728  * #GDBusProxy:g-interface-info) and @property_name is referenced by
729  * it, then @value is checked against the type of the property.
730  *
731  * Returns: A reference to the #GVariant instance that holds the value
732  * for @property_name or %NULL if the value is not in the cache. The
733  * returned reference must be freed with g_variant_unref().
734  *
735  * Since: 2.26
736  */
737 GVariant *
738 g_dbus_proxy_get_cached_property (GDBusProxy   *proxy,
739                                   const gchar  *property_name)
740 {
741   const GDBusPropertyInfo *info;
742   GVariant *value;
743
744   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
745   g_return_val_if_fail (property_name != NULL, NULL);
746
747   G_LOCK (properties_lock);
748
749   value = g_hash_table_lookup (proxy->priv->properties, property_name);
750   if (value == NULL)
751     goto out;
752
753   info = lookup_property_info (proxy, property_name);
754   if (info != NULL)
755     {
756       const gchar *type_string = g_variant_get_type_string (value);
757       if (g_strcmp0 (type_string, info->signature) != 0)
758         {
759           g_warning ("Trying to get property %s with type %s but according to the expected "
760                      "interface the type is %s",
761                      property_name,
762                      type_string,
763                      info->signature);
764           value = NULL;
765           goto out;
766         }
767     }
768
769   g_variant_ref (value);
770
771  out:
772   G_UNLOCK (properties_lock);
773   return value;
774 }
775
776 /**
777  * g_dbus_proxy_set_cached_property:
778  * @proxy: A #GDBusProxy
779  * @property_name: Property name.
780  * @value: (allow-none): Value for the property or %NULL to remove it from the cache.
781  *
782  * If @value is not %NULL, sets the cached value for the property with
783  * name @property_name to the value in @value.
784  *
785  * If @value is %NULL, then the cached value is removed from the
786  * property cache.
787  *
788  * If @proxy has an expected interface (see
789  * #GDBusProxy:g-interface-info) and @property_name is referenced by
790  * it, then @value is checked against the type of the property.
791  *
792  * If the @value #GVariant is floating, it is consumed. This allows
793  * convenient 'inline' use of g_variant_new(), e.g.
794  * |[
795  *  g_dbus_proxy_set_cached_property (proxy,
796  *                                    "SomeProperty",
797  *                                    g_variant_new ("(si)",
798  *                                                  "A String",
799  *                                                  42));
800  * ]|
801  *
802  * Normally you will not need to use this method since @proxy is
803  * tracking changes using the
804  * <literal>org.freedesktop.DBus.Properties.PropertiesChanged</literal>
805  * D-Bus signal. However, for performance reasons an object may decide
806  * to not use this signal for some properties and instead use a
807  * proprietary out-of-band mechanism to transmit changes.
808  *
809  * As a concrete example, consider an object with a property
810  * <literal>ChatroomParticipants</literal> which is an array of
811  * strings. Instead of transmitting the same (long) array every time
812  * the property changes, it is more efficient to only transmit the
813  * delta using e.g. signals <literal>ChatroomParticipantJoined(String
814  * name)</literal> and <literal>ChatroomParticipantParted(String
815  * name)</literal>.
816  *
817  * Since: 2.26
818  */
819 void
820 g_dbus_proxy_set_cached_property (GDBusProxy   *proxy,
821                                   const gchar  *property_name,
822                                   GVariant     *value)
823 {
824   const GDBusPropertyInfo *info;
825
826   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
827   g_return_if_fail (property_name != NULL);
828
829   G_LOCK (properties_lock);
830
831   if (value != NULL)
832     {
833       info = lookup_property_info (proxy, property_name);
834       if (info != NULL)
835         {
836           if (g_strcmp0 (info->signature, g_variant_get_type_string (value)) != 0)
837             {
838               g_warning ("Trying to set property %s of type %s but according to the expected "
839                          "interface the type is %s",
840                          property_name,
841                          g_variant_get_type_string (value),
842                          info->signature);
843               goto out;
844             }
845         }
846       g_hash_table_insert (proxy->priv->properties,
847                            g_strdup (property_name),
848                            g_variant_ref_sink (value));
849     }
850   else
851     {
852       g_hash_table_remove (proxy->priv->properties, property_name);
853     }
854
855  out:
856   G_UNLOCK (properties_lock);
857 }
858
859 /* ---------------------------------------------------------------------------------------------------- */
860
861 static void
862 on_signal_received (GDBusConnection *connection,
863                     const gchar     *sender_name,
864                     const gchar     *object_path,
865                     const gchar     *interface_name,
866                     const gchar     *signal_name,
867                     GVariant        *parameters,
868                     gpointer         user_data)
869 {
870   SignalSubscriptionData *data = user_data;
871   GDBusProxy *proxy;
872
873   G_LOCK (signal_subscription_lock);
874   proxy = data->proxy;
875   if (proxy == NULL)
876     {
877       G_UNLOCK (signal_subscription_lock);
878       return;
879     }
880   else
881     {
882       g_object_ref (proxy);
883       G_UNLOCK (signal_subscription_lock);
884     }
885
886   if (!proxy->priv->initialized)
887     goto out;
888
889   G_LOCK (properties_lock);
890
891   if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
892     {
893       G_UNLOCK (properties_lock);
894       goto out;
895     }
896
897   if (proxy->priv->expected_interface != NULL)
898     {
899       const GDBusSignalInfo *info;
900       info = g_dbus_interface_info_lookup_signal (proxy->priv->expected_interface, signal_name);
901       if (info != NULL)
902         {
903           GVariantType *expected_type;
904           expected_type = _g_dbus_compute_complete_signature (info->args);
905           if (!g_variant_type_equal (expected_type, g_variant_get_type (parameters)))
906             {
907               gchar *expected_type_string = g_variant_type_dup_string (expected_type);
908               g_warning ("Dropping signal %s of type %s since the type from the expected interface is %s",
909                          info->name,
910                          g_variant_get_type_string (parameters),
911                          expected_type_string);
912               g_free (expected_type_string);
913               g_variant_type_free (expected_type);
914               G_UNLOCK (properties_lock);
915               goto out;
916             }
917           g_variant_type_free (expected_type);
918         }
919     }
920
921   G_UNLOCK (properties_lock);
922
923   g_signal_emit (proxy,
924                  signals[SIGNAL_SIGNAL],
925                  0,
926                  sender_name,
927                  signal_name,
928                  parameters);
929
930  out:
931   if (proxy != NULL)
932     g_object_unref (proxy);
933 }
934
935 /* ---------------------------------------------------------------------------------------------------- */
936
937 /* must hold properties_lock */
938 static void
939 insert_property_checked (GDBusProxy  *proxy,
940                          gchar *property_name,
941                          GVariant *value)
942 {
943   if (proxy->priv->expected_interface != NULL)
944     {
945       const GDBusPropertyInfo *info;
946       info = g_dbus_interface_info_lookup_property (proxy->priv->expected_interface, property_name);
947       /* Only check known properties */
948       if (info != NULL)
949         {
950           /* Warn about properties with the wrong type */
951           if (g_strcmp0 (info->signature, g_variant_get_type_string (value)) != 0)
952             {
953               g_warning ("Received property %s with type %s does not match expected type "
954                          "%s in the expected interface",
955                          property_name,
956                          g_variant_get_type_string (value),
957                          info->signature);
958               goto invalid;
959             }
960         }
961     }
962
963   g_hash_table_insert (proxy->priv->properties,
964                        property_name, /* adopts string */
965                        value); /* adopts value */
966
967   return;
968
969  invalid:
970   g_variant_unref (value);
971   g_free (property_name);
972 }
973
974 typedef struct
975 {
976   GDBusProxy *proxy;
977   gchar *prop_name;
978 } InvalidatedPropGetData;
979
980 static void
981 invalidated_property_get_cb (GDBusConnection *connection,
982                              GAsyncResult    *res,
983                              gpointer         user_data)
984 {
985   InvalidatedPropGetData *data = user_data;
986   const gchar *invalidated_properties[] = {NULL};
987   GVariantBuilder builder;
988   GVariant *value = NULL;
989   GVariant *unpacked_value = NULL;
990
991   /* errors are fine, the other end could have disconnected */
992   value = g_dbus_connection_call_finish (connection, res, NULL);
993   if (value == NULL)
994     {
995       goto out;
996     }
997
998   if (!g_variant_is_of_type (value, G_VARIANT_TYPE ("(v)")))
999     {
1000       g_warning ("Expected type '(v)' for Get() reply, got '%s'", g_variant_get_type_string (value));
1001       goto out;
1002     }
1003
1004   g_variant_get (value, "(v)", &unpacked_value);
1005
1006   /* synthesize the a{sv} in the PropertiesChanged signal */
1007   g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
1008   g_variant_builder_add (&builder, "{sv}", data->prop_name, unpacked_value);
1009
1010   G_LOCK (properties_lock);
1011   insert_property_checked (data->proxy,
1012                            data->prop_name,  /* adopts string */
1013                            unpacked_value);  /* adopts value */
1014   data->prop_name = NULL;
1015   G_UNLOCK (properties_lock);
1016
1017   g_signal_emit (data->proxy,
1018                  signals[PROPERTIES_CHANGED_SIGNAL], 0,
1019                  g_variant_builder_end (&builder), /* consumed */
1020                  invalidated_properties);
1021
1022
1023  out:
1024   if (value != NULL)
1025     g_variant_unref (value);
1026   g_object_unref (data->proxy);
1027   g_free (data->prop_name);
1028   g_slice_free (InvalidatedPropGetData, data);
1029 }
1030
1031 static void
1032 on_properties_changed (GDBusConnection *connection,
1033                        const gchar     *sender_name,
1034                        const gchar     *object_path,
1035                        const gchar     *interface_name,
1036                        const gchar     *signal_name,
1037                        GVariant        *parameters,
1038                        gpointer         user_data)
1039 {
1040   SignalSubscriptionData *data = user_data;
1041   gboolean emit_g_signal = FALSE;
1042   GDBusProxy *proxy;
1043   const gchar *interface_name_for_signal;
1044   GVariant *changed_properties;
1045   gchar **invalidated_properties;
1046   GVariantIter iter;
1047   gchar *key;
1048   GVariant *value;
1049   guint n;
1050
1051   changed_properties = NULL;
1052   invalidated_properties = NULL;
1053
1054   G_LOCK (signal_subscription_lock);
1055   proxy = data->proxy;
1056   if (proxy == NULL)
1057     {
1058       G_UNLOCK (signal_subscription_lock);
1059       goto out;
1060     }
1061   else
1062     {
1063       g_object_ref (proxy);
1064       G_UNLOCK (signal_subscription_lock);
1065     }
1066
1067   if (!proxy->priv->initialized)
1068     goto out;
1069
1070   G_LOCK (properties_lock);
1071
1072   if (proxy->priv->name_owner != NULL && g_strcmp0 (sender_name, proxy->priv->name_owner) != 0)
1073     {
1074       G_UNLOCK (properties_lock);
1075       goto out;
1076     }
1077
1078   if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(sa{sv}as)")))
1079     {
1080       g_warning ("Value for PropertiesChanged signal with type '%s' does not match '(sa{sv}as)'",
1081                  g_variant_get_type_string (parameters));
1082       G_UNLOCK (properties_lock);
1083       goto out;
1084     }
1085
1086   g_variant_get (parameters,
1087                  "(&s@a{sv}^a&s)",
1088                  &interface_name_for_signal,
1089                  &changed_properties,
1090                  &invalidated_properties);
1091
1092   if (g_strcmp0 (interface_name_for_signal, proxy->priv->interface_name) != 0)
1093     {
1094       G_UNLOCK (properties_lock);
1095       goto out;
1096     }
1097
1098   g_variant_iter_init (&iter, changed_properties);
1099   while (g_variant_iter_next (&iter, "{sv}", &key, &value))
1100     {
1101       insert_property_checked (proxy,
1102                                key, /* adopts string */
1103                                value); /* adopts value */
1104       emit_g_signal = TRUE;
1105     }
1106
1107   if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES)
1108     {
1109       if (proxy->priv->name_owner != NULL)
1110         {
1111           for (n = 0; invalidated_properties[n] != NULL; n++)
1112             {
1113               InvalidatedPropGetData *data;
1114               data = g_slice_new0 (InvalidatedPropGetData);
1115               data->proxy = g_object_ref (proxy);
1116               data->prop_name = g_strdup (invalidated_properties[n]);
1117               g_dbus_connection_call (proxy->priv->connection,
1118                                       proxy->priv->name_owner,
1119                                       proxy->priv->object_path,
1120                                       "org.freedesktop.DBus.Properties",
1121                                       "Get",
1122                                       g_variant_new ("(ss)", proxy->priv->interface_name, data->prop_name),
1123                                       G_VARIANT_TYPE ("(v)"),
1124                                       G_DBUS_CALL_FLAGS_NONE,
1125                                       -1,           /* timeout */
1126                                       NULL,         /* GCancellable */
1127                                       (GAsyncReadyCallback) invalidated_property_get_cb,
1128                                       data);
1129             }
1130         }
1131     }
1132   else
1133     {
1134       emit_g_signal = TRUE;
1135       for (n = 0; invalidated_properties[n] != NULL; n++)
1136         {
1137           g_hash_table_remove (proxy->priv->properties, invalidated_properties[n]);
1138         }
1139     }
1140
1141   G_UNLOCK (properties_lock);
1142
1143   if (emit_g_signal)
1144     {
1145       g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
1146                      0,
1147                      changed_properties,
1148                      invalidated_properties);
1149     }
1150
1151  out:
1152   if (changed_properties != NULL)
1153     g_variant_unref (changed_properties);
1154   g_free (invalidated_properties);
1155   if (proxy != NULL)
1156     g_object_unref (proxy);
1157 }
1158
1159 /* ---------------------------------------------------------------------------------------------------- */
1160
1161 static void
1162 process_get_all_reply (GDBusProxy *proxy,
1163                        GVariant   *result)
1164 {
1165   GVariantIter *iter;
1166   gchar *key;
1167   GVariant *value;
1168   guint num_properties;
1169
1170   if (!g_variant_is_of_type (result, G_VARIANT_TYPE ("(a{sv})")))
1171     {
1172       g_warning ("Value for GetAll reply with type '%s' does not match '(a{sv})'",
1173                  g_variant_get_type_string (result));
1174       goto out;
1175     }
1176
1177   G_LOCK (properties_lock);
1178
1179   g_variant_get (result, "(a{sv})", &iter);
1180   while (g_variant_iter_next (iter, "{sv}", &key, &value))
1181     {
1182       insert_property_checked (proxy,
1183                                key, /* adopts string */
1184                                value); /* adopts value */
1185     }
1186   g_variant_iter_free (iter);
1187
1188   num_properties = g_hash_table_size (proxy->priv->properties);
1189   G_UNLOCK (properties_lock);
1190
1191   /* Synthesize ::g-properties-changed changed */
1192   if (num_properties > 0)
1193     {
1194       GVariant *changed_properties;
1195       const gchar *invalidated_properties[1] = {NULL};
1196
1197       g_variant_get (result,
1198                      "(@a{sv})",
1199                      &changed_properties);
1200       g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
1201                      0,
1202                      changed_properties,
1203                      invalidated_properties);
1204       g_variant_unref (changed_properties);
1205     }
1206
1207  out:
1208   ;
1209 }
1210
1211 typedef struct
1212 {
1213   GDBusProxy *proxy;
1214   GCancellable *cancellable;
1215   gchar *name_owner;
1216 } LoadPropertiesOnNameOwnerChangedData;
1217
1218 static void
1219 on_name_owner_changed_get_all_cb (GDBusConnection *connection,
1220                                   GAsyncResult    *res,
1221                                   gpointer         user_data)
1222 {
1223   LoadPropertiesOnNameOwnerChangedData *data = user_data;
1224   GVariant *result;
1225   GError *error;
1226   gboolean cancelled;
1227
1228   cancelled = FALSE;
1229
1230   error = NULL;
1231   result = g_dbus_connection_call_finish (connection,
1232                                           res,
1233                                           &error);
1234   if (result == NULL)
1235     {
1236       if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_CANCELLED)
1237         cancelled = TRUE;
1238       /* We just ignore if GetAll() is failing. Because this might happen
1239        * if the object has no properties at all. Or if the caller is
1240        * not authorized to see the properties.
1241        *
1242        * Either way, apps can know about this by using
1243        * get_cached_property_names() or get_cached_property().
1244        *
1245        * TODO: handle G_DBUS_DEBUG flag 'proxy' and, if enabled, log the
1246        * fact that GetAll() failed
1247        */
1248       //g_debug ("error: %d %d %s", error->domain, error->code, error->message);
1249       g_error_free (error);
1250     }
1251
1252   /* and finally we can notify */
1253   if (!cancelled)
1254     {
1255       G_LOCK (properties_lock);
1256       g_free (data->proxy->priv->name_owner);
1257       data->proxy->priv->name_owner = data->name_owner;
1258       data->name_owner = NULL; /* to avoid an extra copy, we steal the string */
1259       g_hash_table_remove_all (data->proxy->priv->properties);
1260       G_UNLOCK (properties_lock);
1261       if (result != NULL)
1262         {
1263           process_get_all_reply (data->proxy, result);
1264           g_variant_unref (result);
1265         }
1266
1267       g_object_notify (G_OBJECT (data->proxy), "g-name-owner");
1268     }
1269
1270   if (data->cancellable == data->proxy->priv->get_all_cancellable)
1271     data->proxy->priv->get_all_cancellable = NULL;
1272
1273   g_object_unref (data->proxy);
1274   g_object_unref (data->cancellable);
1275   g_free (data->name_owner);
1276   g_free (data);
1277 }
1278
1279 static void
1280 on_name_owner_changed (GDBusConnection *connection,
1281                        const gchar      *sender_name,
1282                        const gchar      *object_path,
1283                        const gchar      *interface_name,
1284                        const gchar      *signal_name,
1285                        GVariant         *parameters,
1286                        gpointer          user_data)
1287 {
1288   SignalSubscriptionData *data = user_data;
1289   GDBusProxy *proxy;
1290   const gchar *old_owner;
1291   const gchar *new_owner;
1292
1293   G_LOCK (signal_subscription_lock);
1294   proxy = data->proxy;
1295   if (proxy == NULL)
1296     {
1297       G_UNLOCK (signal_subscription_lock);
1298       goto out;
1299     }
1300   else
1301     {
1302       g_object_ref (proxy);
1303       G_UNLOCK (signal_subscription_lock);
1304     }
1305
1306   /* if we are already trying to load properties, cancel that */
1307   if (proxy->priv->get_all_cancellable != NULL)
1308     {
1309       g_cancellable_cancel (proxy->priv->get_all_cancellable);
1310       proxy->priv->get_all_cancellable = NULL;
1311     }
1312
1313   g_variant_get (parameters,
1314                  "(&s&s&s)",
1315                  NULL,
1316                  &old_owner,
1317                  &new_owner);
1318
1319   if (strlen (new_owner) == 0)
1320     {
1321       G_LOCK (properties_lock);
1322       g_free (proxy->priv->name_owner);
1323       proxy->priv->name_owner = NULL;
1324
1325       /* Synthesize ::g-properties-changed changed */
1326       if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES) &&
1327           g_hash_table_size (proxy->priv->properties) > 0)
1328         {
1329           GVariantBuilder builder;
1330           GPtrArray *invalidated_properties;
1331           GHashTableIter iter;
1332           const gchar *key;
1333
1334           /* Build changed_properties (always empty) and invalidated_properties ... */
1335           g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
1336
1337           invalidated_properties = g_ptr_array_new_with_free_func (g_free);
1338           g_hash_table_iter_init (&iter, proxy->priv->properties);
1339           while (g_hash_table_iter_next (&iter, (gpointer) &key, NULL))
1340             g_ptr_array_add (invalidated_properties, g_strdup (key));
1341           g_ptr_array_add (invalidated_properties, NULL);
1342
1343           /* ... throw out the properties ... */
1344           g_hash_table_remove_all (proxy->priv->properties);
1345
1346           G_UNLOCK (properties_lock);
1347
1348           /* ... and finally emit the ::g-properties-changed signal */
1349           g_signal_emit (proxy, signals[PROPERTIES_CHANGED_SIGNAL],
1350                          0,
1351                          g_variant_builder_end (&builder) /* consumed */,
1352                          (const gchar* const *) invalidated_properties->pdata);
1353           g_ptr_array_unref (invalidated_properties);
1354         }
1355       else
1356         {
1357           G_UNLOCK (properties_lock);
1358         }
1359       g_object_notify (G_OBJECT (proxy), "g-name-owner");
1360     }
1361   else
1362     {
1363       G_LOCK (properties_lock);
1364
1365       /* ignore duplicates - this can happen when activating the service */
1366       if (g_strcmp0 (new_owner, proxy->priv->name_owner) == 0)
1367         {
1368           G_UNLOCK (properties_lock);
1369           goto out;
1370         }
1371
1372       if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES)
1373         {
1374           g_free (proxy->priv->name_owner);
1375           proxy->priv->name_owner = g_strdup (new_owner);
1376
1377           g_hash_table_remove_all (proxy->priv->properties);
1378           G_UNLOCK (properties_lock);
1379           g_object_notify (G_OBJECT (proxy), "g-name-owner");
1380         }
1381       else
1382         {
1383           LoadPropertiesOnNameOwnerChangedData *data;
1384
1385           G_UNLOCK (properties_lock);
1386
1387           /* start loading properties.. only then emit notify::g-name-owner .. we
1388            * need to be able to cancel this in the event another NameOwnerChanged
1389            * signal suddenly happens
1390            */
1391
1392           g_assert (proxy->priv->get_all_cancellable == NULL);
1393           proxy->priv->get_all_cancellable = g_cancellable_new ();
1394           data = g_new0 (LoadPropertiesOnNameOwnerChangedData, 1);
1395           data->proxy = g_object_ref (proxy);
1396           data->cancellable = proxy->priv->get_all_cancellable;
1397           data->name_owner = g_strdup (new_owner);
1398           g_dbus_connection_call (proxy->priv->connection,
1399                                   data->name_owner,
1400                                   proxy->priv->object_path,
1401                                   "org.freedesktop.DBus.Properties",
1402                                   "GetAll",
1403                                   g_variant_new ("(s)", proxy->priv->interface_name),
1404                                   G_VARIANT_TYPE ("(a{sv})"),
1405                                   G_DBUS_CALL_FLAGS_NONE,
1406                                   -1,           /* timeout */
1407                                   proxy->priv->get_all_cancellable,
1408                                   (GAsyncReadyCallback) on_name_owner_changed_get_all_cb,
1409                                   data);
1410         }
1411     }
1412
1413  out:
1414   if (proxy != NULL)
1415     g_object_unref (proxy);
1416 }
1417
1418 /* ---------------------------------------------------------------------------------------------------- */
1419
1420 typedef struct
1421 {
1422   GDBusProxy *proxy;
1423   GCancellable *cancellable;
1424   GSimpleAsyncResult *simple;
1425 } AsyncInitData;
1426
1427 static void
1428 async_init_data_free (AsyncInitData *data)
1429 {
1430   g_object_unref (data->proxy);
1431   if (data->cancellable != NULL)
1432     g_object_unref (data->cancellable);
1433   g_object_unref (data->simple);
1434   g_free (data);
1435 }
1436
1437 static void
1438 async_init_get_all_cb (GDBusConnection *connection,
1439                        GAsyncResult    *res,
1440                        gpointer         user_data)
1441 {
1442   AsyncInitData *data = user_data;
1443   GVariant *result;
1444   GError *error;
1445
1446   error = NULL;
1447   result = g_dbus_connection_call_finish (connection,
1448                                           res,
1449                                           &error);
1450   if (result == NULL)
1451     {
1452       /* We just ignore if GetAll() is failing. Because this might happen
1453        * if the object has no properties at all. Or if the caller is
1454        * not authorized to see the properties.
1455        *
1456        * Either way, apps can know about this by using
1457        * get_cached_property_names() or get_cached_property().
1458        *
1459        * TODO: handle G_DBUS_DEBUG flag 'proxy' and, if enabled, log the
1460        * fact that GetAll() failed
1461        */
1462       //g_debug ("error: %d %d %s", error->domain, error->code, error->message);
1463       g_error_free (error);
1464     }
1465   else
1466     {
1467       g_simple_async_result_set_op_res_gpointer (data->simple,
1468                                                  result,
1469                                                  (GDestroyNotify) g_variant_unref);
1470     }
1471
1472   g_simple_async_result_complete_in_idle (data->simple);
1473   async_init_data_free (data);
1474 }
1475
1476 static void
1477 async_init_data_set_name_owner (AsyncInitData *data,
1478                                 const gchar   *name_owner)
1479 {
1480   gboolean get_all;
1481
1482
1483   if (name_owner != NULL)
1484     {
1485       /* it starts as NULL anyway */
1486       G_LOCK (properties_lock);
1487       data->proxy->priv->name_owner = g_strdup (name_owner);
1488       G_UNLOCK (properties_lock);
1489     }
1490
1491   get_all = TRUE;
1492
1493   if (data->proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES)
1494     {
1495       /* Don't load properties if the API user doesn't want them */
1496       get_all = FALSE;
1497     }
1498   else if (name_owner == NULL && data->proxy->priv->name != NULL)
1499     {
1500       /* Don't attempt to load properties if the name_owner is NULL (which
1501        * usually means the name isn't owned), unless name is also NULL (which
1502        * means we actually wanted to talk to the directly-connected process -
1503        * either dbus-daemon or a peer - instead of going via dbus-daemon)
1504        */
1505         get_all = FALSE;
1506     }
1507
1508   if (get_all)
1509     {
1510       /* load all properties asynchronously */
1511       g_dbus_connection_call (data->proxy->priv->connection,
1512                               name_owner,
1513                               data->proxy->priv->object_path,
1514                               "org.freedesktop.DBus.Properties",
1515                               "GetAll",
1516                               g_variant_new ("(s)", data->proxy->priv->interface_name),
1517                               G_VARIANT_TYPE ("(a{sv})"),
1518                               G_DBUS_CALL_FLAGS_NONE,
1519                               -1,           /* timeout */
1520                               data->cancellable,
1521                               (GAsyncReadyCallback) async_init_get_all_cb,
1522                               data);
1523     }
1524   else
1525     {
1526       g_simple_async_result_complete_in_idle (data->simple);
1527       async_init_data_free (data);
1528     }
1529 }
1530
1531 static void
1532 async_init_get_name_owner_cb (GDBusConnection *connection,
1533                               GAsyncResult    *res,
1534                               gpointer         user_data)
1535 {
1536   AsyncInitData *data = user_data;
1537   GError *error;
1538   GVariant *result;
1539
1540   error = NULL;
1541   result = g_dbus_connection_call_finish (connection,
1542                                           res,
1543                                           &error);
1544   if (result == NULL)
1545     {
1546       if (error->domain == G_DBUS_ERROR &&
1547           error->code == G_DBUS_ERROR_NAME_HAS_NO_OWNER)
1548         {
1549           g_error_free (error);
1550           async_init_data_set_name_owner (data, NULL);
1551         }
1552       else
1553         {
1554           g_simple_async_result_take_error (data->simple, error);
1555           g_simple_async_result_complete_in_idle (data->simple);
1556           async_init_data_free (data);
1557         }
1558     }
1559   else
1560     {
1561       /* borrowed from result to avoid an extra copy */
1562       const gchar *name_owner;
1563
1564       g_variant_get (result, "(&s)", &name_owner);
1565       async_init_data_set_name_owner (data, name_owner);
1566       g_variant_unref (result);
1567     }
1568 }
1569
1570 static void
1571 async_init_call_get_name_owner (AsyncInitData *data)
1572 {
1573   g_dbus_connection_call (data->proxy->priv->connection,
1574                           "org.freedesktop.DBus",  /* name */
1575                           "/org/freedesktop/DBus", /* object path */
1576                           "org.freedesktop.DBus",  /* interface */
1577                           "GetNameOwner",
1578                           g_variant_new ("(s)",
1579                                          data->proxy->priv->name),
1580                           G_VARIANT_TYPE ("(s)"),
1581                           G_DBUS_CALL_FLAGS_NONE,
1582                           -1,           /* timeout */
1583                           data->cancellable,
1584                           (GAsyncReadyCallback) async_init_get_name_owner_cb,
1585                           data);
1586 }
1587
1588 static void
1589 async_init_start_service_by_name_cb (GDBusConnection *connection,
1590                                      GAsyncResult    *res,
1591                                      gpointer         user_data)
1592 {
1593   AsyncInitData *data = user_data;
1594   GError *error;
1595   GVariant *result;
1596
1597   error = NULL;
1598   result = g_dbus_connection_call_finish (connection,
1599                                           res,
1600                                           &error);
1601   if (result == NULL)
1602     {
1603       /* Errors are not unexpected; the bus will reply e.g.
1604        *
1605        *   org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Epiphany2
1606        *   was not provided by any .service files
1607        *
1608        * or (see #677718)
1609        *
1610        *   org.freedesktop.systemd1.Masked: Unit polkit.service is masked.
1611        *
1612        * This doesn't mean that the name doesn't have an owner, just
1613        * that it's not provided by a .service file or can't currently
1614        * be started.
1615        *
1616        * In particular, in both cases, it could be that a service
1617        * owner will actually appear later. So instead of erroring out,
1618        * we just proceed to invoke GetNameOwner() if dealing with the
1619        * kind of errors above.
1620        */
1621       if (error->domain == G_DBUS_ERROR && error->code == G_DBUS_ERROR_SERVICE_UNKNOWN)
1622         {
1623           g_error_free (error);
1624         }
1625       else
1626         {
1627           gchar *remote_error = g_dbus_error_get_remote_error (error);
1628           if (g_strcmp0 (remote_error, "org.freedesktop.systemd1.Masked") == 0)
1629             {
1630               g_error_free (error);
1631               g_free (remote_error);
1632             }
1633           else
1634             {
1635               g_prefix_error (&error,
1636                               _("Error calling StartServiceByName for %s: "),
1637                               data->proxy->priv->name);
1638               g_free (remote_error);
1639               goto failed;
1640             }
1641         }
1642     }
1643   else
1644     {
1645       guint32 start_service_result;
1646       g_variant_get (result,
1647                      "(u)",
1648                      &start_service_result);
1649       g_variant_unref (result);
1650       if (start_service_result == 1 ||  /* DBUS_START_REPLY_SUCCESS */
1651           start_service_result == 2)    /* DBUS_START_REPLY_ALREADY_RUNNING */
1652         {
1653           /* continue to invoke GetNameOwner() */
1654         }
1655       else
1656         {
1657           error = g_error_new (G_IO_ERROR,
1658                                G_IO_ERROR_FAILED,
1659                                _("Unexpected reply %d from StartServiceByName(\"%s\") method"),
1660                                start_service_result,
1661                                data->proxy->priv->name);
1662           goto failed;
1663         }
1664     }
1665
1666   async_init_call_get_name_owner (data);
1667   return;
1668
1669  failed:
1670   g_warn_if_fail (error != NULL);
1671   g_simple_async_result_take_error (data->simple, error);
1672   g_simple_async_result_complete_in_idle (data->simple);
1673   async_init_data_free (data);
1674 }
1675
1676 static void
1677 async_init_call_start_service_by_name (AsyncInitData *data)
1678 {
1679   g_dbus_connection_call (data->proxy->priv->connection,
1680                           "org.freedesktop.DBus",  /* name */
1681                           "/org/freedesktop/DBus", /* object path */
1682                           "org.freedesktop.DBus",  /* interface */
1683                           "StartServiceByName",
1684                           g_variant_new ("(su)",
1685                                          data->proxy->priv->name,
1686                                          0),
1687                           G_VARIANT_TYPE ("(u)"),
1688                           G_DBUS_CALL_FLAGS_NONE,
1689                           -1,           /* timeout */
1690                           data->cancellable,
1691                           (GAsyncReadyCallback) async_init_start_service_by_name_cb,
1692                           data);
1693 }
1694
1695 static void
1696 async_initable_init_second_async (GAsyncInitable      *initable,
1697                                   gint                 io_priority,
1698                                   GCancellable        *cancellable,
1699                                   GAsyncReadyCallback  callback,
1700                                   gpointer             user_data)
1701 {
1702   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1703   AsyncInitData *data;
1704
1705   data = g_new0 (AsyncInitData, 1);
1706   data->proxy = g_object_ref (proxy);
1707   data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
1708   data->simple = g_simple_async_result_new (G_OBJECT (proxy),
1709                                             callback,
1710                                             user_data,
1711                                             NULL);
1712   g_simple_async_result_set_check_cancellable (data->simple, cancellable);
1713
1714   /* Check name ownership asynchronously - possibly also start the service */
1715   if (proxy->priv->name == NULL)
1716     {
1717       /* Do nothing */
1718       async_init_data_set_name_owner (data, NULL);
1719     }
1720   else if (g_dbus_is_unique_name (proxy->priv->name))
1721     {
1722       async_init_data_set_name_owner (data, proxy->priv->name);
1723     }
1724   else
1725     {
1726       if ((proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START) ||
1727           (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START_AT_CONSTRUCTION))
1728         {
1729           async_init_call_get_name_owner (data);
1730         }
1731       else
1732         {
1733           async_init_call_start_service_by_name (data);
1734         }
1735     }
1736 }
1737
1738 static gboolean
1739 async_initable_init_second_finish (GAsyncInitable  *initable,
1740                                    GAsyncResult    *res,
1741                                    GError         **error)
1742 {
1743   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1744   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1745   GVariant *result;
1746   gboolean ret;
1747
1748   ret = FALSE;
1749
1750   if (g_simple_async_result_propagate_error (simple, error))
1751     goto out;
1752
1753   result = g_simple_async_result_get_op_res_gpointer (simple);
1754   if (result != NULL)
1755     {
1756       process_get_all_reply (proxy, result);
1757     }
1758
1759   ret = TRUE;
1760
1761  out:
1762   proxy->priv->initialized = TRUE;
1763   return ret;
1764 }
1765
1766 /* ---------------------------------------------------------------------------------------------------- */
1767
1768 static void
1769 async_initable_init_first (GAsyncInitable *initable)
1770 {
1771   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1772
1773   if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES))
1774     {
1775       /* subscribe to PropertiesChanged() */
1776       proxy->priv->properties_changed_subscription_id =
1777         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1778                                             proxy->priv->name,
1779                                             "org.freedesktop.DBus.Properties",
1780                                             "PropertiesChanged",
1781                                             proxy->priv->object_path,
1782                                             proxy->priv->interface_name,
1783                                             G_DBUS_SIGNAL_FLAGS_NONE,
1784                                             on_properties_changed,
1785                                             signal_subscription_ref (proxy->priv->signal_subscription_data),
1786                                             (GDestroyNotify) signal_subscription_unref);
1787     }
1788
1789   if (!(proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS))
1790     {
1791       /* subscribe to all signals for the object */
1792       proxy->priv->signals_subscription_id =
1793         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1794                                             proxy->priv->name,
1795                                             proxy->priv->interface_name,
1796                                             NULL,                        /* member */
1797                                             proxy->priv->object_path,
1798                                             NULL,                        /* arg0 */
1799                                             G_DBUS_SIGNAL_FLAGS_NONE,
1800                                             on_signal_received,
1801                                             signal_subscription_ref (proxy->priv->signal_subscription_data),
1802                                             (GDestroyNotify) signal_subscription_unref);
1803     }
1804
1805   if (proxy->priv->name != NULL && !g_dbus_is_unique_name (proxy->priv->name))
1806     {
1807       proxy->priv->name_owner_changed_subscription_id =
1808         g_dbus_connection_signal_subscribe (proxy->priv->connection,
1809                                             "org.freedesktop.DBus",  /* name */
1810                                             "org.freedesktop.DBus",  /* interface */
1811                                             "NameOwnerChanged",      /* signal name */
1812                                             "/org/freedesktop/DBus", /* path */
1813                                             proxy->priv->name,       /* arg0 */
1814                                             G_DBUS_SIGNAL_FLAGS_NONE,
1815                                             on_name_owner_changed,
1816                                             signal_subscription_ref (proxy->priv->signal_subscription_data),
1817                                             (GDestroyNotify) signal_subscription_unref);
1818     }
1819 }
1820
1821 /* ---------------------------------------------------------------------------------------------------- */
1822
1823 /* initialization is split into two parts - the first is the
1824  * non-blocing part that requires the callers GMainContext - the
1825  * second is a blocking part async part that doesn't require the
1826  * callers GMainContext.. we do this split so the code can be reused
1827  * in the GInitable implementation below.
1828  *
1829  * Note that obtaining a GDBusConnection is not shared between the two
1830  * paths.
1831  */
1832
1833 typedef struct
1834 {
1835   GDBusProxy          *proxy;
1836   gint                 io_priority;
1837   GCancellable        *cancellable;
1838   GAsyncReadyCallback  callback;
1839   gpointer             user_data;
1840 } GetConnectionData;
1841
1842 static void
1843 get_connection_cb (GObject       *source_object,
1844                    GAsyncResult  *res,
1845                    gpointer       user_data)
1846 {
1847   GetConnectionData *data = user_data;
1848   GError *error;
1849
1850   error = NULL;
1851   data->proxy->priv->connection = g_bus_get_finish (res, &error);
1852   if (data->proxy->priv->connection == NULL)
1853     {
1854       GSimpleAsyncResult *simple;
1855       simple = g_simple_async_result_new (G_OBJECT (data->proxy),
1856                                           data->callback,
1857                                           data->user_data,
1858                                           NULL);
1859       g_simple_async_result_set_check_cancellable (simple, data->cancellable);
1860       g_simple_async_result_take_error (simple, error);
1861       g_simple_async_result_complete_in_idle (simple);
1862       g_object_unref (simple);
1863     }
1864   else
1865     {
1866       async_initable_init_first (G_ASYNC_INITABLE (data->proxy));
1867       async_initable_init_second_async (G_ASYNC_INITABLE (data->proxy),
1868                                         data->io_priority,
1869                                         data->cancellable,
1870                                         data->callback,
1871                                         data->user_data);
1872     }
1873
1874   if (data->cancellable != NULL)
1875     g_object_unref (data->cancellable);
1876
1877   g_object_unref (data->proxy);
1878   g_free (data);
1879 }
1880
1881 static void
1882 async_initable_init_async (GAsyncInitable      *initable,
1883                            gint                 io_priority,
1884                            GCancellable        *cancellable,
1885                            GAsyncReadyCallback  callback,
1886                            gpointer             user_data)
1887 {
1888   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1889
1890   if (proxy->priv->bus_type != G_BUS_TYPE_NONE)
1891     {
1892       GetConnectionData *data;
1893
1894       g_assert (proxy->priv->connection == NULL);
1895
1896       data = g_new0 (GetConnectionData, 1);
1897       data->proxy = g_object_ref (proxy);
1898       data->io_priority = io_priority;
1899       data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
1900       data->callback = callback;
1901       data->user_data = user_data;
1902       g_bus_get (proxy->priv->bus_type,
1903                  cancellable,
1904                  get_connection_cb,
1905                  data);
1906     }
1907   else
1908     {
1909       async_initable_init_first (initable);
1910       async_initable_init_second_async (initable, io_priority, cancellable, callback, user_data);
1911     }
1912 }
1913
1914 static gboolean
1915 async_initable_init_finish (GAsyncInitable  *initable,
1916                             GAsyncResult    *res,
1917                             GError         **error)
1918 {
1919   return async_initable_init_second_finish (initable, res, error);
1920 }
1921
1922 static void
1923 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1924 {
1925   async_initable_iface->init_async = async_initable_init_async;
1926   async_initable_iface->init_finish = async_initable_init_finish;
1927 }
1928
1929 /* ---------------------------------------------------------------------------------------------------- */
1930
1931 typedef struct
1932 {
1933   GMainContext *context;
1934   GMainLoop *loop;
1935   GAsyncResult *res;
1936 } InitableAsyncInitableData;
1937
1938 static void
1939 async_initable_init_async_cb (GObject      *source_object,
1940                               GAsyncResult *res,
1941                               gpointer      user_data)
1942 {
1943   InitableAsyncInitableData *data = user_data;
1944   data->res = g_object_ref (res);
1945   g_main_loop_quit (data->loop);
1946 }
1947
1948 /* Simply reuse the GAsyncInitable implementation but run the first
1949  * part (that is non-blocking and requires the callers GMainContext)
1950  * with the callers GMainContext.. and the second with a private
1951  * GMainContext (bug 621310 is slightly related).
1952  *
1953  * Note that obtaining a GDBusConnection is not shared between the two
1954  * paths.
1955  */
1956 static gboolean
1957 initable_init (GInitable     *initable,
1958                GCancellable  *cancellable,
1959                GError       **error)
1960 {
1961   GDBusProxy *proxy = G_DBUS_PROXY (initable);
1962   InitableAsyncInitableData *data;
1963   gboolean ret;
1964
1965   ret = FALSE;
1966
1967   if (proxy->priv->bus_type != G_BUS_TYPE_NONE)
1968     {
1969       g_assert (proxy->priv->connection == NULL);
1970       proxy->priv->connection = g_bus_get_sync (proxy->priv->bus_type,
1971                                                 cancellable,
1972                                                 error);
1973       if (proxy->priv->connection == NULL)
1974         goto out;
1975     }
1976
1977   async_initable_init_first (G_ASYNC_INITABLE (initable));
1978
1979   data = g_new0 (InitableAsyncInitableData, 1);
1980   data->context = g_main_context_new ();
1981   data->loop = g_main_loop_new (data->context, FALSE);
1982
1983   g_main_context_push_thread_default (data->context);
1984
1985   async_initable_init_second_async (G_ASYNC_INITABLE (initable),
1986                                     G_PRIORITY_DEFAULT,
1987                                     cancellable,
1988                                     async_initable_init_async_cb,
1989                                     data);
1990
1991   g_main_loop_run (data->loop);
1992
1993   ret = async_initable_init_second_finish (G_ASYNC_INITABLE (initable),
1994                                            data->res,
1995                                            error);
1996
1997   g_main_context_pop_thread_default (data->context);
1998
1999   g_main_context_unref (data->context);
2000   g_main_loop_unref (data->loop);
2001   g_object_unref (data->res);
2002   g_free (data);
2003
2004  out:
2005
2006   return ret;
2007 }
2008
2009 static void
2010 initable_iface_init (GInitableIface *initable_iface)
2011 {
2012   initable_iface->init = initable_init;
2013 }
2014
2015 /* ---------------------------------------------------------------------------------------------------- */
2016
2017 /**
2018  * g_dbus_proxy_new:
2019  * @connection: A #GDBusConnection.
2020  * @flags: Flags used when constructing the proxy.
2021  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
2022  * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection.
2023  * @object_path: An object path.
2024  * @interface_name: A D-Bus interface name.
2025  * @cancellable: (allow-none): A #GCancellable or %NULL.
2026  * @callback: Callback function to invoke when the proxy is ready.
2027  * @user_data: User data to pass to @callback.
2028  *
2029  * Creates a proxy for accessing @interface_name on the remote object
2030  * at @object_path owned by @name at @connection and asynchronously
2031  * loads D-Bus properties unless the
2032  * %G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES flag is used. Connect to
2033  * the #GDBusProxy::g-properties-changed signal to get notified about
2034  * property changes.
2035  *
2036  * If the %G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS flag is not set, also sets up
2037  * match rules for signals. Connect to the #GDBusProxy::g-signal signal
2038  * to handle signals from the remote object.
2039  *
2040  * If @name is a well-known name and the
2041  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START and %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START_AT_CONSTRUCTION
2042  * flags aren't set and no name owner currently exists, the message bus
2043  * will be requested to launch a name owner for the name.
2044  *
2045  * This is a failable asynchronous constructor - when the proxy is
2046  * ready, @callback will be invoked and you can use
2047  * g_dbus_proxy_new_finish() to get the result.
2048  *
2049  * See g_dbus_proxy_new_sync() and for a synchronous version of this constructor.
2050  *
2051  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
2052  *
2053  * Since: 2.26
2054  */
2055 void
2056 g_dbus_proxy_new (GDBusConnection     *connection,
2057                   GDBusProxyFlags      flags,
2058                   GDBusInterfaceInfo  *info,
2059                   const gchar         *name,
2060                   const gchar         *object_path,
2061                   const gchar         *interface_name,
2062                   GCancellable        *cancellable,
2063                   GAsyncReadyCallback  callback,
2064                   gpointer             user_data)
2065 {
2066   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2067   g_return_if_fail ((name == NULL && g_dbus_connection_get_unique_name (connection) == NULL) || g_dbus_is_name (name));
2068   g_return_if_fail (g_variant_is_object_path (object_path));
2069   g_return_if_fail (g_dbus_is_interface_name (interface_name));
2070
2071   g_async_initable_new_async (G_TYPE_DBUS_PROXY,
2072                               G_PRIORITY_DEFAULT,
2073                               cancellable,
2074                               callback,
2075                               user_data,
2076                               "g-flags", flags,
2077                               "g-interface-info", info,
2078                               "g-name", name,
2079                               "g-connection", connection,
2080                               "g-object-path", object_path,
2081                               "g-interface-name", interface_name,
2082                               NULL);
2083 }
2084
2085 /**
2086  * g_dbus_proxy_new_finish:
2087  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback function passed to g_dbus_proxy_new().
2088  * @error: Return location for error or %NULL.
2089  *
2090  * Finishes creating a #GDBusProxy.
2091  *
2092  * Returns: A #GDBusProxy or %NULL if @error is set. Free with g_object_unref().
2093  *
2094  * Since: 2.26
2095  */
2096 GDBusProxy *
2097 g_dbus_proxy_new_finish (GAsyncResult  *res,
2098                          GError       **error)
2099 {
2100   GObject *object;
2101   GObject *source_object;
2102
2103   source_object = g_async_result_get_source_object (res);
2104   g_assert (source_object != NULL);
2105
2106   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2107                                         res,
2108                                         error);
2109   g_object_unref (source_object);
2110
2111   if (object != NULL)
2112     return G_DBUS_PROXY (object);
2113   else
2114     return NULL;
2115 }
2116
2117 /**
2118  * g_dbus_proxy_new_sync:
2119  * @connection: A #GDBusConnection.
2120  * @flags: Flags used when constructing the proxy.
2121  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
2122  * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection.
2123  * @object_path: An object path.
2124  * @interface_name: A D-Bus interface name.
2125  * @cancellable: (allow-none): A #GCancellable or %NULL.
2126  * @error: (allow-none): Return location for error or %NULL.
2127  *
2128  * Creates a proxy for accessing @interface_name on the remote object
2129  * at @object_path owned by @name at @connection and synchronously
2130  * loads D-Bus properties unless the
2131  * %G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES flag is used.
2132  *
2133  * If the %G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS flag is not set, also sets up
2134  * match rules for signals. Connect to the #GDBusProxy::g-signal signal
2135  * to handle signals from the remote object.
2136  *
2137  * If @name is a well-known name and the
2138  * %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START and %G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START_AT_CONSTRUCTION
2139  * flags aren't set and no name owner currently exists, the message bus
2140  * will be requested to launch a name owner for the name.
2141  *
2142  * This is a synchronous failable constructor. See g_dbus_proxy_new()
2143  * and g_dbus_proxy_new_finish() for the asynchronous version.
2144  *
2145  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
2146  *
2147  * Returns: A #GDBusProxy or %NULL if error is set. Free with g_object_unref().
2148  *
2149  * Since: 2.26
2150  */
2151 GDBusProxy *
2152 g_dbus_proxy_new_sync (GDBusConnection     *connection,
2153                        GDBusProxyFlags      flags,
2154                        GDBusInterfaceInfo  *info,
2155                        const gchar         *name,
2156                        const gchar         *object_path,
2157                        const gchar         *interface_name,
2158                        GCancellable        *cancellable,
2159                        GError             **error)
2160 {
2161   GInitable *initable;
2162
2163   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2164   g_return_val_if_fail ((name == NULL && g_dbus_connection_get_unique_name (connection) == NULL) ||
2165                         g_dbus_is_name (name), NULL);
2166   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
2167   g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
2168
2169   initable = g_initable_new (G_TYPE_DBUS_PROXY,
2170                              cancellable,
2171                              error,
2172                              "g-flags", flags,
2173                              "g-interface-info", info,
2174                              "g-name", name,
2175                              "g-connection", connection,
2176                              "g-object-path", object_path,
2177                              "g-interface-name", interface_name,
2178                              NULL);
2179   if (initable != NULL)
2180     return G_DBUS_PROXY (initable);
2181   else
2182     return NULL;
2183 }
2184
2185 /* ---------------------------------------------------------------------------------------------------- */
2186
2187 /**
2188  * g_dbus_proxy_new_for_bus:
2189  * @bus_type: A #GBusType.
2190  * @flags: Flags used when constructing the proxy.
2191  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface that @proxy conforms to or %NULL.
2192  * @name: A bus name (well-known or unique).
2193  * @object_path: An object path.
2194  * @interface_name: A D-Bus interface name.
2195  * @cancellable: (allow-none): A #GCancellable or %NULL.
2196  * @callback: Callback function to invoke when the proxy is ready.
2197  * @user_data: User data to pass to @callback.
2198  *
2199  * Like g_dbus_proxy_new() but takes a #GBusType instead of a #GDBusConnection.
2200  *
2201  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
2202  *
2203  * Since: 2.26
2204  */
2205 void
2206 g_dbus_proxy_new_for_bus (GBusType             bus_type,
2207                           GDBusProxyFlags      flags,
2208                           GDBusInterfaceInfo  *info,
2209                           const gchar         *name,
2210                           const gchar         *object_path,
2211                           const gchar         *interface_name,
2212                           GCancellable        *cancellable,
2213                           GAsyncReadyCallback  callback,
2214                           gpointer             user_data)
2215 {
2216   g_return_if_fail (g_dbus_is_name (name));
2217   g_return_if_fail (g_variant_is_object_path (object_path));
2218   g_return_if_fail (g_dbus_is_interface_name (interface_name));
2219
2220   g_async_initable_new_async (G_TYPE_DBUS_PROXY,
2221                               G_PRIORITY_DEFAULT,
2222                               cancellable,
2223                               callback,
2224                               user_data,
2225                               "g-flags", flags,
2226                               "g-interface-info", info,
2227                               "g-name", name,
2228                               "g-bus-type", bus_type,
2229                               "g-object-path", object_path,
2230                               "g-interface-name", interface_name,
2231                               NULL);
2232 }
2233
2234 /**
2235  * g_dbus_proxy_new_for_bus_finish:
2236  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback function passed to g_dbus_proxy_new_for_bus().
2237  * @error: Return location for error or %NULL.
2238  *
2239  * Finishes creating a #GDBusProxy.
2240  *
2241  * Returns: A #GDBusProxy or %NULL if @error is set. Free with g_object_unref().
2242  *
2243  * Since: 2.26
2244  */
2245 GDBusProxy *
2246 g_dbus_proxy_new_for_bus_finish (GAsyncResult  *res,
2247                                  GError       **error)
2248 {
2249   return g_dbus_proxy_new_finish (res, error);
2250 }
2251
2252 /**
2253  * g_dbus_proxy_new_for_bus_sync:
2254  * @bus_type: A #GBusType.
2255  * @flags: Flags used when constructing the proxy.
2256  * @info: (allow-none): A #GDBusInterfaceInfo specifying the minimal interface
2257  *        that @proxy conforms to or %NULL.
2258  * @name: A bus name (well-known or unique).
2259  * @object_path: An object path.
2260  * @interface_name: A D-Bus interface name.
2261  * @cancellable: (allow-none): A #GCancellable or %NULL.
2262  * @error: Return location for error or %NULL.
2263  *
2264  * Like g_dbus_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection.
2265  *
2266  * See <xref linkend="gdbus-wellknown-proxy"/> for an example of how #GDBusProxy can be used.
2267  *
2268  * Returns: A #GDBusProxy or %NULL if error is set. Free with g_object_unref().
2269  *
2270  * Since: 2.26
2271  */
2272 GDBusProxy *
2273 g_dbus_proxy_new_for_bus_sync (GBusType             bus_type,
2274                                GDBusProxyFlags      flags,
2275                                GDBusInterfaceInfo  *info,
2276                                const gchar         *name,
2277                                const gchar         *object_path,
2278                                const gchar         *interface_name,
2279                                GCancellable        *cancellable,
2280                                GError             **error)
2281 {
2282   GInitable *initable;
2283
2284   g_return_val_if_fail (g_dbus_is_name (name), NULL);
2285   g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
2286   g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
2287
2288   initable = g_initable_new (G_TYPE_DBUS_PROXY,
2289                              cancellable,
2290                              error,
2291                              "g-flags", flags,
2292                              "g-interface-info", info,
2293                              "g-name", name,
2294                              "g-bus-type", bus_type,
2295                              "g-object-path", object_path,
2296                              "g-interface-name", interface_name,
2297                              NULL);
2298   if (initable != NULL)
2299     return G_DBUS_PROXY (initable);
2300   else
2301     return NULL;
2302 }
2303
2304 /* ---------------------------------------------------------------------------------------------------- */
2305
2306 /**
2307  * g_dbus_proxy_get_connection:
2308  * @proxy: A #GDBusProxy.
2309  *
2310  * Gets the connection @proxy is for.
2311  *
2312  * Returns: (transfer none): A #GDBusConnection owned by @proxy. Do not free.
2313  *
2314  * Since: 2.26
2315  */
2316 GDBusConnection *
2317 g_dbus_proxy_get_connection (GDBusProxy *proxy)
2318 {
2319   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2320   return proxy->priv->connection;
2321 }
2322
2323 /**
2324  * g_dbus_proxy_get_flags:
2325  * @proxy: A #GDBusProxy.
2326  *
2327  * Gets the flags that @proxy was constructed with.
2328  *
2329  * Returns: Flags from the #GDBusProxyFlags enumeration.
2330  *
2331  * Since: 2.26
2332  */
2333 GDBusProxyFlags
2334 g_dbus_proxy_get_flags (GDBusProxy *proxy)
2335 {
2336   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), 0);
2337   return proxy->priv->flags;
2338 }
2339
2340 /**
2341  * g_dbus_proxy_get_name:
2342  * @proxy: A #GDBusProxy.
2343  *
2344  * Gets the name that @proxy was constructed for.
2345  *
2346  * Returns: A string owned by @proxy. Do not free.
2347  *
2348  * Since: 2.26
2349  */
2350 const gchar *
2351 g_dbus_proxy_get_name (GDBusProxy *proxy)
2352 {
2353   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2354   return proxy->priv->name;
2355 }
2356
2357 /**
2358  * g_dbus_proxy_get_name_owner:
2359  * @proxy: A #GDBusProxy.
2360  *
2361  * The unique name that owns the name that @proxy is for or %NULL if
2362  * no-one currently owns that name. You may connect to the
2363  * #GObject::notify signal to track changes to the
2364  * #GDBusProxy:g-name-owner property.
2365  *
2366  * Returns: The name owner or %NULL if no name owner exists. Free with g_free().
2367  *
2368  * Since: 2.26
2369  */
2370 gchar *
2371 g_dbus_proxy_get_name_owner (GDBusProxy *proxy)
2372 {
2373   gchar *ret;
2374
2375   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2376
2377   G_LOCK (properties_lock);
2378   ret = g_strdup (proxy->priv->name_owner);
2379   G_UNLOCK (properties_lock);
2380   return ret;
2381 }
2382
2383 /**
2384  * g_dbus_proxy_get_object_path:
2385  * @proxy: A #GDBusProxy.
2386  *
2387  * Gets the object path @proxy is for.
2388  *
2389  * Returns: A string owned by @proxy. Do not free.
2390  *
2391  * Since: 2.26
2392  */
2393 const gchar *
2394 g_dbus_proxy_get_object_path (GDBusProxy *proxy)
2395 {
2396   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2397   return proxy->priv->object_path;
2398 }
2399
2400 /**
2401  * g_dbus_proxy_get_interface_name:
2402  * @proxy: A #GDBusProxy.
2403  *
2404  * Gets the D-Bus interface name @proxy is for.
2405  *
2406  * Returns: A string owned by @proxy. Do not free.
2407  *
2408  * Since: 2.26
2409  */
2410 const gchar *
2411 g_dbus_proxy_get_interface_name (GDBusProxy *proxy)
2412 {
2413   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2414   return proxy->priv->interface_name;
2415 }
2416
2417 /**
2418  * g_dbus_proxy_get_default_timeout:
2419  * @proxy: A #GDBusProxy.
2420  *
2421  * Gets the timeout to use if -1 (specifying default timeout) is
2422  * passed as @timeout_msec in the g_dbus_proxy_call() and
2423  * g_dbus_proxy_call_sync() functions.
2424  *
2425  * See the #GDBusProxy:g-default-timeout property for more details.
2426  *
2427  * Returns: Timeout to use for @proxy.
2428  *
2429  * Since: 2.26
2430  */
2431 gint
2432 g_dbus_proxy_get_default_timeout (GDBusProxy *proxy)
2433 {
2434   gint ret;
2435
2436   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), -1);
2437
2438   G_LOCK (properties_lock);
2439   ret = proxy->priv->timeout_msec;
2440   G_UNLOCK (properties_lock);
2441   return ret;
2442 }
2443
2444 /**
2445  * g_dbus_proxy_set_default_timeout:
2446  * @proxy: A #GDBusProxy.
2447  * @timeout_msec: Timeout in milliseconds.
2448  *
2449  * Sets the timeout to use if -1 (specifying default timeout) is
2450  * passed as @timeout_msec in the g_dbus_proxy_call() and
2451  * g_dbus_proxy_call_sync() functions.
2452  *
2453  * See the #GDBusProxy:g-default-timeout property for more details.
2454  *
2455  * Since: 2.26
2456  */
2457 void
2458 g_dbus_proxy_set_default_timeout (GDBusProxy *proxy,
2459                                   gint        timeout_msec)
2460 {
2461   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2462   g_return_if_fail (timeout_msec == -1 || timeout_msec >= 0);
2463
2464   G_LOCK (properties_lock);
2465
2466   if (proxy->priv->timeout_msec != timeout_msec)
2467     {
2468       proxy->priv->timeout_msec = timeout_msec;
2469       G_UNLOCK (properties_lock);
2470
2471       g_object_notify (G_OBJECT (proxy), "g-default-timeout");
2472     }
2473   else
2474     {
2475       G_UNLOCK (properties_lock);
2476     }
2477 }
2478
2479 /**
2480  * g_dbus_proxy_get_interface_info:
2481  * @proxy: A #GDBusProxy
2482  *
2483  * Returns the #GDBusInterfaceInfo, if any, specifying the interface
2484  * that @proxy conforms to. See the #GDBusProxy:g-interface-info
2485  * property for more details.
2486  *
2487  * Returns: A #GDBusInterfaceInfo or %NULL. Do not unref the returned
2488  * object, it is owned by @proxy.
2489  *
2490  * Since: 2.26
2491  */
2492 GDBusInterfaceInfo *
2493 g_dbus_proxy_get_interface_info (GDBusProxy *proxy)
2494 {
2495   GDBusInterfaceInfo *ret;
2496
2497   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2498
2499   G_LOCK (properties_lock);
2500   ret = proxy->priv->expected_interface;
2501   G_UNLOCK (properties_lock);
2502   /* FIXME: returning a borrowed ref with no guarantee that nobody will
2503    * call g_dbus_proxy_set_interface_info() and make it invalid...
2504    */
2505   return ret;
2506 }
2507
2508 /**
2509  * g_dbus_proxy_set_interface_info:
2510  * @proxy: A #GDBusProxy
2511  * @info: (allow-none): Minimum interface this proxy conforms to or %NULL to unset.
2512  *
2513  * Ensure that interactions with @proxy conform to the given
2514  * interface. See the #GDBusProxy:g-interface-info property for more
2515  * details.
2516  *
2517  * Since: 2.26
2518  */
2519 void
2520 g_dbus_proxy_set_interface_info (GDBusProxy         *proxy,
2521                                  GDBusInterfaceInfo *info)
2522 {
2523   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2524   G_LOCK (properties_lock);
2525
2526   if (proxy->priv->expected_interface != NULL)
2527     {
2528       g_dbus_interface_info_cache_release (proxy->priv->expected_interface);
2529       g_dbus_interface_info_unref (proxy->priv->expected_interface);
2530     }
2531   proxy->priv->expected_interface = info != NULL ? g_dbus_interface_info_ref (info) : NULL;
2532   if (proxy->priv->expected_interface != NULL)
2533     g_dbus_interface_info_cache_build (proxy->priv->expected_interface);
2534
2535   G_UNLOCK (properties_lock);
2536 }
2537
2538 /* ---------------------------------------------------------------------------------------------------- */
2539
2540 static gboolean
2541 maybe_split_method_name (const gchar  *method_name,
2542                          gchar       **out_interface_name,
2543                          const gchar **out_method_name)
2544 {
2545   gboolean was_split;
2546
2547   was_split = FALSE;
2548   g_assert (out_interface_name != NULL);
2549   g_assert (out_method_name != NULL);
2550   *out_interface_name = NULL;
2551   *out_method_name = NULL;
2552
2553   if (strchr (method_name, '.') != NULL)
2554     {
2555       gchar *p;
2556       gchar *last_dot;
2557
2558       p = g_strdup (method_name);
2559       last_dot = strrchr (p, '.');
2560       *last_dot = '\0';
2561
2562       *out_interface_name = p;
2563       *out_method_name = last_dot + 1;
2564
2565       was_split = TRUE;
2566     }
2567
2568   return was_split;
2569 }
2570
2571 typedef struct
2572 {
2573   GVariant *value;
2574 #ifdef G_OS_UNIX
2575   GUnixFDList *fd_list;
2576 #endif
2577 } ReplyData;
2578
2579 static void
2580 reply_data_free (ReplyData *data)
2581 {
2582   g_variant_unref (data->value);
2583 #ifdef G_OS_UNIX
2584   if (data->fd_list != NULL)
2585     g_object_unref (data->fd_list);
2586 #endif
2587   g_slice_free (ReplyData, data);
2588 }
2589
2590 static void
2591 reply_cb (GDBusConnection *connection,
2592           GAsyncResult    *res,
2593           gpointer         user_data)
2594 {
2595   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
2596   GVariant *value;
2597   GError *error;
2598 #ifdef G_OS_UNIX
2599   GUnixFDList *fd_list;
2600 #endif
2601
2602   error = NULL;
2603 #ifdef G_OS_UNIX
2604   value = g_dbus_connection_call_with_unix_fd_list_finish (connection,
2605                                                            &fd_list,
2606                                                            res,
2607                                                            &error);
2608 #else
2609   value = g_dbus_connection_call_finish (connection,
2610                                          res,
2611                                          &error);
2612 #endif
2613   if (error != NULL)
2614     {
2615       g_simple_async_result_take_error (simple, error);
2616     }
2617   else
2618     {
2619       ReplyData *data;
2620       data = g_slice_new0 (ReplyData);
2621       data->value = value;
2622 #ifdef G_OS_UNIX
2623       data->fd_list = fd_list;
2624 #endif
2625       g_simple_async_result_set_op_res_gpointer (simple, data, (GDestroyNotify) reply_data_free);
2626     }
2627
2628   /* no need to complete in idle since the method GDBusConnection already does */
2629   g_simple_async_result_complete (simple);
2630   g_object_unref (simple);
2631 }
2632
2633 /* properties_lock must be held for as long as you will keep the
2634  * returned value
2635  */
2636 static const GDBusMethodInfo *
2637 lookup_method_info (GDBusProxy  *proxy,
2638                     const gchar *method_name)
2639 {
2640   const GDBusMethodInfo *info = NULL;
2641
2642   if (proxy->priv->expected_interface == NULL)
2643     goto out;
2644
2645   info = g_dbus_interface_info_lookup_method (proxy->priv->expected_interface, method_name);
2646
2647 out:
2648   return info;
2649 }
2650
2651 /* properties_lock must be held for as long as you will keep the
2652  * returned value
2653  */
2654 static const gchar *
2655 get_destination_for_call (GDBusProxy *proxy)
2656 {
2657   const gchar *ret;
2658
2659   ret = NULL;
2660
2661   /* If proxy->priv->name is a unique name, then proxy->priv->name_owner
2662    * is never NULL and always the same as proxy->priv->name. We use this
2663    * knowledge to avoid checking if proxy->priv->name is a unique or
2664    * well-known name.
2665    */
2666   ret = proxy->priv->name_owner;
2667   if (ret != NULL)
2668     goto out;
2669
2670   if (proxy->priv->flags & G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START)
2671     goto out;
2672
2673   ret = proxy->priv->name;
2674
2675  out:
2676   return ret;
2677 }
2678
2679 /* ---------------------------------------------------------------------------------------------------- */
2680
2681 static void
2682 g_dbus_proxy_call_internal (GDBusProxy          *proxy,
2683                             const gchar         *method_name,
2684                             GVariant            *parameters,
2685                             GDBusCallFlags       flags,
2686                             gint                 timeout_msec,
2687                             GUnixFDList         *fd_list,
2688                             GCancellable        *cancellable,
2689                             GAsyncReadyCallback  callback,
2690                             gpointer             user_data)
2691 {
2692   GSimpleAsyncResult *simple;
2693   gboolean was_split;
2694   gchar *split_interface_name;
2695   const gchar *split_method_name;
2696   const gchar *target_method_name;
2697   const gchar *target_interface_name;
2698   gchar *destination;
2699   GVariantType *reply_type;
2700   GAsyncReadyCallback my_callback;
2701
2702   g_return_if_fail (G_IS_DBUS_PROXY (proxy));
2703   g_return_if_fail (g_dbus_is_member_name (method_name) || g_dbus_is_interface_name (method_name));
2704   g_return_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
2705   g_return_if_fail (timeout_msec == -1 || timeout_msec >= 0);
2706 #ifdef G_OS_UNIX
2707   g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
2708 #else
2709   g_return_if_fail (fd_list == NULL);
2710 #endif
2711
2712   reply_type = NULL;
2713   split_interface_name = NULL;
2714
2715   /* g_dbus_connection_call() is optimised for the case of a NULL
2716    * callback.  If we get a NULL callback from our user then make sure
2717    * we pass along a NULL callback for ourselves as well.
2718    */
2719   if (callback != NULL)
2720     {
2721       my_callback = (GAsyncReadyCallback) reply_cb;
2722       simple = g_simple_async_result_new (G_OBJECT (proxy),
2723                                           callback,
2724                                           user_data,
2725                                           g_dbus_proxy_call_internal);
2726       g_simple_async_result_set_check_cancellable (simple, cancellable);
2727     }
2728   else
2729     {
2730       my_callback = NULL;
2731       simple = NULL;
2732     }
2733
2734   G_LOCK (properties_lock);
2735
2736   was_split = maybe_split_method_name (method_name, &split_interface_name, &split_method_name);
2737   target_method_name = was_split ? split_method_name : method_name;
2738   target_interface_name = was_split ? split_interface_name : proxy->priv->interface_name;
2739
2740   /* Warn if method is unexpected (cf. :g-interface-info) */
2741   if (!was_split)
2742     {
2743       const GDBusMethodInfo *expected_method_info;
2744       expected_method_info = lookup_method_info (proxy, target_method_name);
2745       if (expected_method_info != NULL)
2746         reply_type = _g_dbus_compute_complete_signature (expected_method_info->out_args);
2747     }
2748
2749   destination = NULL;
2750   if (proxy->priv->name != NULL)
2751     {
2752       destination = g_strdup (get_destination_for_call (proxy));
2753       if (destination == NULL)
2754         {
2755           if (simple != NULL)
2756             {
2757               g_simple_async_result_set_error (simple,
2758                                                G_IO_ERROR,
2759                                                G_IO_ERROR_FAILED,
2760                                                _("Cannot invoke method; proxy is for a well-known name without an owner and proxy was constructed with the G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag"));
2761               g_simple_async_result_complete_in_idle (simple);
2762               g_object_unref (simple);
2763             }
2764           G_UNLOCK (properties_lock);
2765           goto out;
2766         }
2767     }
2768
2769   G_UNLOCK (properties_lock);
2770
2771 #ifdef G_OS_UNIX
2772   g_dbus_connection_call_with_unix_fd_list (proxy->priv->connection,
2773                                             destination,
2774                                             proxy->priv->object_path,
2775                                             target_interface_name,
2776                                             target_method_name,
2777                                             parameters,
2778                                             reply_type,
2779                                             flags,
2780                                             timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2781                                             fd_list,
2782                                             cancellable,
2783                                             my_callback,
2784                                             simple);
2785 #else
2786   g_dbus_connection_call (proxy->priv->connection,
2787                           destination,
2788                           proxy->priv->object_path,
2789                           target_interface_name,
2790                           target_method_name,
2791                           parameters,
2792                           reply_type,
2793                           flags,
2794                           timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2795                           cancellable,
2796                           my_callback,
2797                           simple);
2798 #endif
2799
2800  out:
2801   if (reply_type != NULL)
2802     g_variant_type_free (reply_type);
2803
2804   g_free (destination);
2805   g_free (split_interface_name);
2806 }
2807
2808 static GVariant *
2809 g_dbus_proxy_call_finish_internal (GDBusProxy    *proxy,
2810                                    GUnixFDList  **out_fd_list,
2811                                    GAsyncResult  *res,
2812                                    GError       **error)
2813 {
2814   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2815   GVariant *value;
2816   ReplyData *data;
2817
2818   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2819   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2820   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2821
2822   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_proxy_call_internal);
2823
2824   value = NULL;
2825
2826   if (g_simple_async_result_propagate_error (simple, error))
2827     goto out;
2828
2829   data = g_simple_async_result_get_op_res_gpointer (simple);
2830   value = g_variant_ref (data->value);
2831 #ifdef G_OS_UNIX
2832   if (out_fd_list != NULL)
2833     *out_fd_list = data->fd_list != NULL ? g_object_ref (data->fd_list) : NULL;
2834 #endif
2835
2836  out:
2837   return value;
2838 }
2839
2840 static GVariant *
2841 g_dbus_proxy_call_sync_internal (GDBusProxy      *proxy,
2842                                  const gchar     *method_name,
2843                                  GVariant        *parameters,
2844                                  GDBusCallFlags   flags,
2845                                  gint             timeout_msec,
2846                                  GUnixFDList     *fd_list,
2847                                  GUnixFDList    **out_fd_list,
2848                                  GCancellable    *cancellable,
2849                                  GError         **error)
2850 {
2851   GVariant *ret;
2852   gboolean was_split;
2853   gchar *split_interface_name;
2854   const gchar *split_method_name;
2855   const gchar *target_method_name;
2856   const gchar *target_interface_name;
2857   gchar *destination;
2858   GVariantType *reply_type;
2859
2860   g_return_val_if_fail (G_IS_DBUS_PROXY (proxy), NULL);
2861   g_return_val_if_fail (g_dbus_is_member_name (method_name) || g_dbus_is_interface_name (method_name), NULL);
2862   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
2863   g_return_val_if_fail (timeout_msec == -1 || timeout_msec >= 0, NULL);
2864 #ifdef G_OS_UNIX
2865   g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
2866 #else
2867   g_return_val_if_fail (fd_list == NULL, NULL);
2868 #endif
2869   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2870
2871   reply_type = NULL;
2872
2873   G_LOCK (properties_lock);
2874
2875   was_split = maybe_split_method_name (method_name, &split_interface_name, &split_method_name);
2876   target_method_name = was_split ? split_method_name : method_name;
2877   target_interface_name = was_split ? split_interface_name : proxy->priv->interface_name;
2878
2879   /* Warn if method is unexpected (cf. :g-interface-info) */
2880   if (!was_split)
2881     {
2882       const GDBusMethodInfo *expected_method_info;
2883       expected_method_info = lookup_method_info (proxy, target_method_name);
2884       if (expected_method_info != NULL)
2885         reply_type = _g_dbus_compute_complete_signature (expected_method_info->out_args);
2886     }
2887
2888   destination = NULL;
2889   if (proxy->priv->name != NULL)
2890     {
2891       destination = g_strdup (get_destination_for_call (proxy));
2892       if (destination == NULL)
2893         {
2894           g_set_error_literal (error,
2895                                G_IO_ERROR,
2896                                G_IO_ERROR_FAILED,
2897                                _("Cannot invoke method; proxy is for a well-known name without an owner and proxy was constructed with the G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START flag"));
2898           ret = NULL;
2899           G_UNLOCK (properties_lock);
2900           goto out;
2901         }
2902     }
2903
2904   G_UNLOCK (properties_lock);
2905
2906 #ifdef G_OS_UNIX
2907   ret = g_dbus_connection_call_with_unix_fd_list_sync (proxy->priv->connection,
2908                                                        destination,
2909                                                        proxy->priv->object_path,
2910                                                        target_interface_name,
2911                                                        target_method_name,
2912                                                        parameters,
2913                                                        reply_type,
2914                                                        flags,
2915                                                        timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2916                                                        fd_list,
2917                                                        out_fd_list,
2918                                                        cancellable,
2919                                                        error);
2920 #else
2921   ret = g_dbus_connection_call_sync (proxy->priv->connection,
2922                                      destination,
2923                                      proxy->priv->object_path,
2924                                      target_interface_name,
2925                                      target_method_name,
2926                                      parameters,
2927                                      reply_type,
2928                                      flags,
2929                                      timeout_msec == -1 ? proxy->priv->timeout_msec : timeout_msec,
2930                                      cancellable,
2931                                      error);
2932 #endif
2933
2934  out:
2935   if (reply_type != NULL)
2936     g_variant_type_free (reply_type);
2937
2938   g_free (destination);
2939   g_free (split_interface_name);
2940
2941   return ret;
2942 }
2943
2944 /* ---------------------------------------------------------------------------------------------------- */
2945
2946 /**
2947  * g_dbus_proxy_call:
2948  * @proxy: A #GDBusProxy.
2949  * @method_name: Name of method to invoke.
2950  * @parameters: (allow-none): A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
2951  * @flags: Flags from the #GDBusCallFlags enumeration.
2952  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
2953  *                "infinite") or -1 to use the proxy default timeout.
2954  * @cancellable: (allow-none): A #GCancellable or %NULL.
2955  * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
2956  * care about the result of the method invocation.
2957  * @user_data: The data to pass to @callback.
2958  *
2959  * Asynchronously invokes the @method_name method on @proxy.
2960  *
2961  * If @method_name contains any dots, then @name is split into interface and
2962  * method name parts. This allows using @proxy for invoking methods on
2963  * other interfaces.
2964  *
2965  * If the #GDBusConnection associated with @proxy is closed then
2966  * the operation will fail with %G_IO_ERROR_CLOSED. If
2967  * @cancellable is canceled, the operation will fail with
2968  * %G_IO_ERROR_CANCELLED. If @parameters contains a value not
2969  * compatible with the D-Bus protocol, the operation fails with
2970  * %G_IO_ERROR_INVALID_ARGUMENT.
2971  *
2972  * If the @parameters #GVariant is floating, it is consumed. This allows
2973  * convenient 'inline' use of g_variant_new(), e.g.:
2974  * |[
2975  *  g_dbus_proxy_call (proxy,
2976  *                     "TwoStrings",
2977  *                     g_variant_new ("(ss)",
2978  *                                    "Thing One",
2979  *                                    "Thing Two"),
2980  *                     G_DBUS_CALL_FLAGS_NONE,
2981  *                     -1,
2982  *                     NULL,
2983  *                     (GAsyncReadyCallback) two_strings_done,
2984  *                     &amp;data);
2985  * ]|
2986  *
2987  * If @proxy has an expected interface (see
2988  * #GDBusProxy:g-interface-info) and @method_name is referenced by it,
2989  * then the return value is checked against the return type.
2990  *
2991  * This is an asynchronous method. When the operation is finished,
2992  * @callback will be invoked in the
2993  * <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2994  * of the thread you are calling this method from.
2995  * You can then call g_dbus_proxy_call_finish() to get the result of
2996  * the operation. See g_dbus_proxy_call_sync() for the synchronous
2997  * version of this method.
2998  *
2999  * If @callback is %NULL then the D-Bus method call message will be sent with
3000  * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
3001  *
3002  * Since: 2.26
3003  */
3004 void
3005 g_dbus_proxy_call (GDBusProxy          *proxy,
3006                    const gchar         *method_name,
3007                    GVariant            *parameters,
3008                    GDBusCallFlags       flags,
3009                    gint                 timeout_msec,
3010                    GCancellable        *cancellable,
3011                    GAsyncReadyCallback  callback,
3012                    gpointer             user_data)
3013 {
3014   g_dbus_proxy_call_internal (proxy, method_name, parameters, flags, timeout_msec, NULL, cancellable, callback, user_data);
3015 }
3016
3017 /**
3018  * g_dbus_proxy_call_finish:
3019  * @proxy: A #GDBusProxy.
3020  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_proxy_call().
3021  * @error: Return location for error or %NULL.
3022  *
3023  * Finishes an operation started with g_dbus_proxy_call().
3024  *
3025  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
3026  * return values. Free with g_variant_unref().
3027  *
3028  * Since: 2.26
3029  */
3030 GVariant *
3031 g_dbus_proxy_call_finish (GDBusProxy    *proxy,
3032                           GAsyncResult  *res,
3033                           GError       **error)
3034 {
3035   return g_dbus_proxy_call_finish_internal (proxy, NULL, res, error);
3036 }
3037
3038 /**
3039  * g_dbus_proxy_call_sync:
3040  * @proxy: A #GDBusProxy.
3041  * @method_name: Name of method to invoke.
3042  * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
3043  *              or %NULL if not passing parameters.
3044  * @flags: Flags from the #GDBusCallFlags enumeration.
3045  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
3046  *                "infinite") or -1 to use the proxy default timeout.
3047  * @cancellable: (allow-none): A #GCancellable or %NULL.
3048  * @error: Return location for error or %NULL.
3049  *
3050  * Synchronously invokes the @method_name method on @proxy.
3051  *
3052  * If @method_name contains any dots, then @name is split into interface and
3053  * method name parts. This allows using @proxy for invoking methods on
3054  * other interfaces.
3055  *
3056  * If the #GDBusConnection associated with @proxy is disconnected then
3057  * the operation will fail with %G_IO_ERROR_CLOSED. If
3058  * @cancellable is canceled, the operation will fail with
3059  * %G_IO_ERROR_CANCELLED. If @parameters contains a value not
3060  * compatible with the D-Bus protocol, the operation fails with
3061  * %G_IO_ERROR_INVALID_ARGUMENT.
3062  *
3063  * If the @parameters #GVariant is floating, it is consumed. This allows
3064  * convenient 'inline' use of g_variant_new(), e.g.:
3065  * |[
3066  *  g_dbus_proxy_call_sync (proxy,
3067  *                          "TwoStrings",
3068  *                          g_variant_new ("(ss)",
3069  *                                         "Thing One",
3070  *                                         "Thing Two"),
3071  *                          G_DBUS_CALL_FLAGS_NONE,
3072  *                          -1,
3073  *                          NULL,
3074  *                          &amp;error);
3075  * ]|
3076  *
3077  * The calling thread is blocked until a reply is received. See
3078  * g_dbus_proxy_call() for the asynchronous version of this
3079  * method.
3080  *
3081  * If @proxy has an expected interface (see
3082  * #GDBusProxy:g-interface-info) and @method_name is referenced by it,
3083  * then the return value is checked against the return type.
3084  *
3085  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
3086  * return values. Free with g_variant_unref().
3087  *
3088  * Since: 2.26
3089  */
3090 GVariant *
3091 g_dbus_proxy_call_sync (GDBusProxy      *proxy,
3092                         const gchar     *method_name,
3093                         GVariant        *parameters,
3094                         GDBusCallFlags   flags,
3095                         gint             timeout_msec,
3096                         GCancellable    *cancellable,
3097                         GError         **error)
3098 {
3099   return g_dbus_proxy_call_sync_internal (proxy, method_name, parameters, flags, timeout_msec, NULL, NULL, cancellable, error);
3100 }
3101
3102 /* ---------------------------------------------------------------------------------------------------- */
3103
3104 #ifdef G_OS_UNIX
3105
3106 /**
3107  * g_dbus_proxy_call_with_unix_fd_list:
3108  * @proxy: A #GDBusProxy.
3109  * @method_name: Name of method to invoke.
3110  * @parameters: (allow-none): A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
3111  * @flags: Flags from the #GDBusCallFlags enumeration.
3112  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
3113  *                "infinite") or -1 to use the proxy default timeout.
3114  * @fd_list: (allow-none): A #GUnixFDList or %NULL.
3115  * @cancellable: (allow-none): A #GCancellable or %NULL.
3116  * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
3117  * care about the result of the method invocation.
3118  * @user_data: The data to pass to @callback.
3119  *
3120  * Like g_dbus_proxy_call() but also takes a #GUnixFDList object.
3121  *
3122  * This method is only available on UNIX.
3123  *
3124  * Since: 2.30
3125  */
3126 void
3127 g_dbus_proxy_call_with_unix_fd_list (GDBusProxy          *proxy,
3128                                      const gchar         *method_name,
3129                                      GVariant            *parameters,
3130                                      GDBusCallFlags       flags,
3131                                      gint                 timeout_msec,
3132                                      GUnixFDList         *fd_list,
3133                                      GCancellable        *cancellable,
3134                                      GAsyncReadyCallback  callback,
3135                                      gpointer             user_data)
3136 {
3137   g_dbus_proxy_call_internal (proxy, method_name, parameters, flags, timeout_msec, fd_list, cancellable, callback, user_data);
3138 }
3139
3140 /**
3141  * g_dbus_proxy_call_with_unix_fd_list_finish:
3142  * @proxy: A #GDBusProxy.
3143  * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
3144  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_proxy_call_with_unix_fd_list().
3145  * @error: Return location for error or %NULL.
3146  *
3147  * Finishes an operation started with g_dbus_proxy_call_with_unix_fd_list().
3148  *
3149  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
3150  * return values. Free with g_variant_unref().
3151  *
3152  * Since: 2.30
3153  */
3154 GVariant *
3155 g_dbus_proxy_call_with_unix_fd_list_finish (GDBusProxy    *proxy,
3156                                             GUnixFDList  **out_fd_list,
3157                                             GAsyncResult  *res,
3158                                             GError       **error)
3159 {
3160   return g_dbus_proxy_call_finish_internal (proxy, out_fd_list, res, error);
3161 }
3162
3163 /**
3164  * g_dbus_proxy_call_with_unix_fd_list_sync:
3165  * @proxy: A #GDBusProxy.
3166  * @method_name: Name of method to invoke.
3167  * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
3168  *              or %NULL if not passing parameters.
3169  * @flags: Flags from the #GDBusCallFlags enumeration.
3170  * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning
3171  *                "infinite") or -1 to use the proxy default timeout.
3172  * @fd_list: (allow-none): A #GUnixFDList or %NULL.
3173  * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
3174  * @cancellable: (allow-none): A #GCancellable or %NULL.
3175  * @error: Return location for error or %NULL.
3176  *
3177  * Like g_dbus_proxy_call_sync() but also takes and returns #GUnixFDList objects.
3178  *
3179  * This method is only available on UNIX.
3180  *
3181  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
3182  * return values. Free with g_variant_unref().
3183  *
3184  * Since: 2.30
3185  */
3186 GVariant *
3187 g_dbus_proxy_call_with_unix_fd_list_sync (GDBusProxy      *proxy,
3188                                           const gchar     *method_name,
3189                                           GVariant        *parameters,
3190                                           GDBusCallFlags   flags,
3191                                           gint             timeout_msec,
3192                                           GUnixFDList     *fd_list,
3193                                           GUnixFDList    **out_fd_list,
3194                                           GCancellable    *cancellable,
3195                                           GError         **error)
3196 {
3197   return g_dbus_proxy_call_sync_internal (proxy, method_name, parameters, flags, timeout_msec, fd_list, out_fd_list, cancellable, error);
3198 }
3199
3200 #endif /* G_OS_UNIX */
3201
3202 /* ---------------------------------------------------------------------------------------------------- */
3203
3204 static GDBusInterfaceInfo *
3205 _g_dbus_proxy_get_info (GDBusInterface *interface)
3206 {
3207   GDBusProxy *proxy = G_DBUS_PROXY (interface);
3208   return g_dbus_proxy_get_interface_info (proxy);
3209 }
3210
3211 static GDBusObject *
3212 _g_dbus_proxy_get_object (GDBusInterface *interface)
3213 {
3214   GDBusProxy *proxy = G_DBUS_PROXY (interface);
3215   return proxy->priv->object;
3216 }
3217
3218 static GDBusObject *
3219 _g_dbus_proxy_dup_object (GDBusInterface *interface)
3220 {
3221   GDBusProxy *proxy = G_DBUS_PROXY (interface);
3222   GDBusObject *ret = NULL;
3223
3224   G_LOCK (properties_lock);
3225   if (proxy->priv->object != NULL)
3226     ret = g_object_ref (proxy->priv->object);
3227   G_UNLOCK (properties_lock);
3228   return ret;
3229 }
3230
3231 static void
3232 _g_dbus_proxy_set_object (GDBusInterface *interface,
3233                           GDBusObject    *object)
3234 {
3235   GDBusProxy *proxy = G_DBUS_PROXY (interface);
3236   G_LOCK (properties_lock);
3237   if (proxy->priv->object != NULL)
3238     g_object_remove_weak_pointer (G_OBJECT (proxy->priv->object), (gpointer *) &proxy->priv->object);
3239   proxy->priv->object = object;
3240   if (proxy->priv->object != NULL)
3241     g_object_add_weak_pointer (G_OBJECT (proxy->priv->object), (gpointer *) &proxy->priv->object);
3242   G_UNLOCK (properties_lock);
3243 }
3244
3245 static void
3246 dbus_interface_iface_init (GDBusInterfaceIface *dbus_interface_iface)
3247 {
3248   dbus_interface_iface->get_info   = _g_dbus_proxy_get_info;
3249   dbus_interface_iface->get_object = _g_dbus_proxy_get_object;
3250   dbus_interface_iface->dup_object = _g_dbus_proxy_dup_object;
3251   dbus_interface_iface->set_object = _g_dbus_proxy_set_object;
3252 }
3253
3254 /* ---------------------------------------------------------------------------------------------------- */