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