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