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