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