Imported Upstream version 2.59.0
[platform/upstream/glib.git] / gio / gdbusconnection.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 /*
22  * TODO for GDBus:
23  *
24  * - would be nice to expose GDBusAuthMechanism and an extension point
25  *
26  * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27  *   the mechanism VFuncs need to be able to set an error.
28  *
29  * - Need to document other mechanisms/sources for determining the D-Bus
30  *   address of a well-known bus.
31  *
32  *   - e.g. on Win32 we need code like from here
33  *
34  *     http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
35  *
36  *     that was never copied over here because it originally was copy-paste
37  *     from the GPLv2 / AFL 2.1 libdbus sources.
38  *
39  *   - on OS X we need to look in launchd for the address
40  *
41  *     https://bugs.freedesktop.org/show_bug.cgi?id=14259
42  *
43  *   - on X11 we need to look in a X11 property on the X server
44  *     - (we can also just use dbus-launch(1) from the D-Bus
45  *        distribution)
46  *
47  *   - (ideally) this requires D-Bus spec work because none of
48  *     this has never really been specced out properly (except
49  *     the X11 bits)
50  *
51  * - Related to the above, we also need to be able to launch a message bus
52  *   instance.... Since we don't want to write our own bus daemon we should
53  *   launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
54  *
55  * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56  *   to specify where the nonce is stored. This will allow people to use
57  *   G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58  *   to easily achieve secure RPC via nonce-tcp.
59  *
60  * - need to expose an extension point for resolving D-Bus address and
61  *   turning them into GIOStream objects. This will allow us to implement
62  *   e.g. X11 D-Bus transports without dlopen()'ing or linking against
63  *   libX11 from libgio.
64  *   - see g_dbus_address_connect() in gdbusaddress.c
65  *
66  * - would be cute to use kernel-specific APIs to resolve fds for
67  *   debug output when using G_DBUS_DEBUG=message, e.g. in addition to
68  *
69  *     fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
70  *
71  *   maybe we can show more information about what fd 21 really is.
72  *   Ryan suggests looking in /proc/self/fd for clues / symlinks!
73  *   Initial experiments on Linux 2.6 suggests that the symlink looks
74  *   like this:
75  *
76  *    3 -> /proc/18068/fd
77  *
78  *   e.g. not of much use.
79  *
80  *  - GDBus High-Level docs
81  *    - Proxy: properties, signals...
82  *    - Connection: IOStream based, ::close, connection setup steps
83  *                  mainloop integration, threading
84  *    - Differences from libdbus (extend "Migrating from")
85  *      - the message handling thread
86  *      - Using GVariant instead of GValue
87  *    - Explain why the high-level API is a good thing and what
88  *      kind of pitfalls it avoids
89  *      - Export objects before claiming names
90  *    - Talk about auto-starting services (cf. GBusNameWatcherFlags)
91  */
92
93 #include "config.h"
94
95 #include <stdlib.h>
96 #include <string.h>
97
98 #include "gdbusauth.h"
99 #include "gdbusutils.h"
100 #include "gdbusaddress.h"
101 #include "gdbusmessage.h"
102 #include "gdbusconnection.h"
103 #include "gdbuserror.h"
104 #include "gioenumtypes.h"
105 #include "gdbusintrospection.h"
106 #include "gdbusmethodinvocation.h"
107 #include "gdbusprivate.h"
108 #include "gdbusauthobserver.h"
109 #include "ginitable.h"
110 #include "gasyncinitable.h"
111 #include "giostream.h"
112 #include "gasyncresult.h"
113 #include "gtask.h"
114
115 #ifdef G_OS_UNIX
116 #include "gunixconnection.h"
117 #include "gunixfdmessage.h"
118 #endif
119
120 #include "glibintl.h"
121
122 /**
123  * SECTION:gdbusconnection
124  * @short_description: D-Bus Connections
125  * @include: gio/gio.h
126  *
127  * The #GDBusConnection type is used for D-Bus connections to remote
128  * peers such as a message buses. It is a low-level API that offers a
129  * lot of flexibility. For instance, it lets you establish a connection
130  * over any transport that can by represented as an #GIOStream.
131  *
132  * This class is rarely used directly in D-Bus clients. If you are writing
133  * a D-Bus client, it is often easier to use the g_bus_own_name(),
134  * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
135  *
136  * As an exception to the usual GLib rule that a particular object must not
137  * be used by two threads at the same time, #GDBusConnection's methods may be
138  * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
139  * can safely return the same #GDBusConnection when called from any thread.
140  *
141  * Most of the ways to obtain a #GDBusConnection automatically initialize it
142  * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
143  * g_bus_get(), and the synchronous versions of those methods, give you an
144  * initialized connection. Language bindings for GIO should use
145  * g_initable_new() or g_async_initable_new_async(), which also initialize the
146  * connection.
147  *
148  * If you construct an uninitialized #GDBusConnection, such as via
149  * g_object_new(), you must initialize it via g_initable_init() or
150  * g_async_initable_init_async() before using its methods or properties.
151  * Calling methods or accessing properties on a #GDBusConnection that has not
152  * completed initialization successfully is considered to be invalid, and leads
153  * to undefined behaviour. In particular, if initialization fails with a
154  * #GError, the only valid thing you can do with that #GDBusConnection is to
155  * free it with g_object_unref().
156  *
157  * ## An example D-Bus server # {#gdbus-server}
158  *
159  * Here is an example for a D-Bus server:
160  * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
161  *
162  * ## An example for exporting a subtree # {#gdbus-subtree-server}
163  *
164  * Here is an example for exporting a subtree:
165  * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
166  *
167  * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
168  *
169  * Here is an example for passing UNIX file descriptors:
170  * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-unix-fd-client.c)
171  *
172  * ## An example for exporting a GObject # {#gdbus-export}
173  *
174  * Here is an example for exporting a #GObject:
175  * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
176  */
177
178 /* ---------------------------------------------------------------------------------------------------- */
179
180 typedef struct _GDBusConnectionClass GDBusConnectionClass;
181
182 /**
183  * GDBusConnectionClass:
184  * @closed: Signal class handler for the #GDBusConnection::closed signal.
185  *
186  * Class structure for #GDBusConnection.
187  *
188  * Since: 2.26
189  */
190 struct _GDBusConnectionClass
191 {
192   /*< private >*/
193   GObjectClass parent_class;
194
195   /*< public >*/
196   /* Signals */
197   void (*closed) (GDBusConnection *connection,
198                   gboolean         remote_peer_vanished,
199                   GError          *error);
200 };
201
202 G_LOCK_DEFINE_STATIC (message_bus_lock);
203
204 static GWeakRef the_session_bus;
205 static GWeakRef the_system_bus;
206
207 /* Extra pseudo-member of GDBusSendMessageFlags.
208  * Set by initable_init() to indicate that despite not being initialized yet,
209  * enough of the only-valid-after-init members are set that we can send a
210  * message, and we're being called from its thread, so no memory barrier is
211  * required before accessing them.
212  */
213 #define SEND_MESSAGE_FLAGS_INITIALIZING (1u << 31)
214
215 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
216 #define CALL_FLAGS_INITIALIZING (1u << 31)
217
218 /* ---------------------------------------------------------------------------------------------------- */
219
220 typedef struct
221 {
222   GDestroyNotify              callback;
223   gpointer                    user_data;
224   GMainContext               *context;
225 } CallDestroyNotifyData;
226
227 static gboolean
228 call_destroy_notify_data_in_idle (gpointer user_data)
229 {
230   CallDestroyNotifyData *data = user_data;
231   data->callback (data->user_data);
232   return FALSE;
233 }
234
235 static void
236 call_destroy_notify_data_free (CallDestroyNotifyData *data)
237 {
238   if (data->context != NULL)
239     g_main_context_unref (data->context);
240   g_free (data);
241 }
242
243 /*
244  * call_destroy_notify: <internal>
245  * @context: (nullable): A #GMainContext or %NULL.
246  * @callback: (nullable): A #GDestroyNotify or %NULL.
247  * @user_data: Data to pass to @callback.
248  *
249  * Schedules @callback to run in @context.
250  */
251 static void
252 call_destroy_notify (GMainContext  *context,
253                      GDestroyNotify callback,
254                      gpointer       user_data)
255 {
256   GSource *idle_source;
257   CallDestroyNotifyData *data;
258
259   if (callback == NULL)
260     goto out;
261
262   data = g_new0 (CallDestroyNotifyData, 1);
263   data->callback = callback;
264   data->user_data = user_data;
265   data->context = context;
266   if (data->context != NULL)
267     g_main_context_ref (data->context);
268
269   idle_source = g_idle_source_new ();
270   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
271   g_source_set_callback (idle_source,
272                          call_destroy_notify_data_in_idle,
273                          data,
274                          (GDestroyNotify) call_destroy_notify_data_free);
275   g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
276   g_source_attach (idle_source, data->context);
277   g_source_unref (idle_source);
278
279  out:
280   ;
281 }
282
283 /* ---------------------------------------------------------------------------------------------------- */
284
285 static gboolean
286 _g_strv_has_string (const gchar* const *haystack,
287                     const gchar        *needle)
288 {
289   guint n;
290
291   for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
292     {
293       if (g_strcmp0 (haystack[n], needle) == 0)
294         return TRUE;
295     }
296   return FALSE;
297 }
298
299 /* ---------------------------------------------------------------------------------------------------- */
300
301 #ifdef G_OS_WIN32
302 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
303 #else
304 // TODO: for some reason this doesn't work on Windows
305 #define CONNECTION_ENSURE_LOCK(obj) do {                                \
306     if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock)))                     \
307       {                                                                 \
308         g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
309                              "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
310       }                                                                 \
311   } while (FALSE)
312 #endif
313
314 #define CONNECTION_LOCK(obj) do {                                       \
315     g_mutex_lock (&(obj)->lock);                                        \
316   } while (FALSE)
317
318 #define CONNECTION_UNLOCK(obj) do {                                     \
319     g_mutex_unlock (&(obj)->lock);                                      \
320   } while (FALSE)
321
322 /* Flags in connection->atomic_flags */
323 enum {
324     FLAG_INITIALIZED = 1 << 0,
325     FLAG_EXIT_ON_CLOSE = 1 << 1,
326     FLAG_CLOSED = 1 << 2
327 };
328
329 /**
330  * GDBusConnection:
331  *
332  * The #GDBusConnection structure contains only private data and
333  * should only be accessed using the provided API.
334  *
335  * Since: 2.26
336  */
337 struct _GDBusConnection
338 {
339   /*< private >*/
340   GObject parent_instance;
341
342   /* ------------------------------------------------------------------------ */
343   /* -- General object state ------------------------------------------------ */
344   /* ------------------------------------------------------------------------ */
345
346   /* General-purpose lock for most fields */
347   GMutex lock;
348
349   /* A lock used in the init() method of the GInitable interface - see comments
350    * in initable_init() for why a separate lock is needed.
351    *
352    * If you need both @lock and @init_lock, you must take @init_lock first.
353    */
354   GMutex init_lock;
355
356   /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
357    * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
358    */
359   gchar *machine_id;
360
361   /* The underlying stream used for communication
362    * Read-only after initable_init(), so it may be read if you either
363    * hold @init_lock or check for initialization first.
364    */
365   GIOStream *stream;
366
367   /* The object used for authentication (if any).
368    * Read-only after initable_init(), so it may be read if you either
369    * hold @init_lock or check for initialization first.
370    */
371   GDBusAuth *auth;
372
373   /* Last serial used. Protected by @lock. */
374   guint32 last_serial;
375
376   /* The object used to send/receive messages.
377    * Read-only after initable_init(), so it may be read if you either
378    * hold @init_lock or check for initialization first.
379    */
380   GDBusWorker *worker;
381
382   /* If connected to a message bus, this contains the unique name assigned to
383    * us by the bus (e.g. ":1.42").
384    * Read-only after initable_init(), so it may be read if you either
385    * hold @init_lock or check for initialization first.
386    */
387   gchar *bus_unique_name;
388
389   /* The GUID returned by the other side if we authenticed as a client or
390    * the GUID to use if authenticating as a server.
391    * Read-only after initable_init(), so it may be read if you either
392    * hold @init_lock or check for initialization first.
393    */
394   gchar *guid;
395
396   /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
397    * Inspect @initialization_error to see whether it succeeded or failed.
398    *
399    * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
400    *
401    * FLAG_CLOSED is the closed property. It may be read at any time, but
402    * may only be written while holding @lock.
403    */
404   volatile gint atomic_flags;
405
406   /* If the connection could not be established during initable_init(),
407    * this GError will be set.
408    * Read-only after initable_init(), so it may be read if you either
409    * hold @init_lock or check for initialization first.
410    */
411   GError *initialization_error;
412
413   /* The result of g_main_context_ref_thread_default() when the object
414    * was created (the GObject _init() function) - this is used for delivery
415    * of the :closed GObject signal.
416    *
417    * Only set in the GObject init function, so no locks are needed.
418    */
419   GMainContext *main_context_at_construction;
420
421   /* Read-only construct properties, no locks needed */
422   gchar *address;
423   GDBusConnectionFlags flags;
424
425   /* Map used for managing method replies, protected by @lock */
426   GHashTable *map_method_serial_to_task;  /* guint32 -> GTask* */
427
428   /* Maps used for managing signal subscription, protected by @lock */
429   GHashTable *map_rule_to_signal_data;                      /* match rule (gchar*)    -> SignalData */
430   GHashTable *map_id_to_signal_data;                        /* id (guint)             -> SignalData */
431   GHashTable *map_sender_unique_name_to_signal_data_array;  /* unique sender (gchar*) -> GPtrArray* of SignalData */
432
433   /* Maps used for managing exported objects and subtrees,
434    * protected by @lock
435    */
436   GHashTable *map_object_path_to_eo;  /* gchar* -> ExportedObject* */
437   GHashTable *map_id_to_ei;           /* guint  -> ExportedInterface* */
438   GHashTable *map_object_path_to_es;  /* gchar* -> ExportedSubtree* */
439   GHashTable *map_id_to_es;           /* guint  -> ExportedSubtree* */
440
441   /* Map used for storing last used serials for each thread, protected by @lock */
442   GHashTable *map_thread_to_last_serial;
443
444   /* Structure used for message filters, protected by @lock */
445   GPtrArray *filters;
446
447   /* Capabilities negotiated during authentication
448    * Read-only after initable_init(), so it may be read without holding a
449    * lock, if you check for initialization first.
450    */
451   GDBusCapabilityFlags capabilities;
452
453   /* Protected by @init_lock */
454   GDBusAuthObserver *authentication_observer;
455
456   /* Read-only after initable_init(), so it may be read if you either
457    * hold @init_lock or check for initialization first.
458    */
459   GCredentials *credentials;
460
461   /* set to TRUE when finalizing */
462   gboolean finalizing;
463 };
464
465 typedef struct ExportedObject ExportedObject;
466 static void exported_object_free (ExportedObject *eo);
467
468 typedef struct ExportedSubtree ExportedSubtree;
469 static void exported_subtree_free (ExportedSubtree *es);
470
471 enum
472 {
473   CLOSED_SIGNAL,
474   LAST_SIGNAL,
475 };
476
477 enum
478 {
479   PROP_0,
480   PROP_STREAM,
481   PROP_ADDRESS,
482   PROP_FLAGS,
483   PROP_GUID,
484   PROP_UNIQUE_NAME,
485   PROP_CLOSED,
486   PROP_EXIT_ON_CLOSE,
487   PROP_CAPABILITY_FLAGS,
488   PROP_AUTHENTICATION_OBSERVER,
489 };
490
491 static void distribute_signals (GDBusConnection  *connection,
492                                 GDBusMessage     *message);
493
494 static void distribute_method_call (GDBusConnection  *connection,
495                                     GDBusMessage     *message);
496
497 static gboolean handle_generic_unlocked (GDBusConnection *connection,
498                                          GDBusMessage    *message);
499
500
501 static void purge_all_signal_subscriptions (GDBusConnection *connection);
502 static void purge_all_filters (GDBusConnection *connection);
503
504 static void schedule_method_call (GDBusConnection            *connection,
505                                   GDBusMessage               *message,
506                                   guint                       registration_id,
507                                   guint                       subtree_registration_id,
508                                   const GDBusInterfaceInfo   *interface_info,
509                                   const GDBusMethodInfo      *method_info,
510                                   const GDBusPropertyInfo    *property_info,
511                                   GVariant                   *parameters,
512                                   const GDBusInterfaceVTable *vtable,
513                                   GMainContext               *main_context,
514                                   gpointer                    user_data);
515
516 #define _G_ENSURE_LOCK(name) do {                                       \
517     if (G_UNLIKELY (G_TRYLOCK(name)))                                   \
518       {                                                                 \
519         g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
520                              "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
521       }                                                                 \
522   } while (FALSE)                                                       \
523
524 static guint signals[LAST_SIGNAL] = { 0 };
525
526 static void initable_iface_init       (GInitableIface      *initable_iface);
527 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
528
529 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
530                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
531                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
532                          );
533
534 /*
535  * Check that all members of @connection that can only be accessed after
536  * the connection is initialized can safely be accessed. If not,
537  * log a critical warning. This function is a memory barrier.
538  *
539  * Returns: %TRUE if initialized
540  */
541 static gboolean
542 check_initialized (GDBusConnection *connection)
543 {
544   /* The access to @atomic_flags isn't conditional, so that this function
545    * provides a memory barrier for thread-safety even if checks are disabled.
546    * (If you don't want this stricter guarantee, you can call
547    * g_return_if_fail (check_initialized (c)).)
548    *
549    * This isn't strictly necessary now that we've decided use of an
550    * uninitialized GDBusConnection is undefined behaviour, but it seems
551    * better to be as deterministic as is feasible.
552    *
553    * (Anything that could suffer a crash from seeing undefined values
554    * must have a race condition - thread A initializes the connection while
555    * thread B calls a method without initialization, hoping that thread A will
556    * win the race - so its behaviour is undefined anyway.)
557    */
558   gint flags = g_atomic_int_get (&connection->atomic_flags);
559
560   g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
561
562   /* We can safely access this, due to the memory barrier above */
563   g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
564
565   return TRUE;
566 }
567
568 typedef enum {
569     MAY_BE_UNINITIALIZED = (1<<1)
570 } CheckUnclosedFlags;
571
572 /*
573  * Check the same thing as check_initialized(), and also that the
574  * connection is not closed. If the connection is uninitialized,
575  * raise a critical warning (it's programmer error); if it's closed,
576  * raise a recoverable GError (it's a runtime error).
577  *
578  * This function is a memory barrier.
579  *
580  * Returns: %TRUE if initialized and not closed
581  */
582 static gboolean
583 check_unclosed (GDBusConnection     *connection,
584                 CheckUnclosedFlags   check,
585                 GError             **error)
586 {
587   /* check_initialized() is effectively inlined, so we don't waste time
588    * doing two memory barriers
589    */
590   gint flags = g_atomic_int_get (&connection->atomic_flags);
591
592   if (!(check & MAY_BE_UNINITIALIZED))
593     {
594       g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
595       g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
596     }
597
598   if (flags & FLAG_CLOSED)
599     {
600       g_set_error_literal (error,
601                            G_IO_ERROR,
602                            G_IO_ERROR_CLOSED,
603                            _("The connection is closed"));
604       return FALSE;
605     }
606
607   return TRUE;
608 }
609
610 static GHashTable *alive_connections = NULL;
611
612 static void
613 g_dbus_connection_dispose (GObject *object)
614 {
615   GDBusConnection *connection = G_DBUS_CONNECTION (object);
616
617   G_LOCK (message_bus_lock);
618   CONNECTION_LOCK (connection);
619   if (connection->worker != NULL)
620     {
621       _g_dbus_worker_stop (connection->worker);
622       connection->worker = NULL;
623       if (alive_connections != NULL)
624         g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
625     }
626   else
627     {
628       if (alive_connections != NULL)
629         g_warn_if_fail (!g_hash_table_contains (alive_connections, connection));
630     }
631   CONNECTION_UNLOCK (connection);
632   G_UNLOCK (message_bus_lock);
633
634   if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
635     G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
636 }
637
638 static void
639 g_dbus_connection_finalize (GObject *object)
640 {
641   GDBusConnection *connection = G_DBUS_CONNECTION (object);
642
643   connection->finalizing = TRUE;
644
645   purge_all_signal_subscriptions (connection);
646
647   purge_all_filters (connection);
648   g_ptr_array_unref (connection->filters);
649
650   if (connection->authentication_observer != NULL)
651     g_object_unref (connection->authentication_observer);
652
653   if (connection->auth != NULL)
654     g_object_unref (connection->auth);
655
656   if (connection->credentials)
657     g_object_unref (connection->credentials);
658
659   if (connection->stream != NULL)
660     {
661       g_object_unref (connection->stream);
662       connection->stream = NULL;
663     }
664
665   g_free (connection->address);
666
667   g_free (connection->guid);
668   g_free (connection->bus_unique_name);
669
670   if (connection->initialization_error != NULL)
671     g_error_free (connection->initialization_error);
672
673   g_hash_table_unref (connection->map_method_serial_to_task);
674
675   g_hash_table_unref (connection->map_rule_to_signal_data);
676   g_hash_table_unref (connection->map_id_to_signal_data);
677   g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
678
679   g_hash_table_unref (connection->map_id_to_ei);
680   g_hash_table_unref (connection->map_object_path_to_eo);
681   g_hash_table_unref (connection->map_id_to_es);
682   g_hash_table_unref (connection->map_object_path_to_es);
683
684   g_hash_table_unref (connection->map_thread_to_last_serial);
685
686   g_main_context_unref (connection->main_context_at_construction);
687
688   g_free (connection->machine_id);
689
690   g_mutex_clear (&connection->init_lock);
691   g_mutex_clear (&connection->lock);
692
693   G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
694 }
695
696 /* called in any user thread, with the connection's lock not held */
697 static void
698 g_dbus_connection_get_property (GObject    *object,
699                                 guint       prop_id,
700                                 GValue     *value,
701                                 GParamSpec *pspec)
702 {
703   GDBusConnection *connection = G_DBUS_CONNECTION (object);
704
705   switch (prop_id)
706     {
707     case PROP_STREAM:
708       g_value_set_object (value, g_dbus_connection_get_stream (connection));
709       break;
710
711     case PROP_GUID:
712       g_value_set_string (value, g_dbus_connection_get_guid (connection));
713       break;
714
715     case PROP_UNIQUE_NAME:
716       g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
717       break;
718
719     case PROP_CLOSED:
720       g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
721       break;
722
723     case PROP_EXIT_ON_CLOSE:
724       g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
725       break;
726
727     case PROP_CAPABILITY_FLAGS:
728       g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
729       break;
730
731     case PROP_FLAGS:
732       g_value_set_flags (value, g_dbus_connection_get_flags (connection));
733       break;
734
735     default:
736       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
737       break;
738     }
739 }
740
741 /* called in any user thread, with the connection's lock not held */
742 static void
743 g_dbus_connection_set_property (GObject      *object,
744                                 guint         prop_id,
745                                 const GValue *value,
746                                 GParamSpec   *pspec)
747 {
748   GDBusConnection *connection = G_DBUS_CONNECTION (object);
749
750   switch (prop_id)
751     {
752     case PROP_STREAM:
753       connection->stream = g_value_dup_object (value);
754       break;
755
756     case PROP_GUID:
757       connection->guid = g_value_dup_string (value);
758       break;
759
760     case PROP_ADDRESS:
761       connection->address = g_value_dup_string (value);
762       break;
763
764     case PROP_FLAGS:
765       connection->flags = g_value_get_flags (value);
766       break;
767
768     case PROP_EXIT_ON_CLOSE:
769       g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
770       break;
771
772     case PROP_AUTHENTICATION_OBSERVER:
773       connection->authentication_observer = g_value_dup_object (value);
774       break;
775
776     default:
777       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
778       break;
779     }
780 }
781
782 /* Base-class implementation of GDBusConnection::closed.
783  *
784  * Called in a user thread, by the main context that was thread-default when
785  * the object was constructed.
786  */
787 static void
788 g_dbus_connection_real_closed (GDBusConnection *connection,
789                                gboolean         remote_peer_vanished,
790                                GError          *error)
791 {
792   gint flags = g_atomic_int_get (&connection->atomic_flags);
793
794   /* Because atomic int access is a memory barrier, we can safely read
795    * initialization_error without a lock, as long as we do it afterwards.
796    */
797   if (remote_peer_vanished &&
798       (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
799       (flags & FLAG_INITIALIZED) != 0 &&
800       connection->initialization_error == NULL)
801     {
802       raise (SIGTERM);
803     }
804 }
805
806 static void
807 g_dbus_connection_class_init (GDBusConnectionClass *klass)
808 {
809   GObjectClass *gobject_class;
810
811   gobject_class = G_OBJECT_CLASS (klass);
812
813   gobject_class->finalize     = g_dbus_connection_finalize;
814   gobject_class->dispose      = g_dbus_connection_dispose;
815   gobject_class->set_property = g_dbus_connection_set_property;
816   gobject_class->get_property = g_dbus_connection_get_property;
817
818   klass->closed = g_dbus_connection_real_closed;
819
820   /**
821    * GDBusConnection:stream:
822    *
823    * The underlying #GIOStream used for I/O.
824    *
825    * If this is passed on construction and is a #GSocketConnection,
826    * then the corresponding #GSocket will be put into non-blocking mode.
827    *
828    * While the #GDBusConnection is active, it will interact with this
829    * stream from a worker thread, so it is not safe to interact with
830    * the stream directly.
831    *
832    * Since: 2.26
833    */
834   g_object_class_install_property (gobject_class,
835                                    PROP_STREAM,
836                                    g_param_spec_object ("stream",
837                                                         P_("IO Stream"),
838                                                         P_("The underlying streams used for I/O"),
839                                                         G_TYPE_IO_STREAM,
840                                                         G_PARAM_READABLE |
841                                                         G_PARAM_WRITABLE |
842                                                         G_PARAM_CONSTRUCT_ONLY |
843                                                         G_PARAM_STATIC_NAME |
844                                                         G_PARAM_STATIC_BLURB |
845                                                         G_PARAM_STATIC_NICK));
846
847   /**
848    * GDBusConnection:address:
849    *
850    * A D-Bus address specifying potential endpoints that can be used
851    * when establishing the connection.
852    *
853    * Since: 2.26
854    */
855   g_object_class_install_property (gobject_class,
856                                    PROP_ADDRESS,
857                                    g_param_spec_string ("address",
858                                                         P_("Address"),
859                                                         P_("D-Bus address specifying potential socket endpoints"),
860                                                         NULL,
861                                                         G_PARAM_WRITABLE |
862                                                         G_PARAM_CONSTRUCT_ONLY |
863                                                         G_PARAM_STATIC_NAME |
864                                                         G_PARAM_STATIC_BLURB |
865                                                         G_PARAM_STATIC_NICK));
866
867   /**
868    * GDBusConnection:flags:
869    *
870    * Flags from the #GDBusConnectionFlags enumeration.
871    *
872    * Since: 2.26
873    */
874   g_object_class_install_property (gobject_class,
875                                    PROP_FLAGS,
876                                    g_param_spec_flags ("flags",
877                                                        P_("Flags"),
878                                                        P_("Flags"),
879                                                        G_TYPE_DBUS_CONNECTION_FLAGS,
880                                                        G_DBUS_CONNECTION_FLAGS_NONE,
881                                                        G_PARAM_READABLE |
882                                                        G_PARAM_WRITABLE |
883                                                        G_PARAM_CONSTRUCT_ONLY |
884                                                        G_PARAM_STATIC_NAME |
885                                                        G_PARAM_STATIC_BLURB |
886                                                        G_PARAM_STATIC_NICK));
887
888   /**
889    * GDBusConnection:guid:
890    *
891    * The GUID of the peer performing the role of server when
892    * authenticating.
893    *
894    * If you are constructing a #GDBusConnection and pass
895    * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
896    * #GDBusConnection:flags property then you MUST also set this
897    * property to a valid guid.
898    *
899    * If you are constructing a #GDBusConnection and pass
900    * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
901    * #GDBusConnection:flags property you will be able to read the GUID
902    * of the other peer here after the connection has been successfully
903    * initialized.
904    *
905    * Since: 2.26
906    */
907   g_object_class_install_property (gobject_class,
908                                    PROP_GUID,
909                                    g_param_spec_string ("guid",
910                                                         P_("GUID"),
911                                                         P_("GUID of the server peer"),
912                                                         NULL,
913                                                         G_PARAM_READABLE |
914                                                         G_PARAM_WRITABLE |
915                                                         G_PARAM_CONSTRUCT_ONLY |
916                                                         G_PARAM_STATIC_NAME |
917                                                         G_PARAM_STATIC_BLURB |
918                                                         G_PARAM_STATIC_NICK));
919
920   /**
921    * GDBusConnection:unique-name:
922    *
923    * The unique name as assigned by the message bus or %NULL if the
924    * connection is not open or not a message bus connection.
925    *
926    * Since: 2.26
927    */
928   g_object_class_install_property (gobject_class,
929                                    PROP_UNIQUE_NAME,
930                                    g_param_spec_string ("unique-name",
931                                                         P_("unique-name"),
932                                                         P_("Unique name of bus connection"),
933                                                         NULL,
934                                                         G_PARAM_READABLE |
935                                                         G_PARAM_STATIC_NAME |
936                                                         G_PARAM_STATIC_BLURB |
937                                                         G_PARAM_STATIC_NICK));
938
939   /**
940    * GDBusConnection:closed:
941    *
942    * A boolean specifying whether the connection has been closed.
943    *
944    * Since: 2.26
945    */
946   g_object_class_install_property (gobject_class,
947                                    PROP_CLOSED,
948                                    g_param_spec_boolean ("closed",
949                                                          P_("Closed"),
950                                                          P_("Whether the connection is closed"),
951                                                          FALSE,
952                                                          G_PARAM_READABLE |
953                                                          G_PARAM_STATIC_NAME |
954                                                          G_PARAM_STATIC_BLURB |
955                                                          G_PARAM_STATIC_NICK));
956
957   /**
958    * GDBusConnection:exit-on-close:
959    *
960    * A boolean specifying whether the process will be terminated (by
961    * calling `raise(SIGTERM)`) if the connection is closed by the
962    * remote peer.
963    *
964    * Note that #GDBusConnection objects returned by g_bus_get_finish()
965    * and g_bus_get_sync() will (usually) have this property set to %TRUE.
966    *
967    * Since: 2.26
968    */
969   g_object_class_install_property (gobject_class,
970                                    PROP_EXIT_ON_CLOSE,
971                                    g_param_spec_boolean ("exit-on-close",
972                                                          P_("Exit on close"),
973                                                          P_("Whether the process is terminated when the connection is closed"),
974                                                          FALSE,
975                                                          G_PARAM_READABLE |
976                                                          G_PARAM_WRITABLE |
977                                                          G_PARAM_STATIC_NAME |
978                                                          G_PARAM_STATIC_BLURB |
979                                                          G_PARAM_STATIC_NICK));
980
981   /**
982    * GDBusConnection:capabilities:
983    *
984    * Flags from the #GDBusCapabilityFlags enumeration
985    * representing connection features negotiated with the other peer.
986    *
987    * Since: 2.26
988    */
989   g_object_class_install_property (gobject_class,
990                                    PROP_CAPABILITY_FLAGS,
991                                    g_param_spec_flags ("capabilities",
992                                                        P_("Capabilities"),
993                                                        P_("Capabilities"),
994                                                        G_TYPE_DBUS_CAPABILITY_FLAGS,
995                                                        G_DBUS_CAPABILITY_FLAGS_NONE,
996                                                        G_PARAM_READABLE |
997                                                        G_PARAM_STATIC_NAME |
998                                                        G_PARAM_STATIC_BLURB |
999                                                        G_PARAM_STATIC_NICK));
1000
1001   /**
1002    * GDBusConnection:authentication-observer:
1003    *
1004    * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1005    *
1006    * Since: 2.26
1007    */
1008   g_object_class_install_property (gobject_class,
1009                                    PROP_AUTHENTICATION_OBSERVER,
1010                                    g_param_spec_object ("authentication-observer",
1011                                                         P_("Authentication Observer"),
1012                                                         P_("Object used to assist in the authentication process"),
1013                                                         G_TYPE_DBUS_AUTH_OBSERVER,
1014                                                         G_PARAM_WRITABLE |
1015                                                         G_PARAM_CONSTRUCT_ONLY |
1016                                                         G_PARAM_STATIC_NAME |
1017                                                         G_PARAM_STATIC_BLURB |
1018                                                         G_PARAM_STATIC_NICK));
1019
1020   /**
1021    * GDBusConnection::closed:
1022    * @connection: the #GDBusConnection emitting the signal
1023    * @remote_peer_vanished: %TRUE if @connection is closed because the
1024    *     remote peer closed its end of the connection
1025    * @error: (nullable): a #GError with more details about the event or %NULL
1026    *
1027    * Emitted when the connection is closed.
1028    *
1029    * The cause of this event can be
1030    *
1031    * - If g_dbus_connection_close() is called. In this case
1032    *   @remote_peer_vanished is set to %FALSE and @error is %NULL.
1033    *
1034    * - If the remote peer closes the connection. In this case
1035    *   @remote_peer_vanished is set to %TRUE and @error is set.
1036    *
1037    * - If the remote peer sends invalid or malformed data. In this
1038    *   case @remote_peer_vanished is set to %FALSE and @error is set.
1039    *
1040    * Upon receiving this signal, you should give up your reference to
1041    * @connection. You are guaranteed that this signal is emitted only
1042    * once.
1043    *
1044    * Since: 2.26
1045    */
1046   signals[CLOSED_SIGNAL] = g_signal_new (I_("closed"),
1047                                          G_TYPE_DBUS_CONNECTION,
1048                                          G_SIGNAL_RUN_LAST,
1049                                          G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1050                                          NULL,
1051                                          NULL,
1052                                          NULL,
1053                                          G_TYPE_NONE,
1054                                          2,
1055                                          G_TYPE_BOOLEAN,
1056                                          G_TYPE_ERROR);
1057 }
1058
1059 static void
1060 g_dbus_connection_init (GDBusConnection *connection)
1061 {
1062   g_mutex_init (&connection->lock);
1063   g_mutex_init (&connection->init_lock);
1064
1065   connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1066
1067   connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1068                                                           g_str_equal);
1069   connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1070                                                         g_direct_equal);
1071   connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1072                                                                                    g_str_equal,
1073                                                                                    g_free,
1074                                                                                    (GDestroyNotify) g_ptr_array_unref);
1075
1076   connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1077                                                              g_str_equal,
1078                                                              NULL,
1079                                                              (GDestroyNotify) exported_object_free);
1080
1081   connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1082                                                g_direct_equal);
1083
1084   connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1085                                                              g_str_equal,
1086                                                              NULL,
1087                                                              (GDestroyNotify) exported_subtree_free);
1088
1089   connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1090                                                g_direct_equal);
1091
1092   connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1093                                                             g_direct_equal);
1094
1095   connection->main_context_at_construction = g_main_context_ref_thread_default ();
1096
1097   connection->filters = g_ptr_array_new ();
1098 }
1099
1100 /**
1101  * g_dbus_connection_get_stream:
1102  * @connection: a #GDBusConnection
1103  *
1104  * Gets the underlying stream used for IO.
1105  *
1106  * While the #GDBusConnection is active, it will interact with this
1107  * stream from a worker thread, so it is not safe to interact with
1108  * the stream directly.
1109  *
1110  * Returns: (transfer none): the stream used for IO
1111  *
1112  * Since: 2.26
1113  */
1114 GIOStream *
1115 g_dbus_connection_get_stream (GDBusConnection *connection)
1116 {
1117   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1118
1119   /* do not use g_return_val_if_fail(), we want the memory barrier */
1120   if (!check_initialized (connection))
1121     return NULL;
1122
1123   return connection->stream;
1124 }
1125
1126 /**
1127  * g_dbus_connection_start_message_processing:
1128  * @connection: a #GDBusConnection
1129  *
1130  * If @connection was created with
1131  * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1132  * starts processing messages. Does nothing on if @connection wasn't
1133  * created with this flag or if the method has already been called.
1134  *
1135  * Since: 2.26
1136  */
1137 void
1138 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1139 {
1140   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1141
1142   /* do not use g_return_val_if_fail(), we want the memory barrier */
1143   if (!check_initialized (connection))
1144     return;
1145
1146   g_assert (connection->worker != NULL);
1147   _g_dbus_worker_unfreeze (connection->worker);
1148 }
1149
1150 /**
1151  * g_dbus_connection_is_closed:
1152  * @connection: a #GDBusConnection
1153  *
1154  * Gets whether @connection is closed.
1155  *
1156  * Returns: %TRUE if the connection is closed, %FALSE otherwise
1157  *
1158  * Since: 2.26
1159  */
1160 gboolean
1161 g_dbus_connection_is_closed (GDBusConnection *connection)
1162 {
1163   gint flags;
1164
1165   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1166
1167   flags = g_atomic_int_get (&connection->atomic_flags);
1168
1169   return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1170 }
1171
1172 /**
1173  * g_dbus_connection_get_capabilities:
1174  * @connection: a #GDBusConnection
1175  *
1176  * Gets the capabilities negotiated with the remote peer
1177  *
1178  * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1179  *
1180  * Since: 2.26
1181  */
1182 GDBusCapabilityFlags
1183 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1184 {
1185   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1186
1187   /* do not use g_return_val_if_fail(), we want the memory barrier */
1188   if (!check_initialized (connection))
1189     return G_DBUS_CAPABILITY_FLAGS_NONE;
1190
1191   return connection->capabilities;
1192 }
1193
1194 /**
1195  * g_dbus_connection_get_flags:
1196  * @connection: a #GDBusConnection
1197  *
1198  * Gets the flags used to construct this connection
1199  *
1200  * Returns: zero or more flags from the #GDBusConnectionFlags enumeration
1201  *
1202  * Since: 2.60
1203  */
1204 GDBusConnectionFlags
1205 g_dbus_connection_get_flags (GDBusConnection *connection)
1206 {
1207   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CONNECTION_FLAGS_NONE);
1208
1209   /* do not use g_return_val_if_fail(), we want the memory barrier */
1210   if (!check_initialized (connection))
1211     return G_DBUS_CONNECTION_FLAGS_NONE;
1212
1213   return connection->flags;
1214 }
1215
1216 /* ---------------------------------------------------------------------------------------------------- */
1217
1218 /* Called in a temporary thread without holding locks. */
1219 static void
1220 flush_in_thread_func (GTask         *task,
1221                       gpointer       source_object,
1222                       gpointer       task_data,
1223                       GCancellable  *cancellable)
1224 {
1225   GError *error = NULL;
1226
1227   if (g_dbus_connection_flush_sync (source_object,
1228                                     cancellable,
1229                                     &error))
1230     g_task_return_boolean (task, TRUE);
1231   else
1232     g_task_return_error (task, error);
1233 }
1234
1235 /**
1236  * g_dbus_connection_flush:
1237  * @connection: a #GDBusConnection
1238  * @cancellable: (nullable): a #GCancellable or %NULL
1239  * @callback: (nullable): a #GAsyncReadyCallback to call when the
1240  *     request is satisfied or %NULL if you don't care about the result
1241  * @user_data: The data to pass to @callback
1242  *
1243  * Asynchronously flushes @connection, that is, writes all queued
1244  * outgoing message to the transport and then flushes the transport
1245  * (using g_output_stream_flush_async()). This is useful in programs
1246  * that wants to emit a D-Bus signal and then exit immediately. Without
1247  * flushing the connection, there is no guaranteed that the message has
1248  * been sent to the networking buffers in the OS kernel.
1249  *
1250  * This is an asynchronous method. When the operation is finished,
1251  * @callback will be invoked in the
1252  * [thread-default main context][g-main-context-push-thread-default]
1253  * of the thread you are calling this method from. You can
1254  * then call g_dbus_connection_flush_finish() to get the result of the
1255  * operation. See g_dbus_connection_flush_sync() for the synchronous
1256  * version.
1257  *
1258  * Since: 2.26
1259  */
1260 void
1261 g_dbus_connection_flush (GDBusConnection     *connection,
1262                          GCancellable        *cancellable,
1263                          GAsyncReadyCallback  callback,
1264                          gpointer             user_data)
1265 {
1266   GTask *task;
1267
1268   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1269
1270   task = g_task_new (connection, cancellable, callback, user_data);
1271   g_task_set_source_tag (task, g_dbus_connection_flush);
1272   g_task_run_in_thread (task, flush_in_thread_func);
1273   g_object_unref (task);
1274 }
1275
1276 /**
1277  * g_dbus_connection_flush_finish:
1278  * @connection: a #GDBusConnection
1279  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1280  *     to g_dbus_connection_flush()
1281  * @error: return location for error or %NULL
1282  *
1283  * Finishes an operation started with g_dbus_connection_flush().
1284  *
1285  * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1286  *
1287  * Since: 2.26
1288  */
1289 gboolean
1290 g_dbus_connection_flush_finish (GDBusConnection  *connection,
1291                                 GAsyncResult     *res,
1292                                 GError          **error)
1293 {
1294   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1295   g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1296   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1297
1298   return g_task_propagate_boolean (G_TASK (res), error);
1299 }
1300
1301 /**
1302  * g_dbus_connection_flush_sync:
1303  * @connection: a #GDBusConnection
1304  * @cancellable: (nullable): a #GCancellable or %NULL
1305  * @error: return location for error or %NULL
1306  *
1307  * Synchronously flushes @connection. The calling thread is blocked
1308  * until this is done. See g_dbus_connection_flush() for the
1309  * asynchronous version of this method and more details about what it
1310  * does.
1311  *
1312  * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1313  *
1314  * Since: 2.26
1315  */
1316 gboolean
1317 g_dbus_connection_flush_sync (GDBusConnection  *connection,
1318                               GCancellable     *cancellable,
1319                               GError          **error)
1320 {
1321   gboolean ret;
1322
1323   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1324   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1325
1326   ret = FALSE;
1327
1328   /* This is only a best-effort attempt to see whether the connection is
1329    * closed, so it doesn't need the lock. If the connection closes just
1330    * after this check, but before scheduling the flush operation, the
1331    * result will be more or less the same as if the connection closed while
1332    * the flush operation was pending - it'll fail with either CLOSED or
1333    * CANCELLED.
1334    */
1335   if (!check_unclosed (connection, 0, error))
1336     goto out;
1337
1338   g_assert (connection->worker != NULL);
1339
1340   ret = _g_dbus_worker_flush_sync (connection->worker,
1341                                    cancellable,
1342                                    error);
1343
1344  out:
1345   return ret;
1346 }
1347
1348 /* ---------------------------------------------------------------------------------------------------- */
1349
1350 typedef struct
1351 {
1352   GDBusConnection *connection;
1353   GError *error;
1354   gboolean remote_peer_vanished;
1355 } EmitClosedData;
1356
1357 static void
1358 emit_closed_data_free (EmitClosedData *data)
1359 {
1360   g_object_unref (data->connection);
1361   if (data->error != NULL)
1362     g_error_free (data->error);
1363   g_free (data);
1364 }
1365
1366 /* Called in a user thread that has acquired the main context that was
1367  * thread-default when the object was constructed
1368  */
1369 static gboolean
1370 emit_closed_in_idle (gpointer user_data)
1371 {
1372   EmitClosedData *data = user_data;
1373   gboolean result;
1374
1375   g_object_notify (G_OBJECT (data->connection), "closed");
1376   g_signal_emit (data->connection,
1377                  signals[CLOSED_SIGNAL],
1378                  0,
1379                  data->remote_peer_vanished,
1380                  data->error,
1381                  &result);
1382   return FALSE;
1383 }
1384
1385 /* Can be called from any thread, must hold lock.
1386  * FLAG_CLOSED must already have been set.
1387  */
1388 static void
1389 schedule_closed_unlocked (GDBusConnection *connection,
1390                           gboolean         remote_peer_vanished,
1391                           GError          *error)
1392 {
1393   GSource *idle_source;
1394   EmitClosedData *data;
1395
1396   CONNECTION_ENSURE_LOCK (connection);
1397
1398   data = g_new0 (EmitClosedData, 1);
1399   data->connection = g_object_ref (connection);
1400   data->remote_peer_vanished = remote_peer_vanished;
1401   data->error = error != NULL ? g_error_copy (error) : NULL;
1402
1403   idle_source = g_idle_source_new ();
1404   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1405   g_source_set_callback (idle_source,
1406                          emit_closed_in_idle,
1407                          data,
1408                          (GDestroyNotify) emit_closed_data_free);
1409   g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1410   g_source_attach (idle_source, connection->main_context_at_construction);
1411   g_source_unref (idle_source);
1412 }
1413
1414 /* ---------------------------------------------------------------------------------------------------- */
1415
1416 /**
1417  * g_dbus_connection_close:
1418  * @connection: a #GDBusConnection
1419  * @cancellable: (nullable): a #GCancellable or %NULL
1420  * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
1421  *     satisfied or %NULL if you don't care about the result
1422  * @user_data: The data to pass to @callback
1423  *
1424  * Closes @connection. Note that this never causes the process to
1425  * exit (this might only happen if the other end of a shared message
1426  * bus connection disconnects, see #GDBusConnection:exit-on-close).
1427  *
1428  * Once the connection is closed, operations such as sending a message
1429  * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1430  * will not automatically flush the connection so queued messages may
1431  * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1432  *
1433  * If @connection is already closed, this method fails with
1434  * %G_IO_ERROR_CLOSED.
1435  *
1436  * When @connection has been closed, the #GDBusConnection::closed
1437  * signal is emitted in the
1438  * [thread-default main context][g-main-context-push-thread-default]
1439  * of the thread that @connection was constructed in.
1440  *
1441  * This is an asynchronous method. When the operation is finished,
1442  * @callback will be invoked in the 
1443  * [thread-default main context][g-main-context-push-thread-default]
1444  * of the thread you are calling this method from. You can
1445  * then call g_dbus_connection_close_finish() to get the result of the
1446  * operation. See g_dbus_connection_close_sync() for the synchronous
1447  * version.
1448  *
1449  * Since: 2.26
1450  */
1451 void
1452 g_dbus_connection_close (GDBusConnection     *connection,
1453                          GCancellable        *cancellable,
1454                          GAsyncReadyCallback  callback,
1455                          gpointer             user_data)
1456 {
1457   GTask *task;
1458
1459   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1460
1461   /* do not use g_return_val_if_fail(), we want the memory barrier */
1462   if (!check_initialized (connection))
1463     return;
1464
1465   g_assert (connection->worker != NULL);
1466
1467   task = g_task_new (connection, cancellable, callback, user_data);
1468   g_task_set_source_tag (task, g_dbus_connection_close);
1469   _g_dbus_worker_close (connection->worker, task);
1470   g_object_unref (task);
1471 }
1472
1473 /**
1474  * g_dbus_connection_close_finish:
1475  * @connection: a #GDBusConnection
1476  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1477  *     to g_dbus_connection_close()
1478  * @error: return location for error or %NULL
1479  *
1480  * Finishes an operation started with g_dbus_connection_close().
1481  *
1482  * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1483  *
1484  * Since: 2.26
1485  */
1486 gboolean
1487 g_dbus_connection_close_finish (GDBusConnection  *connection,
1488                                 GAsyncResult     *res,
1489                                 GError          **error)
1490 {
1491   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1492   g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1493   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1494
1495   return g_task_propagate_boolean (G_TASK (res), error);
1496 }
1497
1498 typedef struct {
1499     GMainLoop *loop;
1500     GAsyncResult *result;
1501 } SyncCloseData;
1502
1503 /* Can be called by any thread, without the connection lock */
1504 static void
1505 sync_close_cb (GObject *source_object,
1506                GAsyncResult *res,
1507                gpointer user_data)
1508 {
1509   SyncCloseData *data = user_data;
1510
1511   data->result = g_object_ref (res);
1512   g_main_loop_quit (data->loop);
1513 }
1514
1515 /**
1516  * g_dbus_connection_close_sync:
1517  * @connection: a #GDBusConnection
1518  * @cancellable: (nullable): a #GCancellable or %NULL
1519  * @error: return location for error or %NULL
1520  *
1521  * Synchronously closes @connection. The calling thread is blocked
1522  * until this is done. See g_dbus_connection_close() for the
1523  * asynchronous version of this method and more details about what it
1524  * does.
1525  *
1526  * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1527  *
1528  * Since: 2.26
1529  */
1530 gboolean
1531 g_dbus_connection_close_sync (GDBusConnection  *connection,
1532                               GCancellable     *cancellable,
1533                               GError          **error)
1534 {
1535   gboolean ret;
1536
1537   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1538   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1539
1540   ret = FALSE;
1541
1542   if (check_unclosed (connection, 0, error))
1543     {
1544       GMainContext *context;
1545       SyncCloseData data;
1546
1547       context = g_main_context_new ();
1548       g_main_context_push_thread_default (context);
1549       data.loop = g_main_loop_new (context, TRUE);
1550       data.result = NULL;
1551
1552       g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1553       g_main_loop_run (data.loop);
1554       ret = g_dbus_connection_close_finish (connection, data.result, error);
1555
1556       g_object_unref (data.result);
1557       g_main_loop_unref (data.loop);
1558       g_main_context_pop_thread_default (context);
1559       g_main_context_unref (context);
1560     }
1561
1562   return ret;
1563 }
1564
1565 /* ---------------------------------------------------------------------------------------------------- */
1566
1567 /**
1568  * g_dbus_connection_get_last_serial:
1569  * @connection: a #GDBusConnection
1570  *
1571  * Retrieves the last serial number assigned to a #GDBusMessage on
1572  * the current thread. This includes messages sent via both low-level
1573  * API such as g_dbus_connection_send_message() as well as
1574  * high-level API such as g_dbus_connection_emit_signal(),
1575  * g_dbus_connection_call() or g_dbus_proxy_call().
1576  *
1577  * Returns: the last used serial or zero when no message has been sent
1578  *     within the current thread
1579  *
1580  * Since: 2.34
1581  */
1582 guint32
1583 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1584 {
1585   guint32 ret;
1586
1587   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1588
1589   CONNECTION_LOCK (connection);
1590   ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1591                                                g_thread_self ()));
1592   CONNECTION_UNLOCK (connection);
1593
1594   return ret;
1595 }
1596
1597 /* ---------------------------------------------------------------------------------------------------- */
1598
1599 /* Can be called by any thread, with the connection lock held */
1600 static gboolean
1601 g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
1602                                          GDBusMessage      *message,
1603                                          GDBusSendMessageFlags flags,
1604                                          volatile guint32  *out_serial,
1605                                          GError           **error)
1606 {
1607   guchar *blob;
1608   gsize blob_size;
1609   guint32 serial_to_use;
1610   gboolean ret;
1611
1612   CONNECTION_ENSURE_LOCK (connection);
1613
1614   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1615   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1616
1617   /* TODO: check all necessary headers are present */
1618
1619   ret = FALSE;
1620   blob = NULL;
1621
1622   if (out_serial != NULL)
1623     *out_serial = 0;
1624
1625   /* If we're in initable_init(), don't check for being initialized, to avoid
1626    * chicken-and-egg problems. initable_init() is responsible for setting up
1627    * our prerequisites (mainly connection->worker), and only calling us
1628    * from its own thread (so no memory barrier is needed).
1629    */
1630   if (!check_unclosed (connection,
1631                        (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1632                        error))
1633     goto out;
1634
1635   blob = g_dbus_message_to_blob (message,
1636                                  &blob_size,
1637                                  connection->capabilities,
1638                                  error);
1639   if (blob == NULL)
1640     goto out;
1641
1642   if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1643     serial_to_use = g_dbus_message_get_serial (message);
1644   else
1645     serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1646
1647   switch (blob[0])
1648     {
1649     case 'l':
1650       ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1651       break;
1652     case 'B':
1653       ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1654       break;
1655     default:
1656       g_assert_not_reached ();
1657       break;
1658     }
1659
1660 #if 0
1661   g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1662               blob_size, serial_to_use, connection);
1663   g_printerr ("----\n");
1664   hexdump (blob, blob_size);
1665   g_printerr ("----\n");
1666 #endif
1667
1668   /* TODO: use connection->auth to encode the blob */
1669
1670   if (out_serial != NULL)
1671     *out_serial = serial_to_use;
1672
1673   /* store used serial for the current thread */
1674   /* TODO: watch the thread disposal and remove associated record
1675    *       from hashtable
1676    *  - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1677    */
1678   g_hash_table_replace (connection->map_thread_to_last_serial,
1679                         g_thread_self (),
1680                         GUINT_TO_POINTER (serial_to_use));
1681
1682   if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1683     g_dbus_message_set_serial (message, serial_to_use);
1684
1685   g_dbus_message_lock (message);
1686   _g_dbus_worker_send_message (connection->worker,
1687                                message,
1688                                (gchar*) blob,
1689                                blob_size);
1690   blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1691
1692   ret = TRUE;
1693
1694  out:
1695   g_free (blob);
1696
1697   return ret;
1698 }
1699
1700 /**
1701  * g_dbus_connection_send_message:
1702  * @connection: a #GDBusConnection
1703  * @message: a #GDBusMessage
1704  * @flags: flags affecting how the message is sent
1705  * @out_serial: (out) (optional): return location for serial number assigned
1706  *     to @message when sending it or %NULL
1707  * @error: Return location for error or %NULL
1708  *
1709  * Asynchronously sends @message to the peer represented by @connection.
1710  *
1711  * Unless @flags contain the
1712  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1713  * will be assigned by @connection and set on @message via
1714  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1715  * serial number used will be written to this location prior to
1716  * submitting the message to the underlying transport.
1717  *
1718  * If @connection is closed then the operation will fail with
1719  * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1720  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1721  *
1722  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1723  * for an example of how to use this low-level API to send and receive
1724  * UNIX file descriptors.
1725  *
1726  * Note that @message must be unlocked, unless @flags contain the
1727  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1728  *
1729  * Returns: %TRUE if the message was well-formed and queued for
1730  *     transmission, %FALSE if @error is set
1731  *
1732  * Since: 2.26
1733  */
1734 gboolean
1735 g_dbus_connection_send_message (GDBusConnection        *connection,
1736                                 GDBusMessage           *message,
1737                                 GDBusSendMessageFlags   flags,
1738                                 volatile guint32       *out_serial,
1739                                 GError                **error)
1740 {
1741   gboolean ret;
1742
1743   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1744   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1745   g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1746   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1747
1748   CONNECTION_LOCK (connection);
1749   ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1750   CONNECTION_UNLOCK (connection);
1751   return ret;
1752 }
1753
1754 /* ---------------------------------------------------------------------------------------------------- */
1755
1756 typedef struct
1757 {
1758   guint32 serial;
1759
1760   gulong cancellable_handler_id;
1761
1762   GSource *timeout_source;
1763
1764   gboolean delivered;
1765 } SendMessageData;
1766
1767 /* Can be called from any thread with or without lock held */
1768 static void
1769 send_message_data_free (SendMessageData *data)
1770 {
1771   g_assert (data->timeout_source == NULL);
1772   g_assert (data->cancellable_handler_id == 0);
1773
1774   g_slice_free (SendMessageData, data);
1775 }
1776
1777 /* ---------------------------------------------------------------------------------------------------- */
1778
1779 /* can be called from any thread with lock held; @task is (transfer full) */
1780 static void
1781 send_message_with_reply_cleanup (GTask *task, gboolean remove)
1782 {
1783   GDBusConnection *connection = g_task_get_source_object (task);
1784   SendMessageData *data = g_task_get_task_data (task);
1785
1786   CONNECTION_ENSURE_LOCK (connection);
1787
1788   g_assert (!data->delivered);
1789
1790   data->delivered = TRUE;
1791
1792   if (data->timeout_source != NULL)
1793     {
1794       g_source_destroy (data->timeout_source);
1795       data->timeout_source = NULL;
1796     }
1797   if (data->cancellable_handler_id > 0)
1798     {
1799       g_cancellable_disconnect (g_task_get_cancellable (task), data->cancellable_handler_id);
1800       data->cancellable_handler_id = 0;
1801     }
1802
1803   if (remove)
1804     {
1805       gboolean removed = g_hash_table_remove (connection->map_method_serial_to_task,
1806                                               GUINT_TO_POINTER (data->serial));
1807       g_warn_if_fail (removed);
1808     }
1809
1810   g_object_unref (task);
1811 }
1812
1813 /* ---------------------------------------------------------------------------------------------------- */
1814
1815 /* Called from GDBus worker thread with lock held; @task is (transfer full). */
1816 static void
1817 send_message_data_deliver_reply_unlocked (GTask           *task,
1818                                           GDBusMessage    *reply)
1819 {
1820   SendMessageData *data = g_task_get_task_data (task);
1821
1822   if (data->delivered)
1823     goto out;
1824
1825   g_task_return_pointer (task, g_object_ref (reply), g_object_unref);
1826
1827   send_message_with_reply_cleanup (task, TRUE);
1828
1829  out:
1830   ;
1831 }
1832
1833 /* Called from a user thread, lock is not held */
1834 static void
1835 send_message_data_deliver_error (GTask      *task,
1836                                  GQuark      domain,
1837                                  gint        code,
1838                                  const char *message)
1839 {
1840   GDBusConnection *connection = g_task_get_source_object (task);
1841   SendMessageData *data = g_task_get_task_data (task);
1842
1843   CONNECTION_LOCK (connection);
1844   if (data->delivered)
1845     {
1846       CONNECTION_UNLOCK (connection);
1847       return;
1848     }
1849
1850   g_object_ref (task);
1851   send_message_with_reply_cleanup (task, TRUE);
1852   CONNECTION_UNLOCK (connection);
1853
1854   g_task_return_new_error (task, domain, code, "%s", message);
1855   g_object_unref (task);
1856 }
1857
1858 /* ---------------------------------------------------------------------------------------------------- */
1859
1860 /* Called from a user thread, lock is not held; @task is (transfer full) */
1861 static gboolean
1862 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1863 {
1864   GTask *task = user_data;
1865
1866   send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_CANCELLED,
1867                                    _("Operation was cancelled"));
1868   return FALSE;
1869 }
1870
1871 /* Can be called from any thread with or without lock held */
1872 static void
1873 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1874                                       gpointer      user_data)
1875 {
1876   GTask *task = user_data;
1877   GSource *idle_source;
1878
1879   /* postpone cancellation to idle handler since we may be called directly
1880    * via g_cancellable_connect() (e.g. holding lock)
1881    */
1882   idle_source = g_idle_source_new ();
1883   g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
1884   g_task_attach_source (task, idle_source, send_message_with_reply_cancelled_idle_cb);
1885   g_source_unref (idle_source);
1886 }
1887
1888 /* ---------------------------------------------------------------------------------------------------- */
1889
1890 /* Called from a user thread, lock is not held; @task is (transfer full) */
1891 static gboolean
1892 send_message_with_reply_timeout_cb (gpointer user_data)
1893 {
1894   GTask *task = user_data;
1895
1896   send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
1897                                    _("Timeout was reached"));
1898   return FALSE;
1899 }
1900
1901 /* ---------------------------------------------------------------------------------------------------- */
1902
1903 /* Called from a user thread, connection's lock is held */
1904 static void
1905 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection     *connection,
1906                                                     GDBusMessage        *message,
1907                                                     GDBusSendMessageFlags flags,
1908                                                     gint                 timeout_msec,
1909                                                     volatile guint32    *out_serial,
1910                                                     GCancellable        *cancellable,
1911                                                     GAsyncReadyCallback  callback,
1912                                                     gpointer             user_data)
1913 {
1914   GTask *task;
1915   SendMessageData *data;
1916   GError *error = NULL;
1917   volatile guint32 serial;
1918
1919   if (out_serial == NULL)
1920     out_serial = &serial;
1921
1922   if (timeout_msec == -1)
1923     timeout_msec = 25 * 1000;
1924
1925   data = g_slice_new0 (SendMessageData);
1926   task = g_task_new (connection, cancellable, callback, user_data);
1927   g_task_set_source_tag (task,
1928                          g_dbus_connection_send_message_with_reply_unlocked);
1929   g_task_set_task_data (task, data, (GDestroyNotify) send_message_data_free);
1930
1931   if (g_task_return_error_if_cancelled (task))
1932     {
1933       g_object_unref (task);
1934       return;
1935     }
1936
1937   if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1938     {
1939       g_task_return_error (task, error);
1940       g_object_unref (task);
1941       return;
1942     }
1943   data->serial = *out_serial;
1944
1945   if (cancellable != NULL)
1946     {
1947       data->cancellable_handler_id = g_cancellable_connect (cancellable,
1948                                                             G_CALLBACK (send_message_with_reply_cancelled_cb),
1949                                                             g_object_ref (task),
1950                                                             g_object_unref);
1951     }
1952
1953   if (timeout_msec != G_MAXINT)
1954     {
1955       data->timeout_source = g_timeout_source_new (timeout_msec);
1956       g_task_attach_source (task, data->timeout_source,
1957                             (GSourceFunc) send_message_with_reply_timeout_cb);
1958       g_source_unref (data->timeout_source);
1959     }
1960
1961   g_hash_table_insert (connection->map_method_serial_to_task,
1962                        GUINT_TO_POINTER (*out_serial),
1963                        g_steal_pointer (&task));
1964 }
1965
1966 /**
1967  * g_dbus_connection_send_message_with_reply:
1968  * @connection: a #GDBusConnection
1969  * @message: a #GDBusMessage
1970  * @flags: flags affecting how the message is sent
1971  * @timeout_msec: the timeout in milliseconds, -1 to use the default
1972  *     timeout or %G_MAXINT for no timeout
1973  * @out_serial: (out) (optional): return location for serial number assigned
1974  *     to @message when sending it or %NULL
1975  * @cancellable: (nullable): a #GCancellable or %NULL
1976  * @callback: (nullable): a #GAsyncReadyCallback to call when the request
1977  *     is satisfied or %NULL if you don't care about the result
1978  * @user_data: The data to pass to @callback
1979  *
1980  * Asynchronously sends @message to the peer represented by @connection.
1981  *
1982  * Unless @flags contain the
1983  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1984  * will be assigned by @connection and set on @message via
1985  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1986  * serial number used will be written to this location prior to
1987  * submitting the message to the underlying transport.
1988  *
1989  * If @connection is closed then the operation will fail with
1990  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1991  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1992  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1993  *
1994  * This is an asynchronous method. When the operation is finished, @callback
1995  * will be invoked in the 
1996  * [thread-default main context][g-main-context-push-thread-default]
1997  * of the thread you are calling this method from. You can then call
1998  * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1999  * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2000  *
2001  * Note that @message must be unlocked, unless @flags contain the
2002  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2003  *
2004  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2005  * for an example of how to use this low-level API to send and receive
2006  * UNIX file descriptors.
2007  *
2008  * Since: 2.26
2009  */
2010 void
2011 g_dbus_connection_send_message_with_reply (GDBusConnection       *connection,
2012                                            GDBusMessage          *message,
2013                                            GDBusSendMessageFlags  flags,
2014                                            gint                   timeout_msec,
2015                                            volatile guint32      *out_serial,
2016                                            GCancellable          *cancellable,
2017                                            GAsyncReadyCallback    callback,
2018                                            gpointer               user_data)
2019 {
2020   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2021   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2022   g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2023   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2024
2025   CONNECTION_LOCK (connection);
2026   g_dbus_connection_send_message_with_reply_unlocked (connection,
2027                                                       message,
2028                                                       flags,
2029                                                       timeout_msec,
2030                                                       out_serial,
2031                                                       cancellable,
2032                                                       callback,
2033                                                       user_data);
2034   CONNECTION_UNLOCK (connection);
2035 }
2036
2037 /**
2038  * g_dbus_connection_send_message_with_reply_finish:
2039  * @connection: a #GDBusConnection
2040  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2041  *     g_dbus_connection_send_message_with_reply()
2042  * @error: teturn location for error or %NULL
2043  *
2044  * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2045  *
2046  * Note that @error is only set if a local in-process error
2047  * occurred. That is to say that the returned #GDBusMessage object may
2048  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2049  * g_dbus_message_to_gerror() to transcode this to a #GError.
2050  *
2051  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2052  * for an example of how to use this low-level API to send and receive
2053  * UNIX file descriptors.
2054  *
2055  * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2056  *
2057  * Since: 2.26
2058  */
2059 GDBusMessage *
2060 g_dbus_connection_send_message_with_reply_finish (GDBusConnection  *connection,
2061                                                   GAsyncResult     *res,
2062                                                   GError          **error)
2063 {
2064   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2065   g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
2066   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2067
2068   return g_task_propagate_pointer (G_TASK (res), error);
2069 }
2070
2071 /* ---------------------------------------------------------------------------------------------------- */
2072
2073 typedef struct
2074 {
2075   GAsyncResult *res;
2076   GMainContext *context;
2077   GMainLoop *loop;
2078 } SendMessageSyncData;
2079
2080 /* Called from a user thread, lock is not held */
2081 static void
2082 send_message_with_reply_sync_cb (GDBusConnection *connection,
2083                                  GAsyncResult    *res,
2084                                  gpointer         user_data)
2085 {
2086   SendMessageSyncData *data = user_data;
2087   data->res = g_object_ref (res);
2088   g_main_loop_quit (data->loop);
2089 }
2090
2091 /**
2092  * g_dbus_connection_send_message_with_reply_sync:
2093  * @connection: a #GDBusConnection
2094  * @message: a #GDBusMessage
2095  * @flags: flags affecting how the message is sent.
2096  * @timeout_msec: the timeout in milliseconds, -1 to use the default
2097  *     timeout or %G_MAXINT for no timeout
2098  * @out_serial: (out) (optional): return location for serial number
2099  *     assigned to @message when sending it or %NULL
2100  * @cancellable: (nullable): a #GCancellable or %NULL
2101  * @error: return location for error or %NULL
2102  *
2103  * Synchronously sends @message to the peer represented by @connection
2104  * and blocks the calling thread until a reply is received or the
2105  * timeout is reached. See g_dbus_connection_send_message_with_reply()
2106  * for the asynchronous version of this method.
2107  *
2108  * Unless @flags contain the
2109  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2110  * will be assigned by @connection and set on @message via
2111  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2112  * serial number used will be written to this location prior to
2113  * submitting the message to the underlying transport.
2114  *
2115  * If @connection is closed then the operation will fail with
2116  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2117  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2118  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2119  *
2120  * Note that @error is only set if a local in-process error
2121  * occurred. That is to say that the returned #GDBusMessage object may
2122  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2123  * g_dbus_message_to_gerror() to transcode this to a #GError.
2124  *
2125  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2126  * for an example of how to use this low-level API to send and receive
2127  * UNIX file descriptors.
2128  *
2129  * Note that @message must be unlocked, unless @flags contain the
2130  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2131  *
2132  * Returns: (transfer full): a locked #GDBusMessage that is the reply
2133  *     to @message or %NULL if @error is set
2134  *
2135  * Since: 2.26
2136  */
2137 GDBusMessage *
2138 g_dbus_connection_send_message_with_reply_sync (GDBusConnection        *connection,
2139                                                 GDBusMessage           *message,
2140                                                 GDBusSendMessageFlags   flags,
2141                                                 gint                    timeout_msec,
2142                                                 volatile guint32       *out_serial,
2143                                                 GCancellable           *cancellable,
2144                                                 GError                **error)
2145 {
2146   SendMessageSyncData data;
2147   GDBusMessage *reply;
2148
2149   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2150   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2151   g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2152   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2153   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2154
2155   data.res = NULL;
2156   data.context = g_main_context_new ();
2157   data.loop = g_main_loop_new (data.context, FALSE);
2158
2159   g_main_context_push_thread_default (data.context);
2160
2161   g_dbus_connection_send_message_with_reply (connection,
2162                                              message,
2163                                              flags,
2164                                              timeout_msec,
2165                                              out_serial,
2166                                              cancellable,
2167                                              (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2168                                              &data);
2169   g_main_loop_run (data.loop);
2170   reply = g_dbus_connection_send_message_with_reply_finish (connection,
2171                                                             data.res,
2172                                                             error);
2173
2174   g_main_context_pop_thread_default (data.context);
2175
2176   g_main_context_unref (data.context);
2177   g_main_loop_unref (data.loop);
2178   if (data.res)
2179     g_object_unref (data.res);
2180
2181   return reply;
2182 }
2183
2184 /* ---------------------------------------------------------------------------------------------------- */
2185
2186 typedef struct
2187 {
2188   guint                       id;
2189   guint                       ref_count;
2190   GDBusMessageFilterFunction  filter_function;
2191   gpointer                    user_data;
2192   GDestroyNotify              user_data_free_func;
2193   GMainContext               *context;
2194 } FilterData;
2195
2196 /* requires CONNECTION_LOCK */
2197 static FilterData **
2198 copy_filter_list (GPtrArray *filters)
2199 {
2200   FilterData **copy;
2201   guint n;
2202
2203   copy = g_new (FilterData *, filters->len + 1);
2204   for (n = 0; n < filters->len; n++)
2205     {
2206       copy[n] = filters->pdata[n];
2207       copy[n]->ref_count++;
2208     }
2209   copy[n] = NULL;
2210
2211   return copy;
2212 }
2213
2214 /* requires CONNECTION_LOCK */
2215 static void
2216 free_filter_list (FilterData **filters)
2217 {
2218   guint n;
2219
2220   for (n = 0; filters[n]; n++)
2221     {
2222       filters[n]->ref_count--;
2223       if (filters[n]->ref_count == 0)
2224         {
2225           call_destroy_notify (filters[n]->context,
2226                                filters[n]->user_data_free_func,
2227                                filters[n]->user_data);
2228           g_main_context_unref (filters[n]->context);
2229           g_free (filters[n]);
2230         }
2231     }
2232   g_free (filters);
2233 }
2234
2235 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2236 static void
2237 on_worker_message_received (GDBusWorker  *worker,
2238                             GDBusMessage *message,
2239                             gpointer      user_data)
2240 {
2241   GDBusConnection *connection;
2242   FilterData **filters;
2243   guint n;
2244   gboolean alive;
2245
2246   G_LOCK (message_bus_lock);
2247   alive = g_hash_table_contains (alive_connections, user_data);
2248   if (!alive)
2249     {
2250       G_UNLOCK (message_bus_lock);
2251       return;
2252     }
2253   connection = G_DBUS_CONNECTION (user_data);
2254   g_object_ref (connection);
2255   G_UNLOCK (message_bus_lock);
2256
2257   //g_debug ("in on_worker_message_received");
2258
2259   g_object_ref (message);
2260   g_dbus_message_lock (message);
2261
2262   //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2263
2264   /* First collect the set of callback functions */
2265   CONNECTION_LOCK (connection);
2266   filters = copy_filter_list (connection->filters);
2267   CONNECTION_UNLOCK (connection);
2268
2269   /* then call the filters in order (without holding the lock) */
2270   for (n = 0; filters[n]; n++)
2271     {
2272       message = filters[n]->filter_function (connection,
2273                                              message,
2274                                              TRUE,
2275                                              filters[n]->user_data);
2276       if (message == NULL)
2277         break;
2278       g_dbus_message_lock (message);
2279     }
2280
2281   CONNECTION_LOCK (connection);
2282   free_filter_list (filters);
2283   CONNECTION_UNLOCK (connection);
2284
2285   /* Standard dispatch unless the filter ate the message - no need to
2286    * do anything if the message was altered
2287    */
2288   if (message != NULL)
2289     {
2290       GDBusMessageType message_type;
2291
2292       message_type = g_dbus_message_get_message_type (message);
2293       if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2294         {
2295           guint32 reply_serial;
2296           GTask *task;
2297
2298           reply_serial = g_dbus_message_get_reply_serial (message);
2299           CONNECTION_LOCK (connection);
2300           task = g_hash_table_lookup (connection->map_method_serial_to_task,
2301                                       GUINT_TO_POINTER (reply_serial));
2302           if (task != NULL)
2303             {
2304               /* This removes @task from @map_method_serial_to_task. */
2305               //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2306               send_message_data_deliver_reply_unlocked (task, message);
2307             }
2308           else
2309             {
2310               //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2311             }
2312           CONNECTION_UNLOCK (connection);
2313         }
2314       else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2315         {
2316           CONNECTION_LOCK (connection);
2317           distribute_signals (connection, message);
2318           CONNECTION_UNLOCK (connection);
2319         }
2320       else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2321         {
2322           CONNECTION_LOCK (connection);
2323           distribute_method_call (connection, message);
2324           CONNECTION_UNLOCK (connection);
2325         }
2326     }
2327
2328   if (message != NULL)
2329     g_object_unref (message);
2330   g_object_unref (connection);
2331 }
2332
2333 /* Called in GDBusWorker's thread, lock is not held */
2334 static GDBusMessage *
2335 on_worker_message_about_to_be_sent (GDBusWorker  *worker,
2336                                     GDBusMessage *message,
2337                                     gpointer      user_data)
2338 {
2339   GDBusConnection *connection;
2340   FilterData **filters;
2341   guint n;
2342   gboolean alive;
2343
2344   G_LOCK (message_bus_lock);
2345   alive = g_hash_table_contains (alive_connections, user_data);
2346   if (!alive)
2347     {
2348       G_UNLOCK (message_bus_lock);
2349       return message;
2350     }
2351   connection = G_DBUS_CONNECTION (user_data);
2352   g_object_ref (connection);
2353   G_UNLOCK (message_bus_lock);
2354
2355   //g_debug ("in on_worker_message_about_to_be_sent");
2356
2357   /* First collect the set of callback functions */
2358   CONNECTION_LOCK (connection);
2359   filters = copy_filter_list (connection->filters);
2360   CONNECTION_UNLOCK (connection);
2361
2362   /* then call the filters in order (without holding the lock) */
2363   for (n = 0; filters[n]; n++)
2364     {
2365       g_dbus_message_lock (message);
2366       message = filters[n]->filter_function (connection,
2367                                              message,
2368                                              FALSE,
2369                                              filters[n]->user_data);
2370       if (message == NULL)
2371         break;
2372     }
2373
2374   CONNECTION_LOCK (connection);
2375   free_filter_list (filters);
2376   CONNECTION_UNLOCK (connection);
2377
2378   g_object_unref (connection);
2379
2380   return message;
2381 }
2382
2383 /* called with connection lock held, in GDBusWorker thread */
2384 static gboolean
2385 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2386 {
2387   GTask *task = value;
2388   SendMessageData *data = g_task_get_task_data (task);
2389
2390   if (data->delivered)
2391     return FALSE;
2392
2393   g_task_return_new_error (task,
2394                            G_IO_ERROR,
2395                            G_IO_ERROR_CLOSED,
2396                            _("The connection is closed"));
2397
2398   /* Ask send_message_with_reply_cleanup not to remove the element from the
2399    * hash table - we're in the middle of a foreach; that would be unsafe.
2400    * Instead, return TRUE from this function so that it gets removed safely.
2401    */
2402   send_message_with_reply_cleanup (task, FALSE);
2403   return TRUE;
2404 }
2405
2406 /* Called in GDBusWorker's thread - we must not block - without lock held */
2407 static void
2408 on_worker_closed (GDBusWorker *worker,
2409                   gboolean     remote_peer_vanished,
2410                   GError      *error,
2411                   gpointer     user_data)
2412 {
2413   GDBusConnection *connection;
2414   gboolean alive;
2415   guint old_atomic_flags;
2416
2417   G_LOCK (message_bus_lock);
2418   alive = g_hash_table_contains (alive_connections, user_data);
2419   if (!alive)
2420     {
2421       G_UNLOCK (message_bus_lock);
2422       return;
2423     }
2424   connection = G_DBUS_CONNECTION (user_data);
2425   g_object_ref (connection);
2426   G_UNLOCK (message_bus_lock);
2427
2428   //g_debug ("in on_worker_closed: %s", error->message);
2429
2430   CONNECTION_LOCK (connection);
2431   /* Even though this is atomic, we do it inside the lock to avoid breaking
2432    * assumptions in remove_match_rule(). We'd need the lock in a moment
2433    * anyway, so, no loss.
2434    */
2435   old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2436
2437   if (!(old_atomic_flags & FLAG_CLOSED))
2438     {
2439       g_hash_table_foreach_remove (connection->map_method_serial_to_task, cancel_method_on_close, NULL);
2440       schedule_closed_unlocked (connection, remote_peer_vanished, error);
2441     }
2442   CONNECTION_UNLOCK (connection);
2443
2444   g_object_unref (connection);
2445 }
2446
2447 /* ---------------------------------------------------------------------------------------------------- */
2448
2449 /* Determines the biggest set of capabilities we can support on this
2450  * connection.
2451  *
2452  * Called with the init_lock held.
2453  */
2454 static GDBusCapabilityFlags
2455 get_offered_capabilities_max (GDBusConnection *connection)
2456 {
2457       GDBusCapabilityFlags ret;
2458       ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2459 #ifdef G_OS_UNIX
2460       if (G_IS_UNIX_CONNECTION (connection->stream))
2461         ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2462 #endif
2463       return ret;
2464 }
2465
2466 /* Called in a user thread, lock is not held */
2467 static gboolean
2468 initable_init (GInitable     *initable,
2469                GCancellable  *cancellable,
2470                GError       **error)
2471 {
2472   GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2473   gboolean ret;
2474
2475   /* This method needs to be idempotent to work with the singleton
2476    * pattern. See the docs for g_initable_init(). We implement this by
2477    * locking.
2478    *
2479    * Unfortunately we can't use the main lock since the on_worker_*()
2480    * callbacks above needs the lock during initialization (for message
2481    * bus connections we do a synchronous Hello() call on the bus).
2482    */
2483   g_mutex_lock (&connection->init_lock);
2484
2485   ret = FALSE;
2486
2487   /* Make this a no-op if we're already initialized (successfully or
2488    * unsuccessfully)
2489    */
2490   if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2491     {
2492       ret = (connection->initialization_error == NULL);
2493       goto out;
2494     }
2495
2496   /* Because of init_lock, we can't get here twice in different threads */
2497   g_assert (connection->initialization_error == NULL);
2498
2499   /* The user can pass multiple (but mutally exclusive) construct
2500    * properties:
2501    *
2502    *  - stream (of type GIOStream)
2503    *  - address (of type gchar*)
2504    *
2505    * At the end of the day we end up with a non-NULL GIOStream
2506    * object in connection->stream.
2507    */
2508   if (connection->address != NULL)
2509     {
2510       g_assert (connection->stream == NULL);
2511
2512       if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2513           (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2514         {
2515           g_set_error_literal (&connection->initialization_error,
2516                                G_IO_ERROR,
2517                                G_IO_ERROR_INVALID_ARGUMENT,
2518                                _("Unsupported flags encountered when constructing a client-side connection"));
2519           goto out;
2520         }
2521
2522       connection->stream = g_dbus_address_get_stream_sync (connection->address,
2523                                                            NULL, /* TODO: out_guid */
2524                                                            cancellable,
2525                                                            &connection->initialization_error);
2526       if (connection->stream == NULL)
2527         goto out;
2528     }
2529   else if (connection->stream != NULL)
2530     {
2531       /* nothing to do */
2532     }
2533   else
2534     {
2535       g_assert_not_reached ();
2536     }
2537
2538   /* Authenticate the connection */
2539   if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2540     {
2541       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2542       g_assert (connection->guid != NULL);
2543       connection->auth = _g_dbus_auth_new (connection->stream);
2544       if (!_g_dbus_auth_run_server (connection->auth,
2545                                     connection->authentication_observer,
2546                                     connection->guid,
2547                                     (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2548                                     get_offered_capabilities_max (connection),
2549                                     &connection->capabilities,
2550                                     &connection->credentials,
2551                                     cancellable,
2552                                     &connection->initialization_error))
2553         goto out;
2554     }
2555   else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2556     {
2557       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2558       g_assert (connection->guid == NULL);
2559       connection->auth = _g_dbus_auth_new (connection->stream);
2560       connection->guid = _g_dbus_auth_run_client (connection->auth,
2561                                                   connection->authentication_observer,
2562                                                   get_offered_capabilities_max (connection),
2563                                                   &connection->capabilities,
2564                                                   cancellable,
2565                                                   &connection->initialization_error);
2566       if (connection->guid == NULL)
2567         goto out;
2568     }
2569
2570   if (connection->authentication_observer != NULL)
2571     {
2572       g_object_unref (connection->authentication_observer);
2573       connection->authentication_observer = NULL;
2574     }
2575
2576   //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2577
2578   //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2579
2580 #ifdef G_OS_UNIX
2581   /* We want all IO operations to be non-blocking since they happen in
2582    * the worker thread which is shared by _all_ connections.
2583    */
2584   if (G_IS_SOCKET_CONNECTION (connection->stream))
2585     {
2586       g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2587     }
2588 #endif
2589
2590   G_LOCK (message_bus_lock);
2591   if (alive_connections == NULL)
2592     alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2593   g_hash_table_add (alive_connections, connection);
2594   G_UNLOCK (message_bus_lock);
2595
2596   connection->worker = _g_dbus_worker_new (connection->stream,
2597                                            connection->capabilities,
2598                                            ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2599                                            on_worker_message_received,
2600                                            on_worker_message_about_to_be_sent,
2601                                            on_worker_closed,
2602                                            connection);
2603
2604   /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2605   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2606     {
2607       GVariant *hello_result;
2608
2609       /* we could lift this restriction by adding code in gdbusprivate.c */
2610       if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2611         {
2612           g_set_error_literal (&connection->initialization_error,
2613                                G_IO_ERROR,
2614                                G_IO_ERROR_FAILED,
2615                                "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2616           goto out;
2617         }
2618
2619       hello_result = g_dbus_connection_call_sync (connection,
2620                                                   "org.freedesktop.DBus", /* name */
2621                                                   "/org/freedesktop/DBus", /* path */
2622                                                   "org.freedesktop.DBus", /* interface */
2623                                                   "Hello",
2624                                                   NULL, /* parameters */
2625                                                   G_VARIANT_TYPE ("(s)"),
2626                                                   CALL_FLAGS_INITIALIZING,
2627                                                   -1,
2628                                                   NULL, /* TODO: cancellable */
2629                                                   &connection->initialization_error);
2630       if (hello_result == NULL)
2631         goto out;
2632
2633       g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2634       g_variant_unref (hello_result);
2635       //g_debug ("unique name is '%s'", connection->bus_unique_name);
2636     }
2637
2638   ret = TRUE;
2639  out:
2640   if (!ret)
2641     {
2642       g_assert (connection->initialization_error != NULL);
2643       g_propagate_error (error, g_error_copy (connection->initialization_error));
2644     }
2645
2646   g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2647   g_mutex_unlock (&connection->init_lock);
2648
2649   return ret;
2650 }
2651
2652 static void
2653 initable_iface_init (GInitableIface *initable_iface)
2654 {
2655   initable_iface->init = initable_init;
2656 }
2657
2658 /* ---------------------------------------------------------------------------------------------------- */
2659
2660 static void
2661 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2662 {
2663   /* Use default */
2664 }
2665
2666 /* ---------------------------------------------------------------------------------------------------- */
2667
2668 /**
2669  * g_dbus_connection_new:
2670  * @stream: a #GIOStream
2671  * @guid: (nullable): the GUID to use if a authenticating as a server or %NULL
2672  * @flags: flags describing how to make the connection
2673  * @observer: (nullable): a #GDBusAuthObserver or %NULL
2674  * @cancellable: (nullable): a #GCancellable or %NULL
2675  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2676  * @user_data: the data to pass to @callback
2677  *
2678  * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2679  * with the end represented by @stream.
2680  *
2681  * If @stream is a #GSocketConnection, then the corresponding #GSocket
2682  * will be put into non-blocking mode.
2683  *
2684  * The D-Bus connection will interact with @stream from a worker thread.
2685  * As a result, the caller should not interact with @stream after this
2686  * method has been called, except by calling g_object_unref() on it.
2687  *
2688  * If @observer is not %NULL it may be used to control the
2689  * authentication process.
2690  *
2691  * When the operation is finished, @callback will be invoked. You can
2692  * then call g_dbus_connection_new_finish() to get the result of the
2693  * operation.
2694  *
2695  * This is a asynchronous failable constructor. See
2696  * g_dbus_connection_new_sync() for the synchronous
2697  * version.
2698  *
2699  * Since: 2.26
2700  */
2701 void
2702 g_dbus_connection_new (GIOStream            *stream,
2703                        const gchar          *guid,
2704                        GDBusConnectionFlags  flags,
2705                        GDBusAuthObserver    *observer,
2706                        GCancellable         *cancellable,
2707                        GAsyncReadyCallback   callback,
2708                        gpointer              user_data)
2709 {
2710   _g_dbus_initialize ();
2711
2712   g_return_if_fail (G_IS_IO_STREAM (stream));
2713
2714   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2715                               G_PRIORITY_DEFAULT,
2716                               cancellable,
2717                               callback,
2718                               user_data,
2719                               "stream", stream,
2720                               "guid", guid,
2721                               "flags", flags,
2722                               "authentication-observer", observer,
2723                               NULL);
2724 }
2725
2726 /**
2727  * g_dbus_connection_new_finish:
2728  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2729  *     passed to g_dbus_connection_new().
2730  * @error: return location for error or %NULL
2731  *
2732  * Finishes an operation started with g_dbus_connection_new().
2733  *
2734  * Returns: a #GDBusConnection or %NULL if @error is set. Free
2735  *     with g_object_unref().
2736  *
2737  * Since: 2.26
2738  */
2739 GDBusConnection *
2740 g_dbus_connection_new_finish (GAsyncResult  *res,
2741                               GError       **error)
2742 {
2743   GObject *object;
2744   GObject *source_object;
2745
2746   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2747   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2748
2749   source_object = g_async_result_get_source_object (res);
2750   g_assert (source_object != NULL);
2751   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2752                                         res,
2753                                         error);
2754   g_object_unref (source_object);
2755   if (object != NULL)
2756     return G_DBUS_CONNECTION (object);
2757   else
2758     return NULL;
2759 }
2760
2761 /**
2762  * g_dbus_connection_new_sync:
2763  * @stream: a #GIOStream
2764  * @guid: (nullable): the GUID to use if a authenticating as a server or %NULL
2765  * @flags: flags describing how to make the connection
2766  * @observer: (nullable): a #GDBusAuthObserver or %NULL
2767  * @cancellable: (nullable): a #GCancellable or %NULL
2768  * @error: return location for error or %NULL
2769  *
2770  * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2771  * with the end represented by @stream.
2772  *
2773  * If @stream is a #GSocketConnection, then the corresponding #GSocket
2774  * will be put into non-blocking mode.
2775  *
2776  * The D-Bus connection will interact with @stream from a worker thread.
2777  * As a result, the caller should not interact with @stream after this
2778  * method has been called, except by calling g_object_unref() on it.
2779  *
2780  * If @observer is not %NULL it may be used to control the
2781  * authentication process.
2782  *
2783  * This is a synchronous failable constructor. See
2784  * g_dbus_connection_new() for the asynchronous version.
2785  *
2786  * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2787  *
2788  * Since: 2.26
2789  */
2790 GDBusConnection *
2791 g_dbus_connection_new_sync (GIOStream             *stream,
2792                             const gchar           *guid,
2793                             GDBusConnectionFlags   flags,
2794                             GDBusAuthObserver     *observer,
2795                             GCancellable          *cancellable,
2796                             GError               **error)
2797 {
2798   _g_dbus_initialize ();
2799   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2800   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2801   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2802                          cancellable,
2803                          error,
2804                          "stream", stream,
2805                          "guid", guid,
2806                          "flags", flags,
2807                          "authentication-observer", observer,
2808                          NULL);
2809 }
2810
2811 /* ---------------------------------------------------------------------------------------------------- */
2812
2813 /**
2814  * g_dbus_connection_new_for_address:
2815  * @address: a D-Bus address
2816  * @flags: flags describing how to make the connection
2817  * @observer: (nullable): a #GDBusAuthObserver or %NULL
2818  * @cancellable: (nullable): a #GCancellable or %NULL
2819  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2820  * @user_data: the data to pass to @callback
2821  *
2822  * Asynchronously connects and sets up a D-Bus client connection for
2823  * exchanging D-Bus messages with an endpoint specified by @address
2824  * which must be in the
2825  * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2826  *
2827  * This constructor can only be used to initiate client-side
2828  * connections - use g_dbus_connection_new() if you need to act as the
2829  * server. In particular, @flags cannot contain the
2830  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2831  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2832  *
2833  * When the operation is finished, @callback will be invoked. You can
2834  * then call g_dbus_connection_new_finish() to get the result of the
2835  * operation.
2836  *
2837  * If @observer is not %NULL it may be used to control the
2838  * authentication process.
2839  *
2840  * This is a asynchronous failable constructor. See
2841  * g_dbus_connection_new_for_address_sync() for the synchronous
2842  * version.
2843  *
2844  * Since: 2.26
2845  */
2846 void
2847 g_dbus_connection_new_for_address (const gchar          *address,
2848                                    GDBusConnectionFlags  flags,
2849                                    GDBusAuthObserver    *observer,
2850                                    GCancellable         *cancellable,
2851                                    GAsyncReadyCallback   callback,
2852                                    gpointer              user_data)
2853 {
2854   _g_dbus_initialize ();
2855
2856   g_return_if_fail (address != NULL);
2857
2858   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2859                               G_PRIORITY_DEFAULT,
2860                               cancellable,
2861                               callback,
2862                               user_data,
2863                               "address", address,
2864                               "flags", flags,
2865                               "authentication-observer", observer,
2866                               NULL);
2867 }
2868
2869 /**
2870  * g_dbus_connection_new_for_address_finish:
2871  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2872  *     to g_dbus_connection_new()
2873  * @error: return location for error or %NULL
2874  *
2875  * Finishes an operation started with g_dbus_connection_new_for_address().
2876  *
2877  * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2878  *     g_object_unref().
2879  *
2880  * Since: 2.26
2881  */
2882 GDBusConnection *
2883 g_dbus_connection_new_for_address_finish (GAsyncResult  *res,
2884                                           GError       **error)
2885 {
2886   GObject *object;
2887   GObject *source_object;
2888
2889   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2890   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2891
2892   source_object = g_async_result_get_source_object (res);
2893   g_assert (source_object != NULL);
2894   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2895                                         res,
2896                                         error);
2897   g_object_unref (source_object);
2898   if (object != NULL)
2899     return G_DBUS_CONNECTION (object);
2900   else
2901     return NULL;
2902 }
2903
2904 /**
2905  * g_dbus_connection_new_for_address_sync:
2906  * @address: a D-Bus address
2907  * @flags: flags describing how to make the connection
2908  * @observer: (nullable): a #GDBusAuthObserver or %NULL
2909  * @cancellable: (nullable): a #GCancellable or %NULL
2910  * @error: return location for error or %NULL
2911  *
2912  * Synchronously connects and sets up a D-Bus client connection for
2913  * exchanging D-Bus messages with an endpoint specified by @address
2914  * which must be in the
2915  * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2916  *
2917  * This constructor can only be used to initiate client-side
2918  * connections - use g_dbus_connection_new_sync() if you need to act
2919  * as the server. In particular, @flags cannot contain the
2920  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2921  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2922  *
2923  * This is a synchronous failable constructor. See
2924  * g_dbus_connection_new_for_address() for the asynchronous version.
2925  *
2926  * If @observer is not %NULL it may be used to control the
2927  * authentication process.
2928  *
2929  * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2930  *     g_object_unref().
2931  *
2932  * Since: 2.26
2933  */
2934 GDBusConnection *
2935 g_dbus_connection_new_for_address_sync (const gchar           *address,
2936                                         GDBusConnectionFlags   flags,
2937                                         GDBusAuthObserver     *observer,
2938                                         GCancellable          *cancellable,
2939                                         GError               **error)
2940 {
2941   _g_dbus_initialize ();
2942
2943   g_return_val_if_fail (address != NULL, NULL);
2944   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2945   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2946                          cancellable,
2947                          error,
2948                          "address", address,
2949                          "flags", flags,
2950                          "authentication-observer", observer,
2951                          NULL);
2952 }
2953
2954 /* ---------------------------------------------------------------------------------------------------- */
2955
2956 /**
2957  * g_dbus_connection_set_exit_on_close:
2958  * @connection: a #GDBusConnection
2959  * @exit_on_close: whether the process should be terminated
2960  *     when @connection is closed by the remote peer
2961  *
2962  * Sets whether the process should be terminated when @connection is
2963  * closed by the remote peer. See #GDBusConnection:exit-on-close for
2964  * more details.
2965  *
2966  * Note that this function should be used with care. Most modern UNIX
2967  * desktops tie the notion of a user session the session bus, and expect
2968  * all of a users applications to quit when their bus connection goes away.
2969  * If you are setting @exit_on_close to %FALSE for the shared session
2970  * bus connection, you should make sure that your application exits
2971  * when the user session ends.
2972  *
2973  * Since: 2.26
2974  */
2975 void
2976 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2977                                      gboolean         exit_on_close)
2978 {
2979   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2980
2981   if (exit_on_close)
2982     g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2983   else
2984     g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2985
2986 }
2987
2988 /**
2989  * g_dbus_connection_get_exit_on_close:
2990  * @connection: a #GDBusConnection
2991  *
2992  * Gets whether the process is terminated when @connection is
2993  * closed by the remote peer. See
2994  * #GDBusConnection:exit-on-close for more details.
2995  *
2996  * Returns: whether the process is terminated when @connection is
2997  *     closed by the remote peer
2998  *
2999  * Since: 2.26
3000  */
3001 gboolean
3002 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3003 {
3004   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3005
3006   if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3007     return TRUE;
3008   else
3009     return FALSE;
3010 }
3011
3012 /**
3013  * g_dbus_connection_get_guid:
3014  * @connection: a #GDBusConnection
3015  *
3016  * The GUID of the peer performing the role of server when
3017  * authenticating. See #GDBusConnection:guid for more details.
3018  *
3019  * Returns: The GUID. Do not free this string, it is owned by
3020  *     @connection.
3021  *
3022  * Since: 2.26
3023  */
3024 const gchar *
3025 g_dbus_connection_get_guid (GDBusConnection *connection)
3026 {
3027   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3028   return connection->guid;
3029 }
3030
3031 /**
3032  * g_dbus_connection_get_unique_name:
3033  * @connection: a #GDBusConnection
3034  *
3035  * Gets the unique name of @connection as assigned by the message
3036  * bus. This can also be used to figure out if @connection is a
3037  * message bus connection.
3038  *
3039  * Returns: (nullable): the unique name or %NULL if @connection is not a message
3040  *     bus connection. Do not free this string, it is owned by
3041  *     @connection.
3042  *
3043  * Since: 2.26
3044  */
3045 const gchar *
3046 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3047 {
3048   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3049
3050   /* do not use g_return_val_if_fail(), we want the memory barrier */
3051   if (!check_initialized (connection))
3052     return NULL;
3053
3054   return connection->bus_unique_name;
3055 }
3056
3057 /**
3058  * g_dbus_connection_get_peer_credentials:
3059  * @connection: a #GDBusConnection
3060  *
3061  * Gets the credentials of the authenticated peer. This will always
3062  * return %NULL unless @connection acted as a server
3063  * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3064  * when set up and the client passed credentials as part of the
3065  * authentication process.
3066  *
3067  * In a message bus setup, the message bus is always the server and
3068  * each application is a client. So this method will always return
3069  * %NULL for message bus clients.
3070  *
3071  * Returns: (transfer none) (nullable): a #GCredentials or %NULL if not
3072  *     available. Do not free this object, it is owned by @connection.
3073  *
3074  * Since: 2.26
3075  */
3076 GCredentials *
3077 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3078 {
3079   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3080
3081   /* do not use g_return_val_if_fail(), we want the memory barrier */
3082   if (!check_initialized (connection))
3083     return NULL;
3084
3085   return connection->credentials;
3086 }
3087
3088 /* ---------------------------------------------------------------------------------------------------- */
3089
3090 static volatile guint _global_filter_id = 1;
3091
3092 /**
3093  * g_dbus_connection_add_filter:
3094  * @connection: a #GDBusConnection
3095  * @filter_function: a filter function
3096  * @user_data: user data to pass to @filter_function
3097  * @user_data_free_func: function to free @user_data with when filter
3098  *     is removed or %NULL
3099  *
3100  * Adds a message filter. Filters are handlers that are run on all
3101  * incoming and outgoing messages, prior to standard dispatch. Filters
3102  * are run in the order that they were added.  The same handler can be
3103  * added as a filter more than once, in which case it will be run more
3104  * than once.  Filters added during a filter callback won't be run on
3105  * the message being processed. Filter functions are allowed to modify
3106  * and even drop messages.
3107  *
3108  * Note that filters are run in a dedicated message handling thread so
3109  * they can't block and, generally, can't do anything but signal a
3110  * worker thread. Also note that filters are rarely needed - use API
3111  * such as g_dbus_connection_send_message_with_reply(),
3112  * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3113  *
3114  * If a filter consumes an incoming message the message is not
3115  * dispatched anywhere else - not even the standard dispatch machinery
3116  * (that API such as g_dbus_connection_signal_subscribe() and
3117  * g_dbus_connection_send_message_with_reply() relies on) will see the
3118  * message. Similarly, if a filter consumes an outgoing message, the
3119  * message will not be sent to the other peer.
3120  *
3121  * If @user_data_free_func is non-%NULL, it will be called (in the
3122  * thread-default main context of the thread you are calling this
3123  * method from) at some point after @user_data is no longer
3124  * needed. (It is not guaranteed to be called synchronously when the
3125  * filter is removed, and may be called after @connection has been
3126  * destroyed.)
3127  *
3128  * Returns: a filter identifier that can be used with
3129  *     g_dbus_connection_remove_filter()
3130  *
3131  * Since: 2.26
3132  */
3133 guint
3134 g_dbus_connection_add_filter (GDBusConnection            *connection,
3135                               GDBusMessageFilterFunction  filter_function,
3136                               gpointer                    user_data,
3137                               GDestroyNotify              user_data_free_func)
3138 {
3139   FilterData *data;
3140
3141   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3142   g_return_val_if_fail (filter_function != NULL, 0);
3143   g_return_val_if_fail (check_initialized (connection), 0);
3144
3145   CONNECTION_LOCK (connection);
3146   data = g_new0 (FilterData, 1);
3147   data->id = g_atomic_int_add (&_global_filter_id, 1); /* TODO: overflow etc. */
3148   data->ref_count = 1;
3149   data->filter_function = filter_function;
3150   data->user_data = user_data;
3151   data->user_data_free_func = user_data_free_func;
3152   data->context = g_main_context_ref_thread_default ();
3153   g_ptr_array_add (connection->filters, data);
3154   CONNECTION_UNLOCK (connection);
3155
3156   return data->id;
3157 }
3158
3159 /* only called from finalize(), removes all filters */
3160 static void
3161 purge_all_filters (GDBusConnection *connection)
3162 {
3163   guint n;
3164   for (n = 0; n < connection->filters->len; n++)
3165     {
3166       FilterData *data = connection->filters->pdata[n];
3167
3168       call_destroy_notify (data->context,
3169                            data->user_data_free_func,
3170                            data->user_data);
3171       g_main_context_unref (data->context);
3172       g_free (data);
3173     }
3174 }
3175
3176 /**
3177  * g_dbus_connection_remove_filter:
3178  * @connection: a #GDBusConnection
3179  * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3180  *
3181  * Removes a filter.
3182  *
3183  * Note that since filters run in a different thread, there is a race
3184  * condition where it is possible that the filter will be running even
3185  * after calling g_dbus_connection_remove_filter(), so you cannot just
3186  * free data that the filter might be using. Instead, you should pass
3187  * a #GDestroyNotify to g_dbus_connection_add_filter(), which will be
3188  * called when it is guaranteed that the data is no longer needed.
3189  *
3190  * Since: 2.26
3191  */
3192 void
3193 g_dbus_connection_remove_filter (GDBusConnection *connection,
3194                                  guint            filter_id)
3195 {
3196   guint n;
3197   gboolean found;
3198   FilterData *to_destroy;
3199
3200   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3201   g_return_if_fail (check_initialized (connection));
3202
3203   CONNECTION_LOCK (connection);
3204   found = FALSE;
3205   to_destroy = NULL;
3206   for (n = 0; n < connection->filters->len; n++)
3207     {
3208       FilterData *data = connection->filters->pdata[n];
3209       if (data->id == filter_id)
3210         {
3211           found = TRUE;
3212           g_ptr_array_remove_index (connection->filters, n);
3213           data->ref_count--;
3214           if (data->ref_count == 0)
3215             to_destroy = data;
3216           break;
3217         }
3218     }
3219   CONNECTION_UNLOCK (connection);
3220
3221   /* do free without holding lock */
3222   if (to_destroy != NULL)
3223     {
3224       if (to_destroy->user_data_free_func != NULL)
3225         to_destroy->user_data_free_func (to_destroy->user_data);
3226       g_main_context_unref (to_destroy->context);
3227       g_free (to_destroy);
3228     }
3229   else if (!found)
3230     {
3231       g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3232     }
3233 }
3234
3235 /* ---------------------------------------------------------------------------------------------------- */
3236
3237 typedef struct
3238 {
3239   gchar *rule;
3240   gchar *sender;
3241   gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3242   gchar *interface_name;
3243   gchar *member;
3244   gchar *object_path;
3245   gchar *arg0;
3246   GDBusSignalFlags flags;
3247   GArray *subscribers;
3248 } SignalData;
3249
3250 typedef struct
3251 {
3252   GDBusSignalCallback callback;
3253   gpointer user_data;
3254   GDestroyNotify user_data_free_func;
3255   guint id;
3256   GMainContext *context;
3257 } SignalSubscriber;
3258
3259 static void
3260 signal_data_free (SignalData *signal_data)
3261 {
3262   g_free (signal_data->rule);
3263   g_free (signal_data->sender);
3264   g_free (signal_data->sender_unique_name);
3265   g_free (signal_data->interface_name);
3266   g_free (signal_data->member);
3267   g_free (signal_data->object_path);
3268   g_free (signal_data->arg0);
3269   g_array_free (signal_data->subscribers, TRUE);
3270   g_free (signal_data);
3271 }
3272
3273 static gchar *
3274 args_to_rule (const gchar      *sender,
3275               const gchar      *interface_name,
3276               const gchar      *member,
3277               const gchar      *object_path,
3278               const gchar      *arg0,
3279               GDBusSignalFlags  flags)
3280 {
3281   GString *rule;
3282
3283   rule = g_string_new ("type='signal'");
3284   if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3285     g_string_prepend_c (rule, '-');
3286   if (sender != NULL)
3287     g_string_append_printf (rule, ",sender='%s'", sender);
3288   if (interface_name != NULL)
3289     g_string_append_printf (rule, ",interface='%s'", interface_name);
3290   if (member != NULL)
3291     g_string_append_printf (rule, ",member='%s'", member);
3292   if (object_path != NULL)
3293     g_string_append_printf (rule, ",path='%s'", object_path);
3294
3295   if (arg0 != NULL)
3296     {
3297       if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3298         g_string_append_printf (rule, ",arg0path='%s'", arg0);
3299       else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3300         g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3301       else
3302         g_string_append_printf (rule, ",arg0='%s'", arg0);
3303     }
3304
3305   return g_string_free (rule, FALSE);
3306 }
3307
3308 static volatile guint _global_subscriber_id = 1;
3309 static volatile guint _global_registration_id = 1;
3310 static volatile guint _global_subtree_registration_id = 1;
3311
3312 /* ---------------------------------------------------------------------------------------------------- */
3313
3314 /* Called in a user thread, lock is held */
3315 static void
3316 add_match_rule (GDBusConnection *connection,
3317                 const gchar     *match_rule)
3318 {
3319   GError *error;
3320   GDBusMessage *message;
3321
3322   if (match_rule[0] == '-')
3323     return;
3324
3325   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3326                                             "/org/freedesktop/DBus", /* path */
3327                                             "org.freedesktop.DBus", /* interface */
3328                                             "AddMatch");
3329   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3330   error = NULL;
3331   if (!g_dbus_connection_send_message_unlocked (connection,
3332                                                 message,
3333                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3334                                                 NULL,
3335                                                 &error))
3336     {
3337       g_critical ("Error while sending AddMatch() message: %s", error->message);
3338       g_error_free (error);
3339     }
3340   g_object_unref (message);
3341 }
3342
3343 /* ---------------------------------------------------------------------------------------------------- */
3344
3345 /* Called in a user thread, lock is held */
3346 static void
3347 remove_match_rule (GDBusConnection *connection,
3348                    const gchar     *match_rule)
3349 {
3350   GError *error;
3351   GDBusMessage *message;
3352
3353   if (match_rule[0] == '-')
3354     return;
3355
3356   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3357                                             "/org/freedesktop/DBus", /* path */
3358                                             "org.freedesktop.DBus", /* interface */
3359                                             "RemoveMatch");
3360   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3361
3362   error = NULL;
3363   if (!g_dbus_connection_send_message_unlocked (connection,
3364                                                 message,
3365                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3366                                                 NULL,
3367                                                 &error))
3368     {
3369       /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3370        * critical; but we're holding the lock, and our caller checked whether
3371        * we were already closed, so we can't get that error.
3372        */
3373       g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3374       g_error_free (error);
3375     }
3376   g_object_unref (message);
3377 }
3378
3379 /* ---------------------------------------------------------------------------------------------------- */
3380
3381 static gboolean
3382 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3383 {
3384   return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3385          g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3386          g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3387          (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3388           g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3389 }
3390
3391 /* ---------------------------------------------------------------------------------------------------- */
3392
3393 /**
3394  * g_dbus_connection_signal_subscribe:
3395  * @connection: a #GDBusConnection
3396  * @sender: (nullable): sender name to match on (unique or well-known name)
3397  *     or %NULL to listen from all senders
3398  * @interface_name: (nullable): D-Bus interface name to match on or %NULL to
3399  *     match on all interfaces
3400  * @member: (nullable): D-Bus signal name to match on or %NULL to match on
3401  *     all signals
3402  * @object_path: (nullable): object path to match on or %NULL to match on
3403  *     all object paths
3404  * @arg0: (nullable): contents of first string argument to match on or %NULL
3405  *     to match on all kinds of arguments
3406  * @flags: #GDBusSignalFlags describing how arg0 is used in subscribing to the
3407  *     signal
3408  * @callback: callback to invoke when there is a signal matching the requested data
3409  * @user_data: user data to pass to @callback
3410  * @user_data_free_func: (nullable): function to free @user_data with when
3411  *     subscription is removed or %NULL
3412  *
3413  * Subscribes to signals on @connection and invokes @callback with a whenever
3414  * the signal is received. Note that @callback will be invoked in the 
3415  * [thread-default main context][g-main-context-push-thread-default]
3416  * of the thread you are calling this method from.
3417  *
3418  * If @connection is not a message bus connection, @sender must be
3419  * %NULL.
3420  *
3421  * If @sender is a well-known name note that @callback is invoked with
3422  * the unique name for the owner of @sender, not the well-known name
3423  * as one would expect. This is because the message bus rewrites the
3424  * name. As such, to avoid certain race conditions, users should be
3425  * tracking the name owner of the well-known name and use that when
3426  * processing the received signal.
3427  *
3428  * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3429  * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3430  * interpreted as part of a namespace or path.  The first argument
3431  * of a signal is matched against that part as specified by D-Bus.
3432  *
3433  * If @user_data_free_func is non-%NULL, it will be called (in the
3434  * thread-default main context of the thread you are calling this
3435  * method from) at some point after @user_data is no longer
3436  * needed. (It is not guaranteed to be called synchronously when the
3437  * signal is unsubscribed from, and may be called after @connection
3438  * has been destroyed.)
3439  *
3440  * The returned subscription identifier is an opaque value which is guaranteed
3441  * to never be zero.
3442  *
3443  * This function can never fail.
3444  *
3445  * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3446  *
3447  * Since: 2.26
3448  */
3449 guint
3450 g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
3451                                     const gchar         *sender,
3452                                     const gchar         *interface_name,
3453                                     const gchar         *member,
3454                                     const gchar         *object_path,
3455                                     const gchar         *arg0,
3456                                     GDBusSignalFlags     flags,
3457                                     GDBusSignalCallback  callback,
3458                                     gpointer             user_data,
3459                                     GDestroyNotify       user_data_free_func)
3460 {
3461   gchar *rule;
3462   SignalData *signal_data;
3463   SignalSubscriber subscriber;
3464   GPtrArray *signal_data_array;
3465   const gchar *sender_unique_name;
3466
3467   /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3468    * an OOM condition. We might want to change that but that would involve making
3469    * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3470    * handle that. And there's really no sensible way of handling this short of retrying
3471    * to add the match rule... and then there's the little thing that, hey, maybe there's
3472    * a reason the bus in an OOM condition.
3473    *
3474    * Doable, but not really sure it's worth it...
3475    */
3476
3477   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3478   g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3479   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3480   g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3481   g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3482   g_return_val_if_fail (callback != NULL, 0);
3483   g_return_val_if_fail (check_initialized (connection), 0);
3484   g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3485   g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3486
3487   CONNECTION_LOCK (connection);
3488
3489   /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3490    * with a '-' character to prefix the rule (which will otherwise be
3491    * normal).
3492    *
3493    * This allows us to hash the rule and do our lifecycle tracking in
3494    * the usual way, but the '-' prevents the match rule from ever
3495    * actually being send to the bus (either for add or remove).
3496    */
3497   rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3498
3499   if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3500     sender_unique_name = sender;
3501   else
3502     sender_unique_name = "";
3503
3504   subscriber.callback = callback;
3505   subscriber.user_data = user_data;
3506   subscriber.user_data_free_func = user_data_free_func;
3507   subscriber.id = g_atomic_int_add (&_global_subscriber_id, 1); /* TODO: overflow etc. */
3508   subscriber.context = g_main_context_ref_thread_default ();
3509
3510   /* see if we've already have this rule */
3511   signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3512   if (signal_data != NULL)
3513     {
3514       g_array_append_val (signal_data->subscribers, subscriber);
3515       g_free (rule);
3516       goto out;
3517     }
3518
3519   signal_data = g_new0 (SignalData, 1);
3520   signal_data->rule                  = rule;
3521   signal_data->sender                = g_strdup (sender);
3522   signal_data->sender_unique_name    = g_strdup (sender_unique_name);
3523   signal_data->interface_name        = g_strdup (interface_name);
3524   signal_data->member                = g_strdup (member);
3525   signal_data->object_path           = g_strdup (object_path);
3526   signal_data->arg0                  = g_strdup (arg0);
3527   signal_data->flags                 = flags;
3528   signal_data->subscribers           = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3529   g_array_append_val (signal_data->subscribers, subscriber);
3530
3531   g_hash_table_insert (connection->map_rule_to_signal_data,
3532                        signal_data->rule,
3533                        signal_data);
3534
3535   /* Add the match rule to the bus...
3536    *
3537    * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3538    * always send such messages to us.
3539    */
3540   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3541     {
3542       if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3543         add_match_rule (connection, signal_data->rule);
3544     }
3545
3546   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3547                                            signal_data->sender_unique_name);
3548   if (signal_data_array == NULL)
3549     {
3550       signal_data_array = g_ptr_array_new ();
3551       g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3552                            g_strdup (signal_data->sender_unique_name),
3553                            signal_data_array);
3554     }
3555   g_ptr_array_add (signal_data_array, signal_data);
3556
3557  out:
3558   g_hash_table_insert (connection->map_id_to_signal_data,
3559                        GUINT_TO_POINTER (subscriber.id),
3560                        signal_data);
3561
3562   CONNECTION_UNLOCK (connection);
3563
3564   return subscriber.id;
3565 }
3566
3567 /* ---------------------------------------------------------------------------------------------------- */
3568
3569 /* called in any thread */
3570 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3571 static void
3572 unsubscribe_id_internal (GDBusConnection *connection,
3573                          guint            subscription_id,
3574                          GArray          *out_removed_subscribers)
3575 {
3576   SignalData *signal_data;
3577   GPtrArray *signal_data_array;
3578   guint n;
3579
3580   signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3581                                      GUINT_TO_POINTER (subscription_id));
3582   if (signal_data == NULL)
3583     {
3584       /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3585       goto out;
3586     }
3587
3588   for (n = 0; n < signal_data->subscribers->len; n++)
3589     {
3590       SignalSubscriber *subscriber;
3591
3592       subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3593       if (subscriber->id != subscription_id)
3594         continue;
3595
3596       g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3597                                            GUINT_TO_POINTER (subscription_id)));
3598       g_array_append_val (out_removed_subscribers, *subscriber);
3599       g_array_remove_index (signal_data->subscribers, n);
3600
3601       if (signal_data->subscribers->len == 0)
3602         {
3603           g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3604
3605           signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3606                                                    signal_data->sender_unique_name);
3607           g_warn_if_fail (signal_data_array != NULL);
3608           g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3609
3610           if (signal_data_array->len == 0)
3611             {
3612               g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3613                                                    signal_data->sender_unique_name));
3614             }
3615
3616           /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3617           if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3618               !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3619               !g_dbus_connection_is_closed (connection) &&
3620               !connection->finalizing)
3621             {
3622               /* The check for g_dbus_connection_is_closed() means that
3623                * sending the RemoveMatch message can't fail with
3624                * G_IO_ERROR_CLOSED, because we're holding the lock,
3625                * so on_worker_closed() can't happen between the check we just
3626                * did, and releasing the lock later.
3627                */
3628               remove_match_rule (connection, signal_data->rule);
3629             }
3630
3631           signal_data_free (signal_data);
3632         }
3633
3634       goto out;
3635     }
3636
3637   g_assert_not_reached ();
3638
3639  out:
3640   ;
3641 }
3642
3643 /**
3644  * g_dbus_connection_signal_unsubscribe:
3645  * @connection: a #GDBusConnection
3646  * @subscription_id: a subscription id obtained from
3647  *     g_dbus_connection_signal_subscribe()
3648  *
3649  * Unsubscribes from signals.
3650  *
3651  * Since: 2.26
3652  */
3653 void
3654 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3655                                       guint            subscription_id)
3656 {
3657   GArray *subscribers;
3658   guint n;
3659
3660   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3661   g_return_if_fail (check_initialized (connection));
3662
3663   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3664
3665   CONNECTION_LOCK (connection);
3666   unsubscribe_id_internal (connection,
3667                            subscription_id,
3668                            subscribers);
3669   CONNECTION_UNLOCK (connection);
3670
3671   /* invariant */
3672   g_assert (subscribers->len == 0 || subscribers->len == 1);
3673
3674   /* call GDestroyNotify without lock held */
3675   for (n = 0; n < subscribers->len; n++)
3676     {
3677       SignalSubscriber *subscriber;
3678       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3679       call_destroy_notify (subscriber->context,
3680                            subscriber->user_data_free_func,
3681                            subscriber->user_data);
3682       g_main_context_unref (subscriber->context);
3683     }
3684
3685   g_array_free (subscribers, TRUE);
3686 }
3687
3688 /* ---------------------------------------------------------------------------------------------------- */
3689
3690 typedef struct
3691 {
3692   guint                subscription_id;
3693   GDBusSignalCallback  callback;
3694   gpointer             user_data;
3695   GDBusMessage        *message;
3696   GDBusConnection     *connection;
3697   const gchar         *sender;
3698   const gchar         *path;
3699   const gchar         *interface;
3700   const gchar         *member;
3701 } SignalInstance;
3702
3703 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3704  * no locks held
3705  */
3706 static gboolean
3707 emit_signal_instance_in_idle_cb (gpointer data)
3708 {
3709   SignalInstance *signal_instance = data;
3710   GVariant *parameters;
3711   gboolean has_subscription;
3712
3713   parameters = g_dbus_message_get_body (signal_instance->message);
3714   if (parameters == NULL)
3715     {
3716       parameters = g_variant_new ("()");
3717       g_variant_ref_sink (parameters);
3718     }
3719   else
3720     {
3721       g_variant_ref_sink (parameters);
3722     }
3723
3724 #if 0
3725   g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3726            signal_instance->subscription_id,
3727            signal_instance->sender,
3728            signal_instance->path,
3729            signal_instance->interface,
3730            signal_instance->member,
3731            g_variant_print (parameters, TRUE));
3732 #endif
3733
3734   /* Careful here, don't do the callback if we no longer has the subscription */
3735   CONNECTION_LOCK (signal_instance->connection);
3736   has_subscription = FALSE;
3737   if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3738                            GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3739     has_subscription = TRUE;
3740   CONNECTION_UNLOCK (signal_instance->connection);
3741
3742   if (has_subscription)
3743     signal_instance->callback (signal_instance->connection,
3744                                signal_instance->sender,
3745                                signal_instance->path,
3746                                signal_instance->interface,
3747                                signal_instance->member,
3748                                parameters,
3749                                signal_instance->user_data);
3750
3751   g_variant_unref (parameters);
3752
3753   return FALSE;
3754 }
3755
3756 static void
3757 signal_instance_free (SignalInstance *signal_instance)
3758 {
3759   g_object_unref (signal_instance->message);
3760   g_object_unref (signal_instance->connection);
3761   g_free (signal_instance);
3762 }
3763
3764 static gboolean
3765 namespace_rule_matches (const gchar *namespace,
3766                         const gchar *name)
3767 {
3768   gint len_namespace;
3769   gint len_name;
3770
3771   len_namespace = strlen (namespace);
3772   len_name = strlen (name);
3773
3774   if (len_name < len_namespace)
3775     return FALSE;
3776
3777   if (memcmp (namespace, name, len_namespace) != 0)
3778     return FALSE;
3779
3780   return len_namespace == len_name || name[len_namespace] == '.';
3781 }
3782
3783 static gboolean
3784 path_rule_matches (const gchar *path_a,
3785                    const gchar *path_b)
3786 {
3787   gint len_a, len_b;
3788
3789   len_a = strlen (path_a);
3790   len_b = strlen (path_b);
3791
3792   if (len_a < len_b && (len_a == 0 || path_a[len_a - 1] != '/'))
3793     return FALSE;
3794
3795   if (len_b < len_a && (len_b == 0 || path_b[len_b - 1] != '/'))
3796     return FALSE;
3797
3798   return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3799 }
3800
3801 /* called in GDBusWorker thread WITH lock held */
3802 static void
3803 schedule_callbacks (GDBusConnection *connection,
3804                     GPtrArray       *signal_data_array,
3805                     GDBusMessage    *message,
3806                     const gchar     *sender)
3807 {
3808   guint n, m;
3809   const gchar *interface;
3810   const gchar *member;
3811   const gchar *path;
3812   const gchar *arg0;
3813
3814   interface = NULL;
3815   member = NULL;
3816   path = NULL;
3817   arg0 = NULL;
3818
3819   interface = g_dbus_message_get_interface (message);
3820   member = g_dbus_message_get_member (message);
3821   path = g_dbus_message_get_path (message);
3822   arg0 = g_dbus_message_get_arg0 (message);
3823
3824 #if 0
3825   g_print ("In schedule_callbacks:\n"
3826            "  sender    = '%s'\n"
3827            "  interface = '%s'\n"
3828            "  member    = '%s'\n"
3829            "  path      = '%s'\n"
3830            "  arg0      = '%s'\n",
3831            sender,
3832            interface,
3833            member,
3834            path,
3835            arg0);
3836 #endif
3837
3838   /* TODO: if this is slow, then we can change signal_data_array into
3839    *       map_object_path_to_signal_data_array or something.
3840    */
3841   for (n = 0; n < signal_data_array->len; n++)
3842     {
3843       SignalData *signal_data = signal_data_array->pdata[n];
3844
3845       if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3846         continue;
3847
3848       if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3849         continue;
3850
3851       if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3852         continue;
3853
3854       if (signal_data->arg0 != NULL)
3855         {
3856           if (arg0 == NULL)
3857             continue;
3858
3859           if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3860             {
3861               if (!namespace_rule_matches (signal_data->arg0, arg0))
3862                 continue;
3863             }
3864           else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3865             {
3866               if (!path_rule_matches (signal_data->arg0, arg0))
3867                 continue;
3868             }
3869           else if (!g_str_equal (signal_data->arg0, arg0))
3870             continue;
3871         }
3872
3873       for (m = 0; m < signal_data->subscribers->len; m++)
3874         {
3875           SignalSubscriber *subscriber;
3876           GSource *idle_source;
3877           SignalInstance *signal_instance;
3878
3879           subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3880
3881           signal_instance = g_new0 (SignalInstance, 1);
3882           signal_instance->subscription_id = subscriber->id;
3883           signal_instance->callback = subscriber->callback;
3884           signal_instance->user_data = subscriber->user_data;
3885           signal_instance->message = g_object_ref (message);
3886           signal_instance->connection = g_object_ref (connection);
3887           signal_instance->sender = sender;
3888           signal_instance->path = path;
3889           signal_instance->interface = interface;
3890           signal_instance->member = member;
3891
3892           idle_source = g_idle_source_new ();
3893           g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3894           g_source_set_callback (idle_source,
3895                                  emit_signal_instance_in_idle_cb,
3896                                  signal_instance,
3897                                  (GDestroyNotify) signal_instance_free);
3898           g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
3899           g_source_attach (idle_source, subscriber->context);
3900           g_source_unref (idle_source);
3901         }
3902     }
3903 }
3904
3905 /* called in GDBusWorker thread with lock held */
3906 static void
3907 distribute_signals (GDBusConnection *connection,
3908                     GDBusMessage    *message)
3909 {
3910   GPtrArray *signal_data_array;
3911   const gchar *sender;
3912
3913   sender = g_dbus_message_get_sender (message);
3914
3915   if (G_UNLIKELY (_g_dbus_debug_signal ()))
3916     {
3917       _g_dbus_debug_print_lock ();
3918       g_print ("========================================================================\n"
3919                "GDBus-debug:Signal:\n"
3920                " <<<< RECEIVED SIGNAL %s.%s\n"
3921                "      on object %s\n"
3922                "      sent by name %s\n",
3923                g_dbus_message_get_interface (message),
3924                g_dbus_message_get_member (message),
3925                g_dbus_message_get_path (message),
3926                sender != NULL ? sender : "(none)");
3927       _g_dbus_debug_print_unlock ();
3928     }
3929
3930   /* collect subscribers that match on sender */
3931   if (sender != NULL)
3932     {
3933       signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3934       if (signal_data_array != NULL)
3935         schedule_callbacks (connection, signal_data_array, message, sender);
3936     }
3937
3938   /* collect subscribers not matching on sender */
3939   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3940   if (signal_data_array != NULL)
3941     schedule_callbacks (connection, signal_data_array, message, sender);
3942 }
3943
3944 /* ---------------------------------------------------------------------------------------------------- */
3945
3946 /* only called from finalize(), removes all subscriptions */
3947 static void
3948 purge_all_signal_subscriptions (GDBusConnection *connection)
3949 {
3950   GHashTableIter iter;
3951   gpointer key;
3952   GArray *ids;
3953   GArray *subscribers;
3954   guint n;
3955
3956   ids = g_array_new (FALSE, FALSE, sizeof (guint));
3957   g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3958   while (g_hash_table_iter_next (&iter, &key, NULL))
3959     {
3960       guint subscription_id = GPOINTER_TO_UINT (key);
3961       g_array_append_val (ids, subscription_id);
3962     }
3963
3964   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3965   for (n = 0; n < ids->len; n++)
3966     {
3967       guint subscription_id = g_array_index (ids, guint, n);
3968       unsubscribe_id_internal (connection,
3969                                subscription_id,
3970                                subscribers);
3971     }
3972   g_array_free (ids, TRUE);
3973
3974   /* call GDestroyNotify without lock held */
3975   for (n = 0; n < subscribers->len; n++)
3976     {
3977       SignalSubscriber *subscriber;
3978       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3979       call_destroy_notify (subscriber->context,
3980                            subscriber->user_data_free_func,
3981                            subscriber->user_data);
3982       g_main_context_unref (subscriber->context);
3983     }
3984
3985   g_array_free (subscribers, TRUE);
3986 }
3987
3988 /* ---------------------------------------------------------------------------------------------------- */
3989
3990 static GDBusInterfaceVTable *
3991 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3992 {
3993   /* Don't waste memory by copying padding - remember to update this
3994    * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3995    */
3996   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3997 }
3998
3999 static void
4000 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4001 {
4002   g_free (vtable);
4003 }
4004
4005 /* ---------------------------------------------------------------------------------------------------- */
4006
4007 static GDBusSubtreeVTable *
4008 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4009 {
4010   /* Don't waste memory by copying padding - remember to update this
4011    * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4012    */
4013   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4014 }
4015
4016 static void
4017 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4018 {
4019   g_free (vtable);
4020 }
4021
4022 /* ---------------------------------------------------------------------------------------------------- */
4023
4024 struct ExportedObject
4025 {
4026   gchar *object_path;
4027   GDBusConnection *connection;
4028
4029   /* maps gchar* -> ExportedInterface* */
4030   GHashTable *map_if_name_to_ei;
4031 };
4032
4033 /* only called with lock held */
4034 static void
4035 exported_object_free (ExportedObject *eo)
4036 {
4037   g_free (eo->object_path);
4038   g_hash_table_unref (eo->map_if_name_to_ei);
4039   g_free (eo);
4040 }
4041
4042 typedef struct
4043 {
4044   ExportedObject *eo;
4045
4046   guint                       id;
4047   gchar                      *interface_name;
4048   GDBusInterfaceVTable       *vtable;
4049   GDBusInterfaceInfo         *interface_info;
4050
4051   GMainContext               *context;
4052   gpointer                    user_data;
4053   GDestroyNotify              user_data_free_func;
4054 } ExportedInterface;
4055
4056 /* called with lock held */
4057 static void
4058 exported_interface_free (ExportedInterface *ei)
4059 {
4060   g_dbus_interface_info_cache_release (ei->interface_info);
4061   g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4062
4063   call_destroy_notify (ei->context,
4064                        ei->user_data_free_func,
4065                        ei->user_data);
4066
4067   g_main_context_unref (ei->context);
4068
4069   g_free (ei->interface_name);
4070   _g_dbus_interface_vtable_free (ei->vtable);
4071   g_free (ei);
4072 }
4073
4074 /* ---------------------------------------------------------------------------------------------------- */
4075
4076 /* Convenience function to check if @registration_id (if not zero) or
4077  * @subtree_registration_id (if not zero) has been unregistered. If
4078  * so, returns %TRUE.
4079  *
4080  * May be called by any thread. Caller must *not* hold lock.
4081  */
4082 static gboolean
4083 has_object_been_unregistered (GDBusConnection  *connection,
4084                               guint             registration_id,
4085                               guint             subtree_registration_id)
4086 {
4087   gboolean ret;
4088
4089   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4090
4091   ret = FALSE;
4092
4093   CONNECTION_LOCK (connection);
4094   if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4095                                                    GUINT_TO_POINTER (registration_id)) == NULL)
4096     {
4097       ret = TRUE;
4098     }
4099   else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4100                                                                 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4101     {
4102       ret = TRUE;
4103     }
4104   CONNECTION_UNLOCK (connection);
4105
4106   return ret;
4107 }
4108
4109 /* ---------------------------------------------------------------------------------------------------- */
4110
4111 typedef struct
4112 {
4113   GDBusConnection *connection;
4114   GDBusMessage *message;
4115   gpointer user_data;
4116   const gchar *property_name;
4117   const GDBusInterfaceVTable *vtable;
4118   GDBusInterfaceInfo *interface_info;
4119   const GDBusPropertyInfo *property_info;
4120   guint registration_id;
4121   guint subtree_registration_id;
4122 } PropertyData;
4123
4124 static void
4125 property_data_free (PropertyData *data)
4126 {
4127   g_object_unref (data->connection);
4128   g_object_unref (data->message);
4129   g_free (data);
4130 }
4131
4132 /* called in thread where object was registered - no locks held */
4133 static gboolean
4134 invoke_get_property_in_idle_cb (gpointer _data)
4135 {
4136   PropertyData *data = _data;
4137   GVariant *value;
4138   GError *error;
4139   GDBusMessage *reply;
4140
4141   if (has_object_been_unregistered (data->connection,
4142                                     data->registration_id,
4143                                     data->subtree_registration_id))
4144     {
4145       reply = g_dbus_message_new_method_error (data->message,
4146                                                "org.freedesktop.DBus.Error.UnknownMethod",
4147                                                _("No such interface ā€œorg.freedesktop.DBus.Propertiesā€ on object at path %s"),
4148                                                g_dbus_message_get_path (data->message));
4149       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4150       g_object_unref (reply);
4151       goto out;
4152     }
4153
4154   error = NULL;
4155   value = data->vtable->get_property (data->connection,
4156                                       g_dbus_message_get_sender (data->message),
4157                                       g_dbus_message_get_path (data->message),
4158                                       data->interface_info->name,
4159                                       data->property_name,
4160                                       &error,
4161                                       data->user_data);
4162
4163
4164   if (value != NULL)
4165     {
4166       g_assert_no_error (error);
4167
4168       g_variant_take_ref (value);
4169       reply = g_dbus_message_new_method_reply (data->message);
4170       g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4171       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4172       g_variant_unref (value);
4173       g_object_unref (reply);
4174     }
4175   else
4176     {
4177       gchar *dbus_error_name;
4178       g_assert (error != NULL);
4179       dbus_error_name = g_dbus_error_encode_gerror (error);
4180       reply = g_dbus_message_new_method_error_literal (data->message,
4181                                                        dbus_error_name,
4182                                                        error->message);
4183       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4184       g_free (dbus_error_name);
4185       g_error_free (error);
4186       g_object_unref (reply);
4187     }
4188
4189  out:
4190   return FALSE;
4191 }
4192
4193 /* called in thread where object was registered - no locks held */
4194 static gboolean
4195 invoke_set_property_in_idle_cb (gpointer _data)
4196 {
4197   PropertyData *data = _data;
4198   GError *error;
4199   GDBusMessage *reply;
4200   GVariant *value;
4201
4202   error = NULL;
4203   value = NULL;
4204
4205   g_variant_get (g_dbus_message_get_body (data->message),
4206                  "(ssv)",
4207                  NULL,
4208                  NULL,
4209                  &value);
4210
4211   if (!data->vtable->set_property (data->connection,
4212                                    g_dbus_message_get_sender (data->message),
4213                                    g_dbus_message_get_path (data->message),
4214                                    data->interface_info->name,
4215                                    data->property_name,
4216                                    value,
4217                                    &error,
4218                                    data->user_data))
4219     {
4220       gchar *dbus_error_name;
4221       g_assert (error != NULL);
4222       dbus_error_name = g_dbus_error_encode_gerror (error);
4223       reply = g_dbus_message_new_method_error_literal (data->message,
4224                                                        dbus_error_name,
4225                                                        error->message);
4226       g_free (dbus_error_name);
4227       g_error_free (error);
4228     }
4229   else
4230     {
4231       reply = g_dbus_message_new_method_reply (data->message);
4232     }
4233
4234   g_assert (reply != NULL);
4235   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4236   g_object_unref (reply);
4237   g_variant_unref (value);
4238
4239   return FALSE;
4240 }
4241
4242 /* called in any thread with connection's lock held */
4243 static gboolean
4244 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
4245                                              GDBusMessage               *message,
4246                                              guint                       registration_id,
4247                                              guint                       subtree_registration_id,
4248                                              gboolean                    is_get,
4249                                              GDBusInterfaceInfo         *interface_info,
4250                                              const GDBusInterfaceVTable *vtable,
4251                                              GMainContext               *main_context,
4252                                              gpointer                    user_data)
4253 {
4254   gboolean handled;
4255   const char *interface_name;
4256   const char *property_name;
4257   const GDBusPropertyInfo *property_info;
4258   GSource *idle_source;
4259   PropertyData *property_data;
4260   GDBusMessage *reply;
4261
4262   handled = FALSE;
4263
4264   if (is_get)
4265     g_variant_get (g_dbus_message_get_body (message),
4266                    "(&s&s)",
4267                    &interface_name,
4268                    &property_name);
4269   else
4270     g_variant_get (g_dbus_message_get_body (message),
4271                    "(&s&sv)",
4272                    &interface_name,
4273                    &property_name,
4274                    NULL);
4275
4276   if (vtable == NULL)
4277     goto out;
4278
4279   /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4280    */
4281   property_info = NULL;
4282
4283   /* TODO: the cost of this is O(n) - it might be worth caching the result */
4284   property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4285   if (property_info == NULL)
4286     {
4287       reply = g_dbus_message_new_method_error (message,
4288                                                "org.freedesktop.DBus.Error.InvalidArgs",
4289                                                _("No such property ā€œ%sā€"),
4290                                                property_name);
4291       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4292       g_object_unref (reply);
4293       handled = TRUE;
4294       goto out;
4295     }
4296
4297   if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4298     {
4299       reply = g_dbus_message_new_method_error (message,
4300                                                "org.freedesktop.DBus.Error.InvalidArgs",
4301                                                _("Property ā€œ%sā€ is not readable"),
4302                                                property_name);
4303       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4304       g_object_unref (reply);
4305       handled = TRUE;
4306       goto out;
4307     }
4308   else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4309     {
4310       reply = g_dbus_message_new_method_error (message,
4311                                                "org.freedesktop.DBus.Error.InvalidArgs",
4312                                                _("Property ā€œ%sā€ is not writable"),
4313                                                property_name);
4314       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4315       g_object_unref (reply);
4316       handled = TRUE;
4317       goto out;
4318     }
4319
4320   if (!is_get)
4321     {
4322       GVariant *value;
4323
4324       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4325        * of the given value is wrong
4326        */
4327       g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4328       if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4329         {
4330           reply = g_dbus_message_new_method_error (message,
4331                                                    "org.freedesktop.DBus.Error.InvalidArgs",
4332                                                    _("Error setting property ā€œ%sā€: Expected type ā€œ%sā€ but got ā€œ%sā€"),
4333                                                    property_name, property_info->signature,
4334                                                    g_variant_get_type_string (value));
4335           g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4336           g_variant_unref (value);
4337           g_object_unref (reply);
4338           handled = TRUE;
4339           goto out;
4340         }
4341
4342       g_variant_unref (value);
4343     }
4344
4345   /* If the vtable pointer for get_property() resp. set_property() is
4346    * NULL then dispatch the call via the method_call() handler.
4347    */
4348   if (is_get)
4349     {
4350       if (vtable->get_property == NULL)
4351         {
4352           schedule_method_call (connection, message, registration_id, subtree_registration_id,
4353                                 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4354                                 vtable, main_context, user_data);
4355           handled = TRUE;
4356           goto out;
4357         }
4358     }
4359   else
4360     {
4361       if (vtable->set_property == NULL)
4362         {
4363           schedule_method_call (connection, message, registration_id, subtree_registration_id,
4364                                 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4365                                 vtable, main_context, user_data);
4366           handled = TRUE;
4367           goto out;
4368         }
4369     }
4370
4371   /* ok, got the property info - call user code in an idle handler */
4372   property_data = g_new0 (PropertyData, 1);
4373   property_data->connection = g_object_ref (connection);
4374   property_data->message = g_object_ref (message);
4375   property_data->user_data = user_data;
4376   property_data->property_name = property_name;
4377   property_data->vtable = vtable;
4378   property_data->interface_info = interface_info;
4379   property_data->property_info = property_info;
4380   property_data->registration_id = registration_id;
4381   property_data->subtree_registration_id = subtree_registration_id;
4382
4383   idle_source = g_idle_source_new ();
4384   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4385   g_source_set_callback (idle_source,
4386                          is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4387                          property_data,
4388                          (GDestroyNotify) property_data_free);
4389   if (is_get)
4390     g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4391   else
4392     g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4393   g_source_attach (idle_source, main_context);
4394   g_source_unref (idle_source);
4395
4396   handled = TRUE;
4397
4398  out:
4399   return handled;
4400 }
4401
4402 /* called in GDBusWorker thread with connection's lock held */
4403 static gboolean
4404 handle_getset_property (GDBusConnection *connection,
4405                         ExportedObject  *eo,
4406                         GDBusMessage    *message,
4407                         gboolean         is_get)
4408 {
4409   ExportedInterface *ei;
4410   gboolean handled;
4411   const char *interface_name;
4412   const char *property_name;
4413
4414   handled = FALSE;
4415
4416   if (is_get)
4417     g_variant_get (g_dbus_message_get_body (message),
4418                    "(&s&s)",
4419                    &interface_name,
4420                    &property_name);
4421   else
4422     g_variant_get (g_dbus_message_get_body (message),
4423                    "(&s&sv)",
4424                    &interface_name,
4425                    &property_name,
4426                    NULL);
4427
4428   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4429    * no such interface registered
4430    */
4431   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4432   if (ei == NULL)
4433     {
4434       GDBusMessage *reply;
4435       reply = g_dbus_message_new_method_error (message,
4436                                                "org.freedesktop.DBus.Error.InvalidArgs",
4437                                                _("No such interface ā€œ%sā€"),
4438                                                interface_name);
4439       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4440       g_object_unref (reply);
4441       handled = TRUE;
4442       goto out;
4443     }
4444
4445   handled = validate_and_maybe_schedule_property_getset (eo->connection,
4446                                                          message,
4447                                                          ei->id,
4448                                                          0,
4449                                                          is_get,
4450                                                          ei->interface_info,
4451                                                          ei->vtable,
4452                                                          ei->context,
4453                                                          ei->user_data);
4454  out:
4455   return handled;
4456 }
4457
4458 /* ---------------------------------------------------------------------------------------------------- */
4459
4460 typedef struct
4461 {
4462   GDBusConnection *connection;
4463   GDBusMessage *message;
4464   gpointer user_data;
4465   const GDBusInterfaceVTable *vtable;
4466   GDBusInterfaceInfo *interface_info;
4467   guint registration_id;
4468   guint subtree_registration_id;
4469 } PropertyGetAllData;
4470
4471 static void
4472 property_get_all_data_free (PropertyData *data)
4473 {
4474   g_object_unref (data->connection);
4475   g_object_unref (data->message);
4476   g_free (data);
4477 }
4478
4479 /* called in thread where object was registered - no locks held */
4480 static gboolean
4481 invoke_get_all_properties_in_idle_cb (gpointer _data)
4482 {
4483   PropertyGetAllData *data = _data;
4484   GVariantBuilder builder;
4485   GDBusMessage *reply;
4486   guint n;
4487
4488   if (has_object_been_unregistered (data->connection,
4489                                     data->registration_id,
4490                                     data->subtree_registration_id))
4491     {
4492       reply = g_dbus_message_new_method_error (data->message,
4493                                                "org.freedesktop.DBus.Error.UnknownMethod",
4494                                                _("No such interface ā€œorg.freedesktop.DBus.Propertiesā€ on object at path %s"),
4495                                                g_dbus_message_get_path (data->message));
4496       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4497       g_object_unref (reply);
4498       goto out;
4499     }
4500
4501   /* TODO: Right now we never fail this call - we just omit values if
4502    *       a get_property() call is failing.
4503    *
4504    *       We could fail the whole call if just a single get_property() call
4505    *       returns an error. We need clarification in the D-Bus spec about this.
4506    */
4507   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4508   g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4509   for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4510     {
4511       const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4512       GVariant *value;
4513
4514       if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4515         continue;
4516
4517       value = data->vtable->get_property (data->connection,
4518                                           g_dbus_message_get_sender (data->message),
4519                                           g_dbus_message_get_path (data->message),
4520                                           data->interface_info->name,
4521                                           property_info->name,
4522                                           NULL,
4523                                           data->user_data);
4524
4525       if (value == NULL)
4526         continue;
4527
4528       g_variant_take_ref (value);
4529       g_variant_builder_add (&builder,
4530                              "{sv}",
4531                              property_info->name,
4532                              value);
4533       g_variant_unref (value);
4534     }
4535   g_variant_builder_close (&builder);
4536
4537   reply = g_dbus_message_new_method_reply (data->message);
4538   g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4539   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4540   g_object_unref (reply);
4541
4542  out:
4543   return FALSE;
4544 }
4545
4546 static gboolean
4547 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4548 {
4549   gint i;
4550
4551   if (!interface_info->properties)
4552     return FALSE;
4553
4554   for (i = 0; interface_info->properties[i]; i++)
4555     if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4556       return TRUE;
4557
4558   return FALSE;
4559 }
4560
4561 /* called in any thread with connection's lock held */
4562 static gboolean
4563 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
4564                                               GDBusMessage               *message,
4565                                               guint                       registration_id,
4566                                               guint                       subtree_registration_id,
4567                                               GDBusInterfaceInfo         *interface_info,
4568                                               const GDBusInterfaceVTable *vtable,
4569                                               GMainContext               *main_context,
4570                                               gpointer                    user_data)
4571 {
4572   gboolean handled;
4573   GSource *idle_source;
4574   PropertyGetAllData *property_get_all_data;
4575
4576   handled = FALSE;
4577
4578   if (vtable == NULL)
4579     goto out;
4580
4581   /* If the vtable pointer for get_property() is NULL but we have a
4582    * non-zero number of readable properties, then dispatch the call via
4583    * the method_call() handler.
4584    */
4585   if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4586     {
4587       schedule_method_call (connection, message, registration_id, subtree_registration_id,
4588                             interface_info, NULL, NULL, g_dbus_message_get_body (message),
4589                             vtable, main_context, user_data);
4590       handled = TRUE;
4591       goto out;
4592     }
4593
4594   /* ok, got the property info - call user in an idle handler */
4595   property_get_all_data = g_new0 (PropertyGetAllData, 1);
4596   property_get_all_data->connection = g_object_ref (connection);
4597   property_get_all_data->message = g_object_ref (message);
4598   property_get_all_data->user_data = user_data;
4599   property_get_all_data->vtable = vtable;
4600   property_get_all_data->interface_info = interface_info;
4601   property_get_all_data->registration_id = registration_id;
4602   property_get_all_data->subtree_registration_id = subtree_registration_id;
4603
4604   idle_source = g_idle_source_new ();
4605   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4606   g_source_set_callback (idle_source,
4607                          invoke_get_all_properties_in_idle_cb,
4608                          property_get_all_data,
4609                          (GDestroyNotify) property_get_all_data_free);
4610   g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
4611   g_source_attach (idle_source, main_context);
4612   g_source_unref (idle_source);
4613
4614   handled = TRUE;
4615
4616  out:
4617   return handled;
4618 }
4619
4620 /* called in GDBusWorker thread with connection's lock held */
4621 static gboolean
4622 handle_get_all_properties (GDBusConnection *connection,
4623                            ExportedObject  *eo,
4624                            GDBusMessage    *message)
4625 {
4626   ExportedInterface *ei;
4627   gboolean handled;
4628   const char *interface_name;
4629
4630   handled = FALSE;
4631
4632   g_variant_get (g_dbus_message_get_body (message),
4633                  "(&s)",
4634                  &interface_name);
4635
4636   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4637    * no such interface registered
4638    */
4639   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4640   if (ei == NULL)
4641     {
4642       GDBusMessage *reply;
4643       reply = g_dbus_message_new_method_error (message,
4644                                                "org.freedesktop.DBus.Error.InvalidArgs",
4645                                                _("No such interface ā€œ%sā€"),
4646                                                interface_name);
4647       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4648       g_object_unref (reply);
4649       handled = TRUE;
4650       goto out;
4651     }
4652
4653   handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4654                                                           message,
4655                                                           ei->id,
4656                                                           0,
4657                                                           ei->interface_info,
4658                                                           ei->vtable,
4659                                                           ei->context,
4660                                                           ei->user_data);
4661  out:
4662   return handled;
4663 }
4664
4665 /* ---------------------------------------------------------------------------------------------------- */
4666
4667 static const gchar introspect_header[] =
4668   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4669   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4670   "<!-- GDBus " PACKAGE_VERSION " -->\n"
4671   "<node>\n";
4672
4673 static const gchar introspect_tail[] =
4674   "</node>\n";
4675
4676 static const gchar introspect_properties_interface[] =
4677   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
4678   "    <method name=\"Get\">\n"
4679   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4680   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4681   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4682   "    </method>\n"
4683   "    <method name=\"GetAll\">\n"
4684   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4685   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4686   "    </method>\n"
4687   "    <method name=\"Set\">\n"
4688   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4689   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4690   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4691   "    </method>\n"
4692   "    <signal name=\"PropertiesChanged\">\n"
4693   "      <arg type=\"s\" name=\"interface_name\"/>\n"
4694   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4695   "      <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4696   "    </signal>\n"
4697   "  </interface>\n";
4698
4699 static const gchar introspect_introspectable_interface[] =
4700   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4701   "    <method name=\"Introspect\">\n"
4702   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4703   "    </method>\n"
4704   "  </interface>\n"
4705   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
4706   "    <method name=\"Ping\"/>\n"
4707   "    <method name=\"GetMachineId\">\n"
4708   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4709   "    </method>\n"
4710   "  </interface>\n";
4711
4712 static void
4713 introspect_append_header (GString *s)
4714 {
4715   g_string_append (s, introspect_header);
4716 }
4717
4718 static void
4719 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4720 {
4721   if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4722     {
4723       const gchar *begin;
4724       const gchar *end;
4725       gchar *s;
4726
4727       begin = object_path + path_len;
4728       end = strchr (begin, '/');
4729       if (end != NULL)
4730         s = g_strndup (begin, end - begin);
4731       else
4732         s = g_strdup (begin);
4733
4734       if (!g_hash_table_contains (set, s))
4735         g_hash_table_add (set, s);
4736       else
4737         g_free (s);
4738     }
4739 }
4740
4741 /* TODO: we want a nicer public interface for this */
4742 /* called in any thread with connection's lock held */
4743 static gchar **
4744 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4745                                             const gchar     *path)
4746 {
4747   GPtrArray *p;
4748   gchar **ret;
4749   GHashTableIter hash_iter;
4750   const gchar *object_path;
4751   gsize path_len;
4752   GHashTable *set;
4753   GList *keys;
4754   GList *l;
4755
4756   CONNECTION_ENSURE_LOCK (connection);
4757
4758   path_len = strlen (path);
4759   if (path_len > 1)
4760     path_len++;
4761
4762   set = g_hash_table_new (g_str_hash, g_str_equal);
4763
4764   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4765   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4766     maybe_add_path (path, path_len, object_path, set);
4767
4768   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4769   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4770     maybe_add_path (path, path_len, object_path, set);
4771
4772   p = g_ptr_array_new ();
4773   keys = g_hash_table_get_keys (set);
4774   for (l = keys; l != NULL; l = l->next)
4775     g_ptr_array_add (p, l->data);
4776   g_hash_table_unref (set);
4777   g_list_free (keys);
4778
4779   g_ptr_array_add (p, NULL);
4780   ret = (gchar **) g_ptr_array_free (p, FALSE);
4781   return ret;
4782 }
4783
4784 /* called in any thread with connection's lock not held */
4785 static gchar **
4786 g_dbus_connection_list_registered (GDBusConnection *connection,
4787                                    const gchar     *path)
4788 {
4789   gchar **ret;
4790   CONNECTION_LOCK (connection);
4791   ret = g_dbus_connection_list_registered_unlocked (connection, path);
4792   CONNECTION_UNLOCK (connection);
4793   return ret;
4794 }
4795
4796 /* called in GDBusWorker thread with connection's lock held */
4797 static gboolean
4798 handle_introspect (GDBusConnection *connection,
4799                    ExportedObject  *eo,
4800                    GDBusMessage    *message)
4801 {
4802   guint n;
4803   GString *s;
4804   GDBusMessage *reply;
4805   GHashTableIter hash_iter;
4806   ExportedInterface *ei;
4807   gchar **registered;
4808
4809   /* first the header with the standard interfaces */
4810   s = g_string_sized_new (sizeof (introspect_header) +
4811                           sizeof (introspect_properties_interface) +
4812                           sizeof (introspect_introspectable_interface) +
4813                           sizeof (introspect_tail));
4814   introspect_append_header (s);
4815   if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4816                             "org.freedesktop.DBus.Properties"))
4817     g_string_append (s, introspect_properties_interface);
4818
4819   if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4820                             "org.freedesktop.DBus.Introspectable"))
4821     g_string_append (s, introspect_introspectable_interface);
4822
4823   /* then include the registered interfaces */
4824   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4825   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4826     g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4827
4828   /* finally include nodes registered below us */
4829   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4830   for (n = 0; registered != NULL && registered[n] != NULL; n++)
4831     g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
4832   g_strfreev (registered);
4833   g_string_append (s, introspect_tail);
4834
4835   reply = g_dbus_message_new_method_reply (message);
4836   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4837   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4838   g_object_unref (reply);
4839   g_string_free (s, TRUE);
4840
4841   return TRUE;
4842 }
4843
4844 /* called in thread where object was registered - no locks held */
4845 static gboolean
4846 call_in_idle_cb (gpointer user_data)
4847 {
4848   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4849   GDBusInterfaceVTable *vtable;
4850   guint registration_id;
4851   guint subtree_registration_id;
4852
4853   registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4854   subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4855
4856   if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4857                                     registration_id,
4858                                     subtree_registration_id))
4859     {
4860       GDBusMessage *reply;
4861       reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4862                                                "org.freedesktop.DBus.Error.UnknownMethod",
4863                                                _("No such interface ā€œ%sā€ on object at path %s"),
4864                                                g_dbus_method_invocation_get_interface_name (invocation),
4865                                                g_dbus_method_invocation_get_object_path (invocation));
4866       g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4867       g_object_unref (reply);
4868       goto out;
4869     }
4870
4871   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4872   g_assert (vtable != NULL && vtable->method_call != NULL);
4873
4874   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4875                        g_dbus_method_invocation_get_sender (invocation),
4876                        g_dbus_method_invocation_get_object_path (invocation),
4877                        g_dbus_method_invocation_get_interface_name (invocation),
4878                        g_dbus_method_invocation_get_method_name (invocation),
4879                        g_dbus_method_invocation_get_parameters (invocation),
4880                        g_object_ref (invocation),
4881                        g_dbus_method_invocation_get_user_data (invocation));
4882
4883  out:
4884   return FALSE;
4885 }
4886
4887 /* called in GDBusWorker thread with connection's lock held */
4888 static void
4889 schedule_method_call (GDBusConnection            *connection,
4890                       GDBusMessage               *message,
4891                       guint                       registration_id,
4892                       guint                       subtree_registration_id,
4893                       const GDBusInterfaceInfo   *interface_info,
4894                       const GDBusMethodInfo      *method_info,
4895                       const GDBusPropertyInfo    *property_info,
4896                       GVariant                   *parameters,
4897                       const GDBusInterfaceVTable *vtable,
4898                       GMainContext               *main_context,
4899                       gpointer                    user_data)
4900 {
4901   GDBusMethodInvocation *invocation;
4902   GSource *idle_source;
4903
4904   invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4905                                               g_dbus_message_get_path (message),
4906                                               g_dbus_message_get_interface (message),
4907                                               g_dbus_message_get_member (message),
4908                                               method_info,
4909                                               property_info,
4910                                               connection,
4911                                               message,
4912                                               parameters,
4913                                               user_data);
4914
4915   /* TODO: would be nicer with a real MethodData like we already
4916    * have PropertyData and PropertyGetAllData... */
4917   g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4918   g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4919   g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4920
4921   idle_source = g_idle_source_new ();
4922   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4923   g_source_set_callback (idle_source,
4924                          call_in_idle_cb,
4925                          invocation,
4926                          g_object_unref);
4927   g_source_set_name (idle_source, "[gio, " __FILE__ "] call_in_idle_cb");
4928   g_source_attach (idle_source, main_context);
4929   g_source_unref (idle_source);
4930 }
4931
4932 /* called in GDBusWorker thread with connection's lock held */
4933 static gboolean
4934 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
4935                                          GDBusMessage               *message,
4936                                          guint                       registration_id,
4937                                          guint                       subtree_registration_id,
4938                                          GDBusInterfaceInfo         *interface_info,
4939                                          const GDBusInterfaceVTable *vtable,
4940                                          GMainContext               *main_context,
4941                                          gpointer                    user_data)
4942 {
4943   GDBusMethodInfo *method_info;
4944   GDBusMessage *reply;
4945   GVariant *parameters;
4946   gboolean handled;
4947   GVariantType *in_type;
4948
4949   handled = FALSE;
4950
4951   /* TODO: the cost of this is O(n) - it might be worth caching the result */
4952   method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4953
4954   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4955    * error to the caller
4956    */
4957   if (method_info == NULL)
4958     {
4959       reply = g_dbus_message_new_method_error (message,
4960                                                "org.freedesktop.DBus.Error.UnknownMethod",
4961                                                _("No such method ā€œ%sā€"),
4962                                                g_dbus_message_get_member (message));
4963       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4964       g_object_unref (reply);
4965       handled = TRUE;
4966       goto out;
4967     }
4968
4969   parameters = g_dbus_message_get_body (message);
4970   if (parameters == NULL)
4971     {
4972       parameters = g_variant_new ("()");
4973       g_variant_ref_sink (parameters);
4974     }
4975   else
4976     {
4977       g_variant_ref (parameters);
4978     }
4979
4980   /* Check that the incoming args are of the right type - if they are not, return
4981    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4982    */
4983   in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4984   if (!g_variant_is_of_type (parameters, in_type))
4985     {
4986       gchar *type_string;
4987
4988       type_string = g_variant_type_dup_string (in_type);
4989
4990       reply = g_dbus_message_new_method_error (message,
4991                                                "org.freedesktop.DBus.Error.InvalidArgs",
4992                                                _("Type of message, ā€œ%sā€, does not match expected type ā€œ%sā€"),
4993                                                g_variant_get_type_string (parameters),
4994                                                type_string);
4995       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4996       g_variant_type_free (in_type);
4997       g_variant_unref (parameters);
4998       g_object_unref (reply);
4999       g_free (type_string);
5000       handled = TRUE;
5001       goto out;
5002     }
5003   g_variant_type_free (in_type);
5004
5005   /* schedule the call in idle */
5006   schedule_method_call (connection, message, registration_id, subtree_registration_id,
5007                         interface_info, method_info, NULL, parameters,
5008                         vtable, main_context, user_data);
5009   g_variant_unref (parameters);
5010   handled = TRUE;
5011
5012  out:
5013   return handled;
5014 }
5015
5016 /* ---------------------------------------------------------------------------------------------------- */
5017
5018 /* called in GDBusWorker thread with connection's lock held */
5019 static gboolean
5020 obj_message_func (GDBusConnection *connection,
5021                   ExportedObject  *eo,
5022                   GDBusMessage    *message)
5023 {
5024   const gchar *interface_name;
5025   const gchar *member;
5026   const gchar *signature;
5027   gboolean handled;
5028
5029   handled = FALSE;
5030
5031   interface_name = g_dbus_message_get_interface (message);
5032   member = g_dbus_message_get_member (message);
5033   signature = g_dbus_message_get_signature (message);
5034
5035   /* see if we have an interface for handling this call */
5036   if (interface_name != NULL)
5037     {
5038       ExportedInterface *ei;
5039       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5040       if (ei != NULL)
5041         {
5042           /* we do - invoke the handler in idle in the right thread */
5043
5044           /* handle no vtable or handler being present */
5045           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5046             goto out;
5047
5048           handled = validate_and_maybe_schedule_method_call (connection,
5049                                                              message,
5050                                                              ei->id,
5051                                                              0,
5052                                                              ei->interface_info,
5053                                                              ei->vtable,
5054                                                              ei->context,
5055                                                              ei->user_data);
5056           goto out;
5057         }
5058     }
5059
5060   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5061       g_strcmp0 (member, "Introspect") == 0 &&
5062       g_strcmp0 (signature, "") == 0)
5063     {
5064       handled = handle_introspect (connection, eo, message);
5065       goto out;
5066     }
5067   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5068            g_strcmp0 (member, "Get") == 0 &&
5069            g_strcmp0 (signature, "ss") == 0)
5070     {
5071       handled = handle_getset_property (connection, eo, message, TRUE);
5072       goto out;
5073     }
5074   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5075            g_strcmp0 (member, "Set") == 0 &&
5076            g_strcmp0 (signature, "ssv") == 0)
5077     {
5078       handled = handle_getset_property (connection, eo, message, FALSE);
5079       goto out;
5080     }
5081   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5082            g_strcmp0 (member, "GetAll") == 0 &&
5083            g_strcmp0 (signature, "s") == 0)
5084     {
5085       handled = handle_get_all_properties (connection, eo, message);
5086       goto out;
5087     }
5088
5089  out:
5090   return handled;
5091 }
5092
5093 /**
5094  * g_dbus_connection_register_object:
5095  * @connection: a #GDBusConnection
5096  * @object_path: the object path to register at
5097  * @interface_info: introspection data for the interface
5098  * @vtable: (nullable): a #GDBusInterfaceVTable to call into or %NULL
5099  * @user_data: (nullable): data to pass to functions in @vtable
5100  * @user_data_free_func: function to call when the object path is unregistered
5101  * @error: return location for error or %NULL
5102  *
5103  * Registers callbacks for exported objects at @object_path with the
5104  * D-Bus interface that is described in @interface_info.
5105  *
5106  * Calls to functions in @vtable (and @user_data_free_func) will happen
5107  * in the 
5108  * [thread-default main context][g-main-context-push-thread-default]
5109  * of the thread you are calling this method from.
5110  *
5111  * Note that all #GVariant values passed to functions in @vtable will match
5112  * the signature given in @interface_info - if a remote caller passes
5113  * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5114  * is returned to the remote caller.
5115  *
5116  * Additionally, if the remote caller attempts to invoke methods or
5117  * access properties not mentioned in @interface_info the
5118  * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5119  * `org.freedesktop.DBus.Error.InvalidArgs` errors
5120  * are returned to the caller.
5121  *
5122  * It is considered a programming error if the
5123  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5124  * #GVariant of incorrect type.
5125  *
5126  * If an existing callback is already registered at @object_path and
5127  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5128  *
5129  * GDBus automatically implements the standard D-Bus interfaces
5130  * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5131  * and org.freedesktop.Peer, so you don't have to implement those for the
5132  * objects you export. You can implement org.freedesktop.DBus.Properties
5133  * yourself, e.g. to handle getting and setting of properties asynchronously.
5134  *
5135  * Note that the reference count on @interface_info will be
5136  * incremented by 1 (unless allocated statically, e.g. if the
5137  * reference count is -1, see g_dbus_interface_info_ref()) for as long
5138  * as the object is exported. Also note that @vtable will be copied.
5139  *
5140  * See this [server][gdbus-server] for an example of how to use this method.
5141  *
5142  * Returns: 0 if @error is set, otherwise a registration id (never 0)
5143  *     that can be used with g_dbus_connection_unregister_object()
5144  *
5145  * Since: 2.26
5146  */
5147 guint
5148 g_dbus_connection_register_object (GDBusConnection             *connection,
5149                                    const gchar                 *object_path,
5150                                    GDBusInterfaceInfo          *interface_info,
5151                                    const GDBusInterfaceVTable  *vtable,
5152                                    gpointer                     user_data,
5153                                    GDestroyNotify               user_data_free_func,
5154                                    GError                     **error)
5155 {
5156   ExportedObject *eo;
5157   ExportedInterface *ei;
5158   guint ret;
5159
5160   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5161   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5162   g_return_val_if_fail (interface_info != NULL, 0);
5163   g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5164   g_return_val_if_fail (error == NULL || *error == NULL, 0);
5165   g_return_val_if_fail (check_initialized (connection), 0);
5166
5167   ret = 0;
5168
5169   CONNECTION_LOCK (connection);
5170
5171   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5172   if (eo == NULL)
5173     {
5174       eo = g_new0 (ExportedObject, 1);
5175       eo->object_path = g_strdup (object_path);
5176       eo->connection = connection;
5177       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5178                                                      g_str_equal,
5179                                                      NULL,
5180                                                      (GDestroyNotify) exported_interface_free);
5181       g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5182     }
5183
5184   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5185   if (ei != NULL)
5186     {
5187       g_set_error (error,
5188                    G_IO_ERROR,
5189                    G_IO_ERROR_EXISTS,
5190                    _("An object is already exported for the interface %s at %s"),
5191                    interface_info->name,
5192                    object_path);
5193       goto out;
5194     }
5195
5196   ei = g_new0 (ExportedInterface, 1);
5197   ei->id = g_atomic_int_add (&_global_registration_id, 1); /* TODO: overflow etc. */
5198   ei->eo = eo;
5199   ei->user_data = user_data;
5200   ei->user_data_free_func = user_data_free_func;
5201   ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5202   ei->interface_info = g_dbus_interface_info_ref (interface_info);
5203   g_dbus_interface_info_cache_build (ei->interface_info);
5204   ei->interface_name = g_strdup (interface_info->name);
5205   ei->context = g_main_context_ref_thread_default ();
5206
5207   g_hash_table_insert (eo->map_if_name_to_ei,
5208                        (gpointer) ei->interface_name,
5209                        ei);
5210   g_hash_table_insert (connection->map_id_to_ei,
5211                        GUINT_TO_POINTER (ei->id),
5212                        ei);
5213
5214   ret = ei->id;
5215
5216  out:
5217   CONNECTION_UNLOCK (connection);
5218
5219   return ret;
5220 }
5221
5222 /**
5223  * g_dbus_connection_unregister_object:
5224  * @connection: a #GDBusConnection
5225  * @registration_id: a registration id obtained from
5226  *     g_dbus_connection_register_object()
5227  *
5228  * Unregisters an object.
5229  *
5230  * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5231  *
5232  * Since: 2.26
5233  */
5234 gboolean
5235 g_dbus_connection_unregister_object (GDBusConnection *connection,
5236                                      guint            registration_id)
5237 {
5238   ExportedInterface *ei;
5239   ExportedObject *eo;
5240   gboolean ret;
5241
5242   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5243   g_return_val_if_fail (check_initialized (connection), FALSE);
5244
5245   ret = FALSE;
5246
5247   CONNECTION_LOCK (connection);
5248
5249   ei = g_hash_table_lookup (connection->map_id_to_ei,
5250                             GUINT_TO_POINTER (registration_id));
5251   if (ei == NULL)
5252     goto out;
5253
5254   eo = ei->eo;
5255
5256   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5257   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5258   /* unregister object path if we have no more exported interfaces */
5259   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5260     g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5261                                          eo->object_path));
5262
5263   ret = TRUE;
5264
5265  out:
5266   CONNECTION_UNLOCK (connection);
5267
5268   return ret;
5269 }
5270
5271 typedef struct {
5272   GClosure *method_call_closure;
5273   GClosure *get_property_closure;
5274   GClosure *set_property_closure;
5275 } RegisterObjectData;
5276
5277 static RegisterObjectData *
5278 register_object_data_new (GClosure *method_call_closure,
5279                           GClosure *get_property_closure,
5280                           GClosure *set_property_closure)
5281 {
5282   RegisterObjectData *data;
5283
5284   data = g_new0 (RegisterObjectData, 1);
5285
5286   if (method_call_closure != NULL)
5287     {
5288       data->method_call_closure = g_closure_ref (method_call_closure);
5289       g_closure_sink (method_call_closure);
5290       if (G_CLOSURE_NEEDS_MARSHAL (method_call_closure))
5291         g_closure_set_marshal (method_call_closure, g_cclosure_marshal_generic);
5292     }
5293
5294   if (get_property_closure != NULL)
5295     {
5296       data->get_property_closure = g_closure_ref (get_property_closure);
5297       g_closure_sink (get_property_closure);
5298       if (G_CLOSURE_NEEDS_MARSHAL (get_property_closure))
5299         g_closure_set_marshal (get_property_closure, g_cclosure_marshal_generic);
5300     }
5301
5302   if (set_property_closure != NULL)
5303     {
5304       data->set_property_closure = g_closure_ref (set_property_closure);
5305       g_closure_sink (set_property_closure);
5306       if (G_CLOSURE_NEEDS_MARSHAL (set_property_closure))
5307         g_closure_set_marshal (set_property_closure, g_cclosure_marshal_generic);
5308     }
5309
5310   return data;
5311 }
5312
5313 static void
5314 register_object_free_func (gpointer user_data)
5315 {
5316   RegisterObjectData *data = user_data;
5317
5318   g_clear_pointer (&data->method_call_closure, g_closure_unref);
5319   g_clear_pointer (&data->get_property_closure, g_closure_unref);
5320   g_clear_pointer (&data->set_property_closure, g_closure_unref);
5321
5322   g_free (data);
5323 }
5324
5325 static void
5326 register_with_closures_on_method_call (GDBusConnection       *connection,
5327                                        const gchar           *sender,
5328                                        const gchar           *object_path,
5329                                        const gchar           *interface_name,
5330                                        const gchar           *method_name,
5331                                        GVariant              *parameters,
5332                                        GDBusMethodInvocation *invocation,
5333                                        gpointer               user_data)
5334 {
5335   RegisterObjectData *data = user_data;
5336   GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5337
5338   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
5339   g_value_set_object (&params[0], connection);
5340
5341   g_value_init (&params[1], G_TYPE_STRING);
5342   g_value_set_string (&params[1], sender);
5343
5344   g_value_init (&params[2], G_TYPE_STRING);
5345   g_value_set_string (&params[2], object_path);
5346
5347   g_value_init (&params[3], G_TYPE_STRING);
5348   g_value_set_string (&params[3], interface_name);
5349
5350   g_value_init (&params[4], G_TYPE_STRING);
5351   g_value_set_string (&params[4], method_name);
5352
5353   g_value_init (&params[5], G_TYPE_VARIANT);
5354   g_value_set_variant (&params[5], parameters);
5355
5356   g_value_init (&params[6], G_TYPE_DBUS_METHOD_INVOCATION);
5357   g_value_set_object (&params[6], invocation);
5358
5359   g_closure_invoke (data->method_call_closure, NULL, G_N_ELEMENTS (params), params, NULL);
5360
5361   g_value_unset (params + 0);
5362   g_value_unset (params + 1);
5363   g_value_unset (params + 2);
5364   g_value_unset (params + 3);
5365   g_value_unset (params + 4);
5366   g_value_unset (params + 5);
5367   g_value_unset (params + 6);
5368 }
5369
5370 static GVariant *
5371 register_with_closures_on_get_property (GDBusConnection *connection,
5372                                         const gchar     *sender,
5373                                         const gchar     *object_path,
5374                                         const gchar     *interface_name,
5375                                         const gchar     *property_name,
5376                                         GError         **error,
5377                                         gpointer         user_data)
5378 {
5379   RegisterObjectData *data = user_data;
5380   GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5381   GValue result_value = G_VALUE_INIT;
5382   GVariant *result;
5383
5384   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
5385   g_value_set_object (&params[0], connection);
5386
5387   g_value_init (&params[1], G_TYPE_STRING);
5388   g_value_set_string (&params[1], sender);
5389
5390   g_value_init (&params[2], G_TYPE_STRING);
5391   g_value_set_string (&params[2], object_path);
5392
5393   g_value_init (&params[3], G_TYPE_STRING);
5394   g_value_set_string (&params[3], interface_name);
5395
5396   g_value_init (&params[4], G_TYPE_STRING);
5397   g_value_set_string (&params[4], property_name);
5398
5399   g_value_init (&result_value, G_TYPE_VARIANT);
5400
5401   g_closure_invoke (data->get_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5402
5403   result = g_value_get_variant (&result_value);
5404   if (result)
5405     g_variant_ref (result);
5406
5407   g_value_unset (params + 0);
5408   g_value_unset (params + 1);
5409   g_value_unset (params + 2);
5410   g_value_unset (params + 3);
5411   g_value_unset (params + 4);
5412   g_value_unset (&result_value);
5413
5414   if (!result)
5415     g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5416                  _("Unable to retrieve property %s.%s"),
5417                  interface_name, property_name);
5418
5419   return result;
5420 }
5421
5422 static gboolean
5423 register_with_closures_on_set_property (GDBusConnection *connection,
5424                                         const gchar     *sender,
5425                                         const gchar     *object_path,
5426                                         const gchar     *interface_name,
5427                                         const gchar     *property_name,
5428                                         GVariant        *value,
5429                                         GError         **error,
5430                                         gpointer         user_data)
5431 {
5432   RegisterObjectData *data = user_data;
5433   GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5434   GValue result_value = G_VALUE_INIT;
5435   gboolean result;
5436
5437   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
5438   g_value_set_object (&params[0], connection);
5439
5440   g_value_init (&params[1], G_TYPE_STRING);
5441   g_value_set_string (&params[1], sender);
5442
5443   g_value_init (&params[2], G_TYPE_STRING);
5444   g_value_set_string (&params[2], object_path);
5445
5446   g_value_init (&params[3], G_TYPE_STRING);
5447   g_value_set_string (&params[3], interface_name);
5448
5449   g_value_init (&params[4], G_TYPE_STRING);
5450   g_value_set_string (&params[4], property_name);
5451
5452   g_value_init (&params[5], G_TYPE_VARIANT);
5453   g_value_set_variant (&params[5], value);
5454
5455   g_value_init (&result_value, G_TYPE_BOOLEAN);
5456
5457   g_closure_invoke (data->set_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5458
5459   result = g_value_get_boolean (&result_value);
5460
5461   g_value_unset (params + 0);
5462   g_value_unset (params + 1);
5463   g_value_unset (params + 2);
5464   g_value_unset (params + 3);
5465   g_value_unset (params + 4);
5466   g_value_unset (params + 5);
5467   g_value_unset (&result_value);
5468
5469   if (!result)
5470     g_set_error (error,
5471                  G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5472                  _("Unable to set property %s.%s"),
5473                  interface_name, property_name);
5474
5475   return result;
5476 }
5477
5478 /**
5479  * g_dbus_connection_register_object_with_closures: (rename-to g_dbus_connection_register_object)
5480  * @connection: A #GDBusConnection.
5481  * @object_path: The object path to register at.
5482  * @interface_info: Introspection data for the interface.
5483  * @method_call_closure: (nullable): #GClosure for handling incoming method calls.
5484  * @get_property_closure: (nullable): #GClosure for getting a property.
5485  * @set_property_closure: (nullable): #GClosure for setting a property.
5486  * @error: Return location for error or %NULL.
5487  *
5488  * Version of g_dbus_connection_register_object() using closures instead of a
5489  * #GDBusInterfaceVTable for easier binding in other languages.
5490  *
5491  * Returns: 0 if @error is set, otherwise a registration id (never 0)
5492  * that can be used with g_dbus_connection_unregister_object() .
5493  *
5494  * Since: 2.46
5495  */
5496 guint
5497 g_dbus_connection_register_object_with_closures (GDBusConnection     *connection,
5498                                                  const gchar         *object_path,
5499                                                  GDBusInterfaceInfo  *interface_info,
5500                                                  GClosure            *method_call_closure,
5501                                                  GClosure            *get_property_closure,
5502                                                  GClosure            *set_property_closure,
5503                                                  GError             **error)
5504 {
5505   RegisterObjectData *data;
5506   GDBusInterfaceVTable vtable =
5507     {
5508       method_call_closure != NULL  ? register_with_closures_on_method_call  : NULL,
5509       get_property_closure != NULL ? register_with_closures_on_get_property : NULL,
5510       set_property_closure != NULL ? register_with_closures_on_set_property : NULL
5511     };
5512
5513   data = register_object_data_new (method_call_closure, get_property_closure, set_property_closure);
5514
5515   return g_dbus_connection_register_object (connection,
5516                                             object_path,
5517                                             interface_info,
5518                                             &vtable,
5519                                             data,
5520                                             register_object_free_func,
5521                                             error);
5522 }
5523
5524 /* ---------------------------------------------------------------------------------------------------- */
5525
5526 /**
5527  * g_dbus_connection_emit_signal:
5528  * @connection: a #GDBusConnection
5529  * @destination_bus_name: (nullable): the unique bus name for the destination
5530  *     for the signal or %NULL to emit to all listeners
5531  * @object_path: path of remote object
5532  * @interface_name: D-Bus interface to emit a signal on
5533  * @signal_name: the name of the signal to emit
5534  * @parameters: (nullable): a #GVariant tuple with parameters for the signal
5535  *              or %NULL if not passing parameters
5536  * @error: Return location for error or %NULL
5537  *
5538  * Emits a signal.
5539  *
5540  * If the parameters GVariant is floating, it is consumed.
5541  *
5542  * This can only fail if @parameters is not compatible with the D-Bus protocol
5543  * (%G_IO_ERROR_INVALID_ARGUMENT), or if @connection has been closed
5544  * (%G_IO_ERROR_CLOSED).
5545  *
5546  * Returns: %TRUE unless @error is set
5547  *
5548  * Since: 2.26
5549  */
5550 gboolean
5551 g_dbus_connection_emit_signal (GDBusConnection  *connection,
5552                                const gchar      *destination_bus_name,
5553                                const gchar      *object_path,
5554                                const gchar      *interface_name,
5555                                const gchar      *signal_name,
5556                                GVariant         *parameters,
5557                                GError          **error)
5558 {
5559   GDBusMessage *message;
5560   gboolean ret;
5561
5562   message = NULL;
5563   ret = FALSE;
5564
5565   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5566   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5567   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5568   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5569   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5570   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5571   g_return_val_if_fail (check_initialized (connection), FALSE);
5572
5573   if (G_UNLIKELY (_g_dbus_debug_emission ()))
5574     {
5575       _g_dbus_debug_print_lock ();
5576       g_print ("========================================================================\n"
5577                "GDBus-debug:Emission:\n"
5578                " >>>> SIGNAL EMISSION %s.%s()\n"
5579                "      on object %s\n"
5580                "      destination %s\n",
5581                interface_name, signal_name,
5582                object_path,
5583                destination_bus_name != NULL ? destination_bus_name : "(none)");
5584       _g_dbus_debug_print_unlock ();
5585     }
5586
5587   message = g_dbus_message_new_signal (object_path,
5588                                        interface_name,
5589                                        signal_name);
5590
5591   if (destination_bus_name != NULL)
5592     g_dbus_message_set_header (message,
5593                                G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5594                                g_variant_new_string (destination_bus_name));
5595
5596   if (parameters != NULL)
5597     g_dbus_message_set_body (message, parameters);
5598
5599   ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5600   g_object_unref (message);
5601
5602   return ret;
5603 }
5604
5605 static void
5606 add_call_flags (GDBusMessage           *message,
5607                          GDBusCallFlags  flags)
5608 {
5609   GDBusMessageFlags msg_flags = 0;
5610
5611   if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5612     msg_flags |= G_DBUS_MESSAGE_FLAGS_NO_AUTO_START;
5613   if (flags & G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION)
5614     msg_flags |= G_DBUS_MESSAGE_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION;
5615   if (msg_flags)
5616     g_dbus_message_set_flags (message, msg_flags);
5617 }
5618
5619 static GVariant *
5620 decode_method_reply (GDBusMessage        *reply,
5621                      const gchar         *method_name,
5622                      const GVariantType  *reply_type,
5623                      GUnixFDList        **out_fd_list,
5624                      GError             **error)
5625 {
5626   GVariant *result;
5627
5628   result = NULL;
5629   switch (g_dbus_message_get_message_type (reply))
5630     {
5631     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5632       result = g_dbus_message_get_body (reply);
5633       if (result == NULL)
5634         {
5635           result = g_variant_new ("()");
5636           g_variant_ref_sink (result);
5637         }
5638       else
5639         {
5640           g_variant_ref (result);
5641         }
5642
5643       if (!g_variant_is_of_type (result, reply_type))
5644         {
5645           gchar *type_string = g_variant_type_dup_string (reply_type);
5646
5647           g_set_error (error,
5648                        G_IO_ERROR,
5649                        G_IO_ERROR_INVALID_ARGUMENT,
5650                        _("Method ā€œ%sā€ returned type ā€œ%sā€, but expected ā€œ%sā€"),
5651                        method_name, g_variant_get_type_string (result), type_string);
5652
5653           g_variant_unref (result);
5654           g_free (type_string);
5655           result = NULL;
5656         }
5657
5658 #ifdef G_OS_UNIX
5659       if (result != NULL)
5660         {
5661           if (out_fd_list != NULL)
5662             {
5663               *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5664               if (*out_fd_list != NULL)
5665                 g_object_ref (*out_fd_list);
5666             }
5667         }
5668 #endif
5669       break;
5670
5671     case G_DBUS_MESSAGE_TYPE_ERROR:
5672       g_dbus_message_to_gerror (reply, error);
5673       break;
5674
5675     default:
5676       g_assert_not_reached ();
5677       break;
5678     }
5679
5680   return result;
5681 }
5682
5683
5684 typedef struct
5685 {
5686   GVariantType *reply_type;
5687   gchar *method_name; /* for error message */
5688
5689   GUnixFDList *fd_list;
5690 } CallState;
5691
5692 static void
5693 call_state_free (CallState *state)
5694 {
5695   g_variant_type_free (state->reply_type);
5696   g_free (state->method_name);
5697
5698   if (state->fd_list != NULL)
5699     g_object_unref (state->fd_list);
5700   g_slice_free (CallState, state);
5701 }
5702
5703 /* called in any thread, with the connection's lock not held */
5704 static void
5705 g_dbus_connection_call_done (GObject      *source,
5706                              GAsyncResult *result,
5707                              gpointer      user_data)
5708 {
5709   GDBusConnection *connection = G_DBUS_CONNECTION (source);
5710   GTask *task = user_data;
5711   CallState *state = g_task_get_task_data (task);
5712   GError *error = NULL;
5713   GDBusMessage *reply;
5714   GVariant *value = NULL;
5715
5716   reply = g_dbus_connection_send_message_with_reply_finish (connection,
5717                                                             result,
5718                                                             &error);
5719
5720   if (G_UNLIKELY (_g_dbus_debug_call ()))
5721     {
5722       _g_dbus_debug_print_lock ();
5723       g_print ("========================================================================\n"
5724                "GDBus-debug:Call:\n"
5725                " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5726                "      ",
5727                state->method_name,
5728                g_dbus_message_get_reply_serial (reply));
5729       if (reply != NULL)
5730         {
5731           g_print ("SUCCESS\n");
5732         }
5733       else
5734         {
5735           g_print ("FAILED: %s\n",
5736                    error->message);
5737         }
5738       _g_dbus_debug_print_unlock ();
5739     }
5740
5741   if (reply != NULL)
5742     value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5743
5744   if (error != NULL)
5745     g_task_return_error (task, error);
5746   else
5747     g_task_return_pointer (task, value, (GDestroyNotify) g_variant_unref);
5748
5749   g_clear_object (&reply);
5750   g_object_unref (task);
5751 }
5752
5753 /* called in any thread, with the connection's lock not held */
5754 static void
5755 g_dbus_connection_call_internal (GDBusConnection        *connection,
5756                                  const gchar            *bus_name,
5757                                  const gchar            *object_path,
5758                                  const gchar            *interface_name,
5759                                  const gchar            *method_name,
5760                                  GVariant               *parameters,
5761                                  const GVariantType     *reply_type,
5762                                  GDBusCallFlags          flags,
5763                                  gint                    timeout_msec,
5764                                  GUnixFDList            *fd_list,
5765                                  GCancellable           *cancellable,
5766                                  GAsyncReadyCallback     callback,
5767                                  gpointer                user_data)
5768 {
5769   GDBusMessage *message;
5770   guint32 serial;
5771
5772   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5773   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5774   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5775   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5776   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5777   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5778   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5779   g_return_if_fail (check_initialized (connection));
5780 #ifdef G_OS_UNIX
5781   g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5782 #else
5783   g_return_if_fail (fd_list == NULL);
5784 #endif
5785
5786   message = g_dbus_message_new_method_call (bus_name,
5787                                             object_path,
5788                                             interface_name,
5789                                             method_name);
5790   add_call_flags (message, flags);
5791   if (parameters != NULL)
5792     g_dbus_message_set_body (message, parameters);
5793
5794 #ifdef G_OS_UNIX
5795   if (fd_list != NULL)
5796     g_dbus_message_set_unix_fd_list (message, fd_list);
5797 #endif
5798
5799   /* If the user has no callback then we can just send the message with
5800    * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5801    * the logic for processing the reply.  If the service sends the reply
5802    * anyway then it will just be ignored.
5803    */
5804   if (callback != NULL)
5805     {
5806       CallState *state;
5807       GTask *task;
5808
5809       state = g_slice_new0 (CallState);
5810       state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5811
5812       if (reply_type == NULL)
5813         reply_type = G_VARIANT_TYPE_ANY;
5814
5815       state->reply_type = g_variant_type_copy (reply_type);
5816
5817       task = g_task_new (connection, cancellable, callback, user_data);
5818       g_task_set_source_tag (task, g_dbus_connection_call_internal);
5819       g_task_set_task_data (task, state, (GDestroyNotify) call_state_free);
5820
5821       g_dbus_connection_send_message_with_reply (connection,
5822                                                  message,
5823                                                  G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5824                                                  timeout_msec,
5825                                                  &serial,
5826                                                  cancellable,
5827                                                  g_dbus_connection_call_done,
5828                                                  task);
5829     }
5830   else
5831     {
5832       GDBusMessageFlags flags;
5833
5834       flags = g_dbus_message_get_flags (message);
5835       flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5836       g_dbus_message_set_flags (message, flags);
5837
5838       g_dbus_connection_send_message (connection,
5839                                       message,
5840                                       G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5841                                       &serial, NULL);
5842     }
5843
5844   if (G_UNLIKELY (_g_dbus_debug_call ()))
5845     {
5846       _g_dbus_debug_print_lock ();
5847       g_print ("========================================================================\n"
5848                "GDBus-debug:Call:\n"
5849                " >>>> ASYNC %s.%s()\n"
5850                "      on object %s\n"
5851                "      owned by name %s (serial %d)\n",
5852                interface_name,
5853                method_name,
5854                object_path,
5855                bus_name != NULL ? bus_name : "(none)",
5856                serial);
5857       _g_dbus_debug_print_unlock ();
5858     }
5859
5860   if (message != NULL)
5861     g_object_unref (message);
5862 }
5863
5864 /* called in any thread, with the connection's lock not held */
5865 static GVariant *
5866 g_dbus_connection_call_finish_internal (GDBusConnection  *connection,
5867                                         GUnixFDList     **out_fd_list,
5868                                         GAsyncResult     *res,
5869                                         GError          **error)
5870 {
5871   GTask *task;
5872   CallState *state;
5873   GVariant *ret;
5874
5875   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5876   g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
5877   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5878
5879   task = G_TASK (res);
5880   state = g_task_get_task_data (task);
5881
5882   ret = g_task_propagate_pointer (task, error);
5883   if (!ret)
5884     return NULL;
5885
5886   if (out_fd_list != NULL)
5887     *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5888   return ret;
5889 }
5890
5891 /* called in any user thread, with the connection's lock not held */
5892 static GVariant *
5893 g_dbus_connection_call_sync_internal (GDBusConnection         *connection,
5894                                       const gchar             *bus_name,
5895                                       const gchar             *object_path,
5896                                       const gchar             *interface_name,
5897                                       const gchar             *method_name,
5898                                       GVariant                *parameters,
5899                                       const GVariantType      *reply_type,
5900                                       GDBusCallFlags           flags,
5901                                       gint                     timeout_msec,
5902                                       GUnixFDList             *fd_list,
5903                                       GUnixFDList            **out_fd_list,
5904                                       GCancellable            *cancellable,
5905                                       GError                 **error)
5906 {
5907   GDBusMessage *message;
5908   GDBusMessage *reply;
5909   GVariant *result;
5910   GError *local_error;
5911   GDBusSendMessageFlags send_flags;
5912
5913   message = NULL;
5914   reply = NULL;
5915   result = NULL;
5916
5917   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5918   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5919   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5920   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5921   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5922   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5923   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5924 #ifdef G_OS_UNIX
5925   g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5926 #else
5927   g_return_val_if_fail (fd_list == NULL, NULL);
5928 #endif
5929   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5930
5931   if (!(flags & CALL_FLAGS_INITIALIZING))
5932     g_return_val_if_fail (check_initialized (connection), FALSE);
5933
5934   if (reply_type == NULL)
5935     reply_type = G_VARIANT_TYPE_ANY;
5936
5937   message = g_dbus_message_new_method_call (bus_name,
5938                                             object_path,
5939                                             interface_name,
5940                                             method_name);
5941   add_call_flags (message, flags);
5942   if (parameters != NULL)
5943     g_dbus_message_set_body (message, parameters);
5944
5945 #ifdef G_OS_UNIX
5946   if (fd_list != NULL)
5947     g_dbus_message_set_unix_fd_list (message, fd_list);
5948 #endif
5949
5950   if (G_UNLIKELY (_g_dbus_debug_call ()))
5951     {
5952       _g_dbus_debug_print_lock ();
5953       g_print ("========================================================================\n"
5954                "GDBus-debug:Call:\n"
5955                " >>>> SYNC %s.%s()\n"
5956                "      on object %s\n"
5957                "      owned by name %s\n",
5958                interface_name,
5959                method_name,
5960                object_path,
5961                bus_name != NULL ? bus_name : "(none)");
5962       _g_dbus_debug_print_unlock ();
5963     }
5964
5965   local_error = NULL;
5966
5967   send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5968
5969   /* translate from one flavour of flags to another... */
5970   if (flags & CALL_FLAGS_INITIALIZING)
5971     send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5972
5973   reply = g_dbus_connection_send_message_with_reply_sync (connection,
5974                                                           message,
5975                                                           send_flags,
5976                                                           timeout_msec,
5977                                                           NULL, /* volatile guint32 *out_serial */
5978                                                           cancellable,
5979                                                           &local_error);
5980
5981   if (G_UNLIKELY (_g_dbus_debug_call ()))
5982     {
5983       _g_dbus_debug_print_lock ();
5984       g_print ("========================================================================\n"
5985                "GDBus-debug:Call:\n"
5986                " <<<< SYNC COMPLETE %s.%s()\n"
5987                "      ",
5988                interface_name,
5989                method_name);
5990       if (reply != NULL)
5991         {
5992           g_print ("SUCCESS\n");
5993         }
5994       else
5995         {
5996           g_print ("FAILED: %s\n",
5997                    local_error->message);
5998         }
5999       _g_dbus_debug_print_unlock ();
6000     }
6001
6002   if (reply == NULL)
6003     {
6004       if (error != NULL)
6005         *error = local_error;
6006       else
6007         g_error_free (local_error);
6008       goto out;
6009     }
6010
6011   result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6012
6013  out:
6014   if (message != NULL)
6015     g_object_unref (message);
6016   if (reply != NULL)
6017     g_object_unref (reply);
6018
6019   return result;
6020 }
6021
6022 /* ---------------------------------------------------------------------------------------------------- */
6023
6024 /**
6025  * g_dbus_connection_call:
6026  * @connection: a #GDBusConnection
6027  * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6028  *     @connection is not a message bus connection
6029  * @object_path: path of remote object
6030  * @interface_name: D-Bus interface to invoke method on
6031  * @method_name: the name of the method to invoke
6032  * @parameters: (nullable): a #GVariant tuple with parameters for the method
6033  *     or %NULL if not passing parameters
6034  * @reply_type: (nullable): the expected type of the reply (which will be a
6035  *     tuple), or %NULL
6036  * @flags: flags from the #GDBusCallFlags enumeration
6037  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6038  *     timeout or %G_MAXINT for no timeout
6039  * @cancellable: (nullable): a #GCancellable or %NULL
6040  * @callback: (nullable): a #GAsyncReadyCallback to call when the request
6041  *     is satisfied or %NULL if you don't care about the result of the
6042  *     method invocation
6043  * @user_data: the data to pass to @callback
6044  *
6045  * Asynchronously invokes the @method_name method on the
6046  * @interface_name D-Bus interface on the remote object at
6047  * @object_path owned by @bus_name.
6048  *
6049  * If @connection is closed then the operation will fail with
6050  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6051  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6052  * not compatible with the D-Bus protocol, the operation fails with
6053  * %G_IO_ERROR_INVALID_ARGUMENT.
6054  *
6055  * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6056  * error will be raised if it does not match.  Said another way, if you give a @reply_type
6057  * then any non-%NULL return value will be of this type. Unless itā€™s
6058  * %G_VARIANT_TYPE_UNIT, the @reply_type will be a tuple containing one or more
6059  * values.
6060  *
6061  * If the @parameters #GVariant is floating, it is consumed. This allows
6062  * convenient 'inline' use of g_variant_new(), e.g.:
6063  * |[<!-- language="C" -->
6064  *  g_dbus_connection_call (connection,
6065  *                          "org.freedesktop.StringThings",
6066  *                          "/org/freedesktop/StringThings",
6067  *                          "org.freedesktop.StringThings",
6068  *                          "TwoStrings",
6069  *                          g_variant_new ("(ss)",
6070  *                                         "Thing One",
6071  *                                         "Thing Two"),
6072  *                          NULL,
6073  *                          G_DBUS_CALL_FLAGS_NONE,
6074  *                          -1,
6075  *                          NULL,
6076  *                          (GAsyncReadyCallback) two_strings_done,
6077  *                          NULL);
6078  * ]|
6079  *
6080  * This is an asynchronous method. When the operation is finished,
6081  * @callback will be invoked in the
6082  * [thread-default main context][g-main-context-push-thread-default]
6083  * of the thread you are calling this method from. You can then call
6084  * g_dbus_connection_call_finish() to get the result of the operation.
6085  * See g_dbus_connection_call_sync() for the synchronous version of this
6086  * function.
6087  *
6088  * If @callback is %NULL then the D-Bus method call message will be sent with
6089  * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6090  *
6091  * Since: 2.26
6092  */
6093 void
6094 g_dbus_connection_call (GDBusConnection     *connection,
6095                         const gchar         *bus_name,
6096                         const gchar         *object_path,
6097                         const gchar         *interface_name,
6098                         const gchar         *method_name,
6099                         GVariant            *parameters,
6100                         const GVariantType  *reply_type,
6101                         GDBusCallFlags       flags,
6102                         gint                 timeout_msec,
6103                         GCancellable        *cancellable,
6104                         GAsyncReadyCallback  callback,
6105                         gpointer             user_data)
6106 {
6107   g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, cancellable, callback, user_data);
6108 }
6109
6110 /**
6111  * g_dbus_connection_call_finish:
6112  * @connection: a #GDBusConnection
6113  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6114  * @error: return location for error or %NULL
6115  *
6116  * Finishes an operation started with g_dbus_connection_call().
6117  *
6118  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6119  *     return values. Free with g_variant_unref().
6120  *
6121  * Since: 2.26
6122  */
6123 GVariant *
6124 g_dbus_connection_call_finish (GDBusConnection  *connection,
6125                                GAsyncResult     *res,
6126                                GError          **error)
6127 {
6128   return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6129 }
6130
6131 /**
6132  * g_dbus_connection_call_sync:
6133  * @connection: a #GDBusConnection
6134  * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6135  *     @connection is not a message bus connection
6136  * @object_path: path of remote object
6137  * @interface_name: D-Bus interface to invoke method on
6138  * @method_name: the name of the method to invoke
6139  * @parameters: (nullable): a #GVariant tuple with parameters for the method
6140  *     or %NULL if not passing parameters
6141  * @reply_type: (nullable): the expected type of the reply, or %NULL
6142  * @flags: flags from the #GDBusCallFlags enumeration
6143  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6144  *     timeout or %G_MAXINT for no timeout
6145  * @cancellable: (nullable): a #GCancellable or %NULL
6146  * @error: return location for error or %NULL
6147  *
6148  * Synchronously invokes the @method_name method on the
6149  * @interface_name D-Bus interface on the remote object at
6150  * @object_path owned by @bus_name.
6151  *
6152  * If @connection is closed then the operation will fail with
6153  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6154  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6155  * contains a value not compatible with the D-Bus protocol, the operation
6156  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6157  *
6158  * If @reply_type is non-%NULL then the reply will be checked for having
6159  * this type and an error will be raised if it does not match.  Said
6160  * another way, if you give a @reply_type then any non-%NULL return
6161  * value will be of this type.
6162  *
6163  * If the @parameters #GVariant is floating, it is consumed.
6164  * This allows convenient 'inline' use of g_variant_new(), e.g.:
6165  * |[<!-- language="C" -->
6166  *  g_dbus_connection_call_sync (connection,
6167  *                               "org.freedesktop.StringThings",
6168  *                               "/org/freedesktop/StringThings",
6169  *                               "org.freedesktop.StringThings",
6170  *                               "TwoStrings",
6171  *                               g_variant_new ("(ss)",
6172  *                                              "Thing One",
6173  *                                              "Thing Two"),
6174  *                               NULL,
6175  *                               G_DBUS_CALL_FLAGS_NONE,
6176  *                               -1,
6177  *                               NULL,
6178  *                               &error);
6179  * ]|
6180  *
6181  * The calling thread is blocked until a reply is received. See
6182  * g_dbus_connection_call() for the asynchronous version of
6183  * this method.
6184  *
6185  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6186  *     return values. Free with g_variant_unref().
6187  *
6188  * Since: 2.26
6189  */
6190 GVariant *
6191 g_dbus_connection_call_sync (GDBusConnection     *connection,
6192                              const gchar         *bus_name,
6193                              const gchar         *object_path,
6194                              const gchar         *interface_name,
6195                              const gchar         *method_name,
6196                              GVariant            *parameters,
6197                              const GVariantType  *reply_type,
6198                              GDBusCallFlags       flags,
6199                              gint                 timeout_msec,
6200                              GCancellable        *cancellable,
6201                              GError             **error)
6202 {
6203   return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, NULL, cancellable, error);
6204 }
6205
6206 /* ---------------------------------------------------------------------------------------------------- */
6207
6208 #ifdef G_OS_UNIX
6209
6210 /**
6211  * g_dbus_connection_call_with_unix_fd_list:
6212  * @connection: a #GDBusConnection
6213  * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6214  *     @connection is not a message bus connection
6215  * @object_path: path of remote object
6216  * @interface_name: D-Bus interface to invoke method on
6217  * @method_name: the name of the method to invoke
6218  * @parameters: (nullable): a #GVariant tuple with parameters for the method
6219  *     or %NULL if not passing parameters
6220  * @reply_type: (nullable): the expected type of the reply, or %NULL
6221  * @flags: flags from the #GDBusCallFlags enumeration
6222  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6223  *     timeout or %G_MAXINT for no timeout
6224  * @fd_list: (nullable): a #GUnixFDList or %NULL
6225  * @cancellable: (nullable): a #GCancellable or %NULL
6226  * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
6227  *     satisfied or %NULL if you don't * care about the result of the
6228  *     method invocation
6229  * @user_data: The data to pass to @callback.
6230  *
6231  * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6232  *
6233  * This method is only available on UNIX.
6234  *
6235  * Since: 2.30
6236  */
6237 void
6238 g_dbus_connection_call_with_unix_fd_list (GDBusConnection     *connection,
6239                                           const gchar         *bus_name,
6240                                           const gchar         *object_path,
6241                                           const gchar         *interface_name,
6242                                           const gchar         *method_name,
6243                                           GVariant            *parameters,
6244                                           const GVariantType  *reply_type,
6245                                           GDBusCallFlags       flags,
6246                                           gint                 timeout_msec,
6247                                           GUnixFDList         *fd_list,
6248                                           GCancellable        *cancellable,
6249                                           GAsyncReadyCallback  callback,
6250                                           gpointer             user_data)
6251 {
6252   g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, cancellable, callback, user_data);
6253 }
6254
6255 /**
6256  * g_dbus_connection_call_with_unix_fd_list_finish:
6257  * @connection: a #GDBusConnection
6258  * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6259  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6260  *     g_dbus_connection_call_with_unix_fd_list()
6261  * @error: return location for error or %NULL
6262  *
6263  * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6264  *
6265  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6266  *     return values. Free with g_variant_unref().
6267  *
6268  * Since: 2.30
6269  */
6270 GVariant *
6271 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection  *connection,
6272                                                  GUnixFDList     **out_fd_list,
6273                                                  GAsyncResult     *res,
6274                                                  GError          **error)
6275 {
6276   return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6277 }
6278
6279 /**
6280  * g_dbus_connection_call_with_unix_fd_list_sync:
6281  * @connection: a #GDBusConnection
6282  * @bus_name: (nullable): a unique or well-known bus name or %NULL
6283  *     if @connection is not a message bus connection
6284  * @object_path: path of remote object
6285  * @interface_name: D-Bus interface to invoke method on
6286  * @method_name: the name of the method to invoke
6287  * @parameters: (nullable): a #GVariant tuple with parameters for
6288  *     the method or %NULL if not passing parameters
6289  * @reply_type: (nullable): the expected type of the reply, or %NULL
6290  * @flags: flags from the #GDBusCallFlags enumeration
6291  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6292  *     timeout or %G_MAXINT for no timeout
6293  * @fd_list: (nullable): a #GUnixFDList or %NULL
6294  * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6295  * @cancellable: (nullable): a #GCancellable or %NULL
6296  * @error: return location for error or %NULL
6297  *
6298  * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6299  *
6300  * This method is only available on UNIX.
6301  *
6302  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6303  *     return values. Free with g_variant_unref().
6304  *
6305  * Since: 2.30
6306  */
6307 GVariant *
6308 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection     *connection,
6309                                                const gchar         *bus_name,
6310                                                const gchar         *object_path,
6311                                                const gchar         *interface_name,
6312                                                const gchar         *method_name,
6313                                                GVariant            *parameters,
6314                                                const GVariantType  *reply_type,
6315                                                GDBusCallFlags       flags,
6316                                                gint                 timeout_msec,
6317                                                GUnixFDList         *fd_list,
6318                                                GUnixFDList        **out_fd_list,
6319                                                GCancellable        *cancellable,
6320                                                GError             **error)
6321 {
6322   return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, out_fd_list, cancellable, error);
6323 }
6324
6325 #endif /* G_OS_UNIX */
6326
6327 /* ---------------------------------------------------------------------------------------------------- */
6328
6329 struct ExportedSubtree
6330 {
6331   guint                     id;
6332   gchar                    *object_path;
6333   GDBusConnection          *connection;
6334   GDBusSubtreeVTable       *vtable;
6335   GDBusSubtreeFlags         flags;
6336
6337   GMainContext             *context;
6338   gpointer                  user_data;
6339   GDestroyNotify            user_data_free_func;
6340 };
6341
6342 static void
6343 exported_subtree_free (ExportedSubtree *es)
6344 {
6345   call_destroy_notify (es->context,
6346                        es->user_data_free_func,
6347                        es->user_data);
6348
6349   g_main_context_unref (es->context);
6350
6351   _g_dbus_subtree_vtable_free (es->vtable);
6352   g_free (es->object_path);
6353   g_free (es);
6354 }
6355
6356 /* called without lock held in the thread where the caller registered
6357  * the subtree
6358  */
6359 static gboolean
6360 handle_subtree_introspect (GDBusConnection *connection,
6361                            ExportedSubtree *es,
6362                            GDBusMessage    *message)
6363 {
6364   GString *s;
6365   gboolean handled;
6366   GDBusMessage *reply;
6367   gchar **children;
6368   gboolean is_root;
6369   const gchar *sender;
6370   const gchar *requested_object_path;
6371   const gchar *requested_node;
6372   GDBusInterfaceInfo **interfaces;
6373   guint n;
6374   gchar **subnode_paths;
6375   gboolean has_properties_interface;
6376   gboolean has_introspectable_interface;
6377
6378   handled = FALSE;
6379
6380   requested_object_path = g_dbus_message_get_path (message);
6381   sender = g_dbus_message_get_sender (message);
6382   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6383
6384   s = g_string_new (NULL);
6385   introspect_append_header (s);
6386
6387   /* Strictly we don't need the children in dynamic mode, but we avoid the
6388    * conditionals to preserve code clarity
6389    */
6390   children = es->vtable->enumerate (es->connection,
6391                                     sender,
6392                                     es->object_path,
6393                                     es->user_data);
6394
6395   if (!is_root)
6396     {
6397       requested_node = strrchr (requested_object_path, '/') + 1;
6398
6399       /* Assert existence of object if we are not dynamic */
6400       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6401           !_g_strv_has_string ((const gchar * const *) children, requested_node))
6402         goto out;
6403     }
6404   else
6405     {
6406       requested_node = NULL;
6407     }
6408
6409   interfaces = es->vtable->introspect (es->connection,
6410                                        sender,
6411                                        es->object_path,
6412                                        requested_node,
6413                                        es->user_data);
6414   if (interfaces != NULL)
6415     {
6416       has_properties_interface = FALSE;
6417       has_introspectable_interface = FALSE;
6418
6419       for (n = 0; interfaces[n] != NULL; n++)
6420         {
6421           if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6422             has_properties_interface = TRUE;
6423           else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6424             has_introspectable_interface = TRUE;
6425         }
6426       if (!has_properties_interface)
6427         g_string_append (s, introspect_properties_interface);
6428       if (!has_introspectable_interface)
6429         g_string_append (s, introspect_introspectable_interface);
6430
6431       for (n = 0; interfaces[n] != NULL; n++)
6432         {
6433           g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6434           g_dbus_interface_info_unref (interfaces[n]);
6435         }
6436       g_free (interfaces);
6437     }
6438
6439   /* then include <node> entries from the Subtree for the root */
6440   if (is_root)
6441     {
6442       for (n = 0; children != NULL && children[n] != NULL; n++)
6443         g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
6444     }
6445
6446   /* finally include nodes registered below us */
6447   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6448   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6449     g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
6450   g_strfreev (subnode_paths);
6451
6452   g_string_append (s, "</node>\n");
6453
6454   reply = g_dbus_message_new_method_reply (message);
6455   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6456   g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6457   g_object_unref (reply);
6458
6459   handled = TRUE;
6460
6461  out:
6462   g_string_free (s, TRUE);
6463   g_strfreev (children);
6464   return handled;
6465 }
6466
6467 /* called without lock held in the thread where the caller registered
6468  * the subtree
6469  */
6470 static gboolean
6471 handle_subtree_method_invocation (GDBusConnection *connection,
6472                                   ExportedSubtree *es,
6473                                   GDBusMessage    *message)
6474 {
6475   gboolean handled;
6476   const gchar *sender;
6477   const gchar *interface_name;
6478   const gchar *member;
6479   const gchar *signature;
6480   const gchar *requested_object_path;
6481   const gchar *requested_node;
6482   gboolean is_root;
6483   GDBusInterfaceInfo *interface_info;
6484   const GDBusInterfaceVTable *interface_vtable;
6485   gpointer interface_user_data;
6486   guint n;
6487   GDBusInterfaceInfo **interfaces;
6488   gboolean is_property_get;
6489   gboolean is_property_set;
6490   gboolean is_property_get_all;
6491
6492   handled = FALSE;
6493   interfaces = NULL;
6494
6495   requested_object_path = g_dbus_message_get_path (message);
6496   sender = g_dbus_message_get_sender (message);
6497   interface_name = g_dbus_message_get_interface (message);
6498   member = g_dbus_message_get_member (message);
6499   signature = g_dbus_message_get_signature (message);
6500   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6501
6502   is_property_get = FALSE;
6503   is_property_set = FALSE;
6504   is_property_get_all = FALSE;
6505   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6506     {
6507       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6508         is_property_get = TRUE;
6509       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6510         is_property_set = TRUE;
6511       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6512         is_property_get_all = TRUE;
6513     }
6514
6515   if (!is_root)
6516     {
6517       requested_node = strrchr (requested_object_path, '/') + 1;
6518
6519       if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6520         {
6521           /* We don't want to dispatch to unenumerated
6522            * nodes, so ensure that the child exists.
6523            */
6524           gchar **children;
6525           gboolean exists;
6526
6527           children = es->vtable->enumerate (es->connection,
6528                                             sender,
6529                                             es->object_path,
6530                                             es->user_data);
6531
6532           exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6533           g_strfreev (children);
6534
6535           if (!exists)
6536             goto out;
6537         }
6538     }
6539   else
6540     {
6541       requested_node = NULL;
6542     }
6543
6544   /* get introspection data for the node */
6545   interfaces = es->vtable->introspect (es->connection,
6546                                        sender,
6547                                        requested_object_path,
6548                                        requested_node,
6549                                        es->user_data);
6550
6551   if (interfaces == NULL)
6552     goto out;
6553
6554   interface_info = NULL;
6555   for (n = 0; interfaces[n] != NULL; n++)
6556     {
6557       if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6558         interface_info = interfaces[n];
6559     }
6560
6561   /* dispatch the call if the user wants to handle it */
6562   if (interface_info != NULL)
6563     {
6564       /* figure out where to dispatch the method call */
6565       interface_user_data = NULL;
6566       interface_vtable = es->vtable->dispatch (es->connection,
6567                                                sender,
6568                                                es->object_path,
6569                                                interface_name,
6570                                                requested_node,
6571                                                &interface_user_data,
6572                                                es->user_data);
6573       if (interface_vtable == NULL)
6574         goto out;
6575
6576       CONNECTION_LOCK (connection);
6577       handled = validate_and_maybe_schedule_method_call (es->connection,
6578                                                          message,
6579                                                          0,
6580                                                          es->id,
6581                                                          interface_info,
6582                                                          interface_vtable,
6583                                                          es->context,
6584                                                          interface_user_data);
6585       CONNECTION_UNLOCK (connection);
6586     }
6587   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6588   else if (is_property_get || is_property_set || is_property_get_all)
6589     {
6590       if (is_property_get)
6591         g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6592       else if (is_property_set)
6593         g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6594       else if (is_property_get_all)
6595         g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6596       else
6597         g_assert_not_reached ();
6598
6599       /* see if the object supports this interface at all */
6600       for (n = 0; interfaces[n] != NULL; n++)
6601         {
6602           if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6603             interface_info = interfaces[n];
6604         }
6605
6606       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6607        * claims it won't support the interface
6608        */
6609       if (interface_info == NULL)
6610         {
6611           GDBusMessage *reply;
6612           reply = g_dbus_message_new_method_error (message,
6613                                                    "org.freedesktop.DBus.Error.InvalidArgs",
6614                                                    _("No such interface ā€œ%sā€"),
6615                                                    interface_name);
6616           g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6617           g_object_unref (reply);
6618           handled = TRUE;
6619           goto out;
6620         }
6621
6622       /* figure out where to dispatch the property get/set/getall calls */
6623       interface_user_data = NULL;
6624       interface_vtable = es->vtable->dispatch (es->connection,
6625                                                sender,
6626                                                es->object_path,
6627                                                interface_name,
6628                                                requested_node,
6629                                                &interface_user_data,
6630                                                es->user_data);
6631       if (interface_vtable == NULL)
6632         {
6633           g_warning ("The subtree introspection function indicates that '%s' "
6634                      "is a valid interface name, but calling the dispatch "
6635                      "function on that interface gave us NULL", interface_name);
6636           goto out;
6637         }
6638
6639       if (is_property_get || is_property_set)
6640         {
6641           CONNECTION_LOCK (connection);
6642           handled = validate_and_maybe_schedule_property_getset (es->connection,
6643                                                                  message,
6644                                                                  0,
6645                                                                  es->id,
6646                                                                  is_property_get,
6647                                                                  interface_info,
6648                                                                  interface_vtable,
6649                                                                  es->context,
6650                                                                  interface_user_data);
6651           CONNECTION_UNLOCK (connection);
6652         }
6653       else if (is_property_get_all)
6654         {
6655           CONNECTION_LOCK (connection);
6656           handled = validate_and_maybe_schedule_property_get_all (es->connection,
6657                                                                   message,
6658                                                                   0,
6659                                                                   es->id,
6660                                                                   interface_info,
6661                                                                   interface_vtable,
6662                                                                   es->context,
6663                                                                   interface_user_data);
6664           CONNECTION_UNLOCK (connection);
6665         }
6666     }
6667
6668  out:
6669   if (interfaces != NULL)
6670     {
6671       for (n = 0; interfaces[n] != NULL; n++)
6672         g_dbus_interface_info_unref (interfaces[n]);
6673       g_free (interfaces);
6674     }
6675
6676   return handled;
6677 }
6678
6679 typedef struct
6680 {
6681   GDBusMessage *message;
6682   ExportedSubtree *es;
6683 } SubtreeDeferredData;
6684
6685 static void
6686 subtree_deferred_data_free (SubtreeDeferredData *data)
6687 {
6688   g_object_unref (data->message);
6689   g_free (data);
6690 }
6691
6692 /* called without lock held in the thread where the caller registered the subtree */
6693 static gboolean
6694 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6695 {
6696   SubtreeDeferredData *data = _data;
6697   gboolean handled;
6698
6699   handled = FALSE;
6700
6701   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6702       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6703       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6704     handled = handle_subtree_introspect (data->es->connection,
6705                                          data->es,
6706                                          data->message);
6707   else
6708     handled = handle_subtree_method_invocation (data->es->connection,
6709                                                 data->es,
6710                                                 data->message);
6711
6712   if (!handled)
6713     {
6714       CONNECTION_LOCK (data->es->connection);
6715       handled = handle_generic_unlocked (data->es->connection, data->message);
6716       CONNECTION_UNLOCK (data->es->connection);
6717     }
6718
6719   /* if we couldn't handle the request, just bail with the UnknownMethod error */
6720   if (!handled)
6721     {
6722       GDBusMessage *reply;
6723       reply = g_dbus_message_new_method_error (data->message,
6724                                                "org.freedesktop.DBus.Error.UnknownMethod",
6725                                                _("Method ā€œ%sā€ on interface ā€œ%sā€ with signature ā€œ%sā€ does not exist"),
6726                                                g_dbus_message_get_member (data->message),
6727                                                g_dbus_message_get_interface (data->message),
6728                                                g_dbus_message_get_signature (data->message));
6729       g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6730       g_object_unref (reply);
6731     }
6732
6733   return FALSE;
6734 }
6735
6736 /* called in GDBusWorker thread with connection's lock held */
6737 static gboolean
6738 subtree_message_func (GDBusConnection *connection,
6739                       ExportedSubtree *es,
6740                       GDBusMessage    *message)
6741 {
6742   GSource *idle_source;
6743   SubtreeDeferredData *data;
6744
6745   data = g_new0 (SubtreeDeferredData, 1);
6746   data->message = g_object_ref (message);
6747   data->es = es;
6748
6749   /* defer this call to an idle handler in the right thread */
6750   idle_source = g_idle_source_new ();
6751   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6752   g_source_set_callback (idle_source,
6753                          process_subtree_vtable_message_in_idle_cb,
6754                          data,
6755                          (GDestroyNotify) subtree_deferred_data_free);
6756   g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6757   g_source_attach (idle_source, es->context);
6758   g_source_unref (idle_source);
6759
6760   /* since we own the entire subtree, handlers for objects not in the subtree have been
6761    * tried already by libdbus-1 - so we just need to ensure that we're always going
6762    * to reply to the message
6763    */
6764   return TRUE;
6765 }
6766
6767 /**
6768  * g_dbus_connection_register_subtree:
6769  * @connection: a #GDBusConnection
6770  * @object_path: the object path to register the subtree at
6771  * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6772  *     dispatch nodes in the subtree
6773  * @flags: flags used to fine tune the behavior of the subtree
6774  * @user_data: data to pass to functions in @vtable
6775  * @user_data_free_func: function to call when the subtree is unregistered
6776  * @error: return location for error or %NULL
6777  *
6778  * Registers a whole subtree of dynamic objects.
6779  *
6780  * The @enumerate and @introspection functions in @vtable are used to
6781  * convey, to remote callers, what nodes exist in the subtree rooted
6782  * by @object_path.
6783  *
6784  * When handling remote calls into any node in the subtree, first the
6785  * @enumerate function is used to check if the node exists. If the node exists
6786  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6787  * the @introspection function is used to check if the node supports the
6788  * requested method. If so, the @dispatch function is used to determine
6789  * where to dispatch the call. The collected #GDBusInterfaceVTable and
6790  * #gpointer will be used to call into the interface vtable for processing
6791  * the request.
6792  *
6793  * All calls into user-provided code will be invoked in the
6794  * [thread-default main context][g-main-context-push-thread-default]
6795  * of the thread you are calling this method from.
6796  *
6797  * If an existing subtree is already registered at @object_path or
6798  * then @error is set to #G_IO_ERROR_EXISTS.
6799  *
6800  * Note that it is valid to register regular objects (using
6801  * g_dbus_connection_register_object()) in a subtree registered with
6802  * g_dbus_connection_register_subtree() - if so, the subtree handler
6803  * is tried as the last resort. One way to think about a subtree
6804  * handler is to consider it a fallback handler for object paths not
6805  * registered via g_dbus_connection_register_object() or other bindings.
6806  *
6807  * Note that @vtable will be copied so you cannot change it after
6808  * registration.
6809  *
6810  * See this [server][gdbus-subtree-server] for an example of how to use
6811  * this method.
6812  *
6813  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6814  * that can be used with g_dbus_connection_unregister_subtree() .
6815  *
6816  * Since: 2.26
6817  */
6818 guint
6819 g_dbus_connection_register_subtree (GDBusConnection           *connection,
6820                                     const gchar               *object_path,
6821                                     const GDBusSubtreeVTable  *vtable,
6822                                     GDBusSubtreeFlags          flags,
6823                                     gpointer                   user_data,
6824                                     GDestroyNotify             user_data_free_func,
6825                                     GError                   **error)
6826 {
6827   guint ret;
6828   ExportedSubtree *es;
6829
6830   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6831   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6832   g_return_val_if_fail (vtable != NULL, 0);
6833   g_return_val_if_fail (error == NULL || *error == NULL, 0);
6834   g_return_val_if_fail (check_initialized (connection), 0);
6835
6836   ret = 0;
6837
6838   CONNECTION_LOCK (connection);
6839
6840   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6841   if (es != NULL)
6842     {
6843       g_set_error (error,
6844                    G_IO_ERROR,
6845                    G_IO_ERROR_EXISTS,
6846                    _("A subtree is already exported for %s"),
6847                    object_path);
6848       goto out;
6849     }
6850
6851   es = g_new0 (ExportedSubtree, 1);
6852   es->object_path = g_strdup (object_path);
6853   es->connection = connection;
6854
6855   es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6856   es->flags = flags;
6857   es->id = g_atomic_int_add (&_global_subtree_registration_id, 1); /* TODO: overflow etc. */
6858   es->user_data = user_data;
6859   es->user_data_free_func = user_data_free_func;
6860   es->context = g_main_context_ref_thread_default ();
6861
6862   g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6863   g_hash_table_insert (connection->map_id_to_es,
6864                        GUINT_TO_POINTER (es->id),
6865                        es);
6866
6867   ret = es->id;
6868
6869  out:
6870   CONNECTION_UNLOCK (connection);
6871
6872   return ret;
6873 }
6874
6875 /* ---------------------------------------------------------------------------------------------------- */
6876
6877 /**
6878  * g_dbus_connection_unregister_subtree:
6879  * @connection: a #GDBusConnection
6880  * @registration_id: a subtree registration id obtained from
6881  *     g_dbus_connection_register_subtree()
6882  *
6883  * Unregisters a subtree.
6884  *
6885  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6886  *
6887  * Since: 2.26
6888  */
6889 gboolean
6890 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6891                                       guint            registration_id)
6892 {
6893   ExportedSubtree *es;
6894   gboolean ret;
6895
6896   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6897   g_return_val_if_fail (check_initialized (connection), FALSE);
6898
6899   ret = FALSE;
6900
6901   CONNECTION_LOCK (connection);
6902
6903   es = g_hash_table_lookup (connection->map_id_to_es,
6904                             GUINT_TO_POINTER (registration_id));
6905   if (es == NULL)
6906     goto out;
6907
6908   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6909   g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6910
6911   ret = TRUE;
6912
6913  out:
6914   CONNECTION_UNLOCK (connection);
6915
6916   return ret;
6917 }
6918
6919 /* ---------------------------------------------------------------------------------------------------- */
6920
6921 /* may be called in any thread, with connection's lock held */
6922 static void
6923 handle_generic_ping_unlocked (GDBusConnection *connection,
6924                               const gchar     *object_path,
6925                               GDBusMessage    *message)
6926 {
6927   GDBusMessage *reply;
6928   reply = g_dbus_message_new_method_reply (message);
6929   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6930   g_object_unref (reply);
6931 }
6932
6933 /* may be called in any thread, with connection's lock held */
6934 static void
6935 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6936                                         const gchar     *object_path,
6937                                         GDBusMessage    *message)
6938 {
6939   GDBusMessage *reply;
6940
6941   reply = NULL;
6942   if (connection->machine_id == NULL)
6943     {
6944       GError *error;
6945
6946       error = NULL;
6947       connection->machine_id = _g_dbus_get_machine_id (&error);
6948       if (connection->machine_id == NULL)
6949         {
6950           reply = g_dbus_message_new_method_error_literal (message,
6951                                                            "org.freedesktop.DBus.Error.Failed",
6952                                                            error->message);
6953           g_error_free (error);
6954         }
6955     }
6956
6957   if (reply == NULL)
6958     {
6959       reply = g_dbus_message_new_method_reply (message);
6960       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6961     }
6962   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6963   g_object_unref (reply);
6964 }
6965
6966 /* may be called in any thread, with connection's lock held */
6967 static void
6968 handle_generic_introspect_unlocked (GDBusConnection *connection,
6969                                     const gchar     *object_path,
6970                                     GDBusMessage    *message)
6971 {
6972   guint n;
6973   GString *s;
6974   gchar **registered;
6975   GDBusMessage *reply;
6976
6977   /* first the header */
6978   s = g_string_new (NULL);
6979   introspect_append_header (s);
6980
6981   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6982   for (n = 0; registered != NULL && registered[n] != NULL; n++)
6983       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
6984   g_strfreev (registered);
6985   g_string_append (s, "</node>\n");
6986
6987   reply = g_dbus_message_new_method_reply (message);
6988   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6989   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6990   g_object_unref (reply);
6991   g_string_free (s, TRUE);
6992 }
6993
6994 /* may be called in any thread, with connection's lock held */
6995 static gboolean
6996 handle_generic_unlocked (GDBusConnection *connection,
6997                          GDBusMessage    *message)
6998 {
6999   gboolean handled;
7000   const gchar *interface_name;
7001   const gchar *member;
7002   const gchar *signature;
7003   const gchar *path;
7004
7005   CONNECTION_ENSURE_LOCK (connection);
7006
7007   handled = FALSE;
7008
7009   interface_name = g_dbus_message_get_interface (message);
7010   member = g_dbus_message_get_member (message);
7011   signature = g_dbus_message_get_signature (message);
7012   path = g_dbus_message_get_path (message);
7013
7014   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7015       g_strcmp0 (member, "Introspect") == 0 &&
7016       g_strcmp0 (signature, "") == 0)
7017     {
7018       handle_generic_introspect_unlocked (connection, path, message);
7019       handled = TRUE;
7020     }
7021   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7022            g_strcmp0 (member, "Ping") == 0 &&
7023            g_strcmp0 (signature, "") == 0)
7024     {
7025       handle_generic_ping_unlocked (connection, path, message);
7026       handled = TRUE;
7027     }
7028   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7029            g_strcmp0 (member, "GetMachineId") == 0 &&
7030            g_strcmp0 (signature, "") == 0)
7031     {
7032       handle_generic_get_machine_id_unlocked (connection, path, message);
7033       handled = TRUE;
7034     }
7035
7036   return handled;
7037 }
7038
7039 /* ---------------------------------------------------------------------------------------------------- */
7040
7041 /* called in GDBusWorker thread with connection's lock held */
7042 static void
7043 distribute_method_call (GDBusConnection *connection,
7044                         GDBusMessage    *message)
7045 {
7046   GDBusMessage *reply;
7047   ExportedObject *eo;
7048   ExportedSubtree *es;
7049   const gchar *object_path;
7050   const gchar *interface_name;
7051   const gchar *member;
7052   const gchar *path;
7053   gchar *subtree_path;
7054   gchar *needle;
7055
7056   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7057
7058   interface_name = g_dbus_message_get_interface (message);
7059   member = g_dbus_message_get_member (message);
7060   path = g_dbus_message_get_path (message);
7061   subtree_path = g_strdup (path);
7062   needle = strrchr (subtree_path, '/');
7063   if (needle != NULL && needle != subtree_path)
7064     {
7065       *needle = '\0';
7066     }
7067   else
7068     {
7069       g_free (subtree_path);
7070       subtree_path = NULL;
7071     }
7072
7073
7074   if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7075     {
7076       _g_dbus_debug_print_lock ();
7077       g_print ("========================================================================\n"
7078                "GDBus-debug:Incoming:\n"
7079                " <<<< METHOD INVOCATION %s.%s()\n"
7080                "      on object %s\n"
7081                "      invoked by name %s\n"
7082                "      serial %d\n",
7083                interface_name, member,
7084                path,
7085                g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7086                g_dbus_message_get_serial (message));
7087       _g_dbus_debug_print_unlock ();
7088     }
7089
7090   object_path = g_dbus_message_get_path (message);
7091   g_assert (object_path != NULL);
7092
7093   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7094   if (eo != NULL)
7095     {
7096       if (obj_message_func (connection, eo, message))
7097         goto out;
7098     }
7099
7100   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7101   if (es != NULL)
7102     {
7103       if (subtree_message_func (connection, es, message))
7104         goto out;
7105     }
7106
7107   if (subtree_path != NULL)
7108     {
7109       es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7110       if (es != NULL)
7111         {
7112           if (subtree_message_func (connection, es, message))
7113             goto out;
7114         }
7115     }
7116
7117   if (handle_generic_unlocked (connection, message))
7118     goto out;
7119
7120   /* if we end up here, the message has not been not handled - so return an error saying this */
7121   reply = g_dbus_message_new_method_error (message,
7122                                            "org.freedesktop.DBus.Error.UnknownMethod",
7123                                            _("No such interface ā€œ%sā€ on object at path %s"),
7124                                            interface_name,
7125                                            object_path);
7126   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7127   g_object_unref (reply);
7128
7129  out:
7130   g_free (subtree_path);
7131 }
7132
7133 /* ---------------------------------------------------------------------------------------------------- */
7134
7135 /* Called in any user thread, with the message_bus_lock held. */
7136 static GWeakRef *
7137 message_bus_get_singleton (GBusType   bus_type,
7138                            GError   **error)
7139 {
7140   GWeakRef *ret;
7141   const gchar *starter_bus;
7142
7143   ret = NULL;
7144
7145   switch (bus_type)
7146     {
7147     case G_BUS_TYPE_SESSION:
7148       ret = &the_session_bus;
7149       break;
7150
7151     case G_BUS_TYPE_SYSTEM:
7152       ret = &the_system_bus;
7153       break;
7154
7155     case G_BUS_TYPE_STARTER:
7156       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7157       if (g_strcmp0 (starter_bus, "session") == 0)
7158         {
7159           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7160           goto out;
7161         }
7162       else if (g_strcmp0 (starter_bus, "system") == 0)
7163         {
7164           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7165           goto out;
7166         }
7167       else
7168         {
7169           if (starter_bus != NULL)
7170             {
7171               g_set_error (error,
7172                            G_IO_ERROR,
7173                            G_IO_ERROR_INVALID_ARGUMENT,
7174                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7175                              " ā€” unknown value ā€œ%sā€"),
7176                            starter_bus);
7177             }
7178           else
7179             {
7180               g_set_error_literal (error,
7181                                    G_IO_ERROR,
7182                                    G_IO_ERROR_INVALID_ARGUMENT,
7183                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7184                                      "variable is not set"));
7185             }
7186         }
7187       break;
7188
7189     default:
7190       g_assert_not_reached ();
7191       break;
7192     }
7193
7194  out:
7195   return ret;
7196 }
7197
7198 /* Called in any user thread, without holding locks. */
7199 static GDBusConnection *
7200 get_uninitialized_connection (GBusType       bus_type,
7201                               GCancellable  *cancellable,
7202                               GError       **error)
7203 {
7204   GWeakRef *singleton;
7205   GDBusConnection *ret;
7206
7207   ret = NULL;
7208
7209   G_LOCK (message_bus_lock);
7210   singleton = message_bus_get_singleton (bus_type, error);
7211   if (singleton == NULL)
7212     goto out;
7213
7214   ret = g_weak_ref_get (singleton);
7215
7216   if (ret == NULL)
7217     {
7218       gchar *address;
7219       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7220       if (address == NULL)
7221         goto out;
7222       ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7223                           "address", address,
7224                           "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7225                                    G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7226                           "exit-on-close", TRUE,
7227                           NULL);
7228
7229       g_weak_ref_set (singleton, ret);
7230       g_free (address);
7231     }
7232
7233   g_assert (ret != NULL);
7234
7235  out:
7236   G_UNLOCK (message_bus_lock);
7237   return ret;
7238 }
7239
7240 /* May be called from any thread. Must not hold message_bus_lock. */
7241 GDBusConnection *
7242 _g_bus_get_singleton_if_exists (GBusType bus_type)
7243 {
7244   GWeakRef *singleton;
7245   GDBusConnection *ret = NULL;
7246
7247   G_LOCK (message_bus_lock);
7248   singleton = message_bus_get_singleton (bus_type, NULL);
7249   if (singleton == NULL)
7250     goto out;
7251
7252   ret = g_weak_ref_get (singleton);
7253
7254  out:
7255   G_UNLOCK (message_bus_lock);
7256   return ret;
7257 }
7258
7259 /* May be called from any thread. Must not hold message_bus_lock. */
7260 void
7261 _g_bus_forget_singleton (GBusType bus_type)
7262 {
7263   GWeakRef *singleton;
7264
7265   G_LOCK (message_bus_lock);
7266
7267   singleton = message_bus_get_singleton (bus_type, NULL);
7268
7269   if (singleton != NULL)
7270     g_weak_ref_set (singleton, NULL);
7271
7272   G_UNLOCK (message_bus_lock);
7273 }
7274
7275 /**
7276  * g_bus_get_sync:
7277  * @bus_type: a #GBusType
7278  * @cancellable: (nullable): a #GCancellable or %NULL
7279  * @error: return location for error or %NULL
7280  *
7281  * Synchronously connects to the message bus specified by @bus_type.
7282  * Note that the returned object may shared with other callers,
7283  * e.g. if two separate parts of a process calls this function with
7284  * the same @bus_type, they will share the same object.
7285  *
7286  * This is a synchronous failable function. See g_bus_get() and
7287  * g_bus_get_finish() for the asynchronous version.
7288  *
7289  * The returned object is a singleton, that is, shared with other
7290  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7291  * event that you need a private message bus connection, use
7292  * g_dbus_address_get_for_bus_sync() and
7293  * g_dbus_connection_new_for_address().
7294  *
7295  * Note that the returned #GDBusConnection object will (usually) have
7296  * the #GDBusConnection:exit-on-close property set to %TRUE.
7297  *
7298  * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7299  *     Free with g_object_unref().
7300  *
7301  * Since: 2.26
7302  */
7303 GDBusConnection *
7304 g_bus_get_sync (GBusType       bus_type,
7305                 GCancellable  *cancellable,
7306                 GError       **error)
7307 {
7308   GDBusConnection *connection;
7309
7310   _g_dbus_initialize ();
7311
7312   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7313
7314   connection = get_uninitialized_connection (bus_type, cancellable, error);
7315   if (connection == NULL)
7316     goto out;
7317
7318   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7319     {
7320       g_object_unref (connection);
7321       connection = NULL;
7322     }
7323
7324  out:
7325   return connection;
7326 }
7327
7328 static void
7329 bus_get_async_initable_cb (GObject      *source_object,
7330                            GAsyncResult *res,
7331                            gpointer      user_data)
7332 {
7333   GTask *task = user_data;
7334   GError *error = NULL;
7335
7336   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7337                                      res,
7338                                      &error))
7339     {
7340       g_assert (error != NULL);
7341       g_task_return_error (task, error);
7342       g_object_unref (source_object);
7343     }
7344   else
7345     {
7346       g_task_return_pointer (task, source_object, g_object_unref);
7347     }
7348   g_object_unref (task);
7349 }
7350
7351 /**
7352  * g_bus_get:
7353  * @bus_type: a #GBusType
7354  * @cancellable: (nullable): a #GCancellable or %NULL
7355  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7356  * @user_data: the data to pass to @callback
7357  *
7358  * Asynchronously connects to the message bus specified by @bus_type.
7359  *
7360  * When the operation is finished, @callback will be invoked. You can
7361  * then call g_bus_get_finish() to get the result of the operation.
7362  *
7363  * This is a asynchronous failable function. See g_bus_get_sync() for
7364  * the synchronous version.
7365  *
7366  * Since: 2.26
7367  */
7368 void
7369 g_bus_get (GBusType             bus_type,
7370            GCancellable        *cancellable,
7371            GAsyncReadyCallback  callback,
7372            gpointer             user_data)
7373 {
7374   GDBusConnection *connection;
7375   GTask *task;
7376   GError *error = NULL;
7377
7378   _g_dbus_initialize ();
7379
7380   task = g_task_new (NULL, cancellable, callback, user_data);
7381   g_task_set_source_tag (task, g_bus_get);
7382
7383   connection = get_uninitialized_connection (bus_type, cancellable, &error);
7384   if (connection == NULL)
7385     {
7386       g_assert (error != NULL);
7387       g_task_return_error (task, error);
7388       g_object_unref (task);
7389     }
7390   else
7391     {
7392       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7393                                    G_PRIORITY_DEFAULT,
7394                                    cancellable,
7395                                    bus_get_async_initable_cb,
7396                                    task);
7397     }
7398 }
7399
7400 /**
7401  * g_bus_get_finish:
7402  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7403  *     to g_bus_get()
7404  * @error: return location for error or %NULL
7405  *
7406  * Finishes an operation started with g_bus_get().
7407  *
7408  * The returned object is a singleton, that is, shared with other
7409  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7410  * event that you need a private message bus connection, use
7411  * g_dbus_address_get_for_bus_sync() and
7412  * g_dbus_connection_new_for_address().
7413  *
7414  * Note that the returned #GDBusConnection object will (usually) have
7415  * the #GDBusConnection:exit-on-close property set to %TRUE.
7416  *
7417  * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7418  *     Free with g_object_unref().
7419  *
7420  * Since: 2.26
7421  */
7422 GDBusConnection *
7423 g_bus_get_finish (GAsyncResult  *res,
7424                   GError       **error)
7425 {
7426   g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
7427   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7428
7429   return g_task_propagate_pointer (G_TASK (res), error);
7430 }
7431
7432 /* ---------------------------------------------------------------------------------------------------- */