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